code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public void validate() throws Exception {
if (crawlStorageFolder == null) {
throw new Exception("Crawl storage folder is not set in the CrawlConfig.");
}
if (politenessDelay < 0) {
throw new Exception("Invalid value for politeness delay: " + politenessDelay);
}
if (maxDepthOfCrawling < -1) {
throw new Exception("Maximum crawl depth should be either a positive number or -1 for unlimited depth.");
}
if (maxDepthOfCrawling > Short.MAX_VALUE) {
throw new Exception("Maximum value for crawl depth is " + Short.MAX_VALUE);
}
}
| Validates the configs specified by this instance. |
public Object[] parse(String source,ParsePosition pos){
if (source == null) {
Object[] empty={};
return empty;
}
int maximumArgumentNumber=-1;
for (int i=0; i <= maxOffset; i++) {
if (argumentNumbers[i] > maximumArgumentNumber) {
maximumArgumentNumber=argumentNumbers[i];
}
}
Object[] resultArray=new Object[maximumArgumentNumber + 1];
int patternOffset=0;
int sourceOffset=pos.index;
ParsePosition tempStatus=new ParsePosition(0);
for (int i=0; i <= maxOffset; ++i) {
int len=offsets[i] - patternOffset;
if (len == 0 || pattern.regionMatches(patternOffset,source,sourceOffset,len)) {
sourceOffset+=len;
patternOffset+=len;
}
else {
pos.errorIndex=sourceOffset;
return null;
}
if (formats[i] == null) {
int tempLength=(i != maxOffset) ? offsets[i + 1] : pattern.length();
int next;
if (patternOffset >= tempLength) {
next=source.length();
}
else {
next=source.indexOf(pattern.substring(patternOffset,tempLength),sourceOffset);
}
if (next < 0) {
pos.errorIndex=sourceOffset;
return null;
}
else {
String strValue=source.substring(sourceOffset,next);
if (!strValue.equals("{" + argumentNumbers[i] + "}")) resultArray[argumentNumbers[i]]=source.substring(sourceOffset,next);
sourceOffset=next;
}
}
else {
tempStatus.index=sourceOffset;
resultArray[argumentNumbers[i]]=formats[i].parseObject(source,tempStatus);
if (tempStatus.index == sourceOffset) {
pos.errorIndex=sourceOffset;
return null;
}
sourceOffset=tempStatus.index;
}
}
int len=pattern.length() - patternOffset;
if (len == 0 || pattern.regionMatches(patternOffset,source,sourceOffset,len)) {
pos.index=sourceOffset + len;
}
else {
pos.errorIndex=sourceOffset;
return null;
}
return resultArray;
}
| Parses the string. <p>Caveats: The parse may fail in a number of circumstances. For example: <ul> <li>If one of the arguments does not occur in the pattern. <li>If the format of an argument loses information, such as with a choice format where a large number formats to "many". <li>Does not yet handle recursion (where the substituted strings contain {n} references.) <li>Will not always find a match (or the correct match) if some part of the parse is ambiguous. For example, if the pattern "{1},{2}" is used with the string arguments {"a,b", "c"}, it will format as "a,b,c". When the result is parsed, it will return {"a", "b,c"}. <li>If a single argument is parsed more than once in the string, then the later parse wins. </ul> When the parse fails, use ParsePosition.getErrorIndex() to find out where in the string the parsing failed. The returned error index is the starting offset of the sub-patterns that the string is comparing with. For example, if the parsing string "AAA {0} BBB" is comparing against the pattern "AAD {0} BBB", the error index is 0. When an error occurs, the call to this method will return null. If the source is null, return an empty array. |
@Override public RegularTimePeriod next(){
Minute result;
if (this.minute != LAST_MINUTE_IN_HOUR) {
result=new Minute(this.minute + 1,getHour());
}
else {
Hour nextHour=(Hour)getHour().next();
if (nextHour != null) {
result=new Minute(FIRST_MINUTE_IN_HOUR,nextHour);
}
else {
result=null;
}
}
return result;
}
| Returns the minute following this one. |
public void selectDistributionSetValue(){
selectedDefaultDisSetType=(Long)combobox.getValue();
if (!selectedDefaultDisSetType.equals(currentDefaultDisSetType)) {
changeIcon.setVisible(true);
notifyConfigurationChanged();
}
else {
changeIcon.setVisible(false);
}
}
| Method that is called when combobox event is performed. |
public IntroFragmentModel compile(){
return new IntroFragmentModel(introFragment == null ? new SimpleIntroFragment() : introFragment,title,description,image,backgroundColor,imageElevation,titleTextColor,descriptionTextColor);
}
| Compile to intro fragment model. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-02-25 10:38:02.458 -0500",hash_original_method="B0CD1CF37C47B6EE8CA9750CE89F4BC8",hash_generated_method="3F9500F6CC498B34F0757D541AC9F0D3") @DSVerified @DSSpec(DSCat.IO) @DSSink({DSSinkKind.NETWORK}) public int soml(String reversePath) throws IOException {
return sendCommand(SMTPCommand.SOML,reversePath);
}
| A convenience method to send the SMTP SOML command to the server, receive the reply, and return the reply code. <p> |
private int checkInterruptWhileWaiting(Node node){
return Thread.interrupted() ? (transferAfterCancelledWait(node) ? THROW_IE : REINTERRUPT) : 0;
}
| Checks for interrupt, returning THROW_IE if interrupted before signalled, REINTERRUPT if after signalled, or 0 if not interrupted. |
public void actionPerformed(ActionEvent ae){
long nowTime=System.currentTimeMillis();
long elapsedTime=nowTime - prevTime;
long totalTime=nowTime - startTime;
System.out.println("Elapsed time = " + elapsedTime);
if (totalTime > DURATION) {
timer.stop();
}
prevTime=nowTime;
try {
if (firstTime) {
Thread.sleep(INITIAL_PROCESSING_TIME);
firstTime=false;
}
else {
Thread.sleep(PROCESSING_TIME);
}
}
catch ( Exception e) {
}
}
| This method will be called during every tick of the Timers. We insert an artificial delay each time, to simulate some processing. The first time through, this delay is greater than the delay between timing events, so that we can see how this hiccup is handled by fixed-rate and fixed-delay timers. |
public void addTree(TreeRTG tree,boolean allowed){
if (allowed) {
this.rtgTrees.add(tree);
}
}
| Adds a tree to the list of RTG trees associated with this collection. The 'allowed' parameter allows us to pass biome config booleans dynamically when configuring the trees in the collection. |
public static Set<Feature> conjoin(Set<Feature> feats1,Set<Feature> feats2){
if (feats1.size() == 0 || feats2.size() == 0) return new LinkedHashSet<>();
Set<Feature> features=new LinkedHashSet<>(feats1.size() * feats2.size());
for ( Feature a : feats1) {
for ( Feature b : feats2) {
if (a == b) features.add(a);
else features.add(a.conjoinWith(b));
}
}
return features;
}
| Conjoins two feature sets. This produces a cross product of features. That is, every feature from the first parameter is conjoined with every feature of the second one. If either of the input sets are empty, this function returns the empty set. |
public static void write(File file,CharSequence data,Charset encoding) throws IOException {
write(file,data,encoding,false);
}
| Writes a CharSequence to a file creating the file if it does not exist. |
public static ScriptEngine createEngine(){
ScriptEngine engine=manager.getEngineByName("nashorn");
if (engine == null) {
engine=manager.getEngineByName("rhino");
}
return engine;
}
| Create a new ScriptEngine. This allows for modules to move away from the Bindings set by Toast and create their own Scripting environment if they wish to. This allows for enhanced control over the JavaScript used in their code. |
public static void dropTable(SQLiteDatabase db,boolean ifExists){
String sql="DROP TABLE " + (ifExists ? "IF EXISTS " : "") + "'GroupImage'";
db.execSQL(sql);
}
| Drops the underlying database table. |
public static void main(String[] args){
String alg="SHA";
boolean file=false;
if (args.length == 0 || args.length > 4) {
printUsage();
return;
}
for (int i=0; i < args.length; i++) {
String currArg=args[i].toLowerCase(Locale.US);
if (currArg.equals("-help") || currArg.equals("-usage")) {
printUsage();
return;
}
if (currArg.equals("-alg")) {
alg=args[i + 1];
}
if (currArg.equals("-file")) {
file=true;
}
}
if (file) {
digestFile(args[args.length - 1],alg);
}
else {
try {
String hash=digestString(args[args.length - 1],alg);
System.out.println("Hash is: " + hash);
}
catch ( NoSuchAlgorithmException nsae) {
System.out.println("No such algorithm available");
}
}
}
| Command line interface. Use -help for arguments. |
public static Range shift(Range base,double delta){
return shift(base,delta,false);
}
| Shifts the range by the specified amount. |
private static ApiUsage of(List<IN4JSProject> projects,Map<IN4JSProject,IN4JSProject> concreteApiImplProjectMapping,ApiImplMapping apiImplMapping,boolean implementationIdRequired){
return new ApiUsage(null,projects,concreteApiImplProjectMapping,apiImplMapping,Collections.emptyList(),implementationIdRequired);
}
| Create result for cases where no no implemenationId could be determined. |
@Override public int describeContents(){
return 0;
}
| Implement the Parcelable interface |
public void println(String[] values) throws IOException {
for (int i=0; i < values.length; i++) {
print(values[i]);
}
println();
}
| Print a single line of comma separated values. The values will be quoted if needed. Quotes and newLine characters will be escaped. |
private void recomputeFocus(MotionEvent event){
for (int i=0; i < mHighlightViews.size(); i++) {
HighlightView hv=mHighlightViews.get(i);
hv.setFocus(false);
hv.invalidate();
}
for (int i=0; i < mHighlightViews.size(); i++) {
HighlightView hv=mHighlightViews.get(i);
int edge=hv.getHit(event.getX(),event.getY());
if (edge != HighlightView.GROW_NONE) {
if (!hv.hasFocus()) {
hv.setFocus(true);
hv.invalidate();
}
break;
}
}
invalidate();
}
| Recompute focus. |
@Deprecated public AltFormat(String name,WireFormat wireFormat,ContentType contentType,List<ContentType> acceptList,boolean isSelectableByType){
this(builder().setName(name).setWireFormat(wireFormat).setContentType(contentType).setAcceptableTypes(acceptList).setSelectableByType(isSelectableByType).check());
}
| Constructs a new alternate representation format with the provided attributes. |
protected void reportMetricsIfNeeded(){
if (getGatherPerformanceMetrics()) {
if ((System.currentTimeMillis() - this.metricsLastReportedMs) > getReportMetricsIntervalMillis()) {
reportMetrics();
}
}
}
| Reports currently collected metrics if this feature is enabled and the timeout has passed. |
@Override public Set<byte[]> keySet(){
final TreeSet<byte[]> set=new TreeSet<byte[]>(this.table.ordering);
try {
final Iterator<byte[]> i=this.table.keys(true,false);
while (i.hasNext()) {
set.add(i.next());
}
}
catch ( final IOException e) {
}
return set;
}
| Return a Set of the keys contained in this map. This may not be a useful method, if possible use the keys() method instead to iterate all keys from the backend-file |
protected void computeAverageChainingDistances(KNNQuery<O> knnq,DistanceQuery<O> dq,DBIDs ids,WritableDoubleDataStore acds){
FiniteProgress lrdsProgress=LOG.isVerbose() ? new FiniteProgress("Computing average chaining distances",ids.size(),LOG) : null;
for (DBIDIter iter=ids.iter(); iter.valid(); iter.advance()) {
final KNNList neighbors=knnq.getKNNForDBID(iter,k);
final int r=neighbors.size();
DoubleDBIDListIter it1=neighbors.iter(), it2=neighbors.iter();
final double[] mindists=new double[r];
for (int i=0; it1.valid(); it1.advance(), ++i) {
mindists[i]=DBIDUtil.equal(it1,iter) ? Double.NaN : it1.doubleValue();
}
double acsum=0.;
for (int j=((r < k) ? r : k) - 1; j > 0; --j) {
int minpos=-1;
double mindist=Double.NaN;
for (int i=0; i < mindists.length; ++i) {
double curdist=mindists[i];
if (curdist == curdist && !(curdist > mindist)) {
minpos=i;
mindist=curdist;
}
}
acsum+=mindist * j;
mindists[minpos]=Double.NaN;
it1.seek(minpos);
it2.seek(0);
for (int i=0; it2.valid(); it2.advance(), ++i) {
final double curdist=mindists[i];
if (curdist != curdist) {
continue;
}
double newdist=dq.distance(it1,it2);
if (newdist < curdist) {
mindists[i]=newdist;
}
}
}
acds.putDouble(iter,acsum / (r * 0.5 * (r - 1.)));
LOG.incrementProcessed(lrdsProgress);
}
LOG.ensureCompleted(lrdsProgress);
}
| Computes the average chaining distance, the average length of a path through the given set of points to each target. The authors of COF decided to approximate this value using a weighted mean that assumes every object is reached from the previous point (but actually every point could be best reachable from the first, in which case this does not make much sense.) TODO: can we accelerate this by using the kNN of the neighbors? |
public boolean isEmtpy(){
return depth() == 0;
}
| Returns true if the queue is empty, otherwise false |
@Override protected void onPrivateMessage(String sender,String login,String hostname,String target,String text){
Message message=new Message(" " + sender + " - "+ text);
String queryNick=sender;
if (queryNick.equals(this.getNick())) {
queryNick=target;
}
Conversation conversation=server.getConversation(queryNick);
if (conversation == null) {
conversation=new Query(queryNick);
conversation.setHistorySize(service.getSettings().getHistorySize());
conversation.addMessage(message);
server.addConversation(conversation);
Intent intent=Broadcast.createConversationIntent(Broadcast.CONVERSATION_NEW,server.getId(),queryNick);
service.sendBroadcast(intent);
}
else {
conversation.addMessage(message);
Intent intent=Broadcast.createConversationIntent(Broadcast.CONVERSATION_MESSAGE,server.getId(),queryNick);
service.sendBroadcast(intent);
}
if (sender.equals(this.getNick())) {
return;
}
if (conversation.getStatus() != Conversation.STATUS_SELECTED || !server.getIsForeground()) {
service.addNewMention(server.getId(),conversation," " + sender + " - "+ text,service.getSettings().isVibrateHighlightEnabled(),service.getSettings().isSoundHighlightEnabled(),service.getSettings().isLedHighlightEnabled());
}
if (isMentioned(text)) {
message.setColor(Message.COLOR_RED);
conversation.setStatus(Conversation.STATUS_HIGHLIGHT);
}
}
| On Private Message |
private static String formatSampleRate(int rate){
return MHZ_FORMATTER.format((double)rate / 1E6d);
}
| Formats the rate in hertz for display as megahertz |
public boolean isSet(final String flag){
final Flag aFlag=getFlag(flag);
return (aFlag != null) && aFlag.isSet();
}
| Returns true if a particular flag was provided in the arguments. |
private void transferPlaylistToModels(PlaylistV2 playlist){
if (playlist != null) {
mPlaylistLoading=true;
mAliasModel.addAliases(playlist.getAliases());
mChannelModel.addChannels(playlist.getChannels());
mChannelMapModel.addChannelMaps(playlist.getChannelMaps());
mPlaylistLoading=false;
}
}
| Transfers data from persisted playlist into system models |
public void write(char c) throws IOException {
if (_outputStream == null) throw new IOException("Writer closed");
if ((c < 0xd800) || (c > 0xdfff)) {
write((int)c);
}
else if (c < 0xdc00) {
_highSurrogate=c;
}
else {
int code=((_highSurrogate - 0xd800) << 10) + (c - 0xdc00) + 0x10000;
write(code);
}
}
| Writes a single character. This method supports 16-bits character surrogates. |
public boolean contains(Point2D p){
return path.contains(p);
}
| Delegates to the enclosed <code>GeneralPath</code>. |
protected void closeDown(){
try {
if (!region.isDestroyed()) {
region.destroyRegion();
}
}
catch ( Exception e) {
this.logWriter.error("DiskRegionTestingBase::closeDown:Exception in destroyiong the region",e);
}
}
| clears and closes the region |
public CreatePacFileDialog(Shell parent){
super(parent,SWT.CLOSE | SWT.TITLE | SWT.MIN| SWT.RESIZE);
}
| Create the dialog. |
public Object invoke(Object proxy,Method method,Object[] args) throws Throwable {
String name=method.getName();
if (Object.class == method.getDeclaringClass()) {
if ("equals".equals(name)) {
Object obj=args[0];
return new Boolean(checkEquals(obj));
}
else if ("toString".equals(name)) return annotation.toString();
else if ("hashCode".equals(name)) return new Integer(hashCode());
}
else if ("annotationType".equals(name) && method.getParameterTypes().length == 0) return getAnnotationType();
MemberValue mv=annotation.getMemberValue(name);
if (mv == null) return getDefault(name,method);
else return mv.getValue(classLoader,pool,method);
}
| Executes a method invocation on a proxy instance. The implementations of <code>toString()</code>, <code>equals()</code>, and <code>hashCode()</code> are directly supplied by the <code>AnnotationImpl</code>. The <code>annotationType()</code> method is also available on the proxy instance. |
public boolean dumpNamespace(String namespace){
synchronized (this) {
if (usingNamespaces(namespace)) {
Hashtable h=(Hashtable)namespaceHash.remove(namespace);
if (h == null) return false;
h.clear();
return true;
}
return false;
}
}
| Removes the VMs and the namespace from the manager. Used when a template is reloaded to avoid accumulating drek |
public void filter(Geometry geom){
if (geom instanceof LineString) {
LineString line=(LineString)geom;
if (line.isEmpty()) return;
int minSize=((LineString)line).isClosed() ? 4 : 2;
TaggedLineString taggedLine=new TaggedLineString((LineString)line,minSize);
linestringMap.put(line,taggedLine);
}
}
| Filters linear geometries. geom a geometry of any type |
public void shutdown(){
if (timerTask != null) {
timerTask.cancel();
timerTask=null;
}
if (timer != null) {
timer.cancel();
timer.purge();
timer=null;
}
periodicTask.shutdown();
}
| Shuts down. |
public static void checkSlashes(int depth,boolean create,String ans,String ask) throws Exception {
check(ans,ask);
if (depth == 0) return;
checkSlash(depth,create,ans,ask,"/");
checkSlash(depth,create,ans,ask,"//");
checkSlash(depth,create,ans,ask,"///");
if (win32) {
checkSlash(depth,create,ans,ask,"\\");
checkSlash(depth,create,ans,ask,"\\\\");
checkSlash(depth,create,ans,ask,"\\/");
checkSlash(depth,create,ans,ask,"/\\");
checkSlash(depth,create,ans,ask,"\\\\\\");
}
}
| Check slash cases for the given ask string |
public RouteTest(String name){
super(name);
}
| Constructs a new Route test case with the given name. <!-- begin-user-doc --> <!-- end-user-doc --> |
private int calculateTotalKey(@NonNull String text){
String[] lines=text.split("\n");
int number=0;
for (int i=0; i < lines.length; i++) {
number+=KEY_CODE.equals(lines[i]) ? 1 : 0;
}
return number;
}
| calculate the content has how many "```" |
public void appendToDDLWriter(String stringToWrite){
appendToDDLWriter(createSchemaWriter,stringToWrite);
}
| PUBLIC: If the schema manager is writing to a writer, append this string to that writer. |
public void testInputResources() throws Exception {
File f=this.initFile("testInputResources");
writeAscendingIntFile(f,100);
for (int fcnt=0; fcnt < 25000; fcnt++) {
BufferedFileDataInput bfdi=new BufferedFileDataInput(f);
long offset=bfdi.getOffset();
for (int i=0; i < 100; i++) {
String position="fcnt: " + fcnt + " i: "+ i;
assertEquals(position,i,bfdi.readInt());
offset+=4;
assertEquals(position,offset,bfdi.getOffset());
}
bfdi.close();
}
}
| Confirm that we can re-read the same file thousands of times without triggering a resource leak, e.g., of file descriptors. |
@Override public void close(){
if (begun) throw new IllegalStateException(getClass().getSimpleName() + " close() without end()");
}
| Releases any GPU resources retained by this batch. This should be called when the batch will never again be used. |
public static void downto(Date self,Date to,Closure closure){
if (self.compareTo(to) >= 0) {
for (Date i=(Date)self.clone(); i.compareTo(to) >= 0; i=previous(i)) {
closure.call(i);
}
}
else throw new GroovyRuntimeException("The argument (" + to + ") to downto() cannot be later than the value ("+ self+ ") it's called on.");
}
| Iterates from this date down to the given date, inclusive, decrementing by one day each time. |
public void addHeaderLine(String line){
mLines.add(line);
}
| Add a BED header line. |
static <T extends Entity>Optional<T> lookup(Repository repository,Class<T> klass,EntityIndex<T,UUID> keyAttribute,UUID id){
try (ResultSet<EntityHandle<T>> resultSet=repository.query(klass,equal(keyAttribute,id))){
if (resultSet.isEmpty()) {
return Optional.empty();
}
else {
return Optional.of(resultSet.uniqueResult().get());
}
}
}
| Lookup an entity by a unique ID. |
protected void writeXml(MListTable<?> table,OutputStream outputStream) throws IOException {
final List<?> list=table.getList();
TransportFormatAdapter.writeXml((Serializable)list,outputStream);
}
| Exporte une MListTable dans un fichier au format xml. |
public void removeAll(){
checkWidget();
text.setText("");
table.removeAll();
}
| Removes all of the items from the receiver's list and clear the contents of receiver's text field. <p> |
@Override public boolean equals(Object obj){
if (!(obj instanceof GenericEntity)) return false;
try {
return this.compareTo((GenericEntity)obj) == 0;
}
catch ( ClassCastException e) {
return false;
}
}
| Determines the equality of two GenericEntity objects, overrides the default equals |
public ParetoDominanceComparator(){
super(new AggregateConstraintComparator(),new ParetoObjectiveComparator());
}
| Constructs a Pareto dominance comparator. |
public static void addSentencePreviousMeta(Vertex question,Vertex answer,Vertex previous,boolean require,Network network){
Relationship relationship=question.getRelationship(Primitive.RESPONSE,answer);
if (relationship != null) {
Vertex meta=relationship.getMeta();
if (previous != null) {
meta=network.createMeta(relationship);
meta.addRelationship(Primitive.PREVIOUS,previous);
}
if (meta != null) {
if (require) {
meta.addRelationship(Primitive.REQUIRE,Primitive.PREVIOUS);
}
else {
Relationship required=meta.getRelationship(Primitive.REQUIRE,Primitive.PREVIOUS);
if (required != null) {
relationship.getMeta().internalRemoveRelationship(required);
}
}
}
}
network.checkReduction(question);
Collection<Relationship> synonyms=question.getRelationships(Primitive.SYNONYM);
if (synonyms != null) {
for ( Relationship synonym : synonyms) {
relationship=synonym.getTarget().getRelationship(Primitive.RESPONSE,answer);
if (relationship != null) {
Vertex meta=relationship.getMeta();
if (previous != null) {
meta=network.createMeta(relationship);
meta.addRelationship(Primitive.PREVIOUS,previous);
}
if (meta != null) {
if (require) {
meta.addRelationship(Primitive.REQUIRE,Primitive.PREVIOUS);
}
else {
Relationship required=meta.getRelationship(Primitive.REQUIRE,Primitive.PREVIOUS);
if (required != null) {
relationship.getMeta().internalRemoveRelationship(required);
}
}
}
}
}
}
}
| Add the previous for a response match to the question meta. |
protected MarkerImpl(){
super();
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public void removeObsoletePreviews(ArrayList<Object> list){
Utilities.assertWorkerThread();
LongSparseArray<HashSet<String>> validPackages=new LongSparseArray<>();
for ( Object obj : list) {
final UserHandleCompat user;
final String pkg;
if (obj instanceof ResolveInfo) {
user=UserHandleCompat.myUserHandle();
pkg=((ResolveInfo)obj).activityInfo.packageName;
}
else {
LauncherAppWidgetProviderInfo info=(LauncherAppWidgetProviderInfo)obj;
user=mWidgetManager.getUser(info);
pkg=info.provider.getPackageName();
}
final long userId=mUserManager.getSerialNumberForUser(user);
HashSet<String> packages=validPackages.get(userId);
if (packages == null) {
packages=new HashSet<>();
validPackages.put(userId,packages);
}
packages.add(pkg);
}
LongSparseArray<HashSet<String>> packagesToDelete=new LongSparseArray<>();
Cursor c=null;
try {
c=mDb.query(new String[]{CacheDb.COLUMN_USER,CacheDb.COLUMN_PACKAGE,CacheDb.COLUMN_LAST_UPDATED,CacheDb.COLUMN_VERSION},null,null);
while (c.moveToNext()) {
long userId=c.getLong(0);
String pkg=c.getString(1);
long lastUpdated=c.getLong(2);
long version=c.getLong(3);
HashSet<String> packages=validPackages.get(userId);
if (packages != null && packages.contains(pkg)) {
long[] versions=getPackageVersion(pkg);
if (versions[0] == version && versions[1] == lastUpdated) {
continue;
}
}
packages=packagesToDelete.get(userId);
if (packages == null) {
packages=new HashSet<>();
packagesToDelete.put(userId,packages);
}
packages.add(pkg);
}
for (int i=0; i < packagesToDelete.size(); i++) {
long userId=packagesToDelete.keyAt(i);
UserHandleCompat user=mUserManager.getUserForSerialNumber(userId);
for ( String pkg : packagesToDelete.valueAt(i)) {
removePackage(pkg,user,userId);
}
}
}
catch ( SQLException e) {
Log.e(TAG,"Error updating widget previews",e);
}
finally {
if (c != null) {
c.close();
}
}
}
| Updates the persistent DB: 1. Any preview generated for an old package version is removed 2. Any preview for an absent package is removed This ensures that we remove entries for packages which changed while the launcher was dead. |
public EchoBreakpointHitParser(final ClientReader clientReader){
super(clientReader,DebugCommandType.RESP_BPE_HIT);
}
| Creates a new Echo Breakpoint hit reply parser. |
protected ObjectLiteralImpl(){
super();
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public static void checkGlError(String op){
int error=GLES20.glGetError();
if (error != GLES20.GL_NO_ERROR) {
String msg=op + ": glError 0x" + Integer.toHexString(error);
Log.e(TAG,msg);
throw new RuntimeException(msg);
}
}
| Checks to see if a GLES error has been raised. |
public UniformDiscrete(int min,int max){
setMinMax(min,max);
}
| Creates a new discrete uniform distribution |
@SuppressWarnings("UnusedDeclaration") @Beta(Beta.Feature.Sandbox) public static void enableSandbox(){
Fabric.getLogger().i(Digits.TAG,"Sandbox is enabled");
getInstance().getSandboxConfig().enable();
getInstance().getApiClientManager().createNewClient();
}
| Enable sandbox mode |
public void generateServicesMap(){
try {
File metaInfFile=getMetaInfFile();
File serviceMapFile=new File(metaInfFile,"crux-remote");
if (serviceMapFile.exists() && !isOverride()) {
logger.info("Service map already exists. Skipping generation...");
return;
}
initializeScannerURLs();
Set<String> searchClassesByInterface=ClassScanner.searchClassesByInterface(RemoteService.class);
Properties cruxRemote=new Properties();
for ( String serviceClass : searchClassesByInterface) {
Class<?> clazz=Class.forName(serviceClass);
if (clazz.isInterface()) {
Class<?> service=Services.getService(serviceClass);
if (service != null) {
cruxRemote.put(serviceClass,service.getCanonicalName());
}
}
}
if (metaInfFile.exists()) {
if (!metaInfFile.isDirectory()) {
throw new ServiceMapperException("Can not create a META-INF directory on " + getProjectDir().getCanonicalPath());
}
}
else {
metaInfFile.mkdirs();
}
cruxRemote.store(new FileOutputStream(serviceMapFile),"Crux RemoteServices implementations");
}
catch ( IOException e) {
throw new ServiceMapperException("Error creating remote service map",e);
}
catch ( ClassNotFoundException e) {
throw new ServiceMapperException("Error creating remote service map",e);
}
}
| Generates Remote Service map |
public static boolean isConvolveOpValid(ConvolveOp cop){
Kernel kernel=cop.getKernel();
int kw=kernel.getWidth();
int kh=kernel.getHeight();
if (!(kw == 3 && kh == 3) && !(kw == 5 && kh == 5)) {
return false;
}
return true;
}
| ConvolveOp support |
public static Map<String,Object> returnMessage(String code,String message){
Map<String,Object> result=new HashMap<String,Object>();
if (code != null) result.put(ModelService.RESPONSE_MESSAGE,code);
if (message != null) result.put(ModelService.SUCCESS_MESSAGE,message);
return result;
}
| A small routine to make a result map with the message and the response code NOTE: This brings out some bad points to our message convention: we should be using a single message or message list and what type of message that is should be determined by the RESPONSE_MESSAGE (and there's another annoyance, it should be RESPONSE_CODE) |
public static List<String> tokenize(String arguments){
return tokenize(arguments,false);
}
| Tokenizes the given String into String tokens |
public IndexingStats stats(String... types){
IndexingStats.Stats total=totalStats.stats();
Map<String,IndexingStats.Stats> typesSt=null;
if (types != null && types.length > 0) {
typesSt=new HashMap<>(typesStats.size());
if (types.length == 1 && types[0].equals("_all")) {
for ( Map.Entry<String,StatsHolder> entry : typesStats.entrySet()) {
typesSt.put(entry.getKey(),entry.getValue().stats());
}
}
else {
for ( Map.Entry<String,StatsHolder> entry : typesStats.entrySet()) {
if (Regex.simpleMatch(types,entry.getKey())) {
typesSt.put(entry.getKey(),entry.getValue().stats());
}
}
}
}
return new IndexingStats(total,typesSt);
}
| Returns the stats, including type specific stats. If the types are null/0 length, then nothing is returned for them. If they are set, then only types provided will be returned, or <tt>_all</tt> for all types. |
public static CertPath buildPath(String[] fileNames) throws Exception {
return buildPath("",fileNames);
}
| Read a bunch of certs from files and create a CertPath from them. |
public void forceRemoveCompletion(){
if (!replicatingNodes.isEmpty() || !tokenMetadata.getLeavingEndpoints().isEmpty()) {
logger.warn("Removal not confirmed for for {}",StringUtils.join(this.replicatingNodes,","));
for ( InetAddress endpoint : tokenMetadata.getLeavingEndpoints()) {
UUID hostId=tokenMetadata.getHostId(endpoint);
Gossiper.instance.advertiseTokenRemoved(endpoint,hostId);
excise(tokenMetadata.getTokens(endpoint),endpoint);
}
replicatingNodes.clear();
removingNode=null;
}
else {
logger.warn("No tokens to force removal on, call 'removenode' first");
}
}
| Force a remove operation to complete. This may be necessary if a remove operation blocks forever due to node/stream failure. removeToken() must be called first, this is a last resort measure. No further attempt will be made to restore replicas. |
public void fillFromToWith(int from,int to,Object val){
checkRangeFromTo(from,to,this.size);
for (int i=from; i <= to; ) setQuick(i++,val);
}
| Sets the specified range of elements in the specified array to the specified value. |
@DSComment("Package priviledge") @DSBan(DSCat.DEFAULT_MODIFIER) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:58:26.340 -0500",hash_original_method="AC949E64AEE76B7FF936E7A1B08DF381",hash_generated_method="07410662D5F8988EAC507F19EF8D94E0") void onMMIDone(GsmMmiCode mmi){
if (mPendingMMIs.remove(mmi) || mmi.isUssdRequest()) {
mMmiCompleteRegistrants.notifyRegistrants(new AsyncResult(null,mmi,null));
}
}
| Removes the given MMI from the pending list and notifies registrants that it is complete. |
public JSONArray put(Collection<?> value){
this.put(new JSONArray(value));
return this;
}
| Put a value in the JSONArray, where the value will be a JSONArray which is produced from a Collection. |
@Override public boolean isActive(){
return amIActive;
}
| Used by the Whitebox GUI to tell if this plugin is still running. |
public synchronized void needHeartBeat(){
threadsNeedingHeartBeat++;
progress.progress();
if (threadsNeedingHeartBeat == 1) {
}
}
| inform the background thread that heartbeats are to be issued. Issue a heart beat also |
public WrappedRuntimeException(Exception e){
super(e.getMessage());
m_exception=e;
}
| Construct a WrappedRuntimeException from a checked exception. |
public void unread(char ch) throws IOException {
this.currentReader.pbReader.unread(ch);
}
| Pushes the last character read back to the stream. |
public void removeFromLists(int key){
this.subjectArea.remove(key);
this.courseNbr.remove(key);
this.itype.remove(key);
this.classNumber.remove(key);
}
| Remove object specified by the index from the lists |
@Override public String toString(){
return "m = " + m + ", t = "+ t+ " k_0 "+ k_0;
}
| Returns a string representation of the object. |
public ScannerToken<? extends Object> readNextTerminal() throws IOException {
if (0 == fNumberOfBufferedTokens) return fScanner.readNextTerminal();
else {
fNumberOfBufferedTokens--;
ScannerToken<? extends Object> t=fTokenQueue.remove(0);
return t;
}
}
| Reads the next terminal from the input, unless there are buffered tokens. Maintains counter fNumberOfBufferedTokens. |
void compWriteObjectNotify(){
byte count=JComponent.getWriteObjCounter(this);
JComponent.setWriteObjCounter(this,(byte)(count + 1));
if (count != 0) {
return;
}
uninstallUIAndProperties();
if (getToolTipText() != null || this instanceof javax.swing.table.JTableHeader) {
ToolTipManager.sharedInstance().unregisterComponent(JComponent.this);
}
}
| This is called from Component by way of reflection. Do NOT change the name unless you change the code in Component as well. |
private void reset(String TableName){
String sql="UPDATE " + TableName + " SET Processing='N' WHERE AD_Client_ID="+ p_AD_Client_ID+ " AND (Processing<>'N' OR Processing IS NULL)";
int unlocked=DB.executeUpdate(sql,get_TrxName());
sql="UPDATE " + TableName + " SET Posted='N' WHERE AD_Client_ID="+ p_AD_Client_ID+ " AND (Posted NOT IN ('Y','N') OR Posted IS NULL) AND Processed='Y'";
int invalid=DB.executeUpdate(sql,get_TrxName());
if (unlocked + invalid != 0) log.fine(TableName + " - Unlocked=" + unlocked+ " - Invalid="+ invalid);
m_countReset+=unlocked + invalid;
}
| Reset Accounting Table and update count |
public Object jjtAccept(SyntaxTreeBuilderVisitor visitor,Object data) throws VisitorException {
return visitor.visit(this,data);
}
| Accept the visitor. |
public FastCharArrayReader(char buf[]){
this.buf=buf;
this.pos=0;
this.count=buf.length;
}
| Creates a CharArrayReader from the specified array of chars. |
public static synchronized void initialize(){
if (agent != null) {
return;
}
Config config=ConfigFactory.load();
boolean useBaggage=config.getBoolean("pivot-tracing.agent.use_baggage");
boolean useDynamic=config.getBoolean("pivot-tracing.agent.use_dynamic");
boolean emitIfNoResults=config.getBoolean("pivot-tracing.agent.emit_if_no_results");
String resultsTopic=config.getString("pivot-tracing.pubsub.results_topic");
int reportInterval=config.getInt("pivot-tracing.agent.report_interval_ms");
BaggageAPI baggageApi=useBaggage ? new BaggageAPIImpl() : new BaggageAPIDisabled();
EmitAPI emitApi=new EmitAPIImpl(reportInterval,resultsTopic,emitIfNoResults);
DynamicManager dynamic=useDynamic ? DynamicInstrumentation.get() : null;
agent=new PTAgent(baggageApi,emitApi,dynamic);
PrivilegedProxy.Register(agent);
System.out.println("Pivot Tracing initialized");
}
| Initialize the PivotTracing agent. This call will subscribe to pubsub in order to receive weave commands, and attempt to connect to the process's debug port |
public boolean meets(PressurizedInput input){
if (input == null || !input.isValid()) {
return false;
}
if (!(StackUtils.equalsWildcard(input.theSolid,theSolid) && input.theFluid.isFluidEqual(theFluid) && input.theGas.isGasEqual(theGas))) {
return false;
}
return input.theSolid.stackSize >= theSolid.stackSize && input.theFluid.amount >= theFluid.amount && input.theGas.amount >= theGas.amount;
}
| Actual implementation of meetsInput(), performs the checks. |
private int moveGap(int offset,int remove,int oldGapSize,int newGapSize,int newGapStart){
final int newGapEnd=newGapStart + newGapSize;
if (offset < fGapStart) {
int afterRemove=offset + remove;
if (afterRemove < fGapStart) {
final int betweenSize=fGapStart - afterRemove;
arrayCopy(afterRemove,fContent,newGapEnd,betweenSize);
}
}
else {
final int offsetShifted=offset + oldGapSize;
final int betweenSize=offsetShifted - fGapEnd;
arrayCopy(fGapEnd,fContent,fGapStart,betweenSize);
}
return newGapEnd;
}
| Moves the gap to <code>newGapStart</code>. |
private void drawHexView(final Graphics g){
final int standardSize=2 * getCharacterWidth(g);
final int firstX=(-m_firstColumn * m_charWidth) + m_paddingHexLeft + m_offsetViewWidth;
int x=firstX;
int y=m_paddingTop;
boolean evenColumn=true;
byte[] data=null;
int bytesToDraw;
if (m_status == DefinitionStatus.DEFINED) {
bytesToDraw=getBytesToDraw();
data=m_dataProvider.getData(getFirstVisibleOffset(),bytesToDraw);
}
else {
bytesToDraw=getMaximumVisibleBytes();
}
long currentOffset=getFirstVisibleOffset();
for (int i=0; i < bytesToDraw; i++, currentOffset++) {
final ColoredRange range=findColoredRange(currentOffset);
if (i != 0) {
if ((i % m_bytesPerRow) == 0) {
x=firstX;
y+=m_rowHeight;
evenColumn=true;
}
else if ((i % m_bytesPerColumn) == 0) {
x+=m_columnSpacing;
evenColumn=!evenColumn;
}
}
if (isEnabled()) {
if (isSelectedOffset(currentOffset)) {
g.setColor(m_selectionColor);
g.fillRect(x,y - m_charHeight,2 * m_charWidth,m_charHeight + 2);
g.setColor(evenColumn ? m_fontColorHex1 : m_fontColorHex2);
}
else if ((range != null) && range.containsOffset(currentOffset)) {
final Color bgColor=range.getBackgroundColor();
if (bgColor != null) {
g.setColor(bgColor);
}
g.fillRect(x,y - m_charHeight,2 * m_charWidth,m_charHeight + 2);
if (range.getColor() != null) {
g.setColor(range.getColor());
}
else {
g.setColor(evenColumn ? m_fontColorHex1 : m_fontColorHex2);
}
}
else {
if ((m_colormap != null) && m_colormap.colorize(data,i)) {
final Color backgroundColor=m_colormap.getBackgroundColor(data,i);
final Color foregroundColor=m_colormap.getForegroundColor(data,i);
if (backgroundColor != null) {
g.setColor(backgroundColor);
g.fillRect(x,y - m_charHeight,2 * m_charWidth,m_charHeight + 2);
}
if (foregroundColor != null) {
g.setColor(foregroundColor);
}
}
else {
g.setColor(evenColumn ? m_fontColorHex1 : m_fontColorHex2);
}
}
}
else {
g.setColor(m_disabledColor != m_bgColorHex ? m_disabledColor : Color.WHITE);
}
if (m_status == DefinitionStatus.DEFINED) {
final int columnBytes=Math.min(m_dataProvider.getDataLength() - i,m_bytesPerColumn);
final int dataPosition=m_flipBytes ? ((i / m_bytesPerColumn) * m_bytesPerColumn) + (columnBytes - (i % columnBytes) - 1) : i;
g.drawString(HEX_BYTES[data[dataPosition] & 0xFF],x,y);
}
else {
g.drawString("??",x,y);
}
x+=standardSize;
}
}
| Draws the content of the hex view. |
public Node encode(mxCodec enc,Object obj){
String name=mxCodecRegistry.getName(obj);
Element node=enc.document.createElement(name);
if (obj instanceof mxStylesheet) {
mxStylesheet stylesheet=(mxStylesheet)obj;
Iterator<Map.Entry<String,Map<String,Object>>> it=stylesheet.getStyles().entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String,Map<String,Object>> entry=it.next();
Element styleNode=enc.document.createElement("add");
String stylename=entry.getKey();
styleNode.setAttribute("as",stylename);
Map<String,Object> style=entry.getValue();
Iterator<Map.Entry<String,Object>> it2=style.entrySet().iterator();
while (it2.hasNext()) {
Map.Entry<String,Object> entry2=it2.next();
Element entryNode=enc.document.createElement("add");
entryNode.setAttribute("as",String.valueOf(entry2.getKey()));
entryNode.setAttribute("value",String.valueOf(entry2.getValue()));
styleNode.appendChild(entryNode);
}
if (styleNode.getChildNodes().getLength() > 0) {
node.appendChild(styleNode);
}
}
}
return node;
}
| Encodes the given mxStylesheet. |
public void endVisit(ArrayInitializer node){
}
| End of visit the given type-specific AST node. <p> The default implementation does nothing. Subclasses may reimplement. </p> |
public static _Fields findByName(String name){
return byName.get(name);
}
| Find the _Fields constant that matches name, or null if its not found. |
@CanIgnoreReturnValue public static <T>T readLines(URL url,Charset charset,LineProcessor<T> callback) throws IOException {
return asCharSource(url,charset).readLines(callback);
}
| Streams lines from a URL, stopping when our callback returns false, or we have read all of the lines. |
public boolean asksAllowsChildren(){
return asksAllowsChildren;
}
| Tells how leaf nodes are determined. |
public void mouseReleased(MouseEvent event){
tryPopup(event);
}
| Invoked when a mouse button has been released on a component. |
private void findStabbedSegments(Coordinate stabbingRayLeftPt,DirectedEdge dirEdge,List stabbedSegments){
Coordinate[] pts=dirEdge.getEdge().getCoordinates();
for (int i=0; i < pts.length - 1; i++) {
seg.p0=pts[i];
seg.p1=pts[i + 1];
if (seg.p0.y > seg.p1.y) seg.reverse();
double maxx=Math.max(seg.p0.x,seg.p1.x);
if (maxx < stabbingRayLeftPt.x) continue;
if (seg.isHorizontal()) continue;
if (stabbingRayLeftPt.y < seg.p0.y || stabbingRayLeftPt.y > seg.p1.y) continue;
if (CGAlgorithms.computeOrientation(seg.p0,seg.p1,stabbingRayLeftPt) == CGAlgorithms.RIGHT) continue;
int depth=dirEdge.getDepth(Position.LEFT);
if (!seg.p0.equals(pts[i])) depth=dirEdge.getDepth(Position.RIGHT);
DepthSegment ds=new DepthSegment(seg,depth);
stabbedSegments.add(ds);
}
}
| Finds all non-horizontal segments intersecting the stabbing line in the input dirEdge. The stabbing line is the ray to the right of stabbingRayLeftPt. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-06 08:48:10.882 -0400",hash_original_method="5702A363D6AA8AC6DC93E3805C32E157",hash_generated_method="B62E1D2DA86DD6FBB9E0231DBC0CFAD3") private PrintDocumentInfo(){
}
| Creates a new instance. |
public CopySourceEdit(int offset,int length,CopyTargetEdit target){
this(offset,length);
setTargetEdit(target);
}
| Constructs a new copy source edit. |
public boolean isSetError(){
return this.error != null;
}
| Returns true if field error is set (has been assigned a value) and false otherwise |
public int hashCode(){
int hash=hashCode;
if (hash == 0) {
hash=1;
if (fullName != null) {
hash+=fullName.hashCode();
}
else {
hash+=relativeName.hashCode();
}
hashCode=hash;
}
return hash;
}
| Returns the hash code for this distribution point name. |
public DepthFirstSearch(int bound){
this.depthBound=bound;
}
| Initiate the Depth First Search with the given fixed-depth bound to search. |
public DtoProductAssociationServiceImpl(final DtoFactory dtoFactory,final GenericService<ProductAssociation> productAssociationGenericService,final AdaptersRepository adaptersRepository){
super(dtoFactory,productAssociationGenericService,adaptersRepository);
productAssociationService=(ProductAssociationService)productAssociationGenericService;
}
| Construct base remote service. |
public void write(char[] cbuf,int off,int len) throws IOException {
if (len > 0) {
checkWrite();
}
super.write(cbuf,off,len);
}
| Writes a portion of an array of characters. |
private String renderTupleExpr(TupleExpr theExpr) throws Exception {
SerqlTupleExprRenderer aRenderer=new SerqlTupleExprRenderer();
aRenderer.mProjection=new ArrayList<ProjectionElemList>(mProjection);
aRenderer.mDistinct=mDistinct;
aRenderer.mReduced=mReduced;
aRenderer.mExtensions=new HashMap<String,ValueExpr>(mExtensions);
aRenderer.mOrdering=new ArrayList<OrderElem>(mOrdering);
aRenderer.mLimit=mLimit;
aRenderer.mOffset=mOffset;
return aRenderer.render(theExpr);
}
| Renders the tuple expression as a query string. It creates a new SerqlTupleExprRenderer rather than reusing this one. |
public static void drawToPng(final String dest,final AnnotatedTypeMirror type){
drawToPng(new File(dest),type);
}
| Draws a dot file for type in a temporary directory then calls the "dot" program to convert that file into a png at the location dest. This method will fail if a temp file can't be created. |
protected POInfo initPO(Properties ctx){
POInfo poi=POInfo.getPOInfo(ctx,Table_ID,get_TrxName());
return poi;
}
| Load Meta Data |
protected User(String username,String password){
super();
Assert.hasText(username,"Not allowed to create an User with an empty username");
Assert.hasText(password,"Not allowed to create an User with an empty password");
this.username=username;
this.password=password;
}
| Create a new User with an username. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.