code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public List<Object> extractPropertyValues(Object data,Map<String,String> valueMap,int cascade,Network network,Map<String,Vertex> processed){
List<Object> values=new ArrayList<Object>();
Set<Object> valuesSet=new HashSet<Object>();
if (data instanceof JSONArray) {
for ( Object value : ((JSONArray)data)) {
if (value instanceof JSONObject) {
value=((JSONObject)value).get("mainsnak");
if (value instanceof JSONObject) {
value=((JSONObject)value).get("datavalue");
if (value instanceof JSONObject) {
value=((JSONObject)value).get("value");
if (value instanceof JSONObject) {
Object id=((JSONObject)value).get("numeric-id");
if (id instanceof Integer) {
String qid="Q" + id;
if (cascade > 0) {
Vertex nested=processId((String)qid,cascade - 1,false,"",network,processed);
if (!valuesSet.contains(nested)) {
valuesSet.add(nested);
values.add(nested);
}
}
else if (valueMap != null) {
String label=valueMap.get(qid);
if (label != null) {
if (!valuesSet.contains(label)) {
valuesSet.add(label);
values.add(label);
}
}
}
continue;
}
Object propertyValue=((JSONObject)value).get("text");
if (propertyValue == null) {
propertyValue=((JSONObject)value).get("time");
if (propertyValue instanceof String) {
try {
propertyValue=Utils.parseDate(((String)propertyValue).substring(1,((String)propertyValue).indexOf('T')));
}
catch ( Exception exception) {
}
}
}
else if (propertyValue instanceof String) {
propertyValue=network.createWord((String)propertyValue);
}
if (propertyValue != null) {
if (!valuesSet.contains(propertyValue)) {
valuesSet.add(propertyValue);
values.add(propertyValue);
}
}
}
}
}
}
}
}
return values;
}
| Extract the relevant data from the wikidata claims. |
private static void uaRIMinGe(MatrixBlock in,MatrixBlock out,double[] bv,int[] bvi,BinaryOperator bOp) throws DMLRuntimeException {
int ind0=uariminGe(0.0,bv,bvi,bOp);
int m=in.rlen;
for (int i=0; i < m; i++) {
double ai=in.quickGetValue(i,0);
int ind=(ai == 0) ? ind0 : uariminGe(ai,bv,bvi,bOp);
out.quickSetValue(i,0,ind);
}
}
| UAgg rowIndexMin for GreaterThanEqual operator |
public Node build(){
ContainerNode ret=null;
if (nodeType == NodeType.Component) {
ret=new Component();
((Component)ret).setComponentType(componentType);
}
else if (nodeType == NodeType.Consumer) {
ret=new Consumer();
((Consumer)ret).setEndpointType(endpointType);
}
else if (nodeType == NodeType.Producer) {
ret=new Producer();
((Producer)ret).setEndpointType(endpointType);
}
ret.setCorrelationIds(correlationIds);
ret.setOperation(operation);
ret.setProperties(properties);
ret.setUri(uri);
ret.setDuration(duration);
ret.setTimestamp(timestamp);
for (int i=0; i < nodes.size(); i++) {
ret.getNodes().add(nodes.get(i).build());
}
return ret;
}
| This method builds the node hierarchy. |
protected static final void adjustModuleName(DebugModule d){
d.name=adjustModuleName(d.name);
}
| Royale Enhancement Request: 53160... If a debug module represents an AS2 class, the module name should be in the form of classname: fileURL Matador uses classname: absolutePath (note: absolute, not cannonical) |
public CF4(int numberOfVariables){
super(numberOfVariables,2,1);
}
| Constructs a CF4 test problem with the specified number of decision variables. |
public AnchorPane createFingerPrintPanel(ArrayList<FpPanel> fingerprintPanelList){
return createFingerPrintPanel(fingerprintPanelList,null);
}
| creates a new fingerprint panel from scratch (new uuid) |
public double evaluate(double xp){
double num=0.0;
double denom=0.0;
for (int j=0; j <= order; j++) {
if (xp == x[j]) {
num=y[j];
denom=1.0;
break;
}
double term=weights[j] / (xp - x[j]);
num+=term * y[j];
denom+=term;
}
return num / denom;
}
| Evaluates the Lagrange polynomial at real value xp. Evaluates the Lagrange polynomial using the barycentric formula. |
public TrackerDataHelper(Context context,IFormatter formatter){
mContext=context;
mFormatter=formatter;
}
| Creates instance |
public NoAvailableServersException(String message,Throwable cause){
super(message,cause);
}
| Create a new instance of NoAvailableServersException with a detail message and cause |
@Override protected int sizeOf(String key,BitmapDrawable value){
final int bitmapSize=ImageProvider.getBitmapSize(value) / 1024;
return bitmapSize == 0 ? 1 : bitmapSize;
}
| Measure item size in kilobytes rather than units which is more practical for a bitmap cache |
public GUIFragmentLoader(Map<String,GUIFragmentProvider> guiFragmentProviderMap){
this.guiFragmentProviderMap=guiFragmentProviderMap;
classCache=new HashMap<String,IGenerator>();
}
| Creates a new instance of XMLRulesLoader |
public Mailbox loadMailbox(MailboxSession session,File root,String namespace,String user,String folderName) throws MailboxException {
String mailboxName=getMailboxNameFromFolderName(folderName);
return loadMailbox(session,new File(root,folderName),new MailboxPath(namespace,user,mailboxName));
}
| Creates a Mailbox object with data loaded from the file system |
@After public void teardown(){
logger.info("--> resetting breaker settings");
Settings resetSettings=settingsBuilder().put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_LIMIT_SETTING,HierarchyCircuitBreakerService.DEFAULT_FIELDDATA_BREAKER_LIMIT).put(HierarchyCircuitBreakerService.FIELDDATA_CIRCUIT_BREAKER_OVERHEAD_SETTING,HierarchyCircuitBreakerService.DEFAULT_FIELDDATA_OVERHEAD_CONSTANT).put(HierarchyCircuitBreakerService.REQUEST_CIRCUIT_BREAKER_LIMIT_SETTING,HierarchyCircuitBreakerService.DEFAULT_REQUEST_BREAKER_LIMIT).put(HierarchyCircuitBreakerService.REQUEST_CIRCUIT_BREAKER_TYPE_SETTING,CircuitBreaker.Type.MEMORY).put(HierarchyCircuitBreakerService.REQUEST_CIRCUIT_BREAKER_OVERHEAD_SETTING,1.0).build();
assertAcked(client().admin().cluster().prepareUpdateSettings().setTransientSettings(resetSettings));
}
| Reset all breaker settings back to their defaults |
protected void processAttribute(Vector attrNames,Vector attrValues,Vector attrTypes) throws Exception {
String key=XMLUtil.scanIdentifier(this.reader);
XMLUtil.skipWhitespace(this.reader,null);
if (!XMLUtil.read(this.reader,'&').equals("=")) {
XMLUtil.errorExpectedInput(reader.getSystemID(),reader.getLineNr(),"`='");
}
XMLUtil.skipWhitespace(this.reader,null);
String value=XMLUtil.scanString(this.reader,'&',this.entityResolver);
attrNames.addElement(key);
attrValues.addElement(value);
attrTypes.addElement("CDATA");
this.validator.attributeAdded(key,value,this.reader.getSystemID(),this.reader.getLineNr());
}
| Processes an attribute of an element. |
@Override public void deleteSingleVolumeSnapshot(StorageSystem storage,URI snapshot,TaskCompleter taskCompleter) throws DeviceControllerException {
_log.info("START deleteSingleVolumeSnapshot");
try {
callEMCRefreshIfRequired(_dbClient,_helper,storage,Arrays.asList(snapshot));
BlockSnapshot snap=_dbClient.queryObject(BlockSnapshot.class,snapshot);
CIMObjectPath syncObjectPath=_cimPath.getSyncObject(storage,snap);
if (_helper.checkExists(storage,syncObjectPath,false,false) != null) {
deactivateSnapshot(storage,snap,syncObjectPath);
if (storage.checkIfVmax3()) {
_helper.removeVolumeFromStorageGroupsIfVolumeIsNotInAnyMV(storage,snap);
_helper.removeVolumeFromParkingSLOStorageGroup(storage,snap.getNativeId(),false);
_log.info("Done invoking remove volume {} from parking SLO storage group",snap.getNativeId());
CIMArgument[] inArgsDetach=_helper.getUnlinkBlockSnapshotSessionTargetInputArguments(syncObjectPath);
CIMArgument[] outArgsDetach=new CIMArgument[5];
CIMObjectPath replicationSvcPath=_cimPath.getControllerReplicationSvcPath(storage);
_helper.invokeMethodSynchronously(storage,replicationSvcPath,SmisConstants.MODIFY_REPLICA_SYNCHRONIZATION,inArgsDetach,outArgsDetach,null);
CIMObjectPath configSvcPath=_cimPath.getConfigSvcPath(storage);
CIMArgument[] inArgs=_helper.getDeleteVolumesInputArguments(storage,new String[]{snap.getNativeId()});
CIMArgument[] outArgs=new CIMArgument[5];
_helper.invokeMethodSynchronously(storage,configSvcPath,SmisConstants.RETURN_ELEMENTS_TO_STORAGE_POOL,inArgs,outArgs,null);
}
else {
CIMArgument[] outArgs=new CIMArgument[5];
_helper.callModifyReplica(storage,_helper.getDeleteSnapshotSynchronousInputArguments(syncObjectPath),outArgs);
}
snap.setInactive(true);
snap.setIsSyncActive(false);
_dbClient.updateObject(snap);
taskCompleter.ready(_dbClient);
}
else {
snap.setInactive(true);
snap.setIsSyncActive(false);
_dbClient.updateObject(snap);
taskCompleter.ready(_dbClient);
}
}
catch ( WBEMException e) {
String message=String.format("Error encountered during delete snapshot %s on array %s",snapshot.toString(),storage.getSerialNumber());
_log.error(message,e);
ServiceError error=DeviceControllerErrors.smis.unableToCallStorageProvider(e.getMessage());
taskCompleter.error(_dbClient,error);
}
catch ( Exception e) {
String message=String.format("Generic exception when trying to delete snapshot %s on array %s",snapshot.toString(),storage.getSerialNumber());
_log.error(message,e);
ServiceError error=DeviceControllerErrors.smis.methodFailed("deleteSingleVolumeSnapshot",e.getMessage());
taskCompleter.error(_dbClient,error);
}
}
| Should implement deletion of single volume snapshot. That is, deleting a snap that was created independent of other volumes. |
public boolean hasBProfile(){
return DSSXMLUtils.isNotEmpty(signatureElement,xPathQueryHolder.XPATH_SIGNED_SIGNATURE_PROPERTIES);
}
| Checks the presence of ... segment in the signature, what is the proof -B profile existence |
public static void shrinkSelectionUp(final ZyGraph graph){
checkArguments(graph);
final SelectableGraph<NaviNode> selectableGraph=SelectableGraph.wrap(graph);
GraphHelpers.shrinkSelectionUp(selectableGraph);
}
| Does a Shrink Selection Up operation on a graph. |
public Finished(byte[] bytes){
data=bytes;
length=data.length;
}
| Creates outbound message |
public static void init(Context context){
if (cameraManager == null) {
cameraManager=new CameraManager(context);
}
}
| Initializes this static object with the Context of the calling Activity. |
public void runInjectorPipeline(String inputFile,String topic){
runInjectorPipeline(TextIO.Read.from(inputFile),topic,null);
}
| Runs a batch pipeline to inject data into the PubSubIO input topic. <p>The injector pipeline will read from the given text file, and inject data into the Google Cloud Pub/Sub topic. |
public void updateCharacterStream(String columnName,java.io.Reader reader,int length) throws SQLException {
updateCharacterStream(findColumn(columnName),reader,length);
}
| JDBC 2.0 Update a column with a character stream value. The updateXXX() methods are used to update column values in the current row, or the insert row. The updateXXX() methods do not update the underlying database, instead the updateRow() or insertRow() methods are called to update the database. |
public boolean load(Element catalogTrees){
loadCatalogTrees(catalogTrees);
return true;
}
| Create a CatalogTreeManager object of the correct class, then register and fill it. |
private int nextInt(double theMean){
double xm=theMean;
double g=this.cached_g;
if (xm == -1.0) return 0;
if (xm < SWITCH_MEAN) {
int poisson=-1;
double product=1;
do {
poisson++;
product*=randomGenerator.raw();
}
while (product >= g);
return poisson;
}
else if (xm < MEAN_MAX) {
double t;
double em;
double sq=this.cached_sq;
double alxm=this.cached_alxm;
RandomEngine rand=this.randomGenerator;
do {
double y;
do {
y=Math.tan(Math.PI * rand.raw());
em=sq * y + xm;
}
while (em < 0.0);
em=(double)(int)(em);
t=0.9 * (1.0 + y * y) * Math.exp(em * alxm - logGamma(em + 1.0) - g);
}
while (rand.raw() > t);
return (int)em;
}
else {
return (int)xm;
}
}
| Returns a random number from the distribution; bypasses the internal state. |
public String toString(){
final StringBuilder sb=new StringBuilder();
sb.append(getClass().getName());
sb.append("{icuVersion=" + icuVersion);
sb.append(",ucolRuntimeVersion=" + ucolRuntimeVersion);
sb.append(",ucolBuilderVersion=" + ucolBuilderVersion);
sb.append(",ucolTailoringsVersion=" + ucolTailoringsVersion);
sb.append("}");
return sb.toString();
}
| A human readable representation of the data record. |
public void dispose(){
graphics.dispose();
graphics=null;
}
| Overrides <code>Graphics.dispose</code>. |
public void loadAccess(boolean reload){
loadOrgAccess(reload);
loadTableAccess(reload);
loadTableInfo(reload);
loadColumnAccess(reload);
loadRecordAccess(reload);
if (reload) {
m_windowAccess=null;
m_processAccess=null;
m_taskAccess=null;
m_workflowAccess=null;
m_formAccess=null;
m_browseAccess=null;
}
loadIncludedRoles(reload);
}
| Load Access Info |
@Override public void generateCode(BlockScope currentScope,boolean valueRequired){
this.expression.generateCode(currentScope,true);
}
| Code generation for instanceOfExpression |
public static String normalizeShort(String value){
return normalizeIntegerValue(value,"-32768","32767");
}
| Normalizes an xsd:short. |
public static void requireAnyAttribute(SimpleMethod method,Element element,String... attributeNames) throws ValidationException {
StringBuilder sb=new StringBuilder();
for ( String name : attributeNames) {
String attributeValue=element.getAttribute(name);
if (attributeValue.length() > 0) {
return;
}
if (sb.length() > 0) {
sb.append(" ");
}
sb.append("\"").append(name).append("\"");
}
handleError("Element must include one of " + sb + " attributes.",method,element);
}
| Tests <code>element</code> for any one required attribute from a set of attribute names. |
public float put(K key,float value){
float previous=0;
int index=insertionIndex(key);
boolean isNewMapping=true;
if (index < 0) {
index=-index - 1;
previous=_values[index];
isNewMapping=false;
}
K oldKey=(K)_set[index];
_set[index]=key;
_values[index]=value;
if (isNewMapping) {
postInsertHook(oldKey == null);
}
return previous;
}
| Inserts a key/value pair into the map. |
private SoundGroup initSoundSystem(){
SoundGroup group=getSoundSystemFacade().getGroup(SoundLayer.USER_INTERFACE.groupName);
group.loadSound("harp-1","harp-1.ogg",SoundFileType.OGG,false);
group.loadSound("click-4","click-4.ogg",SoundFileType.OGG,false);
group.loadSound("click-5","click-5.ogg",SoundFileType.OGG,false);
group.loadSound("click-6","click-6.ogg",SoundFileType.OGG,false);
group.loadSound("click-8","click-8.ogg",SoundFileType.OGG,false);
group.loadSound("click-10","click-10.ogg",SoundFileType.OGG,false);
return group;
}
| Initialize the sounds used by the user interfase. |
public boolean hasUnreadMessages(){
synchronized (this) {
return mHasUnreadMessages;
}
}
| Returns true if there are any unread messages in the conversation. |
public void reset(){
super.reset();
fmod.reset();
}
| Resets this wave and its modulating wave as well. |
public static ListViewLicenseFragment newInstance(int[] licenseIDs){
return (ListViewLicenseFragment)onNewInstance(new ListViewLicenseFragment(),licenseIDs);
}
| Use this factory method to create a new instance of this fragment using the provided parameters. |
@Override public void onOverScrolled(OverScrollMode mode){
if (!isEnabled()) {
return;
}
if (isDown) {
switch (mode) {
case NONE:
overScrollMode=mode;
break;
case BOTTOM:
if (pullForActionMode.equals(PullForActionMode.BOTTOM) || pullForActionMode.equals(PullForActionMode.TOP_AND_BOTTOM)) {
overScrollMode=mode;
}
else {
overScrollMode=OverScrollMode.NONE;
}
break;
case TOP:
if (pullForActionMode.equals(PullForActionMode.TOP) || pullForActionMode.equals(PullForActionMode.TOP_AND_BOTTOM)) {
overScrollMode=mode;
}
else {
overScrollMode=OverScrollMode.NONE;
}
break;
}
}
}
| Callback of the BouncingListView |
public void testGetF23Momentary(){
AbstractThrottle instance=new AbstractThrottleImpl();
boolean expResult=false;
boolean result=instance.getF23Momentary();
assertEquals(expResult,result);
}
| Test of getF23Momentary method, of class AbstractThrottle. |
Type fold1(int opcode,Type operand){
try {
Object od=operand.constValue();
switch (opcode) {
case nop:
return operand;
case ineg:
return syms.intType.constType(-intValue(od));
case ixor:
return syms.intType.constType(~intValue(od));
case bool_not:
return syms.booleanType.constType(b2i(intValue(od) == 0));
case ifeq:
return syms.booleanType.constType(b2i(intValue(od) == 0));
case ifne:
return syms.booleanType.constType(b2i(intValue(od) != 0));
case iflt:
return syms.booleanType.constType(b2i(intValue(od) < 0));
case ifgt:
return syms.booleanType.constType(b2i(intValue(od) > 0));
case ifle:
return syms.booleanType.constType(b2i(intValue(od) <= 0));
case ifge:
return syms.booleanType.constType(b2i(intValue(od) >= 0));
case lneg:
return syms.longType.constType(new Long(-longValue(od)));
case lxor:
return syms.longType.constType(new Long(~longValue(od)));
case fneg:
return syms.floatType.constType(new Float(-floatValue(od)));
case dneg:
return syms.doubleType.constType(new Double(-doubleValue(od)));
default :
return null;
}
}
catch (ArithmeticException e) {
return null;
}
}
| Fold unary operation. |
@GenerateLink(rel="download artifact") @GET @Path("/public/download/{artifact}") @Produces(MediaType.APPLICATION_OCTET_STREAM) public Response downloadPublicArtifactLatestVersion(@PathParam("artifact") final String artifact,@QueryParam("label") final String label){
try {
String version=artifactStorage.getLatestVersion(artifact,label);
return doDownloadArtifact(artifact,version,null);
}
catch ( ArtifactNotFoundException e) {
return Response.status(Response.Status.NOT_FOUND).entity(e.getMessage()).build();
}
catch ( Exception e) {
LOG.error(e.getMessage(),e);
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("Unexpected error. Can't download the latest version of artifact '" + artifact).build();
}
}
| Downloads the latest version of the artifact. |
public long minRate(){
Long min=null;
for ( Sample s : samples) {
if (min == null) {
min=new Long(s.rate());
}
min=Math.min(min,s.rate());
}
return min.longValue();
}
| Returns the minimum of the message rates in the SampleGroup. |
public void updateQuantityCsv(ItemBean original,ItemBean itemToAdd,boolean add){
BigDecimal originalQuantity=original.getQtyCsv();
BigDecimal quantityToAdd=itemToAdd.getQtyCsv();
BigDecimal finalQuantity=null;
if (!add) finalQuantity=originalQuantity.subtract(quantityToAdd);
else finalQuantity=originalQuantity.add(quantityToAdd);
original.setQtyCsv(finalQuantity);
}
| Update Quantity CSV in inventory |
public AggregateableEvaluation(Instances data,CostMatrix costMatrix) throws Exception {
super(data,costMatrix);
m_delegate=new weka.classifiers.evaluation.AggregateableEvaluation(data,costMatrix);
}
| Constructs a new AggregateableEvaluation object |
public static double tanh(double value){
if (USE_JDK_MATH) {
return Math.tanh(value);
}
boolean negateResult=false;
if (value < 0.0) {
value=-value;
negateResult=true;
}
double z;
if (value < TANH_1_THRESHOLD) {
if (value < TWO_POW_N55) {
return negateResult ? -value * (1.0 - value) : value * (1.0 + value);
}
else if (value >= 1) {
z=1.0 - 2.0 / (expm1(value + value) + 2.0);
}
else {
final double t=expm1(-(value + value));
z=-t / (t + 2.0);
}
}
else {
z=value != value ? Double.NaN : 1.0;
}
return negateResult ? -z : z;
}
| Some properties of tanh(x) = sinh(x)/cosh(x) = (exp(2*x)-1)/(exp(2*x)+1): 1) defined on ]-Infinity,+Infinity[ 2) result in ]-1,1[ 3) tanh(x) = -tanh(-x) (implies tanh(0) = 0) 4) tanh(epsilon) ~= epsilon 5) lim(tanh(x),x->+Infinity) = 1 6) reaches 1 (double loss of precision) for x = 19.061547465398498 |
public Source<Double> fromNegativeDoubleMaxToNegativeZero(){
return Compositions.weightWithValues(Doubles.fromNegativeDoubleMaxToNegativeZero(),-Double.MAX_VALUE,-0d);
}
| Generates Doubles inclusively bounded below by -Double.MAX_VALUE and above by a value very close to zero on the negative side. The Source is weighted so it is likely to generate the upper and lower limits of the domain one or more times. |
public static double accumulateSum(final Vec w,final Vec x,final Vec y,final Function f){
if (w.length() != x.length() || x.length() != y.length()) throw new ArithmeticException("All 3 vector inputs must have equal lengths");
double val=0;
final boolean skipZeros=f.f(0) == 0;
final boolean wSparse=w.isSparse();
final boolean xSparse=x.isSparse();
final boolean ySparse=y.isSparse();
if (wSparse && !xSparse && !ySparse) {
for ( IndexValue wiv : w) {
final int idx=wiv.getIndex();
val+=wiv.getValue() * f.f(x.get(idx) - y.get(idx));
}
}
else if (!wSparse && !xSparse && !ySparse) {
for (int i=0; i < w.length(); i++) val+=w.get(i) * f.f(x.get(i) - y.get(i));
}
else {
Iterator<IndexValue> xIter=x.iterator();
Iterator<IndexValue> yIter=y.iterator();
IndexValue xiv=xIter.hasNext() ? xIter.next() : badIV;
IndexValue yiv=yIter.hasNext() ? yIter.next() : badIV;
for ( IndexValue wiv : w) {
int index=wiv.getIndex();
double w_i=wiv.getValue();
while (xiv.getIndex() < index && xIter.hasNext()) xiv=xIter.next();
while (yiv.getIndex() < index && yIter.hasNext()) yiv=yIter.next();
final double x_i, y_i;
if (xiv.getIndex() == index) x_i=xiv.getValue();
else x_i=0;
if (yiv.getIndex() == index) y_i=yiv.getValue();
else y_i=0;
if (skipZeros && x_i == 0 && y_i == 0) continue;
val+=w_i * f.f(x_i - y_i);
}
}
return val;
}
| Computes the result of <big>∑</big><sub>∀ i ∈ |w|</sub> w<sub>i</sub> f(x<sub>i</sub>-y<sub>i</sub>) |
public String toString(){
if (!parsed) return "Version[unknown]";
if (!preRelease) return String.format("Version[%s.%s.%s]",major,minor,build);
else return String.format("Version[%s.%s.%s-%s%s]",major,minor,build,prebuild,prereleaseType);
}
| Convert the Version to String Format, for use in printing to the console or other implementations |
public synchronized void reset(){
bufferHolder.setCollection(new LinkedList());
}
| Reset BufferList. It will empty the buffer and leave its size at the current value |
@DSComment("From safe class list") @DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:33:23.180 -0500",hash_original_method="A3423B1919CBB5E5DDAE8E35A522AED2",hash_generated_method="C622C575F82B87F3E28E2B38FD9B52B9") public int keyAt(int index){
return mKeys[index];
}
| Given an index in the range <code>0...size()-1</code>, returns the key from the <code>index</code>th key-value mapping that this SparseIntArray stores. |
@DSComment("Event associated with motion") @DSSafe(DSCat.GUI) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:29:10.770 -0500",hash_original_method="C4E1548FEFF7CE0FD853413E91CFBE59",hash_generated_method="BB84597C158113D132EC190F62F58E4F") static public MotionEvent obtain(long downTime,long eventTime,int action,float x,float y,int metaState){
return obtain(downTime,eventTime,action,x,y,1.0f,1.0f,metaState,1.0f,1.0f,0,0);
}
| Create a new MotionEvent, filling in a subset of the basic motion values. Those not specified here are: device id (always 0), pressure and size (always 1), x and y precision (always 1), and edgeFlags (always 0). |
public static boolean reflectionEquals(final Object lhs,final Object rhs,final String... excludeFields){
return reflectionEquals(lhs,rhs,false,null,excludeFields);
}
| <p>This method uses reflection to determine if the two <code>Object</code>s are equal.</p> <p>It uses <code>AccessibleObject.setAccessible</code> to gain access to private fields. This means that it will throw a security exception if run under a security manager, if the permissions are not set up correctly. It is also not as efficient as testing explicitly. Non-primitive fields are compared using <code>equals()</code>.</p> <p>Transient members will be not be tested, as they are likely derived fields, and not part of the value of the Object.</p> <p>Static fields will not be tested. Superclass fields will be included.</p> |
public void resumeJob(JobKey jobKey) throws SchedulerException {
sched.resumeJob(jobKey);
}
| <p> Calls the equivalent method on the 'proxied' <code>QuartzScheduler</code>. </p> |
protected void assignTextContent(TikXmlConfig config,String textContent,T value){
}
| Override this method if your chile element has a text content |
@Override public int available() throws IOException {
return wrapped.available();
}
| Overrides behavior of GZIPInputStream which assumes we have all the data available which is not true for streaming. We instead rely on the underlying stream to tell us how much data is available. <p> Programs should not count on this method to return the actual number of bytes that could be read without blocking. |
public EsriPointList(){
super();
setType(SHAPE_TYPE_POINT);
}
| Construct an EsriPointList. |
public final void createTables(EXT_TABLES_SQL[] tables) throws AdeException {
if (tables == null) {
return;
}
final IDataStoreUser ud=Ade.getAde().getDataStore().user();
for (int i=0; i < tables.length; i++) {
final String sql=String.format("CREATE TABLE %s (%s)",tables[i].name(),tables[i].create());
logger.trace(sql);
ud.executeDml(sql);
}
}
| Create given tables. |
public void close(){
if (database != null) {
this.database.close();
}
}
| Close the database connection. |
public Workflow.Method updateConsistencyGroupReadOnlyStateMethod(List<URI> vplexVolumeURIs,Boolean isReadOnly){
return new Workflow.Method("updateConsistencyGroupReadOnlyState",vplexVolumeURIs,isReadOnly);
}
| Method to update ConsistencyGroup read-only state, must match args of updateConsistencyGroupReadOnlyState (except stepId) |
public GlobalVisualEffectEvent(String effectName,int duration,int strength){
super(Events.GLOBAL_VISUAL);
put(NAME_ATTR,effectName);
put(DURATION_ATTR,duration);
put(STRENGTH_ATTR,strength);
}
| Create a new GlobalVisualEffectEvent with a specified strength. |
public boolean removeLast(K obj){
Entry<K> x=head;
if (x == null) {
return false;
}
Entry<K> prev=null;
while (x.next != null) {
prev=x;
x=x.next;
}
if (x.obj != obj) {
return false;
}
if (prev != null) {
prev.next=null;
}
if (head == tail) {
head=prev;
}
tail=prev;
return true;
}
| Remove the last element, if it matches. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:28:38.287 -0500",hash_original_method="80FE207FA2FD7B3EC5D1B03F798F20EC",hash_generated_method="1C849907C54C6142A002D3424F672FE5") public static void appendEscapedSQLString(StringBuilder sb,String sqlString){
sb.append('\'');
if (sqlString.indexOf('\'') != -1) {
int length=sqlString.length();
for (int i=0; i < length; i++) {
char c=sqlString.charAt(i);
if (c == '\'') {
sb.append('\'');
}
sb.append(c);
}
}
else sb.append(sqlString);
sb.append('\'');
}
| Appends an SQL string to the given StringBuilder, including the opening and closing single quotes. Any single quotes internal to sqlString will be escaped. This method is deprecated because we want to encourage everyone to use the "?" binding form. However, when implementing a ContentProvider, one may want to add WHERE clauses that were not provided by the caller. Since "?" is a positional form, using it in this case could break the caller because the indexes would be shifted to accomodate the ContentProvider's internal bindings. In that case, it may be necessary to construct a WHERE clause manually. This method is useful for those cases. |
public void unsetNextExcuteDate(){
issetBitfield=EncodingUtils.clearBit(issetBitfield,NEXTEXCUTEDATE_ISSET_ID);
}
| Description: <br> |
@Override public void putAll(Map<? extends K,? extends V> map){
ensureCapacity(map.size());
super.putAll(map);
}
| Copies all the mappings in the specified map to this map. These mappings will replace all mappings that this map had for any of the keys currently in the given map. |
@SuppressWarnings("unchecked") public Set<File> glob(Draft2Job job,File workingDir,Object glob) throws Draft2GlobException {
Preconditions.checkNotNull(job);
Preconditions.checkNotNull(workingDir);
if (Draft2ExpressionBeanHelper.isExpression(glob)) {
try {
glob=Draft2ExpressionBeanHelper.<String>evaluate(job,glob);
}
catch ( Draft2ExpressionException e) {
logger.error("Failed to evaluate glob " + glob,e);
throw new Draft2GlobException("Failed to evaluate glob " + glob,e);
}
}
if (glob == null) {
return Collections.<File>emptySet();
}
List<String> globs=new ArrayList<>();
if (glob instanceof List<?>) {
globs=(List<String>)glob;
}
else {
globs.add((String)glob);
}
Set<File> files=new HashSet<File>();
for ( String singleGlob : globs) {
List<File> globDirs=new ArrayList<File>();
if (singleGlob.startsWith("/")) {
File globDir=new File(singleGlob).getParentFile();
globDirs.add(globDir);
String globString=new File(singleGlob).getName();
files.addAll(listDir(globString,false,globDirs));
}
else if (singleGlob.contains("/") && !(singleGlob.startsWith("/"))) {
String[] splitGlob=singleGlob.split("/");
globDirs.add(workingDir);
for (int i=0; i < splitGlob.length - 1; i++) {
if (splitGlob[i].equals("..")) {
List<File> newGlobDirs=new ArrayList<File>();
for ( File dir : globDirs) {
newGlobDirs.add(dir.getParentFile());
}
globDirs=newGlobDirs;
}
else {
Set<File> newGlobDirs=listDir(splitGlob[i],true,globDirs);
globDirs.clear();
for ( File dir : newGlobDirs) {
globDirs.add(dir);
}
}
}
files.addAll(listDir(splitGlob[splitGlob.length - 1],false,globDirs));
}
else {
globDirs.add(workingDir);
files.addAll(listDir(singleGlob,false,globDirs));
}
}
return files;
}
| Find all files that match GLOB inside the working directory |
public boolean matchesNormalizedStart(final String text){
return matchesStart(ConversationParser.parseAsMatcher(text));
}
| Check if the Sentence beginning matches the given String. The match Sentence can contain explicit expressions, which are compared after normalizing, or ExpressionType specifiers like "VER" or "SUB*" in upper case. |
private boolean isValidToken(String s){
int len=s.length();
if (len > 0) {
for (int i=0; i < len; ++i) {
char c=s.charAt(i);
if (!isTokenChar(c)) {
return false;
}
}
return true;
}
else {
return false;
}
}
| Determines whether or not a given string is a legal token. |
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. |
@Override public void propertyChange(PropertyChangeEvent evt){
if (evt.getPropertyName().equals(ClassField.PROPERTY_PSICLASS)) {
if (evt.getNewValue() == null) {
clear();
}
else {
setEnabled(true);
if (myPsiClass == null || !myPsiClass.equals(evt.getNewValue())) {
myPsiClass=(PsiClass)evt.getNewValue();
initValues();
}
}
}
}
| Called when ClassField is set and when user selects entry in the MethodDropDown |
public void countUp(){
count.addAndGet(1);
}
| Increments the count. Once the count has reached zero once, incrementing the count back above zero will have no affect. |
public void updateAlertDefinitions(StatAlertDefinition[] alertDefs,int actionCode){
sendAsync(UpdateAlertDefinitionMessage.create(alertDefs,actionCode));
}
| This method would be used to set Sta Alert Definitions for the GemFireVM. This method would mostly be called on each member after initial set up whenever one or more Stat Alert Definitions get added/updated/removed. |
public int costInline(int thresh,Environment env,Context ctx){
return 1 + expr.costInline(thresh,env,ctx);
}
| The cost of inlining this statement |
public static Object binaryOperation(Object obj1,Object obj2,int kind) throws UtilEvalError {
if (obj1 == NULL || obj2 == NULL) throw new UtilEvalError("Null value or 'null' literal in binary operation");
if (obj1 == VOID || obj2 == VOID) throw new UtilEvalError("Undefined variable, class, or 'void' literal in binary operation");
Class lhsOrgType=obj1.getClass();
Class rhsOrgType=obj2.getClass();
if (obj1 instanceof Primitive) obj1=((Primitive)obj1).getValue();
if (obj2 instanceof Primitive) obj2=((Primitive)obj2).getValue();
Object[] operands=promotePrimitives(obj1,obj2);
Object lhs=operands[0];
Object rhs=operands[1];
if (lhs.getClass() != rhs.getClass()) throw new UtilEvalError("Type mismatch in operator. " + lhs.getClass() + " cannot be used with "+ rhs.getClass());
Object result;
try {
result=binaryOperationImpl(lhs,rhs,kind);
}
catch ( ArithmeticException e) {
throw new UtilTargetError("Arithemetic Exception in binary op",e);
}
if (result instanceof Boolean) return ((Boolean)result).booleanValue() ? Primitive.TRUE : Primitive.FALSE;
else if ((lhsOrgType == Primitive.class && rhsOrgType == Primitive.class)) return new Primitive(result);
else return result;
}
| Perform a binary operation on two Primitives or wrapper types. If both original args were Primitives return a Primitive result else it was mixed (wrapper/primitive) return the wrapper type. The exception is for boolean operations where we will return the primitive type either way. |
int writeInt2(int n,int offset){
byte[] temp={(byte)((n >> 8) & 0xff),(byte)(n & 0xff)};
return writeBytes(temp,offset);
}
| Write a two-byte integer into the pngBytes array at a given position. |
public void startElement(String ns,String localName,String name,Attributes atts) throws org.xml.sax.SAXException {
Element elem;
if ((null == ns) || (ns.length() == 0)) elem=m_doc.createElementNS(null,name);
else elem=m_doc.createElementNS(ns,name);
append(elem);
try {
int nAtts=atts.getLength();
if (0 != nAtts) {
for (int i=0; i < nAtts; i++) {
if (atts.getType(i).equalsIgnoreCase("ID")) setIDAttribute(atts.getValue(i),elem);
String attrNS=atts.getURI(i);
if ("".equals(attrNS)) attrNS=null;
String attrQName=atts.getQName(i);
if (attrQName.startsWith("xmlns:")) attrNS="http://www.w3.org/2000/xmlns/";
elem.setAttributeNS(attrNS,attrQName,atts.getValue(i));
}
}
m_elemStack.push(elem);
m_currentNode=elem;
}
catch ( java.lang.Exception de) {
throw new org.xml.sax.SAXException(de);
}
}
| Receive notification of the beginning of an element. <p>The Parser will invoke this method at the beginning of every element in the XML document; there will be a corresponding endElement() event for every startElement() event (even when the element is empty). All of the element's content will be reported, in order, before the corresponding endElement() event.</p> <p>If the element name has a namespace prefix, the prefix will still be attached. Note that the attribute list provided will contain only attributes with explicit values (specified or defaulted): #IMPLIED attributes will be omitted.</p> |
public boolean equals(Object object){
return (super.equals(object) && object instanceof JobPriority);
}
| Returns whether this job priority attribute is equivalent to the passed in object. To be equivalent, all of the following conditions must be true: <OL TYPE=1> <LI> <CODE>object</CODE> is not null. <LI> <CODE>object</CODE> is an instance of class JobPriority. <LI> This job priority attribute's value and <CODE>object</CODE>'s value are equal. </OL> |
@Override public void append(String s,TextAttributeSet attrs){
int beginIndex=stringBuilder.length();
int endIndex=beginIndex + s.length();
stringBuilder.append(s);
attributeList.add(new AttributeDefinition(attrs,beginIndex,endIndex));
}
| Append a string with attributes. |
public void readFully(byte[] bytes) throws IOException {
readFully(bytes,0,bytes.length);
}
| Reads a full byte array completely. |
public SendableVideoMessage.SendableVideoMessageBuilder replyTo(Message replyTo){
this.replyTo=replyTo != null ? replyTo.getMessageId() : 0;
return this;
}
| *Optional Sets the Message object that you want to reply to |
static void compositeRequestFocus(Component component,boolean direction){
if (component instanceof Container) {
Container container=(Container)component;
if (container.isFocusCycleRoot()) {
FocusTraversalPolicy policy=container.getFocusTraversalPolicy();
Component comp=policy.getDefaultComponent(container);
if (comp != null) {
comp.requestFocus();
return;
}
}
Container rootAncestor=container.getFocusCycleRootAncestor();
if (rootAncestor != null) {
FocusTraversalPolicy policy=rootAncestor.getFocusTraversalPolicy();
Component comp;
if (direction) {
comp=policy.getComponentAfter(rootAncestor,container);
}
else {
comp=policy.getComponentBefore(rootAncestor,container);
}
if (comp != null) {
comp.requestFocus();
return;
}
}
}
component.requestFocus();
}
| Convenience method to transfer focus to the next child of component. |
public NodeList selectNodeList(Node contextNode,Node xpathnode,String str,Node namespaceNode) throws TransformerException {
if (!str.equals(xpathStr) || xpathExpression == null) {
if (xpf == null) {
xpf=XPathFactory.newInstance();
try {
xpf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,Boolean.TRUE);
}
catch ( XPathFactoryConfigurationException ex) {
throw new TransformerException("empty",ex);
}
}
XPath xpath=xpf.newXPath();
xpath.setNamespaceContext(new DOMNamespaceContext(namespaceNode));
xpathStr=str;
try {
xpathExpression=xpath.compile(xpathStr);
}
catch ( XPathExpressionException ex) {
throw new TransformerException("empty",ex);
}
}
try {
return (NodeList)xpathExpression.evaluate(contextNode,XPathConstants.NODESET);
}
catch ( XPathExpressionException ex) {
throw new TransformerException("empty",ex);
}
}
| Use an XPath string to select a nodelist. XPath namespace prefixes are resolved from the namespaceNode. |
public void initialise(int k,double epsilon) throws Exception {
this.epsilon=epsilon;
super.initialise(k);
}
| Initialises the calculator |
public LineTag createLineTag(){
LineTagImpl lineTag=new LineTagImpl();
return lineTag;
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public UnassignedDatasetException(){
super();
}
| Creates a new <code>UnassignedDatasetException</code> instance with no detail message. |
private LogPolicy addPolicy(String propertyName,boolean defaultValue){
String flag=LogManager.getLogManager().getProperty(propertyName);
if (flag != null) {
policy.put(propertyName,Boolean.parseBoolean(flag));
}
else {
policy.put(propertyName,defaultValue);
}
return this;
}
| Adds a particular configuration property for controlling content to be included in the formatter's output. |
public static <T>void subsribeToTraversable(Traversable<T> s,Subscriber<T> sub){
Javaslang.traversable(s).subscribe(sub);
}
| Have a reactive-stream subscriber subscribe to a Javaslang Stream. |
public List<NamedRelatedVirtualPoolRep> listMatchedVirtualPools(URI id){
VirtualPoolList response=client.get(VirtualPoolList.class,getIdUrl() + "/matched-vpools",id);
return defaultList(response.getVirtualPool());
}
| Lists the virtual pools which match the given storage pool by ID. <p> API Call: <tt>GET /vdc/storage-pools/{id}/matched-vpools</tt> |
@Override public void clearSession(long id){
sessionManager.clearSession(id);
}
| Clears the session associated with the id. |
private void renameHeapVariables(IR ir){
int n=ir.HIRInfo.dictionary.getNumberOfHeapVariables();
if (n == 0) {
return;
}
HashMap<Object,Stack<HeapOperand<Object>>> stacks=new HashMap<Object,Stack<HeapOperand<Object>>>(n);
for (Iterator<HeapVariable<Object>> e=ir.HIRInfo.dictionary.getHeapVariables(); e.hasNext(); ) {
HeapVariable<Object> H=e.next();
Stack<HeapOperand<Object>> S=new Stack<HeapOperand<Object>>();
S.push(new HeapOperand<Object>(H));
Object heapType=H.getHeapType();
stacks.put(heapType,S);
}
BasicBlock entry=ir.cfg.entry();
numPredProcessed=new int[ir.getMaxBasicBlockNumber()];
search2(entry,stacks);
}
| Rename the implicit heap variables in the SSA form so that each heap variable has only one definition. <p> Algorithm: Cytron et. al 91 (see renameSymbolicRegisters) |
public void delete(String name) throws IOException {
if (name.equalsIgnoreCase(NUMBER)) {
serial=null;
}
else {
throw new IOException("Attribute name not recognized by " + "CertAttrSet:CertificateSerialNumber.");
}
}
| Delete the attribute value. |
private DD arctan(DD x){
DD t=x;
DD t2=t.sqr();
DD at=new DD(0.0);
DD two=new DD(2.0);
int k=0;
DD d=new DD(1.0);
int sign=1;
while (t.doubleValue() > DD.EPS) {
k++;
if (sign < 0) at=at.subtract(t.divide(d));
else at=at.add(t.divide(d));
d=d.add(two);
t=t.multiply(t2);
sign=-sign;
}
return at;
}
| Computes the arctangent based on the Taylor series expansion arctan(x) = x - x^3 / 3 + x^5 / 5 - x^7 / 7 + ... |
public void beginShape(){
beginShape(POLYGON);
}
| Start a new shape of type POLYGON |
private void sendObjectMessage(List<TaskMessage> messages){
Session session=null;
Connection conn=null;
int sentMsgCount=0;
try {
if (messages.size() > 0) {
conn=qFactory.createConnection();
session=conn.createSession(false,Session.AUTO_ACKNOWLEDGE);
MessageProducer producer=session.createProducer(queue);
for ( TaskMessage objectToSend : messages) {
PlatformUser user=dm.getCurrentUserIfPresent();
if (user != null) {
objectToSend.setCurrentUserKey(user.getKey());
}
ObjectMessage msg=session.createObjectMessage();
msg.setObject(objectToSend);
producer.send(msg);
sentMsgCount++;
}
}
}
catch ( JMSException e) {
SaaSSystemException sse=new SaaSSystemException(e);
logger.logError(Log4jLogger.SYSTEM_LOG,sse,LogMessageIdentifier.ERROR_SEND_MESSAGE_TO_JMS_QUEUE_FAILED,getMessagesStatues(messages,sentMsgCount));
String status=getMessagesStatues(messages,sentMsgCount);
logger.logError(LogMessageIdentifier.ERROR_SEND_MESSAGE_TO_JMS_QUEUE_FAILED_DETAILS,Integer.toString(sentMsgCount),Integer.toString(messages.size()),status);
throw sse;
}
finally {
closeSession(session);
closeConnection(conn);
}
}
| Sends the message objects to the JMS queue, each of them in a single message. |
@Override public void handlePatch(Operation patch){
try {
State currentState=getState(patch);
State patchState=patch.getBody(State.class);
this.validatePatch(patchState);
this.applyPatch(currentState,patchState);
this.validateState(currentState);
patch.complete();
processPatch(patch,currentState,patchState);
}
catch ( Throwable e) {
ServiceUtils.logSevere(this,e);
if (!OperationUtils.isCompleted(patch)) {
patch.fail(e);
}
}
}
| Handle service patch. |
private void ensureAvail(int n){
if (pos + n >= buf.length) {
int newSize=Math.max(pos + n,buf.length * 2);
buf=Arrays.copyOf(buf,newSize);
}
}
| make sure there will be enought space in buffer to write N bytes |
private double[][] loadParameters(File file) throws IOException {
SampleReader reader=null;
List<double[]> parameterList=new ArrayList<double[]>();
try {
reader=new SampleReader(file,parameterFile);
while (reader.hasNext()) {
parameterList.add(toArray(reader.next()));
}
}
finally {
if (reader != null) {
reader.close();
}
}
return parameterList.toArray(new double[0][]);
}
| Returns the parameters from the specified file. |
public static boolean isAffectedByECM(Entity ae,Coords a,Coords b,List<ECMInfo> allECMInfo){
ECMInfo ecmInfo=getECMEffects(ae,a,b,true,allECMInfo);
return (ecmInfo != null) && ecmInfo.isECM();
}
| This method checks to see if a line from a to b is affected by any ECM field (including Angel) of the enemy of ae |
public int readTag() throws IOException {
if (isAtEnd()) {
lastTag=0;
return 0;
}
lastTag=readRawVarint32();
if (lastTag == 0) {
throw InvalidProtocolBufferNanoException.invalidTag();
}
return lastTag;
}
| Attempt to read a field tag, returning zero if we have reached EOF. Protocol message parsers use this to read tags, since a protocol message may legally end wherever a tag occurs, and zero is not a valid tag number. |
public static void intBenchmarkPrimitive(int runs,int rows,int columns,boolean print){
throw new InternalError();
}
| Runs a bench on matrices holding int elements. |
@Override public void updateNCharacterStream(int columnIndex,Reader x) throws SQLException {
updateNCharacterStream(columnIndex,x,-1);
}
| Updates a column in the current or insert row. |
public String[] keyArray(){
return keyArray(null);
}
| Return a copy of the internal keys array. This array can be modified. |
private static boolean looksLikeMethodDecl(IDocument document,int position,String partitioning){
position=eatIdentToLeft(document,position,partitioning);
if (position < 1) return false;
position=eatBrackets(document,position - 1,partitioning);
if (position < 1) return false;
position=eatIdentToLeft(document,position - 1,partitioning);
return position != -1;
}
| Checks whether the content of <code>document</code> at <code>position</code> looks like a method declaration header (i.e. only the return type and method name). <code>position</code> must be just left of the opening parenthesis of the parameter list. |
public boolean hasExpiration(ByteArrayWrapper key){
return this.expirationsMap.containsKey(key);
}
| Check method if key has expiration |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.