code
stringlengths 10
174k
| nl
stringlengths 3
129k
|
---|---|
public TFloatLongIterator(TFloatLongHashMap map){
super(map);
_map=map;
}
| Creates an iterator over the specified map |
public JUnitGuiceClassRunner(final Class<?> clazz) throws InitializationError {
super(clazz);
this.injector=createInjector(clazz);
}
| Creates a new class runner instance |
public static void main(String[] args){
if (args.length != 3) return;
Config config=ConfigUtils.loadConfig(args[0]);
config.plans().setInputFile(null);
config.facilities().setInputFile(null);
config.network().setInputFile(null);
config.transit().setUseTransit(true);
Scenario scenario=ScenarioUtils.loadScenario(config);
log.info("Reading transit router network from file...");
Gbl.startMeasurement();
TransitRouterNetwork transitRouterNetwork=new TransitRouterNetwork();
new TransitRouterNetworkReaderMatsimV1(scenario,transitRouterNetwork).readFile(args[1]);
Gbl.printElapsedTime();
Gbl.printMemoryUsage();
System.gc();
Gbl.printMemoryUsage();
log.info("done.");
log.info("Thinning transit router network...");
Gbl.startMeasurement();
new RemoveRedundantLinks().run(transitRouterNetwork);
new RemoveRedundantDistanceLinks().run(transitRouterNetwork);
Gbl.printElapsedTime();
Gbl.printMemoryUsage();
System.gc();
Gbl.printMemoryUsage();
log.info("done.");
log.info("Writing thinned transit router network to file...");
new TransitRouterNetworkWriter(transitRouterNetwork).write(args[2]);
log.info("done.");
log.info("Writing thinned transit router network as matsim network to file...");
new NetworkWriter(transitRouterNetwork).write(args[2].replace("thinned","thinned_MATSim"));
log.info("done.");
}
| Expect two input strings: <li> <ul>config file</ul> <ul>output file</ul> </li> |
private boolean verifyPoint(GPNode inner1){
if (inner1.depth() + inner1.atDepth() + 1 > maxDepth) return false;
return true;
}
| Returns true if inner1's depth + atdepth +1 is within the depth bounds |
protected boolean isPutMethod(ODataRequest.Method method){
return ODataRequest.Method.PUT.equals(method);
}
| This method specifies requested method is PUT or not. |
public final void testGetSystemScope(){
String name=Security.getProperty("system.scope");
assertNotNull(name);
IdentityScope scope=IdentityScope.getSystemScope();
assertNotNull(scope);
assertEquals(name,scope.getClass().getName());
}
| just call IdentityScope.getSystemScope() |
public static void main(final String[] args){
DOMTestCase.doMain(hc_characterdataindexsizeerrsubstringcountnegative.class,args);
}
| Runs this test from the command line. |
public void writeMessageNoTag(final MessageLite value) throws IOException {
writeRawVarint32(value.getSerializedSize());
value.writeTo(this);
}
| Write an embedded message field to the stream. |
@Override public String toString(){
return byteArrayToIPString(address);
}
| Return printable version of the IP address |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-06 08:48:10.318 -0400",hash_original_method="6ED420CF552A86625F93410A37AE84F2",hash_generated_method="2F8A160491D2810787A3AB449FF5BB11") public Resolution(String id,String label,int horizontalDpi,int verticalDpi){
if (TextUtils.isEmpty(id)) {
throw new IllegalArgumentException("id cannot be empty.");
}
if (TextUtils.isEmpty(label)) {
throw new IllegalArgumentException("label cannot be empty.");
}
if (horizontalDpi <= 0) {
throw new IllegalArgumentException("horizontalDpi " + "cannot be less than or equal to zero.");
}
if (verticalDpi <= 0) {
throw new IllegalArgumentException("verticalDpi" + " cannot be less than or equal to zero.");
}
mId=id;
mLabel=label;
mHorizontalDpi=horizontalDpi;
mVerticalDpi=verticalDpi;
}
| Creates a new instance. |
public void reset(){
container.removeAll();
colorBar.clear();
ArrayList<ColorMap> colorMapList=Landscape.getInstance().getLayerManager().getColorMaps();
for (int i=0; i < colorMapList.size(); ++i) {
colorBar.add(new ColorBar(colorMapList.get(i),false));
}
if (colorBar.size() == 0) {
container.setLayout(new GridLayout(1,1));
container.add(new Label("No color bars."));
}
else {
container.setLayout(new GridLayout(colorBar.size(),1));
for (int i=0; i < colorBar.size(); ++i) {
container.add(colorBar.get(i));
}
}
validate();
repaint();
}
| Reset all of the color bars |
private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
if (factor == null) {
throw new NullPointerException();
}
if (lag < 0) {
throw new IllegalStateException();
}
}
| Adds semantic checks to the default deserialization method. This method must have the standard signature for a readObject method, and the body of the method must begin with "s.defaultReadObject();". Other than that, any semantic checks can be specified and do not need to stay the same from version to version. A readObject method of this form may be added to any class, even if Tetrad sessions were previously saved out using a version of the class that didn't include it. (That's what the "s.defaultReadObject();" is for. See J. Bloch, Effective Java, for help. |
public int next(){
if (_currentNode == DTM.NULL) {
return DTM.NULL;
}
int node=_currentNode;
final int nodeType=_nodeType;
if (nodeType != DTM.ELEMENT_NODE) {
while ((node=_nextsib2(node)) != DTM.NULL && _exptype2(node) != nodeType) {
}
}
else {
while ((node=_nextsib2(node)) != DTM.NULL && _exptype2(node) < DTM.NTYPES) {
}
}
_currentNode=node;
return (node == DTM.NULL) ? DTM.NULL : returnNode(makeNodeHandle(node));
}
| Get the next node in the iteration. |
@Override protected void installTileRasterLater(LevelSet levelSet,Tile tile,DataRaster tileRaster,AVList params){
this.updateExtremeElevations(tileRaster);
super.installTileRasterLater(levelSet,tile,tileRaster,params);
}
| Overridden to compute the extreme elevations prior to installing a tile in the filesystem. |
private void cleanupDiscovery(StorageSystem system){
try {
system.setReachableStatus(false);
_dbClient.persistObject(system);
}
catch ( DatabaseException e) {
_logger.error("discoverStorage failed. Failed to update discovery status to ERROR.",e);
}
}
| If discovery fails, then mark the system as unreachable. The discovery framework will remove the storage system from the database. |
private List<Object> convertFunnelStepObjectToList(Object parameter){
if (parameter instanceof List) {
return (List<Object>)funnelObjectInspector.getList(parameter);
}
else {
return Arrays.asList(ObjectInspectorUtils.copyToStandardObject(parameter,funnelObjectInspector.getListElementObjectInspector()));
}
}
| Convert object to list of funnels for a funnel step. |
public static byte[] hexStringToByteArray(String s){
if (s == null || s.length() == 0) {
return null;
}
int len=s.length();
if (len % 2 != 0) {
throw new IllegalArgumentException();
}
byte[] data=new byte[len / 2];
for (int i=0; i < len; i+=2) {
data[i / 2]=(byte)((Character.digit(s.charAt(i),16) << 4) + Character.digit(s.charAt(i + 1),16));
}
return data;
}
| Decode hex string to a byte array |
public OMSpline(double latPoint,double lonPoint,int[] xypoints,int cMode){
super(latPoint,lonPoint,xypoints,cMode);
}
| Create an x/y OMSpline at an offset from lat/lon. If you want the curve to be connected, you need to ensure that the first and last coordinate pairs are the same. |
@Override public void process(KeyValPair<K,V> tuple){
K key=tuple.getKey();
MutableInt count=counts.get(key);
if (count == null) {
count=new MutableInt(0);
counts.put(cloneKey(key),count);
}
count.increment();
}
| For each tuple (a key value pair): Adds the values for each key, Counts the number of occurrence of each key |
public FactoryConfigurationError(Exception e,String msg){
super(msg);
this.exception=e;
}
| Create a new <code>FactoryConfigurationError</code> with the given <code>Exception</code> base cause and detail message. |
public String amounts(Properties ctx,int WindowNo,GridTab mTab,GridField mField,Object value,Object oldValue){
if (isCalloutActive()) return "";
int C_Invoice_ID=Env.getContextAsInt(ctx,WindowNo,"C_Invoice_ID");
if (C_Invoice_ID == 0) return "";
BigDecimal Amount=(BigDecimal)mTab.getValue("Amount");
BigDecimal DiscountAmt=(BigDecimal)mTab.getValue("DiscountAmt");
BigDecimal WriteOffAmt=(BigDecimal)mTab.getValue("WriteOffAmt");
BigDecimal OverUnderAmt=(BigDecimal)mTab.getValue("OverUnderAmt");
BigDecimal InvoiceAmt=(BigDecimal)mTab.getValue("InvoiceAmt");
log.fine("Amt=" + Amount + ", Discount="+ DiscountAmt+ ", WriteOff="+ WriteOffAmt+ ", OverUnder="+ OverUnderAmt+ ", Invoice="+ InvoiceAmt);
String colName=mField.getColumnName();
if (colName.equals("Amount")) {
WriteOffAmt=InvoiceAmt.subtract(Amount).subtract(DiscountAmt).subtract(OverUnderAmt);
mTab.setValue("WriteOffAmt",WriteOffAmt);
}
else {
Amount=InvoiceAmt.subtract(DiscountAmt).subtract(WriteOffAmt).subtract(OverUnderAmt);
mTab.setValue("Amount",Amount);
}
return "";
}
| Payment_Amounts. Change of: - IsOverUnderPayment -> set OverUnderAmt to 0 - C_Currency_ID, C_ConvesionRate_ID -> convert all - PayAmt, DiscountAmt, WriteOffAmt, OverUnderAmt -> PayAmt make sure that add up to InvoiceOpenAmt |
@Override public boolean first() throws SQLException {
try {
debugCodeCall("first");
checkClosed();
if (result.getRowId() < 0) {
return nextRow();
}
resetResult();
return nextRow();
}
catch ( Exception e) {
throw logAndConvert(e);
}
}
| Moves the current position to the first row. This is the same as calling beforeFirst() followed by next(). |
public Object remove(int index){
int _numObjs=numObjs;
if (index >= _numObjs) throw new ArrayIndexOutOfBoundsException(index);
Object[] _objs=this.objs;
Object ret=_objs[index];
_objs[index]=_objs[_numObjs - 1];
_objs[_numObjs - 1]=null;
numObjs--;
return ret;
}
| Removes the object at the given index, moving the topmost object into its position. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-03-25 15:47:16.612 -0400",hash_original_method="D336BDB6264C4835A6DCD28216EF4935",hash_generated_method="7A5A1E56A7E371652DBBF49CCF9E5ECC") public void enable(BluetoothAdapter adapter){
int mask=(BluetoothReceiver.STATE_TURNING_ON_FLAG | BluetoothReceiver.STATE_ON_FLAG | BluetoothReceiver.SCAN_MODE_CONNECTABLE_FLAG);
long start=-1;
BluetoothReceiver receiver=getBluetoothReceiver(mask);
int state=adapter.getState();
switch (state) {
case BluetoothAdapter.STATE_ON:
assertTrue(adapter.isEnabled());
removeReceiver(receiver);
return;
case BluetoothAdapter.STATE_TURNING_ON:
assertFalse(adapter.isEnabled());
mask=0;
break;
case BluetoothAdapter.STATE_OFF:
assertFalse(adapter.isEnabled());
start=System.currentTimeMillis();
assertTrue(adapter.enable());
break;
case BluetoothAdapter.STATE_TURNING_OFF:
start=System.currentTimeMillis();
assertTrue(adapter.enable());
break;
default :
removeReceiver(receiver);
fail(String.format("enable() invalid state: state=%d",state));
}
long s=System.currentTimeMillis();
while (System.currentTimeMillis() - s < ENABLE_DISABLE_TIMEOUT) {
state=adapter.getState();
if (state == BluetoothAdapter.STATE_ON && (receiver.getFiredFlags() & mask) == mask) {
assertTrue(adapter.isEnabled());
long finish=receiver.getCompletedTime();
if (start != -1 && finish != -1) {
writeOutput(String.format("enable() completed in %d ms",(finish - start)));
}
else {
writeOutput("enable() completed");
}
removeReceiver(receiver);
return;
}
sleep(POLL_TIME);
}
int firedFlags=receiver.getFiredFlags();
removeReceiver(receiver);
fail(String.format("enable() timeout: state=%d (expected %d), flags=0x%x (expected 0x%x)",state,BluetoothAdapter.STATE_ON,firedFlags,mask));
}
| Enables Bluetooth and checks to make sure that Bluetooth was turned on and that the correct actions were broadcast. |
private void fireFeatureEnabled(final String name,final String value){
logger.debug("Feature enabled: " + name + " = "+ value);
for ( final FeatureChangeListener l : featureListeners) {
l.featureEnabled(name,value);
}
}
| Fire feature enabled to all registered listeners. |
private void updateProgress(String progressLabel,int progress){
if (myHost != null && ((progress != previousProgress) || (!progressLabel.equals(previousProgressLabel)))) {
myHost.updateProgress(progressLabel,progress);
}
previousProgress=progress;
previousProgressLabel=progressLabel;
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
public long create(User user){
if (user.getSettingsId() == 0) {
user.setSettings(mSettingsDataSource.createNewDefaultSettings());
}
return mDaoSession.getUserDao().insert(user);
}
| Creates a new user and assigns default settings |
private void updateProgress(String progressLabel,int progress){
if (myHost != null) {
myHost.updateProgress(progressLabel,progress);
}
else {
System.out.println(progressLabel + " " + progress+ "%");
}
}
| Used to communicate a progress update between a plugin tool and the main Whitebox user interface. |
@Override public String toString(){
return CommandProcessingException.class.getSimpleName() + "[errorType=" + errorTypeStrings[errorType]+ ", errorData="+ errorData+ "]";
}
| Returns the String representation of this <code>CommandProcessingException<code> |
protected CustomToolBar createEditToolBar(){
CustomToolBar editTools=new CustomToolBar();
for ( Action action : actionManager.getNetworkEditingActions()) {
editTools.add(action);
}
editTools.add(actionManager.getZeroSelectedObjectsAction());
editTools.add(actionManager.getRandomizeObjectsAction());
return editTools;
}
| Create the edit tool bar. |
public static boolean isHexCharacter(final char c){
return isDecCharacter(c) || ((c >= 'a') && (c <= 'f')) || ((c >= 'A') && (c <= 'F'));
}
| Tests whether a character is a valid character of a hexadecimal string. |
public static int compare(double left,Object right) throws PageException {
if (right instanceof Number) return compare(left,((Number)right).doubleValue());
else if (right instanceof String) return compare(left,(String)right);
else if (right instanceof Boolean) return compare(left,((Boolean)right).booleanValue() ? 1D : 0D);
else if (right instanceof Date) return compare(left,((Date)right));
else if (right instanceof Castable) {
if (isComparableComponent((Castable)right)) return -compareComponent((Castable)right,left);
return -((Castable)right).compareTo(left);
}
else if (right instanceof Locale) return compare(Caster.toString(left),((Locale)right));
else if (right == null) return 1;
else if (right instanceof Character) return compare(left,((Character)right).toString());
else if (right instanceof Calendar) return compare(left,((Calendar)right).getTime());
else if (right instanceof TimeZone) return compare(Caster.toString(left),((TimeZone)right));
else return error(true,false);
}
| compares a double with a Object |
private static String readFromPath(String path){
try {
StringBuilder sb=new StringBuilder();
BufferedReader reader=new BufferedReader(new FileReader(path));
String line;
while ((line=reader.readLine()) != null) {
sb.append(line).append("\n");
}
return sb.toString();
}
catch ( IOException e) {
LOG.e(e,format("Failed to read xml form into a String. FilePath= %s",path));
return null;
}
}
| Returns the xml form as a String from the path. If for any reason, the file couldn't be read, it returns <code>null</code> |
public ListIterator<E> listIterator(){
return new ListItr(0);
}
| Returns a list iterator over the elements in this list (in proper sequence). <p>The returned list iterator is <a href="#fail-fast"><i>fail-fast</i></a>. |
public boolean convert(){
if (getC_Currency_ID() == Doc.NO_CURRENCY) setC_Currency_ID(m_acctSchema.getC_Currency_ID());
if (m_acctSchema.getC_Currency_ID() == getC_Currency_ID()) {
setAmtAcctDr(getAmtSourceDr());
setAmtAcctCr(getAmtSourceCr());
return true;
}
int C_ConversionType_ID=0;
int AD_Org_ID=0;
if (m_docLine != null) {
C_ConversionType_ID=m_docLine.getC_ConversionType_ID();
AD_Org_ID=m_docLine.getAD_Org_ID();
}
if (C_ConversionType_ID == 0) {
if (m_doc == null) {
log.severe("No Document VO");
return false;
}
C_ConversionType_ID=m_doc.getC_ConversionType_ID();
if (AD_Org_ID == 0) AD_Org_ID=m_doc.getAD_Org_ID();
}
setAmtAcctDr(MConversionRate.convert(getCtx(),getAmtSourceDr(),getC_Currency_ID(),m_acctSchema.getC_Currency_ID(),getDateAcct(),C_ConversionType_ID,m_doc.getAD_Client_ID(),AD_Org_ID));
if (getAmtAcctDr() == null) return false;
setAmtAcctCr(MConversionRate.convert(getCtx(),getAmtSourceCr(),getC_Currency_ID(),m_acctSchema.getC_Currency_ID(),getDateAcct(),C_ConversionType_ID,m_doc.getAD_Client_ID(),AD_Org_ID));
return true;
}
| Convert to Accounted Currency |
public void bindAllArgsAsStrings(String[] bindArgs){
if (bindArgs != null) {
for (int i=bindArgs.length; i != 0; i--) {
bindString(i,bindArgs[i - 1]);
}
}
}
| Given an array of String bindArgs, this method binds all of them in one single call. |
public static int executeUpdate(String sql,int param,String trxName){
return executeUpdate(sql,param,trxName,0);
}
| Execute Update. saves "DBExecuteError" in Log |
public boolean isCreditCardDisabled(){
return (isPersistedType(PaymentInfoType.CREDIT_CARD) && isCreditCardAvailable()) ? true : false;
}
| Reflects the state of the payment type in relation to persisted object. |
public GregorianCalendar(int year,int month,int dayOfMonth,int hourOfDay,int minute){
this(year,month,dayOfMonth,hourOfDay,minute,0,0);
}
| Constructs a <code>GregorianCalendar</code> with the given date and time set for the default time zone with the default locale. |
public HttpsURL(final String user,final String password,final String host,final int port,final String path) throws URIException {
this(user,password,host,port,path,null,null);
}
| Construct a HTTPS URL from given components. |
public DefaultResultAdapterContext(boolean registerDefaults){
adapters=new ArrayList<>();
if (registerDefaults) {
adapters.add(new VoidResultAdapter());
adapters.add(new SameTypeResultAdapter());
adapters.add(new NullSimpleResultAdapter());
adapters.add(new NullToIteratorResultAdapter());
adapters.add(new NullToCollectionResultAdapter());
adapters.add(new NullToIterableResultAdapter());
adapters.add(new NullToSliceResultAdapter());
adapters.add(new NullToFutureResultAdapter());
adapters.add(new NullToListenableFutureResultAdapter());
adapters.add(new NumberIterableResultAdapter());
adapters.add(new SimpleIterableResultAdapter());
adapters.add(new IteratorIterableResultAdapter());
adapters.add(new CollectionIterableResultAdapter());
adapters.add(new SliceIterableResultAdapter());
adapters.add(new PageIterableResultAdapter());
adapters.add(new GeoPageIterableResultAdapter());
adapters.add(new FutureIterableResultAdapter());
adapters.add(new ListenableFutureIterableResultAdapter());
Collections.sort(adapters);
}
}
| Instantiates the context |
public boolean isAutoAdjustBlendFactor(){
return (layerManager.autoAdjustOpacity);
}
| Is the blend factor auto-adjusting |
public GroupChatMessageDeleteTask(ChatServiceImpl chatService,InstantMessagingService imService,LocalContentResolver contentResolver,String chatId){
super(contentResolver,MessageData.CONTENT_URI,MessageData.KEY_MESSAGE_ID,MessageData.KEY_CHAT_ID,SELECTION_CHATMESSAGES_BY_CHATID,chatId);
mChatService=chatService;
mImService=imService;
}
| Deletion of all chat messages from the specified group chat id. |
public ToStringBuilder append(String fieldName,float value){
style.append(buffer,fieldName,value);
return this;
}
| <p>Append to the <code>toString</code> an <code>float</code> value.</p> |
public static void print(StackMapTable smt,PrintWriter writer){
try {
new Printer(smt.get(),writer).parse();
}
catch ( BadBytecode e) {
writer.println(e.getMessage());
}
}
| Prints the stack table map. |
@DSComment("From safe class list") @DSSafe(DSCat.SAFE_LIST) @DSSource({DSSourceKind.SENSITIVE_UNCATEGORIZED}) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 13:02:43.830 -0500",hash_original_method="961A5CFC9275837B3D79C86ECF9A0692",hash_generated_method="635F9BB5EC31EC20435F9A758E3D2B16") public TestResult run(){
TestResult result=createResult();
run(result);
return result;
}
| A convenience method to run this test, collecting the results with a default TestResult object. |
public static boolean isValidSignature(byte[] pubKey,byte[] message,byte[] signature) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, SignatureException, InvalidKeySpecException {
Signature ecdsaVerify=Signature.getInstance("SHA256withECDSA",new BouncyCastleProvider());
ecdsaVerify.initVerify(decodeNISTP256PublicKeyFromBytes(pubKey));
ecdsaVerify.update(message);
return ecdsaVerify.verify(signature);
}
| <p> Verify an SSH signature against a given public key and message</p> |
public void runTest() throws Throwable {
Document doc;
Node newNode;
String newValue;
doc=(Document)load("hc_staff",true);
newNode=doc.createComment("This is a new Comment node");
newValue=newNode.getNodeValue();
assertEquals("initial","This is a new Comment node",newValue);
newNode.setNodeValue("This should have an effect");
newValue=newNode.getNodeValue();
assertEquals("afterChange","This should have an effect",newValue);
}
| Runs the test case. |
public void validateBusinessObjectData(Integer expectedBusinessObjectDataId,String expectedNamespace,String expectedBusinessObjectDefinitionName,String expectedBusinessObjectFormatUsage,String expectedBusinessObjectFormatFileType,Integer expectedBusinessObjectFormatVersion,String expectedBusinessObjectDataPartitionValue,List<String> expectedBusinessObjectDataSubPartitionValues,Integer expectedBusinessObjectDataVersion,Boolean expectedLatestVersion,String expectedStatusCode,String expectedStorageName,String expectedStorageDirectoryPath,List<StorageFile> expectedStorageFiles,List<Attribute> expectedAttributes,BusinessObjectData actualBusinessObjectData){
validateBusinessObjectData(expectedBusinessObjectDataId,expectedNamespace,expectedBusinessObjectDefinitionName,expectedBusinessObjectFormatUsage,expectedBusinessObjectFormatFileType,expectedBusinessObjectFormatVersion,expectedBusinessObjectDataPartitionValue,expectedBusinessObjectDataSubPartitionValues,expectedBusinessObjectDataVersion,expectedLatestVersion,expectedStatusCode,actualBusinessObjectData);
assertEquals(1,actualBusinessObjectData.getStorageUnits().size());
StorageUnit actualStorageUnit=actualBusinessObjectData.getStorageUnits().get(0);
assertEquals(expectedStorageName,actualStorageUnit.getStorage().getName());
assertEquals(expectedStorageDirectoryPath,actualStorageUnit.getStorageDirectory() != null ? actualStorageUnit.getStorageDirectory().getDirectoryPath() : null);
AbstractServiceTest.assertEqualsIgnoreOrder("storage files",expectedStorageFiles,actualStorageUnit.getStorageFiles());
assertEquals(expectedAttributes,actualBusinessObjectData.getAttributes());
}
| Validates business object data against specified arguments and expected (hard coded) test values. |
public static double pareto(){
return pareto(1.0);
}
| Returns a random real number from the standard Pareto distribution. |
public double actual(){
return m_Actual;
}
| Gets the actual class value. |
private int currentDepth(){
try {
Integer oneBased=((Integer)DEPTH_FIELD.get(this));
return oneBased - 1;
}
catch ( IllegalAccessException e) {
throw new AssertionError(e);
}
}
| Returns a 0-based depth within the object graph of the current object being serialized. |
public IMFErrorLoggerImpl(){
this.errorObjects=Collections.synchronizedSet(new HashSet<ErrorLogger.ErrorObject>());
}
| Instantiates a new IMF error logger impl object |
public static void main(String[] args){
LatLonPoint llpt1=new LatLonPoint.Double(87.00,-74.50);
System.out.println(llpt1.toString());
UPSPoint ups=new UPSPoint(llpt1);
System.out.println(ups.toString());
LatLonPoint llpt2=ups.toLatLonPoint(false);
System.out.println(llpt2.toString());
System.out.println("--------------------------------------------");
llpt1=new LatLonPoint.Double(-89.00,110.50);
System.out.println(llpt1.toString());
ups=new UPSPoint(llpt1);
System.out.println(ups.toString());
llpt2=ups.toLatLonPoint(true);
System.out.println(llpt2.toString());
}
| Tested against the NIMA calculator |
private void disablePahoLogging(){
LogManager.getLogManager().reset();
logging=false;
HashMap<String,Connection> connections=(HashMap<String,Connection>)Connections.getInstance(context).getConnections();
if (!connections.isEmpty()) {
Entry<String,Connection> entry=connections.entrySet().iterator().next();
Connection connection=(Connection)entry.getValue();
connection.getClient().setTraceEnabled(false);
clientConnections.invalidateOptionsMenu();
}
else {
Log.i("SampleListener","No connection to disable log in service");
}
clientConnections.invalidateOptionsMenu();
}
| Disables logging in the Paho MQTT client |
public double computeAverageLocalOfObservationsWithCorrection() throws Exception {
double te=0.0;
for (int b=0; b < totalObservations; b++) {
TransferEntropyKernelCounts kernelCounts=teKernelEstimator.getCount(destPastVectors[b],destNextVectors[b],sourceVectors[b],b);
double cont=0.0;
if (kernelCounts.countNextPastSource > 0) {
cont=MathsUtils.digamma(kernelCounts.countNextPastSource) - MathsUtils.digamma(kernelCounts.countPastSource) - MathsUtils.digamma(kernelCounts.countNextPast) + MathsUtils.digamma(kernelCounts.countPast);
}
te+=cont;
}
lastAverage=te / (double)totalObservations / log2;
return lastAverage;
}
| <p>Computes the average Transfer Entropy for the previously supplied observations, using the Grassberger correction for the point count k: log_e(k) ~= digamma(k).</p> <p><b>HOWEVER</b> -- Kaiser and Schreiber, Physica D 166 (2002) pp. 43-62 suggest (on p. 57) that for the TE though the adverse correction of the bias correction is worse than the correction itself (because the probabilities being multiplied/divided are not independent), so recommend not to use this method. </p> <p>As such, it is implemented here for testing purposes only.</p> |
public static final double squareSum(final double[] v1){
double acc=0.0;
for (int row=0; row < v1.length; row++) {
final double v=v1[row];
acc+=v * v;
}
return acc;
}
| Squared Euclidean length of the vector |
protected void trimContextForElement(SVGGraphicContext svgGC,Element element){
String tag=element.getTagName();
Map groupAttrMap=svgGC.getGroupContext();
if (tag != null) {
Iterator iter=groupAttrMap.keySet().iterator();
while (iter.hasNext()) {
String attrName=(String)iter.next();
SVGAttribute attr=SVGAttributeMap.get(attrName);
if (attr != null && !attr.appliesTo(tag)) groupAttrMap.remove(attrName);
}
}
}
| Removes properties that do not apply for a specific element |
public void printf(String format,Object... args){
out.printf(LOCALE,format,args);
out.flush();
}
| Prints a formatted string to this output stream, using the specified format string and arguments, and then flushes this output stream. |
public static Test suite(){
return (new TestSuite(ReplaceViewHandlerTestCase.class));
}
| Return the tests included in this test suite. |
private long hash(final long[] a,final int l,final int k){
final int[] w=weight[k];
long h=init[k];
int i=l;
while (i-- != 0) h^=(h << 5) + a[i] * w[i % NUMBER_OF_WEIGHTS] + (h >>> 2);
return (h & 0x7FFFFFFFFFFFFFFFL) % m;
}
| Hashes the given long array with the given hash function. |
@DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2013-12-30 12:58:13.021 -0500",hash_original_method="0B2DE5EAED23ABC2AB533476CA60B194",hash_generated_method="F9084A2132A4774A25EB67D6F9253A14") public void socksAccept() throws IOException {
Socks4Message reply=socksReadReply();
if (reply.getCommandOrResult() != Socks4Message.RETURN_SUCCESS) {
throw new IOException(reply.getErrorString(reply.getCommandOrResult()));
}
}
| Perform an accept for a SOCKS bind. |
@SuppressWarnings("unchecked") public static <C extends Comparable>ImmutableRangeSet<C> of(){
return (ImmutableRangeSet<C>)EMPTY;
}
| Returns an empty immutable range set. |
public static Map<String,XmlNamespace> calculateNamespaces(Element root,ElementMetadata<?,?> metadata){
Map<String,XmlNamespace> namespaceMap=Maps.newHashMap();
calculateNamespaces(namespaceMap,root,metadata);
return namespaceMap;
}
| Calculate the set of namespaces on an element. This will find all namespaces declared on the element or child elements, ordered in depth-first order. |
public final SSLEngine createSSLEngine(String peerHost,int peerPort){
try {
return contextSpi.engineCreateSSLEngine(peerHost,peerPort);
}
catch ( AbstractMethodError e) {
UnsupportedOperationException unsup=new UnsupportedOperationException("Provider: " + getProvider() + " does not support this operation");
unsup.initCause(e);
throw unsup;
}
}
| Creates a new <code>SSLEngine</code> using this context using advisory peer information. <P> Applications using this factory method are providing hints for an internal session reuse strategy. <P> Some cipher suites (such as Kerberos) require remote hostname information, in which case peerHost needs to be specified. |
public static boolean isConnectedWifi(Context context){
NetworkInfo info=Connectivity.getNetworkInfo(context);
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
}
| Check if there is any connectivity to a Wifi network |
public void open(final Shell parent){
if (this.index == -1) {
this.index=new Random().nextInt(this.tips.size());
}
buildShell(parent);
if (this.style == TipStyle.HEADER) {
buildHeader();
}
else {
buildLeftColumn();
}
buildTip();
buildButtons();
openShell();
}
| Open the "tip of the day" box |
public static Class<?>[] wrappersToPrimitives(final Class<?>[] classes){
if (classes == null) {
return null;
}
if (classes.length == 0) {
return classes;
}
Class<?>[] convertedClasses=new Class[classes.length];
for (int i=0; i < classes.length; i++) {
convertedClasses[i]=ClassUtils.wrapperToPrimitive(classes[i]);
}
return convertedClasses;
}
| <p>Converts the specified array of wrapper Class objects to an array of its corresponding primitive Class objects.</p> <p>This method invokes <code>wrapperToPrimitive()</code> for each element of the passed in array.</p> |
private boolean canUseThisAd(NativeExpressAdView adNative){
if (adNative == null || adNative.isLoading()) return false;
return true;
}
| Determines if the native ad can be used. |
public final boolean isDependentRegionLinefeedStatusChanged(){
return (myFlags & DEPENDENT_REGION_LF_CHANGED_MASK) != 0;
}
| Allows to answer whether 'contains line feed' status has been changed for the target dependent region during formatting. |
public void computeAxis(float yMin,float yMax){
if (mViewPortHandler.contentWidth() > 10 && !mViewPortHandler.isFullyZoomedOutY()) {
PointD p1=mTrans.getValuesByTouchPoint(mViewPortHandler.contentLeft(),mViewPortHandler.contentTop());
PointD p2=mTrans.getValuesByTouchPoint(mViewPortHandler.contentLeft(),mViewPortHandler.contentBottom());
if (!mYAxis.isInverted()) {
yMin=(float)p2.y;
yMax=(float)p1.y;
}
else {
yMin=(float)p1.y;
yMax=(float)p2.y;
}
}
computeAxisValues(yMin,yMax);
}
| Computes the axis values. |
private void writeAttribute(java.lang.String namespace,java.lang.String attName,java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName,attValue);
}
else {
registerPrefix(xmlWriter,namespace);
xmlWriter.writeAttribute(namespace,attName,attValue);
}
}
| Util method to write an attribute without the ns prefix |
public Item perFieldAnalyzer(Map<String,String> perFieldAnalyzer){
this.perFieldAnalyzer=perFieldAnalyzer;
return this;
}
| Sets the analyzer(s) to use at any given field. |
public String toString(){
return getName();
}
| String Representation |
private void indexQuery(QueryEntry entry,ServerSessionContext session,CompletableFuture<QueryResponse> future){
if (entry.getIndex() > session.getLastApplied()) {
session.registerIndexQuery(entry.getIndex(),null);
}
else {
applyQuery(entry,future);
}
}
| Ensures the given query is applied after the appropriate index. |
public DirectedOrderedSparseMultigraph(){
vertices=new LinkedHashMap<V,Pair<Set<E>>>();
edges=new LinkedHashMap<E,Pair<V>>();
}
| Creates a new instance. |
public void visible(boolean visible){
this.visible=visible;
}
| Sets visible flag. |
public static void writeStringMap(DataOutput out,@Nullable Map<String,String> map) throws IOException {
if (map != null) {
out.writeInt(map.size());
for ( Map.Entry<String,String> e : map.entrySet()) {
writeUTFStringNullable(out,e.getKey());
writeUTFStringNullable(out,e.getValue());
}
}
else out.writeInt(-1);
}
| Writes string-to-string map to given data output. |
@PUT @Path("/{machineId}/cancel") public void cancelExecution(@PathParam("machineId") Long machineId){
}
| Cancel a machine being executed. |
public SQLiteSession(SQLiteConnectionPool connectionPool){
if (connectionPool == null) {
throw new IllegalArgumentException("connectionPool must not be null");
}
mConnectionPool=connectionPool;
}
| Creates a session bound to the specified connection pool. |
public static Stats of(int... values){
StatsAccumulator acummulator=new StatsAccumulator();
acummulator.addAll(values);
return acummulator.snapshot();
}
| Returns statistics over a dataset containing the given values. |
public static Test suite(){
final TestSuite suite=new TestSuite("B+Tree basics");
suite.addTestSuite(TestUtilMethods.class);
suite.addTestSuite(TestFindChild.class);
suite.addTestSuite(TestInsertLookupRemoveKeysInRootLeaf.class);
suite.addTestSuite(TestSplitRootLeaf.class);
suite.addTestSuite(TestSplitJoinRootLeaf.class);
suite.addTestSuite(TestSplitJoinThreeLevels.class);
suite.addTestSuite(TestLeafSplitShortestSeparatorKey.class);
suite.addTestSuite(TestLinearListMethods.class);
suite.addTestSuite(TestIndexCounter.class);
suite.addTestSuite(TestConstrainKeys.class);
suite.addTest(TestAll_Iterators.suite());
suite.addTestSuite(TestRemoveAll.class);
suite.addTestSuite(TestTouch.class);
suite.addTestSuite(TestBTree.class);
suite.addTestSuite(TestDirtyIterators.class);
suite.addTestSuite(TestIncrementalWrite.class);
suite.addTestSuite(TestCopyOnWrite.class);
suite.addTestSuite(TestDeleteMarkers.class);
suite.addTestSuite(TestPutIfAbsent.class);
suite.addTestSuite(TestCommit.class);
suite.addTestSuite(TestDirtyListener.class);
suite.addTestSuite(TestReopen.class);
suite.addTestSuite(TestNullValues.class);
suite.addTestSuite(TestBTreeRecycle.class);
suite.addTestSuite(TestTransientBTree.class);
suite.addTestSuite(TestRawRecords.class);
suite.addTestSuite(StressTestBTreeRemove.class);
suite.addTestSuite(TestBloomFilter.class);
suite.addTestSuite(TestBTreeWithBloomFilter.class);
suite.addTestSuite(TestBTreeBranchingFactors.class);
return suite;
}
| Returns a test that will run each of the implementation specific test suites in turn. |
public float screenY(float x,float y){
showMissingWarning("screenY");
return 0;
}
| Given an x and y coordinate, returns the y position of where that point would be placed on screen, once affected by translate(), scale(), or any other transformations. |
public void addDivider(ArchiveTokenDivider div){
m_dividers.add(div);
}
| Agrega un nuevo clasificador al archivador |
public void forceKeyspaceFlush(String keyspaceName,String... columnFamilies) throws IOException {
for ( ColumnFamilyStore cfStore : getValidColumnFamilies(true,false,keyspaceName,columnFamilies)) {
logger.debug("Forcing flush on keyspace {}, CF {}",keyspaceName,cfStore.name);
cfStore.forceBlockingFlush();
}
}
| Flush all memtables for a keyspace and column families. |
private void extract(Detail detail,DefaultType access) throws Exception {
List<MethodDetail> methods=detail.getMethods();
if (access == PROPERTY) {
for ( MethodDetail entry : methods) {
Annotation[] list=entry.getAnnotations();
Method method=entry.getMethod();
Class value=factory.getType(method);
if (value != null) {
process(method,list);
}
}
}
}
| This is used to scan all the methods of the class in order to determine if it should have a default annotation. If the method should have a default XML annotation then it is added to the list of contacts to be used to form the class schema. |
public void recordBounds(final PlanetModel planetModel,final LatLonBounds boundsInfo,final Plane p,final Membership... bounds){
findIntersectionBounds(planetModel,boundsInfo,p,bounds);
}
| Accumulate bounds information for this plane, intersected with another plane and the world. Updates both latitude and longitude information, using max/min points found within the specified bounds. Also takes into account the error envelope for all planes being intersected. |
private void rebuildNode(){
m_realizer.regenerate();
m_graph.updateViews();
}
| Regenerates the content of the node and updates the graph view. |
public void addException(long fromDomainValue,long toDomainValue){
addException(new SegmentRange(fromDomainValue,toDomainValue));
}
| Adds a segment range as an exception. An exception segment is defined as a segment to exclude from what would otherwise be considered a valid segment of the timeline. An exception segment can not be contained inside an already excluded segment. If so, no action will occur (the proposed exception segment will be discarded). <p> The segment range is identified by a domainValue that begins a valid segment and ends with a domainValue that ends a valid segment. Therefore the range will contain all segments whose segmentStart <= domainValue and segmentEnd <= toDomainValue. |
private Properties cloneProperties(Properties properties){
Properties clonedProperties=new Properties();
for (Enumeration<?> propertyNames=properties.propertyNames(); propertyNames.hasMoreElements(); ) {
Object key=propertyNames.nextElement();
clonedProperties.put(key,properties.get(key));
}
return clonedProperties;
}
| Creates a clone of the specified properties object. |
public void delete(String name) throws IOException {
if (name.equalsIgnoreCase(SUBJECT_NAME)) {
names=null;
}
else {
throw new IOException("Attribute name not recognized by " + "CertAttrSet:SubjectAlternativeName.");
}
encodeThis();
}
| Delete the attribute value. |
public static ExtensionRegistry newInstance(){
return new ExtensionRegistry();
}
| Construct a new, empty instance. |
private static Integer computeLegacyIdFromCamera2Id(@Nonnull String camera2Id){
try {
return Integer.parseInt(camera2Id);
}
catch ( NumberFormatException ignored) {
}
return null;
}
| This should compute a Legacy Api1 camera Id for the given camera2 device. This class will return null if the camera2 identifier cannot be transformed into an api1 id. |
private ManagedSystemInfo(int gmtOffset,String osName){
if ((osName == null) || (osName.length() == 0)) {
m_osName="";
}
else {
m_osName=osName.trim();
}
m_gmtOffset=gmtOffset;
logger.trace(String.format("ManagedSystemInfo CTOR( gmt=%d, osName=%s )...",m_gmtOffset,m_osName));
}
| Internal CTOR. Values come from database row in MANAGED_SYSTEMS table. Vacant values are moot, as they will be set unconditionally from external values. |
public byte[] toBytes() throws UnsupportedEncodingException {
StringBuilder result=new StringBuilder(256);
result.append(requestLine).append("\r\n");
for (int i=0; i < namesAndValues.size(); i+=2) {
result.append(namesAndValues.get(i)).append(": ").append(namesAndValues.get(i + 1)).append("\r\n");
}
result.append("\r\n");
return result.toString().getBytes("ISO-8859-1");
}
| Returns bytes of a request header for sending on an HTTP transport. |
private void usageError(String errorMsg) throws AdeUsageException {
System.out.flush();
System.err.println("Usage:");
System.err.println("\ttrain <analysis_group_name> [<start date> | <start date> <end date>] ");
System.err.println("\ttrain all [<start date> | <start date> <end date>");
System.err.println();
System.err.println("Reads summary of all messages within the specified dates and system id");
System.err.println("and updates the default model for this system.");
System.err.println("Specifying 'all' instead of analysis_group_name creates a model for each system in the database");
System.err.println("For Linux, analysis group name is the name of the group for a set of Linux Systems.");
System.err.println();
System.err.flush();
throw new AdeUsageException(errorMsg);
}
| Output error message together with the syntax for this class. |
public void insert(String namespace,String set,Key key,List<Bin> bins){
insert(namespace,set,key,bins,0);
}
| inserts a record. If the record exists, and exception will be thrown. |
@DSSafe(DSCat.SAFE_LIST) @DSGenerator(tool_name="Doppelganger",tool_version="2.0",generated_on="2014-09-03 14:59:54.196 -0400",hash_original_method="95E1997ED876C3EFBCA8CFB5348AD2D8",hash_generated_method="239D91317D1BB114819FD0921C6687B1") public static InputStream toInputStream(String input,String encoding) throws IOException {
byte[] bytes=input.getBytes(Charsets.toCharset(encoding));
return new ByteArrayInputStream(bytes);
}
| Convert the specified string to an input stream, encoded as bytes using the specified character encoding. <p> Character encoding names can be found at <a href="http://www.iana.org/assignments/character-sets">IANA</a>. |
public static boolean interfaceOf(Class<?> objectClass,Object interfaceObject){
Class<?> interfaceClass=interfaceObject.getClass();
return interfaceOf(objectClass,interfaceClass);
}
| Tests if a class properly implements the specified interface. |
JCNewClass makeNewClass(Type ctype,List<JCExpression> args){
return makeNewClass(ctype,args,rs.resolveConstructor(null,attrEnv,ctype,TreeInfo.types(args),List.<Type>nil()));
}
| Make an attributed class instance creation expression. |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.