hexsha
stringlengths
40
40
size
int64
8
1.04M
content
stringlengths
8
1.04M
avg_line_length
float64
2.24
100
max_line_length
int64
4
1k
alphanum_fraction
float64
0.25
0.97
888353837f30324115c4d6d595b34fc27f3e3cce
1,882
/* * Copyright 2021 Steinar Bang * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations * under the License. */ package no.priv.bang.handlereg.services; import no.priv.bang.beans.immutable.Immutable; public class NyFavoritt extends Immutable { private String brukernavn; private Butikk butikk; private NyFavoritt() {} public String getBrukernavn() { return brukernavn; } public Butikk getButikk() { return butikk; } @Override public String toString() { return "NyFavoritt [brukernavn=" + brukernavn + ", butikk=" + butikk + "]"; } public static NyFavorittBuilder with() { return new NyFavorittBuilder(); } public static class NyFavorittBuilder { private String brukernavn; private Butikk butikk; private NyFavorittBuilder() {} public NyFavoritt build() { NyFavoritt favorittOgBrukernavn = new NyFavoritt(); favorittOgBrukernavn.brukernavn = this.brukernavn; favorittOgBrukernavn.butikk = this.butikk; return favorittOgBrukernavn; } public NyFavorittBuilder brukernavn(String brukernavn) { this.brukernavn = brukernavn; return this; } public NyFavorittBuilder butikk(Butikk favoritt) { this.butikk = favoritt; return this; } } }
26.507042
83
0.659936
fd9c973690e7237bcef26b6cd067e61848ed0acb
3,537
/* * Copyright 2016-2017 Testify Project. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.testifyproject.core; import java.lang.reflect.Type; import org.testifyproject.Instance; import org.testifyproject.guava.common.reflect.TypeToken; import lombok.EqualsAndHashCode; import lombok.ToString; /** * Default implementation of {@link Instance} contract. * * @author saden * @param <T> the underlying instance type */ @ToString @EqualsAndHashCode public class DefaultInstance<T> implements Instance<T> { private final T instance; private final String name; private final Type contract; DefaultInstance(T instance, String name, Type contract) { this.name = name; this.instance = instance; this.contract = contract; } /** * Create a instance with the given instance object. * * @param <T> the underlying instance type * @param instance the instance object * @return returns an instance */ public static <T> Instance<T> of(T instance) { Class<?> contract = instance == null ? null : instance.getClass(); return new DefaultInstance(instance, null, contract); } /** * Create a instance with the given instance object and name. * * @param <T> the underlying instance type * @param instance the instance object * @param name the name associated with the object * @return returns an instance */ public static <T> Instance<T> of(T instance, String name) { Class<?> contract = instance == null ? null : instance.getClass(); return new DefaultInstance(instance, name, contract); } /** * Create a instance with the given instance object and contract. * * @param <T> the underlying instance type * @param instance the instance object * @param contract the contract implemented by the instance * @return returns an instance */ public static <T> Instance<T> of(T instance, Type contract) { return new DefaultInstance(instance, null, contract); } /** * <p> * Create an instance with the given instance object, name and contract. * </p> * * @param <T> the underlying instance type * @param instance the instance object * @param name the name associated with the object * @param contract the contract implemented by the instance * @return returns an instance */ public static <T> Instance<T> of(T instance, String name, Type contract) { return new DefaultInstance(instance, name, contract); } @Override public T getValue() { return instance; } @Override public String getName() { return name; } @Override public Class<? extends T> getContract() { return contract == null ? null : (Class<? extends T>) TypeToken.of(contract).getRawType(); } @Override public Type getGenericContract() { return contract; } }
28.756098
78
0.658468
5d1d8be7c68572f52a3f32140396c2093c2e09f7
2,718
/** * Copyright 2013 <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kxd.talos.trace.core.span; import com.kxd.talos.trace.core.utils.Nullable; import com.kxd.talos.trace.core.utils.JdkRuntimeUtilities; /** * The ServerSpan is initialized by {@link ServerTracer} and keeps track of Trace/Span state of our service request. * * @author adriaens */ public class ServerSpan { public final static ServerSpan EMPTY = new ServerSpan(null,null); public static final ServerSpan NOT_SAMPLED = new ServerSpan(null,false); private Span span = null; private Boolean sample; public static ServerSpan create(Span span, Boolean sample) { return new ServerSpan(span, sample); } /** * Creates a new initializes instance. Using this constructor also indicates we need to sample this request. * * @param traceId Trace id. * @param spanId Span id. * @param parentSpanId Parent span id, can be <code>null</code>. * @param name Span name. Should be lowercase and not <code>null</code> or empty. */ public static ServerSpan create(String traceId, String spanId, @Nullable String parentSpanId, String name) { Span span = new Span(); span.setTrace_id(traceId); span.setId(spanId); if (parentSpanId != null) { span.setParent_id(parentSpanId); } span.setName(name); span.setThreadName(JdkRuntimeUtilities.getCurrentThreadName()); span.setProcessId(JdkRuntimeUtilities.getProcessId()); return create(span, true); } /** * Creates a new empty instance with no Span but with sample indication. * * @param sample Indicates if we should sample this span. */ public ServerSpan create(final Boolean sample) { return create(null, sample); } private ServerSpan(Span span, Boolean sample){ this.sample = sample; this.span = span; } public Span getSpan() { return span; } public void setSpan(Span span) { this.span = span; } public Boolean getSample() { return sample; } public void setSample(Boolean sample) { this.sample = sample; } }
30.539326
116
0.681383
db7209cb197b84fa9fe30bde8393b170a1e001c7
1,960
package com.tts.service; import com.tts.util.DateUtils; import com.tts.util.WXUtils; import com.tts.util.XmlHelper; import com.tts.weixin.MessageType; import com.tts.weixin.request.TextMessageRequest; import com.tts.weixin.response.TextMessageResponse; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; /** * WX. * User: eric * Date: 13-12-4 * Time: ไธ‹ๅˆ1:15 * To change this template use File | Settings | File Templates. */ @Service("wxService") public class WxService implements IWXService { private static Logger logger = LoggerFactory.getLogger(WxService.class); public String messageHandler(String xml) { String result = ""; if (StringUtils.isNotBlank(xml)) { String type = XmlHelper.getMessageType(xml); if (MessageType.MSG_TEXT.equals(type)) { TextMessageRequest text = WXUtils.toObjectByXml(xml, TextMessageRequest.class); //TextMessageResponse reply = new TextMessageResponse(XmlHelper.toXml(text.getFromUserName()),XmlHelper.toXml(MP), DateUtils.getTimestamp(),XmlHelper.toXml(text.getFromUserName()+":"+text.getContent()),"0"); TextMessageResponse reply = new TextMessageResponse(text.getFromUserName(),MP, DateUtils.getTimestamp(),text.getFromUserName()+":"+text.getContent()); result = WXUtils.toXmlByObject("UTF-8",reply); } else if (MessageType.MSG_IMAGE.equals(type)) { } else if (MessageType.MSG_VOICE.equals(type)) { } else if (MessageType.MSG_VIDEO.equals(type)) { } else if (MessageType.MSG_LOCATION.equals(type)) { } else if (MessageType.MSG_LINK.equals(type)) { } else if (MessageType.MSG_EVENT.equals(type)) { } else { } } logger.info("reply message:\n"+result+"\n"); return result; } }
36.296296
223
0.67398
71c9cedcafb4a23e2ce2584ae5ccc735cf39ec2d
1,480
package com.billy.android.swipe.demo.util; import android.app.Activity; import android.graphics.Color; import android.os.Build; import android.view.View; import android.view.WindowManager; /** * @author billy.qi */ public class Util { public static boolean setStatusBarTransparent(Activity activity, boolean darkStatusBar) { View decorView = activity.getWindow().getDecorView(); boolean isInMultiWindowMode = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && activity.isInMultiWindowMode(); if (isInMultiWindowMode || Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) { return false; } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } else { int systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE; if (darkStatusBar && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { systemUiVisibility |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR; } decorView.setSystemUiVisibility(systemUiVisibility); activity.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); activity.getWindow().setStatusBarColor(Color.TRANSPARENT); } return true; } }
43.529412
119
0.715541
a793f32513990ae6a4a6727eb54ef353f957a809
1,949
package com.symbol.wfc.pttpro.intent; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import java.util.List; public class SpinnerAdapter extends ArrayAdapter { private Context mContext; private List<String> mList; public SpinnerAdapter(Context context, List<String> list) { super(context, R.layout.spinner_drop_down_view, list); mContext = context; this.mList = list; } @Override public View getDropDownView(int position, View convertView, ViewGroup parent) { return getCustomView(position, convertView, parent); } @Override public View getView(int position, View convertView, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.spinner_view_layout, null, true); ((TextView) convertView.findViewById(R.id.spinner_default_view)).setText(mList.get(position)); return convertView; } public View getCustomView(int position, View view, ViewGroup parent) { LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.spinner_drop_down_view, null, true); TextView title = view.findViewById(R.id.title); title.setText(mList.get(position)); ImageView image = view.findViewById(R.id.image_view); int drawableId = (mList.get(position).equals("Adhoc")) ? R.mipmap.ic_person_icon : R.mipmap.ic_group_icon_dark; image.setImageDrawable(mContext.getDrawable(drawableId)); return view; } @Override public int getCount() { return mList != null ? mList.size() : 0; } }
34.192982
119
0.710108
1dff1231ac063b956eff8b7f8cc4e9c8cbd04bb7
92
package br.com.olimposistema.aipa.anexo; public interface PathAnexo { String getPath(); }
15.333333
40
0.771739
8622fd3ef40d51ae795cd0364b291a1b4ac882c7
3,803
/* * ยฉ Copyright IBM Corp. 2010 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.ibm.xsp.extlib.sbt.model; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.util.HashMap; import java.util.List; import java.util.Map; import com.ibm.commons.util.StringUtil; import com.ibm.sbt.services.endpoints.Endpoint; import com.ibm.sbt.services.endpoints.EndpointFactory; import com.ibm.xsp.extlib.model.DataBlockAccessor; /** * Data accessor holding JSON objects. * <p> * </p> * @author Philippe Riand */ public abstract class RestDataBlockAccessor extends DataBlockAccessor { private static final long serialVersionUID = 1L; private String endpoint; private String serviceUrl; //private String authorizationBean; //private String url; private Map<String,String> urlParameters; public RestDataBlockAccessor() {} // Serializable public RestDataBlockAccessor(RestDataSource ds) { super(ds,ds.getMaxBlockCount()); this.endpoint = ds.getEndpoint(); this.serviceUrl = ds.getServiceUrl(); //this.url = ds.getUrl(); this.urlParameters = new HashMap<String, String>(); List<UrlParameter> params = ds.getUrlParameters(); if(params!=null && !params.isEmpty()) { for(UrlParameter p: params) { String name = p.getName(); String value = p.getValue(); urlParameters.put(name,value); } } } public String getServiceUrl() { return serviceUrl; } public com.ibm.sbt.services.endpoints.Endpoint findEndpointBean() { String name = getEndpoint(); String def = null; if(StringUtil.isEmpty(name)) { def = ((RestDataSource)getDataSource()).getDefaultEndpoint(); } Endpoint ep = EndpointFactory.getEndpoint(name, def); return ep; } public String findEndpointName(){ String name = getEndpoint(); if(StringUtil.isEmpty(name)){ name = ((RestDataSource)getDataSource()).getDefaultEndpoint(); } return name; } public String getEndpoint() { return endpoint; } public void setEndpoint(String endpoint) { this.endpoint = endpoint; } public Map<String, String> getUrlParameters() { return urlParameters; } public void setUrlParameters(Map<String, String> urlParameters) { this.urlParameters = urlParameters; } @Override public void writeExternal(ObjectOutput out) throws IOException { super.writeExternal(out); out.writeObject(endpoint); out.writeObject(serviceUrl); // out.writeObject(authorizationBean); // out.writeObject(url); out.writeObject(urlParameters); } @SuppressWarnings("unchecked") @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); endpoint = (String)in.readObject(); serviceUrl = (String)in.readObject(); // authorizationBean = (String)in.readObject(); // url = (String)in.readObject(); urlParameters = (Map<String,String>)in.readObject(); } }
31.172131
89
0.656587
ea6e7dd9bf697ca15391691874bde8e14680c016
343
package com.home.commonBase.constlist.generate; import com.home.commonBase.config.game.enumT.SceneTypeConfig; /** ๅœบๆ™ฏ็ฑปๅž‹(generated by shine) */ public class SceneType { /** ้•ฟๅบฆ */ public static int size=1; /** ่Žทๅ–ๅฎžไพ‹็ฑปๅž‹ */ public static int getInstanceType(int type) { return SceneTypeConfig.get(type).instanceType; } }
20.176471
62
0.696793
53bc1bf2d9d7eec0f993eed43339195a2e040f11
18,237
package hudson.plugins.disk_usage; import hudson.plugins.disk_usage.unused.DiskUsageNotUsedDataCalculationThread; import hudson.Extension; import hudson.Plugin; import hudson.Util; import hudson.model.*; import hudson.model.Item; import hudson.model.RootAction; import hudson.plugins.disk_usage.unused.DiskUsageItemGroup; import hudson.security.Permission; import hudson.util.Graph; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.servlet.ServletException; import jenkins.model.Jenkins; import org.jfree.data.category.DefaultCategoryDataset; import org.kohsuke.stapler.StaplerRequest; import org.kohsuke.stapler.StaplerResponse; /** * Entry point of the the plugin. * * @author dvrzalik */ @Extension public class DiskUsagePlugin extends Plugin { // private Long diskUsageBuilds = 0l; // private Long diskUsageJobsWithoutBuilds = 0l; // private Long diskUsageNotLoadedJobs = 0l; // private Long diskUsageNotLoadedBuilds = 0l; // private Long diskUsageWorkspaces = 0l; // private Long diskUsageLockedBuilds = 0l; // private Long diskUsageNonSlaveWorkspaces = 0l; private Map<ItemGroup,DiskUsageItemGroup> diskUsageItemGroups = new ConcurrentHashMap<ItemGroup,DiskUsageItemGroup>(); public DiskUsagePlugin(){ } public void addNewItemGroup(ItemGroup group, DiskUsageItemGroup diskUsage){ DiskUsageItemGroup usage = diskUsageItemGroups.get(group); diskUsageItemGroups.put(group, diskUsage); if(usage==null){ usage.load(); } } protected void loadDiskUsageItemGroups(){ diskUsageItemGroups.clear(); List<Action> actions = Jenkins.getInstance().getActions(); for(Action a : actions){ if(a instanceof DiskUsageJenkinsAction){ DiskUsageJenkinsAction jenkinsDUAction = (DiskUsageJenkinsAction) a; diskUsageItemGroups.put(Jenkins.getInstance(), jenkinsDUAction.getDiskUsageItemGroup()); loadAllDiskUsageForSubItemGroups(Jenkins.getInstance()); return; } } loadAllDiskUsageItemGroups(Jenkins.getInstance()); } public void loadAllDiskUsageForSubItemGroups(ItemGroup group){ for(Item item : (Collection<Item>)group.getItems()){ if(item instanceof ItemGroup){ loadAllDiskUsageItemGroups((ItemGroup)item); } } } protected void loadAllDiskUsageItemGroups(ItemGroup group){ DiskUsageItemGroup diskUsage = new DiskUsageItemGroup(group); diskUsage.load(); diskUsageItemGroups.put(group,diskUsage); for(Item item : (Collection<Item>)group.getItems()){ if(item instanceof ItemGroup){ loadAllDiskUsageItemGroups((ItemGroup)item); } } } public Map<ItemGroup,DiskUsageItemGroup> getDiskUsageItemGroups(){ return diskUsageItemGroups; } protected DiskUsageItemGroup loadDiskUsageItemGroupForItemGroup(ItemGroup group){ DiskUsageItemGroup diskUsage = new DiskUsageItemGroup(group); if(diskUsage.getConfigFile().exists()){ diskUsage.load(); } //new one else{ diskUsage.save(); } diskUsageItemGroups.put(group,diskUsage); return diskUsage; } public DiskUsageItemGroup getDiskUsageItemGrouForJenkinsRootAction(){ DiskUsageItemGroup usage = diskUsageItemGroups.get(Jenkins.getInstance()); if(usage==null){ usage = new DiskUsageItemGroup(Jenkins.getInstance()); usage.load(); diskUsageItemGroups.put(Jenkins.getInstance(),usage); } return usage; } public DiskUsageItemGroup getDiskUsageItemGroup(ItemGroup group){ DiskUsageItemGroup usage = diskUsageItemGroups.get(group); if(usage==null){ return loadDiskUsageItemGroupForItemGroup(group); } return usage; } public void putDiskUsageItemGroup(ItemGroup group) throws IOException{ if(!diskUsageItemGroups.containsKey(group)){ DiskUsageItemGroup usage = new DiskUsageItemGroup(group); diskUsageItemGroups.put(group, usage); usage.save(); } } public void removeDiskUsageItemGroup(ItemGroup group){ diskUsageItemGroups.remove(group); } // public void loadNotUsedDataDiskUsage(){ // diskUsageGroupItems.load(); // } public void refreshGlobalInformation() throws IOException{ DiskUsageJenkinsAction.getInstance().actualizeAllCashedDate(); } public Long getCashedGlobalBuildsDiskUsage(){ return getDiskUsageItemGrouForJenkinsRootAction().getCaschedDiskUsageBuilds().get("all"); } public Long getCashedGlobalJobsDiskUsage(){ return (getCashedGlobalBuildsDiskUsage() + getCashedGlobalJobsWithoutBuildsDiskUsage()); } public Long getCashedGlobalJobsWithoutBuildsDiskUsage(){ return getDiskUsageItemGrouForJenkinsRootAction().getCashedDiskUsageWithoutBuilds(); } public Long getCashedGlobalLockedBuildsDiskUsage(){ return getDiskUsageItemGrouForJenkinsRootAction().getCaschedDiskUsageBuilds().get("locked"); } public Long getCashedGlobalNotLoadedBuildsDiskUsage(){ return getDiskUsageItemGrouForJenkinsRootAction().getCaschedDiskUsageBuilds().get("notLoaded"); } public Long getCashedGlobalWorkspacesDiskUsage(){ return getDiskUsageItemGrouForJenkinsRootAction().getCashedDiskUsageWorkspaces(); } public Long getCashedNonSlaveDiskUsageWorkspace(){ return getDiskUsageItemGrouForJenkinsRootAction().getCashedDiskUsageCustomWorkspaces(); } public Long getCashedSlaveDiskUsageWorkspace(){ return getCashedGlobalWorkspacesDiskUsage() - getCashedNonSlaveDiskUsageWorkspace(); } public Long getGlobalBuildsDiskUsage() throws IOException{ refreshGlobalInformation(); return getCashedGlobalBuildsDiskUsage(); } public Long getGlobalJobsDiskUsage() throws IOException{ refreshGlobalInformation(); return getCashedGlobalJobsDiskUsage(); } public Long getGlobalJobsWithoutBuildsDiskUsage() throws IOException{ refreshGlobalInformation(); return getCashedGlobalJobsWithoutBuildsDiskUsage(); } public Long getGlobalWorkspacesDiskUsage() throws IOException{ refreshGlobalInformation(); return this.getCashedGlobalWorkspacesDiskUsage(); } public Long getGlobalNonSlaveDiskUsageWorkspace() throws IOException{ refreshGlobalInformation(); return getCashedNonSlaveDiskUsageWorkspace(); } public Long getGlobalSlaveDiskUsageWorkspace() throws IOException{ refreshGlobalInformation(); return getCashedSlaveDiskUsageWorkspace(); } public Long getGlobalNotLoadedBuildsDiskUsageWorkspace() throws IOException{ refreshGlobalInformation(); return getCashedGlobalNotLoadedBuildsDiskUsage(); } public BuildDiskUsageCalculationThread getBuildsDiskUsageThread(){ return AperiodicWork.all().get(BuildDiskUsageCalculationThread.class); } public JobWithoutBuildsDiskUsageCalculation getJobsDiskUsageThread(){ return AperiodicWork.all().get(JobWithoutBuildsDiskUsageCalculation.class); } public WorkspaceDiskUsageCalculationThread getWorkspaceDiskUsageThread(){ return AperiodicWork.all().get(WorkspaceDiskUsageCalculationThread.class); } public DiskUsageNotUsedDataCalculationThread getNotUsedDataDiskUsageThread(){ return AperiodicWork.all().get(DiskUsageNotUsedDataCalculationThread.class); } /** * @return DiskUsage for given project (shortcut for the view). Never null. */ public ProjectDiskUsageAction getDiskUsage(Job project) { ProjectDiskUsageAction action = project.getAction(ProjectDiskUsageAction.class); return action; } public String getDiskUsageInString(Long size){ return DiskUsageUtil.getSizeString(size); } /** * @return Project list sorted by occupied disk space */ public List getProjectList() throws IOException { refreshGlobalInformation(); Comparator<AbstractProject> comparator = new Comparator<AbstractProject>() { public int compare(AbstractProject o1, AbstractProject o2) { ProjectDiskUsageAction dua1 = getDiskUsage(o1); ProjectDiskUsageAction dua2 = getDiskUsage(o2); long result = dua2.getJobRootDirDiskUsage(true) + dua2.getAllDiskUsageWorkspace(true) - dua1.getJobRootDirDiskUsage(true) - dua1.getAllDiskUsageWorkspace(true); if(result > 0) return 1; if(result < 0) return -1; return 0; } }; List<AbstractProject> projectList = Jenkins.getInstance().getAllItems(AbstractProject.class); Collections.sort(projectList, comparator); return projectList; } public void doFilter(StaplerRequest req, StaplerResponse rsp) throws ServletException, IOException{ Date older = DiskUsageUtil.getDate(req.getParameter("older"), req.getParameter("olderUnit")); Date younger = DiskUsageUtil.getDate(req.getParameter("younger"), req.getParameter("youngerUnit")); req.setAttribute("filter", "filter"); req.setAttribute("older", older); req.setAttribute("younger", younger); req.getView(this, "index.jelly").forward(req, rsp); } public DiskUsageProjectActionFactory.DescriptorImpl getConfiguration(){ return DiskUsageProjectActionFactory.DESCRIPTOR; } public Graph getOverallGraph(){ File jobsDir = new File(Jenkins.getInstance().getRootDir(), "jobs"); long maxValue = getCashedGlobalJobsDiskUsage(); if(getConfiguration().getShowFreeSpaceForJobDirectory()){ maxValue = jobsDir.getTotalSpace(); } long maxValueWorkspace = Math.max(getCashedNonSlaveDiskUsageWorkspace(), getCashedSlaveDiskUsageWorkspace()); List<DiskUsageOvearallGraphGenerator.DiskUsageRecord> record = DiskUsageProjectActionFactory.DESCRIPTOR.getHistory(); //First iteration just to get scale of the y-axis for (DiskUsageOvearallGraphGenerator.DiskUsageRecord usage : record){ if(getConfiguration().getShowFreeSpaceForJobDirectory()){ maxValue = Math.max(maxValue,usage.getAllSpace()); } maxValue = Math.max(maxValue, usage.getJobsDiskUsage()); maxValueWorkspace = Math.max(maxValueWorkspace, usage.getSlaveWorkspacesUsage()); maxValueWorkspace = Math.max(maxValueWorkspace, usage.getNonSlaveWorkspacesUsage()); } int floor = (int) DiskUsageUtil.getScale(maxValue); int floorWorkspace = (int) DiskUsageUtil.getScale(maxValueWorkspace); String unit = DiskUsageUtil.getUnitString(floor); String unitWorkspace = DiskUsageUtil.getUnitString(floorWorkspace); double base = Math.pow(1024, floor); double baseWorkspace = Math.pow(1024, floorWorkspace); DefaultCategoryDataset dataset = new DefaultCategoryDataset(); DefaultCategoryDataset datasetW = new DefaultCategoryDataset(); for (DiskUsageOvearallGraphGenerator.DiskUsageRecord usage : record) { Date label = usage.getDate(); if(getConfiguration().getShowFreeSpaceForJobDirectory()){ dataset.addValue(((Long) usage.getAllSpace()) / base, "space for jobs directory", label); } dataset.addValue(((Long) usage.getJobsDiskUsage()) / base, "all jobs", label); dataset.addValue(((Long) usage.getBuildsDiskUsage()) / base, "all builds", label); datasetW.addValue(((Long) usage.getSlaveWorkspacesUsage()) / baseWorkspace, "slave workspaces", label); datasetW.addValue(((Long) usage.getNonSlaveWorkspacesUsage()) / baseWorkspace, "non slave workspaces", label); } //add current state if(getConfiguration().getShowFreeSpaceForJobDirectory()){ dataset.addValue(((Long) jobsDir.getTotalSpace()) / base, "space for jobs directory", "current"); } dataset.addValue(((Long) getCashedGlobalJobsDiskUsage()) / base, "all jobs", "current"); dataset.addValue(((Long) getCashedGlobalBuildsDiskUsage()) / base, "all builds", "current"); datasetW.addValue(((Long) getCashedSlaveDiskUsageWorkspace()) / baseWorkspace, "slave workspaces", "current"); datasetW.addValue(((Long) getCashedNonSlaveDiskUsageWorkspace()) / baseWorkspace, "non slave workspaces", "current"); return new DiskUsageGraph(dataset, unit, datasetW, unitWorkspace); } public void doRecordBuildDiskUsage(StaplerRequest req, StaplerResponse res) throws ServletException, IOException, Exception { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); if(getConfiguration().isCalculationBuildsEnabled() && !getBuildsDiskUsageThread().isExecuting()) getBuildsDiskUsageThread().doAperiodicRun(); res.forwardToPreviousPage(req); } public void doRecordJobsDiskUsage(StaplerRequest req, StaplerResponse res) throws ServletException, IOException, Exception { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); if(getConfiguration().isCalculationJobsEnabled() && !getJobsDiskUsageThread().isExecuting()) getJobsDiskUsageThread().doAperiodicRun(); res.forwardToPreviousPage(req); } public void doRecordWorkspaceDiskUsage(StaplerRequest req, StaplerResponse res) throws ServletException, IOException, Exception { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); if(getConfiguration().isCalculationWorkspaceEnabled() && !getWorkspaceDiskUsageThread().isExecuting()) getWorkspaceDiskUsageThread().doAperiodicRun(); res.forwardToPreviousPage(req); } public void doRecordNotUsedDataDiskUsage(StaplerRequest req, StaplerResponse res) throws ServletException, IOException, Exception { Jenkins.getInstance().checkPermission(Jenkins.ADMINISTER); if(getConfiguration().isCalculationNotUsedDataEnabled() && !getNotUsedDataDiskUsageThread().isExecuting()) getNotUsedDataDiskUsageThread().doAperiodicRun(); res.forwardToPreviousPage(req); } public String getCountIntervalForBuilds(){ long nextExecution = getBuildsDiskUsageThread().scheduledLastInstanceExecutionTime() - System.currentTimeMillis(); if(nextExecution<=0) //not scheduled nextExecution = getBuildsDiskUsageThread().getRecurrencePeriod(); return DiskUsageUtil.formatTimeInMilisec(nextExecution); } public String getCountIntervalForJobs(){ long nextExecution = getJobsDiskUsageThread().scheduledLastInstanceExecutionTime() - System.currentTimeMillis(); if(nextExecution<=0) //not scheduled nextExecution = getJobsDiskUsageThread().getRecurrencePeriod(); return DiskUsageUtil.formatTimeInMilisec(nextExecution); } public String getCountIntervalForWorkspaces(){ long nextExecution = getWorkspaceDiskUsageThread().scheduledLastInstanceExecutionTime() - System.currentTimeMillis(); if(nextExecution<=0) //not scheduled nextExecution = getWorkspaceDiskUsageThread().getRecurrencePeriod(); return DiskUsageUtil.formatTimeInMilisec(nextExecution); } public boolean hasAdministrativePermission(){ return Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER); } public String getCountIntervalForNotUsedData(){ long nextExecution = getNotUsedDataDiskUsageThread().scheduledLastInstanceExecutionTime() - System.currentTimeMillis(); if(nextExecution<=0) //not scheduled nextExecution = getNotUsedDataDiskUsageThread().getRecurrencePeriod(); return DiskUsageUtil.formatTimeInMilisec(nextExecution); } public String getTotalSizeOfNotLoadedBuilds(){ Long size = 0L; for(Item item : Jenkins.getInstance().getItems()){ if(item instanceof AbstractProject){ AbstractProject project = (AbstractProject) item; ProjectDiskUsageAction action = project.getAction(ProjectDiskUsageAction.class); size += action.getAllDiskUsageNotLoadedBuilds(true); } } return DiskUsageUtil.getSizeString(size); } public Map<AbstractProject,Long> getNotLoadedBuilds(){ Map<AbstractProject,Long> notLoadedBuilds = new HashMap<AbstractProject,Long>(); for(Item item : Jenkins.getInstance().getItems()){ if(item instanceof AbstractProject){ AbstractProject project = (AbstractProject) item; ProjectDiskUsage usage = DiskUsageUtil.getDiskUsageProperty(project).getDiskUsage(); ProjectDiskUsageAction action = project.getAction(ProjectDiskUsageAction.class); if(!usage.getNotLoadedBuilds().isEmpty()){ notLoadedBuilds.put(project, action.getAllDiskUsageNotLoadedBuilds(true)); } } } return notLoadedBuilds; } public void doUnused(StaplerRequest req, StaplerResponse res) throws IOException, ServletException{ Map<AbstractProject,Map<String,Long>> notLoadedBuilds = new HashMap<AbstractProject,Map<String,Long>>(); Map<String,Long> notLoadedJobs = new HashMap<String,Long>(); req.getView(this, "unused.jelly").forward(req, res); } }
42.709602
176
0.695125
c25919c40cc15196c98a2593bd981c64a1098fbb
1,278
package com.test.newshop1.ui.profileActivity; import androidx.lifecycle.ViewModelProviders; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.test.newshop1.R; import com.test.newshop1.ui.ViewModelFactory; import com.test.newshop1.utilities.InjectorUtil; public class ProfileFragment extends Fragment { private ProfileViewModel mViewModel; public static ProfileFragment newInstance() { return new ProfileFragment(); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.profile_fragment, container, false); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ViewModelFactory factory = InjectorUtil.provideViewModelFactory(getActivity()); mViewModel = ViewModelProviders.of(getActivity(), factory).get(ProfileViewModel.class); // TODO: Use the ViewModel } }
31.95
95
0.754304
493e18f56ff4ed882e9cc645909c2508211ef19d
316
package Factory.FactoryMethod; public class Consumer { public static void main(String[] args) { TF_Factory tf_factory = new TF_Factory(); TF lipStick = tf_factory.getLipStick(); lipStick.show(); YSL lipStick1 = new YSL_Factory().getLipStick(); lipStick1.show(); } }
24.307692
56
0.639241
6af56492e9c61192a2cd59d00f2c773c66c4db49
1,228
/* * Copyright 2014-present IVK JSC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.broker.libupmq.transport; import java.io.IOException; /** * An asynchronous listener of commands * * */ public interface TransportListener { /** * called to process a command * * @param command */ void onCommand(Object command); /** * An unrecoverable exception has occured on the transport * * @param error */ void onException(IOException error); /** * The transport has suffered an interuption from which it hopes to recover * */ void transportInterupted(); /** * The transport has resumed after an interuption * */ void transportResumed(); }
22.327273
76
0.710098
fc32f1558dc15ff24387f721d9b1dfdafca6bd2b
1,837
package net.minestom.server.inventory; import net.minestom.server.inventory.condition.InventoryCondition; import net.minestom.server.item.ItemStack; import org.jetbrains.annotations.NotNull; import java.util.List; /** * Represents an inventory where its items can be modified/retrieved. */ public interface InventoryModifier { /** * Sets an {@link ItemStack} at the specified slot. * * @param slot the slot to set the item * @param itemStack the item to set */ void setItemStack(int slot, @NotNull ItemStack itemStack); /** * Adds an {@link ItemStack} to the inventory. * * @param itemStack the item to add * @return true if the item has been successfully fully added, false otherwise */ boolean addItemStack(@NotNull ItemStack itemStack); /** * Clears the inventory. */ void clear(); /** * Gets the {@link ItemStack} at the specified slot. * * @param slot the slot to check * @return the item in the slot {@code slot} */ @NotNull ItemStack getItemStack(int slot); /** * Gets all the {@link ItemStack} in the inventory. * * @return an array containing all the inventory's items */ @NotNull ItemStack[] getItemStacks(); /** * Gets the size of the inventory. * * @return the inventory's size */ int getSize(); /** * Gets all the {@link InventoryCondition} of this inventory. * * @return the inventory conditions */ @NotNull List<InventoryCondition> getInventoryConditions(); /** * Adds a new {@link InventoryCondition} to this inventory. * * @param inventoryCondition the inventory condition to add */ void addInventoryCondition(@NotNull InventoryCondition inventoryCondition); }
24.824324
82
0.643985
52dfd0d00d6860eb4c17789489e4d47cf1434c0b
217
package com.myzuji.study.java.easyexcel.read; import com.alibaba.excel.annotation.ExcelProperty; import lombok.Data; @Data public class DemoData1 { @ExcelProperty("ๅ•†ๆˆท่ฎขๅ•ๅท") private String merchantOrderNo; }
18.083333
50
0.774194
e90bda50d10a2dc302c0d89a2700eca8c3509ecc
1,012
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package entiteis; /** * * @author valmi */ public class Conta { private int conta; private String nome; protected double saldo; public Conta(){ } public Conta(int conta, String nome, double saldo) { this.conta = conta; this.nome = nome; this.saldo = saldo; } public int getConta() { return conta; } public void setConta(int conta) { this.conta = conta; } public String getNome() { return nome; } public void setNome(String nome) { this.nome = nome; } public double getSaldo() { return saldo; } public void saque(double conta){ saldo = saldo - conta; } public void deposito(double conta){ saldo = saldo + conta; } }
17.754386
79
0.567194
ed6d5d1f03b234f70b41fbc691b400d0f4a2c5df
855
package net.core.tutorial.medium._08_Multithreading.exampleForProducerAndConsumer; /** * Consumer from the producer-consumer approach. * @author Ihor Savchenko * @version 1.0 */ public class Consumer implements Runnable{ private final int id; private final SingleElementBuffer monitor; public Consumer(SingleElementBuffer monitor, int id) { this.monitor = monitor; this.id = id; } public void run() { while(true){ try { Integer element = monitor.get(); System.out.println(System.currentTimeMillis() + ": " + element + " consumed by consumer with id=" + id); } catch(InterruptedException e) { System.out.println(Thread.currentThread().getName() + " was stopped"); return; } } } }
27.580645
120
0.596491
a70516dcbc8a3b13a04c729d2aa39ef7e23a23ec
569
package iskallia.vaultgen.mixin; import iskallia.vaultgen.IDimContext; import net.minecraft.util.RegistryKey; import net.minecraft.world.World; import net.minecraft.world.gen.LazyAreaLayerContext; import org.spongepowered.asm.mixin.Mixin; @Mixin(LazyAreaLayerContext.class) public class MixinLazyAreaLayerContext implements IDimContext { public RegistryKey<World> dimension; @Override public RegistryKey<World> getDimension() { return this.dimension; } @Override public void setDimension(RegistryKey<World> dimension) { this.dimension = dimension; } }
22.76
63
0.806678
5fd3aee000577c742026ba3d75f507f77d61e559
5,699
package de.knoobie.project.nagisa.gson.model.bo; import de.knoobie.project.clannadutils.common.ListUtils; import de.knoobie.project.clannadutils.common.StringUtils; import de.knoobie.project.nagisa.gson.model.bo.enums.VGMdbNameLanguage; import de.knoobie.project.nagisa.gson.model.bo.enums.VGMdbProductType; import de.knoobie.project.nagisa.gson.model.bo.enums.VGMdbWebsiteType; import de.knoobie.project.nagisa.gson.model.dto.json.common.Names; import de.knoobie.project.nagisa.gson.model.dto.json.product.Product; import java.util.ArrayList; import java.util.List; import lombok.Data; public @Data class VGMdbProduct { public static final String VGMDB_DIR = "product"; private String description; private String link; private VGMdbMeta meta; private String name; private String organizations; private VGMdbPicture picture; private String releaseDate; private VGMdbProductType type; private String vgmdbLink; // need 4 another VGMdbProduct private List<VGMdbName> names = new ArrayList<>(); /** * Alle Titel die zu diesem Francise gehรถren -> z.B. Clannad 5 Stk ( Games & * Series ) */ private List<VGMdbProductMerchandise> titles = new ArrayList<>(); /** * Francise des Products -> z.B. 'Shigatsu wa Kimi no Uso' / 'Clannad' */ private List<VGMdbProductMerchandise> franchises = new ArrayList<>(); /** * Release einer Serie / eines Games -> z.B. Shigatsu wa Kimi no Uso Anime * Serie / Clannad Game */ private List<VGMdbProductMerchandise> releases = new ArrayList<>(); /** * Alben related to this Product */ private List<VGMdbAlbum> albums = new ArrayList<>(); private List<VGMdbWebsite> websites = new ArrayList<>(); public VGMdbProduct(Names names, String link) { this(names, link, StringUtils.EMPTY); } public VGMdbProduct(Names names, String link, String type) { this.setNames(VGMdbName.parseNames(names)); this.setLink(StringUtils.trim(link)); this.setType(VGMdbProductType.getProductTypeByName(type)); } public VGMdbProduct(Product product) { if (product == null) { return; } this.setName(StringUtils.trim(product.getName())); this.getNames().add(new VGMdbName(StringUtils.trim(product.getRealName()), VGMdbNameLanguage.original)); this.setLink(StringUtils.trim(product.getLink())); this.setReleaseDate(StringUtils.trim(product.getReleaseDate())); this.setDescription(StringUtils.trim(product.getDescription())); this.setOrganizations(ListUtils.getListAsString(product.getOrganizations())); this.setType(VGMdbProductType.getProductTypeByName(product.getType())); this.setVgmdbLink(StringUtils.trim(product.getVgmdbLink())); this.setMeta(new VGMdbMeta(product.getMeta())); this.setPicture(new VGMdbPicture(StringUtils.trim(product.getPictureSmall()), StringUtils.trim(product.getPictureFull()))); if (!ListUtils.isEmpty(product.getAlbums())) { product.getAlbums().stream().forEach((album) -> { getAlbums().add(new VGMdbAlbum( album.getNames(), album.getLink(), album.getCatalog(), album.getType(), album.getDate(), album.getReprint(), album.getClassifications())); }); } if (!ListUtils.isEmpty(product.getTitles())) { product.getTitles().stream().forEach((merchandise) -> { getTitles().add(new VGMdbProductMerchandise(merchandise)); }); } if (!ListUtils.isEmpty(product.getFranchises())) { product.getFranchises().stream().forEach((franchise) -> { getFranchises().add(new VGMdbProductMerchandise(franchise)); }); } if (!ListUtils.isEmpty(product.getReleases())) { product.getReleases().stream().forEach((release) -> { getReleases().add(new VGMdbProductMerchandise(release)); }); } if (product.getWebsites() != null) { if (!ListUtils.isEmpty(product.getWebsites().getOfficial())) { product.getWebsites().getOfficial().stream().forEach((officialWebsite) -> { getWebsites().add(new VGMdbWebsite( officialWebsite.getName(), officialWebsite.getLink(), VGMdbWebsiteType.official)); }); } if (!ListUtils.isEmpty(product.getWebsites().getPersonal())) { product.getWebsites().getPersonal().stream().forEach((personalWebsite) -> { getWebsites().add(new VGMdbWebsite( personalWebsite.getName(), personalWebsite.getLink(), VGMdbWebsiteType.personal)); }); } if (!ListUtils.isEmpty(product.getWebsites().getReference())) { product.getWebsites().getReference().stream().forEach((referenceWebsite) -> { getWebsites().add(new VGMdbWebsite( referenceWebsite.getName(), referenceWebsite.getLink(), VGMdbWebsiteType.reference)); }); } } } }
40.133803
113
0.586243
7b34967dc0eb40d89a2e0325159ccf4b8c564b59
1,781
package stack.simulator.machine.events; import stack.excetpion.SimulatorException; import stack.simulator.Context; import stack.simulator.des.DiscreteEventSimulator; import stack.simulator.des.Event; import stack.simulator.machine.models.CoreModel; public class RAEvent extends Event { Context context; CoreModel src, target; MessageType type; int address, data; public RAEvent(Context context, CoreModel src, CoreModel target, MessageType type, int address, int data) { this.context = context; this.src = src; this.target = target; this.type = type; this.address = address; this.data = data; } @Override public void callback(DiscreteEventSimulator DES) throws SimulatorException { RAEvent response; switch (type){ case RABlockingStore: target.store(address, data); // send ack response = new RAEvent(context, target, src, MessageType.RABlockingStoreAck, 0, 0); target.sendRA(target, src, response); break; case RAStore: target.store(address, data); // send ack response = new RAEvent(context, target, src, MessageType.RAAck, 0, 0); target.sendRA(target, src, response); break; case RAStoreNoAck: target.store(address, data); break; case RABlockingStoreAck: context.endStall(); context.registerAck(); break; case RAAck: context.registerAck(); break; case RALoad: data = target.load(address); response = new RAEvent(context, target, src, MessageType.RALoadResponse, address, data); target.sendRA(target, src, response); break; case RALoadResponse: src.getStack(0, context).add(0, data); context.endStall(); context.cycle(); break; default: throw new SimulatorException("unknown RA message!"); } } public MessageType getType(){ return type; } }
25.442857
108
0.718697
32c35fc040f8c61f8d79a362500f22f12440e441
523
package ru.apetrov.generic; /** * Created by Andrey on 08.03.2017. */ public abstract class Base { /** * id of model. */ private String id; /** * Constructor of class. * @param id id. */ public Base(String id) { this.id = id; } /** * Getter of id. * @return id id. */ public String getId() { return id; } /** * Setter of id. * @param id id. */ public void setId(String id) { this.id = id; } }
14.135135
35
0.464627
bd3c51f8c85ccec317afec42f5414bacafbd02b6
131
package top.eatfingersss.sudokugamedemo.view; public interface EncapsilationView { void nodeGet(); void addListenner(); }
18.714286
45
0.755725
9357aa06dad1091e35549ba87bf02ce4d84b0267
882
package com.company; import javafx.util.Pair; import java.util.Comparator; import java.util.Map; import java.util.PriorityQueue; import java.util.Scanner; public class Main { public static void main(String args[]) { Scanner in = new Scanner(System.in); // game loop int index = 0, val = 0; while (true) { val = -1; index = 0; for (int i = 0; i < 8; i++) { int mountainH = in.nextInt(); // represents the height of one mountain. if(mountainH > val){ index = i; val = mountainH; } } // Write an action using System.out.println() // To debug: System.err.println("Debug messages..."); System.out.println(index); // The index of the mountain to fire on. } } }
25.2
87
0.514739
ddce24592e60ec2ec6235ffe4badd05dca2e811a
1,102
package ca.on.oicr.gsi.vidarr; import java.util.Map; import org.junit.Assert; public class ListBasicTypeTest extends BasicTypeTest { String listStringFormat = "{\"is\":\"list\",\"inner\":\"%s\"}"; @Override public void testSerialize() { for (Map.Entry<BasicType, String> type : primitiveTypes.entrySet()) { serializeTester(String.format(listStringFormat, type.getValue()), type.getKey().asList()); } } @Override public void testDeserialize() { for (Map.Entry<BasicType, String> type : primitiveTypes.entrySet()) { deserializeTester(type.getKey().asList(), String.format(listStringFormat, type.getValue())); } } @Override public void testEquals() { BasicType list1 = BasicType.INTEGER.asList(), list2 = BasicType.INTEGER.asList(), listDifferent = BasicType.BOOLEAN.asList(), integer = BasicType.INTEGER; Assert.assertEquals(list1, list1); Assert.assertEquals(list2, list1); Assert.assertNotEquals(null, list1); Assert.assertNotEquals(listDifferent, list1); Assert.assertNotEquals(integer, list1); } }
29.783784
98
0.69147
2afe7389f1ccd69e2ae2d8365d3f533db553e2b2
31,570
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.numbers.fraction; import java.io.Serializable; import org.apache.commons.numbers.core.ArithmeticUtils; import org.apache.commons.numbers.core.NativeOperators; /** * Representation of a rational number. * * <p>The number is expressed as the quotient {@code p/q} of two 32-bit integers, * a numerator {@code p} and a non-zero denominator {@code q}. * * <p>This class is immutable. * * <a href="https://en.wikipedia.org/wiki/Rational_number">Rational number</a> */ public final class Fraction extends Number implements Comparable<Fraction>, NativeOperators<Fraction>, Serializable { /** A fraction representing "0". */ public static final Fraction ZERO = new Fraction(0); /** A fraction representing "1". */ public static final Fraction ONE = new Fraction(1); /** Serializable version identifier. */ private static final long serialVersionUID = 20190701L; /** The default epsilon used for convergence. */ private static final double DEFAULT_EPSILON = 1e-5; /** The default iterations used for convergence. */ private static final int DEFAULT_MAX_ITERATIONS = 100; /** Message for non-finite input double argument to factory constructors. */ private static final String NOT_FINITE = "Not finite: "; /** The overflow limit for conversion from a double (2^31). */ private static final long OVERFLOW = 1L << 31; /** The numerator of this fraction reduced to lowest terms. */ private final int numerator; /** The denominator of this fraction reduced to lowest terms. */ private final int denominator; /** * Private constructor: Instances are created using factory methods. * * <p>This constructor should only be invoked when the fraction is known * to be non-zero; otherwise use {@link #ZERO}. This avoids creating * the zero representation {@code 0 / -1}. * * @param num Numerator. * @param den Denominator. * @throws ArithmeticException if the denominator is {@code zero}. */ private Fraction(int num, int den) { if (den == 0) { throw new FractionException(FractionException.ERROR_ZERO_DENOMINATOR); } if (num == den) { numerator = 1; denominator = 1; } else { // Reduce numerator (p) and denominator (q) by greatest common divisor. int p; int q; // If num and den are both 2^-31, or if one is 0 and the other is 2^-31, // the calculation of the gcd below will fail. Ensure that this does not // happen by dividing both by 2 in case both are even. if (((num | den) & 1) == 0) { p = num >> 1; q = den >> 1; } else { p = num; q = den; } // Will not throw. // Cannot return 0 as gcd(0, 0) has been eliminated. final int d = ArithmeticUtils.gcd(p, q); numerator = p / d; denominator = q / d; } } /** * Private constructor: Instances are created using factory methods. * * <p>This sets the denominator to 1. * * @param num Numerator. */ private Fraction(int num) { numerator = num; denominator = 1; } /** * Create a fraction given the double value and either the maximum error * allowed or the maximum number of denominator digits. * * <p> * NOTE: This constructor is called with: * <ul> * <li>EITHER a valid epsilon value and the maxDenominator set to * Integer.MAX_VALUE (that way the maxDenominator has no effect) * <li>OR a valid maxDenominator value and the epsilon value set to * zero (that way epsilon only has effect if there is an exact * match before the maxDenominator value is reached). * </ul> * <p> * It has been done this way so that the same code can be reused for * both scenarios. However this could be confusing to users if it * were part of the public API and this method should therefore remain * PRIVATE. * </p> * * <p> * See JIRA issue ticket MATH-181 for more details: * https://issues.apache.org/jira/browse/MATH-181 * </p> * * <p> * Warning: This conversion assumes the value is not zero. * </p> * * @param value Value to convert to a fraction. Must not be zero. * @param epsilon Maximum error allowed. * The resulting fraction is within {@code epsilon} of {@code value}, * in absolute terms. * @param maxDenominator Maximum denominator value allowed. * @param maxIterations Maximum number of convergents. * @throws IllegalArgumentException if the given {@code value} is NaN or infinite. * @throws ArithmeticException if the continued fraction failed to converge. */ private Fraction(final double value, final double epsilon, final int maxDenominator, final int maxIterations) { if (!Double.isFinite(value)) { throw new IllegalArgumentException(NOT_FINITE + value); } // Remove sign, this is restored at the end. // (Assumes the value is not zero and thus signum(value) is not zero). final double absValue = Math.abs(value); double r0 = absValue; long a0 = (long) Math.floor(r0); if (a0 > OVERFLOW) { throw new FractionException(FractionException.ERROR_CONVERSION_OVERFLOW, value, a0, 1); } // check for (almost) integer arguments, which should not go to iterations. if (r0 - a0 <= epsilon) { int num = (int) a0; int den = 1; // Restore the sign. if (Math.signum(num) != Math.signum(value)) { if (num == Integer.MIN_VALUE) { den = -den; } else { num = -num; } } this.numerator = num; this.denominator = den; return; } // Support 2^31 as maximum denominator. // This is negative as an integer so convert to long. final long maxDen = Math.abs((long) maxDenominator); long p0 = 1; long q0 = 0; long p1 = a0; long q1 = 1; long p2 = 0; long q2 = 1; int n = 0; boolean stop = false; do { ++n; final double r1 = 1.0 / (r0 - a0); final long a1 = (long) Math.floor(r1); p2 = (a1 * p1) + p0; q2 = (a1 * q1) + q0; if (Long.compareUnsigned(p2, OVERFLOW) > 0 || Long.compareUnsigned(q2, OVERFLOW) > 0) { // In maxDenominator mode, fall-back to the previous valid fraction. if (epsilon == 0.0) { p2 = p1; q2 = q1; break; } throw new FractionException(FractionException.ERROR_CONVERSION_OVERFLOW, value, p2, q2); } final double convergent = (double) p2 / (double) q2; if (n < maxIterations && Math.abs(convergent - absValue) > epsilon && q2 < maxDen) { p0 = p1; p1 = p2; q0 = q1; q1 = q2; a0 = a1; r0 = r1; } else { stop = true; } } while (!stop); if (n >= maxIterations) { throw new FractionException(FractionException.ERROR_CONVERSION, value, maxIterations); } // Use p2 / q2 or p1 / q1 if q2 has grown too large in maxDenominator mode // Note: Conversion of long 2^31 to an integer will create a negative. This could // be either the numerator or denominator. This is handled by restoring the sign. int num; int den; if (q2 <= maxDen) { num = (int) p2; den = (int) q2; } else { num = (int) p1; den = (int) q1; } // Restore the sign. if (Math.signum(num) * Math.signum(den) != Math.signum(value)) { if (num == Integer.MIN_VALUE) { den = -den; } else { num = -num; } } this.numerator = num; this.denominator = den; } /** * Create a fraction given the double value. * * @param value Value to convert to a fraction. * @throws IllegalArgumentException if the given {@code value} is NaN or infinite. * @throws ArithmeticException if the continued fraction failed to converge. * @return a new instance. */ public static Fraction from(final double value) { return from(value, DEFAULT_EPSILON, DEFAULT_MAX_ITERATIONS); } /** * Create a fraction given the double value and maximum error allowed. * * <p> * References: * <ul> * <li><a href="http://mathworld.wolfram.com/ContinuedFraction.html"> * Continued Fraction</a> equations (11) and (22)-(26)</li> * </ul> * * @param value Value to convert to a fraction. * @param epsilon Maximum error allowed. The resulting fraction is within * {@code epsilon} of {@code value}, in absolute terms. * @param maxIterations Maximum number of convergents. * @throws IllegalArgumentException if the given {@code value} is NaN or infinite; * {@code epsilon} is not positive; or {@code maxIterations < 1}. * @throws ArithmeticException if the continued fraction failed to converge. * @return a new instance. */ public static Fraction from(final double value, final double epsilon, final int maxIterations) { if (value == 0) { return ZERO; } if (maxIterations < 1) { throw new IllegalArgumentException("Max iterations must be strictly positive: " + maxIterations); } if (epsilon >= 0) { return new Fraction(value, epsilon, Integer.MIN_VALUE, maxIterations); } throw new IllegalArgumentException("Epsilon must be positive: " + maxIterations); } /** * Create a fraction given the double value and maximum denominator. * * <p> * References: * <ul> * <li><a href="http://mathworld.wolfram.com/ContinuedFraction.html"> * Continued Fraction</a> equations (11) and (22)-(26)</li> * </ul> * * <p>Note: The magnitude of the {@code maxDenominator} is used allowing use of * {@link Integer#MIN_VALUE} for a supported maximum denominator of 2<sup>31</sup>. * * @param value Value to convert to a fraction. * @param maxDenominator Maximum allowed value for denominator. * @throws IllegalArgumentException if the given {@code value} is NaN or infinite * or {@code maxDenominator} is zero. * @throws ArithmeticException if the continued fraction failed to converge. * @return a new instance. */ public static Fraction from(final double value, final int maxDenominator) { if (value == 0) { return ZERO; } if (maxDenominator == 0) { // Re-use the zero denominator message throw new IllegalArgumentException(FractionException.ERROR_ZERO_DENOMINATOR); } return new Fraction(value, 0, maxDenominator, DEFAULT_MAX_ITERATIONS); } /** * Create a fraction given the numerator. The denominator is {@code 1}. * * @param num Numerator. * @return a new instance. */ public static Fraction of(final int num) { if (num == 0) { return ZERO; } return new Fraction(num); } /** * Create a fraction given the numerator and denominator. * The fraction is reduced to lowest terms. * * @param num Numerator. * @param den Denominator. * @throws ArithmeticException if the denominator is {@code zero}. * @return a new instance. */ public static Fraction of(final int num, final int den) { if (num == 0) { return ZERO; } return new Fraction(num, den); } /** * Returns a {@code Fraction} instance representing the specified string {@code s}. * * <p>If {@code s} is {@code null}, then a {@code NullPointerException} is thrown. * * <p>The string must be in a format compatible with that produced by * {@link #toString() Fraction.toString()}. * The format expects an integer optionally followed by a {@code '/'} character and * and second integer. Leading and trailing spaces are allowed around each numeric part. * Each numeric part is parsed using {@link Integer#parseInt(String)}. The parts * are interpreted as the numerator and optional denominator of the fraction. If absent * the denominator is assumed to be "1". * * <p>Examples of valid strings and the equivalent {@code Fraction} are shown below: * * <pre> * "0" = Fraction.of(0) * "42" = Fraction.of(42) * "0 / 1" = Fraction.of(0, 1) * "1 / 3" = Fraction.of(1, 3) * "-4 / 13" = Fraction.of(-4, 13)</pre> * * <p>Note: The fraction is returned in reduced form and the numerator and denominator * may not match the values in the input string. For this reason the result of * {@code Fraction.parse(s).toString().equals(s)} may not be {@code true}. * * @param s String representation. * @return an instance. * @throws NullPointerException if the string is null. * @throws NumberFormatException if the string does not contain a parsable fraction. * @see Integer#parseInt(String) * @see #toString() */ public static Fraction parse(String s) { final String stripped = s.replace(",", ""); final int slashLoc = stripped.indexOf('/'); // if no slash, parse as single number if (slashLoc == -1) { return of(Integer.parseInt(stripped.trim())); } final int num = Integer.parseInt(stripped.substring(0, slashLoc).trim()); final int denom = Integer.parseInt(stripped.substring(slashLoc + 1).trim()); return of(num, denom); } @Override public Fraction zero() { return ZERO; } @Override public Fraction one() { return ONE; } /** * Access the numerator as an {@code int}. * * @return the numerator as an {@code int}. */ public int getNumerator() { return numerator; } /** * Access the denominator as an {@code int}. * * @return the denominator as an {@code int}. */ public int getDenominator() { return denominator; } /** * Retrieves the sign of this fraction. * * @return -1 if the value is strictly negative, 1 if it is strictly * positive, 0 if it is 0. */ public int signum() { return Integer.signum(numerator) * Integer.signum(denominator); } /** * Returns the absolute value of this fraction. * * @return the absolute value. */ public Fraction abs() { return signum() >= 0 ? this : negate(); } @Override public Fraction negate() { return numerator == Integer.MIN_VALUE ? new Fraction(numerator, -denominator) : new Fraction(-numerator, denominator); } /** * {@inheritDoc} * * <p>Raises an exception if the fraction is equal to zero. * * @throws ArithmeticException if the current numerator is {@code zero} */ @Override public Fraction reciprocal() { return new Fraction(denominator, numerator); } /** * Returns the {@code double} value closest to this fraction. * This calculates the fraction as numerator divided by denominator. * * @return the fraction as a {@code double}. */ @Override public double doubleValue() { return (double) numerator / (double) denominator; } /** * Returns the {@code float} value closest to this fraction. * This calculates the fraction as numerator divided by denominator. * * @return the fraction as a {@code float}. */ @Override public float floatValue() { return (float) doubleValue(); } /** * Returns the whole number part of the fraction. * * @return the largest {@code int} value that is not larger than this fraction. */ @Override public int intValue() { // Note: numerator / denominator fails for Integer.MIN_VALUE / -1. // Casting the double value handles this case. return (int) doubleValue(); } /** * Returns the whole number part of the fraction. * * @return the largest {@code long} value that is not larger than this fraction. */ @Override public long longValue() { return (long) numerator / denominator; } /** * Adds the specified {@code value} to this fraction, returning * the result in reduced form. * * @param value Value to add. * @return {@code this + value}. * @throws ArithmeticException if the resulting numerator * cannot be represented in an {@code int}. */ public Fraction add(final int value) { if (value == 0) { return this; } if (isZero()) { return new Fraction(value); } // Convert to numerator with same effective denominator final long num = (long) value * denominator; return of(Math.toIntExact(numerator + num), denominator); } /** * Adds the specified {@code value} to this fraction, returning * the result in reduced form. * * @param value Value to add. * @return {@code this + value}. * @throws ArithmeticException if the resulting numerator or denominator * cannot be represented in an {@code int}. */ @Override public Fraction add(Fraction value) { return addSub(value, true /* add */); } /** * Subtracts the specified {@code value} from this fraction, returning * the result in reduced form. * * @param value Value to subtract. * @return {@code this - value}. * @throws ArithmeticException if the resulting numerator * cannot be represented in an {@code int}. */ public Fraction subtract(final int value) { if (value == 0) { return this; } if (isZero()) { // Special case for min value return value == Integer.MIN_VALUE ? new Fraction(Integer.MIN_VALUE, -1) : new Fraction(-value); } // Convert to numerator with same effective denominator final long num = (long) value * denominator; return of(Math.toIntExact(numerator - num), denominator); } /** * Subtracts the specified {@code value} from this fraction, returning * the result in reduced form. * * @param value Value to subtract. * @return {@code this - value}. * @throws ArithmeticException if the resulting numerator or denominator * cannot be represented in an {@code int}. */ @Override public Fraction subtract(Fraction value) { return addSub(value, false /* subtract */); } /** * Implements add and subtract using algorithm described in Knuth 4.5.1. * * @param value Fraction to add or subtract. * @param isAdd Whether the operation is "add" or "subtract". * @return a new instance. * @throws ArithmeticException if the resulting numerator or denominator * cannot be represented in an {@code int}. */ private Fraction addSub(Fraction value, boolean isAdd) { if (value.isZero()) { return this; } // Zero is identity for addition. if (isZero()) { return isAdd ? value : value.negate(); } /* * Let the two fractions be u/u' and v/v', and d1 = gcd(u', v'). * First, compute t, defined as: * * t = u(v'/d1) +/- v(u'/d1) */ final int d1 = ArithmeticUtils.gcd(denominator, value.denominator); final long uvp = (long) numerator * (long) (value.denominator / d1); final long upv = (long) value.numerator * (long) (denominator / d1); /* * The largest possible absolute value of a product of two ints is 2^62, * which can only happen as a result of -2^31 * -2^31 = 2^62, so a * product of -2^62 is not possible. It follows that (uvp - upv) cannot * overflow, and (uvp + upv) could only overflow if uvp = upv = 2^62. * But for this to happen, the terms u, v, v'/d1 and u'/d1 would all * have to be -2^31, which is not possible because v'/d1 and u'/d1 * are necessarily coprime. */ final long t = isAdd ? uvp + upv : uvp - upv; /* * Because u is coprime to u' and v is coprime to v', t is necessarily * coprime to both v'/d1 and u'/d1. However, it might have a common * factor with d1. */ final long d2 = ArithmeticUtils.gcd(t, d1); // result is (t/d2) / (u'/d1)(v'/d2) return of(Math.toIntExact(t / d2), Math.multiplyExact(denominator / d1, value.denominator / (int) d2)); } /** * Multiply this fraction by the passed {@code value}, returning * the result in reduced form. * * @param value Value to multiply by. * @return {@code this * value}. * @throws ArithmeticException if the resulting numerator * cannot be represented in an {@code int}. */ @Override public Fraction multiply(final int value) { if (value == 0 || isZero()) { return ZERO; } // knuth 4.5.1 // Make sure we don't overflow unless the result *must* overflow. // (see multiply(Fraction) using value / 1 as the argument). final int d2 = ArithmeticUtils.gcd(value, denominator); return new Fraction(Math.multiplyExact(numerator, value / d2), denominator / d2); } /** * Multiply this fraction by the passed {@code value}, returning * the result in reduced form. * * @param value Value to multiply by. * @return {@code this * value}. * @throws ArithmeticException if the resulting numerator or denominator * cannot be represented in an {@code int}. */ @Override public Fraction multiply(Fraction value) { if (value.isZero() || isZero()) { return ZERO; } return multiply(value.numerator, value.denominator); } /** * Multiply this fraction by the passed fraction decomposed into a numerator and * denominator, returning the result in reduced form. * * <p>This is a utility method to be used by multiply and divide. The decomposed * fraction arguments and this fraction are not checked for zero. * * @param num Fraction numerator. * @param den Fraction denominator. * @return {@code this * num / den}. * @throws ArithmeticException if the resulting numerator or denominator cannot * be represented in an {@code int}. */ private Fraction multiply(int num, int den) { // knuth 4.5.1 // Make sure we don't overflow unless the result *must* overflow. final int d1 = ArithmeticUtils.gcd(numerator, den); final int d2 = ArithmeticUtils.gcd(num, denominator); return new Fraction(Math.multiplyExact(numerator / d1, num / d2), Math.multiplyExact(denominator / d2, den / d1)); } /** * Divide this fraction by the passed {@code value}, returning * the result in reduced form. * * @param value Value to divide by * @return {@code this / value}. * @throws ArithmeticException if the value to divide by is zero * or if the resulting numerator or denominator cannot be represented * by an {@code int}. */ public Fraction divide(final int value) { if (value == 0) { throw new FractionException(FractionException.ERROR_DIVIDE_BY_ZERO); } if (isZero()) { return ZERO; } // Multiply by reciprocal // knuth 4.5.1 // Make sure we don't overflow unless the result *must* overflow. // (see multiply(Fraction) using 1 / value as the argument). final int d1 = ArithmeticUtils.gcd(numerator, value); return new Fraction(numerator / d1, Math.multiplyExact(denominator, value / d1)); } /** * Divide this fraction by the passed {@code value}, returning * the result in reduced form. * * @param value Value to divide by * @return {@code this / value}. * @throws ArithmeticException if the value to divide by is zero * or if the resulting numerator or denominator cannot be represented * by an {@code int}. */ @Override public Fraction divide(Fraction value) { if (value.isZero()) { throw new FractionException(FractionException.ERROR_DIVIDE_BY_ZERO); } if (isZero()) { return ZERO; } // Multiply by reciprocal return multiply(value.denominator, value.numerator); } /** * Returns a {@code Fraction} whose value is * <code>this<sup>exponent</sup></code>, returning the result in reduced form. * * @param exponent exponent to which this {@code Fraction} is to be raised. * @return <code>this<sup>exponent</sup></code>. * @throws ArithmeticException if the intermediate result would overflow. */ @Override public Fraction pow(final int exponent) { if (exponent == 1) { return this; } if (exponent == 0) { return ONE; } if (isZero()) { if (exponent < 0) { throw new FractionException(FractionException.ERROR_ZERO_DENOMINATOR); } return ZERO; } if (exponent > 0) { return new Fraction(ArithmeticUtils.pow(numerator, exponent), ArithmeticUtils.pow(denominator, exponent)); } if (exponent == -1) { return this.reciprocal(); } if (exponent == Integer.MIN_VALUE) { // MIN_VALUE can't be negated return new Fraction(ArithmeticUtils.pow(denominator, Integer.MAX_VALUE) * denominator, ArithmeticUtils.pow(numerator, Integer.MAX_VALUE) * numerator); } return new Fraction(ArithmeticUtils.pow(denominator, -exponent), ArithmeticUtils.pow(numerator, -exponent)); } /** * Returns the {@code String} representing this fraction. * Uses: * <ul> * <li>{@code "0"} if {@code numerator} is zero. * <li>{@code "numerator"} if {@code denominator} is one. * <li>{@code "numerator / denominator"} for all other cases. * </ul> * * @return a string representation of the fraction. */ @Override public String toString() { final String str; if (isZero()) { str = "0"; } else if (denominator == 1) { str = Integer.toString(numerator); } else { str = numerator + " / " + denominator; } return str; } /** * Compares this object with the specified object for order using the signed magnitude. * * @param other {@inheritDoc} * @return {@inheritDoc} */ @Override public int compareTo(Fraction other) { // Compute the sign of each part final int lns = Integer.signum(numerator); final int lds = Integer.signum(denominator); final int rns = Integer.signum(other.numerator); final int rds = Integer.signum(other.denominator); final int lhsSigNum = lns * lds; final int rhsSigNum = rns * rds; if (lhsSigNum != rhsSigNum) { return (lhsSigNum > rhsSigNum) ? 1 : -1; } // Same sign. // Avoid a multiply if both fractions are zero if (lhsSigNum == 0) { return 0; } // Compare absolute magnitude. // Multiplication by the signum is equal to the absolute. final long nOd = ((long) numerator) * lns * other.denominator * rds; final long dOn = ((long) denominator) * lds * other.numerator * rns; return Long.compare(nOd, dOn); } /** * Test for equality with another object. If the other object is a {@code Fraction} then a * comparison is made of the sign and magnitude; otherwise {@code false} is returned. * * @param other {@inheritDoc} * @return {@inheritDoc} */ @Override public boolean equals(Object other) { if (this == other) { return true; } if (other instanceof Fraction) { // Since fractions are always in lowest terms, numerators and // denominators can be compared directly for equality. final Fraction rhs = (Fraction) other; if (signum() == rhs.signum()) { return Math.abs(numerator) == Math.abs(rhs.numerator) && Math.abs(denominator) == Math.abs(rhs.denominator); } } return false; } @Override public int hashCode() { // Incorporate the sign and absolute values of the numerator and denominator. // Equivalent to: // int hash = 1; // hash = 31 * hash + Math.abs(numerator); // hash = 31 * hash + Math.abs(denominator); // hash = hash * signum() // Note: x * Integer.signum(x) == Math.abs(x). final int numS = Integer.signum(numerator); final int denS = Integer.signum(denominator); return (31 * (31 + numerator * numS) + denominator * denS) * numS * denS; } /** * Returns true if this fraction is zero. * * @return true if zero */ private boolean isZero() { return numerator == 0; } }
34.654226
109
0.579443
3123b55ac297767c61edf1e42dd659968a2ade7e
5,937
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.vfs.ex.dummy; import com.intellij.openapi.Disposable; import com.intellij.openapi.application.Application; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.project.ProjectManager; import com.intellij.openapi.project.ProjectManagerListener; import com.intellij.openapi.project.ex.ProjectManagerEx; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.text.StringUtil; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.util.containers.ConcurrentFactoryMap; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentMap; import java.util.function.Predicate; import java.util.stream.Collectors; /** * @author gregsh */ public abstract class DummyCachingFileSystem<T extends VirtualFile> extends DummyFileSystem { private final String myProtocol; private final ConcurrentMap<String, T> myCachedFiles = ConcurrentFactoryMap.create( this::findFileByPathInner, ContainerUtil::createConcurrentWeakValueMap); public DummyCachingFileSystem(String protocol) { myProtocol = protocol; final Application application = ApplicationManager.getApplication(); application.getMessageBus().connect().subscribe(ProjectManager.TOPIC, new ProjectManagerListener() { @Override public void projectOpened(@NotNull final Project project) { onProjectOpened(project); } @Override public void projectClosed(@NotNull Project project) { registerDisposeCallback(project); } }); initProjectMap(); } @NotNull @Override public final String getProtocol() { return myProtocol; } @Override @Nullable public final VirtualFile createRoot(String name) { return null; } @Override public final T findFileByPath(@NotNull String path) { return myCachedFiles.get(path); } @Override @NotNull public String extractPresentableUrl(@NotNull String path) { VirtualFile file = findFileByPath(path); return file != null ? getPresentableUrl(file) : super.extractPresentableUrl(path); } protected String getPresentableUrl(@NotNull VirtualFile file) { return file.getPresentableName(); } protected abstract T findFileByPathInner(@NotNull String path); protected void doRenameFile(VirtualFile vFile, String newName) { throw new UnsupportedOperationException("not implemented"); } @Nullable public Project getProject(@Nullable String projectId) { Project project = projectId == null ? null : ProjectManagerEx.getInstanceEx().findOpenProjectByHash(projectId); if (ApplicationManager.getApplication().isUnitTestMode() && project != null) { registerDisposeCallback(project); DISPOSE_CALLBACK.set(project, Boolean.TRUE); } return project; } @NotNull public Collection<T> getCachedFiles() { return myCachedFiles.values().stream() .filter(Objects::nonNull) .filter(VirtualFile::isValid) .collect(Collectors.toList()); } public void onProjectClosed() { clearCache(); if (ApplicationManager.getApplication().isUnitTestMode()) { cleanup(); } } public void onProjectOpened(final Project project) { clearCache(); } private static final Key<Boolean> DISPOSE_CALLBACK = Key.create("DISPOSE_CALLBACK"); private void registerDisposeCallback(Project project) { if (Boolean.TRUE.equals(DISPOSE_CALLBACK.get(project))) return; // use Disposer instead of ProjectManagerListener#projectClosed() because Disposer.dispose(project) // is called later and some cached files should stay valid till the last moment Disposer.register(project, new Disposable() { @Override public void dispose() { onProjectClosed(); } }); } private void initProjectMap() { for (Project project : ProjectManager.getInstance().getOpenProjects()) { if (project.isOpen()) onProjectOpened(project); } } protected void clearCache() { retainFiles(VirtualFile::isValid); } protected void retainFiles(@NotNull Predicate<? super VirtualFile> c) { for (Map.Entry<String, T> entry : myCachedFiles.entrySet()) { T t = entry.getValue(); if (t == null || !c.test(t)) { //CFM::entrySet returns copy myCachedFiles.remove(entry.getKey()); } } } private void cleanup() { myCachedFiles.clear(); } @Override public void renameFile(Object requestor, @NotNull VirtualFile vFile, @NotNull String newName) { String oldName = vFile.getName(); beforeFileRename(vFile, requestor, oldName, newName); try { doRenameFile(vFile, newName); } finally { fileRenamed(vFile, requestor, oldName, newName); } } protected void beforeFileRename(@NotNull VirtualFile file, Object requestor, @NotNull String oldName, @NotNull String newName) { fireBeforePropertyChange(requestor, file, VirtualFile.PROP_NAME, oldName, newName); myCachedFiles.remove(file.getPath()); } protected void fileRenamed(@NotNull VirtualFile file, Object requestor, String oldName, String newName) { //noinspection unchecked myCachedFiles.put(file.getPath(), (T)file); firePropertyChanged(requestor, file, VirtualFile.PROP_NAME, oldName, newName); } protected static String escapeSlash(String name) { return name == null ? "" : StringUtil.replace(name, "/", "&slash;"); } protected static String unescapeSlash(String name) { return name == null ? "" : StringUtil.replace(name, "&slash;", "/"); } }
32.091892
140
0.728988
ab43718ad1d4555c5e6cdba6eb21e4cde3581a31
3,961
package org.bunkr.cli.commands; import javafx.beans.property.BooleanProperty; import javafx.beans.property.SimpleBooleanProperty; import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Subparser; import org.bunkr.cli.CLI; import org.bunkr.core.ArchiveInfoContext; import org.bunkr.core.exceptions.TraversalException; import org.bunkr.core.inventory.FileInventoryItem; import org.bunkr.core.inventory.IFFTraversalTarget; import org.bunkr.core.inventory.InventoryPather; import org.bunkr.core.usersec.UserSecurityProvider; import org.bunkr.core.utils.Formatters; import javax.xml.bind.DatatypeConverter; /** * Created At: 2016-10-09 */ public class ShowFileMetadataCommand implements ICLICommand { public static final String ARG_PATH = "path"; @Override public void buildParser(Subparser target) { target.help("output the metadata for the file at the given path"); target.description( "This the metadata associated with the given file. This includes all information except for the " + "actual file contents. It will contain a representation of the symmetric key, so dont use it in " + "sensitive contexts." ); target.addArgument("path") .dest(ARG_PATH) .type(String.class) .help("directory path to list"); } @Override public void handle(Namespace args) throws Exception { UserSecurityProvider usp = new UserSecurityProvider(makeCLIPasswordProvider(args.get(CLI.ARG_PASSWORD_FILE))); ArchiveInfoContext aic = new ArchiveInfoContext(args.get(CLI.ARG_ARCHIVE_PATH), usp); IFFTraversalTarget t = InventoryPather.traverse(aic.getInventory(), args.getString(ARG_PATH)); if (t.isAFile()) { FileInventoryItem file = (FileInventoryItem) t; System.out.printf("Name: %s\n", file.getName()); System.out.printf("UUID: %s\n", file.getUuid()); System.out.printf("Actual size: %d (%s)\n", file.getActualSize(), Formatters.formatBytes(file.getActualSize())); System.out.printf("Size on disk: %d (%s)\n", file.getSizeOnDisk(), Formatters.formatBytes(file.getSizeOnDisk())); float compression = 1 - (file.getSizeOnDisk()) / (float)(file.getActualSize()); System.out.printf("Compression saving: %.2f%%\n", compression * 100); System.out.printf("Modified at: %s\n", Formatters.formatPrettyDate(file.getModifiedAt())); System.out.printf("Media type: %s\n", file.getMediaType()); System.out.printf("Integrity hash: %s\n", DatatypeConverter.printHexBinary(file.getIntegrityHash())); System.out.printf("Encryption algorithm: %s\n", file.getEncryptionAlgorithm()); if (file.getEncryptionData() != null) System.out.printf("Encryption data: %s\n", DatatypeConverter.printHexBinary(file.getEncryptionData())); System.out.printf("Block count: %d\n", file.getBlocks().size()); System.out.printf("Block ranges: "); BooleanProperty first = new SimpleBooleanProperty(true); file.getBlocks().iteratePairs().forEachRemaining(p -> { if (first.getValue()) first.set(false); else System.out.printf(", "); if (p.getValue() > 1) { System.out.printf("%d-%d", p.getKey(), p.getKey() + p.getValue()); } else { System.out.printf("%d", p.getKey()); } }); System.out.println(); } else { throw new TraversalException("'%s' is not a file", args.getString(ARG_PATH)); } } }
45.011364
134
0.609442
4f011048cdbbb2cc5fb1c19a0293f0f1c89d30af
4,727
package org.imagearchive.lsm.toolbox.info.scaninfo; import java.util.LinkedHashMap; public class Recording{ public LinkedHashMap<String, Object> records = new LinkedHashMap<String, Object>(); public static Object[][] data = { { new Long(0x010000001), DataType.STRING, "ENTRY_NAME" }, { new Long(0x010000002), DataType.STRING, "ENTRY_DESCRIPTION" }, { new Long(0x010000003), DataType.STRING, "ENTRY_NOTES" }, { new Long(0x010000004), DataType.STRING, "ENTRY_OBJECTIVE" }, { new Long(0x010000005), DataType.STRING, "PROCESSING_SUMMARY" }, { new Long(0x010000006), DataType.STRING, "SPECIAL_SCAN" }, { new Long(0x010000007), DataType.STRING, "SCAN_TYPE" }, { new Long(0x010000008), DataType.STRING, "SCAN_MODE" }, { new Long(0x010000009), DataType.LONG, "STACKS_COUNT" }, { new Long(0x01000000A), DataType.LONG, "LINES_PER_PLANE" }, { new Long(0x01000000B), DataType.LONG, "SAMPLES_PER_LINE" }, { new Long(0x01000000C), DataType.LONG, "PLANES_PER_VOLUME" }, { new Long(0x01000000D), DataType.LONG, "IMAGES_WIDTH" }, { new Long(0x01000000E), DataType.LONG, "IMAGES_HEIGHT" }, { new Long(0x01000000F), DataType.LONG, "NUMBER_OF_PLANES" }, { new Long(0x010000010), DataType.LONG, "IMAGES_NUMBER_STACKS" }, { new Long(0x010000011), DataType.LONG, "IMAGES_NUMBER_CHANNELS" }, { new Long(0x010000012), DataType.LONG, "LINESCAN_XY" }, { new Long(0x010000013), DataType.LONG, "SCAN_DIRECTION" }, { new Long(0x010000014), DataType.LONG, "TIME_SERIES" }, { new Long(0x010000015), DataType.LONG, "ORIGNAL_SCAN_DATA" }, { new Long(0x010000016), DataType.DOUBLE, "ZOOM_X" }, { new Long(0x010000017), DataType.DOUBLE, "ZOOM_Y" }, { new Long(0x010000018), DataType.DOUBLE, "ZOOM_Z" }, { new Long(0x010000019), DataType.DOUBLE, "SAMPLE_0X" }, { new Long(0x01000001A), DataType.DOUBLE, "SAMPLE_0Y" }, { new Long(0x01000001B), DataType.DOUBLE, "SAMPLE_0Z" }, { new Long(0x01000001C), DataType.DOUBLE, "SAMPLE_SPACING" }, { new Long(0x01000001D), DataType.DOUBLE, "LINE_SPACING" }, { new Long(0x01000001E), DataType.DOUBLE, "PLANE_SPACING" }, { new Long(0x01000001F), DataType.DOUBLE, "PLANE_WIDTH" }, { new Long(0x010000020), DataType.DOUBLE, "PLANE_HEIGHT" }, { new Long(0x010000021), DataType.DOUBLE, "VOLUME_DEPTH" }, { new Long(0x010000034), DataType.DOUBLE, "ROTATION" }, { new Long(0x010000035), DataType.DOUBLE, "PRECESSION" }, { new Long(0x010000036), DataType.DOUBLE, "SAMPLE_0TIME" }, { new Long(0x010000037), DataType.STRING, "START_SCAN_TRIGGER_IN" }, { new Long(0x010000038), DataType.STRING, "START_SCAN_TRIGGER_OUT" }, { new Long(0x010000039), DataType.LONG, "START_SCAN_EVENT" }, { new Long(0x010000040), DataType.DOUBLE, "START_SCAN_TIME" }, { new Long(0x010000041), DataType.STRING, "STOP_SCAN_TRIGGER_IN" }, { new Long(0x010000042), DataType.STRING, "STOP_SCAN_TRIGGER_OUT" }, { new Long(0x010000043), DataType.LONG, "STOP_SCAN_EVENT" }, { new Long(0x010000044), DataType.DOUBLE, "START_SCAN_TIME2" }, { new Long(0x010000045), DataType.LONG, "USE_ROIS" }, { new Long(0x010000046), DataType.LONG, "USE_REDUCED_MEMORY_ROIS" }, //in the description it's a Double { new Long(0x010000047), DataType.STRING, "USER" }, { new Long(0x010000048), DataType.LONG, "USE_BCCORECCTION" }, { new Long(0x010000049), DataType.DOUBLE, "POSITION_BCCORRECTION1" }, { new Long(0x010000050), DataType.DOUBLE, "POSITION_BCCORRECTION2" }, { new Long(0x010000051), DataType.LONG, "INTERPOLATIONY" }, { new Long(0x010000052), DataType.LONG, "CAMERA_BINNING" }, { new Long(0x010000053), DataType.LONG, "CAMERA_SUPERSAMPLING" }, { new Long(0x010000054), DataType.LONG, "CAMERA_FRAME_WIDTH" }, { new Long(0x010000055), DataType.LONG, "CAMERA_FRAME_HEIGHT" }, { new Long(0x010000056), DataType.DOUBLE, "CAMERA_OFFSETX" }, { new Long(0x010000057), DataType.DOUBLE, "CAMERA_OFFSETY" }}; public static boolean isRecording(long tagEntry) {//268435456 if (tagEntry == 0x010000000){ return true; } else return false; } public Track[] tracks; public Marker[] markers; public Timer[] timers; public Laser[] lasers; }
56.27381
115
0.624074
b6e782e2897cbcbde0358544c58e5b5e442b81db
184
class trim{ public static void main(String[] args) { String s1="hello yugandar"; System.out.println(s1+"hello yugandar"); System.out.println(s1.trim()+"yuga"); } }
23
45
0.63587
c19e40a815053634e71b8573b9fd0be312b4928c
1,162
package com.mongodb.orm.engine.type; import java.util.Collection; import java.util.HashSet; import java.util.Set; import com.mongodb.exception.MongoORMException; /** * Set implementation of TypeHandler * @author: xiangping_yu * @data : 2014-7-25 * @since : 1.5 */ public class SetTypeHandler implements TypeHandler<Set<?>> { private Class<?> clazz; public SetTypeHandler(Class<?> clazz) { this.clazz = clazz; } @Override public Object getParameter(String name, Set<?> instance) { return instance; } @SuppressWarnings({"rawtypes", "unchecked"}) @Override public Set<?> getResult(String name, Object instance, Object value) { try { Set result = null; if(clazz.isInterface()) { result = new HashSet<Object>(); } else { result = (Set)clazz.newInstance(); } if (value instanceof Collection) { result.addAll((Collection)value); } else { result.add(value); } return result; } catch (Exception ex) { throw new MongoORMException("Get result from "+instance.getClass()+" has error. Target property is "+name, ex); } } }
22.784314
117
0.636833
5ca0708dadae950d848898797a968bc8dd9658bd
1,064
package it.feio.android.analitica; import android.text.TextUtils; import it.feio.android.analitica.exceptions.InvalidIdentifierException; public class PiwikServiceIdentifier extends ServiceIdentifier { /** * @param identifiers Must be both Piwik service URL and applicationId * @throws InvalidIdentifierException */ public PiwikServiceIdentifier(String... identifiers) throws InvalidIdentifierException { super(identifiers); } @Override void validate(String... identifiers) throws InvalidIdentifierException { boolean success = identifiers.length == 2 && android.util.Patterns.WEB_URL.matcher(identifiers[0]).matches() && TextUtils.isDigitsOnly(identifiers[1]); if (!success) { throw new InvalidIdentifierException("Piwik identifiers MUST be both service URL AND applicationId"); } } public String getUrl() { return identifiers[0]; } public int getApplicationId() { return Integer.valueOf(identifiers[1]); } }
30.4
113
0.68797
ae1da32ab1d30c3384de73714ca577ae6ebb9174
1,285
/** * Copyright (c) The openTCS Authors. * * This program is free software and subject to the MIT license. (For details, * see the licensing information (LICENSE.txt) you should have received with * this copy of the software.) */ package org.opentcs.data; import org.opentcs.access.KernelRuntimeException; /** * Thrown when an object was supposed to be returned/removed/modified, but could * not be found. * * @author Stefan Walter (Fraunhofer IML) */ public class ObjectUnknownException extends KernelRuntimeException { /** * Creates a new ObjectExistsException with the given detail message. * * @param message The detail message. */ public ObjectUnknownException(String message) { super(message); } /** * Creates a new ObjectExistsException for the given object reference. * * @param ref The object reference. */ public ObjectUnknownException(TCSObjectReference<?> ref) { super("Object unknown: " + (ref == null ? "<null>" : ref.toString())); } /** * Creates a new ObjectExistsException with the given detail message and * cause. * * @param message The detail message. * @param cause The cause. */ public ObjectUnknownException(String message, Throwable cause) { super(message, cause); } }
25.7
80
0.696498
8260a1162b84c07a7b2cc3a33fcafe4d4d6bc272
2,887
package com.beiran.core.system.entity; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Getter; import lombok.Setter; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.GenericGenerator; import javax.persistence.*; import java.util.Date; import java.util.Objects; import java.util.Set; /** * ็ณป็ปŸไฝฟ็”จ่€… */ @Getter @Setter @Table(name = "erp_user") @Entity public class User { /** * ็”จๆˆท็ผ–ๅท */ @GenericGenerator(name = "g_uuid", strategy = "uuid") @GeneratedValue(generator = "g_uuid") @Id private String userId; /** * ็”จๆˆทๅ๏ผˆ็”จไฝœ็™ปๅฝ•๏ผ‰ */ @Column(length = 50, unique = true, nullable = false) private String userName; /** * ็”จๆˆทๅคดๅƒ */ private String userAvatar; /** * ็”จๆˆทๆ˜ต็งฐ */ @Column(length = 100) private String nickName; /** * ็™ปๅฝ•ๅฏ†็ ๏ผŒๅญ˜ๅ…ฅๆ•ฐๆฎๅบ“ๅ‰ๅ…ˆๅŠ ๅฏ† */ @JsonIgnore private String userPassword; /** * ็”จๆˆท็Šถๆ€ */ private UserState userState; /** * ็”จๆˆท่”็ณปๆ–นๅผ */ @Column(length = 32) private String userPhone; /** * ็”จๆˆทๆ€งๅˆซ */ private UserSex userSex; /** * ็”จๆˆท้‚ฎ็ฎฑ */ @Column(length = 100) private String userEmail; /** * ็”จๆˆทๅˆ›ๅปบๆ—ถ้—ด๏ผŒๅˆ›ๅปบๆ—ถ้—ด้ป˜่ฎคไธบๅ…ฅ่Œๆ—ถ้—ด๏ผŒ็”ฑ Hibernate ่‡ชๅŠจ่ต‹ๅ€ผ */ @CreationTimestamp @Temporal(TemporalType.TIMESTAMP) private Date userCreateTime; /** * ็”จๆˆทๅฒ—ไฝ */ @JoinColumn(name = "userJobId") @OneToOne private Job userJob; /** * ็”จๆˆท่ง’่‰ฒ */ @JoinTable(name = "erp_user_role", joinColumns = @JoinColumn(referencedColumnName = "userId", name = "userId") , inverseJoinColumns = { @JoinColumn(referencedColumnName = "roleId", name = "roleId") }) @ManyToMany(fetch = FetchType.EAGER) private Set<Role> userRoles; /** * ็”จๆˆท็Šถๆ€ๆžšไธพ็ฑป */ public enum UserState { ACTIVE("ๅฏ็”จ"), DISABLED("ๅœ็”จ"); private String value; private UserState(String value) { this.value = value; } public String getValue() { return this.value; } } /** * ็”จๆˆทๆ€งๅˆซๆžšไธพ็ฑป */ public enum UserSex { MALE("็”ท"), FEMALE("ๅฅณ"), SECRET("ไฟๅฏ†"); private String value; private UserSex(String value) { this.value = value; } public String getValue() { return this.value; } } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } User user = (User) o; return Objects.equals(userId, user.userId) && Objects.equals(userName, user.userName); } @Override public int hashCode() { return Objects.hash(userId, userName); } }
18.157233
99
0.554209
4e8dc1a8b9522b99451faacb8aa9a89ce4195bc3
452
package com.vitaxa.jasteambot.steam.trade.offer.model; import com.fasterxml.jackson.annotation.JsonProperty; public class OfferAccessToken { @JsonProperty("trade_offer_access_token") private String tradeOfferAccessToken; public OfferAccessToken(String tradeOfferAccessToken) { this.tradeOfferAccessToken = tradeOfferAccessToken; } public String getTradeOfferAccessToken() { return tradeOfferAccessToken; } }
26.588235
59
0.769912
fbd978d76df454815655eeaf2d85b731cb9cf118
7,258
/** * * Copyright 2017 Florian Erhard * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package gedi.core.data.reads; import gedi.core.reference.ReferenceSequence; import gedi.core.region.GenomicRegion; import gedi.core.region.ImmutableReferenceGenomicRegion; import gedi.util.ArrayUtils; import gedi.util.FunctorUtils; import gedi.util.functions.EI; import gedi.util.functions.ExtendedIterator; import java.util.Arrays; import java.util.Comparator; import java.util.Iterator; import org.h2.util.IntIntHashMap; import cern.colt.bitvector.BitVector; public class AlignedReadsDataMerger { private int[] offsets; private AlignedReadsDataFactory fac; private IntIntHashMap[] idMapping; private int nextId = 1; // start with 1 as IntIntHashMap does not support 0->0 // public AlignedReadsDataMerger(){ // } public AlignedReadsDataMerger(int... numConditions) { fac = new AlignedReadsDataFactory(ArrayUtils.sum(numConditions)); offsets = new int[numConditions.length+1]; for (int i=1; i<offsets.length; i++) offsets[i] = offsets[i-1]+numConditions[i-1]; idMapping = new IntIntHashMap[numConditions.length]; for (int i=0; i<idMapping.length; i++) idMapping[i] = new IntIntHashMap(); } public ImmutableReferenceGenomicRegion<DefaultAlignedReadsData> merge(ImmutableReferenceGenomicRegion<? extends AlignedReadsData>... data) { AlignedReadsData[] d2 = new AlignedReadsData[data.length]; ReferenceSequence ref = null; GenomicRegion region = null; for (int i=0; i<d2.length; i++) { if (data[i]!=null) { d2[i] = data[i].getData(); if (ref==null) ref = data[i].getReference(); else if (!ref.equals(data[i].getReference())) throw new IllegalArgumentException("ReferenceRegions must be equal!"); if (region==null) region = data[i].getRegion(); else if (!region.equals(data[i].getRegion())) throw new IllegalArgumentException("ReferenceRegions must be equal!"); } } return new ImmutableReferenceGenomicRegion<DefaultAlignedReadsData>(ref,region,merge(d2)); } private static class DistinctSeq implements Comparable<DistinctSeq> { int d; AlignedReadsVariation[] var; public DistinctSeq(int d, AlignedReadsVariation[] var) { this.d = d; this.var = var; Arrays.sort(var); } @Override public int compareTo(DistinctSeq o) { int n = Math.min(var.length,o.var.length); for (int i=0; i<n; i++) { int r = var[i].compareTo(o.var[i]); if (r!=0) return r; } return var.length-o.var.length; } } public DefaultAlignedReadsData merge(AlignedReadsData... data) { // if (fac==null) { // fac = new AlignedReadsDataFactory(data.length); // offsets = new int[data.length+1]; // for (int i=1; i<offsets.length; i++) // offsets[i] = i; // } fac.start(); int max = 1; for (int i=0; i<data.length; i++) if (data[i]!=null) max = Math.max(max,data[i].getDistinctSequences()); Iterator<DistinctSeq>[] it = new Iterator[data.length]; for (int i=0; i<data.length; i++) if (data[i]!=null) { DistinctSeq[] vars = new DistinctSeq[data[i].getDistinctSequences()]; for (int v=0; v<data[i].getDistinctSequences(); v++) vars[v] = new DistinctSeq(v,data[i].getVariations(v)); Arrays.sort(vars); it[i] = EI.wrap(vars); } else it[i] = EI.empty(); ExtendedIterator<DistinctSeq[]> pit = EI.parallel(DistinctSeq.class, FunctorUtils.naturalComparator(), it); while (pit.hasNext()) { DistinctSeq[] n = pit.next(); int i; for (i=0;n[i]==null; i++); int v = n[i].d; fac.newDistinctSequence(); if (data[i].hasId()) fac.setId(getId(i,data[i].getId(v), data[i].getMultiplicity(v)>1)); fac.setMultiplicity(data[i].getMultiplicity(v)); if (data[i].hasWeights()) fac.setWeight(data[i].getWeight(v)); if (data[i].hasGeometry()) fac.setGeometry(data[i].getGeometryBeforeOverlap(v), data[i].getGeometryOverlap(v),data[i].getGeometryAfterOverlap(v)); for (AlignedReadsVariation vari : n[i].var) fac.addVariation(vari); if (data[i].hasNonzeroInformation()) { for (int c : data[i].getNonzeroCountIndicesForDistinct(v)) fac.setCount(offsets[i]+c, data[i].getCount(v, c)); } else { for (int c=0; c<data[i].getNumConditions(); c++) fac.setCount(offsets[i]+c, data[i].getCount(v, c)); } for (i++ ; i<n.length; i++) { if (n[i]!=null) { if (data[i].hasNonzeroInformation()) { for (int c : data[i].getNonzeroCountIndicesForDistinct(n[i].d)) fac.setCount(offsets[i]+c, data[i].getCount(n[i].d, c)); } else { for (int c=0; c<data[i].getNumConditions(); c++) fac.setCount(offsets[i]+c, data[i].getCount(n[i].d, c)); } } } } // // BitVector done = new BitVector(data.length*max); // // do a linear search, as only few variations are expected! HAHAHA, you fool! is 1231723520 "few"??? // for (int i=0; i<data.length; i++) // if (data[i]!=null) { // for (int v=0; v<data[i].getDistinctSequences(); v++) { // if (done.getQuick(i+v*data.length)) continue; // fac.newDistinctSequence(); // fac.setId(getId(i,data[i].getId(v), data[i].getMultiplicity(v)>1)); // fac.setMultiplicity(data[i].getMultiplicity(v)); // if (data[i].hasWeights()) // fac.setWeight(data[i].getWeight(v)); // if (data[i].hasGeometry()) // fac.setGeometry(data[i].getGeometryBeforeOverlap(v), data[i].getGeometryOverlap(v),data[i].getGeometryAfterOverlap(v)); // for (int c=0; c<data[i].getNumConditions(); c++) // fac.setCount(offsets[i]+c, data[i].getCount(v, c)); // // AlignedReadsVariation[] vars = data[i].getVariations(v); // Arrays.sort(vars); // // for (AlignedReadsVariation vari : vars) // fac.addVariation(vari); // // for (int j=i+1; j<data.length; j++) // if (data[j]!=null) { // for (int w=0; w<data[j].getDistinctSequences(); w++) { // if (done.getQuick(j+w*data.length)) continue; // // AlignedReadsVariation[] wars = data[j].getVariations(w); // Arrays.sort(wars); // // if (Arrays.equals(vars, wars)) { // for (int c=0; c<data[j].getNumConditions(); c++) // fac.setCount(offsets[j]+c, data[j].getCount(w, c)); // done.putQuick(j+w*data.length,true); // break; // } // } // } // // } // } DefaultAlignedReadsData re = fac.create(); // System.out.println(Arrays.toString(data)+" -> "+re); return re; } private int getId(int file, int oldId, boolean save) { int id = idMapping[file].get(oldId); if (id==IntIntHashMap.NOT_FOUND) { if (save) idMapping[file].put(oldId, nextId); id = nextId++; } return id; } }
32.401786
141
0.646046
867e2e630d43e31bbb3fce550358d3c41c57f0f3
4,345
package i2am.benchmark.storm.bloom; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Properties; import java.util.Set; import java.util.UUID; import org.apache.storm.Config; import org.apache.storm.StormSubmitter; import org.apache.storm.generated.AlreadyAliveException; import org.apache.storm.generated.AuthorizationException; import org.apache.storm.generated.InvalidTopologyException; import org.apache.storm.kafka.KafkaSpout; import org.apache.storm.kafka.SpoutConfig; import org.apache.storm.kafka.StringScheme; import org.apache.storm.kafka.ZkHosts; import org.apache.storm.kafka.bolt.KafkaBolt; import org.apache.storm.kafka.bolt.mapper.FieldNameBasedTupleToKafkaMapper; import org.apache.storm.kafka.bolt.selector.DefaultTopicSelector; import org.apache.storm.redis.common.config.JedisClusterConfig; import org.apache.storm.spout.SchemeAsMultiScheme; import org.apache.storm.topology.TopologyBuilder; import redis.clients.jedis.Protocol; public class PerformanceTestTopology { public static void main(String[] args) throws AlreadyAliveException, InvalidTopologyException, AuthorizationException{ String[] zookeepers = args[0].split(","); //KAFAK ZOOKEEPER short zkPort = Short.parseShort(args[1]); /* Kafka -> Storm Config */ StringBuilder sb = new StringBuilder(); for(String zookeeper: zookeepers){ sb.append(zookeeper + ":" + zkPort + ","); } String zkUrl = sb.substring(0, sb.length()-1); String input_topic = args[2]; String output_topic = args[3]; /* Redis Configurations */ String redisKey = args[4]; Set<InetSocketAddress> redisNodes = new HashSet<InetSocketAddress>(); redisNodes.add(new InetSocketAddress("MN", 17000)); redisNodes.add(new InetSocketAddress("SN01", 17001)); redisNodes.add(new InetSocketAddress("SN02", 17002)); redisNodes.add(new InetSocketAddress("SN03", 17003)); redisNodes.add(new InetSocketAddress("SN04", 17004)); redisNodes.add(new InetSocketAddress("SN05", 17005)); redisNodes.add(new InetSocketAddress("SN06", 17006)); redisNodes.add(new InetSocketAddress("SN07", 17007)); redisNodes.add(new InetSocketAddress("SN08", 17008)); /* Jedis */ JedisClusterConfig jedisClusterConfig = new JedisClusterConfig(redisNodes, Protocol.DEFAULT_TIMEOUT, 5); /* WordList to Filter */ List<String> dataArray = new ArrayList<String>(); //ํ•„ํ„ฐ๋ง ํ•  ๋ฐ์ดํ„ฐ for(int i = 5; i < args.length; i++){ dataArray.add(args[i]); } ZkHosts hosts = new ZkHosts(zkUrl); SpoutConfig kafkaSpoutConfig = new SpoutConfig(hosts, input_topic, "/" + input_topic, UUID.randomUUID().toString()); kafkaSpoutConfig.scheme = new SchemeAsMultiScheme(new StringScheme()); /* Storm -> Kafka Configs */ sb = new StringBuilder(); for(String zookeeper : zookeepers){ sb.append(zookeeper + ":9092,"); } String kafkaUrl = sb.substring(0, sb.length()-1); Properties props = new Properties(); props.put("bootstrap.servers", kafkaUrl); props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); props.put("acks", "1"); /* Topology */ KafkaBolt<String, Integer> kafkaBolt = new KafkaBolt<String, Integer>() .withProducerProperties(props) .withTopicSelector(new DefaultTopicSelector(output_topic)) .withTupleToKafkaMapper(new FieldNameBasedTupleToKafkaMapper()); TopologyBuilder builder = new TopologyBuilder(); builder.setSpout("kafka-spout", new KafkaSpout(kafkaSpoutConfig), 8) .setNumTasks(8); builder.setBolt("declare-field-bolt", new DeclareFieldBolt(), 8) .shuffleGrouping("kafka-spout") .setNumTasks(8); builder.setBolt("bloom-filtering-bolt", new BloomFilteringBolt(dataArray, redisKey, jedisClusterConfig), 8) .shuffleGrouping("declare-field-bolt") .setNumTasks(8); builder.setBolt("kafka-bolt", kafkaBolt, 8) .shuffleGrouping("bloom-filtering-bolt") .setNumTasks(8); Config conf = new Config(); conf.setDebug(true); conf.setNumWorkers(32); StormSubmitter.submitTopology("performance-bloomfiltering-topology", conf, builder.createTopology()); } }
38.451327
120
0.729804
9e722f73c9e12d687bee7d76280130d0788eafcd
4,108
package com.hellokoding.datastructure; import java.util.Arrays; import java.util.Objects; public class MyHashtable<K, V> { private static final int INITIAL_CAPACITY = 16; private static final float LOAD_FACTOR = 0.75f; private int size = 0; Entry<K,V>[] entries; @SuppressWarnings({"rawtypes", "unchecked"}) public MyHashtable() { entries = (Entry<K, V>[]) new Entry[INITIAL_CAPACITY]; } @SuppressWarnings({"rawtypes", "unchecked"}) public MyHashtable(int capacity) { entries = (Entry<K, V>[]) new Entry[capacity]; } public V put(K key, V value) { int index = hashFunction(key); Entry<K, V> headEntry = entries[index]; Entry<K, V> currentEntry = headEntry; // Find key in the chain while (Objects.nonNull(currentEntry)) { if (Objects.equals(currentEntry.key, key)) { // Ignore duplicate key return currentEntry.value; } currentEntry = currentEntry.next; } // Add first to the chain Entry<K, V> newEntry = new Entry<>(key, value); newEntry.next = headEntry; entries[index] = newEntry; size++; resize(); return null; } public V get(K key) { int index = hashFunction(key); Entry<K, V> currentEntry = entries[index]; // Find key in the chain while (Objects.nonNull(currentEntry)) { if (Objects.equals(currentEntry.key, key)) { return currentEntry.value; } currentEntry = currentEntry.next; } return null; } public V remove(K key) { int index = hashFunction(key); Entry<K, V> currentEntry = entries[index]; Entry<K, V> previousEntry = null; // Find key in the chain while (Objects.nonNull(currentEntry)) { if (Objects.equals(currentEntry.key, key)) { break; } previousEntry = currentEntry; currentEntry = currentEntry.next; } if (Objects.isNull(currentEntry)) { return null; } // Remove if (Objects.isNull(previousEntry)) { entries[index] = currentEntry.next; } else { previousEntry.next = currentEntry.next; } size--; return currentEntry.value; } public int size() { return size; } private void resize() { if (size <= LOAD_FACTOR * entries.length) return; Entry<K,V>[] currentEntries = entries; entries = (Entry<K, V>[]) new Entry[entries.length*2] ; rehash(currentEntries); } private void rehash(Entry<K,V>[] entries) { size = 0; for (Entry<K, V> entry : entries) { while (Objects.nonNull(entry)) { put(entry.key, entry.value); entry = entry.next; } } } private int hashFunction(K key) { int hashCode = key.hashCode(); int index = hashCode % entries.length; return index; } public static class Entry<K, V> { K key; V value; Entry<K, V> next; Entry(K key, V value) { this.key = key; this.value = value; } } public static void main(String[] args) { MyHashtable<String, Integer> myHashtable = new MyHashtable<>(2); myHashtable.put("k1", 1); myHashtable.put("k2", 2); myHashtable.put("k2", 2); myHashtable.put("k3", 3); Arrays.stream(myHashtable.entries) .forEach(e -> { if (Objects.nonNull(e)) { System.out.printf("%s=%d%s", e.key, e.value, System.lineSeparator()); } }); System.out.println(myHashtable.size()); System.out.println(myHashtable.get("k2")); System.out.println(myHashtable.remove("k1")); System.out.println(myHashtable.get("k1")); System.out.println(myHashtable.size()); } }
24.89697
89
0.537975
3874b7d2f180c32bc5c7e9337a215ab5eab50e19
7,466
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * Project Info: http://plantuml.com * * This file is part of Smetana. * Smetana is a partial translation of Graphviz/Dot sources from C to Java. * * (C) Copyright 2009-2017, Arnaud Roques * * This translation is distributed under the same Licence as the original C program: * ************************************************************************* * Copyright (c) 2011 AT&T Intellectual Property * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: See CVS logs. Details at http://www.graphviz.org/ ************************************************************************* * * THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC * LICENSE ("AGREEMENT"). [Eclipse Public License - v 1.0] * * ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES * RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. * * You may obtain a copy of the License at * * http://www.eclipse.org/legal/epl-v10.html * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package h; import java.util.Arrays; import java.util.List; import smetana.core.__ptr__; //2 dg8cqsmppn0zl04sycueci9yw public interface GVJ_s extends __ptr__ { public static List<String> DEFINITION = Arrays.asList( "struct GVJ_s", "{", "GVC_t *gvc", "GVJ_t *next", "GVJ_t *next_active", "GVCOMMON_t *common", "obj_state_t *obj", "char *input_filename", "int graph_index", "const char *layout_type", "const char *output_filename", "FILE *output_file", "char *output_data", "unsigned int output_data_allocated", "unsigned int output_data_position", "const char *output_langname", "int output_lang", "gvplugin_active_render_t render", "gvplugin_active_device_t device", "gvplugin_active_loadimage_t loadimage", "gvdevice_callbacks_t *callbacks", "pointf device_dpi", "boolean device_sets_dpi", "void *display", "int screen", "void *context", "boolean external_context", "char *imagedata", "int flags", "int numLayers", "int layerNum", "point pagesArraySize", "point pagesArrayFirst", "point pagesArrayMajor", "point pagesArrayMinor", "point pagesArrayElem", "int numPages", "boxf bb", "pointf pad", "boxf clip", "boxf pageBox", "pointf pageSize", "pointf focus", "double zoom", "int rotation", "pointf view", "boxf canvasBox", "pointf margin", "pointf dpi", "unsigned int width", "unsigned int height", "box pageBoundingBox", "box boundingBox", "pointf scale", "pointf translation", "pointf devscale", "boolean fit_mode, needs_refresh, click, has_grown, has_been_rendered", "unsigned char button", "pointf pointer", "pointf oldpointer", "void *current_obj", "void *selected_obj", "char *active_tooltip", "char *selected_href", "gv_argvlist_t selected_obj_type_name", "gv_argvlist_t selected_obj_attributes", "void *window", "gvevent_key_binding_t *keybindings", "int numkeys", "void *keycodes", "}"); } // struct GVJ_s { // GVC_t *gvc; /* parent gvc */ // GVJ_t *next; /* linked list of jobs */ // GVJ_t *next_active; /* linked list of active jobs (e.g. multiple windows) */ // // GVCOMMON_t *common; // // obj_state_t *obj; /* objects can be nested (at least clusters can) // so keep object state on a stack */ // char *input_filename; // int graph_index; // // const char *layout_type; // // const char *output_filename; // FILE *output_file; // char *output_data; // unsigned int output_data_allocated; // unsigned int output_data_position; // // const char *output_langname; // int output_lang; // // gvplugin_active_render_t render; // gvplugin_active_device_t device; // gvplugin_active_loadimage_t loadimage; // gvdevice_callbacks_t *callbacks; // pointf device_dpi; // boolean device_sets_dpi; // // void *display; // int screen; // // void *context; /* gd or cairo surface */ // boolean external_context; /* context belongs to caller */ // char *imagedata; /* location of imagedata */ // // int flags; /* emit_graph flags */ // // int numLayers; /* number of layers */ // int layerNum; /* current layer - 1 based*/ // // point pagesArraySize; /* 2D size of page array */ // point pagesArrayFirst;/* 2D starting corner in */ // point pagesArrayMajor;/* 2D major increment */ // point pagesArrayMinor;/* 2D minor increment */ // point pagesArrayElem; /* 2D coord of current page - 0,0 based */ // int numPages; /* number of pages */ // // boxf bb; /* graph bb with padding - graph units */ // pointf pad; /* padding around bb - graph units */ // boxf clip; /* clip region in graph units */ // boxf pageBox; /* current page in graph units */ // pointf pageSize; /* page size in graph units */ // pointf focus; /* viewport focus - graph units */ // // double zoom; /* viewport zoom factor (points per graph unit) */ // int rotation; /* viewport rotation (degrees) 0=portrait, 90=landscape */ // // pointf view; /* viewport size - points */ // boxf canvasBox; /* viewport area - points */ // pointf margin; /* job-specific margin - points */ // // pointf dpi; /* device resolution device-units-per-inch */ // // unsigned int width; /* device width - device units */ // unsigned int height; /* device height - device units */ // box pageBoundingBox;/* rotated boundingBox - device units */ // box boundingBox; /* cumulative boundingBox over all pages - device units */ // // pointf scale; /* composite device to graph units (zoom and dpi) */ // pointf translation; /* composite translation */ // pointf devscale; /* composite device to points: dpi, y_goes_down */ // // boolean fit_mode, // needs_refresh, // click, // has_grown, // has_been_rendered; // // unsigned char button; /* active button */ // pointf pointer; /* pointer position in device units */ // pointf oldpointer; /* old pointer position in device units */ // // void *current_obj; /* graph object that pointer is in currently */ // // void *selected_obj; /* graph object that has been selected */ // /* (e.g. button 1 clicked on current obj) */ // char *active_tooltip; /* tooltip of active object - or NULL */ // char *selected_href; /* href of selected object - or NULL */ // gv_argvlist_t selected_obj_type_name; /* (e.g. "edge" "node3" "e" "->" "node5" "") */ // gv_argvlist_t selected_obj_attributes; /* attribute triplets: name, value, type */ // /* e.g. "color", "red", GVATTR_COLOR, // "style", "filled", GVATTR_BOOL, */ // // void *window; /* display-specific data for gvrender plugin */ // // /* keybindings for keyboard events */ // gvevent_key_binding_t *keybindings; // int numkeys; // void *keycodes; // };
33.182222
89
0.64412
39cc79a03d068490e9e759f1488620998d206141
7,269
package cz.metacentrum.perun.scim.api.entities; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonSerialize; /** * SCIM Service Provider Configuration * * @author Sona Mastrakova <[email protected]> * @date 08.10.2016 */ @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL) public class ServiceProviderConfiguration { private List<String> schemas; private String documentationUrl; private Patch patch; private Bulk bulk; private Filter filter; private ChangePassword changePassword; private Sort sort; private Etag etag; private XmlDataFormat xmlDataFormat; private List<AuthenticationSchemes> authenticationSchemes; public ServiceProviderConfiguration(List<String> schemas, String documentationUrl, Patch patch, Bulk bulk, Filter filter, ChangePassword changePassword, Sort sort, Etag etag, XmlDataFormat xmlDataFormat, List<AuthenticationSchemes> authenticationSchemes) { this.schemas = schemas; this.documentationUrl = documentationUrl; this.patch = patch; this.bulk = bulk; this.filter = filter; this.changePassword = changePassword; this.sort = sort; this.etag = etag; this.xmlDataFormat = xmlDataFormat; this.authenticationSchemes = authenticationSchemes; } public ServiceProviderConfiguration() { } public List<String> getSchemas() { return schemas; } public void setSchemas(List<String> schemas) { this.schemas = schemas; } public String getDocumentationUrl() { return documentationUrl; } public void setDocumentationUrl(String documentationUrl) { this.documentationUrl = documentationUrl; } public Patch getPatch() { return patch; } public void setPatch(Patch patch) { this.patch = patch; } public Bulk getBulk() { return bulk; } public void setBulk(Bulk bulk) { this.bulk = bulk; } public Filter getFilter() { return filter; } public void setFilter(Filter filter) { this.filter = filter; } public ChangePassword getChangePassword() { return changePassword; } public void setChangePassword(ChangePassword changePassword) { this.changePassword = changePassword; } public Sort getSort() { return sort; } public void setSort(Sort sort) { this.sort = sort; } public Etag getEtag() { return etag; } public void setEtag(Etag etag) { this.etag = etag; } public XmlDataFormat getXmlDataFormat() { return xmlDataFormat; } public void setXmlDataFormat(XmlDataFormat xmlDataFormat) { this.xmlDataFormat = xmlDataFormat; } public List<AuthenticationSchemes> getAuthenticationSchemes() { return authenticationSchemes; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ServiceProviderConfiguration)) return false; ServiceProviderConfiguration that = (ServiceProviderConfiguration) o; if (getSchemas() != null ? !getSchemas().equals(that.getSchemas()) : that.getSchemas() != null) return false; if (getDocumentationUrl() != null ? !getDocumentationUrl().equals(that.getDocumentationUrl()) : that.getDocumentationUrl() != null) return false; if (getPatch() != null ? !getPatch().equals(that.getPatch()) : that.getPatch() != null) return false; if (getBulk() != null ? !getBulk().equals(that.getBulk()) : that.getBulk() != null) return false; if (getFilter() != null ? !getFilter().equals(that.getFilter()) : that.getFilter() != null) return false; if (getChangePassword() != null ? !getChangePassword().equals(that.getChangePassword()) : that.getChangePassword() != null) return false; if (getSort() != null ? !getSort().equals(that.getSort()) : that.getSort() != null) return false; if (getEtag() != null ? !getEtag().equals(that.getEtag()) : that.getEtag() != null) return false; if (getXmlDataFormat() != null ? !getXmlDataFormat().equals(that.getXmlDataFormat()) : that.getXmlDataFormat() != null) return false; return getAuthenticationSchemes() != null ? getAuthenticationSchemes().equals(that.getAuthenticationSchemes()) : that.getAuthenticationSchemes() == null; } @Override public int hashCode() { int result = getSchemas() != null ? getSchemas().hashCode() : 0; result = 31 * result + (getDocumentationUrl() != null ? getDocumentationUrl().hashCode() : 0); result = 31 * result + (getPatch() != null ? getPatch().hashCode() : 0); result = 31 * result + (getBulk() != null ? getBulk().hashCode() : 0); result = 31 * result + (getFilter() != null ? getFilter().hashCode() : 0); result = 31 * result + (getChangePassword() != null ? getChangePassword().hashCode() : 0); result = 31 * result + (getSort() != null ? getSort().hashCode() : 0); result = 31 * result + (getEtag() != null ? getEtag().hashCode() : 0); result = 31 * result + (getXmlDataFormat() != null ? getXmlDataFormat().hashCode() : 0); result = 31 * result + (getAuthenticationSchemes() != null ? getAuthenticationSchemes().hashCode() : 0); return result; } @Override public String toString() { return "ServiceProviderConfiguration{" + "schemas=" + schemas + ", documentationUrl='" + documentationUrl + '\'' + ", patch=" + patch + ", bulk=" + bulk + ", filter=" + filter + ", changePassword=" + changePassword + ", sort=" + sort + ", etag=" + etag + ", xmlDataFormat=" + xmlDataFormat + ", authenticationSchemes=" + authenticationSchemes + '}'; } private static class Bulk { @JsonProperty private Boolean supported; } private static class Filter { @JsonProperty private Boolean supported; } private static class Patch { @JsonProperty private Boolean supported; } private static class ChangePassword { @JsonProperty private Boolean supported; } private static class Sort { @JsonProperty private Boolean supported; } private static class Etag { @JsonProperty private Boolean supported; } private static class XmlDataFormat { @JsonProperty private Boolean supported; } public void setAuthenticationSchemes(List<AuthenticationSchemes> authenticationSchemes) { this.authenticationSchemes = authenticationSchemes; } public void setBulkSupport(Boolean value) { Bulk newBulk = new Bulk(); newBulk.supported = value; this.bulk = newBulk; } public void setFilterSupport(Boolean value) { Filter newFilter = new Filter(); newFilter.supported = value; this.filter = newFilter; } public void setPatchSupport(Boolean value) { Patch newPatch = new Patch(); newPatch.supported = value; this.patch = newPatch; } public void setChangePasswordSupport(Boolean value) { ChangePassword newChangePassword = new ChangePassword(); newChangePassword.supported = value; this.changePassword = newChangePassword; } public void setSortSupport(Boolean value) { Sort newSort = new Sort(); newSort.supported = value; this.sort = newSort; } public void setEtagSupport(Boolean value) { Etag newEtag = new Etag(); newEtag.supported = value; this.etag = newEtag; } public void setXmlDataFormatSupport(Boolean value) { XmlDataFormat newXmlDataFormat = new XmlDataFormat(); newXmlDataFormat.supported = value; this.xmlDataFormat = newXmlDataFormat; } }
27.638783
155
0.707938
94fcc2f7444a87f8a5b99074f32b813fdf4499b9
454
package com.atguigu.gmall.sms.service; import com.baomidou.mybatisplus.extension.service.IService; import com.atguigu.gmall.sms.entity.SkuBoundsEntity; import com.atguigu.core.bean.PageVo; import com.atguigu.core.bean.QueryCondition; /** * ๅ•†ๅ“sku็งฏๅˆ†่ฎพ็ฝฎ * * @author feifei * @email [email protected] * @date 2020-08-24 16:56:22 */ public interface SkuBoundsService extends IService<SkuBoundsEntity> { PageVo queryPage(QueryCondition params); }
21.619048
69
0.773128
571d4a2e1d52cd8d3f9102af3d041346af600e4e
233
package com.incognia.fixtures; import com.incognia.Address; public class AddressFixture { public static Address ADDRESS_ADDRESS_LINE = Address.builder().addressLine("350 Fifth Avenue, Manhattan, New York 10118").build(); }
25.888889
91
0.76824
7627b575f7c7fd177a692cbb41cab6a7f00a115a
1,254
package com.greenpineyu.fel.function.one.impl; import com.greenpineyu.fel.context.FelContext; import com.greenpineyu.fel.function.api.BaseOneOperation; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * ISCH(test)๏ผšๅˆคๆ–ญๆ–‡ๆœฌๅญ—็ฌฆไธฒๆ˜ฏๅฆๅ…จ้ƒจไธบๆฑ‰ๅญ—๏ผŒๅฆ‚ๆžœๆ˜ฏ่ฟ”ๅ›žTRUE๏ผŒๅฆๅˆ™่ฟ”ๅ›žFALSEใ€‚ * test๏ผš้œ€่ฆ่ฟ›่กŒๅˆคๆ–ญ็š„ๆ–‡ๆœฌๅญ—็ฌฆไธฒใ€‚ * ็คบไพ‹๏ผš * ISCH("ๅˆถๅบฆ") ่ฟ”ๅ›žTRUE * ISCH("ๆŠฅ่กจ101") ่ฟ”ๅ›žFALSE * * @author tiankafei */ public class IschOperation extends BaseOneOperation { private IschOperation() { } private static class InternalClass { private final static BaseOneOperation INSTANCE = new IschOperation(); } public static BaseOneOperation getInstance() { return InternalClass.INSTANCE; } @Override public Object evl(Object param, FelContext context, int location) throws Exception { if (param == null) { return Boolean.FALSE; } String regex = "[\u4e00-\u9fa5]{"; if (param instanceof String) { regex = regex + ((String) param).length() + "}"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher((String) param); return Boolean.valueOf(matcher.matches()); } else { return Boolean.FALSE; } } }
25.08
88
0.645136
2d49310fd0526a212a4bbd93d95117d1fa6b414e
26,139
/******************************************************************************* * Copyright (c) 2003, 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.swt.browser; import org.eclipse.swt.*; import org.eclipse.swt.internal.*; import org.eclipse.swt.internal.mozilla.*; import org.eclipse.swt.widgets.*; class PromptService2 { XPCOMObject supports; XPCOMObject promptService; XPCOMObject promptService2; int refCount = 0; PromptService2 () { createCOMInterfaces (); } int AddRef () { refCount++; return refCount; } void createCOMInterfaces () { /* Create each of the interfaces that this object implements */ supports = new XPCOMObject (new int[] {2, 0, 0}) { @Override public long /*int*/ method0 (long /*int*/[] args) {return QueryInterface (args[0], args[1]);} @Override public long /*int*/ method1 (long /*int*/[] args) {return AddRef ();} @Override public long /*int*/ method2 (long /*int*/[] args) {return Release ();} }; promptService = new XPCOMObject (new int[] {2, 0, 0, 3, 5, 4, 6, 10, 7, 8, 7, 7}) { @Override public long /*int*/ method0 (long /*int*/[] args) {return QueryInterface (args[0], args[1]);} @Override public long /*int*/ method1 (long /*int*/[] args) {return AddRef ();} @Override public long /*int*/ method2 (long /*int*/[] args) {return Release ();} @Override public long /*int*/ method3 (long /*int*/[] args) {return Alert (args[0], args[1], args[2]);} @Override public long /*int*/ method4 (long /*int*/[] args) {return AlertCheck (args[0], args[1], args[2], args[3], args[4]);} @Override public long /*int*/ method5 (long /*int*/[] args) {return Confirm (args[0], args[1], args[2], args[3]);} @Override public long /*int*/ method6 (long /*int*/[] args) {return ConfirmCheck (args[0], args[1], args[2], args[3], args[4], args[5]);} @Override public long /*int*/ method7 (long /*int*/[] args) {return ConfirmEx (args[0], args[1], args[2], (int)/*64*/args[3], args[4], args[5], args[6], args[7], args[8], args[9]);} @Override public long /*int*/ method8 (long /*int*/[] args) {return Prompt (args[0], args[1], args[2], args[3], args[4], args[5], args[6]);} @Override public long /*int*/ method9 (long /*int*/[] args) {return PromptUsernameAndPassword (args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);} @Override public long /*int*/ method10 (long /*int*/[] args) {return PromptPassword (args[0], args[1], args[2], args[3], args[4], args[5], args[6]);} @Override public long /*int*/ method11 (long /*int*/[] args) {return Select (args[0], args[1], args[2], (int)/*64*/args[3], args[4], args[5], args[6]);} }; promptService2 = new XPCOMObject (new int[] {2, 0, 0, 3, 5, 4, 6, 10, 7, 8, 7, 7, 7, 9}) { @Override public long /*int*/ method0 (long /*int*/[] args) {return QueryInterface (args[0], args[1]);} @Override public long /*int*/ method1 (long /*int*/[] args) {return AddRef ();} @Override public long /*int*/ method2 (long /*int*/[] args) {return Release ();} @Override public long /*int*/ method3 (long /*int*/[] args) {return Alert (args[0], args[1], args[2]);} @Override public long /*int*/ method4 (long /*int*/[] args) {return AlertCheck (args[0], args[1], args[2], args[3], args[4]);} @Override public long /*int*/ method5 (long /*int*/[] args) {return Confirm (args[0], args[1], args[2], args[3]);} @Override public long /*int*/ method6 (long /*int*/[] args) {return ConfirmCheck (args[0], args[1], args[2], args[3], args[4], args[5]);} @Override public long /*int*/ method7 (long /*int*/[] args) {return ConfirmEx (args[0], args[1], args[2], (int)/*64*/args[3], args[4], args[5], args[6], args[7], args[8], args[9]);} @Override public long /*int*/ method8 (long /*int*/[] args) {return Prompt (args[0], args[1], args[2], args[3], args[4], args[5], args[6]);} @Override public long /*int*/ method9 (long /*int*/[] args) {return PromptUsernameAndPassword (args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);} @Override public long /*int*/ method10 (long /*int*/[] args) {return PromptPassword (args[0], args[1], args[2], args[3], args[4], args[5], args[6]);} @Override public long /*int*/ method11 (long /*int*/[] args) {return Select (args[0], args[1], args[2], (int)/*64*/args[3], args[4], args[5], args[6]);} @Override public long /*int*/ method12 (long /*int*/[] args) {return PromptAuth (args[0], args[1], (int)/*64*/args[2], args[3], args[4], args[5], args[6]);} @Override public long /*int*/ method13 (long /*int*/[] args) {return AsyncPromptAuth (args[0], args[1], args[2], args[3], (int)/*64*/args[4], args[5], args[6], args[7], args[8]);} }; } void disposeCOMInterfaces () { if (supports != null) { supports.dispose (); supports = null; } if (promptService != null) { promptService.dispose (); promptService = null; } if (promptService2 != null) { promptService2.dispose (); promptService2 = null; } } long /*int*/ getAddress () { return promptService2.getAddress (); } int QueryInterface (long /*int*/ riid, long /*int*/ ppvObject) { if (riid == 0 || ppvObject == 0) return XPCOM.NS_ERROR_NO_INTERFACE; nsID guid = new nsID (); XPCOM.memmove (guid, riid, nsID.sizeof); if (guid.Equals (nsISupports.NS_ISUPPORTS_IID)) { XPCOM.memmove (ppvObject, new long /*int*/[] {supports.getAddress ()}, C.PTR_SIZEOF); AddRef (); return XPCOM.NS_OK; } if (guid.Equals (nsIPromptService.NS_IPROMPTSERVICE_IID)) { XPCOM.memmove (ppvObject, new long /*int*/[] {promptService.getAddress ()}, C.PTR_SIZEOF); AddRef (); return XPCOM.NS_OK; } if (guid.Equals (XPCOM.NS_IPROMPTSERVICE2_IID)) { XPCOM.memmove (ppvObject, new long /*int*/[] {promptService2.getAddress ()}, C.PTR_SIZEOF); AddRef (); return XPCOM.NS_OK; } XPCOM.memmove (ppvObject, new long /*int*/[] {0}, C.PTR_SIZEOF); return XPCOM.NS_ERROR_NO_INTERFACE; } int Release () { refCount--; if (refCount == 0) disposeCOMInterfaces (); return refCount; } Browser getBrowser (long /*int*/ aDOMWindow) { if (aDOMWindow == 0) return null; return Mozilla.getBrowser (aDOMWindow); } String getLabel (int buttonFlag, int index, long /*int*/ buttonTitle) { String label = null; int flag = (buttonFlag & (0xff * index)) / index; switch (flag) { case nsIPromptService.BUTTON_TITLE_CANCEL : label = SWT.getMessage ("SWT_Cancel"); break; //$NON-NLS-1$ case nsIPromptService.BUTTON_TITLE_NO : label = SWT.getMessage ("SWT_No"); break; //$NON-NLS-1$ case nsIPromptService.BUTTON_TITLE_OK : label = SWT.getMessage ("SWT_OK"); break; //$NON-NLS-1$ case nsIPromptService.BUTTON_TITLE_SAVE : label = SWT.getMessage ("SWT_Save"); break; //$NON-NLS-1$ case nsIPromptService.BUTTON_TITLE_YES : label = SWT.getMessage ("SWT_Yes"); break; //$NON-NLS-1$ case nsIPromptService.BUTTON_TITLE_IS_STRING : { int length = XPCOM.strlen_PRUnichar (buttonTitle); char[] dest = new char[length]; XPCOM.memmove (dest, buttonTitle, length * 2); label = new String (dest); } } return label; } /* nsIPromptService */ int Alert (long /*int*/ aParent, long /*int*/ aDialogTitle, long /*int*/ aText) { final Browser browser = getBrowser (aParent); int length = XPCOM.strlen_PRUnichar (aDialogTitle); char[] dest = new char[length]; XPCOM.memmove (dest, aDialogTitle, length * 2); String titleLabel = new String (dest); length = XPCOM.strlen_PRUnichar (aText); dest = new char[length]; XPCOM.memmove (dest, aText, length * 2); String textLabel = new String (dest); /* * If mozilla is re-navigating to a page with a bad certificate in order * to get its certificate info then do not show cert error message alerts. */ if (browser != null) { Mozilla mozilla = (Mozilla)browser.webBrowser; if (mozilla.isRetrievingBadCert) return XPCOM.NS_OK; } Shell shell = browser == null ? new Shell () : browser.getShell (); MessageBox messageBox = new MessageBox (shell, SWT.OK | SWT.ICON_WARNING); messageBox.setText (titleLabel); messageBox.setMessage (textLabel); messageBox.open (); return XPCOM.NS_OK; } int AlertCheck (long /*int*/ aParent, long /*int*/ aDialogTitle, long /*int*/ aText, long /*int*/ aCheckMsg, long /*int*/ aCheckState) { Browser browser = getBrowser (aParent); int length = XPCOM.strlen_PRUnichar (aDialogTitle); char[] dest = new char[length]; XPCOM.memmove (dest, aDialogTitle, length * 2); String titleLabel = new String (dest); length = XPCOM.strlen_PRUnichar (aText); dest = new char[length]; XPCOM.memmove (dest, aText, length * 2); String textLabel = new String (dest); length = XPCOM.strlen_PRUnichar (aCheckMsg); dest = new char[length]; XPCOM.memmove (dest, aCheckMsg, length * 2); String checkLabel = new String (dest); Shell shell = browser == null ? new Shell () : browser.getShell (); PromptDialog dialog = new PromptDialog (shell); boolean[] check = new boolean[1]; if (aCheckState != 0) XPCOM.memmove (check, aCheckState); dialog.alertCheck (titleLabel, textLabel, checkLabel, check); if (aCheckState != 0) XPCOM.memmove (aCheckState, check); return XPCOM.NS_OK; } int AsyncPromptAuth(long /*int*/ aParent, long /*int*/ aChannel, long /*int*/ aCallback, long /*int*/ aContext, int level, long /*int*/ authInfo, long /*int*/ checkboxLabel, long /*int*/ checkValue, long /*int*/ _retval) { return XPCOM.NS_ERROR_NOT_IMPLEMENTED; } int Confirm (long /*int*/ aParent, long /*int*/ aDialogTitle, long /*int*/ aText, long /*int*/ _retval) { Browser browser = getBrowser (aParent); if (browser != null && ((Mozilla)browser.webBrowser).ignoreAllMessages) { XPCOM.memmove (_retval, new boolean[] {true}); return XPCOM.NS_OK; } int length = XPCOM.strlen_PRUnichar (aDialogTitle); char[] dest = new char[length]; XPCOM.memmove (dest, aDialogTitle, length * 2); String titleLabel = new String (dest); length = XPCOM.strlen_PRUnichar (aText); dest = new char[length]; XPCOM.memmove (dest, aText, length * 2); String textLabel = new String (dest); Shell shell = browser == null ? new Shell () : browser.getShell (); MessageBox messageBox = new MessageBox (shell, SWT.OK | SWT.CANCEL | SWT.ICON_QUESTION); messageBox.setText (titleLabel); messageBox.setMessage (textLabel); int id = messageBox.open (); boolean[] result = {id == SWT.OK}; XPCOM.memmove (_retval, result); return XPCOM.NS_OK; } int ConfirmCheck (long /*int*/ aParent, long /*int*/ aDialogTitle, long /*int*/ aText, long /*int*/ aCheckMsg, long /*int*/ aCheckState, long /*int*/ _retval) { return XPCOM.NS_ERROR_NOT_IMPLEMENTED; } int ConfirmEx (long /*int*/ aParent, long /*int*/ aDialogTitle, long /*int*/ aText, int aButtonFlags, long /*int*/ aButton0Title, long /*int*/ aButton1Title, long /*int*/ aButton2Title, long /*int*/ aCheckMsg, long /*int*/ aCheckState, long /*int*/ _retval) { Browser browser = getBrowser (aParent); int length = XPCOM.strlen_PRUnichar (aDialogTitle); char[] dest = new char[length]; XPCOM.memmove (dest, aDialogTitle, length * 2); String titleLabel = new String (dest); length = XPCOM.strlen_PRUnichar (aText); dest = new char[length]; XPCOM.memmove (dest, aText, length * 2); String textLabel = new String (dest); String checkLabel = null; if (aCheckMsg != 0) { length = XPCOM.strlen_PRUnichar (aCheckMsg); dest = new char[length]; XPCOM.memmove (dest, aCheckMsg, length * 2); checkLabel = new String (dest); } String button0Label = getLabel (aButtonFlags, nsIPromptService.BUTTON_POS_0, aButton0Title); String button1Label = getLabel (aButtonFlags, nsIPromptService.BUTTON_POS_1, aButton1Title); String button2Label = getLabel (aButtonFlags, nsIPromptService.BUTTON_POS_2, aButton2Title); int defaultIndex = 0; if ((aButtonFlags & nsIPromptService.BUTTON_POS_1_DEFAULT) != 0) { defaultIndex = 1; } else if ((aButtonFlags & nsIPromptService.BUTTON_POS_2_DEFAULT) != 0) { defaultIndex = 2; } Shell shell = browser == null ? new Shell () : browser.getShell (); PromptDialog dialog = new PromptDialog (shell); boolean[] check = new boolean[1]; int[] result = new int[1]; if (aCheckState != 0) XPCOM.memmove (check, aCheckState); dialog.confirmEx (titleLabel, textLabel, checkLabel, button0Label, button1Label, button2Label, defaultIndex, check, result); if (aCheckState != 0) XPCOM.memmove (aCheckState, check); XPCOM.memmove (_retval, result, 4); return XPCOM.NS_OK; } int Prompt (long /*int*/ aParent, long /*int*/ aDialogTitle, long /*int*/ aText, long /*int*/ aValue, long /*int*/ aCheckMsg, long /*int*/ aCheckState, long /*int*/ _retval) { Browser browser = getBrowser (aParent); String titleLabel = null, textLabel, checkLabel = null; String[] valueLabel = new String[1]; char[] dest; int length; if (aDialogTitle != 0) { length = XPCOM.strlen_PRUnichar (aDialogTitle); dest = new char[length]; XPCOM.memmove (dest, aDialogTitle, length * 2); titleLabel = new String (dest); } length = XPCOM.strlen_PRUnichar (aText); dest = new char[length]; XPCOM.memmove (dest, aText, length * 2); textLabel = new String (dest); long /*int*/[] valueAddr = new long /*int*/[1]; XPCOM.memmove (valueAddr, aValue, C.PTR_SIZEOF); if (valueAddr[0] != 0) { length = XPCOM.strlen_PRUnichar (valueAddr[0]); dest = new char[length]; XPCOM.memmove (dest, valueAddr[0], length * 2); valueLabel[0] = new String (dest); } if (aCheckMsg != 0) { length = XPCOM.strlen_PRUnichar (aCheckMsg); if (length > 0) { dest = new char[length]; XPCOM.memmove (dest, aCheckMsg, length * 2); checkLabel = new String (dest); } } Shell shell = browser == null ? new Shell () : browser.getShell (); PromptDialog dialog = new PromptDialog (shell); boolean[] check = new boolean[1], result = new boolean[1]; if (aCheckState != 0) XPCOM.memmove (check, aCheckState); dialog.prompt (titleLabel, textLabel, checkLabel, valueLabel, check, result); XPCOM.memmove (_retval, result); if (result[0]) { /* * User selected OK. User name and password are returned as PRUnichar values. Any default * value that we override must be freed using the nsIMemory service. */ if (valueLabel[0] != null) { long /*int*/[] result2 = new long /*int*/[1]; int rc = XPCOM.NS_GetServiceManager (result2); if (rc != XPCOM.NS_OK) SWT.error (rc); if (result2[0] == 0) SWT.error (XPCOM.NS_NOINTERFACE); nsIServiceManager serviceManager = new nsIServiceManager (result2[0]); result2[0] = 0; byte[] aContractID = MozillaDelegate.wcsToMbcs (null, XPCOM.NS_MEMORY_CONTRACTID, true); rc = serviceManager.GetServiceByContractID (aContractID, nsIMemory.NS_IMEMORY_24_IID, result2); if (rc != XPCOM.NS_OK) { rc = serviceManager.GetServiceByContractID (aContractID, nsIMemory.NS_IMEMORY_IID, result2); } if (rc != XPCOM.NS_OK) SWT.error (rc); if (result2[0] == 0) SWT.error (XPCOM.NS_NOINTERFACE); serviceManager.Release (); nsIMemory memory = new nsIMemory (result2[0]); result2[0] = 0; int cnt = valueLabel[0].length (); char[] buffer = new char[cnt + 1]; valueLabel[0].getChars (0, cnt, buffer, 0); int size = buffer.length * 2; long /*int*/ ptr = memory.Alloc (size); XPCOM.memmove (ptr, buffer, size); XPCOM.memmove (aValue, new long /*int*/[] {ptr}, C.PTR_SIZEOF); if (valueAddr[0] != 0) { memory.Free (valueAddr[0]); } memory.Release (); } } if (aCheckState != 0) XPCOM.memmove (aCheckState, check); return XPCOM.NS_OK; } int PromptAuth(long /*int*/ aParent, long /*int*/ aChannel, int level, long /*int*/ authInfo, long /*int*/ checkboxLabel, long /*int*/ checkboxValue, long /*int*/ _retval) { nsIAuthInformation auth = new nsIAuthInformation (authInfo); Browser browser = getBrowser (aParent); if (browser != null) { Mozilla mozilla = (Mozilla)browser.webBrowser; /* * Do not invoke the listeners if this challenge has been failed too many * times because a listener is likely giving incorrect credentials repeatedly * and will do so indefinitely. */ if (mozilla.authCount++ < 3) { for (int i = 0; i < mozilla.authenticationListeners.length; i++) { AuthenticationEvent event = new AuthenticationEvent (browser); event.location = mozilla.lastNavigateURL; mozilla.authenticationListeners[i].authenticate (event); if (!event.doit) { XPCOM.memmove (_retval, new boolean[] {false}); return XPCOM.NS_OK; } if (event.user != null && event.password != null) { nsEmbedString string = new nsEmbedString (event.user); int rc = auth.SetUsername (string.getAddress ()); if (rc != XPCOM.NS_OK) SWT.error (rc); string.dispose (); string = new nsEmbedString (event.password); rc = auth.SetPassword (string.getAddress ()); if (rc != XPCOM.NS_OK) SWT.error (rc); string.dispose (); XPCOM.memmove (_retval, new boolean[] {true}); return XPCOM.NS_OK; } } } } /* no listener handled the challenge, so show an authentication dialog */ String checkLabel = null; boolean[] checkValue = new boolean[1]; String[] userLabel = new String[1], passLabel = new String[1]; String title = SWT.getMessage ("SWT_Authentication_Required"); //$NON-NLS-1$ if (checkboxLabel != 0 && checkboxValue != 0) { int length = XPCOM.strlen_PRUnichar (checkboxLabel); char[] dest = new char[length]; XPCOM.memmove (dest, checkboxLabel, length * 2); checkLabel = new String (dest); XPCOM.memmove (checkValue, checkboxValue); } /* get initial username and password values */ long /*int*/ ptr = XPCOM.nsEmbedString_new (); int rc = auth.GetUsername (ptr); if (rc != XPCOM.NS_OK) SWT.error (rc); int length = XPCOM.nsEmbedString_Length (ptr); long /*int*/ buffer = XPCOM.nsEmbedString_get (ptr); char[] chars = new char[length]; XPCOM.memmove (chars, buffer, length * 2); userLabel[0] = new String (chars); XPCOM.nsEmbedString_delete (ptr); ptr = XPCOM.nsEmbedString_new (); rc = auth.GetPassword (ptr); if (rc != XPCOM.NS_OK) SWT.error (rc); length = XPCOM.nsEmbedString_Length (ptr); buffer = XPCOM.nsEmbedString_get (ptr); chars = new char[length]; XPCOM.memmove (chars, buffer, length * 2); passLabel[0] = new String (chars); XPCOM.nsEmbedString_delete (ptr); /* compute the message text */ ptr = XPCOM.nsEmbedString_new (); rc = auth.GetRealm (ptr); if (rc != XPCOM.NS_OK) SWT.error (rc); length = XPCOM.nsEmbedString_Length (ptr); buffer = XPCOM.nsEmbedString_get (ptr); chars = new char[length]; XPCOM.memmove (chars, buffer, length * 2); String realm = new String (chars); XPCOM.nsEmbedString_delete (ptr); nsIChannel channel = new nsIChannel (aChannel); long /*int*/[] uri = new long /*int*/[1]; rc = channel.GetURI (uri); if (rc != XPCOM.NS_OK) SWT.error (rc); if (uri[0] == 0) Mozilla.error (XPCOM.NS_NOINTERFACE); nsIURI nsURI = new nsIURI (uri[0]); long /*int*/ host = XPCOM.nsEmbedCString_new (); rc = nsURI.GetHost (host); if (rc != XPCOM.NS_OK) SWT.error (rc); length = XPCOM.nsEmbedCString_Length (host); buffer = XPCOM.nsEmbedCString_get (host); byte[] bytes = new byte[length]; XPCOM.memmove (bytes, buffer, length); String hostString = new String (bytes); XPCOM.nsEmbedCString_delete (host); nsURI.Release (); String message; if (realm.length () > 0 && hostString.length () > 0) { message = Compatibility.getMessage ("SWT_Enter_Username_and_Password", new String[] {realm, hostString}); //$NON-NLS-1$ } else { message = ""; //$NON-NLS-1$ } /* open the prompter */ Shell shell = browser == null ? new Shell () : browser.getShell (); PromptDialog dialog = new PromptDialog (shell); boolean[] result = new boolean[1]; dialog.promptUsernameAndPassword (title, message, checkLabel, userLabel, passLabel, checkValue, result); XPCOM.memmove (_retval, result); if (result[0]) { /* User selected OK */ nsEmbedString string = new nsEmbedString (userLabel[0]); rc = auth.SetUsername(string.getAddress ()); if (rc != XPCOM.NS_OK) SWT.error (rc); string.dispose (); string = new nsEmbedString (passLabel[0]); rc = auth.SetPassword(string.getAddress ()); if (rc != XPCOM.NS_OK) SWT.error (rc); string.dispose (); } if (checkboxValue != 0) XPCOM.memmove (checkboxValue, checkValue); return XPCOM.NS_OK; } int PromptUsernameAndPassword (long /*int*/ aParent, long /*int*/ aDialogTitle, long /*int*/ aText, long /*int*/ aUsername, long /*int*/ aPassword, long /*int*/ aCheckMsg, long /*int*/ aCheckState, long /*int*/ _retval) { Browser browser = getBrowser (aParent); String user = null, password = null; if (browser != null) { Mozilla mozilla = (Mozilla)browser.webBrowser; /* * Do not invoke the listeners if this challenge has been failed too many * times because a listener is likely giving incorrect credentials repeatedly * and will do so indefinitely. */ if (mozilla.authCount++ < 3) { for (int i = 0; i < mozilla.authenticationListeners.length; i++) { AuthenticationEvent event = new AuthenticationEvent (browser); event.location = mozilla.lastNavigateURL; mozilla.authenticationListeners[i].authenticate (event); if (!event.doit) { XPCOM.memmove (_retval, new boolean[] {false}); return XPCOM.NS_OK; } if (event.user != null && event.password != null) { user = event.user; password = event.password; XPCOM.memmove (_retval, new boolean[] {true}); break; } } } } if (user == null) { /* no listener handled the challenge, so show an authentication dialog */ String titleLabel, textLabel, checkLabel = null; String[] userLabel = new String[1], passLabel = new String[1]; char[] dest; int length; if (aDialogTitle != 0) { length = XPCOM.strlen_PRUnichar (aDialogTitle); dest = new char[length]; XPCOM.memmove (dest, aDialogTitle, length * 2); titleLabel = new String (dest); } else { titleLabel = SWT.getMessage ("SWT_Authentication_Required"); //$NON-NLS-1$ } length = XPCOM.strlen_PRUnichar (aText); dest = new char[length]; XPCOM.memmove (dest, aText, length * 2); textLabel = new String (dest); long /*int*/[] userAddr = new long /*int*/[1]; XPCOM.memmove (userAddr, aUsername, C.PTR_SIZEOF); if (userAddr[0] != 0) { length = XPCOM.strlen_PRUnichar (userAddr[0]); dest = new char[length]; XPCOM.memmove (dest, userAddr[0], length * 2); userLabel[0] = new String (dest); } long /*int*/[] passAddr = new long /*int*/[1]; XPCOM.memmove (passAddr, aPassword, C.PTR_SIZEOF); if (passAddr[0] != 0) { length = XPCOM.strlen_PRUnichar (passAddr[0]); dest = new char[length]; XPCOM.memmove (dest, passAddr[0], length * 2); passLabel[0] = new String (dest); } if (aCheckMsg != 0) { length = XPCOM.strlen_PRUnichar (aCheckMsg); if (length > 0) { dest = new char[length]; XPCOM.memmove (dest, aCheckMsg, length * 2); checkLabel = new String (dest); } } Shell shell = browser == null ? new Shell () : browser.getShell (); PromptDialog dialog = new PromptDialog (shell); boolean[] check = new boolean[1], result = new boolean[1]; if (aCheckState != 0) XPCOM.memmove (check, aCheckState); dialog.promptUsernameAndPassword (titleLabel, textLabel, checkLabel, userLabel, passLabel, check, result); XPCOM.memmove (_retval, result); if (result[0]) { /* User selected OK */ user = userLabel[0]; password = passLabel[0]; } if (aCheckState != 0) XPCOM.memmove (aCheckState, check); } if (user != null) { /* * User name and password are returned as PRUnichar values. Any default * value that we override must be freed using the nsIMemory service. */ long /*int*/[] userAddr = new long /*int*/[1]; XPCOM.memmove (userAddr, aUsername, C.PTR_SIZEOF); long /*int*/[] passAddr = new long /*int*/[1]; XPCOM.memmove (passAddr, aPassword, C.PTR_SIZEOF); long /*int*/[] result = new long /*int*/[1]; int rc = XPCOM.NS_GetServiceManager (result); if (rc != XPCOM.NS_OK) SWT.error (rc); if (result[0] == 0) SWT.error (XPCOM.NS_NOINTERFACE); nsIServiceManager serviceManager = new nsIServiceManager (result[0]); result[0] = 0; byte[] aContractID = MozillaDelegate.wcsToMbcs (null, XPCOM.NS_MEMORY_CONTRACTID, true); rc = serviceManager.GetServiceByContractID (aContractID, nsIMemory.NS_IMEMORY_24_IID, result); if (rc != XPCOM.NS_OK) { rc = serviceManager.GetServiceByContractID (aContractID, nsIMemory.NS_IMEMORY_IID, result); } if (rc != XPCOM.NS_OK) SWT.error (rc); if (result[0] == 0) SWT.error (XPCOM.NS_NOINTERFACE); serviceManager.Release (); nsIMemory memory = new nsIMemory (result[0]); result[0] = 0; if (userAddr[0] != 0) memory.Free (userAddr[0]); if (passAddr[0] != 0) memory.Free (passAddr[0]); memory.Release (); /* write the name and password values */ int cnt = user.length (); char[] buffer = new char[cnt + 1]; user.getChars (0, cnt, buffer, 0); int size = buffer.length * 2; long /*int*/ ptr = C.malloc (size); XPCOM.memmove (ptr, buffer, size); XPCOM.memmove (aUsername, new long /*int*/[] {ptr}, C.PTR_SIZEOF); cnt = password.length (); buffer = new char[cnt + 1]; password.getChars (0, cnt, buffer, 0); size = buffer.length * 2; ptr = C.malloc (size); XPCOM.memmove (ptr, buffer, size); XPCOM.memmove (aPassword, new long /*int*/[] {ptr}, C.PTR_SIZEOF); } return XPCOM.NS_OK; } int PromptPassword (long /*int*/ aParent, long /*int*/ aDialogTitle, long /*int*/ aText, long /*int*/ aPassword, long /*int*/ aCheckMsg, long /*int*/ aCheckState, long /*int*/ _retval) { return XPCOM.NS_ERROR_NOT_IMPLEMENTED; } int Select (long /*int*/ aParent, long /*int*/ aDialogTitle, long /*int*/ aText, int aCount, long /*int*/ aSelectList, long /*int*/ aOutSelection, long /*int*/ _retval) { return XPCOM.NS_ERROR_NOT_IMPLEMENTED; } }
37.827786
259
0.668847
8eb618f44bb139ea8b515085a8899e87aa165b15
1,433
/* * Danny Do * CS141 * Assignment 4 * 5/16/18 */ import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class LicensePlate { public static void main(String []args) throws IOException { askInput(); } public static void askInput() throws IOException { Scanner in = new Scanner(System.in); File file = new File("/src/wordsEn.txt"); Scanner fileScan = new Scanner(file); ArrayList<String>dictArray = new ArrayList<String>(); while(fileScan.hasNextLine()) { dictArray.add(fileScan.nextLine()); String userInput = " "; do { System.out.println("Enter a 3 letter string"); userInput = in.nextLine().toLowerCase(); if(userInput.toLowerCase().equals("exit")) { System.exit(0); } else { if(userInput.length()!=3) System.out.println("Enter only 3 letters"); else { userInput = in.nextLine().toLowerCase(); char[]lettersArr = new char[3]; lettersArr[0] = userInput.charAt(0); lettersArr[1] = userInput.charAt(1); lettersArr[2] = userInput.charAt(2); for(String s :dictArray) { int foundLetters = 0; for(int i = 0; i<s.length(); i++) { if(foundLetters<=2) if(s.charAt(i)== lettersArr[foundLetters]) foundLetters ++; } if(foundLetters ==3) { System.out.println(s); } } } } }while(userInput !="exit"); } in.close(); fileScan.close(); } }
22.046154
61
0.63224
0f445c46d622ae13eccf804ff9e84e48bf50bfba
788
package net.minecraft.client.renderer.texture; import java.io.IOException; import net.minecraft.client.renderer.texture.AbstractTexture; import net.minecraft.client.resources.IResourceManager; import net.minecraft.util.ResourceLocation; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class SimpleTexture extends AbstractTexture { private static final Logger LOGGER = LogManager.getLogger(); protected final ResourceLocation textureLocation; public SimpleTexture(ResourceLocation var1) { this.textureLocation = var1; } public void loadTexture(IResourceManager param1) throws IOException { // $FF: Couldn't be decompiled } private static RuntimeException a(RuntimeException var0) { return var0; } }
30.307692
72
0.782995
bbdfb63cafdb531f59b531068eb826bcde4898a2
821
package com.google.appengine.api.images; import java.util.logging.Level; import java.util.logging.Logger; public class ImagesServiceFactory { private static String LOG_TAG = ImagesServiceFactory.class.getName(); public static Image makeImage(byte[] bytes) { try { return new Image(bytes); } catch(Exception e) { Logger.getLogger(LOG_TAG).log(Level.SEVERE, e.toString()); return null; } } public static ImagesService getImagesService() { return new ImagesService(); } public static Transform makeCrop(int left, int top, int right, int bottom) { return new Transform(left, top, right, bottom); } public static Transform makeResize(int width, int height) { return new Transform(width, height); } public static Transform makeRotate(int rotation) { return new Transform(rotation); } }
24.147059
77
0.738124
5624788964135b97415ce72d997d598485301bde
1,276
package io.github.liveisgood8.jacksonversioning; import com.fasterxml.jackson.core.JsonProcessingException; import io.github.liveisgood8.jacksonversioning.annotation.JsonVersioned; import io.github.liveisgood8.jacksonversioning.util.TestUtils; import io.github.liveisgood8.jacksonversioning.util.VersionConstant; import org.junit.jupiter.api.Test; class UntilVersionTest { private static final int AMOUNT = 500; private static final TestObject TEST_OBJECT = new TestObject("test"); @Test void testForV1_0() throws JsonProcessingException { TestUtils.assertSerializedJson( String.format("{\"name\":\"%s\",\"amount\":%d}", TEST_OBJECT.name, AMOUNT), TEST_OBJECT, VersionConstant.V1_0 ); } @Test void testForV3_0() throws JsonProcessingException { TestUtils.assertSerializedJson(String.format("{\"name\":\"%s\"}", TEST_OBJECT.name), TEST_OBJECT, VersionConstant.V3_0); } private static class TestObject { public final String name; public TestObject(String name) { this.name = name; } @JsonVersioned(until = VersionConstant.V2_0_STRING) public Integer getAmount() { return AMOUNT; } } }
30.380952
128
0.679467
269812924c7c1af3c3b255b71ce14eb0e0e400a8
39,504
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package amgad.h; import Entity.BoardDecisions; import Entity.Classes; import Entity.Contacts; import Entity.EmployeeAttendance; import Entity.Evaluation; import Entity.Payroll; import Entity.Persons; import Entity.SchoolExpenses; import Entity.Staff; import Entity.StudyYears; import Entity.Subjects; import Entity.UserLog; import Util.HibernateUtil; import Util.LoginSec; import java.io.IOException; import java.sql.Timestamp; import java.util.Date; import java.util.List; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.fxml.FXMLLoader; import javafx.geometry.NodeOrientation; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.layout.AnchorPane; import javafx.stage.Modality; import javafx.stage.Stage; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; /** * * @author Abdo */ public class Management { private root MainApp; private static Stage dialogStage; private static Stage dialogStage2; private static Contacts C; UserLog ul; static Staff edit;//staff TO BE EDITED static EmployeeAttendance editStatus; static Payroll editPayrollStatus; EmployeeAttendance EA; Payroll PR; SessionFactory sf = HibernateUtil.getSessionFactory(); Session s; ObservableList<Contacts> ContactsList = FXCollections.observableArrayList(); public ObservableList<Contacts> getContactsList() { return ContactsList; } static ObservableList<BoardDecisions> BoardDecisionList = FXCollections.observableArrayList(); public static ObservableList<BoardDecisions> getBoardDecisionList() { return BoardDecisionList; } static ObservableList<SchoolExpenses> SchoolExpensesList = FXCollections.observableArrayList(); public static ObservableList<SchoolExpenses> getSchoolExpensesList() { return SchoolExpensesList; } public static void setC(Contacts con) { C = con; } public static Contacts getContacts() { return C; } public static EmployeeAttendance getEditStatus() { return editStatus; } public static void setEditStatus(EmployeeAttendance editStatus) { Management.editStatus = editStatus; } public static Staff getEdit() { return edit; } public static void setEdit(Staff dit) { edit = dit; } public static Payroll getEditPayrollStatus() { return editPayrollStatus; } public static void setEditPayrollStatus(Payroll editPayrollStatus) { Management.editPayrollStatus = editPayrollStatus; } static ObservableList<Staff> PersonsList = FXCollections.observableArrayList(); public static ObservableList<Staff> getPersonsList() { return PersonsList; } static ObservableList<Persons> EmpList = FXCollections.observableArrayList(); public static ObservableList<Persons> getEmpList() { return EmpList; } static ObservableList<Payroll> PayrollList = FXCollections.observableArrayList(); public static ObservableList<Payroll> getPayrollList() { return PayrollList; } static ObservableList<Evaluation> EvaluationList = FXCollections.observableArrayList(); public static ObservableList<Evaluation> getEvaluationList() { return EvaluationList; } public List<StudyYears> getSY() { s = sf.openSession(); s.beginTransaction(); Query query = s.getNamedQuery("StudyYears.findAll"); List<StudyYears> sy = query.list(); s.close(); return sy; } public List<Subjects> getSYSubjects(String SYDesc) { s = sf.openSession(); s.beginTransaction(); Query query = s.getNamedQuery("Subjects.findBySyDesc").setParameter("syDesc", SYDesc); List<Subjects> sy = query.list(); s.close(); return sy; } public void setEvaluationList(List<Evaluation> EvaluationList) { this.EvaluationList = FXCollections.observableArrayList(EvaluationList); } public List<Evaluation> getEvaluations() { s = sf.openSession(); s.beginTransaction(); Query query = s.getNamedQuery("Evaluation.findByPId").setParameter("pId", edit.getPId()); List<Evaluation> sy = query.list(); s.close(); return sy; } public List<Staff> getTeachers() { s = sf.openSession(); s.beginTransaction(); Query query = s.getNamedQuery("Staff.findAll"); List<Staff> sy = query.list(); s.close(); return sy; } public List<Staff> getActiveTeachers() { s = sf.openSession(); s.beginTransaction(); Query query = s.getNamedQuery("Staff.findByStatus").setParameter("status", "1"); List<Staff> sy = query.list(); s.close(); return sy; } public List<BoardDecisions> getBoardDecision() { s = sf.openSession(); s.beginTransaction(); Query query = s.getNamedQuery("BoardDecisions.findAll"); List<BoardDecisions> sy = query.list(); s.close(); return sy; } public List<SchoolExpenses> getSchoolExpenses() { s = sf.openSession(); s.beginTransaction(); Query query = s.getNamedQuery("SchoolExpenses.findAll"); List<SchoolExpenses> sy = query.list(); s.close(); return sy; } public static Stage getDialogStage() { return dialogStage; } public static Stage getDialogStage2() { return dialogStage2; } public List<Classes> getStudyYears() { s = sf.openSession(); s.beginTransaction(); Query query = s.createQuery("from Classes"); List<Classes> sy = query.list(); s.close(); return sy; } public Classes getClassesByDesc(String desc) { s = sf.openSession(); s.beginTransaction(); Query query = s.getNamedQuery("Classes.findByClassDesc"). setParameter("classDesc", desc); List<Classes> sy = query.list(); s.close(); return sy.get(0); } public void setMainApp(root mainApp) { this.MainApp = mainApp; } public void newEmp() { try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(Main.class.getResource("/View/RegisterEmp.fxml")); AnchorPane page = loader.load(); dialogStage = new Stage(); dialogStage.getIcons().add(new Image(Main.class.getResourceAsStream("/resources/6.jpg"))); dialogStage.setTitle("ุชุณุฌูŠู„ ุงู„ู…ูˆุธููŠู†"); dialogStage.initModality(Modality.WINDOW_MODAL); dialogStage.initOwner(this.MainApp.getPrimaryStage()); Scene scene = new Scene(page); scene.setNodeOrientation(NodeOrientation.LEFT_TO_RIGHT); dialogStage.setScene(scene); dialogStage.showAndWait(); } catch (IOException e) { e.printStackTrace(); } } public void PersistNewTeac(Persons p, Staff te) { try { String log = "User : " + LoginSec.getLoggedUser().getUName() + " -- Created"; s = sf.openSession(); Transaction t = s.beginTransaction(); s.persist(p); log += " -- new Person with id " + p.getPId(); s.persist(te); log += " -- new Staff with id " + te.getStId(); for (Contacts c : ContactsList) { c.setPId(p); s.persist(c); log += " -- new Contact with id " + c.getCId(); } ul = new UserLog(); ul.setUId(LoginSec.getLoggedUser()); ul.setLogDate(new Timestamp(new Date().getTime())); ul.setLogDESC(log); s.persist(ul); t.commit(); this.dialogStage.close(); } catch (Exception e) { System.err.println("ERROR IN HIBERNATE : " + e); System.err.println("ERROR IN HIBERNATE : " + e.getCause()); } } public void editEmp() { try { PersonsList.addAll(getTeachers()); FXMLLoader loader = new FXMLLoader(); loader.setLocation(Main.class.getResource("/View/EditEmp.fxml")); AnchorPane page = loader.load(); dialogStage = new Stage(); dialogStage.getIcons().add(new Image(Main.class.getResourceAsStream("/resources/6.jpg"))); dialogStage.setTitle("ุชุนุฏุจู„ ุงู„ู…ูˆุธููŠู†"); dialogStage.initModality(Modality.WINDOW_MODAL); dialogStage.initOwner(this.MainApp.getPrimaryStage()); Scene scene = new Scene(page); scene.setNodeOrientation(NodeOrientation.LEFT_TO_RIGHT); dialogStage.setScene(scene); dialogStage.showAndWait(); PersonsList.clear(); } catch (IOException e) { e.printStackTrace(); } } public void editTeacherDetail() { try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(Main.class.getResource("/View/EditEmpDetail.fxml")); AnchorPane page = loader.load(); dialogStage2 = new Stage(); dialogStage2.getIcons().add(new Image(Main.class.getResourceAsStream("/resources/6.jpg"))); dialogStage2.setTitle("ุชุนุฏูŠู„ ุจูŠุงู†ุงุช ุงู„ุทุงู„ุจ"); dialogStage2.initModality(Modality.WINDOW_MODAL); dialogStage2.initOwner(this.getDialogStage()); Scene scene = new Scene(page); scene.setNodeOrientation(NodeOrientation.LEFT_TO_RIGHT); dialogStage2.setScene(scene); dialogStage2.showAndWait(); } catch (IOException e) { e.printStackTrace(); } } public void UpdateTeacher(Staff st, List<Contacts> cons) { try { String log = "User : " + LoginSec.getLoggedUser().getUName() + " -- Updated"; s = sf.openSession(); Transaction t = s.beginTransaction(); s.update(st); log += " -- Person with id " + st.getPId(); log += " -- Staff with id " + st.getStId(); for (Contacts c : cons) { c.setPId(st.getPId()); s.saveOrUpdate(c); log += " -- Contact with id " + c.getCId(); } ul = new UserLog(); ul.setUId(LoginSec.getLoggedUser()); ul.setLogDate(new Timestamp(new Date().getTime())); ul.setLogDESC(log); s.persist(ul); s.update(st.getPId()); t.commit(); Management.dialogStage2.close(); PersonsList.clear(); PersonsList.addAll(getTeachers()); System.out.println("All Done"); } catch (Exception e) { System.err.println("ERROR IN HIBERNATE : " + e.getLocalizedMessage()); System.err.println("ERROR IN HIBERNATE : " + e); System.err.println("ERROR IN HIBERNATE : " + e.getCause()); throw e; } } public void newCon() { try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(Main.class.getResource("/View/EmpContacts.fxml")); AnchorPane page = loader.load(); dialogStage2 = new Stage(); dialogStage2.getIcons().add(new Image(Main.class.getResourceAsStream("/resources/6.jpg"))); dialogStage2.setTitle("ุฌู‡ุงุช ุงู„ุงุชุตุงู„"); dialogStage2.initModality(Modality.WINDOW_MODAL); dialogStage2.initOwner(this.getDialogStage()); Scene scene = new Scene(page); scene.setNodeOrientation(NodeOrientation.LEFT_TO_RIGHT); dialogStage2.setScene(scene); dialogStage2.showAndWait(); } catch (IOException e) { e.printStackTrace(); } } public void newSub() { try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(Main.class.getResource("/View/EmpClasses.fxml")); AnchorPane page = loader.load(); dialogStage2 = new Stage(); dialogStage2.getIcons().add(new Image(Main.class.getResourceAsStream("/resources/6.jpg"))); dialogStage2.setTitle("ุงู„ูุตูˆู„"); dialogStage2.initModality(Modality.WINDOW_MODAL); dialogStage2.initOwner(this.getDialogStage()); Scene scene = new Scene(page); scene.setNodeOrientation(NodeOrientation.LEFT_TO_RIGHT); dialogStage2.setScene(scene); dialogStage2.showAndWait(); } catch (IOException e) { e.printStackTrace(); } } public void AbsentEmp() { try { PersonsList.addAll(getActiveTeachers()); FXMLLoader loader = new FXMLLoader(); loader.setLocation(Main.class.getResource("/View/Absent_Emp.fxml")); AnchorPane page = loader.load(); dialogStage = new Stage(); dialogStage.getIcons().add(new Image(Main.class.getResourceAsStream("/resources/6.jpg"))); dialogStage.setTitle("ุชุณุฌูŠู„ ุบูŠุงุจ ุงู„ู…ูˆุธููŠู†"); dialogStage.initModality(Modality.WINDOW_MODAL); dialogStage.initOwner(this.MainApp.getPrimaryStage()); Scene scene = new Scene(page); scene.setNodeOrientation(NodeOrientation.LEFT_TO_RIGHT); dialogStage.setScene(scene); dialogStage.showAndWait(); PersonsList.clear(); } catch (IOException e) { e.printStackTrace(); } } public boolean PersistNewAbsent(String Notes, Staff su, Date dt, String Type, String DurationType, String Duration) { try { String log = "User : " + LoginSec.getLoggedUser().getUName() + " -- Created"; s = sf.openSession(); Transaction t = s.beginTransaction(); EA = new EmployeeAttendance(); EA.setStatus(true); if (Notes.equals("")) { EA.setEaDesc(null); } EA.setEaDate(dt); EA.setStId(su); EA.setTimeAmount(Integer.parseInt(Duration)); if (DurationType.equals("ุฏู‚ุงุฆู‚")) { EA.setTimeType("1"); } else { EA.setTimeType("2"); } if (Type.equals("ุชุฃุฎูŠุฑ")) { EA.setAbscenceType("1"); } else if (Type.equals("ุงุณุชุฆุฐุงู†")) { EA.setAbscenceType("2"); } else if (Type.equals("ู…ู†ุญุฉ")) { EA.setAbscenceType("3"); } else if (Type.equals("ุณู†ูˆูŠุฉ")) { EA.setAbscenceType("5"); } else { EA.setAbscenceType("6"); } s.persist(EA); log += " -- new Employee Absence with id " + EA.getEaId(); ul = new UserLog(); ul.setUId(LoginSec.getLoggedUser()); ul.setLogDate(new Timestamp(new Date().getTime())); ul.setLogDESC(log); s.persist(ul); t.commit(); PersonsList.clear(); PersonsList.addAll(getActiveTeachers()); return true; } catch (Exception e) { System.err.println("El72 " + e.getMessage()); return false; } } public void BoardDecision() { try { BoardDecisionList.addAll(getBoardDecision()); FXMLLoader loader = new FXMLLoader(); loader.setLocation(Main.class.getResource("/View/BoardDecision.fxml")); AnchorPane page = loader.load(); dialogStage = new Stage(); dialogStage.getIcons().add(new Image(Main.class.getResourceAsStream("/resources/6.jpg"))); dialogStage.setTitle("ู‚ุฑุงุฑุงุช ุงู„ุงุฏุงุฑุฉ"); dialogStage.initModality(Modality.WINDOW_MODAL); dialogStage.initOwner(this.MainApp.getPrimaryStage()); Scene scene = new Scene(page); scene.setNodeOrientation(NodeOrientation.LEFT_TO_RIGHT); dialogStage.setScene(scene); dialogStage.showAndWait(); BoardDecisionList.clear(); } catch (IOException e) { e.printStackTrace(); } } public void PersistDecision(BoardDecisions bd) { try { String log = "User : " + LoginSec.getLoggedUser().getUName() + " -- Created"; s = sf.openSession(); Transaction t = s.beginTransaction(); s.persist(bd); log += " -- new Board Decision with id " + bd.getBdId(); ul = new UserLog(); ul.setUId(LoginSec.getLoggedUser()); ul.setLogDate(new Timestamp(new Date().getTime())); ul.setLogDESC(log); s.persist(ul); t.commit(); BoardDecisionList.clear(); BoardDecisionList.addAll(getBoardDecision()); } catch (Exception e) { System.err.println("El72 " + e.getMessage()); } } public void UpdateDecision(BoardDecisions bd) { try { String log = "User : " + LoginSec.getLoggedUser().getUName() + " -- Updated"; s = sf.openSession(); Transaction t = s.beginTransaction(); s.update(bd); log += " -- Board Decision with id " + bd.getBdId(); ul = new UserLog(); ul.setUId(LoginSec.getLoggedUser()); ul.setLogDate(new Timestamp(new Date().getTime())); ul.setLogDESC(log); s.persist(ul); t.commit(); BoardDecisionList.clear(); BoardDecisionList.addAll(getBoardDecision()); } catch (Exception e) { System.err.println("El72 " + e.getMessage()); } } public void newSchoolExpense() { try { SchoolExpensesList.addAll(getSchoolExpenses()); FXMLLoader loader = new FXMLLoader(); loader.setLocation(Main.class.getResource("/View/SchoolExpenses.fxml")); AnchorPane page = loader.load(); dialogStage2 = new Stage(); dialogStage2.getIcons().add(new Image(Main.class.getResourceAsStream("/resources/6.jpg"))); dialogStage2.setTitle("ู†ุซุฑูŠุงุช ุงู„ู…ุฏุฑุณุฉ"); dialogStage2.initModality(Modality.WINDOW_MODAL); dialogStage2.initOwner(this.getDialogStage()); Scene scene = new Scene(page); scene.setNodeOrientation(NodeOrientation.LEFT_TO_RIGHT); dialogStage2.setScene(scene); dialogStage2.showAndWait(); SchoolExpensesList.clear(); } catch (IOException e) { e.printStackTrace(); } } public void PersistSchoolExpense(SchoolExpenses bd) { try { String log = "User : " + LoginSec.getLoggedUser().getUName() + " -- Created"; s = sf.openSession(); Transaction t = s.beginTransaction(); s.persist(bd); log += " -- new School Expense with id " + bd.getSceId(); ul = new UserLog(); ul.setUId(LoginSec.getLoggedUser()); ul.setLogDate(new Timestamp(new Date().getTime())); ul.setLogDESC(log); s.persist(ul); t.commit(); SchoolExpensesList.clear(); SchoolExpensesList.addAll(getSchoolExpenses()); } catch (Exception e) { System.err.println("El72 " + e.getMessage()); } } public void UpdateSchoolExpense(SchoolExpenses bd) { try { String log = "User : " + LoginSec.getLoggedUser().getUName() + " -- Updated"; s = sf.openSession(); Transaction t = s.beginTransaction(); s.update(bd); log += " -- School Expenses with id " + bd.getSceId(); ul = new UserLog(); ul.setUId(LoginSec.getLoggedUser()); ul.setLogDate(new Timestamp(new Date().getTime())); ul.setLogDESC(log); s.persist(ul); t.commit(); SchoolExpensesList.clear(); SchoolExpensesList.addAll(getSchoolExpenses()); } catch (Exception e) { System.err.println("El72 " + e.getMessage()); } } public void ViewTeacher() { try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(Main.class.getResource("/View/ViewStaff.fxml")); AnchorPane page = loader.load(); dialogStage2 = new Stage(); dialogStage2.getIcons().add(new Image(Main.class.getResourceAsStream("/resources/6.jpg"))); dialogStage2.setTitle("ุนุฑุถ ุงู„ู…ูˆุธู"); dialogStage2.initModality(Modality.WINDOW_MODAL); dialogStage2.initOwner(this.getDialogStage()); Scene scene = new Scene(page); scene.setNodeOrientation(NodeOrientation.LEFT_TO_RIGHT); dialogStage2.setScene(scene); dialogStage2.showAndWait(); } catch (IOException e) { e.printStackTrace(); } } public void UpdateAbscenceStatus(EmployeeAttendance ea) { try { String log = "User : " + LoginSec.getLoggedUser().getUName() + " -- Updated"; s = sf.openSession(); Transaction t = s.beginTransaction(); s.update(ea); log += " -- Emp Attendece with id " + ea.getEaId(); ul = new UserLog(); ul.setUId(LoginSec.getLoggedUser()); ul.setLogDate(new Timestamp(new Date().getTime())); ul.setLogDESC(log); s.persist(ul); t.commit(); } catch (Exception e) { System.err.println("ERROR IN HIBERNATE : " + e); System.err.println("ERROR IN HIBERNATE : " + e.getCause()); } } public void ViewEditAbscentStatus() { try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(Main.class.getResource("/View/EditStaffAbscentStatus.fxml")); AnchorPane page = loader.load(); dialogStage2 = new Stage(); dialogStage2.getIcons().add(new Image(Main.class.getResourceAsStream("/resources/6.jpg"))); dialogStage2.setTitle("ุชุนุฏูŠู„ ุญุงู„ุฉ ุงู„ุบูŠุงุจ"); dialogStage2.initModality(Modality.WINDOW_MODAL); dialogStage2.initOwner(this.getDialogStage()); Scene scene = new Scene(page); scene.setNodeOrientation(NodeOrientation.LEFT_TO_RIGHT); dialogStage2.setScene(scene); dialogStage2.showAndWait(); } catch (IOException e) { e.printStackTrace(); } } public List<Persons> getActiveEmp() { s = sf.openSession(); s.beginTransaction(); Query query = s.getNamedQuery("Persons.findforBonus"); List<Persons> sy = query.list(); query = s.getNamedQuery("Persons.findforBonus2"); sy.addAll(query.list()); s.close(); return sy; } public List<Payroll> getPayrolls() { s = sf.openSession(); s.beginTransaction(); Query query = s.getNamedQuery("Payroll.findAll"); List<Payroll> sy = query.list(); s.close(); return sy; } public void bonus() { try { EmpList.addAll(getActiveEmp()); FXMLLoader loader = new FXMLLoader(); loader.setLocation(Main.class.getResource("/View/Bonus.fxml")); AnchorPane page = loader.load(); dialogStage = new Stage(); dialogStage.getIcons().add(new Image(Main.class.getResourceAsStream("/resources/6.jpg"))); dialogStage.setTitle("ุงู„ู…ูƒุงูุฃุช"); dialogStage.initModality(Modality.WINDOW_MODAL); dialogStage.initOwner(this.MainApp.getPrimaryStage()); Scene scene = new Scene(page); scene.setNodeOrientation(NodeOrientation.LEFT_TO_RIGHT); dialogStage.setScene(scene); dialogStage.showAndWait(); EmpList.clear(); } catch (IOException e) { e.printStackTrace(); } } public boolean PersistNewBonus(String Notes, Persons su, Date dt, String Type, String Amount, boolean Recieved) { try { String log = "User : " + LoginSec.getLoggedUser().getUName() + " -- Created"; s = sf.openSession(); Transaction t = s.beginTransaction(); PR = new Payroll(); PR.setAmount(Double.parseDouble(Amount)); PR.setPrStatus(true); PR.setPRNotes(Notes); PR.setPrDate(dt); PR.setPId(su); PR.setPrTypeBonus(Type); PR.setPrType("1"); // 1 for bonus s.persist(PR); log += " -- new Bonus Payroll with id " + PR.getPrId(); ul = new UserLog(); ul.setUId(LoginSec.getLoggedUser()); ul.setLogDate(new Timestamp(new Date().getTime())); ul.setLogDESC(log); s.persist(ul); t.commit(); s.refresh(PR); EmpList.clear(); EmpList.addAll(getActiveEmp()); return true; } catch (Exception e) { System.err.println("El72 " + e.getMessage()); return false; } } public void penalty() { try { EmpList.addAll(getActiveEmp()); FXMLLoader loader = new FXMLLoader(); loader.setLocation(Main.class.getResource("/View/Penalty.fxml")); AnchorPane page = loader.load(); dialogStage = new Stage(); dialogStage.getIcons().add(new Image(Main.class.getResourceAsStream("/resources/6.jpg"))); dialogStage.setTitle("ุงู„ุฌุฒุงุกุงุช"); dialogStage.initModality(Modality.WINDOW_MODAL); dialogStage.initOwner(this.MainApp.getPrimaryStage()); Scene scene = new Scene(page); scene.setNodeOrientation(NodeOrientation.LEFT_TO_RIGHT); dialogStage.setScene(scene); dialogStage.showAndWait(); EmpList.clear(); } catch (IOException e) { e.printStackTrace(); } } public boolean PersistNewPenalty(String Notes, Persons su, Date dt, String Amount, String IssuedBy) { try { String log = "User : " + LoginSec.getLoggedUser().getUName() + " -- Created"; s = sf.openSession(); Transaction t = s.beginTransaction(); PR = new Payroll(); PR.setAmount(Double.parseDouble(Amount)); PR.setPrStatus(true); PR.setPRNotes(IssuedBy + " - " + Notes); PR.setPrDate(new Timestamp(dt.getTime())); PR.setPId(su); PR.setPrType("2"); // 2 for Penalty s.persist(PR); log += " -- new Penalty Payroll with id " + PR.getPrId(); ul = new UserLog(); ul.setUId(LoginSec.getLoggedUser()); ul.setLogDate(new Timestamp(new Date().getTime())); ul.setLogDESC(log); s.persist(ul); t.commit(); s.refresh(PR); EmpList.clear(); EmpList.addAll(getActiveEmp()); return true; } catch (Exception e) { System.err.println("El72 " + e.getMessage()); return false; } } public void ViewPayroll() { try { PayrollList.addAll(getPayrolls()); FXMLLoader loader = new FXMLLoader(); loader.setLocation(Main.class.getResource("/View/ViewPayroll.fxml")); AnchorPane page = loader.load(); dialogStage = new Stage(); dialogStage.getIcons().add(new Image(Main.class.getResourceAsStream("/resources/6.jpg"))); dialogStage.setTitle("ุงู„ู…ุฑุชุจุงุช"); dialogStage.initModality(Modality.WINDOW_MODAL); dialogStage.initOwner(this.MainApp.getPrimaryStage()); Scene scene = new Scene(page); scene.setNodeOrientation(NodeOrientation.LEFT_TO_RIGHT); dialogStage.setScene(scene); dialogStage.showAndWait(); PayrollList.clear(); } catch (IOException e) { e.printStackTrace(); } } public void insurance() { try { EmpList.addAll(getActiveEmp()); FXMLLoader loader = new FXMLLoader(); loader.setLocation(Main.class.getResource("/View/Insurance.fxml")); AnchorPane page = loader.load(); dialogStage = new Stage(); dialogStage.getIcons().add(new Image(Main.class.getResourceAsStream("/resources/6.jpg"))); dialogStage.setTitle("ุงู„ุชุฃู…ูŠู†ุงุช"); dialogStage.initModality(Modality.WINDOW_MODAL); dialogStage.initOwner(this.MainApp.getPrimaryStage()); Scene scene = new Scene(page); scene.setNodeOrientation(NodeOrientation.LEFT_TO_RIGHT); dialogStage.setScene(scene); dialogStage.showAndWait(); EmpList.clear(); } catch (IOException e) { e.printStackTrace(); } } public boolean PersistNewInsurance(String Notes, Persons su, Date dt, String Amount) { try { String log = "User : " + LoginSec.getLoggedUser().getUName() + " -- Created"; s = sf.openSession(); Transaction t = s.beginTransaction(); PR = new Payroll(); PR.setAmount(Double.parseDouble(Amount)); PR.setPrStatus(true); PR.setPRNotes(Notes); PR.setPrDate(dt); PR.setPId(su); PR.setPrType("3"); // 3 for Insurance s.persist(PR); log += " -- new Insurance Payroll with id " + PR.getPrId(); ul = new UserLog(); ul.setUId(LoginSec.getLoggedUser()); ul.setLogDate(new Timestamp(new Date().getTime())); ul.setLogDESC(log); s.persist(ul); t.commit(); EmpList.clear(); EmpList.addAll(getActiveEmp()); return true; } catch (Exception e) { System.err.println("El72 " + e.getMessage()); return false; } } public Payroll PersistNewNetSalary(String Notes, Persons su, Double Amount, String IssuedBy) { try { String log = "User : " + LoginSec.getLoggedUser().getUName() + " -- Created"; s = sf.openSession(); Transaction t = s.beginTransaction(); PR = new Payroll(); PR.setAmount(Amount); PR.setPrStatus(true); PR.setPRNotes(Notes); // PR.setPrDate(dt); PR.setPId(su); PR.setPrType("9"); // 9 for net salary s.persist(PR); log += " -- new net salary Payroll with id " + PR.getPrId(); ul = new UserLog(); ul.setUId(LoginSec.getLoggedUser()); ul.setLogDate(new Timestamp(new Date().getTime())); ul.setLogDESC(log); s.persist(ul); t.commit(); s.refresh(PR); return PR; } catch (Exception e) { System.err.println("El72 " + e.getMessage()); throw e; } } public Payroll PersistNewDeductionsSalary(String Notes, Persons su, Double Amount) { try { String log = "User : " + LoginSec.getLoggedUser().getUName() + " -- Created"; s = sf.openSession(); Transaction t = s.beginTransaction(); PR = new Payroll(); PR.setAmount(Amount); PR.setPrStatus(true); PR.setPRNotes(Notes); // PR.setPrDate(dt); PR.setPId(su); PR.setPrType("8"); // 9 for net salary s.persist(PR); log += " -- new Deductions Salary Payroll with id " + PR.getPrId(); ul = new UserLog(); ul.setUId(LoginSec.getLoggedUser()); ul.setLogDate(new Timestamp(new Date().getTime())); ul.setLogDESC(log); s.persist(ul); t.commit(); s.refresh(PR); return PR; } catch (Exception e) { System.err.println("El72 " + e.getMessage()); throw e; } } public Payroll PersistNewBonusSalary(String Notes, Persons su, Double Amount) { try { String log = "User : " + LoginSec.getLoggedUser().getUName() + " -- Created"; s = sf.openSession(); Transaction t = s.beginTransaction(); PR = new Payroll(); PR.setAmount(Amount); PR.setPrStatus(true); PR.setPRNotes(Notes); // PR.setPrDate(dt); PR.setPId(su); PR.setPrType("7"); // 7 for bonus salary s.persist(PR); log += " -- new Bonus Salary Payroll with id " + PR.getPrId(); ul = new UserLog(); ul.setUId(LoginSec.getLoggedUser()); ul.setLogDate(new Timestamp(new Date().getTime())); ul.setLogDESC(log); s.persist(ul); t.commit(); s.refresh(PR); return PR; } catch (Exception e) { System.err.println("El72 " + e.getMessage()); throw e; } } public void UpdatePayroll(Payroll r) { try { String log = "User : " + LoginSec.getLoggedUser().getUName() + " -- Updated"; s = sf.openSession(); Transaction t = s.beginTransaction(); s.update(r); log += " -- Payroll with id " + r.getPrId(); ul = new UserLog(); ul.setUId(LoginSec.getLoggedUser()); ul.setLogDate(new Timestamp(new Date().getTime())); ul.setLogDESC(log); s.persist(ul); t.commit(); } catch (Exception e) { System.err.println("El72 " + e.getMessage()); } } public void PersistEval(Evaluation e) { try { String log = "User : " + LoginSec.getLoggedUser().getUName() + " -- Created"; s = sf.openSession(); Transaction t = s.beginTransaction(); s.persist(e); log += " -- new Evaluation with id " + e.getEvaId(); log += " -- for Person with id " + e.getPid(); ul = new UserLog(); ul.setUId(LoginSec.getLoggedUser()); ul.setLogDate(new Timestamp(new Date().getTime())); ul.setLogDESC(log); s.persist(ul); t.commit(); EvaluationList.clear(); setEvaluationList(getEvaluations()); } catch (Exception ex) { System.err.println("El72 " + ex.getMessage()); } } public void EditEval(Evaluation e) { try { String log = "User : " + LoginSec.getLoggedUser().getUName() + " -- Updated"; s = sf.openSession(); Transaction t = s.beginTransaction(); s.update(e); log += " -- Evaluation with id " + e.getEvaId(); log += " -- for Person with id " + e.getPid(); ul = new UserLog(); ul.setUId(LoginSec.getLoggedUser()); ul.setLogDate(new Timestamp(new Date().getTime())); ul.setLogDESC(log); s.persist(ul); t.commit(); EvaluationList.clear(); setEvaluationList(getEvaluations()); } catch (Exception ex) { System.err.println("El72 " + ex.getMessage()); } } public void ViewEditPenaltyStatus() { try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(Main.class.getResource("/View/EditEmpPayrollStatus.fxml")); AnchorPane page = loader.load(); dialogStage2 = new Stage(); dialogStage2.getIcons().add(new Image(Main.class.getResourceAsStream("/resources/6.jpg"))); dialogStage2.setTitle("ุชุนุฏูŠู„ ุงู„ุญุงู„ุฉ"); dialogStage2.initModality(Modality.WINDOW_MODAL); dialogStage2.initOwner(this.getDialogStage()); Scene scene = new Scene(page); scene.setNodeOrientation(NodeOrientation.LEFT_TO_RIGHT); dialogStage2.setScene(scene); dialogStage2.showAndWait(); } catch (IOException e) { e.printStackTrace(); } } public void UpdatePenaltyStatus() { try { String log = "User : " + LoginSec.getLoggedUser().getUName() + " -- Updated"; s = sf.openSession(); Transaction t = s.beginTransaction(); s.update(editPayrollStatus); log += " -- Payroll with id " + editPayrollStatus.getPrId(); ul = new UserLog(); ul.setUId(LoginSec.getLoggedUser()); ul.setLogDate(new Timestamp(new Date().getTime())); ul.setLogDESC(log); s.persist(ul); t.commit(); s.refresh(editPayrollStatus); } catch (Exception e) { System.err.println("ERROR IN HIBERNATE : " + e); System.err.println("ERROR IN HIBERNATE : " + e.getCause()); } } public void ReportsMan() { try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(Main.class.getResource("/View/ManagementReport.fxml")); AnchorPane page = loader.load(); dialogStage = new Stage(); dialogStage.getIcons().add(new Image(Main.class.getResourceAsStream("/resources/6.jpg"))); dialogStage.setTitle("ุชู‚ุงุฑูŠุฑ ุงู„ุงุฏุงุฑุฉ"); dialogStage.initModality(Modality.WINDOW_MODAL); dialogStage.initOwner(this.MainApp.getPrimaryStage()); Scene scene = new Scene(page); scene.setNodeOrientation(NodeOrientation.LEFT_TO_RIGHT); dialogStage.setScene(scene); dialogStage.showAndWait(); } catch (IOException e) { e.printStackTrace(); } } public Integer getExpensebyDesc(String syDesc) { s = sf.openSession(); s.beginTransaction(); Query query = s.createSQLQuery("select id from school_expense_lkp where expense_desc = '"+syDesc+"'"); List<Integer> x = query.list(); s.close(); return x.get(0); } public Integer getStudyYearbyDesc(String syDesc) { s = sf.openSession(); s.beginTransaction(); Query query = s.getNamedQuery("StudyYears.findBySyDesc1").setParameter("syDesc", syDesc); List<Integer> x = query.list(); s.close(); return x.get(0); } public Subjects getSubjectsByDescAndYDesc(String desc, String YDesc) { s = sf.openSession(); s.beginTransaction(); Query query = s.getNamedQuery("Subjects.findBySuDescAndSyId"). setParameter("suDesc", desc).setParameter("syDesc", YDesc); List<Subjects> sy = query.list(); s.close(); return sy.get(0); } }
35.52518
110
0.564297
a105031c11dcb2be65e47bbcf4215871cd0c4bf4
1,867
package com.cqx; import com.fasterxml.jackson.databind.ObjectMapper; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Unit test for simple App. */ public class AppTest extends TestCase { /** * Create the test case * * @param testName name of the test case */ public AppTest( String testName ) { super( testName ); } /** * @return the suite of tests being tested */ public static Test suite() { return new TestSuite( AppTest.class ); } /** * Rigourous Test :-) */ public void testApp() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); Person person = new Person(); List<String> list = new ArrayList<>(); list.add("1"); list.add("2"); list.add("3"); List<List<String>> lists = new ArrayList<>(); lists.add(list); lists.add(list); lists.add(list); String[] array = new String[]{"a", "b", "c"}; person.setDatas(lists); person.setDatas1(array); String s = objectMapper.writeValueAsString(person); System.out.println(s); Person person1 = objectMapper.readValue(s, Person.class); assertTrue(true); } public static class Person { private List<List<String>> datas; private String[] datas1; public List<List<String>> getDatas() { return datas; } public void setDatas(List<List<String>> datas) { this.datas = datas; } public String[] getDatas1() { return datas1; } public void setDatas1(String[] datas1) { this.datas1 = datas1; } } }
23.632911
65
0.573112
77f91ca883fa0df59b3bc6c0ec41743d1625e519
5,481
package fr.xephi.authme.process.register; import ch.jalu.injector.factory.SingletonStore; import fr.xephi.authme.TestHelper; import fr.xephi.authme.data.auth.PlayerCache; import fr.xephi.authme.datasource.DataSource; import fr.xephi.authme.message.MessageKey; import fr.xephi.authme.process.register.executors.PasswordRegisterParams; import fr.xephi.authme.process.register.executors.RegistrationExecutor; import fr.xephi.authme.process.register.executors.RegistrationMethod; import fr.xephi.authme.process.register.executors.TwoFactorRegisterParams; import fr.xephi.authme.service.CommonService; import fr.xephi.authme.settings.properties.RegistrationSettings; import fr.xephi.authme.settings.properties.RestrictionSettings; import org.bukkit.entity.Player; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import static org.mockito.ArgumentMatchers.any; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.only; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyZeroInteractions; /** * Test for {@link AsyncRegister}. */ @RunWith(MockitoJUnitRunner.class) public class AsyncRegisterTest { @InjectMocks private AsyncRegister asyncRegister; @Mock private PlayerCache playerCache; @Mock private CommonService commonService; @Mock private DataSource dataSource; @Mock private SingletonStore<RegistrationExecutor> registrationExecutorStore; @Test public void shouldDetectAlreadyLoggedInPlayer() { // given String name = "robert"; Player player = mockPlayerWithName(name); given(playerCache.isAuthenticated(name)).willReturn(true); RegistrationExecutor executor = mock(RegistrationExecutor.class); singletonStoreWillReturn(registrationExecutorStore, executor); // when asyncRegister.register(RegistrationMethod.PASSWORD_REGISTRATION, PasswordRegisterParams.of(player, "abc", null)); // then verify(commonService).send(player, MessageKey.ALREADY_LOGGED_IN_ERROR); verifyZeroInteractions(dataSource, executor); } @Test public void shouldStopForDisabledRegistration() { // given String name = "albert"; Player player = mockPlayerWithName(name); given(playerCache.isAuthenticated(name)).willReturn(false); given(commonService.getProperty(RegistrationSettings.IS_ENABLED)).willReturn(false); RegistrationExecutor executor = mock(RegistrationExecutor.class); singletonStoreWillReturn(registrationExecutorStore, executor); // when asyncRegister.register(RegistrationMethod.TWO_FACTOR_REGISTRATION, TwoFactorRegisterParams.of(player)); // then verify(commonService).send(player, MessageKey.REGISTRATION_DISABLED); verifyZeroInteractions(dataSource, executor); } @Test public void shouldStopForAlreadyRegisteredName() { // given String name = "dilbert"; Player player = mockPlayerWithName(name); given(playerCache.isAuthenticated(name)).willReturn(false); given(commonService.getProperty(RegistrationSettings.IS_ENABLED)).willReturn(true); given(dataSource.isAuthAvailable(name)).willReturn(true); RegistrationExecutor executor = mock(RegistrationExecutor.class); singletonStoreWillReturn(registrationExecutorStore, executor); // when asyncRegister.register(RegistrationMethod.TWO_FACTOR_REGISTRATION, TwoFactorRegisterParams.of(player)); // then verify(commonService).send(player, MessageKey.NAME_ALREADY_REGISTERED); verify(dataSource, only()).isAuthAvailable(name); verifyZeroInteractions(executor); } @Test @SuppressWarnings("unchecked") public void shouldStopForFailedExecutorCheck() { // given String name = "edbert"; Player player = mockPlayerWithName(name); TestHelper.mockPlayerIp(player, "33.44.55.66"); given(playerCache.isAuthenticated(name)).willReturn(false); given(commonService.getProperty(RegistrationSettings.IS_ENABLED)).willReturn(true); given(commonService.getProperty(RestrictionSettings.MAX_REGISTRATION_PER_IP)).willReturn(0); given(dataSource.isAuthAvailable(name)).willReturn(false); RegistrationExecutor executor = mock(RegistrationExecutor.class); TwoFactorRegisterParams params = TwoFactorRegisterParams.of(player); given(executor.isRegistrationAdmitted(params)).willReturn(false); singletonStoreWillReturn(registrationExecutorStore, executor); // when asyncRegister.register(RegistrationMethod.TWO_FACTOR_REGISTRATION, params); // then verify(dataSource, only()).isAuthAvailable(name); verify(executor, only()).isRegistrationAdmitted(params); } private static Player mockPlayerWithName(String name) { Player player = mock(Player.class); given(player.getName()).willReturn(name); return player; } @SuppressWarnings("unchecked") private static void singletonStoreWillReturn(SingletonStore<RegistrationExecutor> store, RegistrationExecutor mock) { given(store.getSingleton(any(Class.class))).willReturn(mock); } }
39.717391
121
0.738369
b5a0302344afb61b9a5b4ba69154c6eb35bb9ad2
133
/** * Provides tools for parsing long strings into individual components such as terms. */ package com.dsi.parallax.ml.util.lexer;
33.25
85
0.759398
d5649341d819100f3e21a69667a0f9636d87e456
1,745
package com.daninovac.batch.jobs.utils.xml; import com.thoughtworks.xstream.converters.Converter; import com.thoughtworks.xstream.converters.MarshallingContext; import com.thoughtworks.xstream.converters.UnmarshallingContext; import com.thoughtworks.xstream.io.HierarchicalStreamReader; import com.thoughtworks.xstream.io.HierarchicalStreamWriter; import java.util.AbstractMap; import java.util.Map; import org.bson.Document; public class XmlXStreamConverter implements Converter { @Override public boolean canConvert(Class clazz) { return AbstractMap.class.isAssignableFrom(clazz); } @Override public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) { //noinspection rawtypes AbstractMap map = (AbstractMap) value; for (Object object : map.entrySet()) { @SuppressWarnings("rawtypes") Map.Entry entry = (Map.Entry) object; writer.startNode(entry.getKey().toString()); Object val = entry.getValue(); if (val instanceof Map) { marshal(val, writer, context); } else if (null != val) { writer.setValue(val.toString()); } writer.endNode(); } } @Override public Document unmarshal( HierarchicalStreamReader reader, UnmarshallingContext unmarshallingContext) { Document propertiesBSON = new Document(); while (reader.hasMoreChildren()) { reader.moveDown(); String key = reader.getNodeName(); Object value; if (reader.hasMoreChildren()) { value = unmarshal(reader, unmarshallingContext); } else { value = reader.getValue(); } propertiesBSON.append(key, value); reader.moveUp(); } return propertiesBSON; } }
26.439394
68
0.701433
bd18632a8b34c7b42f645de9af54d938edbef040
5,771
/* * Copyright 2007 The Kuali Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kuali.ole.sys.web.struts; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionMapping; import org.apache.struts.upload.FormFile; import org.kuali.ole.module.purap.document.RequisitionDocument; import org.kuali.ole.select.businessobject.OleLoadFailureRecords; import org.kuali.ole.select.businessobject.OleLoadSumRecords; import org.kuali.ole.select.document.AcquisitionBatchInputFileDocument; import org.kuali.ole.sys.businessobject.AcquisitionBatchUpload; import org.kuali.rice.krad.util.ObjectUtils; import org.kuali.rice.kns.web.struts.form.KualiTransactionalDocumentFormBase; import org.kuali.rice.kns.web.ui.HeaderField; import org.kuali.rice.kew.api.WorkflowDocument; /** * Struts action form for the batch upload screen. */ public class AcquisitionBatchInputFileForm extends KualiTransactionalDocumentFormBase { private FormFile uploadFile; private AcquisitionBatchUpload acquisitionBatchUpload; //private List<KeyLabelPair> userFiles; // private String url; private OleLoadSumRecords oleLoadSumRecords; private List<OleLoadFailureRecords> oleLoadFailureRecordsList; private String fileName; private String titleKey; //private String attachmentLink; //private String fileContents; /*public String getAttachmentLink() { return attachmentLink; } public void setAttachmentLink(String attachmentLink) { this.attachmentLink = attachmentLink; }*/ /** * Gets the batchUpload attribute. */ public AcquisitionBatchUpload getAcquisitionBatchUpload() { return acquisitionBatchUpload; } /** * Sets the batchUpload attribute value. */ public void setAcquisitionBatchUpload(AcquisitionBatchUpload batchUpload) { this.acquisitionBatchUpload = batchUpload; } /** * Gets the uploadFile attribute. */ public FormFile getUploadFile() { return uploadFile; } /** * Sets the uploadFile attribute value. */ public void setUploadFile(FormFile uploadFile) { this.uploadFile = uploadFile; } /** * Gets the userFiles attribute. */ /* public List<KeyLabelPair> getUserFiles() { return userFiles; } *//** * Sets the userFiles attribute value. *//* public void setUserFiles(List<KeyLabelPair> userFiles) { this.userFiles = userFiles; }*/ /** * Gets the titleKey attribute. */ public String getTitleKey() { return titleKey; } /** * Sets the titleKey attribute value. */ public void setTitleKey(String titleKey) { this.titleKey = titleKey; } /** * Gets the url attribute. * @return Returns the url. */ /* public String getUrl() { return url; }*/ /** * Sets the url attribute value. * @param url The url to set. */ /*public void setUrl(String url) { this.url = url; }*/ public OleLoadSumRecords getOleLoadSumRecords() { return oleLoadSumRecords; } public void setOleLoadSumRecords(OleLoadSumRecords oleLoadSumRecords) { this.oleLoadSumRecords = oleLoadSumRecords; } public List<OleLoadFailureRecords> getOleLoadFailureRecordsList() { return oleLoadFailureRecordsList; } public void setOleLoadFailureRecordsList(List<OleLoadFailureRecords> oleLoadFailureRecordsList) { this.oleLoadFailureRecordsList = oleLoadFailureRecordsList; } public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } @Override public String getRefreshCaller(){ return "refreshCaller"; } @Override public void reset(ActionMapping mapping, HttpServletRequest request) { super.reset(mapping, request); } public AcquisitionBatchInputFileForm(){ super(); this.acquisitionBatchUpload = new AcquisitionBatchUpload(); setDocTypeName("OLE_ACQBTHUPLOAD"); setDocument(new AcquisitionBatchInputFileDocument()); } /*public String getFileContents() { return fileContents; } public void setFileContents(String fileContents) { this.fileContents = fileContents; }*/ /** * KRAD Conversion: Performs customization of an header fields. * * Use of data dictionary for bo RequisitionDocument. */ public void populateHeaderFields(WorkflowDocument workflowDocument) { super.populateHeaderFields(workflowDocument); if (ObjectUtils.isNotNull(this.oleLoadSumRecords)) { String displayValue=getDocInfo().get(3).getDisplayValue(); getDocInfo().remove(3); getDocInfo().add(new HeaderField("DataDictionary.OleLoadSumRecords.attributes.loadCreatedDate", displayValue)); getDocInfo().add(new HeaderField("DataDictionary.OleLoadSumRecords.attributes.acqLoadSumId", this.oleLoadSumRecords.getAcqLoadSumId().toString())); } } }
29.443878
158
0.692081
885710460d4b1ce0202c6df2a1614d46490e1658
20,498
/* * Copyright (c) Microsoft. All rights reserved. * Licensed under the MIT license. See LICENSE file in the project root for full license information. */ package tests.unit.com.microsoft.azure.sdk.iot.device.transport.mqtt; import com.microsoft.azure.sdk.iot.device.exceptions.ProtocolException; import com.microsoft.azure.sdk.iot.device.exceptions.TransportException; import com.microsoft.azure.sdk.iot.device.transport.mqtt.MqttConnection; import mockit.Deencapsulation; import mockit.Mocked; import mockit.NonStrictExpectations; import mockit.Verifications; import org.apache.commons.lang3.tuple.Pair; import org.eclipse.paho.client.mqttv3.*; import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence; import org.junit.Test; import javax.net.ssl.SSLContext; import java.io.IOException; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import static org.junit.Assert.*; /* Unit test for MqttConnection Coverage : 100% method, 100% line */ public class MqttConnectionTest { private static final String SERVER_URI = "test.host.name"; private static final String CLIENT_ID = "test.iothub"; private static final String USER_NAME = "test-deviceId"; private static final String PWORD = "this is not a secret"; @Mocked SSLContext mockIotHubSSLContext; @Mocked private MqttAsyncClient mockMqttAsyncClient; @Mocked private MqttConnectOptions mockMqttConnectionOptions; @Mocked private MemoryPersistence mockMemoryPersistence; @Mocked private IMqttToken mockMqttToken; private void baseConstructorExpectations() throws MqttException { new NonStrictExpectations() { { new MemoryPersistence(); result = mockMemoryPersistence; new MqttAsyncClient(SERVER_URI, CLIENT_ID, mockMemoryPersistence); result = mockMqttAsyncClient; new MqttConnectOptions(); result = mockMqttConnectionOptions; } }; } private void baseConstructorVerifications() throws MqttException { new Verifications() { { mockMqttConnectionOptions.setKeepAliveInterval(anyInt); times = 1; mockMqttConnectionOptions.setCleanSession(anyBoolean); times = 1; mockMqttConnectionOptions.setMqttVersion(anyInt); times = 1; mockMqttConnectionOptions.setUserName(USER_NAME); times = 1; mockMqttConnectionOptions.setPassword(PWORD.toCharArray()); times = 1; mockMqttConnectionOptions.setSocketFactory(mockIotHubSSLContext.getSocketFactory()); times = 1; new ConcurrentLinkedQueue<>(); times = 1; new Object(); times = 1; } }; } //Tests_SRS_MQTTCONNECTION_25_003: [The constructor shall create lock, queue for this MqttConnection.] //Tests_SRS_MQTTCONNECTION_25_004: [The constructor shall create an MqttAsync client and update the connection options using the provided SERVER_URI, CLIENT_ID, USER_NAME, PWORD and sslContext.] @Test public void constructorSucceeds() throws Exception { //arrange baseConstructorExpectations(); //act final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, SERVER_URI, CLIENT_ID, USER_NAME, PWORD, mockIotHubSSLContext); //assert baseConstructorVerifications(); MqttAsyncClient actualAsyncClient = Deencapsulation.getField(mqttConnection, "mqttAsyncClient"); assertNotNull(actualAsyncClient); MqttConnectOptions actualConnectionOptions = Deencapsulation.getField(mqttConnection, "connectionOptions"); assertNotNull(actualConnectionOptions); Queue<Pair<String, byte[]>> actualQueue = Deencapsulation.getField(mqttConnection, "allReceivedMessages"); assertNotNull(actualQueue); Object actualLock = Deencapsulation.getField(mqttConnection, "mqttLock"); assertNotNull(actualLock); } @Test (expected = ProtocolException.class) public void constructorThrowsOnAsyncClientFailure() throws Exception { //arrange new NonStrictExpectations() { { new MemoryPersistence(); result = mockMemoryPersistence; new MqttAsyncClient(SERVER_URI, CLIENT_ID, mockMemoryPersistence); result = mockMqttAsyncClient; new MqttConnectOptions(); result = new MqttException(anyInt, (Throwable)any); } }; //act final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, SERVER_URI, CLIENT_ID, USER_NAME, PWORD, mockIotHubSSLContext); } //Tests_SRS_MQTTCONNECTION_25_001: [The constructor shall throw IllegalArgumentException if any of the input parameters are null other than password.] @Test (expected = IllegalArgumentException.class) public void constructorWithNullServerUriThrows() throws Exception { final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, new Class[] {String.class, String.class, String.class, String.class, SSLContext.class}, null, CLIENT_ID, USER_NAME, PWORD, mockIotHubSSLContext); } @Test (expected = IllegalArgumentException.class) public void constructorWithNullClientIdThrows() throws Exception { final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, new Class[] {String.class, String.class, String.class, String.class, SSLContext.class}, SERVER_URI, null, USER_NAME, PWORD, mockIotHubSSLContext); } @Test (expected = IllegalArgumentException.class) public void constructorWithNullUserNameThrows() throws Exception { final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, new Class[] {String.class, String.class, String.class, String.class, SSLContext.class}, SERVER_URI, CLIENT_ID, null, PWORD, mockIotHubSSLContext); } //Tests_SRS_MQTTCONNECTION_25_002: [The constructor shall throw IllegalArgumentException if SERVER_URI, CLIENT_ID, USER_NAME, PWORD are empty.] @Test (expected = IllegalArgumentException.class) public void constructorWithEmptyServerUriThrows() throws Exception { final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, new Class[] {String.class, String.class, String.class, String.class, SSLContext.class}, "", CLIENT_ID, USER_NAME, PWORD, mockIotHubSSLContext); } @Test (expected = IllegalArgumentException.class) public void constructorWithEmptyClientIdThrows() throws Exception { final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, new Class[] {String.class, String.class, String.class, String.class, SSLContext.class}, SERVER_URI, "", USER_NAME, PWORD, mockIotHubSSLContext); } @Test (expected = IllegalArgumentException.class) public void constructorWithEmptyUserNameThrows() throws Exception { final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, new Class[] {String.class, String.class, String.class, String.class, SSLContext.class}, SERVER_URI, CLIENT_ID, "", PWORD, mockIotHubSSLContext); } @Test (expected = IllegalArgumentException.class) public void constructorWithEmptySSLThrows() throws Exception { final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, new Class[] {String.class, String.class, String.class, String.class, SSLContext.class}, SERVER_URI, CLIENT_ID, USER_NAME, PWORD, null); } //Tests_SRS_MQTTCONNECTION_25_007: [Getter for the MqttAsyncClient.] @Test public void getAsyncClientSucceeds() throws Exception { //arrange final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, new Class[] {String.class, String.class, String.class, String.class, SSLContext.class}, SERVER_URI, CLIENT_ID, USER_NAME, PWORD, mockIotHubSSLContext); //act MqttAsyncClient mqttAsyncClient = Deencapsulation.invoke(mqttConnection, "getMqttAsyncClient"); //assert assertNotNull(mqttAsyncClient); } //Tests_SRS_MQTTCONNECTION_25_008: [Getter for the Message Queue.] @Test public void getAllReceivedMessagesSucceeds() throws Exception { //arrange final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, new Class[] {String.class, String.class, String.class, String.class, SSLContext.class}, SERVER_URI, CLIENT_ID, USER_NAME, PWORD, mockIotHubSSLContext); //act ConcurrentLinkedQueue concurrentLinkedQueue = Deencapsulation.invoke(mqttConnection, "getAllReceivedMessages"); //assert assertNotNull(concurrentLinkedQueue); } //Tests_SRS_MQTTCONNECTION_25_009: [Getter for the Mqtt Lock on this connection.] @Test public void getMqttLockSucceeds() throws Exception { //arrange final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, new Class[] {String.class, String.class, String.class, String.class, SSLContext.class}, SERVER_URI, CLIENT_ID, USER_NAME, PWORD, mockIotHubSSLContext); //act Object mqttLock = Deencapsulation.invoke(mqttConnection, "getMqttLock"); //assert assertNotNull(mqttLock); } //Tests_SRS_MQTTCONNECTION_25_010: [Getter for the MqttConnectionOptions.] @Test public void getConnectionOptionsSucceeds() throws Exception { //arrange final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, new Class[] {String.class, String.class, String.class, String.class, SSLContext.class}, SERVER_URI, CLIENT_ID, USER_NAME, PWORD, mockIotHubSSLContext); //act MqttConnectOptions mqttConnectOptions = Deencapsulation.invoke(mqttConnection, "getConnectionOptions"); //assert assertNotNull(mqttConnectOptions); } //Tests_SRS_MQTTCONNECTION_25_011: [Setter for the MqttAsyncClient which can be null.] @Test public void setMqttAsyncClientSucceeds() throws Exception { //arrange final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, new Class[] {String.class, String.class, String.class, String.class, SSLContext.class}, SERVER_URI, CLIENT_ID, USER_NAME, PWORD, mockIotHubSSLContext); MqttAsyncClient testMqttAsyncClient = null; //act Deencapsulation.invoke(mqttConnection, "setMqttAsyncClient", new Class[] {MqttAsyncClient.class}, testMqttAsyncClient); //assert MqttAsyncClient actualMqttAsyncClient = Deencapsulation.getField(mqttConnection, "mqttAsyncClient"); assertEquals(actualMqttAsyncClient, testMqttAsyncClient); } //Tests_SRS_MQTTCONNECTION_25_005: [This method shall set the callback for Mqtt.] @Test public void setMqttCallbackSucceeds(@Mocked MqttCallback mockedMqttCallback) throws Exception { //arrange final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, new Class[] {String.class, String.class, String.class, String.class, SSLContext.class}, SERVER_URI, CLIENT_ID, USER_NAME, PWORD, mockIotHubSSLContext); MqttCallback testMqttCallback = mockedMqttCallback; //act Deencapsulation.invoke(mqttConnection, "setMqttCallback", new Class[] {MqttCallback.class}, testMqttCallback); //assert MqttCallback actualMqttCallback = Deencapsulation.getField(mqttConnection, "mqttCallback"); assertEquals(actualMqttCallback, testMqttCallback); } //Tests_SRS_MQTTCONNECTION_25_006: [This method shall throw IllegalArgumentException if callback is null.] @Test (expected = IllegalArgumentException.class) public void setMqttCallbackThrowsOnNull(@Mocked MqttCallback mockedMqttCallback) throws Exception { //arrange final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, new Class[] {String.class, String.class, String.class, String.class, SSLContext.class}, SERVER_URI, CLIENT_ID, USER_NAME, PWORD, mockIotHubSSLContext); MqttCallback testMqttCallback = null; //act Deencapsulation.invoke(mqttConnection, "setMqttCallback", new Class[] {MqttCallback.class}, testMqttCallback); //assert MqttCallback actualMqttCallback = Deencapsulation.getField(mqttConnection, "mqttCallback"); assertEquals(actualMqttCallback, testMqttCallback); } //Tests_SRS_MQTTCONNECTION_25_012: [This function shall invoke the saved mqttAsyncClient to send the message ack for the provided messageId and then return true.] @Test public void sendMessageAckSendsAck() throws MqttException { //arrange final int expectedMessageId = 13; final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, new Class[] {String.class, String.class, String.class, String.class, SSLContext.class}, SERVER_URI, CLIENT_ID, USER_NAME, PWORD, mockIotHubSSLContext); //act boolean returnedValue = Deencapsulation.invoke(mqttConnection, "sendMessageAcknowledgement", expectedMessageId); //assert assertTrue(returnedValue); new Verifications() { { mockMqttAsyncClient.setManualAcks(true); times = 1; mockMqttAsyncClient.messageArrivedComplete(expectedMessageId, anyInt); } }; } //Tests_SRS_MQTTCONNECTION_25_013: [If this function encounters an MqttException when sending the message ack over the mqtt async client, this function shall translate that exception and throw it.] @Test (expected = ProtocolException.class) public void sendMessageCatchsMqttExceptionAndTranslates() throws MqttException { //arrange final int expectedMessageId = 13; final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, new Class[] {String.class, String.class, String.class, String.class, SSLContext.class}, SERVER_URI, CLIENT_ID, USER_NAME, PWORD, mockIotHubSSLContext); final MqttException mqttException = new MqttException(new Throwable()); new NonStrictExpectations() { { mockMqttAsyncClient.messageArrivedComplete(anyInt, anyInt); result = mqttException; } }; //act boolean returnedValue = Deencapsulation.invoke(mqttConnection, "sendMessageAcknowledgement", expectedMessageId); } //Tests_SRS_MQTTCONNECTION_34_014: [If the saved mqttAsyncClient is not null, this function shall return the // result of invoking isConnected on that object.] @Test public void isConnectedChecksMqttAsyncClientFalse() { //arrange final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, new Class[] {String.class, String.class, String.class, String.class, SSLContext.class}, SERVER_URI, CLIENT_ID, USER_NAME, PWORD, mockIotHubSSLContext); Deencapsulation.setField(mqttConnection, "mqttAsyncClient", mockMqttAsyncClient); new NonStrictExpectations() { { mockMqttAsyncClient.isConnected(); result = false; } }; //act boolean isConnected = Deencapsulation.invoke(mqttConnection, "isConnected"); //assert new Verifications() { { mockMqttAsyncClient.isConnected(); times = 1; } }; assertFalse(isConnected); } //Tests_SRS_MQTTCONNECTION_34_014: [If the saved mqttAsyncClient is not null, this function shall return the // result of invoking isConnected on that object.] @Test public void isConnectedChecksMqttAsyncClientTrue() { //arrange final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, new Class[] {String.class, String.class, String.class, String.class, SSLContext.class}, SERVER_URI, CLIENT_ID, USER_NAME, PWORD, mockIotHubSSLContext); Deencapsulation.setField(mqttConnection, "mqttAsyncClient", mockMqttAsyncClient); new NonStrictExpectations() { { mockMqttAsyncClient.isConnected(); result = true; } }; //act boolean isConnected = Deencapsulation.invoke(mqttConnection, "isConnected"); //assert new Verifications() { { mockMqttAsyncClient.isConnected(); times = 1; } }; assertTrue(isConnected); } //Tests_SRS_MQTTCONNECTION_34_015: [If the saved mqttAsyncClient is null, this function shall return false.] @Test public void isConnectedReturnsFalseIfMqttAsyncClientIsNull() { //arrange final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, new Class[] {String.class, String.class, String.class, String.class, SSLContext.class}, SERVER_URI, CLIENT_ID, USER_NAME, PWORD, mockIotHubSSLContext); Deencapsulation.setField(mqttConnection, "mqttAsyncClient", null); //act boolean isConnected = Deencapsulation.invoke(mqttConnection, "isConnected"); //assert assertFalse(isConnected); } //Tests_SRS_MQTTCONNECTION_34_016: [If the saved mqttAsyncClient is not null, this function shall return the // result of invoking disconnect on that object.] @Test public void disconnectInvokesDisconnectOnAsyncClient() throws MqttException { //arrange final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, new Class[] {String.class, String.class, String.class, String.class, SSLContext.class}, SERVER_URI, CLIENT_ID, USER_NAME, PWORD, mockIotHubSSLContext); Deencapsulation.setField(mqttConnection, "mqttAsyncClient", mockMqttAsyncClient); new NonStrictExpectations() { { mockMqttAsyncClient.disconnect(); result = mockMqttToken; } }; //act IMqttToken actualToken = Deencapsulation.invoke(mqttConnection, "disconnect"); //assert assertEquals(mockMqttToken, actualToken); new Verifications() { { mockMqttAsyncClient.disconnect(); times = 1; } }; } //Tests_SRS_MQTTCONNECTION_34_017: [If the saved mqttAsyncClient is null, this function shall return null.] @Test public void disconnectReturnsNullIfNullAsyncClient() throws MqttException { //arrange final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, new Class[] {String.class, String.class, String.class, String.class, SSLContext.class}, SERVER_URI, CLIENT_ID, USER_NAME, PWORD, mockIotHubSSLContext); Deencapsulation.setField(mqttConnection, "mqttAsyncClient", null); //act IMqttToken actualToken = Deencapsulation.invoke(mqttConnection, "disconnect"); //assert assertNull(actualToken); } //Tests_SRS_MQTTCONNECTION_34_018: [If the saved mqttAsyncClient is not null, this function shall invoke // close on that object.] @Test public void closeInvokesCloseOnAsyncClient() throws MqttException { //arrange final MqttConnection mqttConnection = Deencapsulation.newInstance(MqttConnection.class, new Class[] {String.class, String.class, String.class, String.class, SSLContext.class}, SERVER_URI, CLIENT_ID, USER_NAME, PWORD, mockIotHubSSLContext); Deencapsulation.setField(mqttConnection, "mqttAsyncClient", mockMqttAsyncClient); //act Deencapsulation.invoke(mqttConnection, "close"); //assert new Verifications() { { mockMqttAsyncClient.close(); times = 1; } }; } }
43.244726
247
0.700849
8dae0415223399201c7d949c3f4bb5f28752ebab
18,327
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1 begin_comment comment|/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ end_comment begin_package DECL|package|org.apache.hadoop.examples package|package name|org operator|. name|apache operator|. name|hadoop operator|. name|examples package|; end_package begin_import import|import name|java operator|. name|io operator|. name|DataInput import|; end_import begin_import import|import name|java operator|. name|io operator|. name|DataOutput import|; end_import begin_import import|import name|java operator|. name|io operator|. name|IOException import|; end_import begin_import import|import name|java operator|. name|util operator|. name|StringTokenizer import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|conf operator|. name|Configuration import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|fs operator|. name|Path import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|io operator|. name|IntWritable import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|io operator|. name|LongWritable import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|io operator|. name|RawComparator import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|io operator|. name|Text import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|io operator|. name|WritableComparable import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|io operator|. name|WritableComparator import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|mapreduce operator|. name|lib operator|. name|input operator|. name|FileInputFormat import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|mapreduce operator|. name|lib operator|. name|output operator|. name|FileOutputFormat import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|mapreduce operator|. name|Job import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|mapreduce operator|. name|Mapper import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|mapreduce operator|. name|Partitioner import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|mapreduce operator|. name|Reducer import|; end_import begin_import import|import name|org operator|. name|apache operator|. name|hadoop operator|. name|util operator|. name|GenericOptionsParser import|; end_import begin_comment comment|/** * This is an example Hadoop Map/Reduce application. * It reads the text input files that must contain two integers per a line. * The output is sorted by the first and second number and grouped on the * first number. * * To run: bin/hadoop jar build/hadoop-examples.jar secondarysort *<i>in-dir</i><i>out-dir</i> */ end_comment begin_class DECL|class|SecondarySort specifier|public class|class name|SecondarySort block|{ comment|/** * Define a pair of integers that are writable. * They are serialized in a byte comparable format. */ DECL|class|IntPair specifier|public specifier|static class|class name|IntPair implements|implements name|WritableComparable argument_list|< name|IntPair argument_list|> block|{ DECL|field|first specifier|private name|int name|first init|= literal|0 decl_stmt|; DECL|field|second specifier|private name|int name|second init|= literal|0 decl_stmt|; comment|/** * Set the left and right values. */ DECL|method|set (int left, int right) specifier|public name|void name|set parameter_list|( name|int name|left parameter_list|, name|int name|right parameter_list|) block|{ name|first operator|= name|left expr_stmt|; name|second operator|= name|right expr_stmt|; block|} DECL|method|getFirst () specifier|public name|int name|getFirst parameter_list|() block|{ return|return name|first return|; block|} DECL|method|getSecond () specifier|public name|int name|getSecond parameter_list|() block|{ return|return name|second return|; block|} comment|/** * Read the two integers. * Encoded as: MIN_VALUE -&gt; 0, 0 -&gt; -MIN_VALUE, MAX_VALUE-&gt; -1 */ annotation|@ name|Override DECL|method|readFields (DataInput in) specifier|public name|void name|readFields parameter_list|( name|DataInput name|in parameter_list|) throws|throws name|IOException block|{ name|first operator|= name|in operator|. name|readInt argument_list|() operator|+ name|Integer operator|. name|MIN_VALUE expr_stmt|; name|second operator|= name|in operator|. name|readInt argument_list|() operator|+ name|Integer operator|. name|MIN_VALUE expr_stmt|; block|} annotation|@ name|Override DECL|method|write (DataOutput out) specifier|public name|void name|write parameter_list|( name|DataOutput name|out parameter_list|) throws|throws name|IOException block|{ name|out operator|. name|writeInt argument_list|( name|first operator|- name|Integer operator|. name|MIN_VALUE argument_list|) expr_stmt|; name|out operator|. name|writeInt argument_list|( name|second operator|- name|Integer operator|. name|MIN_VALUE argument_list|) expr_stmt|; block|} annotation|@ name|Override DECL|method|hashCode () specifier|public name|int name|hashCode parameter_list|() block|{ return|return name|first operator|* literal|157 operator|+ name|second return|; block|} annotation|@ name|Override DECL|method|equals (Object right) specifier|public name|boolean name|equals parameter_list|( name|Object name|right parameter_list|) block|{ if|if condition|( name|right operator|instanceof name|IntPair condition|) block|{ name|IntPair name|r init|= operator|( name|IntPair operator|) name|right decl_stmt|; return|return name|r operator|. name|first operator|== name|first operator|&& name|r operator|. name|second operator|== name|second return|; block|} else|else block|{ return|return literal|false return|; block|} block|} comment|/** A Comparator that compares serialized IntPair. */ DECL|class|Comparator specifier|public specifier|static class|class name|Comparator extends|extends name|WritableComparator block|{ DECL|method|Comparator () specifier|public name|Comparator parameter_list|() block|{ name|super argument_list|( name|IntPair operator|. name|class argument_list|) expr_stmt|; block|} DECL|method|compare (byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) specifier|public name|int name|compare parameter_list|( name|byte index|[] name|b1 parameter_list|, name|int name|s1 parameter_list|, name|int name|l1 parameter_list|, name|byte index|[] name|b2 parameter_list|, name|int name|s2 parameter_list|, name|int name|l2 parameter_list|) block|{ return|return name|compareBytes argument_list|( name|b1 argument_list|, name|s1 argument_list|, name|l1 argument_list|, name|b2 argument_list|, name|s2 argument_list|, name|l2 argument_list|) return|; block|} block|} static|static block|{ comment|// register this comparator name|WritableComparator operator|. name|define argument_list|( name|IntPair operator|. name|class argument_list|, operator|new name|Comparator argument_list|() argument_list|) expr_stmt|; block|} annotation|@ name|Override DECL|method|compareTo (IntPair o) specifier|public name|int name|compareTo parameter_list|( name|IntPair name|o parameter_list|) block|{ if|if condition|( name|first operator|!= name|o operator|. name|first condition|) block|{ return|return name|first operator|< name|o operator|. name|first condition|? operator|- literal|1 else|: literal|1 return|; block|} elseif|else if|if condition|( name|second operator|!= name|o operator|. name|second condition|) block|{ return|return name|second operator|< name|o operator|. name|second condition|? operator|- literal|1 else|: literal|1 return|; block|} else|else block|{ return|return literal|0 return|; block|} block|} block|} comment|/** * Partition based on the first part of the pair. */ DECL|class|FirstPartitioner specifier|public specifier|static class|class name|FirstPartitioner extends|extends name|Partitioner argument_list|< name|IntPair argument_list|, name|IntWritable argument_list|> block|{ annotation|@ name|Override DECL|method|getPartition (IntPair key, IntWritable value, int numPartitions) specifier|public name|int name|getPartition parameter_list|( name|IntPair name|key parameter_list|, name|IntWritable name|value parameter_list|, name|int name|numPartitions parameter_list|) block|{ return|return name|Math operator|. name|abs argument_list|( name|key operator|. name|getFirst argument_list|() operator|* literal|127 argument_list|) operator|% name|numPartitions return|; block|} block|} comment|/** * Compare only the first part of the pair, so that reduce is called once * for each value of the first part. */ DECL|class|FirstGroupingComparator specifier|public specifier|static class|class name|FirstGroupingComparator implements|implements name|RawComparator argument_list|< name|IntPair argument_list|> block|{ annotation|@ name|Override DECL|method|compare (byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) specifier|public name|int name|compare parameter_list|( name|byte index|[] name|b1 parameter_list|, name|int name|s1 parameter_list|, name|int name|l1 parameter_list|, name|byte index|[] name|b2 parameter_list|, name|int name|s2 parameter_list|, name|int name|l2 parameter_list|) block|{ return|return name|WritableComparator operator|. name|compareBytes argument_list|( name|b1 argument_list|, name|s1 argument_list|, name|Integer operator|. name|SIZE operator|/ literal|8 argument_list|, name|b2 argument_list|, name|s2 argument_list|, name|Integer operator|. name|SIZE operator|/ literal|8 argument_list|) return|; block|} annotation|@ name|Override DECL|method|compare (IntPair o1, IntPair o2) specifier|public name|int name|compare parameter_list|( name|IntPair name|o1 parameter_list|, name|IntPair name|o2 parameter_list|) block|{ name|int name|l init|= name|o1 operator|. name|getFirst argument_list|() decl_stmt|; name|int name|r init|= name|o2 operator|. name|getFirst argument_list|() decl_stmt|; return|return name|l operator|== name|r condition|? literal|0 else|: operator|( name|l operator|< name|r condition|? operator|- literal|1 else|: literal|1 operator|) return|; block|} block|} comment|/** * Read two integers from each line and generate a key, value pair * as ((left, right), right). */ DECL|class|MapClass specifier|public specifier|static class|class name|MapClass extends|extends name|Mapper argument_list|< name|LongWritable argument_list|, name|Text argument_list|, name|IntPair argument_list|, name|IntWritable argument_list|> block|{ DECL|field|key specifier|private specifier|final name|IntPair name|key init|= operator|new name|IntPair argument_list|() decl_stmt|; DECL|field|value specifier|private specifier|final name|IntWritable name|value init|= operator|new name|IntWritable argument_list|() decl_stmt|; annotation|@ name|Override DECL|method|map (LongWritable inKey, Text inValue, Context context) specifier|public name|void name|map parameter_list|( name|LongWritable name|inKey parameter_list|, name|Text name|inValue parameter_list|, name|Context name|context parameter_list|) throws|throws name|IOException throws|, name|InterruptedException block|{ name|StringTokenizer name|itr init|= operator|new name|StringTokenizer argument_list|( name|inValue operator|. name|toString argument_list|() argument_list|) decl_stmt|; name|int name|left init|= literal|0 decl_stmt|; name|int name|right init|= literal|0 decl_stmt|; if|if condition|( name|itr operator|. name|hasMoreTokens argument_list|() condition|) block|{ name|left operator|= name|Integer operator|. name|parseInt argument_list|( name|itr operator|. name|nextToken argument_list|() argument_list|) expr_stmt|; if|if condition|( name|itr operator|. name|hasMoreTokens argument_list|() condition|) block|{ name|right operator|= name|Integer operator|. name|parseInt argument_list|( name|itr operator|. name|nextToken argument_list|() argument_list|) expr_stmt|; block|} name|key operator|. name|set argument_list|( name|left argument_list|, name|right argument_list|) expr_stmt|; name|value operator|. name|set argument_list|( name|right argument_list|) expr_stmt|; name|context operator|. name|write argument_list|( name|key argument_list|, name|value argument_list|) expr_stmt|; block|} block|} block|} comment|/** * A reducer class that just emits the sum of the input values. */ DECL|class|Reduce specifier|public specifier|static class|class name|Reduce extends|extends name|Reducer argument_list|< name|IntPair argument_list|, name|IntWritable argument_list|, name|Text argument_list|, name|IntWritable argument_list|> block|{ DECL|field|SEPARATOR specifier|private specifier|static specifier|final name|Text name|SEPARATOR init|= operator|new name|Text argument_list|( literal|"------------------------------------------------" argument_list|) decl_stmt|; DECL|field|first specifier|private specifier|final name|Text name|first init|= operator|new name|Text argument_list|() decl_stmt|; annotation|@ name|Override DECL|method|reduce (IntPair key, Iterable<IntWritable> values, Context context ) specifier|public name|void name|reduce parameter_list|( name|IntPair name|key parameter_list|, name|Iterable argument_list|< name|IntWritable argument_list|> name|values parameter_list|, name|Context name|context parameter_list|) throws|throws name|IOException throws|, name|InterruptedException block|{ name|context operator|. name|write argument_list|( name|SEPARATOR argument_list|, literal|null argument_list|) expr_stmt|; name|first operator|. name|set argument_list|( name|Integer operator|. name|toString argument_list|( name|key operator|. name|getFirst argument_list|() argument_list|) argument_list|) expr_stmt|; for|for control|( name|IntWritable name|value range|: name|values control|) block|{ name|context operator|. name|write argument_list|( name|first argument_list|, name|value argument_list|) expr_stmt|; block|} block|} block|} DECL|method|main (String[] args) specifier|public specifier|static name|void name|main parameter_list|( name|String index|[] name|args parameter_list|) throws|throws name|Exception block|{ name|Configuration name|conf init|= operator|new name|Configuration argument_list|() decl_stmt|; name|String index|[] name|otherArgs init|= operator|new name|GenericOptionsParser argument_list|( name|conf argument_list|, name|args argument_list|) operator|. name|getRemainingArgs argument_list|() decl_stmt|; if|if condition|( name|otherArgs operator|. name|length operator|!= literal|2 condition|) block|{ name|System operator|. name|err operator|. name|println argument_list|( literal|"Usage: secondarysort<in><out>" argument_list|) expr_stmt|; name|System operator|. name|exit argument_list|( literal|2 argument_list|) expr_stmt|; block|} name|Job name|job init|= name|Job operator|. name|getInstance argument_list|( name|conf argument_list|, literal|"secondary sort" argument_list|) decl_stmt|; name|job operator|. name|setJarByClass argument_list|( name|SecondarySort operator|. name|class argument_list|) expr_stmt|; name|job operator|. name|setMapperClass argument_list|( name|MapClass operator|. name|class argument_list|) expr_stmt|; name|job operator|. name|setReducerClass argument_list|( name|Reduce operator|. name|class argument_list|) expr_stmt|; comment|// group and partition by the first int in the pair name|job operator|. name|setPartitionerClass argument_list|( name|FirstPartitioner operator|. name|class argument_list|) expr_stmt|; name|job operator|. name|setGroupingComparatorClass argument_list|( name|FirstGroupingComparator operator|. name|class argument_list|) expr_stmt|; comment|// the map output is IntPair, IntWritable name|job operator|. name|setMapOutputKeyClass argument_list|( name|IntPair operator|. name|class argument_list|) expr_stmt|; name|job operator|. name|setMapOutputValueClass argument_list|( name|IntWritable operator|. name|class argument_list|) expr_stmt|; comment|// the reduce output is Text, IntWritable name|job operator|. name|setOutputKeyClass argument_list|( name|Text operator|. name|class argument_list|) expr_stmt|; name|job operator|. name|setOutputValueClass argument_list|( name|IntWritable operator|. name|class argument_list|) expr_stmt|; name|FileInputFormat operator|. name|addInputPath argument_list|( name|job argument_list|, operator|new name|Path argument_list|( name|otherArgs index|[ literal|0 index|] argument_list|) argument_list|) expr_stmt|; name|FileOutputFormat operator|. name|setOutputPath argument_list|( name|job argument_list|, operator|new name|Path argument_list|( name|otherArgs index|[ literal|1 index|] argument_list|) argument_list|) expr_stmt|; name|System operator|. name|exit argument_list|( name|job operator|. name|waitForCompletion argument_list|( literal|true argument_list|) condition|? literal|0 else|: literal|1 argument_list|) expr_stmt|; block|} block|} end_class end_unit
14.396701
814
0.787909
c46c701626e14bb3f796c14d7a5ed5a359ff87b1
2,295
/* * Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazon.randomcutforest.state.sampler; import static com.amazon.randomcutforest.state.Version.V2_0; import lombok.Data; /** * A data object representing the state of a * {@link com.amazon.randomcutforest.sampler.CompactSampler}. */ @Data public class CompactSamplerState { /** * a version string for extensibility */ private String version = V2_0; /** * An array of sampler weights. */ private float[] weight; /** * An array of index values identifying the points in the sample. These indexes * will correspond to a {@link com.amazon.randomcutforest.store.PointStore}. */ private int[] pointIndex; /** * boolean for deciding to store sequence indices */ private boolean storeSequenceIndicesEnabled; /** * The sequence indexes of points in the sample. */ private long[] sequenceIndex; /** * The number of points in the sample. */ private int size; /** * The maximum number of points that the sampler can contain. */ private int capacity; /** * The behavior of the sampler at initial sampling */ private double initialAcceptFraction; /** * The time-decay parameter for this sampler */ private double timeDecay; /** * Last update of timeDecay */ private long sequenceIndexOfMostRecentTimeDecayUpdate; /** * maximum timestamp seen in update/computeWeight */ private long maxSequenceIndex; /** * boolean indicating if the compression is enabled */ private boolean compressed; /** * saving the random state, if desired */ private long randomSeed; }
27.650602
83
0.669717
f6b0e3324a3109674007ddd8dd0a70458471a836
915
package magicbees.item; import magicbees.block.types.HiveType; import net.minecraft.block.Block; import net.minecraft.item.ItemBlock; import net.minecraft.item.ItemStack; import net.minecraft.util.IIcon; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; /** * Created by Allen on 7/29/2014. */ public class ItemMagicHive extends ItemBlock { public ItemMagicHive(Block block) { super(block); setMaxDamage(0); setHasSubtypes(true); } @Override public int getMetadata(int i) { return i; } protected Block getBlock() { return field_150939_a; } @SideOnly(Side.CLIENT) @Override public IIcon getIconFromDamage(int meta) { return this.getBlock().getIcon(1, meta); } @Override public String getUnlocalizedName(ItemStack itemstack) { return getBlock().getUnlocalizedName() + "." + HiveType.getHiveFromMeta(itemstack.getItemDamage()).name().toLowerCase(); } }
21.27907
122
0.75082
6bcfa3ded0c4678ed278f102270d2c78e86578e9
7,081
package com.ViktorVano.SpeechRecognitionAI.Audio; import java.io.*; import javax.sound.sampled.*; import static com.ViktorVano.SpeechRecognitionAI.Miscellaneous.Variables.*; public class AudioCapture { private AudioFormat adFormat; private TargetDataLine targetDataLine; private byte[] mainBuffer = new byte[1000000]; private int mainBufferLength = 0; private int silenceCount = 0; private boolean audioRecorded = false; private boolean recordAudioFlag = true; SourceDataLine sourceLine; AudioInputStream inputStream; public AudioCapture() { captureAudio(); } private void captureAudio() { try { adFormat = AudioParameters.getAudioFormat(); DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, adFormat); targetDataLine = (TargetDataLine) AudioSystem.getLine(dataLineInfo); targetDataLine.open(adFormat); targetDataLine.start(); CaptureThread captureThread = new CaptureThread(); captureThread.start(); System.out.println("Started listening."); } catch (Exception e) { StackTraceElement stackEle[] = e.getStackTrace(); for (StackTraceElement val : stackEle) { System.out.println(val); } System.exit(0); } } public boolean isAudioRecorded() { return audioRecorded; } public byte[] getRecord() { if(audioRecorded) return mainBuffer; else return null; } public int getRecordLength() { return mainBufferLength; } public void clearRecord() { mainBuffer = new byte[1000000]; mainBufferLength = 0; silenceCount = 0; audioRecorded = false; System.out.println("Listening again"); } public void playRecord() { PlayThread playThread; InputStream byteInputStream; DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, adFormat); System.out.println("Playing: " + mainBufferLength); try { byteInputStream = new ByteArrayInputStream(mainBuffer); inputStream = new AudioInputStream(byteInputStream, adFormat, mainBufferLength / adFormat.getFrameSize()); sourceLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo); sourceLine.open(adFormat); sourceLine.start(); playThread = new PlayThread(); playThread.start(); while (playThread.isAlive()); System.out.println("Recording played."); } catch (Exception e) { System.out.println(e); System.exit(0); } } public void playRecord(RecordedAudio recordedAudio) { PlayThread playThread; InputStream byteInputStream; DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, adFormat); System.out.println("Playing: " + recordedAudio.audioRecordLength); try { byteInputStream = new ByteArrayInputStream(recordedAudio.audioRecord); inputStream = new AudioInputStream(byteInputStream, adFormat, recordedAudio.audioRecordLength / adFormat.getFrameSize()); sourceLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo); sourceLine.open(adFormat); sourceLine.start(); playThread = new PlayThread(); playThread.start(); while (playThread.isAlive()); System.out.println("Recording played."); } catch (Exception e) { System.out.println(e); System.exit(0); } } class CaptureThread extends Thread { byte[] tempCaptureBuffer = new byte[(int)AudioParameters.sampleRate]; public void run() { try { while (recordAudioFlag) { int cnt = targetDataLine.read(tempCaptureBuffer, 0, tempCaptureBuffer.length); if (cnt > 0 && mainBufferLength < 980000) { boolean addRecording = false; for(int i = 0; i< tempCaptureBuffer.length; i+=2) { if(Math.abs(tempCaptureBuffer[i] + tempCaptureBuffer[i+1]*256) > recorderThreshold) { addRecording = true; break; } } if(addRecording && !audioRecorded) { System.out.println("Adding a packet"); for(int i = 0; i< tempCaptureBuffer.length; i++) { mainBuffer[i + mainBufferLength] = tempCaptureBuffer[i]; } mainBufferLength += cnt; System.out.println("Main Buffer Length: " + mainBufferLength); silenceCount = 0; }else if(mainBufferLength > 0 && silenceCount < 3 && mainBufferLength < 950000) { for(int i = 0; i< tempCaptureBuffer.length; i++) { mainBuffer[i + mainBufferLength] = tempCaptureBuffer[i]; } mainBufferLength += cnt; System.out.println("Main Buffer Length: " + mainBufferLength); silenceCount ++; }else if (mainBufferLength > 0 && !audioRecorded) { audioRecorded = true; System.out.println("Recording stopped."); } }else if(mainBufferLength >= 980000 && !audioRecorded) { audioRecorded = true; System.out.println("Buffer is full. Recording stopped."); } } } catch (Exception e) { System.out.println("CaptureThread::run()" + e); System.exit(0); } targetDataLine.close(); System.out.println("Audio recording stopped."); } } class PlayThread extends Thread { byte[] tempPlayBuffer = new byte[1000000]; public void run() { try { int cnt; while ((cnt = inputStream.read(tempPlayBuffer, 0, tempPlayBuffer.length)) != -1) { if (cnt > 0) { System.out.println("Played message length: " + cnt); sourceLine.write(tempPlayBuffer, 0, cnt); } } } catch (Exception e) { System.out.println(e); System.exit(0); } } } }
35.762626
133
0.518571
082542fe3a23e02ea4342f087df3e45c4f18a364
235
package com.shawnclake.part9.tree; import com.shawnclake.part9.Token; public class AssignNode extends BinaryOperatorNode { public AssignNode(Node left, Node right, Token operator) { super(left, right, operator); } }
21.363636
62
0.731915
5165e68e59f049030fa4824e176c491a4677e48c
8,126
package v27; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.TreeSet; import logic.ChartTime1mLogic; import logic.FileLockLogic; import util.FileUtil; import util.StringUtil; /** * ไฟๅญ˜ใ—ใŸ4ๆœฌๅ€คใƒใƒฃใƒผใƒˆใƒ‡ใƒผใ‚ฟใจใ€PUSH APIใงๅ—ไฟกใ—ใŸใƒใƒฃใƒผใƒˆใƒ‡ใƒผใ‚ฟใ‚’ใƒžใƒผใ‚ธใ—ใŸ4ๆœฌๅ€คใ‚’ๅ‡บๅŠ›ใ™ใ‚‹ใƒ„ใƒผใƒซใ€‚ */ public class MainMergeChartData_r3 { /** * ๅŸบๆบ–ใƒ‘ใ‚นใ€‚ */ private static final String DIRPATH = "/tmp/"; /** * ใƒใƒฃใƒผใƒˆ๏ผค๏ผขใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒชใƒ‘ใ‚นใ€‚ */ private static final String DIR_DBPATH = DIRPATH + "db/"; /** * 1ๅˆ†่ถณใฎ4ๆœฌๅ€คใƒใƒฃใƒผใƒˆ๏ผค๏ผขใƒ•ใ‚กใ‚คใƒซๅใ€‚ */ private static final String DB_FILENAME = "ChartData1m.db"; /** * ใƒใƒฃใƒผใƒˆใƒ‡ใƒผใ‚ฟใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒชใƒ‘ใ‚นใ€‚ */ private static final String DIR_CHARTPATH = DIRPATH + "chart/"; /** * PUSH APIใงๅ—ไฟกใ—ใŸใƒใƒฃใƒผใƒˆใƒ‡ใƒผใ‚ฟใƒ•ใ‚กใ‚คใƒซๅใ€‚ */ private static final String CHART_CSV_FILENAME = "ChartData.csv"; /** * ใƒ•ใ‚กใ‚คใƒซใƒญใƒƒใ‚ฏ็ฎก็†็”จ0ใƒใ‚คใƒˆใฎใƒ•ใ‚กใ‚คใƒซๅใ€‚ๅญ˜ๅœจใ—ใชใ‘ใ‚Œใฐ็”Ÿๆˆใ•ใ‚Œใ‚‹ใ€‚ */ private static final String LOCK_FILENAME = "ChartData.lock"; /** * ใƒžใƒผใ‚ธใ—ใŸใƒใƒฃใƒผใƒˆใƒ‡ใƒผใ‚ฟใƒ•ใ‚กใ‚คใƒซๅใ€‚ */ private static final String CHART_TXT_FILENAME = "ChartData1m_r3.txt"; /** * ใƒใƒฃใƒผใƒˆๆƒ…ๅ ฑใ‚ฏใƒฉใ‚นใ€‚ */ public static class ChartInfo { /** * 4ๆœฌๅ€คใƒใƒฃใƒผใƒˆ๏ผค๏ผขใƒ•ใ‚กใ‚คใƒซใฎใ‚ซใƒฉใƒ ๆ•ฐใ€‚ */ public static final int MAX_COLS = 6; /** * ๆ™‚้–“่ถณใฎๅ ดๅˆใฏๆ—ฅๆ™‚ใ€‚ๆ—ฅ่ถณใฎๅ ดๅˆใฏๆ—ฅไป˜ใ€‚ */ public String date; /** * ๅง‹ๅ€คใ€‚ */ public int openPrice; /** * ้ซ˜ๅ€คใ€‚ */ public int highPrice; /** * ๅฎ‰ๅ€คใ€‚ */ public int lowPrice; /** * ็ต‚ๅ€คใ€‚ */ public int closePrice; /** * ใƒ‡ใƒผใ‚ฟใƒ•ใƒฉใ‚ฐใ€‚0:ใƒ‡ใƒผใ‚ฟใชใ—ใ€1:4ๆœฌๅ€คใฎใƒ‡ใƒผใ‚ฟใ€2:PUSH APIใงๅ–ๅพ—ใ—ใŸใƒ‡ใƒผใ‚ฟใ€3:ใ‚ณใƒ”ใƒผใ•ใ‚ŒใŸใƒ‡ใƒผใ‚ฟใ€‚ */ public int flag; /** * ใ‚ณใƒณใ‚นใƒˆใƒฉใ‚ฏใ‚ฟ๏ผˆใƒ‡ใƒผใ‚ฟใชใ—๏ผ‰ใ€‚ * * @param date ๆ™‚้–“่ถณใฎๅ ดๅˆใฏๆ—ฅๆ™‚ใ€‚ๆ—ฅ่ถณใฎๅ ดๅˆใฏๆ—ฅไป˜ใ€‚ */ public ChartInfo(String date) { this.date = date; this.openPrice = 0; this.highPrice = 0; this.lowPrice = 0; this.closePrice = 0; this.flag = 0; } /** * ใ‚ณใƒณใ‚นใƒˆใƒฉใ‚ฏใ‚ฟ๏ผˆ4ๆœฌๅ€คใƒใƒฃใƒผใƒˆ๏ผค๏ผขใƒ•ใ‚กใ‚คใƒซ๏ผ‰ใ€‚ * * @param cols 4ๆœฌๅ€คใƒใƒฃใƒผใƒˆ๏ผค๏ผขใƒ•ใ‚กใ‚คใƒซใฎ1ใƒฌใ‚ณใƒผใƒ‰ใฎๅ…จใฆใฎใ‚ซใƒฉใƒ ๆ–‡ๅญ—ๅˆ—ใ€‚ */ public ChartInfo(String[] cols) { int i = 0; this.date = cols[i++]; this.openPrice = StringUtil.parseInt(cols[i++]); this.highPrice = StringUtil.parseInt(cols[i++]); this.lowPrice = StringUtil.parseInt(cols[i++]); this.closePrice = StringUtil.parseInt(cols[i++]); i++; this.flag = 1; } /** * ใ‚ณใƒณใ‚นใƒˆใƒฉใ‚ฏใ‚ฟ๏ผˆPUSH APIใงๅ—ไฟกใ—ใŸใƒใƒฃใƒผใƒˆใƒ‡ใƒผใ‚ฟ๏ผ‰ใ€‚ * * @param date ๆ™‚้–“่ถณใฎๅ ดๅˆใฏๆ—ฅๆ™‚ใ€‚ๆ—ฅ่ถณใฎๅ ดๅˆใฏๆ—ฅไป˜ใ€‚ * @param price ็พๅ€คใ€‚ */ public ChartInfo(String date, int price) { this.date = date; this.openPrice = price; this.highPrice = price; this.lowPrice = price; this.closePrice = price; this.flag = 2; } /** * ใƒžใƒผใ‚ธใ—ใŸใƒใƒฃใƒผใƒˆใƒ‡ใƒผใ‚ฟใƒ•ใ‚กใ‚คใƒซใฎใƒ˜ใƒƒใƒ€ๆ–‡ๅญ—ๅˆ—ใ‚’็”Ÿๆˆใ™ใ‚‹ใ€‚ * * @return ใƒ˜ใƒƒใƒ€ๆ–‡ๅญ—ๅˆ—ใ€‚ */ public static String toHeaderString() { String[] sa = new String[6]; int i = 0; sa[i++] = "date "; sa[i++] = "open"; sa[i++] = "high"; sa[i++] = "low"; sa[i++] = "close"; sa[i++] = "flag"; String val = "# " + StringUtil.joinTab(sa); return val; } /** * ใ‚คใƒณใ‚นใ‚ฟใƒณใ‚นใฎไธปใ‚ญใƒผ(date)ใ‚’ๅ–ๅพ—ใ™ใ‚‹ใ€‚ * * @return ไธปใ‚ญใƒผใ€‚ */ public String getKey() { return date; } /** * ใƒžใƒผใ‚ธใ—ใŸใƒใƒฃใƒผใƒˆใƒ‡ใƒผใ‚ฟใƒ•ใ‚กใ‚คใƒซใฎใƒฌใ‚ณใƒผใƒ‰ๆ–‡ๅญ—ๅˆ—ใ‚’็”Ÿๆˆใ™ใ‚‹ใ€‚ * * @return ใƒฌใ‚ณใƒผใƒ‰ๆ–‡ๅญ—ๅˆ—ใ€‚ */ public String toLineString() { String[] sa = new String[6]; int i = 0; sa[i++] = date; sa[i++] = "" + openPrice; sa[i++] = "" + highPrice; sa[i++] = "" + lowPrice; sa[i++] = "" + closePrice; sa[i++] = "" + flag; String val = StringUtil.joinTab(sa); return val; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{date=").append(date); sb.append(", close=").append(closePrice); sb.append(", flag=").append(flag); sb.append("}"); return sb.toString(); } } /** * ใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒชๅใฎใƒชใ‚นใƒˆใ€‚ */ private static Set<String> nameSet; /** * ไฟๅญ˜ใ—ใŸ4ๆœฌๅ€คใƒใƒฃใƒผใƒˆใƒ‡ใƒผใ‚ฟใฎ็ต‚ๅ€คใจใ€PUSH APIใงๅ—ไฟกใ—ใŸใƒใƒฃใƒผใƒˆใƒ‡ใƒผใ‚ฟใ‚’ใƒžใƒผใ‚ธใ™ใ‚‹ใ€‚ */ public static void main(String[] args) { listChartFiles(DIR_CHARTPATH); System.out.println(nameSet); for (String name : nameSet) { new MainMergeChartData_r3(name).execute(); } } /** * ใƒใƒฃใƒผใƒˆใƒ‡ใƒผใ‚ฟใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒชๅใ‹ใ‚‰ใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒชๅใƒชใ‚นใƒˆใ‚’ไฝœๆˆใ™ใ‚‹ใ€‚ * * @param dirpath ใƒใƒฃใƒผใƒˆใƒ‡ใƒผใ‚ฟใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒชใƒ‘ใ‚นใ€‚ */ private static void listChartFiles(String dirpath) { nameSet = new TreeSet<>(); File dir = new File(dirpath); for (File f : dir.listFiles()) { if (f.isFile()) { continue; } String name = f.getName(); nameSet.add(name); } } /** * ใƒใƒฃใƒผใƒˆ๏ผค๏ผขใƒ•ใ‚กใ‚คใƒซใƒ‘ใ‚นใ€‚ */ private String dbFilePath; /** * ใƒžใƒผใ‚ธใ—ใŸใƒใƒฃใƒผใƒˆใƒ‡ใƒผใ‚ฟใ‚’ๆ™‚็ณปๅˆ—ใซไธฆในใŸใƒžใƒƒใƒ—ใ€‚ */ private Map<String, ChartInfo> chartMap = new TreeMap<>(); /** * ใƒใƒฃใƒผใƒˆใƒ‡ใƒผใ‚ฟใƒ•ใ‚กใ‚คใƒซใƒ‘ใ‚นใ€‚ */ private String csvFilePath; /** * ใƒžใƒผใ‚ธใ—ใŸใƒใƒฃใƒผใƒˆใƒ‡ใƒผใ‚ฟใƒ•ใ‚กใ‚คใƒซใƒ‘ใ‚นใ€‚ */ private String txtFilePath; /** * ใƒใƒฃใƒผใƒˆใƒ‡ใƒผใ‚ฟใƒญใƒƒใ‚ฏใ‚’็ฎก็†ใ™ใ‚‹ใ€‚ */ private FileLockLogic fileLockLogic; /** * ใ‚ณใƒณใ‚นใƒˆใƒฉใ‚ฏใ‚ฟใ€‚ * * @param name ใƒ‡ใ‚ฃใƒฌใ‚ฏใƒˆใƒชๅใ€‚ */ public MainMergeChartData_r3(String name) { String code = StringUtil.parseString(name, "_"); String dirDbPath = DIR_DBPATH + code; this.dbFilePath = dirDbPath + "/" + DB_FILENAME; String dirChartPath = DIR_CHARTPATH + name; this.csvFilePath = dirChartPath + "/" + CHART_CSV_FILENAME; this.txtFilePath = dirChartPath + "/" + CHART_TXT_FILENAME; this.fileLockLogic = new FileLockLogic(dirChartPath + "/" + LOCK_FILENAME); } /** * ไฟๅญ˜ใ—ใŸ4ๆœฌๅ€คใƒใƒฃใƒผใƒˆใƒ‡ใƒผใ‚ฟใฎ็ต‚ๅ€คใจใ€PUSH APIใงๅ—ไฟกใ—ใŸใƒใƒฃใƒผใƒˆใƒ‡ใƒผใ‚ฟใ‚’ใƒžใƒผใ‚ธใ™ใ‚‹ใ€‚ */ public void execute() { read1mChartData(); readCsvChartData(); writeChartMap(); } /** * 1ๅˆ†่ถณใฎ4ๆœฌๅ€คใƒใƒฃใƒผใƒˆ๏ผค๏ผขใƒ•ใ‚กใ‚คใƒซใ‹ใ‚‰็ต‚ๅ€คใ‚’่ชญใฟ่พผใ‚€ใ€‚ */ private void read1mChartData() { List<String> lines = FileUtil.readAllLines(dbFilePath); int readCnt = 0; for (String s : lines) { if (s.startsWith("#")) { continue; } String[] cols = StringUtil.splitComma(s); if (cols.length != ChartInfo.MAX_COLS) { System.out.println("Warning: SKIP cols.length=" + cols.length + ", line=" + s); continue; } ChartInfo ci = new ChartInfo(cols); String key = ci.getKey(); chartMap.put(key, ci); readCnt++; } System.out.println("MainMergeChartData_r3.read1mChartData(): " + dbFilePath + ", readCnt=" + readCnt); } /** * PUSH APIใงๅ—ไฟกใ—ใŸใƒใƒฃใƒผใƒˆใƒ‡ใƒผใ‚ฟใƒ•ใ‚กใ‚คใƒซใ‹ใ‚‰็พๅ€คใ‚’่ชญใฟ่พผใ‚€ใ€‚ */ private void readCsvChartData() { fileLockLogic.lockFile(); List<String> lines; try { lines = FileUtil.readAllLines(csvFilePath); } finally { fileLockLogic.unlockFile(); } int readCnt = 0; for (String s : lines) { if (s.startsWith("#")) { continue; } String[] cols = StringUtil.splitComma(s); if (cols.length < 2) { System.out.println("Warning: SKIP cols.length=" + cols.length + ", line=" + s); continue; } String datetime = cols[0]; int price = (int) StringUtil.parseDouble(cols[1]); String date = datetime.substring(0, 10).replaceAll("-", "/"); String time = datetime.substring(11); String startTime = ChartTime1mLogic.search(time); if (startTime == null) { continue; } String key = date + " " + startTime; ChartInfo ci = chartMap.get(key); if (ci == null) { ci = new ChartInfo(key, price); chartMap.put(key, ci); readCnt++; } else { // 4ๆœฌๅ€คใฏ็ขบๅฎšๅ€คใชใฎใงไธŠๆ›ธใใ—ใชใ„ if (ci.flag != 1) { // ้ซ˜ๅ€คใŒๆ›ดๆ–ฐใ•ใ‚ŒใŸๅ ดๅˆใฎใฟไธŠๆ›ธใใ™ใ‚‹ if (ci.highPrice < price) { ci.highPrice = price; } // ๅฎ‰ๅ€คใŒๆ›ดๆ–ฐใ•ใ‚ŒใŸๅ ดๅˆใฎใฟไธŠๆ›ธใใ™ใ‚‹ if (ci.lowPrice > price) { ci.lowPrice = price; } // PUSH APIใฎใƒ‡ใƒผใ‚ฟใฏใ€ๆ™‚็ณปๅˆ—ใซใ‚ฝใƒผใƒˆใ•ใ‚Œใฆใ„ใ‚‹ๅ‰ๆใงใ€ๅธธใซๆ–ฐใ—ใ„็พๅ€คใงไธŠๆ›ธใใ™ใ‚‹ ci.closePrice = price; readCnt++; } } } System.out.println("MainMergeChartData_r3.readCsvChartData(): " + csvFilePath + ", readCnt=" + readCnt); } /** * ใƒžใƒผใ‚ธใ—ใŸใƒใƒฃใƒผใƒˆใƒ‡ใƒผใ‚ฟใƒ•ใ‚กใ‚คใƒซใ‚’ๆ›ธใ่พผใ‚€ใ€‚ */ private void writeChartMap() { List<String> lines = new ArrayList<>(); lines.add(ChartInfo.toHeaderString()); System.out.println("MainMergeChartData_r3.writeChartMap(): " + txtFilePath + ", chartMap.size=" + chartMap.size()); for (String key : chartMap.keySet()) { ChartInfo ci = chartMap.get(key); lines.add(ci.toLineString()); } FileUtil.writeAllLines(txtFilePath, lines); } }
22.954802
118
0.599311
8e979758954a05496cb0bfa5503306019a3837e1
1,913
/** * ่ฏทๅ‹ฟๅฐ†ไฟฑไน้ƒจไธ“ไบซ่ต„ๆบๅคๅˆถ็ป™ๅ…ถไป–ไบบ๏ผŒไฟๆŠค็Ÿฅ่ฏ†ไบงๆƒๅณๆ˜ฏไฟๆŠคๆˆ‘ไปฌๆ‰€ๅœจ็š„่กŒไธš๏ผŒ่ฟ›่€ŒไฟๆŠคๆˆ‘ไปฌ่‡ชๅทฑ็š„ๅˆฉ็›Š * ๅณไพฟๆ˜ฏๅ…ฌๅธ็š„ๅŒไบ‹๏ผŒไนŸ่ฏทๅฐŠ้‡ JFinal ไฝœ่€…็š„ๅŠชๅŠ›ไธŽไป˜ๅ‡บ๏ผŒไธ่ฆๅคๅˆถ็ป™ๅŒไบ‹ * * ๅฆ‚ๆžœไฝ ๅฐšๆœชๅŠ ๅ…ฅไฟฑไน้ƒจ๏ผŒ่ฏท็ซ‹ๅณๅˆ ้™ค่ฏฅ้กน็›ฎ๏ผŒๆˆ–่€…็ŽฐๅœจๅŠ ๅ…ฅไฟฑไน้ƒจ๏ผšhttp://jfinal.com/club * * ไฟฑไน้ƒจๅฐ†ๆไพ› jfinal-club ้กน็›ฎๆ–‡ๆกฃไธŽ่ฎพ่ฎก่ต„ๆบใ€ไธ“็”จ QQ ็พค๏ผŒไปฅๅŠไฝœ่€…ๅœจไฟฑไน้ƒจๅฎšๆœŸ็š„ๅˆ†ไบซไธŽ็ญ”็–‘๏ผŒ * ไปทๅ€ผ่ฟœๆฏ”ไป…ไป…ๆ‹ฅๆœ‰ jfinal club ้กน็›ฎๆบไปฃ็ ่ฆๅคงๅพ—ๅคš * * JFinal ไฟฑไน้ƒจๆ˜ฏไบ”ๅนดไปฅๆฅ้ฆ–ๆฌกๅฏปๆฑ‚ๅค–้ƒจ่ต„ๆบ็š„ๅฐ่ฏ•๏ผŒไปฅไพฟไบŽๆœ‰่ต„ๆบๅˆ›ๅปบๆ›ดๅŠ  * ้ซ˜ๅ“่ดจ็š„ไบงๅ“ไธŽๆœๅŠก๏ผŒไธบๅคงๅฎถๅธฆๆฅๆ›ดๅคง็š„ไปทๅ€ผ๏ผŒๆ‰€ไปฅ่ฏทๅคงๅฎถๅคšๅคšๆ”ฏๆŒ๏ผŒไธ่ฆๅฐ† * ้ฆ–ๆฌก็š„ๅฐ่ฏ•ๆ‰ผๆ€ๅœจไบ†ๆ‘‡็ฏฎไน‹ไธญ */ package com.cser.play.common; import com.cser.play.apply.ApplyController; import com.cser.play.common.upload.UploadController; import com.cser.play.company.CompanyController; import com.cser.play.deal.DealRecordController; import com.cser.play.gift.GiftController; import com.cser.play.login.LoginController; import com.cser.play.message.NoticeController; import com.cser.play.order.OrderController; import com.cser.play.pay.PayController; import com.cser.play.product.ProductController; import com.cser.play.qr.QrCodeController; import com.cser.play.reg.RegController; import com.cser.play.sign.SignInController; import com.cser.play.suggest.SuggestController; import com.cser.play.task.TaskController; import com.cser.play.user.UserInfoController; import com.jfinal.config.Routes; /** * ๅ‰ๅฐ่ทฏ็”ฑ * * @author res * */ public class FrontRoutes extends Routes { @Override public void config() { add("/user", UserInfoController.class); add("/sign", SignInController.class); add("/gift", GiftController.class); add("/task", TaskController.class); add("/deal", DealRecordController.class); add("/company", CompanyController.class); add("/login", LoginController.class); add("/reg", RegController.class); add("/upload", UploadController.class); add("/qrcode", QrCodeController.class); add("/apply", ApplyController.class); add("/product", ProductController.class); add("/order", OrderController.class); add("/notice", NoticeController.class); add("/pay", PayController.class); add("/suggest",SuggestController.class); } }
30.365079
57
0.764767
70159260a1354739c2ed1dbd16b8cda80c54452e
605
package com.ishland.c2me.common.optimization.worldgen.global_biome_cache; import net.minecraft.util.math.ChunkSectionPos; import net.minecraft.util.registry.RegistryEntry; import net.minecraft.world.biome.Biome; import net.minecraft.world.biome.source.util.MultiNoiseUtil; public interface IGlobalBiomeCache { RegistryEntry<Biome>[][][] preloadBiomes(ChunkSectionPos pos, RegistryEntry<Biome>[][][] def, MultiNoiseUtil.MultiNoiseSampler multiNoiseSampler); RegistryEntry<Biome> getBiomeForNoiseGenFast(int biomeX, int biomeY, int biomeZ, MultiNoiseUtil.MultiNoiseSampler multiNoiseSampler); }
43.214286
150
0.826446
6fdf5682dd163da2f3bcdcae41711998fb9064b6
2,084
package com.training.restapi.controller; import static org.junit.Assert.fail; import java.util.Objects; import org.json.JSONException; import org.junit.Test; import org.junit.runner.RunWith; import org.skyscreamer.jsonassert.JSONAssert; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class JukeboxSettingsControllerTests { private static final String MODEL = "model5"; private static final String SETTINGS_ID = "09809898as8908a0ds9f890adf"; private static final String OFFSET = "0"; private static final String LIMIT = "10"; private static final String JUKEBOXLISTPATH = "/jukeboxlist"; private static final String LOCALHOST = "http://localhost:"; @LocalServerPort private int port; @Autowired private TestRestTemplate restTemplate; @Test public void testGetJukeboxList() { String body = restTemplate .getForObject(createURLWithPort(JUKEBOXLISTPATH, SETTINGS_ID, MODEL, OFFSET, LIMIT), String.class); String expResult = "[{\"id\":\"09809898as8908a0ds9f890adf\",\"model\":\"model5\",\"components\":[{\"name\":\"Name\"}]}]"; try { JSONAssert.assertEquals(expResult, body, false); } catch (JSONException e) { fail(e.getMessage()); } } //create an url to compare with the result of the test private String createURLWithPort(String... parameters) { StringBuilder sb = new StringBuilder(1024); sb.append(LOCALHOST); sb.append(port); if (Objects.nonNull(parameters)) { for (String parameter : parameters) { sb.append("/").append(parameter); } } return sb.toString(); } }
35.931034
129
0.698656
3f8fccbfac2e71992ceada0b5bdbf13ff8733c35
17,292
/* * Copyright 2010-2021 Australian Signals Directorate * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package au.gov.asd.tac.constellation.utilities.graphics; import java.util.Arrays; import org.testng.annotations.Test; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; import org.testng.annotations.BeforeClass; /** * @author groombridge34a */ public class MathdNGTest { private static final double D1 = 1.23D; private static final double D2 = 3.21D; private static final double D3 = 4.56D; private static final double D4 = 6.54D; private static final double D5 = 7.89D; private static final double D6 = 9.87D; private static final double D7 = 1.91D; private static final double D8 = 8.28D; private static final double D9 = 3.73D; private static final double D10 = 10.11D; private static final double D11 = 20.22D; private static final double D12 = 30.33D; private static final double D13 = 40.44D; private static final double D14 = 50.55D; private static final double D15 = 60.66D; private static final double D16 = 70.77D; private static final double D17 = 80.88D; private static final double D18 = 90.99D; private static final Matrix44d M1 = new Matrix44d(); private static final Matrix44d M2 = new Matrix44d(); private static final double[] M1_R1 = {1.01D, 1.02D, 1.03D, 1.04D}; private static final double[] M1_R2 = {2.01D, 2.02D, 2.03D, 2.04D}; private static final double[] M1_R3 = {3.01D, 3.02D, 3.03D, 3.04D}; private static final double[] M1_R4 = {4.01D, 4.02D, 4.03D, 4.04D}; private static final double[] M2_R1 = {65.679F, 56.648F, 13.849F, 13.444F}; private static final double[] M2_R2 = {96.743F, 26.754F, 78.915F, 49.802F}; private static final double[] M2_R3 = {46.065F, 74.118F, 50.392F, 7.753F}; private static final double[] M2_R4 = {34.086F, 11.219F, 86.116F, 15.307F}; private static final Matrix33d M3 = new Matrix33d(); private static final Matrix33d M4 = new Matrix33d(); private static final double[] M3_R1 = {5.05D, 8.08D, 12.13D}; private static final double[] M3_R2 = {6.06D, 9.09D, 14.15D}; private static final double[] M3_R3 = {7.07D, 10.11D, 16.17D}; private static final double[] M4_R1 = {54.568D, 45.537D, 2.738D, 2.333D}; private static final double[] M4_R2 = {85.632D, 15.643D, 67.804D, 38.791D}; private static final double[] M4_R3 = {35.942D, 63.007D, 49.281D, 6.642D}; @BeforeClass public void before() { M1.setA(new double[] { M1_R1[0], M1_R1[1], M1_R1[2], M1_R1[3], M1_R2[0], M1_R2[1], M1_R2[2], M1_R2[3], M1_R3[0], M1_R3[1], M1_R3[2], M1_R3[3], M1_R4[0], M1_R4[1], M1_R4[2], M1_R4[3]}); M2.setA(new double[] { M2_R1[0], M2_R1[1], M2_R1[2], M2_R1[3], M2_R2[0], M2_R2[1], M2_R2[2], M2_R2[3], M2_R3[0], M2_R3[1], M2_R3[2], M2_R3[3], M2_R4[0], M2_R4[1], M2_R4[2], M2_R4[3]}); M3.setA(new double[] { M3_R1[0], M3_R1[1], M3_R1[2], M3_R2[0], M3_R2[1], M3_R2[2], M3_R3[0], M3_R3[1], M3_R3[2]}); M4.setA(new double[] { M4_R1[0], M4_R1[1], M4_R1[2], M4_R2[0], M4_R2[1], M4_R2[2], M4_R3[0], M4_R3[1], M4_R3[2]}); } // convenience method to get a copy of a 4x4 matrix, as it's clunky private Matrix44d copyMatrix(final Matrix44d m) { final Matrix44d ret = new Matrix44d(); ret.setA(Arrays.copyOf(m.getA(), m.getA().length)); return ret; } // convenience method to get a copy of a 3x3 matrix, as it's clunky private Matrix33d copyMatrix(final Matrix33d m) { final Matrix33d ret = new Matrix33d(); ret.setA(Arrays.copyOf(m.getA(), m.getA().length)); return ret; } /** * Can add two 3d vectors. */ @Test public void testAdd() { final Vector3d result = new Vector3d(); Mathd.add(result, new Vector3d(D1, D2, D3), new Vector3d(D4, D5, D6)); assertEquals(result.a, new double[] {7.77D, 11.1D, 14.43D}); } /** * Can subtract two 3d vectors. */ @Test public void testSubtract() { final Vector3d result = new Vector3d(); Mathd.subtract(result, new Vector3d(D4, D5, D6), new Vector3d(D1, D2, D3)); assertEquals(result.a, new double[] {5.3100000000000005D, 4.68D, 5.31D}); } /** * Can get the cross product of two 3d vectors. */ @Test public void testCrossProduct() { final Vector3d result = new Vector3d(); Mathd.crossProduct(result, new Vector3d(D1, D2, D3), new Vector3d(D4, D5, D6)); assertEquals(result.a, new double[] { -4.2956999999999965D, 17.682299999999998D, -11.288700000000002D}); } /** * Can get the dot product of two 3d vectors. */ @Test public void testDotProduct() { assertEquals( Mathd.dotProduct(new Vector3d(D1, D2, D3), new Vector3d(D4, D5, D6)), 78.3783D); } /** * Can get the angle between two 3d vectors. */ @Test public void testGetAngleBetweenVectors() { final double d = Mathd.getAngleBetweenVectors( new Vector3d(0.12D, 0.34D, 0.56D), new Vector3d(0.78D, 0.99D, 1.01D)); assertEquals(d, 0.0916836222806647D); } /** * Can get the square of the distance between two points. */ @Test public void testDistanceSquared() { assertEquals(Mathd.distanceSquared( new Vector3d(D1, D2, D3), new Vector3d(D4, D5, D6)), 78.2946D); } /** * Can get the distance between two points. */ @Test public void testDistance() { assertEquals(Mathd.getDistance( new Vector3d(D1, D2, D3), new Vector3d(D4, D5, D6)), 8.848423588413928D); } /** * Can multiply two 4x4 matrices. */ @Test public void testMatrixMultiply44() { final Matrix44d m = new Matrix44d(); Mathd.matrixMultiply(m, copyMatrix(M1), copyMatrix(M2)); assertEquals(m.getA(), new double[] { 275.7941993808746D, 277.2903993797302D, 278.78659937858583D, 280.2827993774414D, 588.7261308860778D, 591.2482708358764D, 593.770410785675D, 596.2925507354737D, 378.27226499080655D, 380.05554491996764D, 381.8388248491287D, 383.6221047782898D, 377.5672708034515D, 379.03455076217654D, 380.50183072090147D, 381.9691106796265D}); } /** * Can multiply two 3x3 matrices. */ @Test public void testMatrixMultiply33() { final Matrix33d m = new Matrix33d(); Mathd.matrixMultiply(m, copyMatrix(M3), copyMatrix(M4)); assertEquals(m.getA(), new double[] { 570.88028D, 882.5219500000001D, 1350.53185D, 1006.61246D, 1519.59987D, 2356.4552900000003D, 911.7461900000001D, 1361.3759D, 2124.39928D}); } /** * Can transform a 3d vector. */ @Test public void testTransformVector3() { final Vector3d result = new Vector3d(); Mathd.transformVector(result, new Vector3d(D1, D2, D3), copyMatrix(M1)); assertEquals(result.a, new double[] { 25.43D, 25.529999999999998D, 25.629999999999995D}); } /** * Can transform a 4d vector. */ @Test public void testTransformVector4() { final Vector4d result = new Vector4d(); final Vector4d v = new Vector4d(); v.set(D1, D2, D3, D4); Mathd.transformVector(result, v, copyMatrix(M2)); assertEquals(result.getA(), new double[] { 824.3090130615234D, 566.9076994514465D, 1063.337557554245D, 311.86199438095093D}); } /** * Can transform a 3d vector. */ @Test public void testRotateVector3() { final Vector3d result = new Vector3d(); Mathd.rotateVector(result, new Vector3d(D1, D2, D3), copyMatrix(M3)); assertEquals(result.a, new double[] { 57.903299999999994D, 85.21889999999999D, 134.0766D}); } /** * Can make a 3x3 scaling matrix. */ @Test public void testMakeScalingMatrix33() { // using the doubles method final Matrix33d m1 = copyMatrix(M3); Mathd.makeScalingMatrix(m1, D1, D2, D3); assertEquals(m1.getA(), new double[] { D1, 0F, 0F, 0F, D2, 0F, 0F, 0F, D3}); // using the vector method final Matrix33d m2 = copyMatrix(M4); Mathd.makeScalingMatrix(m2, new Vector3d(D4, D5, D6)); assertEquals(m2.getA(), new double[] { D4, 0F, 0F, 0F, D5, 0F, 0F, 0F, D6}); } /** * Can make a 4x4 scaling matrix. */ @Test public void testMakeScalingMatrix44() { // using the doubles method final Matrix44d m1 = copyMatrix(M1); Mathd.makeScalingMatrix(m1, D7, D8, D9); assertEquals(m1.getA(), new double[] { D7, 0F, 0F, 0F, 0F, D8, 0F, 0F, 0F, 0F, D9, 0F, 0F, 0F, 0F, 1F}); // using the vector method final Matrix44d m2 = copyMatrix(M2); Mathd.makeScalingMatrix(m2, new Vector3d(D10, D11, D12)); assertEquals(m2.getA(), new double[] { D10, 0F, 0F, 0F, 0F, D11, 0F, 0F, 0F, 0F, D12, 0F, 0F, 0F, 0F, 1F}); } /** * Can make a 3x3 rotation matrix. */ @Test public void testMakeRotationMatrix33() { final Matrix33d m1 = copyMatrix(M3); final Matrix33d identity33 = new Matrix33d(); identity33.identity(); // identity matrix is returned if the magnitude is zero Mathd.makeRotationMatrix(m1, 0D, 0D, 0D, 0D); assertEquals(m1.getA(), identity33.getA()); // successfully made into a rotation matrix final Matrix33d m2 = copyMatrix(M4); Mathd.makeRotationMatrix(m2, D1, D2, D3, D4); assertEquals(m2.getA(), new double[] { 0.4271055495613798D, 0.8490941209819682D, -0.3108376155611322D, -0.5852453544323359D, 0.5216443276644285D, 0.6207858491709487D, 0.6892522939020523D, -0.0832248107801089D, 0.719725577023197D}); } /** * Can make a 4x4 rotation matrix. */ @Test public void testMakeRotationMatrix44() { final Matrix44d m1 = copyMatrix(M1); final Matrix44d identity44 = new Matrix44d(); identity44.identity(); // identity matrix is returned if the magnitude is zero Mathd.makeRotationMatrix(m1, 0D, 0D, 0D, 0D); assertEquals(m1.getA(), identity44.getA()); // successfully made into a rotation matrix final Matrix44d m2 = copyMatrix(M2); Mathd.makeRotationMatrix(m2, D5, D6, D7, D8); assertEquals(m2.getA(), new double[] { 0.5589836199169947D, 0.7504799679705509D, 0.35258634451636583D, 0.0D, -0.520198525374364D, -0.013729040864614989D, 0.8539350137072931D, 0.0D, 0.6457017940681519D, -0.6607505816205222D, 0.3827242637007897D, 0.0D, 0.0D, 0.0D, 0.0D, 1.0D}); } /** * Can make a 4x4 translation matrix. */ @Test public void testMakeTranslationMatrix() { final Matrix44d m = copyMatrix(M1); Mathd.makeTranslationMatrix(m, D1, D2, D3); assertEquals(m.getA(), new double[] { 1D, 0D, 0D, 0D, 0D, 1D, 0D, 0D, 0D, 0D, 1D, 0D, D1, D2, D3, 1D}); } /** * Can invert a 4x4 matrix. */ @Test public void testInvert() { final Matrix44d m = new Matrix44d(); Mathd.invertMatrix(m, copyMatrix(M2)); assertEquals(m.getA(), new double[] { 0.051592217523495354D, -0.01710738552898974D, -0.037714071542736975D, 0.02944883916107982D, -0.021455704776316496D, 0.007608652064829005D, 0.030366860010860388D, -0.021291554933531992D, -0.0025899242357718213D, -0.004133664641347953D, 0.0011821506051511632D, 0.015125007187779248D, -0.08459049976527729D, 0.05577418800733334D, 0.055075057287938094D, -0.0697346445301143D}); } /** * Unable to invert a 4x4 matrix because the 4x4 determinant is zero. */ @Test public void testUnableInvert() { final Matrix44d m = new Matrix44d(); Mathd.invertMatrix(m, new Matrix44d()); for (double d : m.getA()) { assertEquals(d, Double.NaN); } } /** * Can get the distance a point is from a plane. */ @Test public void testGetDistanceToPlane() { final Vector4d plane = new Vector4d(); plane.set(D4, D5, D6, D7); assertEquals(Mathd.getDistanceToPlane(new Vector3d(D3, D2, D1), plane), 69.1994D); } /** * Can get the plane equation from three points. */ @Test public void testGetPlaneEquation() { final Vector4d planeEq = new Vector4d(); Mathd.getPlaneEquation(planeEq, new Vector3d(D3, D2, D1), new Vector3d(D4, D5, D6), new Vector3d(D12, D10, D11)); assertEquals(planeEq.getA(), new double[] { -0.1356231359237909D, -0.8578200895113308D, 0.4957328504678396D, 2.762292581068417D}); } /** * Can test the distance of a ray to the center of a sphere. */ @Test public void testRaySphereTest() { // calculated distance to intersection is positive assertEquals(Mathd.raySphereTest(new Vector3d(D1, D2, D3), new Vector3d(D4, D5, D6), new Vector3d(D7, D8, D9), 200D), -197.4008032677102D); // calculated distance to intersection is negative assertEquals(Mathd.raySphereTest(new Vector3d(-1000D, -1000D, -1000D), new Vector3d(D4, D5, D6), new Vector3d(D7, D8, D9), 200D), -43484.95313337911D); } /** * Can perform a three dimensional Catmull-Rom "spline" interpolation * between p1 and p2. */ @Test public void testCatmullRom() { final double[] vOut = new double[3]; Mathd.catmullRom(vOut, new double[] {D1, D12, D2}, new double[] {D11, D3, D10}, new double[] {D4, D9, D5}, new double[] {D8, D6, D7}, 0.432D); assertEquals(vOut, new double[] {15.76962848256D, 2.09403313152D, 9.98578804224D}); } /** * Can check if two doubles are within an error range. */ @Test public void testCompareDoubles() { // difference between doubles is under the error tolerance assertTrue(Mathd.closeEnough(D2, D1, 1.99D)); // difference between doubles is over the error tolerance assertFalse(Mathd.closeEnough(D5, D3, 3.33D)); } /** * Can calculate the next "smooth" step for a point to take between two * other points. */ @Test public void testSmoothStep() { // The decision points hinge on the result of the formula // (x - edge1) / (edge2 - edge1) // result is greater than 1 assertEquals(Mathd.m3dSmoothStep(D1, D2, D17), 1D); // result is less than 1 assertEquals(Mathd.m3dSmoothStep(D2, D1, D3), 0D); // formula result is in between 0 and 1 assertEquals(Mathd.m3dSmoothStep(D1, D18, D9), 0.0022839983390191836D); } /** * Can get a planar shadow matrix. */ @Test public void testMakePlanarShadowMatrix() { final double[] proj = new double[16]; Mathd.m3dMakePlanarShadowMatrix(proj, new double[] {D10, D3, D9, D4}, new double[] {D8, D5, D7}); assertEquals(proj, new double[] { -43.10269999999999D, 79.7679D, 19.3101D, 0D, 37.75679999999999D, -90.8351D, 8.709599999999998D, 0D, 30.884399999999996D, 29.4297D, -119.68919999999999D, 0D, 54.151199999999996D, 51.6006D, 12.491399999999999D, -126.81349999999999D }); } /** * Can determine the point on a ray closest to another given point in space. */ @Test public void testClosestPointOnRay() { assertEquals(Mathd.closestPointOnRay(new Vector3d(D9, D1, D13), new Vector3d(D10, D2, D14), new Vector3d(D11, D3, D15), new Vector3d(D12, D4, D16)), 1.118990511176196E10D); } }
35.950104
108
0.595131
57862e8108c4d72131516bc072e8666e6fa963e9
2,263
package com.ezwel.htl.interfaces.commons.thread; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ezwel.htl.interfaces.commons.annotation.APIType; import com.ezwel.htl.interfaces.commons.constants.OperateConstants; import com.ezwel.htl.interfaces.commons.exception.APIException; /** * <pre> * ์ฃผ์–ด์ง„ ๊ฐœ์ˆ˜๋งŒํผ์˜ ์“ฐ๋ ˆ๋“œ๋ฅผ ๊ฐ–๋Š” ์“ฐ๋ ˆ๋“œํ’€์„ ์ƒ์„ฑํ•˜๊ณ  * ์ƒ์„ฑํ•œ ์“ฐ๋ ˆ๋“œํ’€์— ๊ฐ ์“ฐ๋ ˆ๋“œ๋ณ„ ์‹คํ–‰ํ•  Callable.call์„ ๋“ฑ๋กํ•˜์—ฌ * ๋“ฑ๋ก๋œ ๊ฐœ์ˆ˜ ๋งŒํผ ์“ฐ๋ ˆ๋“œ๋ณ„ ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•˜๋Š” CallableExecutor * </pre> * @author [email protected] * @date 2018. 11. 8. * @serviceType API */ @APIType(description="๋ฉˆํ‹ฐ์“ฐ๋ ˆ๋“œ ํ’€ ์ƒ์„ฑ ๋ฐ ์‹คํ–‰ ์œ ํ‹ธ") public class CallableExecutor { private static final Logger logger = LoggerFactory.getLogger(CallableExecutor.class); private ExecutorService executor; private List<Future<?>> result; public void initThreadPool() { initThreadPool(0); } public void initThreadPool(int poolCount) { if(executor != null) { this.clear(); } if(poolCount < 1) { executor = Executors.newCachedThreadPool(); //ํƒœ์Šคํฌ์˜ ์ˆซ์ž์— ๋”ฐ๋ผ ์“ฐ๋ ˆ๋“œ์˜ ์ˆซ์ž๊ฐ€ ๊ฐ€๋ณ€๋จ (์“ฐ๋ ˆ๋“œ์ˆซ์ž๋ฅผ์ง€์ •ํ• ํ•„์š”์—†์Œ) } else { executor = Executors.newFixedThreadPool(poolCount); } result = new ArrayList<Future<?>>(); } public <T> Future<T> call(Callable<T> task, Long sleepMillis) { Future<T> future = null; try { future = executor.submit(task); if(sleepMillis != null && sleepMillis > OperateConstants.LONG_ZERO_VALUE) { Thread.sleep(sleepMillis); } } catch (InterruptedException e) { logger.error("[CallableExecutor Call]", e); } catch (Exception e) { logger.error("[CallableExecutor Call]", e); } return future; } public boolean addCall(Callable<?> task) { return addCall(task, null); } public boolean addCall(Callable<?> task, Long sleepMillis) { return addResult(call(task, sleepMillis)); } public boolean addResult(Future<?> in){ return result.add(in); } public List<Future<?>> getResult() { return result; } public void clear(){ if(result != null) { result.clear(); } if(executor != null && !executor.isShutdown()) { executor.shutdown(); } } }
23.821053
89
0.707026
d0ed0f604b64e8ab2bb88166123e3545dc16a73f
972
package ua.training.cruise_company_servlet.controller.command; import ua.training.cruise_company_servlet.controller.constant.AttributesConstants; import ua.training.cruise_company_servlet.controller.constant.PathConstants; import ua.training.cruise_company_servlet.model.service.ExcursionService; import javax.servlet.http.HttpServletRequest; public class TravelAgentDeleteExcursionCommand implements Command { private final ExcursionService excursionService = new ExcursionService(); @Override public String execute(HttpServletRequest request) { Long excursionId = Long.valueOf(request.getParameter(AttributesConstants.EXCURSION_ID)); String param; if( excursionService.deleteExcursion(excursionId)){ param = "?deleted=true"; } else { param = "?deleted=false"; } return "redirect:" + PathConstants.SERVLET_PATH + PathConstants.TRAVEL_AGENT_MANAGE_EXCURSIONS_COMMAND + param; } }
40.5
119
0.766461
3b685c19e76ac1ff48e3e5ec31073dfe3fb555f7
893
package org.robobinding.viewattribute; import java.util.Map; import org.robobinding.util.SearchableClasses; import com.google.common.collect.Maps; /** * * @since 1.0 * @version $Revision: 1.0 $ * @author Cheng Wei */ public class ViewListenersMap { private final Map<Class<?>, Class<? extends ViewListeners>> mappings; private final SearchableClasses searchableViewClasses; public ViewListenersMap(Map<Class<?>, Class<? extends ViewListeners>> mappings) { this.mappings = Maps.newHashMap(mappings); searchableViewClasses = new SearchableClasses(mappings.keySet()); } public Class<? extends ViewListeners> findMostSuitable(Class<?> viewClass) { Class<?> foundViewClass = searchableViewClasses.findNearestAssignableFrom(viewClass); if (foundViewClass == null) { return null; } else { return mappings.get(foundViewClass); } } }
27.060606
88
0.721165
fdf70aaaff1abe9c9d4d2407091f49bb20f95fac
1,480
package fdiscovery.approach.equivalence; import fdiscovery.general.ColumnFile; import fdiscovery.general.ColumnFiles; import java.util.ArrayList; import fdiscovery.preprocessing.SVFileProcessor; public class EquivalenceManagedFileBasedPartitions extends ArrayList<EquivalenceManagedFileBasedPartition> { private static final long serialVersionUID = -7785660771108809119L; public EquivalenceManagedFileBasedPartitions(SVFileProcessor fileProcessor) { int numberOfColumns = fileProcessor.getNumberOfColumns(); int numberOfRows = fileProcessor.getNumberOfRows(); int columnIndex = 0; for (ColumnFile columnFile : fileProcessor.getColumnFiles()) { this.add(new EquivalenceManagedFileBasedPartition(columnIndex++, numberOfColumns, numberOfRows, columnFile)); } } public EquivalenceManagedFileBasedPartitions(ColumnFiles columnFiles, int numberOfRows) { int numberOfColumns = columnFiles.getNumberOfColumns(); int columnIndex = 0; for (ColumnFile columnFile : columnFiles) { this.add(new EquivalenceManagedFileBasedPartition(columnIndex++, numberOfColumns, numberOfRows, columnFile)); } } @Override public String toString() { String output = new String(); output += "BEG FileBasedPartitions\n"; for (EquivalenceManagedFileBasedPartition partition : this) { output += partition.toString(); output += "\n"; } output += "END FileBasedPartitions\n"; return output; } }
31.489362
114
0.757432
61dcd03b13fb630592076d3902e791e977d89d77
3,024
package cn.xl.network.http; import android.support.annotation.NonNull; import android.util.Log; import java.io.File; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import okhttp3.MediaType; import okhttp3.RequestBody; public class Request<T> { @NonNull public String path; public Map<String, String> headers = new HashMap<>(); public Map<String, String> params; public Map<String, RequestBody> files; public T jsonParams; public static Request create(String path) { return new Request<Object>(path, false, false, null); } public static Request paramRequest(String path) { return new Request<Object>(path, true, false, null); } public static Request fileRequest(String path) { return new Request<Object>(path, false, true, null); } public static <E> Request<E> jsonRequest(String path, E params) { return new Request<>(path, false, false, params); } private Request(@NonNull String path, boolean hasParams, boolean hasFile, T paramsBean) { this.path = path; if (hasParams) { params = new HashMap<>(); } else { params = Collections.emptyMap(); } if (hasFile) { files = new LinkedHashMap<>(); } else { files = Collections.emptyMap(); } jsonParams = paramsBean; } public Request addHeader(String name, Object value) { headers.put(name, String.valueOf(value)); return this; } public Request addParam(String key, Object value) { if (params == Collections.EMPTY_MAP) { Log.i("xxx", "EMPTY_MAP"); return this; } params.put(key, String.valueOf(value)); return this; } public Request addText(String key, String text) { RequestBody requestBody = RequestBody.create(MediaType.parse("text/*"), text); files.put(key, requestBody); return this; } public Request addFilePath(String key, String filePath) { File file = new File(filePath); addFile(key, file); return this; } public Request addFile(String key, File file) { if (file == null || !file.exists()) { Log.e("xxx", "addFile: file not exist"); return this; } String name = String.format("%s\"; filename=\"%s", key, file.getName()); RequestBody requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file); files.put(name, requestBody); return this; } public void addFilePaths(String key, List<String> filePathList) { File file; for (String filePath : filePathList) { file = new File(filePath); addFile(key, file); } } public void addFiles(String key, List<File> fileList) { for (File file : fileList) { addFile(key, file); } } }
28
99
0.60582
e01b80f6d4d76bb7c1839812cc6c6f11db04d861
2,386
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.msmq.native_support; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public class NativeLibraryLoader { public static void loadLibrary(String libname) throws IOException { String actualLibName = System.mapLibraryName(libname); File lib = extractResource(actualLibName); System.load(lib.getAbsolutePath()); } static File extractResource(String resourcename) throws IOException { InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(resourcename); if(in == null) throw new IOException("Unable to find library "+resourcename+" on classpath"); File tmpDir = new File(System.getProperty("java.tmpdir","tmplib")); if (!tmpDir.exists() ) { if( !tmpDir.mkdirs()) throw new IOException("Unable to create JNI library working directory "+tmpDir); } File outfile = new File(tmpDir,resourcename); OutputStream out = new FileOutputStream(outfile); copy(in,out); out.close(); in.close(); return outfile; } static void copy(InputStream in, OutputStream out) throws IOException { byte[] tmp = new byte[8192]; int len = 0; while (true) { len = in.read(tmp); if (len <= 0) { break; } out.write(tmp, 0, len); } } }
37.873016
104
0.656329
f70fb372d269fef73e96e0015235584fb0ae1eaf
820
package io.github.evilarceus.xero.common.item; import io.github.evilarceus.xero.common.reference.Reference; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; public class ItemWrapper extends Item { public ItemWrapper() { super(); } @Override public String getUnlocalizedName() { return String.format("item.%s%s", Reference.MODID + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName())); } public String getUnlocalizedName(ItemStack itemStack) { return String.format("item.%s%s", Reference.MODID + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName())); } protected String getUnwrappedUnlocalizedName(String unlocalizedName) { return unlocalizedName.substring(unlocalizedName.indexOf(".") + 1); } }
28.275862
122
0.708537
0c21e8636471e88cef09eca92b4ac754b86bdcf8
1,022
package be.ugent.rml.termgenerator; import be.ugent.rml.functions.FunctionUtils; import be.ugent.rml.functions.SingleRecordFunctionExecutor; import be.ugent.rml.records.Record; import be.ugent.rml.term.NamedNode; import be.ugent.rml.term.Term; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class NamedNodeGenerator extends TermGenerator { public NamedNodeGenerator(SingleRecordFunctionExecutor functionExecutor) { super(functionExecutor); } @Override public List<Term> generate(Record record) throws Exception { List<String> objectStrings = new ArrayList<>(); FunctionUtils.functionObjectToList(functionExecutor.execute(record), objectStrings); ArrayList<Term> objects = new ArrayList<>(); if (objectStrings.size() > 0) { for (String object : objectStrings) { //todo check valid IRI objects.add(new NamedNode(object)); } } return objects; } }
29.2
92
0.694716
84d98760ceae64bf983b0ddc8f0479718b2dfd12
1,283
package io.gaurs.sbm.model.logical; import com.fasterxml.jackson.annotation.JsonProperty; import io.swagger.v3.oas.annotations.media.Schema; import javax.validation.constraints.NotBlank; import javax.validation.constraints.NotNull; import java.math.BigInteger; /** * The published employee record. This is different from * {@link io.gaurs.sbm.model.physical.EmployeePhysical} to abstract consumers * from internal physical models. * * @author gaurs */ @Schema public record Employee(@JsonProperty("id") @Schema(description = "employee id - unique identifier", implementation = Integer.class, name = "id", example = "101") BigInteger id, @JsonProperty("firstName") @NotNull @NotBlank @Schema(description = "employee first name", implementation = String.class, name = "firstName", required = true, example = "Sumit") String firstName, @JsonProperty("lastName") @NotNull @NotBlank @Schema(description = "employee last name", implementation = String.class, name = "lastName", required = true, example = "Gaur")String lastName, @JsonProperty("address") @NotNull @Schema(description = "employee last name", implementation = EmployeeAddress.class, name = "address", required = true) EmployeeAddress address){ }
53.458333
218
0.724084
67f68d16a3909976c592ebf6406ab919f3f5c813
11,613
package io.github.ramboxeu.techworks.common.recipe; import io.github.ramboxeu.techworks.Techworks; import io.github.ramboxeu.techworks.common.registration.TechworksItems; import io.github.ramboxeu.techworks.common.registry.IItemSupplier; import io.github.ramboxeu.techworks.common.registry.ItemRegistryObject; import io.github.ramboxeu.techworks.common.tag.TechworksItemTags; import net.minecraft.advancements.ICriterionInstance; import net.minecraft.advancements.criterion.EntityPredicate; import net.minecraft.advancements.criterion.InventoryChangeTrigger; import net.minecraft.advancements.criterion.ItemPredicate; import net.minecraft.advancements.criterion.MinMaxBounds; import net.minecraft.data.CookingRecipeBuilder; import net.minecraft.data.DataGenerator; import net.minecraft.data.IFinishedRecipe; import net.minecraft.data.RecipeProvider; import net.minecraft.item.Item; import net.minecraft.item.Items; import net.minecraft.item.crafting.Ingredient; import net.minecraft.tags.ITag; import net.minecraft.util.IItemProvider; import net.minecraft.util.ResourceLocation; import net.minecraftforge.common.Tags; import net.minecraftforge.registries.ForgeRegistries; import java.util.Arrays; import java.util.function.Consumer; public class TechworksRecipeProvider extends RecipeProvider { public TechworksRecipeProvider(DataGenerator generatorIn) { super(generatorIn); } @Override protected void registerRecipes(Consumer<IFinishedRecipe> consumer) { // Grinder dustFromIngot(consumer, TechworksItemTags.COPPER_INGOTS, TechworksItems.COPPER_DUST); dustFromIngot(consumer, TechworksItemTags.LITHIUM_INGOTS, TechworksItems.LITHIUM_DUST); dustFromIngot(consumer, Tags.Items.INGOTS_IRON, TechworksItems.IRON_DUST); dustFromIngot(consumer, Tags.Items.INGOTS_GOLD, TechworksItems.GOLD_DUST); dustFromOre(consumer, TechworksItemTags.COPPER_ORES, TechworksItems.COPPER_DUST); dustFromOre(consumer, TechworksItemTags.LITHIUM_ORES, TechworksItems.LITHIUM_DUST); dustFromOre(consumer, Tags.Items.ORES_IRON, TechworksItems.IRON_DUST); dustFromOre(consumer, Tags.Items.ORES_GOLD, TechworksItems.GOLD_DUST); crushedOre(consumer, TechworksItemTags.COPPER_ORES, TechworksItems.CRUSHED_COPPER_ORE); crushedOre(consumer, TechworksItemTags.LITHIUM_ORES, TechworksItems.CRUSHED_LITHIUM_ORE); crushedOre(consumer, Tags.Items.ORES_IRON, TechworksItems.CRUSHED_IRON_ORE); crushedOre(consumer, Tags.Items.ORES_GOLD, TechworksItems.CRUSHED_GOLD_ORE); // Smelting ingotFromOre(consumer, TechworksItemTags.COPPER_ORES, TechworksItems.COPPER_INGOT, "copper_ore"); ingotFromOre(consumer, TechworksItemTags.LITHIUM_ORES, TechworksItems.LITHIUM_INGOT, "lithium_ore"); ingotFromDust(consumer, TechworksItemTags.COPPER_DUSTS, TechworksItems.COPPER_INGOT, "copper_dust"); ingotFromDust(consumer, TechworksItemTags.LITHIUM_DUSTS, TechworksItems.LITHIUM_INGOT, "lithium_dust"); ingotFromDust(consumer, TechworksItemTags.IRON_DUSTS, Items.IRON_INGOT, "iron_dust"); ingotFromDust(consumer, TechworksItemTags.GOLD_DUSTS, Items.GOLD_INGOT, "gold_dust"); ingotFromCrushedOre(consumer, TechworksItems.CRUSHED_COPPER_ORE, TechworksItems.COPPER_INGOT); ingotFromCrushedOre(consumer, TechworksItems.CRUSHED_LITHIUM_ORE, TechworksItems.LITHIUM_INGOT); ingotFromCrushedOre(consumer, TechworksItems.CRUSHED_IRON_ORE, Items.IRON_INGOT); ingotFromCrushedOre(consumer, TechworksItems.CRUSHED_GOLD_ORE, Items.GOLD_INGOT); // Ore Washing oreWashing(consumer, TechworksItems.CRUSHED_COPPER_ORE, oreWashingResult(TechworksItems.COPPER_DUST).count(2, 3), oreWashingResult(Items.GRAVEL).count(1)); oreWashing(consumer, TechworksItems.CRUSHED_LITHIUM_ORE, oreWashingResult(TechworksItems.LITHIUM_DUST).count(2, 3), oreWashingResult(Items.GRAVEL).count(1)); oreWashing(consumer, TechworksItems.CRUSHED_IRON_ORE, oreWashingResult(TechworksItems.IRON_DUST).count(2, 3), oreWashingResult(Items.GRAVEL).count(1)); oreWashing(consumer, TechworksItems.CRUSHED_GOLD_ORE, oreWashingResult(TechworksItems.GOLD_DUST).count(2, 3), oreWashingResult(Items.GRAVEL).count(1)); // Metal Pressing plate(consumer, Tags.Items.INGOTS_IRON, TechworksItems.IRON_PLATE); gear(consumer, Tags.Items.INGOTS_IRON, TechworksItems.IRON_GEAR); // Industrial Smelting quadIngotFromOre(consumer, Tags.Items.ORES_IRON, Items.IRON_INGOT); quadIngotFromOre(consumer, Tags.Items.ORES_GOLD, Items.GOLD_INGOT); quadIngotFromOre(consumer, TechworksItemTags.COPPER_ORES, TechworksItems.COPPER_INGOT); quadIngotFromOre(consumer, TechworksItemTags.LITHIUM_ORES, TechworksItems.LITHIUM_INGOT); } @Override public String getName() { return "Recipes: techworks"; } private static void dustFromIngot(Consumer<IFinishedRecipe> consumer, ITag.INamedTag<Item> ingotTag, ItemRegistryObject<?> dust) { GrinderRecipeBuilder.grinding(ingredient(ingotTag), result(dust), 1500).build(consumer, "grinder/" + dust.getId().getPath() + "_from_ingot"); } private static void dustFromOre(Consumer<IFinishedRecipe> consumer, ITag.INamedTag<Item> oreTag, ItemRegistryObject<?> dust) { GrinderRecipeBuilder.grinding(ingredient(oreTag), result(dust), 2000).build(consumer, "grinder/" + dust.getId().getPath() + "_from_ore"); } public static void crushedOre(Consumer<IFinishedRecipe> consumer, ITag.INamedTag<Item> oreTag, ItemRegistryObject<?> crushedOre) { GrinderRecipeBuilder.oreCrushing(ingredient(oreTag), result(crushedOre, 2), 2000).build(consumer, "grinder/" + crushedOre.getId().getPath()); } public static void ingotFromDust(Consumer<IFinishedRecipe> consumer, ITag.INamedTag<Item> dustTag, ItemRegistryObject<?> ingot, String criterionItemName) { ingotFromDust(consumer, dustTag, result(ingot), criterionItemName, ingot.getId().getPath()); } public static void ingotFromDust(Consumer<IFinishedRecipe> consumer, ITag.INamedTag<Item> dustTag, Item ingot, String criterionItemName) { ingotFromDust(consumer, dustTag, () -> ingot, criterionItemName, name(ingot)); } public static void ingotFromDust(Consumer<IFinishedRecipe> consumer, ITag.INamedTag<Item> dustTag, IRecipeResult result, String criterionItemName, String name) { SmeltingRecipeBuilder.smelting(ingredient(dustTag), result, 0.35f, 1500).build(consumer, "furnace/electric/" + name + "_from_dust"); CookingRecipeBuilder.smeltingRecipe(ingredient(dustTag), result.getItem(), 0.35f, 150).addCriterion("has_" + criterionItemName, hasItem(dustTag)).build(consumer, modLoc("furnace/vanilla/" + name + "_from_dust")); CookingRecipeBuilder.blastingRecipe(ingredient(dustTag), result.getItem(), 0.35f, 75).addCriterion("has_" + criterionItemName, hasItem(dustTag)).build(consumer, modLoc("furnace/blast/" + name + "_from_dust")); } public static void ingotFromOre(Consumer<IFinishedRecipe> consumer, ITag.INamedTag<Item> oreTag, ItemRegistryObject<?> ingot, String criterionItemName) { SmeltingRecipeBuilder.smelting(ingredient(oreTag), result(ingot), 0.7f, 2000).build(consumer, "furnace/electric/" + ingot.getId().getPath() + "_from_ore"); CookingRecipeBuilder.smeltingRecipe(ingredient(oreTag), ingot.get(), 0.7f, 200).addCriterion("has_" + criterionItemName, hasItem(oreTag)).build(consumer, modLoc("furnace/vanilla/" + ingot.getId().getPath() + "_from_ore")); CookingRecipeBuilder.blastingRecipe(ingredient(oreTag), ingot.get(), 0.7f, 100).addCriterion("has_" + criterionItemName, hasItem(oreTag)).build(consumer, modLoc("furnace/blast/" + ingot.getId().getPath() + "_from_ore")); } public static void ingotFromCrushedOre(Consumer<IFinishedRecipe> consumer, ItemRegistryObject<?> crushedOre, ItemRegistryObject<?> ingot) { SmeltingRecipeBuilder.smelting(ingredient(crushedOre), result(ingot), 0.6f, 1500).build(consumer, "furnace/electric/" + ingot.getId().getPath() + "_from_crushed_ore"); } public static void ingotFromCrushedOre(Consumer<IFinishedRecipe> consumer, ItemRegistryObject<?> crushedOre, Item ingot) { SmeltingRecipeBuilder.smelting(ingredient(crushedOre), () -> ingot, 0.6f, 1500).build(consumer, "furnace/electric/" + name(ingot) + "_from_crushed_ore"); } public static void oreWashing(Consumer<IFinishedRecipe> consumer, ItemRegistryObject<?> crushedOre, OreWashingRecipeBuilder.ResultBuilder... results) { if (results.length == 0) throw new IllegalArgumentException("Empty results"); Item primary = results[0].getResult().getItem(); new OreWashingRecipeBuilder(ingredient(crushedOre), Arrays.asList(results)).build(consumer, "ore_washer/" + name(primary)); } public static OreWashingRecipeBuilder.ResultBuilder oreWashingResult(IItemSupplier supplier) { return new OreWashingRecipeBuilder.ResultBuilder(supplier::getAsItem); } public static OreWashingRecipeBuilder.ResultBuilder oreWashingResult(IItemProvider provider) { return new OreWashingRecipeBuilder.ResultBuilder(provider::asItem); } public static void plate(Consumer<IFinishedRecipe> consumer, ITag.INamedTag<Item> ingotTag, ItemRegistryObject<?> plate) { MetalPressingRecipeBuilder.plate(ingredient(ingotTag), result(plate)).build(consumer, plate.getId().getPath()); } public static void gear(Consumer<IFinishedRecipe> consumer, ITag.INamedTag<Item> ingotTag, ItemRegistryObject<?> plate) { MetalPressingRecipeBuilder.gear(ingredient(ingotTag), result(plate)).build(consumer, plate.getId().getPath()); } public static void quadIngotFromOre(Consumer<IFinishedRecipe> consumer, ITag.INamedTag<Item> oreTag, Item ingot) { IndustrialSmeltingRecipeBuilder.smelting(Ingredient.fromTag(oreTag), result(ingot, 4), 450, 360000).build(consumer, "furnace/industrial/" + name(ingot)); } public static void quadIngotFromOre(Consumer<IFinishedRecipe> consumer, ITag.INamedTag<Item> oreTag, ItemRegistryObject<?> ingot) { IndustrialSmeltingRecipeBuilder.smelting(Ingredient.fromTag(oreTag), result(ingot, 4), 450, 360000).build(consumer, "furnace/industrial/" + ingot.getId().getPath()); } private static Ingredient ingredient(ITag.INamedTag<Item> tag) { return Ingredient.fromTag(tag); } private static Ingredient ingredient(IItemSupplier tag) { return Ingredient.fromItems(tag.getAsItem()); } private static IRecipeResult result(IItemSupplier item) { return new RecipeResult(item, 1); } private static IRecipeResult result(IItemSupplier item, int count) { return new RecipeResult(item, count); } private static IRecipeResult result(IItemProvider item, int count) { return new RecipeResult(item, count); } private static ICriterionInstance hasItem(ITag.INamedTag<Item> tag) { ItemPredicate[] predicates = new ItemPredicate[] { ItemPredicate.Builder.create().tag(tag).build() }; return new InventoryChangeTrigger.Instance(EntityPredicate.AndPredicate.ANY_AND, MinMaxBounds.IntBound.UNBOUNDED, MinMaxBounds.IntBound.UNBOUNDED, MinMaxBounds.IntBound.UNBOUNDED, predicates); } private static String name(Item item) { return ForgeRegistries.ITEMS.getKey(item).getPath(); } private static ResourceLocation modLoc(String name) { return new ResourceLocation(Techworks.MOD_ID, name); } }
60.170984
230
0.763283
9f809b5d61b4826d39ccedce05f78ae5c41b94ab
2,475
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.plc4x.java.mock; import org.apache.plc4x.java.api.PlcDriver; import org.apache.plc4x.java.api.authentication.PlcAuthentication; import org.apache.plc4x.java.api.PlcConnection; import org.apache.plc4x.java.api.exceptions.PlcConnectionException; import org.apache.plc4x.java.mock.connection.MockConnection; import org.apache.plc4x.java.mock.field.MockField; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * Mocking Driver that keeps a Map of references to Connections so that you can fetch a reference to a connection * which will be acquired by someone else (via the connection string). * This allows for efficient Mocking. */ public class MockDriver implements PlcDriver { private Map<String, PlcConnection> connectionMap = new ConcurrentHashMap<>(); @Override public String getProtocolCode() { return "mock"; } @Override public String getProtocolName() { return "Mock Protocol Implementation"; } @Override public PlcConnection getConnection(String url) throws PlcConnectionException { return getConnection(url, null); } @Override public PlcConnection getConnection(String url, PlcAuthentication authentication) throws PlcConnectionException { String deviceName = url.substring(5); if (deviceName.isEmpty()) { throw new PlcConnectionException("Invalid URL: no device name given."); } return connectionMap.computeIfAbsent(deviceName, name -> new MockConnection(authentication)); } @Override public MockField prepareField(String query){ return MockField.of(query); } }
35.357143
116
0.740606
7f808f05e5a7d5200dbb37ab52c87c8cd6641ca8
287
package com.jiangkang.ktools.download; /** * Created by jiangkang on 2017/10/10. * * define the download action and state */ public interface DownloadListener { void onDownloading(int progress, long contentLength); void onSuccess(); void onError(String message); }
15.944444
57
0.714286
f707bef70b19ef660bc273e9dc5728f86589f5fe
1,249
package com.ddphin.rabbitmq.entity; import com.alibaba.fastjson.JSONObject; import lombok.Data; import org.springframework.amqp.rabbit.connection.CorrelationData; import org.springframework.util.Assert; /** * CorrelationDataMQ * * @Date 2019/8/20 ไธ‹ๅˆ7:49 * @Author ddphin */ @Data public class CorrelationDataMQ extends CorrelationData { private String id; private String data; private String clazz; private Integer retry; private String exchange; private String routingKey; private Integer millis; public CorrelationDataMQ() {} public CorrelationDataMQ(String exchange, String routingKey, Integer millis, final Object message, String id) { Assert.notNull(id, "id ๆถˆๆฏไฝ“ไธ่ƒฝไธบNULL"); Assert.notNull(message, "message ๆถˆๆฏไฝ“ไธ่ƒฝไธบNULL"); Assert.notNull(exchange, "exchange ไธ่ƒฝไธบNULL"); Assert.notNull(routingKey, "routingKey ไธ่ƒฝไธบNULL"); this.id = id; this.data = JSONObject.toJSONString(message); this.clazz = message.getClass().getName(); this.retry = 0; this.exchange = exchange; this.routingKey = routingKey; this.millis = millis; } public CorrelationDataMQ retry() { ++this.retry; return this; } }
26.574468
115
0.682946
2666fcf9da0b59873ee8787af03aa0e0575c3207
13,949
/* * This file is generated by jOOQ. */ package org.blackdread.sqltojava.jooq.generated; import org.blackdread.sqltojava.jooq.generated.tables.Tables; import org.blackdread.sqltojava.jooq.generated.tables.*; import org.jooq.Catalog; import org.jooq.Table; import org.jooq.impl.SchemaImpl; import java.util.Arrays; import java.util.List; /** * This class is generated by jOOQ. */ @SuppressWarnings({"all", "unchecked", "rawtypes"}) public class InformationSchema extends SchemaImpl { /** * The reference instance of <code>information_schema</code> */ public static final InformationSchema INFORMATION_SCHEMA = new InformationSchema(); private static final long serialVersionUID = 1L; /** * The table <code>information_schema.CHARACTER_SETS</code>. */ public final CharacterSets CHARACTER_SETS = CharacterSets.CHARACTER_SETS; /** * The table <code>information_schema.COLLATION_CHARACTER_SET_APPLICABILITY</code>. */ public final CollationCharacterSetApplicability COLLATION_CHARACTER_SET_APPLICABILITY = CollationCharacterSetApplicability.COLLATION_CHARACTER_SET_APPLICABILITY; /** * The table <code>information_schema.COLLATIONS</code>. */ public final Collations COLLATIONS = Collations.COLLATIONS; /** * The table <code>information_schema.COLUMN_PRIVILEGES</code>. */ public final ColumnPrivileges COLUMN_PRIVILEGES = ColumnPrivileges.COLUMN_PRIVILEGES; /** * The table <code>information_schema.COLUMNS</code>. */ public final Columns COLUMNS = Columns.COLUMNS; /** * The table <code>information_schema.ENGINES</code>. */ public final Engines ENGINES = Engines.ENGINES; /** * The table <code>information_schema.EVENTS</code>. */ public final Events EVENTS = Events.EVENTS; /** * The table <code>information_schema.FILES</code>. */ public final Files FILES = Files.FILES; /** * The table <code>information_schema.GLOBAL_STATUS</code>. */ public final GlobalStatus GLOBAL_STATUS = GlobalStatus.GLOBAL_STATUS; /** * The table <code>information_schema.GLOBAL_VARIABLES</code>. */ public final GlobalVariables GLOBAL_VARIABLES = GlobalVariables.GLOBAL_VARIABLES; /** * The table <code>information_schema.INNODB_BUFFER_PAGE</code>. */ public final InnodbBufferPage INNODB_BUFFER_PAGE = InnodbBufferPage.INNODB_BUFFER_PAGE; /** * The table <code>information_schema.INNODB_BUFFER_PAGE_LRU</code>. */ public final InnodbBufferPageLru INNODB_BUFFER_PAGE_LRU = InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU; /** * The table <code>information_schema.INNODB_BUFFER_POOL_STATS</code>. */ public final InnodbBufferPoolStats INNODB_BUFFER_POOL_STATS = InnodbBufferPoolStats.INNODB_BUFFER_POOL_STATS; /** * The table <code>information_schema.INNODB_CMP</code>. */ public final InnodbCmp INNODB_CMP = InnodbCmp.INNODB_CMP; /** * The table <code>information_schema.INNODB_CMP_PER_INDEX</code>. */ public final InnodbCmpPerIndex INNODB_CMP_PER_INDEX = InnodbCmpPerIndex.INNODB_CMP_PER_INDEX; /** * The table <code>information_schema.INNODB_CMP_PER_INDEX_RESET</code>. */ public final InnodbCmpPerIndexReset INNODB_CMP_PER_INDEX_RESET = InnodbCmpPerIndexReset.INNODB_CMP_PER_INDEX_RESET; /** * The table <code>information_schema.INNODB_CMP_RESET</code>. */ public final InnodbCmpReset INNODB_CMP_RESET = InnodbCmpReset.INNODB_CMP_RESET; /** * The table <code>information_schema.INNODB_CMPMEM</code>. */ public final InnodbCmpmem INNODB_CMPMEM = InnodbCmpmem.INNODB_CMPMEM; /** * The table <code>information_schema.INNODB_CMPMEM_RESET</code>. */ public final InnodbCmpmemReset INNODB_CMPMEM_RESET = InnodbCmpmemReset.INNODB_CMPMEM_RESET; /** * The table <code>information_schema.INNODB_FT_BEING_DELETED</code>. */ public final InnodbFtBeingDeleted INNODB_FT_BEING_DELETED = InnodbFtBeingDeleted.INNODB_FT_BEING_DELETED; /** * The table <code>information_schema.INNODB_FT_CONFIG</code>. */ public final InnodbFtConfig INNODB_FT_CONFIG = InnodbFtConfig.INNODB_FT_CONFIG; /** * The table <code>information_schema.INNODB_FT_DEFAULT_STOPWORD</code>. */ public final InnodbFtDefaultStopword INNODB_FT_DEFAULT_STOPWORD = InnodbFtDefaultStopword.INNODB_FT_DEFAULT_STOPWORD; /** * The table <code>information_schema.INNODB_FT_DELETED</code>. */ public final InnodbFtDeleted INNODB_FT_DELETED = InnodbFtDeleted.INNODB_FT_DELETED; /** * The table <code>information_schema.INNODB_FT_INDEX_CACHE</code>. */ public final InnodbFtIndexCache INNODB_FT_INDEX_CACHE = InnodbFtIndexCache.INNODB_FT_INDEX_CACHE; /** * The table <code>information_schema.INNODB_FT_INDEX_TABLE</code>. */ public final InnodbFtIndexTable INNODB_FT_INDEX_TABLE = InnodbFtIndexTable.INNODB_FT_INDEX_TABLE; /** * The table <code>information_schema.INNODB_LOCK_WAITS</code>. */ public final InnodbLockWaits INNODB_LOCK_WAITS = InnodbLockWaits.INNODB_LOCK_WAITS; /** * The table <code>information_schema.INNODB_LOCKS</code>. */ public final InnodbLocks INNODB_LOCKS = InnodbLocks.INNODB_LOCKS; /** * The table <code>information_schema.INNODB_METRICS</code>. */ public final InnodbMetrics INNODB_METRICS = InnodbMetrics.INNODB_METRICS; /** * The table <code>information_schema.INNODB_SYS_COLUMNS</code>. */ public final InnodbSysColumns INNODB_SYS_COLUMNS = InnodbSysColumns.INNODB_SYS_COLUMNS; /** * The table <code>information_schema.INNODB_SYS_DATAFILES</code>. */ public final InnodbSysDatafiles INNODB_SYS_DATAFILES = InnodbSysDatafiles.INNODB_SYS_DATAFILES; /** * The table <code>information_schema.INNODB_SYS_FIELDS</code>. */ public final InnodbSysFields INNODB_SYS_FIELDS = InnodbSysFields.INNODB_SYS_FIELDS; /** * The table <code>information_schema.INNODB_SYS_FOREIGN</code>. */ public final InnodbSysForeign INNODB_SYS_FOREIGN = InnodbSysForeign.INNODB_SYS_FOREIGN; /** * The table <code>information_schema.INNODB_SYS_FOREIGN_COLS</code>. */ public final InnodbSysForeignCols INNODB_SYS_FOREIGN_COLS = InnodbSysForeignCols.INNODB_SYS_FOREIGN_COLS; /** * The table <code>information_schema.INNODB_SYS_INDEXES</code>. */ public final InnodbSysIndexes INNODB_SYS_INDEXES = InnodbSysIndexes.INNODB_SYS_INDEXES; /** * The table <code>information_schema.INNODB_SYS_TABLES</code>. */ public final InnodbSysTables INNODB_SYS_TABLES = InnodbSysTables.INNODB_SYS_TABLES; /** * The table <code>information_schema.INNODB_SYS_TABLESPACES</code>. */ public final InnodbSysTablespaces INNODB_SYS_TABLESPACES = InnodbSysTablespaces.INNODB_SYS_TABLESPACES; /** * The table <code>information_schema.INNODB_SYS_TABLESTATS</code>. */ public final InnodbSysTablestats INNODB_SYS_TABLESTATS = InnodbSysTablestats.INNODB_SYS_TABLESTATS; /** * The table <code>information_schema.INNODB_SYS_VIRTUAL</code>. */ public final InnodbSysVirtual INNODB_SYS_VIRTUAL = InnodbSysVirtual.INNODB_SYS_VIRTUAL; /** * The table <code>information_schema.INNODB_TEMP_TABLE_INFO</code>. */ public final InnodbTempTableInfo INNODB_TEMP_TABLE_INFO = InnodbTempTableInfo.INNODB_TEMP_TABLE_INFO; /** * The table <code>information_schema.INNODB_TRX</code>. */ public final InnodbTrx INNODB_TRX = InnodbTrx.INNODB_TRX; /** * The table <code>information_schema.KEY_COLUMN_USAGE</code>. */ public final KeyColumnUsage KEY_COLUMN_USAGE = KeyColumnUsage.KEY_COLUMN_USAGE; /** * The table <code>information_schema.OPTIMIZER_TRACE</code>. */ public final OptimizerTrace OPTIMIZER_TRACE = OptimizerTrace.OPTIMIZER_TRACE; /** * The table <code>information_schema.PARAMETERS</code>. */ public final Parameters PARAMETERS = Parameters.PARAMETERS; /** * The table <code>information_schema.PARTITIONS</code>. */ public final Partitions PARTITIONS = Partitions.PARTITIONS; /** * The table <code>information_schema.PLUGINS</code>. */ public final Plugins PLUGINS = Plugins.PLUGINS; /** * The table <code>information_schema.PROCESSLIST</code>. */ public final Processlist PROCESSLIST = Processlist.PROCESSLIST; /** * The table <code>information_schema.PROFILING</code>. */ public final Profiling PROFILING = Profiling.PROFILING; /** * The table <code>information_schema.REFERENTIAL_CONSTRAINTS</code>. */ public final ReferentialConstraints REFERENTIAL_CONSTRAINTS = ReferentialConstraints.REFERENTIAL_CONSTRAINTS; /** * The table <code>information_schema.ROUTINES</code>. */ public final Routines ROUTINES = Routines.ROUTINES; /** * The table <code>information_schema.SCHEMA_PRIVILEGES</code>. */ public final SchemaPrivileges SCHEMA_PRIVILEGES = SchemaPrivileges.SCHEMA_PRIVILEGES; /** * The table <code>information_schema.SCHEMATA</code>. */ public final Schemata SCHEMATA = Schemata.SCHEMATA; /** * The table <code>information_schema.SESSION_STATUS</code>. */ public final SessionStatus SESSION_STATUS = SessionStatus.SESSION_STATUS; /** * The table <code>information_schema.SESSION_VARIABLES</code>. */ public final SessionVariables SESSION_VARIABLES = SessionVariables.SESSION_VARIABLES; /** * The table <code>information_schema.STATISTICS</code>. */ public final Statistics STATISTICS = Statistics.STATISTICS; /** * The table <code>information_schema.TABLE_CONSTRAINTS</code>. */ public final TableConstraints TABLE_CONSTRAINTS = TableConstraints.TABLE_CONSTRAINTS; /** * The table <code>information_schema.TABLE_PRIVILEGES</code>. */ public final TablePrivileges TABLE_PRIVILEGES = TablePrivileges.TABLE_PRIVILEGES; /** * The table <code>information_schema.TABLES</code>. */ public final Tables TABLES = Tables.TABLES; /** * The table <code>information_schema.TABLESPACES</code>. */ public final Tablespaces TABLESPACES = Tablespaces.TABLESPACES; /** * The table <code>information_schema.TRIGGERS</code>. */ public final Triggers TRIGGERS = Triggers.TRIGGERS; /** * The table <code>information_schema.USER_PRIVILEGES</code>. */ public final UserPrivileges USER_PRIVILEGES = UserPrivileges.USER_PRIVILEGES; /** * The table <code>information_schema.VIEWS</code>. */ public final Views VIEWS = Views.VIEWS; /** * No further instances allowed */ private InformationSchema() { super("information_schema", null); } @Override public Catalog getCatalog() { return DefaultCatalog.DEFAULT_CATALOG; } @Override public final List<Table<?>> getTables() { return Arrays.<Table<?>>asList( CharacterSets.CHARACTER_SETS, CollationCharacterSetApplicability.COLLATION_CHARACTER_SET_APPLICABILITY, Collations.COLLATIONS, ColumnPrivileges.COLUMN_PRIVILEGES, Columns.COLUMNS, Engines.ENGINES, Events.EVENTS, Files.FILES, GlobalStatus.GLOBAL_STATUS, GlobalVariables.GLOBAL_VARIABLES, InnodbBufferPage.INNODB_BUFFER_PAGE, InnodbBufferPageLru.INNODB_BUFFER_PAGE_LRU, InnodbBufferPoolStats.INNODB_BUFFER_POOL_STATS, InnodbCmp.INNODB_CMP, InnodbCmpPerIndex.INNODB_CMP_PER_INDEX, InnodbCmpPerIndexReset.INNODB_CMP_PER_INDEX_RESET, InnodbCmpReset.INNODB_CMP_RESET, InnodbCmpmem.INNODB_CMPMEM, InnodbCmpmemReset.INNODB_CMPMEM_RESET, InnodbFtBeingDeleted.INNODB_FT_BEING_DELETED, InnodbFtConfig.INNODB_FT_CONFIG, InnodbFtDefaultStopword.INNODB_FT_DEFAULT_STOPWORD, InnodbFtDeleted.INNODB_FT_DELETED, InnodbFtIndexCache.INNODB_FT_INDEX_CACHE, InnodbFtIndexTable.INNODB_FT_INDEX_TABLE, InnodbLockWaits.INNODB_LOCK_WAITS, InnodbLocks.INNODB_LOCKS, InnodbMetrics.INNODB_METRICS, InnodbSysColumns.INNODB_SYS_COLUMNS, InnodbSysDatafiles.INNODB_SYS_DATAFILES, InnodbSysFields.INNODB_SYS_FIELDS, InnodbSysForeign.INNODB_SYS_FOREIGN, InnodbSysForeignCols.INNODB_SYS_FOREIGN_COLS, InnodbSysIndexes.INNODB_SYS_INDEXES, InnodbSysTables.INNODB_SYS_TABLES, InnodbSysTablespaces.INNODB_SYS_TABLESPACES, InnodbSysTablestats.INNODB_SYS_TABLESTATS, InnodbSysVirtual.INNODB_SYS_VIRTUAL, InnodbTempTableInfo.INNODB_TEMP_TABLE_INFO, InnodbTrx.INNODB_TRX, KeyColumnUsage.KEY_COLUMN_USAGE, OptimizerTrace.OPTIMIZER_TRACE, Parameters.PARAMETERS, Partitions.PARTITIONS, Plugins.PLUGINS, Processlist.PROCESSLIST, Profiling.PROFILING, ReferentialConstraints.REFERENTIAL_CONSTRAINTS, Routines.ROUTINES, SchemaPrivileges.SCHEMA_PRIVILEGES, Schemata.SCHEMATA, SessionStatus.SESSION_STATUS, SessionVariables.SESSION_VARIABLES, Statistics.STATISTICS, TableConstraints.TABLE_CONSTRAINTS, TablePrivileges.TABLE_PRIVILEGES, Tables.TABLES, Tablespaces.TABLESPACES, Triggers.TRIGGERS, UserPrivileges.USER_PRIVILEGES, Views.VIEWS); } }
33.856796
165
0.705642
220c018399fa7c979c0f883fe397c6aa5013e82f
493
import java.util.ArrayList; public class TexteURI { public int texteId; public String url; public ArrayList<String> uris; public TexteURI(int anId,String anUrl){ this.texteId = anId; this.url = anUrl; this.uris = new ArrayList<String>(); } public void addUri(String uri){ this.uris.add(uri); } public String toString(){ String s = ""; s += "ID: " + texteId + "\n"; s += "URL: " + url + "\n"; for(String uri:uris){ s += uri ; } return s; } }
15.40625
40
0.598377
82d9947c66e1614cec2399432fd14624f0f7a89b
784
package com.revature.aspect; public class NotAuthenticatedException extends Exception { public NotAuthenticatedException() { // TODO Auto-generated constructor stub } public NotAuthenticatedException(String message) { super(message); // TODO Auto-generated constructor stub } public NotAuthenticatedException(Throwable cause) { super(cause); // TODO Auto-generated constructor stub } public NotAuthenticatedException(String message, Throwable cause) { super(message, cause); // TODO Auto-generated constructor stub } public NotAuthenticatedException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); // TODO Auto-generated constructor stub } }
25.290323
93
0.780612
64d48c374ee87b4b5d5e82b3590ba54bc87239eb
4,598
package collagene.restrictionEnzyme; import collagene.seq.AnnotatedSequence; import collagene.seq.RestrictionSite; import collagene.seq.SeqAnnotation; import collagene.seq.SequenceRange; import collagene.sequtil.NucleotideUtil; /** * One fragment from digest */ public class SequenceFragmentRestrictionDigest implements SequenceFragment { public AnnotatedSequence origseq; public RestrictionSite fromSite; public RestrictionSite toSite; public AnnotatedSequence newseq; public int getUpperFrom() { if(fromSite==null) return 0; else return fromSite.cuttingUpperPos; } public int getUpperTo() { if(toSite==null) { return origseq.getLength(); } else return toSite.cuttingUpperPos; } private boolean goesAround() { return getUpperFrom()>=getUpperTo(); } public int getUpperLength() { SequenceRange r=new SequenceRange(); r.from=getUpperFrom(); r.to=getUpperTo(); if(r.from==r.to) return origseq.getLength(); else return r.getSize(origseq); } public void setSequence(AnnotatedSequence seq) { newseq=seq; } public AnnotatedSequence getFragmentSequence() { if(newseq!=null) return newseq; newseq=new AnnotatedSequence(); newseq.name=origseq.name+"_"+Math.random(); newseq.isCircular=false; int featureshift=0; System.out.println("goes around! "+goesAround()); if(goesAround()) { //Pull out upper and lower rang separately SequenceRange rangeUpper=new SequenceRange(fromSite.cuttingUpperPos, toSite.cuttingUpperPos); SequenceRange rangeLower=new SequenceRange(fromSite.cuttingLowerPos, toSite.cuttingLowerPos); if(rangeUpper.from==rangeUpper.to) rangeUpper.to+=newseq.getLength(); if(rangeLower.from==rangeLower.to) rangeLower.to+=newseq.getLength(); String supper=origseq.getSequence(rangeUpper); String slower=origseq.getSequenceLower(rangeLower); //Now have to find out which strand has the overhang int delta=fromSite.cuttingUpperPos-fromSite.cuttingLowerPos; if(fromSite.cut.upper<fromSite.cut.lower) { //Upper overhang. delta should be negative if(delta>0) delta-=origseq.getLength(); String padLeft=NucleotideUtil.getRepeatOligo(' ',-delta); slower=padLeft+slower; featureshift=fromSite.cuttingUpperPos; } else { //Negative overhang. delta should be positive if(delta>0) delta+=origseq.getLength(); String padLeft=NucleotideUtil.getRepeatOligo(' ',delta); supper=padLeft+supper; featureshift=fromSite.cuttingLowerPos; } //Add enough spaces on the right supper=supper+NucleotideUtil.getRepeatOligo(' ', Math.max(0,slower.length()-supper.length())); slower=slower+NucleotideUtil.getRepeatOligo(' ', Math.max(0,supper.length()-slower.length())); newseq.setSequence(supper,slower); } else { String supper=origseq.getSequence(); String slower=origseq.getSequenceLower(); //Cut it on the right if(toSite!=null) { int diff=toSite.cuttingUpperPos-toSite.cuttingLowerPos; supper=supper.substring(0,toSite.cuttingUpperPos)+NucleotideUtil.getRepeatOligo(' ',Math.max(0, -diff)); slower=slower.substring(0,toSite.cuttingLowerPos)+NucleotideUtil.getRepeatOligo(' ',Math.max(0, diff)); } //Cut it on the left if(fromSite!=null) { int diff=fromSite.cuttingUpperPos-fromSite.cuttingLowerPos; supper=NucleotideUtil.getRepeatOligo(' ',Math.max(0, diff))+supper.substring(fromSite.cuttingUpperPos); slower=NucleotideUtil.getRepeatOligo(' ',Math.max(0,-diff))+slower.substring(fromSite.cuttingLowerPos); } newseq.setSequence(supper, slower); if(fromSite!=null) featureshift=Math.min(fromSite.cuttingUpperPos,fromSite.cuttingLowerPos); } //Transfer features for(SeqAnnotation annot:origseq.annotations) { annot=new SeqAnnotation(annot); annot.range=annot.range.toUnwrappedRange(origseq); annot.range.shift(-featureshift); if(annot.getFrom()>=0 && annot.getTo()<=newseq.getLength()) newseq.addAnnotation(annot); else { //For circular sequences, need to rotate around one turn and try again. ooor? if(annot.getFrom()<0) annot.range.shift(+origseq.getLength()); else annot.range.shift(-origseq.getLength()); if(annot.getFrom()>=0 && annot.getTo()<=newseq.getLength()) newseq.addAnnotation(annot); } } newseq.normalizeFeaturePos(); return newseq; } @Override public RestrictionSite getFromSite() { return fromSite; } @Override public RestrictionSite getToSite() { return toSite; } }
26.578035
108
0.718356
4b27fcfafd360011736105f04cf8af195af1f91e
1,604
package com.guosen.zebra.distributed.transaction.seata.conf; import com.google.common.collect.Lists; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; /** * ZebraSeataConfiugrationๆ ก้ชŒๅ™จ */ public final class ZebraSeataConfigurationValidator { private static final Logger LOGGER = LoggerFactory.getLogger(ZebraSeataConfigurationValidator.class); /** * default groupๅฏนๅบ”็š„seata server้…็ฝฎkey */ private static final String DEFAULT_GROUP_LIST_KEY = "service.default.grouplist"; /** * ๅฟ…ๅกซ็š„้…็ฝฎ้กน */ private static final List<String> REQUIRED_CONFIG_KEYS = Lists.newArrayList(DEFAULT_GROUP_LIST_KEY); private ZebraSeataConfigurationValidator(){} /** * ๆ‰ง่กŒๆ ก้ชŒ * @param zebraSeataConfiguration seata้…็ฝฎ * @throws IllegalArgumentException ๆ ก้ชŒไธ้€š่ฟ‡ */ public static void validate(ZebraSeataConfiguration zebraSeataConfiguration) { validateRequiredConf(zebraSeataConfiguration); } private static void validateRequiredConf(ZebraSeataConfiguration zebraSeataConfiguration) { for (String requiredConfigKey : REQUIRED_CONFIG_KEYS) { String requiredConfigValue = zebraSeataConfiguration.getConfig(requiredConfigKey); if (StringUtils.isBlank(requiredConfigValue)) { String errorMessage = requiredConfigKey + " is required."; LOGGER.error(errorMessage); throw new IllegalArgumentException(errorMessage); } } } }
32.734694
106
0.700748
7863b3b4e8a2e55d106ab706a5ab0d79b73fa9eb
1,339
package cn.felord.wepay.ali.sdk.api.domain; import cn.felord.wepay.ali.sdk.api.AlipayObject; import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiField; /** * ่ฎขๅ•ๆœๅŠก่€…ๅ˜ๆ›ดๆŽฅๅฃ * * @author auto create * @version $Id: $Id */ public class AlipayDaoweiOrderSpModifyModel extends AlipayObject { private static final long serialVersionUID = 4526356681723694864L; /** * ๅˆฐไฝไธšๅŠก่ฎขๅ•ๅท๏ผŒๅ…จๅฑ€ๅ”ฏไธ€๏ผŒ็”ฑ32ไฝๆ•ฐๅญ—็ป„ๆˆ๏ผŒ็”จๆˆทๅœจๅˆฐไฝไธ‹ๅ•ๆ—ถ็ณป็ปŸ็”ŸๆˆๅนถๆถˆๆฏๅŒๆญฅ็ป™ๅ•†ๅฎถ๏ผŒๅ•†ๆˆทๅช่ƒฝๆŸฅ่‡ชๅทฑๅŒๆญฅๅˆฐ็š„่ฎขๅ•ๅท */ @ApiField("order_no") private String orderNo; /** * ๅค–้ƒจๆœๅŠก่€…id๏ผŒ็”ฑๅ•†ๆˆท่‡ชๅทฑ็”Ÿๆˆ๏ผŒไฟ่ฏๅŒไธ€ๅ•†ๆˆทidๅ”ฏไธ€๏ผŒๅŒๆญฅๆœๅŠก่€…ไฟกๆฏๆˆ–่€…ไฟฎๆ”น่ฎขๅ•ๆœๅŠก่€…ไฟกๆฏๆ—ถ่ฎพ็ฝฎ๏ผŒ้•ฟๅบฆไธ่ถ…่ฟ‡64ไธชๅญ—็ฌฆ */ @ApiField("out_sp_id") private String outSpId; /** * <p>Getter for the field <code>orderNo</code>.</p> * * @return a {@link java.lang.String} object. */ public String getOrderNo() { return this.orderNo; } /** * <p>Setter for the field <code>orderNo</code>.</p> * * @param orderNo a {@link java.lang.String} object. */ public void setOrderNo(String orderNo) { this.orderNo = orderNo; } /** * <p>Getter for the field <code>outSpId</code>.</p> * * @return a {@link java.lang.String} object. */ public String getOutSpId() { return this.outSpId; } /** * <p>Setter for the field <code>outSpId</code>.</p> * * @param outSpId a {@link java.lang.String} object. */ public void setOutSpId(String outSpId) { this.outSpId = outSpId; } }
21.253968
67
0.681852
ed99ab0c4824df7e6674073b2a6eef33d8ea354d
2,767
/* * ApplicationInsights-Java * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the ""Software""), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit * persons to whom the Software is furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ package com.microsoft.applicationinsights.agent.internal.configuration; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import org.slf4j.Logger; class ConfigurationLogger { // cannot use logger before loading configuration, so need to store warning messages locally until // logger is initialized private final List<Message> messages = new CopyOnWriteArrayList<>(); void warn(String message, Object... args) { messages.add(new Message(ConfigurationLogLevel.WARN, message, args)); } void debug(String message, Object... args) { messages.add(new Message(ConfigurationLogLevel.DEBUG, message, args)); } void log(Logger logger) { for (Message message : messages) { message.log(logger); } } private static class Message { private final ConfigurationLogLevel level; private final String message; private final Object[] args; private Message(ConfigurationLogLevel level, String message, Object... args) { this.level = level; this.message = message; this.args = args; } private void log(Logger logger) { level.log(logger, message, args); } } private enum ConfigurationLogLevel { WARN { @Override public void log(Logger logger, String message, Object... args) { logger.warn(message, args); } }, DEBUG { @Override public void log(Logger logger, String message, Object... args) { logger.debug(message, args); } }; public abstract void log(Logger logger, String message, Object... args); } }
34.160494
100
0.718468
37fd8dfe6278e3b132e7ee5e3b9a30685a235081
77
package org.amv.access.client.android; public interface AccessApiClient { }
15.4
38
0.805195
a284ce0da3c593bb36f78af098c32f8b57377445
586
package com.google.firebase.iid; import com.google.firebase.events.Event; import com.google.firebase.events.EventHandler; import com.google.firebase.iid.FirebaseInstanceId; final /* synthetic */ class zzq implements EventHandler { private final FirebaseInstanceId.zza zzbe; zzq(FirebaseInstanceId.zza zza) { this.zzbe = zza; } public final void handle(Event event) { FirebaseInstanceId.zza zza = this.zzbe; synchronized (zza) { if (zza.isEnabled()) { FirebaseInstanceId.this.zzg(); } } } }
25.478261
57
0.651877
cd94b61344cbf1a1d80435879bf41b98a676b392
11,098
/* * Copyright 2010 gark87 * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gark87.intellij.lang.ini.parsing.test; import org.gark87.intellij.lang.ini.parsing._IniLexer; import org.jetbrains.annotations.NonNls; import org.junit.Test; import com.intellij.lexer.Lexer; import com.intellij.psi.tree.IElementType; /** * @author gark87 <[email protected]> */ public abstract class IniLexerTest extends com.intellij.testFramework.UsefulTestCase { public IniLexerTest() { } private static void doTest(@NonNls String text, @NonNls String... expectedTokens) { Lexer lexer = new _IniLexer(); doTest(text, expectedTokens, lexer); } private static void doTest(String text, String[] expectedTokens, Lexer lexer) { lexer.start(text); int idx = 0; IElementType type; while ((type = lexer.getTokenType()) != null) { if (idx >= expectedTokens.length) fail("Too many tokens"); String tokenName = type.toString(); String expectedTokenType = expectedTokens[idx++]; String expectedTokenText = expectedTokens[idx++]; assertEquals("wrong type @" + idx / 2, expectedTokenType, tokenName); String tokenText = lexer.getBufferSequence().subSequence(lexer.getTokenStart(), lexer.getTokenEnd()).toString(); assertEquals("wrong text @" + idx / 2, expectedTokenText, tokenText); lexer.advance(); } if (idx < expectedTokens.length) fail("Not enough tokens"); } @Test public void testSimpleProperty() throws Exception { doTest("xxx=yyy", "Ini:KEY_CHARACTERS", "xxx", "Ini:KEY_VALUE_SEPARATOR", "=", "Ini:VALUE_CHARACTERS", "yyy"); doTest(" xxx = yyy ", "WHITE_SPACE", " ", "Ini:KEY_CHARACTERS", "xxx", "Ini:KEY_VALUE_SEPARATOR", " = ", "Ini:VALUE_CHARACTERS", "yyy "); } @Test public void testSpacedValue() throws Exception { doTest("xxx=yyy zzz", "Ini:KEY_CHARACTERS", "xxx", "Ini:KEY_VALUE_SEPARATOR", "=", "Ini:VALUE_CHARACTERS", "yyy zzz"); } @Test public void testQuotedString() throws Exception { doTest("xxx=\"y;y\"", "Ini:KEY_CHARACTERS", "xxx", "Ini:KEY_VALUE_SEPARATOR", "=", "Ini:QUOTED_STRING", "\"y;y\""); doTest(" xxx = \" y#y \" ", "WHITE_SPACE", " ", "Ini:KEY_CHARACTERS", "xxx", "Ini:KEY_VALUE_SEPARATOR", " = ", "Ini:QUOTED_STRING", "\" y#y \"", "Ini:VALUE_CHARACTERS", " "); doTest(" xxx = \" \\\" \\t\" ", "WHITE_SPACE", " ", "Ini:KEY_CHARACTERS", "xxx", "Ini:KEY_VALUE_SEPARATOR", " = ", "Ini:QUOTED_STRING", "\" \\\" \\t\"", "Ini:VALUE_CHARACTERS", " "); doTest(" xxx = A \" y[y \" B ", "WHITE_SPACE", " ", "Ini:KEY_CHARACTERS", "xxx", "Ini:KEY_VALUE_SEPARATOR", " = ", "Ini:VALUE_CHARACTERS", "A ", "Ini:QUOTED_STRING", "\" y[y \"", "Ini:VALUE_CHARACTERS", " B "); doTest("xxx=A\"y]y\"B", "Ini:KEY_CHARACTERS", "xxx", "Ini:KEY_VALUE_SEPARATOR", "=", "Ini:VALUE_CHARACTERS", "A", "Ini:QUOTED_STRING", "\"y]y\"", "Ini:VALUE_CHARACTERS", "B"); } @Test public void testIncompleteProperty() throws Exception { doTest("a", "Ini:KEY_CHARACTERS", "a"); doTest("a.2=", "Ini:KEY_CHARACTERS", "a.2", "Ini:KEY_VALUE_SEPARATOR", "="); } @Test public void testIncompleteSection() throws Exception { doTest("[", "Ini:LBRACKET", "["); doTest("[ a", "Ini:LBRACKET", "[", "WHITE_SPACE", " ", "Ini:SECTION", "a"); } @Test public void testEscaping() throws Exception { doTest("sdlfkjsd\\l\\\\\\:\\=gk = s\\nsssd", "Ini:KEY_CHARACTERS", "sdlfkjsd\\l\\\\\\:\\=gk", "Ini:KEY_VALUE_SEPARATOR", " = ", "Ini:VALUE_CHARACTERS", "s\\nsssd"); } @Test public void testCRLFEscaping() throws Exception { doTest("sdlfkjsdsssd=a\\\nb", "Ini:KEY_CHARACTERS", "sdlfkjsdsssd", "Ini:KEY_VALUE_SEPARATOR", "=", "Ini:VALUE_CHARACTERS", "a\\\nb"); } @Test public void testCRLFEscapingKey() throws Exception { doTest("x\\\ny:z", "Ini:KEY_CHARACTERS", "x\\\ny", "Ini:KEY_VALUE_SEPARATOR", ":", "Ini:VALUE_CHARACTERS", "z"); } @Test public void testWhitespace() throws Exception { doTest("x y", "Ini:KEY_CHARACTERS", "x", "WHITE_SPACE", " ", "BAD_CHARACTER", "y"); } @Test public void testComments() throws Exception { doTest("#test comment \n" + "\n" + ";test comment 2\r\n" + ";last comment 3 ", "Ini:END_OF_LINE_COMMENT", "#test comment \n", "Ini:EOL", "\n", "Ini:END_OF_LINE_COMMENT", ";test comment 2\r\n", "Ini:END_OF_LINE_COMMENT", ";last comment 3 "); } @Test public void testCommentsAndProperties() throws Exception { doTest("name=value ;comment\n", "Ini:KEY_CHARACTERS", "name", "Ini:KEY_VALUE_SEPARATOR", "=", "Ini:VALUE_CHARACTERS", "value ", "Ini:END_OF_LINE_COMMENT", ";comment\n"); doTest("name=value#comment", "Ini:KEY_CHARACTERS", "name", "Ini:KEY_VALUE_SEPARATOR", "=", "Ini:VALUE_CHARACTERS", "value", "Ini:END_OF_LINE_COMMENT", "#comment"); doTest(";comment\n" + "#comment\n" + "name=value", "Ini:END_OF_LINE_COMMENT", ";comment\n", "Ini:END_OF_LINE_COMMENT", "#comment\n", "Ini:KEY_CHARACTERS", "name", "Ini:KEY_VALUE_SEPARATOR", "=", "Ini:VALUE_CHARACTERS", "value"); doTest("name ;comment\n" + " #comment\n" + " = value", "Ini:KEY_CHARACTERS", "name", "WHITE_SPACE", " ", "Ini:END_OF_LINE_COMMENT", ";comment\n ", "Ini:END_OF_LINE_COMMENT", "#comment\n ", "Ini:KEY_VALUE_SEPARATOR", "= ", "Ini:VALUE_CHARACTERS", "value"); doTest("name = ;comment\n" + " #comment\n" + " value", "Ini:KEY_CHARACTERS", "name", "Ini:KEY_VALUE_SEPARATOR", " = ", "Ini:END_OF_LINE_COMMENT", ";comment\n ", "Ini:END_OF_LINE_COMMENT", "#comment\n ", "Ini:VALUE_CHARACTERS", "value"); } @Test public void testCommentsAndSections() throws Exception { doTest(" [section;test ]", "WHITE_SPACE", " ", "Ini:LBRACKET", "[", "Ini:SECTION", "section", "Ini:END_OF_LINE_COMMENT", ";test ]"); doTest(" [ ;test ]", "WHITE_SPACE", " ", "Ini:LBRACKET", "[", "WHITE_SPACE", " ", "Ini:END_OF_LINE_COMMENT", ";test ]"); doTest(" [section] ;comment", "WHITE_SPACE", " ", "Ini:LBRACKET", "[", "Ini:SECTION", "section", "Ini:RBRACKET", "]", "WHITE_SPACE", " ", "Ini:END_OF_LINE_COMMENT", ";comment"); } @Test public void testTabs() throws Exception { doTest("install/htdocs/imcms/html/link_editor.jsp/1002 = URL\\n\\\n" + "\t\\t\\teller meta_id:", "Ini:KEY_CHARACTERS", "install/htdocs/imcms/html/link_editor.jsp/1002", "Ini:KEY_VALUE_SEPARATOR", " = ", "Ini:VALUE_CHARACTERS", "URL\\n\\\n" + "\t\\t\\teller meta_id:"); } @Test public void testIndentedComments() throws Exception { doTest(" #comm1\n#comm2=n\n\t#comm3", "WHITE_SPACE", " ", "Ini:END_OF_LINE_COMMENT", "#comm1\n", "Ini:END_OF_LINE_COMMENT", "#comm2=n\n\t", "Ini:END_OF_LINE_COMMENT", "#comm3"); } @Test public void testSection() throws Exception { doTest(" [section]", "WHITE_SPACE", " ", "Ini:LBRACKET", "[", "Ini:SECTION", "section", "Ini:RBRACKET", "]"); doTest(" [[test ]", "WHITE_SPACE", " ", "Ini:LBRACKET", "[", "Ini:SECTION", "[test", "WHITE_SPACE", " ", "Ini:RBRACKET", "]"); doTest("[ a=b]", "Ini:LBRACKET", "[", "WHITE_SPACE", " ", "Ini:SECTION", "a=b", "Ini:RBRACKET", "]"); doTest("[\"section\"]", "Ini:LBRACKET", "[", "Ini:SECTION", "\"section\"", "Ini:RBRACKET", "]"); } @Test public void testExample() throws Exception { doTest("[staging : production]\n" + "; PHP settings we want to initialize\n" + "phpSettings.display_errors = 0\n" + "includePaths.library = APPLICATION_PATH \"/../library\"", "Ini:LBRACKET", "[", "Ini:SECTION", "staging", "Ini:SECTION_SEPARATOR", " : ", "Ini:SECTION", "production", "Ini:RBRACKET", "]", "Ini:EOL", "\n", "Ini:END_OF_LINE_COMMENT", "; PHP settings we want to initialize\n", "Ini:KEY_CHARACTERS", "phpSettings.display_errors", "Ini:KEY_VALUE_SEPARATOR", " = ", "Ini:VALUE_CHARACTERS", "0", "Ini:EOL", "\n", "Ini:KEY_CHARACTERS", "includePaths.library", "Ini:KEY_VALUE_SEPARATOR", " = ", "Ini:VALUE_CHARACTERS", "APPLICATION_PATH ", "Ini:QUOTED_STRING", "\"/../library\""); } }
34.359133
124
0.494413
3132687034c2a17c7e81e92fdc66227ef91b7442
997
package com.jeeagile.system.mapper; import com.jeeagile.frame.annotation.AgileMapperScan; import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Select; import java.util.List; /** * @author JeeAgile * @date 2021-03-21 * @description */ @AgileMapperScan public interface AgileSysPersonMapper { /** * ๆ นๆฎ็”จๆˆทID่Žทๅ–ๅทฒๅˆ†้…็š„่ง’่‰ฒๅ็งฐ */ @Select(" select distinct r.role_name" + " from agile_sys_role r" + " left join agile_sys_user_role ur on r.id = ur.role_id" + " where r.role_status = '0' and ur.user_id = #{userId}") List<String> getRoleNameByUserId(@Param("userId") String userId); /** * ๆ นๆฎ็”จๆˆทID่Žทๅ–ๅทฒๅˆ†้…็š„ๅฒ—ไฝๅ็งฐ */ @Select(" select distinct r.post_name" + " from agile_sys_post r" + " left join agile_sys_user_post ur on r.id = ur.post_id" + " where r.post_status = '0' and ur.user_id = #{userId}") List<String> getPostNameByUserId(@Param("userId") String userId); }
29.323529
70
0.650953
306bfd5f0c4ddbfc8ae385af8fbe329c0bfdbf4a
2,218
package com.baeldung.readonlytransactions.mysql.dao; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.SplittableRandom; import java.util.concurrent.atomic.AtomicLong; public class MyRepoJdbc extends BaseRepo { static { try { Class.forName("com.mysql.cj.jdbc.Driver"); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } private HikariDataSource ds; private SplittableRandom random = new SplittableRandom(); public MyRepoJdbc(boolean readOnly, boolean autocommit) { HikariConfig config = new HikariConfig(); config.setJdbcUrl("jdbc:mysql://localhost/baeldung?useUnicode=true&characterEncoding=UTF-8"); config.setUsername("baeldung"); config.setPassword("baeldung"); config.setReadOnly(readOnly); config.setAutoCommit(autocommit); ds = new HikariDataSource(config); } private Connection getConnection() throws SQLException { return ds.getConnection(); } public long runQuery(Boolean autoCommit, Boolean readOnly) { try { return execQuery(count -> runSql(count, autoCommit, readOnly)); } finally { ds.close(); } } private void runSql(AtomicLong count, Boolean autoCommit, Boolean readOnly) { if (Thread.interrupted()) { return; } try (Connection connect = getConnection(); PreparedStatement statement = connect.prepareStatement("select * from transactions where id = ?")) { if (autoCommit != null) connect.setAutoCommit(autoCommit); if (readOnly != null) connect.setReadOnly(readOnly); statement.setLong(1, 1L + random.nextLong(0, 100000)); ResultSet resultSet = statement.executeQuery(); if (autoCommit != null && !autoCommit) connect.commit(); count.incrementAndGet(); resultSet.close(); } catch (Exception ignored) { } } }
31.239437
151
0.641118
efbd91e007bee78180071248e9f22cd19d12564a
5,431
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package ml.paulobatista.restclient.http; import com.google.gson.Gson; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import ml.paulobatista.restclient.Nota; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.HttpClientBuilder; import java.lang.reflect.Type; import com.google.gson.reflect.TypeToken; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.text.SimpleDateFormat; import java.util.logging.Level; import java.util.logging.Logger; import org.apache.http.NameValuePair; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.StringEntity; import org.apache.http.message.BasicNameValuePair; /** * * @author paulo */ public class ClienteRest { private final String USER_AGENT = "Mozilla/5.0"; private final String WEBSERVICE = "http://localhost:8080/ProjetoRest/resources/notas/"; public ArrayList<Nota> getNotas() throws Exception { String url = WEBSERVICE + "list"; String response = this.sendGet(url); //return response Type type = new TypeToken<List<Nota>>() { }.getType(); //Type listType = new TypeToken<List<Nota>>() {}.getType(); Gson gson = new Gson(); ArrayList<Nota> notas = (ArrayList<Nota>) gson.fromJson(response, type); return notas; } public Nota getNota(int id) throws Exception { String url = WEBSERVICE + "get/" + id; String response = this.sendGet(url); Gson gson = new Gson(); Nota nota = gson.fromJson(response, Nota.class); return nota; } public void sendNota(Nota nota) { } public void sendPut(Nota nota) throws UnsupportedEncodingException { String url = WEBSERVICE + "put/" + nota.getId(); HttpClient client = HttpClientBuilder.create().build(); HttpPut put = new HttpPut(url); //put.setHeader("User-Agent", USER_AGENT); put.setHeader("Accept", "application/json"); put.setHeader("Content-type", "application/json"); Gson gson = new Gson(); String json = gson.toJson(nota); StringEntity params = new StringEntity(json); put.setEntity(params); try { int response = client.execute(put).getStatusLine().getStatusCode(); System.out.println("Status Code: " + response) ; } catch (IOException ex) { Logger.getLogger(ClienteRest.class.getName()).log(Level.SEVERE, null, ex); } } public void sendPost(Nota nota) throws UnsupportedEncodingException { String url = WEBSERVICE + "post"; HttpClient client = HttpClientBuilder.create().build(); HttpPost post = new HttpPost(url); post.setHeader("Accept", "application/json"); post.setHeader("Content-type", "application/json"); Gson gson = new Gson(); String json = gson.toJson(nota); StringEntity params = new StringEntity(json); post.setEntity(params); try { int response = client.execute(post).getStatusLine().getStatusCode(); System.out.println("Status Code post: " + response) ; } catch (IOException ex) { Logger.getLogger(ClienteRest.class.getName()).log(Level.SEVERE, null, ex); } } public void sendDelete(int id) throws Exception { String url = WEBSERVICE + "del/" + id; HttpClient client = HttpClientBuilder.create().build(); HttpDelete delete = new HttpDelete(url); delete.setHeader("User-Agent", USER_AGENT); HttpResponse response = client.execute(delete); System.out.println(response.getStatusLine().getStatusCode()); } private String sendGet(String url) throws Exception { //String url = WEBSERVICE + "list"; HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(url); // add request header request.addHeader("User-Agent", USER_AGENT); HttpResponse response = client.execute(request); System.out.println("Response Code : " + response.getStatusLine().getStatusCode()); BufferedReader rd = new BufferedReader( new InputStreamReader(response.getEntity().getContent())); StringBuffer result = new StringBuffer(); String line = ""; while ((line = rd.readLine()) != null) { result.append(line); } //System.out.println(result); return result.toString(); } public static void main(String[] args) throws Exception { ClienteRest http = new ClienteRest(); System.out.println("Testing 1 - Send Http GET request"); //http.getNotas(); //http.sendDelete(); //System.out.println("\nTesting 2 - Send Http POST request"); //http.sendPost(); } }
32.915152
91
0.646842
c2b3efd7fbd179addaf050c20d62e7c0e89a6261
1,239
package gov.healthit.chpl.dto.questionableActivity; import gov.healthit.chpl.dto.CertifiedProductDetailsDTO; import gov.healthit.chpl.entity.questionableActivity.QuestionableActivityListingEntity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.experimental.SuperBuilder; @Data @EqualsAndHashCode(callSuper = true) @NoArgsConstructor @SuperBuilder @AllArgsConstructor public class QuestionableActivityListingDTO extends QuestionableActivityDTO { private Long listingId; private String certificationStatusChangeReason; private String reason; private CertifiedProductDetailsDTO listing; public QuestionableActivityListingDTO(QuestionableActivityListingEntity entity) { super(entity); this.listingId = entity.getListingId(); this.certificationStatusChangeReason = entity.getCertificationStatusChangeReason(); this.reason = entity.getReason(); if (entity.getListing() != null) { this.listing = new CertifiedProductDetailsDTO(entity.getListing()); } } @Override public Class<?> getActivityObjectClass() { return CertifiedProductDetailsDTO.class; } }
33.486486
91
0.77724
850a1c0225f94b560419dec0812781fe6003c884
7,089
/******************************************************************************* * Copyright 2018 Univocity Software Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ package com.univocity.parsers.issues.github; import com.univocity.parsers.annotations.*; import com.univocity.parsers.common.processor.*; import com.univocity.parsers.common.record.*; import com.univocity.parsers.csv.*; import org.testng.annotations.*; import java.io.*; import java.util.*; import static org.testng.Assert.*; /** * From: https://github.com/univocity/univocity-parsers/issues/283 * * @author Univocity Software Pty Ltd - <a href="mailto:[email protected]">[email protected]</a> */ public class Github_283 { private static final String INPUT = "a,A, a , A ,a ,A , b \n1,2,3,4,5,6,7"; private static final String[] ALL_FIELDS = new String[]{"a", "A", " a ", " A ", "a ", "A ", "B"}; @DataProvider public Object[][] paramProvider() { return new Object[][]{ {true, ALL_FIELDS}, {false, ALL_FIELDS}, {true, new String[]{" a ", " A ", "a ", "A ", "B"}}, {false, new String[]{" a ", " A ", "a ", "A ", "B"}}, {true, new String[]{"a", "A", " a ", " A ", " B"}}, {false, new String[]{"a", "A", " a ", " A ", " B"}}, }; } @Test(dataProvider = "paramProvider") public void testHandlingOfSimilarHeaders(boolean trim, String[] selectedFields) { CsvParserSettings settings = new CsvParserSettings(); settings.setLineSeparatorDetectionEnabled(true); settings.setHeaderExtractionEnabled(true); settings.trimValues(trim); settings.selectFields(selectedFields); CsvParser parser = new CsvParser(settings); parser.beginParsing(new StringReader(INPUT)); String[] headers = parser.getContext().headers(); assertEquals(headers.length, 7); Set<String> selected = new LinkedHashSet<String>(Arrays.asList(selectedFields)); Record record = parser.parseNextRecord(); assertEqual(selected, "a", getValue(record, "a"), 1); assertEqual(selected, "A", getValue(record, "A"), 2); assertEqual(selected, " a ", getValue(record, " a "), 3); assertEqual(selected, " A ", getValue(record, " A "), 4); assertEqual(selected, "a ", getValue(record, "a "), 5); assertEqual(selected, "A ", getValue(record, "A "), 6); String _B = selectedFields[selectedFields.length - 1]; assertEqual(selected, _B, getValue(record, "b"), 7); assertEqual(selected, _B, getValue(record, " b "), 7); assertEqual(selected, _B, getValue(record, "B"), 7); assertEqual(selected, _B, getValue(record, " B"), 7); assertEqual(selected, _B, getValue(record, " B "), 7); parser.stopParsing(); } private Integer getValue(Record record, String field) { try { return record.getInt(field); } catch (IllegalArgumentException e) { assertTrue(e.getMessage().startsWith("Header name '" + field + "' not found.")); return null; } } private void assertEqual(Set<String> selectedFields, String field, Integer value, int expected) { if (selectedFields.contains(field)) { assertEquals(value.intValue(), expected); } else { assertNull(value); } } @Test(dataProvider = "paramProvider") public void testWritingSimilarHeaders(boolean trim, String[] selectedFields) { CsvWriterSettings settings = new CsvWriterSettings(); settings.getFormat().setLineSeparator("\n"); settings.setHeaders(ALL_FIELDS); settings.trimValues(trim); settings.selectFields(selectedFields); settings.setHeaderWritingEnabled(true); StringWriter output = new StringWriter(); CsvWriter writer = new CsvWriter(output, settings); writer.writeRow(1, 2, 3, 4, 5, 6, 7); writer.close(); validateWrittenOutput(output, selectedFields); } private void validateWrittenOutput(StringWriter output, String[] selectedFields){ Set<String> selected = new LinkedHashSet<String>(Arrays.asList(selectedFields)); StringBuilder expectedOutput = new StringBuilder(); for (int i = 0; i < ALL_FIELDS.length; i++) { if (i > 0) { expectedOutput.append(','); } expectedOutput.append(ALL_FIELDS[i]); } expectedOutput.append('\n'); for (int i = 0; i < ALL_FIELDS.length; i++) { if (i > 0) { expectedOutput.append(','); } if (selected.contains(ALL_FIELDS[i]) || i == 6) /* header 6 is 'b', while selection is 'B' or ' B'. */ { expectedOutput.append(i + 1); } } expectedOutput.append('\n'); assertEquals(output.toString(), expectedOutput.toString()); } public static class A { @Parsed(field = "a") private Integer a1; @Parsed(field = "A") private Integer a2; @Parsed(field = " a ") private Integer a3; @Parsed(field = " A ") private Integer a4; @Parsed(field = "a ") private Integer a5; @Parsed(field = "A ") private Integer a6; @Parsed(field = "B") private Integer b; } @Test(dataProvider = "paramProvider") public void testHandlingOfSimilarHeadersInClass(boolean trim, String[] selectedFields) throws Exception { CsvParserSettings settings = new CsvParserSettings(); BeanListProcessor<A> processor = new BeanListProcessor<A>(A.class); settings.setProcessor(processor); settings.setLineSeparatorDetectionEnabled(true); settings.setHeaderExtractionEnabled(true); settings.selectFields(selectedFields); settings.trimValues(trim); new CsvParser(settings).parse(new StringReader(INPUT)); Set<String> selected = new LinkedHashSet<String>(Arrays.asList(selectedFields)); A a = processor.getBeans().get(0); assertEqual(selected, "a", a.a1, 1); assertEqual(selected, "A", a.a2, 2); assertEqual(selected, " a ", a.a3, 3); assertEqual(selected, " A ", a.a4, 4); assertEqual(selected, "a ", a.a5, 5); assertEqual(selected, "A ", a.a6, 6); String _B = selectedFields[selectedFields.length - 1]; assertEqual(selected, _B, a.b, 7); } @Test(dataProvider = "paramProvider") public void testWritingSimilarHeadersInClass(boolean trim, String[] selectedFields) throws Exception { CsvWriterSettings settings = new CsvWriterSettings(); settings.getFormat().setLineSeparator("\n"); settings.trimValues(trim); settings.selectFields(selectedFields); settings.setHeaderWritingEnabled(true); settings.setRowWriterProcessor(new BeanWriterProcessor<A>(A.class)); StringWriter output = new StringWriter(); CsvWriter writer = new CsvWriter(output, settings); A a = new A(); a.a1 = 1; a.a2 = 2; a.a3 = 3; a.a4 = 4; a.a5 = 5; a.a6 = 6; a.b = 7; writer.processRecord(a); writer.close(); validateWrittenOutput(output, selectedFields); } }
31.647321
107
0.675977
86d89875f469e8f0dc96e8deb0ba7db847a40065
1,173
package shinil.direct.share.thread; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import shinil.direct.share.util.Constants; /** * @author shinilms */ public final class StartProxyThread extends Thread { private boolean isTrue = true; private ServerSocket serverSocket; public boolean isSocketBound() { return serverSocket != null && serverSocket.isBound(); } public StartProxyThread() { try { this.serverSocket = new ServerSocket(); this.serverSocket.setReuseAddress(true); this.serverSocket.bind(new InetSocketAddress(Constants.PROXY_PORT)); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { super.run(); while (isTrue) { try { new ProxyConnectionThread(serverSocket.accept()); } catch (Exception e) {/*ignore*/} } } public void stopProxy() { isTrue = false; try { serverSocket.close(); serverSocket = null; } catch (Exception e) {/*ignore*/} } }
23.938776
80
0.597613
5de9c3c68bf46c015a0510d656b5143e68b7619c
20,317
package it.polimi.ingsw.view.CLI.display; import it.polimi.ingsw.model.card.DevelopmentCardTable; import it.polimi.ingsw.utility.AnsiColors; /** * this class shows to the player the development card table, in particular every last card of a Development Card Deck * available in the table using data contained in */ public class DevelopmentCardTableDisplay { private DevelopmentCardTable tableCard; private boolean[][] getAvailable; public DevelopmentCardTableDisplay(DevelopmentCardTable developmentCardTable, boolean[][] getAvailable) { this.tableCard = developmentCardTable; this.getAvailable = getAvailable; } public void displayCardTable() { //public static void main(String[] args) { /* DevelopmentCardDeck[][] squareCards = new DevelopmentCardDeck[3][4]; //create the hash map for the cost of a Card ArrayList<Resource> array = new ArrayList<>(); array.add(0, new Resource(Color.BLUE)); array.add(1, new Resource(Color.YELLOW)); array.add(2, new Resource(Color.YELLOW)); array.add(3, new Resource(Color.YELLOW)); array.add(4, new Resource(Color.YELLOW)); array.add(5, new Resource(Color.YELLOW)); array.add(6, new Resource(Color.YELLOW)); array.add(7, new Resource(Color.YELLOW)); ArrayList<Resource> proceeds = new ArrayList<>(); proceeds.add(0, new Resource(Color.GREY)); proceeds.add(1, new Resource(Color.GREY)); proceeds.add(2, new Resource(Color.YELLOW)); ArrayList<Resource> cost = new ArrayList<>(); cost.add(0, new Resource(Color.BLUE)); cost.add(1, new Resource(Color.BLUE)); cost.add(2, new Resource(Color.BLUE)); cost.add(3, new Resource(Color.BLUE)); DevelopmentCard card1 = new DevelopmentCard(3,1, Color.GREEN, 1, array, proceeds, cost); DevelopmentCard card2 = new DevelopmentCard(2,2, Color.GREEN, 2, array, proceeds, cost); DevelopmentCard card3 = new DevelopmentCard(6,3, Color.GREEN, 3, array, proceeds, cost); DevelopmentCard card4 = new DevelopmentCard(3,1, Color.GREEN, 4, array, proceeds, cost); ArrayList<DevelopmentCard> list = new ArrayList<>(); list.add(card1); list.add(card2); list.add(card3); list.add(card4); DevelopmentCardDeck smallDeck1 = new DevelopmentCardDeck(list); DevelopmentCard card91 = new DevelopmentCard(3, 2,Color.GREEN, 2, array, proceeds, cost); DevelopmentCard card92 = new DevelopmentCard(2,1, Color.GREEN, 2, array, proceeds, cost); DevelopmentCard card93 = new DevelopmentCard(6,4, Color.GREEN, 2, array, proceeds, cost); DevelopmentCard card94 = new DevelopmentCard(3,1, Color.GREEN, 2, array, proceeds, cost); ArrayList<DevelopmentCard> list12 = new ArrayList<>(); list12.add(card91); list12.add(card92); list12.add(card93); list12.add(card94); DevelopmentCardDeck smallDeck12 = new DevelopmentCardDeck(list12); DevelopmentCard card81 = new DevelopmentCard(3,2, Color.GREEN, 3, array, proceeds, cost); DevelopmentCard card82 = new DevelopmentCard(2,2, Color.GREEN, 3, array, proceeds, cost); DevelopmentCard card83 = new DevelopmentCard(6,2, Color.GREEN, 3, array, proceeds, cost); DevelopmentCard card84 = new DevelopmentCard(3,2, Color.GREEN, 3, array, proceeds, cost); ArrayList<DevelopmentCard> list13 = new ArrayList<>(); list13.add(card81); list13.add(card82); list13.add(card83); list13.add(card84); DevelopmentCardDeck smallDeck13 = new DevelopmentCardDeck(list13); DevelopmentCard card5 = new DevelopmentCard(3,2, Color.BLUE, 1, array, proceeds, cost); DevelopmentCard card6 = new DevelopmentCard(2,2, Color.BLUE, 1, array, proceeds, cost); DevelopmentCard card7 = new DevelopmentCard(6, 2,Color.BLUE, 1, array, proceeds, cost); DevelopmentCard card8 = new DevelopmentCard(3,2, Color.BLUE, 1, array, proceeds, cost); DevelopmentCard card55 = new DevelopmentCard(3,2,Color.BLUE, 2, array, proceeds, cost); DevelopmentCard card66 = new DevelopmentCard(2,2, Color.BLUE, 2, array, proceeds, cost); DevelopmentCard card77 = new DevelopmentCard(6,2, Color.BLUE, 2, array, proceeds, cost); DevelopmentCard card88 = new DevelopmentCard(3,2, Color.BLUE, 2, array, proceeds, cost); DevelopmentCard card555 = new DevelopmentCard(3,2, Color.BLUE, 3, array, proceeds, cost); DevelopmentCard card666 = new DevelopmentCard(2,2, Color.BLUE, 3, array, proceeds, cost); DevelopmentCard card777 = new DevelopmentCard(6,2, Color.BLUE, 3, array, proceeds, cost); DevelopmentCard card888 = new DevelopmentCard(3,1, Color.BLUE, 3, array, proceeds, cost); ArrayList<DevelopmentCard> list1 = new ArrayList<>(); list1.add(card5); list1.add(card6); list1.add(card7); list1.add(card8); DevelopmentCardDeck smallDeck2 = new DevelopmentCardDeck(list1); ArrayList<DevelopmentCard> list11 = new ArrayList<>(); list11.add(card55); list11.add(card66); list11.add(card77); list11.add(card88); DevelopmentCardDeck smallDeck22 = new DevelopmentCardDeck(list11); ArrayList<DevelopmentCard> list111 = new ArrayList<>(); list111.add(card555); list111.add(card666); list111.add(card777); list111.add(card888); DevelopmentCardDeck smallDeck222 = new DevelopmentCardDeck(list111); DevelopmentCard card9 = new DevelopmentCard(3, 1,Color.YELLOW, 1, array, proceeds, cost); DevelopmentCard card10 = new DevelopmentCard(2, 1,Color.YELLOW, 2, array, proceeds, cost); DevelopmentCard card11 = new DevelopmentCard(6, 1,Color.YELLOW, 3, array, proceeds, cost); DevelopmentCard card12 = new DevelopmentCard(3, 1,Color.YELLOW, 4, array, proceeds, cost); ArrayList<DevelopmentCard> list2 = new ArrayList<>(); list2.add(card9); list2.add(card10); list2.add(card11); list2.add(card12); DevelopmentCardDeck smallDeck3 = new DevelopmentCardDeck(list2); DevelopmentCard card13 = new DevelopmentCard(3,2, Color.PURPLE, 1, array, proceeds, cost); DevelopmentCard card14 = new DevelopmentCard(2,2, Color.PURPLE, 1, array, proceeds, cost); DevelopmentCard card15 = new DevelopmentCard(6, 2,Color.PURPLE, 1, array, proceeds, cost); DevelopmentCard card16 = new DevelopmentCard(3,2, Color.PURPLE, 1, array, proceeds, cost); ArrayList<DevelopmentCard> list3 = new ArrayList<>(); list3.add(card13); list3.add(card14); list3.add(card15); list3.add(card16); DevelopmentCardDeck smallDeck4 = new DevelopmentCardDeck(list3); squareCards[0][0] = smallDeck1; squareCards[1][0] = smallDeck12; squareCards[2][0] = smallDeck13; squareCards[0][1] = smallDeck2; squareCards[1][1] = smallDeck22; squareCards[2][1] = smallDeck222; squareCards[0][2] = smallDeck3; squareCards[1][2] = smallDeck3; squareCards[2][2] = smallDeck3; squareCards[0][3] = smallDeck4; squareCards[1][3] = smallDeck4; squareCards[2][3] = smallDeck4; boolean[][] available = new boolean[3][4]; available[1][0] = true; available[2][0] = false; available[0][0] = true; available[2][1] = true; available[1][1] = true; available[0][1] = false; available[2][2] = true; available[1][2] = true; available[0][2] = true; available[0][3] = true; available[1][3] = true; available[2][3] = true; DevelopmentCardTable developmentCardTable = new DevelopmentCardTable(squareCards);*/ System.out.println(AnsiColors.BLUE_BOLD + "HERE IS THE DEVELOPMENT CARD TABLE:\n" + AnsiColors.RESET); String row0 = ""; String row01 = ""; String row02 = ""; String row1 = ""; String row2 = ""; String row3 = ""; String row4 = ""; String row5 = ""; String row6 = ""; String row7 = ""; String row8 = ""; String row9 = ""; String row10 = ""; String row11 = ""; String row12 = ""; String row13 = ""; String row14 = ""; String row15 = ""; String row16 = ""; String row17 = ""; String row18 = ""; /*row6 += tableCardCopy.getDeckTable(2,j).takeCard().getvictorytostring(); row5 += tableCardCopy.getDeckTable(1,j).takeCard().getEarnForCli(); row4 += tableCardCopy.getDeckTable(0,j).takeCard().getpaytostring(); row3 += tableCardCopy.getDeckTable(2,j).takeCard().getcosttostring(); row2 += tableCardCopy.getDeckTable(1,j).takeCard().getleveltostring(); row1 += tableCardCopy.getDeckTable(0,j).takeCard().getColortoString();*/ for (int j = 0; j < 4; j++) { if (tableCard.getTable()[0][j].getDevelopDeck().isEmpty()) { row18 += " "; row17 += " "; row16 += " "; row15 += AnsiColors.RED_BOLD + " EMPTY DECK " + AnsiColors.RESET; row14 += " "; row13 += " "; row02 += " "; } else { int size1 = tableCard.getTable()[0][j].getDevelopDeck().size() - 1; //actual Dim of the Deck in the table row18 += tableCard.getTable()[0][j].getDevelopDeck().get(size1).getvictorytostring(); row17 += tableCard.getTable()[0][j].getDevelopDeck().get(size1).getearntostring(); row16 += tableCard.getTable()[0][j].getDevelopDeck().get(size1).getpaytostring(); row15 += tableCard.getTable()[0][j].getDevelopDeck().get(size1).getcosttostring(); row14 += tableCard.getTable()[0][j].getDevelopDeck().get(size1).getleveltostring(); row13 += tableCard.getTable()[0][j].getDevelopDeck().get(size1).getColortoString(); row02 += tableCard.getTable()[0][j].getDevelopDeck().get(size1).getIDtoString(); } if (tableCard.getTable()[1][j].getDevelopDeck().isEmpty()) { // If that card deck is empty! row12 += " "; row11 += " "; row10 += " "; row9 += AnsiColors.RED_BOLD + " EMPTY DECK " + AnsiColors.RESET; row8 += " "; row7 += " "; row01 += " "; } else { int size2 = tableCard.getTable()[1][j].getDevelopDeck().size() - 1; row12 += tableCard.getTable()[1][j].getDevelopDeck().get(size2).getvictorytostring(); row11 += tableCard.getTable()[1][j].getDevelopDeck().get(size2).getearntostring(); row10 += tableCard.getTable()[1][j].getDevelopDeck().get(size2).getpaytostring(); row9 += tableCard.getTable()[1][j].getDevelopDeck().get(size2).getcosttostring(); row8 += tableCard.getTable()[1][j].getDevelopDeck().get(size2).getleveltostring(); row7 += tableCard.getTable()[1][j].getDevelopDeck().get(size2).getColortoString(); row01 += tableCard.getTable()[1][j].getDevelopDeck().get(size2).getIDtoString(); } if (tableCard.getTable()[2][j].getDevelopDeck().isEmpty()) { row6 += " "; row5 += " "; row4 += " "; row3 += AnsiColors.RED_BOLD + " EMPTY DECK " + AnsiColors.RESET; row2 += " "; row1 += " "; row0 += " "; } else { int size3 = tableCard.getTable()[2][j].getDevelopDeck().size() - 1; row6 += tableCard.getTable()[2][j].getDevelopDeck().get(size3).getvictorytostring(); row5 += tableCard.getTable()[2][j].getDevelopDeck().get(size3).getearntostring(); row4 += tableCard.getTable()[2][j].getDevelopDeck().get(size3).getpaytostring(); row3 += tableCard.getTable()[2][j].getDevelopDeck().get(size3).getcosttostring(); row2 += tableCard.getTable()[2][j].getDevelopDeck().get(size3).getleveltostring(); row1 += tableCard.getTable()[2][j].getDevelopDeck().get(size3).getColortoString(); row0 += tableCard.getTable()[2][j].getDevelopDeck().get(size3).getIDtoString(); } } /*for(int j = 0; j < 4 ;j++) { if (developmentCardTable.getTable()[0][j].getDevelopDeck().isEmpty()) { row18 += " "; row17 += " "; row16 += " "; row15 += AnsiColors.RED_BOLD + " EMPTY DECK " + AnsiColors.RESET; row14 += " "; row13 += " "; row02 += " "; } else { int size1 = developmentCardTable.getTable()[0][j].getDevelopDeck().size() - 1; //actual Dim of the Deck in the table row18 += developmentCardTable.getTable()[0][j].getDevelopDeck().get(size1).getvictorytostring(); row17 += developmentCardTable.getTable()[0][j].getDevelopDeck().get(size1).getearntostring(); row16 += developmentCardTable.getTable()[0][j].getDevelopDeck().get(size1).getpaytostring(); row15 += developmentCardTable.getTable()[0][j].getDevelopDeck().get(size1).getcosttostring(); row14 += developmentCardTable.getTable()[0][j].getDevelopDeck().get(size1).getleveltostring(); row13 += developmentCardTable.getTable()[0][j].getDevelopDeck().get(size1).getColortoString(); row02 += developmentCardTable.getTable()[0][j].getDevelopDeck().get(size1).getIDtoString(); } if (developmentCardTable.getTable()[1][j].getDevelopDeck().isEmpty()) { // If that card deck is empty! row12 += " "; row11 += " "; row10 += " "; row9 += AnsiColors.RED_BOLD + " EMPTY DECK " + AnsiColors.RESET; row8 += " "; row7 += " "; row01 += " "; } else { int size2 = developmentCardTable.getTable()[1][j].getDevelopDeck().size() - 1; row12 += developmentCardTable.getTable()[1][j].getDevelopDeck().get(size2).getvictorytostring(); row11 += developmentCardTable.getTable()[1][j].getDevelopDeck().get(size2).getearntostring(); row10 += developmentCardTable.getTable()[1][j].getDevelopDeck().get(size2).getpaytostring(); row9 += developmentCardTable.getTable()[1][j].getDevelopDeck().get(size2).getcosttostring(); row8 += developmentCardTable.getTable()[1][j].getDevelopDeck().get(size2).getleveltostring(); row7 += developmentCardTable.getTable()[1][j].getDevelopDeck().get(size2).getColortoString(); row01 += developmentCardTable.getTable()[1][j].getDevelopDeck().get(size2).getIDtoString(); } if (developmentCardTable.getTable()[2][j].getDevelopDeck().isEmpty()) { row6 += " "; row5 += " "; row4 += " "; row3 += AnsiColors.RED_BOLD + " EMPTY DECK " + AnsiColors.RESET; row2 += " "; row1 += " "; row0 += " "; } else { int size3 = developmentCardTable.getTable()[2][j].getDevelopDeck().size() - 1; row6 += developmentCardTable.getTable()[2][j].getDevelopDeck().get(size3).getvictorytostring(); row5 += developmentCardTable.getTable()[2][j].getDevelopDeck().get(size3).getearntostring(); row4 += developmentCardTable.getTable()[2][j].getDevelopDeck().get(size3).getpaytostring(); row3 += developmentCardTable.getTable()[2][j].getDevelopDeck().get(size3).getcosttostring(); row2 += developmentCardTable.getTable()[2][j].getDevelopDeck().get(size3).getleveltostring(); row1 += developmentCardTable.getTable()[2][j].getDevelopDeck().get(size3).getColortoString(); row0 += developmentCardTable.getTable()[2][j].getDevelopDeck().get(size3).getIDtoString(); } }*/ for(int i = 0; i < 4 ; i++){ if(!getAvailable[0][i]){ //if(!available[0][i]){ System.out.print(AnsiColors.RED_BOLD+"CARD ("+0+","+i+") "+AnsiColors.RESET); }else { System.out.print("CARD ("+0+","+i+") "); } } System.out.print("\n"); System.out.println("โ”Œ---------------------โ” โ”Œ----------------------โ” โ”Œ------------------------โ” โ”Œ-----------------------โ” "); System.out.println(row02); System.out.println(row13); System.out.println(row14); System.out.println(row15); System.out.println(row16); System.out.println(row17); System.out.println(row18); System.out.println("โ””---------------------โ”˜ โ””---------------------โ”˜ โ””-----------------------โ”˜ โ””----------------------โ”˜ "); System.out.println("\n"); for(int i = 0; i <4 ; i++){ if(!getAvailable[1][i]){ //if(!available[1][i]){ System.out.print(AnsiColors.RED_BOLD+"CARD ("+1+","+i+") "+AnsiColors.RESET); }else { System.out.print("CARD ("+1+","+i+") "); } } System.out.println("\n"); System.out.println("โ”Œ--------------------โ” โ”Œ---------------------โ” โ”Œ---------------------โ” โ”Œ----------------------โ” "); System.out.println(row01); System.out.println(row7); System.out.println(row8); System.out.println(row9); System.out.println(row10); System.out.println(row11); System.out.println(row12); System.out.println("โ””--------------------โ”˜ โ””---------------------โ”˜ โ””---------------------โ”˜ โ””-----------------------โ”˜ "); System.out.println("\n"); for(int i = 0; i < 4 ; i++){ if(!getAvailable[2][i]){ //if(!available[2][i]){ System.out.print(AnsiColors.RED_BOLD+"CARD ("+2+","+i+") "+AnsiColors.RESET); }else { System.out.print("CARD ("+2+","+i+") "); } } System.out.println("\n"); System.out.println("โ”Œ--------------------โ” โ”Œ----------------------โ” โ”Œ----------------------โ” โ”Œ----------------------โ” "); System.out.println(row0); System.out.println(row1); System.out.println(row2); System.out.println(row3); System.out.println(row4); System.out.println(row5); System.out.println(row6); System.out.println("โ””--------------------โ”˜ โ””----------------------โ”˜ โ””------------------------โ”˜ โ””------------------------โ”˜ "); } }
50.539801
144
0.530246
4bbacaee7dfb61a5aefccbc9efc6c1e2cb1513a5
643
package org.metaborg.spoofax.core.language.dialect; import org.apache.commons.vfs2.FileObject; import org.metaborg.core.language.IdentificationFacet; import rx.functions.Func1; public class MetaFileIdentifier implements Func1<FileObject, Boolean> { private final IdentificationFacet identification; public MetaFileIdentifier(IdentificationFacet identification) { this.identification = identification; } @Override public Boolean call(FileObject resource) { if(DialectIdentifier.metaResource(resource) != null) { return identification.identify(resource); } return false; } }
27.956522
71
0.74339
f94ae2a2166c08056f9f2cc831387f2828e70f48
8,530
/** * Copyright (C) 2014 OpenTravel Alliance ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.opentravel.schemacompiler.model; import org.opentravel.schemacompiler.event.ModelEvent; import org.opentravel.schemacompiler.event.ModelEventBuilder; import org.opentravel.schemacompiler.event.ModelEventType; import org.opentravel.schemacompiler.model.TLEnumValue.EnumValueListManager; import org.opentravel.schemacompiler.version.Versioned; import java.util.Comparator; import java.util.List; /** * Abstract base class for the open and closed enumeration types. * * @author S. Livezey */ public abstract class TLAbstractEnumeration extends TLLibraryMember implements TLVersionedExtensionOwner, TLDocumentationOwner { private String name; private TLExtension extension; private TLDocumentation documentation; private EnumValueListManager enumValueManager = new EnumValueListManager( this ); /** * Returns the value of the 'name' field. * * @return String */ public String getName() { return name; } /** * Assigns the value of the 'name' field. * * @param name the field value to assign */ public void setName(String name) { ModelEvent<?> event = new ModelEventBuilder( ModelEventType.NAME_MODIFIED, this ).setOldValue( this.name ) .setNewValue( name ).buildEvent(); this.name = name; publishEvent( event ); } /** * @see org.opentravel.schemacompiler.model.NamedEntity#getLocalName() */ @Override public String getLocalName() { return getName(); } /** * @see org.opentravel.schemacompiler.version.Versioned#getVersion() */ @Override public String getVersion() { AbstractLibrary owningLibrary = getOwningLibrary(); String version = null; if (owningLibrary instanceof TLLibrary) { version = ((TLLibrary) owningLibrary).getVersion(); } return version; } /** * @see org.opentravel.schemacompiler.version.Versioned#getVersionScheme() */ @Override public String getVersionScheme() { AbstractLibrary owningLibrary = getOwningLibrary(); String versionScheme = null; if (owningLibrary instanceof TLLibrary) { versionScheme = ((TLLibrary) owningLibrary).getVersionScheme(); } return versionScheme; } /** * @see org.opentravel.schemacompiler.version.Versioned#getBaseNamespace() */ @Override public String getBaseNamespace() { AbstractLibrary owningLibrary = getOwningLibrary(); String baseNamespace; if (owningLibrary instanceof TLLibrary) { baseNamespace = ((TLLibrary) owningLibrary).getBaseNamespace(); } else { baseNamespace = getNamespace(); } return baseNamespace; } /** * @see org.opentravel.schemacompiler.version.Versioned#isLaterVersion(org.opentravel.schemacompiler.version.Versioned) */ @Override public boolean isLaterVersion(Versioned otherVersionedItem) { boolean result = false; if ((otherVersionedItem != null) && otherVersionedItem.getClass().equals( this.getClass() ) && (this.getOwningLibrary() != null) && (otherVersionedItem.getOwningLibrary() != null) && (this.getLocalName() != null) && this.getLocalName().equals( otherVersionedItem.getLocalName() )) { result = this.getOwningLibrary().isLaterVersion( otherVersionedItem.getOwningLibrary() ); } return result; } /** * @see org.opentravel.schemacompiler.model.TLExtensionOwner#getExtension() */ @Override public TLExtension getExtension() { return extension; } /** * @see org.opentravel.schemacompiler.model.TLExtensionOwner#setExtension(org.opentravel.schemacompiler.model.TLExtension) */ @Override public void setExtension(TLExtension extension) { if (extension != this.extension) { // Even though there is only one extension, send to events so that all extension owners // behave the same (as if there is a list of multiple extensions). if (this.extension != null) { ModelEvent<?> event = new ModelEventBuilder( ModelEventType.EXTENDS_REMOVED, this ) .setAffectedItem( this.extension ).buildEvent(); this.extension.setOwner( null ); this.extension = null; publishEvent( event ); } if (extension != null) { ModelEvent<?> event = new ModelEventBuilder( ModelEventType.EXTENDS_ADDED, this ) .setAffectedItem( extension ).buildEvent(); extension.setOwner( this ); this.extension = extension; publishEvent( event ); } } } /** * @see org.opentravel.schemacompiler.model.TLDocumentationOwner#getDocumentation() */ public TLDocumentation getDocumentation() { return documentation; } /** * @see org.opentravel.schemacompiler.model.TLDocumentationOwner#setDocumentation(org.opentravel.schemacompiler.model.TLDocumentation) */ public void setDocumentation(TLDocumentation documentation) { if (documentation != this.documentation) { ModelEvent<?> event = new ModelEventBuilder( ModelEventType.DOCUMENTATION_MODIFIED, this ) .setOldValue( this.documentation ).setNewValue( documentation ).buildEvent(); if (documentation != null) { documentation.setOwner( this ); } if (this.documentation != null) { this.documentation.setOwner( null ); } this.documentation = documentation; publishEvent( event ); } } /** * Returns the value of the 'values' field. * * @return List&lt;TLEnumValue&gt; */ public List<TLEnumValue> getValues() { return enumValueManager.getChildren(); } /** * Adds a <code>TLEnumValue</code> to the current list. * * @param value the enumeration value to add */ public void addValue(TLEnumValue value) { enumValueManager.addChild( value ); } /** * Adds a <code>TLEnumValue</code> element to the current list. * * @param index the index at which the given indicator should be added * @param value the enumeration value to add * @throws IndexOutOfBoundsException thrown if the index is out of range (index &lt; 0 || index &gt; size()) */ public void addValue(int index, TLEnumValue value) { enumValueManager.addChild( index, value ); } /** * Removes a <code>TLEnumValue</code> from the current list. * * @param value the enumeration value to remove */ public void removeValue(TLEnumValue value) { enumValueManager.removeChild( value ); } /** * Moves this value up by one position in the list. If the value is not owned by this object or it is already at the * front of the list, this method has no effect. * * @param value the value to move */ public void moveUp(TLEnumValue value) { enumValueManager.moveUp( value ); } /** * Moves this value down by one position in the list. If the value is not owned by this object or it is already at * the end of the list, this method has no effect. * * @param value the value to move */ public void moveDown(TLEnumValue value) { enumValueManager.moveDown( value ); } /** * Sorts the list of values using the comparator provided. * * @param comparator the comparator to use when sorting the list */ public void sortValues(Comparator<TLEnumValue> comparator) { enumValueManager.sortChildren( comparator ); } }
32.934363
138
0.644549
e17b12e442144bc8fea9410a5922145e5b82fae6
2,251
package gov.nih.nci.evs.gobp.extract; import gov.nih.nci.evs.gobp.print.PrintOWL1; import gov.nih.nci.evs.owl.data.OWLKb; import java.io.IOException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import org.apache.log4j.Logger; public class ExtractBranch { private static org.apache.log4j.Logger logger = Logger .getLogger(gov.nih.nci.evs.gobp.extract.ExtractBranch.class); /** * Don't look at me like that. We are extracting BP from GO. We know we are extracting * BP and only BP. We also know that we want only internal roles - anything pointing to an outside * entity should be discarded * * Input - the pretty OWL we created from the source. * Output - a pretty branch of biological processes */ public static String extract(String owlFileLoc, String namespace, String focusConcept) throws IOException { //Take the focus concept and extract to a new ontology with that as the root String outputFileLoc; String path = owlFileLoc.substring(0, owlFileLoc.lastIndexOf(System.getProperty("file.separator"))); if (!owlFileLoc.startsWith("file")) { owlFileLoc = "file://" + owlFileLoc; } OWLKb owlkb = new OWLKb(owlFileLoc, namespace); DateFormat dateFormat = new SimpleDateFormat("yy.MM.dd.HHmm"); Date date = new Date(); String sDate = dateFormat.format(date); outputFileLoc = path + "/Extraction_" + sDate + ".owl"; //create a new ontology //read old ontology and find the root concept. owlkb.removeBranch("GO_0003674"); owlkb.removeBranch("GO_0005575"); owlkb.removeBranch("Deprecated"); //Get the descendants of the root and add each to the new ontology // owlkb.saveOntology(outputFileLoc); //Examine the old ontology and grab the axioms. Any role axioms only keep if domain and range are in the new ontology //print out the extraction logger.info("Extraction done. Printing to " + outputFileLoc); new PrintOWL1(owlkb, outputFileLoc, "./config/go_headerCode.txt"); // TODO // make // this // a // parameter return outputFileLoc; } public static void cleanBranches(OWLKb owlkb) { // remove any outgoing roles or references } }
31.263889
120
0.706353
01e26904026fd37d16375d5f79fb9d3130d768e6
9,459
/******************************************************************************* * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Stephan Herrmann - Contribution for bug 215139 *******************************************************************************/ package org.eclipse.jdt.internal.core.search; import org.eclipse.core.runtime.Path; import org.eclipse.jdt.core.IClassFile; import org.eclipse.jdt.core.ICompilationUnit; import org.eclipse.jdt.core.IJavaElement; import org.eclipse.jdt.core.IJavaProject; import org.eclipse.jdt.core.IPackageFragment; import org.eclipse.jdt.core.IPackageFragmentRoot; import org.eclipse.jdt.core.IType; import org.eclipse.jdt.core.JavaModelException; import org.eclipse.jdt.core.compiler.CharOperation; import org.eclipse.jdt.core.search.IJavaSearchScope; import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants; import org.eclipse.jdt.internal.compiler.env.AccessRestriction; import org.eclipse.jdt.internal.compiler.impl.CompilerOptions; import org.eclipse.jdt.internal.core.Openable; import org.eclipse.jdt.internal.core.PackageFragmentRoot; import org.eclipse.jdt.internal.core.util.HandleFactory; import org.eclipse.jdt.internal.core.util.HashtableOfArrayToObject; /** * Parent class for Type and Method NameMatchRequestor classes */ public abstract class NameMatchRequestorWrapper { // scope is needed to retrieve project path for external resource protected IJavaSearchScope scope; // in case of IJavaSearchScope defined by clients, use an HandleFactory instead private HandleFactory handleFactory; /** * Cache package fragment root information to optimize speed performance. */ private String lastPkgFragmentRootPath; private IPackageFragmentRoot lastPkgFragmentRoot; /** * Cache package handles to optimize memory. */ private HashtableOfArrayToObject packageHandles; private Object lastProject; private long complianceValue; public NameMatchRequestorWrapper(IJavaSearchScope scope) { this.scope = scope; if (!(scope instanceof AbstractJavaSearchScope)) { this.handleFactory = new HandleFactory(); } } /* (non-Javadoc) * @see org.eclipse.jdt.internal.core.search.IRestrictedAccessTypeRequestor#acceptType(int, char[], char[], char[][], java.lang.String, org.eclipse.jdt.internal.compiler.env.AccessRestriction) */ public IType getType(int modifiers, char[] packageName, char[] simpleTypeName, char[][] enclosingTypeNames, String path, AccessRestriction access) { IType type = null; try { if (this.handleFactory != null) { Openable openable = this.handleFactory.createOpenable(path, this.scope); if (openable == null) return type; switch(openable.getElementType()) { case IJavaElement.COMPILATION_UNIT: ICompilationUnit cu = (ICompilationUnit) openable; if (enclosingTypeNames != null && enclosingTypeNames.length > 0) { type = cu.getType(new String(enclosingTypeNames[0])); for (int j = 1, l = enclosingTypeNames.length; j < l; j++) { type = type.getType(new String(enclosingTypeNames[j])); } type = type.getType(new String(simpleTypeName)); } else { type = cu.getType(new String(simpleTypeName)); } break; case IJavaElement.CLASS_FILE: type = ((IClassFile) openable).getType(); break; } } else { int separatorIndex = path.indexOf(IJavaSearchScope.JAR_FILE_ENTRY_SEPARATOR); type = separatorIndex == -1 ? createTypeFromPath(path, new String(simpleTypeName), enclosingTypeNames) : createTypeFromJar(path, separatorIndex); } } catch (JavaModelException e) { } return type; } private IType createTypeFromJar(String resourcePath, int separatorIndex) throws JavaModelException { // Optimization: cache package fragment root handle and package handles if (this.lastPkgFragmentRootPath == null || this.lastPkgFragmentRootPath.length() > resourcePath.length() || !resourcePath.startsWith(this.lastPkgFragmentRootPath)) { String jarPath = resourcePath.substring(0, separatorIndex); IPackageFragmentRoot root = ((AbstractJavaSearchScope) this.scope).packageFragmentRoot(resourcePath, separatorIndex, jarPath); if (root == null) return null; this.lastPkgFragmentRootPath = jarPath; this.lastPkgFragmentRoot = root; this.packageHandles = new HashtableOfArrayToObject(5); } // create handle String classFilePath = resourcePath.substring(separatorIndex + 1); String[] simpleNames = new Path(classFilePath).segments(); String[] pkgName; int length = simpleNames.length - 1; if (length > 0) { pkgName = new String[length]; System.arraycopy(simpleNames, 0, pkgName, 0, length); } else { pkgName = CharOperation.NO_STRINGS; } IPackageFragment pkgFragment = (IPackageFragment) this.packageHandles.get(pkgName); if (pkgFragment == null) { pkgFragment = ((PackageFragmentRoot) this.lastPkgFragmentRoot).getPackageFragment(pkgName); // see https://bugs.eclipse.org/bugs/show_bug.cgi?id=317264 if (//$NON-NLS-1$ length == 5 && pkgName[4].equals("enum")) { IJavaProject proj = (IJavaProject) pkgFragment.getAncestor(IJavaElement.JAVA_PROJECT); if (!proj.equals(this.lastProject)) { String complianceStr = proj.getOption(CompilerOptions.OPTION_Source, true); this.complianceValue = CompilerOptions.versionToJdkLevel(complianceStr); this.lastProject = proj; } if (this.complianceValue >= ClassFileConstants.JDK1_5) return null; } this.packageHandles.put(pkgName, pkgFragment); } return pkgFragment.getClassFile(simpleNames[length]).getType(); } private IType createTypeFromPath(String resourcePath, String simpleTypeName, char[][] enclosingTypeNames) throws JavaModelException { // path to a file in a directory // Optimization: cache package fragment root handle and package handles int rootPathLength = -1; if (this.lastPkgFragmentRootPath == null || !(resourcePath.startsWith(this.lastPkgFragmentRootPath) && (rootPathLength = this.lastPkgFragmentRootPath.length()) > 0 && resourcePath.charAt(rootPathLength) == '/')) { PackageFragmentRoot root = (PackageFragmentRoot) ((AbstractJavaSearchScope) this.scope).packageFragmentRoot(resourcePath, /*not a jar*/ -1, /*no jar path*/ null); if (root == null) return null; this.lastPkgFragmentRoot = root; this.lastPkgFragmentRootPath = root.internalPath().toString(); this.packageHandles = new HashtableOfArrayToObject(5); } // create handle resourcePath = resourcePath.substring(this.lastPkgFragmentRootPath.length() + 1); String[] simpleNames = new Path(resourcePath).segments(); String[] pkgName; int length = simpleNames.length - 1; if (length > 0) { pkgName = new String[length]; System.arraycopy(simpleNames, 0, pkgName, 0, length); } else { pkgName = CharOperation.NO_STRINGS; } IPackageFragment pkgFragment = (IPackageFragment) this.packageHandles.get(pkgName); if (pkgFragment == null) { pkgFragment = ((PackageFragmentRoot) this.lastPkgFragmentRoot).getPackageFragment(pkgName); this.packageHandles.put(pkgName, pkgFragment); } String simpleName = simpleNames[length]; if (org.eclipse.jdt.internal.core.util.Util.isJavaLikeFileName(simpleName)) { ICompilationUnit unit = pkgFragment.getCompilationUnit(simpleName); int etnLength = enclosingTypeNames == null ? 0 : enclosingTypeNames.length; IType type = (etnLength == 0) ? unit.getType(simpleTypeName) : unit.getType(new String(enclosingTypeNames[0])); if (etnLength > 0) { for (int i = 1; i < etnLength; i++) { type = type.getType(new String(enclosingTypeNames[i])); } type = type.getType(simpleTypeName); } return type; } else if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(simpleName)) { IClassFile classFile = pkgFragment.getClassFile(simpleName); return classFile.getType(); } return null; } }
48.757732
221
0.635902
fb7467aad4a7014c464cbcf13610b2501c5879f8
3,186
package jetbrains.mps.debugger.api.lang.typesystem; /*Generated by MPS */ import jetbrains.mps.lang.typesystem.runtime.AbstractInferenceRule_Runtime; import jetbrains.mps.lang.typesystem.runtime.InferenceRule_Runtime; import org.jetbrains.mps.openapi.model.SNode; import jetbrains.mps.typesystem.inference.TypeCheckingContext; import jetbrains.mps.lang.typesystem.runtime.IsApplicableStatus; import jetbrains.mps.typesystem.inference.EquationInfo; import jetbrains.mps.lang.smodel.generator.smodelAdapter.SPropertyOperations; import org.jetbrains.mps.openapi.language.SAbstractConcept; import jetbrains.mps.smodel.builder.SNodeBuilder; import org.jetbrains.mps.openapi.language.SProperty; import jetbrains.mps.smodel.adapter.structure.MetaAdapterFactory; import org.jetbrains.mps.openapi.language.SConcept; public class typeof_DebuggerReference_InferenceRule extends AbstractInferenceRule_Runtime implements InferenceRule_Runtime { public typeof_DebuggerReference_InferenceRule() { } public void applyRule(final SNode debuggerReference, final TypeCheckingContext typeCheckingContext, IsApplicableStatus status) { { SNode _nodeToCheck_1029348928467 = debuggerReference; EquationInfo _info_12389875345 = new EquationInfo(_nodeToCheck_1029348928467, null, "r:31e73d62-e873-4ed6-bd22-16d8721ebfa3(jetbrains.mps.debugger.api.lang.typesystem)", "2526721715665562909", 0, null); typeCheckingContext.createEquation((SNode) typeCheckingContext.typeOf(_nodeToCheck_1029348928467, "r:31e73d62-e873-4ed6-bd22-16d8721ebfa3(jetbrains.mps.debugger.api.lang.typesystem)", "2526721715665547052", true), (SNode) createDebuggerType_uu2qih_a1a0c0a0b(SPropertyOperations.getString(debuggerReference, PROPS.debuggerName$HZD3)), _info_12389875345); } } public SAbstractConcept getApplicableConcept() { return CONCEPTS.DebuggerReference$vJ; } public IsApplicableStatus isApplicableAndPattern(SNode argument) { return new IsApplicableStatus(argument.getConcept().isSubConceptOf(getApplicableConcept()), null); } public boolean overrides() { return false; } private static SNode createDebuggerType_uu2qih_a1a0c0a0b(String p0) { SNodeBuilder n0 = new SNodeBuilder().init(CONCEPTS.DebuggerType$_e); n0.setProperty(PROPS.name$xEfR, p0); return n0.getResult(); } private static final class PROPS { /*package*/ static final SProperty debuggerName$HZD3 = MetaAdapterFactory.getProperty(0xfbc142795e2a4c87L, 0xa5d15f7061e6c456L, 0xf528808f912d151L, 0xf528808f912d155L, "debuggerName"); /*package*/ static final SProperty name$xEfR = MetaAdapterFactory.getProperty(0xfbc142795e2a4c87L, 0xa5d15f7061e6c456L, 0xf528808f912bd83L, 0x23a852e9c43c456dL, "name"); } private static final class CONCEPTS { /*package*/ static final SConcept DebuggerReference$vJ = MetaAdapterFactory.getConcept(0xfbc142795e2a4c87L, 0xa5d15f7061e6c456L, 0xf528808f912d151L, "jetbrains.mps.debugger.api.lang.structure.DebuggerReference"); /*package*/ static final SConcept DebuggerType$_e = MetaAdapterFactory.getConcept(0xfbc142795e2a4c87L, 0xa5d15f7061e6c456L, 0xf528808f912bd83L, "jetbrains.mps.debugger.api.lang.structure.DebuggerType"); } }
60.113208
359
0.821092
2d896d4c38912d6237862f97279cc20ead071b12
9,479
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.sling.adapter.annotations; import com.google.common.collect.ImmutableMap; import org.apache.sling.adapter.annotations.testing.adapters.AbstractNoOpAdapterFactory; import org.apache.sling.adapter.annotations.testing.adapters.DeprecatedAdapterFactory; import org.apache.sling.adapter.annotations.testing.adapters.InvalidNoAdaptablesAdapterFactory; import org.apache.sling.adapter.annotations.testing.adapters.InvalidEmptyAdapterFactory; import org.apache.sling.adapter.annotations.testing.adapters.InvalidNoAdaptersAdapterFactory; import org.apache.sling.adapter.annotations.testing.adapters.ShortToIntegerAndLongAdapterFactory; import org.apache.sling.adapter.annotations.testing.adapters.LongToIntegerIfFitsAdapterFactory; import org.apache.sling.adapter.annotations.testing.adapters.IntegerAndShortToLongAdapterFactory; import org.apache.sling.adapter.annotations.testing.adapters.TextLengthIfFitsAdapterFactory; import org.apache.sling.adapter.annotations.util.AppSlingClient; import org.apache.sling.adapter.annotations.util.Util; import org.apache.sling.api.SlingHttpServletRequest; import org.apache.sling.api.adapter.AdapterFactory; import org.apache.sling.api.resource.Resource; import org.apache.sling.testing.clients.ClientException; import org.apache.sling.testing.clients.osgi.OsgiConsoleClient; import org.apache.sling.testing.clients.util.JsonUtils; import org.codehaus.jackson.JsonNode; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.osgi.framework.Constants; import org.osgi.service.component.ComponentConstants; import java.io.IOException; import java.math.BigInteger; import java.net.URISyntaxException; import java.util.Arrays; import java.util.Collections; import java.util.Map; import java.util.concurrent.TimeoutException; import java.util.function.UnaryOperator; import static org.junit.Assert.assertEquals; public class ServicePropertiesIT implements AdapterAnnotationsIT { private static final String ADAPTER_CONDITION = "adapter.condition"; private static final String ADAPTER_DEPRECATED = "adapter.deprecated"; private static OsgiConsoleClient client; @BeforeClass public static void setUpOnce() throws InterruptedException, TimeoutException, ClientException, URISyntaxException { client = AppSlingClient.newSlingClient().adaptTo(OsgiConsoleClient.class); } @AfterClass public static void tearDown() throws IOException { if (client != null) { client.close(); } } @Override @Test public void testLongToIntegerIfFitsAdapterFactory() throws ClientException { assertProperties(LongToIntegerIfFitsAdapterFactory.class.getName(), properties -> properties .put(AdapterFactory.ADAPTABLE_CLASSES, Collections.singletonList(Long.class.getName())) .put(AdapterFactory.ADAPTER_CLASSES, Collections.singletonList(Integer.class.getName())) .put(ADAPTER_CONDITION, LongToIntegerIfFitsAdapterFactory.CONDITION)); } @Override @Test public void testTextLengthIfFitsAdapterFactory() throws ClientException { assertProperties(TextLengthIfFitsAdapterFactory.class.getName(), properties -> properties .put(AdapterFactory.ADAPTABLE_CLASSES, Arrays.asList(CharSequence.class.getName(), String.class.getName())) .put(AdapterFactory.ADAPTER_CLASSES, Arrays.asList( Short.class.getName(), Integer.class.getName(), Long.class.getName(), BigInteger.class.getName() )) .put(ADAPTER_CONDITION, TextLengthIfFitsAdapterFactory.CONDITION)); } @Override @Test public void testShortToIntegerAndLongAdapterFactory() throws ClientException { assertProperties(ShortToIntegerAndLongAdapterFactory.class.getName(), properties -> properties .put(AdapterFactory.ADAPTABLE_CLASSES, Collections.singletonList(Short.class.getName())) .put(AdapterFactory.ADAPTER_CLASSES, Arrays.asList(Integer.class.getName(), Long.class.getName()))); } @Override @Test public void testIntegerAndShortToLongAdapterFactory() throws ClientException { assertProperties(IntegerAndShortToLongAdapterFactory.class.getName(), properties -> properties .put(AdapterFactory.ADAPTABLE_CLASSES, Arrays.asList(Integer.class.getName(), Short.class.getName())) .put(AdapterFactory.ADAPTER_CLASSES, Collections.singletonList(Long.class.getName()))); } @Test public void testInvalidMissingAdaptablesAndAdaptersAdapter() throws ClientException { assertProperties(InvalidEmptyAdapterFactory.class.getName(), properties -> properties .put(ADAPTER_CONDITION, AbstractNoOpAdapterFactory.INVALID_CONFIGURATION_MESSAGE)); } @Test public void testInvalidMissingAdaptablesAdapter() throws ClientException { assertProperties(InvalidNoAdaptablesAdapterFactory.class.getName(), properties -> properties .put(ADAPTER_CONDITION, AbstractNoOpAdapterFactory.INVALID_CONFIGURATION_MESSAGE) .put(AdapterFactory.ADAPTER_CLASSES, Collections.singletonList(Void.class.getName()))); } @Test public void testInvalidMissingAdaptersAdapter() throws ClientException { assertProperties(InvalidNoAdaptersAdapterFactory.class.getName(), properties -> properties .put(ADAPTER_CONDITION, AbstractNoOpAdapterFactory.INVALID_CONFIGURATION_MESSAGE) .put(AdapterFactory.ADAPTABLE_CLASSES, Collections.singletonList(Void.class.getName()))); } @Override @Test public void testDeprecatedAdapterFactory() throws ClientException { assertProperties(DeprecatedAdapterFactory.class.getName(), properties -> properties .put(ADAPTER_DEPRECATED, true) .put(AdapterFactory.ADAPTABLE_CLASSES, Collections.singletonList(SlingHttpServletRequest.class.getName())) .put(AdapterFactory.ADAPTER_CLASSES, Collections.singletonList(Resource.class.getName()))); } @Override @Test public void testInvalidAdapterFactories() throws ClientException { assertProperties(InvalidEmptyAdapterFactory.class.getName(), properties -> properties .put(ADAPTER_CONDITION, AbstractNoOpAdapterFactory.INVALID_CONFIGURATION_MESSAGE)); assertProperties(InvalidNoAdaptablesAdapterFactory.class.getName(), properties -> properties .put(ADAPTER_CONDITION, AbstractNoOpAdapterFactory.INVALID_CONFIGURATION_MESSAGE) .put(AdapterFactory.ADAPTER_CLASSES, Collections.singletonList(Void.class.getName()))); assertProperties(InvalidNoAdaptersAdapterFactory.class.getName(), properties -> properties .put(ADAPTER_CONDITION, AbstractNoOpAdapterFactory.INVALID_CONFIGURATION_MESSAGE) .put(AdapterFactory.ADAPTABLE_CLASSES, Collections.singletonList(Void.class.getName()))); } private static void assertProperties(final String componentName, final UnaryOperator<ImmutableMap.Builder<String, Object>> properties) throws ClientException { final Map<String, Object> expected = properties.apply(ImmutableMap.<String, Object>builder() .put(ComponentConstants.COMPONENT_NAME, componentName) .put(Constants.SERVICE_SCOPE, Constants.SCOPE_BUNDLE)) .build(); assertEquals(expected, getNonDynamicPropertiesOfComponentService(componentName)); } private static Map<String, Object> getNonDynamicPropertiesOfComponentService(final String nameOrId) throws ClientException { final JsonNode componentJson = JsonUtils.getJsonNodeFromString( client.doGet("/system/console/components/" + nameOrId + ".json").getContent()); final JsonNode serviceJson = JsonUtils.getJsonNodeFromString( client.doGet("/system/console/services/" + getServiceIdFromComponentJson(componentJson) + ".json").getContent()); return Util.getNonDynamicPropertiesForService(serviceJson); } private static int getServiceIdFromComponentJson(final JsonNode componentJson) { final JsonNode props = componentJson.get("data").get(0).get("props"); for (final JsonNode prop : props) { if ("serviceId".equals(prop.get("key").getValueAsText())) { return Integer.parseInt(prop.get("value").getValueAsText()); } } throw new AssertionError("No service ID found"); } }
52.370166
135
0.743433