code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
void visitSubroutine(final Label JSR,final long id,final int nbSubroutines){
Label stack=this;
while (stack != null) {
Label l=stack;
stack=l.next;
l.next=null;
if (JSR != null) {
if ((l.status & VISITED2) != 0) {
continue;
}
l.status|=VISITED2;
if ((l.status & RET) != 0) {
if (!l.inSameSubroutine(JSR)) {
Edge e=new Edge();
e.info=l.inputStackTop;
e.successor=JSR.successors.successor;
e.next=l.successors;
l.successors=e;
}
}
}
else {
if (l.inSubroutine(id)) {
continue;
}
l.addToSubroutine(id,nbSubroutines);
}
Edge e=l.successors;
while (e != null) {
if ((l.status & Label.JSR) == 0 || e != l.successors.next) {
if (e.successor.next == null) {
e.successor.next=stack;
stack=e.successor;
}
}
e=e.next;
}
}
}
| Finds the basic blocks that belong to a given subroutine, and marks these blocks as belonging to this subroutine. This method follows the control flow graph to find all the blocks that are reachable from the current block WITHOUT following any JSR target. |
public Complex cos(){
return new Complex(Math.cos(re) * Math.cosh(im),-Math.sin(re) * Math.sinh(im));
}
| Returns the complex cosine of this complex number. |
public void close() throws SQLException {
this.closed=true;
for ( Connection c : this.serverConnections.values()) {
try {
c.close();
}
catch ( SQLException ex) {
}
}
}
| Close this connection proxy which entails closing all open connections to MySQL servers. |
public String plus(Object value){
return this.theString + value;
}
| Fairly simple method used for the plus (+) base concatenation in Groovy. |
public String showAttributes(){
DataSortedTableModel model;
ListSelectorDialog dialog;
int i;
JList list;
String name;
int result;
if (!isPanelSelected()) {
return null;
}
list=new JList(getCurrentPanel().getAttributes());
dialog=new ListSelectorDialog(getParentFrame(),list);
result=dialog.showDialog();
if (result == ListSelectorDialog.APPROVE_OPTION) {
model=(DataSortedTableModel)getCurrentPanel().getTable().getModel();
name=list.getSelectedValue().toString();
i=model.getAttributeColumn(name);
JTableHelper.scrollToVisible(getCurrentPanel().getTable(),0,i);
getCurrentPanel().getTable().setSelectedColumn(i);
return name;
}
else {
return null;
}
}
| displays all the attributes, returns the selected item or NULL if canceled |
@Override public void mouseReleased(MouseEvent event){
if (event.getSource() == getComponentDecreaseSpinnerButton()) {
decreaseTimer.stop();
}
else {
increaseTimer.stop();
}
}
| mouseReleased, This will be called when the spinner button is released. |
private static String thresholdsToString(String[] thresholdArray){
String result=null;
if (thresholdArray.length > 0) {
result=thresholdArray[0];
for (int i=1; i < thresholdArray.length; i++) {
result+="; ";
result+=thresholdArray[i];
}
}
return result;
}
| Converts a given array of strings into a single string with the array elements separated by a semi-colon. |
public boolean willOpenInForeground(TabLaunchType type,boolean isNewTabIncognito){
if (type == TabLaunchType.FROM_RESTORE) return false;
return type != TabLaunchType.FROM_LONGPRESS_BACKGROUND || (!mTabModelSelector.isIncognitoSelected() && isNewTabIncognito);
}
| Determine if a launch type will result in the tab being opened in the foreground. |
@Override public void messageSent(final NextFilter nextFilter,final IoSession session,final WriteRequest writeRequest) throws Exception {
if (writeRequest.getMessage() != null && writeRequest.getMessage() instanceof ProxyHandshakeIoBuffer) {
return;
}
nextFilter.messageSent(session,writeRequest);
}
| Filter handshake related messages from reaching the messageSent callbacks of downstream filters. |
protected void writeTableComment(Table table,StringBuilder ddl){
printComment("-----------------------------------------------------------------------",ddl);
printComment(getFullyQualifiedTableNameShorten(table),ddl);
printComment("-----------------------------------------------------------------------",ddl);
println(ddl);
}
| Outputs a comment for the table. |
@DSComment("constructor") @DSSafe(DSCat.SAFE_OTHERS) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:33:23.158 -0500",hash_original_method="3CB703BA4BBEFDD58F8198A538C651FA",hash_generated_method="CF855BD0B8B8C8AFFCD8B68DE31A2318") public SparseIntArray(){
this(10);
}
| Creates a new SparseIntArray containing no mappings. |
public void clearUnused(){
Log log=getLog();
try {
if (session == null) session=new StorageScopeEngine(factory,log,new StorageScopeCleaner[]{new FileStorageScopeCleaner(Scope.SCOPE_SESSION,null),new DatasourceStorageScopeCleaner(Scope.SCOPE_SESSION,null)});
if (client == null) client=new StorageScopeEngine(factory,log,new StorageScopeCleaner[]{new FileStorageScopeCleaner(Scope.SCOPE_CLIENT,null),new DatasourceStorageScopeCleaner(Scope.SCOPE_CLIENT,null)});
storeUnusedStorageScope(factory,Scope.SCOPE_CLIENT);
storeUnusedStorageScope(factory,Scope.SCOPE_SESSION);
clearUnusedMemoryScope(factory,Scope.SCOPE_CLIENT);
clearUnusedMemoryScope(factory,Scope.SCOPE_SESSION);
session.clean();
client.clean();
clearUnusedApplications(factory);
}
catch ( Throwable t) {
error(t);
}
}
| remove all unused scope objects |
void seed(){
for (int j=0; j <= sentLen - 1; j++) {
if (pGrammar.hasRuleForSpan(j,j,input.distance(j,j))) {
if (null == pGrammar.getTrieRoot()) {
throw new RuntimeException("trie root is null");
}
addDotItem(pGrammar.getTrieRoot(),j,j,null,null,new SourcePath());
}
}
}
| Add initial dot items: dot-items pointer to the root of the grammar trie. |
@SuppressWarnings("unchecked") public static <T>Matcher<T> any(){
return Any.ANY;
}
| Returns a wildcard matcher. |
public static void scaleM(double[] m,int mOffset,double x,double y,double z){
for (int i=0; i < 4; i++) {
int mi=mOffset + i;
m[mi]*=x;
m[4 + mi]*=y;
m[8 + mi]*=z;
}
}
| Scales matrix m in place by sx, sy, and sz |
private static byte[] readClass(final InputStream is) throws IOException {
if (is == null) {
throw new IOException("Class not found");
}
byte[] b=new byte[is.available()];
int len=0;
while (true) {
int n=is.read(b,len,b.length - len);
if (n == -1) {
if (len < b.length) {
byte[] c=new byte[len];
System.arraycopy(b,0,c,0,len);
b=c;
}
return b;
}
len+=n;
if (len == b.length) {
int last=is.read();
if (last < 0) {
return b;
}
byte[] c=new byte[b.length + 1000];
System.arraycopy(b,0,c,0,len);
c[len++]=(byte)last;
b=c;
}
}
}
| Reads the bytecode of a class. |
public GridCacheVersion mappedVersion(int idx){
return mappedVers == null ? null : mappedVers[idx];
}
| Returns DHT candidate version for acquired near lock on DHT node. |
private String addStyleName(String style){
if (styleNameMapping == null) {
return style;
}
StringBuilder sb=null;
for (int counter=style.length() - 1; counter >= 0; counter--) {
if (!isValidCharacter(style.charAt(counter))) {
if (sb == null) {
sb=new StringBuilder(style);
}
sb.setCharAt(counter,'a');
}
}
String mappedName=(sb != null) ? sb.toString() : style;
while (styleNameMapping.get(mappedName) != null) {
mappedName=mappedName + 'x';
}
styleNameMapping.put(style,mappedName);
return mappedName;
}
| Adds the style named <code>style</code> to the style mapping. This returns the name that should be used when outputting. CSS does not allow the full Unicode set to be used as a style name. |
private Organization validateForOnBehalfUserCreation(String organizationId,String password,PlatformUser currentUser) throws ObjectNotFoundException, OperationNotPermittedException {
ArgumentValidator.notNull("organizationId",organizationId);
ArgumentValidator.notNull("password",password);
Organization customer=new Organization();
customer.setOrganizationId(organizationId);
customer=(Organization)dm.getReferenceByBusinessKey(customer);
if (!currentUser.getOrganization().isActingOnBehalf(customer)) {
OperationNotPermittedException onpe=new OperationNotPermittedException();
logger.logWarn(Log4jLogger.SYSTEM_LOG,onpe,LogMessageIdentifier.WARN_USER_CREATE_CUSTOMER_FAILED,currentUser.getUserId(),currentUser.getOrganization().getOrganizationId(),customer.getOrganizationId());
throw onpe;
}
return customer;
}
| Validates that the preconditions for the creation of a on-behalf user are met. |
public long nextLong(){
return org.evosuite.runtime.Random.nextLong();
}
| Replacement function for nextLong |
public static boolean deleteFileWithBackup(Path file,String datasource){
String fn=file.toAbsolutePath().toString();
if (!fn.startsWith(datasource)) {
LOGGER.warn("could not delete file '" + fn + "': datasource '"+ datasource+ "' does not match");
return false;
}
if (Files.isDirectory(file)) {
LOGGER.warn("could not delete file '" + fn + "': file is a directory!");
return false;
}
fn=fn.replace(datasource,datasource + FileSystems.getDefault().getSeparator() + Constants.BACKUP_FOLDER);
try {
Path backup=Paths.get(fn);
if (!Files.exists(backup.getParent())) {
Files.createDirectories(backup.getParent());
}
Files.deleteIfExists(backup);
return moveFileSafe(file,backup);
}
catch ( IOException e) {
LOGGER.warn("Could not delete file: " + e.getMessage());
return false;
}
}
| <b>PHYSICALLY</b> deletes a file by moving it to datasource backup folder<br> DS\.backup\<filename><br> maintaining its originating directory |
public static byte[] internalize(Name name){
return internalize(name.getByteArray(),name.getByteOffset(),name.getByteLength());
}
| Return internal representation of given name, converting '/' to '.'. |
@Override public String toString(){
if (length == 0) {
return "FacetLabel: []";
}
String[] parts=new String[length];
System.arraycopy(components,0,parts,0,length);
return "FacetLabel: " + Arrays.toString(parts);
}
| Returns a string representation of the path. |
protected void init(){
if (initialized) return;
Map<String,Class<? extends FXGNode>> elementNodes=new HashMap<String,Class<? extends FXGNode>>(DEFAULT_FXG_1_0_NODES.size() + 4);
elementNodes.putAll(DEFAULT_FXG_1_0_NODES);
elementNodesByURI=new HashMap<String,Map<String,Class<? extends FXGNode>>>(1);
elementNodesByURI.put(FXG_NAMESPACE,elementNodes);
HashSet<String> skippedElements=new HashSet<String>(1);
skippedElements.add(FXG_PRIVATE_ELEMENT);
skippedElementsByURI=new HashMap<String,Set<String>>(1);
skippedElementsByURI.put(FXG_NAMESPACE,skippedElements);
initialized=true;
}
| initializes the version handler with FXG 2.0 specific information |
public final double calculateTreeLogLikelihood(Tree tree){
int[] n=new int[size];
int nTips=tree.getExternalNodeCount();
preCalculation(tree);
int index=size - 1;
double t=t(index);
double g=g(index,x0,t);
double logP=Math.log(g);
for (int i=0; i < tree.getInternalNodeCount(); i++) {
double x=tree.getNodeHeight(tree.getInternalNode(i));
index=index(x);
double contrib=Math.log(birth(birthChanges ? index : 0) * g(index,x,t(index)));
logP+=contrib;
t=t(index);
g=g(index,x,t);
}
for (int i=0; i < nTips; i++) {
double y=tree.getNodeHeight(tree.getExternalNode(i));
index=index(y);
double contrib=Math.log(psi(samplingChanges ? index : 0)) - Math.log(g(index,y,t(index)));
;
logP+=contrib;
}
for (int j=0; j < size - 1; j++) {
double contrib=0;
double time=t(j + 1);
n[j]=lineageCountAtTime(time,tree);
if (n[j] > 0) {
contrib+=n[j] * Math.log(g(j,time,t(j)));
}
logP+=contrib;
}
return logP;
}
| Generic likelihood calculation |
public Boolean sismember(final byte[] key,final byte[] member){
checkIsInMulti();
client.sismember(key,member);
return client.getIntegerReply() == 1;
}
| Return 1 if member is a member of the set stored at key, otherwise 0 is returned. <p> Time complexity O(1) |
Type attribTree(JCTree tree,Env<AttrContext> env,ResultInfo resultInfo){
Env<AttrContext> prevEnv=this.env;
ResultInfo prevResult=this.resultInfo;
try {
this.env=env;
this.resultInfo=resultInfo;
tree.accept(this);
if (tree == breakTree && resultInfo.checkContext.deferredAttrContext().mode == AttrMode.CHECK) {
throw new BreakAttr(copyEnv(env));
}
return result;
}
catch ( CompletionFailure ex) {
tree.type=syms.errType;
return chk.completionError(tree.pos(),ex);
}
finally {
this.env=prevEnv;
this.resultInfo=prevResult;
}
}
| Visitor method: attribute a tree, catching any completion failure exceptions. Return the tree's type. |
@Override public void initialize(){
super.initialize();
DefaultLookup.setDefaultLookup(new SynthDefaultLookup());
setStyleFactory(factory);
KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener(_handler);
}
| Called by UIManager when this look and feel is installed. |
private float spacing(WrapMotionEvent event){
float x=event.getX(0) - event.getX(1);
float y=event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}
| Determine the space between the first two fingers |
protected void parseHeaderLine(String line) throws IOException {
int len=2;
int n=line.indexOf(": ");
if (n == -1) {
len=1;
n=line.indexOf(':');
if (n == -1) return;
}
String key=line.substring(0,n);
String val=line.substring(n + len);
List<String> list=headers.get(key);
if (list != null) {
list.add(val);
}
else {
list=new ArrayList<String>();
list.add(val);
headers.put(key,list);
}
}
| Reads one response header line and adds it to the headers map. |
public MediaSize(float x,float y,int units){
super(x,y,units);
if (x > y) {
throw new IllegalArgumentException("X dimension > Y dimension");
}
sizeVector.add(this);
}
| Construct a new media size attribute from the given floating-point values. |
public void fill(int rgb){
g.fill(rgb);
}
| Set the fill to either a grayscale value or an ARGB int. |
public boolean equals(Object obj){
if (obj == this) {
return true;
}
if (obj instanceof AnnotationMember) {
AnnotationMember that=(AnnotationMember)obj;
if (name.equals(that.name) && tag == that.tag) {
if (tag == ARRAY) {
return equalArrayValue(that.value);
}
else if (tag == ERROR) {
return false;
}
else {
return value.equals(that.value);
}
}
}
return false;
}
| Returns true if the specified object represents equal element (equivalent name-value pair). <br> A special case is the contained Throwable value; it is considered transcendent so no other element would be equal. |
private void init(final AttributeSet attrs,final int defStyleAttr,final int defStyleRes){
final TypedArray attributes=getContext().obtainStyledAttributes(attrs,R.styleable.DotIndicator,defStyleAttr,defStyleRes);
final int defaultSelectedDotDiameterPx=DimensionHelper.dpToPx(getContext(),DEFAULT_SELECTED_DOT_DIAMETER_DP);
final int defaultUnselectedDotDiameterPx=DimensionHelper.dpToPx(getContext(),DEFAULT_UNSELECTED_DOT_DIAMETER_DP);
final int defaultSpacingBetweenDotsPx=DimensionHelper.dpToPx(getContext(),DEFAULT_SPACING_BETWEEN_DOTS_DP);
numberOfDots=attributes.getInt(R.styleable.DotIndicator_numberOfDots,DEFAULT_NUMBER_OF_DOTS);
selectedDotIndex=attributes.getInt(R.styleable.DotIndicator_selectedDotIndex,DEFAULT_SELECTED_DOT_INDEX);
unselectedDotDiameterPx=attributes.getDimensionPixelSize(R.styleable.DotIndicator_unselectedDotDiameter,defaultUnselectedDotDiameterPx);
selectedDotDiameterPx=attributes.getDimensionPixelSize(R.styleable.DotIndicator_selectedDotDiameter,defaultSelectedDotDiameterPx);
unselectedDotColor=attributes.getColor(R.styleable.DotIndicator_unselectedDotColor,DEFAULT_UNSELECTED_DOT_COLOR);
selectedDotColor=attributes.getColor(R.styleable.DotIndicator_selectedDotColor,DEFAULT_SELECTED_DOT_COLOR);
spacingBetweenDotsPx=attributes.getDimensionPixelSize(R.styleable.DotIndicator_spacingBetweenDots,defaultSpacingBetweenDotsPx);
dotTransitionDuration=attributes.getDimensionPixelSize(R.styleable.DotIndicator_dotTransitionDuration,DEFAULT_DOT_TRANSITION_DURATION_MS);
attributes.recycle();
setLayoutParams(new LayoutParams(MATCH_PARENT,MATCH_PARENT));
setGravity(Gravity.CENTER);
reflectParametersInView();
}
| Initialises the member variables of this DotIndicator and creates the UI. This method should only be invoked during construction. |
public void block(){
lock.writeLock();
}
| Blocks current thread till all activities left "busy" state and prevents them from further entering to "busy" state. |
@Override public boolean appendTasks(ImageToProcess img,Set<TaskImageContainer> tasks){
int countImageRefs=numPropagatedImageReferences(img,tasks);
if (img != null) {
incrementSemaphoreReferenceCount(img,countImageRefs);
}
incrementTaskDone(tasks);
scheduleTasks(tasks);
return true;
}
| Spawns dependent tasks from internal implementation of a set of tasks. If a dependent task does NOT require the image reference, it should be passed a null pointer as an image reference. In general, this method should be called after the task has completed its own computations, but before it has released its own image reference (via the releaseSemaphoreReference call). |
Account(){
id=0;
balance=0;
annualInterestRate=0;
dateCreated=new Date();
}
| Creates a default account |
private void createLogoutEvent(Session session){
if (session.getUserToken() != null && session.getUserToken().length() == 0) {
GatheredEvent event=new GatheredEvent();
event.setActor(session.getPlatformUserId());
event.setType(EventType.PLATFORM_EVENT);
event.setEventId(PlatformEventIdentifier.USER_LOGOUT_FROM_SERVICE);
event.setOccurrenceTime(System.currentTimeMillis());
event.setSubscriptionTKey(session.getSubscriptionTKey().longValue());
try {
evtMgmt.recordEvent(event);
}
catch ( DuplicateEventException e) {
logger.logDebug(e.getMessage());
}
}
}
| Creates a logout event for the given session. A logout event is only generated in case the user token is not set anymore, what means that the user has really logged in earlier |
public void clear(){
ref.length=0;
}
| Reset this builder to the empty state. |
public static TupleSchema of(String name,TupleSlot... slots){
checkNotNull(name,"name must not be null");
checkNotNull(slots,"slots must not be null");
Map<String,Integer> slotLookup=IntStream.range(0,slots.length).collect(null,null,null);
checkArgument(slots.length == slotLookup.size(),"Slot names are not unique");
return new TupleSchema(name,slots,slotLookup);
}
| Create a TupleSchema having the supplied TupleSlots. |
boolean isPrivileged(){
return isPrivileged;
}
| Returns true if this context is privileged. |
public Iterable<FunctionImport> build(FactoryLookup lookup){
List<FunctionImport> builder=new ArrayList<>();
for ( FunctionImportImpl.Builder functionImportBuilder : functionImportBuilders) {
EntitySet entitySet=lookup.getEntitySet(functionImportBuilder.getEntitySetName());
Function function=lookup.getFunction(functionImportBuilder.getFunctionName());
if (entitySet == null && function.isBound()) {
throw new IllegalArgumentException("Could not find EntitySet with name: " + functionImportBuilder.getEntitySetName());
}
functionImportBuilder.setEntitySet(entitySet);
functionImportBuilder.setFunction(function);
builder.add(functionImportBuilder.build());
}
return Collections.unmodifiableList(builder);
}
| Returns built function imports using passed lookup for searching entity sets and functions for appropriate function import. |
public boolean isEnabled(){
if (source instanceof Component) {
return ((Component)source).isEnabled();
}
else if (source instanceof MenuItem) {
return ((MenuItem)source).isEnabled();
}
else {
return true;
}
}
| Determine if the object is enabled. |
@SuppressWarnings("unchecked") public ClusterUpdateSettingsRequest transientSettings(Map source){
try {
XContentBuilder builder=XContentFactory.contentBuilder(XContentType.JSON);
builder.map(source);
transientSettings(builder.string());
}
catch ( IOException e) {
throw new ElasticsearchGenerationException("Failed to generate [" + source + "]",e);
}
return this;
}
| Sets the transient settings to be updated. They will not survive a full cluster restart |
private void layoutComponents(){
setLayout(new GridBagLayout());
setBorder(new CompoundBorder(new TitledBorder(DISPLAY_NAME),new EmptyBorder(6,6,6,6)));
setToolTipText(DESCRIPTION);
GridBagConstraints c=new GridBagConstraints();
c.anchor=GridBagConstraints.WEST;
c.fill=GridBagConstraints.HORIZONTAL;
c.gridheight=1;
c.gridwidth=GridBagConstraints.RELATIVE;
c.insets=LABEL_INSETS;
c.gridx=0;
c.gridy=0;
c.weightx=0.33f;
c.weighty=0;
add(new JLabel("Minimum value"),c);
c.insets=FIELD_INSETS;
c.gridx=1;
c.weightx=0.66f;
add(minimumValue,c);
c.insets=LABEL_INSETS;
c.gridx=0;
c.gridy++;
c.weightx=0.33f;
add(new JLabel("Maximum value"),c);
c.insets=FIELD_INSETS;
c.gridx=1;
c.weightx=0.66f;
add(maximumValue,c);
c.anchor=GridBagConstraints.NORTHWEST;
c.fill=GridBagConstraints.BOTH;
c.gridwidth=GridBagConstraints.REMAINDER;
c.insets=EMPTY_INSETS;
c.gridx=0;
c.gridy++;
c.weightx=1.0f;
c.weighty=1.0f;
add(Box.createGlue(),c);
}
| Layout components. |
public int addMultiNewarray(CtClass clazz,int[] dimensions){
int len=dimensions.length;
for (int i=0; i < len; ++i) addIconst(dimensions[i]);
growStack(len);
return addMultiNewarray(clazz,len);
}
| Appends MULTINEWARRAY. |
public int transcribe(IPoint[] hull,int offset){
int idx=offset;
int sz=points.size();
for (int i=0; i < sz; i++) {
hull[idx++]=points.get(i);
}
return idx;
}
| Fill array with points starting at given offset. |
public void editTracks(){
List<Track> trackSelection=getRootController().getSelectedTracks();
if (!trackSelection.isEmpty()) {
boolean[] edit={true};
if (trackSelection.size() > 1) {
String alertHeader="Are you sure you want to edit multiple files?";
Alert alert=createAlert("",alertHeader,"",AlertType.CONFIRMATION);
Optional<ButtonType> result=alert.showAndWait();
result.ifPresent(null);
}
if (edit[0]) {
if (editStage == null) {
editStage=initStage(EDIT_LAYOUT,"Edit");
((EditController)controllers.get(EDIT_LAYOUT)).setStage(editStage);
}
showStage(editStage);
LOG.debug("Showing edit stage");
}
}
}
| Shows the edit window. If the size of track selection is greater than 1, an <tt>Alert</tt> is opened asking for a confirmation of the user. |
public ReadMemoryReply(final int packetId,final int errorCode,final IAddress address,final byte[] data){
super(packetId,errorCode);
if (success()) {
Preconditions.checkNotNull(address,"IE01066: Address argument can not be null");
Preconditions.checkNotNull(data,"IE01067: Data argument can not be null");
}
else {
if (address != null) {
throw new IllegalArgumentException("IE01068: Address argument must be null");
}
if (data != null) {
throw new IllegalArgumentException("IE01069: Data argument must be null");
}
}
startAddress=address;
memoryData=data == null ? null : data.clone();
}
| Creates a new Read Memory reply. |
public static CompileStates instance(Context context){
CompileStates instance=context.get(compileStatesKey);
if (instance == null) {
instance=new CompileStates(context);
}
return instance;
}
| Get the CompileStates instance for this context. |
@Override public void stateChanged(ChangeEvent e){
if (e.getSource() == this.acceptCheckBox) {
this.acceptButton.setEnabled(this.acceptCheckBox.isSelected());
}
}
| Listens to changes of the check box, enables the accept button when the check box is active. |
public void addPoint(Vector3 point1,Vector3 controlPoint,Vector3 point2){
mPoint1=point1;
mControlPoint=controlPoint;
mPoint2=point2;
}
| Add a Curve |
@Override public void sendErrorStatus(String errorStatus) throws IOException {
this.sendMessage(OPERATIONS + ": " + errorStatus+ "\n");
}
| constructs an error message and sends it to the client. The error message will be <ul> <li> OPERATIONS: </li> <li> the error string </li> <li> "\n" </li> </ul> |
private boolean selectID(int nodeID,boolean show){
if (m_root == null) return false;
log.config("NodeID=" + nodeID + ", Show="+ show+ ", root="+ m_root);
MTreeNode node=m_root.findNode(nodeID);
if (node != null) {
TreePath treePath=new TreePath(node.getPath());
log.config("Node=" + node + ", Path="+ treePath.toString());
tree.setSelectionPath(treePath);
if (show) {
tree.makeVisible(treePath);
tree.scrollPathToVisible(treePath);
}
return true;
}
log.info("Node not found; ID=" + nodeID);
return false;
}
| Select ID in Tree |
public ProductTypeServiceImpl(final GenericDAO<ProductType,Long> productTypeDao){
super(productTypeDao);
}
| Construct service. |
public int size(){
return data.size();
}
| Returns the number of observations used in this test. |
@Override public void createUntamperedRequest(){
CollisionDJBX33A DJBX33A=new CollisionDJBX33A();
String untampered=UtilHashDoS.generateUntampered(DJBX33A,optionNumberAttributes.getValue(),optionUseNamespaces.isOn());
String soapMessage=this.getOptionTextAreaSoapMessage().getValue();
String soapMessageFinal=this.getOptionTextAreaSoapMessage().replacePlaceholderWithPayload(soapMessage,untampered);
Map<String,String> httpHeaderMap=new HashMap<String,String>();
for ( Map.Entry<String,String> entry : getOriginalRequestHeaderFields().entrySet()) {
httpHeaderMap.put(entry.getKey(),entry.getValue());
}
this.setUntamperedRequestObject(httpHeaderMap,getOriginalRequest().getEndpoint(),soapMessageFinal);
}
| custom untampered request needed for prevention of false positives based on effect of XML Attribute Count Attack |
@Override public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
mHanler=new Handler();
setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
if (!Engine.getInstance().isStarted()) {
startActivityForResult(new Intent(this,ScreenSplash.class),Main.RC_SPLASH);
return;
}
Bundle bundle=savedInstanceState;
if (bundle == null) {
Intent intent=getIntent();
bundle=intent == null ? null : intent.getExtras();
}
if (bundle != null && bundle.getInt("action",Main.ACTION_NONE) != Main.ACTION_NONE) {
handleAction(bundle);
}
else if (mScreenService != null) {
mScreenService.show(ScreenHome.class);
}
}
| Called when the activity is first created. |
public static String readInputStream(InputStream in) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(in));
char[] buffer=new char[INITIAL_READ_BUFFER_SIZE];
StringBuilder sb=new StringBuilder();
int readCount;
while ((readCount=br.read(buffer)) != -1) {
sb.append(buffer,0,readCount);
}
return sb.toString();
}
| Read a string from an input stream. |
@Override public ClusterSearchShardsRequest indices(String... indices){
if (indices == null) {
throw new IllegalArgumentException("indices must not be null");
}
else {
for (int i=0; i < indices.length; i++) {
if (indices[i] == null) {
throw new IllegalArgumentException("indices[" + i + "] must not be null");
}
}
}
this.indices=indices;
return this;
}
| Sets the indices the search will be executed on. |
@Override protected DeLiCluEntry createRootEntry(){
return new DeLiCluDirectoryEntry(0,null,false,true);
}
| Creates an entry representing the root node. |
public final void close(){
try {
this.dataOut.flush();
if (this.trace) {
this.traceDataOut.flush();
}
}
catch ( IOException ignore) {
}
try {
outStream.close();
if (this.trace) {
this.traceOutStream.close();
}
}
catch ( IOException ex) {
throw new GemFireIOException(LocalizedStrings.StatArchiveWriter_COULD_NOT_CLOSE_STATARCHIVER_FILE.toLocalizedString(),ex);
}
if (getSampleCount() == 0) {
deleteFileIfPossible(new File(getArchiveName()));
}
}
| Closes the statArchiver by flushing its data to disk a closing its output stream. |
public static void createAllTables(SQLiteDatabase db,boolean ifNotExists){
RecommendEntityDao.createTable(db,ifNotExists);
}
| Creates underlying database table using DAOs. |
public ContentDispositionHeader createContentDispositionHeader(String contentDisposition) throws ParseException {
if (contentDisposition == null) throw new NullPointerException("null arg contentDisposition");
ContentDisposition c=new ContentDisposition();
c.setDispositionType(contentDisposition);
return c;
}
| Creates a new ContentDispositionHeader based on the newly supplied contentDisposition value. |
public int encodeBase64Partial(int bits,int outputBytes,byte[] buffer,int outPtr){
buffer[outPtr++]=_base64ToAsciiB[(bits >> 18) & 0x3F];
buffer[outPtr++]=_base64ToAsciiB[(bits >> 12) & 0x3F];
if (_usesPadding) {
byte pb=(byte)_paddingChar;
buffer[outPtr++]=(outputBytes == 2) ? _base64ToAsciiB[(bits >> 6) & 0x3F] : pb;
buffer[outPtr++]=pb;
}
else {
if (outputBytes == 2) {
buffer[outPtr++]=_base64ToAsciiB[(bits >> 6) & 0x3F];
}
}
return outPtr;
}
| Method that outputs partial chunk (which only encodes one or two bytes of data). Data given is still aligned same as if it as full data; that is, missing data is at the "right end" (LSB) of int. |
public final boolean isProxy(){
return flags[PROXY_TICKET_FLAG];
}
| Determines is this ticket is a proxy-ticket. |
public OracleException(String message,Throwable cause,int errorCode){
super(message,cause);
this.errorCode=errorCode;
}
| Constructs an <code>OracleException</code> with a given message, cause, error code, and error prefix. |
public HandlerSubscriber(EventExecutor executor){
this(executor,DEFAULT_LOW_WATERMARK,DEFAULT_HIGH_WATERMARK);
}
| Create a new handler subscriber with the default low and high watermarks. The supplied executor must be the same event loop as the event loop that this handler is eventually registered with, if not, an exception will be thrown when the handler is registered. |
protected Intersection findClosestIntersection(LatLonPoint latLon){
Intersection inter=(Intersection)interQuadTree.get(latLon.getY(),latLon.getX());
if (inter == null) logger.warning("no intersection at " + latLon);
return inter;
}
| Look in intersection Quad Tree for closest intersection to point at specified latitude and longitude. <p> |
public void addSpokenFlag(int flag){
final int flags=mMetadata.getInt(KEY_METADATA_SPEECH_FLAGS,0);
mMetadata.putInt(KEY_METADATA_SPEECH_FLAGS,flags | flag);
}
| Adds a spoken feedback flag to this utterance's metadata. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:55:20.434 -0500",hash_original_method="A949ED7F371D2CEC2724714D98F74A81",hash_generated_method="A35FEC8DECEC7FCDFB70A09E65B2BE34") protected SIPTransactionStack(StackMessageFactory messageFactory){
this();
this.sipMessageFactory=messageFactory;
}
| Construcor for the stack. Registers the request and response factories for the stack. |
private static Result<?> decodeVariableHeader(ByteBuf buffer,MqttFixedHeader mqttFixedHeader){
switch (mqttFixedHeader.messageType()) {
case CONNECT:
return decodeConnectionVariableHeader(buffer);
case CONNACK:
return decodeConnAckVariableHeader(buffer);
case SUBSCRIBE:
case UNSUBSCRIBE:
case SUBACK:
case UNSUBACK:
case PUBACK:
case PUBREC:
case PUBCOMP:
case PUBREL:
return decodePacketIdVariableHeader(buffer);
case PUBLISH:
return decodePublishVariableHeader(buffer,mqttFixedHeader);
default :
return new Result<>(null,0);
}
}
| Decodes the variable header (if any) |
public String multivalEncode(String value){
return value.replaceAll("\\\\","\\\\\\\\").replaceAll(",","\\\\,");
}
| Encodes a string value according to the conventions for supporting multiple values for a parameter (commas and backslashes are escaped). |
public UrlModuleSourceProvider(Iterable<URI> privilegedUris,Iterable<URI> fallbackUris,UrlConnectionExpiryCalculator urlConnectionExpiryCalculator,UrlConnectionSecurityDomainProvider urlConnectionSecurityDomainProvider){
this.privilegedUris=privilegedUris;
this.fallbackUris=fallbackUris;
this.urlConnectionExpiryCalculator=urlConnectionExpiryCalculator;
this.urlConnectionSecurityDomainProvider=urlConnectionSecurityDomainProvider;
}
| Creates a new module script provider that loads modules against a set of privileged and fallback URIs. It will use the specified heuristic cache expiry calculator and security domain provider. |
public void test_getInstanceLjava_lang_StringLjava_lang_String() throws NoSuchAlgorithmException, NoSuchProviderException, IllegalArgumentException, KeyManagementException {
try {
SSLContext.getInstance(null,mProv.getName());
fail("NoSuchAlgorithmException or NullPointerException should be thrown " + "(protocol is null)");
}
catch ( NoSuchAlgorithmException e) {
}
catch ( NullPointerException e) {
}
for (int i=0; i < invalidValues.length; i++) {
try {
SSLContext.getInstance(invalidValues[i],mProv.getName());
fail("NoSuchAlgorithmException must be thrown (protocol: ".concat(invalidValues[i]).concat(")"));
}
catch ( NoSuchAlgorithmException e) {
}
}
String prov=null;
for (int i=0; i < validValues.length; i++) {
try {
SSLContext.getInstance(validValues[i],prov);
fail("IllegalArgumentException must be thrown when provider is null (protocol: ".concat(invalidValues[i]).concat(")"));
}
catch ( IllegalArgumentException e) {
}
try {
SSLContext.getInstance(validValues[i],"");
fail("IllegalArgumentException must be thrown when provider is empty (protocol: ".concat(invalidValues[i]).concat(")"));
}
catch ( IllegalArgumentException e) {
}
}
for (int i=0; i < validValues.length; i++) {
for (int j=1; j < invalidValues.length; j++) {
try {
SSLContext.getInstance(validValues[i],invalidValues[j]);
fail("NoSuchProviderException must be thrown (protocol: ".concat(invalidValues[i]).concat(" provider: ").concat(invalidValues[j]).concat(")"));
}
catch ( NoSuchProviderException e) {
}
}
}
SSLContext sslC;
for (int i=0; i < validValues.length; i++) {
sslC=SSLContext.getInstance(validValues[i],mProv.getName());
assertTrue("Not instanceof SSLContext object",sslC instanceof SSLContext);
assertEquals("Incorrect protocol",sslC.getProtocol(),validValues[i]);
assertEquals("Incorrect provider",sslC.getProvider().getName(),mProv.getName());
checkSSLContext(sslC);
}
}
| Test for <code>getInstance(String protocol, String provider)</code> method Assertions: throws NullPointerException when protocol is null; throws NoSuchAlgorithmException when protocol is not correct; throws IllegalArgumentException when provider is null or empty; throws NoSuchProviderException when provider is available; returns SSLContext object |
public WrappedByteBuffer putLong(long v){
_autoExpand(8);
_buf.putLong(v);
return this;
}
| Puts an eight-byte long into the buffer at the current position. |
private void verifyMigrationDone(String version){
CoordinatorClient coordinator=getCoordinator();
Assert.assertEquals(MigrationStatus.DONE,coordinator.getMigrationStatus());
String checkpoint=getCheckpoint(version);
Assert.assertNull(checkpoint);
}
| Verify if migration checkpoint information is cleared after migration done |
public RepaintManager(ImageRenderer r){
renderer=r;
}
| Creates a new repaint manager. |
public void testMaxNegZero(){
byte aBytes[]={45,91,3,-15,35,26,3,91};
int aSign=-1;
byte rBytes[]={0};
BigInteger aNumber=new BigInteger(aSign,aBytes);
BigInteger bNumber=BigInteger.ZERO;
BigInteger result=aNumber.max(bNumber);
byte resBytes[]=new byte[rBytes.length];
resBytes=result.toByteArray();
for (int i=0; i < resBytes.length; i++) {
assertTrue(resBytes[i] == rBytes[i]);
}
assertTrue("incorrect sign",result.signum() == 0);
}
| max(BigInteger val). max of negative and ZERO. |
static int[] convertMidTerms(int[] k){
int[] res=new int[3];
if (k.length == 1) {
res[0]=k[0];
}
else {
if (k.length != 3) {
throw new IllegalArgumentException("Only Trinomials and pentanomials supported");
}
if (k[0] < k[1] && k[0] < k[2]) {
res[0]=k[0];
if (k[1] < k[2]) {
res[1]=k[1];
res[2]=k[2];
}
else {
res[1]=k[2];
res[2]=k[1];
}
}
else if (k[1] < k[2]) {
res[0]=k[1];
if (k[0] < k[2]) {
res[1]=k[0];
res[2]=k[2];
}
else {
res[1]=k[2];
res[2]=k[0];
}
}
else {
res[0]=k[2];
if (k[0] < k[1]) {
res[1]=k[0];
res[2]=k[1];
}
else {
res[1]=k[1];
res[2]=k[0];
}
}
}
return res;
}
| Returns a sorted array of middle terms of the reduction polynomial. |
public boolean isBufferDirty(){
return true;
}
| Checks whether the image buffer should be repainted. |
public int fetchInteger(int tag) throws BerException {
int result=0;
final int backup=next;
try {
if (fetchTag() != tag) {
throw new BerException();
}
result=fetchIntegerValue();
}
catch ( BerException e) {
next=backup;
throw e;
}
return result;
}
| Fetch an integer with the specified tag. |
protected void drawImage(int x,int y,int w,int h,String image){
Image img=loadImage(image);
if (img != null) {
g.drawImage(img,x,y,w,h,null);
}
}
| Draws an image for the given parameters. |
@UnpreemptibleNoWarn("The caller is prepared to lose control when it allocates a lock") static void growLocks(int id){
int spineId=id >> LOG_LOCK_CHUNK_SIZE;
if (spineId >= LOCK_SPINE_SIZE) {
VM.sysFail("Cannot grow lock array greater than maximum possible index");
}
for (int i=chunksAllocated; i <= spineId; i++) {
if (locks[i] != null) {
continue;
}
Lock[] newChunk=new Lock[LOCK_CHUNK_SIZE];
lockAllocationMutex.lock();
if (locks[i] == null) {
locks[i]=newChunk;
chunksAllocated++;
}
lockAllocationMutex.unlock();
}
}
| Grow the locks table by allocating a new spine chunk. |
public PLCubicPanorama(){
super();
}
| init methods |
public GetResponseMessage(GetResponseMessage other){
if (other.isSetHeader()) {
this.header=new AsyncMessageHeader(other.header);
}
if (other.isSetValues()) {
List<VersionedValue> __this__values=new ArrayList<VersionedValue>();
for ( VersionedValue other_element : other.values) {
__this__values.add(new VersionedValue(other_element));
}
this.values=__this__values;
}
if (other.isSetError()) {
this.error=new SyncError(other.error);
}
}
| Performs a deep copy on <i>other</i>. |
public static String printDateTime(LocalDateTime datetime){
return dfISO8601.print(datetime);
}
| Prints the given datetime as a string. |
@Override public SignatureLibraryRelease parse() throws IOException {
final SignatureLibraryRelease release=new SignatureLibraryRelease(this.getSignatureLibrary(),this.getReleaseVersionNumber());
final Model model1=new Model(SIGNALP_SIGNATURE_NAME1,SIGNALP_SIGNATURE_NAME1,null,null);
final Signature.Builder builder1=new Signature.Builder(SIGNALP_SIGNATURE_NAME1);
final Signature signature1=builder1.name(SIGNALP_SIGNATURE_NAME1).model(model1).signatureLibraryRelease(release).build();
release.addSignature(signature1);
final Model model2=new Model(SIGNALP_SIGNATURE_NAME2,SIGNALP_SIGNATURE_NAME2,null,null);
final Signature.Builder builder2=new Signature.Builder(SIGNALP_SIGNATURE_NAME2);
final Signature signature2=builder2.name(SIGNALP_SIGNATURE_NAME2).model(model2).signatureLibraryRelease(release).build();
release.addSignature(signature2);
return release;
}
| This is rather badly named as there is nothing to parse... <p/> However, the point is that it returns a SignatureLibraryRelease for SignalP, containing two Signature objects called "SignalP-TM" and "SignalP-noTM". |
public Frame(int locals,int stack){
this.locals=new Type[locals];
this.stack=new Type[stack];
}
| Create a new frame with the specified local variable table size, and max stack size |
public void enlarge(double scale){
double latMargin=scale * (lat2 - lat1);
double lngMargin=scale * (lng2 - lng1);
lat1-=latMargin;
lat2+=latMargin;
lng1-=lngMargin;
lng2+=lngMargin;
}
| e.g. scale=0.1 means increase the size by 10% on all sides. |
public void exportCode(JavaClass source,JavaClass target) throws Exception {
ExportAnalyzer analyzer=new ExportAnalyzer(source,target);
CodeEnhancer visitor=new CodeEnhancer(source,this);
visitor.analyze(analyzer,false);
visitor.update();
}
| Exports code. |
protected void drawFollow(Graphics g,Point2D[] pts,boolean reverse){
LinkedList points=new LinkedList();
if (reverse) {
for (int i=pts.length - 1; i >= 0; i--) points.add(pts[i]);
}
else {
for (int i=0; i < pts.length; i++) points.add(pts[i]);
}
LinkedList polysegment=new LinkedList();
int l, x1, y1, x2, y2;
String c;
Point2D p1, p2;
double angle;
for (int i=0; i < text.length(); i++) {
c=text.substring(i,i + 1);
l=metrics.stringWidth(c);
if (points.isEmpty()) break;
LineUtil.retrievePoints(l,points,polysegment);
p1=(Point2D)polysegment.getFirst();
x1=(int)p1.getX();
y1=(int)p1.getY();
p2=(Point2D)polysegment.getLast();
x2=(int)p2.getX();
y2=(int)p2.getY();
angle=Math.atan2(y2 - y1,x2 - x1);
drawAngledString(g,c,x1,y1,angle);
}
}
| Draws the text character per character to follow the polyline |
public TacticalGraphicSymbol(String sidc){
super();
init(sidc);
}
| Constructs a new symbol with no position. |
public static TestDiagnosticLine fromDiagnosticFileLine(String diagnosticLine){
final String trimmedLine=diagnosticLine.trim();
if (trimmedLine.startsWith("#") || trimmedLine.isEmpty()) {
return new TestDiagnosticLine("",-1,diagnosticLine,EMPTY);
}
TestDiagnostic diagnostic=fromDiagnosticFileString(diagnosticLine);
return new TestDiagnosticLine("",diagnostic.getLineNumber(),diagnosticLine,Arrays.asList(diagnostic));
}
| Convert a line in a DiagnosticFile to a TestDiagnosticLine |
public void appendTextString(byte[] textString){
if (null == textString) {
throw new NullPointerException("Text-string is null.");
}
if (null == mData) {
mData=new byte[textString.length];
System.arraycopy(textString,0,mData,0,textString.length);
}
else {
ByteArrayOutputStream newTextString=new ByteArrayOutputStream();
try {
newTextString.write(mData);
newTextString.write(textString);
}
catch ( IOException e) {
e.printStackTrace();
throw new NullPointerException("appendTextString: failed when write a new Text-string");
}
mData=newTextString.toByteArray();
}
}
| Append to Text-string. |
public PoolingByteArrayOutputStream(ByteArrayPool pool){
this(pool,DEFAULT_SIZE);
}
| Constructs a new PoolingByteArrayOutputStream with a default size. If more bytes are written to this instance, the underlying byte array will expand. |
private void updateAlias(JLabel label,Alias alias){
if (alias != null) {
label.setText(alias.getName());
String icon=alias.getIconName();
if (icon != null) {
label.setIcon(mSettingsManager.getImageIcon(icon,SettingsManager.DEFAULT_ICON_SIZE));
}
else {
label.setIcon(null);
}
}
else {
label.setText("");
label.setIcon(null);
}
}
| Updates the alias label with text and icon from the alias. Note: this does not occur on the Swing event thread -- wrap any calls to this method with an event thread call. |
public boolean verifyReader(){
return this.verifyReader;
}
| <p> Returns if the CSVReader will verify the reader before each read. </p> <p> By default the value is true which is the functionality for version 3.0. If set to false the reader is always assumed ready to read - this is the functionality for version 2.4 and before. </p> <p> The reason this method was needed was that certain types of Readers would return false for its ready() method until a read was done (namely readers created using Channels). This caused opencsv not to read from those readers. </p> |
private static void launchDebugger(String dmlScriptStr,String fnameOptConfig,Map<String,String> argVals,boolean parsePyDML) throws ParseException, IOException, DMLRuntimeException, DMLDebuggerException, LanguageException, HopsException, LopsException {
DMLDebuggerProgramInfo dbprog=new DMLDebuggerProgramInfo();
DMLConfig conf=DMLConfig.readConfigurationFile(fnameOptConfig);
ConfigurationManager.setGlobalConfig(conf);
AParserWrapper parser=AParserWrapper.createParser(parsePyDML);
DMLProgram prog=parser.parse(DML_FILE_PATH_ANTLR_PARSER,dmlScriptStr,argVals);
DMLTranslator dmlt=new DMLTranslator(prog);
dmlt.liveVariableAnalysis(prog);
dmlt.validateParseTree(prog);
dmlt.constructHops(prog);
dmlt.rewriteHopsDAG(prog);
dmlt.constructLops(prog);
dbprog.rtprog=prog.getRuntimeProgram(conf);
try {
initHadoopExecution(conf);
DMLDebugger SystemMLdb=new DMLDebugger(dbprog,dmlScriptStr);
SystemMLdb.runSystemMLDebugger();
}
finally {
cleanupHadoopExecution(conf);
}
}
| launchDebugger: Launcher for DML debugger. This method should be called after execution and debug properties have been correctly set, and customized parameters have been put into _argVals |
public static VMRequest highFraction(float frac){
if (VM.HEAP_LAYOUT_64BIT) {
return common64Bit(true);
}
return new VMRequest(REQUEST_FRACTION,Address.zero(),Extent.zero(),frac,true);
}
| A request for a fraction of available memory, optionally requesting the highest available. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.