query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
A convenience method for creating an immutable map.
@param self a Map
@return an immutable Map
@see java.util.Collections#unmodifiableMap(java.util.Map)
@since 1.0 | [
"public static <K,V> Map<K,V> asImmutable(Map<? extends K, ? extends V> self) {\n return Collections.unmodifiableMap(self);\n }"
] | [
"public static double SquaredEuclidean(double[] x, double[] y) {\n double d = 0.0, u;\n\n for (int i = 0; i < x.length; i++) {\n u = x[i] - y[i];\n d += u * u;\n }\n\n return d;\n }",
"public static final String printBookingType(BookingType value)\n {\n return (Integer.toString(value == null ? BookingType.COMMITTED.getValue() : value.getValue()));\n }",
"public void removeMarker(Marker marker) {\n if (markers != null && markers.contains(marker)) {\n markers.remove(marker);\n }\n marker.setMap(null);\n }",
"public SerialMessage getMessage(AlarmType alarmType) {\r\n\t\tlogger.debug(\"Creating new message for application command SENSOR_ALARM_GET for node {}\", this.getNode().getNodeId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.ApplicationCommandHandler, SerialMessage.SerialMessagePriority.Get);\r\n \tbyte[] newPayload = { \t(byte) this.getNode().getNodeId(), \r\n \t\t\t\t\t\t\t3, \r\n\t\t\t\t\t\t\t\t(byte) getCommandClass().getKey(), \r\n\t\t\t\t\t\t\t\t(byte) SENSOR_ALARM_GET,\r\n\t\t\t\t\t\t\t\t(byte) alarmType.getKey() };\r\n \tresult.setMessagePayload(newPayload);\r\n \treturn result;\t\t\r\n\t}",
"public void setKeywords(final List<String> keywords) {\n StringBuilder builder = new StringBuilder();\n for (String keyword: keywords) {\n if (builder.length() > 0) {\n builder.append(',');\n }\n builder.append(keyword.trim());\n }\n this.keywords = Optional.of(builder.toString());\n }",
"public static spilloverpolicy get(nitro_service service, String name) throws Exception{\n\t\tspilloverpolicy obj = new spilloverpolicy();\n\t\tobj.set_name(name);\n\t\tspilloverpolicy response = (spilloverpolicy) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static boolean canUseAsDelayedQueue(final Jedis jedis, final String key) {\n final String type = jedis.type(key);\n return (ZSET.equalsIgnoreCase(type) || NONE.equalsIgnoreCase(type));\n }",
"public void setKey(int keyIndex, float time, final float[] values)\n {\n int index = keyIndex * mFloatsPerKey;\n Integer valSize = mFloatsPerKey-1;\n\n if (values.length != valSize)\n {\n throw new IllegalArgumentException(\"This key needs \" + valSize.toString() + \" float per value\");\n }\n mKeys[index] = time;\n System.arraycopy(values, 0, mKeys, index + 1, values.length);\n }",
"public void setObjectForStatement(PreparedStatement ps, int index,\r\n Object value, int sqlType) throws SQLException\r\n {\r\n if (sqlType == Types.TINYINT)\r\n {\r\n ps.setByte(index, ((Byte) value).byteValue());\r\n }\r\n else\r\n {\r\n super.setObjectForStatement(ps, index, value, sqlType);\r\n }\r\n }"
] |
Shows error dialog, manually supplying details instead of getting them from an exception stack trace.
@param message the error message
@param details the details | [
"public static void showErrorDialog(String message, String details) {\n\n Window window = prepareWindow(DialogWidth.wide);\n window.setCaption(\"Error\");\n window.setContent(new CmsSetupErrorDialog(message, details, null, window));\n A_CmsUI.get().addWindow(window);\n\n }"
] | [
"public <T extends Variable> T lookupVariable(String token) {\n Variable result = variables.get(token);\n return (T)result;\n }",
"protected void propagateOnEnter(GVRPickedObject hit)\n {\n GVRSceneObject hitObject = hit.getHitObject();\n GVREventManager eventManager = getGVRContext().getEventManager();\n if (mEventOptions.contains(EventOptions.SEND_TOUCH_EVENTS))\n {\n if (mEventOptions.contains(EventOptions.SEND_TO_LISTENERS))\n {\n eventManager.sendEvent(this, ITouchEvents.class, \"onEnter\", hitObject, hit);\n }\n if (mEventOptions.contains(EventOptions.SEND_TO_HIT_OBJECT))\n {\n eventManager.sendEvent(hitObject, ITouchEvents.class, \"onEnter\", hitObject, hit);\n }\n if (mEventOptions.contains(EventOptions.SEND_TO_SCENE) && (mScene != null))\n {\n eventManager.sendEvent(mScene, ITouchEvents.class, \"onEnter\", hitObject, hit);\n }\n }\n if (mEventOptions.contains(EventOptions.SEND_PICK_EVENTS))\n {\n if (mEventOptions.contains(EventOptions.SEND_TO_LISTENERS))\n {\n eventManager.sendEvent(this, IPickEvents.class, \"onEnter\", hitObject, hit);\n }\n if (mEventOptions.contains(EventOptions.SEND_TO_HIT_OBJECT))\n {\n eventManager.sendEvent(hitObject, IPickEvents.class, \"onEnter\", hitObject, hit);\n }\n if (mEventOptions.contains(EventOptions.SEND_TO_SCENE) && (mScene != null))\n {\n eventManager.sendEvent(mScene, IPickEvents.class, \"onEnter\", hitObject, hit);\n }\n }\n }",
"public static cachepolicylabel_policybinding_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tcachepolicylabel_policybinding_binding obj = new cachepolicylabel_policybinding_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcachepolicylabel_policybinding_binding response[] = (cachepolicylabel_policybinding_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static <T> String join(Collection<T> col, String delim) {\n StringBuilder sb = new StringBuilder();\n Iterator<T> iter = col.iterator();\n if (iter.hasNext())\n sb.append(iter.next().toString());\n while (iter.hasNext()) {\n sb.append(delim);\n sb.append(iter.next().toString());\n }\n return sb.toString();\n }",
"private void createSimpleCubeSixMeshes(GVRContext gvrContext,\n boolean facingOut, String vertexDesc, ArrayList<GVRTexture> textureList)\n {\n GVRSceneObject[] children = new GVRSceneObject[6];\n GVRMesh[] meshes = new GVRMesh[6];\n GVRVertexBuffer vbuf = new GVRVertexBuffer(gvrContext, vertexDesc, SIMPLE_VERTICES.length / 3);\n\n if (facingOut)\n {\n vbuf.setFloatArray(\"a_position\", SIMPLE_VERTICES, 3, 0);\n vbuf.setFloatArray(\"a_normal\", SIMPLE_OUTWARD_NORMALS, 3, 0);\n vbuf.setFloatArray(\"a_texcoord\", SIMPLE_OUTWARD_TEXCOORDS, 2, 0);\n meshes[0] = createMesh(vbuf, SIMPLE_OUTWARD_FRONT_INDICES);\n meshes[1] = createMesh(vbuf, SIMPLE_OUTWARD_RIGHT_INDICES);\n meshes[2] = createMesh(vbuf, SIMPLE_OUTWARD_BACK_INDICES);\n meshes[3] = createMesh(vbuf, SIMPLE_OUTWARD_LEFT_INDICES);\n meshes[4] = createMesh(vbuf, SIMPLE_OUTWARD_TOP_INDICES);\n meshes[5] = createMesh(vbuf, SIMPLE_OUTWARD_BOTTOM_INDICES);\n }\n else\n {\n vbuf.setFloatArray(\"a_position\", SIMPLE_VERTICES, 3, 0);\n vbuf.setFloatArray(\"a_normal\", SIMPLE_INWARD_NORMALS, 3, 0);\n vbuf.setFloatArray(\"a_texcoord\", SIMPLE_INWARD_TEXCOORDS, 2, 0);\n meshes[0] = createMesh(vbuf, SIMPLE_INWARD_FRONT_INDICES);\n meshes[1] = createMesh(vbuf, SIMPLE_INWARD_RIGHT_INDICES);\n meshes[2] = createMesh(vbuf, SIMPLE_INWARD_BACK_INDICES);\n meshes[3] = createMesh(vbuf, SIMPLE_INWARD_LEFT_INDICES);\n meshes[4] = createMesh(vbuf, SIMPLE_INWARD_TOP_INDICES);\n meshes[5] = createMesh(vbuf, SIMPLE_INWARD_BOTTOM_INDICES);\n }\n\n for (int i = 0; i < 6; i++)\n {\n children[i] = new GVRSceneObject(gvrContext, meshes[i], textureList.get(i));\n addChildObject(children[i]);\n }\n\n // attached an empty renderData for parent object, so that we can set some common properties\n GVRRenderData renderData = new GVRRenderData(gvrContext);\n attachRenderData(renderData);\n }",
"private synchronized void initializeFatClient(String storeName, Properties storeClientProps) {\n // updates the coordinator metadata with recent stores and cluster xml\n updateCoordinatorMetadataWithLatestState();\n\n logger.info(\"Creating a Fat client for store: \" + storeName);\n SocketStoreClientFactory fatClientFactory = getFatClientFactory(this.coordinatorConfig.getBootstrapURLs(),\n storeClientProps);\n\n if(this.fatClientMap == null) {\n this.fatClientMap = new HashMap<String, DynamicTimeoutStoreClient<ByteArray, byte[]>>();\n }\n DynamicTimeoutStoreClient<ByteArray, byte[]> fatClient = new DynamicTimeoutStoreClient<ByteArray, byte[]>(storeName,\n fatClientFactory,\n 1,\n this.coordinatorMetadata.getStoreDefs(),\n this.coordinatorMetadata.getClusterXmlStr());\n this.fatClientMap.put(storeName, fatClient);\n\n }",
"public static <T> Iterator<T> unique(Iterator<T> self) {\n return toList((Iterable<T>) unique(toList(self))).listIterator();\n }",
"public Object moveToNextValue(Object val) throws SQLException {\n\t\tif (dataPersister == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn dataPersister.moveToNextValue(val);\n\t\t}\n\t}",
"public CSTNode get( int index ) \n {\n CSTNode element = null;\n\n if( index < size() ) \n {\n element = (CSTNode)elements.get( index );\n }\n\n return element;\n }"
] |
Use this API to add vlan. | [
"public static base_response add(nitro_service client, vlan resource) throws Exception {\n\t\tvlan addresource = new vlan();\n\t\taddresource.id = resource.id;\n\t\taddresource.aliasname = resource.aliasname;\n\t\taddresource.ipv6dynamicrouting = resource.ipv6dynamicrouting;\n\t\treturn addresource.add_resource(client);\n\t}"
] | [
"public <T extends StatementDocument> void nullEdit(PropertyIdValue propertyId)\n\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tPropertyDocument currentDocument = (PropertyDocument) this.wikibaseDataFetcher\n\t\t\t\t.getEntityDocument(propertyId.getId());\n\t\t\n\t\tnullEdit(currentDocument);\n\t}",
"public List<ServerGroup> getServerGroups() {\n ArrayList<ServerGroup> groups = new ArrayList<ServerGroup>();\n try {\n JSONObject response = new JSONObject(doGet(BASE_SERVERGROUP, null));\n JSONArray serverArray = response.getJSONArray(\"servergroups\");\n\n for (int i = 0; i < serverArray.length(); i++) {\n JSONObject jsonServerGroup = serverArray.getJSONObject(i);\n ServerGroup group = getServerGroupFromJSON(jsonServerGroup);\n groups.add(group);\n }\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return groups;\n }",
"private static JSONArray parseDockers(ArrayList<Point> dockers) throws JSONException {\n if (dockers != null) {\n JSONArray dockersArray = new JSONArray();\n\n for (Point docker : dockers) {\n JSONObject dockerObject = new JSONObject();\n\n dockerObject.put(\"x\",\n docker.getX().doubleValue());\n dockerObject.put(\"y\",\n docker.getY().doubleValue());\n\n dockersArray.put(dockerObject);\n }\n\n return dockersArray;\n }\n\n return new JSONArray();\n }",
"public static aaaparameter get(nitro_service service) throws Exception{\n\t\taaaparameter obj = new aaaparameter();\n\t\taaaparameter[] response = (aaaparameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"private ProjectFile handleZipFile(InputStream stream) throws Exception\n {\n File dir = null;\n\n try\n {\n dir = InputStreamHelper.writeZipStreamToTempDir(stream);\n ProjectFile result = handleDirectory(dir);\n if (result != null)\n {\n return result;\n }\n }\n\n finally\n {\n FileHelper.deleteQuietly(dir);\n }\n\n return null;\n }",
"public static Map<String, String[]> mapUrlEncodedParameters(byte[] dataArray) throws Exception {\n Map<String, String[]> mapPostParameters = new HashMap<String, String[]>();\n\n try {\n ByteArrayOutputStream byteout = new ByteArrayOutputStream();\n for (int x = 0; x < dataArray.length; x++) {\n // split the data up by & to get the parts\n if (dataArray[x] == '&' || x == (dataArray.length - 1)) {\n if (x == (dataArray.length - 1)) {\n byteout.write(dataArray[x]);\n }\n // find '=' and split the data up into key value pairs\n int equalsPos = -1;\n ByteArrayOutputStream key = new ByteArrayOutputStream();\n ByteArrayOutputStream value = new ByteArrayOutputStream();\n byte[] byteArray = byteout.toByteArray();\n for (int xx = 0; xx < byteArray.length; xx++) {\n if (byteArray[xx] == '=') {\n equalsPos = xx;\n } else {\n if (equalsPos == -1) {\n key.write(byteArray[xx]);\n } else {\n value.write(byteArray[xx]);\n }\n }\n }\n\n ArrayList<String> values = new ArrayList<String>();\n\n if (mapPostParameters.containsKey(key.toString())) {\n values = new ArrayList<String>(Arrays.asList(mapPostParameters.get(key.toString())));\n mapPostParameters.remove(key.toString());\n }\n\n values.add(value.toString());\n /**\n * If equalsPos is not -1, then there was a '=' for the key\n * If value.size is 0, then there is no value so want to add in the '='\n * Since it will not be added later like params with keys and valued\n */\n if (equalsPos != -1 && value.size() == 0) {\n key.write((byte) '=');\n }\n\n mapPostParameters.put(key.toString(), values.toArray(new String[values.size()]));\n\n byteout = new ByteArrayOutputStream();\n } else {\n byteout.write(dataArray[x]);\n }\n }\n } catch (Exception e) {\n throw new Exception(\"Could not parse request data: \" + e.getMessage());\n }\n\n return mapPostParameters;\n }",
"private int findYOffsetForGroupLabel(JRDesignBand band) {\n\t\tint offset = 0;\n\t\tfor (JRChild jrChild : band.getChildren()) {\n\t\t\tJRDesignElement elem = (JRDesignElement) jrChild;\n\t\t\tif (elem.getKey() != null && elem.getKey().startsWith(\"variable_for_column_\")) {\n\t\t\t\toffset = elem.getY();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn offset;\n\t}",
"private void setTempoMaster(DeviceUpdate newMaster) {\n DeviceUpdate oldMaster = tempoMaster.getAndSet(newMaster);\n if ((newMaster == null && oldMaster != null) ||\n (newMaster != null && ((oldMaster == null) || !newMaster.getAddress().equals(oldMaster.getAddress())))) {\n // This is a change in master, so report it to any registered listeners\n deliverMasterChangedAnnouncement(newMaster);\n }\n }",
"protected boolean intersect(GVRSceneObject.BoundingVolume bv1, GVRSceneObject.BoundingVolume bv2)\n {\n return (bv1.maxCorner.x >= bv2.minCorner.x) &&\n (bv1.maxCorner.y >= bv2.minCorner.y) &&\n (bv1.maxCorner.z >= bv2.minCorner.z) &&\n (bv1.minCorner.x <= bv2.maxCorner.x) &&\n (bv1.minCorner.y <= bv2.maxCorner.y) &&\n (bv1.minCorner.z <= bv2.maxCorner.z);\n }"
] |
Start a task. The id is needed to end the task
@param id
@param taskName | [
"public void startTask(int id, String taskName) {\n if (isActivated) {\n durations.add(new Duration(id, taskName, BenchmarkUtil.elapsedRealTimeNanos()));\n }\n }"
] | [
"public HashMap<K2, HashMap<K3, V>> get(final K1 firstKey) {\n\t\treturn map.get(firstKey);\n\t}",
"public static void createDirectory(Path dir, String dirDesc)\n {\n try\n {\n Files.createDirectories(dir);\n }\n catch (IOException ex)\n {\n throw new WindupException(\"Error creating \" + dirDesc + \" folder: \" + dir.toString() + \" due to: \" + ex.getMessage(), ex);\n }\n }",
"@Override\n public SuggestAccountsRequest suggestAccounts() throws RestApiException {\n return new SuggestAccountsRequest() {\n @Override\n public List<AccountInfo> get() throws RestApiException {\n return AccountsRestClient.this.suggestAccounts(this);\n }\n };\n }",
"void handleFacebookError(HttpStatus statusCode, FacebookError error) {\n\t\tif (error != null && error.getCode() != null) {\n\t\t\tint code = error.getCode();\n\t\t\t\n\t\t\tif (code == UNKNOWN) {\n\t\t\t\tthrow new UncategorizedApiException(FACEBOOK_PROVIDER_ID, error.getMessage(), null);\n\t\t\t} else if (code == SERVICE) {\n\t\t\t\tthrow new ServerException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == TOO_MANY_CALLS || code == USER_TOO_MANY_CALLS || code == EDIT_FEED_TOO_MANY_USER_CALLS || code == EDIT_FEED_TOO_MANY_USER_ACTION_CALLS) {\n\t\t\t\tthrow new RateLimitExceededException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PERMISSION_DENIED || isUserPermissionError(code)) {\n\t\t\t\tthrow new InsufficientPermissionException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PARAM_SESSION_KEY || code == PARAM_SIGNATURE) {\n\t\t\t\tthrow new InvalidAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN && error.getSubcode() == null) {\n\t\t\t\tthrow new InvalidAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN && error.getSubcode() == 463) {\n\t\t\t\tthrow new ExpiredAuthorizationException(FACEBOOK_PROVIDER_ID);\n\t\t\t} else if (code == PARAM_ACCESS_TOKEN) {\n\t\t\t\tthrow new RevokedAuthorizationException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == MESG_DUPLICATE) { \n\t\t\t\tthrow new DuplicateStatusException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else if (code == DATA_OBJECT_NOT_FOUND || code == PATH_UNKNOWN) {\n\t\t\t\tthrow new ResourceNotFoundException(FACEBOOK_PROVIDER_ID, error.getMessage());\n\t\t\t} else {\n\t\t\t\tthrow new UncategorizedApiException(FACEBOOK_PROVIDER_ID, error.getMessage(), null);\n\t\t\t}\n\t\t}\n\n\t}",
"public IntBuffer getIntVec(String attributeName)\n {\n int size = getAttributeSize(attributeName);\n if (size <= 0)\n {\n return null;\n }\n size *= 4 * getVertexCount();\n ByteBuffer buffer = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());\n IntBuffer data = buffer.asIntBuffer();\n if (!NativeVertexBuffer.getIntVec(getNative(), attributeName, data, 0, 0))\n {\n throw new IllegalArgumentException(\"Attribute name \" + attributeName + \" cannot be accessed\");\n }\n return data;\n }",
"public Stats getPhotoStats(String photoId, Date date) throws FlickrException {\n return getStats(METHOD_GET_PHOTO_STATS, \"photo_id\", photoId, date);\n }",
"public void setConvergence( int maxIterations , double ftol , double gtol ) {\n this.maxIterations = maxIterations;\n this.ftol = ftol;\n this.gtol = gtol;\n }",
"public static void removeColumns( DMatrixRMaj A , int col0 , int col1 )\n {\n if( col1 < col0 ) {\n throw new IllegalArgumentException(\"col1 must be >= col0\");\n } else if( col0 >= A.numCols || col1 >= A.numCols ) {\n throw new IllegalArgumentException(\"Columns which are to be removed must be in bounds\");\n }\n\n int step = col1-col0+1;\n int offset = 0;\n for (int row = 0, idx=0; row < A.numRows; row++) {\n for (int i = 0; i < col0; i++,idx++) {\n A.data[idx] = A.data[idx+offset];\n }\n offset += step;\n for (int i = col1+1; i < A.numCols; i++,idx++) {\n A.data[idx] = A.data[idx+offset];\n }\n }\n A.numCols -= step;\n }",
"public void setTimewarpInt(String timewarp) {\n\n try {\n m_userSettings.setTimeWarp(Long.valueOf(timewarp).longValue());\n } catch (Exception e) {\n m_userSettings.setTimeWarp(-1);\n }\n }"
] |
Converts an image in RGB mode to BINARY mode
@param img image
@param threshold grays cale threshold
@return new MarvinImage instance in BINARY mode | [
"public static MarvinImage rgbToBinary(MarvinImage img, int threshold) {\n MarvinImage resultImage = new MarvinImage(img.getWidth(), img.getHeight(), MarvinImage.COLOR_MODEL_BINARY);\n\n for (int y = 0; y < img.getHeight(); y++) {\n for (int x = 0; x < img.getWidth(); x++) {\n int gray = (int) ((img.getIntComponent0(x, y) * 0.3) + (img.getIntComponent1(x, y) * 0.59) + (img.getIntComponent2(x, y) * 0.11));\n\n if (gray <= threshold) {\n resultImage.setBinaryColor(x, y, true);\n } else {\n resultImage.setBinaryColor(x, y, false);\n }\n }\n }\n return resultImage;\n }"
] | [
"public static void printHelp(final Options options) {\n Collection<Option> c = options.getOptions();\n System.out.println(\"Command line options are:\");\n int longestLongOption = 0;\n for (Option op : c) {\n if (op.getLongOpt().length() > longestLongOption) {\n longestLongOption = op.getLongOpt().length();\n }\n }\n\n longestLongOption += 2;\n String spaces = StringUtils.repeat(\" \", longestLongOption);\n\n for (Option op : c) {\n System.out.print(\"\\t-\" + op.getOpt() + \" --\" + op.getLongOpt());\n if (op.getLongOpt().length() < spaces.length()) {\n System.out.print(spaces.substring(op.getLongOpt().length()));\n } else {\n System.out.print(\" \");\n }\n System.out.println(op.getDescription());\n }\n }",
"public void init(Configuration configuration) {\n if (devMode && reload && !listeningToDispatcher) {\n // this is the only way I found to be able to get added to to\n // ConfigurationProvider list\n // listening to events in Dispatcher\n listeningToDispatcher = true;\n Dispatcher.addDispatcherListener(this);\n }\n }",
"private int findYOffsetForGroupLabel(JRDesignBand band) {\n\t\tint offset = 0;\n\t\tfor (JRChild jrChild : band.getChildren()) {\n\t\t\tJRDesignElement elem = (JRDesignElement) jrChild;\n\t\t\tif (elem.getKey() != null && elem.getKey().startsWith(\"variable_for_column_\")) {\n\t\t\t\toffset = elem.getY();\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn offset;\n\t}",
"public static ZMatrixRMaj hermitian(int length, double min, double max, Random rand) {\n ZMatrixRMaj A = new ZMatrixRMaj(length,length);\n\n fillHermitian(A, min, max, rand);\n\n return A;\n }",
"@Override\n public void deploy(InputStream inputStream) throws IOException {\n final List<? extends HasMetadata> entities = deploy(\"application\", inputStream);\n\n if (this.applicationName == null) {\n\n Optional<String> deploymentConfig = entities.stream()\n .filter(hm -> hm instanceof DeploymentConfig)\n .map(hm -> (DeploymentConfig) hm)\n .map(dc -> dc.getMetadata().getName()).findFirst();\n\n deploymentConfig.ifPresent(name -> this.applicationName = name);\n }\n }",
"public static MapBounds adjustBoundsToScaleAndMapSize(\n final GenericMapAttributeValues mapValues,\n final Rectangle paintArea,\n final MapBounds bounds,\n final double dpi) {\n MapBounds newBounds = bounds;\n if (mapValues.isUseNearestScale()) {\n newBounds = newBounds.adjustBoundsToNearestScale(\n mapValues.getZoomLevels(),\n mapValues.getZoomSnapTolerance(),\n mapValues.getZoomLevelSnapStrategy(),\n mapValues.getZoomSnapGeodetic(),\n paintArea, dpi);\n }\n\n newBounds = new BBoxMapBounds(newBounds.toReferencedEnvelope(paintArea));\n\n if (mapValues.isUseAdjustBounds()) {\n newBounds = newBounds.adjustedEnvelope(paintArea);\n }\n return newBounds;\n }",
"public static sslservice[] get(nitro_service service) throws Exception{\n\t\tsslservice obj = new sslservice();\n\t\tsslservice[] response = (sslservice[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private String addPathProperty(final List<String> command, final String typeName, final String propertyName, final Map<String, String> properties, final DirectoryGrouping directoryGrouping,\n final File typeDir, File serverDir) {\n final String result;\n final String value = properties.get(propertyName);\n if (value == null) {\n switch (directoryGrouping) {\n case BY_TYPE:\n result = getAbsolutePath(typeDir, \"servers\", serverName);\n break;\n case BY_SERVER:\n default:\n result = getAbsolutePath(serverDir, typeName);\n break;\n }\n properties.put(propertyName, result);\n } else {\n final File dir = new File(value);\n switch (directoryGrouping) {\n case BY_TYPE:\n result = getAbsolutePath(dir, \"servers\", serverName);\n break;\n case BY_SERVER:\n default:\n result = getAbsolutePath(dir, serverName);\n break;\n }\n }\n command.add(String.format(\"-D%s=%s\", propertyName, result));\n return result;\n }",
"@Override\n public ModelNode resolveValue(ExpressionResolver resolver, ModelNode value) throws OperationFailedException {\n\n // Pass non-LIST values through the superclass so it can reject weird values and, in the odd chance\n // that's how this object is set up, turn undefined into a default list value.\n ModelNode superResult = value.getType() == ModelType.LIST ? value : super.resolveValue(resolver, value);\n\n // If it's not a LIST (almost certainly UNDEFINED), then nothing more we can do\n if (superResult.getType() != ModelType.LIST) {\n return superResult;\n }\n // Resolve each element.\n // Don't mess with the original value\n ModelNode clone = superResult == value ? value.clone() : superResult;\n ModelNode result = new ModelNode();\n result.setEmptyList();\n for (ModelNode element : clone.asList()) {\n result.add(valueType.resolveValue(resolver, element));\n }\n // Validate the entire list\n getValidator().validateParameter(getName(), result);\n return result;\n }"
] |
Read a four byte integer from the data.
@param offset current offset into data block
@param data data block
@return int value | [
"public int readInt(int offset, byte[] data)\n {\n int result = 0;\n int i = offset + m_offset;\n for (int shiftBy = 0; shiftBy < 32; shiftBy += 8)\n {\n result |= ((data[i] & 0xff)) << shiftBy;\n ++i;\n }\n return result;\n }"
] | [
"public static Span toSpan(Range range) {\n return new Span(toRowColumn(range.getStartKey()), range.isStartKeyInclusive(),\n toRowColumn(range.getEndKey()), range.isEndKeyInclusive());\n }",
"public GenericCriteria process(ProjectProperties properties, byte[] data, int dataOffset, int entryOffset, List<GenericCriteriaPrompt> prompts, List<FieldType> fields, boolean[] criteriaType)\n {\n m_properties = properties;\n m_prompts = prompts;\n m_fields = fields;\n m_criteriaType = criteriaType;\n m_dataOffset = dataOffset;\n if (m_criteriaType != null)\n {\n m_criteriaType[0] = true;\n m_criteriaType[1] = true;\n }\n\n m_criteriaBlockMap.clear();\n\n m_criteriaData = data;\n m_criteriaTextStart = MPPUtility.getShort(m_criteriaData, m_dataOffset + getCriteriaTextStartOffset());\n\n //\n // Populate the map\n //\n int criteriaStartOffset = getCriteriaStartOffset();\n int criteriaBlockSize = getCriteriaBlockSize();\n\n //System.out.println();\n //System.out.println(ByteArrayHelper.hexdump(data, dataOffset, criteriaStartOffset, false));\n\n if (m_criteriaData.length <= m_criteriaTextStart)\n {\n return null; // bad data\n }\n\n while (criteriaStartOffset + criteriaBlockSize <= m_criteriaTextStart)\n {\n byte[] block = new byte[criteriaBlockSize];\n System.arraycopy(m_criteriaData, m_dataOffset + criteriaStartOffset, block, 0, criteriaBlockSize);\n m_criteriaBlockMap.put(Integer.valueOf(criteriaStartOffset), block);\n //System.out.println(Integer.toHexString(criteriaStartOffset) + \": \" + ByteArrayHelper.hexdump(block, false));\n criteriaStartOffset += criteriaBlockSize;\n }\n\n if (entryOffset == -1)\n {\n entryOffset = getCriteriaStartOffset();\n }\n\n List<GenericCriteria> list = new LinkedList<GenericCriteria>();\n processBlock(list, m_criteriaBlockMap.get(Integer.valueOf(entryOffset)));\n GenericCriteria criteria;\n if (list.isEmpty())\n {\n criteria = null;\n }\n else\n {\n criteria = list.get(0);\n }\n return criteria;\n }",
"private int getCostRateTableEntryIndex(Date date)\n {\n int result = -1;\n\n CostRateTable table = getCostRateTable();\n if (table != null)\n {\n if (table.size() == 1)\n {\n result = 0;\n }\n else\n {\n result = table.getIndexByDate(date);\n }\n }\n\n return result;\n }",
"public static double J(int n, double x) {\r\n int j, m;\r\n double ax, bj, bjm, bjp, sum, tox, ans;\r\n boolean jsum;\r\n\r\n double ACC = 40.0;\r\n double BIGNO = 1.0e+10;\r\n double BIGNI = 1.0e-10;\r\n\r\n if (n == 0) return J0(x);\r\n if (n == 1) return J(x);\r\n\r\n ax = Math.abs(x);\r\n if (ax == 0.0) return 0.0;\r\n else if (ax > (double) n) {\r\n tox = 2.0 / ax;\r\n bjm = J0(ax);\r\n bj = J(ax);\r\n for (j = 1; j < n; j++) {\r\n bjp = j * tox * bj - bjm;\r\n bjm = bj;\r\n bj = bjp;\r\n }\r\n ans = bj;\r\n } else {\r\n tox = 2.0 / ax;\r\n m = 2 * ((n + (int) Math.sqrt(ACC * n)) / 2);\r\n jsum = false;\r\n bjp = ans = sum = 0.0;\r\n bj = 1.0;\r\n for (j = m; j > 0; j--) {\r\n bjm = j * tox * bj - bjp;\r\n bjp = bj;\r\n bj = bjm;\r\n if (Math.abs(bj) > BIGNO) {\r\n bj *= BIGNI;\r\n bjp *= BIGNI;\r\n ans *= BIGNI;\r\n sum *= BIGNI;\r\n }\r\n if (jsum) sum += bj;\r\n jsum = !jsum;\r\n if (j == n) ans = bjp;\r\n }\r\n sum = 2.0 * sum - bj;\r\n ans /= sum;\r\n }\r\n\r\n return x < 0.0 && n % 2 == 1 ? -ans : ans;\r\n }",
"public static String getStringOption(Map<String, String> configOptions, String optionKey, String defaultValue) {\n\n String result = configOptions.get(optionKey);\n return null != result ? result : defaultValue;\n }",
"public boolean handleKeyDeletion(final String key) {\n\n if (m_keyset.getKeySet().contains(key)) {\n if (removeKeyForAllLanguages(key)) {\n m_keyset.removeKey(key);\n return true;\n } else {\n return false;\n }\n }\n return true;\n }",
"public static base_responses delete(nitro_service client, String acl6name[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (acl6name != null && acl6name.length > 0) {\n\t\t\tnsacl6 deleteresources[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++){\n\t\t\t\tdeleteresources[i] = new nsacl6();\n\t\t\t\tdeleteresources[i].acl6name = acl6name[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher cancelPendingRequests() {\n if (pendingRequests.size() != 0) {\n for (int i = 0; i < pendingRequests.size(); i++) {\n int reqId = pendingRequests.keyAt(i);\n Request r = pendingRequests.valueAt(i);\n if (!r.isFinished() && !r.isCancelled()) {\n cancelRequest(r, reqId);\n }\n }\n }\n return this;\n }",
"public static ProxyMetaClass getInstance(Class theClass) throws IntrospectionException {\n MetaClassRegistry metaRegistry = GroovySystem.getMetaClassRegistry();\n MetaClass meta = metaRegistry.getMetaClass(theClass);\n return new ProxyMetaClass(metaRegistry, theClass, meta);\n }"
] |
Checks that the data starting at startLocRecord looks like a local file record header.
@param channel the channel
@param startLocRecord offset into channel of the start of the local record
@param compressedSize expected compressed size of the file, or -1 to indicate this isn't known | [
"private static boolean validateLocalFileRecord(FileChannel channel, long startLocRecord, long compressedSize) throws IOException {\n\n ByteBuffer lfhBuffer = getByteBuffer(LOCLEN);\n read(lfhBuffer, channel, startLocRecord);\n if (lfhBuffer.limit() < LOCLEN || getUnsignedInt(lfhBuffer, 0) != LOCSIG) {\n return false;\n }\n\n if (compressedSize == -1) {\n // We can't further evaluate\n return true;\n }\n\n int fnLen = getUnsignedShort(lfhBuffer, LOC_FILENAMELEN);\n int extFieldLen = getUnsignedShort(lfhBuffer, LOC_EXTFLDLEN);\n long nextSigPos = startLocRecord + LOCLEN + compressedSize + fnLen + extFieldLen;\n\n read(lfhBuffer, channel, nextSigPos);\n long header = getUnsignedInt(lfhBuffer, 0);\n return header == LOCSIG || header == EXTSIG || header == CENSIG;\n }"
] | [
"@Override\n public void put(ByteArray keyBytes, Versioned<byte[]> valueBytes, byte[] transforms)\n throws VoldemortException {\n // acquire write lock\n writeLock.lock();\n try {\n String key = ByteUtils.getString(keyBytes.get(), \"UTF-8\");\n Versioned<String> value = new Versioned<String>(ByteUtils.getString(valueBytes.getValue(),\n \"UTF-8\"),\n valueBytes.getVersion());\n\n Versioned<Object> valueObject = convertStringToObject(key, value);\n\n this.put(key, valueObject);\n } finally {\n writeLock.unlock();\n }\n }",
"public StatementGroup findStatementGroup(String propertyIdValue) {\n\t\tif (this.claims.containsKey(propertyIdValue)) {\n\t\t\treturn new StatementGroupImpl(this.claims.get(propertyIdValue));\n\t\t}\n\t\treturn null;\n\t}",
"public static void scanClassPathForFormattingAnnotations() {\n\n\t\tExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);\n\n\t\t// scan classpath and filter out classes that don't begin with \"com.nds\"\n\t\tReflections reflections = new Reflections(\"com.nds\",\"com.cisco\");\n\n\t\tSet<Class<?>> annotated = reflections.getTypesAnnotatedWith(DefaultFormat.class);\n\n// Reflections ciscoReflections = new Reflections(\"com.cisco\");\n//\n// annotated.addAll(ciscoReflections.getTypesAnnotatedWith(DefaultFormat.class));\n\n\t\tfor (Class<?> markerClass : annotated) {\n\n\t\t\t// if the marker class is indeed implementing FoundationLoggingMarker\n\t\t\t// interface\n\t\t\tif (FoundationLoggingMarker.class.isAssignableFrom(markerClass)) {\n\n\t\t\t\tfinal Class<? extends FoundationLoggingMarker> clazz = (Class<? extends FoundationLoggingMarker>) markerClass;\n\n\t\t\t\texecutorService.execute(new Runnable() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void run() {\n\n\t\t\t\t\t\tif (markersMap.get(clazz) == null) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t// generate formatter class for this marker\n\t\t\t\t\t\t\t\t// class\n\t\t\t\t\t\t\t\tgenerateAndUpdateFormatterInMap(clazz);\n\t\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\t\tLOGGER.trace(\"problem generating formatter class from static scan method. error is: \" + e.toString());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t} else {// if marker class does not implement FoundationLoggingMarker\n\t\t\t\t\t// interface, log ERROR\n\n\t\t\t\t// verify the LOGGER was initialized. It might not be as this\n\t\t\t\t// Method is called in a static block\n\t\t\t\tif (LOGGER == null) {\n\t\t\t\t\tLOGGER = LoggerFactory.getLogger(AbstractFoundationLoggingMarker.class);\n\t\t\t\t}\n\t\t\t\tLOGGER.error(\"Formatter annotations should only appear on foundationLoggingMarker implementations\");\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tTimeUnit.SECONDS.sleep(30);\n\t\t} catch (InterruptedException e) {\n\t\t\tLOGGER.trace(e.toString(), e);\n\t\t}\n\t\texecutorService.shutdown();\n\t\t// try {\n\t\t// executorService.awaitTermination(15, TimeUnit.SECONDS);\n\t\t// } catch (InterruptedException e) {\n\t\t// LOGGER.error(\"creation of formatters has been interrupted\");\n\t\t// }\n\t}",
"public void createRelationFieldMap(Props props)\n {\n byte[] fieldMapData = null;\n for (Integer key : RELATION_KEYS)\n {\n fieldMapData = props.getByteArray(key);\n if (fieldMapData != null)\n {\n break;\n }\n }\n\n if (fieldMapData == null)\n {\n populateDefaultData(getDefaultRelationData());\n }\n else\n {\n createFieldMap(fieldMapData);\n }\n }",
"public static final PhotoList<Photo> createPhotoList(Element photosElement) {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n photos.setPage(photosElement.getAttribute(\"page\"));\r\n photos.setPages(photosElement.getAttribute(\"pages\"));\r\n photos.setPerPage(photosElement.getAttribute(\"perpage\"));\r\n photos.setTotal(photosElement.getAttribute(\"total\"));\r\n\r\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }",
"public CollectionRequest<Team> findByOrganization(String organization) {\n \n String path = String.format(\"/organizations/%s/teams\", organization);\n return new CollectionRequest<Team>(this, Team.class, path, \"GET\");\n }",
"public static long count(nitro_service service, String id) throws Exception{\n\t\tlinkset_interface_binding obj = new linkset_interface_binding();\n\t\tobj.set_id(id);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tlinkset_interface_binding response[] = (linkset_interface_binding[]) obj.get_resources(service,option);\n\t\tif (response != null) {\n\t\t\treturn response[0].__count;\n\t\t}\n\t\treturn 0;\n\t}",
"void setParent(ProjectCalendarWeek parent)\n {\n m_parent = parent;\n\n for (int loop = 0; loop < m_days.length; loop++)\n {\n if (m_days[loop] == null)\n {\n m_days[loop] = DayType.DEFAULT;\n }\n }\n }",
"private String formatPriority(Priority value)\n {\n String result = null;\n\n if (value != null)\n {\n String[] priorityTypes = LocaleData.getStringArray(m_locale, LocaleData.PRIORITY_TYPES);\n int priority = value.getValue();\n if (priority < Priority.LOWEST)\n {\n priority = Priority.LOWEST;\n }\n else\n {\n if (priority > Priority.DO_NOT_LEVEL)\n {\n priority = Priority.DO_NOT_LEVEL;\n }\n }\n\n priority /= 100;\n\n result = priorityTypes[priority - 1];\n }\n\n return (result);\n }"
] |
Returns angle in degrees between two points
@param ax x of the point 1
@param ay y of the point 1
@param bx x of the point 2
@param by y of the point 2
@return angle in degrees between two points | [
"private static float angleDeg(final float ax, final float ay,\n final float bx, final float by) {\n final double angleRad = Math.atan2(ay - by, ax - bx);\n double angle = Math.toDegrees(angleRad);\n if (angleRad < 0) {\n angle += 360;\n }\n return (float) angle;\n }"
] | [
"public final void cancelOld(\n final long starttimeThreshold, final long checkTimeThreshold, final String message) {\n final CriteriaBuilder builder = getSession().getCriteriaBuilder();\n final CriteriaUpdate<PrintJobStatusExtImpl> update =\n builder.createCriteriaUpdate(PrintJobStatusExtImpl.class);\n final Root<PrintJobStatusExtImpl> root = update.from(PrintJobStatusExtImpl.class);\n update.where(builder.and(\n builder.equal(root.get(\"status\"), PrintJobStatus.Status.WAITING),\n builder.or(\n builder.lessThan(root.get(\"entry\").get(\"startTime\"), starttimeThreshold),\n builder.and(builder.isNotNull(root.get(\"lastCheckTime\")),\n builder.lessThan(root.get(\"lastCheckTime\"), checkTimeThreshold))\n )\n ));\n update.set(root.get(\"status\"), PrintJobStatus.Status.CANCELLED);\n update.set(root.get(\"error\"), message);\n getSession().createQuery(update).executeUpdate();\n }",
"public Bundler put(String key, String value) {\n delegate.putString(key, value);\n return this;\n }",
"public final void error(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.ERROR, pObject, null);\r\n\t}",
"private JarFile loadJar(File archive) throws DecompilationException\n {\n try\n {\n return new JarFile(archive);\n }\n catch (IOException ex)\n {\n throw new DecompilationException(\"Can't load .jar: \" + archive.getPath(), ex);\n }\n }",
"private static <T, ID> MappedDeleteCollection<T, ID> build(Dao<T, ID> dao, TableInfo<T, ID> tableInfo, int dataSize)\n\t\t\tthrows SQLException {\n\t\tFieldType idField = tableInfo.getIdField();\n\t\tif (idField == null) {\n\t\t\tthrow new SQLException(\n\t\t\t\t\t\"Cannot delete \" + tableInfo.getDataClass() + \" because it doesn't have an id field defined\");\n\t\t}\n\t\tStringBuilder sb = new StringBuilder(128);\n\t\tDatabaseType databaseType = dao.getConnectionSource().getDatabaseType();\n\t\tappendTableName(databaseType, sb, \"DELETE FROM \", tableInfo.getTableName());\n\t\tFieldType[] argFieldTypes = new FieldType[dataSize];\n\t\tappendWhereIds(databaseType, idField, sb, dataSize, argFieldTypes);\n\t\treturn new MappedDeleteCollection<T, ID>(dao, tableInfo, sb.toString(), argFieldTypes);\n\t}",
"public ClassNode addInterface(String name) {\n ClassNode intf = infoBase.node(name);\n addInterface(intf);\n return this;\n }",
"public static boolean any(Object self, Closure closure) {\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {\n if (bcw.call(iter.next())) return true;\n }\n return false;\n }",
"private void addClass(URLClassLoader loader, JarEntry jarEntry, XMLStreamWriter writer, boolean mapClassMethods) throws ClassNotFoundException, XMLStreamException, IntrospectionException\n {\n String className = jarEntry.getName().replaceAll(\"\\\\.class\", \"\").replaceAll(\"/\", \".\");\n writer.writeStartElement(\"class\");\n writer.writeAttribute(\"name\", className);\n\n Set<Method> methodSet = new HashSet<Method>();\n Class<?> aClass = loader.loadClass(className);\n\n processProperties(writer, methodSet, aClass);\n\n if (mapClassMethods && !Modifier.isInterface(aClass.getModifiers()))\n {\n processClassMethods(writer, aClass, methodSet);\n }\n writer.writeEndElement();\n }",
"public void addStep(String name, String robot, Map<String, Object> options){\n steps.addStep(name, robot, options);\n }"
] |
Removes the given service provider factory from the set of
providers for the service.
@param serviceName
The fully qualified name of the service interface.
@param factory
A factory for creating a specific type of service
provider. May be <tt>null</tt> in which case this
method does nothing.
@throws IllegalArgumentException if serviceName is <tt>null</tt> | [
"public static synchronized void unregister(final String serviceName,\n final Callable<Class< ? >> factory) {\n if ( serviceName == null ) {\n throw new IllegalArgumentException( \"serviceName cannot be null\" );\n }\n if ( factories != null ) {\n List<Callable<Class< ? >>> l = factories.get( serviceName );\n if ( l != null ) {\n l.remove( factory );\n }\n }\n }"
] | [
"public String getRealm() {\n if (UNDEFINED.equals(realm)) {\n Principal principal = securityIdentity.getPrincipal();\n String realm = null;\n if (principal instanceof RealmPrincipal) {\n realm = ((RealmPrincipal)principal).getRealm();\n }\n this.realm = realm;\n\n }\n\n return this.realm;\n }",
"private List<String> processAllListeners(View rootView) {\n List<String> refinementAttributes = new ArrayList<>();\n\n // Register any AlgoliaResultsListener (unless it has a different variant than searcher)\n final List<AlgoliaResultsListener> resultListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaResultsListener.class);\n if (resultListeners.isEmpty()) {\n throw new IllegalStateException(Errors.LAYOUT_MISSING_RESULT_LISTENER);\n }\n for (AlgoliaResultsListener listener : resultListeners) {\n if (!this.resultListeners.contains(listener)) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n this.resultListeners.add(listener);\n searcher.registerResultListener(listener);\n prepareWidget(listener, refinementAttributes);\n }\n }\n }\n\n // Register any AlgoliaErrorListener (unless it has a different variant than searcher)\n final List<AlgoliaErrorListener> errorListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaErrorListener.class);\n for (AlgoliaErrorListener listener : errorListeners) {\n if (!this.errorListeners.contains(listener)) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n this.errorListeners.add(listener);\n }\n }\n searcher.registerErrorListener(listener);\n prepareWidget(listener, refinementAttributes);\n }\n\n // Register any AlgoliaSearcherListener (unless it has a different variant than searcher)\n final List<AlgoliaSearcherListener> searcherListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaSearcherListener.class);\n for (AlgoliaSearcherListener listener : searcherListeners) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n listener.initWithSearcher(searcher);\n prepareWidget(listener, refinementAttributes);\n }\n }\n\n return refinementAttributes;\n }",
"private Object getConstantValue(FieldType type, byte[] block)\n {\n Object value;\n DataType dataType = type.getDataType();\n\n if (dataType == null)\n {\n value = null;\n }\n else\n {\n switch (dataType)\n {\n case DURATION:\n {\n value = MPPUtility.getAdjustedDuration(m_properties, MPPUtility.getInt(block, getValueOffset()), MPPUtility.getDurationTimeUnits(MPPUtility.getShort(block, getTimeUnitsOffset())));\n break;\n }\n\n case NUMERIC:\n {\n value = Double.valueOf(MPPUtility.getDouble(block, getValueOffset()));\n break;\n }\n\n case PERCENTAGE:\n {\n value = Double.valueOf(MPPUtility.getShort(block, getValueOffset()));\n break;\n }\n\n case CURRENCY:\n {\n value = Double.valueOf(MPPUtility.getDouble(block, getValueOffset()) / 100);\n break;\n }\n\n case STRING:\n {\n int textOffset = getTextOffset(block);\n value = MPPUtility.getUnicodeString(m_criteriaData, m_dataOffset + m_criteriaTextStart + textOffset);\n break;\n }\n\n case BOOLEAN:\n {\n int intValue = MPPUtility.getShort(block, getValueOffset());\n value = (intValue == 1 ? Boolean.TRUE : Boolean.FALSE);\n break;\n }\n\n case DATE:\n {\n value = MPPUtility.getTimestamp(block, getValueOffset());\n break;\n }\n\n default:\n {\n value = null;\n break;\n }\n }\n }\n\n return value;\n }",
"public @Nullable ChangeEvent<BsonDocument> getUnprocessedEventForDocumentId(\n final BsonValue documentId\n ) {\n final ChangeEvent<BsonDocument> event;\n nsLock.readLock().lock();\n try {\n event = this.events.get(documentId);\n } finally {\n nsLock.readLock().unlock();\n }\n\n nsLock.writeLock().lock();\n try {\n this.events.remove(documentId);\n return event;\n } finally {\n nsLock.writeLock().unlock();\n }\n }",
"private void populateRecurringException(ProjectCalendarException mpxjException, Exceptions.Exception xmlException)\n {\n RecurringData data = mpxjException.getRecurring();\n xmlException.setEnteredByOccurrences(Boolean.TRUE);\n xmlException.setOccurrences(NumberHelper.getBigInteger(data.getOccurrences()));\n\n switch (data.getRecurrenceType())\n {\n case DAILY:\n {\n xmlException.setType(BigInteger.valueOf(7));\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n break;\n }\n\n case WEEKLY:\n {\n xmlException.setType(BigInteger.valueOf(6));\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n xmlException.setDaysOfWeek(getDaysOfTheWeek(data));\n break;\n }\n\n case MONTHLY:\n {\n xmlException.setPeriod(NumberHelper.getBigInteger(data.getFrequency()));\n if (data.getRelative())\n {\n xmlException.setType(BigInteger.valueOf(5));\n xmlException.setMonthItem(BigInteger.valueOf(data.getDayOfWeek().getValue() + 2));\n xmlException.setMonthPosition(BigInteger.valueOf(NumberHelper.getInt(data.getDayNumber()) - 1));\n }\n else\n {\n xmlException.setType(BigInteger.valueOf(4));\n xmlException.setMonthDay(NumberHelper.getBigInteger(data.getDayNumber()));\n }\n break;\n }\n\n case YEARLY:\n {\n xmlException.setMonth(BigInteger.valueOf(NumberHelper.getInt(data.getMonthNumber()) - 1));\n if (data.getRelative())\n {\n xmlException.setType(BigInteger.valueOf(3));\n xmlException.setMonthItem(BigInteger.valueOf(data.getDayOfWeek().getValue() + 2));\n xmlException.setMonthPosition(BigInteger.valueOf(NumberHelper.getInt(data.getDayNumber()) - 1));\n }\n else\n {\n xmlException.setType(BigInteger.valueOf(2));\n xmlException.setMonthDay(NumberHelper.getBigInteger(data.getDayNumber()));\n }\n }\n }\n }",
"AlbumArt getArtwork(int artworkId, SlotReference slot, CdjStatus.TrackType trackType, Client client)\n throws IOException {\n\n // Send the artwork request\n Message response = client.simpleRequest(Message.KnownType.ALBUM_ART_REQ, Message.KnownType.ALBUM_ART,\n client.buildRMST(Message.MenuIdentifier.DATA, slot.slot, trackType), new NumberField((long)artworkId));\n\n // Create an image from the response bytes\n return new AlbumArt(new DataReference(slot, artworkId), ((BinaryField)response.arguments.get(3)).getValue());\n }",
"public ClassDescriptor getSuperClassDescriptor()\r\n {\r\n if (!m_superCldSet)\r\n {\r\n if(getBaseClass() != null)\r\n {\r\n m_superCld = getRepository().getDescriptorFor(getBaseClass());\r\n if(m_superCld.isAbstract() || m_superCld.isInterface())\r\n {\r\n throw new MetadataException(\"Super class mapping only work for real class, but declared super class\" +\r\n \" is an interface or is abstract. Declared class: \" + m_superCld.getClassNameOfObject());\r\n }\r\n }\r\n m_superCldSet = true;\r\n }\r\n\r\n return m_superCld;\r\n }",
"private void validateArguments() throws BuildException {\n Path tempDir = getTempDir();\n\n if (tempDir == null) {\n throw new BuildException(\"Temporary directory cannot be null.\");\n }\n \n if (Files.exists(tempDir)) {\n if (!Files.isDirectory(tempDir)) {\n throw new BuildException(\"Temporary directory is not a folder: \" + tempDir.toAbsolutePath());\n }\n } else {\n try {\n Files.createDirectories(tempDir);\n } catch (IOException e) {\n throw new BuildException(\"Failed to create temporary folder: \" + tempDir, e);\n }\n }\n }",
"protected String sendRequestToDF(String df_service, Object msgContent) {\n\n IDFComponentDescription[] receivers = getReceivers(df_service);\n if (receivers.length > 0) {\n IMessageEvent mevent = createMessageEvent(\"send_request\");\n mevent.getParameter(SFipa.CONTENT).setValue(msgContent);\n for (int i = 0; i < receivers.length; i++) {\n mevent.getParameterSet(SFipa.RECEIVERS).addValue(\n receivers[i].getName());\n logger.info(\"The receiver is \" + receivers[i].getName());\n }\n sendMessage(mevent);\n }\n logger.info(\"Message sended to \" + df_service + \" to \"\n + receivers.length + \" receivers\");\n return (\"Message sended to \" + df_service);\n }"
] |
init database with demo data | [
"@PostConstruct\n public void initDatabase() {\n MongoDBInit.LOGGER.info(\"initializing MongoDB\");\n String dbName = System.getProperty(\"mongodb.name\");\n if (dbName == null) {\n throw new RuntimeException(\"Missing database name; Set system property 'mongodb.name'\");\n }\n MongoDatabase db = this.mongo.getDatabase(dbName);\n\n try {\n PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();\n Resource[] resources = resolver.getResources(\"classpath*:mongodb/*.ndjson\");\n MongoDBInit.LOGGER.info(\"Scanning for collection data\");\n for (Resource res : resources) {\n String filename = res.getFilename();\n String collection = filename.substring(0, filename.length() - 7);\n MongoDBInit.LOGGER.info(\"Found collection file: {}\", collection);\n MongoCollection<DBObject> dbCollection = db.getCollection(collection, DBObject.class);\n try (Scanner scan = new Scanner(res.getInputStream(), \"UTF-8\")) {\n int lines = 0;\n while (scan.hasNextLine()) {\n String json = scan.nextLine();\n Object parse = JSON.parse(json);\n if (parse instanceof DBObject) {\n DBObject dbObject = (DBObject) parse;\n dbCollection.insertOne(dbObject);\n } else {\n MongoDBInit.LOGGER.error(\"Invalid object found: {}\", parse);\n throw new RuntimeException(\"Invalid object\");\n }\n lines++;\n }\n MongoDBInit.LOGGER.info(\"Imported {} objects into collection {}\", lines, collection);\n }\n }\n } catch (IOException e) {\n throw new RuntimeException(\"Error importing objects\", e);\n }\n }"
] | [
"public String renameApp(String appName, String newName) {\n return connection.execute(new AppRename(appName, newName), apiKey).getName();\n }",
"protected DirectiveStatement parseDirectiveStatement(DirectiveStContext node)\r\n\t{\r\n\t\tDirectiveStContext stContext = (DirectiveStContext) node;\r\n\t\tDirectiveExpContext direExp = stContext.directiveExp();\r\n\t\tToken token = direExp.Identifier().getSymbol();\r\n\t\tString directive = token.getText().toLowerCase().intern();\r\n\t\tTerminalNode value = direExp.StringLiteral();\r\n\t\tList<TerminalNode> idNodeList = null;\r\n\t\tDirectiveExpIDListContext directExpidLisCtx = direExp.directiveExpIDList();\r\n\t\tif (directExpidLisCtx != null)\r\n\t\t{\r\n\t\t\tidNodeList = directExpidLisCtx.Identifier();\r\n\t\t}\r\n\r\n\t\tSet<String> idList = null;\r\n\t\tDirectiveStatement ds = null;\r\n\r\n\t\tif (value != null)\r\n\t\t{\r\n\t\t\tString idListValue = this.getStringValue(value.getText());\r\n\t\t\tidList = new HashSet(Arrays.asList(idListValue.split(\",\")));\r\n\t\t\tds = new DirectiveStatement(directive, idList, this.getBTToken(token));\r\n\r\n\t\t}\r\n\t\telse if (idNodeList != null)\r\n\t\t{\r\n\t\t\tidList = new HashSet<String>();\r\n\t\t\tfor (TerminalNode t : idNodeList)\r\n\t\t\t{\r\n\t\t\t\tidList.add(t.getText());\r\n\t\t\t}\r\n\t\t\tds = new DirectiveStatement(directive, idList, this.getBTToken(token));\r\n\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tds = new DirectiveStatement(directive, Collections.EMPTY_SET, this.getBTToken(token));\r\n\t\t}\r\n\r\n\t\tif (directive.equals(\"dynamic\"))\r\n\t\t{\r\n\r\n\t\t\tif (ds.getIdList().size() == 0)\r\n\t\t\t{\r\n\t\t\t\tdata.allDynamic = true;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tdata.dynamicObjectSet = ds.getIdList();\r\n\t\t\t}\r\n\t\t\tds = new DirectiveStatement(directive, Collections.EMPTY_SET, this.getBTToken(token));\r\n\t\t\t\r\n\t\t\treturn ds;\r\n\r\n\t\t}\r\n\t\telse if (directive.equalsIgnoreCase(\"safe_output_open\".intern()))\r\n\t\t{\r\n\t\t\tthis.pbCtx.isSafeOutput = true;\r\n\t\t\treturn ds;\r\n\t\t}\r\n\t\telse if (directive.equalsIgnoreCase(\"safe_output_close\".intern()))\r\n\t\t{\r\n\t\t\tthis.pbCtx.isSafeOutput = false;\r\n\t\t\treturn ds;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\treturn ds;\r\n\t\t}\r\n\t}",
"@VisibleForTesting\n protected static double getNearestNiceValue(\n final double value, final DistanceUnit scaleUnit, final boolean lockUnits) {\n DistanceUnit bestUnit = bestUnit(scaleUnit, value, lockUnits);\n double factor = scaleUnit.convertTo(1.0, bestUnit);\n\n // nearest power of 10 lower than value\n int digits = (int) Math.floor((Math.log(value * factor) / Math.log(10)));\n double pow10 = Math.pow(10, digits);\n\n // ok, find first character\n double firstChar = value * factor / pow10;\n\n // right, put it into the correct bracket\n int barLen;\n if (firstChar >= 10.0) {\n barLen = 10;\n } else if (firstChar >= 5.0) {\n barLen = 5;\n } else if (firstChar >= 2.0) {\n barLen = 2;\n } else {\n barLen = 1;\n }\n\n // scale it up the correct power of 10\n return barLen * pow10 / factor;\n }",
"public void init(Configuration configuration) {\n if (devMode && reload && !listeningToDispatcher) {\n // this is the only way I found to be able to get added to to\n // ConfigurationProvider list\n // listening to events in Dispatcher\n listeningToDispatcher = true;\n Dispatcher.addDispatcherListener(this);\n }\n }",
"protected Declaration createDeclaration(String property, Term<?> term)\n {\n Declaration d = CSSFactory.getRuleFactory().createDeclaration();\n d.unlock();\n d.setProperty(property);\n d.add(term);\n return d;\n }",
"public static Double checkLatitude(String name, Double latitude) {\n if (latitude == null) {\n throw new IndexException(\"{} required\", name);\n } else if (latitude < MIN_LATITUDE || latitude > MAX_LATITUDE) {\n throw new IndexException(\"{} must be in range [{}, {}], but found {}\",\n name,\n MIN_LATITUDE,\n MAX_LATITUDE,\n latitude);\n }\n return latitude;\n }",
"public MACAddress toEUI64(boolean asMAC) {\r\n\t\tif(!isExtended()) {//getSegmentCount() == EXTENDED_UNIQUE_IDENTIFIER_48_SEGMENT_COUNT\r\n\t\t\tMACAddressCreator creator = getAddressCreator();\r\n\t\t\tMACAddressSegment segs[] = creator.createSegmentArray(EXTENDED_UNIQUE_IDENTIFIER_64_SEGMENT_COUNT);\r\n\t\t\tMACAddressSection section = getSection();\r\n\t\t\tsection.getSegments(0, 3, segs, 0);\r\n\t\t\tMACAddressSegment ffSegment = creator.createSegment(0xff);\r\n\t\t\tsegs[3] = ffSegment;\r\n\t\t\tsegs[4] = asMAC ? ffSegment : creator.createSegment(0xfe);\r\n\t\t\tsection.getSegments(3, 6, segs, 5);\r\n\t\t\tInteger prefLength = getPrefixLength();\r\n\t\t\tif(prefLength != null) {\r\n\t\t\t\tMACAddressSection resultSection = creator.createSectionInternal(segs, true);\r\n\t\t\t\tif(prefLength >= 24) {\r\n\t\t\t\t\tprefLength += MACAddress.BITS_PER_SEGMENT << 1; //two segments\r\n\t\t\t\t}\r\n\t\t\t\tresultSection.assignPrefixLength(prefLength);\r\n\t\t\t}\r\n\t\t\treturn creator.createAddressInternal(segs);\r\n\t\t} else {\r\n\t\t\tMACAddressSection section = getSection();\r\n\t\t\tMACAddressSegment seg3 = section.getSegment(3);\r\n\t\t\tMACAddressSegment seg4 = section.getSegment(4);\r\n\t\t\tif(seg3.matches(0xff) && seg4.matches(asMAC ? 0xff : 0xfe)) {\r\n\t\t\t\treturn this;\r\n\t\t\t}\r\n\t\t}\r\n\t\tthrow new IncompatibleAddressException(this, \"ipaddress.mac.error.not.eui.convertible\");\r\n\t}",
"protected boolean _load ()\r\n {\r\n java.sql.ResultSet rs = null;\r\n try\r\n {\r\n // This synchronization is necessary for Oracle JDBC drivers 8.1.7, 9.0.1, 9.2.0.1\r\n // The documentation says synchronization is done within the driver, but they\r\n // must have overlooked something. Without the lock we'd get mysterious error\r\n // messages. \r\n synchronized(getDbMeta())\r\n {\r\n getDbMetaTreeModel().setStatusBarMessage(\"Reading columns for table \" + getSchema().getCatalog().getCatalogName() + \".\" + getSchema().getSchemaName() + \".\" + getTableName());\r\n rs = getDbMeta().getColumns(getSchema().getCatalog().getCatalogName(), \r\n getSchema().getSchemaName(),\r\n getTableName(), \"%\");\r\n final java.util.ArrayList alNew = new java.util.ArrayList();\r\n while (rs.next())\r\n {\r\n alNew.add(new DBMetaColumnNode(getDbMeta(), getDbMetaTreeModel(), DBMetaTableNode.this, rs.getString(\"COLUMN_NAME\")));\r\n }\r\n alChildren = alNew; \r\n javax.swing.SwingUtilities.invokeLater(new Runnable()\r\n {\r\n public void run()\r\n {\r\n getDbMetaTreeModel().nodeStructureChanged(DBMetaTableNode.this);\r\n }\r\n });\r\n rs.close();\r\n }\r\n }\r\n catch (java.sql.SQLException sqlEx)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving columns\", sqlEx);\r\n try\r\n {\r\n if (rs != null) rs.close ();\r\n }\r\n catch (java.sql.SQLException sqlEx2)\r\n {\r\n this.getDbMetaTreeModel().reportSqlError(\"Error retrieving columns\", sqlEx2);\r\n }\r\n return false;\r\n }\r\n return true;\r\n }",
"public void setBaselineDurationText(int baselineNumber, String value)\n {\n set(selectField(TaskFieldLists.BASELINE_DURATIONS, baselineNumber), value);\n }"
] |
Used to NOT the argument clause specified. | [
"public Where<T, ID> not(Where<T, ID> comparison) {\n\t\taddClause(new Not(pop(\"NOT\")));\n\t\treturn this;\n\t}"
] | [
"public static void zero( DMatrixSparseCSC A , int row0, int row1, int col0, int col1 ) {\n for (int col = col1-1; col >= col0; col--) {\n int numRemoved = 0;\n\n int idx0 = A.col_idx[col], idx1 = A.col_idx[col+1];\n for (int i = idx0; i < idx1; i++) {\n int row = A.nz_rows[i];\n\n // if sorted a faster technique could be used\n if( row >= row0 && row < row1 ) {\n numRemoved++;\n } else if( numRemoved > 0 ){\n A.nz_rows[i-numRemoved]=row;\n A.nz_values[i-numRemoved]=A.nz_values[i];\n }\n }\n\n if( numRemoved > 0 ) {\n // this could be done more intelligently. Each time a column is adjusted all the columns are adjusted\n // after it. Maybe accumulate the changes in each column and do it in one pass? Need an array to store\n // those results though\n\n for (int i = idx1; i < A.nz_length; i++) {\n A.nz_rows[i - numRemoved] = A.nz_rows[i];\n A.nz_values[i - numRemoved] = A.nz_values[i];\n }\n A.nz_length -= numRemoved;\n\n for (int i = col+1; i <= A.numCols; i++) {\n A.col_idx[i] -= numRemoved;\n }\n }\n }\n }",
"@Override\n @SuppressFBWarnings(value = \"UL_UNRELEASED_LOCK\", justification = \"False positive from FindBugs\")\n public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) {\n if (!isActive()) {\n throw new ContextNotActiveException();\n }\n checkContextInitialized();\n final BeanStore beanStore = getBeanStore();\n if (beanStore == null) {\n return null;\n }\n if (contextual == null) {\n throw ContextLogger.LOG.contextualIsNull();\n }\n BeanIdentifier id = getId(contextual);\n ContextualInstance<T> beanInstance = beanStore.get(id);\n if (beanInstance != null) {\n return beanInstance.getInstance();\n } else if (creationalContext != null) {\n LockedBean lock = null;\n try {\n if (multithreaded) {\n lock = beanStore.lock(id);\n beanInstance = beanStore.get(id);\n if (beanInstance != null) {\n return beanInstance.getInstance();\n }\n }\n T instance = contextual.create(creationalContext);\n if (instance != null) {\n beanInstance = new SerializableContextualInstanceImpl<Contextual<T>, T>(contextual, instance, creationalContext, serviceRegistry.get(ContextualStore.class));\n beanStore.put(id, beanInstance);\n }\n return instance;\n } finally {\n if (lock != null) {\n lock.unlock();\n }\n }\n } else {\n return null;\n }\n }",
"public static void scanClassPathForFormattingAnnotations() {\n\n\t\tExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);\n\n\t\t// scan classpath and filter out classes that don't begin with \"com.nds\"\n\t\tReflections reflections = new Reflections(\"com.nds\",\"com.cisco\");\n\n\t\tSet<Class<?>> annotated = reflections.getTypesAnnotatedWith(DefaultFormat.class);\n\n// Reflections ciscoReflections = new Reflections(\"com.cisco\");\n//\n// annotated.addAll(ciscoReflections.getTypesAnnotatedWith(DefaultFormat.class));\n\n\t\tfor (Class<?> markerClass : annotated) {\n\n\t\t\t// if the marker class is indeed implementing FoundationLoggingMarker\n\t\t\t// interface\n\t\t\tif (FoundationLoggingMarker.class.isAssignableFrom(markerClass)) {\n\n\t\t\t\tfinal Class<? extends FoundationLoggingMarker> clazz = (Class<? extends FoundationLoggingMarker>) markerClass;\n\n\t\t\t\texecutorService.execute(new Runnable() {\n\n\t\t\t\t\t@Override\n\t\t\t\t\tpublic void run() {\n\n\t\t\t\t\t\tif (markersMap.get(clazz) == null) {\n\t\t\t\t\t\t\ttry {\n\t\t\t\t\t\t\t\t// generate formatter class for this marker\n\t\t\t\t\t\t\t\t// class\n\t\t\t\t\t\t\t\tgenerateAndUpdateFormatterInMap(clazz);\n\t\t\t\t\t\t\t} catch (Exception e) {\n\t\t\t\t\t\t\t\tLOGGER.trace(\"problem generating formatter class from static scan method. error is: \" + e.toString());\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t});\n\n\t\t\t} else {// if marker class does not implement FoundationLoggingMarker\n\t\t\t\t\t// interface, log ERROR\n\n\t\t\t\t// verify the LOGGER was initialized. It might not be as this\n\t\t\t\t// Method is called in a static block\n\t\t\t\tif (LOGGER == null) {\n\t\t\t\t\tLOGGER = LoggerFactory.getLogger(AbstractFoundationLoggingMarker.class);\n\t\t\t\t}\n\t\t\t\tLOGGER.error(\"Formatter annotations should only appear on foundationLoggingMarker implementations\");\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\tTimeUnit.SECONDS.sleep(30);\n\t\t} catch (InterruptedException e) {\n\t\t\tLOGGER.trace(e.toString(), e);\n\t\t}\n\t\texecutorService.shutdown();\n\t\t// try {\n\t\t// executorService.awaitTermination(15, TimeUnit.SECONDS);\n\t\t// } catch (InterruptedException e) {\n\t\t// LOGGER.error(\"creation of formatters has been interrupted\");\n\t\t// }\n\t}",
"public static Optional<Field> getField(Class<?> type, final String fieldName) {\n Optional<Field> field = Iterables.tryFind(newArrayList(type.getDeclaredFields()), havingFieldName(fieldName));\n\n if (!field.isPresent() && type.getSuperclass() != null){\n field = getField(type.getSuperclass(), fieldName);\n }\n\n return field;\n }",
"private <T> Observable<PollingState<T>> updateStateFromGetResourceOperationAsync(final PollingState<T> pollingState, String url) {\n return pollAsync(url, pollingState.loggingContext())\n .flatMap(new Func1<Response<ResponseBody>, Observable<PollingState<T>>>() {\n @Override\n public Observable<PollingState<T>> call(Response<ResponseBody> response) {\n try {\n pollingState.updateFromResponseOnPutPatch(response);\n return Observable.just(pollingState);\n } catch (CloudException | IOException e) {\n return Observable.error(e);\n }\n }\n });\n }",
"public static int countTrue(BMatrixRMaj A) {\n int total = 0;\n\n int N = A.getNumElements();\n\n for (int i = 0; i < N; i++) {\n if( A.data[i] )\n total++;\n }\n\n return total;\n }",
"private List<Object> convertType(DataType type, byte[] data)\n {\n List<Object> result = new ArrayList<Object>();\n int index = 0;\n\n while (index < data.length)\n {\n switch (type)\n {\n case STRING:\n {\n String value = MPPUtility.getUnicodeString(data, index);\n result.add(value);\n index += ((value.length() + 1) * 2);\n break;\n }\n\n case CURRENCY:\n {\n Double value = Double.valueOf(MPPUtility.getDouble(data, index) / 100);\n result.add(value);\n index += 8;\n break;\n }\n\n case NUMERIC:\n {\n Double value = Double.valueOf(MPPUtility.getDouble(data, index));\n result.add(value);\n index += 8;\n break;\n }\n\n case DATE:\n {\n Date value = MPPUtility.getTimestamp(data, index);\n result.add(value);\n index += 4;\n break;\n\n }\n\n case DURATION:\n {\n TimeUnit units = MPPUtility.getDurationTimeUnits(MPPUtility.getShort(data, index + 4), m_properties.getDefaultDurationUnits());\n Duration value = MPPUtility.getAdjustedDuration(m_properties, MPPUtility.getInt(data, index), units);\n result.add(value);\n index += 6;\n break;\n }\n\n case BOOLEAN:\n {\n Boolean value = Boolean.valueOf(MPPUtility.getShort(data, index) == 1);\n result.add(value);\n index += 2;\n break;\n }\n\n default:\n {\n index = data.length;\n break;\n }\n }\n }\n\n return result;\n }",
"private RawGcsCreationToken put(final GcsRestCreationToken token, ByteBuffer chunk,\n final boolean isFinalChunk, long timeoutMillis) throws IOException {\n final int length = chunk.remaining();\n HTTPRequest req = createPutRequest(token, chunk, isFinalChunk, timeoutMillis, length);\n HTTPRequestInfo info = new HTTPRequestInfo(req);\n HTTPResponse response;\n try {\n response = urlfetch.fetch(req);\n } catch (IOException e) {\n throw createIOException(info, e);\n }\n return handlePutResponse(token, isFinalChunk, length, info, response);\n }",
"public static String stringify(ObjectMapper mapper, Object object) {\n try {\n return mapper.writeValueAsString(object);\n } catch (JsonProcessingException e) {\n throw new IllegalArgumentException(e);\n }\n }"
] |
Waits the given amount of time in seconds for a managed domain to start. A domain is considered started when each
of the servers in the domain are started unless the server is disabled.
@param client the client used to communicate with the server
@param startupTimeout the time, in seconds, to wait for the server start
@throws InterruptedException if interrupted while waiting for the server to start
@throws RuntimeException if the process has died
@throws TimeoutException if the timeout has been reached and the server is still not started | [
"public static void waitForDomain(final ModelControllerClient client, final long startupTimeout)\n throws InterruptedException, RuntimeException, TimeoutException {\n waitForDomain(null, client, startupTimeout);\n }"
] | [
"public float getNormalY(int vertex) {\n if (!hasNormals()) {\n throw new IllegalStateException(\"mesh has no normals\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_normals.getFloat((vertex * 3 + 1) * SIZEOF_FLOAT);\n }",
"public void process(CustomFieldContainer indicators, ProjectProperties properties, Props props)\n {\n m_container = indicators;\n m_properties = properties;\n m_data = props.getByteArray(Props.TASK_FIELD_ATTRIBUTES);\n\n if (m_data != null)\n {\n int columnsCount = MPPUtility.getInt(m_data, 4);\n m_headerOffset = 8;\n for (int loop = 0; loop < columnsCount; loop++)\n {\n processColumns();\n }\n }\n }",
"public synchronized void stop () {\n if (isRunning()) {\n MetadataFinder.getInstance().removeTrackMetadataListener(metadataListener);\n WaveformFinder.getInstance().removeWaveformListener(waveformListener);\n BeatGridFinder.getInstance().removeBeatGridListener(beatGridListener);\n running.set(false);\n pendingUpdates.clear();\n queueHandler.interrupt();\n queueHandler = null;\n\n // Report the loss of our signatures, on the proper thread, outside our lock\n final Set<Integer> dyingSignatures = new HashSet<Integer>(signatures.keySet());\n signatures.clear();\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (Integer player : dyingSignatures) {\n deliverSignatureUpdate(player, null);\n }\n }\n });\n }\n deliverLifecycleAnnouncement(logger, false);\n }",
"public String getWrappingHint(String fieldName) {\n if (isEmpty()) {\n return \"\";\n }\n\n return String.format(\" You can use this expression: %s(%s(%s))\",\n formatMethod(wrappingMethodOwnerName, wrappingMethodName, \"\"),\n formatMethod(copyMethodOwnerName, copyMethodName, copyTypeParameterName),\n fieldName);\n }",
"@PostConstruct\n public void init() {\n this.metricRegistry.register(name(\"gc\"), new GarbageCollectorMetricSet());\n this.metricRegistry.register(name(\"memory\"), new MemoryUsageGaugeSet());\n this.metricRegistry.register(name(\"thread-states\"), new ThreadStatesGaugeSet());\n this.metricRegistry.register(name(\"fd-usage\"), new FileDescriptorRatioGauge());\n }",
"public void copy(ProjectCalendar cal)\n {\n setName(cal.getName());\n setParent(cal.getParent());\n System.arraycopy(cal.getDays(), 0, getDays(), 0, getDays().length);\n for (ProjectCalendarException ex : cal.m_exceptions)\n {\n addCalendarException(ex.getFromDate(), ex.getToDate());\n for (DateRange range : ex)\n {\n ex.addRange(new DateRange(range.getStart(), range.getEnd()));\n }\n }\n\n for (ProjectCalendarHours hours : getHours())\n {\n if (hours != null)\n {\n ProjectCalendarHours copyHours = cal.addCalendarHours(hours.getDay());\n for (DateRange range : hours)\n {\n copyHours.addRange(new DateRange(range.getStart(), range.getEnd()));\n }\n }\n }\n }",
"public String processNested(Properties attributes) throws XDocletException\r\n {\r\n String name = OjbMemberTagsHandler.getMemberName();\r\n XClass type = OjbMemberTagsHandler.getMemberType();\r\n int dim = OjbMemberTagsHandler.getMemberDimension();\r\n NestedDef nestedDef = _curClassDef.getNested(name);\r\n\r\n if (type == null)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.COULD_NOT_DETERMINE_TYPE_OF_MEMBER,\r\n new String[]{name}));\r\n }\r\n if (dim > 0)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.MEMBER_CANNOT_BE_NESTED,\r\n new String[]{name, _curClassDef.getName()}));\r\n }\r\n\r\n ClassDescriptorDef nestedTypeDef = _model.getClass(type.getQualifiedName());\r\n\r\n if (nestedTypeDef == null)\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.COULD_NOT_DETERMINE_TYPE_OF_MEMBER,\r\n new String[]{name}));\r\n }\r\n if (nestedDef == null)\r\n {\r\n nestedDef = new NestedDef(name, nestedTypeDef);\r\n _curClassDef.addNested(nestedDef);\r\n }\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processNested\", \" Processing nested object \"+nestedDef.getName()+\" of type \"+nestedTypeDef.getName());\r\n\r\n String attrName;\r\n \r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n nestedDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n return \"\";\r\n }",
"public NamedStyleInfo getNamedStyleInfo(String name) {\n\t\tfor (NamedStyleInfo info : namedStyleInfos) {\n\t\t\tif (info.getName().equals(name)) {\n\t\t\t\treturn info;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"public static ModelNode getParentAddress(final ModelNode address) {\n if (address.getType() != ModelType.LIST) {\n throw new IllegalArgumentException(\"The address type must be a list.\");\n }\n final ModelNode result = new ModelNode();\n final List<Property> addressParts = address.asPropertyList();\n if (addressParts.isEmpty()) {\n throw new IllegalArgumentException(\"The address is empty.\");\n }\n for (int i = 0; i < addressParts.size() - 1; ++i) {\n final Property property = addressParts.get(i);\n result.add(property.getName(), property.getValue());\n }\n return result;\n }"
] |
Creates a new child folder inside this folder.
@param name the new folder's name.
@return the created folder's info. | [
"public BoxFolder.Info createFolder(String name) {\n JsonObject parent = new JsonObject();\n parent.add(\"id\", this.getID());\n\n JsonObject newFolder = new JsonObject();\n newFolder.add(\"name\", name);\n newFolder.add(\"parent\", parent);\n\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), CREATE_FOLDER_URL.build(this.getAPI().getBaseURL()),\n \"POST\");\n request.setBody(newFolder.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFolder createdFolder = new BoxFolder(this.getAPI(), responseJSON.get(\"id\").asString());\n return createdFolder.new Info(responseJSON);\n }"
] | [
"public void buttonClick(View v) {\n switch (v.getId()) {\n case R.id.show:\n showAppMsg();\n break;\n case R.id.cancel_all:\n AppMsg.cancelAll(this);\n break;\n default:\n return;\n }\n }",
"private JSONArray toJsonStringArray(Collection<? extends Object> collection) {\n\n if (null != collection) {\n JSONArray array = new JSONArray();\n for (Object o : collection) {\n array.put(\"\" + o);\n }\n return array;\n } else {\n return null;\n }\n }",
"public static final String printResourceType(ResourceType value)\n {\n return (Integer.toString(value == null ? ResourceType.WORK.getValue() : value.getValue()));\n }",
"public static Object findResult(Object self, Object defaultResult, Closure closure) {\n Object result = findResult(self, closure);\n if (result == null) return defaultResult;\n return result;\n }",
"private boolean checkConverged(DMatrixRMaj A) {\n double worst = 0;\n double worst2 = 0;\n for( int j = 0; j < A.numRows; j++ ) {\n double val = Math.abs(q2.data[j] - q0.data[j]);\n if( val > worst ) worst = val;\n val = Math.abs(q2.data[j] + q0.data[j]);\n if( val > worst2 ) worst2 = val;\n }\n\n // swap vectors\n DMatrixRMaj temp = q0;\n q0 = q2;\n q2 = temp;\n\n if( worst < tol )\n return true;\n else if( worst2 < tol )\n return true;\n else\n return false;\n }",
"public static EventType map(Event event) {\n EventType eventType = new EventType();\n eventType.setTimestamp(Converter.convertDate(event.getTimestamp()));\n eventType.setEventType(convertEventType(event.getEventType()));\n OriginatorType origType = mapOriginator(event.getOriginator());\n eventType.setOriginator(origType);\n MessageInfoType miType = mapMessageInfo(event.getMessageInfo());\n eventType.setMessageInfo(miType);\n eventType.setCustomInfo(convertCustomInfo(event.getCustomInfo()));\n eventType.setContentCut(event.isContentCut());\n if (event.getContent() != null) {\n DataHandler datHandler = getDataHandlerForString(event);\n eventType.setContent(datHandler);\n }\n return eventType;\n }",
"public void validate() throws PackagingException {\n if (control == null || !control.isDirectory()) {\n throw new PackagingException(\"The 'control' attribute doesn't point to a directory. \" + control);\n }\n\n if (changesIn != null) {\n\n if (changesIn.exists() && (!changesIn.isFile() || !changesIn.canRead())) {\n throw new PackagingException(\"The 'changesIn' setting needs to point to a readable file. \" + changesIn + \" was not found/readable.\");\n }\n\n if (changesOut != null && !isWritableFile(changesOut)) {\n throw new PackagingException(\"Cannot write the output for 'changesOut' to \" + changesOut);\n }\n\n if (changesSave != null && !isWritableFile(changesSave)) {\n throw new PackagingException(\"Cannot write the output for 'changesSave' to \" + changesSave);\n }\n\n } else {\n if (changesOut != null || changesSave != null) {\n throw new PackagingException(\"The 'changesOut' or 'changesSave' settings may only be used when there is a 'changesIn' specified.\");\n }\n }\n\n if (Compression.toEnum(compression) == null) {\n throw new PackagingException(\"The compression method '\" + compression + \"' is not supported (expected 'none', 'gzip', 'bzip2' or 'xz')\");\n }\n\n if (deb == null) {\n throw new PackagingException(\"You need to specify where the deb file is supposed to be created.\");\n }\n\n getDigestCode(digest);\n }",
"public void deleteModule(final String name, final String version, final String user, final String password) throws GrapesCommunicationException, AuthenticationException{\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getModulePath(name, version));\n final ClientResponse response = resource.delete(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = String.format(FAILED_TO_GET_MODULE, \"to delete module\", name, version);\n\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }",
"protected void bindHelper(GVRScriptBundle scriptBundle, GVRSceneObject rootSceneObject, int bindMask)\n throws IOException, GVRScriptException\n {\n for (GVRScriptBindingEntry entry : scriptBundle.file.binding) {\n GVRAndroidResource rc;\n if (entry.volumeType == null || entry.volumeType.isEmpty()) {\n rc = scriptBundle.volume.openResource(entry.script);\n } else {\n GVRResourceVolume.VolumeType volumeType = GVRResourceVolume.VolumeType.fromString(entry.volumeType);\n if (volumeType == null) {\n throw new GVRScriptException(String.format(\"Volume type %s is not recognized, script=%s\",\n entry.volumeType, entry.script));\n }\n rc = new GVRResourceVolume(mGvrContext, volumeType).openResource(entry.script);\n }\n\n GVRScriptFile scriptFile = (GVRScriptFile)loadScript(rc, entry.language);\n\n String targetName = entry.target;\n if (targetName.startsWith(TARGET_PREFIX)) {\n TargetResolver resolver = sBuiltinTargetMap.get(targetName);\n IScriptable target = resolver.getTarget(mGvrContext, targetName);\n\n // Apply mask\n boolean toBind = false;\n if ((bindMask & BIND_MASK_GVRSCRIPT) != 0 && targetName.equalsIgnoreCase(TARGET_GVRMAIN)) {\n toBind = true;\n }\n\n if ((bindMask & BIND_MASK_GVRACTIVITY) != 0 && targetName.equalsIgnoreCase(TARGET_GVRAPPLICATION)) {\n toBind = true;\n }\n\n if (toBind) {\n attachScriptFile(target, scriptFile);\n }\n } else {\n if ((bindMask & BIND_MASK_SCENE_OBJECTS) != 0) {\n if (targetName.equals(rootSceneObject.getName())) {\n attachScriptFile(rootSceneObject, scriptFile);\n }\n\n // Search in children\n GVRSceneObject[] sceneObjects = rootSceneObject.getSceneObjectsByName(targetName);\n if (sceneObjects != null) {\n for (GVRSceneObject sceneObject : sceneObjects) {\n GVRScriptBehavior b = new GVRScriptBehavior(sceneObject.getGVRContext());\n b.setScriptFile(scriptFile);\n sceneObject.attachComponent(b);\n }\n }\n }\n }\n }\n }"
] |
Use this API to delete dnsaaaarec resources. | [
"public static base_responses delete(nitro_service client, dnsaaaarec resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnsaaaarec deleteresources[] = new dnsaaaarec[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tdeleteresources[i] = new dnsaaaarec();\n\t\t\t\tdeleteresources[i].hostname = resources[i].hostname;\n\t\t\t\tdeleteresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}"
] | [
"public static String get(MessageKey key) {\n return data.getProperty(key.toString(), key.toString());\n }",
"public String[] getUrl() {\n String[] valueDestination = new String[ url.size() ];\n this.url.getValue(valueDestination);\n return valueDestination;\n }",
"private Resolvable createMetadataProvider(Class<?> rawType) {\n Set<Type> types = Collections.<Type>singleton(rawType);\n return new ResolvableImpl(rawType, types, declaringBean, qualifierInstances, delegate);\n }",
"public static String get(String language) {\n language = language.toLowerCase();\n if(\"ecmascript\".equals(language)) {\n language = \"javascript\";\n }\n\n String extension = extensions.get(language);\n if(extension == null) {\n return null;\n\n } else {\n return loadScriptEnv(language, extension);\n\n }\n }",
"public int evaluate(FieldContainer container)\n {\n //\n // First step - determine the list of criteria we are should use\n //\n List<GraphicalIndicatorCriteria> criteria;\n if (container instanceof Task)\n {\n Task task = (Task) container;\n if (NumberHelper.getInt(task.getUniqueID()) == 0)\n {\n if (m_projectSummaryInheritsFromSummaryRows == false)\n {\n criteria = m_projectSummaryCriteria;\n }\n else\n {\n if (m_summaryRowsInheritFromNonSummaryRows == false)\n {\n criteria = m_summaryRowCriteria;\n }\n else\n {\n criteria = m_nonSummaryRowCriteria;\n }\n }\n }\n else\n {\n if (task.getSummary() == true)\n {\n if (m_summaryRowsInheritFromNonSummaryRows == false)\n {\n criteria = m_summaryRowCriteria;\n }\n else\n {\n criteria = m_nonSummaryRowCriteria;\n }\n }\n else\n {\n criteria = m_nonSummaryRowCriteria;\n }\n }\n }\n else\n {\n // It is possible to have a resource summary row, but at the moment\n // I can't see how you can determine this.\n criteria = m_nonSummaryRowCriteria;\n }\n\n //\n // Now we have the criteria, evaluate each one until we get a result\n //\n int result = -1;\n for (GraphicalIndicatorCriteria gic : criteria)\n {\n result = gic.evaluate(container);\n if (result != -1)\n {\n break;\n }\n }\n\n //\n // If we still don't have a result at the end, return the\n // default value, which is 0\n //\n if (result == -1)\n {\n result = 0;\n }\n\n return (result);\n }",
"private void closeClient(Client client) {\n logger.debug(\"Closing client {}\", client);\n client.close();\n openClients.remove(client.targetPlayer);\n useCounts.remove(client);\n timestamps.remove(client);\n }",
"public static double[][] toDouble(int[][] array) {\n double[][] n = new double[array.length][array[0].length];\n for (int i = 0; i < array.length; i++) {\n for (int j = 0; j < array[0].length; j++) {\n n[i][j] = (double) array[i][j];\n }\n }\n return n;\n }",
"public static Filter.Builder makeAndFilter(Iterable<Filter> subfilters) {\n return Filter.newBuilder()\n .setCompositeFilter(CompositeFilter.newBuilder()\n .addAllFilters(subfilters)\n .setOp(CompositeFilter.Operator.AND));\n }",
"private ResourceReport getResourceReport(TwillController controller, int maxWaitMs) {\n ResourceReport report = controller.getResourceReport();\n int elapsed = 0;\n while (report == null) {\n report = controller.getResourceReport();\n try {\n Thread.sleep(500);\n } catch (InterruptedException e) {\n throw new IllegalStateException(e);\n }\n elapsed += 500;\n if ((maxWaitMs != -1) && (elapsed > maxWaitMs)) {\n String msg = String.format(\"Exceeded max wait time to retrieve ResourceReport from Twill.\"\n + \" Elapsed time = %s ms\", elapsed);\n log.error(msg);\n throw new IllegalStateException(msg);\n }\n if ((elapsed % 10000) == 0) {\n log.info(\"Waiting for ResourceReport from Twill. Elapsed time = {} ms\", elapsed);\n }\n }\n return report;\n }"
] |
Adds a new Pie Slice to the PieChart. After inserting and calculation of the highlighting color
a complete recalculation is initiated.
@param _Slice The newly added PieSlice. | [
"public void addPieSlice(PieModel _Slice) {\n highlightSlice(_Slice);\n mPieData.add(_Slice);\n mTotalValue += _Slice.getValue();\n onDataChanged();\n }"
] | [
"public EventBus emitAsync(Enum<?> event, Object... args) {\n return _emitWithOnceBus(eventContextAsync(event, args));\n }",
"public void updateEmbeddedColumn(GraphDatabaseService executionEngine, Object[] keyValues, String embeddedColumn, Object value) {\n\t\tString query = getUpdateEmbeddedColumnQuery( keyValues, embeddedColumn );\n\t\tMap<String, Object> params = params( ArrayHelper.concat( keyValues, value, value ) );\n\t\texecutionEngine.execute( query, params );\n\t}",
"public static void addService(final ServiceTarget serviceTarget, final Bootstrap.Configuration configuration,\n final ControlledProcessState processState, final BootstrapListener bootstrapListener,\n final RunningModeControl runningModeControl, final AbstractVaultReader vaultReader, final ManagedAuditLogger auditLogger,\n final DelegatingConfigurableAuthorizer authorizer, final ManagementSecurityIdentitySupplier securityIdentitySupplier,\n final SuspendController suspendController) {\n\n // Install Executor services\n final ThreadGroup threadGroup = new ThreadGroup(\"ServerService ThreadGroup\");\n final String namePattern = \"ServerService Thread Pool -- %t\";\n final ThreadFactory threadFactory = doPrivileged(new PrivilegedAction<ThreadFactory>() {\n public ThreadFactory run() {\n return new JBossThreadFactory(threadGroup, Boolean.FALSE, null, namePattern, null, null);\n }\n });\n\n // TODO determine why QueuelessThreadPoolService makes boot take > 35 secs\n// final QueuelessThreadPoolService serverExecutorService = new QueuelessThreadPoolService(Integer.MAX_VALUE, false, new TimeSpec(TimeUnit.SECONDS, 5));\n// serverExecutorService.getThreadFactoryInjector().inject(threadFactory);\n final boolean forDomain = ProcessType.DOMAIN_SERVER == getProcessType(configuration.getServerEnvironment());\n final ServerExecutorService serverExecutorService = new ServerExecutorService(threadFactory, forDomain);\n serviceTarget.addService(MANAGEMENT_EXECUTOR, serverExecutorService)\n .addAliases(Services.JBOSS_SERVER_EXECUTOR, ManagementRemotingServices.SHUTDOWN_EXECUTOR_NAME) // Use this executor for mgmt shutdown for now\n .install();\n final ServerScheduledExecutorService serverScheduledExecutorService = new ServerScheduledExecutorService(threadFactory);\n serviceTarget.addService(JBOSS_SERVER_SCHEDULED_EXECUTOR, serverScheduledExecutorService)\n .addAliases(JBOSS_SERVER_SCHEDULED_EXECUTOR)\n .addDependency(MANAGEMENT_EXECUTOR, ExecutorService.class, serverScheduledExecutorService.executorInjector)\n .install();\n\n final CapabilityRegistry capabilityRegistry = configuration.getCapabilityRegistry();\n ServerService service = new ServerService(configuration, processState, null, bootstrapListener, new ServerDelegatingResourceDefinition(),\n runningModeControl, vaultReader, auditLogger, authorizer, securityIdentitySupplier, capabilityRegistry, suspendController);\n\n ExternalManagementRequestExecutor.install(serviceTarget, threadGroup, EXECUTOR_CAPABILITY.getCapabilityServiceName(), service.getStabilityMonitor());\n\n ServiceBuilder<?> serviceBuilder = serviceTarget.addService(Services.JBOSS_SERVER_CONTROLLER, service);\n serviceBuilder.addDependency(DeploymentMountProvider.SERVICE_NAME,DeploymentMountProvider.class, service.injectedDeploymentRepository);\n serviceBuilder.addDependency(ContentRepository.SERVICE_NAME, ContentRepository.class, service.injectedContentRepository);\n serviceBuilder.addDependency(Services.JBOSS_SERVICE_MODULE_LOADER, ServiceModuleLoader.class, service.injectedModuleLoader);\n serviceBuilder.addDependency(Services.JBOSS_EXTERNAL_MODULE_SERVICE, ExternalModuleService.class,\n service.injectedExternalModuleService);\n serviceBuilder.addDependency(PATH_MANAGER_CAPABILITY.getCapabilityServiceName(), PathManager.class, service.injectedPathManagerService);\n if (configuration.getServerEnvironment().isAllowModelControllerExecutor()) {\n serviceBuilder.addDependency(MANAGEMENT_EXECUTOR, ExecutorService.class, service.getExecutorServiceInjector());\n }\n if (configuration.getServerEnvironment().getLaunchType() == ServerEnvironment.LaunchType.DOMAIN) {\n serviceBuilder.addDependency(HostControllerConnectionService.SERVICE_NAME, ControllerInstabilityListener.class,\n service.getContainerInstabilityInjector());\n }\n\n serviceBuilder.install();\n }",
"@Deprecated\r\n @SuppressWarnings(\"unchecked\")\r\n private static <E extends LogRecordHandler> E getHandler(Class<E> clazz){\r\n for(LogRecordHandler cand : handlers){\r\n if(clazz == cand.getClass()){\r\n return (E) cand;\r\n }\r\n }\r\n return null;\r\n }",
"public void processAnonymousReference(Properties attributes) throws XDocletException\r\n {\r\n ReferenceDescriptorDef refDef = _curClassDef.getReference(\"super\");\r\n String attrName;\r\n\r\n if (refDef == null)\r\n {\r\n refDef = new ReferenceDescriptorDef(\"super\");\r\n _curClassDef.addReference(refDef);\r\n }\r\n refDef.setAnonymous();\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processAnonymousReference\", \" Processing anonymous reference\");\r\n\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n refDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n }",
"public static ComplexNumber Sin(ComplexNumber z1) {\r\n ComplexNumber result = new ComplexNumber();\r\n\r\n if (z1.imaginary == 0.0) {\r\n result.real = Math.sin(z1.real);\r\n result.imaginary = 0.0;\r\n } else {\r\n result.real = Math.sin(z1.real) * Math.cosh(z1.imaginary);\r\n result.imaginary = Math.cos(z1.real) * Math.sinh(z1.imaginary);\r\n }\r\n\r\n return result;\r\n }",
"private Pair<Double, String>\n summarizeBalance(final Map<Integer, Integer> nodeIdToPartitionCount, String title) {\n StringBuilder builder = new StringBuilder();\n builder.append(\"\\n\" + title + \"\\n\");\n\n Map<Integer, ZoneBalanceStats> zoneToBalanceStats = new HashMap<Integer, ZoneBalanceStats>();\n for(Integer zoneId: cluster.getZoneIds()) {\n zoneToBalanceStats.put(zoneId, new ZoneBalanceStats());\n }\n\n for(Node node: cluster.getNodes()) {\n int curCount = nodeIdToPartitionCount.get(node.getId());\n builder.append(\"\\tNode ID: \" + node.getId() + \" : \" + curCount + \" (\" + node.getHost()\n + \")\\n\");\n zoneToBalanceStats.get(node.getZoneId()).addPartitions(curCount);\n }\n\n // double utilityToBeMinimized = Double.MIN_VALUE;\n double utilityToBeMinimized = 0;\n for(Integer zoneId: cluster.getZoneIds()) {\n builder.append(\"Zone \" + zoneId + \"\\n\");\n builder.append(zoneToBalanceStats.get(zoneId).dumpStats());\n utilityToBeMinimized += zoneToBalanceStats.get(zoneId).getUtility();\n /*- \n * Another utility function to consider \n if(zoneToBalanceStats.get(zoneId).getMaxMinRatio() > utilityToBeMinimized) {\n utilityToBeMinimized = zoneToBalanceStats.get(zoneId).getUtility();\n }\n */\n }\n\n return Pair.create(utilityToBeMinimized, builder.toString());\n }",
"public final File getTaskDirectory() {\n createIfMissing(this.working, \"Working\");\n try {\n return Files.createTempDirectory(this.working.toPath(), TASK_DIR_PREFIX).toFile();\n } catch (IOException e) {\n throw new AssertionError(\"Unable to create temporary directory in '\" + this.working + \"'\");\n }\n }",
"public void setEnterpriseDuration(int index, Duration value)\n {\n set(selectField(AssignmentFieldLists.ENTERPRISE_DURATION, index), value);\n }"
] |
Initialize the random generator with a seed. | [
"private void srand(int ijkl) {\n u = new double[97];\n\n int ij = ijkl / 30082;\n int kl = ijkl % 30082;\n\n // Handle the seed range errors\n // First random number seed must be between 0 and 31328\n // Second seed must have a value between 0 and 30081\n if (ij < 0 || ij > 31328 || kl < 0 || kl > 30081) {\n ij = ij % 31329;\n kl = kl % 30082;\n }\n\n int i = ((ij / 177) % 177) + 2;\n int j = (ij % 177) + 2;\n int k = ((kl / 169) % 178) + 1;\n int l = kl % 169;\n\n int m;\n double s, t;\n for (int ii = 0; ii < 97; ii++) {\n s = 0.0;\n t = 0.5;\n for (int jj = 0; jj < 24; jj++) {\n m = (((i * j) % 179) * k) % 179;\n i = j;\n j = k;\n k = m;\n l = (53 * l + 1) % 169;\n if (((l * m) % 64) >= 32) {\n s += t;\n }\n t *= 0.5;\n }\n u[ii] = s;\n }\n\n c = 362436.0 / 16777216.0;\n cd = 7654321.0 / 16777216.0;\n cm = 16777213.0 / 16777216.0;\n i97 = 96;\n j97 = 32;\n }"
] | [
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoLocalDateTime<DiscordianDate> localDateTime(TemporalAccessor temporal) {\n return (ChronoLocalDateTime<DiscordianDate>) super.localDateTime(temporal);\n }",
"public static base_response enable(nitro_service client, nsfeature resource) throws Exception {\n\t\tnsfeature enableresource = new nsfeature();\n\t\tenableresource.feature = resource.feature;\n\t\treturn enableresource.perform_operation(client,\"enable\");\n\t}",
"public CollectionRequest<Task> projects(String task) {\n \n String path = String.format(\"/tasks/%s/projects\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }",
"private void ensureLength(FieldDescriptorDef fieldDef, String checkLevel)\r\n {\r\n if (!fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_LENGTH))\r\n {\r\n String defaultLength = JdbcTypeHelper.getDefaultLengthFor(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n\r\n if (defaultLength != null)\r\n {\r\n LogHelper.warn(true,\r\n FieldDescriptorConstraints.class,\r\n \"ensureLength\",\r\n \"The field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" has no length setting though its jdbc type requires it (in most databases); using default length of \"+defaultLength);\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_LENGTH, defaultLength);\r\n }\r\n }\r\n }",
"private boolean contains(ArrayList defs, DefBase obj)\r\n {\r\n for (Iterator it = defs.iterator(); it.hasNext();)\r\n {\r\n if (obj.getName().equals(((DefBase)it.next()).getName()))\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }",
"void registerAlias(FieldType type, String alias)\n {\n m_aliasMap.put(new Pair<FieldTypeClass, String>(type.getFieldTypeClass(), alias), type);\n }",
"@Override\n\tpublic EmbeddedBrowser get() {\n\t\tLOGGER.debug(\"Setting up a Browser\");\n\t\t// Retrieve the config values used\n\t\tImmutableSortedSet<String> filterAttributes =\n\t\t\t\tconfiguration.getCrawlRules().getPreCrawlConfig().getFilterAttributeNames();\n\t\tlong crawlWaitReload = configuration.getCrawlRules().getWaitAfterReloadUrl();\n\t\tlong crawlWaitEvent = configuration.getCrawlRules().getWaitAfterEvent();\n\n\t\t// Determine the requested browser type\n\t\tEmbeddedBrowser browser = null;\n\t\tEmbeddedBrowser.BrowserType browserType =\n\t\t\t\tconfiguration.getBrowserConfig().getBrowserType();\n\t\ttry {\n\t\t\tswitch (browserType) {\n\t\t\t\tcase CHROME:\n\t\t\t\t\tbrowser = newChromeBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,\n\t\t\t\t\t\t\tfalse);\n\t\t\t\t\tbreak;\n\t\t\t\tcase CHROME_HEADLESS:\n\t\t\t\t\tbrowser = newChromeBrowser(filterAttributes, crawlWaitReload,\n\t\t\t\t\t\t\tcrawlWaitEvent, true);\n\t\t\t\t\tbreak;\n\t\t\t\tcase FIREFOX:\n\t\t\t\t\tbrowser = newFirefoxBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,\n\t\t\t\t\t\t\tfalse);\n\t\t\t\t\tbreak;\n\t\t\t\tcase FIREFOX_HEADLESS:\n\t\t\t\t\tbrowser = newFirefoxBrowser(filterAttributes, crawlWaitReload, crawlWaitEvent,\n\t\t\t\t\t\t\ttrue);\n\t\t\t\t\tbreak;\n\t\t\t\tcase REMOTE:\n\t\t\t\t\tbrowser = WebDriverBackedEmbeddedBrowser.withRemoteDriver(\n\t\t\t\t\t\t\tconfiguration.getBrowserConfig().getRemoteHubUrl(), filterAttributes,\n\t\t\t\t\t\t\tcrawlWaitEvent, crawlWaitReload);\n\t\t\t\t\tbreak;\n\t\t\t\tcase PHANTOMJS:\n\t\t\t\t\tbrowser =\n\t\t\t\t\t\t\tnewPhantomJSDriver(filterAttributes, crawlWaitReload, crawlWaitEvent);\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new IllegalStateException(\"Unrecognized browser type \"\n\t\t\t\t\t\t\t+ configuration.getBrowserConfig().getBrowserType());\n\t\t\t}\n\t\t} catch (IllegalStateException e) {\n\t\t\tLOGGER.error(\"Crawling with {} failed: \" + e.getMessage(), browserType.toString());\n\t\t\tthrow e;\n\t\t}\n\n\t\t/* for Retina display. */\n\t\tif (browser instanceof WebDriverBackedEmbeddedBrowser) {\n\t\t\tint pixelDensity =\n\t\t\t\t\tthis.configuration.getBrowserConfig().getBrowserOptions().getPixelDensity();\n\t\t\tif (pixelDensity != -1)\n\t\t\t\t((WebDriverBackedEmbeddedBrowser) browser).setPixelDensity(pixelDensity);\n\t\t}\n\n\t\tplugins.runOnBrowserCreatedPlugins(browser);\n\t\treturn browser;\n\t}",
"private static List<CmsCategory> getCategories(CmsObject cms, CmsResource resource) {\n\n if ((null != resource) && (null != cms)) {\n try {\n return CmsCategoryService.getInstance().readResourceCategories(cms, resource);\n } catch (CmsException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n }\n return new ArrayList<CmsCategory>(0);\n }",
"public static base_response update(nitro_service client, callhome resource) throws Exception {\n\t\tcallhome updateresource = new callhome();\n\t\tupdateresource.emailaddress = resource.emailaddress;\n\t\tupdateresource.proxymode = resource.proxymode;\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.port = resource.port;\n\t\treturn updateresource.update_resource(client);\n\t}"
] |
Processes the template for all index descriptors of the current class definition.
@param template The template
@param attributes The attributes of the tag
@exception XDocletException if an error occurs
@doc.tag type="block" | [
"public void forAllIndexDescriptorDefinitions(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curClassDef.getIndexDescriptors(); it.hasNext(); )\r\n {\r\n _curIndexDescriptorDef = (IndexDescriptorDef)it.next();\r\n generate(template);\r\n }\r\n _curIndexDescriptorDef = null;\r\n }"
] | [
"private long validateMessage(FileChannel channel, long start, long len, ByteBuffer buffer) throws IOException {\n buffer.rewind();\n int read = channel.read(buffer, start);\n if (read < 4) return -1;\n\n // check that we have sufficient bytes left in the file\n int size = buffer.getInt(0);\n if (size < Message.MinHeaderSize) return -1;\n\n long next = start + 4 + size;\n if (next > len) return -1;\n\n // read the message\n ByteBuffer messageBuffer = ByteBuffer.allocate(size);\n long curr = start + 4;\n while (messageBuffer.hasRemaining()) {\n read = channel.read(messageBuffer, curr);\n if (read < 0) throw new IllegalStateException(\"File size changed during recovery!\");\n else curr += read;\n }\n messageBuffer.rewind();\n Message message = new Message(messageBuffer);\n if (!message.isValid()) return -1;\n else return next;\n }",
"public float getMetallic()\n {\n Property p = getProperty(PropertyKey.METALLIC.m_key);\n\n if (null == p || null == p.getData())\n {\n throw new IllegalArgumentException(\"Metallic property not found\");\n }\n Object rawValue = p.getData();\n if (rawValue instanceof java.nio.ByteBuffer)\n {\n java.nio.FloatBuffer fbuf = ((java.nio.ByteBuffer) rawValue).asFloatBuffer();\n return fbuf.get();\n }\n else\n {\n return (Float) rawValue;\n }\n }",
"public <T> T fetchObject(String objectId, Class<T> type) {\n\t\tURI uri = URIBuilder.fromUri(getBaseGraphApiUrl() + objectId).build();\n\t\treturn getRestTemplate().getForObject(uri, type);\n\t}",
"private void initKeySetForXmlBundle() {\n\n // consider only available locales\n for (Locale l : m_locales) {\n if (m_xmlBundle.hasLocale(l)) {\n Set<Object> keys = new HashSet<Object>();\n for (I_CmsXmlContentValue msg : m_xmlBundle.getValueSequence(\"Message\", l).getValues()) {\n String msgpath = msg.getPath();\n keys.add(m_xmlBundle.getStringValue(m_cms, msgpath + \"/Key\", l));\n }\n m_keyset.updateKeySet(null, keys);\n }\n }\n\n }",
"public void setClasspath(Path classpath)\r\n {\r\n if (_classpath == null)\r\n {\r\n _classpath = classpath;\r\n }\r\n else\r\n {\r\n _classpath.append(classpath);\r\n }\r\n log(\"Verification classpath is \"+ _classpath,\r\n Project.MSG_VERBOSE);\r\n }",
"public ProteusApplication setServerConfigurationFunction(Function<Undertow.Builder, Undertow.Builder> serverConfigurationFunction)\n {\n this.serverConfigurationFunction = serverConfigurationFunction;\n return this;\n }",
"public static void logLong(String TAG, String longString) {\n InputStream is = new ByteArrayInputStream( longString.getBytes() );\n @SuppressWarnings(\"resource\")\n Scanner scan = new Scanner(is);\n while (scan.hasNextLine()) {\n Log.v(TAG, scan.nextLine());\n }\n }",
"public static base_response disable(nitro_service client, String id) throws Exception {\n\t\tInterface disableresource = new Interface();\n\t\tdisableresource.id = id;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}",
"public int[] next()\n {\n boolean hasNewPerm = false;\n\n escape:while( level >= 0) {\n// boolean foundZero = false;\n for( int i = iter[level]; i < data.length; i = iter[level] ) {\n iter[level]++;\n\n if( data[i] == -1 ) {\n level++;\n data[i] = level-1;\n\n if( level >= data.length ) {\n // a new permutation has been created return the results.\n hasNewPerm = true;\n System.arraycopy(data,0,ret,0,ret.length);\n level = level-1;\n data[i] = -1;\n break escape;\n } else {\n valk[level] = i;\n }\n }\n }\n\n data[valk[level]] = -1;\n iter[level] = 0;\n level = level-1;\n\n }\n\n if( hasNewPerm )\n return ret;\n return null;\n }"
] |
Reports a given exception as a RuntimeException, since the interface does
not allow us to throw checked exceptions directly.
@param e
the exception to report
@throws RuntimeException
in all cases | [
"private void reportException(Exception e) {\n\t\tlogger.error(\"Failed to write JSON export: \" + e.toString());\n\t\tthrow new RuntimeException(e.toString(), e);\n\t}"
] | [
"public static void outputString(final HttpServletResponse response, final Object obj) {\n try {\n response.setContentType(\"text/javascript\");\n response.setCharacterEncoding(\"utf-8\");\n disableCache(response);\n response.getWriter().write(obj.toString());\n response.getWriter().flush();\n response.getWriter().close();\n } catch (IOException e) {\n }\n }",
"@Override\n public PmdRuleSet create() {\n final SAXBuilder parser = new SAXBuilder();\n final Document dom;\n try {\n dom = parser.build(source);\n } catch (JDOMException | IOException e) {\n if (messages != null) {\n messages.addErrorText(INVALID_INPUT + \" : \" + e.getMessage());\n }\n LOG.error(INVALID_INPUT, e);\n return new PmdRuleSet();\n }\n\n final Element eltResultset = dom.getRootElement();\n final Namespace namespace = eltResultset.getNamespace();\n final PmdRuleSet result = new PmdRuleSet();\n\n final String name = eltResultset.getAttributeValue(\"name\");\n final Element descriptionElement = getChild(eltResultset, namespace);\n\n result.setName(name);\n\n if (descriptionElement != null) {\n result.setDescription(descriptionElement.getValue());\n }\n\n for (Element eltRule : getChildren(eltResultset, \"rule\", namespace)) {\n PmdRule pmdRule = new PmdRule(eltRule.getAttributeValue(\"ref\"));\n pmdRule.setClazz(eltRule.getAttributeValue(\"class\"));\n pmdRule.setName(eltRule.getAttributeValue(\"name\"));\n pmdRule.setMessage(eltRule.getAttributeValue(\"message\"));\n parsePmdPriority(eltRule, pmdRule, namespace);\n parsePmdProperties(eltRule, pmdRule, namespace);\n result.addRule(pmdRule);\n }\n return result;\n }",
"protected String classOf(List<IN> lineInfos, int pos) {\r\n Datum<String, String> d = makeDatum(lineInfos, pos, featureFactory);\r\n return classifier.classOf(d);\r\n }",
"private boolean fireEvent(Eventable eventable) {\n\t\tEventable eventToFire = eventable;\n\t\tif (eventable.getIdentification().getHow().toString().equals(\"xpath\")\n\t\t\t\t&& eventable.getRelatedFrame().equals(\"\")) {\n\t\t\teventToFire = resolveByXpath(eventable, eventToFire);\n\t\t}\n\t\tboolean isFired = false;\n\t\ttry {\n\t\t\tisFired = browser.fireEventAndWait(eventToFire);\n\t\t} catch (ElementNotVisibleException | NoSuchElementException e) {\n\t\t\tif (crawlRules.isCrawlHiddenAnchors() && eventToFire.getElement() != null\n\t\t\t\t\t&& \"A\".equals(eventToFire.getElement().getTag())) {\n\t\t\t\tisFired = visitAnchorHrefIfPossible(eventToFire);\n\t\t\t} else {\n\t\t\t\tLOG.debug(\"Ignoring invisible element {}\", eventToFire.getElement());\n\t\t\t}\n\t\t} catch (InterruptedException e) {\n\t\t\tLOG.debug(\"Interrupted during fire event\");\n\t\t\tinterruptThread();\n\t\t\treturn false;\n\t\t}\n\n\t\tLOG.debug(\"Event fired={} for eventable {}\", isFired, eventable);\n\n\t\tif (isFired) {\n\t\t\t// Let the controller execute its specified wait operation on the browser thread safe.\n\t\t\twaitConditionChecker.wait(browser);\n\t\t\tbrowser.closeOtherWindows();\n\t\t\treturn true;\n\t\t} else {\n\t\t\t/*\n\t\t\t * Execute the OnFireEventFailedPlugins with the current crawlPath with the crawlPath\n\t\t\t * removed 1 state to represent the path TO here.\n\t\t\t */\n\t\t\tplugins.runOnFireEventFailedPlugins(context, eventable,\n\t\t\t\t\tcrawlpath.immutableCopyWithoutLast());\n\t\t\treturn false; // no event fired\n\t\t}\n\t}",
"private void logUnexpectedStructure()\n {\n if (m_log != null)\n {\n m_log.println(\"ABORTED COLUMN - unexpected structure: \" + m_currentColumn.getClass().getSimpleName() + \" \" + m_currentColumn.getName());\n }\n }",
"protected String createGlobalStyle()\n {\n StringBuilder ret = new StringBuilder();\n ret.append(createFontFaces());\n ret.append(\"\\n\");\n ret.append(defaultStyle);\n return ret.toString();\n }",
"public void logAttributeWarning(PathAddress address, String message, String attribute) {\n logAttributeWarning(address, null, message, attribute);\n }",
"public void purge(String cacheKey) {\n try {\n if (useMemoryCache) {\n if (memoryCache != null) {\n memoryCache.remove(cacheKey);\n }\n }\n\n if (useDiskCache) {\n if (diskLruCache != null) {\n diskLruCache.remove(cacheKey);\n }\n }\n } catch (Exception e) {\n Log.w(TAG, \"Could not remove entry in cache purge\", e);\n }\n }",
"protected String escapeApostrophes(String text) {\r\n\t\tString resultString;\r\n\t\tif (text.contains(\"'\")) {\r\n\t\t\tStringBuilder stringBuilder = new StringBuilder();\r\n\t\t\tstringBuilder.append(\"concat('\");\r\n\t\t\tstringBuilder.append(text.replace(\"'\", \"',\\\"'\\\",'\"));\r\n\t\t\tstringBuilder.append(\"')\");\r\n\t\t\tresultString = stringBuilder.toString();\r\n\t\t} else {\r\n\t\t\tresultString = \"'\" + text + \"'\";\r\n\t\t}\r\n\t\treturn resultString;\r\n\t}"
] |
Gets the aggregate result count summary. only list the counts for brief
understanding
@return the aggregate result count summary | [
"public Map<String, Integer> getAggregateResultCountSummary() {\n\n Map<String, Integer> summaryMap = new LinkedHashMap<String, Integer>();\n\n for (Entry<String, LinkedHashSet<String>> entry : aggregateResultMap\n .entrySet()) {\n summaryMap.put(entry.getKey(), entry.getValue().size());\n }\n\n return summaryMap;\n }"
] | [
"private Collection parseTreeCollection(Element collectionElement) {\n\n Collection collection = new Collection();\n parseCommonFields(collectionElement, collection);\n collection.setTitle(collectionElement.getAttribute(\"title\"));\n collection.setDescription(collectionElement.getAttribute(\"description\"));\n\n // Collections can contain either sets or collections (but not both)\n NodeList childCollectionElements = collectionElement.getElementsByTagName(\"collection\");\n for (int i = 0; i < childCollectionElements.getLength(); i++) {\n Element childCollectionElement = (Element) childCollectionElements.item(i);\n collection.addCollection(parseTreeCollection(childCollectionElement));\n }\n\n NodeList childPhotosetElements = collectionElement.getElementsByTagName(\"set\");\n for (int i = 0; i < childPhotosetElements.getLength(); i++) {\n Element childPhotosetElement = (Element) childPhotosetElements.item(i);\n collection.addPhotoset(createPhotoset(childPhotosetElement));\n }\n\n return collection;\n }",
"public static systemuser get(nitro_service service, String username) throws Exception{\n\t\tsystemuser obj = new systemuser();\n\t\tobj.set_username(username);\n\t\tsystemuser response = (systemuser) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static List<Versioned<byte[]>> pruneNonReplicaEntries(List<Versioned<byte[]>> vals,\n List<Integer> keyReplicas,\n MutableBoolean didPrune) {\n List<Versioned<byte[]>> prunedVals = new ArrayList<Versioned<byte[]>>(vals.size());\n for(Versioned<byte[]> val: vals) {\n VectorClock clock = (VectorClock) val.getVersion();\n List<ClockEntry> clockEntries = new ArrayList<ClockEntry>();\n for(ClockEntry clockEntry: clock.getEntries()) {\n if(keyReplicas.contains((int) clockEntry.getNodeId())) {\n clockEntries.add(clockEntry);\n } else {\n didPrune.setValue(true);\n }\n }\n prunedVals.add(new Versioned<byte[]>(val.getValue(),\n new VectorClock(clockEntries, clock.getTimestamp())));\n }\n return prunedVals;\n }",
"public FieldType getFieldByAlias(FieldTypeClass typeClass, String alias)\n {\n return m_aliasMap.get(new Pair<FieldTypeClass, String>(typeClass, alias));\n }",
"protected void parseRoutingCodeHeader() {\n\n String rtCode = this.request.getHeader(RestMessageHeaders.X_VOLD_ROUTING_TYPE_CODE);\n if(rtCode != null) {\n try {\n int routingTypeCode = Integer.parseInt(rtCode);\n this.parsedRoutingType = RequestRoutingType.getRequestRoutingType(routingTypeCode);\n } catch(NumberFormatException nfe) {\n logger.error(\"Exception when validating request. Incorrect routing type parameter. Cannot parse this to long: \"\n + rtCode,\n nfe);\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Incorrect routing type parameter. Cannot parse this to long: \"\n + rtCode);\n } catch(VoldemortException ve) {\n logger.error(\"Exception when validating request. Incorrect routing type code: \"\n + rtCode, ve);\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Incorrect routing type code: \" + rtCode);\n }\n }\n }",
"<P extends PatchingArtifact.ArtifactState, S extends PatchingArtifact.ArtifactState> PatchingArtifactStateHandler<S> getHandlerForArtifact(PatchingArtifact<P, S> artifact) {\n return handlers.get(artifact);\n }",
"public void addResourceAssignment(ResourceAssignment assignment)\n {\n if (getExistingResourceAssignment(assignment.getResource()) == null)\n {\n m_assignments.add(assignment);\n getParentFile().getResourceAssignments().add(assignment);\n\n Resource resource = assignment.getResource();\n if (resource != null)\n {\n resource.addResourceAssignment(assignment);\n }\n }\n }",
"public static base_responses update(nitro_service client, clusternodegroup resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tclusternodegroup updateresources[] = new clusternodegroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new clusternodegroup();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].strict = resources[i].strict;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public List<Cluster> cluster(final Collection<Point2D> points) {\n \tfinal List<Cluster> clusters = new ArrayList<Cluster>();\n final Map<Point2D, PointStatus> visited = new HashMap<Point2D, DBScan.PointStatus>();\n\n KDTree<Point2D> tree = new KDTree<Point2D>(2);\n \n // Populate the kdTree\n for (final Point2D point : points) {\n \tdouble[] key = {point.x, point.y};\n \ttree.insert(key, point);\n }\n \n for (final Point2D point : points) {\n if (visited.get(point) != null) {\n continue;\n }\n final List<Point2D> neighbors = getNeighbors(point, tree);\n if (neighbors.size() >= minPoints) {\n // DBSCAN does not care about center points\n final Cluster cluster = new Cluster(clusters.size());\n clusters.add(expandCluster(cluster, point, neighbors, tree, visited));\n } else {\n visited.put(point, PointStatus.NOISE);\n }\n }\n\n for (Cluster cluster : clusters) {\n \tcluster.calculateCentroid();\n }\n \n return clusters;\n }"
] |
Send an album art update announcement to all registered listeners. | [
"private void deliverAlbumArtUpdate(int player, AlbumArt art) {\n if (!getAlbumArtListeners().isEmpty()) {\n final AlbumArtUpdate update = new AlbumArtUpdate(player, art);\n for (final AlbumArtListener listener : getAlbumArtListeners()) {\n try {\n listener.albumArtChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering album art update to listener\", t);\n }\n }\n }\n }"
] | [
"private License getLicense(final String licenseId) {\n License result = null;\n final Set<DbLicense> matchingLicenses = licenseMatcher.getMatchingLicenses(licenseId);\n\n if (matchingLicenses.isEmpty()) {\n result = DataModelFactory.createLicense(\"#\" + licenseId + \"# (to be identified)\", NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET, NOT_IDENTIFIED_YET);\n result.setUnknown(true);\n } else {\n if (matchingLicenses.size() > 1 && LOG.isWarnEnabled()) {\n LOG.warn(String.format(\"%s matches multiple licenses %s. \" +\n \"Please run the report showing multiple matching on licenses\",\n licenseId, matchingLicenses.toString()));\n }\n result = mapper.getLicense(matchingLicenses.iterator().next());\n\n }\n\n return result;\n }",
"public static appfwwsdl get(nitro_service service, String name) throws Exception{\n\t\tappfwwsdl obj = new appfwwsdl();\n\t\tobj.set_name(name);\n\t\tappfwwsdl response = (appfwwsdl) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private void compile(ICompilationUnit[] sourceUnits, boolean lastRound) {\n this.stats.startTime = System.currentTimeMillis();\n try {\n // build and record parsed units\n reportProgress(Messages.compilation_beginningToCompile);\n\n if (this.options.complianceLevel >= ClassFileConstants.JDK9) {\n // in Java 9 the compiler must never ask the oracle for a module that is contained in the input units:\n sortModuleDeclarationsFirst(sourceUnits);\n }\n if (this.annotationProcessorManager == null) {\n beginToCompile(sourceUnits);\n } else {\n ICompilationUnit[] originalUnits = sourceUnits.clone(); // remember source units in case a source type collision occurs\n try {\n beginToCompile(sourceUnits);\n if (!lastRound) {\n processAnnotations();\n }\n if (!this.options.generateClassFiles) {\n // -proc:only was set on the command line\n return;\n }\n } catch (SourceTypeCollisionException e) {\n backupAptProblems();\n reset();\n // a generated type was referenced before it was created\n // the compiler either created a MissingType or found a BinaryType for it\n // so add the processor's generated files & start over,\n // but remember to only pass the generated files to the annotation processor\n int originalLength = originalUnits.length;\n int newProcessedLength = e.newAnnotationProcessorUnits.length;\n ICompilationUnit[] combinedUnits = new ICompilationUnit[originalLength + newProcessedLength];\n System.arraycopy(originalUnits, 0, combinedUnits, 0, originalLength);\n System.arraycopy(e.newAnnotationProcessorUnits, 0, combinedUnits, originalLength, newProcessedLength);\n this.annotationProcessorStartIndex = originalLength;\n compile(combinedUnits, e.isLastRound);\n return;\n }\n }\n // Restore the problems before the results are processed and cleaned up.\n restoreAptProblems();\n processCompiledUnits(0, lastRound);\n } catch (AbortCompilation e) {\n this.handleInternalException(e, null);\n }\n if (this.options.verbose) {\n if (this.totalUnits > 1) {\n this.out.println(\n Messages.bind(Messages.compilation_units, String.valueOf(this.totalUnits)));\n } else {\n this.out.println(\n Messages.bind(Messages.compilation_unit, String.valueOf(this.totalUnits)));\n }\n }\n }",
"@Override\n public void run()\n {\n try {\n startBarrier.await();\n\n int idleCount = 0;\n while (!isRunning.compareAndSet(idleCount > LINGER_ITERATIONS && deadPool.isEmpty() && completionKeyToProcessMap.isEmpty(), false)) {\n idleCount = (!shutdown && process()) ? 0 : (idleCount + 1);\n }\n }\n catch (Exception e) {\n // TODO: how to handle this error?\n e.printStackTrace();\n isRunning.set(false);\n }\n }",
"private void toCorrectDateWithDay(Calendar date, WeekOfMonth week) {\n\n date.set(Calendar.DAY_OF_MONTH, 1);\n int daysToFirstWeekDayMatch = ((m_weekDay.toInt() + I_CmsSerialDateValue.NUM_OF_WEEKDAYS)\n - (date.get(Calendar.DAY_OF_WEEK))) % I_CmsSerialDateValue.NUM_OF_WEEKDAYS;\n date.add(Calendar.DAY_OF_MONTH, daysToFirstWeekDayMatch);\n int wouldBeDayOfMonth = date.get(Calendar.DAY_OF_MONTH)\n + ((week.ordinal()) * I_CmsSerialDateValue.NUM_OF_WEEKDAYS);\n if (wouldBeDayOfMonth > date.getActualMaximum(Calendar.DAY_OF_MONTH)) {\n date.set(Calendar.DAY_OF_MONTH, wouldBeDayOfMonth - I_CmsSerialDateValue.NUM_OF_WEEKDAYS);\n } else {\n date.set(Calendar.DAY_OF_MONTH, wouldBeDayOfMonth);\n }\n\n }",
"public void setOutRGB(IntRange outRGB) {\r\n this.outRed = outRGB;\r\n this.outGreen = outRGB;\r\n this.outBlue = outRGB;\r\n\r\n CalculateMap(inRed, outRGB, mapRed);\r\n CalculateMap(inGreen, outRGB, mapGreen);\r\n CalculateMap(inBlue, outRGB, mapBlue);\r\n }",
"private void addMetadataProviderForMedia(String key, MetadataProvider provider) {\n if (!metadataProviders.containsKey(key)) {\n metadataProviders.put(key, Collections.newSetFromMap(new ConcurrentHashMap<MetadataProvider, Boolean>()));\n }\n Set<MetadataProvider> providers = metadataProviders.get(key);\n providers.add(provider);\n }",
"public AT_Row setPaddingBottomChar(Character paddingBottomChar) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingBottomChar(paddingBottomChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"private void started(final ProcessorGraphNode processorGraphNode) {\n this.processorLock.lock();\n try {\n this.runningProcessors.put(processorGraphNode.getProcessor(), null);\n } finally {\n this.processorLock.unlock();\n }\n }"
] |
Parse a percent complete value.
@param value sting representation of a percent complete value.
@return Double instance | [
"public static final Double parsePercent(String value)\n {\n return value == null ? null : Double.valueOf(Double.parseDouble(value) * 100.0);\n }"
] | [
"private void tryToSetParsedValue(String value) throws Exception {\n\n JSONObject json = JSONParser.parseStrict(value).isObject();\n JSONValue val = json.get(JsonKey.START);\n setStart(readOptionalDate(val));\n val = json.get(JsonKey.END);\n setEnd(readOptionalDate(val));\n setWholeDay(readOptionalBoolean(json.get(JsonKey.WHOLE_DAY)));\n JSONObject patternJson = json.get(JsonKey.PATTERN).isObject();\n readPattern(patternJson);\n setExceptions(readDates(json.get(JsonKey.EXCEPTIONS)));\n setSeriesEndDate(readOptionalDate(json.get(JsonKey.SERIES_ENDDATE)));\n setOccurrences(readOptionalInt(json.get(JsonKey.SERIES_OCCURRENCES)));\n setDerivedEndType();\n setCurrentTillEnd(readOptionalBoolean(json.get(JsonKey.CURRENT_TILL_END)));\n setParentSeriesId(readOptionalUUID(json.get(JsonKey.PARENT_SERIES)));\n\n }",
"private synchronized Constructor getIndirectionHandlerConstructor()\r\n {\r\n if(_indirectionHandlerConstructor == null)\r\n {\r\n Class[] paramType = {PBKey.class, Identity.class};\r\n\r\n try\r\n {\r\n _indirectionHandlerConstructor = getIndirectionHandlerClass().getConstructor(paramType);\r\n }\r\n catch(NoSuchMethodException ex)\r\n {\r\n throw new MetadataException(\"The class \"\r\n + _indirectionHandlerClass.getName()\r\n + \" specified for IndirectionHandlerClass\"\r\n + \" is required to have a public constructor with signature (\"\r\n + PBKey.class.getName()\r\n + \", \"\r\n + Identity.class.getName()\r\n + \").\");\r\n }\r\n }\r\n return _indirectionHandlerConstructor;\r\n }",
"public static boolean isRegularQueue(final Jedis jedis, final String key) {\n return LIST.equalsIgnoreCase(jedis.type(key));\n }",
"public void orderSets(String[] photosetIds) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ORDER_SETS);\r\n ;\r\n\r\n parameters.put(\"photoset_ids\", StringUtilities.join(photosetIds, \",\"));\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"public static Stack getStack() {\n Stack stack = interceptionContexts.get();\n if (stack == null) {\n stack = new Stack(interceptionContexts);\n interceptionContexts.set(stack);\n }\n return stack;\n }",
"@RequestMapping(value = \"api/servergroup\", method = RequestMethod.GET)\n public\n @ResponseBody\n HashMap<String, Object> getServerGroups(Model model,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"search\", required = false) String search,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier) throws Exception {\n if (profileId == null && profileIdentifier == null) {\n throw new Exception(\"profileId required\");\n }\n if (profileId == null) {\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n }\n\n List<ServerGroup> serverGroups = ServerRedirectService.getInstance().tableServerGroups(profileId);\n\n if (search != null) {\n Iterator<ServerGroup> iterator = serverGroups.iterator();\n while (iterator.hasNext()) {\n ServerGroup serverGroup = iterator.next();\n if (!serverGroup.getName().toLowerCase().contains(search.toLowerCase())) {\n iterator.remove();\n }\n }\n }\n HashMap<String, Object> returnJson = Utils.getJQGridJSON(serverGroups, \"servergroups\");\n return returnJson;\n }",
"protected Element createTextElement(String data, float width)\n {\n Element el = createTextElement(width);\n Text text = doc.createTextNode(data);\n el.appendChild(text);\n return el;\n }",
"protected String statusMsg(final String queue, final Job job) throws IOException {\n final WorkerStatus status = new WorkerStatus();\n status.setRunAt(new Date());\n status.setQueue(queue);\n status.setPayload(job);\n return ObjectMapperFactory.get().writeValueAsString(status);\n }",
"synchronized int storeObject(JSONObject obj, Table table) {\n if (!this.belowMemThreshold()) {\n Logger.v(\"There is not enough space left on the device to store data, data discarded\");\n return DB_OUT_OF_MEMORY_ERROR;\n }\n\n final String tableName = table.getName();\n\n Cursor cursor = null;\n int count = DB_UPDATE_ERROR;\n\n //noinspection TryFinallyCanBeTryWithResources\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n\n final ContentValues cv = new ContentValues();\n cv.put(KEY_DATA, obj.toString());\n cv.put(KEY_CREATED_AT, System.currentTimeMillis());\n db.insert(tableName, null, cv);\n cursor = db.rawQuery(\"SELECT COUNT(*) FROM \" + tableName, null);\n cursor.moveToFirst();\n count = cursor.getInt(0);\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error adding data to table \" + tableName + \" Recreating DB\");\n\n if (cursor != null) {\n cursor.close();\n cursor = null;\n }\n dbHelper.deleteDatabase();\n } finally {\n if (cursor != null) {\n cursor.close();\n }\n dbHelper.close();\n }\n return count;\n }"
] |
This produces a string with no compressed segments and all segments of full length,
which is 4 characters for IPv6 segments and 3 characters for IPv4 segments. | [
"@Override\n\tpublic String toFullString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = getStringCache().fullString) == null) {\n\t\t\tgetStringCache().fullString = result = toNormalizedString(IPv6StringCache.fullParams);\n\t\t}\n\t\treturn result;\n\t}"
] | [
"static void addDeployOperationStep(final CompositeOperationBuilder builder, final DeploymentDescription deployment) {\n final String name = deployment.getName();\n\n final Set<String> serverGroups = deployment.getServerGroups();\n // If the server groups are empty this is a standalone deployment\n if (serverGroups.isEmpty()) {\n final ModelNode address = createAddress(DEPLOYMENT, name);\n builder.addStep(createOperation(DEPLOYMENT_DEPLOY_OPERATION, address));\n } else {\n for (String serverGroup : serverGroups) {\n final ModelNode address = createAddress(SERVER_GROUP, serverGroup, DEPLOYMENT, name);\n builder.addStep(createOperation(DEPLOYMENT_DEPLOY_OPERATION, address));\n }\n }\n }",
"public static nsrpcnode get(nitro_service service, String ipaddress) throws Exception{\n\t\tnsrpcnode obj = new nsrpcnode();\n\t\tobj.set_ipaddress(ipaddress);\n\t\tnsrpcnode response = (nsrpcnode) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public synchronized Message menuRequestTyped(Message.KnownType requestType, Message.MenuIdentifier targetMenu,\n CdjStatus.TrackSourceSlot slot, CdjStatus.TrackType trackType, Field... arguments)\n throws IOException {\n\n if (!menuLock.isHeldByCurrentThread()) {\n throw new IllegalStateException(\"renderMenuItems() cannot be called without first successfully calling tryLockingForMenuOperation()\");\n }\n\n Field[] combinedArguments = new Field[arguments.length + 1];\n combinedArguments[0] = buildRMST(targetMenu, slot, trackType);\n System.arraycopy(arguments, 0, combinedArguments, 1, arguments.length);\n final Message response = simpleRequest(requestType, Message.KnownType.MENU_AVAILABLE, combinedArguments);\n final NumberField reportedRequestType = (NumberField)response.arguments.get(0);\n if (reportedRequestType.getValue() != requestType.protocolValue) {\n throw new IOException(\"Menu request did not return result for same type as request; sent type: \" +\n requestType.protocolValue + \", received type: \" + reportedRequestType.getValue() +\n \", response: \" + response);\n }\n return response;\n }",
"private boolean isNullOrEmpty(Object paramValue) {\n boolean isNullOrEmpty = false;\n if (paramValue == null) {\n isNullOrEmpty = true;\n }\n if (paramValue instanceof String) {\n if (((String) paramValue).trim().equalsIgnoreCase(\"\")) {\n isNullOrEmpty = true;\n }\n } else if (paramValue instanceof List) {\n return ((List) paramValue).isEmpty();\n }\n return isNullOrEmpty;\n }",
"public double getDurationMs() {\n double durationMs = 0;\n for (Duration duration : durations) {\n if (duration.taskFinished()) {\n durationMs += duration.getDurationMS();\n }\n }\n return durationMs;\n }",
"private void writeResources() throws IOException\n {\n writeAttributeTypes(\"resource_types\", ResourceField.values());\n\n m_writer.writeStartList(\"resources\");\n for (Resource resource : m_projectFile.getResources())\n {\n writeFields(null, resource, ResourceField.values());\n }\n m_writer.writeEndList();\n }",
"public ResponseFromManager generateUpdateExecuteTask(ParallelTask task) {\n\n // add to map now; as can only pass final\n ParallelTaskManager.getInstance().addTaskToInProgressMap(\n task.getTaskId(), task);\n logger.info(\"Added task {} to the running inprogress map...\",\n task.getTaskId());\n\n boolean useReplacementVarMap = false;\n boolean useReplacementVarMapNodeSpecific = false;\n Map<String, StrStrMap> replacementVarMapNodeSpecific = null;\n Map<String, String> replacementVarMap = null;\n\n ResponseFromManager batchResponseFromManager = null;\n\n switch (task.getRequestReplacementType()) {\n case UNIFORM_VAR_REPLACEMENT:\n useReplacementVarMap = true;\n useReplacementVarMapNodeSpecific = false;\n replacementVarMap = task.getReplacementVarMap();\n break;\n case TARGET_HOST_SPECIFIC_VAR_REPLACEMENT:\n useReplacementVarMap = false;\n useReplacementVarMapNodeSpecific = true;\n replacementVarMapNodeSpecific = task\n .getReplacementVarMapNodeSpecific();\n break;\n case NO_REPLACEMENT:\n useReplacementVarMap = false;\n useReplacementVarMapNodeSpecific = false;\n break;\n default:\n logger.error(\"error request replacement type. default as no replacement\");\n }// end switch\n\n // generate content in nodedata\n InternalDataProvider dp = InternalDataProvider.getInstance();\n dp.genNodeDataMap(task);\n\n VarReplacementProvider.getInstance()\n .updateRequestWithReplacement(task, useReplacementVarMap,\n replacementVarMap, useReplacementVarMapNodeSpecific,\n replacementVarMapNodeSpecific);\n\n batchResponseFromManager = \n sendTaskToExecutionManager(task);\n\n removeTaskFromInProgressMap(task.getTaskId());\n logger.info(\n \"Removed task {} from the running inprogress map... \"\n + \". This task should be garbage collected if there are no other pointers.\",\n task.getTaskId());\n return batchResponseFromManager;\n\n }",
"public static File[] getVersionDirs(File rootDir, final long minId, final long maxId) {\n return rootDir.listFiles(new FileFilter() {\n\n public boolean accept(File pathName) {\n if(checkVersionDirName(pathName)) {\n long versionId = getVersionId(pathName);\n if(versionId != -1 && versionId <= maxId && versionId >= minId) {\n return true;\n }\n }\n return false;\n }\n });\n }",
"public Association getAssociation(String collectionRole) {\n\t\tif ( associations == null ) {\n\t\t\treturn null;\n\t\t}\n\t\treturn associations.get( collectionRole );\n\t}"
] |
Calculates the radius to a given boundedness value
@param D Diffusion coefficient
@param N Number of steps
@param timelag Timelag
@param B Boundedeness
@return Confinement radius | [
"public static double getRadiusToBoundedness(double D, int N, double timelag, double B){\n\t\tdouble cov_area = a(N)*D*timelag;\n\t\tdouble radius = Math.sqrt(cov_area/(4*B));\n\t\treturn radius;\n\t}"
] | [
"private GenericCriteriaPrompt getPromptValue(FieldType field, byte[] block)\n {\n int textOffset = getPromptOffset(block);\n String value = MPPUtility.getUnicodeString(m_criteriaData, m_criteriaTextStart + textOffset);\n GenericCriteriaPrompt prompt = new GenericCriteriaPrompt(field.getDataType(), value);\n if (m_prompts != null)\n {\n m_prompts.add(prompt);\n }\n return prompt;\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<AccountingDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<AccountingDate>) super.zonedDateTime(temporal);\n }",
"public void addProjectListeners(List<ProjectListener> listeners)\n {\n if (listeners != null)\n {\n for (ProjectListener listener : listeners)\n {\n addProjectListener(listener);\n }\n }\n }",
"public DbConn getConn()\n {\n Connection cnx = null;\n try\n {\n Thread.interrupted(); // this is VERY sad. Needed for Oracle driver which otherwise fails spectacularly.\n cnx = _ds.getConnection();\n if (cnx.getAutoCommit())\n {\n cnx.setAutoCommit(false);\n cnx.rollback(); // To ensure no open transaction created by the pool before changing TX mode\n }\n\n if (cnx.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED)\n {\n cnx.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);\n }\n\n return new DbConn(this, cnx);\n }\n catch (SQLException e)\n {\n DbHelper.closeQuietly(cnx); // May have been left open when the pool has given us a failed connection.\n throw new DatabaseException(e);\n }\n }",
"private <T extends TimephasedItem<?>> int getStartIndex(DateRange range, List<T> assignments, int startIndex)\n {\n int result = -1;\n if (assignments != null)\n {\n long rangeStart = range.getStart().getTime();\n long rangeEnd = range.getEnd().getTime();\n\n for (int loop = startIndex; loop < assignments.size(); loop++)\n {\n T assignment = assignments.get(loop);\n int compareResult = DateHelper.compare(assignment.getStart(), assignment.getFinish(), rangeStart);\n\n //\n // The start of the target range falls after the assignment end -\n // move on to test the next assignment.\n //\n if (compareResult > 0)\n {\n continue;\n }\n\n //\n // The start of the target range falls within the assignment -\n // return the index of this assignment to the caller.\n //\n if (compareResult == 0)\n {\n result = loop;\n break;\n }\n\n //\n // At this point, we know that the start of the target range is before\n // the assignment start. We need to determine if the end of the\n // target range overlaps the assignment.\n //\n compareResult = DateHelper.compare(assignment.getStart(), assignment.getFinish(), rangeEnd);\n if (compareResult >= 0)\n {\n result = loop;\n break;\n }\n }\n }\n return result;\n }",
"public void process(DirectoryEntry projectDir, ProjectFile file, DocumentInputStreamFactory inputStreamFactory) throws IOException\n {\n DirectoryEntry consDir;\n try\n {\n consDir = (DirectoryEntry) projectDir.getEntry(\"TBkndCons\");\n }\n\n catch (FileNotFoundException ex)\n {\n consDir = null;\n }\n\n if (consDir != null)\n {\n FixedMeta consFixedMeta = new FixedMeta(new DocumentInputStream(((DocumentEntry) consDir.getEntry(\"FixedMeta\"))), 10);\n FixedData consFixedData = new FixedData(consFixedMeta, 20, inputStreamFactory.getInstance(consDir, \"FixedData\"));\n // FixedMeta consFixed2Meta = new FixedMeta(new DocumentInputStream(((DocumentEntry) consDir.getEntry(\"Fixed2Meta\"))), 9);\n // FixedData consFixed2Data = new FixedData(consFixed2Meta, 48, getEncryptableInputStream(consDir, \"Fixed2Data\"));\n\n int count = consFixedMeta.getAdjustedItemCount();\n int lastConstraintID = -1;\n\n ProjectProperties properties = file.getProjectProperties();\n EventManager eventManager = file.getEventManager();\n\n boolean project15 = NumberHelper.getInt(properties.getMppFileType()) == 14 && NumberHelper.getInt(properties.getApplicationVersion()) > ApplicationVersion.PROJECT_2010;\n int durationUnitsOffset = project15 ? 18 : 14;\n int durationOffset = project15 ? 14 : 16;\n\n for (int loop = 0; loop < count; loop++)\n {\n byte[] metaData = consFixedMeta.getByteArrayValue(loop);\n\n //\n // SourceForge bug 2209477: we were reading an int here, but\n // it looks like the deleted flag is just a short.\n //\n if (MPPUtility.getShort(metaData, 0) != 0)\n {\n continue;\n }\n\n int index = consFixedData.getIndexFromOffset(MPPUtility.getInt(metaData, 4));\n if (index == -1)\n {\n continue;\n }\n\n //\n // Do we have enough data?\n //\n byte[] data = consFixedData.getByteArrayValue(index);\n if (data.length < 14)\n {\n continue;\n }\n\n int constraintID = MPPUtility.getInt(data, 0);\n if (constraintID <= lastConstraintID)\n {\n continue;\n }\n\n lastConstraintID = constraintID;\n int taskID1 = MPPUtility.getInt(data, 4);\n int taskID2 = MPPUtility.getInt(data, 8);\n\n if (taskID1 == taskID2)\n {\n continue;\n }\n\n // byte[] metaData2 = consFixed2Meta.getByteArrayValue(loop);\n // int index2 = consFixed2Data.getIndexFromOffset(MPPUtility.getInt(metaData2, 4));\n // byte[] data2 = consFixed2Data.getByteArrayValue(index2);\n\n Task task1 = file.getTaskByUniqueID(Integer.valueOf(taskID1));\n Task task2 = file.getTaskByUniqueID(Integer.valueOf(taskID2));\n if (task1 != null && task2 != null)\n {\n RelationType type = RelationType.getInstance(MPPUtility.getShort(data, 12));\n TimeUnit durationUnits = MPPUtility.getDurationTimeUnits(MPPUtility.getShort(data, durationUnitsOffset));\n Duration lag = MPPUtility.getAdjustedDuration(properties, MPPUtility.getInt(data, durationOffset), durationUnits);\n Relation relation = task2.addPredecessor(task1, type, lag);\n relation.setUniqueID(Integer.valueOf(constraintID));\n eventManager.fireRelationReadEvent(relation);\n }\n }\n }\n }",
"public static sslaction get(nitro_service service, String name) throws Exception{\n\t\tsslaction obj = new sslaction();\n\t\tobj.set_name(name);\n\t\tsslaction response = (sslaction) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public boolean isActive(int profileId) {\n boolean active = false;\n PreparedStatement queryStatement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT \" + Constants.CLIENT_IS_ACTIVE + \" FROM \" + Constants.DB_TABLE_CLIENT +\n \" WHERE \" + Constants.GENERIC_CLIENT_UUID + \"= '-1' \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \"= ? \"\n );\n queryStatement.setInt(1, profileId);\n logger.info(queryStatement.toString());\n ResultSet results = queryStatement.executeQuery();\n if (results.next()) {\n active = results.getBoolean(Constants.CLIENT_IS_ACTIVE);\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return active;\n }",
"private void setViewPagerScroller() {\n try {\n Field scrollerField = ViewPager.class.getDeclaredField(\"mScroller\");\n scrollerField.setAccessible(true);\n Field interpolatorField = ViewPager.class.getDeclaredField(\"sInterpolator\");\n interpolatorField.setAccessible(true);\n\n scroller = new CustomDurationScroller(getContext(), (Interpolator)interpolatorField.get(null));\n scrollerField.set(this, scroller);\n } catch (Exception e) {\n e.printStackTrace();\n }\n }"
] |
This method extracts task data from a Planner file.
@param plannerProject Root node of the Planner file | [
"private void readTasks(Project plannerProject) throws MPXJException\n {\n Tasks tasks = plannerProject.getTasks();\n if (tasks != null)\n {\n for (net.sf.mpxj.planner.schema.Task task : tasks.getTask())\n {\n readTask(null, task);\n }\n\n for (net.sf.mpxj.planner.schema.Task task : tasks.getTask())\n {\n readPredecessors(task);\n }\n }\n\n m_projectFile.updateStructure();\n }"
] | [
"public void setShortVec(char[] data)\n {\n if (data == null)\n {\n throw new IllegalArgumentException(\"Input data for indices cannot be null\");\n }\n if (getIndexSize() != 2)\n {\n throw new UnsupportedOperationException(\"Cannot update integer indices with char array\");\n }\n if (!NativeIndexBuffer.setShortArray(getNative(), data))\n {\n throw new UnsupportedOperationException(\"Input array is wrong size\");\n }\n }",
"public DateRange getRange(int index)\n {\n DateRange result;\n\n if (index >= 0 && index < m_ranges.size())\n {\n result = m_ranges.get(index);\n }\n else\n {\n result = DateRange.EMPTY_RANGE;\n }\n\n return (result);\n }",
"public static String getDatatypeIriFromJsonDatatype(String jsonDatatype) {\n\t\tswitch (jsonDatatype) {\n\t\tcase JSON_DT_ITEM:\n\t\t\treturn DT_ITEM;\n\t\tcase JSON_DT_PROPERTY:\n\t\t\treturn DT_PROPERTY;\n\t\tcase JSON_DT_GLOBE_COORDINATES:\n\t\t\treturn DT_GLOBE_COORDINATES;\n\t\tcase JSON_DT_URL:\n\t\t\treturn DT_URL;\n\t\tcase JSON_DT_COMMONS_MEDIA:\n\t\t\treturn DT_COMMONS_MEDIA;\n\t\tcase JSON_DT_TIME:\n\t\t\treturn DT_TIME;\n\t\tcase JSON_DT_QUANTITY:\n\t\t\treturn DT_QUANTITY;\n\t\tcase JSON_DT_STRING:\n\t\t\treturn DT_STRING;\n\t\tcase JSON_DT_MONOLINGUAL_TEXT:\n\t\t\treturn DT_MONOLINGUAL_TEXT;\n\t\tdefault:\n\t\t\tif(!JSON_DATATYPE_PATTERN.matcher(jsonDatatype).matches()) {\n\t\t\t\tthrow new IllegalArgumentException(\"Invalid JSON datatype \\\"\" + jsonDatatype + \"\\\"\");\n\t\t\t}\n\n\t\t\tString[] parts = jsonDatatype.split(\"-\");\n\t\t\tfor(int i = 0; i < parts.length; i++) {\n\t\t\t\tparts[i] = StringUtils.capitalize(parts[i]);\n\t\t\t}\n\t\t\treturn \"http://wikiba.se/ontology#\" + StringUtils.join(parts);\n\t\t}\n\t}",
"private void countEntity() {\n\t\tif (!this.timer.isRunning()) {\n\t\t\tstartTimer();\n\t\t}\n\n\t\tthis.entityCount++;\n\t\tif (this.entityCount % 100 == 0) {\n\t\t\ttimer.stop();\n\t\t\tint seconds = (int) (timer.getTotalWallTime() / 1000000000);\n\t\t\tif (seconds >= this.lastSeconds + this.reportInterval) {\n\t\t\t\tthis.lastSeconds = seconds;\n\t\t\t\tprintStatus();\n\t\t\t\tif (this.timeout > 0 && seconds > this.timeout) {\n\t\t\t\t\tlogger.info(\"Timeout. Aborting processing.\");\n\t\t\t\t\tthrow new TimeoutException();\n\t\t\t\t}\n\t\t\t}\n\t\t\ttimer.start();\n\t\t}\n\t}",
"public boolean isWellKnownIPv4Translatable() { //rfc 6052 rfc 6144\n\t\t//64:ff9b::/96 prefix for auto ipv4/ipv6 translation\n\t\tif(getSegment(0).matches(0x64) && getSegment(1).matches(0xff9b)) {\n\t\t\tfor(int i=2; i<=5; i++) {\n\t\t\t\tif(!getSegment(i).isZero()) {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}",
"private String getCacheFormatEntry() throws IOException {\n ZipEntry zipEntry = zipFile.getEntry(CACHE_FORMAT_ENTRY);\n InputStream is = zipFile.getInputStream(zipEntry);\n try {\n Scanner s = new Scanner(is, \"UTF-8\").useDelimiter(\"\\\\A\");\n String tag = null;\n if (s.hasNext()) tag = s.next();\n return tag;\n } finally {\n is.close();\n }\n }",
"private void map(Resource root) {\n\n for (Resource.ResourceEntry serverGroup : root.getChildren(SERVER_GROUP)) {\n String serverGroupName = serverGroup.getName();\n ModelNode serverGroupModel = serverGroup.getModel();\n String profile = serverGroupModel.require(PROFILE).asString();\n store(serverGroupName, profile, profilesToGroups);\n String socketBindingGroup = serverGroupModel.require(SOCKET_BINDING_GROUP).asString();\n store(serverGroupName, socketBindingGroup, socketsToGroups);\n\n for (Resource.ResourceEntry deployment : serverGroup.getChildren(DEPLOYMENT)) {\n store(serverGroupName, deployment.getName(), deploymentsToGroups);\n }\n\n for (Resource.ResourceEntry overlay : serverGroup.getChildren(DEPLOYMENT_OVERLAY)) {\n store(serverGroupName, overlay.getName(), overlaysToGroups);\n }\n\n }\n\n for (Resource.ResourceEntry host : root.getChildren(HOST)) {\n String hostName = host.getPathElement().getValue();\n for (Resource.ResourceEntry serverConfig : host.getChildren(SERVER_CONFIG)) {\n ModelNode serverConfigModel = serverConfig.getModel();\n String serverGroupName = serverConfigModel.require(GROUP).asString();\n store(serverGroupName, hostName, hostsToGroups);\n }\n }\n }",
"public void setHomeAsUpIndicator(Drawable indicator) {\n if(!deviceSupportMultiPane()) {\n pulsante.setHomeAsUpIndicator(indicator);\n }\n else {\n actionBar.setHomeAsUpIndicator(indicator);\n }\n }",
"@SuppressWarnings(\"unchecked\")\n public static <T extends Serializable> T makeClone(T from) {\n return (T) SerializationUtils.clone(from);\n }"
] |
Find a given range object in a list of ranges by a value in that range. Does a binary
search over the ranges but instead of checking for equality looks within the range.
Takes the array size as an option in case the array grows while searching happens
@param <T> Range type
@param ranges data list
@param value value in the list
@param arraySize the max search index of the list
@return search result of range
TODO: This should move into SegmentList.scala | [
"public static <T extends Range> T findRange(List<T> ranges, long value, int arraySize) {\n if (ranges.size() < 1) return null;\n T first = ranges.get(0);\n T last = ranges.get(arraySize - 1);\n // check out of bounds\n if (value < first.start() || value > last.start() + last.size()) {\n throw new OffsetOutOfRangeException(format(\"offset %s is out of range (%s, %s)\",//\n value,first.start(),last.start()+last.size()));\n }\n\n // check at the end\n if (value == last.start() + last.size()) return null;\n\n int low = 0;\n int high = arraySize - 1;\n while (low <= high) {\n int mid = (high + low) / 2;\n T found = ranges.get(mid);\n if (found.contains(value)) {\n return found;\n } else if (value < found.start()) {\n high = mid - 1;\n } else {\n low = mid + 1;\n }\n }\n return null;\n }"
] | [
"public static final PolylineOptions buildOpenArc(LatLong center, LatLong start, LatLong end) {\n MVCArray res = buildArcPoints(center, start, end);\n return new PolylineOptions().path(res);\n }",
"public static CrashReport fromJson(String json) throws IllegalArgumentException {\n try {\n return new CrashReport(json);\n } catch (JSONException je) {\n throw new IllegalArgumentException(je.toString());\n }\n }",
"protected CmsAccessControlEntry getImportAccessControlEntry(\n CmsResource res,\n String id,\n String allowed,\n String denied,\n String flags) {\n\n return new CmsAccessControlEntry(\n res.getResourceId(),\n new CmsUUID(id),\n Integer.parseInt(allowed),\n Integer.parseInt(denied),\n Integer.parseInt(flags));\n }",
"protected void solveL(double[] vv) {\n\n int ii = 0;\n\n for( int i = 0; i < n; i++ ) {\n int ip = indx[i];\n double sumReal = vv[ip*2];\n double sumImg = vv[ip*2+1];\n\n vv[ip*2] = vv[i*2];\n vv[ip*2+1] = vv[i*2+1];\n\n if( ii != 0 ) {\n// for( int j = ii-1; j < i; j++ )\n// sum -= dataLU[i* n +j]*vv[j];\n int index = i*stride + (ii-1)*2;\n for( int j = ii-1; j < i; j++ ){\n double luReal = dataLU[index++];\n double luImg = dataLU[index++];\n\n double vvReal = vv[j*2];\n double vvImg = vv[j*2+1];\n\n sumReal -= luReal*vvReal - luImg*vvImg;\n sumImg -= luReal*vvImg + luImg*vvReal;\n }\n } else if( sumReal*sumReal + sumImg*sumImg != 0.0 ) {\n ii=i+1;\n }\n vv[i*2] = sumReal;\n vv[i*2+1] = sumImg;\n }\n }",
"private static boolean validateEndRecord(File file, FileChannel channel, long startEndRecord, long endSig) throws IOException {\n\n try {\n channel.position(startEndRecord);\n\n final ByteBuffer endDirHeader = getByteBuffer(ENDLEN);\n read(endDirHeader, channel);\n if (endDirHeader.limit() < ENDLEN) {\n // Couldn't read the full end of central directory record header\n return false;\n } else if (getUnsignedInt(endDirHeader, 0) != endSig) {\n return false;\n }\n\n long pos = getUnsignedInt(endDirHeader, END_CENSTART);\n // TODO deal with Zip64\n if (pos == ZIP64_MARKER) {\n return false;\n }\n\n ByteBuffer cdfhBuffer = getByteBuffer(CENLEN);\n read(cdfhBuffer, channel, pos);\n long header = getUnsignedInt(cdfhBuffer, 0);\n if (header == CENSIG) {\n long firstLoc = getUnsignedInt(cdfhBuffer, CEN_LOC_OFFSET);\n long firstSize = getUnsignedInt(cdfhBuffer, CENSIZ);\n if (firstLoc == 0) {\n // normal case -- first bytes are the first local file\n if (!validateLocalFileRecord(channel, 0, firstSize)) {\n return false;\n }\n } else {\n // confirm that firstLoc is indeed the first local file\n long fileFirstLoc = scanForLocSig(channel);\n if (firstLoc != fileFirstLoc) {\n if (fileFirstLoc == 0) {\n return false;\n } else {\n // scanForLocSig() found a LOCSIG, but not at position zero and not\n // at the expected position.\n // With a file like this, we can't tell if we're in a nested zip\n // or we're in an outer zip and had the bad luck to find random bytes\n // that look like LOCSIG.\n return false;\n }\n }\n }\n\n // At this point, endDirHeader points to the correct end of central dir record.\n // Just need to validate the record is complete, including any comment\n int commentLen = getUnsignedShort(endDirHeader, END_COMMENTLEN);\n long commentEnd = startEndRecord + ENDLEN + commentLen;\n return commentEnd <= channel.size();\n }\n\n return false;\n } catch (EOFException eof) {\n // pos or firstLoc weren't really positions and moved us to an invalid location\n return false;\n }\n }",
"public com.squareup.okhttp.Call getCharactersCharacterIdShipCall(Integer characterId, String datasource,\n String ifNoneMatch, String token, final ApiCallback callback) throws ApiException {\n Object localVarPostBody = new Object();\n\n // create path and map variables\n String localVarPath = \"/v1/characters/{character_id}/ship/\".replaceAll(\"\\\\{\" + \"character_id\" + \"\\\\}\",\n apiClient.escapeString(characterId.toString()));\n\n List<Pair> localVarQueryParams = new ArrayList<Pair>();\n List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();\n if (datasource != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"datasource\", datasource));\n }\n\n if (token != null) {\n localVarQueryParams.addAll(apiClient.parameterToPair(\"token\", token));\n }\n\n Map<String, String> localVarHeaderParams = new HashMap<String, String>();\n if (ifNoneMatch != null) {\n localVarHeaderParams.put(\"If-None-Match\", apiClient.parameterToString(ifNoneMatch));\n }\n\n Map<String, Object> localVarFormParams = new HashMap<String, Object>();\n final String[] localVarAccepts = { \"application/json\" };\n final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);\n if (localVarAccept != null) {\n localVarHeaderParams.put(\"Accept\", localVarAccept);\n }\n\n final String[] localVarContentTypes = {\n\n };\n final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);\n localVarHeaderParams.put(\"Content-Type\", localVarContentType);\n\n String[] localVarAuthNames = new String[] { \"evesso\" };\n return apiClient.buildCall(localVarPath, \"GET\", localVarQueryParams, localVarCollectionQueryParams,\n localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, callback);\n }",
"public int createPartitions(String topic, int partitionNum, boolean enlarge) throws IOException {\n KV<Receive, ErrorMapping> response = send(new CreaterRequest(topic, partitionNum, enlarge));\n return Utils.deserializeIntArray(response.k.buffer())[0];\n }",
"public List<EnabledEndpoint> getEnabledEndpoints(int pathId, String clientUUID, String[] filters) throws Exception {\n ArrayList<EnabledEndpoint> enabledOverrides = new ArrayList<EnabledEndpoint>();\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \"=?\" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \"=?\" +\n \" ORDER BY \" + Constants.ENABLED_OVERRIDES_PRIORITY\n );\n query.setInt(1, pathId);\n query.setString(2, clientUUID);\n results = query.executeQuery();\n\n while (results.next()) {\n EnabledEndpoint endpoint = this.getPartialEnabledEndpointFromResultset(results);\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n\n // this is an errant entry.. perhaps a method got deleted from a plugin\n // we'll also remove it from the endpoint\n if (m == null) {\n PathOverrideService.getInstance().removeOverride(endpoint.getOverrideId());\n continue;\n }\n\n // check filters and see if any match\n boolean addOverride = false;\n if (filters != null) {\n for (String filter : filters) {\n if (m.getMethodType().endsWith(filter)) {\n addOverride = true;\n break;\n }\n }\n } else {\n // if there are no filters then we assume that the requester wants all enabled overrides\n addOverride = true;\n }\n\n if (addOverride) {\n enabledOverrides.add(endpoint);\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n\n // now go through the ArrayList and get the method for all of the endpoints\n // have to do this so we don't have overlapping SQL queries\n ArrayList<EnabledEndpoint> enabledOverridesWithMethods = new ArrayList<EnabledEndpoint>();\n for (EnabledEndpoint endpoint : enabledOverrides) {\n if (endpoint.getOverrideId() >= 0) {\n com.groupon.odo.proxylib.models.Method m = PathOverrideService.getInstance().getMethodForOverrideId(endpoint.getOverrideId());\n endpoint.setMethodInformation(m);\n }\n enabledOverridesWithMethods.add(endpoint);\n }\n\n return enabledOverridesWithMethods;\n }",
"private static final Duration parseDurationInFractionsOfMinutes(ProjectProperties properties, Number value, TimeUnit targetTimeUnit, int factor)\n {\n Duration result = null;\n\n if (value != null)\n {\n result = Duration.getInstance(value.intValue() / factor, TimeUnit.MINUTES);\n if (targetTimeUnit != result.getUnits())\n {\n result = result.convertUnits(targetTimeUnit, properties);\n }\n }\n\n return (result);\n }"
] |
low-level Graph API operations | [
"public <T> T fetchObject(String objectId, Class<T> type) {\n\t\tURI uri = URIBuilder.fromUri(getBaseGraphApiUrl() + objectId).build();\n\t\treturn getRestTemplate().getForObject(uri, type);\n\t}"
] | [
"public double[] getZeroRates(double[] maturities)\n\t{\n\t\tdouble[] values = new double[maturities.length];\n\n\t\tfor(int i=0; i<maturities.length; i++) {\n\t\t\tvalues[i] = getZeroRate(maturities[i]);\n\t\t}\n\n\t\treturn values;\n\t}",
"protected void setBeanStore(BoundBeanStore beanStore) {\n if (beanStore == null) {\n this.beanStore.remove();\n } else {\n this.beanStore.set(beanStore);\n }\n }",
"public int[] getDefalutValuesArray() {\n int[] defaultValues = new int[5];\n\n defaultValues[0] = GLES20.GL_LINEAR_MIPMAP_NEAREST; // MIN FILTER\n defaultValues[1] = GLES20.GL_LINEAR; // MAG FILTER\n defaultValues[2] = 1; // ANISO FILTER\n defaultValues[3] = GLES20.GL_CLAMP_TO_EDGE; // WRAP S\n defaultValues[4] = GLES20.GL_CLAMP_TO_EDGE; // WRAP T\n\n return defaultValues;\n }",
"public CustomHeadersInterceptor addHeaderMap(Map<String, String> headers) {\n for (Map.Entry<String, String> header : headers.entrySet()) {\n this.headers.put(header.getKey(), Collections.singletonList(header.getValue()));\n }\n return this;\n }",
"private void readResourceAssignment(Allocation gpAllocation)\n {\n Integer taskID = Integer.valueOf(NumberHelper.getInt(gpAllocation.getTaskId()) + 1);\n Integer resourceID = Integer.valueOf(NumberHelper.getInt(gpAllocation.getResourceId()) + 1);\n Task task = m_projectFile.getTaskByUniqueID(taskID);\n Resource resource = m_projectFile.getResourceByUniqueID(resourceID);\n if (task != null && resource != null)\n {\n ResourceAssignment mpxjAssignment = task.addResourceAssignment(resource);\n mpxjAssignment.setUnits(gpAllocation.getLoad());\n m_eventManager.fireAssignmentReadEvent(mpxjAssignment);\n }\n }",
"public static ModelNode getOperationAddress(final ModelNode op) {\n return op.hasDefined(OP_ADDR) ? op.get(OP_ADDR) : new ModelNode();\n }",
"private static String qualifiedName(Options opt, String r) {\n\tif (opt.hideGenerics)\n\t r = removeTemplate(r);\n\t// Fast path - nothing to do:\n\tif (opt.showQualified && (opt.showQualifiedGenerics || r.indexOf('<') < 0))\n\t return r;\n\tStringBuilder buf = new StringBuilder(r.length());\n\tqualifiedNameInner(opt, r, buf, 0, !opt.showQualified);\n\treturn buf.toString();\n }",
"public com.groupon.odo.proxylib.models.Method getMethodForOverrideId(int overrideId) {\n com.groupon.odo.proxylib.models.Method method = null;\n\n // special case for IDs < 0\n if (overrideId < 0) {\n method = new com.groupon.odo.proxylib.models.Method();\n method.setId(overrideId);\n\n if (method.getId() == Constants.PLUGIN_RESPONSE_OVERRIDE_CUSTOM ||\n method.getId() == Constants.PLUGIN_RESPONSE_HEADER_OVERRIDE_ADD ||\n method.getId() == Constants.PLUGIN_RESPONSE_HEADER_OVERRIDE_REMOVE) {\n method.setMethodType(Constants.PLUGIN_TYPE_RESPONSE_OVERRIDE);\n } else {\n method.setMethodType(Constants.PLUGIN_TYPE_REQUEST_OVERRIDE);\n }\n } else {\n // get method information from the database\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_OVERRIDE +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n queryStatement.setInt(1, overrideId);\n results = queryStatement.executeQuery();\n\n if (results.next()) {\n method = new com.groupon.odo.proxylib.models.Method();\n method.setClassName(results.getString(Constants.OVERRIDE_CLASS_NAME));\n method.setMethodName(results.getString(Constants.OVERRIDE_METHOD_NAME));\n }\n } catch (SQLException e) {\n e.printStackTrace();\n return null;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n // if method is still null then just return\n if (method == null) {\n return method;\n }\n\n // now get the rest of the data from the plugin manager\n // this gets all of the actual method data\n try {\n method = PluginManager.getInstance().getMethod(method.getClassName(), method.getMethodName());\n method.setId(overrideId);\n } catch (Exception e) {\n // there was some problem.. return null\n return null;\n }\n }\n\n return method;\n }",
"private static void checkPreconditions(final String dateFormat, final Locale locale) {\n\t\tif( dateFormat == null ) {\n\t\t\tthrow new NullPointerException(\"dateFormat should not be null\");\n\t\t} else if( locale == null ) {\n\t\t\tthrow new NullPointerException(\"locale should not be null\");\n\t\t}\n\t}"
] |
Checks the preconditions for creating a new StrRegExReplace processor.
@param regex
the supplied regular expression
@param replacement
the supplied replacement text
@throws IllegalArgumentException
if regex is empty
@throws NullPointerException
if regex or replacement is null | [
"private static void checkPreconditions(final String regex, final String replacement) {\n\t\tif( regex == null ) {\n\t\t\tthrow new NullPointerException(\"regex should not be null\");\n\t\t} else if( regex.length() == 0 ) {\n\t\t\tthrow new IllegalArgumentException(\"regex should not be empty\");\n\t\t}\n\t\t\n\t\tif( replacement == null ) {\n\t\t\tthrow new NullPointerException(\"replacement should not be null\");\n\t\t}\n\t}"
] | [
"private Object toReference(int type, Object referent, int hash)\r\n {\r\n switch (type)\r\n {\r\n case HARD:\r\n return referent;\r\n case SOFT:\r\n return new SoftRef(hash, referent, queue);\r\n case WEAK:\r\n return new WeakRef(hash, referent, queue);\r\n default:\r\n throw new Error();\r\n }\r\n }",
"private ColorItem buildColorItem(int colorId, String label) {\n Color color;\n String colorName;\n switch (colorId) {\n case 0:\n color = new Color(0, 0, 0, 0);\n colorName = \"No Color\";\n break;\n case 1:\n color = Color.PINK;\n colorName = \"Pink\";\n break;\n case 2:\n color = Color.RED;\n colorName = \"Red\";\n break;\n case 3:\n color = Color.ORANGE;\n colorName = \"Orange\";\n break;\n case 4:\n color = Color.YELLOW;\n colorName = \"Yellow\";\n break;\n case 5:\n color = Color.GREEN;\n colorName = \"Green\";\n break;\n case 6:\n color = Color.CYAN;\n colorName = \"Aqua\";\n break;\n case 7:\n color = Color.BLUE;\n colorName = \"Blue\";\n break;\n case 8:\n color = new Color(128, 0, 128);\n colorName = \"Purple\";\n break;\n default:\n color = new Color(0, 0, 0, 0);\n colorName = \"Unknown Color\";\n }\n return new ColorItem(colorId, label, color, colorName);\n }",
"public AnalysisContext copyWithConfiguration(ModelNode configuration) {\n return new AnalysisContext(this.locale, configuration, this.oldApi, this.newApi, this.data);\n }",
"public void setCloseConnectionWatchTimeout(long closeConnectionWatchTimeout, TimeUnit timeUnit) {\n\t\tthis.closeConnectionWatchTimeoutInMs = TimeUnit.MILLISECONDS.convert(closeConnectionWatchTimeout, timeUnit);\n\t}",
"@Override\n public Collection<EnhancedAnnotatedConstructor<T>> getEnhancedConstructors(Class<? extends Annotation> annotationType) {\n Set<EnhancedAnnotatedConstructor<T>> ret = new HashSet<EnhancedAnnotatedConstructor<T>>();\n for (EnhancedAnnotatedConstructor<T> constructor : constructors) {\n if (constructor.isAnnotationPresent(annotationType)) {\n ret.add(constructor);\n }\n }\n return ret;\n }",
"public List<Map<String, String>> pipelinePossibleStates(Assign action, List<Map<String, String>> possibleStateList) {\r\n for (Map<String, String> possibleState : possibleStateList) {\r\n possibleState.put(action.getName(), action.getExpr());\r\n }\n\r\n return possibleStateList;\r\n }",
"@Override\n public ImageSource apply(ImageSource input) {\n int w = input.getWidth();\n int h = input.getHeight();\n\n MatrixSource output = new MatrixSource(input);\n\n Vector3 n = new Vector3(0, 0, 1);\n\n for (int y = 0; y < h; y++) {\n for (int x = 0; x < w; x++) {\n\n if (x < border || x == w - border || y < border || y == h - border) {\n output.setRGB(x, y, VectorHelper.Z_NORMAL);\n continue;\n }\n\n float s0 = input.getR(x - 1, y + 1);\n float s1 = input.getR(x, y + 1);\n float s2 = input.getR(x + 1, y + 1);\n float s3 = input.getR(x - 1, y);\n float s5 = input.getR(x + 1, y);\n float s6 = input.getR(x - 1, y - 1);\n float s7 = input.getR(x, y - 1);\n float s8 = input.getR(x + 1, y - 1);\n\n float nx = -(s2 - s0 + 2 * (s5 - s3) + s8 - s6);\n float ny = -(s6 - s0 + 2 * (s7 - s1) + s8 - s2);\n\n n.set(nx, ny, scale);\n n.nor();\n\n int rgb = VectorHelper.vectorToColor(n);\n output.setRGB(x, y, rgb);\n }\n }\n\n return new MatrixSource(output);\n }",
"public static aaa_stats get(nitro_service service) throws Exception{\n\t\taaa_stats obj = new aaa_stats();\n\t\taaa_stats[] response = (aaa_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}",
"private void addCriteria(List<GenericCriteria> list, byte[] block)\n {\n byte[] leftBlock = getChildBlock(block);\n byte[] rightBlock1 = getListNextBlock(leftBlock);\n byte[] rightBlock2 = getListNextBlock(rightBlock1);\n TestOperator operator = TestOperator.getInstance(MPPUtility.getShort(block, 0) - 0x3E7);\n FieldType leftValue = getFieldType(leftBlock);\n Object rightValue1 = getValue(leftValue, rightBlock1);\n Object rightValue2 = rightBlock2 == null ? null : getValue(leftValue, rightBlock2);\n\n GenericCriteria criteria = new GenericCriteria(m_properties);\n criteria.setLeftValue(leftValue);\n criteria.setOperator(operator);\n criteria.setRightValue(0, rightValue1);\n criteria.setRightValue(1, rightValue2);\n list.add(criteria);\n\n if (m_criteriaType != null)\n {\n m_criteriaType[0] = leftValue.getFieldTypeClass() == FieldTypeClass.TASK;\n m_criteriaType[1] = !m_criteriaType[0];\n }\n\n if (m_fields != null)\n {\n m_fields.add(leftValue);\n }\n\n processBlock(list, getListNextBlock(block));\n }"
] |
Find the style filter that must be applied to this feature.
@param feature
feature to find the style for
@param styles
style filters to select from
@return a style filter | [
"private StyleFilter findStyleFilter(Object feature, List<StyleFilter> styles) {\n\t\tfor (StyleFilter styleFilter : styles) {\n\t\t\tif (styleFilter.getFilter().evaluate(feature)) {\n\t\t\t\treturn styleFilter;\n\t\t\t}\n\t\t}\n\t\treturn new StyleFilterImpl();\n\t}"
] | [
"protected void addFacetPart(CmsSolrQuery query) {\n\n StringBuffer value = new StringBuffer();\n value.append(\"{!key=\").append(m_config.getName());\n addFacetOptions(value);\n if (m_config.getIgnoreAllFacetFilters()\n || (!m_state.getCheckedEntries().isEmpty() && !m_config.getIsAndFacet())) {\n value.append(\" ex=\").append(m_config.getIgnoreTags());\n }\n value.append(\"}\");\n value.append(m_config.getRange());\n query.add(\"facet.range\", value.toString());\n }",
"public static void launchPermissionSettings(Activity activity) {\n Intent intent = new Intent();\n intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);\n intent.setData(Uri.fromParts(\"package\", activity.getPackageName(), null));\n activity.startActivity(intent);\n }",
"public static base_response add(nitro_service client, sslaction resource) throws Exception {\n\t\tsslaction addresource = new sslaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.clientauth = resource.clientauth;\n\t\taddresource.clientcert = resource.clientcert;\n\t\taddresource.certheader = resource.certheader;\n\t\taddresource.clientcertserialnumber = resource.clientcertserialnumber;\n\t\taddresource.certserialheader = resource.certserialheader;\n\t\taddresource.clientcertsubject = resource.clientcertsubject;\n\t\taddresource.certsubjectheader = resource.certsubjectheader;\n\t\taddresource.clientcerthash = resource.clientcerthash;\n\t\taddresource.certhashheader = resource.certhashheader;\n\t\taddresource.clientcertissuer = resource.clientcertissuer;\n\t\taddresource.certissuerheader = resource.certissuerheader;\n\t\taddresource.sessionid = resource.sessionid;\n\t\taddresource.sessionidheader = resource.sessionidheader;\n\t\taddresource.cipher = resource.cipher;\n\t\taddresource.cipherheader = resource.cipherheader;\n\t\taddresource.clientcertnotbefore = resource.clientcertnotbefore;\n\t\taddresource.certnotbeforeheader = resource.certnotbeforeheader;\n\t\taddresource.clientcertnotafter = resource.clientcertnotafter;\n\t\taddresource.certnotafterheader = resource.certnotafterheader;\n\t\taddresource.owasupport = resource.owasupport;\n\t\treturn addresource.add_resource(client);\n\t}",
"public static Filter.Builder makeAncestorFilter(Key ancestor) {\n return makeFilter(\n DatastoreHelper.KEY_PROPERTY_NAME, PropertyFilter.Operator.HAS_ANCESTOR,\n makeValue(ancestor));\n }",
"@RequestMapping(value = \"/profiles\", method = RequestMethod.GET)\n public String list(Model model) {\n Profile profiles = new Profile();\n model.addAttribute(\"addNewProfile\", profiles);\n model.addAttribute(\"version\", Constants.VERSION);\n logger.info(\"Loading initial page\");\n\n return \"profiles\";\n }",
"public CollectionRequest<Team> users(String team) {\n \n String path = String.format(\"/teams/%s/users\", team);\n return new CollectionRequest<Team>(this, Team.class, path, \"GET\");\n }",
"public static <T> Method getMethod(Class<T> c, String name, Class<?>... argTypes) {\n try {\n return c.getMethod(name, argTypes);\n } catch(NoSuchMethodException e) {\n throw new IllegalArgumentException(e);\n }\n }",
"public Task<Void> updateSyncFrequency(@NonNull final SyncFrequency syncFrequency) {\n return this.dispatcher.dispatchTask(new Callable<Void>() {\n @Override\n public Void call() throws Exception {\n SyncImpl.this.proxy.updateSyncFrequency(syncFrequency);\n return null;\n }\n });\n }",
"public void add(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD);\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }"
] |
Use this API to unset the properties of nsacl6 resources.
Properties that need to be unset are specified in args array. | [
"public static base_responses unset(nitro_service client, String acl6name[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (acl6name != null && acl6name.length > 0) {\n\t\t\tnsacl6 unsetresources[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++){\n\t\t\t\tunsetresources[i] = new nsacl6();\n\t\t\t\tunsetresources[i].acl6name = acl6name[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}"
] | [
"protected byte[] readByteArray(InputStream is, int size) throws IOException\n {\n byte[] buffer = new byte[size];\n if (is.read(buffer) != buffer.length)\n {\n throw new EOFException();\n }\n return (buffer);\n }",
"public Info changeMessage(String newMessage) {\n Info newInfo = new Info();\n newInfo.setMessage(newMessage);\n\n URL url = COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"PUT\");\n request.setBody(newInfo.getPendingChanges());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonResponse = JsonObject.readFrom(response.getJSON());\n\n return new Info(jsonResponse);\n }",
"public List<ConnectionInfo> getConnections() {\n final URI uri = uriWithPath(\"./connections/\");\n return Arrays.asList(this.rt.getForObject(uri, ConnectionInfo[].class));\n }",
"public static base_response Import(nitro_service client, application resource) throws Exception {\n\t\tapplication Importresource = new application();\n\t\tImportresource.apptemplatefilename = resource.apptemplatefilename;\n\t\tImportresource.appname = resource.appname;\n\t\tImportresource.deploymentfilename = resource.deploymentfilename;\n\t\treturn Importresource.perform_operation(client,\"Import\");\n\t}",
"public static Node removePartitionFromNode(final Node node, Integer donatedPartition) {\n return UpdateClusterUtils.removePartitionsFromNode(node, Sets.newHashSet(donatedPartition));\n }",
"public void removeValue(T value, boolean reload) {\n int idx = getIndex(value);\n if (idx >= 0) {\n removeItemInternal(idx, reload);\n }\n }",
"public static PropertyResourceBundle getBundle(String baseName, Locale locale) throws UnsupportedEncodingException, IOException{\n\t\tInputStream is = UTF8PropertyResourceBundle.class.getResourceAsStream(\"/\"+baseName + \"_\"+locale.toString()+PROPERTIES_EXT);\n\t\tif(is != null){\n\t\t\treturn new PropertyResourceBundle(new InputStreamReader(is, \"UTF-8\"));\n\t\t}\n\t\treturn null;\n\t}",
"public static DMatrixRBlock transpose(DMatrixRBlock A , DMatrixRBlock A_tran )\n {\n if( A_tran != null ) {\n if( A.numRows != A_tran.numCols || A.numCols != A_tran.numRows )\n throw new IllegalArgumentException(\"Incompatible dimensions.\");\n if( A.blockLength != A_tran.blockLength )\n throw new IllegalArgumentException(\"Incompatible block size.\");\n } else {\n A_tran = new DMatrixRBlock(A.numCols,A.numRows,A.blockLength);\n\n }\n\n for( int i = 0; i < A.numRows; i += A.blockLength ) {\n int blockHeight = Math.min( A.blockLength , A.numRows - i);\n\n for( int j = 0; j < A.numCols; j += A.blockLength ) {\n int blockWidth = Math.min( A.blockLength , A.numCols - j);\n\n int indexA = i*A.numCols + blockHeight*j;\n int indexC = j*A_tran.numCols + blockWidth*i;\n\n transposeBlock( A , A_tran , indexA , indexC , blockWidth , blockHeight );\n }\n }\n\n return A_tran;\n }",
"private static int findTrackIdAtOffset(SlotReference slot, Client client, int offset) throws IOException {\n Message entry = client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slot.slot, CdjStatus.TrackType.REKORDBOX, offset, 1).get(0);\n if (entry.getMenuItemType() == Message.MenuItemType.UNKNOWN) {\n logger.warn(\"Encountered unrecognized track list entry item type: {}\", entry);\n }\n return (int)((NumberField)entry.arguments.get(1)).getValue();\n }"
] |
Read a task from a ConceptDraw PROJECT file.
@param projectIdentifier parent project identifier
@param map outline number to task map
@param task ConceptDraw PROJECT task | [
"private void readTask(String projectIdentifier, Map<String, Task> map, Document.Projects.Project.Task task)\n {\n Task parentTask = map.get(getParentOutlineNumber(task.getOutlineNumber()));\n Task mpxjTask = parentTask.addTask();\n\n TimeUnit units = task.getBaseDurationTimeUnit();\n\n mpxjTask.setCost(task.getActualCost());\n mpxjTask.setDuration(getDuration(units, task.getActualDuration()));\n mpxjTask.setFinish(task.getActualFinishDate());\n mpxjTask.setStart(task.getActualStartDate());\n mpxjTask.setBaselineDuration(getDuration(units, task.getBaseDuration()));\n mpxjTask.setBaselineFinish(task.getBaseFinishDate());\n mpxjTask.setBaselineCost(task.getBaselineCost());\n // task.getBaselineFinishDate()\n // task.getBaselineFinishTemplateOffset()\n // task.getBaselineStartDate()\n // task.getBaselineStartTemplateOffset()\n mpxjTask.setBaselineStart(task.getBaseStartDate());\n // task.getCallouts()\n mpxjTask.setPercentageComplete(task.getComplete());\n mpxjTask.setDeadline(task.getDeadlineDate());\n // task.getDeadlineTemplateOffset()\n // task.getHyperlinks()\n // task.getMarkerID()\n mpxjTask.setName(task.getName());\n mpxjTask.setNotes(task.getNote());\n mpxjTask.setPriority(task.getPriority());\n // task.getRecalcBase1()\n // task.getRecalcBase2()\n mpxjTask.setType(task.getSchedulingType());\n // task.getStyleProject()\n // task.getTemplateOffset()\n // task.getValidatedByProject()\n\n if (task.isIsMilestone())\n {\n mpxjTask.setMilestone(true);\n mpxjTask.setDuration(Duration.getInstance(0, TimeUnit.HOURS));\n mpxjTask.setBaselineDuration(Duration.getInstance(0, TimeUnit.HOURS));\n }\n\n String taskIdentifier = projectIdentifier + \".\" + task.getID();\n m_taskIdMap.put(task.getID(), mpxjTask);\n mpxjTask.setGUID(UUID.nameUUIDFromBytes(taskIdentifier.getBytes()));\n\n map.put(task.getOutlineNumber(), mpxjTask);\n\n for (Document.Projects.Project.Task.ResourceAssignments.ResourceAssignment assignment : task.getResourceAssignments().getResourceAssignment())\n {\n readResourceAssignment(mpxjTask, assignment);\n }\n }"
] | [
"public ModelNode registerDeploymentSubsystemResource(final String subsystemName, final Resource resource) {\n assert subsystemName != null : \"The subsystemName cannot be null\";\n assert resource != null : \"The resource cannot be null\";\n return registerDeploymentSubResource(subsystemName, PathAddress.EMPTY_ADDRESS, resource);\n }",
"public static String readTag(Reader r) throws IOException {\r\n if ( ! r.ready()) {\r\n return null;\r\n }\r\n StringBuilder b = new StringBuilder(\"<\");\r\n int c = r.read();\r\n while (c >= 0) {\r\n b.append((char) c);\r\n if (c == '>') {\r\n break;\r\n }\r\n c = r.read();\r\n }\r\n if (b.length() == 1) {\r\n return null;\r\n }\r\n return b.toString();\r\n }",
"private void readWorkWeeks(Project.Calendars.Calendar xmlCalendar, ProjectCalendar mpxjCalendar)\n {\n WorkWeeks ww = xmlCalendar.getWorkWeeks();\n if (ww != null)\n {\n for (WorkWeek xmlWeek : ww.getWorkWeek())\n {\n ProjectCalendarWeek week = mpxjCalendar.addWorkWeek();\n week.setName(xmlWeek.getName());\n Date startTime = xmlWeek.getTimePeriod().getFromDate();\n Date endTime = xmlWeek.getTimePeriod().getToDate();\n week.setDateRange(new DateRange(startTime, endTime));\n\n WeekDays xmlWeekDays = xmlWeek.getWeekDays();\n if (xmlWeekDays != null)\n {\n for (WeekDay xmlWeekDay : xmlWeekDays.getWeekDay())\n {\n int dayNumber = xmlWeekDay.getDayType().intValue();\n Day day = Day.getInstance(dayNumber);\n week.setWorkingDay(day, BooleanHelper.getBoolean(xmlWeekDay.isDayWorking()));\n ProjectCalendarHours hours = week.addCalendarHours(day);\n\n Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay.WorkingTimes times = xmlWeekDay.getWorkingTimes();\n if (times != null)\n {\n for (Project.Calendars.Calendar.WorkWeeks.WorkWeek.WeekDays.WeekDay.WorkingTimes.WorkingTime period : times.getWorkingTime())\n {\n startTime = period.getFromTime();\n endTime = period.getToTime();\n\n if (startTime != null && endTime != null)\n {\n if (startTime.getTime() >= endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n hours.addRange(new DateRange(startTime, endTime));\n }\n }\n }\n }\n }\n }\n }\n }",
"public List<DbLicense> getModuleLicenses(final String moduleId,\n final LicenseMatcher licenseMatcher) {\n final DbModule module = getModule(moduleId);\n\n final List<DbLicense> licenses = new ArrayList<>();\n final FiltersHolder filters = new FiltersHolder();\n final ArtifactHandler artifactHandler = new ArtifactHandler(repositoryHandler, licenseMatcher);\n\n for (final String gavc : DataUtils.getAllArtifacts(module)) {\n licenses.addAll(artifactHandler.getArtifactLicenses(gavc, filters));\n }\n\n return licenses;\n }",
"public int addPathnameToProfile(int id, String pathname, String actualPath) throws Exception {\n int pathOrder = getPathOrder(id).size() + 1;\n int pathId = -1;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"INSERT INTO \" + Constants.DB_TABLE_PATH\n + \"(\" + Constants.PATH_PROFILE_PATHNAME + \",\"\n + Constants.PATH_PROFILE_ACTUAL_PATH + \",\"\n + Constants.PATH_PROFILE_GROUP_IDS + \",\"\n + Constants.PATH_PROFILE_PROFILE_ID + \",\"\n + Constants.PATH_PROFILE_PATH_ORDER + \",\"\n + Constants.PATH_PROFILE_CONTENT_TYPE + \",\"\n + Constants.PATH_PROFILE_REQUEST_TYPE + \",\"\n + Constants.PATH_PROFILE_GLOBAL + \")\"\n + \" VALUES (?, ?, ?, ?, ?, ?, ?, ?);\",\n PreparedStatement.RETURN_GENERATED_KEYS\n );\n statement.setString(1, pathname);\n statement.setString(2, actualPath);\n statement.setString(3, \"\");\n statement.setInt(4, id);\n statement.setInt(5, pathOrder);\n statement.setString(6, Constants.PATH_PROFILE_DEFAULT_CONTENT_TYPE); // should be set by UI/API\n statement.setInt(7, Constants.REQUEST_TYPE_GET); // should be set by UI/API\n statement.setBoolean(8, false);\n statement.executeUpdate();\n\n // execute statement and get resultSet which will have the generated path ID as the first field\n results = statement.getGeneratedKeys();\n\n if (results.next()) {\n pathId = results.getInt(1);\n } else {\n // something went wrong\n throw new Exception(\"Could not add path\");\n }\n } catch (SQLException e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n // need to add to request response table for all clients\n for (Client client : ClientService.getInstance().findAllClients(id)) {\n this.addPathToRequestResponseTable(id, client.getUUID(), pathId);\n }\n\n return pathId;\n }",
"public static transformpolicy[] get(nitro_service service) throws Exception{\n\t\ttransformpolicy obj = new transformpolicy();\n\t\ttransformpolicy[] response = (transformpolicy[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static void acceptsHex(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_X, OPT_HEX), \"fetch key/entry by key value of hex type\")\n .withRequiredArg()\n .describedAs(\"key-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\n }",
"public B partialFilterSelector(Selector selector) {\n instance.def.selector = Helpers.getJsonObjectFromSelector(selector);\n return returnThis();\n }",
"public Collection<String> getCurrencyCodes() {\n Collection<String> result = get(KEY_QUERY_CURRENCY_CODES, Collection.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }"
] |
Use this API to delete nsip6 of given name. | [
"public static base_response delete(nitro_service client, String ipv6address) throws Exception {\n\t\tnsip6 deleteresource = new nsip6();\n\t\tdeleteresource.ipv6address = ipv6address;\n\t\treturn deleteresource.delete_resource(client);\n\t}"
] | [
"@Override\n public boolean shouldRetry(int retryCount, Response response) {\n int code = response.code();\n //CHECKSTYLE IGNORE MagicNumber FOR NEXT 2 LINES\n return retryCount < this.retryCount\n && (code == 408 || (code >= 500 && code != 501 && code != 505));\n }",
"protected void countStatements(UsageStatistics usageStatistics,\n\t\t\tStatementDocument statementDocument) {\n\t\t// Count Statement data:\n\t\tfor (StatementGroup sg : statementDocument.getStatementGroups()) {\n\t\t\t// Count Statements:\n\t\t\tusageStatistics.countStatements += sg.size();\n\n\t\t\t// Count uses of properties in Statements:\n\t\t\tcountPropertyMain(usageStatistics, sg.getProperty(), sg.size());\n\t\t\tfor (Statement s : sg) {\n\t\t\t\tfor (SnakGroup q : s.getQualifiers()) {\n\t\t\t\t\tcountPropertyQualifier(usageStatistics, q.getProperty(), q.size());\n\t\t\t\t}\n\t\t\t\tfor (Reference r : s.getReferences()) {\n\t\t\t\t\tusageStatistics.countReferencedStatements++;\n\t\t\t\t\tfor (SnakGroup snakGroup : r.getSnakGroups()) {\n\t\t\t\t\t\tcountPropertyReference(usageStatistics,\n\t\t\t\t\t\t\t\tsnakGroup.getProperty(), snakGroup.size());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"public static GridLabelFormat fromConfig(final GridParam param) {\n if (param.labelFormat != null) {\n return new GridLabelFormat.Simple(param.labelFormat);\n } else if (param.valueFormat != null) {\n return new GridLabelFormat.Detailed(\n param.valueFormat, param.unitFormat,\n param.formatDecimalSeparator, param.formatGroupingSeparator);\n }\n return null;\n }",
"public static nsdiameter get(nitro_service service) throws Exception{\n\t\tnsdiameter obj = new nsdiameter();\n\t\tnsdiameter[] response = (nsdiameter[])obj.get_resources(service);\n\t\treturn response[0];\n\t}",
"void lockSharedInterruptibly(final Integer permit) throws InterruptedException {\n if (permit == null) {\n throw new IllegalArgumentException();\n }\n sync.acquireSharedInterruptibly(permit);\n }",
"public static base_response update(nitro_service client, inat resource) throws Exception {\n\t\tinat updateresource = new inat();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.privateip = resource.privateip;\n\t\tupdateresource.tcpproxy = resource.tcpproxy;\n\t\tupdateresource.ftp = resource.ftp;\n\t\tupdateresource.tftp = resource.tftp;\n\t\tupdateresource.usip = resource.usip;\n\t\tupdateresource.usnip = resource.usnip;\n\t\tupdateresource.proxyip = resource.proxyip;\n\t\tupdateresource.mode = resource.mode;\n\t\treturn updateresource.update_resource(client);\n\t}",
"private int slopSize(Versioned<Slop> slopVersioned) {\n int nBytes = 0;\n Slop slop = slopVersioned.getValue();\n nBytes += slop.getKey().length();\n nBytes += ((VectorClock) slopVersioned.getVersion()).sizeInBytes();\n switch(slop.getOperation()) {\n case PUT: {\n nBytes += slop.getValue().length;\n break;\n }\n case DELETE: {\n break;\n }\n default:\n logger.error(\"Unknown slop operation: \" + slop.getOperation());\n }\n return nBytes;\n }",
"public void writeLine(String pattern, Object... parameters) {\n String line = (parameters == null || parameters.length == 0) ? pattern\n : String.format(pattern, parameters);\n lines.add(0, line); // we'll write bottom to top, then purge unwritten\n // lines from end\n updateHUD();\n }",
"public static double elementMax( DMatrixSparseCSC A ) {\n if( A.nz_length == 0)\n return 0;\n\n // if every element is assigned a value then the first element can be a max.\n // Otherwise zero needs to be considered\n double max = A.isFull() ? A.nz_values[0] : 0;\n for(int i = 0; i < A.nz_length; i++ ) {\n double val = A.nz_values[i];\n if( val > max ) {\n max = val;\n }\n }\n\n return max;\n }"
] |
Creates a build
@param appName See {@link #listApps} for a list of apps that can be used.
@param build the build information | [
"public Build createBuild(String appName, Build build) {\n return connection.execute(new BuildCreate(appName, build), apiKey);\n }"
] | [
"public GVRShader getTemplate(GVRContext ctx)\n {\n if (mShaderTemplate == null)\n {\n mShaderTemplate = makeTemplate(ID, ctx);\n ctx.getShaderManager().addShaderID(this);\n }\n return mShaderTemplate;\n }",
"private List<TimephasedWork> splitWork(CostRateTable table, ProjectCalendar calendar, TimephasedWork work, int rateIndex)\n {\n List<TimephasedWork> result = new LinkedList<TimephasedWork>();\n work.setTotalAmount(Duration.getInstance(0, work.getAmountPerDay().getUnits()));\n\n while (true)\n {\n CostRateTableEntry rate = table.get(rateIndex);\n Date splitDate = rate.getEndDate();\n if (splitDate.getTime() >= work.getFinish().getTime())\n {\n result.add(work);\n break;\n }\n\n Date currentPeriodEnd = calendar.getPreviousWorkFinish(splitDate);\n\n TimephasedWork currentPeriod = new TimephasedWork(work);\n currentPeriod.setFinish(currentPeriodEnd);\n result.add(currentPeriod);\n\n Date nextPeriodStart = calendar.getNextWorkStart(splitDate);\n work.setStart(nextPeriodStart);\n\n ++rateIndex;\n }\n\n return result;\n }",
"public float conditionalLogProb(int[] given, int of) {\r\n if (given.length != windowSize - 1) {\r\n System.err.println(\"error computing conditional log prob\");\r\n System.exit(0);\r\n }\r\n int[] label = indicesFront(given);\r\n float[] masses = new float[label.length];\r\n for (int i = 0; i < masses.length; i++) {\r\n masses[i] = table[label[i]];\r\n }\r\n float z = ArrayMath.logSum(masses);\r\n\r\n return table[indexOf(given, of)] - z;\r\n }",
"protected void updateStyle(BoxStyle bstyle, TextPosition text)\n {\n String font = text.getFont().getName();\n String family = null;\n String weight = null;\n String fstyle = null;\n\n bstyle.setFontSize(text.getFontSizeInPt());\n bstyle.setLineHeight(text.getHeight());\n\n if (font != null)\n {\n \t//font style and weight\n for (int i = 0; i < pdFontType.length; i++)\n {\n if (font.toLowerCase().lastIndexOf(pdFontType[i]) >= 0)\n {\n weight = cssFontWeight[i];\n fstyle = cssFontStyle[i];\n break;\n }\n }\n if (weight != null)\n \tbstyle.setFontWeight(weight);\n else\n \tbstyle.setFontWeight(cssFontWeight[0]);\n if (fstyle != null)\n \tbstyle.setFontStyle(fstyle);\n else\n \tbstyle.setFontStyle(cssFontStyle[0]);\n\n //font family\n //If it's a known common font don't embed in html output to save space\n String knownFontFamily = findKnownFontFamily(font);\n if (!knownFontFamily.equals(\"\"))\n family = knownFontFamily;\n else\n {\n family = fontTable.getUsedName(text.getFont());\n if (family == null)\n family = font;\n }\n\n if (family != null)\n \tbstyle.setFontFamily(family);\n }\n\n updateStyleForRenderingMode();\n }",
"private String createPomPath(String relativePath, String moduleName) {\n if (!moduleName.contains(\".xml\")) {\n // Inside the parent pom, the reference is to the pom.xml file\n return relativePath + \"/\" + POM_NAME;\n }\n // There is a reference to another xml file, which is not the pom.\n String dirName = relativePath.substring(0, relativePath.indexOf(\"/\"));\n return dirName + \"/\" + moduleName;\n }",
"public void setAlias(UserAlias userAlias)\r\n\t{\r\n\t\tm_alias = userAlias.getName();\r\n\r\n\t\t// propagate to SelectionCriteria,not to Criteria\r\n\t\tfor (int i = 0; i < m_criteria.size(); i++)\r\n\t\t{\r\n\t\t\tif (!(m_criteria.elementAt(i) instanceof Criteria))\r\n\t\t\t{\r\n\t\t\t\t((SelectionCriteria) m_criteria.elementAt(i)).setAlias(userAlias);\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"public List<Profile> findAllProfiles() throws Exception {\n ArrayList<Profile> allProfiles = new ArrayList<>();\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_PROFILE);\n results = statement.executeQuery();\n while (results.next()) {\n allProfiles.add(this.getProfileFromResultSet(results));\n }\n } catch (Exception e) {\n throw e;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n return allProfiles;\n }",
"private void deselectChildren(CmsTreeItem item) {\r\n\r\n for (String childId : m_childrens.get(item.getId())) {\r\n CmsTreeItem child = m_categories.get(childId);\r\n deselectChildren(child);\r\n child.getCheckBox().setChecked(false);\r\n if (m_selectedCategories.contains(childId)) {\r\n m_selectedCategories.remove(childId);\r\n }\r\n }\r\n }",
"private String convertOutputToHtml(String content) {\n\n if (content.length() == 0) {\n return \"\";\n }\n StringBuilder buffer = new StringBuilder();\n for (String line : content.split(\"\\n\")) {\n buffer.append(CmsEncoder.escapeXml(line) + \"<br>\");\n }\n return buffer.toString();\n }"
] |
Returns the local collection representing the given namespace for raw document operations.
@param namespace the namespace referring to the local collection.
@return the local collection representing the given namespace for raw document operations. | [
"MongoCollection<BsonDocument> getLocalCollection(final MongoNamespace namespace) {\n return getLocalCollection(\n namespace,\n BsonDocument.class,\n MongoClientSettings.getDefaultCodecRegistry());\n }"
] | [
"static String replaceCheckDigit(final String iban, final String checkDigit) {\n return getCountryCode(iban) + checkDigit + getBban(iban);\n }",
"public double[][] getPositionsAsArray(){\n\t\tdouble[][] posAsArr = new double[size()][3];\n\t\tfor(int i = 0; i < size(); i++){\n\t\t\tif(get(i)!=null){\n\t\t\t\tposAsArr[i][0] = get(i).x;\n\t\t\t\tposAsArr[i][1] = get(i).y;\n\t\t\t\tposAsArr[i][2] = get(i).z;\n\t\t\t}\n\t\t\telse{\n\t\t\t\tposAsArr[i] = null;\n\t\t\t}\n\t\t}\n\t\treturn posAsArr;\n\t}",
"public byte[] toByteArray() {\n try {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(baos);\n oos.writeObject(this);\n return baos.toByteArray();\n } catch (IOException e) {\n throw E.ioException(e);\n }\n }",
"public static linkset_interface_binding[] get(nitro_service service, String id) throws Exception{\n\t\tlinkset_interface_binding obj = new linkset_interface_binding();\n\t\tobj.set_id(id);\n\t\tlinkset_interface_binding response[] = (linkset_interface_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public boolean removePredecessor(Task targetTask, RelationType type, Duration lag)\n {\n boolean matchFound = false;\n\n //\n // Retrieve the list of predecessors\n //\n List<Relation> predecessorList = getPredecessors();\n if (!predecessorList.isEmpty())\n {\n //\n // Ensure that we have a valid lag duration\n //\n if (lag == null)\n {\n lag = Duration.getInstance(0, TimeUnit.DAYS);\n }\n\n //\n // Ensure that there is a predecessor relationship between\n // these two tasks, and remove it.\n //\n matchFound = removeRelation(predecessorList, targetTask, type, lag);\n\n //\n // If we have removed a predecessor, then we must remove the\n // corresponding successor entry from the target task list\n //\n if (matchFound)\n {\n //\n // Retrieve the list of successors\n //\n List<Relation> successorList = targetTask.getSuccessors();\n if (!successorList.isEmpty())\n {\n //\n // Ensure that there is a successor relationship between\n // these two tasks, and remove it.\n //\n removeRelation(successorList, this, type, lag);\n }\n }\n }\n\n return matchFound;\n }",
"private static boolean isPredefinedConstant(Expression expression) {\r\n if (expression instanceof PropertyExpression) {\r\n Expression object = ((PropertyExpression) expression).getObjectExpression();\r\n Expression property = ((PropertyExpression) expression).getProperty();\r\n\r\n if (object instanceof VariableExpression) {\r\n List<String> predefinedConstantNames = PREDEFINED_CONSTANTS.get(((VariableExpression) object).getName());\r\n if (predefinedConstantNames != null && predefinedConstantNames.contains(property.getText())) {\r\n return true;\r\n }\r\n }\r\n }\r\n return false;\r\n }",
"private float[] generateParticleTimeStamps(float totalTime)\n {\n float timeStamps[] = new float[mEmitRate * 2];\n\n if ( burstMode ) {\n for (int i = 0; i < mEmitRate * 2; i += 2) {\n timeStamps[i] = totalTime;\n timeStamps[i + 1] = 0;\n }\n }\n else {\n for (int i = 0; i < mEmitRate * 2; i += 2) {\n timeStamps[i] = totalTime + mRandom.nextFloat();\n timeStamps[i + 1] = 0;\n }\n }\n return timeStamps;\n\n }",
"public String getProfileIdFromClientId(int id) {\n return (String) sqlService.getFromTable(Constants.CLIENT_PROFILE_ID, Constants.GENERIC_ID, id, Constants.DB_TABLE_CLIENT);\n }",
"public static rsskeytype get(nitro_service service) throws Exception{\n\t\trsskeytype obj = new rsskeytype();\n\t\trsskeytype[] response = (rsskeytype[])obj.get_resources(service);\n\t\treturn response[0];\n\t}"
] |
Clean obsolete contents from the content repository. It will first mark contents as obsolete then after some time
if these contents are still obsolete they will be removed.
@return a map containing the list of marked contents and the list of deleted contents. | [
"@Override\n public Map<String, Set<String>> cleanObsoleteContent() {\n if(!readWrite) {\n return Collections.emptyMap();\n }\n Map<String, Set<String>> cleanedContents = new HashMap<>(2);\n cleanedContents.put(MARKED_CONTENT, new HashSet<>());\n cleanedContents.put(DELETED_CONTENT, new HashSet<>());\n synchronized (contentHashReferences) {\n for (ContentReference fsContent : listLocalContents()) {\n if (!readWrite) {\n return Collections.emptyMap();\n }\n if (!contentHashReferences.containsKey(fsContent.getHexHash())) { //We have no reference to this content\n if (markAsObsolete(fsContent)) {\n cleanedContents.get(DELETED_CONTENT).add(fsContent.getContentIdentifier());\n } else {\n cleanedContents.get(MARKED_CONTENT).add(fsContent.getContentIdentifier());\n }\n } else {\n obsoleteContents.remove(fsContent.getHexHash()); //Remove existing references from obsoleteContents\n }\n }\n }\n return cleanedContents;\n }"
] | [
"public void fireRelationWrittenEvent(Relation relation)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n listener.relationWritten(relation);\n }\n }\n }",
"private Object getLiteralValue(Expression expression) {\n\t\tif (!(expression instanceof Literal)) {\n\t\t\tthrow new IllegalArgumentException(\"Expression \" + expression + \" is not a Literal.\");\n\t\t}\n\t\treturn ((Literal) expression).getValue();\n\t}",
"public void editPhotos(String photosetId, String primaryPhotoId, String[] photoIds) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT_PHOTOS);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\r\n parameters.put(\"primary_photo_id\", primaryPhotoId);\r\n parameters.put(\"photo_ids\", StringUtilities.join(photoIds, \",\"));\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"@SuppressWarnings(\"SameParameterValue\")\n private void assembleAndSendPacket(Util.PacketType kind, byte[] payload, InetAddress destination, int port) throws IOException {\n DatagramPacket packet = Util.buildPacket(kind,\n ByteBuffer.wrap(announcementBytes, DEVICE_NAME_OFFSET, DEVICE_NAME_LENGTH).asReadOnlyBuffer(),\n ByteBuffer.wrap(payload));\n packet.setAddress(destination);\n packet.setPort(port);\n socket.get().send(packet);\n }",
"public static String createFirstLowCaseName(String scenarioDescription) {\n String[] words = scenarioDescription.trim().split(\" \");\n String name = \"\";\n for (int i = 0; i < words.length; i++) {\n name += changeFirstLetterToCapital(words[i]);\n }\n return changeFirstLetterToLowerCase(name);\n }",
"public void putBeanDeployments(BeanDeploymentArchiveMapping bdaMapping) {\n for (Entry<BeanDeploymentArchive, BeanManagerImpl> entry : bdaMapping.getBdaToBeanManagerMap().entrySet()) {\n beanDeploymentArchives.put(entry.getKey(), entry.getValue());\n addBeanManager(entry.getValue());\n }\n }",
"public static ClassLoader resolveClassLoaderForBeanProxy(String contextId, Class<?> proxiedType, TypeInfo typeInfo, ProxyServices proxyServices) {\n Class<?> superClass = typeInfo.getSuperClass();\n if (superClass.getName().startsWith(JAVA)) {\n ClassLoader cl = proxyServices.getClassLoader(proxiedType);\n if (cl == null) {\n cl = Thread.currentThread().getContextClassLoader();\n }\n return cl;\n }\n return Container.instance(contextId).services().get(ProxyServices.class).getClassLoader(superClass);\n }",
"public static String getShortClassName(Object o) {\r\n String name = o.getClass().getName();\r\n int index = name.lastIndexOf('.');\r\n if (index >= 0) {\r\n name = name.substring(index + 1);\r\n }\r\n return name;\r\n }",
"private int convertMoneyness(double moneyness) {\r\n\t\tif(quotingConvention == QuotingConvention.PAYERVOLATILITYLOGNORMAL) {\r\n\t\t\treturn (int) Math.round(moneyness * 100);\r\n\t\t} else if(quotingConvention == QuotingConvention.RECEIVERPRICE) {\r\n\t\t\treturn - (int) Math.round(moneyness * 10000);\r\n\t\t} else {\r\n\t\t\treturn (int) Math.round(moneyness * 10000);\r\n\t\t}\r\n\t}"
] |
Adds a column pair to this foreignkey.
@param localColumn The column in the local table
@param remoteColumn The column in the remote table | [
"public void addColumnPair(String localColumn, String remoteColumn)\r\n {\r\n if (!_localColumns.contains(localColumn))\r\n { \r\n _localColumns.add(localColumn);\r\n }\r\n if (!_remoteColumns.contains(remoteColumn))\r\n { \r\n _remoteColumns.add(remoteColumn);\r\n }\r\n }"
] | [
"public static double ratioSmallestOverLargest( double []sv ) {\n if( sv.length == 0 )\n return Double.NaN;\n\n double min = sv[0];\n double max = min;\n\n for (int i = 1; i < sv.length; i++) {\n double v = sv[i];\n if( v > max )\n max = v;\n else if( v < min )\n min = v;\n }\n\n return min/max;\n }",
"public static final Rect getViewportBounds() {\n return new Rect(Window.getScrollLeft(), Window.getScrollTop(), Window.getClientWidth(), Window.getClientHeight());\n }",
"public ContentAssistEntry createProposal(final String proposal, final ContentAssistContext context) {\n return this.createProposal(proposal, context.getPrefix(), context, ContentAssistEntry.KIND_UNKNOWN, null);\n }",
"public final void error(Object pObject)\r\n\t{\r\n\t\tgetLogger().log(FQCN, Level.ERROR, pObject, null);\r\n\t}",
"public static base_response delete(nitro_service client, String network) throws Exception {\n\t\troute6 deleteresource = new route6();\n\t\tdeleteresource.network = network;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public void addRequiredBundles(Set<String> requiredBundles) {\n\t\taddRequiredBundles(requiredBundles.toArray(new String[requiredBundles.size()]));\n\t}",
"private String getQueryParam() {\n\n final String param = parseOptionalStringValue(XML_ELEMENT_QUERYPARAM);\n if (param == null) {\n return DEFAULT_QUERY_PARAM;\n } else {\n return param;\n }\n }",
"private static long scanForLocSig(FileChannel channel) throws IOException {\n\n channel.position(0);\n\n ByteBuffer bb = getByteBuffer(CHUNK_SIZE);\n long end = channel.size();\n while (channel.position() <= end) {\n\n read(bb, channel);\n\n int bufferPos = 0;\n while (bufferPos <= bb.limit() - SIG_PATTERN_LENGTH) {\n\n // Following is based on the Boyer Moore algorithm but simplified to reflect\n // a) the size of the pattern is static\n // b) the pattern is static and has no repeating bytes\n\n int patternPos;\n for (patternPos = SIG_PATTERN_LENGTH - 1;\n patternPos >= 0 && LOCSIG_PATTERN[patternPos] == bb.get(bufferPos + patternPos);\n --patternPos) {\n // empty loop while bytes match\n }\n\n // Outer switch gives same results as checking the \"good suffix array\" in the Boyer Moore algorithm\n switch (patternPos) {\n case -1: {\n // Pattern matched. Confirm is this is the start of a valid local file record\n long startLocRecord = channel.position() - bb.limit() + bufferPos;\n long currentPos = channel.position();\n if (validateLocalFileRecord(channel, startLocRecord, -1)) {\n return startLocRecord;\n }\n // Restore position in case it shifted\n channel.position(currentPos);\n\n // wasn't a valid local file record; continue scan\n bufferPos += 4;\n break;\n }\n case 3: {\n // No bytes matched; the common case.\n // With our pattern, this is the only case where the Boyer Moore algorithm's \"bad char array\" may\n // produce a shift greater than the \"good suffix array\" (which would shift 1 byte)\n int idx = bb.get(bufferPos + patternPos) - Byte.MIN_VALUE;\n bufferPos += LOC_BAD_BYTE_SKIP[idx];\n break;\n }\n default:\n // 1 or more bytes matched\n bufferPos += 4;\n }\n }\n }\n\n return -1;\n }",
"public static final UUID parseUUID(String value)\n {\n UUID result = null;\n if (value != null && !value.isEmpty())\n {\n if (value.charAt(0) == '{')\n {\n // PMXML representation: <GUID>{0AB9133E-A09A-9648-B98A-B2384894AC44}</GUID>\n result = UUID.fromString(value.substring(1, value.length() - 1));\n }\n else\n {\n // XER representation: CrkTPqCalki5irI4SJSsRA\n byte[] data = javax.xml.bind.DatatypeConverter.parseBase64Binary(value + \"==\");\n long msb = 0;\n long lsb = 0;\n\n for (int i = 0; i < 8; i++)\n {\n msb = (msb << 8) | (data[i] & 0xff);\n }\n\n for (int i = 8; i < 16; i++)\n {\n lsb = (lsb << 8) | (data[i] & 0xff);\n }\n\n result = new UUID(msb, lsb);\n }\n }\n return result;\n }"
] |
Calculates the bearing, in degrees, of the end LatLong point from this
LatLong point.
@param end The point that the bearing is calculated for.
@return The bearing, in degrees, of the supplied point from this point. | [
"public double getBearing(LatLong end) {\n if (this.equals(end)) {\n return 0;\n }\n\n double lat1 = latToRadians();\n double lon1 = longToRadians();\n double lat2 = end.latToRadians();\n double lon2 = end.longToRadians();\n\n double angle = -Math.atan2(Math.sin(lon1 - lon2) * Math.cos(lat2),\n Math.cos(lat1) * Math.sin(lat2) - Math.sin(lat1)\n * Math.cos(lat2) * Math.cos(lon1 - lon2));\n\n if (angle < 0.0) {\n angle += Math.PI * 2.0;\n }\n if (angle > Math.PI) {\n angle -= Math.PI * 2.0;\n }\n\n return Math.toDegrees(angle);\n }"
] | [
"public static vrid_nsip6_binding[] get(nitro_service service, Long id) throws Exception{\n\t\tvrid_nsip6_binding obj = new vrid_nsip6_binding();\n\t\tobj.set_id(id);\n\t\tvrid_nsip6_binding response[] = (vrid_nsip6_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private static int getContainerPort(Service service, Annotation... qualifiers) {\n for (Annotation q : qualifiers) {\n if (q instanceof Port) {\n Port port = (Port) q;\n if (port.value() > 0) {\n return port.value();\n }\n }\n }\n\n ServicePort servicePort = findQualifiedServicePort(service, qualifiers);\n if (servicePort != null) {\n return servicePort.getTargetPort().getIntVal();\n }\n return 0;\n }",
"public void execute() throws IOException {\n try {\n prepare();\n\n boolean commitResult = commit();\n if (commitResult == false) {\n throw PatchLogger.ROOT_LOGGER.failedToDeleteBackup();\n }\n } catch (PrepareException pe){\n rollback();\n\n throw PatchLogger.ROOT_LOGGER.failedToDelete(pe.getPath());\n }\n\n }",
"public static base_responses update(nitro_service client, systemuser resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsystemuser updateresources[] = new systemuser[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new systemuser();\n\t\t\t\tupdateresources[i].username = resources[i].username;\n\t\t\t\tupdateresources[i].password = resources[i].password;\n\t\t\t\tupdateresources[i].externalauth = resources[i].externalauth;\n\t\t\t\tupdateresources[i].promptstring = resources[i].promptstring;\n\t\t\t\tupdateresources[i].timeout = resources[i].timeout;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static CmsGalleryTabConfiguration resolve(String configStr) {\r\n\r\n CmsGalleryTabConfiguration tabConfig;\r\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(configStr)) {\r\n configStr = \"*sitemap,types,galleries,categories,vfstree,search,results\";\r\n }\r\n if (DEFAULT_CONFIGURATIONS != null) {\r\n tabConfig = DEFAULT_CONFIGURATIONS.get(configStr);\r\n if (tabConfig != null) {\r\n return tabConfig;\r\n }\r\n\r\n }\r\n return parse(configStr);\r\n }",
"public static <T> Iterator<T> unique(Iterator<T> self) {\n return toList((Iterable<T>) unique(toList(self))).listIterator();\n }",
"public void animate(float timeInSec)\n {\n GVRSkeleton skel = getSkeleton();\n GVRPose pose = skel.getPose();\n computePose(timeInSec,pose);\n skel.poseToBones();\n skel.updateBonePose();\n skel.updateSkinPose();\n }",
"public static void applyHyperLinkToElement(DynamicJasperDesign design, DJHyperLink djlink, JRDesignChart chart, String name) {\n\t\tJRDesignExpression hlpe = ExpressionUtils.createAndRegisterExpression(design, name, djlink.getExpression());\n\t\tchart.setHyperlinkReferenceExpression(hlpe);\n\t\tchart.setHyperlinkType( HyperlinkTypeEnum.REFERENCE ); //FIXME Should this be a parameter in the future?\n\t\t\t\t\n\t\tif (djlink.getTooltip() != null){\t\t\t\n\t\t\tJRDesignExpression tooltipExp = ExpressionUtils.createAndRegisterExpression(design, \"tooltip_\" + name, djlink.getTooltip());\n\t\t\tchart.setHyperlinkTooltipExpression(tooltipExp);\n\t\t}\n\t}",
"public static appqoepolicy[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tappqoepolicy obj = new appqoepolicy();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tappqoepolicy[] response = (appqoepolicy[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}"
] |
Retrieves the content of the filename. Also reads from JAR Searches for the resource in the
root folder in the jar
@param fileName Filename.
@return The contents of the file.
@throws IOException On error. | [
"public static String getTemplateAsString(String fileName) throws IOException {\n // in .jar file\n String fNameJar = getFileNameInPath(fileName);\n InputStream inStream = DomUtils.class.getResourceAsStream(\"/\"\n + fNameJar);\n if (inStream == null) {\n // try to find file normally\n File f = new File(fileName);\n if (f.exists()) {\n inStream = new FileInputStream(f);\n } else {\n throw new IOException(\"Cannot find \" + fileName + \" or \"\n + fNameJar);\n }\n }\n\n BufferedReader bufferedReader = new BufferedReader(\n new InputStreamReader(inStream));\n String line;\n StringBuilder stringBuilder = new StringBuilder();\n\n while ((line = bufferedReader.readLine()) != null) {\n stringBuilder.append(line).append(\"\\n\");\n }\n\n bufferedReader.close();\n return stringBuilder.toString();\n }"
] | [
"public T find(AbstractProject<?, ?> project, Class<T> type) {\n // First check that the Flexible Publish plugin is installed:\n if (Jenkins.getInstance().getPlugin(FLEXIBLE_PUBLISH_PLUGIN) != null) {\n // Iterate all the project's publishers and find the flexible publisher:\n for (Publisher publisher : project.getPublishersList()) {\n // Found the flexible publisher:\n if (publisher instanceof FlexiblePublisher) {\n // See if it wraps a publisher of the specified type and if it does, return it:\n T pub = getWrappedPublisher(publisher, type);\n if (pub != null) {\n return pub;\n }\n }\n }\n }\n\n return null;\n }",
"public void process(InputStream is) throws Exception\n {\n readHeader(is);\n readVersion(is);\n readTableData(readTableHeaders(is), is);\n }",
"private PersistenceBroker obtainBroker()\r\n {\r\n PersistenceBroker _broker;\r\n try\r\n {\r\n if (pbKey == null)\r\n {\r\n //throw new OJBRuntimeException(\"Not possible to do action, cause no tx runnning and no PBKey is set\");\r\n log.warn(\"No tx runnning and PBKey is null, try to use the default PB\");\r\n _broker = PersistenceBrokerFactory.defaultPersistenceBroker();\r\n }\r\n else\r\n {\r\n _broker = PersistenceBrokerFactory.createPersistenceBroker(pbKey);\r\n }\r\n }\r\n catch (PBFactoryException e)\r\n {\r\n log.error(\"Could not obtain PB for PBKey \" + pbKey, e);\r\n throw new OJBRuntimeException(\"Unexpected micro-kernel exception\", e);\r\n }\r\n return _broker;\r\n }",
"private JSONArray getApplicablePathNames (String requestUrl, Integer requestType) throws Exception {\n RequestInformation requestInfo = requestInformation.get();\n List<EndpointOverride> applicablePaths;\n JSONArray pathNames = new JSONArray();\n // Get all paths that match the request\n applicablePaths = PathOverrideService.getInstance().getSelectedPaths(Constants.OVERRIDE_TYPE_REQUEST, requestInfo.client,\n requestInfo.profile,\n requestUrl + \"?\" + requestInfo.originalRequestInfo.getQueryString(),\n requestType, true);\n // Extract just the path name from each path\n for (EndpointOverride path : applicablePaths) {\n JSONObject pathName = new JSONObject();\n pathName.put(\"name\", path.getPathName());\n pathNames.put(pathName);\n }\n\n return pathNames;\n }",
"private ProjectCalendar getResourceCalendar(Integer calendarID)\n {\n ProjectCalendar result = null;\n if (calendarID != null)\n {\n ProjectCalendar calendar = m_calMap.get(calendarID);\n if (calendar != null)\n {\n //\n // If the resource is linked to a base calendar, derive\n // a default calendar from the base calendar.\n //\n if (!calendar.isDerived())\n {\n ProjectCalendar resourceCalendar = m_project.addCalendar();\n resourceCalendar.setParent(calendar);\n resourceCalendar.setWorkingDay(Day.MONDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.TUESDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.WEDNESDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.THURSDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.FRIDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.SATURDAY, DayType.DEFAULT);\n resourceCalendar.setWorkingDay(Day.SUNDAY, DayType.DEFAULT);\n result = resourceCalendar;\n }\n else\n {\n //\n // Primavera seems to allow a calendar to be shared between resources\n // whereas in the MS Project model there is a one-to-one\n // relationship. If we find a shared calendar, take a copy of it\n //\n if (calendar.getResource() == null)\n {\n result = calendar;\n }\n else\n {\n ProjectCalendar copy = m_project.addCalendar();\n copy.copy(calendar);\n result = copy;\n }\n }\n }\n }\n\n return result;\n }",
"private void logTimeTakenByPhase(GraphContext graphContext, Class<? extends RulePhase> phase, int timeTaken)\n {\n if (!timeTakenByPhase.containsKey(phase))\n {\n RulePhaseExecutionStatisticsModel model = new GraphService<>(graphContext,\n RulePhaseExecutionStatisticsModel.class).create();\n model.setRulePhase(phase.toString());\n model.setTimeTaken(timeTaken);\n model.setOrderExecuted(timeTakenByPhase.size());\n timeTakenByPhase.put(phase, model.getElement().id());\n }\n else\n {\n GraphService<RulePhaseExecutionStatisticsModel> service = new GraphService<>(graphContext,\n RulePhaseExecutionStatisticsModel.class);\n RulePhaseExecutionStatisticsModel model = service.getById(timeTakenByPhase.get(phase));\n int prevTimeTaken = model.getTimeTaken();\n model.setTimeTaken(prevTimeTaken + timeTaken);\n }\n }",
"@SuppressWarnings(\"unchecked\") public Map<String, Object> getCustomProperties()\n {\n return (Map<String, Object>) getCachedValue(ProjectField.CUSTOM_PROPERTIES);\n }",
"public void copyTo(int srcOffset, byte[] destArray, int destOffset, int size) {\n int cursor = destOffset;\n for (ByteBuffer bb : toDirectByteBuffers(srcOffset, size)) {\n int bbSize = bb.remaining();\n if ((cursor + bbSize) > destArray.length)\n throw new ArrayIndexOutOfBoundsException(String.format(\"cursor + bbSize = %,d\", cursor + bbSize));\n bb.get(destArray, cursor, bbSize);\n cursor += bbSize;\n }\n }",
"public static<A, B, C, Z> Function3<A, B, C, Z> lift(Func3<A, B, C, Z> f) {\n\treturn bridge.lift(f);\n }"
] |
Gets type from super class's type parameter. | [
"@SuppressWarnings(\"unchecked\")\n\tpublic static Type getSuperclassTypeParameter(Class<?> subclass) {\n\t\tType superclass = subclass.getGenericSuperclass();\n\t\tif (superclass instanceof Class) {\n\t\t\tthrow new RuntimeException(\"Missing type parameter.\");\n\t\t}\n\t\treturn ((ParameterizedType) superclass).getActualTypeArguments()[0];\n\t}"
] | [
"@SuppressWarnings(\"WeakerAccess\")\n public Map<DeckReference, WaveformPreview> getLoadedPreviews() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, WaveformPreview>(previewHotCache));\n }",
"public static policydataset get(nitro_service service, String name) throws Exception{\n\t\tpolicydataset obj = new policydataset();\n\t\tobj.set_name(name);\n\t\tpolicydataset response = (policydataset) obj.get_resource(service);\n\t\treturn response;\n\t}",
"protected Integer getCorrectIndex(Integer index) {\n Integer size = jsonNode.size();\n Integer newIndex = index;\n\n // reverse walking through the array\n if(index < 0) {\n newIndex = size + index;\n }\n\n // the negative index would be greater than the size a second time!\n if(newIndex < 0) {\n throw LOG.indexOutOfBounds(index, size);\n }\n\n // the index is greater as the actual size\n if(index > size) {\n throw LOG.indexOutOfBounds(index, size);\n }\n\n return newIndex;\n }",
"public boolean isPartOf(GetVectorTileRequest request) {\n\t\tif (Math.abs(request.scale - scale) > EQUALS_DELTA) { return false; }\n\t\tif (code != null ? !code.equals(request.code) : request.code != null) { return false; }\n\t\tif (crs != null ? !crs.equals(request.crs) : request.crs != null) { return false; }\n\t\tif (filter != null ? !filter.equals(request.filter) : request.filter != null) { return false; }\n\t\tif (panOrigin != null ? !panOrigin.equals(request.panOrigin) : request.panOrigin != null) { return false; }\n\t\tif (renderer != null ? !renderer.equals(request.renderer) : request.renderer != null) { return false; }\n\t\tif (styleInfo != null ? !styleInfo.equals(request.styleInfo) : request.styleInfo != null) { return false; }\n\t\tif (paintGeometries && !request.paintGeometries) { return false; }\n\t\tif (paintLabels && !request.paintLabels) { return false; }\n\t\treturn true;\n\t}",
"public void keyboardSupportEnabled(Activity activity, boolean enable) {\n if (getContent() != null && getContent().getChildCount() > 0) {\n if (mKeyboardUtil == null) {\n mKeyboardUtil = new KeyboardUtil(activity, getContent().getChildAt(0));\n mKeyboardUtil.disable();\n }\n\n if (enable) {\n mKeyboardUtil.enable();\n } else {\n mKeyboardUtil.disable();\n }\n }\n }",
"public Date getStartTime(Date date)\n {\n Date result = m_startTimeCache.get(date);\n if (result == null)\n {\n ProjectCalendarDateRanges ranges = getRanges(date, null, null);\n if (ranges == null)\n {\n result = getParentFile().getProjectProperties().getDefaultStartTime();\n }\n else\n {\n result = ranges.getRange(0).getStart();\n }\n result = DateHelper.getCanonicalTime(result);\n m_startTimeCache.put(new Date(date.getTime()), result);\n }\n return result;\n }",
"@UiHandler(\"m_currentTillEndCheckBox\")\n void onCurrentTillEndChange(ValueChangeEvent<Boolean> event) {\n\n if (handleChange()) {\n m_controller.setCurrentTillEnd(event.getValue());\n }\n }",
"private static void checkPreconditions(final Map<Object, Object> mapping) {\n\t\tif( mapping == null ) {\n\t\t\tthrow new NullPointerException(\"mapping should not be null\");\n\t\t} else if( mapping.isEmpty() ) {\n\t\t\tthrow new IllegalArgumentException(\"mapping should not be empty\");\n\t\t}\n\t}",
"private void throwOrWarnAboutDescriptorProblem(String message) {\n if (validateDescriptions) {\n throw new IllegalArgumentException(message);\n }\n ControllerLogger.ROOT_LOGGER.warn(message);\n }"
] |
Rent a car available in the last serach result
@param intp - the command interpreter instance | [
"public void racRent() {\n\t\tpos = pos - 1;\n\t\tString userName = CarSearch.getLastSearchParams()[0];\n\t\tString pickupDate = CarSearch.getLastSearchParams()[1];\n\t\tString returnDate = CarSearch.getLastSearchParams()[2];\n\t\tthis.searcher.search(userName, pickupDate, returnDate);\n\t\tif (searcher!=null && searcher.getCars()!= null && pos < searcher.getCars().size() && searcher.getCars().get(pos) != null) {\n\t\t\tRESStatusType resStatus = reserver.reserveCar(searcher.getCustomer()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCars().get(pos)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, pickupDate\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, returnDate);\n\t\t\tConfirmationType confirm = reserver.getConfirmation(resStatus\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCustomer()\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, searcher.getCars().get(pos)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, pickupDate\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t, returnDate);\n\n\t\t\tRESCarType car = confirm.getCar();\n\t\t\tCustomerDetailsType customer = confirm.getCustomer();\n\t\t\t\n\t\t\tSystem.out.println(MessageFormat.format(CONFIRMATION\n\t\t\t\t\t, confirm.getDescription()\n\t\t\t\t\t, confirm.getReservationId()\n\t\t\t\t\t, customer.getName()\n\t\t\t\t\t, customer.getEmail()\n\t\t\t\t\t, customer.getCity()\n\t\t\t\t\t, customer.getStatus()\n\t\t\t\t\t, car.getBrand()\n\t\t\t\t\t, car.getDesignModel()\n\t\t\t\t\t, confirm.getFromDate()\n\t\t\t\t\t, confirm.getToDate()\n\t\t\t\t\t, padl(car.getRateDay(), 10)\n\t\t\t\t\t, padl(car.getRateWeekend(), 10)\n\t\t\t\t\t, padl(confirm.getCreditPoints().toString(), 7)));\n\t\t} else {\n\t\t\tSystem.out.println(\"Invalid selection: \" + (pos+1)); //$NON-NLS-1$\n\t\t}\n\t}"
] | [
"public void initialize() {\n\t\tthis.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.GetVersion, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.GetVersion, SerialMessage.SerialMessagePriority.High));\n\t\tthis.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.MemoryGetId, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.MemoryGetId, SerialMessage.SerialMessagePriority.High));\n\t\tthis.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.SerialApiGetCapabilities, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.SerialApiGetCapabilities, SerialMessage.SerialMessagePriority.High));\n\t}",
"public void handle(HttpRequest request, HttpResponder responder) {\n if (urlRewriter != null) {\n try {\n request.setUri(URI.create(request.uri()).normalize().toString());\n if (!urlRewriter.rewrite(request, responder)) {\n return;\n }\n } catch (Throwable t) {\n responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR,\n String.format(\"Caught exception processing request. Reason: %s\",\n t.getMessage()));\n LOG.error(\"Exception thrown during rewriting of uri {}\", request.uri(), t);\n return;\n }\n }\n\n try {\n String path = URI.create(request.uri()).normalize().getPath();\n\n List<PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel>> routableDestinations\n = patternRouter.getDestinations(path);\n\n PatternPathRouterWithGroups.RoutableDestination<HttpResourceModel> matchedDestination =\n getMatchedDestination(routableDestinations, request.method(), path);\n\n if (matchedDestination != null) {\n //Found a httpresource route to it.\n HttpResourceModel httpResourceModel = matchedDestination.getDestination();\n\n // Call preCall method of handler hooks.\n boolean terminated = false;\n HandlerInfo info = new HandlerInfo(httpResourceModel.getMethod().getDeclaringClass().getName(),\n httpResourceModel.getMethod().getName());\n for (HandlerHook hook : handlerHooks) {\n if (!hook.preCall(request, responder, info)) {\n // Terminate further request processing if preCall returns false.\n terminated = true;\n break;\n }\n }\n\n // Call httpresource method\n if (!terminated) {\n // Wrap responder to make post hook calls.\n responder = new WrappedHttpResponder(responder, handlerHooks, request, info);\n if (httpResourceModel.handle(request, responder, matchedDestination.getGroupNameValues()).isStreaming()) {\n responder.sendString(HttpResponseStatus.METHOD_NOT_ALLOWED,\n String.format(\"Body Consumer not supported for internalHttpResponder: %s\",\n request.uri()));\n }\n }\n } else if (routableDestinations.size() > 0) {\n //Found a matching resource but could not find the right HttpMethod so return 405\n responder.sendString(HttpResponseStatus.METHOD_NOT_ALLOWED,\n String.format(\"Problem accessing: %s. Reason: Method Not Allowed\", request.uri()));\n } else {\n responder.sendString(HttpResponseStatus.NOT_FOUND, String.format(\"Problem accessing: %s. Reason: Not Found\",\n request.uri()));\n }\n } catch (Throwable t) {\n responder.sendString(HttpResponseStatus.INTERNAL_SERVER_ERROR,\n String.format(\"Caught exception processing request. Reason: %s\", t.getMessage()));\n LOG.error(\"Exception thrown during request processing for uri {}\", request.uri(), t);\n }\n }",
"public ClientBootstrap bootStrapTcpClient()\n throws HttpRequestCreateException {\n\n ClientBootstrap tcpClient = null;\n try {\n\n // Configure the client.\n tcpClient = new ClientBootstrap(tcpMeta.getChannelFactory());\n\n // Configure the pipeline factory.\n tcpClient.setPipelineFactory(new MyPipelineFactory(TcpUdpSshPingResourceStore.getInstance().getTimer(),\n this, tcpMeta.getTcpIdleTimeoutSec())\n );\n\n tcpClient.setOption(\"connectTimeoutMillis\",\n tcpMeta.getTcpConnectTimeoutMillis());\n tcpClient.setOption(\"tcpNoDelay\", true);\n // tcpClient.setOption(\"keepAlive\", true);\n\n } catch (Exception t) {\n throw new TcpUdpRequestCreateException(\n \"Error in creating request in Tcpworker. \"\n + \" If tcpClient is null. Then fail to create.\", t);\n }\n\n return tcpClient;\n\n }",
"public void addExportedPackages(String... exportedPackages) {\n\t\tString oldBundles = mainAttributes.get(EXPORT_PACKAGE);\n\t\tif (oldBundles == null)\n\t\t\toldBundles = \"\";\n\t\tBundleList oldResultList = BundleList.fromInput(oldBundles, newline);\n\t\tBundleList resultList = BundleList.fromInput(oldBundles, newline);\n\t\tfor (String bundle : exportedPackages)\n\t\t\tresultList.mergeInto(Bundle.fromInput(bundle));\n\t\tString result = resultList.toString();\n\t\tboolean changed = !oldResultList.toString().equals(result);\n\t\tmodified |= changed;\n\t\tif (changed)\n\t\t\tmainAttributes.put(EXPORT_PACKAGE, result);\n\t}",
"public CustomHeadersInterceptor addHeaderMultimap(Map<String, List<String>> headers) {\n this.headers.putAll(headers);\n return this;\n }",
"@Deprecated\n public void validateOperation(final ModelNode operation) throws OperationFailedException {\n if (operation.hasDefined(ModelDescriptionConstants.OPERATION_NAME) && deprecationData != null && deprecationData.isNotificationUseful()) {\n ControllerLogger.DEPRECATED_LOGGER.operationDeprecated(getName(),\n PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)).toCLIStyleString());\n }\n for (AttributeDefinition ad : this.parameters) {\n ad.validateOperation(operation);\n }\n }",
"public void setFileExtensions(final String fileExtensions) {\n this.fileExtensions = IterableExtensions.<String>toList(((Iterable<String>)Conversions.doWrapArray(fileExtensions.trim().split(\"\\\\s*,\\\\s*\"))));\n }",
"protected <T> RequestBuilder doPrepareRequestBuilder(\n ResponseReader responseReader, String methodName, RpcStatsContext statsContext,\n String requestData, AsyncCallback<T> callback) {\n\n RequestBuilder rb = doPrepareRequestBuilderImpl(responseReader, methodName,\n statsContext, requestData, callback);\n\n return rb;\n }",
"public void delete() {\r\n URL url = DEVICE_PIN_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\r\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\r\n BoxAPIResponse response = request.send();\r\n response.disconnect();\r\n }"
] |
This function compares style ID's between features. Features are usually sorted by style. | [
"public int compareTo(InternalFeature o) {\n\t\tif (null == o) {\n\t\t\treturn -1; // avoid NPE, put null objects at the end\n\t\t}\n\t\tif (null != styleDefinition && null != o.getStyleInfo()) {\n\t\t\tif (styleDefinition.getIndex() > o.getStyleInfo().getIndex()) {\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tif (styleDefinition.getIndex() < o.getStyleInfo().getIndex()) {\n\t\t\t\treturn -1;\n\t\t\t}\n\t\t}\n\t\treturn 0;\n\t}"
] | [
"private void readProjectProperties(Document cdp)\n {\n WorkspaceProperties props = cdp.getWorkspaceProperties();\n ProjectProperties mpxjProps = m_projectFile.getProjectProperties();\n mpxjProps.setSymbolPosition(props.getCurrencyPosition());\n mpxjProps.setCurrencyDigits(props.getCurrencyDigits());\n mpxjProps.setCurrencySymbol(props.getCurrencySymbol());\n mpxjProps.setDaysPerMonth(props.getDaysPerMonth());\n mpxjProps.setMinutesPerDay(props.getHoursPerDay());\n mpxjProps.setMinutesPerWeek(props.getHoursPerWeek());\n\n m_workHoursPerDay = mpxjProps.getMinutesPerDay().doubleValue() / 60.0;\n }",
"public Collection<FieldNode> removeAndGetCandidatesWithoutInitialisingMethod() {\n final List<FieldNode> result = new ArrayList<FieldNode>();\n for (final Map.Entry<FieldNode, Initialisers> entry : candidatesAndInitialisers.entrySet()) {\n final Initialisers setters = entry.getValue();\n final List<MethodNode> initialisingMethods = setters.getMethods();\n if (initialisingMethods.isEmpty()) {\n result.add(entry.getKey());\n }\n }\n for (final FieldNode unassociatedVariable : result) {\n candidatesAndInitialisers.remove(unassociatedVariable);\n }\n return result;\n }",
"public void setPath(int pathId, String path) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_ACTUAL_PATH + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, path);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n statement.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"public DomainList getPhotostreamDomains(Date date, int perPage, int page) throws FlickrException {\n return getDomains(METHOD_GET_PHOTOSTREAM_DOMAINS, null, null, date, perPage, page);\n\n }",
"public AsciiTable setTextAlignment(TextAlignment textAlignment){\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setTextAlignment(textAlignment);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"private void addApiDocRoots(String packageListUrl) {\n\tBufferedReader br = null;\n\tpackageListUrl = fixApiDocRoot(packageListUrl);\n\ttry {\n\t URL url = new URL(packageListUrl + \"/package-list\");\n\t br = new BufferedReader(new InputStreamReader(url.openStream()));\n\t String line;\n\t while((line = br.readLine()) != null) {\n\t\tline = line + \".\";\n\t\tPattern pattern = Pattern.compile(line.replace(\".\", \"\\\\.\") + \"[^\\\\.]*\");\n\t\tapiDocMap.put(pattern, packageListUrl);\n\t }\n\t} catch(IOException e) {\n\t System.err.println(\"Errors happened while accessing the package-list file at \"\n\t\t + packageListUrl);\n\t} finally {\n\t if(br != null)\n\t\ttry {\n\t\t br.close();\n\t\t} catch (IOException e) {}\n\t}\n\t\n }",
"public static csvserver_cachepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_cachepolicy_binding obj = new csvserver_cachepolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_cachepolicy_binding response[] = (csvserver_cachepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"protected ViewPort load() {\n resize = Window.addResizeHandler(event -> {\n execute(event.getWidth(), event.getHeight());\n });\n\n execute(window().width(), (int)window().height());\n return viewPort;\n }",
"private static boolean isCollectionMatching(Joinable mainSideJoinable, OgmCollectionPersister inverseSidePersister) {\n\t\tboolean isSameTable = mainSideJoinable.getTableName().equals( inverseSidePersister.getTableName() );\n\n\t\tif ( !isSameTable ) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn Arrays.equals( mainSideJoinable.getKeyColumnNames(), inverseSidePersister.getElementColumnNames() );\n\t}"
] |
Return the class of one of the properties of another class from which the Hibernate metadata is given.
@param meta
The parent class to search a property in.
@param propertyName
The name of the property in the parent class (provided by meta)
@return Returns the class of the property in question.
@throws HibernateLayerException
Throws an exception if the property name could not be retrieved. | [
"protected Class<?> getPropertyClass(ClassMetadata meta, String propertyName) throws HibernateLayerException {\n\t\t// try to assure the correct separator is used\n\t\tpropertyName = propertyName.replace(XPATH_SEPARATOR, SEPARATOR);\n\n\t\tif (propertyName.contains(SEPARATOR)) {\n\t\t\tString directProperty = propertyName.substring(0, propertyName.indexOf(SEPARATOR));\n\t\t\ttry {\n\t\t\t\tType prop = meta.getPropertyType(directProperty);\n\t\t\t\tif (prop.isCollectionType()) {\n\t\t\t\t\tCollectionType coll = (CollectionType) prop;\n\t\t\t\t\tprop = coll.getElementType((SessionFactoryImplementor) sessionFactory);\n\t\t\t\t}\n\t\t\t\tClassMetadata propMeta = sessionFactory.getClassMetadata(prop.getReturnedClass());\n\t\t\t\treturn getPropertyClass(propMeta, propertyName.substring(propertyName.indexOf(SEPARATOR) + 1));\n\t\t\t} catch (HibernateException e) {\n\t\t\t\tthrow new HibernateLayerException(e, ExceptionCode.HIBERNATE_COULD_NOT_RESOLVE, propertyName,\n\t\t\t\t\t\tmeta.getEntityName());\n\t\t\t}\n\t\t} else {\n\t\t\ttry {\n\t\t\t\treturn meta.getPropertyType(propertyName).getReturnedClass();\n\t\t\t} catch (HibernateException e) {\n\t\t\t\tthrow new HibernateLayerException(e, ExceptionCode.HIBERNATE_COULD_NOT_RESOLVE, propertyName,\n\t\t\t\t\t\tmeta.getEntityName());\n\t\t\t}\n\t\t}\n\t}"
] | [
"public static ProtocolConnectionManager create(final Connection connection, final ConnectionOpenHandler openHandler) {\n return create(new EstablishedConnection(connection, openHandler));\n }",
"public void doLocalClear()\r\n {\r\n if(log.isDebugEnabled()) log.debug(\"Clear materialization cache\");\r\n invokeCounter = 0;\r\n enabledReadCache = false;\r\n objectBuffer.clear();\r\n }",
"public void setCastShadow(boolean enableFlag)\n {\n GVRSceneObject owner = getOwnerObject();\n\n if (owner != null)\n {\n GVRShadowMap shadowMap = (GVRShadowMap) getComponent(GVRRenderTarget.getComponentType());\n if (enableFlag)\n {\n if (shadowMap != null)\n {\n shadowMap.setEnable(true);\n }\n else\n {\n float angle = (float) Math.acos(getFloat(\"outer_cone_angle\")) * 2.0f;\n GVRCamera shadowCam = GVRShadowMap.makePerspShadowCamera(getGVRContext().getMainScene().getMainCameraRig().getCenterCamera(), angle);\n shadowMap = new GVRShadowMap(getGVRContext(), shadowCam);\n owner.attachComponent(shadowMap);\n }\n mChanged.set(true);\n }\n else if (shadowMap != null)\n {\n shadowMap.setEnable(false);\n }\n }\n mCastShadow = enableFlag;\n }",
"public static String checkRequiredProperties(Properties props,\r\n String ... requiredProps) {\r\n for (String required : requiredProps) {\r\n if (props.getProperty(required) == null) {\r\n return required;\r\n }\r\n }\r\n return null;\r\n }",
"private Object toReference(int type, Object referent, int hash)\r\n {\r\n switch (type)\r\n {\r\n case HARD:\r\n return referent;\r\n case SOFT:\r\n return new SoftRef(hash, referent, queue);\r\n case WEAK:\r\n return new WeakRef(hash, referent, queue);\r\n default:\r\n throw new Error();\r\n }\r\n }",
"public void process(Resource resource, int index, byte[] data)\n {\n CostRateTable result = new CostRateTable();\n\n if (data != null)\n {\n for (int i = 16; i + 44 <= data.length; i += 44)\n {\n Rate standardRate = new Rate(MPPUtility.getDouble(data, i), TimeUnit.HOURS);\n TimeUnit standardRateFormat = getFormat(MPPUtility.getShort(data, i + 8));\n Rate overtimeRate = new Rate(MPPUtility.getDouble(data, i + 16), TimeUnit.HOURS);\n TimeUnit overtimeRateFormat = getFormat(MPPUtility.getShort(data, i + 24));\n Double costPerUse = NumberHelper.getDouble(MPPUtility.getDouble(data, i + 32) / 100.0);\n Date endDate = MPPUtility.getTimestampFromTenths(data, i + 40);\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRateFormat, overtimeRate, overtimeRateFormat, costPerUse, endDate);\n result.add(entry);\n }\n Collections.sort(result);\n }\n else\n {\n //\n // MS Project economises by not actually storing the first cost rate\n // table if it doesn't need to, so we take this into account here.\n //\n if (index == 0)\n {\n Rate standardRate = resource.getStandardRate();\n Rate overtimeRate = resource.getOvertimeRate();\n Number costPerUse = resource.getCostPerUse();\n CostRateTableEntry entry = new CostRateTableEntry(standardRate, standardRate.getUnits(), overtimeRate, overtimeRate.getUnits(), costPerUse, CostRateTableEntry.DEFAULT_ENTRY.getEndDate());\n result.add(entry);\n }\n else\n {\n result.add(CostRateTableEntry.DEFAULT_ENTRY);\n }\n }\n\n resource.setCostRateTable(index, result);\n }",
"public JsonNode wbSetLabel(String id, String site, String title,\n\t\t\tString newEntity, String language, String value,\n\t\t\tboolean bot, long baserevid, String summary)\n\t\t\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tValidate.notNull(language,\n\t\t\t\t\"Language parameter cannot be null when setting a label\");\n\t\t\n\t\tMap<String, String> parameters = new HashMap<String, String>();\n\t\tparameters.put(\"language\", language);\n\t\tif (value != null) {\n\t\t\tparameters.put(\"value\", value);\n\t\t}\n\t\t\n\t\tJsonNode response = performAPIAction(\"wbsetlabel\", id, site, title, newEntity,\n\t\t\t\tparameters, summary, baserevid, bot);\n\t\treturn response;\n\t}",
"private Set<HttpMethod> getHttpMethods(Method method) {\n Set<HttpMethod> httpMethods = new HashSet<>();\n\n if (method.isAnnotationPresent(GET.class)) {\n httpMethods.add(HttpMethod.GET);\n }\n if (method.isAnnotationPresent(PUT.class)) {\n httpMethods.add(HttpMethod.PUT);\n }\n if (method.isAnnotationPresent(POST.class)) {\n httpMethods.add(HttpMethod.POST);\n }\n if (method.isAnnotationPresent(DELETE.class)) {\n httpMethods.add(HttpMethod.DELETE);\n }\n\n return Collections.unmodifiableSet(httpMethods);\n }",
"public List<Artifact> getArtifacts(final Boolean hasLicense) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactsPath());\n final ClientResponse response = resource.queryParam(ServerAPI.HAS_LICENSE_PARAM, hasLicense.toString())\n .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = \"Failed to get artifacts\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n\n return response.getEntity(ArtifactList.class);\n }"
] |
Copy the specified bytes into a new array
@param array The array to copy from
@param from The index in the array to begin copying from
@param to The least index not copied
@return A new byte[] containing the copied bytes | [
"public static byte[] copy(byte[] array, int from, int to) {\n if(to - from < 0) {\n return new byte[0];\n } else {\n byte[] a = new byte[to - from];\n System.arraycopy(array, from, a, 0, to - from);\n return a;\n }\n }"
] | [
"public static void waitForStandalone(final ModelControllerClient client, final long startupTimeout)\n throws InterruptedException, RuntimeException, TimeoutException {\n waitForStandalone(null, client, startupTimeout);\n }",
"public List<Message> requestFolderMenuFrom(final SlotReference slotReference, final int sortOrder, final int folderId)\n throws Exception {\n\n ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {\n @Override\n public List<Message> useClient(Client client) throws Exception {\n if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {\n try {\n logger.debug(\"Requesting Key menu.\");\n Message response = client.menuRequestTyped(Message.KnownType.FOLDER_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot,\n CdjStatus.TrackType.UNANALYZED, new NumberField(sortOrder), new NumberField(folderId), new NumberField(0xffffff));\n return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.UNANALYZED, response);\n } finally {\n client.unlockForMenuOperations();\n }\n } else {\n throw new TimeoutException(\"Unable to lock player for menu operations.\");\n }\n }\n };\n\n return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, \"requesting folder menu\");\n }",
"private void recurseAndAddFiles(GraphRewrite event, FileService fileService, WindupJavaConfigurationService javaConfigurationService, FileModel file)\n {\n if (javaConfigurationService.checkIfIgnored(event, file))\n return;\n\n String filePath = file.getFilePath();\n File fileReference = new File(filePath);\n Long directorySize = new Long(0);\n\n if (fileReference.isDirectory())\n {\n File[] subFiles = fileReference.listFiles();\n if (subFiles != null)\n {\n for (File reference : subFiles)\n {\n FileModel subFile = fileService.createByFilePath(file, reference.getAbsolutePath());\n recurseAndAddFiles(event, fileService, javaConfigurationService, subFile);\n if (subFile.isDirectory())\n {\n directorySize = directorySize + subFile.getDirectorySize();\n }\n else\n {\n directorySize = directorySize + subFile.getSize();\n }\n }\n }\n file.setDirectorySize(directorySize);\n }\n }",
"public boolean putAtomic(C instance, K key, V value, Map<K, V> snapshot) {\n Assert.checkNotNullParam(\"key\", key);\n final Map<K, V> newMap;\n final int oldSize = snapshot.size();\n if (oldSize == 0) {\n newMap = Collections.singletonMap(key, value);\n } else if (oldSize == 1) {\n final Map.Entry<K, V> entry = snapshot.entrySet().iterator().next();\n final K oldKey = entry.getKey();\n if (oldKey.equals(key)) {\n return false;\n } else {\n newMap = new FastCopyHashMap<K, V>(snapshot);\n newMap.put(key, value);\n }\n } else {\n newMap = new FastCopyHashMap<K, V>(snapshot);\n newMap.put(key, value);\n }\n return updater.compareAndSet(instance, snapshot, newMap);\n }",
"public static crvserver_binding get(nitro_service service, String name) throws Exception{\n\t\tcrvserver_binding obj = new crvserver_binding();\n\t\tobj.set_name(name);\n\t\tcrvserver_binding response = (crvserver_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static void checkFileOrDirectoryToBeRead(File fileOrDir, String fileDesc)\n {\n if (fileOrDir == null)\n throw new IllegalArgumentException(fileDesc + \" must not be null.\");\n if (!fileOrDir.exists())\n throw new IllegalArgumentException(fileDesc + \" does not exist: \" + fileOrDir.getAbsolutePath());\n if (!(fileOrDir.isDirectory() || fileOrDir.isFile()))\n throw new IllegalArgumentException(fileDesc + \" must be a file or a directory: \" + fileOrDir.getPath());\n if (fileOrDir.isDirectory())\n {\n if (fileOrDir.list().length == 0)\n throw new IllegalArgumentException(fileDesc + \" is an empty directory: \" + fileOrDir.getPath());\n }\n }",
"public static <T> T withObjectStreams(Socket socket, @ClosureParams(value=SimpleType.class, options={\"java.io.ObjectInputStream\",\"java.io.ObjectOutputStream\"}) Closure<T> closure) throws IOException {\n InputStream input = socket.getInputStream();\n OutputStream output = socket.getOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(output);\n ObjectInputStream ois = new ObjectInputStream(input);\n try {\n T result = closure.call(new Object[]{ois, oos});\n\n InputStream temp1 = ois;\n ois = null;\n temp1.close();\n temp1 = input;\n input = null;\n temp1.close();\n OutputStream temp2 = oos;\n oos = null;\n temp2.close();\n temp2 = output;\n output = null;\n temp2.close();\n\n return result;\n } finally {\n closeWithWarning(ois);\n closeWithWarning(input);\n closeWithWarning(oos);\n closeWithWarning(output);\n }\n }",
"private void readAssignmentExtendedAttributes(Project.Assignments.Assignment xml, ResourceAssignment mpx)\n {\n for (Project.Assignments.Assignment.ExtendedAttribute attrib : xml.getExtendedAttribute())\n {\n int xmlFieldID = Integer.parseInt(attrib.getFieldID()) & 0x0000FFFF;\n AssignmentField mpxFieldID = MPPAssignmentField.getInstance(xmlFieldID);\n TimeUnit durationFormat = DatatypeConverter.parseDurationTimeUnits(attrib.getDurationFormat(), null);\n DatatypeConverter.parseExtendedAttribute(m_projectFile, mpx, attrib.getValue(), mpxFieldID, durationFormat);\n }\n }",
"public ProjectFile read() throws MPXJException\n {\n MPD9DatabaseReader reader = new MPD9DatabaseReader();\n reader.setProjectID(m_projectID);\n reader.setPreserveNoteFormatting(m_preserveNoteFormatting);\n reader.setDataSource(m_dataSource);\n reader.setConnection(m_connection);\n ProjectFile project = reader.read();\n return (project);\n }"
] |
Output method responsible for sending the updated content to the Subscribers.
@param cn | [
"public void notifySubscriberCallback(ContentNotification cn) {\n String content = fetchContentFromPublisher(cn);\n\n distributeContentToSubscribers(content, cn.getUrl());\n }"
] | [
"public static base_response rename(nitro_service client, cmppolicylabel resource, String new_labelname) throws Exception {\n\t\tcmppolicylabel renameresource = new cmppolicylabel();\n\t\trenameresource.labelname = resource.labelname;\n\t\treturn renameresource.rename_resource(client,new_labelname);\n\t}",
"public static DesignDocument fromFile(File file) throws FileNotFoundException {\r\n assertNotEmpty(file, \"Design js file\");\r\n DesignDocument designDocument;\r\n Gson gson = new Gson();\r\n InputStreamReader reader = null;\r\n try {\r\n reader = new InputStreamReader(new FileInputStream(file),\"UTF-8\");\r\n //Deserialize JS file contents into DesignDocument object\r\n designDocument = gson.fromJson(reader, DesignDocument.class);\r\n return designDocument;\r\n } catch (UnsupportedEncodingException e) {\r\n //UTF-8 should be supported on all JVMs\r\n throw new RuntimeException(e);\r\n } finally {\r\n IOUtils.closeQuietly(reader);\r\n }\r\n }",
"public double getValue(int[] batch) {\n double value = 0.0;\n for (int i=0; i<batch.length; i++) {\n value += getValue(i);\n }\n return value;\n }",
"public void foreach(PixelFunction fn) {\n Arrays.stream(points()).forEach(p -> fn.apply(p.x, p.y, pixel(p)));\n }",
"public HashMap<K2, HashMap<K3, V>> get(final K1 firstKey) {\n\t\treturn map.get(firstKey);\n\t}",
"private void deliverLostAnnouncement(final DeviceAnnouncement announcement) {\n for (final DeviceAnnouncementListener listener : getDeviceAnnouncementListeners()) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n try {\n listener.deviceLost(announcement);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering device lost announcement to listener\", t);\n }\n }\n });\n }\n }",
"public static base_response delete(nitro_service client, String viewname) throws Exception {\n\t\tdnsview deleteresource = new dnsview();\n\t\tdeleteresource.viewname = viewname;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"@SuppressWarnings(\"unused\")\n\t@XmlID\n @XmlAttribute(name = \"id\")\n private String getXmlID(){\n return String.format(\"%s-%s\", this.getClass().getSimpleName(), Long.valueOf(id));\n }",
"public boolean isIdentical(T a, double tol) {\n if( a.getType() != getType() )\n return false;\n return ops.isIdentical(mat,a.mat,tol);\n }"
] |
Finds and sets up the Listeners in the given rootView.
@param rootView a View to traverse looking for listeners.
@return the list of refinement attributes found on listeners. | [
"private List<String> processAllListeners(View rootView) {\n List<String> refinementAttributes = new ArrayList<>();\n\n // Register any AlgoliaResultsListener (unless it has a different variant than searcher)\n final List<AlgoliaResultsListener> resultListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaResultsListener.class);\n if (resultListeners.isEmpty()) {\n throw new IllegalStateException(Errors.LAYOUT_MISSING_RESULT_LISTENER);\n }\n for (AlgoliaResultsListener listener : resultListeners) {\n if (!this.resultListeners.contains(listener)) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n this.resultListeners.add(listener);\n searcher.registerResultListener(listener);\n prepareWidget(listener, refinementAttributes);\n }\n }\n }\n\n // Register any AlgoliaErrorListener (unless it has a different variant than searcher)\n final List<AlgoliaErrorListener> errorListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaErrorListener.class);\n for (AlgoliaErrorListener listener : errorListeners) {\n if (!this.errorListeners.contains(listener)) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n this.errorListeners.add(listener);\n }\n }\n searcher.registerErrorListener(listener);\n prepareWidget(listener, refinementAttributes);\n }\n\n // Register any AlgoliaSearcherListener (unless it has a different variant than searcher)\n final List<AlgoliaSearcherListener> searcherListeners = LayoutViews.findByClass((ViewGroup) rootView, AlgoliaSearcherListener.class);\n for (AlgoliaSearcherListener listener : searcherListeners) {\n final String variant = BindingHelper.getVariantForView((View) listener);\n if (variant == null || searcher.variant.equals(variant)) {\n listener.initWithSearcher(searcher);\n prepareWidget(listener, refinementAttributes);\n }\n }\n\n return refinementAttributes;\n }"
] | [
"public static DMatrixRMaj nullspaceQR( DMatrixRMaj A , int totalSingular ) {\n SolveNullSpaceQR_DDRM solver = new SolveNullSpaceQR_DDRM();\n\n DMatrixRMaj nullspace = new DMatrixRMaj(1,1);\n\n if( !solver.process(A,totalSingular,nullspace))\n throw new RuntimeException(\"Solver failed. try SVD based method instead?\");\n\n return nullspace;\n }",
"public ColumnBuilder addFieldProperty(String propertyName, String value) {\n\t\tfieldProperties.put(propertyName, value);\n\t\treturn this;\n\t}",
"public String addComment(String photosetId, String commentText) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD_COMMENT);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\r\n parameters.put(\"comment_text\", commentText);\r\n\r\n // Note: This method requires an HTTP POST request.\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n // response:\r\n // <comment id=\"97777-12492-72057594037942601\" />\r\n Element commentElement = response.getPayload();\r\n return commentElement.getAttribute(\"id\");\r\n }",
"public List<ServerRedirect> tableServers(int profileId, int serverGroupId) {\n ArrayList<ServerRedirect> servers = new ArrayList<>();\n PreparedStatement queryStatement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n queryStatement = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_SERVERS +\n \" WHERE \" + Constants.GENERIC_PROFILE_ID + \" = ?\" +\n \" AND \" + Constants.SERVER_REDIRECT_GROUP_ID + \" = ?\"\n );\n queryStatement.setInt(1, profileId);\n queryStatement.setInt(2, serverGroupId);\n results = queryStatement.executeQuery();\n while (results.next()) {\n ServerRedirect curServer = new ServerRedirect(results.getInt(Constants.GENERIC_ID),\n results.getString(Constants.SERVER_REDIRECT_REGION),\n results.getString(Constants.SERVER_REDIRECT_SRC_URL),\n results.getString(Constants.SERVER_REDIRECT_DEST_URL),\n results.getString(Constants.SERVER_REDIRECT_HOST_HEADER));\n curServer.setProfileId(profileId);\n servers.add(curServer);\n }\n } catch (SQLException e) {\n e.printStackTrace();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n return servers;\n }",
"public PagedList<V> convert(final PagedList<U> uList) {\n if (uList == null || uList.isEmpty()) {\n return new PagedList<V>() {\n @Override\n public Page<V> nextPage(String s) throws RestException, IOException {\n return null;\n }\n };\n }\n Page<U> uPage = uList.currentPage();\n final PageImpl<V> vPage = new PageImpl<>();\n vPage.setNextPageLink(uPage.nextPageLink());\n vPage.setItems(new ArrayList<V>());\n loadConvertedList(uPage, vPage);\n return new PagedList<V>(vPage) {\n @Override\n public Page<V> nextPage(String nextPageLink) throws RestException, IOException {\n Page<U> uPage = uList.nextPage(nextPageLink);\n final PageImpl<V> vPage = new PageImpl<>();\n vPage.setNextPageLink(uPage.nextPageLink());\n vPage.setItems(new ArrayList<V>());\n loadConvertedList(uPage, vPage);\n return vPage;\n }\n };\n }",
"public Version putVersionedWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper)\n throws ObsoleteVersionException {\n validateTimeout(requestWrapper.getRoutingTimeoutInMs());\n for(int attempts = 0; attempts < this.metadataRefreshAttempts; attempts++) {\n try {\n String keyHexString = \"\";\n long startTimeInMs = System.currentTimeMillis();\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) requestWrapper.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n debugLogStart(\"PUT_VERSION\",\n requestWrapper.getRequestOriginTimeInMs(),\n startTimeInMs,\n keyHexString);\n }\n store.put(requestWrapper);\n if(logger.isDebugEnabled()) {\n debugLogEnd(\"PUT_VERSION\",\n requestWrapper.getRequestOriginTimeInMs(),\n startTimeInMs,\n System.currentTimeMillis(),\n keyHexString,\n 0);\n }\n return requestWrapper.getValue().getVersion();\n } catch(InvalidMetadataException e) {\n logger.info(\"Received invalid metadata exception during put [ \" + e.getMessage()\n + \" ] on store '\" + storeName + \"'. Rebootstrapping\");\n bootStrap();\n }\n }\n throw new VoldemortException(this.metadataRefreshAttempts\n + \" metadata refresh attempts failed.\");\n }",
"private void prefetchRelationships(Query query)\r\n {\r\n List prefetchedRel;\r\n Collection owners;\r\n String relName;\r\n RelationshipPrefetcher[] prefetchers;\r\n\r\n if (query == null || query.getPrefetchedRelationships() == null || query.getPrefetchedRelationships().isEmpty())\r\n {\r\n return;\r\n }\r\n\r\n if (!supportsAdvancedJDBCCursorControl())\r\n {\r\n logger.info(\"prefetching relationships requires JDBC level 2.0\");\r\n return;\r\n }\r\n\r\n // prevent releasing of DBResources\r\n setInBatchedMode(true);\r\n\r\n prefetchedRel = query.getPrefetchedRelationships();\r\n prefetchers = new RelationshipPrefetcher[prefetchedRel.size()];\r\n\r\n // disable auto retrieve for all prefetched relationships\r\n for (int i = 0; i < prefetchedRel.size(); i++)\r\n {\r\n relName = (String) prefetchedRel.get(i);\r\n prefetchers[i] = getBroker().getRelationshipPrefetcherFactory()\r\n .createRelationshipPrefetcher(getQueryObject().getClassDescriptor(), relName);\r\n prefetchers[i].prepareRelationshipSettings();\r\n }\r\n\r\n // materialize ALL owners of this Iterator\r\n owners = getOwnerObjects();\r\n\r\n // prefetch relationships and associate with owners\r\n for (int i = 0; i < prefetchedRel.size(); i++)\r\n {\r\n prefetchers[i].prefetchRelationship(owners);\r\n }\r\n\r\n // reset auto retrieve for all prefetched relationships\r\n for (int i = 0; i < prefetchedRel.size(); i++)\r\n {\r\n prefetchers[i].restoreRelationshipSettings();\r\n }\r\n\r\n try\r\n {\r\n getRsAndStmt().m_rs.beforeFirst(); // reposition resultset jdbc 2.0\r\n }\r\n catch (SQLException e)\r\n {\r\n logger.error(\"beforeFirst failed !\", e);\r\n }\r\n\r\n setInBatchedMode(false);\r\n setHasCalledCheck(false);\r\n }",
"public static Object readObject(File file) throws IOException,\n ClassNotFoundException {\n FileInputStream fileIn = new FileInputStream(file);\n ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(fileIn));\n try {\n return in.readObject();\n } finally {\n IoUtils.safeClose(in);\n }\n }",
"public static void setFieldValue(Object object, String fieldName, Object value) {\n try {\n getDeclaredFieldInHierarchy(object.getClass(), fieldName).set(object, value);\n } catch (IllegalArgumentException e) {\n throw new RuntimeException(e);\n } catch (IllegalAccessException e) {\n throw new RuntimeException(e);\n }\n }"
] |
get the getter method corresponding to given property | [
"public static Method getGetterPropertyMethod(Class<?> type,\r\n\t\t\tString propertyName) {\r\n\t\tString sourceMethodName = \"get\"\r\n\t\t\t\t+ BeanUtils.capitalizePropertyName(propertyName);\r\n\r\n\t\tMethod sourceMethod = BeanUtils.getMethod(type, sourceMethodName);\r\n\r\n\t\tif (sourceMethod == null) {\r\n\t\t\tsourceMethodName = \"is\"\r\n\t\t\t\t\t+ BeanUtils.capitalizePropertyName(propertyName);\r\n\t\t\tsourceMethod = BeanUtils.getMethod(type, sourceMethodName);\r\n\t\t\tif (sourceMethod != null\r\n\t\t\t\t\t&& sourceMethod.getReturnType() != Boolean.TYPE) {\r\n\t\t\t\tsourceMethod = null;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn sourceMethod;\r\n\t}"
] | [
"public void addProperty(String name, String... values) {\n List<String> valueList = new ArrayList<String>();\n for (String value : values) {\n valueList.add(value.trim());\n }\n properties.put(name.trim(), valueList);\n }",
"public static BoxUser.Info createAppUser(BoxAPIConnection api, String name) {\n return createAppUser(api, name, new CreateUserParams());\n }",
"public static Map<Integer, Integer> getMapOfContiguousPartitions(final Cluster cluster,\n int zoneId) {\n List<Integer> partitionIds = new ArrayList<Integer>(cluster.getPartitionIdsInZone(zoneId));\n Map<Integer, Integer> partitionIdToRunLength = Maps.newHashMap();\n\n if(partitionIds.isEmpty()) {\n return partitionIdToRunLength;\n }\n\n int lastPartitionId = partitionIds.get(0);\n int initPartitionId = lastPartitionId;\n\n for(int offset = 1; offset < partitionIds.size(); offset++) {\n int partitionId = partitionIds.get(offset);\n if(partitionId == lastPartitionId + 1) {\n lastPartitionId = partitionId;\n continue;\n }\n int runLength = lastPartitionId - initPartitionId + 1;\n\n partitionIdToRunLength.put(initPartitionId, runLength);\n\n initPartitionId = partitionId;\n lastPartitionId = initPartitionId;\n }\n\n int runLength = lastPartitionId - initPartitionId + 1;\n if(lastPartitionId == cluster.getNumberOfPartitions() - 1\n && partitionIdToRunLength.containsKey(0)) {\n // special case of contiguity that wraps around the ring.\n partitionIdToRunLength.put(initPartitionId, runLength + partitionIdToRunLength.get(0));\n partitionIdToRunLength.remove(0);\n } else {\n partitionIdToRunLength.put(initPartitionId, runLength);\n }\n\n return partitionIdToRunLength;\n }",
"private ModelNode resolveSubsystems(final List<ModelNode> extensions) {\n\n HostControllerLogger.ROOT_LOGGER.debug(\"Applying extensions provided by master\");\n final ModelNode result = operationExecutor.installSlaveExtensions(extensions);\n if (!SUCCESS.equals(result.get(OUTCOME).asString())) {\n throw HostControllerLogger.ROOT_LOGGER.failedToAddExtensions(result.get(FAILURE_DESCRIPTION));\n }\n final ModelNode subsystems = new ModelNode();\n for (final ModelNode extension : extensions) {\n extensionRegistry.recordSubsystemVersions(extension.asString(), subsystems);\n }\n return subsystems;\n }",
"public static appfwprofile_stats[] get(nitro_service service) throws Exception{\n\t\tappfwprofile_stats obj = new appfwprofile_stats();\n\t\tappfwprofile_stats[] response = (appfwprofile_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"public AT_Row setPaddingLeftRight(int padding){\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingLeftRight(padding);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public static nsrollbackcmd[] get(nitro_service service, nsrollbackcmd_args args) throws Exception{\n\t\tnsrollbackcmd obj = new nsrollbackcmd();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tnsrollbackcmd[] response = (nsrollbackcmd[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"private MBeanServer getServerForName(String name) {\n try {\n MBeanServer mbeanServer = null;\n final ObjectName objectNameQuery = new ObjectName(name + \":type=Service,*\");\n\n for (final MBeanServer server : MBeanServerFactory.findMBeanServer(null)) {\n if (server.queryNames(objectNameQuery, null).size() > 0) {\n mbeanServer = server;\n // we found it, bail out\n break;\n }\n }\n\n return mbeanServer;\n } catch (Exception e) {\n }\n\n return null;\n }",
"public Response remove(String id, String rev) {\r\n assertNotEmpty(id, \"id\");\r\n assertNotEmpty(id, \"rev\");\r\n return db.remove(ensureDesignPrefix(id), rev);\r\n\r\n }"
] |
Find and validate manifest.json file in Artifactory for the current image.
Since provided imageTag differs between reverse-proxy and proxy-less configuration, try to build the correct manifest path.
@param server
@param dependenciesClient
@param listener
@return
@throws IOException | [
"private boolean findAndSetManifestFromArtifactory(ArtifactoryServer server, ArtifactoryDependenciesClient dependenciesClient, TaskListener listener) throws IOException {\n String candidateImagePath = DockerUtils.getImagePath(imageTag);\n String manifestPath;\n\n // Try to get manifest, assuming reverse proxy\n manifestPath = StringUtils.join(new String[]{server.getUrl(), targetRepo, candidateImagePath, \"manifest.json\"}, \"/\");\n if (checkAndSetManifestAndImagePathCandidates(manifestPath, candidateImagePath, dependenciesClient, listener)) {\n return true;\n }\n\n // Try to get manifest, assuming proxy-less\n candidateImagePath = candidateImagePath.substring(candidateImagePath.indexOf(\"/\") + 1);\n manifestPath = StringUtils.join(new String[]{server.getUrl(), targetRepo, candidateImagePath, \"manifest.json\"}, \"/\");\n if (checkAndSetManifestAndImagePathCandidates(manifestPath, candidateImagePath, dependenciesClient, listener)) {\n return true;\n }\n\n // Couldn't find correct manifest\n listener.getLogger().println(\"Could not find corresponding manifest.json file in Artifactory.\");\n return false;\n }"
] | [
"public static double blackScholesDigitalOptionValue(\n\t\t\tdouble initialStockValue,\n\t\t\tdouble riskFreeRate,\n\t\t\tdouble volatility,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble optionStrike)\n\t{\n\t\tif(optionStrike <= 0.0)\n\t\t{\n\t\t\t// The Black-Scholes model does not consider it being an option\n\t\t\treturn 1.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate analytic value\n\t\t\tdouble dPlus = (Math.log(initialStockValue / optionStrike) + (riskFreeRate + 0.5 * volatility * volatility) * optionMaturity) / (volatility * Math.sqrt(optionMaturity));\n\t\t\tdouble dMinus = dPlus - volatility * Math.sqrt(optionMaturity);\n\n\t\t\tdouble valueAnalytic = Math.exp(- riskFreeRate * optionMaturity) * NormalDistribution.cumulativeDistribution(dMinus);\n\n\t\t\treturn valueAnalytic;\n\t\t}\n\t}",
"public List<Artifact> getArtifacts(final Boolean hasLicense) throws GrapesCommunicationException {\n final Client client = getClient();\n final WebResource resource = client.resource(serverURL).path(RequestUtils.getArtifactsPath());\n final ClientResponse response = resource.queryParam(ServerAPI.HAS_LICENSE_PARAM, hasLicense.toString())\n .accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = \"Failed to get artifacts\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n\n return response.getEntity(ArtifactList.class);\n }",
"public CompositeGeneratorNode indent(final CompositeGeneratorNode parent, final String indentString) {\n final IndentNode indent = new IndentNode(indentString);\n List<IGeneratorNode> _children = parent.getChildren();\n _children.add(indent);\n return indent;\n }",
"public static double HighAccuracyFunction(double x) {\n if (x < -8 || x > 8)\n return 0;\n\n double sum = x;\n double term = 0;\n\n double nextTerm = x;\n double pwr = x * x;\n double i = 1;\n\n // Iterate until adding next terms doesn't produce\n // any change within the current numerical accuracy.\n\n while (sum != term) {\n term = sum;\n\n // Next term\n nextTerm *= pwr / (i += 2);\n\n sum += nextTerm;\n }\n\n return 0.5 + sum * Math.exp(-0.5 * pwr - 0.5 * Constants.Log2PI);\n }",
"public Configuration getConfiguration(String name) {\n Configuration[] values = getConfigurations(name);\n\n if (values == null) {\n return null;\n }\n\n return values[0];\n }",
"public static appfwprofile_stats get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_stats obj = new appfwprofile_stats();\n\t\tobj.set_name(name);\n\t\tappfwprofile_stats response = (appfwprofile_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"@Override\n public CopticDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }",
"protected static <R extends AddressSection, S extends AddressSegment> R fastIncrement(\n\t\t\tR section,\n\t\t\tlong increment,\n\t\t\tAddressCreator<?, R, ?, S> addrCreator, \n\t\t\tSupplier<R> lowerProducer,\n\t\t\tSupplier<R> upperProducer,\n\t\t\tInteger prefixLength) {\n\t\tif(increment >= 0) {\n\t\t\tBigInteger count = section.getCount();\n\t\t\tif(count.compareTo(LONG_MAX) <= 0) {\n\t\t\t\tlong longCount = count.longValue();\n\t\t\t\tif(longCount > increment) {\n\t\t\t\t\tif(longCount == increment + 1) {\n\t\t\t\t\t\treturn upperProducer.get();\n\t\t\t\t\t}\n\t\t\t\t\treturn incrementRange(section, increment, addrCreator, lowerProducer, prefixLength);\n\t\t\t\t}\n\t\t\t\tBigInteger value = section.getValue();\n\t\t\t\tBigInteger upperValue;\n\t\t\t\tif(value.compareTo(LONG_MAX) <= 0 && (upperValue = section.getUpperValue()).compareTo(LONG_MAX) <= 0) {\n\t\t\t\t\treturn increment(\n\t\t\t\t\t\t\tsection,\n\t\t\t\t\t\t\tincrement,\n\t\t\t\t\t\t\taddrCreator,\n\t\t\t\t\t\t\tcount.longValue(),\n\t\t\t\t\t\t\tvalue.longValue(),\n\t\t\t\t\t\t\tupperValue.longValue(),\n\t\t\t\t\t\t\tlowerProducer,\n\t\t\t\t\t\t\tupperProducer,\n\t\t\t\t\t\t\tprefixLength);\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tBigInteger value = section.getValue();\n\t\t\tif(value.compareTo(LONG_MAX) <= 0) {\n\t\t\t\treturn add(lowerProducer.get(), value.longValue(), increment, addrCreator, prefixLength);\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"private InputStream prepareInputStream(InputStream stream) throws IOException\n {\n InputStream result;\n BufferedInputStream bis = new BufferedInputStream(stream);\n readHeaderProperties(bis);\n if (isCompressed())\n {\n result = new InflaterInputStream(bis);\n }\n else\n {\n result = bis;\n }\n return result;\n }"
] |
Processes the template for the object cache of the current class definition.
@param template The template
@param attributes The attributes of the tag
@exception XDocletException if an error occurs
@doc.tag type="block" | [
"public void forObjectCache(String template, Properties attributes) throws XDocletException\r\n {\r\n _curObjectCacheDef = _curClassDef.getObjectCache();\r\n if (_curObjectCacheDef != null)\r\n {\r\n generate(template);\r\n _curObjectCacheDef = null;\r\n }\r\n }"
] | [
"InputStream openContentStream(final ContentItem item) throws IOException {\n final File file = getFile(item);\n if (file == null) {\n throw new IllegalStateException();\n }\n return new FileInputStream(file);\n }",
"private float max(float x, float y, float z) {\n if (x > y) {\n // not y\n if (x > z) {\n return x;\n }\n else {\n return z;\n }\n }\n else {\n // not x\n if (y > z) {\n return y;\n }\n else {\n return z;\n }\n }\n }",
"void unbind(String key)\r\n {\r\n NamedEntry entry = new NamedEntry(key, null, false);\r\n localUnbind(key);\r\n addForDeletion(entry);\r\n }",
"private ResourceAssignment getExistingResourceAssignment(Resource resource)\n {\n ResourceAssignment assignment = null;\n Integer resourceUniqueID = null;\n\n if (resource != null)\n {\n Iterator<ResourceAssignment> iter = m_assignments.iterator();\n resourceUniqueID = resource.getUniqueID();\n\n while (iter.hasNext() == true)\n {\n assignment = iter.next();\n Integer uniqueID = assignment.getResourceUniqueID();\n if (uniqueID != null && uniqueID.equals(resourceUniqueID) == true)\n {\n break;\n }\n assignment = null;\n }\n }\n\n return assignment;\n }",
"public static boolean isInverse(DMatrixRMaj a , DMatrixRMaj b , double tol ) {\n if( a.numRows != b.numRows || a.numCols != b.numCols ) {\n return false;\n }\n\n int numRows = a.numRows;\n int numCols = a.numCols;\n\n for( int i = 0; i < numRows; i++ ) {\n for( int j = 0; j < numCols; j++ ) {\n double total = 0;\n for( int k = 0; k < numCols; k++ ) {\n total += a.get(i,k)*b.get(k,j);\n }\n\n if( i == j ) {\n if( !(Math.abs(total-1) <= tol) )\n return false;\n } else if( !(Math.abs(total) <= tol) )\n return false;\n }\n }\n\n return true;\n }",
"private ColumnDef addColumnFor(FieldDescriptorDef fieldDef, TableDef tableDef)\r\n {\r\n String name = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN);\r\n ColumnDef columnDef = tableDef.getColumn(name);\r\n\r\n if (columnDef == null)\r\n {\r\n columnDef = new ColumnDef(name);\r\n tableDef.addColumn(columnDef);\r\n }\r\n if (!fieldDef.isNested())\r\n { \r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_JAVANAME, fieldDef.getName());\r\n }\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_TYPE, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_JDBC_TYPE));\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_ID, fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ID));\r\n if (fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_PRIMARYKEY, false))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_PRIMARYKEY, \"true\");\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_REQUIRED, \"true\");\r\n }\r\n else if (!fieldDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_NULLABLE, true))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_REQUIRED, \"true\");\r\n }\r\n if (\"database\".equals(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_AUTOINCREMENT)))\r\n {\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_AUTOINCREMENT, \"true\");\r\n }\r\n columnDef.setProperty(PropertyHelper.TORQUE_PROPERTY_SIZE, fieldDef.getSizeConstraint());\r\n if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION))\r\n {\r\n columnDef.setProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION,\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_DOCUMENTATION));\r\n }\r\n if (fieldDef.hasProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION))\r\n {\r\n columnDef.setProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION,\r\n fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN_DOCUMENTATION));\r\n }\r\n return columnDef;\r\n }",
"public Slice newSlice(long address, int size, Object reference)\n {\n if (address <= 0) {\n throw new IllegalArgumentException(\"Invalid address: \" + address);\n }\n if (reference == null) {\n throw new NullPointerException(\"Object reference is null\");\n }\n if (size == 0) {\n return Slices.EMPTY_SLICE;\n }\n return new Slice(null, address, size, size, reference);\n }",
"public List<GVRAtlasInformation> getAtlasInformation()\n {\n if ((mImage != null) && (mImage instanceof GVRImageAtlas))\n {\n return ((GVRImageAtlas) mImage).getAtlasInformation();\n }\n return null;\n }",
"public void writeFinalResults() {\n\t\tprintStatus();\n\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(\"gender-ratios.csv\"))) {\n\n\t\t\tout.print(\"Site key,pages total,pages on humans,pages on humans with gender\");\n\t\t\tfor (EntityIdValue gender : this.genderNamesList) {\n\t\t\t\tout.print(\",\" + this.genderNames.get(gender) + \" (\"\n\t\t\t\t\t\t+ gender.getId() + \")\");\n\t\t\t}\n\t\t\tout.println();\n\n\t\t\tList<SiteRecord> siteRecords = new ArrayList<>(\n\t\t\t\t\tthis.siteRecords.values());\n\t\t\tCollections.sort(siteRecords, new SiteRecordComparator());\n\t\t\tfor (SiteRecord siteRecord : siteRecords) {\n\t\t\t\tout.print(siteRecord.siteKey + \",\" + siteRecord.pageCount + \",\"\n\t\t\t\t\t\t+ siteRecord.humanPageCount + \",\"\n\t\t\t\t\t\t+ siteRecord.humanGenderPageCount);\n\n\t\t\t\tfor (EntityIdValue gender : this.genderNamesList) {\n\t\t\t\t\tif (siteRecord.genderCounts.containsKey(gender)) {\n\t\t\t\t\t\tout.print(\",\" + siteRecord.genderCounts.get(gender));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tout.print(\",0\");\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tout.println();\n\t\t\t}\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}"
] |
Search for interesting photos using the Flickr Interestingness algorithm.
@param params
Any search parameters
@param perPage
Number of items per page
@param page
The page to start on
@return A PhotoList
@throws FlickrException | [
"public PhotoList<Photo> searchInterestingness(SearchParameters params, int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_INTERESTINGNESS);\r\n\r\n parameters.putAll(params.getAsParameters());\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", Integer.toString(perPage));\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", Integer.toString(page));\r\n }\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n photos.setPage(photosElement.getAttribute(\"page\"));\r\n photos.setPages(photosElement.getAttribute(\"pages\"));\r\n photos.setPerPage(photosElement.getAttribute(\"perpage\"));\r\n photos.setTotal(photosElement.getAttribute(\"total\"));\r\n\r\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n Photo photo = new Photo();\r\n photo.setId(photoElement.getAttribute(\"id\"));\r\n\r\n User owner = new User();\r\n owner.setId(photoElement.getAttribute(\"owner\"));\r\n photo.setOwner(owner);\r\n\r\n photo.setSecret(photoElement.getAttribute(\"secret\"));\r\n photo.setServer(photoElement.getAttribute(\"server\"));\r\n photo.setFarm(photoElement.getAttribute(\"farm\"));\r\n photo.setTitle(photoElement.getAttribute(\"title\"));\r\n photo.setPublicFlag(\"1\".equals(photoElement.getAttribute(\"ispublic\")));\r\n photo.setFriendFlag(\"1\".equals(photoElement.getAttribute(\"isfriend\")));\r\n photo.setFamilyFlag(\"1\".equals(photoElement.getAttribute(\"isfamily\")));\r\n photos.add(photo);\r\n }\r\n return photos;\r\n }"
] | [
"private JSONArray toJsonStringArray(Collection<? extends Object> collection) {\n\n if (null != collection) {\n JSONArray array = new JSONArray();\n for (Object o : collection) {\n array.put(\"\" + o);\n }\n return array;\n } else {\n return null;\n }\n }",
"public static boolean isKeyUsed(final Jedis jedis, final String key) {\n return !NONE.equalsIgnoreCase(jedis.type(key));\n }",
"public static base_responses unlink(nitro_service client, sslcertkey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslcertkey unlinkresources[] = new sslcertkey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tunlinkresources[i] = new sslcertkey();\n\t\t\t\tunlinkresources[i].certkey = resources[i].certkey;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, unlinkresources,\"unlink\");\n\t\t}\n\t\treturn result;\n\t}",
"public static base_responses add(nitro_service client, dnssuffix resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnssuffix addresources[] = new dnssuffix[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnssuffix();\n\t\t\t\taddresources[i].Dnssuffix = resources[i].Dnssuffix;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static AbstractBuild<?, ?> getRootBuild(AbstractBuild<?, ?> currentBuild) {\n AbstractBuild<?, ?> rootBuild = null;\n AbstractBuild<?, ?> parentBuild = getUpstreamBuild(currentBuild);\n while (parentBuild != null) {\n if (isPassIdentifiedDownstream(parentBuild)) {\n rootBuild = parentBuild;\n }\n parentBuild = getUpstreamBuild(parentBuild);\n }\n if (rootBuild == null && isPassIdentifiedDownstream(currentBuild)) {\n return currentBuild;\n }\n return rootBuild;\n }",
"public static nslimitidentifier_binding get(nitro_service service, String limitidentifier) throws Exception{\n\t\tnslimitidentifier_binding obj = new nslimitidentifier_binding();\n\t\tobj.set_limitidentifier(limitidentifier);\n\t\tnslimitidentifier_binding response = (nslimitidentifier_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"private void writeCalendarHours(ProjectCalendar parentCalendar, ProjectCalendarHours record) throws IOException\n {\n m_buffer.setLength(0);\n\n int recordNumber;\n\n if (!parentCalendar.isDerived())\n {\n recordNumber = MPXConstants.BASE_CALENDAR_HOURS_RECORD_NUMBER;\n }\n else\n {\n recordNumber = MPXConstants.RESOURCE_CALENDAR_HOURS_RECORD_NUMBER;\n }\n\n DateRange range1 = record.getRange(0);\n if (range1 == null)\n {\n range1 = DateRange.EMPTY_RANGE;\n }\n\n DateRange range2 = record.getRange(1);\n if (range2 == null)\n {\n range2 = DateRange.EMPTY_RANGE;\n }\n\n DateRange range3 = record.getRange(2);\n if (range3 == null)\n {\n range3 = DateRange.EMPTY_RANGE;\n }\n\n m_buffer.append(recordNumber);\n m_buffer.append(m_delimiter);\n m_buffer.append(format(record.getDay()));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatTime(range1.getStart())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatTime(range1.getEnd())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatTime(range2.getStart())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatTime(range2.getEnd())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatTime(range3.getStart())));\n m_buffer.append(m_delimiter);\n m_buffer.append(format(formatTime(range3.getEnd())));\n stripTrailingDelimiters(m_buffer);\n m_buffer.append(MPXConstants.EOL);\n\n m_writer.write(m_buffer.toString());\n }",
"public List<NodeValue<K, V>> getRepairs(List<NodeValue<K, V>> nodeValues) {\n int size = nodeValues.size();\n if(size <= 1)\n return Collections.emptyList();\n\n Map<K, List<NodeValue<K, V>>> keyToNodeValues = Maps.newHashMap();\n for(NodeValue<K, V> nodeValue: nodeValues) {\n List<NodeValue<K, V>> keyNodeValues = keyToNodeValues.get(nodeValue.getKey());\n if(keyNodeValues == null) {\n keyNodeValues = Lists.newArrayListWithCapacity(5);\n keyToNodeValues.put(nodeValue.getKey(), keyNodeValues);\n }\n keyNodeValues.add(nodeValue);\n }\n\n List<NodeValue<K, V>> result = Lists.newArrayList();\n for(List<NodeValue<K, V>> keyNodeValues: keyToNodeValues.values())\n result.addAll(singleKeyGetRepairs(keyNodeValues));\n return result;\n }",
"public static appfwprofile_excluderescontenttype_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_excluderescontenttype_binding obj = new appfwprofile_excluderescontenttype_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_excluderescontenttype_binding response[] = (appfwprofile_excluderescontenttype_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Gets a color formatted as an integer with ARGB ordering.
@param json {@link JSONObject} to get the color from
@param elementName Name of the color element
@return An ARGB formatted integer
@throws JSONException | [
"public static int getJSONColor(final JSONObject json, String elementName) throws JSONException {\n Object raw = json.get(elementName);\n return convertJSONColor(raw);\n }"
] | [
"public static base_response unset(nitro_service client, inatparam resource, String[] args) throws Exception{\n\t\tinatparam unsetresource = new inatparam();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public static Node addPartitionToNode(final Node node, Integer donatedPartition) {\n return UpdateClusterUtils.addPartitionsToNode(node, Sets.newHashSet(donatedPartition));\n }",
"private GeometryCoordinateSequenceTransformer getTransformer() {\n\t\tif (unitToPixel == null) {\n\t\t\tunitToPixel = new GeometryCoordinateSequenceTransformer();\n\t\t\tunitToPixel.setMathTransform(ProjectiveTransform.create(new AffineTransform(scale, 0, 0, -scale, -scale\n\t\t\t\t\t* panOrigin.x, scale * panOrigin.y)));\n\t\t}\n\t\treturn unitToPixel;\n\t}",
"public static <E> Collection<E> sampleWithReplacement(Collection<E> c, int n) {\r\n return sampleWithReplacement(c, n, new Random());\r\n }",
"public void sendEventsFromQueue() {\n if (null == queue || stopSending) {\n return;\n }\n LOG.fine(\"Scheduler called for sending events\");\n\n int packageSize = getEventsPerMessageCall();\n\n while (!queue.isEmpty()) {\n final List<Event> list = new ArrayList<Event>();\n int i = 0;\n while (i < packageSize && !queue.isEmpty()) {\n Event event = queue.remove();\n if (event != null && !filter(event)) {\n list.add(event);\n i++;\n }\n }\n if (list.size() > 0) {\n executor.execute(new Runnable() {\n public void run() {\n try {\n sendEvents(list);\n } catch (MonitoringException e) {\n e.logException(Level.SEVERE);\n }\n }\n });\n\n }\n }\n\n }",
"public QueryBuilder<T, ID> orderBy(String columnName, boolean ascending) {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new IllegalArgumentException(\"Can't orderBy foreign collection field: \" + columnName);\n\t\t}\n\t\taddOrderBy(new OrderBy(columnName, ascending));\n\t\treturn this;\n\t}",
"private ModelNode parseAddress(final String profileName, final String inputAddress) {\n final ModelNode result = new ModelNode();\n if (profileName != null) {\n result.add(ServerOperations.PROFILE, profileName);\n }\n String[] parts = inputAddress.split(\",\");\n for (String part : parts) {\n String[] address = part.split(\"=\");\n if (address.length != 2) {\n throw new RuntimeException(part + \" is not a valid address segment\");\n }\n result.add(address[0], address[1]);\n }\n return result;\n }",
"public BsonDocument toUpdateDocument() {\n final List<BsonElement> unsets = new ArrayList<>();\n for (final String removedField : this.removedFields) {\n unsets.add(new BsonElement(removedField, new BsonBoolean(true)));\n }\n final BsonDocument updateDocument = new BsonDocument();\n\n if (this.updatedFields.size() > 0) {\n updateDocument.append(\"$set\", this.updatedFields);\n }\n\n if (unsets.size() > 0) {\n updateDocument.append(\"$unset\", new BsonDocument(unsets));\n }\n\n return updateDocument;\n }",
"private void addSuperClasses(Integer directSuperClass,\n\t\t\tClassRecord subClassRecord) {\n\t\tif (subClassRecord.superClasses.contains(directSuperClass)) {\n\t\t\treturn;\n\t\t}\n\t\tsubClassRecord.superClasses.add(directSuperClass);\n\t\tClassRecord superClassRecord = getClassRecord(directSuperClass);\n\t\tif (superClassRecord == null) {\n\t\t\treturn;\n\t\t}\n\n\t\tfor (Integer superClass : superClassRecord.directSuperClasses) {\n\t\t\taddSuperClasses(superClass, subClassRecord);\n\t\t}\n\t}"
] |
Use this API to delete sslfipskey resources of given names. | [
"public static base_responses delete(nitro_service client, String fipskeyname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (fipskeyname != null && fipskeyname.length > 0) {\n\t\t\tsslfipskey deleteresources[] = new sslfipskey[fipskeyname.length];\n\t\t\tfor (int i=0;i<fipskeyname.length;i++){\n\t\t\t\tdeleteresources[i] = new sslfipskey();\n\t\t\t\tdeleteresources[i].fipskeyname = fipskeyname[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}"
] | [
"private static TransportType map2TransportType(String transportId) {\n TransportType type;\n if (CXF_HTTP_TRANSPORT_ID.equals(transportId) || SOAP_HTTP_TRANSPORT_ID.equals(transportId)) {\n type = TransportType.HTTP;\n } else {\n type = TransportType.OTHER;\n }\n return type;\n }",
"public Flags flagList(ImapRequestLineReader request) throws ProtocolException {\n Flags flags = new Flags();\n request.nextWordChar();\n consumeChar(request, '(');\n CharacterValidator validator = new NoopCharValidator();\n String nextWord = consumeWord(request, validator);\n while (!nextWord.endsWith(\")\")) {\n setFlag(nextWord, flags);\n nextWord = consumeWord(request, validator);\n }\n // Got the closing \")\", may be attached to a word.\n if (nextWord.length() > 1) {\n setFlag(nextWord.substring(0, nextWord.length() - 1), flags);\n }\n\n return flags;\n }",
"public void printAnswers(List<CoreLabel> doc, PrintWriter out) {\r\n // boolean tagsMerged = flags.mergeTags;\r\n // boolean useHead = flags.splitOnHead;\r\n\r\n if ( ! \"iob1\".equalsIgnoreCase(flags.entitySubclassification)) {\r\n deEndify(doc);\r\n }\r\n\r\n for (CoreLabel fl : doc) {\r\n String word = fl.word();\r\n if (word == BOUNDARY) { // Using == is okay, because it is set to constant\r\n out.println();\r\n } else {\r\n String gold = fl.get(OriginalAnswerAnnotation.class);\r\n if(gold == null) gold = \"\";\r\n String guess = fl.get(AnswerAnnotation.class);\r\n // System.err.println(fl.word() + \"\\t\" + fl.get(AnswerAnnotation.class) + \"\\t\" + fl.get(AnswerAnnotation.class));\r\n String pos = fl.tag();\r\n String chunk = (fl.get(ChunkAnnotation.class) == null ? \"\" : fl.get(ChunkAnnotation.class));\r\n out.println(fl.word() + '\\t' + pos + '\\t' + chunk + '\\t' +\r\n gold + '\\t' + guess);\r\n }\r\n }\r\n }",
"public static Document readDocumentFromString(String s) throws Exception {\r\n InputSource in = new InputSource(new StringReader(s));\r\n DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();\r\n factory.setNamespaceAware(false);\r\n return factory.newDocumentBuilder().parse(in);\r\n }",
"@Api\n\tpublic static void configureNoCaching(HttpServletResponse response) {\n\t\t// HTTP 1.0 header:\n\t\tresponse.setHeader(HTTP_EXPIRES_HEADER, HTTP_EXPIRES_HEADER_NOCACHE_VALUE);\n\t\tresponse.setHeader(HTTP_CACHE_PRAGMA, HTTP_CACHE_PRAGMA_VALUE);\n\n\t\t// HTTP 1.1 header:\n\t\tresponse.setHeader(HTTP_CACHE_CONTROL_HEADER, HTTP_CACHE_CONTROL_HEADER_NOCACHE_VALUE);\n\t}",
"@Override\n public synchronized void resume() {\n this.paused = false;\n ServerActivityCallback listener = listenerUpdater.get(this);\n if (listener != null) {\n listenerUpdater.compareAndSet(this, listener, null);\n }\n while (!taskQueue.isEmpty() && (activeRequestCount < maxRequestCount || maxRequestCount < 0)) {\n runQueuedTask(false);\n }\n }",
"public static String defaultString(final String str, final String fallback) {\n return isNullOrEmpty(str) ? fallback : str;\n }",
"public String getUuidFromResponse(ResponseOnSingeRequest myResponse) {\n\n String uuid = PcConstants.NA;\n String responseBody = myResponse.getResponseBody();\n Pattern regex = Pattern.compile(getJobIdRegex());\n Matcher matcher = regex.matcher(responseBody);\n if (matcher.matches()) {\n uuid = matcher.group(1);\n }\n\n return uuid;\n }",
"public static base_responses add(nitro_service client, dnstxtrec resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdnstxtrec addresources[] = new dnstxtrec[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dnstxtrec();\n\t\t\t\taddresources[i].domain = resources[i].domain;\n\t\t\t\taddresources[i].String = resources[i].String;\n\t\t\t\taddresources[i].ttl = resources[i].ttl;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}"
] |
Created a fresh CancelIndicator | [
"public CancelIndicator newCancelIndicator(final ResourceSet rs) {\n CancelIndicator _xifexpression = null;\n if ((rs instanceof XtextResourceSet)) {\n final boolean cancelationAllowed = (this.cancelationAllowed.get()).booleanValue();\n final int current = ((XtextResourceSet)rs).getModificationStamp();\n final CancelIndicator _function = () -> {\n return (cancelationAllowed && (((XtextResourceSet)rs).isOutdated() || (current != ((XtextResourceSet)rs).getModificationStamp())));\n };\n return _function;\n } else {\n _xifexpression = CancelIndicator.NullImpl;\n }\n return _xifexpression;\n }"
] | [
"protected void parseSequencesWithColons(TokenList tokens , Sequence sequence ) {\n\n TokenList.Token t = tokens.getFirst();\n if( t == null )\n return;\n\n int state = 0;\n\n TokenList.Token start = null;\n TokenList.Token middle = null;\n TokenList.Token prev = t;\n\n boolean last = false;\n while( true ) {\n if( state == 0 ) {\n if( isVariableInteger(t) && (t.next != null && t.next.getSymbol() == Symbol.COLON) ) {\n start = t;\n state = 1;\n t = t.next;\n } else if( t != null && t.getSymbol() == Symbol.COLON ) {\n // If it starts with a colon then it must be 'all' or a type-o\n IntegerSequence range = new IntegerSequence.Range(null,null);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(range);\n TokenList.Token n = new TokenList.Token(varSequence);\n tokens.insert(t.previous, n);\n tokens.remove(t);\n t = n;\n }\n } else if( state == 1 ) {\n // var : ?\n if (isVariableInteger(t)) {\n state = 2;\n } else {\n // array range\n IntegerSequence range = new IntegerSequence.Range(start,null);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(range);\n replaceSequence(tokens, varSequence, start, prev);\n state = 0;\n }\n } else if ( state == 2 ) {\n // var:var ?\n if( t != null && t.getSymbol() == Symbol.COLON ) {\n middle = prev;\n state = 3;\n } else {\n // create for sequence with start and stop elements only\n IntegerSequence numbers = new IntegerSequence.For(start,null,prev);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(numbers);\n replaceSequence(tokens, varSequence, start, prev );\n if( t != null )\n t = t.previous;\n state = 0;\n }\n } else if ( state == 3 ) {\n // var:var: ?\n if( isVariableInteger(t) ) {\n // create 'for' sequence with three variables\n IntegerSequence numbers = new IntegerSequence.For(start,middle,t);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(numbers);\n t = replaceSequence(tokens, varSequence, start, t);\n } else {\n // array range with 2 elements\n IntegerSequence numbers = new IntegerSequence.Range(start,middle);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(numbers);\n replaceSequence(tokens, varSequence, start, prev);\n }\n state = 0;\n }\n\n if( last ) {\n break;\n } else if( t.next == null ) {\n // handle the case where it is the last token in the sequence\n last = true;\n }\n prev = t;\n t = t.next;\n }\n }",
"protected DateTimeException _peelDTE(DateTimeException e) {\n while (true) {\n Throwable t = e.getCause();\n if (t != null && t instanceof DateTimeException) {\n e = (DateTimeException) t;\n continue;\n }\n break;\n }\n return e;\n }",
"public int getTrailingBitCount(boolean network) {\n\t\tint count = getDivisionCount();\n\t\tif(count == 0) {\n\t\t\treturn 0;\n\t\t}\n\t\tlong back = network ? 0 : getDivision(0).getMaxValue();\n\t\tint bitLen = 0;\n\t\tfor(int i = count - 1; i >= 0; i--) {\n\t\t\tIPAddressDivision seg = getDivision(i);\n\t\t\tlong value = seg.getDivisionValue();\n\t\t\tif(value != back) {\n\t\t\t\treturn bitLen + seg.getTrailingBitCount(network);\n\t\t\t}\n\t\t\tbitLen += seg.getBitCount();\n\t\t}\n\t\treturn bitLen;\n\t}",
"@Override\n\tpublic void writeValue(TimeValue value, Resource resource)\n\t\t\tthrows RDFHandlerException {\n\t\tthis.rdfWriter.writeTripleValueObject(resource, RdfWriter.RDF_TYPE,\n\t\t\t\tRdfWriter.WB_TIME_VALUE);\n\n\t\tthis.rdfWriter.writeTripleValueObject(resource, RdfWriter.WB_TIME,\n\t\t\t\tTimeValueConverter.getTimeLiteral(value, this.rdfWriter));\n\n\t\tthis.rdfWriter.writeTripleIntegerObject(resource,\n\t\t\t\tRdfWriter.WB_TIME_PRECISION, value.getPrecision());\n\t\tthis.rdfWriter.writeTripleIntegerObject(resource,\n\t\t\t\tRdfWriter.WB_TIME_TIMEZONE,\n\t\t\t\tvalue.getTimezoneOffset());\n\t\tthis.rdfWriter.writeTripleUriObject(resource,\n\t\t\t\tRdfWriter.WB_TIME_CALENDAR_MODEL,\n\t\t\t\tvalue.getPreferredCalendarModel());\n\t}",
"public JSONObject toJSON() {\n try {\n return new JSONObject(properties).putOpt(\"name\", getName());\n } catch (JSONException e) {\n e.printStackTrace();\n Log.e(TAG, e, \"toJSON()\");\n throw new RuntimeAssertion(\"NodeEntry.toJSON() failed for '%s'\", this);\n }\n }",
"void sign(byte[] data, int offset, int length,\n ServerMessageBlock request, ServerMessageBlock response) {\n request.signSeq = signSequence;\n if( response != null ) {\n response.signSeq = signSequence + 1;\n response.verifyFailed = false;\n }\n\n try {\n update(macSigningKey, 0, macSigningKey.length);\n int index = offset + ServerMessageBlock.SIGNATURE_OFFSET;\n for (int i = 0; i < 8; i++) data[index + i] = 0;\n ServerMessageBlock.writeInt4(signSequence, data, index);\n update(data, offset, length);\n System.arraycopy(digest(), 0, data, index, 8);\n if (bypass) {\n bypass = false;\n System.arraycopy(\"BSRSPYL \".getBytes(), 0, data, index, 8);\n }\n } catch (Exception ex) {\n if( log.level > 0 )\n ex.printStackTrace( log );\n } finally {\n signSequence += 2;\n }\n }",
"public static byte[] decodeBase64(String value) {\n int byteShift = 4;\n int tmp = 0;\n boolean done = false;\n final StringBuilder buffer = new StringBuilder();\n\n for (int i = 0; i != value.length(); i++) {\n final char c = value.charAt(i);\n final int sixBit = (c < 123) ? EncodingGroovyMethodsSupport.TRANSLATE_TABLE[c] : 66;\n\n if (sixBit < 64) {\n if (done)\n throw new RuntimeException(\"= character not at end of base64 value\"); // TODO: change this exception type\n\n tmp = (tmp << 6) | sixBit;\n\n if (byteShift-- != 4) {\n buffer.append((char) ((tmp >> (byteShift * 2)) & 0XFF));\n }\n\n } else if (sixBit == 64) {\n\n byteShift--;\n done = true;\n\n } else if (sixBit == 66) {\n // RFC 2045 says that I'm allowed to take the presence of\n // these characters as evidence of data corruption\n // So I will\n throw new RuntimeException(\"bad character in base64 value\"); // TODO: change this exception type\n }\n\n if (byteShift == 0) byteShift = 4;\n }\n\n try {\n return buffer.toString().getBytes(\"ISO-8859-1\");\n } catch (UnsupportedEncodingException e) {\n throw new RuntimeException(\"Base 64 decode produced byte values > 255\"); // TODO: change this exception type\n }\n }",
"private JarFile loadJar(File archive) throws DecompilationException\n {\n try\n {\n return new JarFile(archive);\n }\n catch (IOException ex)\n {\n throw new DecompilationException(\"Can't load .jar: \" + archive.getPath(), ex);\n }\n }",
"public static Identifiers convertProfileAndPathIdentifier(String profileIdentifier, String pathIdentifier) throws Exception {\n Identifiers id = new Identifiers();\n\n Integer profileId = null;\n try {\n profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n } catch (Exception e) {\n // this is OK for this since it isn't always needed\n }\n Integer pathId = convertPathIdentifier(pathIdentifier, profileId);\n\n id.setProfileId(profileId);\n id.setPathId(pathId);\n\n return id;\n }"
] |
Checks if a parameter exists. If it exists, it is updated. If it doesn't, it is created. Only works for parameters which key is
unique. Will create a transaction on the given entity manager. | [
"static void setSingleParam(String key, String value, DbConn cnx)\n {\n QueryResult r = cnx.runUpdate(\"globalprm_update_value_by_key\", value, key);\n if (r.nbUpdated == 0)\n {\n cnx.runUpdate(\"globalprm_insert\", key, value);\n }\n cnx.commit();\n }"
] | [
"public ServerGroup addServerGroup(String groupName) {\n ServerGroup group = new ServerGroup();\n\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"name\", groupName),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n try {\n JSONObject response = new JSONObject(doPost(BASE_SERVERGROUP, params));\n group = getServerGroupFromJSON(response);\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return group;\n }",
"public InetSocketAddress getMulticastSocketAddress() {\n if (multicastAddress == null) {\n throw MESSAGES.noMulticastBinding(name);\n }\n return new InetSocketAddress(multicastAddress, multicastPort);\n }",
"@SuppressWarnings(\"unchecked\")\n public Map<BsonValue, ChangeEvent<BsonDocument>> getEvents() {\n nsLock.readLock().lock();\n final Map<BsonValue, ChangeEvent<BsonDocument>> events;\n try {\n events = new HashMap<>(this.events);\n } finally {\n nsLock.readLock().unlock();\n }\n\n nsLock.writeLock().lock();\n try {\n this.events.clear();\n return events;\n } finally {\n nsLock.writeLock().unlock();\n }\n }",
"private List<Variable> parseAssignRange(Sequence sequence, TokenList tokens, TokenList.Token t0) {\n // find assignment symbol\n TokenList.Token tokenAssign = t0.next;\n while( tokenAssign != null && tokenAssign.symbol != Symbol.ASSIGN ) {\n tokenAssign = tokenAssign.next;\n }\n\n if( tokenAssign == null )\n throw new ParseError(\"Can't find assignment operator\");\n\n // see if it is a sub matrix before\n if( tokenAssign.previous.symbol == Symbol.PAREN_RIGHT ) {\n TokenList.Token start = t0.next;\n if( start.symbol != Symbol.PAREN_LEFT )\n throw new ParseError((\"Expected left param for assignment\"));\n TokenList.Token end = tokenAssign.previous;\n TokenList subTokens = tokens.extractSubList(start,end);\n subTokens.remove(subTokens.getFirst());\n subTokens.remove(subTokens.getLast());\n\n handleParentheses(subTokens,sequence);\n\n List<TokenList.Token> inputs = parseParameterCommaBlock(subTokens, sequence);\n\n if (inputs.isEmpty())\n throw new ParseError(\"Empty function input parameters\");\n\n List<Variable> range = new ArrayList<>();\n addSubMatrixVariables(inputs, range);\n if( range.size() != 1 && range.size() != 2 ) {\n throw new ParseError(\"Unexpected number of range variables. 1 or 2 expected\");\n }\n return range;\n }\n\n return null;\n }",
"public void setIntegerAttribute(String name, Integer value) {\n\t\tensureValue();\n\t\tAttribute attribute = new IntegerAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetValue().getAllAttributes().put(name, attribute);\n\t}",
"public TaskMode getTaskMode()\n {\n return BooleanHelper.getBoolean((Boolean) getCachedValue(TaskField.TASK_MODE)) ? TaskMode.MANUALLY_SCHEDULED : TaskMode.AUTO_SCHEDULED;\n }",
"protected static void invalidateSwitchPoints() {\n if (LOG_ENABLED) {\n LOG.info(\"invalidating switch point\");\n }\n \tSwitchPoint old = switchPoint;\n switchPoint = new SwitchPoint();\n synchronized(IndyInterface.class) { SwitchPoint.invalidateAll(new SwitchPoint[]{old}); }\n }",
"@TargetApi(VERSION_CODES.KITKAT)\n public static void showSystemUI(Activity activity) {\n View decorView = activity.getWindow().getDecorView();\n decorView.setSystemUiVisibility(\n View.SYSTEM_UI_FLAG_LAYOUT_STABLE\n | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION\n | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN\n );\n }",
"private static void flushCurrentWord( StringBuilder currentWords, List<Word> formattedWords, boolean cutWhitespace ) {\n if( currentWords.length() > 0 ) {\n if( cutWhitespace && currentWords.charAt( currentWords.length() - 1 ) == ' ' ) {\n currentWords.setLength( currentWords.length() - 1 );\n }\n formattedWords.add( new Word( currentWords.toString() ) );\n currentWords.setLength( 0 );\n }\n }"
] |
Draw a rectangle's interior with this color.
@param rect rectangle
@param color colour | [
"public void fillRectangle(Rectangle rect, Color color) {\n\t\ttemplate.saveState();\n\t\tsetFill(color);\n\t\ttemplate.rectangle(origX + rect.getLeft(), origY + rect.getBottom(), rect.getWidth(), rect.getHeight());\n\t\ttemplate.fill();\n\t\ttemplate.restoreState();\n\t}"
] | [
"public static dnsaaaarec[] get(nitro_service service, dnsaaaarec_args args) throws Exception{\n\t\tdnsaaaarec obj = new dnsaaaarec();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tdnsaaaarec[] response = (dnsaaaarec[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"protected boolean isSecureLink(CmsObject cms, String vfsName, CmsSite targetSite, boolean secureRequest) {\n\n return OpenCms.getStaticExportManager().isSecureLink(cms, vfsName, targetSite.getSiteRoot(), secureRequest);\n }",
"public static void checkStringNotNullOrEmpty(String parameterName,\n String value) {\n if (TextUtils.isEmpty(value)) {\n throw Exceptions.IllegalArgument(\"Current input string %s is %s.\",\n parameterName, value == null ? \"null\" : \"empty\");\n }\n }",
"public void collectVariables(EnvVars env, Run build, TaskListener listener) {\n EnvVars buildParameters = Utils.extractBuildParameters(build, listener);\n if (buildParameters != null) {\n env.putAll(buildParameters);\n }\n addAllWithFilter(envVars, env, filter.getPatternFilter());\n Map<String, String> sysEnv = new HashMap<>();\n Properties systemProperties = System.getProperties();\n Enumeration<?> enumeration = systemProperties.propertyNames();\n while (enumeration.hasMoreElements()) {\n String propertyKey = (String) enumeration.nextElement();\n sysEnv.put(propertyKey, systemProperties.getProperty(propertyKey));\n }\n addAllWithFilter(sysVars, sysEnv, filter.getPatternFilter());\n }",
"public Permissions getPerms(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PERMS);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transport.get(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element permissionsElement = response.getPayload();\r\n Permissions permissions = new Permissions();\r\n permissions.setId(permissionsElement.getAttribute(\"id\"));\r\n permissions.setPublicFlag(\"1\".equals(permissionsElement.getAttribute(\"ispublic\")));\r\n permissions.setFamilyFlag(\"1\".equals(permissionsElement.getAttribute(\"isfamily\")));\r\n permissions.setFriendFlag(\"1\".equals(permissionsElement.getAttribute(\"isfriend\")));\r\n permissions.setComment(permissionsElement.getAttribute(\"permcomment\"));\r\n permissions.setAddmeta(permissionsElement.getAttribute(\"permaddmeta\"));\r\n return permissions;\r\n }",
"public void deleteInactiveContent() throws PatchingException {\n List<File> dirs = getInactiveHistory();\n if (!dirs.isEmpty()) {\n for (File dir : dirs) {\n deleteDir(dir, ALL);\n }\n }\n dirs = getInactiveOverlays();\n if (!dirs.isEmpty()) {\n for (File dir : dirs) {\n deleteDir(dir, ALL);\n }\n }\n }",
"public int clear()\n {\n int n = 0;\n for (GVRCursorController c : controllers)\n {\n c.stopDrag();\n removeCursorController(c);\n ++n;\n }\n return n;\n }",
"public boolean hasRequiredClientProps() {\n boolean valid = true;\n valid &= verifyStringPropSet(CONNECTION_APPLICATION_NAME_PROP, CLIENT_APPLICATION_NAME_PROP);\n valid &= verifyStringPropSet(ACCUMULO_USER_PROP, CLIENT_ACCUMULO_USER_PROP);\n valid &= verifyStringPropSet(ACCUMULO_PASSWORD_PROP, CLIENT_ACCUMULO_PASSWORD_PROP);\n valid &= verifyStringPropSet(ACCUMULO_INSTANCE_PROP, CLIENT_ACCUMULO_INSTANCE_PROP);\n return valid;\n }",
"public static base_response update(nitro_service client, snmpmanager resource) throws Exception {\n\t\tsnmpmanager updateresource = new snmpmanager();\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.netmask = resource.netmask;\n\t\tupdateresource.domainresolveretry = resource.domainresolveretry;\n\t\treturn updateresource.update_resource(client);\n\t}"
] |
Removes file from your assembly.
@param name field name of the file to remove. | [
"public void removeFile(String name) {\n if(files.containsKey(name)) {\n files.remove(name);\n }\n\n if(fileStreams.containsKey(name)) {\n fileStreams.remove(name);\n }\n }"
] | [
"private static JSONArray parseOutgoings(ArrayList<Shape> outgoings) throws JSONException {\n if (outgoings != null) {\n JSONArray outgoingsArray = new JSONArray();\n\n for (Shape outgoing : outgoings) {\n JSONObject outgoingObject = new JSONObject();\n\n outgoingObject.put(\"resourceId\",\n outgoing.getResourceId().toString());\n outgoingsArray.put(outgoingObject);\n }\n\n return outgoingsArray;\n }\n\n return new JSONArray();\n }",
"private Double getDuration(Duration duration)\n {\n Double result;\n if (duration == null)\n {\n result = null;\n }\n else\n {\n if (duration.getUnits() != TimeUnit.HOURS)\n {\n duration = duration.convertUnits(TimeUnit.HOURS, m_projectFile.getProjectProperties());\n }\n\n result = Double.valueOf(duration.getDuration());\n }\n return result;\n }",
"@SuppressWarnings(\"deprecation\")\n public BUILDER addAccessConstraint(final AccessConstraintDefinition accessConstraint) {\n if (accessConstraints == null) {\n accessConstraints = new AccessConstraintDefinition[] {accessConstraint};\n } else {\n accessConstraints = Arrays.copyOf(accessConstraints, accessConstraints.length + 1);\n accessConstraints[accessConstraints.length - 1] = accessConstraint;\n }\n return (BUILDER) this;\n }",
"protected boolean hasTimeStampHeader() {\n String originTime = request.getHeader(RestMessageHeaders.X_VOLD_REQUEST_ORIGIN_TIME_MS);\n boolean result = false;\n if(originTime != null) {\n try {\n // TODO: remove the originTime field from request header,\n // because coordinator should not accept the request origin time\n // from the client.. In this commit, we only changed\n // \"this.parsedRequestOriginTimeInMs\" from\n // \"Long.parseLong(originTime)\" to current system time,\n // The reason that we did not remove the field from request\n // header right now, is because this commit is a quick fix for\n // internal performance test to be available as soon as\n // possible.\n\n this.parsedRequestOriginTimeInMs = System.currentTimeMillis();\n if(this.parsedRequestOriginTimeInMs < 0) {\n RestErrorHandler.writeErrorResponse(messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Origin time cannot be negative \");\n\n } else {\n result = true;\n }\n } catch(NumberFormatException nfe) {\n logger.error(\"Exception when validating request. Incorrect origin time parameter. Cannot parse this to long: \"\n + originTime,\n nfe);\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Incorrect origin time parameter. Cannot parse this to long: \"\n + originTime);\n }\n } else {\n logger.error(\"Error when validating request. Missing origin time parameter.\");\n RestErrorHandler.writeErrorResponse(this.messageEvent,\n HttpResponseStatus.BAD_REQUEST,\n \"Missing origin time parameter.\");\n }\n return result;\n }",
"public void cullHistory(final int profileId, final String clientUUID, final int limit) throws Exception {\n\n //Allow only 1 delete thread to run\n if (threadActive) {\n return;\n }\n\n threadActive = true;\n //Create a thread so proxy will continue to work during long delete\n Thread t1 = new Thread(new Runnable() {\n @Override\n public void run() {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String sqlQuery = \"SELECT COUNT(\" + Constants.GENERIC_ID + \") FROM \" + Constants.DB_TABLE_HISTORY + \" \";\n\n // see if profileId is set or not (-1)\n if (profileId != -1) {\n sqlQuery += \"WHERE \" + Constants.GENERIC_PROFILE_ID + \"=\" + profileId + \" \";\n }\n\n if (clientUUID != null && clientUUID.compareTo(\"\") != 0) {\n sqlQuery += \"AND \" + Constants.GENERIC_CLIENT_UUID + \"='\" + clientUUID + \"' \";\n }\n sqlQuery += \";\";\n\n Statement query = sqlConnection.createStatement();\n ResultSet results = query.executeQuery(sqlQuery);\n if (results.next()) {\n if (results.getInt(\"COUNT(\" + Constants.GENERIC_ID + \")\") < (limit + 10000)) {\n return;\n }\n }\n //Find the last item in the table\n statement = sqlConnection.prepareStatement(\"SELECT \" + Constants.GENERIC_ID + \" FROM \" + Constants.DB_TABLE_HISTORY +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = \\'\" + clientUUID + \"\\'\" +\n \" AND \" + Constants.CLIENT_PROFILE_ID + \" = \" + profileId +\n \" ORDER BY \" + Constants.GENERIC_ID + \" ASC LIMIT 1\");\n\n ResultSet resultSet = statement.executeQuery();\n if (resultSet.next()) {\n int currentSpot = resultSet.getInt(Constants.GENERIC_ID) + 100;\n int finalDelete = currentSpot + 10000;\n //Delete 100 items at a time until 10000 are deleted\n //Do this so table is unlocked frequently to allow other proxy items to access it\n while (currentSpot < finalDelete) {\n PreparedStatement deleteStatement = sqlConnection.prepareStatement(\"DELETE FROM \" + Constants.DB_TABLE_HISTORY +\n \" WHERE \" + Constants.CLIENT_CLIENT_UUID + \" = \\'\" + clientUUID + \"\\'\" +\n \" AND \" + Constants.CLIENT_PROFILE_ID + \" = \" + profileId +\n \" AND \" + Constants.GENERIC_ID + \" < \" + currentSpot);\n deleteStatement.executeUpdate();\n currentSpot += 100;\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n threadActive = false;\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }\n });\n\n t1.start();\n }",
"public void checkConnection() {\n long start = Time.currentTimeMillis();\n\n while (clientChannel == null) {\n\n tcpSocketConsumer.checkNotShutdown();\n\n if (start + timeoutMs > Time.currentTimeMillis())\n try {\n condition.await(1, TimeUnit.MILLISECONDS);\n\n } catch (InterruptedException e) {\n throw new IORuntimeException(\"Interrupted\");\n }\n else\n throw new IORuntimeException(\"Not connected to \" + socketAddressSupplier);\n }\n\n if (clientChannel == null)\n throw new IORuntimeException(\"Not connected to \" + socketAddressSupplier);\n }",
"public static void forceDelete(final Path path) throws IOException {\n\t\tif (!java.nio.file.Files.isDirectory(path)) {\n\t\t\tjava.nio.file.Files.delete(path);\n\t\t} else {\n\t\t\tjava.nio.file.Files.walkFileTree(path, DeleteDirVisitor.getInstance());\n\t\t}\n\t}",
"ValidationResult cleanObjectKey(String name) {\n ValidationResult vr = new ValidationResult();\n name = name.trim();\n for (String x : objectKeyCharsNotAllowed)\n name = name.replace(x, \"\");\n\n if (name.length() > Constants.MAX_KEY_LENGTH) {\n name = name.substring(0, Constants.MAX_KEY_LENGTH-1);\n vr.setErrorDesc(name.trim() + \"... exceeds the limit of \"+ Constants.MAX_KEY_LENGTH + \" characters. Trimmed\");\n vr.setErrorCode(520);\n }\n\n vr.setObject(name.trim());\n\n return vr;\n }",
"private void populateCalendarHours(Record record, ProjectCalendarHours hours) throws MPXJException\n {\n hours.setDay(Day.getInstance(NumberHelper.getInt(record.getInteger(0))));\n addDateRange(hours, record.getTime(1), record.getTime(2));\n addDateRange(hours, record.getTime(3), record.getTime(4));\n addDateRange(hours, record.getTime(5), record.getTime(6));\n }"
] |
Helper function to bind script bundler to various targets | [
"protected void bindHelper(GVRScriptBundle scriptBundle, GVRSceneObject rootSceneObject, int bindMask)\n throws IOException, GVRScriptException\n {\n for (GVRScriptBindingEntry entry : scriptBundle.file.binding) {\n GVRAndroidResource rc;\n if (entry.volumeType == null || entry.volumeType.isEmpty()) {\n rc = scriptBundle.volume.openResource(entry.script);\n } else {\n GVRResourceVolume.VolumeType volumeType = GVRResourceVolume.VolumeType.fromString(entry.volumeType);\n if (volumeType == null) {\n throw new GVRScriptException(String.format(\"Volume type %s is not recognized, script=%s\",\n entry.volumeType, entry.script));\n }\n rc = new GVRResourceVolume(mGvrContext, volumeType).openResource(entry.script);\n }\n\n GVRScriptFile scriptFile = (GVRScriptFile)loadScript(rc, entry.language);\n\n String targetName = entry.target;\n if (targetName.startsWith(TARGET_PREFIX)) {\n TargetResolver resolver = sBuiltinTargetMap.get(targetName);\n IScriptable target = resolver.getTarget(mGvrContext, targetName);\n\n // Apply mask\n boolean toBind = false;\n if ((bindMask & BIND_MASK_GVRSCRIPT) != 0 && targetName.equalsIgnoreCase(TARGET_GVRMAIN)) {\n toBind = true;\n }\n\n if ((bindMask & BIND_MASK_GVRACTIVITY) != 0 && targetName.equalsIgnoreCase(TARGET_GVRAPPLICATION)) {\n toBind = true;\n }\n\n if (toBind) {\n attachScriptFile(target, scriptFile);\n }\n } else {\n if ((bindMask & BIND_MASK_SCENE_OBJECTS) != 0) {\n if (targetName.equals(rootSceneObject.getName())) {\n attachScriptFile(rootSceneObject, scriptFile);\n }\n\n // Search in children\n GVRSceneObject[] sceneObjects = rootSceneObject.getSceneObjectsByName(targetName);\n if (sceneObjects != null) {\n for (GVRSceneObject sceneObject : sceneObjects) {\n GVRScriptBehavior b = new GVRScriptBehavior(sceneObject.getGVRContext());\n b.setScriptFile(scriptFile);\n sceneObject.attachComponent(b);\n }\n }\n }\n }\n }\n }"
] | [
"static void apply(final String patchId, final Collection<ContentModification> modifications, final PatchEntry patchEntry, final ContentItemFilter filter) {\n for (final ContentModification modification : modifications) {\n\n final ContentItem item = modification.getItem();\n // Check if we accept the item\n if (!filter.accepts(item)) {\n continue;\n }\n\n final Location location = new Location(item);\n final ContentEntry contentEntry = new ContentEntry(patchId, modification);\n ContentTaskDefinition definition = patchEntry.get(location);\n if (definition == null) {\n definition = new ContentTaskDefinition(location, contentEntry, false);\n patchEntry.put(location, definition);\n } else {\n definition.setTarget(contentEntry);\n }\n }\n }",
"public Map<DeckReference, TrackMetadata> getLoadedTracks() {\n ensureRunning();\n // Make a copy so callers get an immutable snapshot of the current state.\n return Collections.unmodifiableMap(new HashMap<DeckReference, TrackMetadata>(hotCache));\n }",
"String buildProjectEndpoint(DatastoreOptions options) {\n if (options.getProjectEndpoint() != null) {\n return options.getProjectEndpoint();\n }\n // DatastoreOptions ensures either project endpoint or project ID is set.\n String projectId = checkNotNull(options.getProjectId());\n if (options.getHost() != null) {\n return validateUrl(String.format(\"https://%s/%s/projects/%s\",\n options.getHost(), VERSION, projectId));\n } else if (options.getLocalHost() != null) {\n return validateUrl(String.format(\"http://%s/%s/projects/%s\",\n options.getLocalHost(), VERSION, projectId));\n }\n return validateUrl(String.format(\"%s/%s/projects/%s\",\n DEFAULT_HOST, VERSION, projectId));\n }",
"public Number getCostVariance()\n {\n Number variance = (Number) getCachedValue(TaskField.COST_VARIANCE);\n if (variance == null)\n {\n Number cost = getCost();\n Number baselineCost = getBaselineCost();\n if (cost != null && baselineCost != null)\n {\n variance = NumberHelper.getDouble(cost.doubleValue() - baselineCost.doubleValue());\n set(TaskField.COST_VARIANCE, variance);\n }\n }\n return (variance);\n }",
"public static sslservice[] get(nitro_service service, sslservice_args args) throws Exception{\n\t\tsslservice obj = new sslservice();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tsslservice[] response = (sslservice[])obj.get_resources(service, option);\n\t\treturn response;\n\t}",
"private void processCurrency(Row row)\n {\n String currencyName = row.getString(\"curr_short_name\");\n DecimalFormatSymbols symbols = new DecimalFormatSymbols();\n symbols.setDecimalSeparator(row.getString(\"decimal_symbol\").charAt(0));\n symbols.setGroupingSeparator(row.getString(\"digit_group_symbol\").charAt(0));\n DecimalFormat nf = new DecimalFormat();\n nf.setDecimalFormatSymbols(symbols);\n nf.applyPattern(\"#.#\");\n m_currencyMap.put(currencyName, nf);\n\n if (currencyName.equalsIgnoreCase(m_defaultCurrencyName))\n {\n m_numberFormat = nf;\n m_defaultCurrencyData = row;\n }\n }",
"public void synchronizeTaskIDToHierarchy()\n {\n clear();\n\n int currentID = (getByID(Integer.valueOf(0)) == null ? 1 : 0);\n for (Task task : m_projectFile.getChildTasks())\n {\n task.setID(Integer.valueOf(currentID++));\n add(task);\n currentID = synchroizeTaskIDToHierarchy(task, currentID);\n }\n }",
"private static Map<Integer, LinkedList<MetadataCache>> gatherCandidateAttachmentGroups() {\n Map<Integer,LinkedList<MetadataCache>> candidateGroups = new TreeMap<Integer, LinkedList<MetadataCache>>();\n final Iterator<File> iterator = MetadataFinder.getInstance().getAutoAttachCacheFiles().iterator();\n while (iterator.hasNext()) {\n final File file = iterator.next();\n try {\n final MetadataCache candidate = new MetadataCache(file);\n if (candidateGroups.get(candidate.sourcePlaylist) == null) {\n candidateGroups.put(candidate.sourcePlaylist, new LinkedList<MetadataCache>());\n }\n candidateGroups.get(candidate.sourcePlaylist).add(candidate);\n } catch (Exception e) {\n logger.error(\"Unable to open metadata cache file \" + file + \", discarding\", e);\n iterator.remove();\n }\n }\n return candidateGroups;\n }",
"@RequestMapping(value = \"api/edit/disable\", method = RequestMethod.POST)\n public\n @ResponseBody\n String disableResponses(Model model, int path_id, @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {\n OverrideService.getInstance().disableAllOverrides(path_id, clientUUID);\n //TODO also need to disable custom override if there is one of those\n editService.removeCustomOverride(path_id, clientUUID);\n\n return null;\n }"
] |
Calculates the maximum text height which is possible based on the used Paint and its settings.
@param _Paint Paint object which will be used to display a text.
@param _Text The text which should be measured. If null, a default text is chosen, which
has a maximum possible height
@return Maximum text height in px. | [
"public static float calculateMaxTextHeight(Paint _Paint, String _Text) {\n Rect height = new Rect();\n String text = _Text == null ? \"MgHITasger\" : _Text;\n _Paint.getTextBounds(text, 0, text.length(), height);\n return height.height();\n }"
] | [
"@Override\n\tpublic String getInputToParse(String completeInput, int offset, int completionOffset) {\n\t\tint fixedOffset = getOffsetIncludingWhitespace(completeInput, offset, Math.min(completeInput.length(), completionOffset));\n\t\treturn super.getInputToParse(completeInput, fixedOffset, completionOffset);\n\t}",
"private static int[] getErrorCorrection(int[] codewords, int ecclen) {\r\n\r\n ReedSolomon rs = new ReedSolomon();\r\n rs.init_gf(0x43);\r\n rs.init_code(ecclen, 1);\r\n rs.encode(codewords.length, codewords);\r\n\r\n int[] results = new int[ecclen];\r\n for (int i = 0; i < ecclen; i++) {\r\n results[i] = rs.getResult(results.length - 1 - i);\r\n }\r\n\r\n return results;\r\n }",
"@Override\n public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) {\n this.problemReporter.abortDueToInternalError(\n Messages.bind(Messages.abort_againstSourceModel, new String[] { String.valueOf(sourceTypes[0].getName()), String.valueOf(sourceTypes[0].getFileName()) }));\n }",
"public void setEnterpriseText(int index, String value)\n {\n set(selectField(AssignmentFieldLists.ENTERPRISE_TEXT, index), value);\n }",
"public static void checkDelegateType(Decorator<?> decorator) {\n\n Set<Type> types = new HierarchyDiscovery(decorator.getDelegateType()).getTypeClosure();\n\n for (Type decoratedType : decorator.getDecoratedTypes()) {\n if(!types.contains(decoratedType)) {\n throw BeanLogger.LOG.delegateMustSupportEveryDecoratedType(decoratedType, decorator);\n }\n }\n }",
"public void setWeekOfMonth(String weekOfMonthStr) {\n\n final WeekOfMonth weekOfMonth = WeekOfMonth.valueOf(weekOfMonthStr);\n if ((null == m_model.getWeekOfMonth()) || !m_model.getWeekOfMonth().equals(weekOfMonth)) {\n removeExceptionsOnChange(new Command() {\n\n public void execute() {\n\n m_model.setWeekOfMonth(weekOfMonth);\n onValueChange();\n }\n });\n }\n\n }",
"public static final void setSize(UIObject o, Rect size) {\n o.setPixelSize(size.w, size.h);\n\n }",
"public static <E, V> ServiceFuture<List<E>> fromHeaderPageResponse(Observable<ServiceResponseWithHeaders<Page<E>, V>> first, final Func1<String, Observable<ServiceResponseWithHeaders<Page<E>, V>>> next, final ListOperationCallback<E> callback) {\n final AzureServiceFuture<List<E>> serviceCall = new AzureServiceFuture<>();\n final PagingSubscriber<E> subscriber = new PagingSubscriber<>(serviceCall, new Func1<String, Observable<ServiceResponse<Page<E>>>>() {\n @Override\n public Observable<ServiceResponse<Page<E>>> call(String s) {\n return next.call(s)\n .map(new Func1<ServiceResponseWithHeaders<Page<E>, V>, ServiceResponse<Page<E>>>() {\n @Override\n public ServiceResponse<Page<E>> call(ServiceResponseWithHeaders<Page<E>, V> pageVServiceResponseWithHeaders) {\n return pageVServiceResponseWithHeaders;\n }\n });\n }\n }, callback);\n serviceCall.setSubscription(first\n .single()\n .subscribe(subscriber));\n return serviceCall;\n }",
"public static String getPropertyUri(PropertyIdValue propertyIdValue,\n\t\t\tPropertyContext propertyContext) {\n\t\tswitch (propertyContext) {\n\t\tcase DIRECT:\n\t\t\treturn PREFIX_PROPERTY_DIRECT + propertyIdValue.getId();\n\t\tcase STATEMENT:\n\t\t\treturn PREFIX_PROPERTY + propertyIdValue.getId();\n\t\tcase VALUE_SIMPLE:\n\t\t\treturn PREFIX_PROPERTY_STATEMENT + propertyIdValue.getId();\n\t\tcase VALUE:\n\t\t\treturn PREFIX_PROPERTY_STATEMENT_VALUE + propertyIdValue.getId();\n\t\tcase QUALIFIER:\n\t\t\treturn PREFIX_PROPERTY_QUALIFIER_VALUE + propertyIdValue.getId();\n\t\tcase QUALIFIER_SIMPLE:\n\t\t\treturn PREFIX_PROPERTY_QUALIFIER + propertyIdValue.getId();\n\t\tcase REFERENCE:\n\t\t\treturn PREFIX_PROPERTY_REFERENCE_VALUE + propertyIdValue.getId();\n\t\tcase REFERENCE_SIMPLE:\n\t\t\treturn PREFIX_PROPERTY_REFERENCE + propertyIdValue.getId();\n\t\tcase NO_VALUE:\n\t\t\treturn PREFIX_WIKIDATA_NO_VALUE + propertyIdValue.getId();\n\t\tcase NO_QUALIFIER_VALUE:\n\t\t\treturn PREFIX_WIKIDATA_NO_QUALIFIER_VALUE + propertyIdValue.getId();\n\t\tdefault:\n\t\t\treturn null;\n\t\t}\n\t}"
] |
Seeks forward or backwards to a particular holiday based on the current date
@param holidayString The holiday to seek to
@param direction The direction to seek
@param seekAmount The number of years to seek | [
"public void seekToHoliday(String holidayString, String direction, String seekAmount) {\n Holiday holiday = Holiday.valueOf(holidayString);\n assert(holiday != null);\n \n seekToIcsEvent(HOLIDAY_ICS_FILE, holiday.getSummary(), direction, seekAmount);\n }"
] | [
"public LatLong getLocation() {\n if (location == null) {\n location = new LatLong((JSObject) (getJSObject().getMember(\"location\")));\n }\n return location;\n }",
"public static void unzip(Path zip, Path target) throws IOException {\n try (final ZipFile zipFile = new ZipFile(zip.toFile())){\n unzip(zipFile, target);\n }\n }",
"public static final UUID parseUUID(String value)\n {\n UUID result = null;\n if (value != null && !value.isEmpty())\n {\n if (value.charAt(0) == '{')\n {\n // PMXML representation: <GUID>{0AB9133E-A09A-9648-B98A-B2384894AC44}</GUID>\n result = UUID.fromString(value.substring(1, value.length() - 1));\n }\n else\n {\n // XER representation: CrkTPqCalki5irI4SJSsRA\n byte[] data = javax.xml.bind.DatatypeConverter.parseBase64Binary(value + \"==\");\n long msb = 0;\n long lsb = 0;\n\n for (int i = 0; i < 8; i++)\n {\n msb = (msb << 8) | (data[i] & 0xff);\n }\n\n for (int i = 8; i < 16; i++)\n {\n lsb = (lsb << 8) | (data[i] & 0xff);\n }\n\n result = new UUID(msb, lsb);\n }\n }\n return result;\n }",
"private static int getTrimmedWidth(BufferedImage img) {\n int height = img.getHeight();\n int width = img.getWidth();\n int trimmedWidth = 0;\n\n for (int i = 0; i < height; i++) {\n for (int j = width - 1; j >= 0; j--) {\n if (img.getRGB(j, i) != Color.WHITE.getRGB() && j > trimmedWidth) {\n trimmedWidth = j;\n break;\n }\n }\n }\n\n return trimmedWidth;\n }",
"private void readAssignmentBaselines(Project.Assignments.Assignment assignment, ResourceAssignment mpx)\n {\n for (Project.Assignments.Assignment.Baseline baseline : assignment.getBaseline())\n {\n int number = NumberHelper.getInt(baseline.getNumber());\n\n //baseline.getBCWP()\n //baseline.getBCWS()\n Number cost = DatatypeConverter.parseExtendedAttributeCurrency(baseline.getCost());\n Date finish = DatatypeConverter.parseExtendedAttributeDate(baseline.getFinish());\n //baseline.getNumber()\n Date start = DatatypeConverter.parseExtendedAttributeDate(baseline.getStart());\n Duration work = DatatypeConverter.parseDuration(m_projectFile, TimeUnit.HOURS, baseline.getWork());\n\n if (number == 0)\n {\n mpx.setBaselineCost(cost);\n mpx.setBaselineFinish(finish);\n mpx.setBaselineStart(start);\n mpx.setBaselineWork(work);\n }\n else\n {\n mpx.setBaselineCost(number, cost);\n mpx.setBaselineWork(number, work);\n mpx.setBaselineStart(number, start);\n mpx.setBaselineFinish(number, finish);\n }\n }\n }",
"@NonNull\n @SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher reset() {\n lastResponsePage = 0;\n lastRequestPage = 0;\n lastResponseId = 0;\n endReached = false;\n clearFacetRefinements();\n cancelPendingRequests();\n numericRefinements.clear();\n return this;\n }",
"public Set<DbLicense> resolveLicenses(List<String> licStrings) {\n Set<DbLicense> result = new HashSet<>();\n\n licStrings\n .stream()\n .map(this::getMatchingLicenses)\n .forEach(result::addAll);\n\n return result;\n }",
"private void processFieldNameAliases(Map<Integer, FieldType> map, byte[] data)\n {\n if (data != null)\n {\n int offset = 0;\n int index = 0;\n CustomFieldContainer fields = m_file.getCustomFields();\n while (offset < data.length)\n {\n String alias = MPPUtility.getUnicodeString(data, offset);\n if (!alias.isEmpty())\n {\n FieldType field = map.get(Integer.valueOf(index));\n if (field != null)\n {\n fields.getCustomField(field).setAlias(alias);\n }\n }\n offset += (alias.length() + 1) * 2;\n index++;\n }\n }\n }",
"private void checkAllEnvelopes(PersistenceBroker broker)\r\n {\r\n Iterator iter = ((List) mvOrderOfIds.clone()).iterator();\r\n while(iter.hasNext())\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());\r\n // only non transient objects should be performed\r\n if(!mod.getModificationState().isTransient())\r\n {\r\n mod.markReferenceElements(broker);\r\n }\r\n }\r\n }"
] |
Returns a persistence strategy based on the passed configuration.
@param cacheMapping the selected {@link org.hibernate.ogm.datastore.keyvalue.options.CacheMappingType}
@param externalCacheManager the infinispan cache manager
@param configurationUrl the location of the configuration file
@param jtaPlatform the {@link JtaPlatform}
@param entityTypes the meta-data of the entities
@param associationTypes the meta-data of the associations
@param idSourceTypes the meta-data of the id generators
@return the persistence strategy | [
"public static PersistenceStrategy<?, ?, ?> getInstance(\n\t\t\tCacheMappingType cacheMapping,\n\t\t\tEmbeddedCacheManager externalCacheManager,\n\t\t\tURL configurationUrl,\n\t\t\tJtaPlatform jtaPlatform,\n\t\t\tSet<EntityKeyMetadata> entityTypes,\n\t\t\tSet<AssociationKeyMetadata> associationTypes,\n\t\t\tSet<IdSourceKeyMetadata> idSourceTypes ) {\n\n\t\tif ( cacheMapping == CacheMappingType.CACHE_PER_KIND ) {\n\t\t\treturn getPerKindStrategy(\n\t\t\t\t\texternalCacheManager,\n\t\t\t\t\tconfigurationUrl,\n\t\t\t\t\tjtaPlatform\n\t\t\t);\n\t\t}\n\t\telse {\n\t\t\treturn getPerTableStrategy(\n\t\t\t\t\texternalCacheManager,\n\t\t\t\t\tconfigurationUrl,\n\t\t\t\t\tjtaPlatform,\n\t\t\t\t\tentityTypes,\n\t\t\t\t\tassociationTypes,\n\t\t\t\t\tidSourceTypes\n\t\t\t);\n\t\t}\n\t}"
] | [
"public void check(ModelDef modelDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureReferencedKeys(modelDef, checkLevel);\r\n checkReferenceForeignkeys(modelDef, checkLevel);\r\n checkCollectionForeignkeys(modelDef, checkLevel);\r\n checkKeyModifications(modelDef, checkLevel);\r\n }",
"public static String soundex(String str) {\n if (str.length() < 1)\n return \"\"; // no soundex key for the empty string (could use 000)\n \n char[] key = new char[4];\n key[0] = str.charAt(0);\n int pos = 1;\n char prev = '0';\n for (int ix = 1; ix < str.length() && pos < 4; ix++) {\n char ch = str.charAt(ix);\n int charno;\n if (ch >= 'A' && ch <= 'Z')\n charno = ch - 'A';\n else if (ch >= 'a' && ch <= 'z')\n charno = ch - 'a';\n else\n continue;\n\n if (number[charno] != '0' && number[charno] != prev)\n key[pos++] = number[charno];\n prev = number[charno];\n }\n\n for ( ; pos < 4; pos++)\n key[pos] = '0';\n\n return new String(key);\n }",
"public List<MapRow> readTable(TableReader reader) throws IOException\n {\n reader.read();\n return reader.getRows();\n }",
"public static <T> T splitEachLine(CharSequence self, Pattern pattern, @ClosureParams(value=FromString.class,options=\"List<String>\") Closure<T> closure) throws IOException {\n final List<String> list = readLines(self);\n T result = null;\n for (String line : list) {\n List vals = Arrays.asList(pattern.split(line));\n result = closure.call(vals);\n }\n return result;\n }",
"public static streamidentifier_stats get(nitro_service service, String name) throws Exception{\n\t\tstreamidentifier_stats obj = new streamidentifier_stats();\n\t\tobj.set_name(name);\n\t\tstreamidentifier_stats response = (streamidentifier_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"public <T extends Widget & Checkable> boolean check(int checkableIndex) {\n List<T> children = getCheckableChildren();\n T checkableWidget = children.get(checkableIndex);\n return checkInternal(checkableWidget, true);\n }",
"private static Path resolveDockerDefinition(Path fullpath) {\n final Path ymlPath = fullpath.resolveSibling(fullpath.getFileName() + \".yml\");\n if (Files.exists(ymlPath)) {\n return ymlPath;\n } else {\n final Path yamlPath = fullpath.resolveSibling(fullpath.getFileName() + \".yaml\");\n if (Files.exists(yamlPath)) {\n return yamlPath;\n }\n }\n\n return null;\n }",
"public void getElevationAlongPath(PathElevationRequest req, ElevationServiceCallback callback) {\n \n this.callback = callback;\n \n JSObject doc = (JSObject) getJSObject().eval(\"document\");\n doc.setMember(getVariableName(), this);\n \n StringBuilder r = new StringBuilder(getVariableName())\n .append(\".\")\n .append(\"getElevationAlongPath(\")\n .append(req.getVariableName())\n .append(\", \")\n .append(\"function(results, status) {document.\")\n .append(getVariableName())\n .append(\".processResponse(results, status);});\");\n \n getJSObject().eval(r.toString());\n \n }",
"public static String makeAsciiTable(Object[][] table, Object[] rowLabels, Object[] colLabels, int padLeft, int padRight, boolean tsv) {\r\n StringBuilder buff = new StringBuilder();\r\n // top row\r\n buff.append(makeAsciiTableCell(\"\", padLeft, padRight, tsv)); // the top left cell\r\n for (int j = 0; j < table[0].length; j++) { // assume table is a rectangular matrix\r\n buff.append(makeAsciiTableCell(colLabels[j], padLeft, padRight, (j != table[0].length - 1) && tsv));\r\n }\r\n buff.append('\\n');\r\n // all other rows\r\n for (int i = 0; i < table.length; i++) {\r\n // one row\r\n buff.append(makeAsciiTableCell(rowLabels[i], padLeft, padRight, tsv));\r\n for (int j = 0; j < table[i].length; j++) {\r\n buff.append(makeAsciiTableCell(table[i][j], padLeft, padRight, (j != table[0].length - 1) && tsv));\r\n }\r\n buff.append('\\n');\r\n }\r\n return buff.toString();\r\n }"
] |
Log a warning for the resource at the provided address and a single attribute. The detail message is a default
'Attributes are not understood in the target model version and this resource will need to be ignored on the target host.'
@param address where warning occurred
@param attribute attribute we are warning about | [
"public void logAttributeWarning(PathAddress address, String attribute) {\n logAttributeWarning(address, null, null, attribute);\n }"
] | [
"public void recordServerResult(ServerIdentity server, ModelNode response) {\n\n if (!serverGroupName.equals(server.getServerGroupName()) || !servers.contains(server)) {\n throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.unknownServer(server);\n }\n\n boolean serverFailed = response.has(FAILURE_DESCRIPTION);\n\n\n DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef(\"Recording server result for '%s': failed = %s\",\n server, server);\n\n synchronized (this) {\n int previousFailed = failureCount;\n if (serverFailed) {\n failureCount++;\n }\n else {\n successCount++;\n }\n if (previousFailed <= maxFailed) {\n if (!serverFailed && (successCount + failureCount) == servers.size()) {\n // All results are in; notify parent of success\n parent.recordServerGroupResult(serverGroupName, false);\n }\n else if (serverFailed && failureCount > maxFailed) {\n parent.recordServerGroupResult(serverGroupName, true);\n }\n }\n }\n }",
"public static void printDocumentation() {\n\t\tSystem.out\n\t\t\t\t.println(\"********************************************************************\");\n\t\tSystem.out.println(\"*** Wikidata Toolkit: GenderRatioProcessor\");\n\t\tSystem.out.println(\"*** \");\n\t\tSystem.out\n\t\t\t\t.println(\"*** This program will download and process dumps from Wikidata.\");\n\t\tSystem.out\n\t\t\t\t.println(\"*** It will compute the numbers of articles about humans across\");\n\t\tSystem.out\n\t\t\t\t.println(\"*** Wikimedia projects, and in particular it will count the articles\");\n\t\tSystem.out\n\t\t\t\t.println(\"*** for each sex/gender. Results will be stored in a CSV file.\");\n\t\tSystem.out.println(\"*** See source code for further details.\");\n\t\tSystem.out\n\t\t\t\t.println(\"********************************************************************\");\n\t}",
"public static lbmonbindings_servicegroup_binding[] get(nitro_service service, String monitorname) throws Exception{\n\t\tlbmonbindings_servicegroup_binding obj = new lbmonbindings_servicegroup_binding();\n\t\tobj.set_monitorname(monitorname);\n\t\tlbmonbindings_servicegroup_binding response[] = (lbmonbindings_servicegroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static void setFlag(Activity activity, final int bits, boolean on) {\n Window win = activity.getWindow();\n WindowManager.LayoutParams winParams = win.getAttributes();\n if (on) {\n winParams.flags |= bits;\n } else {\n winParams.flags &= ~bits;\n }\n win.setAttributes(winParams);\n }",
"public static String strMapToStr(Map<String, String> map) {\n\n StringBuilder sb = new StringBuilder();\n\n if (map == null || map.isEmpty())\n return sb.toString();\n\n for (Entry<String, String> entry : map.entrySet()) {\n\n sb.append(\"< \" + entry.getKey() + \", \" + entry.getValue() + \"> \");\n }\n return sb.toString();\n\n }",
"public static sslcipher get(nitro_service service, String ciphergroupname) throws Exception{\n\t\tsslcipher obj = new sslcipher();\n\t\tobj.set_ciphergroupname(ciphergroupname);\n\t\tsslcipher response = (sslcipher) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public void createPdfLayout(Dimension dim)\n {\n if (pdfdocument != null) //processing a PDF document\n {\n try {\n if (createImage)\n img = new BufferedImage(dim.width, dim.height, BufferedImage.TYPE_INT_RGB);\n Graphics2D ig = img.createGraphics();\n \n log.info(\"Creating PDF boxes\");\n VisualContext ctx = new VisualContext(null, null);\n \n boxtree = new CSSBoxTree(ig, ctx, dim, baseurl);\n boxtree.setConfig(config);\n boxtree.processDocument(pdfdocument, startPage, endPage);\n viewport = boxtree.getViewport();\n root = boxtree.getDocument().getDocumentElement();\n log.info(\"We have \" + boxtree.getLastId() + \" boxes\");\n viewport.initSubtree();\n \n log.info(\"Layout for \"+dim.width+\"px\");\n viewport.doLayout(dim.width, true, true);\n log.info(\"Resulting size: \" + viewport.getWidth() + \"x\" + viewport.getHeight() + \" (\" + viewport + \")\");\n \n log.info(\"Updating viewport size\");\n viewport.updateBounds(dim);\n log.info(\"Resulting size: \" + viewport.getWidth() + \"x\" + viewport.getHeight() + \" (\" + viewport + \")\");\n \n if (createImage && (viewport.getWidth() > dim.width || viewport.getHeight() > dim.height))\n {\n img = new BufferedImage(Math.max(viewport.getWidth(), dim.width),\n Math.max(viewport.getHeight(), dim.height),\n BufferedImage.TYPE_INT_RGB);\n ig = img.createGraphics();\n }\n \n log.info(\"Positioning for \"+img.getWidth()+\"x\"+img.getHeight()+\"px\");\n viewport.absolutePositions();\n \n clearCanvas();\n viewport.draw(new GraphicsRenderer(ig));\n setPreferredSize(new Dimension(img.getWidth(), img.getHeight()));\n revalidate();\n } catch (ParserConfigurationException e) {\n e.printStackTrace();\n } catch (IOException e) {\n e.printStackTrace();\n }\n }\n else if (root != null) //processing a DOM tree\n {\n super.createLayout(dim);\n }\n }",
"private void bindProcedure(PreparedStatement stmt, ClassDescriptor cld, Object obj, ProcedureDescriptor proc)\r\n throws SQLException\r\n {\r\n int valueSub = 0;\r\n\r\n // Figure out if we are using a callable statement. If we are, then we\r\n // will need to register one or more output parameters.\r\n CallableStatement callable = null;\r\n try\r\n {\r\n callable = (CallableStatement) stmt;\r\n }\r\n catch(Exception e)\r\n {\r\n m_log.error(\"Error while bind values for class '\" + (cld != null ? cld.getClassNameOfObject() : null)\r\n + \"', using stored procedure: \"+ proc, e);\r\n if(e instanceof SQLException)\r\n {\r\n throw (SQLException) e;\r\n }\r\n else\r\n {\r\n throw new PersistenceBrokerException(\"Unexpected error while bind values for class '\"\r\n + (cld != null ? cld.getClassNameOfObject() : null) + \"', using stored procedure: \"+ proc);\r\n }\r\n }\r\n\r\n // If we have a return value, then register it.\r\n if ((proc.hasReturnValue()) && (callable != null))\r\n {\r\n int jdbcType = proc.getReturnValueFieldRef().getJdbcType().getType();\r\n m_platform.setNullForStatement(stmt, valueSub + 1, jdbcType);\r\n callable.registerOutParameter(valueSub + 1, jdbcType);\r\n valueSub++;\r\n }\r\n\r\n // Process all of the arguments.\r\n Iterator iterator = proc.getArguments().iterator();\r\n while (iterator.hasNext())\r\n {\r\n ArgumentDescriptor arg = (ArgumentDescriptor) iterator.next();\r\n Object val = arg.getValue(obj);\r\n int jdbcType = arg.getJdbcType();\r\n setObjectForStatement(stmt, valueSub + 1, val, jdbcType);\r\n if ((arg.getIsReturnedByProcedure()) && (callable != null))\r\n {\r\n callable.registerOutParameter(valueSub + 1, jdbcType);\r\n }\r\n valueSub++;\r\n }\r\n }",
"public float getBoundsWidth() {\n if (mSceneObject != null) {\n GVRSceneObject.BoundingVolume v = mSceneObject.getBoundingVolume();\n return v.maxCorner.x - v.minCorner.x;\n }\n return 0f;\n }"
] |
Use this API to fetch sslocspresponder resource of given name . | [
"public static sslocspresponder get(nitro_service service, String name) throws Exception{\n\t\tsslocspresponder obj = new sslocspresponder();\n\t\tobj.set_name(name);\n\t\tsslocspresponder response = (sslocspresponder) obj.get_resource(service);\n\t\treturn response;\n\t}"
] | [
"public static Chart getMSDLineWithFreeModelChart(Trajectory t, int lagMin,\n\t\t\tint lagMax, double timelag, double diffusionCoefficient, double intercept) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tdouble[] modelData = new double[lagMax - lagMin + 1];\n\t\tMeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(\n\t\t\t\tt, lagMin);\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t\tmodelData[i - lagMin] = intercept + 4*diffusionCoefficient*(i*timelag);//4 * D * Math.pow(i * timelag, a);\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\t\tchart.addSeries(\"y=4*D*t + a\", xData, modelData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}",
"public void bindScriptBundleToScene(GVRScriptBundle scriptBundle, GVRScene scene) throws IOException, GVRScriptException {\n for (GVRSceneObject sceneObject : scene.getSceneObjects()) {\n bindBundleToSceneObject(scriptBundle, sceneObject);\n }\n }",
"private void handleSerialAPIGetCapabilitiesResponse(SerialMessage incomingMessage) {\n\t\tlogger.trace(\"Handle Message Serial API Get Capabilities\");\n\n\t\tthis.serialAPIVersion = String.format(\"%d.%d\", incomingMessage.getMessagePayloadByte(0), incomingMessage.getMessagePayloadByte(1));\n\t\tthis.manufactureId = ((incomingMessage.getMessagePayloadByte(2)) << 8) | (incomingMessage.getMessagePayloadByte(3));\n\t\tthis.deviceType = ((incomingMessage.getMessagePayloadByte(4)) << 8) | (incomingMessage.getMessagePayloadByte(5));\n\t\tthis.deviceId = (((incomingMessage.getMessagePayloadByte(6)) << 8) | (incomingMessage.getMessagePayloadByte(7)));\n\t\t\n\t\tlogger.debug(String.format(\"API Version = %s\", this.getSerialAPIVersion()));\n\t\tlogger.debug(String.format(\"Manufacture ID = 0x%x\", this.getManufactureId()));\n\t\tlogger.debug(String.format(\"Device Type = 0x%x\", this.getDeviceType()));\n\t\tlogger.debug(String.format(\"Device ID = 0x%x\", this.getDeviceId()));\n\t\t\n\t\t// Ready to get information on Serial API\t\t\n\t\tthis.enqueue(new SerialMessage(SerialMessage.SerialMessageClass.SerialApiGetInitData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.SerialApiGetInitData, SerialMessage.SerialMessagePriority.High));\n\t}",
"public BoxGroupMembership.Info addMembership(BoxUser user, Role role) {\n BoxAPIConnection api = this.getAPI();\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"user\", new JsonObject().add(\"id\", user.getID()));\n requestJSON.add(\"group\", new JsonObject().add(\"id\", this.getID()));\n if (role != null) {\n requestJSON.add(\"role\", role.toJSONString());\n }\n\n URL url = ADD_MEMBERSHIP_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxGroupMembership membership = new BoxGroupMembership(api, responseJSON.get(\"id\").asString());\n return membership.new Info(responseJSON);\n }",
"public static String addFolderSlashIfNeeded(String folderName) {\n if (!\"\".equals(folderName) && !folderName.endsWith(\"/\")) {\n return folderName + \"/\";\n } else {\n return folderName;\n }\n }",
"public Stats getPhotoStats(String photoId, Date date) throws FlickrException {\n return getStats(METHOD_GET_PHOTO_STATS, \"photo_id\", photoId, date);\n }",
"public void setColorForTotal(int row, int column, Color color){\r\n\t\tint mapC = (colors.length-1) - column;\r\n\t\tint mapR = (colors[0].length-1) - row;\r\n\t\tcolors[mapC][mapR]=color;\t\t\r\n\t}",
"public Date getFinishDate()\n {\n Date finishDate = null;\n\n for (Task task : m_tasks)\n {\n //\n // If a hidden \"summary\" task is present we ignore it\n //\n if (NumberHelper.getInt(task.getUniqueID()) == 0)\n {\n continue;\n }\n\n //\n // Select the actual or forecast start date\n //\n Date taskFinishDate;\n taskFinishDate = task.getActualFinish();\n if (taskFinishDate == null)\n {\n taskFinishDate = task.getFinish();\n }\n\n if (taskFinishDate != null)\n {\n if (finishDate == null)\n {\n finishDate = taskFinishDate;\n }\n else\n {\n if (taskFinishDate.getTime() > finishDate.getTime())\n {\n finishDate = taskFinishDate;\n }\n }\n }\n }\n\n return (finishDate);\n }",
"public void setAllowBlank(boolean allowBlank) {\n this.allowBlank = allowBlank;\n\n // Setup the allow blank validation\n if (!allowBlank) {\n if (blankValidator == null) {\n blankValidator = createBlankValidator();\n }\n setupBlurValidation();\n addValidator(blankValidator);\n } else {\n removeValidator(blankValidator);\n }\n }"
] |
the 1st request from the manager. | [
"private final void processMainRequest() {\n\n sender = getSender();\n startTimeMillis = System.currentTimeMillis();\n timeoutDuration = Duration.create(\n request.getActorMaxOperationTimeoutSec(), TimeUnit.SECONDS);\n\n actorMaxOperationTimeoutSec = request.getActorMaxOperationTimeoutSec();\n\n if (request.getProtocol() == RequestProtocol.HTTP \n || request.getProtocol() == RequestProtocol.HTTPS) {\n String urlComplete = String.format(\"%s://%s:%d%s\", request\n .getProtocol().toString(), trueTargetNode, request\n .getPort(), request.getResourcePath());\n\n // http://stackoverflow.com/questions/1600291/validating-url-in-java\n if (!PcHttpUtils.isUrlValid(urlComplete.trim())) {\n String errMsg = \"INVALID_URL\";\n logger.error(\"INVALID_URL: \" + urlComplete + \" return..\");\n replyErrors(errMsg, errMsg, PcConstants.NA, PcConstants.NA_INT);\n return;\n } else {\n logger.debug(\"url pass validation: \" + urlComplete);\n }\n\n asyncWorker = getContext().actorOf(\n Props.create(HttpWorker.class, actorMaxOperationTimeoutSec,\n client, urlComplete, request.getHttpMethod(),\n request.getPostData(), request.getHttpHeaderMap(), request.getResponseHeaderMeta()));\n\n } else if (request.getProtocol() == RequestProtocol.SSH ){\n asyncWorker = getContext().actorOf(\n Props.create(SshWorker.class, actorMaxOperationTimeoutSec,\n request.getSshMeta(), trueTargetNode));\n } else if (request.getProtocol() == RequestProtocol.TCP ){\n asyncWorker = getContext().actorOf(\n Props.create(TcpWorker.class, actorMaxOperationTimeoutSec,\n request.getTcpMeta(), trueTargetNode)); \n } else if (request.getProtocol() == RequestProtocol.UDP ){\n asyncWorker = getContext().actorOf(\n Props.create(UdpWorker.class, actorMaxOperationTimeoutSec,\n request.getUdpMeta(), trueTargetNode)); \n } else if (request.getProtocol() == RequestProtocol.PING ){\n asyncWorker = getContext().actorOf(\n Props.create(PingWorker.class, actorMaxOperationTimeoutSec, request.getPingMeta(),\n trueTargetNode));\n }\n\n asyncWorker.tell(RequestWorkerMsgType.PROCESS_REQUEST, getSelf());\n\n cancelExistingIfAnyAndScheduleTimeoutCall();\n\n }"
] | [
"public <V> V getAttachment(final AttachmentKey<V> key) {\n assert key != null;\n return key.cast(contextAttachments.get(key));\n }",
"private static EndpointReferenceType createEPR(String address, SLProperties props) {\n EndpointReferenceType epr = WSAEndpointReferenceUtils.getEndpointReference(address);\n if (props != null) {\n addProperties(epr, props);\n }\n return epr;\n }",
"public void doLocalClear()\r\n {\r\n if(log.isDebugEnabled()) log.debug(\"Clear materialization cache\");\r\n invokeCounter = 0;\r\n enabledReadCache = false;\r\n objectBuffer.clear();\r\n }",
"public void edit(Note note) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT);\r\n\r\n parameters.put(\"note_id\", note.getId());\r\n Rectangle bounds = note.getBounds();\r\n if (bounds != null) {\r\n parameters.put(\"note_x\", String.valueOf(bounds.x));\r\n parameters.put(\"note_y\", String.valueOf(bounds.y));\r\n parameters.put(\"note_w\", String.valueOf(bounds.width));\r\n parameters.put(\"note_h\", String.valueOf(bounds.height));\r\n }\r\n String text = note.getText();\r\n if (text != null) {\r\n parameters.put(\"note_text\", text);\r\n }\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"public Optional<ServerPort> activePort() {\n final Server server = this.server;\n return server != null ? server.activePort() : Optional.empty();\n }",
"public List<List<IN>> classifyFile(String filename) {\r\n ObjectBank<List<IN>> documents =\r\n makeObjectBankFromFile(filename, plainTextReaderAndWriter);\r\n List<List<IN>> result = new ArrayList<List<IN>>();\r\n\r\n for (List<IN> document : documents) {\r\n // System.err.println(document);\r\n classify(document);\r\n\r\n List<IN> sentence = new ArrayList<IN>();\r\n for (IN wi : document) {\r\n sentence.add(wi);\r\n // System.err.println(wi);\r\n }\r\n result.add(sentence);\r\n }\r\n return result;\r\n }",
"public void bindBundleToSceneObject(GVRScriptBundle scriptBundle, GVRSceneObject rootSceneObject)\n throws IOException, GVRScriptException\n {\n bindHelper(scriptBundle, rootSceneObject, BIND_MASK_SCENE_OBJECTS);\n }",
"public static Iterable<BoxRetentionPolicy.Info> getAll(\r\n String name, String type, String userID, int limit, final BoxAPIConnection api, String ... fields) {\r\n QueryStringBuilder queryString = new QueryStringBuilder();\r\n if (name != null) {\r\n queryString.appendParam(\"policy_name\", name);\r\n }\r\n if (type != null) {\r\n queryString.appendParam(\"policy_type\", type);\r\n }\r\n if (userID != null) {\r\n queryString.appendParam(\"created_by_user_id\", userID);\r\n }\r\n if (fields.length > 0) {\r\n queryString.appendParam(\"fields\", fields);\r\n }\r\n URL url = RETENTION_POLICIES_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryString.toString());\r\n return new BoxResourceIterable<BoxRetentionPolicy.Info>(api, url, limit) {\r\n\r\n @Override\r\n protected BoxRetentionPolicy.Info factory(JsonObject jsonObject) {\r\n BoxRetentionPolicy policy = new BoxRetentionPolicy(api, jsonObject.get(\"id\").asString());\r\n return policy.new Info(jsonObject);\r\n }\r\n\r\n };\r\n }",
"private static void defineField(Map<String, FieldType> container, String name, FieldType type, String alias)\n {\n container.put(name, type);\n if (alias != null)\n {\n ALIASES.put(type, alias);\n }\n }"
] |
Calculate the screen size of a tile. Normally the screen size is expressed in pixels and should therefore be
integers, but for the sake of accuracy we try to keep a double value as long as possible.
@param worldSize
The width and height of a tile in the layer's world coordinate system.
@param scale
The current client side scale.
@return Returns an array of double values where the first value is the tile screen width and the second value is
the tile screen height. | [
"public static int[] getTileScreenSize(double[] worldSize, double scale) {\n\t\tint screenWidth = (int) Math.round(scale * worldSize[0]);\n\t\tint screenHeight = (int) Math.round(scale * worldSize[1]);\n\t\treturn new int[] { screenWidth, screenHeight };\n\t}"
] | [
"@Override\n\tpublic Set<String> getRoundingNames(String... providers) {\n Set<String> result = new HashSet<>();\n String[] providerNames = providers;\n if (providerNames.length == 0) {\n providerNames = Monetary.getDefaultRoundingProviderChain().toArray(new String[Monetary.getDefaultRoundingProviderChain().size()]);\n }\n for (String providerName : providerNames) {\n for (RoundingProviderSpi prov : Bootstrap.getServices(RoundingProviderSpi.class)) {\n try {\n if (prov.getProviderName().equals(providerName) || prov.getProviderName().matches(providerName)) {\n result.addAll(prov.getRoundingNames());\n }\n } catch (Exception e) {\n Logger.getLogger(DefaultMonetaryRoundingsSingletonSpi.class.getName())\n .log(Level.SEVERE, \"Error loading RoundingProviderSpi from provider: \" + prov, e);\n }\n }\n }\n return result;\n }",
"public void setContentType(String photoId, String contentType) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_SET_CONTENTTYPE);\r\n\r\n parameters.put(\"photo_id\", photoId);\r\n parameters.put(\"content_type\", contentType);\r\n\r\n Response response = transport.post(transport.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"protected Object checkUndefined(Object val) {\n if (val instanceof String && ((String) val).equals(\"undefined\")) {\n return null;\n }\n return val;\n }",
"public ModelNode buildExecutableRequest(CommandContext ctx) throws Exception {\n try {\n for (FailureDescProvider h : providers) {\n effectiveProviders.add(h);\n }\n // In case some key-store needs to be persisted\n for (String ks : ksToStore) {\n composite.get(Util.STEPS).add(ElytronUtil.storeKeyStore(ctx, ks));\n effectiveProviders.add(new FailureDescProvider() {\n @Override\n public String stepFailedDescription() {\n return \"Storing the key-store \" + ksToStore;\n }\n });\n }\n // Final steps\n for (int i = 0; i < finalSteps.size(); i++) {\n composite.get(Util.STEPS).add(finalSteps.get(i));\n effectiveProviders.add(finalProviders.get(i));\n }\n return composite;\n } catch (Exception ex) {\n try {\n failureOccured(ctx, null);\n } catch (Exception ex2) {\n ex.addSuppressed(ex2);\n }\n throw ex;\n }\n }",
"public static String frame(String imageUrl) {\n if (imageUrl == null || imageUrl.length() == 0) {\n throw new IllegalArgumentException(\"Image URL must not be blank.\");\n }\n return FILTER_FRAME + \"(\" + imageUrl + \")\";\n }",
"private boolean contains(ArrayList defs, DefBase obj)\r\n {\r\n for (Iterator it = defs.iterator(); it.hasNext();)\r\n {\r\n if (obj.getName().equals(((DefBase)it.next()).getName()))\r\n {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }",
"private void readResource(Document.Resources.Resource resource)\n {\n Resource mpxjResource = m_projectFile.addResource();\n mpxjResource.setName(resource.getName());\n mpxjResource.setResourceCalendar(m_calendarMap.get(resource.getCalendarID()));\n mpxjResource.setStandardRate(new Rate(resource.getCost(), resource.getCostTimeUnit()));\n mpxjResource.setEmailAddress(resource.getEMail());\n mpxjResource.setGroup(resource.getGroup());\n //resource.getHyperlinks()\n mpxjResource.setUniqueID(resource.getID());\n //resource.getMarkerID()\n mpxjResource.setNotes(resource.getNote());\n mpxjResource.setID(Integer.valueOf(resource.getOutlineNumber()));\n //resource.getStyleProject()\n mpxjResource.setType(resource.getSubType() == null ? resource.getType() : resource.getSubType());\n }",
"public static <T> boolean containsAny(Collection<T> collection, Collection<T> toCheck){\r\n for(T c: toCheck){\r\n if(collection.contains(c))\r\n return true;\r\n }\r\n return false;\r\n \r\n }",
"public static double[][] diag(double[] vector){\n\n\t\t// Note: According to the Java Language spec, an array is initialized with the default value, here 0.\n\t\tdouble[][] diagonalMatrix = new double[vector.length][vector.length];\n\n\t\tfor(int index = 0; index < vector.length; index++) {\n\t\t\tdiagonalMatrix[index][index] = vector[index];\n\t\t}\n\n\t\treturn diagonalMatrix;\n\t}"
] |
Add an object into cache by key with expiration time specified
@param key
the key to index the object within the cache
@param obj
the object to be cached
@param expiration
the seconds after which the object will be evicted from the cache | [
"public void cache(String key, Object obj, int expiration) {\n H.Session session = this.session;\n if (null != session) {\n session.cache(key, obj, expiration);\n } else {\n app().cache().put(key, obj, expiration);\n }\n }"
] | [
"public Optional<URL> getServiceUrl(String name) {\n Service service = client.services().inNamespace(namespace).withName(name).get();\n return service != null ? createUrlForService(service) : Optional.empty();\n }",
"public static <T> T splitEachLine(File self, String regex, @ClosureParams(value=SimpleType.class, options=\"java.lang.String[]\") Closure<T> closure) throws IOException {\n return IOGroovyMethods.splitEachLine(newReader(self), regex, closure);\n }",
"public ItemRequest<Section> findById(String section) {\n \n String path = String.format(\"/sections/%s\", section);\n return new ItemRequest<Section>(this, Section.class, path, \"GET\");\n }",
"public static TxInfo getTransactionInfo(Environment env, Bytes prow, Column pcol, long startTs) {\n // TODO ensure primary is visible\n\n IteratorSetting is = new IteratorSetting(10, RollbackCheckIterator.class);\n RollbackCheckIterator.setLocktime(is, startTs);\n\n Entry<Key, Value> entry = ColumnUtil.checkColumn(env, is, prow, pcol);\n\n TxInfo txInfo = new TxInfo();\n\n if (entry == null) {\n txInfo.status = TxStatus.UNKNOWN;\n return txInfo;\n }\n\n ColumnType colType = ColumnType.from(entry.getKey());\n long ts = entry.getKey().getTimestamp() & ColumnConstants.TIMESTAMP_MASK;\n\n switch (colType) {\n case LOCK: {\n if (ts == startTs) {\n txInfo.status = TxStatus.LOCKED;\n txInfo.lockValue = entry.getValue().get();\n } else {\n txInfo.status = TxStatus.UNKNOWN; // locked by another tx\n }\n break;\n }\n case DEL_LOCK: {\n DelLockValue dlv = new DelLockValue(entry.getValue().get());\n\n if (ts != startTs) {\n // expect this to always be false, must be a bug in the iterator\n throw new IllegalStateException(prow + \" \" + pcol + \" (\" + ts + \" != \" + startTs + \") \");\n }\n\n if (dlv.isRollback()) {\n txInfo.status = TxStatus.ROLLED_BACK;\n } else {\n txInfo.status = TxStatus.COMMITTED;\n txInfo.commitTs = dlv.getCommitTimestamp();\n }\n break;\n }\n case WRITE: {\n long timePtr = WriteValue.getTimestamp(entry.getValue().get());\n\n if (timePtr != startTs) {\n // expect this to always be false, must be a bug in the iterator\n throw new IllegalStateException(\n prow + \" \" + pcol + \" (\" + timePtr + \" != \" + startTs + \") \");\n }\n\n txInfo.status = TxStatus.COMMITTED;\n txInfo.commitTs = ts;\n break;\n }\n default:\n throw new IllegalStateException(\"unexpected col type returned \" + colType);\n }\n\n return txInfo;\n }",
"public boolean computeDirect( DMatrixRMaj A ) {\n\n initPower(A);\n\n boolean converged = false;\n\n for( int i = 0; i < maxIterations && !converged; i++ ) {\n// q0.print();\n \n CommonOps_DDRM.mult(A,q0,q1);\n double s = NormOps_DDRM.normPInf(q1);\n CommonOps_DDRM.divide(q1,s,q2);\n\n converged = checkConverged(A);\n }\n\n return converged;\n }",
"public static appfwprofile get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile obj = new appfwprofile();\n\t\tobj.set_name(name);\n\t\tappfwprofile response = (appfwprofile) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static double ChiSquare(double[] histogram1, double[] histogram2) {\n double r = 0;\n for (int i = 0; i < histogram1.length; i++) {\n double t = histogram1[i] + histogram2[i];\n if (t != 0)\n r += Math.pow(histogram1[i] - histogram2[i], 2) / t;\n }\n\n return 0.5 * r;\n }",
"public static boolean hasAnnotation(Method method, Class<? extends Annotation> annotation) {\n return !searchForAnnotation(method, annotation).isEmpty();\n }",
"public String getPromotionDetailsJsonModel() throws IOException {\n final PromotionEvaluationReport sampleReport = new PromotionEvaluationReport();\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.UNPROMOTED_MSG, \"com.acme.secure-smh:core-relay:1.2.0\"), MAJOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.DO_NOT_USE_MSG, \"com.google.guava:guava:20.0\"), MAJOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.MISSING_LICENSE_MSG, \"org.apache.maven.wagon:wagon-webdav-jackrabbit:2.12\"), MINOR);\n sampleReport.addMessage(String.format(TWO_PLACES, PromotionReportTranslator.UNACCEPTABLE_LICENSE_MSG,\n \"aopaliance:aopaliance:1.0 licensed as Attribution-ShareAlike 2.5 Generic, \" +\n \"org.polyjdbc:polyjdbc0.7.1 licensed as Creative Commons Attribution-ShareAlike 3.0 Unported License\"),\n MINOR);\n\n sampleReport.addMessage(PromotionReportTranslator.SNAPSHOT_VERSION_MSG, Tag.CRITICAL);\n return JsonUtils.serialize(sampleReport);\n }"
] |
Convenience method for first removing all enum style constants and then adding the single one.
@see #removeEnumStyleNames(UIObject, Class)
@see #addEnumStyleName(UIObject, Style.HasCssName) | [
"public static <E extends Style.HasCssName, F extends Enum<? extends Style.HasCssName>> void addUniqueEnumStyleName(final UIObject uiObject,\n final Class<F> enumClass,\n final E style) {\n removeEnumStyleNames(uiObject, enumClass);\n addEnumStyleName(uiObject, style);\n }"
] | [
"public static <T> DatabaseTableConfig<T> fromClass(DatabaseType databaseType, Class<T> clazz) throws SQLException {\n\t\tString tableName = extractTableName(databaseType, clazz);\n\t\tif (databaseType.isEntityNamesMustBeUpCase()) {\n\t\t\ttableName = databaseType.upCaseEntityName(tableName);\n\t\t}\n\t\treturn new DatabaseTableConfig<T>(databaseType, clazz, tableName,\n\t\t\t\textractFieldTypes(databaseType, clazz, tableName));\n\t}",
"public static MetaClassRegistry getInstance(int includeExtension) {\n if (includeExtension != DONT_LOAD_DEFAULT) {\n if (instanceInclude == null) {\n instanceInclude = new MetaClassRegistryImpl();\n }\n return instanceInclude;\n } else {\n if (instanceExclude == null) {\n instanceExclude = new MetaClassRegistryImpl(DONT_LOAD_DEFAULT);\n }\n return instanceExclude;\n }\n }",
"public boolean setCustomResponse(String pathValue, String requestType, String customData) {\n try {\n JSONObject path = getPathFromEndpoint(pathValue, requestType);\n if (path == null) {\n String pathName = pathValue;\n createPath(pathName, pathValue, requestType);\n path = getPathFromEndpoint(pathValue, requestType);\n }\n String pathId = path.getString(\"pathId\");\n resetResponseOverride(pathId);\n setCustomResponse(pathId, customData);\n return toggleResponseOverride(pathId, true);\n } catch (Exception e) {\n e.printStackTrace();\n }\n return false;\n }",
"public static base_response unset(nitro_service client, ipv6 resource, String[] args) throws Exception{\n\t\tipv6 unsetresource = new ipv6();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public static base_response save(nitro_service client) throws Exception {\n\t\tnsconfig saveresource = new nsconfig();\n\t\treturn saveresource.perform_operation(client,\"save\");\n\t}",
"public SourceBuilder addLine(String fmt, Object... args) {\n add(fmt, args);\n source.append(LINE_SEPARATOR);\n return this;\n }",
"@SuppressWarnings(\"unchecked\")\n\tpublic <S extends IPAddressPartConfiguredString<T, P>> SQLStringMatcher<T, P, S> getNetworkStringMatcher(boolean isEntireAddress, IPAddressSQLTranslator translator) {\n\t\treturn new SQLStringMatcher<T, P, S>((S) this, isEntireAddress, translator);\n\t}",
"@Nullable\n public final String getStringContent(final long blobHandle, @NotNull final Transaction txn) throws IOException {\n String result;\n result = stringContentCache.tryKey(this, blobHandle);\n if (result == null) {\n final InputStream content = getContent(blobHandle, txn);\n if (content == null) {\n logger.error(\"Blob string not found: \" + getBlobLocation(blobHandle), new FileNotFoundException());\n }\n result = content == null ? null : UTFUtil.readUTF(content);\n if (result != null && result.length() <= config.getBlobStringsCacheMaxValueSize()) {\n if (stringContentCache.getObject(this, blobHandle) == null) {\n stringContentCache.cacheObject(this, blobHandle, result);\n }\n }\n }\n return result;\n }",
"public void setValue(Vector3f scale) {\n mX = scale.x;\n mY = scale.y;\n mZ = scale.z;\n }"
] |
Creates a new RDF serializer based on the current configuration of this
object.
@return the newly created RDF serializer
@throws IOException
if there were problems opening the output files | [
"protected RdfSerializer createRdfSerializer() throws IOException {\n\n\t\tString outputDestinationFinal;\n\t\tif (this.outputDestination != null) {\n\t\t\toutputDestinationFinal = this.outputDestination;\n\t\t} else {\n\t\t\toutputDestinationFinal = \"{PROJECT}\" + this.taskName + \"{DATE}\"\n\t\t\t\t\t+ \".nt\";\n\t\t}\n\n\t\tOutputStream exportOutputStream = getOutputStream(this.useStdOut,\n\t\t\t\tinsertDumpInformation(outputDestinationFinal),\n\t\t\t\tthis.compressionType);\n\n\t\tRdfSerializer serializer = new RdfSerializer(RDFFormat.NTRIPLES,\n\t\t\t\texportOutputStream, this.sites,\n\t\t\t\tPropertyRegister.getWikidataPropertyRegister());\n\t\tserializer.setTasks(this.tasks);\n\n\t\treturn serializer;\n\t}"
] | [
"public FluoKeyValue[] getKeyValues() {\n FluoKeyValue kv = keyVals[0];\n kv.setKey(new Key(row, fam, qual, vis, ColumnType.WRITE.encode(1)));\n kv.getValue().set(WriteValue.encode(0, false, false));\n\n kv = keyVals[1];\n kv.setKey(new Key(row, fam, qual, vis, ColumnType.DATA.encode(0)));\n kv.getValue().set(val);\n\n return keyVals;\n }",
"public <T extends Widget & Checkable> boolean uncheck(int checkableIndex) {\n List<T> children = getCheckableChildren();\n T checkableWidget = children.get(checkableIndex);\n return checkInternal(checkableWidget, false);\n }",
"public static WebDriverBackedEmbeddedBrowser withDriver(WebDriver driver,\n\t\t\tImmutableSortedSet<String> filterAttributes, long crawlWaitEvent,\n\t\t\tlong crawlWaitReload) {\n\t\treturn new WebDriverBackedEmbeddedBrowser(driver, filterAttributes, crawlWaitEvent,\n\t\t\t\tcrawlWaitReload);\n\t}",
"public Weld property(String key, Object value) {\n properties.put(key, value);\n return this;\n }",
"public <T> void cleanNullReferences(Class<T> clazz) {\n\t\tMap<Object, Reference<Object>> objectMap = getMapForClass(clazz);\n\t\tif (objectMap != null) {\n\t\t\tcleanMap(objectMap);\n\t\t}\n\t}",
"public static String join(Collection<String> s, String delimiter, boolean doQuote) {\r\n StringBuffer buffer = new StringBuffer();\r\n Iterator<String> iter = s.iterator();\r\n while (iter.hasNext()) {\r\n if (doQuote) {\r\n buffer.append(\"\\\"\" + iter.next() + \"\\\"\");\r\n } else {\r\n buffer.append(iter.next());\r\n }\r\n if (iter.hasNext()) {\r\n buffer.append(delimiter);\r\n }\r\n }\r\n return buffer.toString();\r\n }",
"public static void multAdd_zeros(final int blockLength ,\n final DSubmatrixD1 Y , final DSubmatrixD1 B ,\n final DSubmatrixD1 C )\n {\n int widthY = Y.col1 - Y.col0;\n\n for( int i = Y.row0; i < Y.row1; i += blockLength ) {\n int heightY = Math.min( blockLength , Y.row1 - i );\n\n for( int j = B.col0; j < B.col1; j += blockLength ) {\n int widthB = Math.min( blockLength , B.col1 - j );\n\n int indexC = (i-Y.row0+C.row0)*C.original.numCols + (j-B.col0+C.col0)*heightY;\n\n for( int k = Y.col0; k < Y.col1; k += blockLength ) {\n int indexY = i*Y.original.numCols + k*heightY;\n int indexB = (k-Y.col0+B.row0)*B.original.numCols + j*widthY;\n\n if( i == Y.row0 ) {\n multBlockAdd_zerosone(Y.original.data,B.original.data,C.original.data,\n indexY,indexB,indexC,heightY,widthY,widthB);\n } else {\n InnerMultiplication_DDRB.blockMultPlus(Y.original.data,B.original.data,C.original.data,\n indexY,indexB,indexC,heightY,widthY,widthB);\n }\n }\n }\n }\n }",
"public static boolean propertyExists(Class<?> clazz, String property, ElementType elementType) {\n\t\tif ( ElementType.FIELD.equals( elementType ) ) {\n\t\t\treturn getDeclaredField( clazz, property ) != null;\n\t\t}\n\t\telse {\n\t\t\tString capitalizedPropertyName = capitalize( property );\n\n\t\t\tMethod method = getMethod( clazz, PROPERTY_ACCESSOR_PREFIX_GET + capitalizedPropertyName );\n\t\t\tif ( method != null && method.getReturnType() != void.class ) {\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tmethod = getMethod( clazz, PROPERTY_ACCESSOR_PREFIX_IS + capitalizedPropertyName );\n\t\t\tif ( method != null && method.getReturnType() == boolean.class ) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}",
"@PostConstruct\n public void init() {\n //init Bus and LifeCycle listeners\n if (bus != null && sendLifecycleEvent ) {\n ServerLifeCycleManager slcm = bus.getExtension(ServerLifeCycleManager.class);\n if (null != slcm) {\n ServiceListenerImpl svrListener = new ServiceListenerImpl();\n svrListener.setSendLifecycleEvent(sendLifecycleEvent);\n svrListener.setQueue(queue);\n svrListener.setMonitoringServiceClient(monitoringServiceClient);\n slcm.registerListener(svrListener);\n }\n\n ClientLifeCycleManager clcm = bus.getExtension(ClientLifeCycleManager.class);\n if (null != clcm) {\n ClientListenerImpl cltListener = new ClientListenerImpl();\n cltListener.setSendLifecycleEvent(sendLifecycleEvent);\n cltListener.setQueue(queue);\n cltListener.setMonitoringServiceClient(monitoringServiceClient);\n clcm.registerListener(cltListener);\n }\n }\n\n if(executorQueueSize == 0) {\r\n \texecutor = Executors.newFixedThreadPool(this.executorPoolSize);\n }else{\r\n executor = new ThreadPoolExecutor(executorPoolSize, executorPoolSize, 0, TimeUnit.SECONDS, \r\n \t\tnew LinkedBlockingQueue<Runnable>(executorQueueSize), Executors.defaultThreadFactory(), \r\n \t\t\tnew RejectedExecutionHandlerImpl());\r\n }\r\n\n scheduler = new Timer();\n scheduler.scheduleAtFixedRate(new TimerTask() {\n public void run() {\n sendEventsFromQueue();\n }\n }, 0, getDefaultInterval());\n }"
] |
Attach a metadata cache file to a particular player media slot, so the cache will be used instead of querying
the player for metadata. This supports operation with metadata during shows where DJs are using all four player
numbers and heavily cross-linking between them.
If the media is ejected from that player slot, the cache will be detached.
@param slot the media slot to which a meta data cache is to be attached
@param file the metadata cache to be attached
@throws IOException if there is a problem reading the cache file
@throws IllegalArgumentException if an invalid player number or slot is supplied
@throws IllegalStateException if the metadata finder is not running | [
"public void attachMetadataCache(SlotReference slot, File file)\n throws IOException {\n ensureRunning();\n if (slot.player < 1 || slot.player > 4 || DeviceFinder.getInstance().getLatestAnnouncementFrom(slot.player) == null) {\n throw new IllegalArgumentException(\"unable to attach metadata cache for player \" + slot.player);\n }\n if ((slot.slot != CdjStatus.TrackSourceSlot.USB_SLOT) && (slot.slot != CdjStatus.TrackSourceSlot.SD_SLOT)) {\n throw new IllegalArgumentException(\"unable to attach metadata cache for slot \" + slot.slot);\n }\n\n MetadataCache cache = new MetadataCache(file);\n final MediaDetails slotDetails = getMediaDetailsFor(slot);\n if (cache.sourceMedia != null && slotDetails != null) {\n if (!slotDetails.hashKey().equals(cache.sourceMedia.hashKey())) {\n throw new IllegalArgumentException(\"Cache was created for different media (\" + cache.sourceMedia.hashKey() +\n \") than is in the slot (\" + slotDetails.hashKey() + \").\");\n }\n if (slotDetails.hasChanged(cache.sourceMedia)) {\n logger.warn(\"Media has changed (\" + slotDetails + \") since cache was created (\" + cache.sourceMedia +\n \"). Attaching anyway as instructed.\");\n }\n }\n attachMetadataCacheInternal(slot, cache);\n }"
] | [
"public static String normalizeWS(String value) {\n char[] tmp = new char[value.length()];\n int pos = 0;\n boolean prevws = false;\n for (int ix = 0; ix < tmp.length; ix++) {\n char ch = value.charAt(ix);\n if (ch != ' ' && ch != '\\t' && ch != '\\n' && ch != '\\r') {\n if (prevws && pos != 0)\n tmp[pos++] = ' ';\n\n tmp[pos++] = ch;\n prevws = false;\n } else\n prevws = true;\n }\n return new String(tmp, 0, pos);\n }",
"public static base_responses add(nitro_service client, nspbr6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnspbr6 addresources[] = new nspbr6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new nspbr6();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].td = resources[i].td;\n\t\t\t\taddresources[i].action = resources[i].action;\n\t\t\t\taddresources[i].srcipv6 = resources[i].srcipv6;\n\t\t\t\taddresources[i].srcipop = resources[i].srcipop;\n\t\t\t\taddresources[i].srcipv6val = resources[i].srcipv6val;\n\t\t\t\taddresources[i].srcport = resources[i].srcport;\n\t\t\t\taddresources[i].srcportop = resources[i].srcportop;\n\t\t\t\taddresources[i].srcportval = resources[i].srcportval;\n\t\t\t\taddresources[i].destipv6 = resources[i].destipv6;\n\t\t\t\taddresources[i].destipop = resources[i].destipop;\n\t\t\t\taddresources[i].destipv6val = resources[i].destipv6val;\n\t\t\t\taddresources[i].destport = resources[i].destport;\n\t\t\t\taddresources[i].destportop = resources[i].destportop;\n\t\t\t\taddresources[i].destportval = resources[i].destportval;\n\t\t\t\taddresources[i].srcmac = resources[i].srcmac;\n\t\t\t\taddresources[i].protocol = resources[i].protocol;\n\t\t\t\taddresources[i].protocolnumber = resources[i].protocolnumber;\n\t\t\t\taddresources[i].vlan = resources[i].vlan;\n\t\t\t\taddresources[i].Interface = resources[i].Interface;\n\t\t\t\taddresources[i].priority = resources[i].priority;\n\t\t\t\taddresources[i].state = resources[i].state;\n\t\t\t\taddresources[i].msr = resources[i].msr;\n\t\t\t\taddresources[i].monitor = resources[i].monitor;\n\t\t\t\taddresources[i].nexthop = resources[i].nexthop;\n\t\t\t\taddresources[i].nexthopval = resources[i].nexthopval;\n\t\t\t\taddresources[i].nexthopvlan = resources[i].nexthopvlan;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"public List<Module> getModules(final Map<String, String> filters) throws GrapesCommunicationException {\n final Client client = getClient();\n WebResource resource = client.resource(serverURL).path(RequestUtils.getAllModulesPath());\n for(final Map.Entry<String,String> queryParam: filters.entrySet()){\n resource = resource.queryParam(queryParam.getKey(), queryParam.getValue());\n }\n\n final ClientResponse response = resource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);\n\n client.destroy();\n if(ClientResponse.Status.OK.getStatusCode() != response.getStatus()){\n final String message = \"Failed to get filtered modules.\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n\n return response.getEntity(new GenericType<List<Module>>(){});\n }",
"public void logWarning(final String message) {\n messageQueue.add(new LogEntry() {\n @Override\n public String getMessage() {\n return message;\n }\n });\n }",
"public static String pad(String str, int totalChars) {\r\n if (str == null) {\r\n str = \"null\";\r\n }\r\n int slen = str.length();\r\n StringBuilder sb = new StringBuilder(str);\r\n for (int i = 0; i < totalChars - slen; i++) {\r\n sb.append(' ');\r\n }\r\n return sb.toString();\r\n }",
"private static long createLongSeed(byte[] seed)\n {\n if (seed == null || seed.length != SEED_SIZE_BYTES)\n {\n throw new IllegalArgumentException(\"Java RNG requires a 64-bit (8-byte) seed.\");\n }\n return BinaryUtils.convertBytesToLong(seed, 0);\n }",
"public HashMap<String, Object> getFirstResult(String query)\n throws Exception {\n HashMap<String, Object> result = null;\n\n Statement queryStatement = null;\n ResultSet results = null;\n try (Connection sqlConnection = getConnection()) {\n queryStatement = sqlConnection.createStatement();\n results = queryStatement.executeQuery(query);\n if (results.next()) {\n result = new HashMap<>();\n String[] columns = getColumnNames(results.getMetaData());\n\n for (String column : columns) {\n result.put(column, results.getObject(column));\n }\n }\n } catch (Exception e) {\n\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (queryStatement != null) {\n queryStatement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return result;\n }",
"public AdminClient checkout() {\n if (isClosed.get()) {\n throw new IllegalStateException(\"Pool is closing\");\n }\n\n AdminClient client;\n\n // Try to get one from the Cache.\n while ((client = clientCache.poll()) != null) {\n if (!client.isClusterModified()) {\n return client;\n } else {\n // Cluster is Modified, after the AdminClient is created. Close it\n client.close();\n }\n }\n\n // None is available, create new one.\n return createAdminClient();\n }",
"public static appfwprofile_crosssitescripting_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_crosssitescripting_binding obj = new appfwprofile_crosssitescripting_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_crosssitescripting_binding response[] = (appfwprofile_crosssitescripting_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] |
Use this API to delete lbroute. | [
"public static base_response delete(nitro_service client, lbroute resource) throws Exception {\n\t\tlbroute deleteresource = new lbroute();\n\t\tdeleteresource.network = resource.network;\n\t\tdeleteresource.netmask = resource.netmask;\n\t\treturn deleteresource.delete_resource(client);\n\t}"
] | [
"static List<NamedArgument> getNamedArgs( ExtensionContext context ) {\n List<NamedArgument> namedArgs = new ArrayList<>();\n\n if( context.getTestMethod().get().getParameterCount() > 0 ) {\n try {\n if( context.getClass().getCanonicalName().equals( METHOD_EXTENSION_CONTEXT ) ) {\n Field field = context.getClass().getSuperclass().getDeclaredField( \"testDescriptor\" );\n Object testDescriptor = ReflectionUtil.getFieldValueOrNull( field, context, ERROR );\n if( testDescriptor != null\n && testDescriptor.getClass().getCanonicalName().equals( TEST_TEMPLATE_INVOCATION_TEST_DESCRIPTOR ) ) {\n Object invocationContext = ReflectionUtil.getFieldValueOrNull( \"invocationContext\", testDescriptor, ERROR );\n if( invocationContext != null\n && invocationContext.getClass().getCanonicalName().equals( PARAMETERIZED_TEST_INVOCATION_CONTEXT ) ) {\n Object arguments = ReflectionUtil.getFieldValueOrNull( \"arguments\", invocationContext, ERROR );\n List<Object> args = Arrays.asList( (Object[]) arguments );\n namedArgs = ParameterNameUtil.mapArgumentsWithParameterNames( context.getTestMethod().get(), args );\n }\n }\n }\n } catch( Exception e ) {\n log.warn( ERROR, e );\n }\n }\n\n return namedArgs;\n }",
"public void forAllIndexDescriptorDefinitions(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curClassDef.getIndexDescriptors(); it.hasNext(); )\r\n {\r\n _curIndexDescriptorDef = (IndexDescriptorDef)it.next();\r\n generate(template);\r\n }\r\n _curIndexDescriptorDef = null;\r\n }",
"public int getSridFromCrs(String crs) {\n\t\tint crsInt;\n\t\tif (crs.indexOf(':') != -1) {\n\t\t\tcrsInt = Integer.parseInt(crs.substring(crs.indexOf(':') + 1));\n\t\t} else {\n\t\t\ttry {\n\t\t\t\tcrsInt = Integer.parseInt(crs);\n\t\t\t} catch (NumberFormatException e) {\n\t\t\t\tcrsInt = 0;\n\t\t\t}\n\t\t}\n\t\treturn crsInt;\n\t}",
"protected static BoxCollaboration.Info create(BoxAPIConnection api, JsonObject accessibleBy, JsonObject item,\n BoxCollaboration.Role role, Boolean notify, Boolean canViewPath) {\n\n\n String queryString = \"\";\n if (notify != null) {\n queryString = new QueryStringBuilder().appendParam(\"notify\", notify.toString()).toString();\n }\n URL url;\n if (queryString.length() > 0) {\n url = COLLABORATIONS_URL_TEMPLATE.buildWithQuery(api.getBaseURL(), queryString);\n } else {\n url = COLLABORATIONS_URL_TEMPLATE.build(api.getBaseURL());\n }\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"item\", item);\n requestJSON.add(\"accessible_by\", accessibleBy);\n requestJSON.add(\"role\", role.toJSONString());\n if (canViewPath != null) {\n requestJSON.add(\"can_view_path\", canViewPath.booleanValue());\n }\n\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxCollaboration newCollaboration = new BoxCollaboration(api, responseJSON.get(\"id\").asString());\n return newCollaboration.new Info(responseJSON);\n }",
"private void reply(final String response, final boolean error,\n final String errorMessage, final String stackTrace,\n final String statusCode, final int statusCodeInt) {\n\n \n if (!sentReply) {\n \n //must update sentReply first to avoid duplicated msg.\n sentReply = true;\n // Close the connection. Make sure the close operation ends because\n // all I/O operations are asynchronous in Netty.\n if(channel!=null && channel.isOpen())\n channel.close().awaitUninterruptibly();\n final ResponseOnSingeRequest res = new ResponseOnSingeRequest(\n response, error, errorMessage, stackTrace, statusCode,\n statusCodeInt, PcDateUtils.getNowDateTimeStrStandard(), null);\n if (!getContext().system().deadLetters().equals(sender)) {\n sender.tell(res, getSelf());\n }\n if (getContext() != null) {\n getContext().stop(getSelf());\n }\n }\n\n }",
"private void processAssignments() throws SQLException\n {\n List<Row> rows = getRows(\"select * from zscheduleitem where zproject=? and z_ent=? order by zorderinactivity\", m_projectID, m_entityMap.get(\"Assignment\"));\n for (Row row : rows)\n {\n Task task = m_project.getTaskByUniqueID(row.getInteger(\"ZACTIVITY_\"));\n Resource resource = m_project.getResourceByUniqueID(row.getInteger(\"ZRESOURCE\"));\n if (task != null && resource != null)\n {\n ResourceAssignment assignment = task.addResourceAssignment(resource);\n assignment.setGUID(row.getUUID(\"ZUNIQUEID\"));\n assignment.setActualFinish(row.getTimestamp(\"ZGIVENACTUALENDDATE_\"));\n assignment.setActualStart(row.getTimestamp(\"ZGIVENACTUALSTARTDATE_\"));\n\n assignment.setWork(assignmentDuration(task, row.getWork(\"ZGIVENWORK_\")));\n assignment.setOvertimeWork(assignmentDuration(task, row.getWork(\"ZGIVENWORKOVERTIME_\")));\n assignment.setActualWork(assignmentDuration(task, row.getWork(\"ZGIVENACTUALWORK_\")));\n assignment.setActualOvertimeWork(assignmentDuration(task, row.getWork(\"ZGIVENACTUALWORKOVERTIME_\")));\n assignment.setRemainingWork(assignmentDuration(task, row.getWork(\"ZGIVENREMAININGWORK_\")));\n\n assignment.setLevelingDelay(row.getDuration(\"ZLEVELINGDELAY_\"));\n\n if (assignment.getRemainingWork() == null)\n {\n assignment.setRemainingWork(assignment.getWork());\n }\n\n if (resource.getType() == ResourceType.WORK)\n {\n assignment.setUnits(Double.valueOf(NumberHelper.getDouble(row.getDouble(\"ZRESOURCEUNITS_\")) * 100.0));\n }\n }\n }\n }",
"public Configuration[] getConfigurations(String name) {\n ArrayList<Configuration> valuesList = new ArrayList<Configuration>();\n\n logger.info(\"Getting data for {}\", name);\n\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n\n String queryString = \"SELECT * FROM \" + Constants.DB_TABLE_CONFIGURATION;\n if (name != null) {\n queryString += \" WHERE \" + Constants.DB_TABLE_CONFIGURATION_NAME + \"=?\";\n }\n\n statement = sqlConnection.prepareStatement(queryString);\n if (name != null) {\n statement.setString(1, name);\n }\n\n results = statement.executeQuery();\n while (results.next()) {\n Configuration config = new Configuration();\n config.setValue(results.getString(Constants.DB_TABLE_CONFIGURATION_VALUE));\n config.setKey(results.getString(Constants.DB_TABLE_CONFIGURATION_NAME));\n config.setId(results.getInt(Constants.GENERIC_ID));\n logger.info(\"the configValue is = {}\", config.getValue());\n valuesList.add(config);\n }\n } catch (SQLException sqe) {\n logger.info(\"Exception in sql\");\n sqe.printStackTrace();\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n if (valuesList.size() == 0) {\n return null;\n }\n\n return valuesList.toArray(new Configuration[0]);\n }",
"private void registerNonExists(\n\t\tfinal org.hibernate.engine.spi.EntityKey[] keys,\n\t\tfinal Loadable[] persisters,\n\t\tfinal SharedSessionContractImplementor session) {\n\n\t\tfinal int[] owners = getOwners();\n\t\tif ( owners != null ) {\n\n\t\t\tEntityType[] ownerAssociationTypes = getOwnerAssociationTypes();\n\t\t\tfor ( int i = 0; i < keys.length; i++ ) {\n\n\t\t\t\tint owner = owners[i];\n\t\t\t\tif ( owner > -1 ) {\n\t\t\t\t\torg.hibernate.engine.spi.EntityKey ownerKey = keys[owner];\n\t\t\t\t\tif ( keys[i] == null && ownerKey != null ) {\n\n\t\t\t\t\t\tfinal PersistenceContext persistenceContext = session.getPersistenceContext();\n\n\t\t\t\t\t\t/*final boolean isPrimaryKey;\n\t\t\t\t\t\tfinal boolean isSpecialOneToOne;\n\t\t\t\t\t\tif ( ownerAssociationTypes == null || ownerAssociationTypes[i] == null ) {\n\t\t\t\t\t\t\tisPrimaryKey = true;\n\t\t\t\t\t\t\tisSpecialOneToOne = false;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tisPrimaryKey = ownerAssociationTypes[i].getRHSUniqueKeyPropertyName()==null;\n\t\t\t\t\t\t\tisSpecialOneToOne = ownerAssociationTypes[i].getLHSPropertyName()!=null;\n\t\t\t\t\t\t}*/\n\n\t\t\t\t\t\t//TODO: can we *always* use the \"null property\" approach for everything?\n\t\t\t\t\t\t/*if ( isPrimaryKey && !isSpecialOneToOne ) {\n\t\t\t\t\t\t\tpersistenceContext.addNonExistantEntityKey(\n\t\t\t\t\t\t\t\t\tnew EntityKey( ownerKey.getIdentifier(), persisters[i], session.getEntityMode() )\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse if ( isSpecialOneToOne ) {*/\n\t\t\t\t\t\tboolean isOneToOneAssociation = ownerAssociationTypes != null &&\n\t\t\t\t\t\t\t\townerAssociationTypes[i] != null &&\n\t\t\t\t\t\t\t\townerAssociationTypes[i].isOneToOne();\n\t\t\t\t\t\tif ( isOneToOneAssociation ) {\n\t\t\t\t\t\t\tpersistenceContext.addNullProperty( ownerKey,\n\t\t\t\t\t\t\t\t\townerAssociationTypes[i].getPropertyName() );\n\t\t\t\t\t\t}\n\t\t\t\t\t\t/*}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tpersistenceContext.addNonExistantEntityUniqueKey( new EntityUniqueKey(\n\t\t\t\t\t\t\t\t\tpersisters[i].getEntityName(),\n\t\t\t\t\t\t\t\t\townerAssociationTypes[i].getRHSUniqueKeyPropertyName(),\n\t\t\t\t\t\t\t\t\townerKey.getIdentifier(),\n\t\t\t\t\t\t\t\t\tpersisters[owner].getIdentifierType(),\n\t\t\t\t\t\t\t\t\tsession.getEntityMode()\n\t\t\t\t\t\t\t) );\n\t\t\t\t\t\t}*/\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"public void flush() throws IOException {\n checkMutable();\n long startTime = System.currentTimeMillis();\n channel.force(true);\n long elapsedTime = System.currentTimeMillis() - startTime;\n LogFlushStats.recordFlushRequest(elapsedTime);\n logger.debug(\"flush time \" + elapsedTime);\n setHighWaterMark.set(getSizeInBytes());\n logger.debug(\"flush high water mark:\" + highWaterMark());\n }"
] |
Returns a new macro resolver that loads message keys from the workplace bundle in the user setting's language.
@param cms the CmsObject.
@return a new macro resolver with messages from the workplace bundle in the current users locale. | [
"public static I_CmsMacroResolver newWorkplaceLocaleResolver(final CmsObject cms) {\n\n // Resolve macros in the property configuration\n CmsMacroResolver resolver = new CmsMacroResolver();\n resolver.setCmsObject(cms);\n CmsUserSettings userSettings = new CmsUserSettings(cms.getRequestContext().getCurrentUser());\n CmsMultiMessages multimessages = new CmsMultiMessages(userSettings.getLocale());\n multimessages.addMessages(OpenCms.getWorkplaceManager().getMessages(userSettings.getLocale()));\n resolver.setMessages(multimessages);\n resolver.setKeepEmptyMacros(true);\n\n return resolver;\n }"
] | [
"public ApnsServiceBuilder withDelegate(ApnsDelegate delegate) {\n this.delegate = delegate == null ? ApnsDelegate.EMPTY : delegate;\n return this;\n }",
"public String addComment(String photosetId, String commentText) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD_COMMENT);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\r\n parameters.put(\"comment_text\", commentText);\r\n\r\n // Note: This method requires an HTTP POST request.\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n // response:\r\n // <comment id=\"97777-12492-72057594037942601\" />\r\n Element commentElement = response.getPayload();\r\n return commentElement.getAttribute(\"id\");\r\n }",
"public static base_response delete(nitro_service client, String ipv6address) throws Exception {\n\t\tnsip6 deleteresource = new nsip6();\n\t\tdeleteresource.ipv6address = ipv6address;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public String setClassification(String classificationType) {\n Metadata metadata = new Metadata().add(Metadata.CLASSIFICATION_KEY, classificationType);\n Metadata classification = null;\n\n try {\n classification = this.createMetadata(Metadata.CLASSIFICATION_TEMPLATE_KEY, \"enterprise\", metadata);\n } catch (BoxAPIException e) {\n if (e.getResponseCode() == 409) {\n metadata = new Metadata(\"enterprise\", Metadata.CLASSIFICATION_TEMPLATE_KEY);\n metadata.replace(Metadata.CLASSIFICATION_KEY, classificationType);\n classification = this.updateMetadata(metadata);\n } else {\n throw e;\n }\n }\n\n return classification.getString(Metadata.CLASSIFICATION_KEY);\n }",
"public static <T> T assertNull(T value, String message) {\n if (value != null)\n throw new IllegalStateException(message);\n return value;\n }",
"@Override\n public void close() {\n status = TrStatus.CLOSED;\n try {\n node.close();\n } catch (IOException e) {\n log.error(\"Failed to close ephemeral node\");\n throw new IllegalStateException(e);\n }\n }",
"final void roll(final long timeForSuffix) {\n\n final File backupFile = this.prepareBackupFile(timeForSuffix);\n\n // close filename\n this.getAppender().closeFile();\n\n // rename filename on disk to filename+suffix(+number)\n this.doFileRoll(this.getAppender().getIoFile(), backupFile);\n\n // setup new file 'filename'\n this.getAppender().openFile();\n\n this.fireFileRollEvent(new FileRollEvent(this, backupFile));\n }",
"@Nonnull\n private ReferencedEnvelope getFeatureBounds(\n final MfClientHttpRequestFactory clientHttpRequestFactory,\n final MapAttributeValues mapValues, final ExecutionContext context) {\n final MapfishMapContext mapContext = createMapContext(mapValues);\n\n String layerName = mapValues.zoomToFeatures.layer;\n ReferencedEnvelope bounds = new ReferencedEnvelope();\n for (MapLayer layer: mapValues.getLayers()) {\n context.stopIfCanceled();\n\n if ((!StringUtils.isEmpty(layerName) && layerName.equals(layer.getName())) ||\n (StringUtils.isEmpty(layerName) && layer instanceof AbstractFeatureSourceLayer)) {\n AbstractFeatureSourceLayer featureLayer = (AbstractFeatureSourceLayer) layer;\n FeatureSource<?, ?> featureSource =\n featureLayer.getFeatureSource(clientHttpRequestFactory, mapContext);\n FeatureCollection<?, ?> features;\n try {\n features = featureSource.getFeatures();\n } catch (IOException e) {\n throw ExceptionUtils.getRuntimeException(e);\n }\n\n if (!features.isEmpty()) {\n final ReferencedEnvelope curBounds = features.getBounds();\n bounds.expandToInclude(curBounds);\n }\n }\n }\n\n return bounds;\n }",
"public ArrayList<String> getCarouselImages(){\n ArrayList<String> carouselImages = new ArrayList<>();\n for(CTInboxMessageContent ctInboxMessageContent: getInboxMessageContents()){\n carouselImages.add(ctInboxMessageContent.getMedia());\n }\n return carouselImages;\n }"
] |
Function to compute the bias gradient for batch convolution | [
"public static int cudnnConvolutionBackwardBias(\n cudnnHandle handle, \n Pointer alpha, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n Pointer beta, \n cudnnTensorDescriptor dbDesc, \n Pointer db)\n {\n return checkResult(cudnnConvolutionBackwardBiasNative(handle, alpha, dyDesc, dy, beta, dbDesc, db));\n }"
] | [
"public int getIntegerBelief(String name){\n Object belief = introspector.getBeliefBase(this).get(name);\n int count = 0;\n if (belief!=null) {\n count = (Integer) belief;\n }\n return (Integer) count;\n }",
"@Override\n public void perform(GraphRewrite event, EvaluationContext context)\n {\n checkVariableName(event, context);\n WindupVertexFrame payload = resolveVariable(event, getVariableName());\n if (payload instanceof FileReferenceModel)\n {\n FileModel file = ((FileReferenceModel) payload).getFile();\n perform(event, context, (XmlFileModel) file);\n }\n else\n {\n super.perform(event, context);\n }\n\n }",
"public void setVertexBuffer(GVRVertexBuffer vbuf)\n {\n if (vbuf == null)\n {\n throw new IllegalArgumentException(\"Vertex buffer cannot be null\");\n }\n mVertices = vbuf;\n NativeMesh.setVertexBuffer(getNative(), vbuf.getNative());\n }",
"@Deprecated\n @Override\n public File fetch(String source, String dest, long diskQuotaSizeInKB) throws Exception {\n return fetchFromSource(source, dest, null, null, -1, diskQuotaSizeInKB, null);\n }",
"protected void setColumnsFinalWidth() {\n log.debug(\"Setting columns final width.\");\n float factor;\n int printableArea = report.getOptions().getColumnWidth();\n\n //Create a list with only the visible columns.\n List visibleColums = getVisibleColumns();\n\n\n if (report.getOptions().isUseFullPageWidth()) {\n int columnsWidth = 0;\n int notRezisableWidth = 0;\n\n //Store in a variable the total with of all visible columns\n for (Object visibleColum : visibleColums) {\n AbstractColumn col = (AbstractColumn) visibleColum;\n columnsWidth += col.getWidth();\n if (col.isFixedWidth())\n notRezisableWidth += col.getWidth();\n }\n\n\n factor = (float) (printableArea - notRezisableWidth) / (float) (columnsWidth - notRezisableWidth);\n\n log.debug(\"printableArea = \" + printableArea\n + \", columnsWidth = \" + columnsWidth\n + \", columnsWidth = \" + columnsWidth\n + \", notRezisableWidth = \" + notRezisableWidth\n + \", factor = \" + factor);\n\n int acumulated = 0;\n int colFinalWidth;\n\n //Select the non-resizable columns\n Collection resizableColumns = CollectionUtils.select(visibleColums, new Predicate() {\n public boolean evaluate(Object arg0) {\n return !((AbstractColumn) arg0).isFixedWidth();\n }\n\n });\n\n //Finally, set the new width to the resizable columns\n for (Iterator iter = resizableColumns.iterator(); iter.hasNext(); ) {\n AbstractColumn col = (AbstractColumn) iter.next();\n\n if (!iter.hasNext()) {\n col.setWidth(printableArea - notRezisableWidth - acumulated);\n } else {\n colFinalWidth = (new Float(col.getWidth() * factor)).intValue();\n acumulated += colFinalWidth;\n col.setWidth(colFinalWidth);\n }\n }\n }\n\n // If the columns width changed, the X position must be setted again.\n int posx = 0;\n for (Object visibleColum : visibleColums) {\n AbstractColumn col = (AbstractColumn) visibleColum;\n col.setPosX(posx);\n posx += col.getWidth();\n }\n }",
"private void writePredecessors(Task task)\n {\n List<Relation> relations = task.getPredecessors();\n for (Relation mpxj : relations)\n {\n RelationshipType xml = m_factory.createRelationshipType();\n m_project.getRelationship().add(xml);\n\n xml.setLag(getDuration(mpxj.getLag()));\n xml.setObjectId(Integer.valueOf(++m_relationshipObjectID));\n xml.setPredecessorActivityObjectId(mpxj.getTargetTask().getUniqueID());\n xml.setSuccessorActivityObjectId(mpxj.getSourceTask().getUniqueID());\n xml.setPredecessorProjectObjectId(PROJECT_OBJECT_ID);\n xml.setSuccessorProjectObjectId(PROJECT_OBJECT_ID);\n xml.setType(RELATION_TYPE_MAP.get(mpxj.getType()));\n }\n }",
"public static boolean containsAtLeastOneNonBlank(List<String> list){\n\t\tfor(String str : list){\n\t\t\tif(StringUtils.isNotBlank(str)){\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\t\treturn false;\n\t}",
"@Override\n public boolean decompose(DMatrixRBlock A) {\n if( A.numCols != A.numRows )\n throw new IllegalArgumentException(\"A must be square\");\n\n this.T = A;\n\n if( lower )\n return decomposeLower();\n else\n return decomposeUpper();\n }",
"protected AbstractColumn buildExpressionColumn() {\n\t\tExpressionColumn column = new ExpressionColumn();\n\t\tpopulateCommonAttributes(column);\n\t\t\n\t\tpopulateExpressionAttributes(column);\n\t\t\n\t\tcolumn.setExpression(customExpression);\n\t\tcolumn.setExpressionToGroupBy(customExpressionToGroupBy);\n\t\tcolumn.setExpressionForCalculation(customExpressionForCalculation);\n\t\t\n\t\treturn column;\n\t}"
] |
Builds the HTML code for a select widget given a bean containing the select options
@param htmlAttributes html attributes for the select widget
@param options the bean containing the select options
@return the HTML for the select box | [
"String buildSelect(String htmlAttributes, SelectOptions options) {\n\n return buildSelect(htmlAttributes, options.getOptions(), options.getValues(), options.getSelectedIndex());\n }"
] | [
"@RequestMapping(value = \"/cert\", method = {RequestMethod.GET, RequestMethod.HEAD})\n public String certPage() throws Exception {\n return \"cert\";\n }",
"public IPv4AddressSection getEmbeddedIPv4AddressSection(int startIndex, int endIndex) {\n\t\tif(startIndex == ((IPv6Address.MIXED_ORIGINAL_SEGMENT_COUNT - this.addressSegmentIndex) << 1) && endIndex == (getSegmentCount() << 1)) {\n\t\t\treturn getEmbeddedIPv4AddressSection();\n\t\t}\n\t\tIPv4AddressCreator creator = getIPv4Network().getAddressCreator();\n\t\tIPv4AddressSegment[] segments = creator.createSegmentArray((endIndex - startIndex) >> 1);\n\t\tint i = startIndex, j = 0;\n\t\tif(i % IPv6Address.BYTES_PER_SEGMENT == 1) {\n\t\t\tIPv6AddressSegment ipv6Segment = getSegment(i >> 1);\n\t\t\ti++;\n\t\t\tipv6Segment.getSplitSegments(segments, j - 1, creator);\n\t\t\tj++;\n\t\t}\n\t\tfor(; i < endIndex; i <<= 1, j <<= 1) {\n\t\t\tIPv6AddressSegment ipv6Segment = getSegment(i >> 1);\n\t\t\tipv6Segment.getSplitSegments(segments, j, creator);\n\t\t}\n\t\treturn createEmbeddedSection(creator, segments, this);\n\t}",
"public void addProducer(Broker broker) {\n Properties props = new Properties();\n props.put(\"host\", broker.host);\n props.put(\"port\", \"\" + broker.port);\n props.putAll(config.getProperties());\n if (sync) {\n SyncProducer producer = new SyncProducer(new SyncProducerConfig(props));\n logger.info(\"Creating sync producer for broker id = \" + broker.id + \" at \" + broker.host + \":\" + broker.port);\n syncProducers.put(broker.id, producer);\n } else {\n AsyncProducer<V> producer = new AsyncProducer<V>(new AsyncProducerConfig(props),//\n new SyncProducer(new SyncProducerConfig(props)),//\n serializer,//\n eventHandler,//\n config.getEventHandlerProperties(),//\n this.callbackHandler, //\n config.getCbkHandlerProperties());\n producer.start();\n logger.info(\"Creating async producer for broker id = \" + broker.id + \" at \" + broker.host + \":\" + broker.port);\n asyncProducers.put(broker.id, producer);\n }\n }",
"public static final String printWorkGroup(WorkGroup value)\n {\n return (Integer.toString(value == null ? WorkGroup.DEFAULT.getValue() : value.getValue()));\n }",
"private static void addCacheFormatEntry(List<Message> trackListEntries, int playlistId, ZipOutputStream zos) throws IOException {\n // Add a marker so we can recognize this as a metadata archive. I would use the ZipFile comment, but\n // that is not available until Java 7, and Beat Link is supposed to be backwards compatible with Java 6.\n // Since we are doing this anyway, we can also provide information about the nature of the cache, and\n // how many metadata entries it contains, which is useful for auto-attachment.\n zos.putNextEntry(new ZipEntry(CACHE_FORMAT_ENTRY));\n String formatEntry = CACHE_FORMAT_IDENTIFIER + \":\" + playlistId + \":\" + trackListEntries.size();\n zos.write(formatEntry.getBytes(\"UTF-8\"));\n }",
"private static Set<String> imageOrientationsOf(ImageMetadata metadata) {\n\n String exifIFD0DirName = new ExifIFD0Directory().getName();\n\n Tag[] tags = Arrays.stream(metadata.getDirectories())\n .filter(dir -> dir.getName().equals(exifIFD0DirName))\n .findFirst()\n .map(Directory::getTags)\n .orElseGet(() -> new Tag[0]);\n\n return Arrays.stream(tags)\n .filter(tag -> tag.getType() == 274)\n .map(Tag::getRawValue)\n .collect(Collectors.toSet());\n }",
"public RuleEnvelope getRule(String ruleId) throws ApiException {\n ApiResponse<RuleEnvelope> resp = getRuleWithHttpInfo(ruleId);\n return resp.getData();\n }",
"public List<WebSocketConnection> get(String key) {\n final List<WebSocketConnection> retList = new ArrayList<>();\n accept(key, C.F.addTo(retList));\n return retList;\n }",
"public Date dateTime(ImapRequestLineReader request) throws ProtocolException {\n char next = request.nextWordChar();\n String dateString;\n // From https://tools.ietf.org/html/rfc3501 :\n // date-time = DQUOTE date-day-fixed \"-\" date-month \"-\" date-year\n // SP time SP zone DQUOTE\n // zone = (\"+\" / \"-\") 4DIGIT\n if (next == '\"') {\n dateString = consumeQuoted(request);\n } else {\n throw new ProtocolException(\"DateTime values must be quoted.\");\n }\n\n try {\n // You can use Z or zzzz\n return new SimpleDateFormat(\"dd-MMM-yyyy hh:mm:ss Z\", Locale.US).parse(dateString);\n } catch (ParseException e) {\n throw new ProtocolException(\"Invalid date format <\" + dateString + \">, should comply to dd-MMM-yyyy hh:mm:ss Z\");\n }\n }"
] |
Examine the given model node, resolving any expressions found within, including within child nodes.
@param node the node
@return a node with all expressions resolved
@throws OperationFailedException if an expression cannot be resolved | [
"private ModelNode resolveExpressionsRecursively(final ModelNode node) throws OperationFailedException {\n if (!node.isDefined()) {\n return node;\n }\n\n ModelType type = node.getType();\n ModelNode resolved;\n if (type == ModelType.EXPRESSION) {\n resolved = resolveExpressionStringRecursively(node.asExpression().getExpressionString(), lenient, true);\n } else if (type == ModelType.OBJECT) {\n resolved = node.clone();\n for (Property prop : resolved.asPropertyList()) {\n resolved.get(prop.getName()).set(resolveExpressionsRecursively(prop.getValue()));\n }\n } else if (type == ModelType.LIST) {\n resolved = node.clone();\n ModelNode list = new ModelNode();\n list.setEmptyList();\n for (ModelNode current : resolved.asList()) {\n list.add(resolveExpressionsRecursively(current));\n }\n resolved = list;\n } else if (type == ModelType.PROPERTY) {\n resolved = node.clone();\n resolved.set(resolved.asProperty().getName(), resolveExpressionsRecursively(resolved.asProperty().getValue()));\n } else {\n resolved = node;\n }\n\n return resolved;\n }"
] | [
"public List<String> getListAttribute(String section, String name) {\n return split(getAttribute(section, name));\n }",
"void rejectAttributes(RejectedAttributesLogContext rejectedAttributes, ModelNode attributeValue) {\n for (RejectAttributeChecker checker : checks) {\n rejectedAttributes.checkAttribute(checker, name, attributeValue);\n }\n }",
"protected void copyStream(File outputDirectory,\n InputStream stream,\n String targetFileName) throws IOException\n {\n File resourceFile = new File(outputDirectory, targetFileName);\n BufferedReader reader = null;\n Writer writer = null;\n try\n {\n reader = new BufferedReader(new InputStreamReader(stream, ENCODING));\n writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(resourceFile), ENCODING));\n\n String line = reader.readLine();\n while (line != null)\n {\n writer.write(line);\n writer.write('\\n');\n line = reader.readLine();\n }\n writer.flush();\n }\n finally\n {\n if (reader != null)\n {\n reader.close();\n }\n if (writer != null)\n {\n writer.close();\n }\n }\n }",
"private String getInverseOneToOneProperty(String property, OgmEntityPersister otherSidePersister) {\n\t\tfor ( String candidate : otherSidePersister.getPropertyNames() ) {\n\t\t\tType candidateType = otherSidePersister.getPropertyType( candidate );\n\t\t\tif ( candidateType.isEntityType()\n\t\t\t\t\t&& ( ( (EntityType) candidateType ).isOneToOne()\n\t\t\t\t\t&& isOneToOneMatching( this, property, (OneToOneType) candidateType ) ) ) {\n\t\t\t\treturn candidate;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}",
"private boolean exceedsScreenDimensions(InternalFeature f, double scale) {\n\t\tEnvelope env = f.getBounds();\n\t\treturn (env.getWidth() * scale > MAXIMUM_TILE_COORDINATE) ||\n\t\t\t\t(env.getHeight() * scale > MAXIMUM_TILE_COORDINATE);\n\t}",
"private Map<UUID, FieldType> populateCustomFieldMap()\n {\n byte[] data = m_taskProps.getByteArray(Props.CUSTOM_FIELDS);\n int length = MPPUtility.getInt(data, 0);\n int index = length + 36;\n\n // 4 byte record count\n int recordCount = MPPUtility.getInt(data, index);\n index += 4;\n\n // 8 bytes per record\n index += (8 * recordCount);\n \n Map<UUID, FieldType> map = new HashMap<UUID, FieldType>();\n while (index < data.length)\n {\n int blockLength = MPPUtility.getInt(data, index); \n if (blockLength <= 0 || index + blockLength > data.length)\n {\n break;\n }\n \n int fieldID = MPPUtility.getInt(data, index + 4);\n FieldType field = FieldTypeHelper.getInstance(fieldID);\n UUID guid = MPPUtility.getGUID(data, index + 160);\n map.put(guid, field);\n index += blockLength;\n }\n return map;\n }",
"static String from(Class<?> entryClass) {\n List<String> tokens = tokenOf(entryClass);\n return fromTokens(tokens);\n }",
"int query(int downloadId) {\n\t\tsynchronized (mCurrentRequests) {\n\t\t\tfor (DownloadRequest request : mCurrentRequests) {\n\t\t\t\tif (request.getDownloadId() == downloadId) {\n\t\t\t\t\treturn request.getDownloadState();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn DownloadManager.STATUS_NOT_FOUND;\n\t}",
"double getThreshold(String x, String y, double p) {\r\n\t\treturn 2 * Math.max(x.length(), y.length()) * (1 - p);\r\n\t}"
] |
Adds a classpath source which contains the given resource.
TODO: [GH-213] this is extremely ugly; separate the code required to run on the
forked JVM into an isolated bundle and either create it on-demand (in temp.
files location?) or locate it in classpath somehow (in a portable way). | [
"private org.apache.tools.ant.types.Path addSlaveClasspath() {\n org.apache.tools.ant.types.Path path = new org.apache.tools.ant.types.Path(getProject());\n\n String [] REQUIRED_SLAVE_CLASSES = {\n SlaveMain.class.getName(),\n Strings.class.getName(),\n MethodGlobFilter.class.getName(),\n TeeOutputStream.class.getName()\n };\n\n for (String clazz : Arrays.asList(REQUIRED_SLAVE_CLASSES)) {\n String resource = clazz.replace(\".\", \"/\") + \".class\";\n File f = LoaderUtils.getResourceSource(getClass().getClassLoader(), resource);\n if (f != null) {\n path.createPath().setLocation(f);\n } else {\n throw new BuildException(\"Could not locate classpath for resource: \" + resource);\n }\n }\n return path;\n }"
] | [
"protected String addDependency(TaskGroup.HasTaskGroup dependency) {\n Objects.requireNonNull(dependency);\n this.taskGroup().addDependencyTaskGroup(dependency.taskGroup());\n return dependency.taskGroup().key();\n }",
"public static String readFlowId(Message message) {\n if (!(message instanceof SoapMessage)) {\n return null;\n }\n String flowId = null;\n Header hdFlowId = ((SoapMessage)message).getHeader(FLOW_ID_QNAME);\n if (hdFlowId != null) {\n if (hdFlowId.getObject() instanceof String) {\n flowId = (String)hdFlowId.getObject();\n } else if (hdFlowId.getObject() instanceof Node) {\n Node headerNode = (Node)hdFlowId.getObject();\n flowId = headerNode.getTextContent();\n } else {\n LOG.warning(\"Found FlowId soap header but value is not a String or a Node! Value: \"\n + hdFlowId.getObject().toString());\n }\n }\n return flowId;\n }",
"public boolean removeHandlerFor(final GVRSceneObject sceneObject) {\n sceneObject.detachComponent(GVRCollider.getComponentType());\n return null != touchHandlers.remove(sceneObject);\n }",
"public DockerContainerObjectBuilder<T> withContainerObjectClass(Class<T> containerObjectClass) {\n if (containerObjectClass == null) {\n throw new IllegalArgumentException(\"container object class cannot be null\");\n }\n this.containerObjectClass = containerObjectClass;\n\n //First we check if this ContainerObject is defining a @CubeDockerFile in static method\n final List<Method> methodsWithCubeDockerFile =\n ReflectionUtil.getMethodsWithAnnotation(containerObjectClass, CubeDockerFile.class);\n\n if (methodsWithCubeDockerFile.size() > 1) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Methods where annotation was found are: %s\",\n CubeDockerFile.class.getSimpleName(), methodsWithCubeDockerFile));\n }\n\n classHasMethodWithCubeDockerFile = !methodsWithCubeDockerFile.isEmpty();\n classDefinesCubeDockerFile = containerObjectClass.isAnnotationPresent(CubeDockerFile.class);\n classDefinesImage = containerObjectClass.isAnnotationPresent(Image.class);\n\n if (classHasMethodWithCubeDockerFile) {\n methodWithCubeDockerFile = methodsWithCubeDockerFile.get(0);\n boolean isMethodStatic = Modifier.isStatic(methodWithCubeDockerFile.getModifiers());\n boolean methodHasNoArguments = methodWithCubeDockerFile.getParameterCount() == 0;\n boolean methodReturnsAnArchive = Archive.class.isAssignableFrom(methodWithCubeDockerFile.getReturnType());\n if (!isMethodStatic || !methodHasNoArguments || !methodReturnsAnArchive) {\n throw new IllegalArgumentException(\n String.format(\"Method %s annotated with %s is expected to be static, no args and return %s.\",\n methodWithCubeDockerFile, CubeDockerFile.class.getSimpleName(), Archive.class.getSimpleName()));\n }\n }\n\n // User has defined @CubeDockerfile on the class and a method\n if (classHasMethodWithCubeDockerFile && classDefinesCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\n \"More than one %s annotation found and only one was expected. Both class and method %s has the annotation.\",\n CubeDockerFile.class.getSimpleName(), methodWithCubeDockerFile));\n }\n\n // User has defined @CubeDockerfile and @Image\n if ((classHasMethodWithCubeDockerFile || classDefinesCubeDockerFile) && classDefinesImage) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s has defined %s annotation and %s annotation together.\",\n containerObjectClass.getSimpleName(), Image.class.getSimpleName(),\n CubeDockerFile.class.getSimpleName()));\n }\n\n // User has not defined either @CubeDockerfile or @Image\n if (!classDefinesCubeDockerFile && !classDefinesImage && !classHasMethodWithCubeDockerFile) {\n throw new IllegalArgumentException(\n String.format(\"Container Object %s is not annotated with either %s or %s annotations.\",\n containerObjectClass.getName(), CubeDockerFile.class.getSimpleName(), Image.class.getSimpleName()));\n }\n\n return this;\n }",
"public void setDividerPadding(float padding, final Axis axis) {\n if (axis == getOrientationAxis()) {\n super.setDividerPadding(padding, axis);\n } else {\n Log.w(TAG, \"Cannot apply divider padding for wrong axis [%s], orientation = %s\",\n axis, getOrientation());\n }\n }",
"private void writeTasks(Project project)\n {\n Project.Tasks tasks = m_factory.createProjectTasks();\n project.setTasks(tasks);\n List<Project.Tasks.Task> list = tasks.getTask();\n\n for (Task task : m_projectFile.getTasks())\n {\n list.add(writeTask(task));\n }\n }",
"public List<BindingInfo> getQueueBindings(String vhost, String queue) {\n final URI uri = uriWithPath(\"./queues/\" + encodePathSegment(vhost) +\n \"/\" + encodePathSegment(queue) + \"/bindings\");\n final BindingInfo[] result = this.rt.getForObject(uri, BindingInfo[].class);\n return asListOrNull(result);\n }",
"public void setContentType(int pathId, String contentType) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_CONTENT_TYPE + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, contentType);\n statement.setInt(2, pathId);\n statement.executeUpdate();\n statement.close();\n } catch (SQLException e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"private void appendJoinSQL92NoParen(Join join, StringBuffer where, StringBuffer buf)\r\n {\r\n if (join.isOuter)\r\n {\r\n buf.append(\" LEFT OUTER JOIN \");\r\n }\r\n else\r\n {\r\n buf.append(\" INNER JOIN \");\r\n }\r\n\r\n buf.append(join.right.getTableAndAlias());\r\n buf.append(\" ON \");\r\n join.appendJoinEqualities(buf);\r\n\r\n appendTableWithJoins(join.right, where, buf);\r\n }"
] |
Calculate the child size along the axis
@param dataIndex data index
@param axis {@link Axis}
@return child size | [
"public float getChildSize(final int dataIndex, final Axis axis) {\n float size = 0;\n Widget child = mContainer.get(dataIndex);\n if (child != null) {\n switch (axis) {\n case X:\n size = child.getLayoutWidth();\n break;\n case Y:\n size = child.getLayoutHeight();\n break;\n case Z:\n size = child.getLayoutDepth();\n break;\n default:\n throw new RuntimeAssertion(\"Bad axis specified: %s\", axis);\n }\n }\n return size;\n }"
] | [
"private void logRequestHistory(HttpMethod httpMethodProxyRequest, PluginResponse httpServletResponse,\n History history) {\n try {\n if (requestInformation.get().handle && requestInformation.get().client.getIsActive()) {\n logger.info(\"Storing history\");\n String createdDate;\n SimpleDateFormat sdf = new SimpleDateFormat();\n sdf.setTimeZone(new SimpleTimeZone(0, \"GMT\"));\n sdf.applyPattern(\"dd MMM yyyy HH:mm:ss\");\n createdDate = sdf.format(new Date()) + \" GMT\";\n\n history.setCreatedAt(createdDate);\n history.setRequestURL(HttpUtilities.getURL(httpMethodProxyRequest.getURI().toString()));\n history.setRequestParams(httpMethodProxyRequest.getQueryString() == null ? \"\"\n : httpMethodProxyRequest.getQueryString());\n history.setRequestHeaders(HttpUtilities.getHeaders(httpMethodProxyRequest));\n history.setResponseHeaders(HttpUtilities.getHeaders(httpServletResponse));\n history.setResponseCode(Integer.toString(httpServletResponse.getStatus()));\n history.setResponseContentType(httpServletResponse.getContentType());\n history.setResponseData(httpServletResponse.getContentString());\n history.setResponseBodyDecoded(httpServletResponse.isContentDecoded());\n HistoryService.getInstance().addHistory(history);\n logger.info(\"Done storing\");\n }\n } catch (URIException e) {\n e.printStackTrace();\n }\n }",
"@Deprecated\n public static TraceContextHolder wrap(TraceContext traceContext) {\n return (traceContext != null) ? new TraceContextHolder(traceContext) : TraceContextHolder.EMPTY;\n }",
"public void clear()\r\n {\r\n Class collClass = getCollectionClass();\r\n\r\n // ECER: assure we notify all objects being removed, \r\n // necessary for RemovalAwareCollections...\r\n if (IRemovalAwareCollection.class.isAssignableFrom(collClass))\r\n {\r\n getData().clear();\r\n }\r\n else\r\n {\r\n Collection coll;\r\n // BRJ: use an empty collection so isLoaded will return true\r\n // for non RemovalAwareCollections only !! \r\n try\r\n {\r\n coll = (Collection) collClass.newInstance();\r\n }\r\n catch (Exception e)\r\n {\r\n coll = new ArrayList();\r\n }\r\n\r\n setData(coll);\r\n }\r\n _size = 0;\r\n }",
"@SuppressWarnings(\"deprecation\")\n\tpublic static boolean timeEquals(java.util.Date d1, java.util.Date d2) {\n if (d1 == null || d2 == null) {\n return false;\n }\n\n return d1.getHours() == d2.getHours()\n && d1.getMinutes() == d2.getMinutes()\n && d1.getSeconds() == d2.getSeconds();\n }",
"private void createNodeMappings(MtasTokenIdFactory mtasTokenIdFactory,\n Level level, Level parentLevel) {\n MtasToken nodeToken;\n if (level.node != null && level.positionStart != null\n && level.positionEnd != null) {\n nodeToken = new MtasTokenString(mtasTokenIdFactory.createTokenId(),\n level.node, \"\");\n nodeToken.setOffset(level.offsetStart, level.offsetEnd);\n nodeToken.setRealOffset(level.realOffsetStart, level.realOffsetEnd);\n nodeToken.addPositionRange(level.positionStart, level.positionEnd);\n tokenCollection.add(nodeToken);\n if (parentLevel != null) {\n parentLevel.tokens.add(nodeToken);\n }\n // only for first mapping(?)\n for (MtasToken token : level.tokens) {\n token.setParentId(nodeToken.getId());\n }\n }\n }",
"public String urlEncode(String s) {\n if (s == null || s.isEmpty()) {\n return s;\n }\n\n return URL.encodeQueryString(s);\n }",
"private static void addVersionInfo(byte[] grid, int size, int version) {\n // TODO: Zint masks with 0x41 instead of 0x01; which is correct? https://sourceforge.net/p/zint/tickets/110/\n long version_data = QR_ANNEX_D[version - 7];\n for (int i = 0; i < 6; i++) {\n grid[((size - 11) * size) + i] += (version_data >> (i * 3)) & 0x01;\n grid[((size - 10) * size) + i] += (version_data >> ((i * 3) + 1)) & 0x01;\n grid[((size - 9) * size) + i] += (version_data >> ((i * 3) + 2)) & 0x01;\n grid[(i * size) + (size - 11)] += (version_data >> (i * 3)) & 0x01;\n grid[(i * size) + (size - 10)] += (version_data >> ((i * 3) + 1)) & 0x01;\n grid[(i * size) + (size - 9)] += (version_data >> ((i * 3) + 2)) & 0x01;\n }\n }",
"private static CmsUUID toUuid(String uuid) {\n\n if (\"null\".equals(uuid) || CmsStringUtil.isEmpty(uuid)) {\n return null;\n }\n return new CmsUUID(uuid);\n\n }",
"public boolean mapsCell(String cell) {\n return mappers.values().stream().anyMatch(mapper -> mapper.mapsCell(cell));\n }"
] |
Use this API to fetch wisite_farmname_binding resources of given name . | [
"public static wisite_farmname_binding[] get(nitro_service service, String sitepath) throws Exception{\n\t\twisite_farmname_binding obj = new wisite_farmname_binding();\n\t\tobj.set_sitepath(sitepath);\n\t\twisite_farmname_binding response[] = (wisite_farmname_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"protected final Event processEvent() throws IOException {\n while (true) {\n String line;\n try {\n line = readLine();\n } catch (final EOFException ex) {\n if (doneOnce) {\n throw ex;\n }\n doneOnce = true;\n line = \"\";\n }\n\n // If the line is empty (a blank line), Dispatch the event, as defined below.\n if (line.isEmpty()) {\n // If the data buffer is an empty string, set the data buffer and the event name buffer to\n // the empty string and abort these steps.\n if (dataBuffer.length() == 0) {\n eventName = \"\";\n continue;\n }\n\n // If the event name buffer is not the empty string but is also not a valid NCName,\n // set the data buffer and the event name buffer to the empty string and abort these steps.\n // NOT IMPLEMENTED\n\n final Event.Builder eventBuilder = new Event.Builder();\n eventBuilder.withEventName(eventName.isEmpty() ? Event.MESSAGE_EVENT : eventName);\n eventBuilder.withData(dataBuffer.toString());\n\n // Set the data buffer and the event name buffer to the empty string.\n dataBuffer = new StringBuilder();\n eventName = \"\";\n\n return eventBuilder.build();\n // If the line starts with a U+003A COLON character (':')\n } else if (line.startsWith(\":\")) {\n // ignore the line\n // If the line contains a U+003A COLON character (':') character\n } else if (line.contains(\":\")) {\n // Collect the characters on the line before the first U+003A COLON character (':'),\n // and let field be that string.\n final int colonIdx = line.indexOf(\":\");\n final String field = line.substring(0, colonIdx);\n\n // Collect the characters on the line after the first U+003A COLON character (':'),\n // and let value be that string.\n // If value starts with a single U+0020 SPACE character, remove it from value.\n String value = line.substring(colonIdx + 1);\n value = value.startsWith(\" \") ? value.substring(1) : value;\n\n processField(field, value);\n // Otherwise, the string is not empty but does not contain a U+003A COLON character (':')\n // character\n } else {\n processField(line, \"\");\n }\n }\n }",
"private void CalculateMap(IntRange inRange, IntRange outRange, int[] map) {\r\n double k = 0, b = 0;\r\n\r\n if (inRange.getMax() != inRange.getMin()) {\r\n k = (double) (outRange.getMax() - outRange.getMin()) / (double) (inRange.getMax() - inRange.getMin());\r\n b = (double) (outRange.getMin()) - k * inRange.getMin();\r\n }\r\n\r\n for (int i = 0; i < 256; i++) {\r\n int v = (int) i;\r\n\r\n if (v >= inRange.getMax())\r\n v = outRange.getMax();\r\n else if (v <= inRange.getMin())\r\n v = outRange.getMin();\r\n else\r\n v = (int) (k * v + b);\r\n\r\n map[i] = v;\r\n }\r\n }",
"public void reportError(NodeT faulted, Throwable throwable) {\n faulted.setPreparer(true);\n String dependency = faulted.key();\n for (String dependentKey : nodeTable.get(dependency).dependentKeys()) {\n DAGNode<DataT, NodeT> dependent = nodeTable.get(dependentKey);\n dependent.lock().lock();\n try {\n dependent.onFaultedResolution(dependency, throwable);\n if (dependent.hasAllResolved()) {\n queue.add(dependent.key());\n }\n } finally {\n dependent.lock().unlock();\n }\n }\n }",
"public static String getCountryCodeAndCheckDigit(final String iban) {\n return iban.substring(COUNTRY_CODE_INDEX,\n COUNTRY_CODE_INDEX + COUNTRY_CODE_LENGTH + CHECK_DIGIT_LENGTH);\n }",
"public PartialCollection<BoxItem.Info> getChildrenRange(long offset, long limit, String... fields) {\n QueryStringBuilder builder = new QueryStringBuilder()\n .appendParam(\"limit\", limit)\n .appendParam(\"offset\", offset);\n\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields).toString();\n }\n\n URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), builder.toString(), getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n String totalCountString = responseJSON.get(\"total_count\").toString();\n long fullSize = Double.valueOf(totalCountString).longValue();\n PartialCollection<BoxItem.Info> children = new PartialCollection<BoxItem.Info>(offset, limit, fullSize);\n JsonArray jsonArray = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : jsonArray) {\n JsonObject jsonObject = value.asObject();\n BoxItem.Info parsedItemInfo = (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), jsonObject);\n if (parsedItemInfo != null) {\n children.add(parsedItemInfo);\n }\n }\n return children;\n }",
"public List<String> getCorporateGroupIds(final String organizationId) {\n final DbOrganization dbOrganization = getOrganization(organizationId);\n return dbOrganization.getCorporateGroupIdPrefixes();\n }",
"public static void checkRequired(OptionSet options, List<String> opts)\n throws VoldemortException {\n List<String> optCopy = Lists.newArrayList();\n for(String opt: opts) {\n if(options.has(opt)) {\n optCopy.add(opt);\n }\n }\n if(optCopy.size() < 1) {\n System.err.println(\"Please specify one of the following options:\");\n for(String opt: opts) {\n System.err.println(\"--\" + opt);\n }\n Utils.croak(\"Missing required option.\");\n }\n if(optCopy.size() > 1) {\n System.err.println(\"Conflicting options:\");\n for(String opt: optCopy) {\n System.err.println(\"--\" + opt);\n }\n Utils.croak(\"Conflicting options detected.\");\n }\n }",
"public static Class<?> getMapValueFieldType(Field mapField, int nestingLevel) {\n\t\treturn getGenericFieldType(mapField, Map.class, 1, null, nestingLevel);\n\t}",
"public ItemRequest<ProjectStatus> findById(String projectStatus) {\n\n String path = String.format(\"/project_statuses/%s\", projectStatus);\n return new ItemRequest<ProjectStatus>(this, ProjectStatus.class, path, \"GET\");\n }"
] |
Evaluates the body if the current class has at least one member with at least one tag with the specified name.
@param template The body of the block tag
@param attributes The attributes of the template tag
@exception XDocletException Description of Exception
@doc.tag type="block"
@doc.param name="tagName" optional="false" description="The tag name."
@doc.param name="paramName" description="The parameter name. If not specified, then the raw
content of the tag is returned."
@doc.param name="error" description="Show this error message if no tag found." | [
"public void ifHasMemberWithTag(String template, Properties attributes) throws XDocletException\r\n {\r\n ArrayList allMemberNames = new ArrayList();\r\n HashMap allMembers = new HashMap();\r\n boolean hasTag = false;\r\n\r\n addMembers(allMemberNames, allMembers, getCurrentClass(), null, null, null);\r\n for (Iterator it = allMemberNames.iterator(); it.hasNext(); ) {\r\n XMember member = (XMember) allMembers.get(it.next());\r\n\r\n if (member instanceof XField) {\r\n setCurrentField((XField)member);\r\n if (hasTag(attributes, FOR_FIELD)) {\r\n hasTag = true;\r\n }\r\n setCurrentField(null);\r\n }\r\n else if (member instanceof XMethod) {\r\n setCurrentMethod((XMethod)member);\r\n if (hasTag(attributes, FOR_METHOD)) {\r\n hasTag = true;\r\n }\r\n setCurrentMethod(null);\r\n }\r\n if (hasTag) {\r\n generate(template);\r\n break;\r\n }\r\n }\r\n }"
] | [
"public static String getParentId(String digest, String host) throws IOException {\n DockerClient dockerClient = null;\n try {\n dockerClient = getDockerClient(host);\n return dockerClient.inspectImageCmd(digest).exec().getParent();\n } finally {\n closeQuietly(dockerClient);\n }\n }",
"public static String getHeaders(HttpServletResponse response) {\n String headerString = \"\";\n Collection<String> headerNames = response.getHeaderNames();\n for (String headerName : headerNames) {\n // there may be multiple headers per header name\n for (String headerValue : response.getHeaders(headerName)) {\n if (headerString.length() != 0) {\n headerString += \"\\n\";\n }\n\n headerString += headerName + \": \" + headerValue;\n }\n }\n\n return headerString;\n }",
"public static final Date parseDateTime(String value)\n {\n Date result = null;\n\n try\n {\n if (value != null && !value.isEmpty())\n {\n result = DATE_TIME_FORMAT.get().parse(value);\n }\n }\n catch (ParseException ex)\n {\n // Ignore\n }\n\n return result;\n }",
"private void addForward(AnalyticModel model, double fixingTime, RandomVariable forward, boolean isParameter) {\n\t\tdouble interpolationEntitiyTime;\n\t\tRandomVariable interpolationEntityForwardValue;\n\t\tswitch(interpolationEntityForward) {\n\t\tcase FORWARD:\n\t\tdefault:\n\t\t\tinterpolationEntitiyTime = fixingTime;\n\t\t\tinterpolationEntityForwardValue = forward;\n\t\t\tbreak;\n\t\tcase FORWARD_TIMES_DISCOUNTFACTOR:\n\t\t\tinterpolationEntitiyTime = fixingTime;\n\t\t\tinterpolationEntityForwardValue = forward.mult(model.getDiscountCurve(getDiscountCurveName()).getValue(model, fixingTime+getPaymentOffset(fixingTime)));\n\t\t\tbreak;\n\t\tcase ZERO:\n\t\t{\n\t\t\tdouble paymentOffset = getPaymentOffset(fixingTime);\n\t\t\tinterpolationEntitiyTime = fixingTime+paymentOffset;\n\t\t\tinterpolationEntityForwardValue = forward.mult(paymentOffset).add(1.0).log().div(paymentOffset);\n\t\t\tbreak;\n\t\t}\n\t\tcase DISCOUNTFACTOR:\n\t\t{\n\t\t\tdouble paymentOffset = getPaymentOffset(fixingTime);\n\t\t\tinterpolationEntitiyTime\t\t= fixingTime+paymentOffset;\n\t\t\tinterpolationEntityForwardValue = getValue(fixingTime).div(forward.mult(paymentOffset).add(1.0));\n\t\t\tbreak;\n\t\t}\n\t\t}\n\t\tsuper.addPoint(interpolationEntitiyTime, interpolationEntityForwardValue, isParameter);\n\t}",
"private static void checkSensibility(AnnotatedType<?> type) {\n // check if it has a constructor\n if (type.getConstructors().isEmpty() && !type.getJavaClass().isInterface()) {\n MetadataLogger.LOG.noConstructor(type);\n }\n\n Set<Class<?>> hierarchy = new HashSet<Class<?>>();\n for (Class<?> clazz = type.getJavaClass(); clazz != null; clazz = clazz.getSuperclass()) {\n hierarchy.add(clazz);\n hierarchy.addAll(Reflections.getInterfaceClosure(clazz));\n }\n checkMembersBelongToHierarchy(type.getConstructors(), hierarchy, type);\n checkMembersBelongToHierarchy(type.getMethods(), hierarchy, type);\n checkMembersBelongToHierarchy(type.getFields(), hierarchy, type);\n }",
"public int nextToken() throws IOException\n {\n int c;\n int nextc = -1;\n boolean quoted = false;\n int result = m_next;\n if (m_next != 0)\n {\n m_next = 0;\n }\n\n m_buffer.setLength(0);\n\n while (result == 0)\n {\n if (nextc != -1)\n {\n c = nextc;\n nextc = -1;\n }\n else\n {\n c = read();\n }\n\n switch (c)\n {\n case TT_EOF:\n {\n if (m_buffer.length() != 0)\n {\n result = TT_WORD;\n m_next = TT_EOF;\n }\n else\n {\n result = TT_EOF;\n }\n break;\n }\n\n case TT_EOL:\n {\n int length = m_buffer.length();\n\n if (length != 0 && m_buffer.charAt(length - 1) == '\\r')\n {\n --length;\n m_buffer.setLength(length);\n }\n\n if (length == 0)\n {\n result = TT_EOL;\n }\n else\n {\n result = TT_WORD;\n m_next = TT_EOL;\n }\n\n break;\n }\n\n default:\n {\n if (c == m_quote)\n {\n if (quoted == false && startQuotedIsValid(m_buffer))\n {\n quoted = true;\n }\n else\n {\n if (quoted == false)\n {\n m_buffer.append((char) c);\n }\n else\n {\n nextc = read();\n if (nextc == m_quote)\n {\n m_buffer.append((char) c);\n nextc = -1;\n }\n else\n {\n quoted = false;\n }\n }\n }\n }\n else\n {\n if (c == m_delimiter && quoted == false)\n {\n result = TT_WORD;\n }\n else\n {\n m_buffer.append((char) c);\n }\n }\n }\n }\n }\n\n m_type = result;\n\n return (result);\n }",
"public synchronized static SQLiteDatabase getConnection(Context context) {\n\t\tif (database == null) {\n\t\t\t// Construct the single helper and open the unique(!) db connection for the app\n\t\t\tdatabase = new CupboardDbHelper(context.getApplicationContext()).getWritableDatabase();\n\t\t}\n\t\treturn database;\n\t}",
"public boolean unlink(D declaration, ServiceReference<S> declarationBinderRef) {\n S declarationBinder = bindersManager.getDeclarationBinder(declarationBinderRef);\n try {\n declarationBinder.removeDeclaration(declaration);\n } catch (BinderException e) {\n LOG.debug(declarationBinder + \" throw an exception when removing of it the Declaration \"\n + declaration, e);\n declaration.unhandle(declarationBinderRef);\n return false;\n } finally {\n declaration.unbind(declarationBinderRef);\n }\n return true;\n }",
"protected void registerUnregisterJMX(boolean doRegister) {\r\n\t\tif (this.mbs == null ){ // this way makes it easier for mocking.\r\n\t\t\tthis.mbs = ManagementFactory.getPlatformMBeanServer();\r\n\t\t}\r\n\t\ttry {\r\n\t\t\tString suffix = \"\";\r\n\r\n\t\t\tif (this.config.getPoolName()!=null){\r\n\t\t\t\tsuffix=\"-\"+this.config.getPoolName();\r\n\t\t\t}\r\n\r\n\t\t\tObjectName name = new ObjectName(MBEAN_BONECP +suffix);\r\n\t\t\tObjectName configname = new ObjectName(MBEAN_CONFIG + suffix);\r\n\r\n\r\n\t\t\tif (doRegister){\r\n\t\t\t\tif (!this.mbs.isRegistered(name)){\r\n\t\t\t\t\tthis.mbs.registerMBean(this.statistics, name);\r\n\t\t\t\t}\r\n\t\t\t\tif (!this.mbs.isRegistered(configname)){\r\n\t\t\t\t\tthis.mbs.registerMBean(this.config, configname);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tif (this.mbs.isRegistered(name)){\r\n\t\t\t\t\tthis.mbs.unregisterMBean(name);\r\n\t\t\t\t}\r\n\t\t\t\tif (this.mbs.isRegistered(configname)){\r\n\t\t\t\t\tthis.mbs.unregisterMBean(configname);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} catch (Exception e) {\r\n\t\t\tlogger.error(\"Unable to start/stop JMX\", e);\r\n\t\t}\r\n\t}"
] |
Normalizes the matrix such that the Frobenius norm is equal to one.
@param A The matrix that is to be normalized. | [
"public static void normalizeF( DMatrixRMaj A ) {\n double val = normF(A);\n\n if( val == 0 )\n return;\n\n int size = A.getNumElements();\n\n for( int i = 0; i < size; i++) {\n A.div(i , val);\n }\n }"
] | [
"void resolveBootUpdates(final ModelController controller, final ActiveOperation.CompletedCallback<ModelNode> callback) throws Exception {\n connection.openConnection(controller, callback);\n // Keep a reference to the the controller\n this.controller = controller;\n }",
"public static double[][] invert(double[][] matrix) {\n\n\t\tif(isSolverUseApacheCommonsMath) {\n\t\t\t// Use LU from common math\n\t\t\tLUDecomposition lu = new LUDecomposition(new Array2DRowRealMatrix(matrix));\n\t\t\tdouble[][] matrixInverse = lu.getSolver().getInverse().getData();\n\n\t\t\treturn matrixInverse;\n\t\t}\n\t\telse {\n\t\t\treturn org.jblas.Solve.pinv(new org.jblas.DoubleMatrix(matrix)).toArray2();\n\t\t}\n\t}",
"private void registerPackageInTypeInterestFactory(String pkg)\n {\n TypeInterestFactory.registerInterest(pkg + \"_pkg\", pkg.replace(\".\", \"\\\\.\"), pkg, TypeReferenceLocation.IMPORT);\n // TODO: Finish the implementation\n }",
"public Object invokeMethod(String name, Object args) {\n Object val = null;\n if (args != null && Object[].class.isAssignableFrom(args.getClass())) {\n Object[] arr = (Object[]) args;\n\n if (arr.length == 1) {\n val = arr[0];\n } else if (arr.length == 2 && arr[0] instanceof Collection && arr[1] instanceof Closure) {\n Closure<?> closure = (Closure<?>) arr[1];\n Iterator<?> iterator = ((Collection) arr[0]).iterator();\n List<Object> list = new ArrayList<Object>();\n while (iterator.hasNext()) {\n list.add(curryDelegateAndGetContent(closure, iterator.next()));\n }\n val = list;\n } else {\n val = Arrays.asList(arr);\n }\n }\n content.put(name, val);\n\n return val;\n }",
"public void readData(BufferedReader in) throws IOException {\r\n String line, value;\r\n // skip old variables if still present\r\n lexOptions.readData(in);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n try {\r\n tlpParams = (TreebankLangParserParams) Class.forName(value).newInstance();\r\n } catch (Exception e) {\r\n IOException ioe = new IOException(\"Problem instantiating parserParams: \" + line);\r\n ioe.initCause(e);\r\n throw ioe;\r\n }\r\n line = in.readLine();\r\n // ensure backwards compatibility\r\n if (line.matches(\"^forceCNF.*\")) {\r\n value = line.substring(line.indexOf(' ') + 1);\r\n forceCNF = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n }\r\n value = line.substring(line.indexOf(' ') + 1);\r\n doPCFG = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n doDep = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n freeDependencies = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n directional = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n genStop = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n distance = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n coarseDistance = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n value = line.substring(line.indexOf(' ') + 1);\r\n dcTags = Boolean.parseBoolean(value);\r\n line = in.readLine();\r\n if ( ! line.matches(\"^nPrune.*\")) {\r\n throw new RuntimeException(\"Expected nPrune, found: \" + line);\r\n }\r\n value = line.substring(line.indexOf(' ') + 1);\r\n nodePrune = Boolean.parseBoolean(value);\r\n line = in.readLine(); // get rid of last line\r\n if (line.length() != 0) {\r\n throw new RuntimeException(\"Expected blank line, found: \" + line);\r\n }\r\n }",
"public void deleteById(Object id) {\n\n int count = beginDelete().whereEquals(idColumn.getColumnName(), id).delete();\n\n if (count == 0) {\n throw new RowNotFoundException(table, id);\n }\n }",
"public void clearAnnotationData(Class<? extends Annotation> annotationClass) {\n stereotypes.invalidate(annotationClass);\n scopes.invalidate(annotationClass);\n qualifiers.invalidate(annotationClass);\n interceptorBindings.invalidate(annotationClass);\n }",
"public ParallelTask execute(ParallecResponseHandler handler) {\n\n ParallelTask task = new ParallelTask();\n\n try {\n targetHostMeta = new TargetHostMeta(targetHosts);\n\n final ParallelTask taskReal = new ParallelTask(requestProtocol,\n concurrency, httpMeta, targetHostMeta, sshMeta, tcpMeta, udpMeta, pingMeta,\n handler, responseContext, \n replacementVarMapNodeSpecific, replacementVarMap,\n requestReplacementType, \n config);\n\n task = taskReal;\n\n logger.info(\"***********START_PARALLEL_HTTP_TASK_\"\n + task.getTaskId() + \"***********\");\n\n // throws ParallelTaskInvalidException\n task.validateWithFillDefault();\n\n task.setSubmitTime(System.currentTimeMillis());\n\n if (task.getConfig().isEnableCapacityAwareTaskScheduler()) {\n\n //late initialize the task scheduler\n ParallelTaskManager.getInstance().initTaskSchedulerIfNot();\n // add task to the wait queue\n ParallelTaskManager.getInstance().getWaitQ().add(task);\n\n logger.info(\"Enabled CapacityAwareTaskScheduler. Submitted task to waitQ in builder.. \"\n + task.getTaskId());\n\n } else {\n\n logger.info(\n \"Disabled CapacityAwareTaskScheduler. Immediately execute task {} \",\n task.getTaskId());\n\n Runnable director = new Runnable() {\n\n public void run() {\n ParallelTaskManager.getInstance()\n .generateUpdateExecuteTask(taskReal);\n }\n };\n new Thread(director).start();\n }\n\n if (this.getMode() == TaskRunMode.SYNC) {\n logger.info(\"Executing task {} in SYNC mode... \",\n task.getTaskId());\n\n while (task != null && !task.isCompleted()) {\n try {\n Thread.sleep(500L);\n } catch (InterruptedException e) {\n logger.error(\"InterruptedException \" + e);\n }\n }\n }\n } catch (ParallelTaskInvalidException ex) {\n\n logger.info(\"Request is invalid with missing parts. Details: \"\n + ex.getMessage() + \" Cannot execute at this time. \"\n + \" Please review your request and try again.\\nCommand:\"\n + httpMeta.toString());\n\n task.setState(ParallelTaskState.COMPLETED_WITH_ERROR);\n task.getTaskErrorMetas().add(\n new TaskErrorMeta(TaskErrorType.VALIDATION_ERROR,\n \"validation eror\"));\n\n } catch (Exception t) {\n logger.error(\"fail task builder. Unknown error: \" + t, t);\n task.setState(ParallelTaskState.COMPLETED_WITH_ERROR);\n task.getTaskErrorMetas().add(\n new TaskErrorMeta(TaskErrorType.UNKNOWN, \"unknown eror\",\n t));\n }\n\n logger.info(\"***********FINISH_PARALLEL_HTTP_TASK_\" + task.getTaskId()\n + \"***********\");\n return task;\n\n }",
"public static base_response update(nitro_service client, callhome resource) throws Exception {\n\t\tcallhome updateresource = new callhome();\n\t\tupdateresource.emailaddress = resource.emailaddress;\n\t\tupdateresource.proxymode = resource.proxymode;\n\t\tupdateresource.ipaddress = resource.ipaddress;\n\t\tupdateresource.port = resource.port;\n\t\treturn updateresource.update_resource(client);\n\t}"
] |
performs a primary key lookup operation against RDBMS and materializes
an object from the resulting row. Only skalar attributes are filled from
the row, references are not resolved.
@param oid contains the primary key info.
@param cld ClassDescriptor providing mapping information.
@return the materialized object, null if no matching row was found or if
any error occured. | [
"public Object materializeObject(ClassDescriptor cld, Identity oid)\r\n throws PersistenceBrokerException\r\n {\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n final SelectStatement sql = broker.serviceSqlGenerator().getPreparedSelectByPkStatement(cld);\r\n Object result = null;\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n try\r\n {\r\n stmt = sm.getSelectByPKStatement(cld);\r\n if (stmt == null)\r\n {\r\n logger.error(\"getSelectByPKStatement returned a null statement\");\r\n throw new PersistenceBrokerException(\"getSelectByPKStatement returned a null statement\");\r\n }\r\n /*\r\n arminw: currently a select by PK could never be a stored procedure,\r\n thus we can always set 'false'. Is this correct??\r\n */\r\n sm.bindSelect(stmt, oid, cld, false);\r\n rs = stmt.executeQuery();\r\n // data available read object, else return null\r\n ResultSetAndStatement rs_stmt = new ResultSetAndStatement(broker.serviceStatementManager(), stmt, rs, sql);\r\n if (rs.next())\r\n {\r\n Map row = new HashMap();\r\n cld.getRowReader().readObjectArrayFrom(rs_stmt, row);\r\n result = cld.getRowReader().readObjectFrom(row);\r\n }\r\n // close resources\r\n rs_stmt.close();\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n logger.error(\"PersistenceBrokerException during the execution of materializeObject: \" + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n throw ExceptionHelper.generateException(e, sql.getStatement(), cld, logger, null);\r\n }\r\n return result;\r\n }"
] | [
"public static Boolean assertFalse(Boolean value, String message) {\n if (Boolean.valueOf(value))\n throw new IllegalArgumentException(message);\n return value;\n }",
"private void readRelationships(Document cdp)\n {\n for (Link link : cdp.getLinks().getLink())\n {\n readRelationship(link);\n }\n }",
"public String putProperty(String key,\n String value) {\n return this.getProperties().put(key,\n value);\n }",
"public void setTileUrls(List<String> tileUrls) {\n\t\tthis.tileUrls = tileUrls;\n\t\tif (null != urlStrategy) {\n\t\t\turlStrategy.setUrls(tileUrls);\n\t\t}\n\t}",
"private <T> MongoCollection<T> getLocalCollection(\n final MongoNamespace namespace,\n final Class<T> resultClass,\n final CodecRegistry codecRegistry\n ) {\n return localClient\n .getDatabase(String.format(\"sync_user_%s\", namespace.getDatabaseName()))\n .getCollection(namespace.getCollectionName(), resultClass)\n .withCodecRegistry(codecRegistry);\n }",
"public static base_responses enable(nitro_service client, String acl6name[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (acl6name != null && acl6name.length > 0) {\n\t\t\tnsacl6 enableresources[] = new nsacl6[acl6name.length];\n\t\t\tfor (int i=0;i<acl6name.length;i++){\n\t\t\t\tenableresources[i] = new nsacl6();\n\t\t\t\tenableresources[i].acl6name = acl6name[i];\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, enableresources,\"enable\");\n\t\t}\n\t\treturn result;\n\t}",
"public static boolean pullImage(Launcher launcher, final String imageTag, final String username, final String password, final String host)\n throws IOException, InterruptedException {\n\n return launcher.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() {\n public Boolean call() throws IOException {\n DockerUtils.pullImage(imageTag, username, password, host);\n return true;\n }\n });\n }",
"@JsonIgnore\n public void setUnknownFields(final Map<String,Object> unknownFields) {\n this.unknownFields.clear();\n this.unknownFields.putAll(unknownFields);\n }",
"protected synchronized StealerBasedRebalanceTask scheduleNextTask(boolean executeService) {\n // Make sure there is work left to do.\n if(doneSignal.getCount() == 0) {\n logger.info(\"All tasks completion signaled... returning\");\n\n return null;\n }\n // Limit number of tasks outstanding.\n if(this.numTasksExecuting >= maxParallelRebalancing) {\n logger.info(\"Executing more tasks than [\" + this.numTasksExecuting\n + \"] the parallel allowed \" + maxParallelRebalancing);\n return null;\n }\n // Shuffle list of stealer IDs each time a new task to schedule needs to\n // be found. Randomizing the order should avoid prioritizing one\n // specific stealer's work ahead of all others.\n List<Integer> stealerIds = new ArrayList<Integer>(tasksByStealer.keySet());\n Collections.shuffle(stealerIds);\n for(int stealerId: stealerIds) {\n if(nodeIdsWithWork.contains(stealerId)) {\n logger.info(\"Stealer \" + stealerId + \" is already working... continuing\");\n continue;\n }\n\n for(StealerBasedRebalanceTask sbTask: tasksByStealer.get(stealerId)) {\n int donorId = sbTask.getStealInfos().get(0).getDonorId();\n if(nodeIdsWithWork.contains(donorId)) {\n logger.info(\"Stealer \" + stealerId + \" Donor \" + donorId\n + \" is already working... continuing\");\n continue;\n }\n // Book keeping\n addNodesToWorkerList(Arrays.asList(stealerId, donorId));\n numTasksExecuting++;\n // Remove this task from list thus destroying list being\n // iterated over. This is safe because returning directly out of\n // this branch.\n tasksByStealer.get(stealerId).remove(sbTask);\n try {\n if(executeService) {\n logger.info(\"Stealer \" + stealerId + \" Donor \" + donorId\n + \" going to schedule work\");\n service.execute(sbTask);\n }\n } catch(RejectedExecutionException ree) {\n logger.error(\"Stealer \" + stealerId\n + \"Rebalancing task rejected by executor service.\", ree);\n throw new VoldemortRebalancingException(\"Stealer \"\n + stealerId\n + \"Rebalancing task rejected by executor service.\");\n }\n return sbTask;\n }\n }\n printRemainingTasks(stealerIds);\n return null;\n }"
] |
Returns the value of the indicated property of the current object on the specified level.
@param level The level
@param name The name of the property
@return The property value | [
"private String getPropertyValue(String level, String name)\r\n {\r\n return getDefForLevel(level).getProperty(name);\r\n }"
] | [
"private String getProjectName() {\n String pName = Strings.emptyToNull(projectName);\n if (pName == null) { \n pName = Strings.emptyToNull(junit4.getProject().getName());\n }\n if (pName == null) {\n pName = \"(unnamed project)\"; \n }\n return pName;\n }",
"private void addIndex(IndexDescriptorDef indexDescDef, TableDef tableDef)\r\n {\r\n IndexDef indexDef = tableDef.getIndex(indexDescDef.getName());\r\n\r\n if (indexDef == null)\r\n {\r\n indexDef = new IndexDef(indexDescDef.getName(),\r\n indexDescDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_UNIQUE, false));\r\n tableDef.addIndex(indexDef);\r\n }\r\n\r\n try\r\n {\r\n String fieldNames = indexDescDef.getProperty(PropertyHelper.OJB_PROPERTY_FIELDS);\r\n ArrayList fields = ((ClassDescriptorDef)indexDescDef.getOwner()).getFields(fieldNames);\r\n FieldDescriptorDef fieldDef;\r\n\r\n for (Iterator it = fields.iterator(); it.hasNext();)\r\n {\r\n fieldDef = (FieldDescriptorDef)it.next();\r\n indexDef.addColumn(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN));\r\n }\r\n }\r\n catch (NoSuchFieldException ex)\r\n {\r\n // won't happen if we already checked the constraints\r\n }\r\n }",
"public static Method[] getUniqueDeclaredMethods(Class<?> leafClass) throws IllegalArgumentException {\n final List<Method> methods = new ArrayList<Method>(32);\n doWithMethods(leafClass, new MethodCallback() {\n @Override\n public void doWith(Method method) {\n boolean knownSignature = false;\n Method methodBeingOverriddenWithCovariantReturnType = null;\n for (Method existingMethod : methods) {\n if (method.getName().equals(existingMethod.getName()) &&\n Arrays.equals(method.getParameterTypes(), existingMethod.getParameterTypes())) {\n // Is this a covariant return type situation?\n if (existingMethod.getReturnType() != method.getReturnType() &&\n existingMethod.getReturnType().isAssignableFrom(method.getReturnType())) {\n methodBeingOverriddenWithCovariantReturnType = existingMethod;\n } else {\n knownSignature = true;\n }\n break;\n }\n }\n if (methodBeingOverriddenWithCovariantReturnType != null) {\n methods.remove(methodBeingOverriddenWithCovariantReturnType);\n }\n if (!knownSignature) {\n methods.add(method);\n }\n }\n });\n return methods.toArray(new Method[methods.size()]);\n }",
"public void recordPutTimeAndSize(long timeNS, long valueSize, long keySize) {\n recordTime(Tracked.PUT, timeNS, 0, valueSize, keySize, 0);\n }",
"public static scpolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tscpolicy_stats obj = new scpolicy_stats();\n\t\tobj.set_name(name);\n\t\tscpolicy_stats response = (scpolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"private void updateScaling() {\n\n List<I_CmsTransform> transforms = new ArrayList<>();\n CmsCroppingParamBean crop = m_croppingProvider.get();\n CmsImageInfoBean info = m_imageInfoProvider.get();\n\n double wv = m_image.getElement().getParentElement().getOffsetWidth();\n double hv = m_image.getElement().getParentElement().getOffsetHeight();\n if (crop == null) {\n transforms.add(\n new CmsBoxFit(CmsBoxFit.Mode.scaleOnlyIfNecessary, wv, hv, info.getWidth(), info.getHeight()));\n } else {\n int wt, ht;\n wt = crop.getTargetWidth() >= 0 ? crop.getTargetWidth() : info.getWidth();\n ht = crop.getTargetHeight() >= 0 ? crop.getTargetHeight() : info.getHeight();\n transforms.add(new CmsBoxFit(CmsBoxFit.Mode.scaleOnlyIfNecessary, wv, hv, wt, ht));\n if (crop.isCropped()) {\n transforms.add(\n new CmsBoxFit(CmsBoxFit.Mode.scaleAlways, wt, ht, crop.getCropWidth(), crop.getCropHeight()));\n transforms.add(new CmsTranslate(crop.getCropX(), crop.getCropY()));\n } else {\n transforms.add(\n new CmsBoxFit(CmsBoxFit.Mode.scaleAlways, wt, ht, crop.getOrgWidth(), crop.getOrgHeight()));\n }\n }\n CmsCompositeTransform chain = new CmsCompositeTransform(transforms);\n m_coordinateTransform = chain;\n if ((crop == null) || !crop.isCropped()) {\n m_region = transformRegionBack(\n m_coordinateTransform,\n CmsRectangle.fromLeftTopWidthHeight(0, 0, info.getWidth(), info.getHeight()));\n } else {\n m_region = transformRegionBack(\n m_coordinateTransform,\n CmsRectangle.fromLeftTopWidthHeight(\n crop.getCropX(),\n crop.getCropY(),\n crop.getCropWidth(),\n crop.getCropHeight()));\n }\n }",
"private boolean isSecuredByProperty(Server server) {\n boolean isSecured = false;\n Object value = server.getEndpoint().get(\"org.talend.tesb.endpoint.secured\"); //Property name TBD\n\n if (value instanceof String) {\n try {\n isSecured = Boolean.valueOf((String) value);\n } catch (Exception ex) {\n }\n }\n\n return isSecured;\n }",
"public void declareInternalData(int maxRows, int maxCols) {\n this.maxRows = maxRows;\n this.maxCols = maxCols;\n\n U_tran = new DMatrixRMaj(maxRows,maxRows);\n Qm = new DMatrixRMaj(maxRows,maxRows);\n\n r_row = new double[ maxCols ];\n }",
"public static MethodNode findSAM(ClassNode type) {\n if (!Modifier.isAbstract(type.getModifiers())) return null;\n if (type.isInterface()) {\n List<MethodNode> methods = type.getMethods();\n MethodNode found=null;\n for (MethodNode mi : methods) {\n // ignore methods, that are not abstract and from Object\n if (!Modifier.isAbstract(mi.getModifiers())) continue;\n // ignore trait methods which have a default implementation\n if (Traits.hasDefaultImplementation(mi)) continue;\n if (mi.getDeclaringClass().equals(OBJECT_TYPE)) continue;\n if (OBJECT_TYPE.getDeclaredMethod(mi.getName(), mi.getParameters())!=null) continue;\n\n // we have two methods, so no SAM\n if (found!=null) return null;\n found = mi;\n }\n return found;\n\n } else {\n\n List<MethodNode> methods = type.getAbstractMethods();\n MethodNode found = null;\n if (methods!=null) {\n for (MethodNode mi : methods) {\n if (!hasUsableImplementation(type, mi)) {\n if (found!=null) return null;\n found = mi;\n }\n }\n }\n return found;\n }\n }"
] |
Sets the distance from the origin to the near clipping plane for the
whole camera rig.
@param near
Distance to the near clipping plane. | [
"public void setNearClippingDistance(float near) {\n if(leftCamera instanceof GVRCameraClippingDistanceInterface &&\n centerCamera instanceof GVRCameraClippingDistanceInterface &&\n rightCamera instanceof GVRCameraClippingDistanceInterface) {\n ((GVRCameraClippingDistanceInterface)leftCamera).setNearClippingDistance(near);\n centerCamera.setNearClippingDistance(near);\n ((GVRCameraClippingDistanceInterface)rightCamera).setNearClippingDistance(near);\n }\n }"
] | [
"public void clearSelections() {\n for (CheckableViewHolder vh : mCheckedVisibleViewHolders) {\n vh.checkbox.setChecked(false);\n }\n mCheckedVisibleViewHolders.clear();\n mCheckedItems.clear();\n }",
"public Task<Void> registerWithEmail(@NonNull final String email, @NonNull final String password) {\n return dispatcher.dispatchTask(\n new Callable<Void>() {\n @Override\n public Void call() {\n registerWithEmailInternal(email, password);\n return null;\n }\n });\n }",
"private ResourceReport getResourceReport(TwillController controller, int maxWaitMs) {\n ResourceReport report = controller.getResourceReport();\n int elapsed = 0;\n while (report == null) {\n report = controller.getResourceReport();\n try {\n Thread.sleep(500);\n } catch (InterruptedException e) {\n throw new IllegalStateException(e);\n }\n elapsed += 500;\n if ((maxWaitMs != -1) && (elapsed > maxWaitMs)) {\n String msg = String.format(\"Exceeded max wait time to retrieve ResourceReport from Twill.\"\n + \" Elapsed time = %s ms\", elapsed);\n log.error(msg);\n throw new IllegalStateException(msg);\n }\n if ((elapsed % 10000) == 0) {\n log.info(\"Waiting for ResourceReport from Twill. Elapsed time = {} ms\", elapsed);\n }\n }\n return report;\n }",
"@Override\n public void init(NamedList args) {\n\n Object regex = args.remove(PARAM_REGEX);\n if (null == regex) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_REGEX);\n }\n try {\n m_regex = Pattern.compile(regex.toString());\n } catch (PatternSyntaxException e) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Invalid regex: \" + regex, e);\n }\n\n Object replacement = args.remove(PARAM_REPLACEMENT);\n if (null == replacement) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_REPLACEMENT);\n }\n m_replacement = replacement.toString();\n\n Object source = args.remove(PARAM_SOURCE);\n if (null == source) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_SOURCE);\n }\n m_source = source.toString();\n\n Object target = args.remove(PARAM_TARGET);\n if (null == target) {\n throw new SolrException(ErrorCode.SERVER_ERROR, \"Missing required init parameter: \" + PARAM_TARGET);\n }\n m_target = target.toString();\n\n }",
"synchronized boolean doReConnect() throws IOException {\n\n // In case we are still connected, test the connection and see if we can reuse it\n if(connectionManager.isConnected()) {\n try {\n final Future<Long> result = channelHandler.executeRequest(ManagementPingRequest.INSTANCE, null).getResult();\n result.get(15, TimeUnit.SECONDS); // Hmm, perhaps 15 is already too much\n return true;\n } catch (Exception e) {\n ServerLogger.AS_ROOT_LOGGER.debugf(e, \"failed to ping the host-controller, going to reconnect\");\n }\n // Disconnect - the HC might have closed the connection without us noticing and is asking for a reconnect\n final Connection connection = connectionManager.getConnection();\n StreamUtils.safeClose(connection);\n if(connection != null) {\n try {\n // Wait for the connection to be closed\n connection.awaitClosed();\n } catch (InterruptedException e) {\n throw new InterruptedIOException();\n }\n }\n }\n\n boolean ok = false;\n final Connection connection = connectionManager.connect();\n try {\n // Reconnect to the host-controller\n final ActiveOperation<Boolean, Void> result = channelHandler.executeRequest(new ServerReconnectRequest(), null);\n try {\n boolean inSync = result.getResult().get();\n ok = true;\n reconnectRunner = null;\n return inSync;\n } catch (ExecutionException e) {\n throw new IOException(e);\n } catch (InterruptedException e) {\n throw new InterruptedIOException();\n }\n } finally {\n if(!ok) {\n StreamUtils.safeClose(connection);\n }\n }\n }",
"public AbstractVolatilitySurfaceParametric getCloneCalibrated(final AnalyticModel calibrationModel, final Vector<AnalyticProduct> calibrationProducts, final List<Double> calibrationTargetValues, Map<String,Object> calibrationParameters, final ParameterTransformation parameterTransformation, OptimizerFactory optimizerFactory) throws SolverException {\n\t\tif(calibrationParameters == null) {\n\t\t\tcalibrationParameters = new HashMap<>();\n\t\t}\n\t\tInteger maxIterationsParameter\t= (Integer)calibrationParameters.get(\"maxIterations\");\n\t\tDouble\taccuracyParameter\t\t= (Double)calibrationParameters.get(\"accuracy\");\n\t\tDouble\tevaluationTimeParameter\t\t= (Double)calibrationParameters.get(\"evaluationTime\");\n\n\t\t// @TODO currently ignored, we use the setting form the OptimizerFactory\n\t\tint maxIterations\t\t= maxIterationsParameter != null ? maxIterationsParameter.intValue() : 600;\n\t\tdouble accuracy\t\t\t= accuracyParameter != null ? accuracyParameter.doubleValue() : 1E-8;\n\t\tdouble evaluationTime\t= evaluationTimeParameter != null ? evaluationTimeParameter.doubleValue() : 0.0;\n\n\t\tAnalyticModel model = calibrationModel.addVolatilitySurfaces(this);\n\t\tSolver solver = new Solver(model, calibrationProducts, calibrationTargetValues, parameterTransformation, evaluationTime, optimizerFactory);\n\n\t\tSet<ParameterObject> objectsToCalibrate = new HashSet<>();\n\t\tobjectsToCalibrate.add(this);\n\t\tAnalyticModel modelCalibrated = solver.getCalibratedModel(objectsToCalibrate);\n\n\t\t// Diagnostic output\n\t\tif (logger.isLoggable(Level.FINE)) {\n\t\t\tdouble lastAccuracy\t\t= solver.getAccuracy();\n\t\t\tint \tlastIterations\t= solver.getIterations();\n\n\t\t\tlogger.fine(\"The solver achieved an accuracy of \" + lastAccuracy + \" in \" + lastIterations + \".\");\n\t\t}\n\n\t\treturn (AbstractVolatilitySurfaceParametric)modelCalibrated.getVolatilitySurface(this.getName());\n\t}",
"public static void main(String[] args) {\n DirectoryIterator iter = new DirectoryIterator(args);\n while(iter.hasNext())\n System.out.println(iter.next().getAbsolutePath());\n }",
"public static String join(Collection<String> s, String delimiter) {\r\n return join(s, delimiter, false);\r\n }",
"protected void consumeChar(ImapRequestLineReader request, char expected)\n throws ProtocolException {\n char consumed = request.consume();\n if (consumed != expected) {\n throw new ProtocolException(\"Expected:'\" + expected + \"' found:'\" + consumed + '\\'');\n }\n }"
] |
Use this API to fetch all the responderpolicy resources that are configured on netscaler. | [
"public static responderpolicy[] get(nitro_service service) throws Exception{\n\t\tresponderpolicy obj = new responderpolicy();\n\t\tresponderpolicy[] response = (responderpolicy[])obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"public Set<RateType> getRateTypes() {\n @SuppressWarnings(\"unchecked\")\n Set<RateType> rateSet = get(KEY_RATE_TYPES, Set.class);\n if (rateSet == null) {\n return Collections.emptySet();\n }\n return Collections.unmodifiableSet(rateSet);\n }",
"private JSONObject getConvertedResponseAsJson(SpellCheckResponse response) {\n\n if (null == response) {\n return null;\n }\n\n final JSONObject suggestions = new JSONObject();\n final Map<String, Suggestion> solrSuggestions = response.getSuggestionMap();\n\n // Add suggestions to the response\n for (final String key : solrSuggestions.keySet()) {\n\n // Indicator to ignore words that are erroneously marked as misspelled.\n boolean ignoreWord = false;\n\n // Suggestions that are in the form \"Xxxx\" -> \"xxxx\" should be ignored.\n if (Character.isUpperCase(key.codePointAt(0))) {\n final String lowercaseKey = key.toLowerCase();\n // If the suggestion map doesn't contain the lowercased word, ignore this entry.\n if (!solrSuggestions.containsKey(lowercaseKey)) {\n ignoreWord = true;\n }\n }\n\n if (!ignoreWord) {\n try {\n // Get suggestions as List\n final List<String> l = solrSuggestions.get(key).getAlternatives();\n suggestions.put(key, l);\n } catch (JSONException e) {\n LOG.debug(\"Exception while converting Solr spellcheckresponse to JSON. \", e);\n }\n }\n }\n\n return suggestions;\n }",
"public static <T extends Spin<?>> T S(Object input, DataFormat<T> format) {\n return SpinFactory.INSTANCE.createSpin(input, format);\n }",
"public OAuth1RequestToken exchangeAuthToken(String authToken) throws FlickrException {\r\n\r\n // Use TreeMap so keys are automatically sorted alphabetically\r\n Map<String, String> parameters = new TreeMap<String, String>();\r\n parameters.put(\"method\", METHOD_EXCHANGE_TOKEN);\r\n parameters.put(Flickr.API_KEY, apiKey);\r\n // This method call must be signed using Flickr (not OAuth) style signing\r\n parameters.put(\"api_sig\", getSignature(sharedSecret, parameters));\r\n\r\n Response response = transportAPI.getNonOAuth(transportAPI.getPath(), parameters);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n OAuth1RequestToken accessToken = constructToken(response);\r\n\r\n return accessToken;\r\n }",
"private void writeResources()\n {\n for (Resource resource : m_projectFile.getResources())\n {\n if (resource.getUniqueID().intValue() != 0)\n {\n writeResource(resource);\n }\n }\n }",
"public static Type getArrayComponentType(Type type) {\n if (type instanceof GenericArrayType) {\n return GenericArrayType.class.cast(type).getGenericComponentType();\n }\n if (type instanceof Class<?>) {\n Class<?> clazz = (Class<?>) type;\n if (clazz.isArray()) {\n return clazz.getComponentType();\n }\n }\n throw new IllegalArgumentException(\"Not an array type \" + type);\n }",
"public ItemRequest<Task> removeFollowers(String task) {\n \n String path = String.format(\"/tasks/%s/removeFollowers\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }",
"public int checkIn() {\n\n try {\n synchronized (STATIC_LOCK) {\n m_logStream = new PrintStream(new FileOutputStream(DEFAULT_LOGFILE_PATH, false));\n CmsObject cms = getCmsObject();\n if (cms != null) {\n return checkInInternal();\n } else {\n m_logStream.println(\"No CmsObject given. Did you call init() first?\");\n return -1;\n }\n }\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n return -2;\n }\n }",
"protected int countedSize() throws PersistenceBrokerException\r\n {\r\n Query countQuery = getBroker().serviceBrokerHelper().getCountQuery(getQueryObject().getQuery());\r\n ResultSetAndStatement rsStmt;\r\n ClassDescriptor cld = getQueryObject().getClassDescriptor();\r\n int count = 0;\r\n\r\n // BRJ: do not use broker.getCount() because it's extent-aware\r\n // the count we need here must not include extents !\r\n if (countQuery instanceof QueryBySQL)\r\n {\r\n String countSql = ((QueryBySQL) countQuery).getSql();\r\n rsStmt = getBroker().serviceJdbcAccess().executeSQL(countSql, cld, Query.NOT_SCROLLABLE);\r\n }\r\n else\r\n {\r\n rsStmt = getBroker().serviceJdbcAccess().executeQuery(countQuery, cld);\r\n }\r\n\r\n try\r\n {\r\n if (rsStmt.m_rs.next())\r\n {\r\n count = rsStmt.m_rs.getInt(1);\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PersistenceBrokerException(e);\r\n }\r\n finally\r\n {\r\n rsStmt.close();\r\n }\r\n\r\n return count;\r\n }"
] |
returns null if no device is found. | [
"private GVRCursorController getUniqueControllerId(int deviceId) {\n GVRCursorController controller = controllerIds.get(deviceId);\n if (controller != null) {\n return controller;\n }\n return null;\n }"
] | [
"private static JsonRtn appendErrorHumanMsg(JsonRtn jsonRtn) {\n if (bundle == null || jsonRtn == null || StringUtils.isEmpty(jsonRtn.getErrCode())) {\n return null;\n }\n\n try {\n jsonRtn.setErrHumanMsg(bundle.getString(jsonRtn.getErrCode()));\n return jsonRtn;\n } catch (Exception e) {\n return null;\n }\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void pushInstallReferrer(Intent intent) {\n try {\n final Bundle extras = intent.getExtras();\n // Preliminary checks\n if (extras == null || !extras.containsKey(\"referrer\")) {\n return;\n }\n final String url;\n try {\n url = URLDecoder.decode(extras.getString(\"referrer\"), \"UTF-8\");\n\n getConfigLogger().verbose(getAccountId(), \"Referrer received: \" + url);\n } catch (Throwable e) {\n // Could not decode\n return;\n }\n if (url == null) {\n return;\n }\n int now = (int) (System.currentTimeMillis() / 1000);\n\n if (installReferrerMap.containsKey(url) && now - installReferrerMap.get(url) < 10) {\n getConfigLogger().verbose(getAccountId(),\"Skipping install referrer due to duplicate within 10 seconds\");\n return;\n }\n\n installReferrerMap.put(url, now);\n\n Uri uri = Uri.parse(\"wzrk://track?install=true&\" + url);\n\n pushDeepLink(uri, true);\n } catch (Throwable t) {\n // no-op\n }\n }",
"@Nonnull\n public final Style getDefaultStyle(@Nonnull final String geometryType) {\n String normalizedGeomName = GEOMETRY_NAME_ALIASES.get(geometryType.toLowerCase());\n if (normalizedGeomName == null) {\n normalizedGeomName = geometryType.toLowerCase();\n }\n Style style = this.defaultStyle.get(normalizedGeomName.toLowerCase());\n if (style == null) {\n style = this.namedStyles.get(normalizedGeomName.toLowerCase());\n }\n\n if (style == null) {\n StyleBuilder builder = new StyleBuilder();\n final Symbolizer symbolizer;\n if (isPointType(normalizedGeomName)) {\n symbolizer = builder.createPointSymbolizer();\n } else if (isLineType(normalizedGeomName)) {\n symbolizer = builder.createLineSymbolizer(Color.black, 2);\n } else if (isPolygonType(normalizedGeomName)) {\n symbolizer = builder.createPolygonSymbolizer(Color.lightGray, Color.black, 2);\n } else if (normalizedGeomName.equalsIgnoreCase(Constants.Style.Raster.NAME)) {\n symbolizer = builder.createRasterSymbolizer();\n } else if (normalizedGeomName.startsWith(Constants.Style.OverviewMap.NAME)) {\n symbolizer = createMapOverviewStyle(normalizedGeomName, builder);\n } else {\n final Style geomStyle = this.defaultStyle.get(Geometry.class.getSimpleName().toLowerCase());\n if (geomStyle != null) {\n return geomStyle;\n } else {\n symbolizer = builder.createPointSymbolizer();\n }\n }\n style = builder.createStyle(symbolizer);\n }\n return style;\n }",
"public void build(Point3d[] points, int nump) throws IllegalArgumentException {\n if (nump < 4) {\n throw new IllegalArgumentException(\"Less than four input points specified\");\n }\n if (points.length < nump) {\n throw new IllegalArgumentException(\"Point array too small for specified number of points\");\n }\n initBuffers(nump);\n setPoints(points, nump);\n buildHull();\n }",
"public void convertToDense() {\n switch ( mat.getType() ) {\n case DSCC: {\n DMatrix m = new DMatrixRMaj(mat.getNumRows(), mat.getNumCols());\n ConvertDMatrixStruct.convert((DMatrix) mat, m);\n setMatrix(m);\n } break;\n case FSCC: {\n FMatrix m = new FMatrixRMaj(mat.getNumRows(), mat.getNumCols());\n ConvertFMatrixStruct.convert((FMatrix) mat, m);\n setMatrix(m);\n } break;\n case DDRM:\n case FDRM:\n case ZDRM:\n case CDRM:\n break;\n default:\n throw new RuntimeException(\"Not a sparse matrix!\");\n }\n }",
"public void pushDryRun() throws Exception {\n if (releaseAction.isCreateVcsTag()) {\n if (scmManager.isTagExists(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), releaseAction.getTagUrl())) {\n throw new Exception(String.format(\"Tag with name '%s' already exists\", releaseAction.getTagUrl()));\n }\n }\n\n String testTagName = releaseAction.getTagUrl() + \"_test\";\n try {\n scmManager.testPush(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), testTagName);\n } catch (Exception e) {\n throw new Exception(String.format(\"Failed while attempting push dry-run: %s\", e.getMessage()), e);\n } finally {\n if (scmManager.isTagExists(scmManager.getRemoteConfig(releaseAction.getTargetRemoteName()), testTagName)) {\n scmManager.deleteLocalTag(testTagName);\n }\n }\n }",
"public void showTrajectoryAndSpline(){\n\t\t\n\t\tif(t.getDimension()==2){\n\t\t \tdouble[] xData = new double[rotatedTrajectory.size()];\n\t\t double[] yData = new double[rotatedTrajectory.size()];\n\t\t for(int i = 0; i < rotatedTrajectory.size(); i++){\n\t\t \txData[i] = rotatedTrajectory.get(i).x;\n\t\t \tyData[i] = rotatedTrajectory.get(i).y;\t\t \t\n\t\t }\n\t\t // Create Chart\n\t\t Chart chart = QuickChart.getChart(\"Spline+Track\", \"X\", \"Y\", \"y(x)\", xData, yData);\n\t\t \n\t\t //Add spline support points\n\t\t double[] subxData = new double[splineSupportPoints.size()];\n\t\t double[] subyData = new double[splineSupportPoints.size()];\n\t\t \n\t\t for(int i = 0; i < splineSupportPoints.size(); i++){\n\t\t \tsubxData[i] = splineSupportPoints.get(i).x;\n\t\t \tsubyData[i] = splineSupportPoints.get(i).y;\n\t\t }\n\t\t Series s = chart.addSeries(\"Spline Support Points\", subxData, subyData);\n\t\t s.setLineStyle(SeriesLineStyle.NONE);\n\t\t s.setSeriesType(SeriesType.Line);\n\t\t \n\t\t //ADd spline points\n\t\t int numberInterpolatedPointsPerSegment = 20;\n\t\t int numberOfSplines = spline.getN();\n\t\t double[] sxData = new double[numberInterpolatedPointsPerSegment*numberOfSplines];\n\t\t \n\t\t double[] syData = new double[numberInterpolatedPointsPerSegment*numberOfSplines];\n\t\t double[] knots = spline.getKnots();\n\t\t for(int i = 0; i < numberOfSplines; i++){\n\t\t \tdouble x = knots[i];\n\t\t \n\t\t \tdouble stopx = knots[i+1];\n\t\t \tdouble dx = (stopx-x)/numberInterpolatedPointsPerSegment;\n\t\t \t\n\t\t \tfor(int j = 0; j < numberInterpolatedPointsPerSegment; j++){\n\n\t\t \t\tsxData[i*numberInterpolatedPointsPerSegment+j] = x;\n\t\t \t\tsyData[i*numberInterpolatedPointsPerSegment+j] = spline.value(x);\n\t\t \t\tx += dx;\n\t\t \t}\n\t\t \t\n\t\t }\n\t\t s = chart.addSeries(\"Spline\", sxData, syData);\n\t\t s.setLineStyle(SeriesLineStyle.DASH_DASH);\n\t\t s.setMarker(SeriesMarker.NONE);\n\t\t s.setSeriesType(SeriesType.Line);\n\t\t \n\t\t \n\t\t //Show it\n\t\t new SwingWrapper(chart).displayChart();\n\t\t} \n\t}",
"public void addChildTask(Task child, int childOutlineLevel)\n {\n int outlineLevel = NumberHelper.getInt(getOutlineLevel());\n\n if ((outlineLevel + 1) == childOutlineLevel)\n {\n m_children.add(child);\n setSummary(true);\n }\n else\n {\n if (m_children.isEmpty() == false)\n {\n (m_children.get(m_children.size() - 1)).addChildTask(child, childOutlineLevel);\n }\n }\n }",
"public void set(String name, Object value) {\n hashAttributes.put(name, value);\n\n if (plugin != null) {\n plugin.invalidate();\n }\n }"
] |
Returns a list of files in given addon passing given filter. | [
"public List<String> filterAddonResources(Addon addon, Predicate<String> filter)\n {\n List<String> discoveredFileNames = new ArrayList<>();\n List<File> addonResources = addon.getRepository().getAddonResources(addon.getId());\n for (File addonFile : addonResources)\n {\n if (addonFile.isDirectory())\n handleDirectory(filter, addonFile, discoveredFileNames);\n else\n handleArchiveByFile(filter, addonFile, discoveredFileNames);\n }\n return discoveredFileNames;\n }"
] | [
"public static <T extends WindupVertexFrame> WindupVertexFrame removeTypeFromModel(GraphContext graphContext, WindupVertexFrame frame, Class<T> type)\n {\n Vertex vertex = frame.getElement();\n graphContext.getGraphTypeManager().removeTypeFromElement(type, vertex);\n return graphContext.getFramed().frameElement(vertex, WindupVertexFrame.class);\n }",
"public void afterLoading(CollectionProxyDefaultImpl colProxy)\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"loading a proxied collection a collection: \" + colProxy);\r\n Collection data = colProxy.getData();\r\n for (Iterator iterator = data.iterator(); iterator.hasNext();)\r\n {\r\n Object o = iterator.next();\r\n if(!isOpen())\r\n {\r\n log.error(\"Collection proxy materialization outside of a running tx, obj=\" + o);\r\n try{throw new Exception(\"Collection proxy materialization outside of a running tx, obj=\" + o);}\r\n catch(Exception e)\r\n {e.printStackTrace();}\r\n }\r\n else\r\n {\r\n Identity oid = getBroker().serviceIdentity().buildIdentity(o);\r\n ClassDescriptor cld = getBroker().getClassDescriptor(ProxyHelper.getRealClass(o));\r\n RuntimeObject rt = new RuntimeObject(o, oid, cld, false, ProxyHelper.isProxy(o));\r\n lockAndRegister(rt, Transaction.READ, isImplicitLocking(), getRegistrationList());\r\n }\r\n }\r\n unregisterFromCollectionProxy(colProxy);\r\n }",
"public ProjectCalendar addResourceCalendar() throws MPXJException\n {\n if (getResourceCalendar() != null)\n {\n throw new MPXJException(MPXJException.MAXIMUM_RECORDS);\n }\n\n ProjectCalendar calendar = new ProjectCalendar(getParentFile());\n setResourceCalendar(calendar);\n return calendar;\n }",
"public static sslglobal_sslpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tsslglobal_sslpolicy_binding obj = new sslglobal_sslpolicy_binding();\n\t\tsslglobal_sslpolicy_binding response[] = (sslglobal_sslpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static long count(nitro_service service, Long id) throws Exception{\n\t\tbridgegroup_vlan_binding obj = new bridgegroup_vlan_binding();\n\t\tobj.set_id(id);\n\t\toptions option = new options();\n\t\toption.set_count(true);\n\t\tbridgegroup_vlan_binding response[] = (bridgegroup_vlan_binding[]) obj.get_resources(service,option);\n\t\tif (response != null) {\n\t\t\treturn response[0].__count;\n\t\t}\n\t\treturn 0;\n\t}",
"public FieldDescriptor getAutoIncrementField()\r\n {\r\n if (m_autoIncrementField == null)\r\n {\r\n FieldDescriptor[] fds = getPkFields();\r\n\r\n for (int i = 0; i < fds.length; i++)\r\n {\r\n FieldDescriptor fd = fds[i];\r\n if (fd.isAutoIncrement())\r\n {\r\n m_autoIncrementField = fd;\r\n break;\r\n }\r\n }\r\n }\r\n if (m_autoIncrementField == null)\r\n {\r\n LoggerFactory.getDefaultLogger().warn(\r\n this.getClass().getName()\r\n + \": \"\r\n + \"Could not find autoincrement attribute for class: \"\r\n + this.getClassNameOfObject());\r\n }\r\n return m_autoIncrementField;\r\n }",
"protected boolean isSingleConnection(DatabaseConnection conn1, DatabaseConnection conn2) throws SQLException {\n\t\t// initialize the connections auto-commit flags\n\t\tconn1.setAutoCommit(true);\n\t\tconn2.setAutoCommit(true);\n\t\ttry {\n\t\t\t// change conn1's auto-commit to be false\n\t\t\tconn1.setAutoCommit(false);\n\t\t\tif (conn2.isAutoCommit()) {\n\t\t\t\t// if the 2nd connection's auto-commit is still true then we have multiple connections\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\t// if the 2nd connection's auto-commit is also false then we have a single connection\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} finally {\n\t\t\t// restore its auto-commit\n\t\t\tconn1.setAutoCommit(true);\n\t\t}\n\t}",
"public boolean matches(PathElement pe) {\n return pe.key.equals(key) && (isWildcard() || pe.value.equals(value));\n }",
"public GVRShader getTemplate(GVRContext ctx)\n {\n if (mShaderTemplate == null)\n {\n mShaderTemplate = makeTemplate(ID, ctx);\n ctx.getShaderManager().addShaderID(this);\n }\n return mShaderTemplate;\n }"
] |
The way calendars are stored in an MPP14 file means that there
can be forward references between the base calendar unique ID for a
derived calendar, and the base calendar itself. To get around this,
we initially populate the base calendar name attribute with the
base calendar unique ID, and now in this method we can convert those
ID values into the correct names.
@param baseCalendars list of calendars and base calendar IDs
@param map map of calendar ID values and calendar objects | [
"private void updateBaseCalendarNames(List<Pair<ProjectCalendar, Integer>> baseCalendars, HashMap<Integer, ProjectCalendar> map)\n {\n for (Pair<ProjectCalendar, Integer> pair : baseCalendars)\n {\n ProjectCalendar cal = pair.getFirst();\n Integer baseCalendarID = pair.getSecond();\n ProjectCalendar baseCal = map.get(baseCalendarID);\n if (baseCal != null && baseCal.getName() != null)\n {\n cal.setParent(baseCal);\n }\n else\n {\n // Remove invalid calendar to avoid serious problems later.\n m_file.removeCalendar(cal);\n }\n }\n }"
] | [
"private ServerBootstrap createBootstrap(final ChannelGroup channelGroup) throws Exception {\n EventLoopGroup bossGroup = new NioEventLoopGroup(bossThreadPoolSize,\n createDaemonThreadFactory(serviceName + \"-boss-thread-%d\"));\n EventLoopGroup workerGroup = new NioEventLoopGroup(workerThreadPoolSize,\n createDaemonThreadFactory(serviceName + \"-worker-thread-%d\"));\n ServerBootstrap bootstrap = new ServerBootstrap();\n bootstrap\n .group(bossGroup, workerGroup)\n .channel(NioServerSocketChannel.class)\n .childHandler(new ChannelInitializer<SocketChannel>() {\n @Override\n protected void initChannel(SocketChannel ch) throws Exception {\n channelGroup.add(ch);\n\n ChannelPipeline pipeline = ch.pipeline();\n if (sslHandlerFactory != null) {\n // Add SSLHandler if SSL is enabled\n pipeline.addLast(\"ssl\", sslHandlerFactory.create(ch.alloc()));\n }\n pipeline.addLast(\"codec\", new HttpServerCodec());\n pipeline.addLast(\"compressor\", new HttpContentCompressor());\n pipeline.addLast(\"chunkedWriter\", new ChunkedWriteHandler());\n pipeline.addLast(\"keepAlive\", new HttpServerKeepAliveHandler());\n pipeline.addLast(\"router\", new RequestRouter(resourceHandler, httpChunkLimit, sslHandlerFactory != null));\n if (eventExecutorGroup == null) {\n pipeline.addLast(\"dispatcher\", new HttpDispatcher());\n } else {\n pipeline.addLast(eventExecutorGroup, \"dispatcher\", new HttpDispatcher());\n }\n\n if (pipelineModifier != null) {\n pipelineModifier.modify(pipeline);\n }\n }\n });\n\n for (Map.Entry<ChannelOption, Object> entry : channelConfigs.entrySet()) {\n bootstrap.option(entry.getKey(), entry.getValue());\n }\n for (Map.Entry<ChannelOption, Object> entry : childChannelConfigs.entrySet()) {\n bootstrap.childOption(entry.getKey(), entry.getValue());\n }\n\n return bootstrap;\n }",
"private void createSuiteList(List<ISuite> suites,\n File outputDirectory,\n boolean onlyFailures) throws Exception\n {\n VelocityContext context = createContext();\n context.put(SUITES_KEY, suites);\n context.put(ONLY_FAILURES_KEY, onlyFailures);\n generateFile(new File(outputDirectory, SUITES_FILE),\n SUITES_FILE + TEMPLATE_EXTENSION,\n context);\n }",
"private final void handleHttpWorkerResponse(\n ResponseOnSingeRequest respOnSingleReq) throws Exception {\n // Successful response from GenericAsyncHttpWorker\n\n // Jeff 20310411: use generic response\n\n String responseContent = respOnSingleReq.getResponseBody();\n response.setResponseContent(respOnSingleReq.getResponseBody());\n\n /**\n * Poller logic if pollable: check if need to poll/ or already complete\n * 1. init poller data and HttpPollerProcessor 2. check if task\n * complete, if not, send the request again.\n */\n if (request.isPollable()) {\n boolean scheduleNextPoll = false;\n boolean errorFindingUuid = false;\n\n // set JobId of the poller\n if (!pollerData.isUuidHasBeenSet()) {\n String jobId = httpPollerProcessor\n .getUuidFromResponse(respOnSingleReq);\n\n if (jobId.equalsIgnoreCase(PcConstants.NA)) {\n errorFindingUuid = true;\n pollingErrorCount++;\n logger.error(\"!!POLLING_JOB_FAIL_FIND_JOBID_IN_RESPONSE!! FAIL FAST NOW. PLEASE CHECK getJobIdRegex or retry. \"\n\n + \"DEBUG: REGEX_JOBID: \"\n + httpPollerProcessor.getJobIdRegex()\n\n + \"RESPONSE: \"\n + respOnSingleReq.getResponseBody()\n + \" polling Error count\"\n + pollingErrorCount\n + \" at \" + PcDateUtils.getNowDateTimeStrStandard());\n // fail fast\n pollerData.setError(true);\n pollerData.setComplete(true);\n\n } else {\n pollerData.setJobIdAndMarkHasBeenSet(jobId);\n // if myResponse has other errors, mark poll data as error.\n pollerData.setError(httpPollerProcessor\n .ifThereIsErrorInResponse(respOnSingleReq));\n }\n\n }\n if (!pollerData.isError()) {\n\n pollerData\n .setComplete(httpPollerProcessor\n .ifTaskCompletedSuccessOrFailureFromResponse(respOnSingleReq));\n pollerData.setCurrentProgress(httpPollerProcessor\n .getProgressFromResponse(respOnSingleReq));\n }\n\n // poll again only if not complete AND no error; 2015: change to\n // over limit\n scheduleNextPoll = !pollerData.isComplete()\n && (pollingErrorCount <= httpPollerProcessor\n .getMaxPollError());\n\n // Schedule next poll and return. (not to answer back to manager yet\n // )\n if (scheduleNextPoll\n && (pollingErrorCount <= httpPollerProcessor\n .getMaxPollError())) {\n\n pollMessageCancellable = getContext()\n .system()\n .scheduler()\n .scheduleOnce(\n Duration.create(httpPollerProcessor\n .getPollIntervalMillis(),\n TimeUnit.MILLISECONDS), getSelf(),\n OperationWorkerMsgType.POLL_PROGRESS,\n getContext().system().dispatcher(), getSelf());\n\n logger.info(\"\\nPOLLER_NOW_ANOTHER_POLL: POLL_RECV_SEND\"\n + String.format(\"PROGRESS:%.3f, BODY:%s \",\n pollerData.getCurrentProgress(),\n responseContent,\n PcDateUtils.getNowDateTimeStrStandard()));\n\n String responseContentNew = errorFindingUuid ? responseContent\n + \"_PollingErrorCount:\" + pollingErrorCount\n : responseContent;\n logger.info(responseContentNew);\n // log\n pollerData.getPollingHistoryMap().put(\n \"RECV_\" + PcDateUtils.getNowDateTimeStrConciseNoZone(),\n String.format(\"PROGRESS:%.3f, BODY:%s\",\n pollerData.getCurrentProgress(),\n responseContent));\n return;\n } else {\n pollerData\n .getPollingHistoryMap()\n .put(\"RECV_\"\n + PcDateUtils.getNowDateTimeStrConciseNoZone(),\n String.format(\n \"POLL_COMPLETED_OR_ERROR: PROGRESS:%.3f, BODY:%s \",\n pollerData.getCurrentProgress(),\n responseContent));\n }\n\n }// end if (request.isPollable())\n\n reply(respOnSingleReq.isFailObtainResponse(),\n respOnSingleReq.getErrorMessage(),\n respOnSingleReq.getStackTrace(),\n respOnSingleReq.getStatusCode(),\n respOnSingleReq.getStatusCodeInt(),\n respOnSingleReq.getReceiveTime(), respOnSingleReq.getResponseHeaders());\n\n }",
"public static vpntrafficpolicy_vpnglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpntrafficpolicy_vpnglobal_binding obj = new vpntrafficpolicy_vpnglobal_binding();\n\t\tobj.set_name(name);\n\t\tvpntrafficpolicy_vpnglobal_binding response[] = (vpntrafficpolicy_vpnglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static base_responses update(nitro_service client, nspbr6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnspbr6 updateresources[] = new nspbr6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nspbr6();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].action = resources[i].action;\n\t\t\t\tupdateresources[i].srcipv6 = resources[i].srcipv6;\n\t\t\t\tupdateresources[i].srcipop = resources[i].srcipop;\n\t\t\t\tupdateresources[i].srcipv6val = resources[i].srcipv6val;\n\t\t\t\tupdateresources[i].srcport = resources[i].srcport;\n\t\t\t\tupdateresources[i].srcportop = resources[i].srcportop;\n\t\t\t\tupdateresources[i].srcportval = resources[i].srcportval;\n\t\t\t\tupdateresources[i].destipv6 = resources[i].destipv6;\n\t\t\t\tupdateresources[i].destipop = resources[i].destipop;\n\t\t\t\tupdateresources[i].destipv6val = resources[i].destipv6val;\n\t\t\t\tupdateresources[i].destport = resources[i].destport;\n\t\t\t\tupdateresources[i].destportop = resources[i].destportop;\n\t\t\t\tupdateresources[i].destportval = resources[i].destportval;\n\t\t\t\tupdateresources[i].srcmac = resources[i].srcmac;\n\t\t\t\tupdateresources[i].protocol = resources[i].protocol;\n\t\t\t\tupdateresources[i].protocolnumber = resources[i].protocolnumber;\n\t\t\t\tupdateresources[i].vlan = resources[i].vlan;\n\t\t\t\tupdateresources[i].Interface = resources[i].Interface;\n\t\t\t\tupdateresources[i].priority = resources[i].priority;\n\t\t\t\tupdateresources[i].msr = resources[i].msr;\n\t\t\t\tupdateresources[i].monitor = resources[i].monitor;\n\t\t\t\tupdateresources[i].nexthop = resources[i].nexthop;\n\t\t\t\tupdateresources[i].nexthopval = resources[i].nexthopval;\n\t\t\t\tupdateresources[i].nexthopvlan = resources[i].nexthopvlan;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static base_response unset(nitro_service client, nsdiameter resource, String[] args) throws Exception{\n\t\tnsdiameter unsetresource = new nsdiameter();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public boolean validation() throws ParallelTaskInvalidException {\n\n ParallelTask task = new ParallelTask();\n targetHostMeta = new TargetHostMeta(targetHosts);\n\n task = new ParallelTask(requestProtocol, concurrency, httpMeta,\n targetHostMeta, sshMeta, tcpMeta, udpMeta, pingMeta, null, responseContext,\n replacementVarMapNodeSpecific,\n replacementVarMap, requestReplacementType, config);\n boolean valid = false;\n\n try {\n valid = task.validateWithFillDefault();\n } catch (ParallelTaskInvalidException e) {\n logger.info(\"task is invalid \" + e);\n }\n\n return valid;\n\n }",
"public synchronized void addNodesToWorkerList(List<Integer> nodeIds) {\n // Bookkeeping for nodes that will be involved in the next task\n nodeIdsWithWork.addAll(nodeIds);\n logger.info(\"Node IDs with work: \" + nodeIdsWithWork + \" Newly added nodes \" + nodeIds);\n }",
"public void unregisterComponent(java.awt.Component c)\r\n {\r\n java.awt.dnd.DragGestureRecognizer recognizer = \r\n (java.awt.dnd.DragGestureRecognizer)this.hmDragGestureRecognizers.remove(c);\r\n if (recognizer != null)\r\n recognizer.setComponent(null);\r\n }"
] |
Scans the given token global token stream for a list of sub-token
streams representing those portions of the global stream that
may contain date time information
@param stream
@return | [
"private List<TokenStream> collectTokenStreams(TokenStream stream) {\n \n // walk through the token stream and build a collection \n // of sub token streams that represent possible date locations\n List<Token> currentGroup = null;\n List<List<Token>> groups = new ArrayList<List<Token>>();\n Token currentToken;\n int currentTokenType;\n StringBuilder tokenString = new StringBuilder();\n while((currentToken = stream.getTokenSource().nextToken()).getType() != DateLexer.EOF) {\n currentTokenType = currentToken.getType();\n tokenString.append(DateParser.tokenNames[currentTokenType]).append(\" \");\n\n // we're currently NOT collecting for a possible date group\n if(currentGroup == null) {\n // skip over white space and known tokens that cannot be the start of a date\n if(currentTokenType != DateLexer.WHITE_SPACE &&\n DateParser.FOLLOW_empty_in_parse186.member(currentTokenType)) {\n\n currentGroup = new ArrayList<Token>();\n currentGroup.add(currentToken);\n }\n }\n\n // we're currently collecting\n else {\n // preserve white space\n if(currentTokenType == DateLexer.WHITE_SPACE) {\n currentGroup.add(currentToken);\n }\n\n else {\n // if this is an unknown token, we'll close out the current group\n if(currentTokenType == DateLexer.UNKNOWN) {\n addGroup(currentGroup, groups);\n currentGroup = null;\n }\n // otherwise, the token is known and we're currently collecting for\n // a group, so we'll add it to the current group\n else {\n currentGroup.add(currentToken);\n }\n }\n }\n }\n\n if(currentGroup != null) {\n addGroup(currentGroup, groups);\n }\n \n _logger.info(\"STREAM: \" + tokenString.toString());\n List<TokenStream> streams = new ArrayList<TokenStream>();\n for(List<Token> group:groups) {\n if(!group.isEmpty()) {\n StringBuilder builder = new StringBuilder();\n builder.append(\"GROUP: \");\n for (Token token : group) {\n builder.append(DateParser.tokenNames[token.getType()]).append(\" \");\n }\n _logger.info(builder.toString());\n\n streams.add(new CommonTokenStream(new NattyTokenSource(group)));\n }\n }\n\n return streams;\n }"
] | [
"public void keyboardSupportEnabled(Activity activity, boolean enable) {\n if (getContent() != null && getContent().getChildCount() > 0) {\n if (mKeyboardUtil == null) {\n mKeyboardUtil = new KeyboardUtil(activity, getContent().getChildAt(0));\n mKeyboardUtil.disable();\n }\n\n if (enable) {\n mKeyboardUtil.enable();\n } else {\n mKeyboardUtil.disable();\n }\n }\n }",
"public Slice newSlice(long address, int size, Object reference)\n {\n if (address <= 0) {\n throw new IllegalArgumentException(\"Invalid address: \" + address);\n }\n if (reference == null) {\n throw new NullPointerException(\"Object reference is null\");\n }\n if (size == 0) {\n return Slices.EMPTY_SLICE;\n }\n return new Slice(null, address, size, size, reference);\n }",
"public static ExtensibleConfigurationPersister createDomainXmlConfigurationPersister(final ConfigurationFile file, ExecutorService executorService, ExtensionRegistry extensionRegistry, final HostControllerEnvironment environment) {\n DomainXml domainXml = new DomainXml(Module.getBootModuleLoader(), executorService, extensionRegistry);\n\n boolean suppressLoad = false;\n ConfigurationFile.InteractionPolicy policy = file.getInteractionPolicy();\n final boolean isReloaded = environment.getRunningModeControl().isReloaded();\n\n if (!isReloaded && (policy == ConfigurationFile.InteractionPolicy.NEW && (file.getBootFile().exists() && file.getBootFile().length() != 0))) {\n throw HostControllerLogger.ROOT_LOGGER.cannotOverwriteDomainXmlWithEmpty(file.getBootFile().getName());\n }\n\n if (!isReloaded && (policy == ConfigurationFile.InteractionPolicy.NEW || policy == ConfigurationFile.InteractionPolicy.DISCARD)) {\n suppressLoad = true;\n }\n\n BackupXmlConfigurationPersister persister = new BackupXmlConfigurationPersister(file, new QName(Namespace.CURRENT.getUriString(), \"domain\"), domainXml, domainXml, suppressLoad);\n for (Namespace namespace : Namespace.domainValues()) {\n if (!namespace.equals(Namespace.CURRENT)) {\n persister.registerAdditionalRootElement(new QName(namespace.getUriString(), \"domain\"), domainXml);\n }\n }\n extensionRegistry.setWriterRegistry(persister);\n return persister;\n }",
"public void clear() {\n\t\tfor (Bean bean : beans.values()) {\n\t\t\tif (null != bean.destructionCallback) {\n\t\t\t\tbean.destructionCallback.run();\n\t\t\t}\n\t\t}\n\t\tbeans.clear();\n\t}",
"private static String getScheme(Service service, Annotation... qualifiers) {\n for (Annotation q : qualifiers) {\n if (q instanceof Scheme) {\n return ((Scheme) q).value();\n }\n }\n\n if (service.getMetadata() != null && service.getMetadata().getAnnotations() != null) {\n String s = service.getMetadata().getAnnotations().get(SERVICE_SCHEME);\n if (s != null && s.isEmpty()) {\n return s;\n }\n }\n\n return DEFAULT_SCHEME;\n }",
"public <CT> CT callBatchTasks(ConnectionSource connectionSource, Callable<CT> callable) throws SQLException {\n\t\tif (connectionSource.isSingleConnection(tableInfo.getTableName())) {\n\t\t\tsynchronized (this) {\n\t\t\t\treturn doCallBatchTasks(connectionSource, callable);\n\t\t\t}\n\t\t} else {\n\t\t\treturn doCallBatchTasks(connectionSource, callable);\n\t\t}\n\t}",
"public byte[] toArray() {\n byte[] copy = new byte[length];\n System.arraycopy(data, offset, copy, 0, length);\n return copy;\n }",
"public AppMsg setLayoutGravity(int gravity) {\n mLayoutParams = new FrameLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, gravity);\n return this;\n }",
"static String createStatsType(Set<String> statsItems, String sortType,\n MtasFunctionParserFunction functionParser) {\n String statsType = STATS_BASIC;\n for (String statsItem : statsItems) {\n if (STATS_FULL_TYPES.contains(statsItem)) {\n statsType = STATS_FULL;\n break;\n } else if (STATS_ADVANCED_TYPES.contains(statsItem)) {\n statsType = STATS_ADVANCED;\n } else if (statsType != STATS_ADVANCED\n && STATS_BASIC_TYPES.contains(statsItem)) {\n statsType = STATS_BASIC;\n } else {\n Matcher m = fpStatsFunctionItems.matcher(statsItem.trim());\n if (m.find()) {\n if (STATS_FUNCTIONS.contains(m.group(2).trim())) {\n statsType = STATS_FULL;\n break;\n }\n }\n }\n }\n if (sortType != null && STATS_TYPES.contains(sortType)) {\n if (STATS_FULL_TYPES.contains(sortType)) {\n statsType = STATS_FULL;\n } else if (STATS_ADVANCED_TYPES.contains(sortType)) {\n statsType = (statsType == null || statsType != STATS_FULL)\n ? STATS_ADVANCED : statsType;\n }\n }\n return statsType;\n }"
] |
Read properties from the raw header data.
@param stream input stream | [
"private void readHeaderProperties(BufferedInputStream stream) throws IOException\n {\n String header = readHeaderString(stream);\n for (String property : header.split(\"\\\\|\"))\n {\n String[] expression = property.split(\"=\");\n m_properties.put(expression[0], expression[1]);\n }\n }"
] | [
"public void localCommit()\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"commit was called\");\r\n if (!this.isInLocalTransaction)\r\n {\r\n throw new TransactionNotInProgressException(\"Not in transaction, call begin() before commit()\");\r\n }\r\n try\r\n {\r\n if(!broker.isManaged())\r\n {\r\n if (batchCon != null)\r\n {\r\n batchCon.commit();\r\n }\r\n else if (con != null)\r\n {\r\n con.commit();\r\n }\r\n }\r\n else\r\n {\r\n if(log.isDebugEnabled()) log.debug(\r\n \"Found managed environment setting in PB, will skip Connection.commit() call\");\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n log.error(\"Commit on underlying connection failed, try to rollback connection\", e);\r\n this.localRollback();\r\n throw new TransactionAbortedException(\"Commit on connection failed\", e);\r\n }\r\n finally\r\n {\r\n this.isInLocalTransaction = false;\r\n restoreAutoCommitState();\r\n this.releaseConnection();\r\n }\r\n }",
"private void tryRefreshAccessToken(final Long reqStartedAt) {\n authLock.writeLock().lock();\n try {\n if (!isLoggedIn()) {\n throw new StitchClientException(StitchClientErrorCode.LOGGED_OUT_DURING_REQUEST);\n }\n\n try {\n final Jwt jwt = Jwt.fromEncoded(getAuthInfo().getAccessToken());\n if (jwt.getIssuedAt() >= reqStartedAt) {\n return;\n }\n } catch (final IOException e) {\n // Swallow\n }\n\n // retry\n refreshAccessToken();\n } finally {\n authLock.writeLock().unlock();\n }\n }",
"private Table buildTable(CmsSqlConsoleResults results) {\n\n IndexedContainer container = new IndexedContainer();\n int numCols = results.getColumns().size();\n for (int c = 0; c < numCols; c++) {\n container.addContainerProperty(Integer.valueOf(c), results.getColumnType(c), null);\n }\n int r = 0;\n for (List<Object> row : results.getData()) {\n Item item = container.addItem(Integer.valueOf(r));\n for (int c = 0; c < numCols; c++) {\n item.getItemProperty(Integer.valueOf(c)).setValue(row.get(c));\n }\n r += 1;\n }\n Table table = new Table();\n table.setContainerDataSource(container);\n for (int c = 0; c < numCols; c++) {\n String col = (results.getColumns().get(c));\n table.setColumnHeader(Integer.valueOf(c), col);\n }\n table.setWidth(\"100%\");\n table.setHeight(\"100%\");\n table.setColumnCollapsingAllowed(true);\n return table;\n }",
"public Metadata getMetadata(String templateName) {\n String scope = Metadata.scopeBasedOnType(templateName);\n return this.getMetadata(templateName, scope);\n }",
"public void setDatesWithCheckState(Collection<CmsPair<Date, Boolean>> datesWithCheckInfo) {\n\n SortedSet<Date> dates = new TreeSet<>();\n m_checkBoxes.clear();\n for (CmsPair<Date, Boolean> p : datesWithCheckInfo) {\n addCheckBox(p.getFirst(), p.getSecond().booleanValue());\n dates.add(p.getFirst());\n }\n reInitLayoutElements();\n setDatesInternal(dates);\n }",
"public void setString(String[] newValue) {\n if ( newValue != null ) {\n this.string.setValue(newValue.length, newValue);\n }\n }",
"public void sendFaderStartCommand(Set<Integer> deviceNumbersToStart, Set<Integer> deviceNumbersToStop) throws IOException {\n ensureRunning();\n byte[] payload = new byte[FADER_START_PAYLOAD.length];\n System.arraycopy(FADER_START_PAYLOAD, 0, payload, 0, FADER_START_PAYLOAD.length);\n payload[2] = getDeviceNumber();\n\n for (int i = 1; i <= 4; i++) {\n if (deviceNumbersToStart.contains(i)) {\n payload[i + 4] = 0;\n }\n if (deviceNumbersToStop.contains(i)) {\n payload[i + 4] = 1;\n }\n }\n\n assembleAndSendPacket(Util.PacketType.FADER_START_COMMAND, payload, getBroadcastAddress(), BeatFinder.BEAT_PORT);\n }",
"public void ifPropertyValueEquals(String template, Properties attributes) throws XDocletException\r\n {\r\n String value = getPropertyValue(attributes.getProperty(ATTRIBUTE_LEVEL), attributes.getProperty(ATTRIBUTE_NAME));\r\n String expected = attributes.getProperty(ATTRIBUTE_VALUE);\r\n\r\n if (value == null)\r\n {\r\n value = attributes.getProperty(ATTRIBUTE_DEFAULT);\r\n }\r\n if (expected.equals(value))\r\n {\r\n generate(template);\r\n }\r\n }",
"public PhotoList<Photo> getPublicPhotos(String userId, Set<String> extras, int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PUBLIC_PHOTOS);\r\n\r\n parameters.put(\"user_id\", userId);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n if (extras != null) {\r\n parameters.put(Extras.KEY_EXTRAS, StringUtilities.join(extras, \",\"));\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosElement = response.getPayload();\r\n photos.setPage(photosElement.getAttribute(\"page\"));\r\n photos.setPages(photosElement.getAttribute(\"pages\"));\r\n photos.setPerPage(photosElement.getAttribute(\"perpage\"));\r\n photos.setTotal(photosElement.getAttribute(\"total\"));\r\n\r\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n for (int i = 0; i < photoNodes.getLength(); i++) {\r\n Element photoElement = (Element) photoNodes.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement));\r\n }\r\n return photos;\r\n }"
] |
Create the image elements for the banners tha goes into the
title and header bands depending on the case | [
"protected void applyBanners() {\n DynamicReportOptions options = getReport().getOptions();\n if (options.getFirstPageImageBanners().isEmpty() && options.getImageBanners().isEmpty()){\n return;\n }\n\n\t\t/*\n\t\t First create image banners for the first page only\n\t\t */\n\t\tJRDesignBand title = (JRDesignBand) getDesign().getTitle();\n\t\t//if there is no title band, but there are banner images for the first page, we create a title band\n\t\tif (title == null && !options.getFirstPageImageBanners().isEmpty()){\n\t\t\ttitle = new JRDesignBand();\n\t\t\tgetDesign().setTitle(title);\n\t\t}\n\t\tapplyImageBannersToBand(title, options.getFirstPageImageBanners().values(), null, true);\n\n\t\t/*\n\t\t Now create image banner for the rest of the pages\n\t\t */\n\t\tJRDesignBand pageHeader = (JRDesignBand) getDesign().getPageHeader();\n\t\t//if there is no title band, but there are banner images for the first page, we create a title band\n\t\tif (pageHeader == null && !options.getImageBanners().isEmpty()){\n\t\t\tpageHeader = new JRDesignBand();\n\t\t\tgetDesign().setPageHeader(pageHeader);\n\t\t}\n\t\tJRDesignExpression printWhenExpression = null;\n\t\tif (!options.getFirstPageImageBanners().isEmpty()){\n\t\t\tprintWhenExpression = new JRDesignExpression();\n\t\t\tprintWhenExpression.setValueClass(Boolean.class);\n\t\t\tprintWhenExpression.setText(EXPRESSION_TRUE_WHEN_NOT_FIRST_PAGE);\n\t\t}\n\t\tapplyImageBannersToBand(pageHeader, options.getImageBanners().values(),printWhenExpression, true);\n\n\n\n\t}"
] | [
"private void writeCustomFields() throws IOException\n {\n m_writer.writeStartList(\"custom_fields\");\n for (CustomField field : m_projectFile.getCustomFields())\n {\n writeCustomField(field);\n }\n m_writer.writeEndList();\n }",
"public void addItem(T value, Direction dir, String text) {\n addItem(value, dir, text, true);\n }",
"private void readNormalDay(ProjectCalendar calendar, Project.Calendars.Calendar.WeekDays.WeekDay weekDay)\n {\n int dayNumber = weekDay.getDayType().intValue();\n Day day = Day.getInstance(dayNumber);\n calendar.setWorkingDay(day, BooleanHelper.getBoolean(weekDay.isDayWorking()));\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n\n Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes times = weekDay.getWorkingTimes();\n if (times != null)\n {\n for (Project.Calendars.Calendar.WeekDays.WeekDay.WorkingTimes.WorkingTime period : times.getWorkingTime())\n {\n Date startTime = period.getFromTime();\n Date endTime = period.getToTime();\n\n if (startTime != null && endTime != null)\n {\n if (startTime.getTime() >= endTime.getTime())\n {\n endTime = DateHelper.addDays(endTime, 1);\n }\n\n hours.addRange(new DateRange(startTime, endTime));\n }\n }\n }\n }",
"private Map<String, I_CmsSearchConfigurationFacetField> getDefaultFieldFacets(boolean categoryConjunction) {\n\n Map<String, I_CmsSearchConfigurationFacetField> fieldFacets = new HashMap<String, I_CmsSearchConfigurationFacetField>();\n fieldFacets.put(\n CmsListManager.FIELD_CATEGORIES,\n new CmsSearchConfigurationFacetField(\n CmsListManager.FIELD_CATEGORIES,\n null,\n Integer.valueOf(1),\n Integer.valueOf(200),\n null,\n \"Category\",\n SortOrder.index,\n null,\n Boolean.valueOf(categoryConjunction),\n null,\n Boolean.TRUE));\n fieldFacets.put(\n CmsListManager.FIELD_PARENT_FOLDERS,\n new CmsSearchConfigurationFacetField(\n CmsListManager.FIELD_PARENT_FOLDERS,\n null,\n Integer.valueOf(1),\n Integer.valueOf(200),\n null,\n \"Folders\",\n SortOrder.index,\n null,\n Boolean.FALSE,\n null,\n Boolean.TRUE));\n return Collections.unmodifiableMap(fieldFacets);\n\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void enableDeviceNetworkInfoReporting(boolean value){\n enableNetworkInfoReporting = value;\n StorageHelper.putBoolean(context,storageKeyWithSuffix(Constants.NETWORK_INFO),enableNetworkInfoReporting);\n getConfigLogger().verbose(getAccountId(), \"Device Network Information reporting set to \" + enableNetworkInfoReporting);\n }",
"private int[] readTypeAnnotations(final MethodVisitor mv,\n final Context context, int u, boolean visible) {\n char[] c = context.buffer;\n int[] offsets = new int[readUnsignedShort(u)];\n u += 2;\n for (int i = 0; i < offsets.length; ++i) {\n offsets[i] = u;\n int target = readInt(u);\n switch (target >>> 24) {\n case 0x00: // CLASS_TYPE_PARAMETER\n case 0x01: // METHOD_TYPE_PARAMETER\n case 0x16: // METHOD_FORMAL_PARAMETER\n u += 2;\n break;\n case 0x13: // FIELD\n case 0x14: // METHOD_RETURN\n case 0x15: // METHOD_RECEIVER\n u += 1;\n break;\n case 0x40: // LOCAL_VARIABLE\n case 0x41: // RESOURCE_VARIABLE\n for (int j = readUnsignedShort(u + 1); j > 0; --j) {\n int start = readUnsignedShort(u + 3);\n int length = readUnsignedShort(u + 5);\n createLabel(start, context.labels);\n createLabel(start + length, context.labels);\n u += 6;\n }\n u += 3;\n break;\n case 0x47: // CAST\n case 0x48: // CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT\n case 0x49: // METHOD_INVOCATION_TYPE_ARGUMENT\n case 0x4A: // CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT\n case 0x4B: // METHOD_REFERENCE_TYPE_ARGUMENT\n u += 4;\n break;\n // case 0x10: // CLASS_EXTENDS\n // case 0x11: // CLASS_TYPE_PARAMETER_BOUND\n // case 0x12: // METHOD_TYPE_PARAMETER_BOUND\n // case 0x17: // THROWS\n // case 0x42: // EXCEPTION_PARAMETER\n // case 0x43: // INSTANCEOF\n // case 0x44: // NEW\n // case 0x45: // CONSTRUCTOR_REFERENCE\n // case 0x46: // METHOD_REFERENCE\n default:\n u += 3;\n break;\n }\n int pathLength = readByte(u);\n if ((target >>> 24) == 0x42) {\n TypePath path = pathLength == 0 ? null : new TypePath(b, u);\n u += 1 + 2 * pathLength;\n u = readAnnotationValues(u + 2, c, true,\n mv.visitTryCatchAnnotation(target, path,\n readUTF8(u, c), visible));\n } else {\n u = readAnnotationValues(u + 3 + 2 * pathLength, c, true, null);\n }\n }\n return offsets;\n }",
"public void postConstruct() {\n parseGeometry();\n\n Assert.isTrue(this.polygon != null, \"Polygon is null. 'area' string is: '\" + this.area + \"'\");\n Assert.isTrue(this.display != null, \"'display' is null\");\n\n Assert.isTrue(this.style == null || this.display == AoiDisplay.RENDER,\n \"'style' does not make sense unless 'display' == RENDER. In this case 'display' == \" +\n this.display);\n }",
"public void initSize(Rectangle rectangle) {\n\t\ttemplate = writer.getDirectContent().createTemplate(rectangle.getWidth(), rectangle.getHeight());\n\t}",
"public KeyChangeResult handleKeyChange(EntryChangeEvent event, boolean allLanguages) {\n\n if (m_keyset.getKeySet().contains(event.getNewValue())) {\n m_container.getItem(event.getItemId()).getItemProperty(TableProperty.KEY).setValue(event.getOldValue());\n return KeyChangeResult.FAILED_DUPLICATED_KEY;\n }\n if (allLanguages && !renameKeyForAllLanguages(event.getOldValue(), event.getNewValue())) {\n m_container.getItem(event.getItemId()).getItemProperty(TableProperty.KEY).setValue(event.getOldValue());\n return KeyChangeResult.FAILED_FOR_OTHER_LANGUAGE;\n }\n return KeyChangeResult.SUCCESS;\n }"
] |
Use this API to fetch nd6ravariables resource of given name . | [
"public static nd6ravariables get(nitro_service service, Long vlan) throws Exception{\n\t\tnd6ravariables obj = new nd6ravariables();\n\t\tobj.set_vlan(vlan);\n\t\tnd6ravariables response = (nd6ravariables) obj.get_resource(service);\n\t\treturn response;\n\t}"
] | [
"public Date getPreviousWorkFinish(Date date)\n {\n Calendar cal = Calendar.getInstance();\n cal.setTime(date);\n updateToPreviousWorkFinish(cal);\n return cal.getTime();\n }",
"public List<Throwable> getCauses(Throwable t)\n {\n List<Throwable> causes = new LinkedList<Throwable>();\n Throwable next = t;\n while (next.getCause() != null)\n {\n next = next.getCause();\n causes.add(next);\n }\n return causes;\n }",
"public static FreeMarkerOperation create(Furnace furnace, String templatePath, String outputFilename,\n String... varNames)\n {\n return new FreeMarkerOperation(furnace, templatePath, outputFilename, varNames);\n }",
"@RequestMapping(value = \"api/servergroup\", method = RequestMethod.POST)\n public\n @ResponseBody\n ServerGroup createServerGroup(Model model,\n @RequestParam(value = \"name\") String name,\n @RequestParam(value = \"profileId\", required = false) Integer profileId,\n @RequestParam(value = \"profileIdentifier\", required = false) String profileIdentifier) throws Exception {\n if (profileId == null && profileIdentifier == null) {\n throw new Exception(\"profileId required\");\n }\n if (profileId == null) {\n profileId = ProfileService.getInstance().getIdFromName(profileIdentifier);\n }\n int groupId = ServerRedirectService.getInstance().addServerGroup(name, profileId);\n return ServerRedirectService.getInstance().getServerGroup(groupId, profileId);\n }",
"public T reverse() {\n String id = getId();\n String REVERSE = \"_REVERSE\";\n if (id.endsWith(REVERSE)) {\n setId(id.substring(0, id.length() - REVERSE.length()));\n }\n\n float start = mStart;\n float end = mEnd;\n mStart = end;\n mEnd = start;\n mReverse = !mReverse;\n return self();\n }",
"public static appfwlearningsettings get(nitro_service service, String profilename) throws Exception{\n\t\tappfwlearningsettings obj = new appfwlearningsettings();\n\t\tobj.set_profilename(profilename);\n\t\tappfwlearningsettings response = (appfwlearningsettings) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public Token add( String word ) {\n Token t = new Token(word);\n push( t );\n return t;\n }",
"public static base_response rename(nitro_service client, gslbservice resource, String new_servicename) throws Exception {\n\t\tgslbservice renameresource = new gslbservice();\n\t\trenameresource.servicename = resource.servicename;\n\t\treturn renameresource.rename_resource(client,new_servicename);\n\t}",
"public static int compare(Integer n1, Integer n2)\n {\n int result;\n if (n1 == null || n2 == null)\n {\n result = (n1 == null && n2 == null ? 0 : (n1 == null ? 1 : -1));\n }\n else\n {\n result = n1.compareTo(n2);\n }\n return (result);\n }"
] |
Generates a torque schema for the model.
@param attributes The attributes of the tag
@return The property value
@exception XDocletException If an error occurs
@doc.tag type="content" | [
"public String createTorqueSchema(Properties attributes) throws XDocletException\r\n {\r\n String dbName = (String)getDocletContext().getConfigParam(CONFIG_PARAM_DATABASENAME);\r\n\r\n _torqueModel = new TorqueModelDef(dbName, _model);\r\n return \"\";\r\n }"
] | [
"private static EndpointReferenceType createEPR(Server server, String address, SLProperties props) {\n EndpointReferenceType sourceEPR = server.getEndpoint().getEndpointInfo().getTarget();\n EndpointReferenceType targetEPR = WSAEndpointReferenceUtils.duplicate(sourceEPR);\n WSAEndpointReferenceUtils.setAddress(targetEPR, address);\n\n if (props != null) {\n addProperties(targetEPR, props);\n }\n return targetEPR;\n }",
"public Set<ServerConfigInfo> getServerConfigsOnSlave(Resource hostResource){\n Set<ServerConfigInfo> groups = new HashSet<>();\n for (ResourceEntry entry : hostResource.getChildren(SERVER_CONFIG)) {\n groups.add(new ServerConfigInfoImpl(entry.getModel()));\n }\n return groups;\n }",
"private int[] getPrimaryCodewords() {\r\n\r\n assert mode == 2 || mode == 3;\r\n\r\n if (primaryData.length() != 15) {\r\n throw new OkapiException(\"Invalid Primary String\");\r\n }\r\n\r\n for (int i = 9; i < 15; i++) { /* check that country code and service are numeric */\r\n if (primaryData.charAt(i) < '0' || primaryData.charAt(i) > '9') {\r\n throw new OkapiException(\"Invalid Primary String\");\r\n }\r\n }\r\n\r\n String postcode;\r\n if (mode == 2) {\r\n postcode = primaryData.substring(0, 9);\r\n int index = postcode.indexOf(' ');\r\n if (index != -1) {\r\n postcode = postcode.substring(0, index);\r\n }\r\n } else {\r\n // if (mode == 3)\r\n postcode = primaryData.substring(0, 6);\r\n }\r\n\r\n int country = Integer.parseInt(primaryData.substring(9, 12));\r\n int service = Integer.parseInt(primaryData.substring(12, 15));\r\n\r\n if (debug) {\r\n System.out.println(\"Using mode \" + mode);\r\n System.out.println(\" Postcode: \" + postcode);\r\n System.out.println(\" Country Code: \" + country);\r\n System.out.println(\" Service: \" + service);\r\n }\r\n\r\n if (mode == 2) {\r\n return getMode2PrimaryCodewords(postcode, country, service);\r\n } else { // mode == 3\r\n return getMode3PrimaryCodewords(postcode, country, service);\r\n }\r\n }",
"public BoxRetentionPolicyAssignment.Info assignTo(BoxFolder folder) {\r\n return BoxRetentionPolicyAssignment.createAssignmentToFolder(this.getAPI(), this.getID(), folder.getID());\r\n }",
"public static auditnslogpolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditnslogpolicy_authenticationvserver_binding obj = new auditnslogpolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauditnslogpolicy_authenticationvserver_binding response[] = (auditnslogpolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static IndexableTaskItem create(final FunctionalTaskItem taskItem) {\n return new IndexableTaskItem() {\n @Override\n protected Observable<Indexable> invokeTaskAsync(TaskGroup.InvocationContext context) {\n FunctionalTaskItem.Context fContext = new FunctionalTaskItem.Context(this);\n fContext.setInnerContext(context);\n return taskItem.call(fContext);\n }\n };\n }",
"public static <E> String serialize(Map<String, E> map, Class<E> jsonObjectClass) throws IOException {\n return mapperFor(jsonObjectClass).serialize(map);\n }",
"public static <T> T objectify(ObjectMapper mapper, Object source, JavaType targetType) {\n try {\n return mapper.readValue(mapper.writeValueAsBytes(source), targetType);\n } catch (RuntimeException e) {\n throw e;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
"public Replication targetOauth(String consumerSecret, String consumerKey, String tokenSecret,\n String token) {\n targetOauth = new JsonObject();\n this.consumerSecret = consumerSecret;\n this.consumerKey = consumerKey;\n this.tokenSecret = tokenSecret;\n this.token = token;\n return this;\n }"
] |
A connection to the database. Should be short-lived. No transaction active by default.
@return a new open connection. | [
"public DbConn getConn()\n {\n Connection cnx = null;\n try\n {\n Thread.interrupted(); // this is VERY sad. Needed for Oracle driver which otherwise fails spectacularly.\n cnx = _ds.getConnection();\n if (cnx.getAutoCommit())\n {\n cnx.setAutoCommit(false);\n cnx.rollback(); // To ensure no open transaction created by the pool before changing TX mode\n }\n\n if (cnx.getTransactionIsolation() != Connection.TRANSACTION_READ_COMMITTED)\n {\n cnx.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);\n }\n\n return new DbConn(this, cnx);\n }\n catch (SQLException e)\n {\n DbHelper.closeQuietly(cnx); // May have been left open when the pool has given us a failed connection.\n throw new DatabaseException(e);\n }\n }"
] | [
"public static List<CompiledAutomaton> createAutomata(String prefix,\n String regexp, Map<String, Automaton> automatonMap) throws IOException {\n List<CompiledAutomaton> list = new ArrayList<>();\n Automaton automatonRegexp = null;\n if (regexp != null) {\n RegExp re = new RegExp(prefix + MtasToken.DELIMITER + regexp + \"\\u0000*\");\n automatonRegexp = re.toAutomaton();\n }\n int step = 500;\n List<String> keyList = new ArrayList<>(automatonMap.keySet());\n for (int i = 0; i < keyList.size(); i += step) {\n int localStep = step;\n boolean success = false;\n CompiledAutomaton compiledAutomaton = null;\n while (!success) {\n success = true;\n int next = Math.min(keyList.size(), i + localStep);\n List<Automaton> listAutomaton = new ArrayList<>();\n for (int j = i; j < next; j++) {\n listAutomaton.add(automatonMap.get(keyList.get(j)));\n }\n Automaton automatonList = Operations.union(listAutomaton);\n Automaton automaton;\n if (automatonRegexp != null) {\n automaton = Operations.intersection(automatonList, automatonRegexp);\n } else {\n automaton = automatonList;\n }\n try {\n compiledAutomaton = new CompiledAutomaton(automaton);\n } catch (TooComplexToDeterminizeException e) {\n log.debug(e);\n success = false;\n if (localStep > 1) {\n localStep /= 2;\n } else {\n throw new IOException(\"TooComplexToDeterminizeException\");\n }\n }\n }\n list.add(compiledAutomaton);\n }\n return list;\n }",
"public void drawGeometry(Geometry geometry, SymbolInfo symbol, Color fillColor, Color strokeColor, float lineWidth,\n\t\t\tfloat[] dashArray, Rectangle clipRect) {\n\t\ttemplate.saveState();\n\t\t// clipping code\n\t\tif (clipRect != null) {\n\t\t\ttemplate.rectangle(clipRect.getLeft() + origX, clipRect.getBottom() + origY, clipRect.getWidth(), clipRect\n\t\t\t\t\t.getHeight());\n\t\t\ttemplate.clip();\n\t\t\ttemplate.newPath();\n\t\t}\n\t\tsetStroke(strokeColor, lineWidth, dashArray);\n\t\tsetFill(fillColor);\n\t\tdrawGeometry(geometry, symbol);\n\t\ttemplate.restoreState();\n\t}",
"public Table createTable(ProjectFile file, byte[] data, VarMeta varMeta, Var2Data varData)\n {\n Table table = new Table();\n\n table.setID(MPPUtility.getInt(data, 0));\n table.setResourceFlag(MPPUtility.getShort(data, 108) == 1);\n table.setName(MPPUtility.removeAmpersands(MPPUtility.getUnicodeString(data, 4)));\n\n byte[] columnData = null;\n Integer tableID = Integer.valueOf(table.getID());\n if (m_tableColumnDataBaseline != null)\n {\n columnData = varData.getByteArray(varMeta.getOffset(tableID, m_tableColumnDataBaseline));\n }\n\n if (columnData == null)\n {\n columnData = varData.getByteArray(varMeta.getOffset(tableID, m_tableColumnDataEnterprise));\n if (columnData == null)\n {\n columnData = varData.getByteArray(varMeta.getOffset(tableID, m_tableColumnDataStandard));\n }\n }\n\n processColumnData(file, table, columnData);\n\n //System.out.println(table);\n\n return (table);\n }",
"public <T extends Widget & Checkable> boolean uncheck(int checkableIndex) {\n List<T> children = getCheckableChildren();\n T checkableWidget = children.get(checkableIndex);\n return checkInternal(checkableWidget, false);\n }",
"private Object toReference(int type, Object referent, int hash)\r\n {\r\n switch (type)\r\n {\r\n case HARD:\r\n return referent;\r\n case SOFT:\r\n return new SoftRef(hash, referent, queue);\r\n case WEAK:\r\n return new WeakRef(hash, referent, queue);\r\n default:\r\n throw new Error();\r\n }\r\n }",
"public boolean checkRead(TransactionImpl tx, Object obj)\r\n {\r\n if (hasReadLock(tx, obj))\r\n {\r\n return true;\r\n }\r\n LockEntry writer = getWriter(obj);\r\n if (writer.isOwnedBy(tx))\r\n {\r\n return true;\r\n }\r\n return false;\r\n }",
"public static base_response update(nitro_service client, onlinkipv6prefix resource) throws Exception {\n\t\tonlinkipv6prefix updateresource = new onlinkipv6prefix();\n\t\tupdateresource.ipv6prefix = resource.ipv6prefix;\n\t\tupdateresource.onlinkprefix = resource.onlinkprefix;\n\t\tupdateresource.autonomusprefix = resource.autonomusprefix;\n\t\tupdateresource.depricateprefix = resource.depricateprefix;\n\t\tupdateresource.decrementprefixlifetimes = resource.decrementprefixlifetimes;\n\t\tupdateresource.prefixvalidelifetime = resource.prefixvalidelifetime;\n\t\tupdateresource.prefixpreferredlifetime = resource.prefixpreferredlifetime;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public static nslimitselector get(nitro_service service, String selectorname) throws Exception{\n\t\tnslimitselector obj = new nslimitselector();\n\t\tobj.set_selectorname(selectorname);\n\t\tnslimitselector response = (nslimitselector) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public String getSearchJsonModel() throws IOException {\n DbSearch search = new DbSearch();\n search.setArtifacts(new ArrayList<>());\n search.setModules(new ArrayList<>());\n return JsonUtils.serialize(search);\n }"
] |
Read a list of fixed size blocks using an instance of the supplied reader class.
@param readerClass reader class
@return list of blocks | [
"public List<MapRow> readBlocks(Class<? extends BlockReader> readerClass) throws IOException\n {\n BlockReader reader;\n\n try\n {\n reader = readerClass.getConstructor(StreamReader.class).newInstance(this);\n }\n catch (Exception ex)\n {\n throw new RuntimeException(ex);\n }\n\n return reader.read();\n }"
] | [
"public Map<String, String> getTitleLocale() {\n\n if (m_localeTitles == null) {\n m_localeTitles = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object inputLocale) {\n\n Locale locale = null;\n if (null != inputLocale) {\n if (inputLocale instanceof Locale) {\n locale = (Locale)inputLocale;\n } else if (inputLocale instanceof String) {\n try {\n locale = LocaleUtils.toLocale((String)inputLocale);\n } catch (IllegalArgumentException | NullPointerException e) {\n // do nothing, just go on without locale\n }\n }\n }\n return getLocaleSpecificTitle(locale);\n }\n\n });\n }\n return m_localeTitles;\n }",
"public ResultSetAndStatement executeQuery(Query query, ClassDescriptor cld) throws PersistenceBrokerException\r\n {\r\n if (logger.isDebugEnabled())\r\n {\r\n logger.debug(\"executeQuery: \" + query);\r\n }\r\n /*\r\n\t\t * MBAIRD: we should create a scrollable resultset if the start at\r\n\t\t * index or end at index is set\r\n\t\t */\r\n boolean scrollable = ((query.getStartAtIndex() > Query.NO_START_AT_INDEX) || (query.getEndAtIndex() > Query.NO_END_AT_INDEX));\r\n /*\r\n\t\t * OR if the prefetching of relationships is being used.\r\n\t\t */\r\n if (query != null && query.getPrefetchedRelationships() != null && !query.getPrefetchedRelationships().isEmpty())\r\n {\r\n scrollable = true;\r\n }\r\n final StatementManagerIF sm = broker.serviceStatementManager();\r\n final SelectStatement sql = broker.serviceSqlGenerator().getPreparedSelectStatement(query, cld);\r\n PreparedStatement stmt = null;\r\n ResultSet rs = null;\r\n try\r\n {\r\n final int queryFetchSize = query.getFetchSize();\r\n final boolean isStoredProcedure = isStoredProcedure(sql.getStatement());\r\n stmt = sm.getPreparedStatement(cld, sql.getStatement() ,\r\n scrollable, queryFetchSize, isStoredProcedure);\r\n if (isStoredProcedure)\r\n {\r\n // Query implemented as a stored procedure, which must return a result set.\r\n // Query sytax is: { ?= call PROCEDURE_NAME(?,...,?)}\r\n getPlatform().registerOutResultSet((CallableStatement) stmt, 1);\r\n sm.bindStatement(stmt, query, cld, 2);\r\n\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeQuery: \" + stmt);\r\n\r\n stmt.execute();\r\n rs = (ResultSet) ((CallableStatement) stmt).getObject(1);\r\n }\r\n else\r\n {\r\n sm.bindStatement(stmt, query, cld, 1);\r\n\r\n if (logger.isDebugEnabled())\r\n logger.debug(\"executeQuery: \" + stmt);\r\n\r\n rs = stmt.executeQuery();\r\n }\r\n\r\n return new ResultSetAndStatement(sm, stmt, rs, sql);\r\n }\r\n catch (PersistenceBrokerException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n logger.error(\"PersistenceBrokerException during the execution of the query: \" + e.getMessage(), e);\r\n throw e;\r\n }\r\n catch (SQLException e)\r\n {\r\n // release resources on exception\r\n sm.closeResources(stmt, rs);\r\n throw ExceptionHelper.generateException(e, sql.getStatement(), null, logger, null);\r\n }\r\n }",
"private void setPropertyFilters(String filters) {\n\t\tthis.filterProperties = new HashSet<>();\n\t\tif (!\"-\".equals(filters)) {\n\t\t\tfor (String pid : filters.split(\",\")) {\n\t\t\t\tthis.filterProperties.add(Datamodel\n\t\t\t\t\t\t.makeWikidataPropertyIdValue(pid));\n\t\t\t}\n\t\t}\n\t}",
"private void initDurationPanel() {\n\n m_durationPrefixLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_DURATION_PREFIX_0));\n m_durationAfterPostfixLabel.setText(Messages.get().key(Messages.GUI_SERIALDATE_DURATION_ENDTYPE_OCC_POSTFIX_0));\n m_seriesEndDate.setDateOnly(true);\n m_seriesEndDate.setAllowInvalidValue(true);\n m_seriesEndDate.setValue(m_model.getSeriesEndDate());\n m_seriesEndDate.getTextField().addFocusHandler(new FocusHandler() {\n\n public void onFocus(FocusEvent event) {\n\n if (handleChange()) {\n onSeriesEndDateFocus(event);\n }\n\n }\n });\n }",
"public final void reset()\n {\n for (int i = 0; i < combinationIndices.length; i++)\n {\n combinationIndices[i] = i;\n }\n remainingCombinations = totalCombinations;\n }",
"protected boolean cannotInstantiate(Class<?> actionClass) {\n\t\treturn actionClass.isAnnotation() || actionClass.isInterface() || actionClass.isEnum()\n\t\t\t\t|| (actionClass.getModifiers() & Modifier.ABSTRACT) != 0 || actionClass.isAnonymousClass();\n\t}",
"private void handleIncomingRequestMessage(SerialMessage incomingMessage) {\n\t\tlogger.debug(\"Message type = REQUEST\");\n\t\tswitch (incomingMessage.getMessageClass()) {\n\t\t\tcase ApplicationCommandHandler:\n\t\t\t\thandleApplicationCommandRequest(incomingMessage);\n\t\t\t\tbreak;\n\t\t\tcase SendData:\n\t\t\t\thandleSendDataRequest(incomingMessage);\n\t\t\t\tbreak;\n\t\t\tcase ApplicationUpdate:\n\t\t\t\thandleApplicationUpdateRequest(incomingMessage);\n\t\t\t\tbreak;\n\t\tdefault:\n\t\t\tlogger.warn(String.format(\"TODO: Implement processing of Request Message = %s (0x%02X)\",\n\t\t\t\t\tincomingMessage.getMessageClass().getLabel(),\n\t\t\t\t\tincomingMessage.getMessageClass().getKey()));\n\t\t\tbreak;\t\n\t\t}\n\t}",
"public TimephasedWorkContainer getBaselineWork(ResourceAssignment assignment, ProjectCalendar calendar, TimephasedWorkNormaliser normaliser, byte[] data, boolean raw)\n {\n TimephasedWorkContainer result = null;\n\n if (data != null && data.length > 0)\n {\n LinkedList<TimephasedWork> list = null;\n\n //System.out.println(ByteArrayHelper.hexdump(data, false));\n int index = 8; // 8 byte header\n int blockSize = 40;\n double previousCumulativeWorkPerformedInMinutes = 0;\n\n Date blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 36);\n index += blockSize;\n TimephasedWork work = null;\n\n while (index + blockSize <= data.length)\n {\n double cumulativeWorkInMinutes = (double) ((long) MPPUtility.getDouble(data, index + 20)) / 1000;\n if (!Duration.durationValueEquals(cumulativeWorkInMinutes, previousCumulativeWorkPerformedInMinutes))\n {\n //double unknownWorkThisPeriodInMinutes = ((long) MPPUtility.getDouble(data, index + 0)) / 1000;\n double normalActualWorkThisPeriodInMinutes = ((double) MPPUtility.getInt(data, index + 8)) / 10;\n double normalRemainingWorkThisPeriodInMinutes = ((double) MPPUtility.getInt(data, index + 28)) / 10;\n double workThisPeriodInMinutes = cumulativeWorkInMinutes - previousCumulativeWorkPerformedInMinutes;\n double overtimeWorkThisPeriodInMinutes = workThisPeriodInMinutes - (normalActualWorkThisPeriodInMinutes + normalRemainingWorkThisPeriodInMinutes);\n double overtimeFactor = overtimeWorkThisPeriodInMinutes / (normalActualWorkThisPeriodInMinutes + normalRemainingWorkThisPeriodInMinutes);\n\n double normalWorkPerDayInMinutes = 480;\n double overtimeWorkPerDayInMinutes = normalWorkPerDayInMinutes * overtimeFactor;\n\n work = new TimephasedWork();\n work.setFinish(MPPUtility.getTimestampFromTenths(data, index + 16));\n work.setStart(blockStartDate);\n work.setTotalAmount(Duration.getInstance(workThisPeriodInMinutes, TimeUnit.MINUTES));\n work.setAmountPerDay(Duration.getInstance(normalWorkPerDayInMinutes + overtimeWorkPerDayInMinutes, TimeUnit.MINUTES));\n\n previousCumulativeWorkPerformedInMinutes = cumulativeWorkInMinutes;\n\n if (list == null)\n {\n list = new LinkedList<TimephasedWork>();\n }\n list.add(work);\n //System.out.println(work);\n }\n blockStartDate = MPPUtility.getTimestampFromTenths(data, index + 36);\n index += blockSize;\n }\n\n if (list != null)\n {\n if (work != null)\n {\n work.setFinish(assignment.getFinish());\n }\n result = new DefaultTimephasedWorkContainer(calendar, normaliser, list, raw);\n }\n }\n\n return result;\n }",
"public String calculateCacheKey(String sql, int[] columnIndexes) {\r\n\t\tStringBuilder tmp = new StringBuilder(sql.length()+4);\r\n\t\ttmp.append(sql);\r\n\t\tfor (int i=0; i < columnIndexes.length; i++){\r\n\t\t\ttmp.append(columnIndexes[i]);\r\n\t\t\ttmp.append(\"CI,\");\r\n\t\t}\r\n\t\treturn tmp.toString();\r\n\t}"
] |
Use this API to fetch authenticationradiuspolicy_vpnglobal_binding resources of given name . | [
"public static authenticationradiuspolicy_vpnglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationradiuspolicy_vpnglobal_binding obj = new authenticationradiuspolicy_vpnglobal_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationradiuspolicy_vpnglobal_binding response[] = (authenticationradiuspolicy_vpnglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"public OpenShiftAssistantTemplate parameter(String name, String value) {\n parameterValues.put(name, value);\n return this;\n }",
"private void writeBooleanField(String fieldName, Object value) throws IOException\n {\n boolean val = ((Boolean) value).booleanValue();\n if (val)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }",
"public static int getDayAsReadableInt(Calendar calendar) {\n int day = calendar.get(Calendar.DAY_OF_MONTH);\n int month = calendar.get(Calendar.MONTH) + 1;\n int year = calendar.get(Calendar.YEAR);\n return year * 10000 + month * 100 + day;\n }",
"public static responderpolicy get(nitro_service service, String name) throws Exception{\n\t\tresponderpolicy obj = new responderpolicy();\n\t\tobj.set_name(name);\n\t\tresponderpolicy response = (responderpolicy) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public Collection<Method> getAllMethods(String name) {\n final Map<ParamList, Map<Class<?>, Method>> nameMap = methods.get(name);\n if (nameMap == null) {\n return Collections.emptySet();\n }\n final Collection<Method> methods = new ArrayList<Method>();\n for (Map<Class<?>, Method> map : nameMap.values()) {\n methods.addAll(map.values());\n }\n return methods;\n }",
"private void onScrollImpl(final Vector3Axis offset, final LayoutScroller.OnScrollListener listener) {\n if (!isScrolling()) {\n mScroller = new ScrollingProcessor(offset, listener);\n mScroller.scroll();\n }\n }",
"private void logTimeTakenByPhase(GraphContext graphContext, Class<? extends RulePhase> phase, int timeTaken)\n {\n if (!timeTakenByPhase.containsKey(phase))\n {\n RulePhaseExecutionStatisticsModel model = new GraphService<>(graphContext,\n RulePhaseExecutionStatisticsModel.class).create();\n model.setRulePhase(phase.toString());\n model.setTimeTaken(timeTaken);\n model.setOrderExecuted(timeTakenByPhase.size());\n timeTakenByPhase.put(phase, model.getElement().id());\n }\n else\n {\n GraphService<RulePhaseExecutionStatisticsModel> service = new GraphService<>(graphContext,\n RulePhaseExecutionStatisticsModel.class);\n RulePhaseExecutionStatisticsModel model = service.getById(timeTakenByPhase.get(phase));\n int prevTimeTaken = model.getTimeTaken();\n model.setTimeTaken(prevTimeTaken + timeTaken);\n }\n }",
"public static Mono<Void> waitForCompletion(CloudFoundryClient cloudFoundryClient, Duration completionTimeout, String jobId) {\n return requestJobV3(cloudFoundryClient, jobId)\n .filter(job -> JobState.PROCESSING != job.getState())\n .repeatWhenEmpty(exponentialBackOff(Duration.ofSeconds(1), Duration.ofSeconds(15), completionTimeout))\n .filter(job -> JobState.FAILED == job.getState())\n .flatMap(JobUtils::getError);\n }",
"protected void parseSequencesWithColons(TokenList tokens , Sequence sequence ) {\n\n TokenList.Token t = tokens.getFirst();\n if( t == null )\n return;\n\n int state = 0;\n\n TokenList.Token start = null;\n TokenList.Token middle = null;\n TokenList.Token prev = t;\n\n boolean last = false;\n while( true ) {\n if( state == 0 ) {\n if( isVariableInteger(t) && (t.next != null && t.next.getSymbol() == Symbol.COLON) ) {\n start = t;\n state = 1;\n t = t.next;\n } else if( t != null && t.getSymbol() == Symbol.COLON ) {\n // If it starts with a colon then it must be 'all' or a type-o\n IntegerSequence range = new IntegerSequence.Range(null,null);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(range);\n TokenList.Token n = new TokenList.Token(varSequence);\n tokens.insert(t.previous, n);\n tokens.remove(t);\n t = n;\n }\n } else if( state == 1 ) {\n // var : ?\n if (isVariableInteger(t)) {\n state = 2;\n } else {\n // array range\n IntegerSequence range = new IntegerSequence.Range(start,null);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(range);\n replaceSequence(tokens, varSequence, start, prev);\n state = 0;\n }\n } else if ( state == 2 ) {\n // var:var ?\n if( t != null && t.getSymbol() == Symbol.COLON ) {\n middle = prev;\n state = 3;\n } else {\n // create for sequence with start and stop elements only\n IntegerSequence numbers = new IntegerSequence.For(start,null,prev);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(numbers);\n replaceSequence(tokens, varSequence, start, prev );\n if( t != null )\n t = t.previous;\n state = 0;\n }\n } else if ( state == 3 ) {\n // var:var: ?\n if( isVariableInteger(t) ) {\n // create 'for' sequence with three variables\n IntegerSequence numbers = new IntegerSequence.For(start,middle,t);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(numbers);\n t = replaceSequence(tokens, varSequence, start, t);\n } else {\n // array range with 2 elements\n IntegerSequence numbers = new IntegerSequence.Range(start,middle);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(numbers);\n replaceSequence(tokens, varSequence, start, prev);\n }\n state = 0;\n }\n\n if( last ) {\n break;\n } else if( t.next == null ) {\n // handle the case where it is the last token in the sequence\n last = true;\n }\n prev = t;\n t = t.next;\n }\n }"
] |
Initialize all components of this URI builder with the components of the given URI.
@param uri the URI
@return this UriComponentsBuilder | [
"public UriComponentsBuilder uri(URI uri) {\n\t\tAssert.notNull(uri, \"'uri' must not be null\");\n\t\tthis.scheme = uri.getScheme();\n\t\tif (uri.isOpaque()) {\n\t\t\tthis.ssp = uri.getRawSchemeSpecificPart();\n\t\t\tresetHierarchicalComponents();\n\t\t}\n\t\telse {\n\t\t\tif (uri.getRawUserInfo() != null) {\n\t\t\t\tthis.userInfo = uri.getRawUserInfo();\n\t\t\t}\n\t\t\tif (uri.getHost() != null) {\n\t\t\t\tthis.host = uri.getHost();\n\t\t\t}\n\t\t\tif (uri.getPort() != -1) {\n\t\t\t\tthis.port = String.valueOf(uri.getPort());\n\t\t\t}\n\t\t\tif (StringUtils.hasLength(uri.getRawPath())) {\n\t\t\t\tthis.pathBuilder = new CompositePathComponentBuilder(uri.getRawPath());\n\t\t\t}\n\t\t\tif (StringUtils.hasLength(uri.getRawQuery())) {\n\t\t\t\tthis.queryParams.clear();\n\t\t\t\tquery(uri.getRawQuery());\n\t\t\t}\n\t\t\tresetSchemeSpecificPart();\n\t\t}\n\t\tif (uri.getRawFragment() != null) {\n\t\t\tthis.fragment = uri.getRawFragment();\n\t\t}\n\t\treturn this;\n\t}"
] | [
"public static void main(String[] args) throws IOException, ClassNotFoundException {\r\n CoNLLDocumentReaderAndWriter f = new CoNLLDocumentReaderAndWriter();\r\n f.init(new SeqClassifierFlags());\r\n int numDocs = 0;\r\n int numTokens = 0;\r\n int numEntities = 0;\r\n String lastAnsBase = \"\";\r\n for (Iterator<List<CoreLabel>> it = f.getIterator(new FileReader(args[0])); it.hasNext(); ) {\r\n List<CoreLabel> doc = it.next();\r\n numDocs++;\r\n for (CoreLabel fl : doc) {\r\n // System.out.println(\"FL \" + (++i) + \" was \" + fl);\r\n if (fl.word().equals(BOUNDARY)) {\r\n continue;\r\n }\r\n String ans = fl.get(AnswerAnnotation.class);\r\n String ansBase;\r\n String ansPrefix;\r\n String[] bits = ans.split(\"-\");\r\n if (bits.length == 1) {\r\n ansBase = bits[0];\r\n ansPrefix = \"\";\r\n } else {\r\n ansBase = bits[1];\r\n ansPrefix = bits[0];\r\n }\r\n numTokens++;\r\n if (ansBase.equals(\"O\")) {\r\n } else if (ansBase.equals(lastAnsBase)) {\r\n if (ansPrefix.equals(\"B\")) {\r\n numEntities++;\r\n }\r\n } else {\r\n numEntities++;\r\n }\r\n }\r\n }\r\n System.out.println(\"File \" + args[0] + \" has \" + numDocs + \" documents, \" +\r\n numTokens + \" (non-blank line) tokens and \" +\r\n numEntities + \" entities.\");\r\n }",
"public JsonTypeDefinition projectionType(String... properties) {\n if(this.getType() instanceof Map<?, ?>) {\n Map<?, ?> type = (Map<?, ?>) getType();\n Arrays.sort(properties);\n Map<String, Object> newType = new LinkedHashMap<String, Object>();\n for(String prop: properties)\n newType.put(prop, type.get(prop));\n return new JsonTypeDefinition(newType);\n } else {\n throw new IllegalArgumentException(\"Cannot take the projection of a type that is not a Map.\");\n }\n }",
"public static MediaType binary( MediaType.Type type, String subType ) {\n return new MediaType( type, subType, true );\n }",
"private void queryDatabaseMetaData()\n {\n ResultSet rs = null;\n\n try\n {\n Set<String> tables = new HashSet<String>();\n DatabaseMetaData dmd = m_connection.getMetaData();\n rs = dmd.getTables(null, null, null, null);\n while (rs.next())\n {\n tables.add(rs.getString(\"TABLE_NAME\"));\n }\n\n m_hasResourceBaselines = tables.contains(\"MSP_RESOURCE_BASELINES\");\n m_hasTaskBaselines = tables.contains(\"MSP_TASK_BASELINES\");\n m_hasAssignmentBaselines = tables.contains(\"MSP_ASSIGNMENT_BASELINES\");\n }\n\n catch (Exception ex)\n {\n // Ignore errors when reading meta data\n }\n\n finally\n {\n if (rs != null)\n {\n try\n {\n rs.close();\n }\n\n catch (SQLException ex)\n {\n // Ignore errors when closing result set\n }\n rs = null;\n }\n }\n }",
"public static rnat_stats get(nitro_service service) throws Exception{\n\t\trnat_stats obj = new rnat_stats();\n\t\trnat_stats[] response = (rnat_stats[])obj.stat_resources(service);\n\t\treturn response[0];\n\t}",
"protected void propagateOnTouch(GVRPickedObject hit)\n {\n if (mEventOptions.contains(EventOptions.SEND_TOUCH_EVENTS))\n {\n GVREventManager eventManager = getGVRContext().getEventManager();\n GVRSceneObject hitObject = hit.getHitObject();\n if (mEventOptions.contains(EventOptions.SEND_TO_LISTENERS))\n {\n eventManager.sendEvent(this, ITouchEvents.class, \"onTouchStart\", hitObject, hit);\n }\n if (mEventOptions.contains(EventOptions.SEND_TO_HIT_OBJECT))\n {\n eventManager.sendEvent(hitObject, ITouchEvents.class, \"onTouchStart\", hitObject, hit);\n }\n if (mEventOptions.contains(EventOptions.SEND_TO_SCENE) && (mScene != null))\n {\n eventManager.sendEvent(mScene, ITouchEvents.class, \"onTouchStart\", hitObject, hit);\n }\n }\n }",
"public E get(int i) {\r\n if (i < 0 || i >= objects.size())\r\n throw new ArrayIndexOutOfBoundsException(\"Index \" + i + \r\n \" outside the bounds [0,\" + \r\n size() + \")\");\r\n return objects.get(i);\r\n }",
"public boolean hasProperties(Set<PropertyKey> keys) {\n for (PropertyKey key : keys) {\n if (null == getProperty(key.m_key)) {\n return false;\n }\n }\n \n return true;\n }",
"@NonNull public CharSequence getQuery() {\n if (searchView != null) {\n return searchView.getQuery();\n } else if (supportView != null) {\n return supportView.getQuery();\n }\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }"
] |
Called when the pattern has changed. | [
"void onPatternChange() {\n\n PatternType patternType = m_model.getPatternType();\n boolean isSeries = !patternType.equals(PatternType.NONE);\n setSerialOptionsVisible(isSeries);\n m_seriesCheckBox.setChecked(isSeries);\n if (isSeries) {\n m_groupPattern.selectButton(m_patternButtons.get(patternType));\n m_controller.getPatternView().onValueChange();\n m_patternOptions.setWidget(m_controller.getPatternView());\n onEndTypeChange();\n }\n m_controller.sizeChanged();\n }"
] | [
"protected boolean boot(List<ModelNode> bootOperations, boolean rollbackOnRuntimeFailure) throws ConfigurationPersistenceException {\n return boot(bootOperations, rollbackOnRuntimeFailure, false, ModelControllerImpl.getMutableRootResourceRegistrationProvider());\n }",
"public void authenticate() {\n URL url;\n try {\n url = new URL(this.getTokenURL());\n } catch (MalformedURLException e) {\n assert false : \"An invalid token URL indicates a bug in the SDK.\";\n throw new RuntimeException(\"An invalid token URL indicates a bug in the SDK.\", e);\n }\n\n String jwtAssertion = this.constructJWTAssertion();\n\n String urlParameters = String.format(JWT_GRANT_TYPE, this.getClientID(), this.getClientSecret(), jwtAssertion);\n\n BoxAPIRequest request = new BoxAPIRequest(this, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n String json;\n try {\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n json = response.getJSON();\n } catch (BoxAPIException ex) {\n // Use the Date advertised by the Box server as the current time to synchronize clocks\n List<String> responseDates = ex.getHeaders().get(\"Date\");\n NumericDate currentTime;\n if (responseDates != null) {\n String responseDate = responseDates.get(0);\n SimpleDateFormat dateFormat = new SimpleDateFormat(\"EEE, d MMM yyyy HH:mm:ss zzz\");\n try {\n Date date = dateFormat.parse(responseDate);\n currentTime = NumericDate.fromMilliseconds(date.getTime());\n } catch (ParseException e) {\n currentTime = NumericDate.now();\n }\n } else {\n currentTime = NumericDate.now();\n }\n\n // Reconstruct the JWT assertion, which regenerates the jti claim, with the new \"current\" time\n jwtAssertion = this.constructJWTAssertion(currentTime);\n urlParameters = String.format(JWT_GRANT_TYPE, this.getClientID(), this.getClientSecret(), jwtAssertion);\n\n // Re-send the updated request\n request = new BoxAPIRequest(this, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n json = response.getJSON();\n }\n\n JsonObject jsonObject = JsonObject.readFrom(json);\n this.setAccessToken(jsonObject.get(\"access_token\").asString());\n this.setLastRefresh(System.currentTimeMillis());\n this.setExpires(jsonObject.get(\"expires_in\").asLong() * 1000);\n\n //if token cache is specified, save to cache\n if (this.accessTokenCache != null) {\n String key = this.getAccessTokenCacheKey();\n JsonObject accessTokenCacheInfo = new JsonObject()\n .add(\"accessToken\", this.getAccessToken())\n .add(\"lastRefresh\", this.getLastRefresh())\n .add(\"expires\", this.getExpires());\n\n this.accessTokenCache.put(key, accessTokenCacheInfo.toString());\n }\n }",
"private String readHeaderString(BufferedInputStream stream) throws IOException\n {\n int bufferSize = 100;\n stream.mark(bufferSize);\n byte[] buffer = new byte[bufferSize];\n stream.read(buffer);\n Charset charset = CharsetHelper.UTF8;\n String header = new String(buffer, charset);\n int prefixIndex = header.indexOf(\"PPX!!!!|\");\n int suffixIndex = header.indexOf(\"|!!!!XPP\");\n\n if (prefixIndex != 0 || suffixIndex == -1)\n {\n throw new IOException(\"File format not recognised\");\n }\n\n int skip = suffixIndex + 9;\n stream.reset();\n stream.skip(skip);\n\n return header.substring(prefixIndex + 8, suffixIndex);\n }",
"@SuppressWarnings(\"WeakerAccess\")\n public static synchronized SlotReference getSlotReference(int player, CdjStatus.TrackSourceSlot slot) {\n Map<CdjStatus.TrackSourceSlot, SlotReference> playerMap = instances.get(player);\n if (playerMap == null) {\n playerMap = new HashMap<CdjStatus.TrackSourceSlot, SlotReference>();\n instances.put(player, playerMap);\n }\n SlotReference result = playerMap.get(slot);\n if (result == null) {\n result = new SlotReference(player, slot);\n playerMap.put(slot, result);\n }\n return result;\n }",
"public static GraphTraversal<Vertex, Vertex> addPipeFor(GraphTraversal<Vertex, Vertex> pipeline,\n Class<? extends WindupVertexFrame> clazz)\n {\n pipeline.has(WindupVertexFrame.TYPE_PROP, GraphTypeManager.getTypeValue(clazz));\n return pipeline;\n }",
"public static void startNamedTimer(String timerName, int todoFlags,\n\t\t\tlong threadId) {\n\t\tgetNamedTimer(timerName, todoFlags, threadId).start();\n\t}",
"private boolean interpolationsDisagree(TrackPositionUpdate lastUpdate, TrackPositionUpdate currentUpdate) {\n long now = System.nanoTime();\n return Math.abs(interpolateTimeSinceUpdate(lastUpdate, now) - interpolateTimeSinceUpdate(currentUpdate, now)) >\n slack.get();\n }",
"void attachMetadataCacheInternal(SlotReference slot, MetadataCache cache) {\n MetadataCache oldCache = metadataCacheFiles.put(slot, cache);\n if (oldCache != null) {\n try {\n oldCache.close();\n } catch (IOException e) {\n logger.error(\"Problem closing previous metadata cache\", e);\n }\n }\n\n deliverCacheUpdate(slot, cache);\n }",
"public static base_response add(nitro_service client, vpath resource) throws Exception {\n\t\tvpath addresource = new vpath();\n\t\taddresource.name = resource.name;\n\t\taddresource.destip = resource.destip;\n\t\taddresource.encapmode = resource.encapmode;\n\t\treturn addresource.add_resource(client);\n\t}"
] |
Deletes a chain of vertices from this list. | [
"public void delete(Vertex vtx1, Vertex vtx2) {\n if (vtx1.prev == null) {\n head = vtx2.next;\n } else {\n vtx1.prev.next = vtx2.next;\n }\n if (vtx2.next == null) {\n tail = vtx1.prev;\n } else {\n vtx2.next.prev = vtx1.prev;\n }\n }"
] | [
"private void updateBundleDescriptorContent() throws CmsXmlException {\n\n if (m_descContent.hasLocale(Descriptor.LOCALE)) {\n m_descContent.removeLocale(Descriptor.LOCALE);\n }\n m_descContent.addLocale(m_cms, Descriptor.LOCALE);\n\n int i = 0;\n Property<Object> descProp;\n String desc;\n Property<Object> defaultValueProp;\n String defaultValue;\n Map<String, Item> keyItemMap = getKeyItemMap();\n List<String> keys = new ArrayList<String>(keyItemMap.keySet());\n Collections.sort(keys, CmsCaseInsensitiveStringComparator.getInstance());\n for (Object key : keys) {\n if ((null != key) && !key.toString().isEmpty()) {\n\n m_descContent.addValue(m_cms, Descriptor.N_MESSAGE, Descriptor.LOCALE, i);\n i++;\n String messagePrefix = Descriptor.N_MESSAGE + \"[\" + i + \"]/\";\n\n m_descContent.getValue(messagePrefix + Descriptor.N_KEY, Descriptor.LOCALE).setStringValue(\n m_cms,\n (String)key);\n descProp = keyItemMap.get(key).getItemProperty(TableProperty.DESCRIPTION);\n if ((null != descProp) && (null != descProp.getValue())) {\n desc = descProp.getValue().toString();\n m_descContent.getValue(messagePrefix + Descriptor.N_DESCRIPTION, Descriptor.LOCALE).setStringValue(\n m_cms,\n desc);\n }\n\n defaultValueProp = keyItemMap.get(key).getItemProperty(TableProperty.DEFAULT);\n if ((null != defaultValueProp) && (null != defaultValueProp.getValue())) {\n defaultValue = defaultValueProp.getValue().toString();\n m_descContent.getValue(messagePrefix + Descriptor.N_DEFAULT, Descriptor.LOCALE).setStringValue(\n m_cms,\n defaultValue);\n }\n\n }\n }\n\n }",
"public static <T> String join(Collection<T> col, String delim) {\n StringBuilder sb = new StringBuilder();\n Iterator<T> iter = col.iterator();\n if (iter.hasNext())\n sb.append(iter.next().toString());\n while (iter.hasNext()) {\n sb.append(delim);\n sb.append(iter.next().toString());\n }\n return sb.toString();\n }",
"public static boolean isAvroSchema(String serializerName) {\n if(serializerName.equals(AVRO_GENERIC_VERSIONED_TYPE_NAME)\n || serializerName.equals(AVRO_GENERIC_TYPE_NAME)\n || serializerName.equals(AVRO_REFLECTIVE_TYPE_NAME)\n || serializerName.equals(AVRO_SPECIFIC_TYPE_NAME)) {\n return true;\n } else {\n return false;\n }\n }",
"private boolean absoluteAdvanced(int row)\r\n {\r\n boolean retval = false;\r\n \r\n try\r\n {\r\n if (getRsAndStmt().m_rs != null)\r\n {\r\n if (row == 0)\r\n {\r\n getRsAndStmt().m_rs.beforeFirst();\r\n }\r\n else\r\n {\r\n retval = getRsAndStmt().m_rs.absolute(row); \r\n }\r\n m_current_row = row;\r\n setHasCalledCheck(false);\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n advancedJDBCSupport = false;\r\n }\r\n return retval;\r\n }",
"private void writeCalendar(ProjectCalendar mpxj)\n {\n CalendarType xml = m_factory.createCalendarType();\n m_apibo.getCalendar().add(xml);\n String type = mpxj.getResource() == null ? \"Global\" : \"Resource\";\n\n xml.setBaseCalendarObjectId(getCalendarUniqueID(mpxj.getParent()));\n xml.setIsPersonal(mpxj.getResource() == null ? Boolean.FALSE : Boolean.TRUE);\n xml.setName(mpxj.getName());\n xml.setObjectId(mpxj.getUniqueID());\n xml.setType(type);\n\n StandardWorkWeek xmlStandardWorkWeek = m_factory.createCalendarTypeStandardWorkWeek();\n xml.setStandardWorkWeek(xmlStandardWorkWeek);\n\n for (Day day : EnumSet.allOf(Day.class))\n {\n StandardWorkHours xmlHours = m_factory.createCalendarTypeStandardWorkWeekStandardWorkHours();\n xmlStandardWorkWeek.getStandardWorkHours().add(xmlHours);\n xmlHours.setDayOfWeek(getDayName(day));\n\n for (DateRange range : mpxj.getHours(day))\n {\n WorkTimeType xmlWorkTime = m_factory.createWorkTimeType();\n xmlHours.getWorkTime().add(xmlWorkTime);\n\n xmlWorkTime.setStart(range.getStart());\n xmlWorkTime.setFinish(getEndTime(range.getEnd()));\n }\n }\n\n HolidayOrExceptions xmlExceptions = m_factory.createCalendarTypeHolidayOrExceptions();\n xml.setHolidayOrExceptions(xmlExceptions);\n\n if (!mpxj.getCalendarExceptions().isEmpty())\n {\n Calendar calendar = DateHelper.popCalendar();\n for (ProjectCalendarException mpxjException : mpxj.getCalendarExceptions())\n {\n calendar.setTime(mpxjException.getFromDate());\n while (calendar.getTimeInMillis() < mpxjException.getToDate().getTime())\n {\n HolidayOrException xmlException = m_factory.createCalendarTypeHolidayOrExceptionsHolidayOrException();\n xmlExceptions.getHolidayOrException().add(xmlException);\n\n xmlException.setDate(calendar.getTime());\n\n for (DateRange range : mpxjException)\n {\n WorkTimeType xmlHours = m_factory.createWorkTimeType();\n xmlException.getWorkTime().add(xmlHours);\n\n xmlHours.setStart(range.getStart());\n\n if (range.getEnd() != null)\n {\n xmlHours.setFinish(getEndTime(range.getEnd()));\n }\n }\n calendar.add(Calendar.DAY_OF_YEAR, 1);\n }\n }\n DateHelper.pushCalendar(calendar);\n }\n }",
"public HttpRequestFactory makeClient(DatastoreOptions options) {\n Credential credential = options.getCredential();\n HttpTransport transport = options.getTransport();\n if (transport == null) {\n transport = credential == null ? new NetHttpTransport() : credential.getTransport();\n transport = transport == null ? new NetHttpTransport() : transport;\n }\n return transport.createRequestFactory(credential);\n }",
"public static <T> boolean containsAny(Collection<T> collection, Collection<T> toCheck){\r\n for(T c: toCheck){\r\n if(collection.contains(c))\r\n return true;\r\n }\r\n return false;\r\n \r\n }",
"protected void prepForWrite(SelectionKey selectionKey) {\n if(logger.isTraceEnabled())\n traceInputBufferState(\"About to clear read buffer\");\n\n if(requestHandlerFactory.shareReadWriteBuffer() == false) {\n inputStream.clear();\n }\n\n if(logger.isTraceEnabled())\n traceInputBufferState(\"Cleared read buffer\");\n\n outputStream.getBuffer().flip();\n selectionKey.interestOps(SelectionKey.OP_WRITE);\n }",
"private String parameter(Options opt, Parameter p[]) {\n\tStringBuilder par = new StringBuilder(1000);\n\tfor (int i = 0; i < p.length; i++) {\n\t par.append(p[i].name() + typeAnnotation(opt, p[i].type()));\n\t if (i + 1 < p.length)\n\t\tpar.append(\", \");\n\t}\n\treturn par.toString();\n }"
] |
Use this API to delete application. | [
"public static base_response delete(nitro_service client, application resource) throws Exception {\n\t\tapplication deleteresource = new application();\n\t\tdeleteresource.appname = resource.appname;\n\t\treturn deleteresource.delete_resource(client);\n\t}"
] | [
"public FindByIndexOptions useIndex(String designDocument, String indexName) {\r\n assertNotNull(designDocument, \"designDocument\");\r\n assertNotNull(indexName, \"indexName\");\r\n JsonArray index = new JsonArray();\r\n index.add(new JsonPrimitive(designDocument));\r\n index.add(new JsonPrimitive(indexName));\r\n this.useIndex = index;\r\n return this;\r\n }",
"public void setParent(ProjectCalendar calendar)\n {\n // I've seen a malformed MSPDI file which sets the parent calendar to itself.\n // Silently ignore this here.\n if (calendar != this)\n {\n if (getParent() != null)\n {\n getParent().removeDerivedCalendar(this);\n }\n\n super.setParent(calendar);\n\n if (calendar != null)\n {\n calendar.addDerivedCalendar(this);\n }\n clearWorkingDateCache();\n }\n }",
"private long doMemoryManagementAndPerFrameCallbacks() {\n long currentTime = GVRTime.getCurrentTime();\n mFrameTime = (currentTime - mPreviousTimeNanos) / 1e9f;\n mPreviousTimeNanos = currentTime;\n\n /*\n * Without the sensor data, can't draw a scene properly.\n */\n if (!(mSensoredScene == null || !mMainScene.equals(mSensoredScene))) {\n Runnable runnable;\n while ((runnable = mRunnables.poll()) != null) {\n try {\n runnable.run();\n } catch (final Exception exc) {\n Log.e(TAG, \"Runnable-on-GL %s threw %s\", runnable, exc.toString());\n exc.printStackTrace();\n }\n }\n\n final List<GVRDrawFrameListener> frameListeners = mFrameListeners;\n for (GVRDrawFrameListener listener : frameListeners) {\n try {\n listener.onDrawFrame(mFrameTime);\n } catch (final Exception exc) {\n Log.e(TAG, \"DrawFrameListener %s threw %s\", listener, exc.toString());\n exc.printStackTrace();\n }\n }\n }\n\n return currentTime;\n }",
"public void edit(Note note) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_EDIT);\r\n\r\n parameters.put(\"note_id\", note.getId());\r\n Rectangle bounds = note.getBounds();\r\n if (bounds != null) {\r\n parameters.put(\"note_x\", String.valueOf(bounds.x));\r\n parameters.put(\"note_y\", String.valueOf(bounds.y));\r\n parameters.put(\"note_w\", String.valueOf(bounds.width));\r\n parameters.put(\"note_h\", String.valueOf(bounds.height));\r\n }\r\n String text = note.getText();\r\n if (text != null) {\r\n parameters.put(\"note_text\", text);\r\n }\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }",
"private String formatDate(Date date) {\n\n if (null == m_dateFormat) {\n m_dateFormat = DateFormat.getDateInstance(\n 0,\n OpenCms.getWorkplaceManager().getWorkplaceLocale(getCmsObject()));\n }\n return m_dateFormat.format(date);\n }",
"private void initAdapter()\n {\n Connection tmp = null;\n DatabaseMetaData meta = null;\n try\n {\n tmp = _ds.getConnection();\n meta = tmp.getMetaData();\n product = meta.getDatabaseProductName().toLowerCase();\n }\n catch (SQLException e)\n {\n throw new DatabaseException(\"Cannot connect to the database\", e);\n }\n finally\n {\n try\n {\n if (tmp != null)\n {\n tmp.close();\n }\n }\n catch (SQLException e)\n {\n // Nothing to do.\n }\n }\n\n DbAdapter newAdpt = null;\n for (String s : ADAPTERS)\n {\n try\n {\n Class<? extends DbAdapter> clazz = Db.class.getClassLoader().loadClass(s).asSubclass(DbAdapter.class);\n newAdpt = clazz.newInstance();\n if (newAdpt.compatibleWith(meta))\n {\n adapter = newAdpt;\n break;\n }\n }\n catch (Exception e)\n {\n throw new DatabaseException(\"Issue when loading database adapter named: \" + s, e);\n }\n }\n\n if (adapter == null)\n {\n throw new DatabaseException(\"Unsupported database! There is no JQM database adapter compatible with product name \" + product);\n }\n else\n {\n jqmlogger.info(\"Using database adapter {}\", adapter.getClass().getCanonicalName());\n }\n }",
"public PreparedStatement getSelectByPKStatement(ClassDescriptor cds) throws PersistenceBrokerSQLException, PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cds.getStatementsForClass(m_conMan).getSelectByPKStmt(m_conMan.getConnection());\r\n }\r\n catch (SQLException e)\r\n {\r\n throw new PersistenceBrokerSQLException(\"Could not build statement ask for\", e);\r\n }\r\n catch (LookupException e)\r\n {\r\n throw new PersistenceBrokerException(\"Used ConnectionManager instance could not obtain a connection\", e);\r\n }\r\n }",
"public Constructor<?> getCompatibleConstructor(Class<?> type,\r\n\t\t\tClass<?> argumentType) {\r\n\t\ttry {\r\n\t\t\treturn type.getConstructor(new Class[] { argumentType });\r\n\t\t} catch (Exception e) {\r\n\t\t\t// get public classes and interfaces\r\n\t\t\tClass<?>[] types = type.getClasses();\r\n\r\n\t\t\tfor (int i = 0; i < types.length; i++) {\r\n\t\t\t\ttry {\r\n\t\t\t\t\treturn type.getConstructor(new Class[] { types[i] });\r\n\t\t\t\t} catch (Exception e1) {\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn null;\r\n\t}",
"public List<Map<String, String>> produceNWise(int nWise, String[] coVariables, Map<String, String[]> variableDomains) {\r\n List<Set<String>> tuples = makeNWiseTuples(coVariables, nWise);\n\r\n List<Map<String, String>> testCases = new ArrayList<>();\r\n for (Set<String> tuple : tuples) {\r\n testCases.addAll(expandTupleIntoTestCases(tuple, variableDomains));\r\n }\n\r\n return testCases;\r\n }"
] |
Parse JSON parameters from this request.
@param jsonRequest The request in the JSON format.
@return CmsSpellcheckingRequest object that contains parsed parameters or null, if JSON input is not well
defined. | [
"private CmsSpellcheckingRequest parseJsonRequest(JSONObject jsonRequest) {\n\n final String id = jsonRequest.optString(JSON_ID);\n\n final JSONObject params = jsonRequest.optJSONObject(JSON_PARAMS);\n\n if (null == params) {\n LOG.debug(\"Invalid JSON request: No field \\\"params\\\" defined. \");\n return null;\n }\n final JSONArray words = params.optJSONArray(JSON_WORDS);\n final String lang = params.optString(JSON_LANG, LANG_DEFAULT);\n if (null == words) {\n LOG.debug(\"Invalid JSON request: No field \\\"words\\\" defined. \");\n return null;\n }\n\n // Convert JSON array to array of type String\n final List<String> wordsToCheck = new LinkedList<String>();\n for (int i = 0; i < words.length(); i++) {\n final String word = words.opt(i).toString();\n wordsToCheck.add(word);\n\n if (Character.isUpperCase(word.codePointAt(0))) {\n wordsToCheck.add(word.toLowerCase());\n }\n }\n\n return new CmsSpellcheckingRequest(wordsToCheck.toArray(new String[wordsToCheck.size()]), lang, id);\n }"
] | [
"public void setProductModules(final String name, final List<String> moduleNames) {\n final DbProduct dbProduct = getProduct(name);\n dbProduct.setModules(moduleNames);\n repositoryHandler.store(dbProduct);\n }",
"public static base_responses add(nitro_service client, dospolicy resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tdospolicy addresources[] = new dospolicy[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new dospolicy();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].qdepth = resources[i].qdepth;\n\t\t\t\taddresources[i].cltdetectrate = resources[i].cltdetectrate;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}",
"private void sendOneAsyncHint(final ByteArray slopKey,\n final Versioned<byte[]> slopVersioned,\n final List<Node> nodesToTry) {\n Node nodeToHostHint = null;\n boolean foundNode = false;\n while(nodesToTry.size() > 0) {\n nodeToHostHint = nodesToTry.remove(0);\n if(!failedNodes.contains(nodeToHostHint) && failureDetector.isAvailable(nodeToHostHint)) {\n foundNode = true;\n break;\n }\n }\n if(!foundNode) {\n Slop slop = slopSerializer.toObject(slopVersioned.getValue());\n logger.error(\"Trying to send an async hint but used up all nodes. key: \"\n + slop.getKey() + \" version: \" + slopVersioned.getVersion().toString());\n return;\n }\n final Node node = nodeToHostHint;\n int nodeId = node.getId();\n\n NonblockingStore nonblockingStore = nonblockingSlopStores.get(nodeId);\n Utils.notNull(nonblockingStore);\n\n final Long startNs = System.nanoTime();\n NonblockingStoreCallback callback = new NonblockingStoreCallback() {\n\n @Override\n public void requestComplete(Object result, long requestTime) {\n Slop slop = null;\n boolean loggerDebugEnabled = logger.isDebugEnabled();\n if(loggerDebugEnabled) {\n slop = slopSerializer.toObject(slopVersioned.getValue());\n }\n Response<ByteArray, Object> response = new Response<ByteArray, Object>(node,\n slopKey,\n result,\n requestTime);\n if(response.getValue() instanceof Exception\n && !(response.getValue() instanceof ObsoleteVersionException)) {\n if(!failedNodes.contains(node))\n failedNodes.add(node);\n if(response.getValue() instanceof UnreachableStoreException) {\n UnreachableStoreException use = (UnreachableStoreException) response.getValue();\n\n if(loggerDebugEnabled) {\n logger.debug(\"Write of key \" + slop.getKey() + \" for \"\n + slop.getNodeId() + \" to node \" + node\n + \" failed due to unreachable: \" + use.getMessage());\n }\n\n failureDetector.recordException(node, (System.nanoTime() - startNs)\n / Time.NS_PER_MS, use);\n }\n sendOneAsyncHint(slopKey, slopVersioned, nodesToTry);\n }\n\n if(loggerDebugEnabled)\n logger.debug(\"Slop write of key \" + slop.getKey() + \" for node \"\n + slop.getNodeId() + \" to node \" + node + \" succeeded in \"\n + (System.nanoTime() - startNs) + \" ns\");\n\n failureDetector.recordSuccess(node, (System.nanoTime() - startNs) / Time.NS_PER_MS);\n\n }\n };\n nonblockingStore.submitPutRequest(slopKey, slopVersioned, null, callback, timeoutMs);\n }",
"public static int compare(double a, double b, double delta) {\n if (equals(a, b, delta)) {\n return 0;\n }\n return Double.compare(a, b);\n }",
"public static float distance(final float ax, final float ay,\n final float bx, final float by) {\n return (float) Math.sqrt(\n (ax - bx) * (ax - bx) +\n (ay - by) * (ay - by)\n );\n }",
"@Override\n\tpublic Inet6Address toInetAddress() {\n\t\tif(hasZone()) {\n\t\t\tInet6Address result;\n\t\t\tif(hasNoValueCache() || (result = valueCache.inetAddress) == null) {\n\t\t\t\tvalueCache.inetAddress = result = (Inet6Address) toInetAddressImpl(getBytes());\n\t\t\t}\n\t\t\treturn result;\n\t\t}\n\t\treturn (Inet6Address) super.toInetAddress();\n\t}",
"public void updateExceptions(SortedSet<Date> exceptions) {\r\n\r\n SortedSet<Date> e = null == exceptions ? new TreeSet<Date>() : exceptions;\r\n if (!m_model.getExceptions().equals(e)) {\r\n m_model.setExceptions(e);\r\n m_view.updateExceptions();\r\n valueChanged();\r\n sizeChanged();\r\n }\r\n\r\n }",
"public String checkIn(byte[] data) {\n String id = UUID.randomUUID().toString();\n dataMap.put(id, data);\n return id;\n }",
"@SuppressWarnings(\"unchecked\")\n public List<Field> getValueAsList() {\n return (List<Field>) type.convert(getValue(), Type.LIST);\n }"
] |
Helper function to find the beat grid section in a rekordbox track analysis file.
@param anlzFile the file that was downloaded from the player
@return the section containing the beat grid | [
"private RekordboxAnlz.BeatGridTag findTag(RekordboxAnlz anlzFile) {\n for (RekordboxAnlz.TaggedSection section : anlzFile.sections()) {\n if (section.body() instanceof RekordboxAnlz.BeatGridTag) {\n return (RekordboxAnlz.BeatGridTag) section.body();\n }\n }\n throw new IllegalArgumentException(\"No beat grid found inside analysis file \" + anlzFile);\n }"
] | [
"private int determineForkedJvmCount(TestsCollection testCollection) {\n int cores = Runtime.getRuntime().availableProcessors();\n int jvmCount;\n if (this.parallelism.equals(PARALLELISM_AUTO)) {\n if (cores >= 8) {\n // Maximum parallel jvms is 4, conserve some memory and memory bandwidth.\n jvmCount = 4;\n } else if (cores >= 4) {\n // Make some space for the aggregator.\n jvmCount = 3;\n } else if (cores == 3) {\n // Yes, three-core chips are a thing.\n jvmCount = 2;\n } else {\n // even for dual cores it usually makes no sense to fork more than one\n // JVM.\n jvmCount = 1;\n }\n } else if (this.parallelism.equals(PARALLELISM_MAX)) {\n jvmCount = Runtime.getRuntime().availableProcessors();\n } else {\n try {\n jvmCount = Math.max(1, Integer.parseInt(parallelism));\n } catch (NumberFormatException e) {\n throw new BuildException(\"parallelism must be 'auto', 'max' or a valid integer: \"\n + parallelism);\n }\n }\n\n if (!testCollection.hasReplicatedSuites()) {\n jvmCount = Math.min(testCollection.testClasses.size(), jvmCount);\n }\n return jvmCount;\n }",
"public void addBeanToBeanMapping(BeanToBeanMapping beanToBeanMapping) {\r\n\t\tbeanToBeanMappings.put(ClassPair.get(beanToBeanMapping\r\n\t\t\t\t.getSourceClass(), beanToBeanMapping.getDestinationClass()),\r\n\t\t\t\tbeanToBeanMapping);\r\n\t}",
"public void open(File versionDir) {\n /* acquire modification lock */\n fileModificationLock.writeLock().lock();\n try {\n /* check that the store is currently closed */\n if(isOpen)\n throw new IllegalStateException(\"Attempt to open already open store.\");\n\n // Find version directory from symbolic link or max version id\n if(versionDir == null) {\n versionDir = ReadOnlyUtils.getCurrentVersion(storeDir);\n\n if(versionDir == null)\n versionDir = new File(storeDir, \"version-0\");\n }\n\n // Set the max version id\n long versionId = ReadOnlyUtils.getVersionId(versionDir);\n if(versionId == -1) {\n throw new VoldemortException(\"Unable to parse id from version directory \"\n + versionDir.getAbsolutePath());\n }\n Utils.mkdirs(versionDir);\n\n // Validate symbolic link, and create it if it doesn't already exist\n Utils.symlink(versionDir.getAbsolutePath(), storeDir.getAbsolutePath() + File.separator + \"latest\");\n this.fileSet = new ChunkedFileSet(versionDir, routingStrategy, nodeId, maxValueBufferAllocationSize);\n storeVersionManager.syncInternalStateFromFileSystem(false);\n this.lastSwapped = System.currentTimeMillis();\n this.isOpen = true;\n } catch(IOException e) {\n logger.error(\"Error in opening store\", e);\n } finally {\n fileModificationLock.writeLock().unlock();\n }\n }",
"public static File guessKeyRingFile() throws FileNotFoundException {\n final Collection<String> possibleLocations = getKnownPGPSecureRingLocations();\n for (final String location : possibleLocations) {\n final File candidate = new File(location);\n if (candidate.exists()) {\n return candidate;\n }\n }\n final StringBuilder message = new StringBuilder(\"Could not locate secure keyring, locations tried: \");\n final Iterator<String> it = possibleLocations.iterator();\n while (it.hasNext()) {\n message.append(it.next());\n if (it.hasNext()) {\n message.append(\", \");\n }\n }\n throw new FileNotFoundException(message.toString());\n }",
"private void processCalendarException(ProjectCalendar calendar, Row row)\n {\n Date fromDate = row.getDate(\"CD_FROM_DATE\");\n Date toDate = row.getDate(\"CD_TO_DATE\");\n boolean working = row.getInt(\"CD_WORKING\") != 0;\n ProjectCalendarException exception = calendar.addCalendarException(fromDate, toDate);\n if (working)\n {\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME1\"), row.getDate(\"CD_TO_TIME1\")));\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME2\"), row.getDate(\"CD_TO_TIME2\")));\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME3\"), row.getDate(\"CD_TO_TIME3\")));\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME4\"), row.getDate(\"CD_TO_TIME4\")));\n exception.addRange(new DateRange(row.getDate(\"CD_FROM_TIME5\"), row.getDate(\"CD_TO_TIME5\")));\n }\n }",
"Map<String, String> packageNameMap() {\n if (packageNames == null) {\n return emptyMap();\n }\n\n Map<String, String> names = new LinkedHashMap<String, String>();\n for (PackageName name : packageNames) {\n names.put(name.getUri(), name.getPackage());\n }\n return names;\n }",
"private void performSetupExchange() throws IOException {\n Message setupRequest = new Message(0xfffffffeL, Message.KnownType.SETUP_REQ, new NumberField(posingAsPlayer, 4));\n sendMessage(setupRequest);\n Message response = Message.read(is);\n if (response.knownType != Message.KnownType.MENU_AVAILABLE) {\n throw new IOException(\"Did not receive message type 0x4000 in response to setup message, got: \" + response);\n }\n if (response.arguments.size() != 2) {\n throw new IOException(\"Did not receive two arguments in response to setup message, got: \" + response);\n }\n final Field player = response.arguments.get(1);\n if (!(player instanceof NumberField)) {\n throw new IOException(\"Second argument in response to setup message was not a number: \" + response);\n }\n if (((NumberField)player).getValue() != targetPlayer) {\n throw new IOException(\"Expected to connect to player \" + targetPlayer +\n \", but welcome response identified itself as player \" + ((NumberField)player).getValue());\n }\n }",
"public static base_responses unset(nitro_service client, String certkey[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (certkey != null && certkey.length > 0) {\n\t\t\tsslcertkey unsetresources[] = new sslcertkey[certkey.length];\n\t\t\tfor (int i=0;i<certkey.length;i++){\n\t\t\t\tunsetresources[i] = new sslcertkey();\n\t\t\t\tunsetresources[i].certkey = certkey[i];\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}",
"public StitchObjectMapper withCodecRegistry(final CodecRegistry codecRegistry) {\n // We can't detect if their codecRegistry has any duplicate providers. There's also a chance\n // that putting ours first may prevent decoding of some of their classes if for example they\n // have their own way of decoding an Integer.\n final CodecRegistry newReg =\n CodecRegistries.fromRegistries(BsonUtils.DEFAULT_CODEC_REGISTRY, codecRegistry);\n return new StitchObjectMapper(this, newReg);\n }"
] |
Insert syntax for our special table
@param sequenceName
@param maxKey
@return sequence insert statement | [
"protected String sp_createSequenceQuery(String sequenceName, long maxKey)\r\n {\r\n return \"insert into \" + SEQ_TABLE_NAME + \" (\"\r\n + SEQ_NAME_STRING + \",\" + SEQ_ID_STRING +\r\n \") values ('\" + sequenceName + \"',\" + maxKey + \")\";\r\n }"
] | [
"protected DataSource getDataSource(JdbcConnectionDescriptor jcd)\r\n throws LookupException\r\n {\r\n final PBKey key = jcd.getPBKey();\r\n DataSource ds = (DataSource) dsMap.get(key);\r\n if (ds == null)\r\n {\r\n // Found no pool for PBKey\r\n try\r\n {\r\n synchronized (poolSynch)\r\n {\r\n // Setup new object pool\r\n ObjectPool pool = setupPool(jcd);\r\n poolMap.put(key, pool);\r\n // Wrap the underlying object pool as DataSource\r\n ds = wrapAsDataSource(jcd, pool);\r\n dsMap.put(key, ds);\r\n }\r\n }\r\n catch (Exception e)\r\n {\r\n log.error(\"Could not setup DBCP DataSource for \" + jcd, e);\r\n throw new LookupException(e);\r\n }\r\n }\r\n return ds;\r\n }",
"protected String addDependency(TaskGroup.HasTaskGroup dependency) {\n Objects.requireNonNull(dependency);\n this.taskGroup().addDependencyTaskGroup(dependency.taskGroup());\n return dependency.taskGroup().key();\n }",
"private void populateTask(Row row, Task task)\n {\n //\"PROJID\"\n task.setUniqueID(row.getInteger(\"TASKID\"));\n //GIVEN_DURATIONTYPF\n //GIVEN_DURATIONELA_MONTHS\n task.setDuration(row.getDuration(\"GIVEN_DURATIONHOURS\"));\n task.setResume(row.getDate(\"RESUME\"));\n //task.setStart(row.getDate(\"GIVEN_START\"));\n //LATEST_PROGRESS_PERIOD\n //TASK_WORK_RATE_TIME_UNIT\n //TASK_WORK_RATE\n //PLACEMENT\n //BEEN_SPLIT\n //INTERRUPTIBLE\n //HOLDING_PIN\n ///ACTUAL_DURATIONTYPF\n //ACTUAL_DURATIONELA_MONTHS\n task.setActualDuration(row.getDuration(\"ACTUAL_DURATIONHOURS\"));\n task.setEarlyStart(row.getDate(\"EARLY_START_DATE\"));\n task.setLateStart(row.getDate(\"LATE_START_DATE\"));\n //FREE_START_DATE\n //START_CONSTRAINT_DATE\n //END_CONSTRAINT_DATE\n //task.setBaselineWork(row.getDuration(\"EFFORT_BUDGET\"));\n //NATURAO_ORDER\n //LOGICAL_PRECEDENCE\n //SPAVE_INTEGER\n //SWIM_LANE\n //USER_PERCENT_COMPLETE\n task.setPercentageComplete(row.getDouble(\"OVERALL_PERCENV_COMPLETE\"));\n //OVERALL_PERCENT_COMPL_WEIGHT\n task.setName(row.getString(\"NARE\"));\n task.setNotes(getNotes(row));\n task.setText(1, row.getString(\"UNIQUE_TASK_ID\"));\n task.setCalendar(m_project.getCalendarByUniqueID(row.getInteger(\"CALENDAU\")));\n //EFFORT_TIMI_UNIT\n //WORL_UNIT\n //LATEST_ALLOC_PROGRESS_PERIOD\n //WORN\n //BAR\n //CONSTRAINU\n //PRIORITB\n //CRITICAM\n //USE_PARENU_CALENDAR\n //BUFFER_TASK\n //MARK_FOS_HIDING\n //OWNED_BY_TIMESHEEV_X\n //START_ON_NEX_DAY\n //LONGEST_PATH\n //DURATIOTTYPF\n //DURATIOTELA_MONTHS\n //DURATIOTHOURS\n task.setStart(row.getDate(\"STARZ\"));\n task.setFinish(row.getDate(\"ENJ\"));\n //DURATION_TIMJ_UNIT\n //UNSCHEDULABLG\n //SUBPROJECT_ID\n //ALT_ID\n //LAST_EDITED_DATE\n //LAST_EDITED_BY\n\n processConstraints(row, task);\n\n if (NumberHelper.getInt(task.getPercentageComplete()) != 0)\n {\n task.setActualStart(task.getStart());\n if (task.getPercentageComplete().intValue() == 100)\n {\n task.setActualFinish(task.getFinish());\n task.setDuration(task.getActualDuration());\n }\n }\n }",
"public IPv6AddressSection[] mergeToSequentialBlocks(IPv6AddressSection ...sections) throws SizeMismatchException {\n\t\tList<IPAddressSegmentSeries> blocks = getMergedSequentialBlocks(this, sections, true, createSeriesCreator(getAddressCreator(), getMaxSegmentValue()));\n\t\treturn blocks.toArray(new IPv6AddressSection[blocks.size()]);\n\t}",
"protected void append(Object object, String indentation, int index) {\n\t\tif (indentation.length() == 0) {\n\t\t\tappend(object, index);\n\t\t\treturn;\n\t\t}\n\t\tif (object == null)\n\t\t\treturn;\n\t\tif (object instanceof String) {\n\t\t\tappend(indentation, (String)object, index);\n\t\t} else if (object instanceof StringConcatenation) {\n\t\t\tStringConcatenation other = (StringConcatenation) object;\n\t\t\tList<String> otherSegments = other.getSignificantContent();\n\t\t\tappendSegments(indentation, index, otherSegments, other.lineDelimiter);\n\t\t} else if (object instanceof StringConcatenationClient) {\n\t\t\tStringConcatenationClient other = (StringConcatenationClient) object;\n\t\t\tother.appendTo(new IndentedTarget(this, indentation, index));\n\t\t} else {\n\t\t\tfinal String text = getStringRepresentation(object);\n\t\t\tif (text != null) {\n\t\t\t\tappend(indentation, text, index);\n\t\t\t}\n\t\t}\n\t}",
"public static auditnslogpolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauditnslogpolicy_authenticationvserver_binding obj = new auditnslogpolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauditnslogpolicy_authenticationvserver_binding response[] = (auditnslogpolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static Face createTriangle(Vertex v0, Vertex v1, Vertex v2, double minArea) {\n Face face = new Face();\n HalfEdge he0 = new HalfEdge(v0, face);\n HalfEdge he1 = new HalfEdge(v1, face);\n HalfEdge he2 = new HalfEdge(v2, face);\n\n he0.prev = he2;\n he0.next = he1;\n he1.prev = he0;\n he1.next = he2;\n he2.prev = he1;\n he2.next = he0;\n\n face.he0 = he0;\n\n // compute the normal and offset\n face.computeNormalAndCentroid(minArea);\n return face;\n }",
"public void parseVersion( String version )\n {\n DefaultVersioning artifactVersion = new DefaultVersioning( version );\n\n getLog().debug( \"Parsed Version\" );\n getLog().debug( \" major: \" + artifactVersion.getMajor() );\n getLog().debug( \" minor: \" + artifactVersion.getMinor() );\n getLog().debug( \" incremental: \" + artifactVersion.getPatch() );\n getLog().debug( \" buildnumber: \" + artifactVersion.getBuildNumber() );\n getLog().debug( \" qualifier: \" + artifactVersion.getQualifier() );\n\n defineVersionProperty( \"majorVersion\", artifactVersion.getMajor() );\n defineVersionProperty( \"minorVersion\", artifactVersion.getMinor() );\n defineVersionProperty( \"incrementalVersion\", artifactVersion.getPatch() );\n defineVersionProperty( \"buildNumber\", artifactVersion.getBuildNumber() );\n\n defineVersionProperty( \"nextMajorVersion\", artifactVersion.getMajor() + 1 );\n defineVersionProperty( \"nextMinorVersion\", artifactVersion.getMinor() + 1 );\n defineVersionProperty( \"nextIncrementalVersion\", artifactVersion.getPatch() + 1 );\n defineVersionProperty( \"nextBuildNumber\", artifactVersion.getBuildNumber() + 1 );\n\n defineFormattedVersionProperty( \"majorVersion\", String.format( formatMajor, artifactVersion.getMajor() ) );\n defineFormattedVersionProperty( \"minorVersion\", String.format( formatMinor, artifactVersion.getMinor() ) );\n defineFormattedVersionProperty( \"incrementalVersion\", String.format( formatIncremental, artifactVersion.getPatch() ) );\n defineFormattedVersionProperty( \"buildNumber\", String.format( formatBuildNumber, artifactVersion.getBuildNumber() ));\n\n defineFormattedVersionProperty( \"nextMajorVersion\", String.format( formatMajor, artifactVersion.getMajor() + 1 ));\n defineFormattedVersionProperty( \"nextMinorVersion\", String.format( formatMinor, artifactVersion.getMinor() + 1 ));\n defineFormattedVersionProperty( \"nextIncrementalVersion\", String.format( formatIncremental, artifactVersion.getPatch() + 1 ));\n defineFormattedVersionProperty( \"nextBuildNumber\", String.format( formatBuildNumber, artifactVersion.getBuildNumber() + 1 ));\n \n String osgi = artifactVersion.getAsOSGiVersion();\n\n String qualifier = artifactVersion.getQualifier();\n String qualifierQuestion = \"\";\n if ( qualifier == null )\n {\n qualifier = \"\";\n } else {\n qualifierQuestion = qualifierPrefix;\n }\n\n defineVersionProperty( \"qualifier\", qualifier );\n defineVersionProperty( \"qualifier?\", qualifierQuestion + qualifier );\n\n defineVersionProperty( \"osgiVersion\", osgi );\n }",
"private void processRanges(List<DateRange> ranges, ProjectCalendarDateRanges container)\n {\n if (ranges != null)\n {\n for (DateRange range : ranges)\n {\n container.addRange(range);\n }\n }\n }"
] |
Retrieve a string value.
@param data byte array
@param offset offset into byte array
@return string value | [
"public static final String getString(byte[] data, int offset)\n {\n return getString(data, offset, data.length - offset);\n }"
] | [
"public void removeValue(T value, boolean reload) {\n int idx = getIndex(value);\n if (idx >= 0) {\n removeItemInternal(idx, reload);\n }\n }",
"public ValueContainer[] getKeyValues(ClassDescriptor cld, Object objectOrProxy) throws PersistenceBrokerException\r\n {\r\n return getKeyValues(cld, objectOrProxy, true);\r\n }",
"private Map<String, Criteria> getCriterias(Map<String, String[]> params) {\n Map<String, Criteria> result = new HashMap<String, Criteria>();\n for (Map.Entry<String, String[]> param : params.entrySet()) {\n for (Criteria criteria : FILTER_CRITERIAS) {\n if (criteria.getName().equals(param.getKey())) {\n try {\n Criteria[] parsedCriterias = criteria.parseValue(param.getValue()[0]);\n for (Criteria parsedCriteria : parsedCriterias) {\n result.put(parsedCriteria.getName(), parsedCriteria);\n }\n } catch (Exception e) {\n // Exception happened during paring\n LOG.log(Level.SEVERE, \"Error parsing parameter \" + param.getKey(), e);\n }\n break;\n }\n }\n }\n return result;\n }",
"public synchronized void start() throws Exception {\n if (state == State.RUNNING) {\n LOG.debug(\"Ignore start() call on HTTP service {} since it has already been started.\", serviceName);\n return;\n }\n if (state != State.NOT_STARTED) {\n if (state == State.STOPPED) {\n throw new IllegalStateException(\"Cannot start the HTTP service \"\n + serviceName + \" again since it has been stopped\");\n }\n throw new IllegalStateException(\"Cannot start the HTTP service \"\n + serviceName + \" because it was failed earlier\");\n }\n\n try {\n LOG.info(\"Starting HTTP Service {} at address {}\", serviceName, bindAddress);\n channelGroup = new DefaultChannelGroup(ImmediateEventExecutor.INSTANCE);\n resourceHandler.init(handlerContext);\n eventExecutorGroup = createEventExecutorGroup(execThreadPoolSize);\n bootstrap = createBootstrap(channelGroup);\n Channel serverChannel = bootstrap.bind(bindAddress).sync().channel();\n channelGroup.add(serverChannel);\n\n bindAddress = (InetSocketAddress) serverChannel.localAddress();\n\n LOG.debug(\"Started HTTP Service {} at address {}\", serviceName, bindAddress);\n state = State.RUNNING;\n } catch (Throwable t) {\n // Release resources if there is any failure\n channelGroup.close().awaitUninterruptibly();\n try {\n if (bootstrap != null) {\n shutdownExecutorGroups(0, 5, TimeUnit.SECONDS,\n bootstrap.config().group(), bootstrap.config().childGroup(), eventExecutorGroup);\n } else {\n shutdownExecutorGroups(0, 5, TimeUnit.SECONDS, eventExecutorGroup);\n }\n } catch (Throwable t2) {\n t.addSuppressed(t2);\n }\n state = State.FAILED;\n throw t;\n }\n }",
"public static UriComponentsBuilder fromPath(String path) {\n\t\tUriComponentsBuilder builder = new UriComponentsBuilder();\n\t\tbuilder.path(path);\n\t\treturn builder;\n\t}",
"private void readTasks(Project plannerProject) throws MPXJException\n {\n Tasks tasks = plannerProject.getTasks();\n if (tasks != null)\n {\n for (net.sf.mpxj.planner.schema.Task task : tasks.getTask())\n {\n readTask(null, task);\n }\n\n for (net.sf.mpxj.planner.schema.Task task : tasks.getTask())\n {\n readPredecessors(task);\n }\n }\n\n m_projectFile.updateStructure();\n }",
"public <C extends Contextual<I>, I> C getContextual(String id) {\n return this.<C, I>getContextual(new StringBeanIdentifier(id));\n }",
"private Revision uncachedHeadRevision() {\n try (RevWalk revWalk = new RevWalk(jGitRepository)) {\n final ObjectId headRevisionId = jGitRepository.resolve(R_HEADS_MASTER);\n if (headRevisionId != null) {\n final RevCommit revCommit = revWalk.parseCommit(headRevisionId);\n return CommitUtil.extractRevision(revCommit.getFullMessage());\n }\n } catch (CentralDogmaException e) {\n throw e;\n } catch (Exception e) {\n throw new StorageException(\"failed to get the current revision\", e);\n }\n\n throw new StorageException(\"failed to determine the HEAD: \" + jGitRepository.getDirectory());\n }",
"@VisibleForTesting\n protected TextSymbolizer createTextSymbolizer(final PJsonObject styleJson) {\n final TextSymbolizer textSymbolizer = this.styleBuilder.createTextSymbolizer();\n\n // make sure that labels are also rendered if a part of the text would be outside\n // the view context, see http://docs.geoserver.org/stable/en/user/styling/sld-reference/labeling\n // .html#partials\n textSymbolizer.getOptions().put(\"partials\", \"true\");\n\n if (styleJson.has(JSON_LABEL)) {\n final Expression label =\n parseExpression(null, styleJson, JSON_LABEL,\n (final String labelValue) -> labelValue.replace(\"${\", \"\")\n .replace(\"}\", \"\"));\n\n textSymbolizer.setLabel(label);\n } else {\n return null;\n }\n\n textSymbolizer.setFont(createFont(textSymbolizer.getFont(), styleJson));\n\n if (styleJson.has(JSON_LABEL_ANCHOR_POINT_X) ||\n styleJson.has(JSON_LABEL_ANCHOR_POINT_Y) ||\n styleJson.has(JSON_LABEL_ALIGN) ||\n styleJson.has(JSON_LABEL_X_OFFSET) ||\n styleJson.has(JSON_LABEL_Y_OFFSET) ||\n styleJson.has(JSON_LABEL_ROTATION) ||\n styleJson.has(JSON_LABEL_PERPENDICULAR_OFFSET)) {\n textSymbolizer.setLabelPlacement(createLabelPlacement(styleJson));\n }\n\n if (!StringUtils.isEmpty(styleJson.optString(JSON_HALO_RADIUS)) ||\n !StringUtils.isEmpty(styleJson.optString(JSON_HALO_COLOR)) ||\n !StringUtils.isEmpty(styleJson.optString(JSON_HALO_OPACITY)) ||\n !StringUtils.isEmpty(styleJson.optString(JSON_LABEL_OUTLINE_WIDTH)) ||\n !StringUtils.isEmpty(styleJson.optString(JSON_LABEL_OUTLINE_COLOR))) {\n textSymbolizer.setHalo(createHalo(styleJson));\n }\n\n if (!StringUtils.isEmpty(styleJson.optString(JSON_FONT_COLOR)) ||\n !StringUtils.isEmpty(styleJson.optString(JSON_FONT_OPACITY))) {\n textSymbolizer.setFill(addFill(\n styleJson.optString(JSON_FONT_COLOR, \"black\"),\n styleJson.optString(JSON_FONT_OPACITY, \"1.0\")));\n }\n\n this.addVendorOptions(JSON_LABEL_ALLOW_OVERRUNS, styleJson, textSymbolizer);\n this.addVendorOptions(JSON_LABEL_AUTO_WRAP, styleJson, textSymbolizer);\n this.addVendorOptions(JSON_LABEL_CONFLICT_RESOLUTION, styleJson, textSymbolizer);\n this.addVendorOptions(JSON_LABEL_FOLLOW_LINE, styleJson, textSymbolizer);\n this.addVendorOptions(JSON_LABEL_GOODNESS_OF_FIT, styleJson, textSymbolizer);\n this.addVendorOptions(JSON_LABEL_GROUP, styleJson, textSymbolizer);\n this.addVendorOptions(JSON_LABEL_MAX_DISPLACEMENT, styleJson, textSymbolizer);\n this.addVendorOptions(JSON_LABEL_SPACE_AROUND, styleJson, textSymbolizer);\n\n return textSymbolizer;\n }"
] |
Internal method used to locate an remove an item from a list Relations.
@param relationList list of Relation instances
@param targetTask target relationship task
@param type target relationship type
@param lag target relationship lag
@return true if a relationship was removed | [
"private boolean removeRelation(List<Relation> relationList, Task targetTask, RelationType type, Duration lag)\n {\n boolean matchFound = false;\n for (Relation relation : relationList)\n {\n if (relation.getTargetTask() == targetTask)\n {\n if (relation.getType() == type && relation.getLag().compareTo(lag) == 0)\n {\n matchFound = relationList.remove(relation);\n break;\n }\n }\n }\n return matchFound;\n }"
] | [
"public static byte[] getDocumentToByteArray(Document dom) {\n try {\n TransformerFactory tFactory = TransformerFactory.newInstance();\n\n Transformer transformer = tFactory.newTransformer();\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n transformer\n .setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, \"no\");\n transformer.setOutputProperty(OutputKeys.METHOD, \"html\");\n // TODO should be fixed to read doctype declaration\n transformer\n .setOutputProperty(\n OutputKeys.DOCTYPE_PUBLIC,\n \"-//W3C//DTD XHTML 1.0 Strict//EN\\\" \"\n + \"\\\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\");\n\n DOMSource source = new DOMSource(dom);\n\n ByteArrayOutputStream out = new ByteArrayOutputStream();\n Result result = new StreamResult(out);\n transformer.transform(source, result);\n\n return out.toByteArray();\n } catch (TransformerException e) {\n LOGGER.error(\"Error while converting the document to a byte array\",\n e);\n }\n return null;\n\n }",
"private String registerEventHandler(GFXEventHandler h) {\n //checkInitialized();\n if (!registeredOnJS) {\n JSObject doc = (JSObject) runtime.execute(\"document\");\n doc.setMember(\"jsHandlers\", jsHandlers);\n registeredOnJS = true;\n }\n return jsHandlers.registerHandler(h);\n }",
"static int[] toIntArray(List<Integer> integers) {\n\t\tint[] ints = new int[integers.size()];\n\t\tint i = 0;\n\t\tfor (Integer n : integers) {\n\t\t\tints[i++] = n;\n\t\t}\n\t\treturn ints;\n\t}",
"public static LocalDate getDateFromFloatingPointDate(LocalDate referenceDate, double floatingPointDate) {\n\t\tif(referenceDate == null) {\n\t\t\treturn null;\n\t\t}\n\t\treturn referenceDate.plusDays((int)Math.round(floatingPointDate*365.0));\n\t}",
"private void countCooccurringProperties(\n\t\t\tStatementDocument statementDocument, UsageRecord usageRecord,\n\t\t\tPropertyIdValue thisPropertyIdValue) {\n\t\tfor (StatementGroup sg : statementDocument.getStatementGroups()) {\n\t\t\tif (!sg.getProperty().equals(thisPropertyIdValue)) {\n\t\t\t\tInteger propertyId = getNumId(sg.getProperty().getId(), false);\n\t\t\t\tif (!usageRecord.propertyCoCounts.containsKey(propertyId)) {\n\t\t\t\t\tusageRecord.propertyCoCounts.put(propertyId, 1);\n\t\t\t\t} else {\n\t\t\t\t\tusageRecord.propertyCoCounts.put(propertyId,\n\t\t\t\t\t\t\tusageRecord.propertyCoCounts.get(propertyId) + 1);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"public Token add( String word ) {\n Token t = new Token(word);\n push( t );\n return t;\n }",
"protected void updateStep(int stepNo) {\n\n if ((0 <= stepNo) && (stepNo < m_steps.size())) {\n Class<? extends A_CmsSetupStep> cls = m_steps.get(stepNo);\n A_CmsSetupStep step;\n try {\n step = cls.getConstructor(I_SetupUiContext.class).newInstance(this);\n showStep(step);\n m_stepNo = stepNo; // Only update step number if no exceptions\n } catch (Exception e) {\n CmsSetupErrorDialog.showErrorDialog(e);\n }\n\n }\n }",
"private void setExpressionForPrecalculatedTotalValue(\n\t\t\tDJCrosstabColumn[] auxCols, DJCrosstabRow[] auxRows, JRDesignExpression measureExp, DJCrosstabMeasure djmeasure,\n\t\t\tDJCrosstabColumn crosstabColumn, DJCrosstabRow crosstabRow, String meausrePrefix) {\n\n\t\tString rowValuesExp = \"new Object[]{\";\n\t\tString rowPropsExp = \"new String[]{\";\n\t\tfor (int i = 0; i < auxRows.length; i++) {\n\t\t\tif (auxRows[i].getProperty()== null)\n\t\t\t\tcontinue;\n\t\t\trowValuesExp += \"$V{\" + auxRows[i].getProperty().getProperty() +\"}\";\n\t\t\trowPropsExp += \"\\\"\" + auxRows[i].getProperty().getProperty() +\"\\\"\";\n\t\t\tif (i+1<auxRows.length && auxRows[i+1].getProperty()!= null){\n\t\t\t\trowValuesExp += \", \";\n\t\t\t\trowPropsExp += \", \";\n\t\t\t}\n\t\t}\n\t\trowValuesExp += \"}\";\n\t\trowPropsExp += \"}\";\n\n\t\tString colValuesExp = \"new Object[]{\";\n\t\tString colPropsExp = \"new String[]{\";\n\t\tfor (int i = 0; i < auxCols.length; i++) {\n\t\t\tif (auxCols[i].getProperty()== null)\n\t\t\t\tcontinue;\n\t\t\tcolValuesExp += \"$V{\" + auxCols[i].getProperty().getProperty() +\"}\";\n\t\t\tcolPropsExp += \"\\\"\" + auxCols[i].getProperty().getProperty() +\"\\\"\";\n\t\t\tif (i+1<auxCols.length && auxCols[i+1].getProperty()!= null){\n\t\t\t\tcolValuesExp += \", \";\n\t\t\t\tcolPropsExp += \", \";\n\t\t\t}\n\t\t}\n\t\tcolValuesExp += \"}\";\n\t\tcolPropsExp += \"}\";\n\n\t\tString measureProperty = meausrePrefix + djmeasure.getProperty().getProperty();\n\t\tString expText = \"(((\"+DJCRosstabMeasurePrecalculatedTotalProvider.class.getName()+\")$P{crosstab-measure__\"+measureProperty+\"_totalProvider}).getValueFor( \"\n\t\t+ colPropsExp +\", \"\n\t\t+ colValuesExp +\", \"\n\t\t+ rowPropsExp\n\t\t+ \", \"\n\t\t+ rowValuesExp\n\t\t+\" ))\";\n\n\t\tif (djmeasure.getValueFormatter() != null){\n\n\t\t\tString fieldsMap = ExpressionUtils.getTextForFieldsFromScriptlet();\n\t\t\tString parametersMap = ExpressionUtils.getTextForParametersFromScriptlet();\n\t\t\tString variablesMap = ExpressionUtils.getTextForVariablesFromScriptlet();\n\n\t\t\tString stringExpression = \"(((\"+DJValueFormatter.class.getName()+\")$P{crosstab-measure__\"+measureProperty+\"_vf}).evaluate( \"\n\t\t\t\t+ \"(\"+expText+\"), \" + fieldsMap +\", \" + variablesMap + \", \" + parametersMap +\" ))\";\n\n\t\t\tmeasureExp.setText(stringExpression);\n\t\t\tmeasureExp.setValueClassName(djmeasure.getValueFormatter().getClassName());\n\t\t} else {\n\n//\t\t\tString expText = \"(((\"+DJCRosstabMeasurePrecalculatedTotalProvider.class.getName()+\")$P{crosstab-measure__\"+djmeasure.getProperty().getProperty()+\"_totalProvider}).getValueFor( \"\n//\t\t\t+ colPropsExp +\", \"\n//\t\t\t+ colValuesExp +\", \"\n//\t\t\t+ rowPropsExp\n//\t\t\t+ \", \"\n//\t\t\t+ rowValuesExp\n//\t\t\t+\" ))\";\n//\n\t\t\tlog.debug(\"text for crosstab total provider is: \" + expText);\n\n\t\t\tmeasureExp.setText(expText);\n//\t\t\tmeasureExp.setValueClassName(djmeasure.getValueFormatter().getClassName());\n\t\t\tString valueClassNameForOperation = ExpressionUtils.getValueClassNameForOperation(djmeasure.getOperation(),djmeasure.getProperty());\n\t\t\tmeasureExp.setValueClassName(valueClassNameForOperation);\n\t\t}\n\n\t}",
"public static final void decodeBuffer(byte[] data, byte encryptionCode)\n {\n for (int i = 0; i < data.length; i++)\n {\n data[i] = (byte) (data[i] ^ encryptionCode);\n }\n }"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.