code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
private static void positionMenu(FinanceService service,Scanner sc) throws IOException, ServiceException {
printPositionMenuHelp();
while (true) {
String requestUrl=baseUrl + PORTFOLIO_FEED_URL_SUFFIX + "/";
switch (processPositionMenuCommand(sc.nextLine().toLowerCase())) {
case QUERY_FEED:
System.out.print("Enter portfolio ID: ");
portfolioIdProperty=sc.nextLine();
requestUrl+=portfolioIdProperty + POSITION_FEED_URL_SUFFIX;
System.out.print("Include returns in query response? (y/n) ");
String includeReturns=sc.nextLine();
if (includeReturns.toLowerCase().equals("y") || includeReturns.toLowerCase().equals("yes")) {
requestUrl+="?returns=true";
}
else if (includeReturns.toLowerCase().equals("n") || includeReturns.toLowerCase().equals("no")) {
requestUrl+="?returns=false";
}
System.out.print("Inline transactions in feed? (y/n) ");
String inlinePositions=sc.nextLine();
if (inlinePositions.toLowerCase().equals("y") || inlinePositions.toLowerCase().equals("yes")) {
requestUrl+="&transactions=true";
}
else if (inlinePositions.toLowerCase().equals("n") || inlinePositions.toLowerCase().equals("no")) {
requestUrl+="&transactions=false";
}
queryPositionFeed(service,requestUrl);
break;
case QUERY_ENTRY:
System.out.println("Enter portfolio ID");
portfolioIdProperty=sc.nextLine();
System.out.println("Enter ticker (<exchange>:<ticker>)");
tickerProperty=sc.nextLine();
requestUrl+=portfolioIdProperty + POSITION_FEED_URL_SUFFIX + "/"+ tickerProperty;
queryPositionEntry(service,requestUrl);
break;
case BACK:
return;
case TRANSACTIONS:
transactionMenu(service,sc);
break;
case QUIT:
System.exit(0);
case HELP:
printPositionMenuHelp();
break;
default :
printPositionMenuHelp();
}
}
}
| Position menu. |
@Override public void write(int b){
}
| Discards the specified byte. |
public DTMConfigurationException(String msg){
super(msg);
}
| Create a new <code>DTMConfigurationException</code> with the <code>String </code> specified as an error message. |
@Override public boolean isActive(){
return amIActive;
}
| Used by the Whitebox GUI to tell if this plugin is still running. |
public b addElement(Element element){
addElementToRegistry(element);
return (this);
}
| Adds an Element to the element. |
public void launchGeneration() throws IOException {
File stringFile=new File(valuesfolder,stringFileName);
stringFileWriter=createIt(stringFile);
stringFileWriter.write(stringfilestart);
stringFileWriter.newLine();
File colorsFile=new File(valuesfolder,colorsFileName);
colorFileWriter=createIt(colorsFile);
colorFileWriter.write(stringfilestart);
colorFileWriter.newLine();
for (int i=0; i < vectors.size(); i++) {
if (i == (vectors.size() - 1)) {
CustomLogger.logError("----------->i == (vectors.size() - 1 is true ");
generateVectorDrawableResult(vectors.get(i),"null",true,i == 0);
}
else {
generateVectorDrawableResult(vectors.get(i),vectors.get(i + 1).getFileName(),false,i == 0);
}
}
generateLevelListVectorDrawable();
generateRoundTripVectorDrawable();
stringFileWriter.write(stringfileend);
stringFileWriter.newLine();
stringFileWriter.flush();
stringFileWriter.close();
colorFileWriter.write(stringfileend);
colorFileWriter.newLine();
colorFileWriter.flush();
colorFileWriter.close();
generateJavaFile();
}
| Launch the files generation |
public void testSpanNearScorerSkipTo1() throws Exception {
SpanNearQuery q=makeQuery();
Weight w=searcher.createNormalizedWeight(q,true);
IndexReaderContext topReaderContext=searcher.getTopReaderContext();
LeafReaderContext leave=topReaderContext.leaves().get(0);
Scorer s=w.scorer(leave);
assertEquals(1,s.iterator().advance(1));
}
| not a direct test of NearSpans, but a demonstration of how/when this causes problems |
@Deprecated public void datasource(String name,String defName,ConsolFun consolFun){
datasource(name,defName,consolFun.getVariable());
}
| Creates a new (static) virtual datasource. The value of the datasource is constant. This value is evaluated by applying the given consolidation function to another virtual datasource. |
private void doDelete(HttpServletRequest request,InstructionalOfferingDetailForm frm) throws Exception {
org.hibernate.Session hibSession=null;
Transaction tx=null;
try {
InstructionalOfferingDAO idao=new InstructionalOfferingDAO();
InstructionalOffering io=idao.get(frm.getInstrOfferingId());
hibSession=idao.getSession();
tx=hibSession.beginTransaction();
io.deleteAllDistributionPreferences(hibSession);
Event.deleteFromEvents(hibSession,io);
Exam.deleteFromExams(hibSession,io);
String className=ApplicationProperty.ExternalActionInstructionalOfferingDelete.value();
if (className != null && className.trim().length() > 0) {
ExternalInstructionalOfferingDeleteAction deleteAction=(ExternalInstructionalOfferingDeleteAction)(Class.forName(className).newInstance());
deleteAction.performExternalInstructionalOfferingDeleteAction(io,hibSession);
}
ChangeLog.addChange(hibSession,sessionContext,io,ChangeLog.Source.OFFERING_DETAIL,ChangeLog.Operation.DELETE,io.getControllingCourseOffering().getSubjectArea(),null);
for ( CourseOffering co : io.getCourseOfferings()) {
co.getSubjectArea().getCourseOfferings().remove(co);
hibSession.delete(co);
}
hibSession.delete(io);
tx.commit();
hibSession.flush();
hibSession.clear();
}
catch ( Exception e) {
if (tx != null) tx.rollback();
Debug.error(e);
throw (e);
}
}
| Delete Instructional Offering |
public static void overScrollBy(final PullToRefreshBase<?> view,final int deltaX,final int scrollX,final int deltaY,final int scrollY,final boolean isTouchEvent){
overScrollBy(view,deltaX,scrollX,deltaY,scrollY,0,isTouchEvent);
}
| Helper method for Overscrolling that encapsulates all of the necessary function. <p/> This should only be used on AdapterView's such as ListView as it just calls through to overScrollBy() with the scrollRange = 0. AdapterView's do not have a scroll range (i.e. getListViewScrollY() doesn't work). |
public boolean hasTrackingScript(){
return hasExtension(GwoTrackingScript.class);
}
| Returns whether it has the script to track this experiment. |
public int copyTo(WritableFontData wfd){
return this.array.copyTo(wfd.boundOffset(0),wfd.array,this.boundOffset(0),this.length());
}
| Copies the FontData to a WritableFontData. |
private double sampleEM(Tree tree,NodeRef node,ColourChangeMatrix mm,MetaPopulation mp,DefaultTreeColouring colouring){
double[] forward;
double[] posterior;
int colour;
DefaultBranchColouring history=null;
double logLikelihood=0.0;
if (tree.isRoot(node)) {
_totalIntegratedRate=0.0;
forward=mm.getEquilibrium();
double[] backward=nodePartials[node.getNumber()];
posterior=new double[colourCount];
double max=-1.0;
double min=1.0;
for (int i=0; i < forward.length; i++) {
posterior[i]=forward[i] * backward[i];
max=Math.max(max,posterior[i]);
min=Math.min(min,posterior[i]);
}
if (debugMessages && min < 0.0) {
System.out.println("Aargh, negative probabilities " + min + " "+ max);
}
if (debugMessages && max < 1.0e-200) {
System.out.println("Hmm, very small numbers indeed " + max);
}
colour=MathUtils.randomChoicePDF(posterior);
logLikelihood+=Math.log(forward[colour]);
}
else {
int nodeNum=node.getNumber();
double[][] backward=nodePartialsEM[nodeNum];
int bottomInterval=node2Interval[nodeNum];
nodeColoursEM[nodeNum]=new int[backward.length];
colour=getColour(tree.getParent(node));
history=new DefaultBranchColouring(colour,colour);
posterior=new double[colourCount];
for (int relinterval=backward.length - 1; relinterval >= 0; relinterval--) {
int interval=relinterval + bottomInterval;
double childHeight=interval2Height[interval];
double uppertime=interval2Height[interval + 1];
double time=uppertime - childHeight;
double[] mxElts=calculateMatrixElts(interval,node,tree,time,avgN0[interval],avgN1[interval],mm);
forward=matrixEvolve(mxElts,colour);
for (int i=0; i < colourCount; i++) {
posterior[i]=forward[i] * backward[relinterval][i];
}
int childColour=MathUtils.randomChoicePDF(posterior);
nodeColoursEM[nodeNum][relinterval]=childColour;
logLikelihood+=sampleConditionalBranchColouringEM(node,colour,childColour,time,childHeight,mxElts,history);
colour=childColour;
}
colouring.setBranchColouring(node,history);
}
setColour(node,colour);
if (!tree.isExternal(node) && useNodeBias) {
double childTime=tree.getNodeHeight(node);
logLikelihood+=Math.log(mm.getEquilibrium(colour) / mp.getDemographic(childTime - tinyTime,colour));
}
for (int i=0; i < tree.getChildCount(node); i++) {
NodeRef child=tree.getChild(node,i);
logLikelihood+=sampleEM(tree,child,mm,mp,colouring);
}
if (debugSampleLikelihoods && tree.isRoot(node)) {
System.out.println("Sampled likelihood " + logLikelihood);
System.out.println("Integrated exit rate " + _totalIntegratedRate);
System.out.println("sampleEMProposal node=" + node.getNumber() + " logL="+ logLikelihood);
}
return logLikelihood;
}
| Samples internal node colours (from root to tips) and events Precondition: parent node has been sampled, descendants have not Requires the results from Felsenstein Backwards pruning, in nodePartials(EM)[] (see pruneEM()) Side effect: updates nodeColours[] |
private static void expandRoot(final EvidenceBuilder fsLog,final int depth){
if (Cfg.DEBUG) {
Check.requires(depth > 0,"wrong recursion depth");
}
saveRootLog(fsLog);
expandPath(fsLog,"/",depth,false);
}
| Expand the root for a maximum depth. 0 means only root, 1 means its sons. |
protected void dispose(IInterval interval){
if (intervals == null) {
return;
}
for (int i=intervals.size() - 1; i >= 0; i--) {
IInterval ival=intervals.get(i);
if ((interval.getLeft() == ival.getLeft()) && (interval.getRight() == ival.getRight())) {
intervals.remove(i);
break;
}
}
}
| Algorithms over SegmentTrees often store additional information with each node, and may wish to clear information and/or perform computations when a segment is deleted. This method is overridden by subclasses as required. For dynamic reasons, search from end to front. |
public IntConstant(int value){
this.value=value;
}
| Creates an initialized constant. |
protected Anonymous_genExpr_1_Impl(){
super();
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public boolean isUseAnisotropicTextureFilter(){
return this.isAnisotropicTextureFilterAvailable && this.isAnisotropicTextureFilterEnabled;
}
| Returns true if anisotropic texture filtering is available in the current GL runtime, and is enabled. Otherwise this returns false. For details on GL anisotropic texture filtering, see <a href="http://www.opengl.org/registry/specs/EXT/texture_filter_anisotropic.txt">http://www.opengl.org/registry/specs/EXT/texture_filter_anisotropic.txt</a>. |
public static TermQueryBuilder termQuery(String name,String value){
return new TermQueryBuilder(name,value);
}
| A Query that matches documents containing a term. |
public void removeListener(final IFilterDialogListener listener){
m_listeners.removeListener(listener);
}
| Removes a previously added listener object. |
private void returnData(Object ret){
if (myHost != null) {
myHost.returnData(ret);
}
}
| Used to communicate a return object from a plugin tool to the main Whitebox user-interface. |
public static void traceThrowable(Throwable e){
PrintWriter writer=DriverManager.getLogWriter();
if (writer != null) {
e.printStackTrace(writer);
}
}
| Write the exception to the driver manager log writer if configured. |
public ClientMessage sendMessage(SimpleString targetAddress,Map<String,Object> properties){
ClientMessage message=createMessage(properties);
sendMessage(targetAddress,message);
return message;
}
| Create a new ClientMessage with the specified properties and send to the server |
public static double P_TruePositives(int y[],int ypred[]){
int s=0;
for (int j=0; j < y.length; j++) {
if (ypred[j] == 1 && y[j] == 1) s++;
}
return s;
}
| P_TruePositives - 1 and supposed to be 1 (the intersection, i.e., logical AND). |
public static String dumpsMap(Map<?,?> map){
StringBuilder builder=new StringBuilder();
if (map == null) {
builder.append("null");
return builder.toString();
}
boolean first=true;
Iterator<?> iter=map.entrySet().iterator();
builder.append('{');
while (iter.hasNext()) {
if (first) first=false;
else builder.append(',');
Map.Entry<?,?> entry=(Map.Entry<?,?>)iter.next();
builder.append('\"');
builder.append(escape(String.valueOf(entry.getKey())));
builder.append('\"');
builder.append(':');
builder.append(dumps(entry.getValue()));
}
builder.append('}');
return builder.toString();
}
| Encode a map into JSON text |
@Interruptible public static int pickAllocator(RVMType type){
return pickAllocator(type,null);
}
| Returns the appropriate allocation scheme/area for the given type. This form is deprecated. Without the RVMMethod argument, it is possible that the wrong allocator is chosen which may affect correctness. The prototypical example is that JMTk meta-data must generally be in immortal or at least non-moving space. |
public static void main(final String[] args){
DOMTestCase.doMain(getAttributeNS04.class,args);
}
| Runs this test from the command line. |
private String createString(String f){
return "srcXInBytes=" + srcXInBytes + f+ "srcY="+ srcY+ f+ "srcZ="+ srcZ+ f+ "srcLOD="+ srcLOD+ f+ "srcMemoryType="+ CUmemorytype.stringFor(srcMemoryType)+ f+ "srcHost="+ srcHost+ f+ "srcDevice="+ srcDevice+ f+ "srcArray="+ srcArray+ f+ "srcContext="+ srcContext+ f+ "srcPitch="+ srcPitch+ f+ "srcHeight="+ srcHeight+ f+ "dstXInBytes="+ dstXInBytes+ f+ "dstY="+ dstY+ f+ "dstZ="+ dstZ+ f+ "dstLOD="+ dstLOD+ f+ "dstMemoryType="+ CUmemorytype.stringFor(dstMemoryType)+ f+ "dstHost="+ dstHost+ f+ "dstDevice="+ dstDevice+ f+ "dstArray="+ dstArray+ f+ "dstContext="+ dstContext+ f+ "dstPitch="+ dstPitch+ f+ "dstHeight="+ dstHeight+ f+ "WidthInBytes="+ WidthInBytes+ f+ "Height="+ Height+ f+ "Depth="+ Depth;
}
| Creates and returns a string representation of this object, using the given separator for the fields |
public boolean verify(PublicKey verificationKey,Signature verificationEngine) throws InvalidKeyException, SignatureException {
verificationEngine.initVerify(verificationKey);
verificationEngine.update(this.content.clone());
return verificationEngine.verify(this.signature.clone());
}
| Verifies that the signature in this SignedObject is the valid signature for the object stored inside, with the given verification key, using the designated verification engine. |
public SparseArray(){
this(10);
}
| Creates a new SparseArray containing no mappings. |
protected EnumImpl(){
super();
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
public <T extends Number>double[] next(Collection<T> values,int numForecasts){
if (values.size() == 0) {
return emptyPredictions(numForecasts);
}
double s=0;
double last_s=0;
double b=0;
double last_b=0;
int counter=0;
T last;
for ( T v : values) {
last=v;
if (counter == 1) {
s=v.doubleValue();
b=v.doubleValue() - last.doubleValue();
}
else {
s=alpha * v.doubleValue() + (1.0d - alpha) * (last_s + last_b);
b=beta * (s - last_s) + (1 - beta) * last_b;
}
counter+=1;
last_s=s;
last_b=b;
}
double[] forecastValues=new double[numForecasts];
for (int i=0; i < numForecasts; i++) {
forecastValues[i]=s + (i * b);
}
return forecastValues;
}
| Calculate a Holt-Linear (doubly exponential weighted) moving average |
public static float abs(float a){
return 0.0f;
}
| Returns the absolute value of a float value. If the argument is not negative, the argument is returned. If the argument is negative, the negation of the argument is returned. Special cases: If the argument is positive zero or negative zero, the result is positive zero. If the argument is infinite, the result is positive infinity. If the argument is NaN, the result is NaN. In other words, the result is equal to the value of the expression: Float.intBitsToFloat(0x7fffffff & Float.floatToIntBits(a)) |
@Override public boolean eIsSet(int featureID){
switch (featureID) {
case UmplePackage.ANONYMOUS_NUM_EXPR_4__INDEX_1:
return INDEX_1_EDEFAULT == null ? index_1 != null : !INDEX_1_EDEFAULT.equals(index_1);
}
return super.eIsSet(featureID);
}
| <!-- begin-user-doc --> <!-- end-user-doc --> |
@Override public int hashCode(){
return 31 * query.hashCode() + occur.hashCode();
}
| Returns a hash code value for this object. |
public void blockUser(InstagramAPIResponseCallback<IGRelationship> callback,String userId){
updateRelationShip(callback,InstagramKitConstants.kRelationshipActionBlock,userId);
}
| Modify the relationship between the current user and the target user. Block a user. <p/> REQUIREMENTS : InstagramKitLoginScopeRelationships during authentication. <p/> To request access to this endpoint, please complete this form - https://help.instagram.com/contact/185819881608116 |
public synchronized boolean onDeltaReceived(UUID nodeId,long timeDelta){
DeltaAverage avg=pendingDeltas.get(nodeId);
if (avg != null) {
avg.onValue(timeDelta);
if (avg.ready()) {
pendingDeltas.remove(nodeId);
deltas.put(nodeId,avg.average());
if (ready()) notifyAll();
return false;
}
return true;
}
return false;
}
| Callback invoked when time delta is received from remote node. |
public boolean fromXml(Element behavior) throws PrincessException {
NodeList children=behavior.getChildNodes();
for (int i=0; i < children.getLength(); i++) {
Node child=children.item(i);
if ("name".equalsIgnoreCase(child.getNodeName())) {
setDescription(child.getTextContent());
}
else if ("forcedWithdrawal".equalsIgnoreCase(child.getNodeName())) {
setForcedWithdrawal(child.getTextContent());
}
else if ("goHome".equalsIgnoreCase(child.getNodeName())) {
setGoHome("true".equalsIgnoreCase(child.getTextContent()));
}
else if ("autoFlee".equalsIgnoreCase(child.getNodeName())) {
setAutoFlee("true".equalsIgnoreCase(child.getTextContent()));
}
else if ("fallShameIndex".equalsIgnoreCase(child.getNodeName())) {
setFallShameIndex(child.getTextContent());
}
else if ("hyperAggressionIndex".equalsIgnoreCase(child.getNodeName())) {
setHyperAggressionIndex(child.getTextContent());
}
else if ("selfPreservationIndex".equalsIgnoreCase(child.getNodeName())) {
setSelfPreservationIndex(child.getTextContent());
}
else if ("homeEdge".equalsIgnoreCase(child.getNodeName())) {
setHomeEdge(child.getTextContent());
}
else if ("herdMentalityIndex".equalsIgnoreCase(child.getNodeName())) {
setHerdMentalityIndex(child.getTextContent());
}
else if ("braveryIndex".equalsIgnoreCase(child.getNodeName())) {
setBraveryIndex(child.getTextContent());
}
else if ("strategicTargets".equalsIgnoreCase(child.getNodeName())) {
NodeList targets=child.getChildNodes();
for (int j=0; j < targets.getLength(); j++) {
Node t=targets.item(j);
if ("target".equalsIgnoreCase(t.getNodeName())) {
addStrategicTarget(t.getTextContent());
}
if ("unit".equalsIgnoreCase(t.getNodeName())) {
addPriorityUnit(t.getTextContent());
}
}
}
}
return true;
}
| Sets up the behavior parameters based on the passed in XML. |
public String toString(){
return "[StaticCodeTemplate: id=" + getID() + ", text="+ getBeforeCaretText()+ "|"+ getAfterCaretText()+ "]";
}
| Returns a string representation of this template for debugging purposes. |
private int handleC(String value,DoubleMetaphoneResult result,int index){
if (conditionC0(value,index)) {
result.append('K');
index+=2;
}
else if (index == 0 && contains(value,index,6,"CAESAR")) {
result.append('S');
index+=2;
}
else if (contains(value,index,2,"CH")) {
index=handleCH(value,result,index);
}
else if (contains(value,index,2,"CZ") && !contains(value,index - 2,4,"WICZ")) {
result.append('S','X');
index+=2;
}
else if (contains(value,index + 1,3,"CIA")) {
result.append('X');
index+=3;
}
else if (contains(value,index,2,"CC") && !(index == 1 && charAt(value,0) == 'M')) {
return handleCC(value,result,index);
}
else if (contains(value,index,2,"CK","CG","CQ")) {
result.append('K');
index+=2;
}
else if (contains(value,index,2,"CI","CE","CY")) {
if (contains(value,index,3,"CIO","CIE","CIA")) {
result.append('S','X');
}
else {
result.append('S');
}
index+=2;
}
else {
result.append('K');
if (contains(value,index + 1,2," C"," Q"," G")) {
index+=3;
}
else if (contains(value,index + 1,1,"C","K","Q") && !contains(value,index + 1,2,"CE","CI")) {
index+=2;
}
else {
index++;
}
}
return index;
}
| Handles 'C' cases |
private static char[] zzUnpackCMap(final String packed){
final char[] map=new char[0x10000];
int i=0;
int j=0;
while (i < 160) {
int count=packed.charAt(i++);
final char value=packed.charAt(i++);
do {
map[j++]=value;
}
while (--count > 0);
}
return map;
}
| Unpacks the compressed character translation table. |
public void remove(MessageListener listener){
m_notifier.remove(listener);
}
| Method remove. |
public void addErrorListener(ActionListener<NetworkEvent> e){
if (errorListeners == null) {
errorListeners=new EventDispatcher();
errorListeners.setBlocking(true);
}
errorListeners.addListener(e);
}
| Adds a generic listener to a network error that is invoked before the exception is propagated. Notice that this doesn't apply to server error codes! Consume the event in order to prevent it from propagating further. |
public double[] row(){
double scale=scale();
double[] x=lp.primal();
for (int j=0; j < n; j++) x[j]/=scale;
return x;
}
| Returns the optimal row strategy of this two-person zero-sum game. |
public static int secondaryHash(Object key){
return secondaryHash(key.hashCode());
}
| Computes a hash code and applies a supplemental hash function to defend against poor quality hash functions. This is critical because HashMap uses power-of-two length hash tables, that otherwise encounter collisions for hash codes that do not differ in lower or upper bits. Routine taken from java.util.concurrent.ConcurrentHashMap.hash(int). |
private static int compUnsigned(int x,int y){
int sign_x=x & Integer.MIN_VALUE;
int sign_y=y & Integer.MIN_VALUE;
int mant_x=x & (~Integer.MIN_VALUE);
int mant_y=y & (~Integer.MIN_VALUE);
if (sign_x == sign_y) return Integer.compare(mant_x,mant_y);
else {
if (sign_x == 0) return -1;
else return 1;
}
}
| Straightforward compare unsigned algorithm. |
public static String shortenURLString(final String url,final int len){
if (url == null) {
return null;
}
int urlLen=url.length();
if (urlLen > len) {
int cpos;
cpos=url.indexOf("://",0);
if (cpos >= 0) {
cpos=url.indexOf("/",cpos + 3);
if (cpos < 0) {
return url.substring(0,len - 2).concat("..");
}
if (cpos >= len - (len / 3)) {
return url.substring(0,len - 2).concat("..");
}
final int lb=((len - cpos) / 2) - 1;
if (lb * 2 + 2 + cpos < len) {
urlLen--;
}
return url.substring(0,cpos + lb).concat("..").concat(url.substring(urlLen - lb));
}
}
return url;
}
| This function shorten URL Strings<br> Example returns:<br> <dl><dt>normal domain:</dt><dd>http://domain.net/leftpath..rightpath</dd> <dt>long domain:</dt><dd>http://very_very_long_domain.net/le..</dd></dl> |
public void removeListener(final PropertyChangeListener listener){
pcs.removePropertyChangeListener(listener);
}
| Removes a change listener. |
protected final long todaysSerialNumber(){
final java.util.Calendar cal=java.util.Calendar.getInstance();
final int d=cal.get(java.util.Calendar.DAY_OF_MONTH);
final int m=cal.get(java.util.Calendar.MONTH);
final int y=cal.get(java.util.Calendar.YEAR);
return fromDMY(d,m + 1,y);
}
| Assigns the today's date to <code>this</code> instance |
public ReadStreamOld(){
}
| Creates an uninitialized stream. Use <code>init</code> to initialize. |
@DSComment("From safe class list") @DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:57:43.418 -0500",hash_original_method="CBAC64602FF2D7F893923E0ABA8C507E",hash_generated_method="248FDBA375E3BBC8FDC6E6B6D66C9BAE") public void addFirst(E e){
if (e == null) throw new NullPointerException();
elements[head=(head - 1) & (elements.length - 1)]=e;
if (head == tail) doubleCapacity();
}
| Inserts the specified element at the front of this deque. |
public static long copyLarge(InputStream input,OutputStream output,byte[] buffer) throws IOException {
long count=0;
int n=0;
while (EOF != (n=input.read(buffer))) {
output.write(buffer,0,n);
count+=n;
}
return count;
}
| Copy bytes from a large (over 2GB) <code>InputStream</code> to an <code>OutputStream</code>. <p> This method uses the provided buffer, so there is no need to use a <code>BufferedInputStream</code>. <p> |
public static void main(String[] args) throws IOException {
DialogueSystem system=new DialogueSystem();
String domainFile=System.getProperty("domain");
String dialogueFile=System.getProperty("dialogue");
String simulatorFile=System.getProperty("simulator");
system.getSettings().fillSettings(System.getProperties());
if (domainFile != null) {
Domain domain;
try {
domain=XMLDomainReader.extractDomain(domainFile);
log.info("Domain from " + domainFile + " successfully extracted");
}
catch ( RuntimeException e) {
system.displayComment("Cannot load domain: " + e);
e.printStackTrace();
domain=XMLDomainReader.extractEmptyDomain(domainFile);
}
system.changeDomain(domain);
}
if (dialogueFile != null) {
system.importDialogue(dialogueFile);
}
if (simulatorFile != null) {
Simulator simulator=new Simulator(system,XMLDomainReader.extractDomain(simulatorFile));
log.info("Simulator with domain " + simulatorFile + " successfully extracted");
system.attachModule(simulator);
}
Settings settings=system.getSettings();
system.changeSettings(settings);
if (!settings.showGUI) {
system.attachModule(new TextOnlyInterface(system));
}
system.startSystem();
log.info("Dialogue system started!");
}
| Starts the dialogue system. The content of the args array is ignored. Command-line parameters can however be specified through system properties via the -D flag. All parameters are optional. <p> Some of the possible properties are: <ul> <li>-Ddomain=path/to/domain/file: dialogue domain file <li>-Ddialogue=path/to/recorded/dialogue: dialogue file to import <li>-Dsimulator=path/to/simulator/file: domain file for the simulator <li>--Dgui=true or false: activates or deactives the GUI </ul> |
private void adjustDayOfMonth(Calendar startTime,int month){
applyLastDayOfMonth(startTime,month);
if (!this.lastDayOfMonth) {
int lastDayOfMonth=startTime.get(Calendar.DAY_OF_MONTH);
if (lastDayOfMonth > getDayOfMonth()) {
startTime.set(Calendar.DAY_OF_MONTH,getDayOfMonth());
}
}
}
| Adjust the day of the month for the given month for a monthly window. If the day of the month is after the last day of the month, it is set to the last day of the month. |
private boolean isAccelerating(SensorEvent event){
float ax=event.values[0];
float ay=event.values[1];
float az=event.values[2];
final double magnitude=Math.sqrt(ax * ax + ay * ay + az * az);
return magnitude > ACCELERATION_THRESHOLD;
}
| Returns true if the device is currently accelerating. |
private ApiInfo apiInfo(){
return new ApiInfoBuilder().title(LocalizedStrings.SwaggerConfig_VENDOR_PRODUCT_LINE.toLocalizedString()).description(LocalizedStrings.SwaggerConfig_DESCRIPTOR.toLocalizedString()).version("1.0").termsOfServiceUrl(LocalizedStrings.SwaggerConfig_EULA_LINK.toLocalizedString()).license("Apache License, version 2.0").licenseUrl(LocalizedStrings.SwaggerConfig_EULA_LINK.toLocalizedString()).contact(new Contact("the Apache Geode Community",LocalizedStrings.SwaggerConfig_PRODUCT_LINK.toLocalizedString(),LocalizedStrings.SwaggerConfig_DEVELOPER_EMAIL.toLocalizedString())).build();
}
| API Info as it appears on the Swagger-UI page |
private void next(){
try (RandomAccessFile inout=new RandomAccessFile("AddressBook.dat","rw")){
if (count * 91 < inout.length()) {
inout.seek(count * 91);
read(inout);
count++;
System.out.println("Reading address #" + count);
}
else {
System.out.println("End of file!");
}
}
catch ( IOException ex) {
}
}
| Read the next Address from the file |
public void testExceptionWithSimpleMapper() throws Exception {
ObjectMapper mapper=new ObjectMapper();
try {
BrokenStringWriter sw=new BrokenStringWriter("TEST");
mapper.writeValue(sw,createLongObject());
fail("Should have gotten an exception");
}
catch ( IOException e) {
verifyException(e,IOException.class,"TEST");
}
}
| Unit test for verifying that regular IOExceptions are not wrapped but are passed through as is. |
public JSONObject optJSONObject(int index){
Object o=this.opt(index);
return o instanceof JSONObject ? (JSONObject)o : null;
}
| Get the optional JSONObject associated with an index. Null is returned if the key is not found, or null if the index has no value, or if the value is not a JSONObject. |
protected boolean canSelect(KMLAbstractFeature feature){
return this.canMoveTo(feature) || this.canShowBalloon(feature);
}
| Determines if there is a some action (fly to and/or open description balloon) to take when the user selects a KML feature in the tree. The controller displays a hand cursor when the mouse is over a feature if the feature can be flown to, or if the has a balloon that can be opened. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:58:14.912 -0500",hash_original_method="E927F529D329E66C9C89B04CCA4C92BD",hash_generated_method="2DB9AC0A20EA2F1287878FFD89410111") public boolean isOpaque(){
return opaque;
}
| Returns true if this URI is opaque. Opaque URIs are absolute and have a scheme-specific part that does not start with a slash character. All parts except scheme, scheme-specific and fragment are undefined. |
private Sandbox(){
}
| end of shitty part |
public void processKeyEvent(Component focusedComponent,KeyEvent e){
if (consumeProcessedKeyEvent(e)) {
return;
}
if (e.getID() == KeyEvent.KEY_TYPED) {
return;
}
if (focusedComponent.getFocusTraversalKeysEnabled() && !e.isConsumed()) {
AWTKeyStroke stroke=AWTKeyStroke.getAWTKeyStrokeForEvent(e), oppStroke=AWTKeyStroke.getAWTKeyStroke(stroke.getKeyCode(),stroke.getModifiers(),!stroke.isOnKeyRelease());
Set<AWTKeyStroke> toTest;
boolean contains, containsOpp;
toTest=focusedComponent.getFocusTraversalKeys(KeyboardFocusManager.FORWARD_TRAVERSAL_KEYS);
contains=toTest.contains(stroke);
containsOpp=toTest.contains(oppStroke);
if (contains || containsOpp) {
consumeTraversalKey(e);
if (contains) {
focusNextComponent(focusedComponent);
}
return;
}
else if (e.getID() == KeyEvent.KEY_PRESSED) {
consumeNextKeyTyped=false;
}
toTest=focusedComponent.getFocusTraversalKeys(KeyboardFocusManager.BACKWARD_TRAVERSAL_KEYS);
contains=toTest.contains(stroke);
containsOpp=toTest.contains(oppStroke);
if (contains || containsOpp) {
consumeTraversalKey(e);
if (contains) {
focusPreviousComponent(focusedComponent);
}
return;
}
toTest=focusedComponent.getFocusTraversalKeys(KeyboardFocusManager.UP_CYCLE_TRAVERSAL_KEYS);
contains=toTest.contains(stroke);
containsOpp=toTest.contains(oppStroke);
if (contains || containsOpp) {
consumeTraversalKey(e);
if (contains) {
upFocusCycle(focusedComponent);
}
return;
}
if (!((focusedComponent instanceof Container) && ((Container)focusedComponent).isFocusCycleRoot())) {
return;
}
toTest=focusedComponent.getFocusTraversalKeys(KeyboardFocusManager.DOWN_CYCLE_TRAVERSAL_KEYS);
contains=toTest.contains(stroke);
containsOpp=toTest.contains(oppStroke);
if (contains || containsOpp) {
consumeTraversalKey(e);
if (contains) {
downFocusCycle((Container)focusedComponent);
}
}
}
}
| This method initiates a focus traversal operation if and only if the KeyEvent represents a focus traversal key for the specified focusedComponent. It is expected that focusedComponent is the current focus owner, although this need not be the case. If it is not, focus traversal will nevertheless proceed as if focusedComponent were the focus owner. |
public void runTest() throws Throwable {
Document doc;
Node newNode;
String newValue;
doc=(Document)load("hc_staff",true);
newNode=doc.createDocumentFragment();
newValue=newNode.getNodeValue();
assertNull("initiallyNull",newValue);
newNode.setNodeValue("This should have no effect");
newValue=newNode.getNodeValue();
assertNull("nullAfterAttemptedChange",newValue);
}
| Runs the test case. |
public void testPolygonNotClosed(){
IllegalArgumentException expected=expectThrows(IllegalArgumentException.class,null);
assertTrue(expected.getMessage(),expected.getMessage().contains("it must close itself"));
}
| polygon must be closed |
@SuppressWarnings("raw") public static String toURI(final Class clazz) throws NullPointerException {
return toURI(clazz.getName());
}
| Get URI for a class. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:29:10.981 -0500",hash_original_method="C00E6E79D43678980DA0F4144A65F6A2",hash_generated_method="9E85982622E02ECD889AA29EF2CC0457") public final MotionEvent clampNoHistory(float left,float top,float right,float bottom){
MotionEvent ev=obtain();
synchronized (gSharedTempLock) {
final int pointerCount=nativeGetPointerCount(mNativePtr);
ensureSharedTempPointerCapacity(pointerCount);
final PointerProperties[] pp=gSharedTempPointerProperties;
final PointerCoords[] pc=gSharedTempPointerCoords;
for (int i=0; i < pointerCount; i++) {
nativeGetPointerProperties(mNativePtr,i,pp[i]);
nativeGetPointerCoords(mNativePtr,i,HISTORY_CURRENT,pc[i]);
pc[i].x=clamp(pc[i].x,left,right);
pc[i].y=clamp(pc[i].y,top,bottom);
}
ev.mNativePtr=nativeInitialize(ev.mNativePtr,nativeGetDeviceId(mNativePtr),nativeGetSource(mNativePtr),nativeGetAction(mNativePtr),nativeGetFlags(mNativePtr),nativeGetEdgeFlags(mNativePtr),nativeGetMetaState(mNativePtr),nativeGetButtonState(mNativePtr),nativeGetXOffset(mNativePtr),nativeGetYOffset(mNativePtr),nativeGetXPrecision(mNativePtr),nativeGetYPrecision(mNativePtr),nativeGetDownTimeNanos(mNativePtr),nativeGetEventTimeNanos(mNativePtr,HISTORY_CURRENT),pointerCount,pp,pc);
return ev;
}
}
| Returns a new motion events whose points have been clamped to the specified bounds. |
private String calculateSongDuration(int seconds){
return new StringBuilder(String.valueOf(seconds / 60)).append(":").append(String.valueOf(seconds % 60)).toString();
}
| Calculate in string (hh:mm) |
public long nextActionMillis(long now,long nextRetryTimeMillis){
for ( FileDownloadInfo info : downloads) {
long individualRetryTimeMillis=getNextActionMillisFor(now,info);
nextRetryTimeMillis=Math.min(individualRetryTimeMillis,nextRetryTimeMillis);
}
return nextRetryTimeMillis;
}
| Return time when this download will be ready for its next action, in milliseconds after given time. |
public static int size(){
return _size;
}
| Number of columns (terminals) in every row. |
protected SVGOMFEDiffuseLightingElement(){
}
| Creates a new SVGOMFEDiffuseLightingElement object. |
public void put(String oldname,String newname){
if (oldname == newname) return;
String oldname2=toJvmName(oldname);
String s=(String)get(oldname2);
if (s == null || !s.equals(oldname2)) super.put(oldname2,toJvmName(newname));
}
| Maps a class name to another name in this hashtable. If the hashtable contains another mapping from the same class name, the old mapping is replaced. This method translates the given class names into the internal form used in the JVM before putting it in the hashtable. <p>If <code>oldname</code> is identical to <code>newname</code>, then this method does not perform anything; it does not record the mapping from <code>oldname</code> to <code>newname</code>. See <code>fix</code> method. |
public SparseMatrix(SparseVector[] rows){
this.rows=rows;
for (int i=0; i < rows.length; i++) if (rows[i].length() != rows[0].length()) throw new IllegalArgumentException("Row " + i + " has "+ rows[i].length()+ " columns instead of "+ rows[0].length());
}
| Creates a new Sparse Matrix backed by the given array of SpareVectors. Altering the array of any object in it will also alter the this matrix. |
protected void updateNodeAndChildren(NodeRef node){
int nodeNum=node.getNumber();
if (!updateNode[nodeNum]) {
updateNode[nodeNum]=true;
updatedNodeList.add(nodeNum);
}
for (int i=0; i < treeModel.getChildCount(node); i++) {
int childNodeNum=(treeModel.getChild(node,i)).getNumber();
if (!updateNode[childNodeNum]) {
updateNode[childNodeNum]=true;
updatedNodeList.add(childNodeNum);
}
}
likelihoodKnown=false;
}
| Nodes are added to upadteNodeList if it is to be updated. |
public CViewsToTagHandler(final JFrame parent){
super(CViewTransferable.VIEW_FLAVOR);
Preconditions.checkNotNull(parent,"IE01936: Parent argument can not be null");
m_parent=parent;
}
| Creates a new handler object. |
public boolean removeTuple(Tuple t){
Table table=t.getTable();
if (m_sets.contains(table)) {
return table.removeTuple(t);
}
else {
return false;
}
}
| Removes the tuple from its source set if that source set is contained within this composite. |
public boolean isUserDefined(){
String cm=getCostingMethod();
return cm != null && cm.equals(COSTINGMETHOD_UserDefined);
}
| Is User Costing Method |
private ExpressionStatement createExpressionStatement(final MethodInvocation invocation){
Assert.isNotNull(invocation);
return invocation.getAST().newExpressionStatement(invocation);
}
| Creates a new expression statement for the method invocation. |
@Override public void onEndPage(final PdfWriter writer,final Document document){
final int pageN=writer.getPageNumber();
final String text=pageN + " / ";
final float len=bf.getWidthPoint(text,8);
cb.beginText();
cb.setFontAndSize(bf,8);
final float width=document.getPageSize().getWidth();
cb.setTextMatrix(width / 2,30);
cb.showText(text);
cb.endText();
cb.addTemplate(template,width / 2 + len,30);
}
| we override the onEndPage method. |
public static CipherTextIvMac encrypt(String plaintext,SecretKeys secretKeys) throws UnsupportedEncodingException, GeneralSecurityException {
return encrypt(plaintext,secretKeys,"UTF-8");
}
| Generates a random IV and encrypts this plain text with the given key. Then attaches a hashed MAC, which is contained in the CipherTextIvMac class. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:36:00.787 -0500",hash_original_method="00F8174F9E89D0C972FA6D3F19742382",hash_generated_method="D90463461B2A94FF94D13FDF69BB80C9") public int describeContents(){
return 0;
}
| Implement the Parcelable interface |
@Override public void execute(){
entity.onTalk(event.get("text"));
}
| executes the event |
public boolean start(boolean right){
if (active) {
return false;
}
else {
active=true;
this.right=right;
return true;
}
}
| Start tracking a drag operation if possible. |
public static Test suite(){
return (new TestSuite(ValueChangeListenerCalledITCase.class));
}
| Return the tests included in this test suite. |
public void visitMethodInsn(int opcode,String owner,String name,String desc,boolean itf){
if (api < Opcodes.ASM5) {
if (itf != (opcode == Opcodes.INVOKEINTERFACE)) {
throw new IllegalArgumentException("INVOKESPECIAL/STATIC on interfaces require ASM 5");
}
visitMethodInsn(opcode,owner,name,desc);
return;
}
if (mv != null) {
mv.visitMethodInsn(opcode,owner,name,desc,itf);
}
}
| Visits a method instruction. A method instruction is an instruction that invokes a method. |
public static void shortToast(Context context,int res){
if (context != null) {
Toast.makeText(context,res,Toast.LENGTH_SHORT).show();
}
else {
Log.e(TAG,"Cannot show toast for text ID " + res + " as context is null");
}
}
| Shows a short Toast style message |
public void testReaderNonBlocking() throws IOException {
Pipe.SourceChannel sourceChannel=createNonBlockingChannel("abc".getBytes("UTF-8"));
try {
Channels.newReader(sourceChannel,"UTF-8").read();
fail();
}
catch ( IllegalBlockingModeException expected) {
}
}
| This fails on the RI which violates its own promise to throw when read in non-blocking mode. |
final boolean casCellsBusy(){
return UNSAFE.compareAndSwapInt(this,CELLSBUSY,0,1);
}
| CASes the cellsBusy field from 0 to 1 to acquire lock. |
private boolean updateLangProb(double[] prob,String word,double alpha){
if (word == null || !wordLangProbMap.containsKey(word)) return false;
double[] langProbMap=wordLangProbMap.get(word);
if (verbose) System.out.println(word + "(" + unicodeEncode(word)+ "):"+ wordProbToString(langProbMap));
double weight=alpha / BASE_FREQ;
for (int i=0; i < prob.length; ++i) {
prob[i]*=weight + langProbMap[i];
}
return true;
}
| update language probabilities with N-gram string(N=1,2,3) |
@Override public void updateReceiptDetails(final Set<BillReceiptInfo> billReceipts){
LOGGER.debug("updateReceiptDetails : Updating Receipt Details Started, billReceipts : " + billReceipts);
final Boolean status=false;
if (billReceipts != null) super.updateReceiptDetails(billReceipts);
LOGGER.debug("updateReceiptDetails : Updating Receipt Details Finished, status : " + status);
}
| This method is invoked from Collections end when an event related to receipt in bill generation occurs. |
@Override protected void onProgressChanged(long currentTime,long duration){
mControlBar.setMax((int)duration);
mControlBar.setProgress((int)currentTime);
mControlBar.setSecondaryProgress(0);
mControlBar.setSecondaryProgress(getStreamerProgress());
if (getCurrentTime() >= 0) mCurrentTimeTextView.setText(StringUtils.millisToString(currentTime));
if (getDuration() >= 0) lengthTime.setText(StringUtils.millisToString(duration));
}
| Updates the overlay when the media playback progress has changed |
public static boolean isMissingValue(double val){
return Double.isNaN(val);
}
| Tests if the given value codes "missing". |
private void printWorkspace(final Workspace w){
Check.notNull(w,"w");
final TextOutputTable table=new TextOutputTable(getDisplay().getWidth());
table.setHeadingsVisible(false);
table.setColumns(new Column[]{new Column("",Sizing.TIGHT),new Column("",Sizing.EXPAND)});
table.addRow(new String[]{Messages.getString("CommandWorkFold.Workspace"),w.getName()});
table.addRow(new String[]{Messages.getString("CommandWorkFold.Collection"),w.getServerName()});
BasicPrinter.printSeparator(getDisplay(),'=');
table.print(getDisplay().getPrintStream());
final WorkingFolder[] workingFolders=w.getFolders();
if (workingFolders != null) {
for (int i=0; i < workingFolders.length; i++) {
final WorkingFolder wf=workingFolders[i];
Check.notNull(wf,"wf");
if (wf.getType() == WorkingFolderType.CLOAK) {
getDisplay().printLine(" (" + Messages.getString("CommandWorkFold.WorkingFolderTypeCloakedLiteral") + ") "+ wf.getDisplayServerItem());
}
else {
getDisplay().printLine(" " + wf.getDisplayServerItem() + ": "+ wf.getLocalItem());
}
}
getDisplay().printLine("");
}
}
| Prints information for a single workspace. |
public boolean isIndexed(){
Object oo=get_Value(COLUMNNAME_IsIndexed);
if (oo != null) {
if (oo instanceof Boolean) return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
| Get Indexed. |
@Override public Object clone() throws CloneNotSupportedException {
return super.clone();
}
| Returns a clone of the entity. |
public String[] split(String expr,int max){
return Pattern.compile(expr).split(this,max);
}
| Splits this String using the supplied regular expression expr. max controls the number of times that the pattern is applied to the string. |
public void testDivideRoundHalfDownNeg2(){
String a="-37361671119238118911893939591735";
int aScale=10;
String b="74723342238476237823787879183470";
int bScale=15;
String c="0E+5";
int resScale=-5;
BigDecimal aNumber=new BigDecimal(new BigInteger(a),aScale);
BigDecimal bNumber=new BigDecimal(new BigInteger(b),bScale);
BigDecimal result=aNumber.divide(bNumber,resScale,BigDecimal.ROUND_HALF_DOWN);
assertEquals("incorrect value",c,result.toString());
assertEquals("incorrect scale",resScale,result.scale());
}
| Divide: rounding mode is ROUND_HALF_UP, result is negative; equidistant |
public void clear(){
clear(DEFAULT_CAPACITY);
}
| Flushes the internal state of the list, resetting the capacity to the default. |
public boolean springBack(int startX,int startY,int minX,int maxX,int minY,int maxY){
mMode=FLING_MODE;
final boolean spingbackX=mScrollerX.springback(startX,minX,maxX);
final boolean spingbackY=mScrollerY.springback(startY,minY,maxY);
return spingbackX || spingbackY;
}
| Call this when you want to 'spring back' into a valid coordinate range. |
public void intersectPermittedSubtree(GeneralSubtree[] permitted){
Map subtreesMap=new HashMap();
for (int i=0; i != permitted.length; i++) {
GeneralSubtree subtree=permitted[i];
Integer tagNo=Integers.valueOf(subtree.getBase().getTagNo());
if (subtreesMap.get(tagNo) == null) {
subtreesMap.put(tagNo,new HashSet());
}
((Set)subtreesMap.get(tagNo)).add(subtree);
}
for (Iterator it=subtreesMap.entrySet().iterator(); it.hasNext(); ) {
Map.Entry entry=(Map.Entry)it.next();
switch (((Integer)entry.getKey()).intValue()) {
case 1:
permittedSubtreesEmail=intersectEmail(permittedSubtreesEmail,(Set)entry.getValue());
break;
case 2:
permittedSubtreesDNS=intersectDNS(permittedSubtreesDNS,(Set)entry.getValue());
break;
case 4:
permittedSubtreesDN=intersectDN(permittedSubtreesDN,(Set)entry.getValue());
break;
case 6:
permittedSubtreesURI=intersectURI(permittedSubtreesURI,(Set)entry.getValue());
break;
case 7:
permittedSubtreesIP=intersectIP(permittedSubtreesIP,(Set)entry.getValue());
}
}
}
| Updates the permitted set of these name constraints with the intersection with the given subtree. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.