code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public boolean isFullyZoomedOut(){
if (isFullyZoomedOutX() && isFullyZoomedOutY()) return true;
else return false;
}
| if the chart is fully zoomed out, return true |
@Override public void start(){
try {
super.start();
readSlopeData();
readLandUseData();
readExcludedAreaData();
readUrbanAreaData();
readTransportData();
readHillShadeData();
System.out.println("Successfully read in all data!");
for (int i=0; i < grid_width; i++) {
for (int j=0; j < grid_height; j++) {
Tile tile=(Tile)landscape.get(i,j);
if (tile != null && tile.urbanized) {
numUrban++;
int numUrbanizedNeighbors=getUrbanNeighbors(tile).size();
if (numUrbanizedNeighbors > 1 && numUrbanizedNeighbors < 6) {
spreadingCenters.add(tile);
}
}
else {
numNonUrban++;
}
}
}
Grower grower=new Grower();
schedule.scheduleRepeating(grower);
}
catch ( FileNotFoundException ex) {
Logger.getLogger(SleuthWorld.class.getName()).log(Level.SEVERE,null,ex);
}
}
| Starts a new run of the simulation. Reads in the data and schedules the growth rules to fire every turn. |
void destroy() throws IOException {
if (raf != null) {
raf.close();
}
if (out != null) {
out.close();
}
}
| Closes the underlying stream/file without finishing the archive, the result will likely be a corrupt archive. <p>This method only exists to support tests that generate corrupt archives so they can clean up any temporary files.</p> |
public static boolean isValidSpecName(final String aSpecName){
String identifier=getIdentifier(aSpecName);
return aSpecName.equals(identifier);
}
| Checks a specification name for its validity WRT the parser identifier definition |
@SuppressFBWarnings(value="EI_EXPOSE_REP2",justification="This class is designed to simply wrap an object array.") public ArrayTuple(final Object[] tuple){
this.tuple=tuple;
}
| Create an <code>ArrayTuple</code> backed by the given array. |
@Override protected Action[] createActions(){
return new Action[]{getOKAction()};
}
| Override so only OK action is created and not Cancel |
private int pop(){
if (outputStackTop > 0) {
return outputStack[--outputStackTop];
}
else {
return STACK | -(--owner.inputStackTop);
}
}
| Pops a type from the output frame stack and returns its value. |
public void keyReleased(KeyEvent e){
if (e.getKeyCode() == KeyEvent.VK_ESCAPE) setText(m_initialText);
}
| Key Released if Escape restore old Text. |
public boolean containsPrefix(String prefix){
return m_Root.contains(prefix);
}
| checks whether the given prefix is stored in the trie |
public int findReferencePosition(int offset,int nextToken){
boolean danglingElse=false;
boolean unindent=false;
boolean indent=false;
boolean matchBrace=false;
boolean matchParen=false;
boolean matchCase=false;
if (offset < fDocument.getLength()) {
try {
IRegion line=fDocument.getLineInformationOfOffset(offset);
int lineOffset=line.getOffset();
int prevPos=Math.max(offset - 1,0);
boolean isFirstTokenOnLine=fDocument.get(lineOffset,prevPos + 1 - lineOffset).trim().length() == 0;
int prevToken=fScanner.previousToken(prevPos,JavaHeuristicScanner.UNBOUND);
boolean bracelessBlockStart=fScanner.isBracelessBlockStart(prevPos,JavaHeuristicScanner.UNBOUND);
switch (nextToken) {
case Symbols.TokenELSE:
danglingElse=true;
break;
case Symbols.TokenCASE:
case Symbols.TokenDEFAULT:
if (isFirstTokenOnLine) matchCase=true;
break;
case Symbols.TokenLBRACE:
if (bracelessBlockStart && !fPrefs.prefIndentBracesForBlocks) unindent=true;
else if ((prevToken == Symbols.TokenCOLON || prevToken == Symbols.TokenEQUAL || prevToken == Symbols.TokenRBRACKET) && !fPrefs.prefIndentBracesForArrays) unindent=true;
else if (!bracelessBlockStart && fPrefs.prefIndentBracesForMethods) indent=true;
break;
case Symbols.TokenRBRACE:
if (isFirstTokenOnLine) matchBrace=true;
break;
case Symbols.TokenRPAREN:
if (isFirstTokenOnLine) matchParen=true;
break;
}
}
catch (BadLocationException e) {
}
}
else {
danglingElse=false;
}
int ref=findReferencePosition(offset,danglingElse,matchBrace,matchParen,matchCase);
if (unindent) fIndent--;
if (indent) fIndent++;
return ref;
}
| Returns the reference position regarding to indentation for <code>position</code>, or <code>NOT_FOUND</code>. <p>If <code>peekNextChar</code> is <code>true</code>, the next token after <code>offset</code> is read and taken into account when computing the indentation. Currently, if the next token is the first token on the line (i.e. only preceded by whitespace), the following tokens are specially handled: <ul> <li><code>switch</code> labels are indented relative to the switch block</li> <li>opening curly braces are aligned correctly with the introducing code</li> <li>closing curly braces are aligned properly with the introducing code of the matching opening brace</li> <li>closing parenthesis' are aligned with their opening peer</li> <li>the <code>else</code> keyword is aligned with its <code>if</code>, anything else is aligned normally (i.e. with the base of any introducing statements).</li> <li>if there is no token on the same line after <code>offset</code>, the indentation is the same as for an <code>else</code> keyword</li> </ul> |
@Override public boolean eIsSet(int featureID){
switch (featureID) {
case UmplePackage.METHOD_DECLARATOR___METHOD_NAME_1:
return METHOD_NAME_1_EDEFAULT == null ? methodName_1 != null : !METHOD_NAME_1_EDEFAULT.equals(methodName_1);
case UmplePackage.METHOD_DECLARATOR___PARAMETER_LIST_1:
return parameterList_1 != null && !parameterList_1.isEmpty();
}
return super.eIsSet(featureID);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
private boolean isRolloverInstallment(Installment installment){
Date systemCreatedDate=basicProperty.getProperty().getCreatedDate();
return propertyTaxUtil.between(new Date(),installment.getFromDate(),installment.getToDate()) && !propertyTaxUtil.between(systemCreatedDate,installment.getFromDate(),installment.getToDate());
}
| Returns true if the installment passed is a rollover installment else returns false |
private int deleteData(){
StringBuilder updateSQL=new StringBuilder();
updateSQL.append("DELETE FROM M_ForecastLine WHERE M_Forecast_ID=").append(p_M_Forecast_ID);
return DB.executeUpdateEx(updateSQL.toString(),get_TrxName());
}
| Delete forecast line |
private static void validate(File file,byte[] actual) throws IOException {
String mode=Settings.getFileProtectionMode();
File digestFile=getDigestFile(file);
if (digestFile.exists()) {
byte[] expected=loadDigest(file);
if (!MessageDigest.isEqual(actual,expected)) {
throw new ValidationException(file,"digest does not match");
}
}
else {
if (mode.equalsIgnoreCase(STRICT_MODE)) {
throw new ValidationException(file,"no digest file");
}
else {
System.err.println("no digest file exists to validate " + file);
}
}
}
| Validates the file. |
public static boolean equals(int[] list1,int[] list2){
if (list1.length != list2.length) return false;
sort(list1);
sort(list2);
for (int i=0; i < list1.length; i++) {
if (list1[i] != list2[i]) return false;
}
return true;
}
| equals returns true if the elements in both lists are equal. False otherwise |
public static HashMap<ICondition,Boolean> testAllConditionsRecursive(final HashSet<ICondition> rules,HashMap<ICondition,Boolean> allConditionsTestedSoFar,final IDelegateBridge aBridge){
if (allConditionsTestedSoFar == null) {
allConditionsTestedSoFar=new HashMap<>();
}
for ( final ICondition c : rules) {
if (!allConditionsTestedSoFar.containsKey(c)) {
testAllConditionsRecursive(new HashSet<>(c.getConditions()),allConditionsTestedSoFar,aBridge);
allConditionsTestedSoFar.put(c,c.isSatisfied(allConditionsTestedSoFar,aBridge));
}
}
return allConditionsTestedSoFar;
}
| Takes the list of ICondition that getAllConditionsRecursive generates, and tests each of them, mapping them one by one to their boolean value. |
public List<TriggerKey> selectTriggersInState(Connection conn,String state) throws SQLException {
PreparedStatement ps=null;
ResultSet rs=null;
try {
ps=conn.prepareStatement(rtp(SELECT_TRIGGERS_IN_STATE));
ps.setString(1,state);
rs=ps.executeQuery();
LinkedList<TriggerKey> list=new LinkedList<TriggerKey>();
while (rs.next()) {
list.add(triggerKey(rs.getString(1),rs.getString(2)));
}
return list;
}
finally {
closeResultSet(rs);
closeStatement(ps);
}
}
| <p> Select all of the triggers in a given state. </p> |
public static void main(String[] args) throws IOException {
process_command_line(args);
info=new JarInfo();
if (printVersion) {
doPrintVersion();
}
if (printHelp) {
doPrintHelp();
}
}
| This main simply prints the version information to allow users to identify the build version of the Jar. |
@Override public boolean contains(int x,int y){
Rectangle r=gridElement.getRectangle();
if (gridElement.isSelectableOn(new Point(r.getX() + x,r.getY() + y))) {
return ElementUtils.checkForOverlap(gridElement,new Point(x,y));
}
else {
return false;
}
}
| Must be overwritten because Swing sometimes uses this method instead of contains(Point) |
@SuppressWarnings("unchecked") default T addDependency(String gav) throws Exception {
addAsLibrary(ArtifactLookup.get().artifact(gav));
return (T)this;
}
| Add a single Maven dependency into the Archive. The following dependency formats are supported: groupId:artifactId groupId:artifactId:version groupId:artifactId:packaging:version groupId:artifactId:packaging:version:classifier |
@Override public void init(FilterConfig fConfig) throws ServletException {
this.filterConfig=fConfig;
this.attribute=fConfig.getInitParameter("attribute");
}
| Place this filter into service. |
public int size(){
return n;
}
| Returns the number of strings in the set. |
public List(Vector items){
this(new DefaultListModel(items));
}
| Creates a new instance of List |
public static void printf(Locale locale,String format,Object... args){
out.printf(locale,format,args);
out.flush();
}
| Print a formatted string to standard output using the specified locale, format string, and arguments, and flush standard output. |
private boolean makeServiceNameUnique(ServiceInfoImpl info){
final String originalQualifiedName=info.getKey();
final long now=System.currentTimeMillis();
boolean collision;
do {
collision=false;
for ( DNSEntry dnsEntry : this.getCache().getDNSEntryList(info.getKey())) {
if (DNSRecordType.TYPE_SRV.equals(dnsEntry.getRecordType()) && !dnsEntry.isExpired(now)) {
final DNSRecord.Service s=(DNSRecord.Service)dnsEntry;
if (s.getPort() != info.getPort() || !s.getServer().equals(_localHost.getName())) {
if (logger.isLoggable(Level.FINER)) {
logger.finer("makeServiceNameUnique() JmDNS.makeServiceNameUnique srv collision:" + dnsEntry + " s.server="+ s.getServer()+ " "+ _localHost.getName()+ " equals:"+ (s.getServer().equals(_localHost.getName())));
}
info.setName(NameRegister.Factory.getRegistry().incrementName(_localHost.getInetAddress(),info.getName(),NameRegister.NameType.SERVICE));
collision=true;
break;
}
}
}
final ServiceInfo selfService=_services.get(info.getKey());
if (selfService != null && selfService != info) {
info.setName(NameRegister.Factory.getRegistry().incrementName(_localHost.getInetAddress(),info.getName(),NameRegister.NameType.SERVICE));
collision=true;
}
}
while (collision);
return !(originalQualifiedName.equals(info.getKey()));
}
| Generate a possibly unique name for a service using the information we have in the cache. |
public static String toString(final BOp bop){
final StringBuilder sb=new StringBuilder();
toString(bop,sb,0);
sb.setLength(sb.length() - 1);
return sb.toString();
}
| Pretty print a bop. |
public WeakHashMapPro(){
this(DEFAULT_INITIAL_CAPACITY,DEFAULT_LOAD_FACTOR);
}
| Constructs a new, empty <tt>WeakHashMap</tt> with the default initial capacity (16) and load factor (0.75). |
public SuggestWordQueue(int size,Comparator<SuggestWord> comparator){
super(size);
this.comparator=comparator;
}
| Specify the size of the queue and the comparator to use for sorting. |
public Object[] values(){
Object[] values=new Object[this.size()];
Entry[] table=this.table;
int i=0;
for (int bucket=0; bucket < table.length; bucket++) {
for (Entry e=table[bucket]; e != null; e=e.next) {
values[i++]=e.value;
}
}
return values;
}
| Returns all of the objects in the map |
private void subscribe(){
String topic=((EditText)connectionDetails.findViewById(R.id.topic)).getText().toString();
((EditText)connectionDetails.findViewById(R.id.topic)).getText().clear();
RadioGroup radio=(RadioGroup)connectionDetails.findViewById(R.id.qosSubRadio);
int checked=radio.getCheckedRadioButtonId();
int qos=ActivityConstants.defaultQos;
switch (checked) {
case R.id.qos0:
qos=0;
break;
case R.id.qos1:
qos=1;
break;
case R.id.qos2:
qos=2;
break;
}
try {
String[] topics=new String[1];
topics[0]=topic;
Connections.getInstance(context).getConnection(clientHandle).getClient().subscribe(topic,qos,null,new ActionListener(context,Action.SUBSCRIBE,clientHandle,topics));
}
catch (MqttSecurityException e) {
Log.e(this.getClass().getCanonicalName(),"Failed to subscribe to" + topic + " the client with the handle "+ clientHandle,e);
}
catch (MqttException e) {
Log.e(this.getClass().getCanonicalName(),"Failed to subscribe to" + topic + " the client with the handle "+ clientHandle,e);
}
}
| Subscribe to a topic that the user has specified |
public static int extractLag_Display(String laggedFactor){
int colonIndex=laggedFactor.indexOf(":L");
int lag=Integer.parseInt(laggedFactor.substring(colonIndex + 2,laggedFactor.length()));
return lag;
}
| Extracts the lag from the lagged factor name string. </p> precondition laggedFactor is a legal lagged factor. |
public boolean phaseHasTurns(IGame.Phase thisPhase){
switch (thisPhase) {
case PHASE_SET_ARTYAUTOHITHEXES:
case PHASE_DEPLOY_MINEFIELDS:
case PHASE_DEPLOYMENT:
case PHASE_MOVEMENT:
case PHASE_FIRING:
case PHASE_PHYSICAL:
case PHASE_TARGETING:
case PHASE_OFFBOARD:
return true;
default :
return false;
}
}
| Returns true if this phase has turns. If false, the phase is simply waiting for everybody to declare "done". |
public static String marshal(Object obj) throws JAXBException {
StringWriter writer=new StringWriter();
JAXBUtils.getJAXBContext().createMarshaller().marshal(obj,writer);
return writer.toString();
}
| Serialize the given object to XML |
public JSONObject putOpt(String key,Object value) throws JSONException {
if (key != null && value != null) {
this.put(key,value);
}
return this;
}
| Put a key/value pair in the JSONObject, but only if the key and the value are both non-null. |
private static Map<String,String> extractMdc(Map<String,String> map,List<String> keys){
return keys.stream().filter(null).collect(Collectors.toMap(null,null));
}
| Get list of fields and populate values into map (if value for key is not empty |
public ExpressionsAdapterFactory(){
if (modelPackage == null) {
modelPackage=ExpressionsPackage.eINSTANCE;
}
}
| Creates an instance of the adapter factory. <!-- begin-user-doc --> <!-- end-user-doc --> |
public static NurbsCurve createSemiCircle(Origin3D o,float r){
Vec4D[] cp=new Vec4D[4];
cp[0]=new Vec4D(o.xAxis.scale(r),1);
cp[3]=cp[0].getInvertedXYZ();
cp[0].addXYZSelf(o.origin);
cp[3].addXYZSelf(o.origin);
cp[1]=new Vec4D(o.xAxis.add(o.yAxis).scaleSelf(r).addSelf(o.origin),0.5f);
cp[2]=new Vec4D(o.xAxis.getInverted().addSelf(o.yAxis).scaleSelf(r).addSelf(o.origin),0.5f);
float[] u={0,0,0,0.5f,1,1,1};
return new BasicNurbsCurve(cp,u,2);
}
| Create a semi-circle NurbsCurve around the given Origin with radius r. |
public synchronized void removePropertyChangeListener(PropertyChangeListener listener){
listenerList.remove(listener);
}
| Removes PropertyChangeListener from the list of listeners. |
@Uninterruptible @Pure public byte parseForArrayElementTypeCode(){
if (VM.VerifyAssertions) {
VM._assert(val.length > 1,"An array descriptor has at least two characters");
VM._assert(val[0] == '[',"An array descriptor must start with '['");
}
return val[1];
}
| Parse "this" array descriptor to obtain type code for its element type. this: descriptor - something like "[Ljava/lang/String;" or "[I" |
public ImageRotationCalculatorImpl(OrientationManager orientationManager,int sensorOrientationDegrees,boolean frontFacing){
mSensorOrientationDegrees=sensorOrientationDegrees;
mFrontFacing=frontFacing;
mOrientationManager=orientationManager;
}
| Create a calculator with the given hardware properties of the camera. |
public void stop(){
messageLogger.stop();
}
| Stops the message logger. |
private void updateProgress(String progressLabel,int progress){
if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) {
myHost.updateProgress(progressLabel,progress);
}
previousProgress=progress;
previousProgressLabel=progressLabel;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
private boolean shouldAddImports(){
if (isInJavadoc() && !isJavadocProcessingEnabled()) return false;
return true;
}
| Returns <code>true</code> if imports should be added. The return value depends on the context and preferences only and does not take into account the contents of the compilation unit or the kind of proposal. Even if <code>true</code> is returned, there may be cases where no imports are added for the proposal. For example: <ul> <li>when completing within the import section</li> <li>when completing informal javadoc references (e.g. within <code><code></code> tags)</li> <li>when completing a type that conflicts with an existing import</li> <li>when completing an implicitly imported type (same package, <code>java.lang</code> types)</li> </ul> <p> The decision whether a qualified type or the simple type name should be inserted must take into account these different scenarios. </p> |
public synchronized void decrement(){
tempSet.set(0,dimension);
for (int q=0; q < votingRecord.size(); q++) {
votingRecord.get(q).xor(tempSet);
tempSet.and(votingRecord.get(q));
}
}
| Decrement every dimension. Assumes at least one count in each dimension i.e: no underflow check currently - will wreak havoc with zero counts |
public TimeLagGraphWorkbench(){
this(new TimeLagGraph());
}
| Constructs a new workbench with an empty graph; useful if another graph will be set later. |
@Override public void registerPackages(ResourceSet resourceSet){
super.registerPackages(resourceSet);
if (!isInWorkspace(com.github.lbroudoux.dsl.eip.EipPackage.class)) {
resourceSet.getPackageRegistry().put(com.github.lbroudoux.dsl.eip.EipPackage.eINSTANCE.getNsURI(),com.github.lbroudoux.dsl.eip.EipPackage.eINSTANCE);
}
}
| This can be used to update the resource set's package registry with all needed EPackages. |
public boolean cmd_save(boolean manualCmd){
if (m_curAPanelTab != null) manualCmd=false;
log.config("Manual=" + manualCmd);
m_errorDisplayed=false;
m_curGC.stopEditor(true);
m_curGC.acceptEditorChanges();
if (m_curAPanelTab != null) {
m_curAPanelTab.saveData();
aSave.setEnabled(false);
}
if (m_curTab.getCommitWarning().length() > 0 && m_curTab.needSave(true,false)) if (!ADialog.ask(m_curWindowNo,this,"SaveChanges?",m_curTab.getCommitWarning())) return false;
boolean retValue=m_curTab.dataSave(manualCmd);
if (manualCmd && !retValue && !m_errorDisplayed) {
showLastError();
}
if (retValue) m_curGC.rowChanged(true,m_curTab.getRecord_ID());
if (manualCmd) {
m_curGC.dynamicDisplay(0);
if (!isNested) m_window.setTitle(getTitle());
}
if (m_curGC.isDetailGrid() && retValue) {
m_curGC.getGCParent().refreshMTab(m_curGC);
}
return retValue;
}
| If required ask if you want to save and save it |
public synchronized int size(){
return this.stack.size();
}
| get the size of a stack |
public static long readVarLong(ByteBuffer buff){
int shift=0;
long l=0;
while (true) {
byte b=(byte)buff.get();
l|=(long)(b & 0x7F) << shift;
shift+=7;
if (b >= 0) {
return l;
}
}
}
| Reads a VarLong. |
@Override public int prepare(Xid xid) throws XAException {
if (isDebugEnabled()) {
debugCode("prepare(" + JdbcXid.toString(xid) + ");");
}
checkOpen();
if (!currentTransaction.equals(xid)) {
throw new XAException(XAException.XAER_INVAL);
}
try (Statement stat=physicalConn.createStatement()){
stat.execute("PREPARE COMMIT " + JdbcXid.toString(xid));
prepared=true;
}
catch ( SQLException e) {
throw convertException(e);
}
return XA_OK;
}
| Prepare a transaction. |
public static void main(String[] args){
System.out.println(PROPERTIES);
}
| Only for testing |
private static void deleteRecursiveSilent(CarbonFile f){
if (f.isDirectory()) {
if (f.listFiles() != null) {
for ( CarbonFile c : f.listFiles()) {
deleteRecursiveSilent(c);
}
}
}
if (f.exists() && !f.delete()) {
return;
}
}
| this method will delete the folders recursively |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:29:44.177 -0500",hash_original_method="E35FF664DA486BBF1CFE86498473FB9B",hash_generated_method="81AF2D5B35CA402304449ACA5C911EFF") public static void disableVsync(){
nDisableVsync();
}
| Disables v-sync. For performance testing only. |
public boolean similar(Object other){
if (!(other instanceof JSONArray)) {
return false;
}
int len=this.length();
if (len != ((JSONArray)other).length()) {
return false;
}
for (int i=0; i < len; i+=1) {
Object valueThis=this.get(i);
Object valueOther=((JSONArray)other).get(i);
if (valueThis instanceof JSONObject) {
if (!((JSONObject)valueThis).similar(valueOther)) {
return false;
}
}
else if (valueThis instanceof JSONArray) {
if (!((JSONArray)valueThis).similar(valueOther)) {
return false;
}
}
else if (!valueThis.equals(valueOther)) {
return false;
}
}
return true;
}
| Determine if two JSONArrays are similar. They must contain similar sequences. |
@Override public boolean eIsSet(int featureID){
switch (featureID) {
case N4JSPackage.IDENTIFIER_REF__STRICT_MODE:
return strictMode != STRICT_MODE_EDEFAULT;
case N4JSPackage.IDENTIFIER_REF__ID:
return id != null;
case N4JSPackage.IDENTIFIER_REF__ID_AS_TEXT:
return ID_AS_TEXT_EDEFAULT == null ? idAsText != null : !ID_AS_TEXT_EDEFAULT.equals(idAsText);
}
return super.eIsSet(featureID);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
private void processBinaryMeta(CacheTypeMetadata meta,TypeDescriptor d) throws IgniteCheckedException {
Map<String,String> aliases=meta.getAliases();
if (aliases == null) aliases=Collections.emptyMap();
for ( Map.Entry<String,Class<?>> entry : meta.getAscendingFields().entrySet()) {
BinaryProperty prop=buildBinaryProperty(entry.getKey(),entry.getValue(),aliases);
d.addProperty(prop,false);
String idxName=prop.name() + "_idx";
d.addIndex(idxName,isGeometryClass(prop.type()) ? GEO_SPATIAL : SORTED);
d.addFieldToIndex(idxName,prop.name(),0,false);
}
for ( Map.Entry<String,Class<?>> entry : meta.getDescendingFields().entrySet()) {
BinaryProperty prop=buildBinaryProperty(entry.getKey(),entry.getValue(),aliases);
d.addProperty(prop,false);
String idxName=prop.name() + "_idx";
d.addIndex(idxName,isGeometryClass(prop.type()) ? GEO_SPATIAL : SORTED);
d.addFieldToIndex(idxName,prop.name(),0,true);
}
for ( String txtIdx : meta.getTextFields()) {
BinaryProperty prop=buildBinaryProperty(txtIdx,String.class,aliases);
d.addProperty(prop,false);
d.addFieldToTextIndex(prop.name());
}
Map<String,LinkedHashMap<String,IgniteBiTuple<Class<?>,Boolean>>> grps=meta.getGroups();
if (grps != null) {
for ( Map.Entry<String,LinkedHashMap<String,IgniteBiTuple<Class<?>,Boolean>>> entry : grps.entrySet()) {
String idxName=entry.getKey();
LinkedHashMap<String,IgniteBiTuple<Class<?>,Boolean>> idxFields=entry.getValue();
int order=0;
for ( Map.Entry<String,IgniteBiTuple<Class<?>,Boolean>> idxField : idxFields.entrySet()) {
BinaryProperty prop=buildBinaryProperty(idxField.getKey(),idxField.getValue().get1(),aliases);
d.addProperty(prop,false);
Boolean descending=idxField.getValue().get2();
d.addFieldToIndex(idxName,prop.name(),order,descending != null && descending);
order++;
}
}
}
for ( Map.Entry<String,Class<?>> entry : meta.getQueryFields().entrySet()) {
BinaryProperty prop=buildBinaryProperty(entry.getKey(),entry.getValue(),aliases);
if (!d.props.containsKey(prop.name())) d.addProperty(prop,false);
}
}
| Processes declarative metadata for binary object. |
private static boolean isCorbaUrl(String url){
return url.startsWith("iiop://") || url.startsWith("iiopname://") || url.startsWith("corbaname:");
}
| These are the URL schemes that need to be processed. IOR and corbaloc URLs can be passed directly to ORB.string_to_object() |
public T caseAnonymous_program_1_(Anonymous_program_1_ object){
return null;
}
| Returns the result of interpreting the object as an instance of '<em>Anonymous program 1</em>'. <!-- begin-user-doc --> This implementation returns null; returning a non-null result will terminate the switch. <!-- end-user-doc --> |
public static BinaryExpression newInitializationExpression(String variable,ClassNode type,Expression rhs){
VariableExpression lhs=new VariableExpression(variable);
if (type != null) {
lhs.setType(type);
}
Token operator=Token.newPlaceholder(Types.ASSIGN);
return new BinaryExpression(lhs,operator,rhs);
}
| Creates variable initialization expression in which the specified expression is written into the specified variable name. |
@Override public boolean containsValue(Object value){
if (value == null) return containsNullValue();
Entry[] tab=table;
for (int i=0; i < tab.length; i++) for (Entry e=tab[i]; e != null; e=e.next) if (value.equals(e.value)) return true;
return false;
}
| Returns <tt>true</tt> if this map maps one or more keys to the specified value. |
public String toString(){
StringBuffer buffer=new StringBuffer();
buffer.append("DbConnectionConfig[");
buffer.append("cntByDriver = ").append(m_cntByDriver);
buffer.append(", cntParam = ").append(m_cntParam);
buffer.append(", url = ").append(m_url);
buffer.append(", user = ").append(m_user);
buffer.append(", pwd = ").append(m_pwd);
buffer.append("]");
return buffer.toString();
}
| toString methode: creates a String representation of the object |
DocCollection createCollection(int nSlices,DocRouter router){
List<Range> ranges=router.partitionRange(nSlices,router.fullRange());
Map<String,Slice> slices=new HashMap<>();
for (int i=0; i < ranges.size(); i++) {
Range range=ranges.get(i);
Slice slice=new Slice("shard" + (i + 1),null,map("range",range));
slices.put(slice.getName(),slice);
}
DocCollection coll=new DocCollection("collection1",slices,null,router);
return coll;
}
| public void testPrintHashCodes() throws Exception { // from negative to positive, the upper bits of the hash ranges should be // shard1: 11 // shard2: 10 // shard3: 00 // shard4: 01 String[] highBitsToShard = {"shard3","shard4","shard1","shard2"}; for (int i = 0; i<26; i++) { String id = new String(Character.toChars('a'+i)); int hash = hash(id); System.out.println("hash of " + id + " is " + Integer.toHexString(hash) + " high bits=" + (hash>>>30) + " shard="+highBitsToShard[hash>>>30]); } } |
public ESRIPointRecord(byte b[],int off) throws IOException {
super(b,off);
int ptr=off + 8;
int shapeType=readLEInt(b,ptr);
ptr+=4;
if (shapeType != SHAPE_TYPE_POINT) {
throw new IOException("Invalid point record. Expected shape " + "type " + SHAPE_TYPE_POINT + " but found "+ shapeType);
}
x=readLEDouble(b,ptr);
ptr+=8;
y=readLEDouble(b,ptr);
ptr+=8;
}
| Initialize a point record from the given buffer. |
public boolean isBeanSupportEnabled(){
return beanSupportEnabled;
}
| Returns true if this instance supports extracting/setting bean properties. |
public NominalToNumericModel(ExampleSet exampleSet,int codingType){
super(exampleSet);
this.codingType=codingType;
}
| Constructs a new model. Use this ctor to create a model for value encoding. |
public static boolean isNullOrEmpty(String... input){
if (input == null) {
return true;
}
for ( String s : input) {
if (s == null || s.isEmpty()) {
return true;
}
}
return false;
}
| Checks if any of the String arguments is null or empty. |
public void test_DELETE_accessPath_delete_c_nothingMatched() throws Exception {
if (TestMode.quads != getTestMode()) return;
doInsertbyURL("POST",packagePath + "test_delete_by_access_path.trig");
final long mutationResult=doDeleteWithAccessPath(null,null,null,new URIImpl("http://xmlns.com/foaf/0.1/XXX"));
assertEquals(0,mutationResult);
}
| Delete using an access path with the context position bound. |
public synchronized boolean makeProxyClass(Class clazz) throws CannotCompileException, NotFoundException {
String classname=clazz.getName();
if (proxyClasses.get(classname) != null) return false;
else {
CtClass ctclazz=produceProxyClass(classPool.get(classname),clazz);
proxyClasses.put(classname,ctclazz);
modifySuperclass(ctclazz);
return true;
}
}
| Makes a proxy class. The produced class is substituted for the original class. |
private static BufferedImage cutByShort(String source) throws UtilException {
try {
BufferedImage src=ImageIO.read(new File(source));
int width=src.getWidth();
int height=src.getHeight();
int size=width > height ? height : width;
BufferedImage dest=new BufferedImage(size,size,BufferedImage.TYPE_INT_RGB);
Graphics g=dest.getGraphics();
g.drawImage(src,0,0,size,size,0,0,size,size,null);
return dest;
}
catch ( IOException e) {
throw new UtilException(ErrorCodeDef.IMAGE_ZOOM_10020,e);
}
}
| Description: <br> |
static void copy32bit(byte[] src,int isrc,byte[] dest,int idest){
dest[idest]=src[isrc];
dest[idest + 1]=src[isrc + 1];
dest[idest + 2]=src[isrc + 2];
dest[idest + 3]=src[isrc + 3];
}
| Copies a 32bit integer. |
public static <E>ImmutableList<E> of(E e1,E e2,E e3,E e4,E e5,E e6,E e7,E e8,E e9,E e10,E e11){
return construct(e1,e2,e3,e4,e5,e6,e7,e8,e9,e10,e11);
}
| Returns an immutable list containing the given elements, in order. |
@Override public double totalEstimatedQuantityForPreviousREs(final Long woActivityId,Long estimateId,final Long activityId,final WorkOrder workOrder){
if (estimateId == null) estimateId=-1l;
Object[] params=null;
Double estQuantity=null;
params=new Object[]{estimateId,workOrder,workOrder,woActivityId,activityId};
estQuantity=(Double)genericService.findByNamedQuery("totalEstimatedQuantityInRE",params);
Double estQuantityRE=null;
params=new Object[]{estimateId,workOrder,workOrder,activityId};
estQuantityRE=(Double)genericService.findByNamedQuery("totalEstimatedQuantityForPreviousREs",params);
if (estQuantity != null && estQuantityRE != null) estQuantity=estQuantity + estQuantityRE;
if (estQuantity == null && estQuantityRE != null) estQuantity=estQuantityRE;
if (estQuantity == null) return 0.0d;
else return estQuantity.doubleValue();
}
| Similar to totalEstimatedQuantityForRE but will consider only previous REs and not all REs |
public Element(String name,String id,XmlTag xml){
final Matcher matcher=sIdPattern.matcher(id);
if (matcher.find() && matcher.groupCount() > 1) {
this.id=matcher.group(2);
String androidNS=matcher.group(1);
this.isAndroidNS=!(androidNS == null || androidNS.length() == 0);
}
if (this.id == null) {
throw new IllegalArgumentException("Invalid format of view id");
}
String[] packages=name.split("\\.");
if (packages.length > 1) {
this.nameFull=name;
this.name=packages[packages.length - 1];
}
else {
this.nameFull=null;
this.name=name;
}
this.xml=xml;
XmlAttribute clickable=xml.getAttribute("android:clickable",null);
boolean hasClickable=clickable != null && clickable.getValue() != null && clickable.getValue().equals("true");
String xmlName=xml.getName();
if (xmlName.contains("RadioButton")) {
}
else {
if ((xmlName.contains("ListView") || xmlName.contains("GridView")) && hasClickable) {
isItemClickable=true;
}
else if (xmlName.contains("Button") || hasClickable) {
isClickable=true;
}
}
isEditText=xmlName.contains("EditText");
}
| Constructs new element |
public void run(Throwing.Runnable runnable){
wrap(runnable).run();
}
| Attempts to run the given runnable. |
@Override public String validateName(String name,boolean increaseNumber){
String result=name;
if (!isOKImpl(name,true).isEmpty() && !increaseNumber || name.isEmpty()) {
return "";
}
int i=1;
while (!isOKImpl(result,true).isEmpty()) {
result=name + i;
i++;
}
return result;
}
| Validates name to be suggested in context |
public boolean isValid(){
if (mXVals == null || mXVals.size() <= 0 || mDataSets == null || mDataSets.size() < 1 || mDataSets.get(0).getYVals().size() <= 0) {
return false;
}
else {
return true;
}
}
| Checks if the ChartData object contains valid data |
public static void closeRegistersQuery(String sessionID,Integer bookID) throws BookException, SessionException, ValidationException {
Validator.validate_String_NotNull_LengthMayorZero(sessionID,ValidationException.ATTRIBUTE_SESSION);
Validator.validate_Integer(bookID,ValidationException.ATTRIBUTE_BOOK);
try {
CacheBag cacheBag=CacheFactory.getCacheInterface().getCacheEntry(sessionID);
if (!cacheBag.containsKey(bookID)) {
throw new BookException(BookException.ERROR_BOOK_NOT_OPEN);
}
THashMap bookInformation=(THashMap)cacheBag.get(bookID);
AxSfQueryResults queryResults=(AxSfQueryResults)bookInformation.get(AXSF_QUERY_RESULTS);
if (queryResults == null) {
throw new BookException(BookException.ERROR_QUERY_NOT_OPEN);
}
else {
bookInformation.remove(AXSF_QUERY_RESULTS);
}
}
catch ( SessionException sE) {
throw sE;
}
catch ( BookException bE) {
throw bE;
}
catch ( Exception e) {
log.error("Impossible to close the book [" + bookID + "] for the session ["+ sessionID+ "]",e);
throw new BookException(BookException.ERROR_CANNOT_CLOSE_BOOK);
}
}
| PUBLIC METHOD |
public NaiveKMeans(DistanceMetric dm,SeedSelection seedSelection){
this(dm,seedSelection,new XORWOW());
}
| Creates a new naive k-Means cluster |
private static int checkFieldTypeSignature(final String signature,int pos){
switch (getChar(signature,pos)) {
case 'L':
return checkClassTypeSignature(signature,pos);
case '[':
return checkTypeSignature(signature,pos + 1);
default :
return checkTypeVariableSignature(signature,pos);
}
}
| Checks a field type signature. |
public URLConnectionRequestPropertiesBuilder withCookie(String cookieName,String cookieValue){
if (requestProperties.containsKey("Cookie")) {
final String cookies=requestProperties.get("Cookie");
requestProperties.put("Cookie",cookies + COOKIES_SEPARATOR + buildCookie(cookieName,cookieValue));
}
else {
requestProperties.put("Cookie",buildCookie(cookieName,cookieValue));
}
return this;
}
| Add provided cookie to 'Cookie' request property. |
@Command(aliases="join",description="Join the game") @PlayerCommand public static void join(CommandContext cmd,@Optional Team team){
Player player=(Player)cmd.getSender();
MatchThread thread=Cardinal.getMatchThread(player);
Match match=thread.getCurrentMatch();
PlayingPlayerContainer playing=team;
if (!match.isFfa()) {
if (playing == null) {
playing=Team.getEmptiestTeam(Team.getTeams(Cardinal.getMatch(player)));
}
}
else {
playing=SinglePlayerContainer.of(player);
}
PlayerContainerData newData=new PlayerContainerData(thread,match,playing);
PlayerContainerData oldData=PlayerContainerData.of(player);
Containers.handleStateChangeEvent(player,oldData,newData);
}
| Join the game. |
public boolean checkPattern(List<LockPatternView.Cell> pattern){
try {
RandomAccessFile raf=new RandomAccessFile(sLockPatternFilename,"r");
final byte[] stored=new byte[(int)raf.length()];
int got=raf.read(stored,0,stored.length);
raf.close();
if (got <= 0) {
return true;
}
return Arrays.equals(stored,LockPatternUtils.patternToHash(pattern));
}
catch ( FileNotFoundException fnfe) {
return true;
}
catch ( IOException ioe) {
return true;
}
}
| Check to see if a pattern matches the saved pattern. If no pattern exists, always returns true. |
public boolean isLeft(){
return m_left;
}
| Is Left Aouter Join |
public synchronized void connected(BluetoothSocket socket){
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread=null;
}
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread=null;
}
if (mAcceptThread != null) {
mAcceptThread.cancel();
mAcceptThread=null;
}
mConnectedThread=new ConnectedThread(socket);
mConnectedThread.start();
mBluetoothDevice=socket.getRemoteDevice();
setState(State.STATE_CONNECTED);
}
| Start the ConnectedThread to begin managing a Bluetooth connection. |
protected CollectionAdminResponse deleteCollection(String collectionName) throws Exception {
SolrClient client=createCloudClient(null);
CollectionAdminResponse res;
try {
ModifiableSolrParams params=new ModifiableSolrParams();
params.set("action",CollectionParams.CollectionAction.DELETE.toString());
params.set("name",collectionName);
QueryRequest request=new QueryRequest(params);
request.setPath("/admin/collections");
res=new CollectionAdminResponse();
res.setResponse(client.request(request));
}
catch ( Exception e) {
log.warn("Error while deleting the collection " + collectionName,e);
return new CollectionAdminResponse();
}
finally {
client.close();
}
return res;
}
| Delete a collection through the Collection API. |
public void sendMessage(String configKey,String value){
if (mPeerId != null) {
DataMap config=new DataMap();
config.putString(configKey,value);
byte[] rawData=config.toByteArray();
Wearable.MessageApi.sendMessage(mGoogleApiClient,mPeerId,PATH_WITH_FEATURE,rawData);
}
}
| Send information using the wearable message API |
public MoveDownAction(){
putValue(SMALL_ICON,new ImageIcon(CMain.class.getResource("data/arrow_down.png")));
}
| Creates a new action handler for the Down button. |
@Override public void startRadio(String streamURL){
mService.play(streamURL);
}
| Start Radio Streaming |
public ClusterInfo(final Map<String,DiskUsage> leastAvailableSpaceUsage,final Map<String,DiskUsage> mostAvailableSpaceUsage,final Map<String,Long> shardSizes,Map<ShardRouting,String> routingToDataPath){
this.leastAvailableSpaceUsage=leastAvailableSpaceUsage;
this.shardSizes=shardSizes;
this.mostAvailableSpaceUsage=mostAvailableSpaceUsage;
this.routingToDataPath=routingToDataPath;
}
| Creates a new ClusterInfo instance. |
public String normalizeSystemName(String systemName){
boolean aMatch=aCodes.reset(systemName).matches();
int aCount=aCodes.groupCount();
boolean hMatch=hCodes.reset(systemName).matches();
int hCount=hCodes.groupCount();
boolean iMatch=iCodes.reset(systemName).matches();
int iCount=iCodes.groupCount();
if (!aMatch || aCount != 2 || (!validSystemNameFormat(systemName,aCodes.group(2).charAt(0)))) {
return "";
}
String nName="";
if (hMatch && hCount == 4) {
nName=hCodes.group(1) + hCodes.group(2) + hCodes.group(3)+ Integer.toString(Integer.parseInt(hCodes.group(4)));
}
if (nName.equals("")) {
if (iMatch && iCount == 5) {
nName=iCodes.group(1) + iCodes.group(2) + iCodes.group(3)+ "."+ iCodes.group(4)+ "."+ iCodes.group(5);
}
else {
if (log.isDebugEnabled()) {
log.debug("valid name doesn't normalize: " + systemName + " hMatch: "+ hMatch+ " hCount: "+ hCount);
}
}
}
return nName;
}
| Public static method to normalize a system name <P> This routine is used to ensure that each system name is uniquely linked to one bit, by removing extra zeros inserted by the user. <P> If the supplied system name does not have a valid format, an empty string is returned. Otherwise a normalized name is returned in the same format as the input name. |
@Override public void configureZone(final StendhalRPZone zone,final Map<String,String> attributes){
buildprincipal(zone);
}
| Configure a zone. |
public boolean equals(Object other){
if (!(other instanceof action_part)) return false;
else return equals((action_part)other);
}
| Generic equality comparison. |
public ParseException generateParseException(){
jj_expentries.clear();
boolean[] la1tokens=new boolean[40];
if (jj_kind >= 0) {
la1tokens[jj_kind]=true;
jj_kind=-1;
}
for (int i=0; i < 23; i++) {
if (jj_la1[i] == jj_gen) {
for (int j=0; j < 32; j++) {
if ((jj_la1_0[i] & (1 << j)) != 0) {
la1tokens[j]=true;
}
if ((jj_la1_1[i] & (1 << j)) != 0) {
la1tokens[32 + j]=true;
}
}
}
}
for (int i=0; i < 40; i++) {
if (la1tokens[i]) {
jj_expentry=new int[1];
jj_expentry[0]=i;
jj_expentries.add(jj_expentry);
}
}
jj_endpos=0;
jj_rescan_token();
jj_add_error_token(0,0);
int[][] exptokseq=new int[jj_expentries.size()][];
for (int i=0; i < jj_expentries.size(); i++) {
exptokseq[i]=jj_expentries.get(i);
}
return new ParseException(token,exptokseq,tokenImage);
}
| Generate ParseException. |
public void reset(){
color=null;
background=null;
}
| Resets the color settings. |
private static double determinant(DelaunayVertex[] matrix,int row,boolean[] columns){
if (row == matrix.length) {
return 1;
}
double sum=0;
int sign=1;
for (int col=0; col < columns.length; col++) {
if (!columns[col]) {
continue;
}
columns[col]=false;
sum+=sign * matrix[row].coordinates[col] * determinant(matrix,row + 1,columns);
columns[col]=true;
sign=-sign;
}
return sum;
}
| Compute the determinant of a submatrix specified by starting row and by "active" columns. |
public DataTable(){
this(new DataSortedTableModel(""));
}
| initializes with no model |
public Object runSafely(Catbert.FastStack stack) throws Exception {
if (isNetworkedPlaylistCall(stack,0)) {
return makeNetworkedCall(stack);
}
Playlist p=getPlaylist(stack);
if (p != null && p.getID() == 0) {
p.clear();
}
else if (Permissions.hasPermission(Permissions.PERMISSION_PLAYLIST,stack.getUIMgr())) {
Wizard.getInstance().removePlaylist(p);
sage.plugin.PluginEventManager.postEvent(sage.plugin.PluginEventManager.PLAYLIST_REMOVED,new Object[]{sage.plugin.PluginEventManager.VAR_PLAYLIST,p,sage.plugin.PluginEventManager.VAR_UICONTEXT,(stack.getUIMgr() != null ? stack.getUIMgr().getLocalUIClientName() : null)});
}
return null;
}
| Removes a specified Playlist from the databse completely. The files in the Playlist will NOT be removed. |
public static void stopStoreSessionListeners(GridKernalContext ctx,Collection<CacheStoreSessionListener> sesLsnrs) throws IgniteCheckedException {
if (sesLsnrs == null) return;
for ( CacheStoreSessionListener lsnr : sesLsnrs) {
if (lsnr instanceof LifecycleAware) ((LifecycleAware)lsnr).stop();
ctx.resource().cleanupGeneric(lsnr);
}
}
| Stops store session listeners. |
private void updateProgress(String progressLabel,int progress){
if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) {
myHost.updateProgress(progressLabel,progress);
}
previousProgress=progress;
previousProgressLabel=progressLabel;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
public synchronized void engineStore(OutputStream stream,char[] password) throws IOException, NoSuchAlgorithmException, CertificateException {
if (password == null) {
throw new IllegalArgumentException("password can't be null");
}
DerOutputStream pfx=new DerOutputStream();
DerOutputStream version=new DerOutputStream();
version.putInteger(VERSION_3);
byte[] pfxVersion=version.toByteArray();
pfx.write(pfxVersion);
DerOutputStream authSafe=new DerOutputStream();
DerOutputStream authSafeContentInfo=new DerOutputStream();
if (privateKeyCount > 0 || secretKeyCount > 0) {
if (debug != null) {
debug.println("Storing " + (privateKeyCount + secretKeyCount) + " protected key(s) in a PKCS#7 data content-type");
}
byte[] safeContentData=createSafeContent();
ContentInfo dataContentInfo=new ContentInfo(safeContentData);
dataContentInfo.encode(authSafeContentInfo);
}
if (certificateCount > 0) {
if (debug != null) {
debug.println("Storing " + certificateCount + " certificate(s) in a PKCS#7 encryptedData content-type");
}
byte[] encrData=createEncryptedData(password);
ContentInfo encrContentInfo=new ContentInfo(ContentInfo.ENCRYPTED_DATA_OID,new DerValue(encrData));
encrContentInfo.encode(authSafeContentInfo);
}
DerOutputStream cInfo=new DerOutputStream();
cInfo.write(DerValue.tag_SequenceOf,authSafeContentInfo);
byte[] authenticatedSafe=cInfo.toByteArray();
ContentInfo contentInfo=new ContentInfo(authenticatedSafe);
contentInfo.encode(authSafe);
byte[] authSafeData=authSafe.toByteArray();
pfx.write(authSafeData);
byte[] macData=calculateMac(password,authenticatedSafe);
pfx.write(macData);
DerOutputStream pfxout=new DerOutputStream();
pfxout.write(DerValue.tag_Sequence,pfx);
byte[] pfxData=pfxout.toByteArray();
stream.write(pfxData);
stream.flush();
}
| Stores this keystore to the given output stream, and protects its integrity with the given password. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.