code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public void quit(){
mQuit=true;
interrupt();
}
| Forces this dispatcher to quit immediately. If any requests are still in the queue, they are not guaranteed to be processed. |
public TaggingData(){
cntxGenVector=new ArrayList<ContextGenerator>();
}
| Instantiates a new tagging data. |
protected void parseKeyBits() throws InvalidKeyException {
try {
DerInputStream in=new DerInputStream(getKey().toByteArray());
DerValue derValue=in.getDerValue();
if (derValue.tag != DerValue.tag_Sequence) {
throw new IOException("Not a SEQUENCE");
}
DerInputStream data=derValue.data;
n=RSAPrivateCrtKeyImpl.getBigInteger(data);
e=RSAPrivateCrtKeyImpl.getBigInteger(data);
if (derValue.data.available() != 0) {
throw new IOException("Extra data available");
}
}
catch ( IOException e) {
throw new InvalidKeyException("Invalid RSA public key",e);
}
}
| Parse the key. Called by X509Key. |
public void removeAllRenamingCallbacks(){
renamingCallbacks.clear();
}
| Removes all board renaming callbacks. |
private static List<Size> pickUpToThree(List<Size> sizes){
List<Size> result=new ArrayList<Size>();
Size largest=sizes.get(0);
result.add(largest);
Size lastSize=largest;
for ( Size size : sizes) {
double targetArea=Math.pow(.5,result.size()) * area(largest);
if (area(size) < targetArea) {
if (!result.contains(lastSize) && (targetArea - area(lastSize) < area(size) - targetArea)) {
result.add(lastSize);
}
else {
result.add(size);
}
}
lastSize=size;
if (result.size() == 3) {
break;
}
}
if (result.size() < 3 && !result.contains(lastSize)) {
result.add(lastSize);
}
return result;
}
| Given a list of sizes of a similar aspect ratio, it tries to pick evenly spaced out options. It starts with the largest, then tries to find one at 50% of the last chosen size for the subsequent size. |
public Days toStandardDays(){
checkYearsAndMonths("Days");
long millis=getMillis();
millis+=((long)getSeconds()) * DateTimeConstants.MILLIS_PER_SECOND;
millis+=((long)getMinutes()) * DateTimeConstants.MILLIS_PER_MINUTE;
millis+=((long)getHours()) * DateTimeConstants.MILLIS_PER_HOUR;
long days=millis / DateTimeConstants.MILLIS_PER_DAY;
days=FieldUtils.safeAdd(days,getDays());
days=FieldUtils.safeAdd(days,((long)getWeeks()) * ((long)DateTimeConstants.DAYS_PER_WEEK));
return Days.days(FieldUtils.safeToInt(days));
}
| Converts this period to a period in days assuming a 7 day week, 24 hour day, 60 minute hour and 60 second minute. <p> This method allows you to convert between different types of period. However to achieve this it makes the assumption that all weeks are 7 days, all days are 24 hours, all hours are 60 minutes and all minutes are 60 seconds. This is not true when daylight savings time is considered, and may also not be true for some unusual chronologies. However, it is included as it is a useful operation for many applications and business rules. <p> If the period contains years or months, an exception will be thrown. |
@Override public void processView(ViewEngineContext context) throws ViewEngineException {
try {
forwardRequest(context,"*.jsp","*.jspx");
}
catch ( ServletException|IOException e) {
throw new ViewEngineException(e);
}
}
| Forwards request to servlet container. |
public ClassOrInterfaceDeclaration addClass(String name,Modifier... modifiers){
ClassOrInterfaceDeclaration classOrInterfaceDeclaration=new ClassOrInterfaceDeclaration(Arrays.stream(modifiers).collect(Collectors.toCollection(null)),false,name);
getTypes().add(classOrInterfaceDeclaration);
classOrInterfaceDeclaration.setParentNode(this);
return classOrInterfaceDeclaration;
}
| Add a class to the types of this compilation unit |
public void registerParserCall(final ASTContainer astContainer){
{
final Long elapsedNanoSec=astContainer.getQueryParseTime();
if (elapsedNanoSec != null) {
parserStat.incrementNrCalls();
parserStat.addElapsed(elapsedNanoSec);
}
}
{
final Long elapsedNanoSec=astContainer.getResolveValuesTime();
if (elapsedNanoSec != null) {
resolveValuesStat.incrementNrCalls();
resolveValuesStat.addElapsed(elapsedNanoSec);
}
}
}
| Registers a call of the parser. |
public final void printLog(String path){
console.printLogToFile(path);
}
| Prints the log to a local file. |
public ListNode partition(ListNode head,int x){
if (head == null || head.next == null) return head;
ListNode dummy=new ListNode(0);
dummy.next=head;
ListNode p=dummy;
ListNode start=dummy;
while (p != null && p.next != null) {
if (p.next.val >= x) p=p.next;
else {
if (p == start) {
start=start.next;
p=p.next;
}
else {
ListNode tmp=p.next;
p.next=tmp.next;
tmp.next=start.next;
start.next=tmp;
start=tmp;
}
}
}
return dummy.next;
}
| Move greater and equal value nodes to tail |
@Deprecated public static int showConfirmDialog(String key,int mode,String propertyConfirmExit,int defaultOption,Object... i18nArgs){
return showConfirmDialog(ApplicationFrame.getApplicationFrame(),key,mode,propertyConfirmExit,defaultOption,true,i18nArgs);
}
| Shows a dialog and returns the return code of the dialog. |
public String parseApiKey(Element element){
return element.getText();
}
| Parse the api key xml element |
public static boolean isCglibProxyClass(Class<?> clazz){
return (clazz != null && isCglibProxyClassName(clazz.getName()));
}
| Check whether the specified class is a CGLIB-generated class. |
public void moveUp(double units){
mTempVec.setAll(WorldParameters.UP_AXIS);
mTempVec.rotateBy(mOrientation).normalize();
mTempVec.multiply(units);
mPosition.add(mTempVec);
if (mLookAtEnabled && mLookAtValid) {
mLookAt.add(mTempVec);
resetToLookAt();
}
markModelMatrixDirty();
}
| Utility method to move the specified number of units along the current up axis. This will also adjust the look at target (if a valid one is currently set). |
public static void putIntLE(long addr,int val){
if (UNALIGNED) UNSAFE.putInt(addr,Integer.reverseBytes(val));
else putIntByByte(addr,val,false);
}
| Stores given integer value assuming that value should be stored in little-endian byte order and native byte order is big-endian. Alignment aware. |
public Date parseDate(String str){
try {
return dateFormat.parse(str);
}
catch ( java.text.ParseException e) {
throw new RuntimeException(e);
}
}
| Parse the given string into Date object. |
public UpdateRackHeartbeat join(String extAddress,int extPort,String clusterId,String address,int port,int portBartender,String displayName,String serverHash,int seedIndex){
Objects.requireNonNull(extAddress);
Objects.requireNonNull(address);
ClusterHeartbeat cluster=_root.findCluster(clusterId);
if (cluster == null) {
cluster=_root.createCluster(clusterId);
log.fine("Heartbeat create new cluster " + clusterId);
}
boolean isSSL=false;
ServerHeartbeat server=cluster.createDynamicServer(address,port,isSSL);
ClusterTarget clusterTarget=null;
RackHeartbeat rack=server.getRack();
if (rack == null) {
rack=getRack(cluster,address);
server=rack.createServer(address,port,isSSL);
log.fine("join-server" + " int=" + address + ":"+ port+ ";"+ portBartender+ " "+ displayName+ " hash="+ serverHash+ " ext="+ extAddress+ ":"+ extPort+ " ("+ _serverSelf.getDisplayName()+ ")");
}
if (cluster != _serverSelf.getCluster()) {
server.toKnown();
clusterTarget=createClusterTarget(cluster);
if (clusterTarget.addServer(server)) {
}
}
server.setPortBartender(portBartender);
if (extAddress != null) {
_serverSelf.setSeedIndex(seedIndex);
_serverSelf.setLastSeedTime(CurrentTime.currentTime());
_serverSelf.update();
}
if (server.isSelf()) {
joinSelf(server,extAddress,extPort,address,port,serverHash);
}
server.clearConnectionFailTime();
server.update();
updateHeartbeats();
if (server.isSelf()) {
return null;
}
else if (clusterId.equals(_serverSelf.getClusterId())) {
return server.getRack().getUpdate();
}
else {
return _serverSelf.getRack().getUpdate();
}
}
| joinServer message to an external configured address from a new server, including SelfServer. External address discovery and dynamic server joins are powered by join server. |
public void actionPerformed(ActionEvent e){
Transferable transferable=InternalClipboard.getInstance().getContents(null);
if (!(transferable instanceof SubgraphSelection)) {
return;
}
SubgraphSelection selection=(SubgraphSelection)transferable;
DataFlavor flavor=new DataFlavor(SubgraphSelection.class,"Subgraph Selection");
try {
List modelList=(List)selection.getTransferData(flavor);
Point point=EditorUtils.getTopLeftPoint(modelList);
point.translate(50,50);
graphEditor().pasteSubsession(modelList,point);
}
catch ( Exception e1) {
throw new RuntimeException(e1);
}
}
| Copies a parentally closed selection of session nodes in the frontmost session editor to the clipboard. |
public static Script pydmlFromFile(String scriptFilePath){
return scriptFromFile(scriptFilePath,ScriptType.PYDML);
}
| Create a PYDML Script object based on a string path to a file. |
public RhythmGroup addOverlays(Collection<RhythmOverlay> overlays){
mOverlays.addAll(overlays);
if (mCurrentOverlayIndex == NO_OVERLAY) {
selectOverlay(0);
}
return this;
}
| Add multiple Rhythm overlays to this group |
private static Converter selectSlow(ConverterSet set,Class<?> type){
Converter[] converters=set.iConverters;
int length=converters.length;
Converter converter;
for (int i=length; --i >= 0; ) {
converter=converters[i];
Class<?> supportedType=converter.getSupportedType();
if (supportedType == type) {
return converter;
}
if (supportedType == null || (type != null && !supportedType.isAssignableFrom(type))) {
set=set.remove(i,null);
converters=set.iConverters;
length=converters.length;
}
}
if (type == null || length == 0) {
return null;
}
if (length == 1) {
return converters[0];
}
for (int i=length; --i >= 0; ) {
converter=converters[i];
Class<?> supportedType=converter.getSupportedType();
for (int j=length; --j >= 0; ) {
if (j != i && converters[j].getSupportedType().isAssignableFrom(supportedType)) {
set=set.remove(j,null);
converters=set.iConverters;
length=converters.length;
i=length - 1;
}
}
}
if (length == 1) {
return converters[0];
}
StringBuffer msg=new StringBuffer();
msg.append("Unable to find best converter for type \"");
msg.append(type.getName());
msg.append("\" from remaining set: ");
for (int i=0; i < length; i++) {
converter=converters[i];
Class<?> supportedType=converter.getSupportedType();
msg.append(converter.getClass().getName());
msg.append('[');
msg.append(supportedType == null ? null : supportedType.getName());
msg.append("], ");
}
throw new IllegalStateException(msg.toString());
}
| Returns the closest matching converter for the given type, but not very efficiently. |
private void validateNoAdditionalVolumes(VPlexStorageViewInfo storageView){
List<? extends BlockObject> bos=BlockObject.fetchAll(getDbClient(),volumesToValidate);
Set<String> storageViewWwns=storageView.getWwnToHluMap().keySet();
for ( BlockObject bo : bos) {
if (bo == null || bo.getInactive()) {
continue;
}
String boWwn=bo.getWWN();
if (NullColumnValueGetter.isNotNullValue(boWwn)) {
if (storageViewWwns.contains(boWwn)) {
storageViewWwns.remove(boWwn);
}
else {
log.info(String.format("Database volume/snap %s (%s) is not in StorageView [%s]",bo.getId(),bo.getWWN(),storageView.getName()));
}
}
}
for ( String wwn : storageViewWwns) {
getValidatorLogger().logDiff(id,"virtual-volume/snap WWN",ValidatorLogger.NO_MATCHING_ENTRY,wwn);
}
}
| Validates the hardware has no additional volumes than were passed in the volumesToValidate list. Uses the virtualVolumeWWNMap to retrieve the volume WWNs and match against hardware. |
public void testMoveRenameDirectorySourceAndDestinationMissingPartially() throws Exception {
create(igfsSecondary,paths(DIR,SUBDIR,SUBSUBDIR,DIR_NEW,SUBDIR_NEW),null);
create(igfs,paths(DIR,DIR_NEW),null);
igfs.rename(SUBSUBDIR,SUBSUBDIR_NEW);
checkExist(igfs,SUBDIR,SUBDIR_NEW);
checkExist(igfs,igfsSecondary,SUBSUBDIR_NEW);
checkNotExist(igfs,igfsSecondary,SUBSUBDIR);
}
| Test move and rename in case source and destination exist partially and the path being renamed is a directory. |
public void validateChangePathParams(URI volumeURI,ExportPathParams newParam){
BlockObject volume=BlockObject.fetch(_dbClient,volumeURI);
_log.info(String.format("Validating path parameters for volume %s (%s) new path parameters %s",volume.getLabel(),volume.getId(),newParam.toString()));
Map<ExportMask,ExportGroup> maskToGroupMap=ExportUtils.getExportMasks(volume,_dbClient);
for ( ExportGroup exportGroup : maskToGroupMap.values()) {
validateChangePathParams(volume.getStorageController(),exportGroup.getId(),volume,newParam);
}
}
| This routine is called by the API service to validate that the change path parameters call will succeed. It locates all the ExportGroups that are exporting the volume. |
public CircuitBreaker(){
failureConditions=new ArrayList<BiPredicate<Object,Throwable>>();
state.set(new ClosedState(this));
}
| Creates a Circuit that opens after a single failure, closes after a single success, and has no delay by default. |
public static int convertToLongArray(final byte[] vals,final long[] dest){
checkSource(vals.length,8);
checkDestination(vals.length,dest.length,8);
return convertToLongArrayInternal(vals,0,vals.length,dest,0);
}
| Converts <code>byte[]</code> to <code>long[]</code>, assuming big-endian byte order. |
protected void searchForAndLoadProperties(String propsFileName){
Properties tmpProperties=new Properties();
Properties includeProperties;
Properties localizedProperties;
boolean foundProperties=false;
if (Debug.debugging("locale")) {
java.util.Locale.setDefault(new java.util.Locale("pl","PL"));
}
if (Debug.debugging("showprogress")) {
updateProgress=true;
}
logger.fine("***** Searching for properties ****");
String propertyPrefix=PropUtils.getScopedPropertyPrefix(getPropertyPrefix());
if (DEBUG) {
logger.fine("Looking for " + propsFileName + " in Resources");
}
InputStream propsIn=getClass().getResourceAsStream(propsFileName);
if (propsIn == null && Environment.isApplet()) {
URL[] cba=new URL[1];
cba[0]=Environment.getApplet().getCodeBase();
URLClassLoader ucl=URLClassLoader.newInstance(cba);
propsIn=ucl.getResourceAsStream(propsFileName);
}
if (propsIn == null) {
propsIn=ClassLoader.getSystemResourceAsStream(propsFileName);
if (propsIn != null && DEBUG) {
logger.fine("Loading properties from System Resources: " + propsFileName);
}
}
else {
if (DEBUG) {
logger.fine("Loading properties from file " + propsFileName + " from package of class "+ getClass());
}
}
if (propsIn != null) {
foundProperties=PropUtils.loadProperties(tmpProperties,propsIn);
init(tmpProperties,"resources");
tmpProperties.clear();
}
if (!foundProperties && (Environment.isApplet() || DEBUG)) {
logger.fine("Unable to locate as resource: " + propsFileName);
}
if (Environment.isApplet()) {
Environment.init(getProperties());
return;
}
Properties systemProperties;
try {
systemProperties=System.getProperties();
}
catch ( java.security.AccessControlException ace) {
systemProperties=new Properties();
}
String configDirProperty=propertyPrefix + PropertyHandler.configDirProperty;
String openmapConfigDirectory=systemProperties.getProperty(configDirProperty);
if (openmapConfigDirectory == null) {
Vector<String> cps=Environment.getClasspathDirs();
String defaultExtraDir="share";
for ( String searchLoc : cps) {
File shareDir=new File(searchLoc,defaultExtraDir);
if (shareDir.exists()) {
openmapConfigDirectory=shareDir.getPath();
break;
}
}
}
Environment.addPathToClasspaths(openmapConfigDirectory);
if (DEBUG) {
logger.fine("PropertyHandler: Looking for " + propsFileName + " in configuration directory: "+ (openmapConfigDirectory == null ? "not set" : openmapConfigDirectory));
}
foundProperties|=PropUtils.loadProperties(tmpProperties,openmapConfigDirectory,propsFileName);
includeProperties=getIncludeProperties(tmpProperties.getProperty(propertyPrefix + includeProperty),tmpProperties);
merge(includeProperties,"include file properties",openmapConfigDirectory);
merge(tmpProperties,propsFileName,openmapConfigDirectory);
tmpProperties.clear();
merge(systemProperties,"system properties","system");
String userHomeDirectory=systemProperties.getProperty("user.home");
if (DEBUG) {
logger.fine("Looking for " + propsFileName + " in user's home directory: "+ userHomeDirectory);
}
foundProperties|=PropUtils.loadProperties(tmpProperties,userHomeDirectory,propsFileName);
if (DEBUG) {
logger.fine("***** Done with property search ****");
}
if (!foundProperties && !Environment.isApplet()) {
PropUtils.copyProperties(PropUtils.promptUserForProperties(),properties);
}
includeProperties=getIncludeProperties(tmpProperties.getProperty(propertyPrefix + includeProperty),tmpProperties);
merge(includeProperties,"include file properties",userHomeDirectory);
merge(tmpProperties,propsFileName,userHomeDirectory);
localizedProperties=getLocalizedProperties(tmpProperties.getProperty(propertyPrefix + localizedProperty),userHomeDirectory);
merge(localizedProperties,"localized properties",null);
Environment.init(getProperties());
}
| Look for a properties file as a resource in the classpath, in the config directory, and in the user's home directory, in that order. If any property is duplicated in any version, last one wins. |
public static <E extends Comparable<E>>boolean isIdentical(BinaryNode<E> node1,BinaryNode<E> node2){
if (node1 == null && node2 == null) return true;
if (node1 == null && node2 != null || (node1 != null && node2 == null)) return false;
if (node1.value == node2.value) {
return true && isIdentical(node1.left,node2.left) && isIdentical(node1.right,node2.right);
}
else {
return false;
}
}
| Checks whether two trees having their roots at node1 and node2 are identical or not. |
@Override public String execCommand(String containerName,String command) throws FatalDockerJSONException {
String output=execCommand(containerName,command,false);
if (output.contains("Permission denied")) {
logger.warn("[" + containerName + "] exec command in privileged mode : "+ command);
output=execCommand(containerName,command,true);
}
return output;
}
| Execute a shell conmmad into a container. Return the output as String |
public boolean isLocallyInitiated(){
boolean streamIsClient=(id % 2 == 1);
return connection.client == streamIsClient;
}
| Returns true if this stream was created by this peer. |
public static int value(String s){
return rcodes.getValue(s);
}
| Converts a String representation of an Rcode into its numeric value |
public boolean catchesAll(){
int size=size();
if (size == 0) {
return false;
}
Entry last=get(size - 1);
return last.getExceptionType().equals(CstType.OBJECT);
}
| Returns whether or not this instance ends with a "catch-all" handler. |
protected void onPlayerDestroyed(){
}
| Called when the player has been destroyed. |
public final boolean sendMessageAtFrontOfQueue(Message msg){
return mExec.sendMessageAtFrontOfQueue(msg);
}
| Enqueue a message at the front of the message queue, to be processed on the next iteration of the message loop. You will receive it in callback, in the thread attached to this handler. <b>This method is only for use in very special circumstances -- it can easily starve the message queue, cause ordering problems, or have other unexpected side-effects.</b> |
public InvalidOpenTypeException(){
super();
}
| An InvalidOpenTypeException with no detail message. |
public void reset(){
super.reset();
resetStreamSettings();
}
| Remove all settings including global settings such as <code>Locale</code>s and listeners, as well as stream settings. |
private boolean verifyEntry(final String entry,final int keyCode){
final String work;
if (keyCode == SWT.DEL) {
work=StringUtil.removeCharAt(this.text.getText(),this.text.getCaretPosition());
}
else if (keyCode == SWT.BS && this.text.getCaretPosition() == 0) {
work=StringUtil.removeCharAt(this.text.getText(),this.text.getCaretPosition() - 1);
}
else if (keyCode == 0) {
work=entry;
}
else {
work=StringUtil.insertString(this.text.getText(),entry,this.text.getCaretPosition());
}
try {
Double.parseDouble(work.replace(',','.'));
}
catch ( final NumberFormatException nfe) {
return false;
}
return true;
}
| Check if an entry is a float |
@Override public boolean accept(final IScope scope,final IShape source,final IShape a){
final IAgent agent=a.getAgent();
if (agent == source.getAgent()) {
return false;
}
return contains(scope,agent);
}
| Method accept() |
public ConfigurationData(BeanFactory beanFactory,TaskExecutor taskExecutor,TaskScheduler taskScheduler,boolean autoStart,StateMachineEnsemble<S,E> ensemble,List<StateMachineListener<S,E>> listeners,boolean securityEnabled,AccessDecisionManager transitionSecurityAccessDecisionManager,AccessDecisionManager eventSecurityAccessDecisionManager,SecurityRule eventSecurityRule,SecurityRule transitionSecurityRule,boolean verifierEnabled,StateMachineModelVerifier<S,E> verifier,String machineId,StateMachineMonitor<S,E> stateMachineMonitor){
this.beanFactory=beanFactory;
this.taskExecutor=taskExecutor;
this.taskScheduler=taskScheduler;
this.autoStart=autoStart;
this.ensemble=ensemble;
this.listeners=listeners;
this.securityEnabled=securityEnabled;
this.transitionSecurityAccessDecisionManager=transitionSecurityAccessDecisionManager;
this.eventSecurityAccessDecisionManager=eventSecurityAccessDecisionManager;
this.eventSecurityRule=eventSecurityRule;
this.transitionSecurityRule=transitionSecurityRule;
this.verifierEnabled=verifierEnabled;
this.verifier=verifier;
this.machineId=machineId;
this.stateMachineMonitor=stateMachineMonitor;
}
| Instantiates a new state machine configuration config data. |
public static void logServiceException(HttpServlet servlet,ServiceException e){
if (e.getResponseBody() != null) {
servlet.log(e.getMessage() + " " + e.getHttpErrorCodeOverride()+ " "+ e.getResponseContentType()+ ": "+ e.getResponseBody(),e);
}
}
| Logs an exception in a convenient format, using the log method of a servlet context. |
public Object jjtAccept(PartitionParserVisitor visitor,Object data){
return visitor.visit(this,data);
}
| Accept the visitor. |
public static void e(String tag,String msg,Throwable tr){
println(ERROR,tag,msg,tr);
}
| Prints a message at ERROR priority. |
public static Socket createSocket(String server,int port,long timeout) throws IOException {
SocketWrapper socketWrapper=new SocketWrapper();
socketWrapper.server=server;
socketWrapper.port=port;
Object sync=new Object();
Thread socketThread=new Thread(new SocketRunnable(socketWrapper,sync));
socketThread.setDaemon(true);
Thread timeoutThread=new Thread(new TimeoutRunnable(sync,timeout * 1000));
timeoutThread.setDaemon(true);
timeoutThread.start();
socketThread.start();
synchronized (sync) {
if (socketWrapper.socket == null) {
try {
sync.wait(timeout * 1000);
}
catch ( InterruptedException e) {
logger.trace("",e);
}
}
}
timeoutThread.interrupt();
socketThread.interrupt();
socketWrapper.valid=false;
if (socketWrapper.getSocket() == null && socketWrapper.exception != null) {
throw socketWrapper.exception;
}
else if (socketWrapper.getSocket() == null) {
throw new TimeoutException();
}
return socketWrapper.getSocket();
}
| Creates a new AsyncSocket object. |
private void writeToken(AuthProvider auth){
AccessGrant accessGrant=auth.getAccessGrant();
String key=accessGrant.getKey();
String secret=accessGrant.getSecret();
String providerid=accessGrant.getProviderId();
Map<String,Object> attributes=accessGrant.getAttributes();
Editor edit=PreferenceManager.getDefaultSharedPreferences(getContext()).edit();
edit.putString(mProviderName.toString() + " key",key);
edit.putString(mProviderName.toString() + " secret",secret);
edit.putString(mProviderName.toString() + " providerid",providerid);
if (attributes != null) {
for ( Map.Entry entry : attributes.entrySet()) {
System.out.println(entry.getKey() + ", " + entry.getValue());
}
for ( String s : attributes.keySet()) {
edit.putString(mProviderName.toString() + "attribute " + s,String.valueOf(attributes.get(s)));
}
}
edit.apply();
}
| Internal Method to create new File in internal memory for each provider and save accessGrant |
public CompositeListener(String name){
this.name=name;
}
| Pass in a Listener name that allows you to differentiate this listener from others |
public boolean use(Player player,Item tool){
if (tool.getName() == "shovel") {
return super.use(player);
}
return false;
}
| Action to take when player uses a shovel |
public static void load(){
loaded=true;
if (!saveFile.exists()) return;
try {
String json=Files.toString(saveFile,charset);
Type type=new TypeToken<Map<UUID,String>>(){
private static final long serialVersionUID=1L;
}
.getType();
map=gson.fromJson(json,type);
}
catch ( JsonSyntaxException e) {
SpongeImpl.getLogger().error("Could not parse username cache file as valid json, deleting file",e);
saveFile.delete();
}
catch ( IOException e) {
SpongeImpl.getLogger().error("Failed to read username cache file from disk, deleting file",e);
saveFile.delete();
}
finally {
if (map == null) {
map=Maps.newHashMap();
}
}
}
| Load the cache from file |
public static double cdf(double z,double[] x){
int[] indices=new int[x.length];
HeapSort.sort(x,indices);
return cdf(z,x,indices);
}
| compute the cumulative probability Pr(x <= z) for a given z and a distribution of x |
public GeoPoint createSurfacePoint(final Vector vector){
return createSurfacePoint(vector.x,vector.y,vector.z);
}
| Compute a GeoPoint that's scaled to actually be on the planet surface. |
public DefaultLineTagDefinition(String title,TagDictionary<AbstractInlineTagDefinition> inlineTags){
this.inlineTags=inlineTags;
setTitles(title);
}
| Creates simple line tag, which consists only of the tag title and a description by default. The description supports the given inline tags. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:57:09.921 -0500",hash_original_method="B47D14DD952D3505364B334F55BDAD78",hash_generated_method="010165353A43B510E9FC39273C78378A") public boolean allowsCoreThreadTimeOut(){
return allowCoreThreadTimeOut;
}
| Returns true if this pool allows core threads to time out and terminate if no tasks arrive within the keepAlive time, being replaced if needed when new tasks arrive. When true, the same keep-alive policy applying to non-core threads applies also to core threads. When false (the default), core threads are never terminated due to lack of incoming tasks. |
void reset(){
initColumns();
_primaryJoinersChkUp=null;
_primaryJoinersChkDel=null;
_primaryJoinersDoUp=null;
_primaryJoinersDoDel=null;
_primaryJoinersDoNull=null;
_secondaryJoiners=null;
}
| Resets the internals of this FKEnforcer (for post-table modification) |
@Override protected void processCommittedData(T stitchedFileMetaData){
try {
mergeOutputFile(stitchedFileMetaData);
}
catch ( IOException e) {
throw new RuntimeException("Unable to merge file: " + stitchedFileMetaData.getStitchedFileRelativePath(),e);
}
}
| Stitches the output file when all blocks for that file are commited |
protected VoteResponse handleVote(VoteRequest request){
if (request.term() < context.getTerm()) {
LOGGER.debug("{} - Rejected {}: candidate's term is less than the current term",context.getCluster().member().address(),request);
return VoteResponse.builder().withStatus(Response.Status.OK).withTerm(context.getTerm()).withVoted(false).build();
}
else if (context.getLeader() != null) {
LOGGER.debug("{} - Rejected {}: leader already exists",context.getCluster().member().address(),request);
return VoteResponse.builder().withStatus(Response.Status.OK).withTerm(context.getTerm()).withVoted(false).build();
}
else if (!context.getClusterState().getRemoteMemberStates().stream().<Integer>map(null).collect(Collectors.toSet()).contains(request.candidate())) {
LOGGER.debug("{} - Rejected {}: candidate is not known to the local member",context.getCluster().member().address(),request);
return VoteResponse.builder().withStatus(Response.Status.OK).withTerm(context.getTerm()).withVoted(false).build();
}
else if (context.getLastVotedFor() == 0) {
if (isLogUpToDate(request.logIndex(),request.logTerm(),request)) {
context.setLastVotedFor(request.candidate());
return VoteResponse.builder().withStatus(Response.Status.OK).withTerm(context.getTerm()).withVoted(true).build();
}
else {
return VoteResponse.builder().withStatus(Response.Status.OK).withTerm(context.getTerm()).withVoted(false).build();
}
}
else if (context.getLastVotedFor() == request.candidate()) {
LOGGER.debug("{} - Accepted {}: already voted for {}",context.getCluster().member().address(),request,context.getCluster().member(context.getLastVotedFor()).address());
return VoteResponse.builder().withStatus(Response.Status.OK).withTerm(context.getTerm()).withVoted(true).build();
}
else {
LOGGER.debug("{} - Rejected {}: already voted for {}",context.getCluster().member().address(),request,context.getCluster().member(context.getLastVotedFor()).address());
return VoteResponse.builder().withStatus(Response.Status.OK).withTerm(context.getTerm()).withVoted(false).build();
}
}
| Handles a vote request. |
public boolean useClientAuth(){
return jcbClientAuth.isSelected();
}
| User wants to use SSL client authentication? |
public void addType(final BaseType baseType){
Preconditions.checkNotNull(baseType,"IE02764: Base type can not be null.");
createTypeNode(baseType,containedRelation,containedRelationMap);
}
| Adds a new type to the dependence graph. Note: the members must be added separately since this method won't create edges, but only type nodes. Only the the given base type itself is inserted into the graph, i.e. the contained types are not added recursively. |
final private boolean doMove(Move move){
Position pos=game.pos;
MoveGen.MoveList moves=new MoveGen().pseudoLegalMoves(pos);
MoveGen.removeIllegal(pos,moves);
int promoteTo=move.promoteTo;
for (int mi=0; mi < moves.size; mi++) {
Move m=moves.m[mi];
if ((m.from == move.from) && (m.to == move.to)) {
if ((m.promoteTo != Piece.EMPTY) && (promoteTo == Piece.EMPTY)) {
promoteMove=m;
gui.requestPromotePiece();
return false;
}
if (m.promoteTo == promoteTo) {
String strMove=TextIO.moveToString(pos,m,false);
game.processString(strMove);
return true;
}
}
}
gui.reportInvalidMove(move);
return false;
}
| Move a piece from one square to another. |
public void paintMenuItemBorder(SynthContext context,Graphics g,int x,int y,int w,int h){
paintBorder(context,g,x,y,w,h,null);
}
| Paints the border of a menu item. |
@UiThread int nextViewId(Context context){
return getFragment(context).nextViewId();
}
| Get the next (mosby internal) view id |
GenericObjectType(@Nonnull String variable){
this(variable,(ReferenceType)null);
}
| Create a GenericObjectType that represents a Simple Type Variable or a simple wildcard with no extensions |
public static String millisecondsToString(long time){
int seconds=(int)((time / 1000) % 60);
int minutes=(int)((time / 60000) % 60);
int hours=(int)((time / 3600000) % 24);
int days=(int)((time / 3600000) / 24);
StringBuilder builder=new StringBuilder();
builder.append(days);
builder.append("d ");
builder.append(hours);
builder.append("h ");
builder.append(minutes);
builder.append("m ");
builder.append(seconds);
builder.append('s');
return builder.toString();
}
| Converts time in milliseconds to a <code>String</code> in the format HH:mm:ss. |
public void testGetF1Momentary(){
AbstractThrottle instance=new AbstractThrottleImpl();
boolean expResult=false;
boolean result=instance.getF1Momentary();
assertEquals(expResult,result);
}
| Test of getF1Momentary method, of class AbstractThrottle. |
public static List<URI> iteratorToList(URIQueryResultList itr){
List<URI> uris=new ArrayList<URI>();
for ( URI uri : itr) {
uris.add(uri);
}
return uris;
}
| Utility functions that returns the iterator entries as a list |
public UF3(int numberOfVariables){
super(numberOfVariables,2);
}
| Constructs a UF3 test problem with the specified number of decision variables. |
public byte[] encrypt(String passphrase,boolean production) throws HyperLedgerException {
try {
byte[] key=SCrypt.generate(passphrase.getBytes("UTF-8"),BITCOIN_SEED,16384,8,8,32);
SecretKeySpec keyspec=new SecretKeySpec(key,"AES");
Cipher cipher=Cipher.getInstance("AES/CBC/PKCS5Padding","BC");
cipher.init(Cipher.ENCRYPT_MODE,keyspec);
byte[] iv=cipher.getIV();
byte[] c=cipher.doFinal(serialize(production).getBytes());
byte[] result=new byte[iv.length + c.length];
System.arraycopy(iv,0,result,0,iv.length);
System.arraycopy(c,0,result,iv.length,c.length);
return result;
}
catch ( UnsupportedEncodingException|NoSuchAlgorithmException|NoSuchProviderException|NoSuchPaddingException|InvalidKeyException|IllegalBlockSizeException|BadPaddingException e) {
throw new HyperLedgerException(e);
}
}
| Encrypt this key with AES/CBC/PKCS5Padding. Useful if you decide to store it. |
public double computeInPlace(double... dataset){
checkArgument(dataset.length > 0,"Cannot calculate quantiles of an empty dataset");
if (containsNaN(dataset)) {
return NaN;
}
long numerator=(long)index * (dataset.length - 1);
int quotient=(int)LongMath.divide(numerator,scale,RoundingMode.DOWN);
int remainder=(int)(numerator - (long)quotient * scale);
selectInPlace(quotient,dataset,0,dataset.length - 1);
if (remainder == 0) {
return dataset[quotient];
}
else {
selectInPlace(quotient + 1,dataset,quotient + 1,dataset.length - 1);
return interpolate(dataset[quotient],dataset[quotient + 1],remainder,scale);
}
}
| Computes the quantile value of the given dataset, performing the computation in-place. |
public XObject execute(XPathContext xctxt) throws javax.xml.transform.TransformerException {
int context=getArg0AsNode(xctxt);
XObject val;
if (DTM.NULL != context) {
DTM dtm=xctxt.getDTM(context);
String qname=dtm.getNodeNameX(context);
val=(null == qname) ? XString.EMPTYSTRING : new XString(qname);
}
else {
val=XString.EMPTYSTRING;
}
return val;
}
| Execute the function. The function must return a valid object. |
public static ODataUri createODataCountEntitiesUri(String serviceRoot,String entitySetName){
CountPath$ countPath=CountPath$.MODULE$;
scala.Option<PathSegment> countPathOption=scala.Option.apply(countPath);
scala.Option<String> noString=scala.Option.apply(null);
EntityCollectionPath entityCollectionPath=new EntityCollectionPath(noString,countPathOption);
scala.Option<EntityCollectionPath> entityCollectionPathOption=scala.Option.apply(entityCollectionPath);
EntitySetPath entitySetPath=new EntitySetPath(entitySetName,entityCollectionPathOption);
List<QueryOption> queryOptions=new ArrayList<>();
ResourcePathUri resourcePathUri=new ResourcePathUri(entitySetPath,asScalaList(queryOptions));
return new ODataUri(serviceRoot,resourcePathUri);
}
| Create a test OData URI for /$count path with a given service root and entity set name. |
public static byte[] readBytes(File file) throws IOException {
byte[] bytes=new byte[(int)file.length()];
FileInputStream fileInputStream=new FileInputStream(file);
DataInputStream dis=new DataInputStream(fileInputStream);
try {
dis.readFully(bytes);
InputStream temp=dis;
dis=null;
temp.close();
}
finally {
closeWithWarning(dis);
}
return bytes;
}
| Reads the content of the file into a byte array. |
protected void paintTabArea(final Graphics g,final int tabPlacement,final int selectedIndex){
final int tabCount=tabPane.getTabCount();
final Rectangle iconRect=new Rectangle(), textRect=new Rectangle();
final Rectangle clipRect=g.getClipBounds();
for (int i=runCount - 1; i >= 0; i--) {
final int start=tabRuns[i];
final int next=tabRuns[(i == runCount - 1) ? 0 : i + 1];
final int end=(next != 0 ? next - 1 : tabCount - 1);
for (int j=start; j <= end; j++) {
if (j != selectedIndex && rects[j].intersects(clipRect)) {
paintTab(g,tabPlacement,rects,j,iconRect,textRect);
}
}
}
if (selectedIndex >= 0 && rects[selectedIndex].intersects(clipRect)) {
paintTab(g,tabPlacement,rects,selectedIndex,iconRect,textRect);
}
}
| Paints the tabs in the tab area. Invoked by paint(). The graphics parameter must be a valid <code>Graphics</code> object. Tab placement may be either: <code>JTabbedPane.TOP</code>, <code>JTabbedPane.BOTTOM</code>, <code>JTabbedPane.LEFT</code>, or <code>JTabbedPane.RIGHT</code>. The selected index must be a valid tabbed pane tab index (0 to tab count - 1, inclusive) or -1 if no tab is currently selected. The handling of invalid parameters is unspecified. |
public SVGOMFECompositeElement(String prefix,AbstractDocument owner){
super(prefix,owner);
initializeLiveAttributes();
}
| Creates a new SVGOMFECompositeElement object. |
public ResultSetSpy(StatementSpy parent,ResultSet realResultSet){
if (realResultSet == null) {
throw new IllegalArgumentException("Must provide a non null real ResultSet");
}
this.realResultSet=realResultSet;
this.parent=parent;
log=SpyLogFactory.getSpyLogDelegator();
reportReturn("new ResultSet");
}
| Create a new ResultSetSpy that wraps another ResultSet object, that logs all method calls, expceptions, etc. |
public DERExternal(ASN1ObjectIdentifier directReference,ASN1Integer indirectReference,ASN1Primitive dataValueDescriptor,int encoding,ASN1Primitive externalData){
setDirectReference(directReference);
setIndirectReference(indirectReference);
setDataValueDescriptor(dataValueDescriptor);
setEncoding(encoding);
setExternalContent(externalData.toASN1Primitive());
}
| Creates a new instance of DERExternal. See X.690 for more informations about the meaning of these parameters |
void doReps(ObjectOutputStream oout,ObjectInputStream oin,StreamBuffer sbuf,int nbatches,int ncycles) throws Exception {
for (int i=0; i < nbatches; i++) {
sbuf.reset();
for (int j=0; j < ncycles; j++) {
oout.writeLong(0);
}
oout.flush();
for (int j=0; j < ncycles; j++) {
oin.readLong();
}
}
}
| Run benchmark for given number of batches, with given number of cycles for each batch. |
public void addPlugInSingleRowFunction(String functionName,String className,String methodName,ConfigurationPlugInSingleRowFunction.ValueCache valueCache,ConfigurationPlugInSingleRowFunction.FilterOptimizable filterOptimizable) throws ConfigurationException {
addPlugInSingleRowFunction(functionName,className,methodName,valueCache,filterOptimizable,false);
}
| Add single-row function with configurations. |
public RenderedImage create(ParameterBlock paramBlock,RenderingHints renderHints){
StringBuffer msg=new StringBuffer();
if (!validateParameters(paramBlock,msg)) {
return null;
}
try {
SeekableStream in=(SeekableStream)paramBlock.getObjectParameter(0);
XTIFFImage image=new XTIFFImage(in,(TIFFDecodeParam)paramBlock.getObjectParameter(1),0);
return image;
}
catch ( Exception e) {
return null;
}
}
| Create an XTIFFImage with the given ParameterBlock if the XTIFFImage can handle the particular ParameterBlock. Otherwise, null image is returned. |
public Object clone(){
return new Area(this);
}
| Returns an exact copy of this <code>Area</code> object. |
@Override public int compareTo(EventInfoResource o){
return ComparisonChain.start().compare(eventId,o.eventId).compareFalseFirst(enabled,o.enabled).compare(bufferCapacity,o.bufferCapacity).compare(etype,o.etype).compare(eventDesc,o.eventDesc).compare(eventName,o.eventName).compare(moduleName,o.moduleName).compare(numOfEvents,o.numOfEvents).result();
}
| The natural order of this class is ascending on eventId and consistent with equals. |
public boolean sort(String inPackage){
if (isAddressSet) {
try {
switch (inPackage.charAt(0)) {
case 'V':
setSpeed(Integer.parseInt(inPackage.substring(1)));
break;
case 'X':
eStop();
break;
case 'F':
handleFunction(inPackage);
break;
case 'f':
forceFunction(inPackage.substring(1));
break;
case 'R':
setDirection(!inPackage.endsWith("0"));
break;
case 'r':
addressRelease();
break;
case 'd':
addressDispatch();
break;
case 'L':
addressRelease();
int addr=Integer.parseInt(inPackage.substring(1));
setAddress(addr,true);
break;
case 'S':
addressRelease();
addr=Integer.parseInt(inPackage.substring(1));
setAddress(addr,false);
break;
case 'E':
addressRelease();
requestEntryFromID(inPackage.substring(1));
break;
case 'C':
setLocoForConsistFunctions(inPackage.substring(1));
break;
case 'c':
setRosterLocoForConsistFunctions(inPackage.substring(1));
break;
case 'I':
idle();
break;
case 's':
handleSpeedStepMode(Integer.parseInt(inPackage.substring(1)));
break;
case 'm':
handleMomentary(inPackage.substring(1));
break;
case 'q':
handleRequest(inPackage.substring(1));
break;
}
}
catch (NullPointerException e) {
log.warn("No throttle frame to receive: " + inPackage);
return false;
}
try {
Thread.sleep(20);
}
catch (java.lang.InterruptedException ex) {
}
}
else {
switch (inPackage.charAt(0)) {
case 'L':
int addr=Integer.parseInt(inPackage.substring(1));
setAddress(addr,true);
break;
case 'S':
addr=Integer.parseInt(inPackage.substring(1));
setAddress(addr,false);
break;
case 'E':
requestEntryFromID(inPackage.substring(1));
break;
case 'C':
setLocoForConsistFunctions(inPackage.substring(1));
break;
case 'c':
setRosterLocoForConsistFunctions(inPackage.substring(1));
break;
default :
break;
}
}
if (inPackage.charAt(0) == 'Q') {
shutdownThrottle();
return false;
}
return true;
}
| Figure out what the received command means, where it has to go, and translate to a jmri method. |
public Set<String> classNames(){
return positiveExamplesByName.keySet();
}
| Gets the content items. |
protected boolean hasAttemptRemaining(){
return mCurrentRetryCount <= mMaxNumRetries;
}
| Returns true if this policy has attempts remaining, false otherwise. |
public DTMIterator iter() throws javax.xml.transform.TransformerException {
error(XPATHErrorResources.ER_CANT_CONVERT_TO_NODELIST,new Object[]{getTypeString()});
return null;
}
| Cast result object to a nodelist. Always issues an error. |
@Override public void remove(ConfuseStatus status,StatusList statusList){
statusList.removeInternal(status);
RPEntity entity=statusList.getEntity();
if (entity == null) {
return;
}
entity.sendPrivateText(NotificationType.SCENE_SETTING,"You are no longer confused.");
entity.remove("status_" + status.getName());
}
| removes a status |
public boolean isAutoRotateEnabled(){
return mAutoRotateEnabled;
}
| Returns whether auto-rotate is enabled. |
public static int skipWhitespace(String str,int pos){
while (pos < str.length()) {
int c=UTF16.charAt(str,pos);
if (!UCharacterProperty.isRuleWhiteSpace(c)) {
break;
}
pos+=UTF16.getCharCount(c);
}
return pos;
}
| Skip over a sequence of zero or more white space characters at pos. Return the index of the first non-white-space character at or after pos, or str.length(), if there is none. |
public static void display(Activity caller){
String versionStr=getVersionString(caller);
String aboutHeader=caller.getString(R.string.app_name) + " v" + versionStr;
View aboutView;
try {
aboutView=caller.getLayoutInflater().inflate(R.layout.about,null);
}
catch ( InflateException ie) {
Log.e(TAG,"Exception while inflating about box: " + ie.getMessage());
return;
}
AlertDialog.Builder builder=new AlertDialog.Builder(caller);
builder.setTitle(aboutHeader);
builder.setIcon(R.drawable.ic_launcher);
builder.setCancelable(true);
builder.setPositiveButton(R.string.ok,null);
builder.setView(aboutView);
builder.show();
}
| Displays the About box. An AlertDialog is created in the calling activity's context. <p> The box will disappear if the "OK" button is touched, if an area outside the box is touched, if the screen is rotated ... doing just about anything makes it disappear. |
public int addLoad(int n,CtClass type){
if (type.isPrimitive()) {
if (type == CtClass.booleanType || type == CtClass.charType || type == CtClass.byteType || type == CtClass.shortType || type == CtClass.intType) addIload(n);
else if (type == CtClass.longType) {
addLload(n);
return 2;
}
else if (type == CtClass.floatType) addFload(n);
else if (type == CtClass.doubleType) {
addDload(n);
return 2;
}
else throw new RuntimeException("void type?");
}
else addAload(n);
return 1;
}
| Appends an instruction for loading a value from the local variable at the index <code>n</code>. |
public void onDataActivity(int direction){
}
| Callback invoked when data activity state changes. |
public boolean isTopType(){
Type _declaredType=this.getDeclaredType();
return (_declaredType instanceof AnyType);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public Element create(String prefix,Document doc){
return new SVGOMTitleElement(prefix,(AbstractDocument)doc);
}
| Creates an instance of the associated element type. |
void createEntry(int hash,Object key,Object value,int bucketIndex){
table[bucketIndex]=new Entry(hash,key,value,table[bucketIndex]);
size++;
}
| Like addEntry except that this version is used when creating entries as part of Map construction or "pseudo-construction" (cloning, deserialization). This version needn't worry about resizing the table. Subclass overrides this to alter the behavior of HashMap(Map), clone, and readObject. |
@Override public Enumeration<Option> listOptions(){
Vector<Option> newVector=new Vector<Option>(4);
newVector.addElement(new Option("\tStart temperature","A",1,"-A <float>"));
newVector.addElement(new Option("\tNumber of runs","U",1,"-U <integer>"));
newVector.addElement(new Option("\tDelta temperature","D",1,"-D <float>"));
newVector.addElement(new Option("\tRandom number seed","R",1,"-R <seed>"));
newVector.addAll(Collections.list(super.listOptions()));
return newVector.elements();
}
| Returns an enumeration describing the available options. |
public static void addQueryListener(IQueryListener l){
InternalSearchUI.getInstance().addQueryListener(l);
}
| Registers the given listener to receive notification of changes to queries. The listener will be notified whenever a query has been added, removed, is starting or has finished. Has no effect if an identical listener is already registered. |
public static List<CoreLabel> toPostProcessedSequence(List<CoreLabel> charSequence){
List<CoreLabel> tokenSequence=new ArrayList<>();
StringBuilder originalToken=new StringBuilder();
StringBuilder currentToken=new StringBuilder();
CoreLabel stopSymbol=new CoreLabel();
stopSymbol.set(CharAnnotation.class,WHITESPACE);
stopSymbol.set(AnswerAnnotation.class,Operation.Whitespace.toString());
charSequence.add(stopSymbol);
for ( CoreLabel outputChar : charSequence) {
String text=outputChar.get(CharAnnotation.class);
String[] fields=outputChar.get(AnswerAnnotation.class).split(OP_DELIM);
Operation label;
try {
label=Operation.valueOf(fields[0]);
}
catch ( IllegalArgumentException e) {
System.err.printf("%s: WARNING Illegal operation %s/%s%n",ProcessorTools.class.getName(),text,fields[0]);
label=Operation.None;
}
if (label == Operation.Whitespace || (label == Operation.None && text.equals(WHITESPACE))) {
String original=originalToken.toString();
String[] outputTokens=currentToken.toString().split("\\s+");
for ( String tokenText : outputTokens) {
CoreLabel token=new CoreLabel();
token.setValue(tokenText);
token.setWord(tokenText);
token.set(OriginalTextAnnotation.class,original);
tokenSequence.add(token);
}
originalToken=new StringBuilder();
currentToken=new StringBuilder();
}
else {
originalToken.append(text);
if (label == Operation.None) {
currentToken.append(text);
}
else if (label == Operation.InsertAfter) {
assert fields.length == 2;
currentToken.append(text).append(fields[1]);
}
else if (label == Operation.InsertBefore) {
assert fields.length == 2;
currentToken.append(fields[1]).append(text);
}
else if (label == Operation.ToUpper) {
currentToken.append(text.toUpperCase());
}
else if (label == Operation.Delete) {
}
}
}
charSequence.remove(charSequence.size() - 1);
return tokenSequence;
}
| Convert a post-processed character sequence to a token sequence. |
@Override public void translate(final ITranslationEnvironment environment,final IInstruction instruction,final List<ReilInstruction> instructions) throws InternalTranslationException {
TranslationHelpers.checkTranslationArguments(environment,instruction,instructions,"cdq");
final long baseOffset=instruction.getAddress().toLong() * 0x100;
final String isolatedMsb=environment.getNextVariableString();
final String shiftedMsb=environment.getNextVariableString();
instructions.add(ReilHelpers.createAnd(baseOffset,OperandSize.DWORD,"eax",OperandSize.DWORD,"2147483648",OperandSize.DWORD,isolatedMsb));
instructions.add(ReilHelpers.createBsh(baseOffset + 1,OperandSize.DWORD,isolatedMsb,OperandSize.DWORD,"-31",OperandSize.DWORD,shiftedMsb));
instructions.add(ReilHelpers.createSub(baseOffset + 2,OperandSize.DWORD,"0",OperandSize.DWORD,shiftedMsb,OperandSize.DWORD,"edx"));
}
| Translates a CDQ instruction to REIL code. |
public static void printReport(File file,String name,boolean isPreview,String fontName,boolean isBuildReport,String logoURL,String printerName,String orientation,int fontSize){
HardcopyWriter writer=null;
Frame mFrame=new Frame();
boolean isLandScape=false;
boolean printHeader=true;
double margin=.5;
Dimension pagesize=null;
if (orientation.equals(Setup.LANDSCAPE)) {
margin=.65;
isLandScape=true;
}
if (orientation.equals(Setup.HANDHELD) || orientation.equals(Setup.HALFPAGE)) {
printHeader=false;
pagesize=new Dimension(TrainCommon.getPageSize(orientation).width + TrainCommon.PAPER_MARGINS.width,TrainCommon.getPageSize(orientation).height + TrainCommon.PAPER_MARGINS.height);
}
try {
writer=new HardcopyWriter(mFrame,name,fontSize,margin,margin,.5,.5,isPreview,printerName,isLandScape,printHeader,pagesize);
}
catch ( HardcopyWriter.PrintCanceledException ex) {
log.debug("Print cancelled");
return;
}
if (!fontName.equals("")) {
writer.setFontName(fontName);
}
BufferedReader in=null;
try {
in=new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
}
catch ( FileNotFoundException e) {
log.error("Build file doesn't exist");
writer.close();
return;
}
catch ( UnsupportedEncodingException e) {
log.error("Doesn't support UTF-8 encoding");
writer.close();
return;
}
String line;
if (!isBuildReport && logoURL != null && !logoURL.equals(Setup.NONE)) {
ImageIcon icon=new ImageIcon(logoURL);
if (icon.getIconWidth() == -1) {
log.error("Logo not found: " + logoURL);
}
else {
writer.write(icon.getImage(),new JLabel(icon));
}
}
Color c=null;
while (true) {
try {
line=in.readLine();
}
catch ( IOException e) {
log.debug("Print read failed");
break;
}
if (line == null) {
if (isPreview) {
try {
writer.write(" ");
}
catch ( IOException e) {
log.debug("Print write failed for null line");
}
}
break;
}
if (isBuildReport) {
line=filterBuildReport(line,false);
if (line.equals("")) {
continue;
}
}
else {
if (line.length() > 0) {
boolean horizontialLineSeparatorFound=true;
for (int i=0; i < line.length(); i++) {
if (line.charAt(i) != HORIZONTAL_LINE_SEPARATOR) {
horizontialLineSeparatorFound=false;
break;
}
}
if (horizontialLineSeparatorFound) {
writer.write(writer.getCurrentLineNumber(),0,writer.getCurrentLineNumber(),line.length() + 1);
c=null;
continue;
}
}
for (int i=0; i < line.length(); i++) {
if (line.charAt(i) == VERTICAL_LINE_SEPARATOR) {
if (Setup.isTabEnabled()) {
writer.write(writer.getCurrentLineNumber(),0,writer.getCurrentLineNumber() + 1,0);
writer.write(writer.getCurrentLineNumber(),line.length() + 1,writer.getCurrentLineNumber() + 1,line.length() + 1);
}
writer.write(writer.getCurrentLineNumber(),i + 1,writer.getCurrentLineNumber() + 1,i + 1);
}
}
line=line.replace(VERTICAL_LINE_SEPARATOR,SPACE);
if ((!Setup.getPickupEnginePrefix().equals("") && line.startsWith(Setup.getPickupEnginePrefix())) || (!Setup.getPickupCarPrefix().equals("") && line.startsWith(Setup.getPickupCarPrefix())) || (!Setup.getSwitchListPickupCarPrefix().equals("") && line.startsWith(Setup.getSwitchListPickupCarPrefix()))) {
c=Setup.getPickupColor();
}
else if ((!Setup.getDropEnginePrefix().equals("") && line.startsWith(Setup.getDropEnginePrefix())) || (!Setup.getDropCarPrefix().equals("") && line.startsWith(Setup.getDropCarPrefix())) || (!Setup.getSwitchListDropCarPrefix().equals("") && line.startsWith(Setup.getSwitchListDropCarPrefix()))) {
c=Setup.getDropColor();
}
else if ((!Setup.getLocalPrefix().equals("") && line.startsWith(Setup.getLocalPrefix())) || (!Setup.getSwitchListLocalPrefix().equals("") && line.startsWith(Setup.getSwitchListLocalPrefix()))) {
c=Setup.getLocalColor();
}
else if (!line.startsWith(TrainCommon.TAB)) {
c=null;
}
if (c != null) {
try {
writer.write(c,line + NEW_LINE);
continue;
}
catch ( IOException e) {
log.debug("Print write color failed");
break;
}
}
}
try {
writer.write(line + NEW_LINE);
}
catch ( IOException e) {
log.debug("Print write failed");
break;
}
}
try {
in.close();
}
catch ( IOException e) {
log.debug("Print close failed");
}
writer.close();
}
| Print or preview a train manifest, build report, or switch list. |
Organization2(String name){
id=UUID.randomUUID();
this.name=name;
}
| Create organization. |
public static void close(){
responseHeaderDB.close();
fileDB.close(true);
}
| close the databases |
public static boolean addEvent(final ConfEvent e){
if (Cfg.DEBUG) {
}
if (eventsMap.containsKey(e.getId()) == true) {
if (Cfg.DEBUG) {
Check.log(TAG + " Warn: " + "Substituting event: "+ e);
}
}
eventsMap.put(e.getId(),e);
return true;
}
| Adds the event. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.