query
stringlengths 7
3.3k
| positive
sequencelengths 1
1
| negative
sequencelengths 9
9
|
---|---|---|
Session connect generate channel.
@param session
the session
@return the channel
@throws JSchException
the j sch exception | [
"public Channel sessionConnectGenerateChannel(Session session)\n throws JSchException {\n \t// set timeout\n session.connect(sshMeta.getSshConnectionTimeoutMillis());\n \n ChannelExec channel = (ChannelExec) session.openChannel(\"exec\");\n channel.setCommand(sshMeta.getCommandLine());\n\n // if run as super user, assuming the input stream expecting a password\n if (sshMeta.isRunAsSuperUser()) {\n \ttry {\n channel.setInputStream(null, true);\n\n OutputStream out = channel.getOutputStream();\n channel.setOutputStream(System.out, true);\n channel.setExtOutputStream(System.err, true);\n channel.setPty(true);\n channel.connect();\n \n\t out.write((sshMeta.getPassword()+\"\\n\").getBytes());\n\t out.flush();\n\t\t\t} catch (IOException e) {\n\t\t\t\tlogger.error(\"error in sessionConnectGenerateChannel for super user\", e);\n\t\t\t}\n } else {\n \tchannel.setInputStream(null);\n \tchannel.connect();\n }\n\n return channel;\n\n }"
] | [
"@Override\n public void addVariable(String varName, Object value) {\n synchronized (mGlobalVariables) {\n mGlobalVariables.put(varName, value);\n }\n refreshGlobalBindings();\n }",
"public Curve getRegressionCurve(){\n\t\t// @TODO Add threadsafe lazy init.\n\t\tif(regressionCurve !=null) {\n\t\t\treturn regressionCurve;\n\t\t}\n\t\tDoubleMatrix a = solveEquationSystem();\n\t\tdouble[] curvePoints=new double[partition.getLength()];\n\t\tcurvePoints[0]=a.get(0);\n\t\tfor(int i=1;i<curvePoints.length;i++) {\n\t\t\tcurvePoints[i]=curvePoints[i-1]+a.get(i)*(partition.getIntervalLength(i-1));\n\t\t}\n\t\treturn new CurveInterpolation(\n\t\t\t\t\"RegressionCurve\",\n\t\t\t\treferenceDate,\n\t\t\t\tCurveInterpolation.InterpolationMethod.LINEAR,\n\t\t\t\tCurveInterpolation.ExtrapolationMethod.CONSTANT,\n\t\t\t\tCurveInterpolation.InterpolationEntity.VALUE,\n\t\t\t\tpartition.getPoints(),\n\t\t\t\tcurvePoints);\n\t}",
"protected boolean executeOperation(final TransactionalProtocolClient.TransactionalOperationListener<ServerOperation> listener, TransactionalProtocolClient client, final ServerIdentity identity, final ModelNode operation, final OperationResultTransformer transformer) {\n if(client == null) {\n return false;\n }\n final OperationMessageHandler messageHandler = new DelegatingMessageHandler(context);\n final OperationAttachments operationAttachments = new DelegatingOperationAttachments(context);\n final ServerOperation serverOperation = new ServerOperation(identity, operation, messageHandler, operationAttachments, transformer);\n try {\n DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef(\"Sending %s to %s\", operation, identity);\n final Future<OperationResponse> result = client.execute(listener, serverOperation);\n recordExecutedRequest(new ExecutedServerRequest(identity, result, transformer));\n } catch (IOException e) {\n final TransactionalProtocolClient.PreparedOperation<ServerOperation> result = BlockingQueueOperationListener.FailedOperation.create(serverOperation, e);\n listener.operationPrepared(result);\n recordExecutedRequest(new ExecutedServerRequest(identity, result.getFinalResult(), transformer));\n }\n return true;\n }",
"public boolean isValid() {\n\t\tif(addressProvider.isUninitialized()) {\n\t\t\ttry {\n\t\t\t\tvalidate();\n\t\t\t\treturn true;\n\t\t\t} catch(AddressStringException e) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn !addressProvider.isInvalid();\n\t}",
"private void addJoinInfo(JoinType type, String localColumnName, String joinedColumnName,\n\t\t\tQueryBuilder<?, ?> joinedQueryBuilder, JoinWhereOperation operation) throws SQLException {\n\t\tJoinInfo joinInfo = new JoinInfo(type, joinedQueryBuilder, operation);\n\t\tif (localColumnName == null) {\n\t\t\tmatchJoinedFields(joinInfo, joinedQueryBuilder);\n\t\t} else {\n\t\t\tmatchJoinedFieldsByName(joinInfo, localColumnName, joinedColumnName, joinedQueryBuilder);\n\t\t}\n\t\tif (joinList == null) {\n\t\t\tjoinList = new ArrayList<JoinInfo>();\n\t\t}\n\t\tjoinList.add(joinInfo);\n\t}",
"public static int cudnnBatchNormalizationBackward(\n cudnnHandle handle, \n int mode, \n Pointer alphaDataDiff, \n Pointer betaDataDiff, \n Pointer alphaParamDiff, \n Pointer betaParamDiff, \n cudnnTensorDescriptor xDesc, /** same desc for x, dx, dy */\n Pointer x, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor dxDesc, \n Pointer dx, \n /** Shared tensor desc for the 4 tensors below */\n cudnnTensorDescriptor dBnScaleBiasDesc, \n Pointer bnScale, /** bnBias doesn't affect backpropagation */\n /** scale and bias diff are not backpropagated below this layer */\n Pointer dBnScaleResult, \n Pointer dBnBiasResult, \n /** Same epsilon as forward pass */\n double epsilon, \n /** Optionally cached intermediate results from\n forward pass */\n Pointer savedMean, \n Pointer savedInvVariance)\n {\n return checkResult(cudnnBatchNormalizationBackwardNative(handle, mode, alphaDataDiff, betaDataDiff, alphaParamDiff, betaParamDiff, xDesc, x, dyDesc, dy, dxDesc, dx, dBnScaleBiasDesc, bnScale, dBnScaleResult, dBnBiasResult, epsilon, savedMean, savedInvVariance));\n }",
"private void addViews(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (View view : file.getViews())\n {\n final View v = view;\n MpxjTreeNode childNode = new MpxjTreeNode(view)\n {\n @Override public String toString()\n {\n return v.getName();\n }\n };\n parentNode.add(childNode);\n }\n }",
"public static <T> List<T> sortWith(Iterable<T> iterable, Comparator<? super T> comparator) {\n\t\treturn ListExtensions.sortInplace(Lists.newArrayList(iterable), comparator);\n\t}",
"public int delete(DatabaseConnection databaseConnection, PreparedDelete<T> preparedDelete) throws SQLException {\n\t\tCompiledStatement compiledStatement = preparedDelete.compile(databaseConnection, StatementType.DELETE);\n\t\ttry {\n\t\t\tint result = compiledStatement.runUpdate();\n\t\t\tif (dao != null && !localIsInBatchMode.get()) {\n\t\t\t\tdao.notifyChanges();\n\t\t\t}\n\t\t\treturn result;\n\t\t} finally {\n\t\t\tIOUtils.closeThrowSqlException(compiledStatement, \"compiled statement\");\n\t\t}\n\t}"
] |
Converters the diffusion coefficient to hydrodynamic diameter and vice versa
@param value Diffusion coefficient in [m^2 s^-1] or hydrodynamic diameter in [m]
@param temperatur Temperatur in [Kelvin]
@param viscosity Viscosity in [kg m^-1 s^-1]
@return Hydrodynmaic diameter [m] / diffusion coefficient [m^2 s^-1] | [
"public double convert(double value, double temperatur, double viscosity){\n\t\treturn temperatur*kB / (Math.PI*viscosity*value);\n\t}"
] | [
"Map<UUID, UUID> getActivityCodes(Activity activity)\n {\n Map<UUID, UUID> map = m_activityCodeCache.get(activity);\n if (map == null)\n {\n map = new HashMap<UUID, UUID>();\n m_activityCodeCache.put(activity, map);\n for (CodeAssignment ca : activity.getCodeAssignment())\n {\n UUID code = getUUID(ca.getCodeUuid(), ca.getCode());\n UUID value = getUUID(ca.getValueUuid(), ca.getValue());\n map.put(code, value);\n }\n }\n return map;\n }",
"private void checkDuplicateStdOutOutput(DumpProcessingAction newAction) {\n\t\tif (newAction.useStdOut()) {\n\t\t\tif (this.quiet) {\n\t\t\t\tlogger.warn(\"Multiple actions are using stdout as output destination.\");\n\t\t\t}\n\t\t\tthis.quiet = true;\n\t\t}\n\t}",
"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 }",
"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 }",
"private boolean hasAbstractPackagePrivateSuperClassWithImplementation(Class<?> clazz, BridgeMethod bridgeMethod) {\n Class<?> superClass = clazz.getSuperclass();\n while (superClass != null) {\n if (Modifier.isAbstract(superClass.getModifiers()) && Reflections.isPackagePrivate(superClass.getModifiers())) {\n // if superclass is abstract, we need to dig deeper\n for (Method method : superClass.getDeclaredMethods()) {\n if (bridgeMethod.signature.matches(method) && method.getGenericReturnType().equals(bridgeMethod.returnType)\n && !Reflections.isAbstract(method)) {\n // this is the case we are after -> methods have same signature and the one in super class has actual implementation\n return true;\n }\n }\n }\n superClass = superClass.getSuperclass();\n }\n return false;\n }",
"private static <D, T> D createDaoFromConfig(ConnectionSource connectionSource, Class<T> clazz) throws SQLException {\n\t\t// no loaded configs\n\t\tif (configMap == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tDatabaseTableConfig<T> config = (DatabaseTableConfig<T>) configMap.get(clazz);\n\t\t// if we don't config information cached return null\n\t\tif (config == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// else create a DAO using configuration\n\t\tDao<T, ?> configedDao = doCreateDao(connectionSource, config);\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tD castDao = (D) configedDao;\n\t\treturn castDao;\n\t}",
"public synchronized int get() {\n if (available == 0) {\n return -1;\n }\n byte value = buffer[idxGet];\n idxGet = (idxGet + 1) % capacity;\n available--;\n return value;\n }",
"@SuppressWarnings(\"deprecation\")\n public BUILDER setAllowedValues(String ... allowedValues) {\n assert allowedValues!= null;\n this.allowedValues = new ModelNode[allowedValues.length];\n for (int i = 0; i < allowedValues.length; i++) {\n this.allowedValues[i] = new ModelNode(allowedValues[i]);\n }\n return (BUILDER) this;\n }",
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public void markReadInboxMessage(final CTInboxMessage message){\n postAsyncSafely(\"markReadInboxMessage\", new Runnable() {\n @Override\n public void run() {\n synchronized (inboxControllerLock) {\n if(ctInboxController != null){\n boolean read = ctInboxController.markReadForMessageWithId(message.getMessageId());\n if (read) {\n _notifyInboxMessagesDidUpdate();\n }\n } else {\n getConfigLogger().debug(getAccountId(),\"Notification Inbox not initialized\");\n }\n }\n }\n });\n }"
] |
Accessor method used to retrieve a Float object representing the
contents of an individual field. If the field does not exist in the
record, null is returned.
@param field the index number of the field to be retrieved
@return the value of the required field | [
"public Number getFloat(int field) throws MPXJException\n {\n try\n {\n Number result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = m_formats.getDecimalFormat().parse(m_fields[field]);\n }\n else\n {\n result = null;\n }\n\n return (result);\n }\n\n catch (ParseException ex)\n {\n throw new MPXJException(\"Failed to parse float\", ex);\n }\n }"
] | [
"public static double computeTauAndDivide(final int j, final int numRows ,\n final double[] u , final double max) {\n double tau = 0;\n// double div_max = 1.0/max;\n// if( Double.isInfinite(div_max)) {\n for( int i = j; i < numRows; i++ ) {\n double d = u[i] /= max;\n tau += d*d;\n }\n// } else {\n// for( int i = j; i < numRows; i++ ) {\n// double d = u[i] *= div_max;\n// tau += d*d;\n// }\n// }\n tau = Math.sqrt(tau);\n\n if( u[j] < 0 )\n tau = -tau;\n\n return tau;\n }",
"public static base_responses delete(nitro_service client, String ciphergroupname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (ciphergroupname != null && ciphergroupname.length > 0) {\n\t\t\tsslcipher deleteresources[] = new sslcipher[ciphergroupname.length];\n\t\t\tfor (int i=0;i<ciphergroupname.length;i++){\n\t\t\t\tdeleteresources[i] = new sslcipher();\n\t\t\t\tdeleteresources[i].ciphergroupname = ciphergroupname[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static boolean invert(final DMatrixRMaj cov , final DMatrixRMaj cov_inv ) {\n if( cov.numCols <= 4 ) {\n if( cov.numCols != cov.numRows ) {\n throw new IllegalArgumentException(\"Must be a square matrix.\");\n }\n\n if( cov.numCols >= 2 )\n UnrolledInverseFromMinor_DDRM.inv(cov,cov_inv);\n else\n cov_inv.data[0] = 1.0/cov.data[0];\n\n } else {\n LinearSolverDense<DMatrixRMaj> solver = LinearSolverFactory_DDRM.symmPosDef(cov.numRows);\n // wrap it to make sure the covariance is not modified.\n solver = new LinearSolverSafe<DMatrixRMaj>(solver);\n if( !solver.setA(cov) )\n return false;\n solver.invert(cov_inv);\n }\n return true;\n }",
"public Swagger read(Class<?> cls) {\n SwaggerDefinition swaggerDefinition = cls.getAnnotation(SwaggerDefinition.class);\n if (swaggerDefinition != null) {\n readSwaggerConfig(cls, swaggerDefinition);\n }\n\n return read(cls, \"\", null, false, new String[0], new String[0], new LinkedHashMap<>(), new ArrayList<>(), new HashSet<>());\n }",
"public void writeTo(Writer destination) {\n Element eltRuleset = new Element(\"ruleset\");\n addAttribute(eltRuleset, \"name\", name);\n addChild(eltRuleset, \"description\", description);\n for (PmdRule pmdRule : rules) {\n Element eltRule = new Element(\"rule\");\n addAttribute(eltRule, \"ref\", pmdRule.getRef());\n addAttribute(eltRule, \"class\", pmdRule.getClazz());\n addAttribute(eltRule, \"message\", pmdRule.getMessage());\n addAttribute(eltRule, \"name\", pmdRule.getName());\n addAttribute(eltRule, \"language\", pmdRule.getLanguage());\n addChild(eltRule, \"priority\", String.valueOf(pmdRule.getPriority()));\n if (pmdRule.hasProperties()) {\n Element ruleProperties = processRuleProperties(pmdRule);\n if (ruleProperties.getContentSize() > 0) {\n eltRule.addContent(ruleProperties);\n }\n }\n eltRuleset.addContent(eltRule);\n }\n XMLOutputter serializer = new XMLOutputter(Format.getPrettyFormat());\n try {\n serializer.output(new Document(eltRuleset), destination);\n } catch (IOException e) {\n throw new IllegalStateException(\"An exception occurred while serializing PmdRuleSet.\", e);\n }\n }",
"public EventsRequest<Event> get(String resource, String sync) {\n return new EventsRequest<Event>(this, Event.class, \"/events\", \"GET\")\n .query(\"resource\", resource)\n .query(\"sync\", sync);\n }",
"public List<Action> getRootActions() {\n\t\tfinal List<Action> rootActions = srcUpdTrees.stream().map(t -> originalActionsSrc.get(t))\n\t\t\t\t.collect(Collectors.toList());\n\n\t\trootActions.addAll(srcDelTrees.stream() //\n\t\t\t\t.filter(t -> !srcDelTrees.contains(t.getParent()) && !srcUpdTrees.contains(t.getParent())) //\n\t\t\t\t.map(t -> originalActionsSrc.get(t)) //\n\t\t\t\t.collect(Collectors.toList()));\n\n\t\trootActions.addAll(dstAddTrees.stream() //\n\t\t\t\t.filter(t -> !dstAddTrees.contains(t.getParent()) && !dstUpdTrees.contains(t.getParent())) //\n\t\t\t\t.map(t -> originalActionsDst.get(t)) //\n\t\t\t\t.collect(Collectors.toList()));\n\n\t\trootActions.addAll(dstMvTrees.stream() //\n\t\t\t\t.filter(t -> !dstMvTrees.contains(t.getParent())) //\n\t\t\t\t.map(t -> originalActionsDst.get(t)) //\n\t\t\t\t.collect(Collectors.toList()));\n\n\t\trootActions.removeAll(Collections.singleton(null));\n\t\treturn rootActions;\n\t}",
"public static String formatAsStackTraceElement(InjectionPoint ij) {\n Member member;\n if (ij.getAnnotated() instanceof AnnotatedField) {\n AnnotatedField<?> annotatedField = (AnnotatedField<?>) ij.getAnnotated();\n member = annotatedField.getJavaMember();\n } else if (ij.getAnnotated() instanceof AnnotatedParameter<?>) {\n AnnotatedParameter<?> annotatedParameter = (AnnotatedParameter<?>) ij.getAnnotated();\n member = annotatedParameter.getDeclaringCallable().getJavaMember();\n } else {\n // Not throwing an exception, because this method is invoked when an exception is already being thrown.\n // Throwing an exception here would hide the original exception.\n return \"-\";\n }\n return formatAsStackTraceElement(member);\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}"
] |
Use this API to fetch csvserver_cspolicy_binding resources of given name . | [
"public static csvserver_cspolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_cspolicy_binding obj = new csvserver_cspolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_cspolicy_binding response[] = (csvserver_cspolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"private List<String> parseRssFeedForeCast(String feed) {\n String[] result = feed.split(\"<br />\");\n List<String> returnList = new ArrayList<String>();\n String[] result2 = result[2].split(\"<BR />\");\n\n returnList.add(result2[3] + \"\\n\");\n returnList.add(result[3] + \"\\n\");\n returnList.add(result[4] + \"\\n\");\n returnList.add(result[5] + \"\\n\");\n returnList.add(result[6] + \"\\n\");\n\n return returnList;\n }",
"public static base_response delete(nitro_service client, ntpserver resource) throws Exception {\n\t\tntpserver deleteresource = new ntpserver();\n\t\tdeleteresource.serverip = resource.serverip;\n\t\tdeleteresource.servername = resource.servername;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"private Point parsePoint(String point) {\n int comma = point.indexOf(',');\n if (comma == -1)\n return null;\n\n float lat = Float.valueOf(point.substring(0, comma));\n float lng = Float.valueOf(point.substring(comma + 1));\n return spatialctx.makePoint(lng, lat);\n }",
"public static Comment createComment(final String entityId,\n\t\t\t\t\t\t\t\t\t\tfinal String entityType,\n\t\t\t\t\t\t\t\t\t\tfinal String action,\n\t\t\t\t\t\t\t\t\t\tfinal String commentedText,\n\t\t\t\t\t\t\t\t\t\tfinal String user,\n\t\t\t\t\t\t\t\t\t\tfinal Date date) {\n\n\t\tfinal Comment comment = new Comment();\n\t\tcomment.setEntityId(entityId);\n\t\tcomment.setEntityType(entityType);\n\t\tcomment.setAction(action);\n\t\tcomment.setCommentText(commentedText);\n\t\tcomment.setCommentedBy(user);\n\t\tcomment.setCreatedDateTime(date);\n\t\treturn comment;\n\t}",
"private void writeAssignmentTimephasedData(ResourceAssignment mpx, Project.Assignments.Assignment xml)\n {\n if (m_writeTimphasedData && mpx.getHasTimephasedData())\n {\n List<TimephasedDataType> list = xml.getTimephasedData();\n ProjectCalendar calendar = mpx.getCalendar();\n BigInteger assignmentID = xml.getUID();\n\n List<TimephasedWork> complete = mpx.getTimephasedActualWork();\n List<TimephasedWork> planned = mpx.getTimephasedWork();\n\n if (m_splitTimephasedAsDays)\n {\n TimephasedWork lastComplete = null;\n if (complete != null && !complete.isEmpty())\n {\n lastComplete = complete.get(complete.size() - 1);\n }\n\n TimephasedWork firstPlanned = null;\n if (planned != null && !planned.isEmpty())\n {\n firstPlanned = planned.get(0);\n }\n\n if (planned != null)\n {\n planned = splitDays(calendar, mpx.getTimephasedWork(), null, lastComplete);\n }\n\n if (complete != null)\n {\n complete = splitDays(calendar, complete, firstPlanned, null);\n }\n }\n\n if (planned != null)\n {\n writeAssignmentTimephasedData(assignmentID, list, planned, 1);\n }\n\n if (complete != null)\n {\n writeAssignmentTimephasedData(assignmentID, list, complete, 2);\n }\n }\n }",
"protected synchronized void releaseBroker(PersistenceBroker broker)\r\n {\r\n /*\r\n arminw:\r\n only close the broker instance if we get\r\n it from the PBF, do nothing if we obtain it from\r\n PBThreadMapping\r\n */\r\n if (broker != null && _needsClose)\r\n {\r\n _needsClose = false;\r\n broker.close();\r\n }\r\n }",
"public static base_responses save(nitro_service client, cacheobject resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tcacheobject saveresources[] = new cacheobject[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tsaveresources[i] = new cacheobject();\n\t\t\t\tsaveresources[i].locator = resources[i].locator;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, saveresources,\"save\");\n\t\t}\n\t\treturn result;\n\t}",
"public static WebDriverBackedEmbeddedBrowser withRemoteDriver(String hubUrl,\n\t\t\tImmutableSortedSet<String> filterAttributes, long crawlWaitEvent,\n\t\t\tlong crawlWaitReload) {\n\t\treturn WebDriverBackedEmbeddedBrowser.withDriver(buildRemoteWebDriver(hubUrl),\n\t\t\t\tfilterAttributes, crawlWaitEvent,\n\t\t\t\tcrawlWaitReload);\n\t}",
"public synchronized void tick() {\n long currentTime = GVRTime.getMilliTime();\n long cutoffTime = currentTime - BUFFER_SECONDS * 1000;\n ListIterator<Long> it = mTimestamps.listIterator();\n while (it.hasNext()) {\n Long timestamp = it.next();\n if (timestamp < cutoffTime) {\n it.remove();\n } else {\n break;\n }\n }\n\n mTimestamps.add(currentTime);\n mStatColumn.addValue(((float)mTimestamps.size()) / BUFFER_SECONDS);\n }"
] |
Add the collection of elements to this collection. This will also them to the associated database table.
@return Returns true if any of the items did not already exist in the collection otherwise false. | [
"@Override\n\tpublic boolean addAll(Collection<? extends T> collection) {\n\t\tboolean changed = false;\n\t\tfor (T data : collection) {\n\t\t\ttry {\n\t\t\t\tif (addElement(data)) {\n\t\t\t\t\tchanged = true;\n\t\t\t\t}\n\t\t\t} catch (SQLException e) {\n\t\t\t\tthrow new IllegalStateException(\"Could not create data elements in dao\", e);\n\t\t\t}\n\t\t}\n\t\treturn changed;\n\t}"
] | [
"public static NamingConvention determineNamingConvention(\n TypeElement type,\n Iterable<ExecutableElement> methods,\n Messager messager,\n Types types) {\n ExecutableElement beanMethod = null;\n ExecutableElement prefixlessMethod = null;\n for (ExecutableElement method : methods) {\n switch (methodNameConvention(method)) {\n case BEAN:\n beanMethod = firstNonNull(beanMethod, method);\n break;\n case PREFIXLESS:\n prefixlessMethod = firstNonNull(prefixlessMethod, method);\n break;\n default:\n break;\n }\n }\n if (prefixlessMethod != null) {\n if (beanMethod != null) {\n messager.printMessage(\n ERROR,\n \"Type contains an illegal mix of get-prefixed and unprefixed getter methods, e.g. '\"\n + beanMethod.getSimpleName() + \"' and '\" + prefixlessMethod.getSimpleName() + \"'\",\n type);\n }\n return new PrefixlessConvention(messager, types);\n } else {\n return new BeanConvention(messager, types);\n }\n }",
"public static void writeShortString(ByteBuffer buffer, String s) {\n if (s == null) {\n buffer.putShort((short) -1);\n } else if (s.length() > Short.MAX_VALUE) {\n throw new IllegalArgumentException(\"String exceeds the maximum size of \" + Short.MAX_VALUE + \".\");\n } else {\n byte[] data = getBytes(s); //topic support non-ascii character\n buffer.putShort((short) data.length);\n buffer.put(data);\n }\n }",
"private void showGlobalContextActionBar() {\n ActionBar actionBar = getActionBar();\n actionBar.setDisplayShowTitleEnabled(true);\n actionBar.setTitle(R.string.app_name);\n }",
"public static void validateCurrentFinalCluster(final Cluster currentCluster,\n final Cluster finalCluster) {\n validateClusterPartitionCounts(currentCluster, finalCluster);\n validateClusterNodeState(currentCluster, finalCluster);\n\n return;\n }",
"public static String readDesignerVersion(ServletContext context) {\n String retStr = \"\";\n BufferedReader br = null;\n try {\n InputStream inputStream = context.getResourceAsStream(\"/META-INF/MANIFEST.MF\");\n br = new BufferedReader(new InputStreamReader(inputStream,\n \"UTF-8\"));\n String line;\n while ((line = br.readLine()) != null) {\n if (line.startsWith(BUNDLE_VERSION)) {\n retStr = line.substring(BUNDLE_VERSION.length() + 1);\n retStr = retStr.trim();\n }\n }\n inputStream.close();\n } catch (Exception e) {\n logger.error(e.getMessage(),\n e);\n } finally {\n if (br != null) {\n IOUtils.closeQuietly(br);\n }\n }\n return retStr;\n }",
"public void end(String key)\n {\n if (key == null)\n {\n return;\n }\n TimingData data = executionInfo.get(key);\n if (data == null)\n {\n LOG.info(\"Called end with key: \" + key + \" without ever calling begin\");\n return;\n }\n data.end();\n }",
"int getDelay(int n) {\n int delay = -1;\n if ((n >= 0) && (n < header.frameCount)) {\n delay = header.frames.get(n).delay;\n }\n return delay;\n }",
"public void addCustomNotificationRecipient(String userID) {\n BoxUser user = new BoxUser(null, userID);\n this.customNotificationRecipients.add(user.new Info());\n\n }",
"@Deprecated\n public <T> List<T> findByIndex(String selectorJson, Class<T> classOfT) {\n return findByIndex(selectorJson, classOfT, new FindByIndexOptions());\n }"
] |
Called when remote end send a message to this connection
@param receivedMessage the message received
@return this context | [
"public WebSocketContext messageReceived(String receivedMessage) {\n this.stringMessage = S.string(receivedMessage).trim();\n isJson = stringMessage.startsWith(\"{\") || stringMessage.startsWith(\"]\");\n tryParseQueryParams();\n return this;\n }"
] | [
"public ClassicCounter<K2> setCounter(K1 o, Counter<K2> c) {\r\n ClassicCounter<K2> old = getCounter(o);\r\n total -= old.totalCount();\r\n if (c instanceof ClassicCounter) {\r\n map.put(o, (ClassicCounter<K2>) c);\r\n } else {\r\n map.put(o, new ClassicCounter<K2>(c));\r\n }\r\n total += c.totalCount();\r\n return old;\r\n }",
"public static final TimeUnit getTimeUnit(int value)\n {\n TimeUnit result = null;\n\n switch (value)\n {\n case 1:\n {\n // Appears to mean \"use the document format\"\n result = TimeUnit.ELAPSED_DAYS;\n break;\n }\n\n case 2:\n {\n result = TimeUnit.HOURS;\n break;\n }\n\n case 4:\n {\n result = TimeUnit.DAYS;\n break;\n }\n\n case 6:\n {\n result = TimeUnit.WEEKS;\n break;\n }\n\n case 8:\n case 10:\n {\n result = TimeUnit.MONTHS;\n break;\n }\n\n case 12:\n {\n result = TimeUnit.YEARS;\n break;\n }\n\n default:\n {\n break;\n }\n }\n\n return result;\n }",
"public static FormValidation validateArtifactoryCombinationFilter(String value)\n throws IOException, InterruptedException {\n String url = Util.fixEmptyAndTrim(value);\n if (url == null)\n return FormValidation.error(\"Mandatory field - You don`t have any deploy matches\");\n\n return FormValidation.ok();\n }",
"@SuppressForbidden(\"legitimate sysstreams.\")\n public static void warn(String message, Throwable t) {\n PrintStream w = (warnings == null ? System.err : warnings);\n try {\n w.print(\"WARN: \");\n w.print(message);\n if (t != null) {\n w.print(\" -> \");\n try {\n t.printStackTrace(w);\n } catch (OutOfMemoryError e) {\n // Ignore, OOM.\n w.print(t.getClass().getName());\n w.print(\": \");\n w.print(t.getMessage());\n w.println(\" (stack unavailable; OOM)\");\n }\n } else {\n w.println();\n }\n w.flush();\n } catch (OutOfMemoryError t2) {\n w.println(\"ERROR: Couldn't even serialize a warning (out of memory).\");\n } catch (Throwable t2) {\n // Can't do anything, really. Probably an OOM?\n w.println(\"ERROR: Couldn't even serialize a warning.\");\n }\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 }",
"public VideoCollection generate(final int videoCount) {\n List<Video> videos = new LinkedList<Video>();\n for (int i = 0; i < videoCount; i++) {\n Video video = generateRandomVideo();\n videos.add(video);\n }\n return new VideoCollection(videos);\n }",
"public Map<String, String> listConfig(String appName) {\n return connection.execute(new ConfigList(appName), apiKey);\n }",
"private void initManagementPart() {\n\n m_manageExceptionsButton.setText(Messages.get().key(Messages.GUI_SERIALDATE_BUTTON_MANAGE_EXCEPTIONS_0));\n m_manageExceptionsButton.getElement().getStyle().setFloat(Style.Float.RIGHT);\n }",
"public int getXForBeat(int beat) {\n BeatGrid grid = beatGrid.get();\n if (grid != null) {\n return millisecondsToX(grid.getTimeWithinTrack(beat));\n }\n return 0;\n }"
] |
Send a mount update announcement to all registered listeners, and see if we can auto-attach a media cache file.
@param slot the slot in which media has been mounted or unmounted
@param mounted will be {@code true} if there is now media mounted in the specified slot | [
"private void deliverMountUpdate(SlotReference slot, boolean mounted) {\n if (mounted) {\n logger.info(\"Reporting media mounted in \" + slot);\n\n } else {\n logger.info(\"Reporting media removed from \" + slot);\n }\n for (final MountListener listener : getMountListeners()) {\n try {\n if (mounted) {\n listener.mediaMounted(slot);\n } else {\n listener.mediaUnmounted(slot);\n }\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering mount update to listener\", t);\n }\n }\n if (mounted) {\n MetadataCache.tryAutoAttaching(slot);\n }\n }"
] | [
"public static void registerMbean(MBeanServer server, ModelMBean mbean, ObjectName name) {\n try {\n synchronized(LOCK) {\n if(server.isRegistered(name))\n JmxUtils.unregisterMbean(server, name);\n server.registerMBean(mbean, name);\n }\n } catch(Exception e) {\n logger.error(\"Error registering mbean:\", e);\n }\n }",
"private ChildTaskContainer getParentTask(Activity activity)\n {\n //\n // Make a map of activity codes and their values for this activity\n //\n Map<UUID, UUID> map = getActivityCodes(activity);\n\n //\n // Work through the activity codes in sequence\n //\n ChildTaskContainer parent = m_projectFile;\n StringBuilder uniqueIdentifier = new StringBuilder();\n for (UUID activityCode : m_codeSequence)\n {\n UUID activityCodeValue = map.get(activityCode);\n String activityCodeText = m_activityCodeValues.get(activityCodeValue);\n if (activityCodeText != null)\n {\n if (uniqueIdentifier.length() != 0)\n {\n uniqueIdentifier.append('>');\n }\n uniqueIdentifier.append(activityCodeValue.toString());\n UUID uuid = UUID.nameUUIDFromBytes(uniqueIdentifier.toString().getBytes());\n Task newParent = findChildTaskByUUID(parent, uuid);\n if (newParent == null)\n {\n newParent = parent.addTask();\n newParent.setGUID(uuid);\n newParent.setName(activityCodeText);\n }\n parent = newParent;\n }\n }\n return parent;\n }",
"public static String getClassName(Class<?> c) {\n String name = c.getName();\n return name.substring(name.lastIndexOf('.') + 1, name.length());\n }",
"public static rewritepolicylabel_rewritepolicy_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\trewritepolicylabel_rewritepolicy_binding obj = new rewritepolicylabel_rewritepolicy_binding();\n\t\tobj.set_labelname(labelname);\n\t\trewritepolicylabel_rewritepolicy_binding response[] = (rewritepolicylabel_rewritepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public NodeInfo getNode(String name) {\n final URI uri = uriWithPath(\"./nodes/\" + encodePathSegment(name));\n return this.rt.getForObject(uri, NodeInfo.class);\n }",
"public SqlStatement getPreparedDeleteStatement(ClassDescriptor cld)\r\n {\r\n SqlForClass sfc = getSqlForClass(cld);\r\n SqlStatement sql = sfc.getDeleteSql();\r\n if(sql == null)\r\n {\r\n ProcedureDescriptor pd = cld.getDeleteProcedure();\r\n\r\n if(pd == null)\r\n {\r\n sql = new SqlDeleteByPkStatement(cld, logger);\r\n }\r\n else\r\n {\r\n sql = new SqlProcedureStatement(pd, logger);\r\n }\r\n // set the sql string\r\n sfc.setDeleteSql(sql);\r\n\r\n if(logger.isDebugEnabled())\r\n {\r\n logger.debug(\"SQL:\" + sql.getStatement());\r\n }\r\n }\r\n return sql;\r\n }",
"public void updateAnimation()\n {\n Date time = new Date();\n long currentTime = time.getTime() - this.beginAnimation;\n if (currentTime > animationTime)\n {\n this.currentQuaternion.set(endQuaternion);\n for (int i = 0; i < 3; i++)\n {\n\n this.currentPos[i] = this.endPos[i];\n }\n this.animate = false;\n }\n\n else\n {\n float t = (float) currentTime / animationTime;\n this.currentQuaternion = this.beginQuaternion.slerp(this.endQuaternion,\n t);\n for (int i = 0; i < 3; i++)\n {\n this.currentPos[i] = this.beginPos[i] + totalTranslation[i] * t;\n }\n\n }\n }",
"private void addCheckBox(final String internalValue, String labelMessageKey) {\r\n\r\n CmsCheckBox box = new CmsCheckBox(Messages.get().key(labelMessageKey));\r\n box.setInternalValue(internalValue);\r\n box.addValueChangeHandler(new ValueChangeHandler<Boolean>() {\r\n\r\n public void onValueChange(ValueChangeEvent<Boolean> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.weeksChange(internalValue, event.getValue());\r\n }\r\n }\r\n });\r\n m_weekPanel.add(box);\r\n m_checkboxes.add(box);\r\n\r\n }",
"private static void processResourceFilter(ProjectFile project, Filter filter)\n {\n for (Resource resource : project.getResources())\n {\n if (filter.evaluate(resource, null))\n {\n System.out.println(resource.getID() + \",\" + resource.getUniqueID() + \",\" + resource.getName());\n }\n }\n }"
] |
Complete the current operation and persist the current state to the disk. This will also trigger the invalidation
of outdated modules.
@param modification the current modification
@param callback the completion callback | [
"private void complete(final InstallationManager.InstallationModification modification, final FinalizeCallback callback) {\n final List<File> processed = new ArrayList<File>();\n List<File> reenabled = Collections.emptyList();\n List<File> disabled = Collections.emptyList();\n try {\n try {\n // Update the state to invalidate and process module resources\n if (stateUpdater.compareAndSet(this, State.PREPARED, State.INVALIDATE)) {\n if (mode == PatchingTaskContext.Mode.APPLY) {\n // Only invalidate modules when applying patches; on rollback files are immediately restored\n for (final File invalidation : moduleInvalidations) {\n processed.add(invalidation);\n PatchModuleInvalidationUtils.processFile(this, invalidation, mode);\n }\n if (!modulesToReenable.isEmpty()) {\n reenabled = new ArrayList<File>(modulesToReenable.size());\n for (final File path : modulesToReenable) {\n reenabled.add(path);\n PatchModuleInvalidationUtils.processFile(this, path, PatchingTaskContext.Mode.ROLLBACK);\n }\n }\n } else if(mode == PatchingTaskContext.Mode.ROLLBACK) {\n if (!modulesToDisable.isEmpty()) {\n disabled = new ArrayList<File>(modulesToDisable.size());\n for (final File path : modulesToDisable) {\n disabled.add(path);\n PatchModuleInvalidationUtils.processFile(this, path, PatchingTaskContext.Mode.APPLY);\n }\n }\n }\n\n }\n modification.complete();\n callback.completed(this);\n state = State.COMPLETED;\n } catch (Exception e) {\n this.moduleInvalidations.clear();\n this.moduleInvalidations.addAll(processed);\n this.modulesToReenable.clear();\n this.modulesToReenable.addAll(reenabled);\n this.modulesToDisable.clear();\n this.moduleInvalidations.addAll(disabled);\n throw new RuntimeException(e);\n }\n } finally {\n if (state != State.COMPLETED) {\n try {\n modification.cancel();\n } finally {\n try {\n undoChanges();\n } finally {\n callback.operationCancelled(this);\n }\n }\n } else {\n try {\n if (checkForGarbageOnRestart) {\n final File cleanupMarker = new File(installedImage.getInstallationMetadata(), \"cleanup-patching-dirs\");\n cleanupMarker.createNewFile();\n }\n storeFailedRenaming();\n } catch (IOException e) {\n PatchLogger.ROOT_LOGGER.debugf(e, \"failed to create cleanup marker\");\n }\n }\n }\n }"
] | [
"public static <E> Filter<E> switchedFilter(Filter<E> filter, boolean negated) {\r\n return (new NegatedFilter<E>(filter, negated));\r\n }",
"public static Field[] getDeclaredFieldsInHierarchy(Class<?> clazz) {\n\n if (clazz.isPrimitive()) {\n throw new IllegalArgumentException(\"Primitive types not supported.\");\n }\n\n List<Field> result = new ArrayList<Field>();\n\n while (true) {\n\n if (clazz == Object.class) {\n break;\n }\n\n result.addAll(Arrays.asList(clazz.getDeclaredFields()));\n clazz = clazz.getSuperclass();\n }\n\n return result.toArray(new Field[result.size()]);\n }",
"public static appfwglobal_auditsyslogpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tappfwglobal_auditsyslogpolicy_binding obj = new appfwglobal_auditsyslogpolicy_binding();\n\t\tappfwglobal_auditsyslogpolicy_binding response[] = (appfwglobal_auditsyslogpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"private boolean hasPrimaryKey(T entity) {\n Object pk = getPrimaryKey(entity);\n if (pk == null) {\n return false;\n } else {\n if (pk instanceof Number && ((Number) pk).longValue() == 0) {\n return false;\n }\n }\n return true;\n }",
"@Nullable\n public ResultT first() {\n final CoreRemoteMongoCursor<ResultT> cursor = iterator();\n if (!cursor.hasNext()) {\n return null;\n }\n return cursor.next();\n }",
"@RequestMapping(value = \"group\", method = RequestMethod.GET)\n public String newGroupGet(Model model) {\n model.addAttribute(\"groups\",\n pathOverrideService.findAllGroups());\n return \"groups\";\n }",
"@Programmatic\n public <T> List<T> fromExcel(\n final Blob excelBlob,\n final Class<T> cls,\n final String sheetName) throws ExcelService.Exception {\n return fromExcel(excelBlob, new WorksheetSpec(cls, sheetName));\n }",
"public void makePickable(GVRSceneObject sceneObject) {\n try {\n GVRMeshCollider collider = new GVRMeshCollider(sceneObject.getGVRContext(), false);\n sceneObject.attachComponent(collider);\n } catch (Exception e) {\n // Possible that some objects (X3D panel nodes) are without mesh\n Log.e(Log.SUBSYSTEM.INPUT, TAG, \"makePickable(): possible that some objects (X3D panel nodes) are without mesh!\");\n }\n }",
"private void onShow() {\n\n if (m_detailsFieldset != null) {\n m_detailsFieldset.getContentPanel().getElement().getStyle().setPropertyPx(\n \"maxHeight\",\n getAvailableHeight(m_messageWidget.getOffsetHeight()));\n }\n }"
] |
Use this API to fetch a cmpglobal_cmppolicy_binding resources. | [
"public static cmpglobal_cmppolicy_binding[] get(nitro_service service) throws Exception{\n\t\tcmpglobal_cmppolicy_binding obj = new cmpglobal_cmppolicy_binding();\n\t\tcmpglobal_cmppolicy_binding response[] = (cmpglobal_cmppolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}"
] | [
"public Set<Processor<?, ?>> getAllProcessors() {\n IdentityHashMap<Processor<?, ?>, Void> all = new IdentityHashMap<>();\n for (ProcessorGraphNode<?, ?> root: this.roots) {\n for (Processor p: root.getAllProcessors()) {\n all.put(p, null);\n }\n }\n return all.keySet();\n }",
"protected void restoreAutoCommitState()\r\n {\r\n try\r\n {\r\n if(!broker.isManaged())\r\n {\r\n if (jcd.getUseAutoCommit() == JdbcConnectionDescriptor.AUTO_COMMIT_SET_TRUE_AND_TEMPORARY_FALSE\r\n && originalAutoCommitState == true && con != null && !con.isClosed())\r\n {\r\n platform.changeAutoCommitState(jcd, con, true);\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 Platform.changeAutoCommitState(...) call\");\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n // should never be reached\r\n throw new OJBRuntimeException(\"Restore of connection autocommit state failed\", e);\r\n }\r\n }",
"public double[] getMoneynessAsOffsets() {\r\n\t\tDoubleStream moneyness = getGridNodesPerMoneyness().keySet().stream().mapToDouble(Integer::doubleValue);\r\n\t\tif(quotingConvention == QuotingConvention.PAYERVOLATILITYLOGNORMAL) {\r\n\t\t\tmoneyness = moneyness.map(new DoubleUnaryOperator() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic double applyAsDouble(double x) {\r\n\t\t\t\t\treturn x * 0.01;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t} else if(quotingConvention == QuotingConvention.RECEIVERPRICE) {\r\n\t\t\tmoneyness = moneyness.map(new DoubleUnaryOperator() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic double applyAsDouble(double x) {\r\n\t\t\t\t\treturn - x * 0.0001;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t} else {\r\n\t\t\tmoneyness = moneyness.map(new DoubleUnaryOperator() {\r\n\t\t\t\t@Override\r\n\t\t\t\tpublic double applyAsDouble(double x) {\r\n\t\t\t\t\treturn x * 0.0001;\r\n\t\t\t\t}\r\n\t\t\t});\r\n\t\t}\r\n\t\treturn moneyness.toArray();\r\n\t}",
"private ColumnDefinition[] columnDefinitions(ColumnDefinition[] columns, String[] order)\n {\n Map<String, ColumnDefinition> map = makeColumnMap(columns);\n ColumnDefinition[] result = new ColumnDefinition[order.length];\n for (int index = 0; index < order.length; index++)\n {\n result[index] = map.get(order[index]);\n }\n return result;\n }",
"public static <T> Collection<MemberResponse<T>> executeOptimistic(IExecutorService execSvc, Set<Member> members, Callable<T> callable) {\n \treturn executeOptimistic(execSvc, members, callable, 60, TimeUnit.SECONDS);\n }",
"private CoreLabel makeCoreLabel(String line) {\r\n CoreLabel wi = new CoreLabel();\r\n // wi.line = line;\r\n String[] bits = line.split(\"\\\\s+\");\r\n switch (bits.length) {\r\n case 0:\r\n case 1:\r\n wi.setWord(BOUNDARY);\r\n wi.set(AnswerAnnotation.class, OTHER);\r\n break;\r\n case 2:\r\n wi.setWord(bits[0]);\r\n wi.set(AnswerAnnotation.class, bits[1]);\r\n break;\r\n case 3:\r\n wi.setWord(bits[0]);\r\n wi.setTag(bits[1]);\r\n wi.set(AnswerAnnotation.class, bits[2]);\r\n break;\r\n case 4:\r\n wi.setWord(bits[0]);\r\n wi.setTag(bits[1]);\r\n wi.set(ChunkAnnotation.class, bits[2]);\r\n wi.set(AnswerAnnotation.class, bits[3]);\r\n break;\r\n case 5:\r\n if (flags.useLemmaAsWord) {\r\n wi.setWord(bits[1]);\r\n } else {\r\n wi.setWord(bits[0]);\r\n }\r\n wi.set(LemmaAnnotation.class, bits[1]);\r\n wi.setTag(bits[2]);\r\n wi.set(ChunkAnnotation.class, bits[3]);\r\n wi.set(AnswerAnnotation.class, bits[4]);\r\n break;\r\n default:\r\n throw new RuntimeIOException(\"Unexpected input (many fields): \" + line);\r\n }\r\n wi.set(OriginalAnswerAnnotation.class, wi.get(AnswerAnnotation.class));\r\n return wi;\r\n }",
"private void addMembers(Collection memberNames, HashMap members, XClass type, String tagName, String paramName, String paramValue) throws XDocletException\r\n {\r\n if (!type.isInterface() && (type.getFields() != null)) {\r\n XField field;\r\n\r\n for (Iterator it = type.getFields().iterator(); it.hasNext(); ) {\r\n field = (XField)it.next();\r\n if (!field.isFinal() && !field.isStatic() && !field.isTransient()) {\r\n if (checkTagAndParam(field.getDoc(), tagName, paramName, paramValue)) {\r\n // already processed ?\r\n if (!members.containsKey(field.getName())) {\r\n memberNames.add(field.getName());\r\n members.put(field.getName(), field);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n\r\n if (type.getMethods() != null) {\r\n XMethod method;\r\n String propertyName;\r\n\r\n for (Iterator it = type.getMethods().iterator(); it.hasNext(); ) {\r\n method = (XMethod)it.next();\r\n if (!method.isConstructor() && !method.isNative() && !method.isStatic()) {\r\n if (checkTagAndParam(method.getDoc(), tagName, paramName, paramValue)) {\r\n if (MethodTagsHandler.isGetterMethod(method) || MethodTagsHandler.isSetterMethod(method)) {\r\n propertyName = MethodTagsHandler.getPropertyNameFor(method);\r\n if (!members.containsKey(propertyName)) {\r\n memberNames.add(propertyName);\r\n members.put(propertyName, method);\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }",
"public void removeMarker(Marker marker) {\n if (markers != null && markers.contains(marker)) {\n markers.remove(marker);\n }\n marker.setMap(null);\n }",
"public static void validateClusterZonesSame(final Cluster lhs, final Cluster rhs) {\n Set<Zone> lhsSet = new HashSet<Zone>(lhs.getZones());\n Set<Zone> rhsSet = new HashSet<Zone>(rhs.getZones());\n if(!lhsSet.equals(rhsSet))\n throw new VoldemortException(\"Zones are not the same [ lhs cluster zones (\"\n + lhs.getZones() + \") not equal to rhs cluster zones (\"\n + rhs.getZones() + \") ]\");\n }"
] |
Extracts the data for a single file from the input stream and writes
it to a target directory.
@param stream input stream
@param dir target directory | [
"private void extractFile(InputStream stream, File dir) throws IOException\n {\n byte[] header = new byte[8];\n byte[] fileName = new byte[13];\n byte[] dataSize = new byte[4];\n\n stream.read(header);\n stream.read(fileName);\n stream.read(dataSize);\n\n int dataSizeValue = getInt(dataSize, 0);\n String fileNameValue = getString(fileName, 0);\n File file = new File(dir, fileNameValue);\n\n if (dataSizeValue == 0)\n {\n FileHelper.createNewFile(file);\n }\n else\n {\n OutputStream os = new FileOutputStream(file);\n FixedLengthInputStream inputStream = new FixedLengthInputStream(stream, dataSizeValue);\n Blast blast = new Blast();\n blast.blast(inputStream, os);\n os.close();\n }\n }"
] | [
"public void addHiDpiImage(String factor, CmsJspImageBean image) {\n\n if (m_hiDpiImages == null) {\n m_hiDpiImages = CmsCollectionsGenericWrapper.createLazyMap(new CmsScaleHiDpiTransformer());\n }\n m_hiDpiImages.put(factor, image);\n }",
"void publish() {\n assert publishedFullRegistry != null : \"Cannot write directly to main registry\";\n\n writeLock.lock();\n try {\n if (!modified) {\n return;\n }\n publishedFullRegistry.writeLock.lock();\n try {\n publishedFullRegistry.clear(true);\n copy(this, publishedFullRegistry);\n pendingRemoveCapabilities.clear();\n pendingRemoveRequirements.clear();\n modified = false;\n } finally {\n publishedFullRegistry.writeLock.unlock();\n }\n } finally {\n writeLock.unlock();\n }\n }",
"private static void firstDotConstellation(int[] dollarPositions, int[] dotPositions, int nestingLevel) {\n int i = 0;\n int unassigned = dotPositions.length - nestingLevel;\n\n for (; i < unassigned; ++i) {\n dotPositions[i] = -1;\n }\n\n for (; i < dotPositions.length; ++i) {\n dotPositions[i] = dollarPositions[i];\n }\n }",
"@Override public Integer[] getUniqueIdentifierArray()\n {\n Integer[] result = new Integer[m_table.size()];\n int index = 0;\n for (Integer value : m_table.keySet())\n {\n result[index] = value;\n ++index;\n }\n return (result);\n }",
"public BoxComment.Info reply(String message) {\n JsonObject itemJSON = new JsonObject();\n itemJSON.add(\"type\", \"comment\");\n itemJSON.add(\"id\", this.getID());\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"item\", itemJSON);\n if (BoxComment.messageContainsMention(message)) {\n requestJSON.add(\"tagged_message\", message);\n } else {\n requestJSON.add(\"message\", message);\n }\n\n URL url = ADD_COMMENT_URL_TEMPLATE.build(this.getAPI().getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxComment addedComment = new BoxComment(this.getAPI(), responseJSON.get(\"id\").asString());\n return addedComment.new Info(responseJSON);\n }",
"public static boolean changeHost(String hostName,\n boolean enable,\n boolean disable,\n boolean remove,\n boolean isEnabled,\n boolean exists) throws Exception {\n\n // Open the file that is the first\n // command line parameter\n File hostsFile = new File(\"/etc/hosts\");\n FileInputStream fstream = new FileInputStream(\"/etc/hosts\");\n\n File outFile = null;\n BufferedWriter bw = null;\n // only do file output for destructive operations\n if (!exists && !isEnabled) {\n outFile = File.createTempFile(\"HostsEdit\", \".tmp\");\n bw = new BufferedWriter(new FileWriter(outFile));\n System.out.println(\"File name: \" + outFile.getPath());\n }\n\n // Get the object of DataInputStream\n DataInputStream in = new DataInputStream(fstream);\n BufferedReader br = new BufferedReader(new InputStreamReader(in));\n String strLine;\n boolean foundHost = false;\n boolean hostEnabled = false;\n\n\t\t/*\n * Group 1 - possible commented out host entry\n\t\t * Group 2 - destination address\n\t\t * Group 3 - host name\n\t\t * Group 4 - everything else\n\t\t */\n Pattern pattern = Pattern.compile(\"\\\\s*(#?)\\\\s*([^\\\\s]+)\\\\s*([^\\\\s]+)(.*)\");\n while ((strLine = br.readLine()) != null) {\n\n Matcher matcher = pattern.matcher(strLine);\n\n // if there is a match to the pattern and the host name is the same as the one we want to set\n if (matcher.find() &&\n matcher.group(3).toLowerCase().compareTo(hostName.toLowerCase()) == 0) {\n foundHost = true;\n if (remove) {\n // skip this line altogether\n continue;\n } else if (enable) {\n // we will disregard group 2 and just set it to 127.0.0.1\n if (!exists && !isEnabled)\n bw.write(\"127.0.0.1 \" + matcher.group(3) + matcher.group(4));\n } else if (disable) {\n if (!exists && !isEnabled)\n bw.write(\"# \" + matcher.group(2) + \" \" + matcher.group(3) + matcher.group(4));\n } else if (isEnabled && matcher.group(1).compareTo(\"\") == 0) {\n // host exists and there is no # before it\n hostEnabled = true;\n }\n } else {\n // just write the line back out\n if (!exists && !isEnabled)\n bw.write(strLine);\n }\n\n if (!exists && !isEnabled)\n bw.write('\\n');\n }\n\n // if we didn't find the host in the file but need to enable it\n if (!foundHost && enable) {\n // write a new host entry\n if (!exists && !isEnabled)\n bw.write(\"127.0.0.1 \" + hostName + '\\n');\n }\n // Close the input stream\n in.close();\n\n if (!exists && !isEnabled) {\n bw.close();\n outFile.renameTo(hostsFile);\n }\n\n // return false if the host wasn't found\n if (exists && !foundHost)\n return false;\n\n // return false if the host wasn't enabled\n if (isEnabled && !hostEnabled)\n return false;\n\n return true;\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 }",
"public void addDependency(final Dependency dependency) {\n if(dependency != null && !dependencies.contains(dependency)){\n this.dependencies.add(dependency);\n }\n }",
"public static base_response Force(nitro_service client, clustersync resource) throws Exception {\n\t\tclustersync Forceresource = new clustersync();\n\t\treturn Forceresource.perform_operation(client,\"Force\");\n\t}"
] |
Checks whether an uploaded file can be created in the VFS, and throws an exception otherwise.
@param cms the current CMS context
@param config the form configuration
@param name the file name of the uploaded file
@param size the size of the uploaded file
@throws CmsUgcException if something goes wrong | [
"public static void checkCreateUpload(CmsObject cms, CmsUgcConfiguration config, String name, long size)\n throws CmsUgcException {\n\n if (!config.getUploadParentFolder().isPresent()) {\n String message = Messages.get().container(Messages.ERR_NO_UPLOADS_ALLOWED_0).key(\n cms.getRequestContext().getLocale());\n throw new CmsUgcException(CmsUgcConstants.ErrorCode.errNoUploadAllowed, message);\n }\n\n if (config.getMaxUploadSize().isPresent()) {\n if (config.getMaxUploadSize().get().longValue() < size) {\n String message = Messages.get().container(Messages.ERR_UPLOAD_TOO_BIG_1, name).key(\n cms.getRequestContext().getLocale());\n throw new CmsUgcException(CmsUgcConstants.ErrorCode.errMaxUploadSizeExceeded, message);\n }\n }\n\n if (config.getValidExtensions().isPresent()) {\n List<String> validExtensions = config.getValidExtensions().get();\n boolean foundExtension = false;\n for (String extension : validExtensions) {\n if (name.toLowerCase().endsWith(extension.toLowerCase())) {\n foundExtension = true;\n break;\n }\n }\n if (!foundExtension) {\n String message = Messages.get().container(Messages.ERR_UPLOAD_FILE_EXTENSION_NOT_ALLOWED_1, name).key(\n cms.getRequestContext().getLocale());\n throw new CmsUgcException(CmsUgcConstants.ErrorCode.errInvalidExtension, message);\n }\n }\n }"
] | [
"public static String entityToString(HttpEntity entity) throws IOException {\n if (entity != null) {\n InputStream is = entity.getContent();\n return IOUtils.toString(is, \"UTF-8\");\n }\n return \"\";\n }",
"@Override\n public final Optional<Boolean> tryOverrideValidation(final MatchInfo matchInfo) throws SocketException,\n UnknownHostException, MalformedURLException {\n for (AddressHostMatcher addressHostMatcher: this.matchersForHost) {\n if (addressHostMatcher.matches(matchInfo)) {\n return Optional.empty();\n }\n }\n\n return Optional.of(false);\n }",
"public static void write(BufferedWriter writer, DatabaseFieldConfig config, String tableName) throws SQLException {\n\t\ttry {\n\t\t\twriteConfig(writer, config, tableName);\n\t\t} catch (IOException e) {\n\t\t\tthrow SqlExceptionUtil.create(\"Could not write config to writer\", e);\n\t\t}\n\t}",
"public void setValueSelected(T value, boolean selected) {\n int idx = getIndex(value);\n if (idx >= 0) {\n setItemSelectedInternal(idx, selected);\n }\n }",
"public void forAllProcedures(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curClassDef.getProcedures(); it.hasNext(); )\r\n {\r\n _curProcedureDef = (ProcedureDef)it.next();\r\n generate(template);\r\n }\r\n _curProcedureDef = null;\r\n }",
"public Matrix4f getFinalTransformMatrix()\n {\n final FloatBuffer fb = ByteBuffer.allocateDirect(4*4*4).order(ByteOrder.nativeOrder()).asFloatBuffer();\n NativeBone.getFinalTransformMatrix(getNative(), fb);\n return new Matrix4f(fb);\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 }",
"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 }",
"private void debugLogEnd(String operationType,\n Long OriginTimeInMs,\n Long RequestStartTimeInMs,\n Long ResponseReceivedTimeInMs,\n String keyString,\n int numVectorClockEntries) {\n long durationInMs = ResponseReceivedTimeInMs - RequestStartTimeInMs;\n logger.debug(\"Received a response from voldemort server for Operation Type: \"\n + operationType\n + \" , For key(s): \"\n + keyString\n + \" , Store: \"\n + this.storeName\n + \" , Origin time of request (in ms): \"\n + OriginTimeInMs\n + \" , Response received at time (in ms): \"\n + ResponseReceivedTimeInMs\n + \" . Request sent at(in ms): \"\n + RequestStartTimeInMs\n + \" , Num vector clock entries: \"\n + numVectorClockEntries\n + \" , Duration from CoordinatorFatClient back to CoordinatorFatClient(in ms): \"\n + durationInMs);\n }"
] |
adds all json extension to an diagram
@param modelJSON
@param current
@throws org.json.JSONException | [
"private static void parseSsextensions(JSONObject modelJSON,\n Diagram current) throws JSONException {\n if (modelJSON.has(\"ssextensions\")) {\n JSONArray array = modelJSON.getJSONArray(\"ssextensions\");\n for (int i = 0; i < array.length(); i++) {\n current.addSsextension(array.getString(i));\n }\n }\n }"
] | [
"public static int byteSizeOf(Bitmap bitmap) {\n if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {\n return bitmap.getAllocationByteCount();\n } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1) {\n return bitmap.getByteCount();\n } else {\n return bitmap.getRowBytes() * bitmap.getHeight();\n }\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 static NamingConvention determineNamingConvention(\n TypeElement type,\n Iterable<ExecutableElement> methods,\n Messager messager,\n Types types) {\n ExecutableElement beanMethod = null;\n ExecutableElement prefixlessMethod = null;\n for (ExecutableElement method : methods) {\n switch (methodNameConvention(method)) {\n case BEAN:\n beanMethod = firstNonNull(beanMethod, method);\n break;\n case PREFIXLESS:\n prefixlessMethod = firstNonNull(prefixlessMethod, method);\n break;\n default:\n break;\n }\n }\n if (prefixlessMethod != null) {\n if (beanMethod != null) {\n messager.printMessage(\n ERROR,\n \"Type contains an illegal mix of get-prefixed and unprefixed getter methods, e.g. '\"\n + beanMethod.getSimpleName() + \"' and '\" + prefixlessMethod.getSimpleName() + \"'\",\n type);\n }\n return new PrefixlessConvention(messager, types);\n } else {\n return new BeanConvention(messager, types);\n }\n }",
"private void exportModules() {\n\n // avoid to export modules if unnecessary\n if (((null != m_copyAndUnzip) && !m_copyAndUnzip.booleanValue())\n || ((null == m_copyAndUnzip) && !m_currentConfiguration.getDefaultCopyAndUnzip())) {\n m_logStream.println();\n m_logStream.println(\"NOT EXPORTING MODULES - you disabled copy and unzip.\");\n m_logStream.println();\n return;\n }\n CmsModuleManager moduleManager = OpenCms.getModuleManager();\n\n Collection<String> modulesToExport = ((m_modulesToExport == null) || m_modulesToExport.isEmpty())\n ? m_currentConfiguration.getConfiguredModules()\n : m_modulesToExport;\n\n for (String moduleName : modulesToExport) {\n CmsModule module = moduleManager.getModule(moduleName);\n if (module != null) {\n CmsModuleImportExportHandler handler = CmsModuleImportExportHandler.getExportHandler(\n getCmsObject(),\n module,\n \"Git export handler\");\n try {\n handler.exportData(\n getCmsObject(),\n new CmsPrintStreamReport(\n m_logStream,\n OpenCms.getWorkplaceManager().getWorkplaceLocale(getCmsObject()),\n false));\n } catch (CmsRoleViolationException | CmsConfigurationException | CmsImportExportException e) {\n e.printStackTrace(m_logStream);\n }\n }\n }\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 }",
"ArgumentsBuilder param(String param, String value) {\n if (value != null) {\n args.add(param);\n args.add(value);\n }\n return this;\n }",
"public static String readTextFile(Context context, int resourceId) {\n InputStream inputStream = context.getResources().openRawResource(\n resourceId);\n return readTextFile(inputStream);\n }",
"public void logWarning(final String message) {\n messageQueue.add(new LogEntry() {\n @Override\n public String getMessage() {\n return message;\n }\n });\n }",
"protected static String getTimePrecisionString(byte precision) {\n\t\tswitch (precision) {\n\t\tcase TimeValue.PREC_SECOND:\n\t\t\treturn \"sec\";\n\t\tcase TimeValue.PREC_MINUTE:\n\t\t\treturn \"min\";\n\t\tcase TimeValue.PREC_HOUR:\n\t\t\treturn \"hour\";\n\t\tcase TimeValue.PREC_DAY:\n\t\t\treturn \"day\";\n\t\tcase TimeValue.PREC_MONTH:\n\t\t\treturn \"month\";\n\t\tcase TimeValue.PREC_YEAR:\n\t\t\treturn \"year\";\n\t\tcase TimeValue.PREC_DECADE:\n\t\t\treturn \"decade\";\n\t\tcase TimeValue.PREC_100Y:\n\t\t\treturn \"100 years\";\n\t\tcase TimeValue.PREC_1KY:\n\t\t\treturn \"1000 years\";\n\t\tcase TimeValue.PREC_10KY:\n\t\t\treturn \"10K years\";\n\t\tcase TimeValue.PREC_100KY:\n\t\t\treturn \"100K years\";\n\t\tcase TimeValue.PREC_1MY:\n\t\t\treturn \"1 million years\";\n\t\tcase TimeValue.PREC_10MY:\n\t\t\treturn \"10 million years\";\n\t\tcase TimeValue.PREC_100MY:\n\t\t\treturn \"100 million years\";\n\t\tcase TimeValue.PREC_1GY:\n\t\t\treturn \"1000 million years\";\n\t\tdefault:\n\t\t\treturn \"Unsupported precision \" + precision;\n\t\t}\n\t}"
] |
Emit an enum event with parameters and force all listener to be called synchronously.
@param event
the target event
@param args
the arguments passed in
@see #emit(Enum, Object...) | [
"public EventBus emitSync(Enum<?> event, Object... args) {\n return _emitWithOnceBus(eventContextSync(event, args));\n }"
] | [
"protected static BigInteger getRadixPower(BigInteger radix, int power) {\n\t\tlong key = (((long) radix.intValue()) << 32) | power;\n\t\tBigInteger result = radixPowerMap.get(key);\n\t\tif(result == null) {\n\t\t\tif(power == 1) {\n\t\t\t\tresult = radix;\n\t\t\t} else if((power & 1) == 0) {\n\t\t\t\tBigInteger halfPower = getRadixPower(radix, power >> 1);\n\t\t\t\tresult = halfPower.multiply(halfPower);\n\t\t\t} else {\n\t\t\t\tBigInteger halfPower = getRadixPower(radix, (power - 1) >> 1);\n\t\t\t\tresult = halfPower.multiply(halfPower).multiply(radix);\n\t\t\t}\n\t\t\tradixPowerMap.put(key, result);\n\t\t}\n\t\treturn result;\n\t}",
"public void createOverride(int groupId, String methodName, String className) throws Exception {\n // first make sure this doesn't already exist\n for (Method method : EditService.getInstance().getMethodsFromGroupId(groupId, null)) {\n if (method.getMethodName().equals(methodName) && method.getClassName().equals(className)) {\n // don't add if it already exists in the group\n return;\n }\n }\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n PreparedStatement statement = sqlConnection.prepareStatement(\n \"INSERT INTO \" + Constants.DB_TABLE_OVERRIDE\n + \"(\" + Constants.OVERRIDE_METHOD_NAME\n + \",\" + Constants.OVERRIDE_CLASS_NAME\n + \",\" + Constants.OVERRIDE_GROUP_ID\n + \")\"\n + \" VALUES (?, ?, ?)\"\n );\n statement.setString(1, methodName);\n statement.setString(2, className);\n statement.setInt(3, groupId);\n statement.executeUpdate();\n } catch (SQLException e) {\n e.printStackTrace();\n }\n }",
"public static void append(Path self, Object text) throws IOException {\n Writer writer = null;\n try {\n writer = new OutputStreamWriter(Files.newOutputStream(self, CREATE, APPEND), Charset.defaultCharset());\n InvokerHelper.write(writer, text);\n writer.flush();\n\n Writer temp = writer;\n writer = null;\n temp.close();\n } finally {\n closeWithWarning(writer);\n }\n }",
"public DownloadRequest addCustomHeader(String key, String value) {\n mCustomHeader.put(key, value);\n return this;\n }",
"private static JSONObject parseStencil(String stencilId) throws JSONException {\n JSONObject stencilObject = new JSONObject();\n\n stencilObject.put(\"id\",\n stencilId.toString());\n\n return stencilObject;\n }",
"public PhotoList<Photo> getWithGeoData(Date minUploadDate, Date maxUploadDate, Date minTakenDate, Date maxTakenDate, int privacyFilter, String sort,\r\n Set<String> extras, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_WITH_GEO_DATA);\r\n\r\n if (minUploadDate != null) {\r\n parameters.put(\"min_upload_date\", Long.toString(minUploadDate.getTime() / 1000L));\r\n }\r\n if (maxUploadDate != null) {\r\n parameters.put(\"max_upload_date\", Long.toString(maxUploadDate.getTime() / 1000L));\r\n }\r\n if (minTakenDate != null) {\r\n parameters.put(\"min_taken_date\", Long.toString(minTakenDate.getTime() / 1000L));\r\n }\r\n if (maxTakenDate != null) {\r\n parameters.put(\"max_taken_date\", Long.toString(maxTakenDate.getTime() / 1000L));\r\n }\r\n if (privacyFilter > 0) {\r\n parameters.put(\"privacy_filter\", Integer.toString(privacyFilter));\r\n }\r\n if (sort != null) {\r\n parameters.put(\"sort\", sort);\r\n }\r\n if (extras != null && !extras.isEmpty()) {\r\n parameters.put(\"extras\", StringUtilities.join(extras, \",\"));\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 PhotoList<Photo> photos = PhotoUtils.createPhotoList(photosElement);\r\n return photos;\r\n }",
"public static UndeployDescription of(final DeploymentDescription deploymentDescription) {\n Assert.checkNotNullParam(\"deploymentDescription\", deploymentDescription);\n return of(deploymentDescription.getName()).addServerGroups(deploymentDescription.getServerGroups());\n }",
"public static String getVersionString() {\n\t\tString versionString = \"UNKNOWN\";\n\t\tProperties propeties = getProperites();\n\t\tif(propeties != null) {\n\t\t\tversionString = propeties.getProperty(\"finmath-lib.version\");\n\t\t}\n\t\treturn versionString;\n\t}",
"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 }"
] |
Enables a custom response
@param model
@param custom
@param path_id
@param clientUUID
@return
@throws Exception | [
"@RequestMapping(value = \"api/edit/enable/custom\", method = RequestMethod.POST)\n public\n @ResponseBody\n String enableCustomResponse(Model model, String custom, int path_id,\n @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {\n if (custom.equals(\"undefined\"))\n return null;\n editService.enableCustomResponse(custom, path_id, clientUUID);\n return null;\n }"
] | [
"public BoxUser.Info getInfo(String... fields) {\n URL url;\n if (fields.length > 0) {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", fields).toString();\n url = USER_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());\n } else {\n url = USER_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n }\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n return new Info(jsonObject);\n }",
"public static PJsonObject parseSpec(final String spec) {\n final JSONObject jsonSpec;\n try {\n jsonSpec = new JSONObject(spec);\n } catch (JSONException e) {\n throw new RuntimeException(\"Cannot parse the spec file: \" + spec, e);\n }\n return new PJsonObject(jsonSpec, \"spec\");\n }",
"public static appfwprofile_csrftag_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_csrftag_binding obj = new appfwprofile_csrftag_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_csrftag_binding response[] = (appfwprofile_csrftag_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public AbstractGraph getModuleGraph(final String moduleId) {\n final ModuleHandler moduleHandler = new ModuleHandler(repoHandler);\n final DbModule module = moduleHandler.getModule(moduleId);\n final DbOrganization organization = moduleHandler.getOrganization(module);\n\n filters.setCorporateFilter(new CorporateFilter(organization));\n\n final AbstractGraph graph = new ModuleGraph();\n addModuleToGraph(module, graph, 0);\n\n return graph;\n }",
"public boolean preHandle(HttpServletRequest request,\n HttpServletResponse response, Object handler) throws Exception {\n\n String queryString = request.getQueryString() == null ? \"\" : request.getQueryString();\n\n if (ConfigurationService.getInstance().isValid()\n || request.getServletPath().startsWith(\"/configuration\")\n || request.getServletPath().startsWith(\"/resources\")\n || queryString.contains(\"requestFromConfiguration=true\")) {\n return true;\n } else {\n response.sendRedirect(\"configuration\");\n return false;\n }\n }",
"public static List<File> extract(File zipFile, File outputFolder) throws IOException {\n List<File> extracted = new ArrayList<File>();\n\n byte[] buffer = new byte[2048];\n\n if (!outputFolder.exists()) {\n outputFolder.mkdir();\n }\n\n ZipInputStream zipInput = new ZipInputStream(new FileInputStream(zipFile));\n\n ZipEntry zipEntry = zipInput.getNextEntry();\n\n while (zipEntry != null) {\n\n String neFileNameName = zipEntry.getName();\n File newFile = new File(outputFolder + File.separator + neFileNameName);\n\n newFile.getParentFile().mkdirs();\n\n if (!zipEntry.isDirectory()) {\n FileOutputStream fos = new FileOutputStream(newFile);\n\n int size;\n while ((size = zipInput.read(buffer)) > 0) {\n fos.write(buffer, 0, size);\n }\n\n fos.close();\n extracted.add(newFile);\n }\n\n zipEntry = zipInput.getNextEntry();\n }\n\n zipInput.closeEntry();\n zipInput.close();\n\n return extracted;\n\n }",
"private String commaSeparate(Collection<String> strings)\n {\n StringBuilder buffer = new StringBuilder();\n Iterator<String> iterator = strings.iterator();\n while (iterator.hasNext())\n {\n String string = iterator.next();\n buffer.append(string);\n if (iterator.hasNext())\n {\n buffer.append(\", \");\n }\n }\n return buffer.toString();\n }",
"public static void keyPresent(final String key, final Map<String, ?> map) {\n if (!map.containsKey(key)) {\n throw new IllegalStateException(\n String.format(\"expected %s to be present\", key));\n }\n }",
"public void configure(Configuration pConfig) throws ConfigurationException\r\n {\r\n if (pConfig instanceof PBPoolConfiguration)\r\n {\r\n PBPoolConfiguration conf = (PBPoolConfiguration) pConfig;\r\n this.setMaxActive(conf.getMaxActive());\r\n this.setMaxIdle(conf.getMaxIdle());\r\n this.setMaxWait(conf.getMaxWaitMillis());\r\n this.setMinEvictableIdleTimeMillis(conf.getMinEvictableIdleTimeMillis());\r\n this.setTimeBetweenEvictionRunsMillis(conf.getTimeBetweenEvictionRunsMilli());\r\n this.setWhenExhaustedAction(conf.getWhenExhaustedAction());\r\n }\r\n else\r\n {\r\n LoggerFactory.getDefaultLogger().error(this.getClass().getName() +\r\n \" cannot read configuration properties, use default.\");\r\n }\r\n }"
] |
Set the dither matrix.
@param matrix the dither matrix
@see #getMatrix | [
"public void setMatrix(int[] matrix) {\n\t\tthis.matrix = matrix;\n\t\tsum = 0;\n\t\tfor (int i = 0; i < matrix.length; i++)\n\t\t\tsum += matrix[i];\n\t}"
] | [
"public static Object instantiate(Class clazz) throws InstantiationException\r\n {\r\n Object result = null;\r\n try\r\n {\r\n result = ClassHelper.newInstance(clazz);\r\n }\r\n catch(IllegalAccessException e)\r\n {\r\n try\r\n {\r\n result = ClassHelper.newInstance(clazz, true);\r\n }\r\n catch(Exception e1)\r\n {\r\n throw new ClassNotPersistenceCapableException(\"Can't instantiate class '\"\r\n + (clazz != null ? clazz.getName() : \"null\")\r\n + \"', message was: \" + e1.getMessage() + \")\", e1);\r\n }\r\n }\r\n return result;\r\n }",
"private void revisitMessages(Definitions def) {\n List<RootElement> rootElements = def.getRootElements();\n List<ItemDefinition> toAddDefinitions = new ArrayList<ItemDefinition>();\n for (RootElement root : rootElements) {\n if (root instanceof Message) {\n if (!existsMessageItemDefinition(rootElements,\n root.getId())) {\n ItemDefinition itemdef = Bpmn2Factory.eINSTANCE.createItemDefinition();\n itemdef.setId(root.getId() + \"Type\");\n toAddDefinitions.add(itemdef);\n ((Message) root).setItemRef(itemdef);\n }\n }\n }\n for (ItemDefinition id : toAddDefinitions) {\n def.getRootElements().add(id);\n }\n }",
"public void initDB() throws PlatformException\r\n {\r\n if (_initScripts.isEmpty())\r\n {\r\n createInitScripts();\r\n }\r\n\r\n Project project = new Project();\r\n TorqueSQLTask sqlTask = new TorqueSQLTask(); \r\n File outputDir = null;\r\n \r\n try\r\n {\r\n outputDir = new File(getWorkDir(), \"sql\");\r\n\r\n outputDir.mkdir();\r\n writeCompressedTexts(outputDir, _initScripts);\r\n\r\n project.setBasedir(outputDir.getAbsolutePath());\r\n\r\n // executing the generated sql, but this time with a torque task \r\n TorqueSQLExec sqlExec = new TorqueSQLExec();\r\n TorqueSQLExec.OnError onError = new TorqueSQLExec.OnError();\r\n\r\n sqlExec.setProject(project);\r\n onError.setValue(\"continue\");\r\n sqlExec.setAutocommit(true);\r\n sqlExec.setDriver(_jcd.getDriver());\r\n sqlExec.setOnerror(onError);\r\n sqlExec.setUserid(_jcd.getUserName());\r\n sqlExec.setPassword(_jcd.getPassWord() == null ? \"\" : _jcd.getPassWord());\r\n sqlExec.setUrl(getDBManipulationUrl());\r\n sqlExec.setSrcDir(outputDir.getAbsolutePath());\r\n sqlExec.setSqlDbMap(SQL_DB_MAP_NAME);\r\n sqlExec.execute();\r\n \r\n deleteDir(outputDir);\r\n }\r\n catch (Exception ex)\r\n {\r\n // clean-up\r\n if (outputDir != null)\r\n {\r\n deleteDir(outputDir);\r\n }\r\n throw new PlatformException(ex);\r\n }\r\n }",
"@Override\n public CopticDate date(int prolepticYear, int month, int dayOfMonth) {\n return CopticDate.of(prolepticYear, month, dayOfMonth);\n }",
"protected <T, A> ActiveOperation<T, A> removeActiveOperation(Integer id) {\n final ActiveOperation<T, A> removed = removeUnderLock(id);\n if(removed != null) {\n for(final Map.Entry<Integer, ActiveRequest<?, ?>> requestEntry : requests.entrySet()) {\n final ActiveRequest<?, ?> request = requestEntry.getValue();\n if(request.context == removed) {\n requests.remove(requestEntry.getKey());\n }\n }\n }\n return removed;\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 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 static Converter<List<String>, Object> createStringConstructorConverter(Class<?> resultClass) {\n try {\n final Constructor<?> constructor = resultClass.getConstructor(String.class);\n return new BasicConverter(defaultValue(resultClass)) {\n @Override\n protected Object convert(String value) throws Exception {\n return constructor.newInstance(value);\n }\n };\n } catch (Exception e) {\n return null;\n }\n }",
"public T addContentModification(final ContentModification modification) {\n if (itemFilter.accepts(modification.getItem())) {\n internalAddModification(modification);\n }\n return returnThis();\n }"
] |
Gets any app users that has an exact match with the externalAppUserId term.
@param api the API connection to be used when retrieving the users.
@param externalAppUserId the external app user id that has been set for app user
@param fields the fields to retrieve. Leave this out for the standard fields.
@return an iterable containing users matching the given email | [
"public static Iterable<BoxUser.Info> getAppUsersByExternalAppUserID(final BoxAPIConnection api,\n final String externalAppUserId, final String... fields) {\n return getUsersInfoForType(api, null, null, externalAppUserId, fields);\n }"
] | [
"public void start(String name)\n {\n GVRAnimator anim = findAnimation(name);\n\n if (name.equals(anim.getName()))\n {\n start(anim);\n return;\n }\n }",
"private int getItemViewType(Class prototypeClass) {\n int itemViewType = -1;\n for (Renderer renderer : prototypes) {\n if (renderer.getClass().equals(prototypeClass)) {\n itemViewType = getPrototypeIndex(renderer);\n break;\n }\n }\n if (itemViewType == -1) {\n throw new PrototypeNotFoundException(\n \"Review your RendererBuilder implementation, you are returning one\"\n + \" prototype class not found in prototypes collection\");\n }\n return itemViewType;\n }",
"public void setRequestType(int pathId, Integer requestType) {\n if (requestType == null) {\n requestType = Constants.REQUEST_TYPE_GET;\n }\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_REQUEST_TYPE + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, requestType);\n statement.setInt(2, pathId);\n statement.executeUpdate();\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 static String getString(Properties props, String name, String defaultValue) {\n return props.containsKey(name) ? props.getProperty(name) : defaultValue;\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 }",
"protected void processStop(Endpoint endpoint, EventTypeEnum eventType) {\n if (!sendLifecycleEvent) {\n return;\n }\n\n Event event = createEvent(endpoint, eventType);\n monitoringServiceClient.putEvents(Collections.singletonList(event));\n if (LOG.isLoggable(Level.INFO)) {\n LOG.info(\"Send \" + eventType + \" event to SAM Server successful!\");\n }\n }",
"public ExecInspection execStartVerbose(String containerId, String... commands) {\n this.readWriteLock.readLock().lock();\n try {\n String id = execCreate(containerId, commands);\n CubeOutput output = execStartOutput(id);\n\n return new ExecInspection(output, inspectExec(id));\n } finally {\n this.readWriteLock.readLock().unlock();\n }\n }",
"@Override\n public boolean postExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, BuildListener listener,\n Throwable error) {\n //listener.getLogger().println(\"[MavenDependenciesRecorder] mojo: \" + mojo.getClass() + \":\" + mojo.getGoal());\n //listener.getLogger().println(\"[MavenDependenciesRecorder] dependencies: \" + pom.getArtifacts());\n recordMavenDependencies(pom.getArtifacts());\n return true;\n }",
"public void printProbs(String filename,\r\n DocumentReaderAndWriter<IN> readerAndWriter) {\r\n // only for the OCR data does this matter\r\n flags.ocrTrain = false;\r\n\r\n ObjectBank<List<IN>> docs =\r\n makeObjectBankFromFile(filename, readerAndWriter);\r\n printProbsDocuments(docs);\r\n }"
] |
Returns the default conversion for the given java type.
@param javaType The qualified java type
@return The default conversion or <code>null</code> if there is no default conversion for the type | [
"public static String getDefaultConversionFor(String javaType)\r\n {\r\n return _jdbcConversions.containsKey(javaType) ? (String)_jdbcConversions.get(javaType) : null;\r\n }"
] | [
"public static boolean reconnect(final Jedis jedis, final int reconAttempts, final long reconnectSleepTime) {\n int i = 1;\n do {\n try {\n jedis.disconnect();\n try {\n Thread.sleep(reconnectSleepTime);\n } catch (Exception e2) {\n }\n jedis.connect();\n } catch (JedisConnectionException jce) {\n } // Ignore bad connection attempts\n catch (Exception e3) {\n LOG.error(\"Unknown Exception while trying to reconnect to Redis\", e3);\n }\n } while (++i <= reconAttempts && !testJedisConnection(jedis));\n return testJedisConnection(jedis);\n }",
"public <V> V getObject(final String key, final Class<V> type) {\n final Object obj = this.values.get(key);\n return type.cast(obj);\n }",
"public UriComponentsBuilder replaceQueryParam(String name, Object... values) {\n\t\tAssert.notNull(name, \"'name' must not be null\");\n\t\tthis.queryParams.remove(name);\n\t\tif (!ObjectUtils.isEmpty(values)) {\n\t\t\tqueryParam(name, values);\n\t\t}\n\t\tresetSchemeSpecificPart();\n\t\treturn this;\n\t}",
"private CmsVfsEntryBean buildVfsEntryBeanForQuickSearch(\n CmsResource resource,\n Multimap<CmsResource, CmsResource> childMap,\n Set<CmsResource> filterMatches,\n Set<String> parentPaths,\n boolean isRoot)\n throws CmsException {\n\n CmsObject cms = getCmsObject();\n String title = cms.readPropertyObject(resource, CmsPropertyDefinition.PROPERTY_TITLE, false).getValue();\n boolean isMatch = filterMatches.contains(resource);\n List<CmsVfsEntryBean> childBeans = Lists.newArrayList();\n\n Collection<CmsResource> children = childMap.get(resource);\n if (!children.isEmpty()) {\n for (CmsResource child : children) {\n CmsVfsEntryBean childBean = buildVfsEntryBeanForQuickSearch(\n child,\n childMap,\n filterMatches,\n parentPaths,\n false);\n childBeans.add(childBean);\n }\n } else if (filterMatches.contains(resource)) {\n if (parentPaths.contains(resource.getRootPath())) {\n childBeans = null;\n }\n // otherwise childBeans remains an empty list\n }\n\n String rootPath = resource.getRootPath();\n CmsVfsEntryBean result = new CmsVfsEntryBean(\n rootPath,\n resource.getStructureId(),\n title,\n CmsIconUtil.getIconClasses(CmsIconUtil.getDisplayType(cms, resource), resource.getName(), true),\n isRoot,\n isEditable(cms, resource),\n childBeans,\n isMatch);\n String siteRoot = null;\n if (OpenCms.getSiteManager().startsWithShared(rootPath)) {\n siteRoot = OpenCms.getSiteManager().getSharedFolder();\n } else {\n String tempSiteRoot = OpenCms.getSiteManager().getSiteRoot(rootPath);\n if (tempSiteRoot != null) {\n siteRoot = tempSiteRoot;\n } else {\n siteRoot = \"\";\n }\n }\n result.setSiteRoot(siteRoot);\n return result;\n }",
"public String login(Authentication authentication) {\n\t\tString token = getToken();\n\t\treturn login(token, authentication);\n\t}",
"public static String getOperationName(final ModelNode op) {\n if (op.hasDefined(OP)) {\n return op.get(OP).asString();\n }\n throw ControllerClientLogger.ROOT_LOGGER.operationNameNotFound();\n }",
"public static dnssuffix[] get(nitro_service service) throws Exception{\n\t\tdnssuffix obj = new dnssuffix();\n\t\tdnssuffix[] response = (dnssuffix[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"private void removeFromInverseAssociations(\n\t\t\tTuple resultset,\n\t\t\tint tableIndex,\n\t\t\tSerializable id,\n\t\t\tSharedSessionContractImplementor session) {\n\t\tnew EntityAssociationUpdater( this )\n\t\t\t\t.id( id )\n\t\t\t\t.resultset( resultset )\n\t\t\t\t.session( session )\n\t\t\t\t.tableIndex( tableIndex )\n\t\t\t\t.propertyMightRequireInverseAssociationManagement( propertyMightBeMainSideOfBidirectionalAssociation )\n\t\t\t\t.removeNavigationalInformationFromInverseSide();\n\t}",
"private void countCoordinateStatement(Statement statement,\n\t\t\tItemDocument itemDocument) {\n\t\tValue value = statement.getValue();\n\t\tif (!(value instanceof GlobeCoordinatesValue)) {\n\t\t\treturn;\n\t\t}\n\n\t\tGlobeCoordinatesValue coordsValue = (GlobeCoordinatesValue) value;\n\t\tif (!this.globe.equals((coordsValue.getGlobe()))) {\n\t\t\treturn;\n\t\t}\n\n\t\tint xCoord = (int) (((coordsValue.getLongitude() + 180.0) / 360.0) * this.width)\n\t\t\t\t% this.width;\n\t\tint yCoord = (int) (((coordsValue.getLatitude() + 90.0) / 180.0) * this.height)\n\t\t\t\t% this.height;\n\n\t\tif (xCoord < 0 || yCoord < 0 || xCoord >= this.width\n\t\t\t\t|| yCoord >= this.height) {\n\t\t\tSystem.out.println(\"Dropping out-of-range coordinate: \"\n\t\t\t\t\t+ coordsValue);\n\t\t\treturn;\n\t\t}\n\n\t\tcountCoordinates(xCoord, yCoord, itemDocument);\n\t\tthis.count += 1;\n\n\t\tif (this.count % 100000 == 0) {\n\t\t\treportProgress();\n\t\t\twriteImages();\n\t\t}\n\t}"
] |
I KNOW WHAT I AM DOING | [
"private static void handleSignals() {\n if (DaemonStarter.isRunMode()) {\n try {\n // handle SIGHUP to prevent process to get killed when exiting the tty\n Signal.handle(new Signal(\"HUP\"), arg0 -> {\n // Nothing to do here\n System.out.println(\"SIG INT\");\n });\n } catch (IllegalArgumentException e) {\n System.err.println(\"Signal HUP not supported\");\n }\n\n try {\n // handle SIGTERM to notify the program to stop\n Signal.handle(new Signal(\"TERM\"), arg0 -> {\n System.out.println(\"SIG TERM\");\n DaemonStarter.stopService();\n });\n } catch (IllegalArgumentException e) {\n System.err.println(\"Signal TERM not supported\");\n }\n\n try {\n // handle SIGINT to notify the program to stop\n Signal.handle(new Signal(\"INT\"), arg0 -> {\n System.out.println(\"SIG INT\");\n DaemonStarter.stopService();\n });\n } catch (IllegalArgumentException e) {\n System.err.println(\"Signal INT not supported\");\n }\n\n try {\n // handle SIGUSR2 to notify the life-cycle listener\n Signal.handle(new Signal(\"USR2\"), arg0 -> {\n System.out.println(\"SIG USR2\");\n DaemonStarter.getLifecycleListener().signalUSR2();\n });\n } catch (IllegalArgumentException e) {\n System.err.println(\"Signal USR2 not supported\");\n }\n }\n }"
] | [
"public static <T> T splitEachLine(InputStream stream, String regex, String charset, @ClosureParams(value=FromString.class,options=\"List<String>\") Closure<T> closure) throws IOException {\n return splitEachLine(new BufferedReader(new InputStreamReader(stream, charset)), regex, closure);\n }",
"public static String constructResourceId(\n final String subscriptionId,\n final String resourceGroupName,\n final String resourceProviderNamespace,\n final String resourceType,\n final String resourceName,\n final String parentResourcePath) {\n String prefixedParentPath = parentResourcePath;\n if (parentResourcePath != null && !parentResourcePath.isEmpty()) {\n prefixedParentPath = \"/\" + parentResourcePath;\n }\n return String.format(\n \"/subscriptions/%s/resourcegroups/%s/providers/%s%s/%s/%s\",\n subscriptionId,\n resourceGroupName,\n resourceProviderNamespace,\n prefixedParentPath,\n resourceType,\n resourceName);\n }",
"public static void setBackgroundDrawable(View view, Drawable drawable) {\n if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.JELLY_BEAN) {\n view.setBackgroundDrawable(drawable);\n } else {\n view.setBackground(drawable);\n }\n }",
"public BufferedImage getImage() {\n ByteBuffer artwork = getRawBytes();\n artwork.rewind();\n byte[] imageBytes = new byte[artwork.remaining()];\n artwork.get(imageBytes);\n try {\n return ImageIO.read(new ByteArrayInputStream(imageBytes));\n } catch (IOException e) {\n logger.error(\"Weird! Caught exception creating image from artwork bytes\", e);\n return null;\n }\n }",
"private void readCalendars(Project project) throws MPXJException\n {\n Calendars calendars = project.getCalendars();\n if (calendars != null)\n {\n for (net.sf.mpxj.planner.schema.Calendar cal : calendars.getCalendar())\n {\n readCalendar(cal, null);\n }\n\n Integer defaultCalendarID = getInteger(project.getCalendar());\n m_defaultCalendar = m_projectFile.getCalendarByUniqueID(defaultCalendarID);\n if (m_defaultCalendar != null)\n {\n m_projectFile.getProjectProperties().setDefaultCalendarName(m_defaultCalendar.getName());\n }\n }\n }",
"public void check(ReferenceDescriptorDef refDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureClassRef(refDef, checkLevel);\r\n checkProxyPrefetchingLimit(refDef, checkLevel);\r\n }",
"private static void updateJar(final File file, final byte[] searchPattern, final int[] badSkipBytes, final int newSig, final int endSig) throws IOException {\n final RandomAccessFile raf = new RandomAccessFile(file, \"rw\");\n try {\n final FileChannel channel = raf.getChannel();\n try {\n long pos = channel.size() - ENDLEN;\n final ScanContext context;\n if (newSig == CRIPPLED_ENDSIG) {\n context = new ScanContext(GOOD_ENDSIG_PATTERN, CRIPPLED_ENDSIG_PATTERN);\n } else if (newSig == GOOD_ENDSIG) {\n context = new ScanContext(CRIPPLED_ENDSIG_PATTERN, GOOD_ENDSIG_PATTERN);\n } else {\n context = null;\n }\n\n if (!validateEndRecord(file, channel, pos, endSig)) {\n pos = scanForEndSig(file, channel, context);\n }\n if (pos == -1) {\n if (context.state == State.NOT_FOUND) {\n // Don't fail patching if we cannot validate a valid zip\n PatchLogger.ROOT_LOGGER.cannotInvalidateZip(file.getAbsolutePath());\n }\n return;\n }\n // Update the central directory record\n channel.position(pos);\n final ByteBuffer buffer = ByteBuffer.allocate(4);\n buffer.order(ByteOrder.LITTLE_ENDIAN);\n buffer.putInt(newSig);\n buffer.flip();\n while (buffer.hasRemaining()) {\n channel.write(buffer);\n }\n } finally {\n safeClose(channel);\n }\n } finally {\n safeClose(raf);\n }\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 }",
"private void ensureNext() {\n // Check if the current scan result has more keys (i.e. the index did not reach the end of the result list)\n if (resultIndex < scanResult.getResult().size()) {\n return;\n }\n // Since the current scan result was fully iterated,\n // if there is another cursor scan it and ensure next key (recursively)\n if (!FIRST_CURSOR.equals(scanResult.getStringCursor())) {\n scanResult = scan(scanResult.getStringCursor(), scanParams);\n resultIndex = 0;\n ensureNext();\n }\n }"
] |
Resize the image passing the new height and width
@param height
@param width
@return | [
"public void resize(int w, int h) {\n\n // using the new approach of Java 2D API\n BufferedImage buf = new BufferedImage(w, h, image.getType());\n Graphics2D g2d = (Graphics2D) buf.getGraphics();\n g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);\n g2d.drawImage(image, 0, 0, w, h, null);\n g2d.dispose();\n image = buf;\n width = w;\n height = h;\n updateColorArray();\n }"
] | [
"@PostConstruct\n\tprotected void postConstruct() throws GeomajasException {\n\t\tif (null != crsDefinitions) {\n\t\t\tfor (CrsInfo crsInfo : crsDefinitions.values()) {\n\t\t\t\ttry {\n\t\t\t\t\tCoordinateReferenceSystem crs = CRS.parseWKT(crsInfo.getCrsWkt());\n\t\t\t\t\tString code = crsInfo.getKey();\n\t\t\t\t\tcrsCache.put(code, CrsFactory.getCrs(code, crs));\n\t\t\t\t} catch (FactoryException e) {\n\t\t\t\t\tthrow new GeomajasException(e, ExceptionCode.CRS_DECODE_FAILURE_FOR_MAP, crsInfo.getKey());\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (null != crsTransformDefinitions) {\n\t\t\tfor (CrsTransformInfo crsTransformInfo : crsTransformDefinitions.values()) {\n\t\t\t\tString key = getTransformKey(crsTransformInfo);\n\t\t\t\ttransformCache.put(key, getCrsTransform(key, crsTransformInfo));\n\t\t\t}\n\t\t}\n\t\tGeometryFactory factory = new GeometryFactory();\n\t\tEMPTY_GEOMETRIES.put(Point.class, factory.createPoint((Coordinate) null));\n\t\tEMPTY_GEOMETRIES.put(LineString.class, factory.createLineString((Coordinate[]) null));\n\t\tEMPTY_GEOMETRIES.put(Polygon.class, factory.createPolygon(null, null));\n\t\tEMPTY_GEOMETRIES.put(MultiPoint.class, factory.createMultiPoint((Coordinate[]) null));\n\t\tEMPTY_GEOMETRIES.put(MultiLineString.class, factory.createMultiLineString((LineString[]) null)); // cast needed!\n\t\tEMPTY_GEOMETRIES.put(MultiPolygon.class, factory.createMultiPolygon((Polygon[]) null)); // cast needed!\n\t\tEMPTY_GEOMETRIES.put(Geometry.class, factory.createGeometryCollection(null));\n\t}",
"public Info getInfo() {\n BoxAPIConnection api = this.getAPI();\n URL url = COLLABORATION_URL_TEMPLATE.build(api.getBaseURL(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n return new Info(jsonObject);\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}",
"public static base_response rename(nitro_service client, nsacl6 resource, String new_acl6name) throws Exception {\n\t\tnsacl6 renameresource = new nsacl6();\n\t\trenameresource.acl6name = resource.acl6name;\n\t\treturn renameresource.rename_resource(client,new_acl6name);\n\t}",
"public Map<String, MBeanOperationInfo> getOperationMetadata() {\n\n MBeanOperationInfo[] operations = mBeanInfo.getOperations();\n\n Map<String, MBeanOperationInfo> operationMap = new TreeMap<String, MBeanOperationInfo>();\n for (MBeanOperationInfo operation: operations) {\n operationMap.put(operation.getName(), operation);\n }\n return operationMap;\n }",
"public static base_response update(nitro_service client, protocolhttpband resource) throws Exception {\n\t\tprotocolhttpband updateresource = new protocolhttpband();\n\t\tupdateresource.reqbandsize = resource.reqbandsize;\n\t\tupdateresource.respbandsize = resource.respbandsize;\n\t\treturn updateresource.update_resource(client);\n\t}",
"static String replaceCheckDigit(final String iban, final String checkDigit) {\n return getCountryCode(iban) + checkDigit + getBban(iban);\n }",
"public static Iterable<BoxCollection.Info> getAllCollections(final BoxAPIConnection api) {\n return new Iterable<BoxCollection.Info>() {\n public Iterator<BoxCollection.Info> iterator() {\n URL url = GET_COLLECTIONS_URL_TEMPLATE.build(api.getBaseURL());\n return new BoxCollectionIterator(api, url);\n }\n };\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 }"
] |
returns position of xpath element which match the expression xpath in the String dom.
@param dom the Document to search in
@param xpath the xpath query
@return position of xpath element, if fails returns -1 | [
"public static int getXPathLocation(String dom, String xpath) {\n\t\tString dom_lower = dom.toLowerCase();\n\t\tString xpath_lower = xpath.toLowerCase();\n\t\tString[] elements = xpath_lower.split(\"/\");\n\t\tint pos = 0;\n\t\tint temp;\n\t\tint number;\n\t\tfor (String element : elements) {\n\t\t\tif (!element.isEmpty() && !element.startsWith(\"@\") && !element.contains(\"()\")) {\n\t\t\t\tif (element.contains(\"[\")) {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tnumber =\n\t\t\t\t\t\t\t\tInteger.parseInt(element.substring(element.indexOf(\"[\") + 1,\n\t\t\t\t\t\t\t\t\t\telement.indexOf(\"]\")));\n\t\t\t\t\t} catch (NumberFormatException e) {\n\t\t\t\t\t\treturn -1;\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tnumber = 1;\n\t\t\t\t}\n\t\t\t\tfor (int i = 0; i < number; i++) {\n\t\t\t\t\t// find new open element\n\t\t\t\t\ttemp = dom_lower.indexOf(\"<\" + stripEndSquareBrackets(element), pos);\n\n\t\t\t\t\tif (temp > -1) {\n\t\t\t\t\t\tpos = temp + 1;\n\n\t\t\t\t\t\t// if depth>1 then goto end of current element\n\t\t\t\t\t\tif (number > 1 && i < number - 1) {\n\t\t\t\t\t\t\tpos =\n\t\t\t\t\t\t\t\t\tgetCloseElementLocation(dom_lower, pos,\n\t\t\t\t\t\t\t\t\t\t\tstripEndSquareBrackets(element));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn pos - 1;\n\t}"
] | [
"public Tree determineHead(Tree t, Tree parent) {\r\n if (nonTerminalInfo == null) {\r\n throw new RuntimeException(\"Classes derived from AbstractCollinsHeadFinder must\" + \" create and fill HashMap nonTerminalInfo.\");\r\n }\r\n if (t == null || t.isLeaf()) {\r\n return null;\r\n }\r\n if (DEBUG) {\r\n System.err.println(\"determineHead for \" + t.value());\r\n }\r\n \r\n Tree[] kids = t.children();\r\n\r\n Tree theHead;\r\n // first check if subclass found explicitly marked head\r\n if ((theHead = findMarkedHead(t)) != null) {\r\n if (DEBUG) {\r\n System.err.println(\"Find marked head method returned \" +\r\n theHead.label() + \" as head of \" + t.label());\r\n }\r\n return theHead;\r\n }\r\n\r\n // if the node is a unary, then that kid must be the head\r\n // it used to special case preterminal and ROOT/TOP case\r\n // but that seemed bad (especially hardcoding string \"ROOT\")\r\n if (kids.length == 1) {\r\n if (DEBUG) {\r\n System.err.println(\"Only one child determines \" +\r\n kids[0].label() + \" as head of \" + t.label());\r\n }\r\n return kids[0];\r\n }\r\n\r\n return determineNonTrivialHead(t, parent);\r\n }",
"private String writeSchemata(File dir) throws IOException\r\n {\r\n writeCompressedTexts(dir, _torqueSchemata);\r\n\r\n StringBuffer includes = new StringBuffer();\r\n\r\n for (Iterator it = _torqueSchemata.keySet().iterator(); it.hasNext();)\r\n {\r\n includes.append((String)it.next());\r\n if (it.hasNext())\r\n {\r\n includes.append(\",\");\r\n }\r\n }\r\n return includes.toString();\r\n }",
"protected void clearStatementCaches(boolean internalClose) {\r\n\r\n\t\tif (this.statementCachingEnabled){ // safety\r\n\r\n\t\t\tif (internalClose){\r\n\t\t\t\tthis.callableStatementCache.clear();\r\n\t\t\t\tthis.preparedStatementCache.clear();\r\n\t\t\t} else {\r\n\t\t\t\tif (this.pool.closeConnectionWatch){ // debugging enabled?\r\n\t\t\t\t\tthis.callableStatementCache.checkForProperClosure();\r\n\t\t\t\t\tthis.preparedStatementCache.checkForProperClosure();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}",
"public void parseRawValue(String value)\n {\n int valueIndex = 0;\n int elementIndex = 0;\n m_elements.clear();\n while (valueIndex < value.length() && elementIndex < m_elements.size())\n {\n int elementLength = m_lengths.get(elementIndex).intValue();\n if (elementIndex > 0)\n {\n m_elements.add(m_separators.get(elementIndex - 1));\n }\n int endIndex = valueIndex + elementLength;\n if (endIndex > value.length())\n {\n endIndex = value.length();\n }\n String element = value.substring(valueIndex, endIndex);\n m_elements.add(element);\n valueIndex += elementLength;\n elementIndex++;\n }\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 }",
"private void checkPrimaryKey(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n if (classDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_GENERATE_TABLE_INFO, true) &&\r\n classDef.getPrimaryKeys().isEmpty())\r\n {\r\n LogHelper.warn(true,\r\n getClass(),\r\n \"checkPrimaryKey\",\r\n \"The class \"+classDef.getName()+\" has no primary key\");\r\n }\r\n }",
"@SuppressWarnings(\"unchecked\")\n public static <T> T getJlsDefaultValue(Class<T> type) {\n if(!type.isPrimitive()) {\n return null;\n }\n return (T) JLS_PRIMITIVE_DEFAULT_VALUES.get(type);\n }",
"@Override\n public void postCrawling(CrawlSession session, ExitStatus exitStatus) {\n LOG.debug(\"postCrawling\");\n StateFlowGraph sfg = session.getStateFlowGraph();\n checkSFG(sfg);\n // TODO: call state abstraction function to get distance matrix and run rscript on it to\n // create clusters\n String[][] clusters = null;\n // generateClusters(session);\n\n result = outModelCache.close(session, exitStatus, clusters);\n\n outputBuilder.write(result, session.getConfig(), clusters);\n StateWriter writer =\n new StateWriter(outputBuilder, sfg, ImmutableMap.copyOf(visitedStates));\n for (State state : result.getStates().values()) {\n try {\n writer.writeHtmlForState(state);\n } catch (Exception Ex) {\n LOG.info(\"couldn't write state :\" + state.getName());\n }\n }\n LOG.info(\"Crawl overview plugin has finished\");\n }",
"public static<A, Z> Function1<A, Z> lift(Func1<A, Z> f) {\n\treturn bridge.lift(f);\n }"
] |
Creates a future that will send a request to the reporting host and call
the handler with the response
@param path the path at the reporting host which the request will be made
@param reportingHandler the handler to receive the response once executed
and recieved
@return a {@link java.util.concurrent.Future} for handing the request | [
"public Future<String> sendRequest(final String path, final ReportingHandler reportingHandler) {\r\n return threadPool.submit(new Callable<String>() {\r\n @Override\r\n public String call() {\r\n String response = getResponse(path);\n\r\n if (reportingHandler != null) {\r\n reportingHandler.handleResponse(response);\r\n }\n\r\n return response;\r\n }\r\n });\r\n }"
] | [
"public void fire(StepFinishedEvent event) {\n Step step = stepStorage.adopt();\n event.process(step);\n\n notifier.fire(event);\n }",
"private void checkId(FieldDescriptorDef fieldDef, String checkLevel) throws ConstraintException\r\n {\r\n if (CHECKLEVEL_NONE.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n\r\n String id = fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_ID);\r\n\r\n if ((id != null) && (id.length() > 0))\r\n {\r\n try\r\n {\r\n Integer.parseInt(id);\r\n }\r\n catch (NumberFormatException ex)\r\n {\r\n throw new ConstraintException(\"The id attribute of field \"+fieldDef.getName()+\" in class \"+fieldDef.getOwner().getName()+\" is not a valid number\");\r\n }\r\n }\r\n }",
"protected void handleRequestOut(T message) throws Fault {\n String flowId = FlowIdHelper.getFlowId(message);\n if (flowId == null\n && message.containsKey(PhaseInterceptorChain.PREVIOUS_MESSAGE)) {\n // Web Service consumer is acting as an intermediary\n @SuppressWarnings(\"unchecked\")\n WeakReference<Message> wrPreviousMessage = (WeakReference<Message>) message\n .get(PhaseInterceptorChain.PREVIOUS_MESSAGE);\n Message previousMessage = (Message) wrPreviousMessage.get();\n flowId = FlowIdHelper.getFlowId(previousMessage);\n if (flowId != null && LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"flowId '\" + flowId + \"' found in previous message\");\n }\n }\n\n if (flowId == null) {\n // No flowId found. Generate one.\n flowId = ContextUtils.generateUUID();\n if (LOG.isLoggable(Level.FINE)) {\n LOG.fine(\"Generate new flowId '\" + flowId + \"'\");\n }\n }\n\n FlowIdHelper.setFlowId(message, flowId);\n }",
"public static boolean compareAnnotatedParameters(AnnotatedParameter<?> p1, AnnotatedParameter<?> p2) {\n return compareAnnotatedCallable(p1.getDeclaringCallable(), p2.getDeclaringCallable()) && p1.getPosition() == p2.getPosition() && compareAnnotated(p1, p2);\n }",
"private static String getLogManagerLoggerName(final String name) {\n return (name.equals(RESOURCE_NAME) ? CommonAttributes.ROOT_LOGGER_NAME : name);\n }",
"public void put(final K key, V value) {\n ManagedReference<V> ref = new ManagedReference<V>(bundle, value) {\n @Override\n public void finalizeReference() {\n super.finalizeReference();\n internalMap.remove(key, get());\n }\n };\n internalMap.put(key, ref);\n }",
"public void lock(Object obj, int lockMode) throws LockNotGrantedException\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"lock object was called on tx \" + this + \", object is \" + obj.toString());\r\n checkOpen();\r\n RuntimeObject rtObject = new RuntimeObject(obj, this);\r\n lockAndRegister(rtObject, lockMode, isImplicitLocking(), getRegistrationList());\r\n// if(isImplicitLocking()) moveToLastInOrderList(rtObject.getIdentity());\r\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 }",
"public int bindShader(GVRContext context, IRenderable rdata, GVRScene scene, boolean isMultiview)\n {\n String signature = getClass().getSimpleName();\n GVRShaderManager shaderManager = context.getShaderManager();\n GVRMaterial mtl = rdata.getMaterial();\n synchronized (shaderManager)\n {\n int nativeShader = shaderManager.getShader(signature);\n\n if (nativeShader == 0)\n {\n nativeShader = addShader(shaderManager, signature, mtl);\n }\n if (nativeShader > 0)\n {\n rdata.setShader(nativeShader, isMultiview);\n }\n return nativeShader;\n }\n }"
] |
in truth we probably only need the types as injected by the metadata binder | [
"private boolean isOrdinal(int paramType) {\n\t\tswitch ( paramType ) {\n\t\t\tcase Types.INTEGER:\n\t\t\tcase Types.NUMERIC:\n\t\t\tcase Types.SMALLINT:\n\t\t\tcase Types.TINYINT:\n\t\t\tcase Types.BIGINT:\n\t\t\tcase Types.DECIMAL: //for Oracle Driver\n\t\t\tcase Types.DOUBLE: //for Oracle Driver\n\t\t\tcase Types.FLOAT: //for Oracle Driver\n\t\t\t\treturn true;\n\t\t\tcase Types.CHAR:\n\t\t\tcase Types.LONGVARCHAR:\n\t\t\tcase Types.VARCHAR:\n\t\t\t\treturn false;\n\t\t\tdefault:\n\t\t\t\tthrow new HibernateException( \"Unable to persist an Enum in a column of SQL Type: \" + paramType );\n\t\t}\n\t}"
] | [
"private <T> T getBeanOrNull(String name, Class<T> requiredType) {\n\t\tif (name == null || !applicationContext.containsBean(name)) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\ttry {\n\t\t\t\treturn applicationContext.getBean(name, requiredType);\n\t\t\t} catch (BeansException be) {\n\t\t\t\tlog.error(\"Error during getBeanOrNull, not rethrown, \" + be.getMessage(), be);\n\t\t\t\treturn null;\n\t\t\t}\n\t\t}\n\t}",
"public String getStatement() throws SQLException {\n\t\tStringBuilder sb = new StringBuilder();\n\t\tappendSql(null, sb, new ArrayList<ArgumentHolder>());\n\t\treturn sb.toString();\n\t}",
"public synchronized void resumeControlPoint(final String entryPoint) {\n for (ControlPoint ep : entryPoints.values()) {\n if (ep.getEntryPoint().equals(entryPoint)) {\n ep.resume();\n }\n }\n }",
"private Collection<Locale> initLocales() {\n\n Collection<Locale> locales = null;\n switch (m_bundleType) {\n case DESCRIPTOR:\n locales = new ArrayList<Locale>(1);\n locales.add(Descriptor.LOCALE);\n break;\n case XML:\n case PROPERTY:\n locales = OpenCms.getLocaleManager().getAvailableLocales(m_cms, m_resource);\n break;\n default:\n throw new IllegalArgumentException();\n }\n return locales;\n\n }",
"public static base_response unset(nitro_service client, lbsipparameters resource, String[] args) throws Exception{\n\t\tlbsipparameters unsetresource = new lbsipparameters();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"protected static List<StackTraceElement> filterStackTrace(StackTraceElement[] stack) {\r\n List<StackTraceElement> filteredStack = new ArrayList<StackTraceElement>();\r\n\r\n int i = 2; // we can skip the first two (first is getStackTrace(), second is this method)\r\n while (i < stack.length) {\r\n boolean isLoggingClass = false;\r\n for (String loggingClass : loggingClasses) {\r\n String className = stack[i].getClassName();\r\n if (className.startsWith(loggingClass)) {\r\n isLoggingClass = true;\r\n break;\r\n }\r\n }\r\n if (!isLoggingClass) {\r\n filteredStack.add(stack[i]);\r\n }\r\n\r\n i += 1;\r\n }\r\n\r\n // if we didn't find anything, keep the full stack\r\n if (filteredStack.size() == 0) {\r\n return Arrays.asList(stack);\r\n }\r\n return filteredStack;\r\n }",
"public boolean detectTierRichCss() {\r\n\r\n boolean result = false;\r\n //The following devices are explicitly ok.\r\n //Note: 'High' BlackBerry devices ONLY\r\n if (detectMobileQuick()) {\r\n\r\n //Exclude iPhone Tier and e-Ink Kindle devices.\r\n if (!detectTierIphone() && !detectKindle()) {\r\n\r\n //The following devices are explicitly ok.\r\n //Note: 'High' BlackBerry devices ONLY\r\n //Older Windows 'Mobile' isn't good enough for iPhone Tier.\r\n if (detectWebkit()\r\n || detectS60OssBrowser()\r\n || detectBlackBerryHigh()\r\n || detectWindowsMobile()\r\n || (userAgent.indexOf(engineTelecaQ) != -1)) {\r\n result = true;\r\n } // if detectWebkit()\r\n } //if !detectTierIphone()\r\n } //if detectMobileQuick()\r\n return result;\r\n }",
"public Script[] getScripts(Integer type) {\n ArrayList<Script> returnData = new ArrayList<>();\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" ORDER BY \" + Constants.GENERIC_ID);\n if (type != null) {\n statement = sqlConnection.prepareStatement(\"SELECT * FROM \" + Constants.DB_TABLE_SCRIPT +\n \" WHERE \" + Constants.SCRIPT_TYPE + \"= ?\" +\n \" ORDER BY \" + Constants.GENERIC_ID);\n statement.setInt(1, type);\n }\n\n logger.info(\"Query: {}\", statement);\n\n results = statement.executeQuery();\n while (results.next()) {\n returnData.add(scriptFromSQLResult(results));\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 (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return returnData.toArray(new Script[0]);\n }",
"private ProjectFile handleDosExeFile(InputStream stream) throws Exception\n {\n File file = InputStreamHelper.writeStreamToTempFile(stream, \".tmp\");\n InputStream is = null;\n\n try\n {\n is = new FileInputStream(file);\n if (is.available() > 1350)\n {\n StreamHelper.skip(is, 1024);\n\n // Bytes at offset 1024\n byte[] data = new byte[2];\n is.read(data);\n\n if (matchesFingerprint(data, WINDOWS_NE_EXE_FINGERPRINT))\n {\n StreamHelper.skip(is, 286);\n\n // Bytes at offset 1312\n data = new byte[34];\n is.read(data);\n if (matchesFingerprint(data, PRX_FINGERPRINT))\n {\n is.close();\n is = null;\n return readProjectFile(new P3PRXFileReader(), file);\n }\n }\n\n if (matchesFingerprint(data, STX_FINGERPRINT))\n {\n StreamHelper.skip(is, 31742);\n // Bytes at offset 32768\n data = new byte[4];\n is.read(data);\n if (matchesFingerprint(data, PRX3_FINGERPRINT))\n {\n is.close();\n is = null;\n return readProjectFile(new SureTrakSTXFileReader(), file);\n }\n }\n }\n return null;\n }\n\n finally\n {\n StreamHelper.closeQuietly(is);\n FileHelper.deleteQuietly(file);\n }\n }"
] |
Use this API to add cachecontentgroup. | [
"public static base_response add(nitro_service client, cachecontentgroup resource) throws Exception {\n\t\tcachecontentgroup addresource = new cachecontentgroup();\n\t\taddresource.name = resource.name;\n\t\taddresource.weakposrelexpiry = resource.weakposrelexpiry;\n\t\taddresource.heurexpiryparam = resource.heurexpiryparam;\n\t\taddresource.relexpiry = resource.relexpiry;\n\t\taddresource.relexpirymillisec = resource.relexpirymillisec;\n\t\taddresource.absexpiry = resource.absexpiry;\n\t\taddresource.absexpirygmt = resource.absexpirygmt;\n\t\taddresource.weaknegrelexpiry = resource.weaknegrelexpiry;\n\t\taddresource.hitparams = resource.hitparams;\n\t\taddresource.invalparams = resource.invalparams;\n\t\taddresource.ignoreparamvaluecase = resource.ignoreparamvaluecase;\n\t\taddresource.matchcookies = resource.matchcookies;\n\t\taddresource.invalrestrictedtohost = resource.invalrestrictedtohost;\n\t\taddresource.polleverytime = resource.polleverytime;\n\t\taddresource.ignorereloadreq = resource.ignorereloadreq;\n\t\taddresource.removecookies = resource.removecookies;\n\t\taddresource.prefetch = resource.prefetch;\n\t\taddresource.prefetchperiod = resource.prefetchperiod;\n\t\taddresource.prefetchperiodmillisec = resource.prefetchperiodmillisec;\n\t\taddresource.prefetchmaxpending = resource.prefetchmaxpending;\n\t\taddresource.flashcache = resource.flashcache;\n\t\taddresource.expireatlastbyte = resource.expireatlastbyte;\n\t\taddresource.insertvia = resource.insertvia;\n\t\taddresource.insertage = resource.insertage;\n\t\taddresource.insertetag = resource.insertetag;\n\t\taddresource.cachecontrol = resource.cachecontrol;\n\t\taddresource.quickabortsize = resource.quickabortsize;\n\t\taddresource.minressize = resource.minressize;\n\t\taddresource.maxressize = resource.maxressize;\n\t\taddresource.memlimit = resource.memlimit;\n\t\taddresource.ignorereqcachinghdrs = resource.ignorereqcachinghdrs;\n\t\taddresource.minhits = resource.minhits;\n\t\taddresource.alwaysevalpolicies = resource.alwaysevalpolicies;\n\t\taddresource.persist = resource.persist;\n\t\taddresource.pinned = resource.pinned;\n\t\taddresource.lazydnsresolve = resource.lazydnsresolve;\n\t\taddresource.hitselector = resource.hitselector;\n\t\taddresource.invalselector = resource.invalselector;\n\t\taddresource.type = resource.type;\n\t\treturn addresource.add_resource(client);\n\t}"
] | [
"protected void processTusFiles(String assemblyUrl) throws IOException, ProtocolException {\n tusClient.setUploadCreationURL(new URL(getClient().getHostUrl() + \"/resumable/files/\"));\n tusClient.enableResuming(tusURLStore);\n\n for (Map.Entry<String, File> entry : files.entrySet()) {\n processTusFile(entry.getValue(), entry.getKey(), assemblyUrl);\n }\n\n for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) {\n processTusFile(entry.getValue(), entry.getKey(), assemblyUrl);\n }\n }",
"public void addRow(String primaryKeyColumnName, Map<String, Object> map)\n {\n Integer rowNumber = Integer.valueOf(m_rowNumber++);\n map.put(\"ROW_NUMBER\", rowNumber);\n Object primaryKey = null;\n if (primaryKeyColumnName != null)\n {\n primaryKey = map.get(primaryKeyColumnName);\n }\n\n if (primaryKey == null)\n {\n primaryKey = rowNumber;\n }\n\n MapRow newRow = new MapRow(map);\n MapRow oldRow = m_rows.get(primaryKey);\n if (oldRow == null)\n {\n m_rows.put(primaryKey, newRow);\n }\n else\n {\n int oldVersion = oldRow.getInteger(\"ROW_VERSION\").intValue();\n int newVersion = newRow.getInteger(\"ROW_VERSION\").intValue();\n if (newVersion > oldVersion)\n {\n m_rows.put(primaryKey, newRow);\n }\n }\n }",
"public double getSpread(double bondPrice, Curve referenceCurve, AnalyticModel model) {\n\t\tGoldenSectionSearch search = new GoldenSectionSearch(-2.0, 2.0);\n\t\twhile(search.getAccuracy() > 1E-11 && !search.isDone()) {\n\t\t\tdouble x = search.getNextPoint();\n\t\t\tdouble fx=getValueWithGivenSpreadOverCurve(0.0,referenceCurve,x,model);\n\t\t\tdouble y = (bondPrice-fx)*(bondPrice-fx);\n\n\t\t\tsearch.setValue(y);\n\t\t}\n\t\treturn search.getBestPoint();\n\t}",
"public Topic getTopicInfo(String topicId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_TOPICS_GET_INFO);\r\n parameters.put(\"topic_id\", topicId);\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\r\n Element topicElement = response.getPayload();\r\n\r\n return parseTopic(topicElement);\r\n }",
"ArgumentsBuilder param(String param, Integer value) {\n if (value != null) {\n args.add(param);\n args.add(value.toString());\n }\n return this;\n }",
"@Override\n protected Deque<Step> childValue(Deque<Step> parentValue) {\n Deque<Step> queue = new LinkedList<>();\n queue.add(parentValue.getFirst());\n return queue;\n }",
"@SafeVarargs\n\tpublic static <T> Set<T> asSet(T... ts) {\n\t\tif ( ts == null ) {\n\t\t\treturn null;\n\t\t}\n\t\telse if ( ts.length == 0 ) {\n\t\t\treturn Collections.emptySet();\n\t\t}\n\t\telse {\n\t\t\tSet<T> set = new HashSet<T>( getInitialCapacityFromExpectedSize( ts.length ) );\n\t\t\tCollections.addAll( set, ts );\n\t\t\treturn Collections.unmodifiableSet( set );\n\t\t}\n\t}",
"public static lbvserver_servicegroup_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_servicegroup_binding obj = new lbvserver_servicegroup_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_servicegroup_binding response[] = (lbvserver_servicegroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static String movePath( final String file,\n final String target ) {\n final String name = new File(file).getName();\n return target.endsWith(\"/\") ? target + name : target + '/' + name;\n }"
] |
AND operation which takes the previous clause and the next clause and AND's them together. | [
"public Where<T, ID> and() {\n\t\tManyClause clause = new ManyClause(pop(\"AND\"), ManyClause.AND_OPERATION);\n\t\tpush(clause);\n\t\taddNeedsFuture(clause);\n\t\treturn this;\n\t}"
] | [
"@NonNull\n @Override\n public File getParent(@NonNull final File from) {\n if (from.getPath().equals(getRoot().getPath())) {\n // Already at root, we can't go higher\n return from;\n } else if (from.getParentFile() != null) {\n return from.getParentFile();\n } else {\n return from;\n }\n }",
"@Pure\n\tpublic static <P1, P2, RESULT> Function1<P2, RESULT> curry(final Function2<? super P1, ? super P2, ? extends RESULT> function,\n\t\t\tfinal P1 argument) {\n\t\tif (function == null)\n\t\t\tthrow new NullPointerException(\"function\");\n\t\treturn new Function1<P2, RESULT>() {\n\t\t\t@Override\n\t\t\tpublic RESULT apply(P2 p) {\n\t\t\t\treturn function.apply(argument, p);\n\t\t\t}\n\t\t};\n\t}",
"public int update(DatabaseConnection databaseConnection, T data, ObjectCache objectCache) throws SQLException {\n\t\ttry {\n\t\t\t// there is always and id field as an argument so just return 0 lines updated\n\t\t\tif (argFieldTypes.length <= 1) {\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t\tObject[] args = getFieldObjects(data);\n\t\t\tObject newVersion = null;\n\t\t\tif (versionFieldType != null) {\n\t\t\t\tnewVersion = versionFieldType.extractJavaFieldValue(data);\n\t\t\t\tnewVersion = versionFieldType.moveToNextValue(newVersion);\n\t\t\t\targs[versionFieldTypeIndex] = versionFieldType.convertJavaFieldToSqlArgValue(newVersion);\n\t\t\t}\n\t\t\tint rowC = databaseConnection.update(statement, args, argFieldTypes);\n\t\t\tif (rowC > 0) {\n\t\t\t\tif (newVersion != null) {\n\t\t\t\t\t// if we have updated a row then update the version field in our object to the new value\n\t\t\t\t\tversionFieldType.assignField(connectionSource, data, newVersion, false, null);\n\t\t\t\t}\n\t\t\t\tif (objectCache != null) {\n\t\t\t\t\t// if we've changed something then see if we need to update our cache\n\t\t\t\t\tObject id = idField.extractJavaFieldValue(data);\n\t\t\t\t\tT cachedData = objectCache.get(clazz, id);\n\t\t\t\t\tif (cachedData != null && cachedData != data) {\n\t\t\t\t\t\t// copy each field from the updated data into the cached object\n\t\t\t\t\t\tfor (FieldType fieldType : tableInfo.getFieldTypes()) {\n\t\t\t\t\t\t\tif (fieldType != idField) {\n\t\t\t\t\t\t\t\tfieldType.assignField(connectionSource, cachedData,\n\t\t\t\t\t\t\t\t\t\tfieldType.extractJavaFieldValue(data), false, objectCache);\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\tlogger.debug(\"update data with statement '{}' and {} args, changed {} rows\", statement, args.length, rowC);\n\t\t\tif (args.length > 0) {\n\t\t\t\t// need to do the (Object) cast to force args to be a single object\n\t\t\t\tlogger.trace(\"update arguments: {}\", (Object) args);\n\t\t\t}\n\t\t\treturn rowC;\n\t\t} catch (SQLException e) {\n\t\t\tthrow SqlExceptionUtil.create(\"Unable to run update stmt on object \" + data + \": \" + statement, e);\n\t\t}\n\t}",
"public ImmutableMap<String, String> getConfigurationTweak(String dbModuleName)\n {\n final DbInfo db = cluster.getNextDb();\n return ImmutableMap.of(\"ness.db.\" + dbModuleName + \".uri\", getJdbcUri(db),\n \"ness.db.\" + dbModuleName + \".ds.user\", db.user);\n }",
"public static void main(String[] args) throws IOException {\n\t\tExampleHelpers.configureLogging();\n\t\tJsonSerializationProcessor.printDocumentation();\n\n\t\tJsonSerializationProcessor jsonSerializationProcessor = new JsonSerializationProcessor();\n\t\tExampleHelpers.processEntitiesFromWikidataDump(jsonSerializationProcessor);\n\t\tjsonSerializationProcessor.close();\n\t}",
"public static void validateZip(File file) throws IOException {\n ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file));\n ZipEntry zipEntry = zipInput.getNextEntry();\n\n while (zipEntry != null) {\n zipEntry = zipInput.getNextEntry();\n }\n\n try {\n if (zipInput != null) {\n zipInput.close();\n }\n } catch (IOException e) {\n }\n }",
"public Profile add(String profileName) throws Exception {\n Profile profile = new Profile();\n int id = -1;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n Clob clobProfileName = sqlService.toClob(profileName, sqlConnection);\n\n statement = sqlConnection.prepareStatement(\n \"INSERT INTO \" + Constants.DB_TABLE_PROFILE\n + \"(\" + Constants.PROFILE_PROFILE_NAME + \") \" +\n \" VALUES (?)\", PreparedStatement.RETURN_GENERATED_KEYS\n );\n\n statement.setClob(1, clobProfileName);\n statement.executeUpdate();\n results = statement.getGeneratedKeys();\n if (results.next()) {\n id = results.getInt(1);\n } else {\n // something went wrong\n throw new Exception(\"Could not add client\");\n }\n results.close();\n statement.close();\n\n statement = sqlConnection.prepareStatement(\"INSERT INTO \" + Constants.DB_TABLE_CLIENT +\n \"(\" + Constants.CLIENT_CLIENT_UUID + \",\" + Constants.CLIENT_IS_ACTIVE + \",\"\n + Constants.CLIENT_PROFILE_ID + \") \" +\n \" VALUES (?, ?, ?)\");\n statement.setString(1, Constants.PROFILE_CLIENT_DEFAULT_ID);\n statement.setBoolean(2, false);\n statement.setInt(3, id);\n statement.executeUpdate();\n\n profile.setName(profileName);\n profile.setId(id);\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 return profile;\n }",
"public final ReadOnlyObjectProperty<LatLongBounds> boundsProperty() {\n if (bounds == null) {\n bounds = new ReadOnlyObjectWrapper<>(getBounds());\n addStateEventHandler(MapStateEventType.idle, () -> {\n bounds.set(getBounds());\n });\n }\n return bounds.getReadOnlyProperty();\n }",
"public static STSClient createSTSX509Client(Bus bus, Map<String, String> stsProps) {\r\n final STSClient stsClient = createClient(bus, stsProps);\r\n\r\n stsClient.setWsdlLocation(stsProps.get(STS_X509_WSDL_LOCATION));\r\n stsClient.setEndpointQName(new QName(stsProps.get(STS_NAMESPACE), stsProps.get(STS_X509_ENDPOINT_NAME)));\r\n\r\n return stsClient;\r\n }"
] |
A safe wrapper to destroy the given resource request. | [
"protected void destroyRequest(AsyncResourceRequest<V> resourceRequest) {\n if(resourceRequest != null) {\n try {\n // To hand control back to the owner of the\n // AsyncResourceRequest, treat \"destroy\" as an exception since\n // there is no resource to pass into useResource, and the\n // timeout has not expired.\n Exception e = new UnreachableStoreException(\"Client request was terminated while waiting in the queue.\");\n resourceRequest.handleException(e);\n } catch(Exception ex) {\n logger.error(\"Exception while destroying resource request:\", ex);\n }\n }\n }"
] | [
"public CmsJspInstanceDateBean getToInstanceDate() {\n\n if (m_instanceDate == null) {\n m_instanceDate = new CmsJspInstanceDateBean(getToDate(), m_cms.getRequestContext().getLocale());\n }\n return m_instanceDate;\n }",
"public static final String getString(InputStream is) throws IOException\n {\n int type = is.read();\n if (type != 1)\n {\n throw new IllegalArgumentException(\"Unexpected string format\");\n }\n\n Charset charset = CharsetHelper.UTF8;\n \n int length = is.read();\n if (length == 0xFF)\n {\n length = getShort(is);\n if (length == 0xFFFE)\n {\n charset = CharsetHelper.UTF16LE;\n length = (is.read() * 2);\n }\n }\n\n String result;\n if (length == 0)\n {\n result = null;\n }\n else\n {\n byte[] stringData = new byte[length]; \n is.read(stringData);\n result = new String(stringData, charset);\n }\n return result;\n }",
"public static String getXPathExpression(Node node) {\n\t\tObject xpathCache = node.getUserData(FULL_XPATH_CACHE);\n\t\tif (xpathCache != null) {\n\t\t\treturn xpathCache.toString();\n\t\t}\n\t\tNode parent = node.getParentNode();\n\n\t\tif ((parent == null) || parent.getNodeName().contains(\"#document\")) {\n\t\t\tString xPath = \"/\" + node.getNodeName() + \"[1]\";\n\t\t\tnode.setUserData(FULL_XPATH_CACHE, xPath, null);\n\t\t\treturn xPath;\n\t\t}\n\n\t\tif (node.hasAttributes() && node.getAttributes().getNamedItem(\"id\") != null) {\n\t\t\tString xPath = \"//\" + node.getNodeName() + \"[@id = '\"\n\t\t\t\t\t+ node.getAttributes().getNamedItem(\"id\").getNodeValue() + \"']\";\n\t\t\tnode.setUserData(FULL_XPATH_CACHE, xPath, null);\n\t\t\treturn xPath;\n\t\t}\n\n\t\tStringBuffer buffer = new StringBuffer();\n\n\t\tif (parent != node) {\n\t\t\tbuffer.append(getXPathExpression(parent));\n\t\t\tbuffer.append(\"/\");\n\t\t}\n\n\t\tbuffer.append(node.getNodeName());\n\n\t\tList<Node> mySiblings = getSiblings(parent, node);\n\n\t\tfor (int i = 0; i < mySiblings.size(); i++) {\n\t\t\tNode el = mySiblings.get(i);\n\n\t\t\tif (el.equals(node)) {\n\t\t\t\tbuffer.append('[').append(Integer.toString(i + 1)).append(']');\n\t\t\t\t// Found so break;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tString xPath = buffer.toString();\n\t\tnode.setUserData(FULL_XPATH_CACHE, xPath, null);\n\t\treturn xPath;\n\t}",
"private void processSchedulingProjectProperties() throws SQLException\n {\n List<Row> rows = getRows(\"select * from \" + m_schema + \"projprop where proj_id=? and prop_name='scheduling'\", m_projectID);\n if (!rows.isEmpty())\n {\n Row row = rows.get(0);\n Record record = Record.getRecord(row.getString(\"prop_value\"));\n if (record != null)\n {\n String[] keyValues = record.getValue().split(\"\\\\|\");\n for (int i = 0; i < keyValues.length - 1; ++i)\n {\n if (\"sched_calendar_on_relationship_lag\".equals(keyValues[i]))\n {\n Map<String, Object> customProperties = new HashMap<String, Object>();\n customProperties.put(\"LagCalendar\", keyValues[i + 1]);\n m_reader.getProject().getProjectProperties().setCustomProperties(customProperties);\n break;\n }\n }\n }\n }\n }",
"public static <T> void write(BufferedWriter writer, DatabaseTableConfig<T> config) throws SQLException {\n\t\ttry {\n\t\t\twriteConfig(writer, config);\n\t\t} catch (IOException e) {\n\t\t\tthrow SqlExceptionUtil.create(\"Could not write config to writer\", e);\n\t\t}\n\t}",
"public String getNotes()\n {\n String notes = (String) getCachedValue(ResourceField.NOTES);\n return (notes == null ? \"\" : notes);\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<Symmetry010Date> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<Symmetry010Date>) super.zonedDateTime(temporal);\n }",
"public static List<DomainControllerData> domainControllerDataFromByteBuffer(byte[] buffer) throws Exception {\n List<DomainControllerData> retval = new ArrayList<DomainControllerData>();\n if (buffer == null) {\n return retval;\n }\n ByteArrayInputStream in_stream = new ByteArrayInputStream(buffer);\n DataInputStream in = new DataInputStream(in_stream);\n String content = SEPARATOR;\n while (SEPARATOR.equals(content)) {\n DomainControllerData data = new DomainControllerData();\n data.readFrom(in);\n retval.add(data);\n try {\n content = readString(in);\n } catch (EOFException ex) {\n content = null;\n }\n }\n in.close();\n return retval;\n }",
"private static boolean isVariableInteger(TokenList.Token t) {\n if( t == null )\n return false;\n\n return t.getScalarType() == VariableScalar.Type.INTEGER;\n }"
] |
Sets the scale value in pixel per map unit.
@param pixelPerUnit
the scale value (pix/map unit) | [
"public void setPixelPerUnit(double pixelPerUnit) {\n\t\tif (pixelPerUnit < MINIMUM_PIXEL_PER_UNIT) {\n\t\t\tpixelPerUnit = MINIMUM_PIXEL_PER_UNIT;\n\t\t}\n\t\tif (pixelPerUnit > MAXIMUM_PIXEL_PER_UNIT) {\n\t\t\tpixelPerUnit = MAXIMUM_PIXEL_PER_UNIT;\n\t\t}\n\t\tthis.pixelPerUnit = pixelPerUnit;\n\t\tsetPixelPerUnitBased(true);\n\t\tpostConstruct();\n\t}"
] | [
"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 List<MapRow> readTableConditional(Class<? extends TableReader> readerClass) throws IOException\n {\n List<MapRow> result;\n if (DatatypeConverter.getBoolean(m_stream))\n {\n result = readTable(readerClass);\n }\n else\n {\n result = Collections.emptyList();\n }\n return result;\n }",
"private boolean matchesFingerprint(byte[] buffer, Pattern fingerprint)\n {\n return fingerprint.matcher(m_charset == null ? new String(buffer) : new String(buffer, m_charset)).matches();\n }",
"public static <X, Y> Pair<X, Y> makePair(X x, Y y) {\r\n return new Pair<X, Y>(x, y);\r\n }",
"public static String joinStrings(List<String> strings, boolean fixCase, char withChar) {\n if (strings == null || strings.size() == 0) {\n return \"\";\n }\n StringBuilder result = null;\n for (String s : strings) {\n if (fixCase) {\n s = fixCase(s);\n }\n if (result == null) {\n result = new StringBuilder(s);\n } else {\n result.append(withChar);\n result.append(s);\n }\n }\n return result.toString();\n }",
"public synchronized boolean checkWrite(TransactionImpl tx, Object obj)\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"LM.checkWrite(tx-\" + tx.getGUID() + \", \" + new Identity(obj, tx.getBroker()).toString() + \")\");\r\n LockStrategy lockStrategy = LockStrategyFactory.getStrategyFor(obj);\r\n return lockStrategy.checkWrite(tx, obj);\r\n }",
"@Override\n public void accept(IBinaryType binaryType, PackageBinding packageBinding, AccessRestriction accessRestriction) {\n if (this.options.verbose) {\n this.out.println(\n Messages.bind(Messages.compilation_loadBinary, new String(binaryType.getName())));\n//\t\t\tnew Exception(\"TRACE BINARY\").printStackTrace(System.out);\n//\t\t System.out.println();\n }\n LookupEnvironment env = packageBinding.environment;\n env.createBinaryTypeFrom(binaryType, packageBinding, accessRestriction);\n }",
"public static base_response add(nitro_service client, dnsview resource) throws Exception {\n\t\tdnsview addresource = new dnsview();\n\t\taddresource.viewname = resource.viewname;\n\t\treturn addresource.add_resource(client);\n\t}",
"public static int cudnnActivationForward(\n cudnnHandle handle, \n cudnnActivationDescriptor activationDesc, \n Pointer alpha, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor yDesc, \n Pointer y)\n {\n return checkResult(cudnnActivationForwardNative(handle, activationDesc, alpha, xDesc, x, beta, yDesc, y));\n }"
] |
Sets currency symbol.
@param symbol currency symbol | [
"public void setCurrencySymbol(String symbol)\n {\n if (symbol == null)\n {\n symbol = DEFAULT_CURRENCY_SYMBOL;\n }\n\n set(ProjectField.CURRENCY_SYMBOL, symbol);\n }"
] | [
"public static boolean isConstructorCall(Expression expression, List<String> classNames) {\r\n return expression instanceof ConstructorCallExpression && classNames.contains(expression.getType().getName());\r\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 <T extends InterconnectObject> T fromJson(String data, Class<T> clazz) throws IOException {\n return InterconnectMapper.mapper.readValue(data, clazz);\n }",
"public Filter geoSearch(String value) {\n GeopositionComparator comp = (GeopositionComparator) prop.getComparator();\n double dist = comp.getMaxDistance();\n double degrees = DistanceUtils.dist2Degrees(dist, DistanceUtils.EARTH_MEAN_RADIUS_KM * 1000.0);\n Shape circle = spatialctx.makeCircle(parsePoint(value), degrees);\n SpatialArgs args = new SpatialArgs(SpatialOperation.Intersects, circle);\n return strategy.makeFilter(args);\n }",
"public List<ChannelInfo> getChannels(String connectionName) {\n final URI uri = uriWithPath(\"./connections/\" + encodePathSegment(connectionName) + \"/channels/\");\n return Arrays.asList(this.rt.getForObject(uri, ChannelInfo[].class));\n }",
"private static String[] readArgsFile(String argsFile) throws IOException {\n final ArrayList<String> lines = new ArrayList<String>();\n final BufferedReader reader = new BufferedReader(\n new InputStreamReader(\n new FileInputStream(argsFile), \"UTF-8\"));\n try {\n String line;\n while ((line = reader.readLine()) != null) {\n line = line.trim();\n if (!line.isEmpty() && !line.startsWith(\"#\")) {\n lines.add(line);\n }\n }\n } finally {\n reader.close();\n }\n return lines.toArray(new String [lines.size()]);\n }",
"private void updateWorkTimeUnit(FastTrackColumn column)\n {\n if (m_workTimeUnit == null && isWorkColumn(column))\n {\n int value = ((DurationColumn) column).getTimeUnitValue();\n if (value != 1)\n {\n m_workTimeUnit = FastTrackUtility.getTimeUnit(value);\n }\n }\n }",
"private static String getUnexpectedTypeMessage(final Class<?> expectedType, final Object actualValue) {\n\t\tif( expectedType == null ) {\n\t\t\tthrow new NullPointerException(\"expectedType should not be null\");\n\t\t}\n\t\tString expectedClassName = expectedType.getName();\n\t\tString actualClassName = (actualValue != null) ? actualValue.getClass().getName() : \"null\";\n\t\treturn String.format(\"the input value should be of type %s but is %s\", expectedClassName, actualClassName);\n\t}",
"public static byte[] synchronizeSlaveHostController(ModelNode operation, final PathAddress address, HostFileRepository fileRepository, ContentRepository contentRepository, boolean backup, byte[] oldHash) {\n ModelNode operationContentItem = operation.get(DeploymentAttributes.CONTENT_RESOURCE_ALL.getName()).get(0);\n byte[] newHash = operationContentItem.require(CONTENT_HASH.getName()).asBytes();\n if (needRemoteContent(fileRepository, contentRepository, backup, oldHash)) { // backup DC needs to pull the content\n fileRepository.getDeploymentFiles(ModelContentReference.fromModelAddress(address, newHash));\n }\n return newHash;\n }"
] |
Remove the report directory. | [
"@Override\n protected void runUnsafe() throws Exception {\n Path reportDirectory = getReportDirectoryPath();\n Files.walkFileTree(reportDirectory, new DeleteVisitor());\n LOGGER.info(\"Report directory <{}> was successfully cleaned.\", reportDirectory);\n }"
] | [
"public static base_responses Import(nitro_service client, sslfipskey resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslfipskey Importresources[] = new sslfipskey[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tImportresources[i] = new sslfipskey();\n\t\t\t\tImportresources[i].fipskeyname = resources[i].fipskeyname;\n\t\t\t\tImportresources[i].key = resources[i].key;\n\t\t\t\tImportresources[i].inform = resources[i].inform;\n\t\t\t\tImportresources[i].wrapkeyname = resources[i].wrapkeyname;\n\t\t\t\tImportresources[i].iv = resources[i].iv;\n\t\t\t\tImportresources[i].exponent = resources[i].exponent;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, Importresources,\"Import\");\n\t\t}\n\t\treturn result;\n\t}",
"public static Integer parseInteger(String value) throws ParseException\n {\n Integer result = null;\n\n if (value.length() > 0 && value.indexOf(' ') == -1)\n {\n if (value.indexOf('.') == -1)\n {\n result = Integer.valueOf(value);\n }\n else\n {\n Number n = DatatypeConverter.parseDouble(value);\n result = Integer.valueOf(n.intValue());\n }\n }\n\n return result;\n }",
"private String getName(CommandContext ctx, boolean failInBatch) throws CommandLineException {\n final ParsedCommandLine args = ctx.getParsedCommandLine();\n final String name = this.name.getValue(args, true);\n if (name == null) {\n throw new CommandFormatException(this.name + \" is missing value.\");\n }\n if (!ctx.isBatchMode() || failInBatch) {\n if (!Util.isValidPath(ctx.getModelControllerClient(), Util.DEPLOYMENT_OVERLAY, name)) {\n throw new CommandFormatException(\"Deployment overlay \" + name + \" does not exist.\");\n }\n }\n return name;\n }",
"public static Map<String, List<String>> getResponseHeaders(String stringUrl) throws IOException {\n return getResponseHeaders(stringUrl, true);\n }",
"private static FieldType getPlaceholder(final Class<?> type, final int fieldID)\n {\n return new FieldType()\n {\n @Override public FieldTypeClass getFieldTypeClass()\n {\n return FieldTypeClass.UNKNOWN;\n }\n\n @Override public String name()\n {\n return \"UNKNOWN\";\n }\n\n @Override public int getValue()\n {\n return fieldID;\n }\n\n @Override public String getName()\n {\n return \"Unknown \" + (type == null ? \"\" : type.getSimpleName() + \"(\" + fieldID + \")\");\n }\n\n @Override public String getName(Locale locale)\n {\n return getName();\n }\n\n @Override public DataType getDataType()\n {\n return null;\n }\n\n @Override public FieldType getUnitsType()\n {\n return null;\n }\n\n @Override public String toString()\n {\n return getName();\n }\n };\n }",
"private static String makeAsciiTableCell(Object obj, int padLeft, int padRight, boolean tsv) {\r\n String result = obj.toString();\r\n if (padLeft > 0) {\r\n result = padLeft(result, padLeft);\r\n }\r\n if (padRight > 0) {\r\n result = pad(result, padRight);\r\n }\r\n if (tsv) {\r\n result = result + '\\t';\r\n }\r\n return result;\r\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 }",
"public void processAnonymousField(Properties attributes) throws XDocletException\r\n {\r\n if (!attributes.containsKey(ATTRIBUTE_NAME))\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.PARAMETER_IS_REQUIRED,\r\n new String[]{ATTRIBUTE_NAME}));\r\n }\r\n\r\n String name = attributes.getProperty(ATTRIBUTE_NAME);\r\n FieldDescriptorDef fieldDef = _curClassDef.getField(name);\r\n String attrName;\r\n\r\n if (fieldDef == null)\r\n {\r\n fieldDef = new FieldDescriptorDef(name);\r\n _curClassDef.addField(fieldDef);\r\n }\r\n fieldDef.setAnonymous();\r\n LogHelper.debug(false, OjbTagsHandler.class, \"processAnonymousField\", \" Processing anonymous field \"+fieldDef.getName());\r\n\r\n attributes.remove(ATTRIBUTE_NAME);\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n fieldDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n fieldDef.setProperty(PropertyHelper.OJB_PROPERTY_ACCESS, \"anonymous\");\r\n }",
"public static void log(String label, byte[] data)\n {\n if (LOG != null)\n {\n LOG.write(label);\n LOG.write(\": \");\n LOG.println(ByteArrayHelper.hexdump(data, true));\n LOG.flush();\n }\n }"
] |
All the indexes defined in the database. Type widening means that the returned Index objects
are limited to the name, design document and type of the index and the names of the fields.
@return a list of defined indexes with name, design document, type and field names. | [
"public List<Index<Field>> allIndexes() {\n List<Index<Field>> indexesOfAnyType = new ArrayList<Index<Field>>();\n indexesOfAnyType.addAll(listIndexType(null, ListableIndex.class));\n return indexesOfAnyType;\n }"
] | [
"public static final BigInteger printPriority(Priority priority)\n {\n int result = Priority.MEDIUM;\n\n if (priority != null)\n {\n result = priority.getValue();\n }\n\n return (BigInteger.valueOf(result));\n }",
"@SuppressWarnings(\"unchecked\")\r\n public static <E> E[] filter(E[] elems, Filter<E> filter) {\r\n List<E> filtered = new ArrayList<E>();\r\n for (E elem: elems) {\r\n if (filter.accept(elem)) {\r\n filtered.add(elem);\r\n }\r\n }\r\n return (filtered.toArray((E[]) Array.newInstance(elems.getClass().getComponentType(), filtered.size())));\r\n }",
"public VALUE get(KEY key) {\n CacheEntry<VALUE> entry;\n synchronized (this) {\n entry = values.get(key);\n }\n VALUE value;\n if (entry != null) {\n if (isExpiring) {\n long age = System.currentTimeMillis() - entry.timeCreated;\n if (age < expirationMillis) {\n value = getValue(key, entry);\n } else {\n countExpired++;\n synchronized (this) {\n values.remove(key);\n }\n value = null;\n }\n } else {\n value = getValue(key, entry);\n }\n } else {\n value = null;\n }\n if (value != null) {\n countHit++;\n } else {\n countMiss++;\n }\n return value;\n }",
"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 }",
"@SuppressWarnings(\"unchecked\")\n\tpublic <T extends Annotation> T getAnnotation(Class<T> annotationType) {\n\t\tfor (Annotation annotation : this.annotations) {\n\t\t\tif (annotation.annotationType().equals(annotationType)) {\n\t\t\t\treturn (T) annotation;\n\t\t\t}\n\t\t}\n\t\tfor (Annotation metaAnn : this.annotations) {\n\t\t\tT ann = metaAnn.annotationType().getAnnotation(annotationType);\n\t\t\tif (ann != null) {\n\t\t\t\treturn ann;\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"public void flipBit(int index)\n {\n assertValidIndex(index);\n int word = index / WORD_LENGTH;\n int offset = index % WORD_LENGTH;\n data[word] ^= (1 << offset);\n }",
"public static dnsview_binding get(nitro_service service, String viewname) throws Exception{\n\t\tdnsview_binding obj = new dnsview_binding();\n\t\tobj.set_viewname(viewname);\n\t\tdnsview_binding response = (dnsview_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static <T, C extends Comparable<? super C>> List<T> sortBy(Iterable<T> iterable,\n\t\t\tfinal Functions.Function1<? super T, C> key) {\n\t\treturn ListExtensions.sortInplaceBy(Lists.newArrayList(iterable), key);\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}"
] |
If directory doesn't exists try to create it.
@param directory given directory to check
@throws ReportGenerationException if can't create specified directory | [
"public static void checkDirectory(File directory) {\n if (!(directory.exists() || directory.mkdirs())) {\n throw new ReportGenerationException(\n String.format(\"Can't create data directory <%s>\", directory.getAbsolutePath())\n );\n }\n }"
] | [
"public static Long getSize(final File file){\n if ( file!=null && file.exists() ){\n return file.length();\n }\n return null;\n }",
"private void deliverWaveformPreviewUpdate(final int player, final WaveformPreview preview) {\n final Set<WaveformListener> listeners = getWaveformListeners();\n if (!listeners.isEmpty()) {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n final WaveformPreviewUpdate update = new WaveformPreviewUpdate(player, preview);\n for (final WaveformListener listener : listeners) {\n try {\n listener.previewChanged(update);\n\n } catch (Throwable t) {\n logger.warn(\"Problem delivering waveform preview update to listener\", t);\n }\n }\n }\n });\n }\n }",
"public CollectionRequest<Task> stories(String task) {\n \n String path = String.format(\"/tasks/%s/stories\", task);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }",
"private void getDailyDates(Calendar calendar, int frequency, List<Date> dates)\n {\n while (moreDates(calendar, dates))\n {\n dates.add(calendar.getTime());\n calendar.add(Calendar.DAY_OF_YEAR, frequency);\n }\n }",
"public ParallelTask getTaskFromInProgressMap(String jobId) {\n if (!inprogressTaskMap.containsKey(jobId))\n return null;\n return inprogressTaskMap.get(jobId);\n }",
"public AsciiTable setPaddingRightChar(Character paddingRightChar) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingRightChar(paddingRightChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"protected Boolean parseOptionalBooleanValue(final String path) {\n\n final I_CmsXmlContentValue value = m_xml.getValue(path, m_locale);\n if (value == null) {\n return null;\n } else {\n final String stringValue = value.getStringValue(null);\n try {\n final Boolean boolValue = Boolean.valueOf(stringValue);\n return boolValue;\n } catch (final NumberFormatException e) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_OPTIONAL_BOOLEAN_MISSING_1, path), e);\n return null;\n }\n }\n }",
"public void setOnKeyboardDone(final IntlPhoneInputListener listener) {\n mPhoneEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_DONE) {\n listener.done(IntlPhoneInput.this, isValid());\n }\n return false;\n }\n });\n }",
"public void bindDelete(PreparedStatement stmt, Identity oid, ClassDescriptor cld) throws SQLException\r\n {\r\n Object[] pkValues = oid.getPrimaryKeyValues();\r\n FieldDescriptor[] pkFields = cld.getPkFields();\r\n int i = 0;\r\n try\r\n {\r\n for (; i < pkValues.length; i++)\r\n {\r\n setObjectForStatement(stmt, i + 1, pkValues[i], pkFields[i].getJdbcType().getType());\r\n }\r\n }\r\n catch (SQLException e)\r\n {\r\n m_log.error(\"bindDelete failed for: \" + oid.toString() + \", while set value '\" +\r\n pkValues[i] + \"' for column \" + pkFields[i].getColumnName());\r\n throw e;\r\n }\r\n }"
] |
Finds binding for a type in the given injector and, if not found,
recurses to its parent
@param injector
the current Injector
@param type
the Class representing the type
@return A boolean flag, <code>true</code> if binding found | [
"private boolean findBinding(Injector injector, Class<?> type) {\n boolean found = false;\n for (Key<?> key : injector.getBindings().keySet()) {\n if (key.getTypeLiteral().getRawType().equals(type)) {\n found = true;\n break;\n }\n }\n if (!found && injector.getParent() != null) {\n return findBinding(injector.getParent(), type);\n }\n\n return found;\n }"
] | [
"I_CmsSerialDateServiceAsync getService() {\r\n\r\n if (SERVICE == null) {\r\n SERVICE = GWT.create(I_CmsSerialDateService.class);\r\n String serviceUrl = CmsCoreProvider.get().link(\"org.opencms.ade.contenteditor.CmsSerialDateService.gwt\");\r\n ((ServiceDefTarget)SERVICE).setServiceEntryPoint(serviceUrl);\r\n }\r\n return SERVICE;\r\n }",
"public int sum() {\n int total = 0;\n int N = getNumElements();\n for (int i = 0; i < N; i++) {\n if( data[i] )\n total += 1;\n }\n return total;\n }",
"private String getApiKey(CmsObject cms, String sitePath) throws CmsException {\n\n String res = cms.readPropertyObject(\n sitePath,\n CmsPropertyDefinition.PROPERTY_GOOGLE_API_KEY_WORKPLACE,\n true).getValue();\n\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(res)) {\n res = cms.readPropertyObject(sitePath, CmsPropertyDefinition.PROPERTY_GOOGLE_API_KEY, true).getValue();\n }\n return res;\n\n }",
"public static aaauser_intranetip_binding[] get(nitro_service service, String username) throws Exception{\n\t\taaauser_intranetip_binding obj = new aaauser_intranetip_binding();\n\t\tobj.set_username(username);\n\t\taaauser_intranetip_binding response[] = (aaauser_intranetip_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static lbvserver[] get_filtered(nitro_service service, filtervalue[] filter) throws Exception{\n\t\tlbvserver obj = new lbvserver();\n\t\toptions option = new options();\n\t\toption.set_filter(filter);\n\t\tlbvserver[] response = (lbvserver[]) obj.getfiltered(service, option);\n\t\treturn response;\n\t}",
"public static final TimeUnit parseDurationTimeUnits(BigInteger value, TimeUnit defaultValue)\n {\n TimeUnit result = defaultValue;\n\n if (value != null)\n {\n switch (value.intValue())\n {\n case 3:\n case 35:\n {\n result = TimeUnit.MINUTES;\n break;\n }\n\n case 4:\n case 36:\n {\n result = TimeUnit.ELAPSED_MINUTES;\n break;\n }\n\n case 5:\n case 37:\n {\n result = TimeUnit.HOURS;\n break;\n }\n\n case 6:\n case 38:\n {\n result = TimeUnit.ELAPSED_HOURS;\n break;\n }\n\n case 7:\n case 39:\n case 53:\n {\n result = TimeUnit.DAYS;\n break;\n }\n\n case 8:\n case 40:\n {\n result = TimeUnit.ELAPSED_DAYS;\n break;\n }\n\n case 9:\n case 41:\n {\n result = TimeUnit.WEEKS;\n break;\n }\n\n case 10:\n case 42:\n {\n result = TimeUnit.ELAPSED_WEEKS;\n break;\n }\n\n case 11:\n case 43:\n {\n result = TimeUnit.MONTHS;\n break;\n }\n\n case 12:\n case 44:\n {\n result = TimeUnit.ELAPSED_MONTHS;\n break;\n }\n\n case 19:\n case 51:\n {\n result = TimeUnit.PERCENT;\n break;\n }\n\n case 20:\n case 52:\n {\n result = TimeUnit.ELAPSED_PERCENT;\n break;\n }\n\n default:\n {\n result = PARENT_FILE.get().getProjectProperties().getDefaultDurationUnits();\n break;\n }\n }\n }\n\n return (result);\n }",
"public String readSnippet(String name) {\n\n String path = CmsStringUtil.joinPaths(\n m_context.getSetupBean().getWebAppRfsPath(),\n CmsSetupBean.FOLDER_SETUP,\n \"html\",\n name);\n try (InputStream stream = new FileInputStream(path)) {\n byte[] data = CmsFileUtil.readFully(stream, false);\n String result = new String(data, \"UTF-8\");\n return result;\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
"public SpinJsonDataFormatException unableToParseValue(String expectedType, JsonNodeType type) {\n return new SpinJsonDataFormatException(exceptionMessage(\"002\", \"Expected '{}', got '{}'\", expectedType, type.toString()));\n }",
"void close() {\n mIODevice = null;\n GVRSceneObject owner = getOwnerObject();\n if (owner.getParent() != null) {\n owner.getParent().removeChildObject(owner);\n }\n }"
] |
Extract data for a single predecessor.
@param task parent task
@param row Synchro predecessor data | [
"private void processPredecessor(Task task, MapRow row)\n {\n Task predecessor = m_taskMap.get(row.getUUID(\"PREDECESSOR_UUID\"));\n if (predecessor != null)\n {\n task.addPredecessor(predecessor, row.getRelationType(\"RELATION_TYPE\"), row.getDuration(\"LAG\"));\n }\n }"
] | [
"public static void configureProtocolHandler() {\n final String pkgs = System.getProperty(\"java.protocol.handler.pkgs\");\n String newValue = \"org.mapfish.print.url\";\n if (pkgs != null && !pkgs.contains(newValue)) {\n newValue = newValue + \"|\" + pkgs;\n } else if (pkgs != null) {\n newValue = pkgs;\n }\n System.setProperty(\"java.protocol.handler.pkgs\", newValue);\n }",
"public boolean isRunning(final ProcessorGraphNode processorGraphNode) {\n this.processorLock.lock();\n try {\n return this.runningProcessors.containsKey(processorGraphNode.getProcessor());\n } finally {\n this.processorLock.unlock();\n }\n }",
"public String getString(Integer offset)\n {\n String result = null;\n\n if (offset != null)\n {\n byte[] value = m_map.get(offset);\n if (value != null)\n {\n result = MPPUtility.getString(value, 0);\n }\n }\n\n return (result);\n }",
"public void printExtraClasses(RootDoc root) {\n\tSet<String> names = new HashSet<String>(classnames.keySet()); \n\tfor(String className: names) {\n\t ClassInfo info = getClassInfo(className, true);\n\t if (info.nodePrinted)\n\t\tcontinue;\n\t ClassDoc c = root.classNamed(className);\n\t if(c != null) {\n\t\tprintClass(c, false);\n\t\tcontinue;\n\t }\n\t // Handle missing classes:\n\t Options opt = optionProvider.getOptionsFor(className);\n\t if(opt.matchesHideExpression(className))\n\t\tcontinue;\n\t w.println(linePrefix + \"// \" + className);\n\t w.print(linePrefix + info.name + \"[label=\");\n\t externalTableStart(opt, className, classToUrl(className));\n\t innerTableStart();\n\t String qualifiedName = qualifiedName(opt, className);\n\t int startTemplate = qualifiedName.indexOf('<');\n\t int idx = qualifiedName.lastIndexOf('.', startTemplate < 0 ? qualifiedName.length() - 1 : startTemplate);\n\t if(opt.postfixPackage && idx > 0 && idx < (qualifiedName.length() - 1)) {\n\t\tString packageName = qualifiedName.substring(0, idx);\n\t\tString cn = qualifiedName.substring(idx + 1);\n\t\ttableLine(Align.CENTER, Font.CLASS.wrap(opt, escape(cn)));\n\t\ttableLine(Align.CENTER, Font.PACKAGE.wrap(opt, packageName));\n\t } else {\n\t\ttableLine(Align.CENTER, Font.CLASS.wrap(opt, escape(qualifiedName)));\n\t }\n\t innerTableEnd();\n\t externalTableEnd();\n\t if (className == null || className.length() == 0)\n\t\tw.print(\",URL=\\\"\" + classToUrl(className) + \"\\\"\");\n\t nodeProperties(opt);\n\t}\n }",
"public void recordGetAllTime(long timeNS,\n int requested,\n int returned,\n long totalValueBytes,\n long totalKeyBytes) {\n recordTime(Tracked.GET_ALL,\n timeNS,\n requested - returned,\n totalValueBytes,\n totalKeyBytes,\n requested);\n }",
"private String getIndirectionTableColName(TableAlias mnAlias, String path)\r\n {\r\n int dotIdx = path.lastIndexOf(\".\");\r\n String column = path.substring(dotIdx);\r\n return mnAlias.alias + column;\r\n }",
"public static Object tryGetSingleton(Class<?> invokerClass, App app) {\n Object singleton = app.singleton(invokerClass);\n if (null == singleton) {\n if (isGlobalOrStateless(invokerClass, new HashSet<Class>())) {\n singleton = app.getInstance(invokerClass);\n }\n }\n if (null != singleton) {\n app.registerSingleton(singleton);\n }\n return singleton;\n }",
"public double stdev() {\n double m = mean();\n\n double total = 0;\n\n final int N = getNumElements();\n if( N <= 1 )\n throw new IllegalArgumentException(\"There must be more than one element to compute stdev\");\n\n\n for( int i = 0; i < N; i++ ) {\n double x = get(i);\n\n total += (x - m)*(x - m);\n }\n\n total /= (N-1);\n\n return Math.sqrt(total);\n }",
"public double[] calculateDrift(ArrayList<T> tracks){\n\t\tdouble[] result = new double[3];\n\t\t\n\t\tdouble sumX =0;\n\t\tdouble sumY = 0;\n\t\tdouble sumZ = 0;\n\t\tint N=0;\n\t\tfor(int i = 0; i < tracks.size(); i++){\n\t\t\tT t = tracks.get(i);\n\t\t\tTrajectoryValidIndexTimelagIterator it = new TrajectoryValidIndexTimelagIterator(t,1);\n\t\n\t\t\t//for(int j = 1; j < t.size(); j++){\n\t\t\twhile(it.hasNext()) {\n\t\t\t\tint j = it.next();\n\t\t\t\tsumX += t.get(j+1).x - t.get(j).x;\n\t\t\t\tsumY += t.get(j+1).y - t.get(j).y;\n\t\t\t\tsumZ += t.get(j+1).z - t.get(j).z;\n\t\t\t\tN++;\n\t\t\t}\n\t\t}\n\t\tresult[0] = sumX/N;\n\t\tresult[1] = sumY/N;\n\t\tresult[2] = sumZ/N;\n\t\treturn result;\n\t}"
] |
Returns a row matrix which contains all the elements in A which are flagged as true in 'marked'
@param A Input matrix
@param marked Input matrix marking elements in A
@param output Storage for output row vector. Can be null. Will be reshaped.
@return Row vector with marked elements | [
"public static DMatrixRMaj elements(DMatrixRMaj A , BMatrixRMaj marked , DMatrixRMaj output ) {\n if( A.numRows != marked.numRows || A.numCols != marked.numCols )\n throw new MatrixDimensionException(\"Input matrices must have the same shape\");\n if( output == null )\n output = new DMatrixRMaj(1,1);\n\n output.reshape(countTrue(marked),1);\n\n int N = A.getNumElements();\n\n int index = 0;\n for (int i = 0; i < N; i++) {\n if( marked.data[i] ) {\n output.data[index++] = A.data[i];\n }\n }\n\n return output;\n }"
] | [
"protected FluentModelTImpl find(String key) {\n for (Map.Entry<String, FluentModelTImpl> entry : this.childCollection.entrySet()) {\n if (entry.getKey().equalsIgnoreCase(key)) {\n return entry.getValue();\n }\n }\n return null;\n }",
"public static Boolean parseBoolean(String value) throws ParseException\n {\n Boolean result = null;\n Integer number = parseInteger(value);\n if (number != null)\n {\n result = number.intValue() == 0 ? Boolean.FALSE : Boolean.TRUE;\n }\n\n return result;\n }",
"@SuppressWarnings(\"unchecked\")\n public <T extends GVRComponent> ArrayList<T> getAllComponents(long type) {\n ArrayList<T> list = new ArrayList<T>();\n GVRComponent component = getComponent(type);\n if (component != null)\n list.add((T) component);\n for (GVRSceneObject child : mChildren) {\n ArrayList<T> temp = child.getAllComponents(type);\n list.addAll(temp);\n }\n return list;\n }",
"public static authenticationvserver_authenticationradiuspolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationvserver_authenticationradiuspolicy_binding obj = new authenticationvserver_authenticationradiuspolicy_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationvserver_authenticationradiuspolicy_binding response[] = (authenticationvserver_authenticationradiuspolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"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 }",
"private ProjectFile read() throws Exception\n {\n m_project = new ProjectFile();\n m_eventManager = m_project.getEventManager();\n\n ProjectConfig config = m_project.getProjectConfig();\n config.setAutoCalendarUniqueID(false);\n config.setAutoTaskUniqueID(false);\n config.setAutoResourceUniqueID(false);\n\n m_project.getProjectProperties().setFileApplication(\"Merlin\");\n m_project.getProjectProperties().setFileType(\"SQLITE\");\n\n m_eventManager.addProjectListeners(m_projectListeners);\n\n populateEntityMap();\n processProject();\n processCalendars();\n processResources();\n processTasks();\n processAssignments();\n processDependencies();\n\n return m_project;\n }",
"private static Dimension adaptTileDimensions(\n final Dimension pixels, final int maxWidth, final int maxHeight) {\n return new Dimension(adaptTileDimension(pixels.width, maxWidth),\n adaptTileDimension(pixels.height, maxHeight));\n }",
"protected Boolean parseOptionalBooleanValue(final String path) {\n\n final I_CmsXmlContentValue value = m_xml.getValue(path, m_locale);\n if (value == null) {\n return null;\n } else {\n final String stringValue = value.getStringValue(null);\n try {\n final Boolean boolValue = Boolean.valueOf(stringValue);\n return boolValue;\n } catch (final NumberFormatException e) {\n LOG.info(Messages.get().getBundle().key(Messages.LOG_OPTIONAL_BOOLEAN_MISSING_1, path), e);\n return null;\n }\n }\n }",
"public CollectionRequest<ProjectStatus> findByProject(String project) {\n\n String path = String.format(\"/projects/%s/project_statuses\", project);\n return new CollectionRequest<ProjectStatus>(this, ProjectStatus.class, path, \"GET\");\n }"
] |
Get a list of referring domains for a collection.
@param date
(Required) Stats will be returned for this date. A day according to Flickr Stats starts at midnight GMT for all users, and timestamps will
automatically be rounded down to the start of the day.
@param collectionId
(Optional) The id of the collection to get stats for. If not provided, stats for all collections will be returned.
@param perPage
(Optional) Number of domains to return per page. If this argument is omitted, it defaults to 25. The maximum allowed value is 100.
@param page
(Optional) The page of results to return. If this argument is omitted, it defaults to 1.
@see "http://www.flickr.com/services/api/flickr.stats.getCollectionDomains.html" | [
"public DomainList getCollectionDomains(Date date, String collectionId, int perPage, int page) throws FlickrException {\n return getDomains(METHOD_GET_COLLECTION_DOMAINS, \"collection_id\", collectionId, date, perPage, page);\n }"
] | [
"public Metadata createMetadata(String templateName, String scope, Metadata metadata) {\n URL url = METADATA_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID(), scope, templateName);\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"POST\");\n request.addHeader(\"Content-Type\", \"application/json\");\n request.setBody(metadata.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n return new Metadata(JsonObject.readFrom(response.getJSON()));\n }",
"public static boolean lower( double[]T , int indexT , int n ) {\n double el_ii;\n double div_el_ii=0;\n\n for( int i = 0; i < n; i++ ) {\n for( int j = i; j < n; j++ ) {\n double sum = T[ indexT + j*n+i];\n\n // todo optimize\n for( int k = 0; k < i; k++ ) {\n sum -= T[ indexT + i*n+k] * T[ indexT + j*n+k];\n }\n\n if( i == j ) {\n // is it positive-definite?\n if( sum <= 0.0 )\n return false;\n\n el_ii = Math.sqrt(sum);\n T[ indexT + i*n+i] = el_ii;\n div_el_ii = 1.0/el_ii;\n } else {\n T[ indexT + j*n+i] = sum*div_el_ii;\n }\n }\n }\n\n return true;\n }",
"protected boolean computeOffset(CacheDataSet cache) {\n // offset computation: update offset for all items in the cache\n float startDataOffset = getStartingOffset((cache.getTotalSizeWithPadding()));\n float layoutOffset = getLayoutOffset();\n\n boolean inBounds = startDataOffset < -layoutOffset;\n\n for (int pos = 0; pos < cache.count(); ++pos) {\n int id = cache.getId(pos);\n if (id != -1) {\n float endDataOffset = cache.setDataAfter(id, startDataOffset);\n inBounds = inBounds &&\n endDataOffset > layoutOffset &&\n startDataOffset < -layoutOffset;\n startDataOffset = endDataOffset;\n Log.d(LAYOUT, TAG, \"computeOffset [%d] = %f\" , id, cache.getDataOffset(id));\n }\n }\n\n return inBounds;\n }",
"public EventBus emitSync(EventObject event, Object... args) {\n return _emitWithOnceBus(eventContextSync(event, args));\n }",
"protected void setBeanDeploymentArchivesAccessibility() {\n for (WeldBeanDeploymentArchive beanDeploymentArchive : beanDeploymentArchives) {\n Set<WeldBeanDeploymentArchive> accessibleArchives = new HashSet<>();\n for (WeldBeanDeploymentArchive candidate : beanDeploymentArchives) {\n if (candidate.equals(beanDeploymentArchive)) {\n continue;\n }\n accessibleArchives.add(candidate);\n }\n beanDeploymentArchive.setAccessibleBeanDeploymentArchives(accessibleArchives);\n }\n }",
"private void checkOrMarkPrivateAccess(Expression source, MethodNode mn) {\n if (mn==null) {\n return;\n }\n ClassNode declaringClass = mn.getDeclaringClass();\n ClassNode enclosingClassNode = typeCheckingContext.getEnclosingClassNode();\n if (declaringClass != enclosingClassNode || typeCheckingContext.getEnclosingClosure() != null) {\n int mods = mn.getModifiers();\n boolean sameModule = declaringClass.getModule() == enclosingClassNode.getModule();\n String packageName = declaringClass.getPackageName();\n if (packageName==null) {\n packageName = \"\";\n }\n if ((Modifier.isPrivate(mods) && sameModule)\n || (Modifier.isProtected(mods) && !packageName.equals(enclosingClassNode.getPackageName()))) {\n addPrivateFieldOrMethodAccess(source, sameModule? declaringClass : enclosingClassNode, StaticTypesMarker.PV_METHODS_ACCESS, mn);\n }\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 }",
"public boolean load()\r\n {\r\n \t_load();\r\n \tjava.util.Iterator it = this.alChildren.iterator();\r\n \twhile (it.hasNext())\r\n \t{\r\n \t\tObject o = it.next();\r\n \t\tif (o instanceof OjbMetaTreeNode) ((OjbMetaTreeNode)o).load();\r\n \t}\r\n \treturn true;\r\n }",
"private void initModeSwitch(final EditMode current) {\n\n FormLayout modes = new FormLayout();\n modes.setHeight(\"100%\");\n modes.setDefaultComponentAlignment(Alignment.MIDDLE_LEFT);\n\n m_modeSelect = new ComboBox();\n m_modeSelect.setCaption(m_messages.key(Messages.GUI_VIEW_SWITCHER_LABEL_0));\n\n // add Modes\n m_modeSelect.addItem(CmsMessageBundleEditorTypes.EditMode.DEFAULT);\n m_modeSelect.setItemCaption(\n CmsMessageBundleEditorTypes.EditMode.DEFAULT,\n m_messages.key(Messages.GUI_VIEW_SWITCHER_EDITMODE_DEFAULT_0));\n m_modeSelect.addItem(CmsMessageBundleEditorTypes.EditMode.MASTER);\n m_modeSelect.setItemCaption(\n CmsMessageBundleEditorTypes.EditMode.MASTER,\n m_messages.key(Messages.GUI_VIEW_SWITCHER_EDITMODE_MASTER_0));\n\n // set current mode as selected\n m_modeSelect.setValue(current);\n\n m_modeSelect.setNewItemsAllowed(false);\n m_modeSelect.setTextInputAllowed(false);\n m_modeSelect.setNullSelectionAllowed(false);\n\n m_modeSelect.addValueChangeListener(new ValueChangeListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void valueChange(ValueChangeEvent event) {\n\n m_listener.handleModeChange((EditMode)event.getProperty().getValue());\n\n }\n });\n\n modes.addComponent(m_modeSelect);\n m_modeSwitch = modes;\n }"
] |
Copy a single named resource from the classpath to the output directory.
@param outputDirectory The destination directory for the copied resource.
@param resourceName The filename of the resource.
@param targetFileName The name of the file created in {@literal outputDirectory}.
@throws IOException If the resource cannot be copied. | [
"protected void copyClasspathResource(File outputDirectory,\n String resourceName,\n String targetFileName) throws IOException\n {\n String resourcePath = classpathPrefix + resourceName;\n InputStream resourceStream = getClass().getClassLoader().getResourceAsStream(resourcePath);\n copyStream(outputDirectory, resourceStream, targetFileName);\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 }",
"private void processTasks() throws IOException\n {\n TaskReader reader = new TaskReader(m_data.getTableData(\"Tasks\"));\n reader.read();\n for (MapRow row : reader.getRows())\n {\n processTask(m_project, row);\n }\n updateDates();\n }",
"public AT_Row setPaddingLeftChar(Character paddingLeftChar) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingLeftChar(paddingLeftChar);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public static final TimeUnit getTimeUnit(int value)\n {\n TimeUnit result = null;\n\n switch (value)\n {\n case 1:\n {\n // Appears to mean \"use the document format\"\n result = TimeUnit.ELAPSED_DAYS;\n break;\n }\n\n case 2:\n {\n result = TimeUnit.HOURS;\n break;\n }\n\n case 4:\n {\n result = TimeUnit.DAYS;\n break;\n }\n\n case 6:\n {\n result = TimeUnit.WEEKS;\n break;\n }\n\n case 8:\n case 10:\n {\n result = TimeUnit.MONTHS;\n break;\n }\n\n case 12:\n {\n result = TimeUnit.YEARS;\n break;\n }\n\n default:\n {\n break;\n }\n }\n\n return result;\n }",
"public Rectangle toRelative(Rectangle rect) {\n\t\treturn new Rectangle(rect.getLeft() - origX, rect.getBottom() - origY, rect.getRight() - origX, rect.getTop()\n\t\t\t\t- origY);\n\t}",
"public static <T_Result, T_Source> List<T_Result> map(Collection<T_Source> source,\n Mapper<T_Result, T_Source> mapper) {\n List<T_Result> result = new LinkedList<T_Result>();\n for (T_Source element : source) {\n result.add(mapper.map(element));\n }\n return result;\n }",
"private String toSQLClause(FieldCriteria c, ClassDescriptor cld)\r\n {\r\n String colName = toSqlClause(c.getAttribute(), cld);\r\n return colName + c.getClause() + c.getValue();\r\n }",
"public synchronized boolean acquireRebalancingPermit(int nodeId) {\n boolean added = rebalancePermits.add(nodeId);\n logger.info(\"Acquiring rebalancing permit for node id \" + nodeId + \", returned: \" + added);\n\n return added;\n }",
"public static <T extends Publisher> T getPublisher(AbstractProject<?, ?> project, Class<T> type) {\n // Search for a publisher of the given type in the project and return it if found:\n T publisher = new PublisherFindImpl<T>().find(project, type);\n if (publisher != null) {\n return publisher;\n }\n // If not found, the publisher might be wrapped by a \"Flexible Publish\" publisher. The below searches for it inside the\n // Flexible Publisher:\n publisher = new PublisherFlexible<T>().find(project, type);\n return publisher;\n }"
] |
Returns a flag, indicating if the current event is a multi-day event.
The method is only called if the single event has an explicitely set end date
or an explicitely changed whole day option.
@return a flag, indicating if the current event takes lasts over more than one day. | [
"private boolean isSingleMultiDay() {\n\n long duration = getEnd().getTime() - getStart().getTime();\n if (duration > I_CmsSerialDateValue.DAY_IN_MILLIS) {\n return true;\n }\n if (isWholeDay() && (duration <= I_CmsSerialDateValue.DAY_IN_MILLIS)) {\n return false;\n }\n Calendar start = new GregorianCalendar();\n start.setTime(getStart());\n Calendar end = new GregorianCalendar();\n end.setTime(getEnd());\n if (start.get(Calendar.DAY_OF_MONTH) == end.get(Calendar.DAY_OF_MONTH)) {\n return false;\n }\n return true;\n\n }"
] | [
"private void readTasks(Document cdp)\n {\n //\n // Sort the projects into the correct order\n //\n List<Project> projects = new ArrayList<Project>(cdp.getProjects().getProject());\n final AlphanumComparator comparator = new AlphanumComparator();\n\n Collections.sort(projects, new Comparator<Project>()\n {\n @Override public int compare(Project o1, Project o2)\n {\n return comparator.compare(o1.getOutlineNumber(), o2.getOutlineNumber());\n }\n });\n\n for (Project project : cdp.getProjects().getProject())\n {\n readProject(project);\n }\n }",
"public List<NodeInfo> getNodes() {\n final URI uri = uriWithPath(\"./nodes/\");\n return Arrays.asList(this.rt.getForObject(uri, NodeInfo[].class));\n }",
"protected void putResponse(JSONObject json,\n String param,\n Object value) {\n try {\n json.put(param,\n value);\n } catch (JSONException e) {\n logger.error(\"json write error\",\n e);\n }\n }",
"public static Date getTimestampFromLong(long timestamp)\n {\n TimeZone tz = TimeZone.getDefault();\n Date result = new Date(timestamp - tz.getRawOffset());\n\n if (tz.inDaylightTime(result) == true)\n {\n int savings;\n\n if (HAS_DST_SAVINGS == true)\n {\n savings = tz.getDSTSavings();\n }\n else\n {\n savings = DEFAULT_DST_SAVINGS;\n }\n\n result = new Date(result.getTime() - savings);\n }\n return (result);\n }",
"protected boolean isStoredProcedure(String sql)\r\n {\r\n /*\r\n Stored procedures start with\r\n {?= call <procedure-name>[<arg1>,<arg2>, ...]}\r\n or\r\n {call <procedure-name>[<arg1>,<arg2>, ...]}\r\n but also statements with white space like\r\n { ?= call <procedure-name>[<arg1>,<arg2>, ...]}\r\n are possible.\r\n */\r\n int k = 0, i = 0;\r\n char c;\r\n while(k < 3 && i < sql.length())\r\n {\r\n c = sql.charAt(i);\r\n if(c != ' ')\r\n {\r\n switch (k)\r\n {\r\n case 0:\r\n if(c != '{') return false;\r\n break;\r\n case 1:\r\n if(c != '?' && c != 'c') return false;\r\n break;\r\n case 2:\r\n if(c != '=' && c != 'a') return false;\r\n break;\r\n }\r\n k++;\r\n }\r\n i++;\r\n }\r\n return true;\r\n }",
"public INode getLastCompleteNodeByOffset(INode node, int offsetPosition, int completionOffset) {\n\t\treturn internalGetLastCompleteNodeByOffset(node.getRootNode(), offsetPosition);\n\t}",
"public boolean isBitwiseOrCompatibleWithRange(int maskValue, Integer segmentPrefixLength) throws PrefixLenException {\r\n\t\treturn super.isBitwiseOrCompatibleWithRange(maskValue, segmentPrefixLength, getNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets());\r\n\t}",
"public static <T> Observable<T> delayedEmitAsync(T event, int milliseconds) {\n return delayProvider.delayedEmitAsync(event, milliseconds);\n }",
"private void getMultipleValues(Method method, Object object, Map<String, String> map)\n {\n try\n {\n int index = 1;\n while (true)\n {\n Object value = filterValue(method.invoke(object, Integer.valueOf(index)));\n if (value != null)\n {\n map.put(getPropertyName(method, index), String.valueOf(value));\n }\n ++index;\n }\n }\n catch (Exception ex)\n {\n // Reached the end of the valid indexes\n }\n }"
] |
Read in lines and execute them.
@param reader the reader from which to get the groovy source to exec
@param out the outputstream to use
@throws java.io.IOException if something goes wrong | [
"protected void runStatements(Reader reader, PrintStream out)\n throws IOException {\n log.debug(\"runStatements()\");\n StringBuilder txt = new StringBuilder();\n String line = \"\";\n BufferedReader in = new BufferedReader(reader);\n\n while ((line = in.readLine()) != null) {\n line = getProject().replaceProperties(line);\n if (line.indexOf(\"--\") >= 0) {\n txt.append(\"\\n\");\n }\n }\n // Catch any statements not followed by ;\n if (!txt.toString().equals(\"\")) {\n execGroovy(txt.toString(), out);\n }\n }"
] | [
"public void close() throws IOException {\n for (CloseableHttpClient c : cachedClients.values()) {\n c.close();\n }\n cachedClients.clear();\n }",
"public void init( double diag[] ,\n double off[],\n int numCols ) {\n reset(numCols);\n\n this.diag = diag;\n this.off = off;\n }",
"public synchronized void stop() {\r\n\r\n if (m_thread != null) {\r\n long timeBeforeShutdownWasCalled = System.currentTimeMillis();\r\n JLANServer.shutdownServer(new String[] {});\r\n while (m_thread.isAlive()\r\n && ((System.currentTimeMillis() - timeBeforeShutdownWasCalled) < MAX_SHUTDOWN_WAIT_MILLIS)) {\r\n try {\r\n Thread.sleep(500);\r\n } catch (InterruptedException e) {\r\n // ignore\r\n }\r\n }\r\n }\r\n\r\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 static void checkPreconditions(List<String> requiredSubStrings) {\n\t\tif( requiredSubStrings == null ) {\n\t\t\tthrow new NullPointerException(\"requiredSubStrings List should not be null\");\n\t\t} else if( requiredSubStrings.isEmpty() ) {\n\t\t\tthrow new IllegalArgumentException(\"requiredSubStrings List should not be empty\");\n\t\t}\n\t}",
"public Optional<Project> findProject(String name) throws IllegalArgumentException {\n if (name == null || name.isEmpty()) {\n throw new IllegalArgumentException(\"Project name cannot be empty\");\n }\n return getProject(name);\n }",
"@Nonnull\n public String getBody() {\n if (body == null) {\n return storage == null ? DEFAULT_BODY : DEFAULT_BODY_STORAGE;\n } else {\n return body;\n }\n }",
"private static String clearPath(String path) {\n try {\n ExpressionBaseState state = new ExpressionBaseState(\"EXPR\", true, false);\n if (Util.isWindows()) {\n // to not require escaping FS name separator\n state.setDefaultHandler(WordCharacterHandler.IGNORE_LB_ESCAPE_OFF);\n } else {\n state.setDefaultHandler(WordCharacterHandler.IGNORE_LB_ESCAPE_ON);\n }\n // Remove escaping characters\n path = ArgumentWithValue.resolveValue(path, state);\n } catch (CommandFormatException ex) {\n // XXX OK, continue translation\n }\n // Remove quote to retrieve candidates.\n if (path.startsWith(\"\\\"\")) {\n path = path.substring(1);\n }\n // Could be an escaped \" character. We don't take into account this corner case.\n // concider it the end of the quoted part.\n if (path.endsWith(\"\\\"\")) {\n path = path.substring(0, path.length() - 1);\n }\n return path;\n }",
"static boolean isOnClasspath(String className) {\n boolean isOnClassPath = true;\n try {\n Class.forName(className);\n } catch (ClassNotFoundException exception) {\n isOnClassPath = false;\n }\n return isOnClassPath;\n }"
] |
Used by FreeStyle Maven jobs only | [
"@Override\n public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener)\n throws InterruptedException, IOException {\n listener.getLogger().println(\"Jenkins Artifactory Plugin version: \" + ActionableHelper.getArtifactoryPluginVersion());\n EnvVars env = build.getEnvironment(listener);\n FilePath workDir = build.getModuleRoot();\n FilePath ws = build.getWorkspace();\n FilePath mavenHome = getMavenHome(listener, env, launcher);\n\n if (!mavenHome.exists()) {\n listener.error(\"Couldn't find Maven home: \" + mavenHome.getRemote());\n throw new Run.RunnerAbortedException();\n }\n ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env, launcher, mavenHome, ws, ws);\n String[] cmds = cmdLine.toCommandArray();\n return RunMaven(build, launcher, listener, env, workDir, cmds);\n }"
] | [
"public InsertBuilder set(String column, String value) {\n columns.add(column);\n values.add(value);\n return this;\n }",
"public void setRequestType(int pathId, Integer requestType) {\n if (requestType == null) {\n requestType = Constants.REQUEST_TYPE_GET;\n }\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_PATH +\n \" SET \" + Constants.PATH_PROFILE_REQUEST_TYPE + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setInt(1, requestType);\n statement.setInt(2, pathId);\n statement.executeUpdate();\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 static void addToString(\n SourceBuilder code,\n Datatype datatype,\n Map<Property, PropertyCodeGenerator> generatorsByProperty,\n boolean forPartial) {\n String typename = (forPartial ? \"partial \" : \"\") + datatype.getType().getSimpleName();\n Predicate<PropertyCodeGenerator> isOptional = generator -> {\n Initially initially = generator.initialState();\n return (initially == Initially.OPTIONAL || (initially == Initially.REQUIRED && forPartial));\n };\n boolean anyOptional = generatorsByProperty.values().stream().anyMatch(isOptional);\n boolean allOptional = generatorsByProperty.values().stream().allMatch(isOptional)\n && !generatorsByProperty.isEmpty();\n\n code.addLine(\"\")\n .addLine(\"@%s\", Override.class)\n .addLine(\"public %s toString() {\", String.class);\n if (allOptional) {\n bodyWithBuilderAndSeparator(code, datatype, generatorsByProperty, typename);\n } else if (anyOptional) {\n bodyWithBuilder(code, datatype, generatorsByProperty, typename, isOptional);\n } else {\n bodyWithConcatenation(code, generatorsByProperty, typename);\n }\n code.addLine(\"}\");\n }",
"public void copyNodeMetaData(ASTNode other) {\n if (other.metaDataMap == null) {\n return;\n }\n if (metaDataMap == null) {\n metaDataMap = new ListHashMap();\n }\n metaDataMap.putAll(other.metaDataMap);\n }",
"public static ntpserver[] get(nitro_service service) throws Exception{\n\t\tntpserver obj = new ntpserver();\n\t\tntpserver[] response = (ntpserver[])obj.get_resources(service);\n\t\treturn response;\n\t}",
"public ManagementModelNode getSelectedNode() {\n if (tree.getSelectionPath() == null) return null;\n return (ManagementModelNode)tree.getSelectionPath().getLastPathComponent();\n }",
"public AT_Row setTargetTranslator(TargetTranslator targetTranslator) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setTargetTranslator(targetTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"public static sslfipskey[] get(nitro_service service, String fipskeyname[]) throws Exception{\n\t\tif (fipskeyname !=null && fipskeyname.length>0) {\n\t\t\tsslfipskey response[] = new sslfipskey[fipskeyname.length];\n\t\t\tsslfipskey obj[] = new sslfipskey[fipskeyname.length];\n\t\t\tfor (int i=0;i<fipskeyname.length;i++) {\n\t\t\t\tobj[i] = new sslfipskey();\n\t\t\t\tobj[i].set_fipskeyname(fipskeyname[i]);\n\t\t\t\tresponse[i] = (sslfipskey) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"protected List<BoxAPIResponse> parseResponse(BoxJSONResponse batchResponse) {\n JsonObject responseJSON = JsonObject.readFrom(batchResponse.getJSON());\n List<BoxAPIResponse> responses = new ArrayList<BoxAPIResponse>();\n Iterator<JsonValue> responseIterator = responseJSON.get(\"responses\").asArray().iterator();\n while (responseIterator.hasNext()) {\n JsonObject jsonResponse = responseIterator.next().asObject();\n BoxAPIResponse response = null;\n\n //Gather headers\n Map<String, String> responseHeaders = new HashMap<String, String>();\n\n if (jsonResponse.get(\"headers\") != null) {\n JsonObject batchResponseHeadersObject = jsonResponse.get(\"headers\").asObject();\n for (JsonObject.Member member : batchResponseHeadersObject) {\n String headerName = member.getName();\n String headerValue = member.getValue().asString();\n responseHeaders.put(headerName, headerValue);\n }\n }\n\n // Construct a BoxAPIResponse when response is null, or a BoxJSONResponse when there's a response\n // (not anticipating any other response as per current APIs.\n // Ideally we should do it based on response header)\n if (jsonResponse.get(\"response\") == null || jsonResponse.get(\"response\").isNull()) {\n response =\n new BoxAPIResponse(jsonResponse.get(\"status\").asInt(), responseHeaders);\n } else {\n response =\n new BoxJSONResponse(jsonResponse.get(\"status\").asInt(), responseHeaders,\n jsonResponse.get(\"response\").asObject());\n }\n responses.add(response);\n }\n return responses;\n }"
] |
Forces removal of one or several faceted attributes for the next queries.
@param attributes one or more attribute names.
@return this {@link Searcher} for chaining. | [
"@SuppressWarnings({\"WeakerAccess\", \"unused\"}) // For library users\n public Searcher deleteFacet(String... attributes) {\n for (String attribute : attributes) {\n facetRequestCount.put(attribute, 0);\n facets.remove(attribute);\n }\n rebuildQueryFacets();\n return this;\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}",
"public String processIndexDescriptor(Properties attributes) throws XDocletException\r\n {\r\n String name = attributes.getProperty(ATTRIBUTE_NAME);\r\n IndexDescriptorDef indexDef = _curClassDef.getIndexDescriptor(name);\r\n String attrName;\r\n \r\n if (indexDef == null)\r\n { \r\n indexDef = new IndexDescriptorDef(name);\r\n _curClassDef.addIndexDescriptor(indexDef);\r\n }\r\n\r\n if ((indexDef.getName() == null) || (indexDef.getName().length() == 0))\r\n {\r\n throw new XDocletException(Translator.getString(XDocletModulesOjbMessages.class,\r\n XDocletModulesOjbMessages.INDEX_NAME_MISSING,\r\n new String[]{_curClassDef.getName()}));\r\n }\r\n attributes.remove(ATTRIBUTE_NAME);\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n indexDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n return \"\";\r\n }",
"public static Map<String, String> getContentMap(File file, String separator) throws IOException {\n List<String> content = getContentLines(file);\n Map<String, String> map = new LinkedHashMap<String, String>();\n \n for (String line : content) {\n String[] spl = line.split(separator);\n if (line.trim().length() > 0) {\n map.put(spl[0], (spl.length > 1 ? spl[1] : \"\"));\n }\n }\n \n return map;\n }",
"public static BsonDocument copyOfDocument(final BsonDocument document) {\n final BsonDocument newDocument = new BsonDocument();\n for (final Map.Entry<String, BsonValue> kv : document.entrySet()) {\n newDocument.put(kv.getKey(), kv.getValue());\n }\n return newDocument;\n }",
"public static double StdDev( int[] values, double mean ){\n double stddev = 0;\n double diff;\n int hits;\n int total = 0;\n\n // for all values\n for ( int i = 0, n = values.length; i < n; i++ )\n {\n hits = values[i];\n diff = (double) i - mean;\n // accumulate std.dev.\n stddev += diff * diff * hits;\n // accumalate total\n total += hits;\n }\n\n return ( total == 0 ) ? 0 : Math.sqrt( stddev / (total - 1) );\n }",
"public double getValueWithGivenYield(double evaluationTime, double rate, AnalyticModel model) {\n\t\tDiscountCurve referenceCurve = DiscountCurveInterpolation.createDiscountCurveFromDiscountFactors(\"referenceCurve\", new double[] {0.0, 1.0}, new double[] {1.0, 1.0});\n\t\treturn getValueWithGivenSpreadOverCurve(evaluationTime, referenceCurve, rate, model);\n\t}",
"private static Iterable<String> splitAndOmitEmpty(final String str, final char splitChar) {\n return new Iterable<String>() {\n @Override\n public Iterator<String> iterator() {\n return new Iterator<String>() {\n\n int startIdx = 0;\n String next = null;\n\n @Override\n public boolean hasNext() {\n while (next == null && startIdx < str.length()) {\n int idx = str.indexOf(splitChar, startIdx);\n if (idx == startIdx) {\n // Omit empty string\n startIdx++;\n continue;\n }\n if (idx >= 0) {\n // Found the next part\n next = str.substring(startIdx, idx);\n startIdx = idx;\n } else {\n // The last part\n if (startIdx < str.length()) {\n next = str.substring(startIdx);\n startIdx = str.length();\n }\n break;\n }\n }\n return next != null;\n }\n\n @Override\n public String next() {\n if (hasNext()) {\n String next = this.next;\n this.next = null;\n return next;\n }\n throw new NoSuchElementException(\"No more element\");\n }\n\n @Override\n public void remove() {\n throw new UnsupportedOperationException(\"Remove not supported\");\n }\n };\n }\n };\n }",
"public void addImportedPackages(Set<String> importedPackages) {\n\t\taddImportedPackages(importedPackages.toArray(new String[importedPackages.size()]));\n\t}",
"private float newRandomIndividualParticleRadius(@NonNull final SceneConfiguration scene) {\n return scene.getParticleRadiusMin() == scene.getParticleRadiusMax() ?\n scene.getParticleRadiusMin() : scene.getParticleRadiusMin() + (random.nextInt(\n (int) ((scene.getParticleRadiusMax() - scene.getParticleRadiusMin()) * 100f)))\n / 100f;\n }"
] |
Validates a favorite entry.
<p>If the favorite entry references a resource or project that can't be read, this will return false.
@param entry the favorite entry
@return the | [
"private boolean validate(CmsFavoriteEntry entry) {\n\n try {\n String siteRoot = entry.getSiteRoot();\n if (!m_okSiteRoots.contains(siteRoot)) {\n m_rootCms.readResource(siteRoot);\n m_okSiteRoots.add(siteRoot);\n }\n CmsUUID project = entry.getProjectId();\n if (!m_okProjects.contains(project)) {\n m_cms.readProject(project);\n m_okProjects.add(project);\n }\n for (CmsUUID id : Arrays.asList(entry.getDetailId(), entry.getStructureId())) {\n if ((id != null) && !m_okStructureIds.contains(id)) {\n m_cms.readResource(id, CmsResourceFilter.IGNORE_EXPIRATION.addRequireVisible());\n m_okStructureIds.add(id);\n }\n }\n return true;\n\n } catch (Exception e) {\n LOG.info(\"Favorite entry validation failed: \" + e.getLocalizedMessage(), e);\n return false;\n }\n\n }"
] | [
"public void fire(StepStartedEvent event) {\n Step step = new Step();\n event.process(step);\n stepStorage.put(step);\n\n notifier.fire(event);\n }",
"private boolean findBinding(Injector injector, Class<?> type) {\n boolean found = false;\n for (Key<?> key : injector.getBindings().keySet()) {\n if (key.getTypeLiteral().getRawType().equals(type)) {\n found = true;\n break;\n }\n }\n if (!found && injector.getParent() != null) {\n return findBinding(injector.getParent(), type);\n }\n\n return found;\n }",
"public void set(Object receiver, String fieldName, /* @Nullable */ Object value) throws SecurityException, NoSuchFieldException, IllegalArgumentException, IllegalAccessException {\n\t\tPreconditions.checkNotNull(receiver,\"receiver\");\n\t\tPreconditions.checkNotNull(fieldName,\"fieldName\");\n\t\tClass<? extends Object> clazz = receiver.getClass();\n\t\tField f = getDeclaredField(clazz, fieldName);\n\t\tif (!f.isAccessible())\n\t\t\tf.setAccessible(true);\n\t\tf.set(receiver, value);\n\t}",
"public static base_response reset(nitro_service client) throws Exception {\n\t\tappfwlearningdata resetresource = new appfwlearningdata();\n\t\treturn resetresource.perform_operation(client,\"reset\");\n\t}",
"public static CmsPair<String, Map<String, String>> parseEmbeddedGalleryOptions(String configuration) {\n\n final Map<String, String> galleryOptions = Maps.newHashMap();\n String resultConfig = CmsStringUtil.substitute(\n PATTERN_EMBEDDED_GALLERY_CONFIG,\n configuration,\n new I_CmsRegexSubstitution() {\n\n public String substituteMatch(String string, Matcher matcher) {\n\n String galleryName = string.substring(matcher.start(1), matcher.end(1));\n String embeddedConfig = string.substring(matcher.start(2), matcher.end(2));\n galleryOptions.put(galleryName, embeddedConfig);\n return galleryName;\n }\n });\n return CmsPair.create(resultConfig, galleryOptions);\n }",
"public void calculateSize(PdfContext context) {\n\t\tfloat width = 0;\n\t\tfloat height = 0;\n\t\tfor (PrintComponent<?> child : children) {\n\t\t\tchild.calculateSize(context);\n\t\t\tfloat cw = child.getBounds().getWidth() + 2 * child.getConstraint().getMarginX();\n\t\t\tfloat ch = child.getBounds().getHeight() + 2 * child.getConstraint().getMarginY();\n\t\t\tswitch (getConstraint().getFlowDirection()) {\n\t\t\t\tcase LayoutConstraint.FLOW_NONE:\n\t\t\t\t\twidth = Math.max(width, cw);\n\t\t\t\t\theight = Math.max(height, ch);\n\t\t\t\t\tbreak;\n\t\t\t\tcase LayoutConstraint.FLOW_X:\n\t\t\t\t\twidth += cw;\n\t\t\t\t\theight = Math.max(height, ch);\n\t\t\t\t\tbreak;\n\t\t\t\tcase LayoutConstraint.FLOW_Y:\n\t\t\t\t\twidth = Math.max(width, cw);\n\t\t\t\t\theight += ch;\n\t\t\t\t\tbreak;\n\t\t\t\tdefault:\n\t\t\t\t\tthrow new IllegalStateException(\"Unknown flow direction \" + getConstraint().getFlowDirection());\n\t\t\t}\n\t\t}\n\t\tif (getConstraint().getWidth() != 0) {\n\t\t\twidth = getConstraint().getWidth();\n\t\t}\n\t\tif (getConstraint().getHeight() != 0) {\n\t\t\theight = getConstraint().getHeight();\n\t\t}\n\t\tsetBounds(new Rectangle(0, 0, width, height));\n\t}",
"public String[] getReportSamples() {\n final Map<String, String> sampleValues = new HashMap<>();\n sampleValues.put(\"name1\", \"Secure Transpiler Mars\");\n sampleValues.put(\"version1\", \"4.7.0\");\n sampleValues.put(\"name2\", \"Secure Transpiler Bounty\");\n sampleValues.put(\"version2\", \"5.0.0\");\n sampleValues.put(\"license\", \"CDDL-1.1\");\n sampleValues.put(\"name\", \"Secure Pretender\");\n sampleValues.put(\"version\", \"2.7.0\");\n sampleValues.put(\"organization\", \"Axway\");\n\n return ReportsRegistry.allReports()\n .stream()\n .map(report -> ReportUtils.generateSampleRequest(report, sampleValues))\n .map(request -> {\n try {\n String desc = \"\";\n final Optional<Report> byId = ReportsRegistry.findById(request.getReportId());\n\n if(byId.isPresent()) {\n desc = byId.get().getDescription() + \"<br/><br/>\";\n }\n\n return String.format(TWO_PLACES, desc, JsonUtils.serialize(request));\n } catch(IOException e) {\n return \"Error \" + e.getMessage();\n }\n })\n .collect(Collectors.toList())\n .toArray(new String[] {});\n }",
"public static scala.collection.Iterable linkedListToScalaIterable(LinkedList<?> linkedList) {\n return JavaConverters.asScalaIterableConverter(linkedList).asScala();\n }",
"public static base_response update(nitro_service client, inatparam resource) throws Exception {\n\t\tinatparam updateresource = new inatparam();\n\t\tupdateresource.nat46v6prefix = resource.nat46v6prefix;\n\t\tupdateresource.nat46ignoretos = resource.nat46ignoretos;\n\t\tupdateresource.nat46zerochecksum = resource.nat46zerochecksum;\n\t\tupdateresource.nat46v6mtu = resource.nat46v6mtu;\n\t\tupdateresource.nat46fragheader = resource.nat46fragheader;\n\t\treturn updateresource.update_resource(client);\n\t}"
] |
Create a hazard curve from given times and given discount factors using default interpolation and extrapolation methods.
@param name The name of this hazard curve.
@param times Array of times as doubles.
@param givenSurvivalProbabilities Array of corresponding survival probabilities.
@return A new discount factor object. | [
"public static HazardCurve createHazardCurveFromSurvivalProbabilities(String name, double[] times, double[] givenSurvivalProbabilities){\n\t\tHazardCurve survivalProbabilities = new HazardCurve(name);\n\n\t\tfor(int timeIndex=0; timeIndex<times.length;timeIndex++) {\n\t\t\tsurvivalProbabilities.addSurvivalProbability(times[timeIndex], givenSurvivalProbabilities[timeIndex], times[timeIndex] > 0);\n\t\t}\n\n\t\treturn survivalProbabilities;\n\t}"
] | [
"public ItemRequest<Workspace> removeUser(String workspace) {\n \n String path = String.format(\"/workspaces/%s/removeUser\", workspace);\n return new ItemRequest<Workspace>(this, Workspace.class, path, \"POST\");\n }",
"public ItemRequest<OrganizationExport> findById(String organizationExport) {\n \n String path = String.format(\"/organization_exports/%s\", organizationExport);\n return new ItemRequest<OrganizationExport>(this, OrganizationExport.class, path, \"GET\");\n }",
"public void disableAllOverrides(int pathID, String clientUUID) {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"DELETE FROM \" + Constants.DB_TABLE_ENABLED_OVERRIDE +\n \" WHERE \" + Constants.ENABLED_OVERRIDES_PATH_ID + \" = ? \" +\n \" AND \" + Constants.GENERIC_CLIENT_UUID + \" = ? \"\n );\n statement.setInt(1, pathID);\n statement.setString(2, clientUUID);\n statement.execute();\n statement.close();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }",
"public void setLargePayloadSupportEnabled(AmazonS3 s3, String s3BucketName) {\n\t\tif (s3 == null || s3BucketName == null) {\n\t\t\tString errorMessage = \"S3 client and/or S3 bucket name cannot be null.\";\n\t\t\tLOG.error(errorMessage);\n\t\t\tthrow new AmazonClientException(errorMessage);\n\t\t}\n\t\tif (isLargePayloadSupportEnabled()) {\n\t\t\tLOG.warn(\"Large-payload support is already enabled. Overwriting AmazonS3Client and S3BucketName.\");\n\t\t}\n\t\tthis.s3 = s3;\n\t\tthis.s3BucketName = s3BucketName;\n\t\tlargePayloadSupport = true;\n\t\tLOG.info(\"Large-payload support enabled.\");\n\t}",
"public void setAmbientIntensity(float r, float g, float b, float a) {\n setVec4(\"ambient_intensity\", r, g, b, a);\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}",
"private static QName convertString(String str) {\n if (str != null) {\n return QName.valueOf(str);\n } else {\n return null;\n }\n }",
"public void forAllIndexColumns(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _curIndexDef.getColumns(); it.hasNext(); )\r\n {\r\n _curColumnDef = _curTableDef.getColumn((String)it.next());\r\n generate(template);\r\n }\r\n _curColumnDef = null;\r\n }",
"public static List<Integer> toIntegerList(List<String> strList, boolean failOnException){\n\t\tList<Integer> intList = new ArrayList<Integer>();\n\t\tfor(String str : strList){\n\t\t\ttry{\n\t\t\t\tintList.add(Integer.parseInt(str));\n\t\t\t}\n\t\t\tcatch(NumberFormatException nfe){\n\t\t\t\tif(failOnException){\n\t\t\t\t\treturn null;\n\t\t\t\t}\n\t\t\t\telse{\n\t\t\t\t\tintList.add(null);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn intList;\n\t}"
] |
Helper to read a line from the config file.
@param propValue the property value
@return the value of the variable set at this line. | [
"private String getValueFromProp(final String propValue) {\n\n String value = propValue;\n // remove quotes\n value = value.trim();\n if ((value.startsWith(\"\\\"\") && value.endsWith(\"\\\"\")) || (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n value = value.substring(1, value.length() - 1);\n }\n return value;\n }"
] | [
"public static int checkVlen(int i) {\n int count = 0;\n if (i >= -112 && i <= 127) {\n return 1;\n } else {\n int len = -112;\n if (i < 0) {\n i ^= -1L; // take one's complement'\n len = -120;\n }\n\n long tmp = i;\n while (tmp != 0) {\n tmp = tmp >> 8;\n len--;\n }\n\n count++;\n\n len = (len < -120) ? -(len + 120) : -(len + 112);\n\n while (len != 0) {\n count++;\n len--;\n }\n\n return count;\n }\n }",
"public static vpnvserver_rewritepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tvpnvserver_rewritepolicy_binding obj = new vpnvserver_rewritepolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnvserver_rewritepolicy_binding response[] = (vpnvserver_rewritepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static ZMatrixRMaj householderVector(ZMatrixRMaj x ) {\n ZMatrixRMaj u = x.copy();\n\n double max = CommonOps_ZDRM.elementMaxAbs(u);\n\n CommonOps_ZDRM.elementDivide(u, max, 0, u);\n\n double nx = NormOps_ZDRM.normF(u);\n Complex_F64 c = new Complex_F64();\n u.get(0,0,c);\n\n double realTau,imagTau;\n\n if( c.getMagnitude() == 0 ) {\n realTau = nx;\n imagTau = 0;\n } else {\n realTau = c.real/c.getMagnitude()*nx;\n imagTau = c.imaginary/c.getMagnitude()*nx;\n }\n\n u.set(0,0,c.real + realTau,c.imaginary + imagTau);\n CommonOps_ZDRM.elementDivide(u,u.getReal(0,0),u.getImag(0,0),u);\n\n return u;\n }",
"public static Predicate is(final String sql) {\n return new Predicate() {\n public String toSql() {\n return sql;\n }\n public void init(AbstractSqlCreator creator) {\n }\n };\n }",
"public BoxFolder.Info restoreFolder(String folderID, String newName, String newParentID) {\n JsonObject requestJSON = new JsonObject();\n\n if (newName != null) {\n requestJSON.add(\"name\", newName);\n }\n\n if (newParentID != null) {\n JsonObject parent = new JsonObject();\n parent.add(\"id\", newParentID);\n requestJSON.add(\"parent\", parent);\n }\n\n URL url = RESTORE_FOLDER_URL_TEMPLATE.build(this.api.getBaseURL(), folderID);\n BoxJSONRequest request = new BoxJSONRequest(this.api, url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxFolder restoredFolder = new BoxFolder(this.api, responseJSON.get(\"id\").asString());\n return restoredFolder.new Info(responseJSON);\n }",
"private void updateDurationTimeUnit(FastTrackColumn column)\n {\n if (m_durationTimeUnit == null && isDurationColumn(column))\n {\n int value = ((DurationColumn) column).getTimeUnitValue();\n if (value != 1)\n {\n m_durationTimeUnit = FastTrackUtility.getTimeUnit(value);\n }\n }\n }",
"private void removeTimedOutLocks(long timeout)\r\n {\r\n int count = 0;\r\n long maxAge = System.currentTimeMillis() - timeout;\r\n boolean breakFromLoop = false;\r\n ObjectLocks temp = null;\r\n \tsynchronized (locktable)\r\n \t{\r\n\t Iterator it = locktable.values().iterator();\r\n\t /**\r\n\t * run this loop while:\r\n\t * - we have more in the iterator\r\n\t * - the breakFromLoop flag hasn't been set\r\n\t * - we haven't removed more than the limit for this cleaning iteration.\r\n\t */\r\n\t while (it.hasNext() && !breakFromLoop && (count <= MAX_LOCKS_TO_CLEAN))\r\n\t {\r\n\t \ttemp = (ObjectLocks) it.next();\r\n\t \tif (temp.getWriter() != null)\r\n\t \t{\r\n\t\t \tif (temp.getWriter().getTimestamp() < maxAge)\r\n\t\t \t{\r\n\t\t \t\t// writer has timed out, set it to null\r\n\t\t \t\ttemp.setWriter(null);\r\n\t\t \t}\r\n\t \t}\r\n\t \tif (temp.getYoungestReader() < maxAge)\r\n\t \t{\r\n\t \t\t// all readers are older than timeout.\r\n\t \t\ttemp.getReaders().clear();\r\n\t \t\tif (temp.getWriter() == null)\r\n\t \t\t{\r\n\t \t\t\t// all readers and writer are older than timeout,\r\n\t \t\t\t// remove the objectLock from the iterator (which\r\n\t \t\t\t// is backed by the map, so it will be removed.\r\n\t \t\t\tit.remove();\r\n\t \t\t}\r\n\t \t}\r\n\t \telse\r\n\t \t{\r\n\t \t\t// we need to walk each reader.\r\n\t \t\tIterator readerIt = temp.getReaders().values().iterator();\r\n\t \t\tLockEntry readerLock = null;\r\n\t \t\twhile (readerIt.hasNext())\r\n\t \t\t{\r\n\t \t\t\treaderLock = (LockEntry) readerIt.next();\r\n\t \t\t\tif (readerLock.getTimestamp() < maxAge)\r\n\t \t\t\t{\r\n\t \t\t\t\t// this read lock is old, remove it.\r\n\t \t\t\t\treaderIt.remove();\r\n\t \t\t\t}\r\n\t \t\t}\r\n\t \t}\r\n\t \tcount++;\r\n\t }\r\n \t}\r\n }",
"public static <K, V> Map<K, V> of(K key, V value) {\n return new ImmutableMapEntry<K, V>(key, value);\n }",
"public List<MapRow> read() throws IOException\n {\n List<MapRow> result = new ArrayList<MapRow>();\n int fileCount = m_stream.readInt();\n if (fileCount != 0)\n {\n for (int index = 0; index < fileCount; index++)\n {\n // We use a LinkedHashMap to preserve insertion order in iteration\n // Useful when debugging the file format.\n Map<String, Object> map = new LinkedHashMap<String, Object>();\n readBlock(map);\n result.add(new MapRow(map));\n }\n }\n return result;\n }"
] |
Get the aggregated result human readable string for easy display.
@param aggregateResultMap the aggregate result map
@return the aggregated result human | [
"public static String getAggregatedResultHuman(Map<String, LinkedHashSet<String>> aggregateResultMap){\n\n StringBuilder res = new StringBuilder();\n\n for (Entry<String, LinkedHashSet<String>> entry : aggregateResultMap\n .entrySet()) {\n LinkedHashSet<String> valueSet = entry.getValue(); \n res.append(\"[\" + entry.getKey() + \" COUNT: \" +valueSet.size() + \" ]:\\n\");\n for(String str: valueSet){\n res.append(\"\\t\" + str + \"\\n\");\n }\n res.append(\"###################################\\n\\n\");\n }\n \n return res.toString();\n \n }"
] | [
"private boolean initCheckTypeModifiers() {\n\n Class<?> classInfoclass = Reflections.loadClass(CLASSINFO_CLASS_NAME, new ClassLoaderResourceLoader(classFileServices.getClass().getClassLoader()));\n if (classInfoclass != null) {\n try {\n Method setFlags = AccessController.doPrivileged(GetDeclaredMethodAction.of(classInfoclass, \"setFlags\", short.class));\n return setFlags != null;\n } catch (Exception exceptionIgnored) {\n BootstrapLogger.LOG.usingOldJandexVersion();\n return false;\n }\n } else {\n return true;\n }\n }",
"public static boolean containsOnlyNull(Object... values){\t\n\t\tfor(Object o : values){\n\t\t\tif(o!= null){\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}",
"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 void serialize(final File folder, final String content, final String fileName) throws IOException {\n if (!folder.exists()) {\n folder.mkdirs();\n }\n\n final File output = new File(folder, fileName);\n\n try (\n final FileWriter writer = new FileWriter(output);\n ) {\n writer.write(content);\n writer.flush();\n } catch (Exception e) {\n throw new IOException(\"Failed to serialize the notification in folder \" + folder.getPath(), e);\n }\n }",
"private static String findOutputPath(String[][] options) {\n\tfor (int i = 0; i < options.length; i++) {\n\t if (options[i][0].equals(\"-d\"))\n\t\treturn options[i][1];\n\t}\n\treturn \".\";\n }",
"public static EventLog getEnterpriseEvents(BoxAPIConnection api, Date after, Date before, BoxEvent.Type... types) {\n return getEnterpriseEvents(api, null, after, before, ENTERPRISE_LIMIT, types);\n }",
"public static MfClientHttpRequestFactory createFactoryWrapper(\n final MfClientHttpRequestFactory requestFactory,\n final UriMatchers matchers, final Map<String, List<String>> headers) {\n return new AbstractMfClientHttpRequestFactoryWrapper(requestFactory, matchers, false) {\n @Override\n protected ClientHttpRequest createRequest(\n final URI uri,\n final HttpMethod httpMethod,\n final MfClientHttpRequestFactory requestFactory) throws IOException {\n final ClientHttpRequest request = requestFactory.createRequest(uri, httpMethod);\n request.getHeaders().putAll(headers);\n return request;\n }\n };\n }",
"private void sendMessage(Message message) throws IOException {\n logger.debug(\"Sending> {}\", message);\n int totalSize = 0;\n for (Field field : message.fields) {\n totalSize += field.getBytes().remaining();\n }\n ByteBuffer combined = ByteBuffer.allocate(totalSize);\n for (Field field : message.fields) {\n logger.debug(\"..sending> {}\", field);\n combined.put(field.getBytes());\n }\n combined.flip();\n Util.writeFully(combined, channel);\n }",
"public static <T> void finish(T query, long correlationId, EventBus bus, String... types) {\n for (String type : types) {\n RemoveQuery<T> next = finish(query, correlationId, type);\n bus.post(next);\n }\n }"
] |
Called every frame if the picker is enabled
to generate pick events.
@param frameTime starting time of the current frame | [
"public void onDrawFrame(float frameTime)\n {\n if (isEnabled() && (mScene != null) && mPickEventLock.tryLock())\n {\n // Don't call if we are in the middle of processing another pick\n try\n {\n doPick();\n }\n finally\n {\n mPickEventLock.unlock();\n }\n }\n }"
] | [
"@SuppressWarnings({\"unused\", \"WeakerAccess\"})\n public int getCount(String event) {\n EventDetail eventDetail = getLocalDataStore().getEventDetail(event);\n if (eventDetail != null) return eventDetail.getCount();\n\n return -1;\n }",
"public static Pointer mmap(long len, int prot, int flags, int fildes, long off)\n throws IOException {\n\n // we don't really have a need to change the recommended pointer.\n Pointer addr = new Pointer(0);\n\n Pointer result = Delegate.mmap(addr,\n new NativeLong(len),\n prot,\n flags,\n fildes,\n new NativeLong(off));\n\n if(Pointer.nativeValue(result) == -1) {\n if(logger.isDebugEnabled())\n logger.debug(errno.strerror());\n\t throw new IOException(\"mmap failed: \" + errno.strerror());\n }\n\n return result;\n\n }",
"public void put(@NotNull final PersistentStoreTransaction txn,\n final long localId,\n @NotNull final ByteIterable value,\n @Nullable final ByteIterable oldValue,\n final int propertyId,\n @NotNull final ComparableValueType type) {\n final Store valueIdx = getOrCreateValueIndex(txn, propertyId);\n final ByteIterable key = PropertyKey.propertyKeyToEntry(new PropertyKey(localId, propertyId));\n final Transaction envTxn = txn.getEnvironmentTransaction();\n primaryStore.put(envTxn, key, value);\n final ByteIterable secondaryValue = LongBinding.longToCompressedEntry(localId);\n boolean success;\n if (oldValue == null) {\n success = allPropsIndex.put(envTxn, IntegerBinding.intToCompressedEntry(propertyId), secondaryValue);\n } else {\n success = deleteFromStore(envTxn, valueIdx, secondaryValue, createSecondaryKeys(store.getPropertyTypes(), oldValue, type));\n }\n if (success) {\n for (final ByteIterable secondaryKey : createSecondaryKeys(store.getPropertyTypes(), value, type)) {\n valueIdx.put(envTxn, secondaryKey, secondaryValue);\n }\n }\n checkStatus(success, \"Failed to put\");\n }",
"private void handleGlobalArguments(CommandLine cmd) {\n\t\tif (cmd.hasOption(CMD_OPTION_DUMP_LOCATION)) {\n\t\t\tthis.dumpDirectoryLocation = cmd\n\t\t\t\t\t.getOptionValue(CMD_OPTION_DUMP_LOCATION);\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_OFFLINE_MODE)) {\n\t\t\tthis.offlineMode = true;\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_QUIET)) {\n\t\t\tthis.quiet = true;\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_CREATE_REPORT)) {\n\t\t\tthis.reportFilename = cmd.getOptionValue(CMD_OPTION_CREATE_REPORT);\n\t\t}\n\n\t\tif (cmd.hasOption(OPTION_FILTER_LANGUAGES)) {\n\t\t\tsetLanguageFilters(cmd.getOptionValue(OPTION_FILTER_LANGUAGES));\n\t\t}\n\n\t\tif (cmd.hasOption(OPTION_FILTER_SITES)) {\n\t\t\tsetSiteFilters(cmd.getOptionValue(OPTION_FILTER_SITES));\n\t\t}\n\n\t\tif (cmd.hasOption(OPTION_FILTER_PROPERTIES)) {\n\t\t\tsetPropertyFilters(cmd.getOptionValue(OPTION_FILTER_PROPERTIES));\n\t\t}\n\n\t\tif (cmd.hasOption(CMD_OPTION_LOCAL_DUMPFILE)) {\n\t\t\tthis.inputDumpLocation = cmd.getOptionValue(OPTION_LOCAL_DUMPFILE);\n\t\t}\n\t}",
"public Set<Class> entityClasses() {\n EntityMetaInfoRepo repo = app().entityMetaInfoRepo().forDb(id);\n return null == repo ? C.<Class>set() : repo.entityClasses();\n }",
"private int getPrototypeIndex(Renderer renderer) {\n int index = 0;\n for (Renderer prototype : prototypes) {\n if (prototype.getClass().equals(renderer.getClass())) {\n break;\n }\n index++;\n }\n return index;\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 }",
"protected ServiceRegistration registerProxy(Object objectProxy, Class clazz) {\n Dictionary<String, Object> props = new Hashtable<String, Object>();\n ServiceRegistration registration;\n registration = context.registerService(clazz, objectProxy, props);\n\n return registration;\n }",
"public final void removeDirectory(final File directory) {\n try {\n FileUtils.deleteDirectory(directory);\n } catch (IOException e) {\n LOGGER.error(\"Unable to delete directory '{}'\", directory);\n }\n }"
] |
Process a calendar exception.
@param calendar parent calendar
@param row calendar exception data | [
"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 }"
] | [
"@Override\n public final String getString(final String key) {\n String result = optString(key);\n if (result == null) {\n throw new ObjectMissingException(this, key);\n }\n return result;\n }",
"public void setTotalColorForColumn(int column, Color color){\r\n\t\tint map = (colors.length-1) - column;\r\n\t\tcolors[map][colors[0].length-1]=color;\r\n\t}",
"static InjectionProvider<?>[] toArray(final Set<InjectionProvider<?>> injectionProviders) {\n return injectionProviders.toArray(new InjectionProvider<?>[injectionProviders.size()]);\n }",
"public BoxTask.Info addTask(BoxTask.Action action, String message, Date dueAt) {\n JsonObject itemJSON = new JsonObject();\n itemJSON.add(\"type\", \"file\");\n itemJSON.add(\"id\", this.getID());\n\n JsonObject requestJSON = new JsonObject();\n requestJSON.add(\"item\", itemJSON);\n requestJSON.add(\"action\", action.toJSONString());\n\n if (message != null && !message.isEmpty()) {\n requestJSON.add(\"message\", message);\n }\n\n if (dueAt != null) {\n requestJSON.add(\"due_at\", BoxDateFormat.format(dueAt));\n }\n\n URL url = ADD_TASK_URL_TEMPLATE.build(this.getAPI().getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(this.getAPI(), url, \"POST\");\n request.setBody(requestJSON.toString());\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n BoxTask addedTask = new BoxTask(this.getAPI(), responseJSON.get(\"id\").asString());\n return addedTask.new Info(responseJSON);\n }",
"private void addChildrenForGroupsNode(I_CmsOuTreeType type, String ouItem) {\n\n try {\n // Cut of type-specific prefix from ouItem with substring()\n List<CmsGroup> groups = m_app.readGroupsForOu(m_cms, ouItem.substring(1), type, false);\n for (CmsGroup group : groups) {\n Pair<String, CmsUUID> key = Pair.of(type.getId(), group.getId());\n Item groupItem = m_treeContainer.addItem(key);\n if (groupItem == null) {\n groupItem = getItem(key);\n }\n groupItem.getItemProperty(PROP_SID).setValue(group.getId());\n groupItem.getItemProperty(PROP_NAME).setValue(getIconCaptionHTML(group, CmsOuTreeType.GROUP));\n groupItem.getItemProperty(PROP_TYPE).setValue(type);\n setChildrenAllowed(key, false);\n m_treeContainer.setParent(key, ouItem);\n }\n } catch (CmsException e) {\n LOG.error(\"Can not read group\", e);\n }\n }",
"@SuppressWarnings(\"unchecked\")\n protected <T extends Indexable> T taskResult(String key) {\n Indexable result = this.taskGroup.taskResult(key);\n if (result == null) {\n return null;\n } else {\n T castedResult = (T) result;\n return castedResult;\n }\n }",
"public static base_responses update(nitro_service client, route6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\troute6 updateresources[] = new route6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new route6();\n\t\t\t\tupdateresources[i].network = resources[i].network;\n\t\t\t\tupdateresources[i].gateway = resources[i].gateway;\n\t\t\t\tupdateresources[i].vlan = resources[i].vlan;\n\t\t\t\tupdateresources[i].weight = resources[i].weight;\n\t\t\t\tupdateresources[i].distance = resources[i].distance;\n\t\t\t\tupdateresources[i].cost = resources[i].cost;\n\t\t\t\tupdateresources[i].advertise = resources[i].advertise;\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].td = resources[i].td;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"private void onShow() {\n\n if (m_detailsFieldset != null) {\n m_detailsFieldset.getContentPanel().getElement().getStyle().setPropertyPx(\n \"maxHeight\",\n getAvailableHeight(m_messageWidget.getOffsetHeight()));\n }\n }",
"private void cleanupDestination(DownloadRequest request, boolean forceClean) {\n if (!request.isResumable() || forceClean) {\n Log.d(\"cleanupDestination() deleting \" + request.getDestinationURI().getPath());\n File destinationFile = new File(request.getDestinationURI().getPath());\n if (destinationFile.exists()) {\n destinationFile.delete();\n }\n }\n }"
] |
Called when a ParentViewHolder has triggered an expansion for it's parent
@param flatParentPosition the position of the parent that is calling to be expanded | [
"@UiThread\n protected void parentExpandedFromViewHolder(int flatParentPosition) {\n ExpandableWrapper<P, C> parentWrapper = mFlatItemList.get(flatParentPosition);\n updateExpandedParent(parentWrapper, flatParentPosition, true);\n }"
] | [
"private void printPropertyRecord(PrintStream out,\n\t\t\tPropertyRecord propertyRecord, PropertyIdValue propertyIdValue) {\n\n\t\tprintTerms(out, propertyRecord.propertyDocument, propertyIdValue, null);\n\n\t\tString datatype = \"Unknown\";\n\t\tif (propertyRecord.propertyDocument != null) {\n\t\t\tdatatype = getDatatypeLabel(propertyRecord.propertyDocument\n\t\t\t\t\t.getDatatype());\n\t\t}\n\n\t\tout.print(\",\"\n\t\t\t\t+ datatype\n\t\t\t\t+ \",\"\n\t\t\t\t+ propertyRecord.statementCount\n\t\t\t\t+ \",\"\n\t\t\t\t+ propertyRecord.itemCount\n\t\t\t\t+ \",\"\n\t\t\t\t+ propertyRecord.statementWithQualifierCount\n\t\t\t\t+ \",\"\n\t\t\t\t+ propertyRecord.qualifierCount\n\t\t\t\t+ \",\"\n\t\t\t\t+ propertyRecord.referenceCount\n\t\t\t\t+ \",\"\n\t\t\t\t+ (propertyRecord.statementCount\n\t\t\t\t\t\t+ propertyRecord.qualifierCount + propertyRecord.referenceCount));\n\n\t\tprintRelatedProperties(out, propertyRecord);\n\n\t\tout.println(\"\");\n\t}",
"public Set<AttributeAccess.Flag> getFlags() {\n if (attributeAccess == null) {\n return Collections.emptySet();\n }\n return attributeAccess.getFlags();\n }",
"@Nonnull\n public BiMap<String, String> getOutputMapper() {\n final BiMap<String, String> outputMapper = this.processor.getOutputMapperBiMap();\n if (outputMapper == null) {\n return HashBiMap.create();\n }\n return outputMapper;\n }",
"private JSONArray readOptionalArray(JSONObject json, String key) {\n\n try {\n return json.getJSONArray(key);\n } catch (JSONException e) {\n LOG.debug(\"Reading optional JSON array failed. Default to provided default value.\", e);\n }\n return null;\n }",
"public OTMConnection acquireConnection(PBKey pbKey)\r\n {\r\n TransactionFactory txFactory = getTransactionFactory();\r\n return txFactory.acquireConnection(pbKey);\r\n }",
"public static DMatrixRMaj stripReal(ZMatrixD1 input , DMatrixRMaj output ) {\n if( output == null ) {\n output = new DMatrixRMaj(input.numRows,input.numCols);\n } else if( input.numCols != output.numCols || input.numRows != output.numRows ) {\n throw new IllegalArgumentException(\"The matrices are not all the same dimension.\");\n }\n\n final int length = input.getDataLength();\n\n for( int i = 0; i < length; i += 2 ) {\n output.data[i/2] = input.data[i];\n }\n return output;\n }",
"protected Connection newConnectionFromDataSource(JdbcConnectionDescriptor jcd)\r\n throws LookupException\r\n {\r\n Connection retval = null;\r\n // use JNDI lookup\r\n DataSource ds = jcd.getDataSource();\r\n\r\n if (ds == null)\r\n {\r\n // [tomdz] Would it suffice to store the datasources only at the JCDs ?\r\n // Only possible problem would be serialization of the JCD because\r\n // the data source object in the JCD does not 'survive' this\r\n ds = (DataSource) dataSourceCache.get(jcd.getDatasourceName());\r\n }\r\n try\r\n {\r\n if (ds == null)\r\n {\r\n /**\r\n * this synchronization block won't be a big deal as we only look up\r\n * new datasources not found in the map.\r\n */\r\n synchronized (dataSourceCache)\r\n {\r\n InitialContext ic = new InitialContext();\r\n ds = (DataSource) ic.lookup(jcd.getDatasourceName());\r\n /**\r\n * cache the datasource lookup.\r\n */\r\n dataSourceCache.put(jcd.getDatasourceName(), ds);\r\n }\r\n }\r\n if (jcd.getUserName() == null)\r\n {\r\n retval = ds.getConnection();\r\n }\r\n else\r\n {\r\n retval = ds.getConnection(jcd.getUserName(), jcd.getPassWord());\r\n }\r\n }\r\n catch (SQLException sqlEx)\r\n {\r\n log.error(\"SQLException thrown while trying to get Connection from Datasource (\" +\r\n jcd.getDatasourceName() + \")\", sqlEx);\r\n throw new LookupException(\"SQLException thrown while trying to get Connection from Datasource (\" +\r\n jcd.getDatasourceName() + \")\", sqlEx);\r\n }\r\n catch (NamingException namingEx)\r\n {\r\n log.error(\"Naming Exception while looking up DataSource (\" + jcd.getDatasourceName() + \")\", namingEx);\r\n throw new LookupException(\"Naming Exception while looking up DataSource (\" + jcd.getDatasourceName() +\r\n \")\", namingEx);\r\n }\r\n // initialize connection\r\n initializeJdbcConnection(retval, jcd);\r\n if(log.isDebugEnabled()) log.debug(\"Create new connection using DataSource: \"+retval);\r\n return retval;\r\n }",
"public EventBus emit(EventObject event, Object... args) {\n return _emitWithOnceBus(eventContext(event, args));\n }",
"private void setQR(DMatrixRMaj Q , DMatrixRMaj R , int growRows ) {\n if( Q.numRows != Q.numCols ) {\n throw new IllegalArgumentException(\"Q should be square.\");\n }\n\n this.Q = Q;\n this.R = R;\n\n m = Q.numRows;\n n = R.numCols;\n\n if( m+growRows > maxRows || n > maxCols ) {\n if( autoGrow ) {\n declareInternalData(m+growRows,n);\n } else {\n throw new IllegalArgumentException(\"Autogrow has been set to false and the maximum number of rows\" +\n \" or columns has been exceeded.\");\n }\n }\n }"
] |
Returns the portion of the field name after the last dot, as field names
may actually be paths. | [
"private static String toColumnName(String fieldName) {\n int lastDot = fieldName.indexOf('.');\n if (lastDot > -1) {\n return fieldName.substring(lastDot + 1);\n } else {\n return fieldName;\n }\n }"
] | [
"public GVRShaderId getShaderType(Class<? extends GVRShader> shaderClass)\n {\n GVRShaderId shaderId = mShaderTemplates.get(shaderClass);\n\n if (shaderId == null)\n {\n GVRContext ctx = getGVRContext();\n shaderId = new GVRShaderId(shaderClass);\n mShaderTemplates.put(shaderClass, shaderId);\n shaderId.getTemplate(ctx);\n }\n return shaderId;\n }",
"boolean lockSharedInterruptibly(final Integer permit, final long timeout, final TimeUnit unit) throws InterruptedException {\n if (permit == null) {\n throw new IllegalArgumentException();\n }\n return sync.tryAcquireSharedNanos(permit, unit.toNanos(timeout));\n }",
"private static void generateJson(CellScanner cellScanner, Function<Bytes, String> encoder,\n PrintStream out) throws JsonIOException {\n Gson gson = new GsonBuilder().serializeNulls().setDateFormat(DateFormat.LONG)\n .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).setVersion(1.0)\n .create();\n\n Map<String, String> json = new LinkedHashMap<>();\n for (RowColumnValue rcv : cellScanner) {\n json.put(FLUO_ROW, encoder.apply(rcv.getRow()));\n json.put(FLUO_COLUMN_FAMILY, encoder.apply(rcv.getColumn().getFamily()));\n json.put(FLUO_COLUMN_QUALIFIER, encoder.apply(rcv.getColumn().getQualifier()));\n json.put(FLUO_COLUMN_VISIBILITY, encoder.apply(rcv.getColumn().getVisibility()));\n json.put(FLUO_VALUE, encoder.apply(rcv.getValue()));\n gson.toJson(json, out);\n out.append(\"\\n\");\n\n if (out.checkError()) {\n break;\n }\n }\n out.flush();\n }",
"public static ModelNode getAccessControl(ModelControllerClient client, OperationRequestAddress address, boolean operations) {\n return getAccessControl(client, null, address, operations);\n }",
"public ProjectCalendar getByName(String calendarName)\n {\n ProjectCalendar calendar = null;\n\n if (calendarName != null && calendarName.length() != 0)\n {\n Iterator<ProjectCalendar> iter = iterator();\n while (iter.hasNext() == true)\n {\n calendar = iter.next();\n String name = calendar.getName();\n\n if ((name != null) && (name.equalsIgnoreCase(calendarName) == true))\n {\n break;\n }\n\n calendar = null;\n }\n }\n\n return (calendar);\n }",
"private static Clique valueOfHelper(int[] relativeIndices) {\r\n // if clique already exists, return that one\r\n Clique c = new Clique();\r\n c.relativeIndices = relativeIndices;\r\n return intern(c);\r\n }",
"public static final Bytes of(ByteBuffer bb) {\n Objects.requireNonNull(bb);\n if (bb.remaining() == 0) {\n return EMPTY;\n }\n byte[] data;\n if (bb.hasArray()) {\n data = Arrays.copyOfRange(bb.array(), bb.position() + bb.arrayOffset(),\n bb.limit() + bb.arrayOffset());\n } else {\n data = new byte[bb.remaining()];\n // duplicate so that it does not change position\n bb.duplicate().get(data);\n }\n return new Bytes(data);\n }",
"public static String resolveProxyUrl(String relativeUrl, TileMap tileMap, String baseTmsUrl) {\n\t\tTileCode tc = parseTileCode(relativeUrl);\n\t\treturn buildUrl(tc, tileMap, baseTmsUrl);\n\t}",
"public void execute() throws MojoExecutionException, MojoFailureException {\n try {\n Set<File> thriftFiles = findThriftFiles();\n\n final File outputDirectory = getOutputDirectory();\n ImmutableSet<File> outputFiles = findGeneratedFilesInDirectory(getOutputDirectory());\n\n Set<String> compileRoots = new HashSet<String>();\n compileRoots.add(\"scrooge\");\n\n if (thriftFiles.isEmpty()) {\n getLog().info(\"No thrift files to compile.\");\n } else if (checkStaleness && ((lastModified(thriftFiles) + staleMillis) < lastModified(outputFiles))) {\n getLog().info(\"Generated thrift files up to date, skipping compile.\");\n attachFiles(compileRoots);\n } else {\n outputDirectory.mkdirs();\n\n // Quick fix to fix issues with two mvn installs in a row (ie no clean)\n cleanDirectory(outputDirectory);\n\n getLog().info(format(\"compiling thrift files %s with Scrooge\", thriftFiles));\n synchronized(lock) {\n ScroogeRunner runner = new ScroogeRunner();\n Map<String, String> thriftNamespaceMap = new HashMap<String, String>();\n for (ThriftNamespaceMapping mapping : thriftNamespaceMappings) {\n thriftNamespaceMap.put(mapping.getFrom(), mapping.getTo());\n }\n\n // Include thrifts from resource as well.\n Set<File> includes = thriftIncludes;\n includes.add(getResourcesOutputDirectory());\n\n // Include thrift root\n final File thriftSourceRoot = getThriftSourceRoot();\n if (thriftSourceRoot != null && thriftSourceRoot.exists()) {\n includes.add(thriftSourceRoot);\n }\n\n runner.compile(\n getLog(),\n includeOutputDirectoryNamespace ? new File(outputDirectory, \"scrooge\") : outputDirectory,\n thriftFiles,\n includes,\n thriftNamespaceMap,\n language,\n thriftOpts);\n }\n attachFiles(compileRoots);\n }\n } catch (IOException e) {\n throw new MojoExecutionException(\"An IO error occurred\", e);\n }\n }"
] |
Given the key, figures out which partition on the local node hosts the key.
@param key
@return | [
"private Integer getKeyPartitionId(byte[] key) {\n Integer keyPartitionId = storeInstance.getNodesPartitionIdForKey(nodeId, key);\n\n Utils.notNull(keyPartitionId);\n return keyPartitionId;\n }"
] | [
"public SingleProfileBackup getProfileBackupData(int profileID, String clientUUID) throws Exception {\n SingleProfileBackup singleProfileBackup = new SingleProfileBackup();\n List<PathOverride> enabledPaths = new ArrayList<>();\n\n List<EndpointOverride> paths = PathOverrideService.getInstance().getPaths(profileID, clientUUID, null);\n for (EndpointOverride override : paths) {\n if (override.getRequestEnabled() || override.getResponseEnabled()) {\n PathOverride pathOverride = new PathOverride();\n pathOverride.setPathName(override.getPathName());\n if (override.getRequestEnabled()) {\n pathOverride.setRequestEnabled(true);\n }\n if (override.getResponseEnabled()) {\n pathOverride.setResponseEnabled(true);\n }\n\n pathOverride.setEnabledEndpoints(override.getEnabledEndpoints());\n enabledPaths.add(pathOverride);\n }\n }\n singleProfileBackup.setEnabledPaths(enabledPaths);\n\n Client backupClient = ClientService.getInstance().findClient(clientUUID, profileID);\n ServerGroup activeServerGroup = ServerRedirectService.getInstance().getServerGroup(backupClient.getActiveServerGroup(), profileID);\n singleProfileBackup.setActiveServerGroup(activeServerGroup);\n\n return singleProfileBackup;\n }",
"@Override\n public Future<RawGcsCreationToken> continueObjectCreationAsync(final RawGcsCreationToken token,\n final ByteBuffer chunk, long timeoutMillis) {\n try {\n ensureInitialized();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n final Environment environment = ApiProxy.getCurrentEnvironment();\n return writePool.schedule(new Callable<RawGcsCreationToken>() {\n @Override\n public RawGcsCreationToken call() throws Exception {\n ApiProxy.setEnvironmentForCurrentThread(environment);\n return append(token, chunk);\n }\n }, 50, TimeUnit.MILLISECONDS);\n }",
"private LoggingConfigurationService configure(final ResourceRoot root, final VirtualFile configFile, final ClassLoader classLoader, final LogContext logContext) throws DeploymentUnitProcessingException {\n InputStream configStream = null;\n try {\n LoggingLogger.ROOT_LOGGER.debugf(\"Found logging configuration file: %s\", configFile);\n\n // Get the filname and open the stream\n final String fileName = configFile.getName();\n configStream = configFile.openStream();\n\n // Check the type of the configuration file\n if (isLog4jConfiguration(fileName)) {\n final ClassLoader current = WildFlySecurityManager.getCurrentContextClassLoaderPrivileged();\n final LogContext old = logContextSelector.getAndSet(CONTEXT_LOCK, logContext);\n try {\n WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(classLoader);\n if (LOG4J_XML.equals(fileName) || JBOSS_LOG4J_XML.equals(fileName)) {\n new DOMConfigurator().doConfigure(configStream, org.apache.log4j.JBossLogManagerFacade.getLoggerRepository(logContext));\n } else {\n final Properties properties = new Properties();\n properties.load(new InputStreamReader(configStream, ENCODING));\n new org.apache.log4j.PropertyConfigurator().doConfigure(properties, org.apache.log4j.JBossLogManagerFacade.getLoggerRepository(logContext));\n }\n } finally {\n logContextSelector.getAndSet(CONTEXT_LOCK, old);\n WildFlySecurityManager.setCurrentContextClassLoaderPrivileged(current);\n }\n return new LoggingConfigurationService(null, resolveRelativePath(root, configFile));\n } else {\n // Create a properties file\n final Properties properties = new Properties();\n properties.load(new InputStreamReader(configStream, ENCODING));\n // Attempt to see if this is a J.U.L. configuration file\n if (isJulConfiguration(properties)) {\n LoggingLogger.ROOT_LOGGER.julConfigurationFileFound(configFile.getName());\n } else {\n // Load non-log4j types\n final PropertyConfigurator propertyConfigurator = new PropertyConfigurator(logContext);\n propertyConfigurator.configure(properties);\n return new LoggingConfigurationService(propertyConfigurator.getLogContextConfiguration(), resolveRelativePath(root, configFile));\n }\n }\n } catch (Exception e) {\n throw LoggingLogger.ROOT_LOGGER.failedToConfigureLogging(e, configFile.getName());\n } finally {\n safeClose(configStream);\n }\n return null;\n }",
"public WebMBeanAdapter createWebMBeanAdapter(String mBeanName, String encoding)\n throws JMException, UnsupportedEncodingException {\n return new WebMBeanAdapter(mBeanServer, mBeanName, encoding);\n }",
"private void writeProjectProperties(ProjectProperties record) throws IOException\n {\n // the ProjectProperties class from MPXJ has the details of how many days per week etc....\n // so I've assigned these variables in here, but actually use them in other methods\n // see the write task method, that's where they're used, but that method only has a Task object\n m_minutesPerDay = record.getMinutesPerDay().doubleValue();\n m_minutesPerWeek = record.getMinutesPerWeek().doubleValue();\n m_daysPerMonth = record.getDaysPerMonth().doubleValue();\n\n // reset buffer to be empty, then concatenate data as required by USACE\n m_buffer.setLength(0);\n m_buffer.append(\"PROJ \");\n m_buffer.append(m_formatter.format(record.getStartDate()).toUpperCase() + \" \"); // DataDate\n m_buffer.append(SDEFmethods.lset(record.getManager(), 4) + \" \"); // ProjIdent\n m_buffer.append(SDEFmethods.lset(record.getProjectTitle(), 48) + \" \"); // ProjName\n m_buffer.append(SDEFmethods.lset(record.getSubject(), 36) + \" \"); // ContrName\n m_buffer.append(\"P \"); // ArrowP\n m_buffer.append(SDEFmethods.lset(record.getKeywords(), 7)); // ContractNum\n m_buffer.append(m_formatter.format(record.getStartDate()).toUpperCase() + \" \"); // ProjStart\n m_buffer.append(m_formatter.format(record.getFinishDate()).toUpperCase()); // ProjEnd\n m_writer.println(m_buffer);\n }",
"private Observable<Indexable> invokeReadyTasksAsync(final InvocationContext context) {\n TaskGroupEntry<TaskItem> readyTaskEntry = super.getNext();\n final List<Observable<Indexable>> observables = new ArrayList<>();\n // Enumerate the ready tasks (those with dependencies resolved) and kickoff them concurrently\n //\n while (readyTaskEntry != null) {\n final TaskGroupEntry<TaskItem> currentEntry = readyTaskEntry;\n final TaskItem currentTaskItem = currentEntry.data();\n if (currentTaskItem instanceof ProxyTaskItem) {\n observables.add(invokeAfterPostRunAsync(currentEntry, context));\n } else {\n observables.add(invokeTaskAsync(currentEntry, context));\n }\n readyTaskEntry = super.getNext();\n }\n return Observable.mergeDelayError(observables);\n }",
"private void changeClusterAndStores(String clusterKey,\n final Cluster cluster,\n String storesKey,\n final List<StoreDefinition> storeDefs) {\n metadataStore.writeLock.lock();\n try {\n VectorClock updatedVectorClock = ((VectorClock) metadataStore.get(clusterKey, null)\n .get(0)\n .getVersion()).incremented(metadataStore.getNodeId(),\n System.currentTimeMillis());\n metadataStore.put(clusterKey, Versioned.value((Object) cluster, updatedVectorClock));\n\n // now put new stores\n updatedVectorClock = ((VectorClock) metadataStore.get(storesKey, null)\n .get(0)\n .getVersion()).incremented(metadataStore.getNodeId(),\n System.currentTimeMillis());\n metadataStore.put(storesKey, Versioned.value((Object) storeDefs, updatedVectorClock));\n\n } catch(Exception e) {\n logger.info(\"Error while changing cluster to \" + cluster + \"for key \" + clusterKey);\n throw new VoldemortException(e);\n } finally {\n metadataStore.writeLock.unlock();\n }\n }",
"public static final Duration parseDuration(String value)\n {\n return value == null ? null : Duration.getInstance(Double.parseDouble(value), TimeUnit.DAYS);\n }",
"public static final MVCArray buildArcPoints(LatLong center, double startBearing, double endBearing, double radius) {\n int points = DEFAULT_ARC_POINTS;\n\n MVCArray res = new MVCArray();\n\n if (startBearing > endBearing) {\n endBearing += 360.0;\n }\n double deltaBearing = endBearing - startBearing;\n deltaBearing = deltaBearing / points;\n for (int i = 0; (i < points + 1); i++) {\n res.push(center.getDestinationPoint(startBearing + i * deltaBearing, radius));\n }\n\n return res;\n\n }"
] |
Logic for timestamp
@param time Epoch date of creation
@return String timestamp | [
"String calculateDisplayTimestamp(long time){\n long now = System.currentTimeMillis()/1000;\n long diff = now-time;\n if(diff < 60){\n return \"Just Now\";\n }else if(diff > 60 && diff < 59*60){\n return (diff/(60)) + \" mins ago\";\n }else if(diff > 59*60 && diff < 23*59*60 ){\n return diff/(60*60) > 1 ? diff/(60*60) + \" hours ago\" : diff/(60*60) + \" hour ago\";\n }else if(diff > 24*60*60 && diff < 48*60*60){\n return \"Yesterday\";\n }else {\n @SuppressLint(\"SimpleDateFormat\")\n SimpleDateFormat sdf = new SimpleDateFormat(\"dd MMM\");\n return sdf.format(new Date(time));\n }\n }"
] | [
"public static double findMax( double[] u, int startU , int length ) {\n double max = -1;\n\n int index = startU*2;\n int stopIndex = (startU + length)*2;\n for( ; index < stopIndex;) {\n double real = u[index++];\n double img = u[index++];\n\n double val = real*real + img*img;\n\n if( val > max ) {\n max = val;\n }\n }\n\n return Math.sqrt(max);\n }",
"public Collection values()\r\n {\r\n if (values != null) return values;\r\n values = new AbstractCollection()\r\n {\r\n public int size()\r\n {\r\n return size;\r\n }\r\n\r\n public void clear()\r\n {\r\n ReferenceMap.this.clear();\r\n }\r\n\r\n public Iterator iterator()\r\n {\r\n return new ValueIterator();\r\n }\r\n };\r\n return values;\r\n }",
"public T copy() {\n T ret = createLike();\n ret.getMatrix().set(this.getMatrix());\n return ret;\n }",
"static Artifact resolveConstrained(MavenProject project, String gav, Pattern versionRegex,\n ArtifactResolver resolver)\n throws VersionRangeResolutionException, ArtifactResolutionException {\n boolean latest = gav.endsWith(\":LATEST\");\n if (latest || gav.endsWith(\":RELEASE\")) {\n Artifact a = new DefaultArtifact(gav);\n\n if (latest) {\n versionRegex = versionRegex == null ? ANY : versionRegex;\n } else {\n versionRegex = versionRegex == null ? ANY_NON_SNAPSHOT : versionRegex;\n }\n\n String upTo = project.getGroupId().equals(a.getGroupId()) && project.getArtifactId().equals(a.getArtifactId())\n ? project.getVersion()\n : null;\n\n return resolver.resolveNewestMatching(gav, upTo, versionRegex, latest, latest);\n } else {\n String projectGav = getProjectArtifactCoordinates(project, null);\n Artifact ret = null;\n\n if (projectGav.equals(gav)) {\n ret = findProjectArtifact(project);\n }\n\n return ret == null ? resolver.resolveArtifact(gav) : ret;\n }\n }",
"@RequestMapping(value = \"/api/profile/{profileIdentifier}/clients/delete\", method = RequestMethod.POST)\n public\n @ResponseBody\n HashMap<String, Object> deleteClient(Model model,\n @RequestParam(\"profileIdentifier\") String profileIdentifier,\n @RequestParam(\"clientUUID\") String[] clientUUID) throws Exception {\n\n logger.info(\"Attempting to remove clients from the profile: \", profileIdentifier);\n logger.info(\"Attempting to remove the following clients: {}\", Arrays.toString(clientUUID));\n\n HashMap<String, Object> valueHash = new HashMap<String, Object>();\n Integer profileId = ControllerUtils.convertProfileIdentifier(profileIdentifier);\n\n for( int i = 0; i < clientUUID.length; i++ )\n {\n if (clientUUID[i].compareTo(Constants.PROFILE_CLIENT_DEFAULT_ID) == 0)\n throw new Exception(\"Default client cannot be deleted\");\n\n clientService.remove(profileId, clientUUID[i]);\n }\n\n valueHash.put(\"clients\", clientService.findAllClients(profileId));\n return valueHash;\n }",
"private void saveToPropertyVfsBundle() throws CmsException {\n\n for (Locale l : m_changedTranslations) {\n SortedProperties props = m_localizations.get(l);\n LockedFile f = m_lockedBundleFiles.get(l);\n if ((null != props) && (null != f)) {\n try {\n ByteArrayOutputStream outputStream = new ByteArrayOutputStream();\n Writer writer = new OutputStreamWriter(outputStream, f.getEncoding());\n props.store(writer, null);\n byte[] contentBytes = outputStream.toByteArray();\n CmsFile file = f.getFile();\n file.setContents(contentBytes);\n String contentEncodingProperty = m_cms.readPropertyObject(\n file,\n CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING,\n false).getValue();\n if ((null == contentEncodingProperty) || !contentEncodingProperty.equals(f.getEncoding())) {\n m_cms.writePropertyObject(\n m_cms.getSitePath(file),\n new CmsProperty(\n CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING,\n f.getEncoding(),\n f.getEncoding()));\n }\n m_cms.writeFile(file);\n } catch (IOException e) {\n LOG.error(\n Messages.get().getBundle().key(\n Messages.ERR_READING_FILE_UNSUPPORTED_ENCODING_2,\n f.getFile().getRootPath(),\n f.getEncoding()),\n e);\n\n }\n }\n }\n }",
"private boolean initCheckTypeModifiers() {\n\n Class<?> classInfoclass = Reflections.loadClass(CLASSINFO_CLASS_NAME, new ClassLoaderResourceLoader(classFileServices.getClass().getClassLoader()));\n if (classInfoclass != null) {\n try {\n Method setFlags = AccessController.doPrivileged(GetDeclaredMethodAction.of(classInfoclass, \"setFlags\", short.class));\n return setFlags != null;\n } catch (Exception exceptionIgnored) {\n BootstrapLogger.LOG.usingOldJandexVersion();\n return false;\n }\n } else {\n return true;\n }\n }",
"@Override\n public void solve(DMatrixRBlock B, DMatrixRBlock X) {\n if( B.blockLength != blockLength )\n throw new IllegalArgumentException(\"Unexpected blocklength in B.\");\n\n DSubmatrixD1 L = new DSubmatrixD1(decomposer.getT(null));\n\n if( X != null ) {\n if( X.blockLength != blockLength )\n throw new IllegalArgumentException(\"Unexpected blocklength in X.\");\n if( X.numRows != L.col1 ) throw new IllegalArgumentException(\"Not enough rows in X\");\n }\n \n if( B.numRows != L.col1 ) throw new IllegalArgumentException(\"Not enough rows in B\");\n\n // L * L^T*X = B\n\n // Solve for Y: L*Y = B\n TriangularSolver_DDRB.solve(blockLength,false,L,new DSubmatrixD1(B),false);\n\n // L^T * X = Y\n TriangularSolver_DDRB.solve(blockLength,false,L,new DSubmatrixD1(B),true);\n\n if( X != null ) {\n // copy the solution from B into X\n MatrixOps_DDRB.extractAligned(B,X);\n }\n\n }",
"private JSONObject getARP(final Context context) {\n try {\n final String nameSpaceKey = getNamespaceARPKey();\n if (nameSpaceKey == null) return null;\n\n final SharedPreferences prefs = StorageHelper.getPreferences(context, nameSpaceKey);\n final Map<String, ?> all = prefs.getAll();\n final Iterator<? extends Map.Entry<String, ?>> iter = all.entrySet().iterator();\n\n while (iter.hasNext()) {\n final Map.Entry<String, ?> kv = iter.next();\n final Object o = kv.getValue();\n if (o instanceof Number && ((Number) o).intValue() == -1) {\n iter.remove();\n }\n }\n final JSONObject ret = new JSONObject(all);\n getConfigLogger().verbose(getAccountId(), \"Fetched ARP for namespace key: \" + nameSpaceKey + \" values: \" + all.toString());\n return ret;\n } catch (Throwable t) {\n getConfigLogger().verbose(getAccountId(), \"Failed to construct ARP object\", t);\n return null;\n }\n }"
] |
Deletes a user from an enterprise account.
@param notifyUser whether or not to send an email notification to the user that their account has been deleted.
@param force whether or not this user should be deleted even if they still own files. | [
"public void delete(boolean notifyUser, boolean force) {\n String queryString = new QueryStringBuilder()\n .appendParam(\"notify\", String.valueOf(notifyUser))\n .appendParam(\"force\", String.valueOf(force))\n .toString();\n\n URL url = USER_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), queryString, this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }"
] | [
"public static Long getSize(final File file){\n if ( file!=null && file.exists() ){\n return file.length();\n }\n return null;\n }",
"public static nslimitidentifier_stats get(nitro_service service, String name) throws Exception{\n\t\tnslimitidentifier_stats obj = new nslimitidentifier_stats();\n\t\tobj.set_name(name);\n\t\tnslimitidentifier_stats response = (nslimitidentifier_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"private static int skipEndOfLine(String text, int offset)\n {\n char c;\n boolean finished = false;\n\n while (finished == false)\n {\n c = text.charAt(offset);\n switch (c)\n {\n case ' ': // found that OBJDATA could be followed by a space the EOL\n case '\\r':\n case '\\n':\n {\n ++offset;\n break;\n }\n\n case '}':\n {\n offset = -1;\n finished = true;\n break;\n }\n\n default:\n {\n finished = true;\n break;\n }\n }\n }\n\n return (offset);\n }",
"protected int readShort(InputStream is) throws IOException\n {\n byte[] data = new byte[2];\n if (is.read(data) != data.length)\n {\n throw new EOFException();\n }\n\n return (MPPUtility.getShort(data, 0));\n }",
"public static HashMap<Integer, List<Integer>>\n getBalancedNumberOfPrimaryPartitionsPerNode(final Cluster nextCandidateCluster,\n Map<Integer, Integer> targetPartitionsPerZone) {\n HashMap<Integer, List<Integer>> numPartitionsPerNode = Maps.newHashMap();\n for(Integer zoneId: nextCandidateCluster.getZoneIds()) {\n List<Integer> partitionsOnNode = Utils.distributeEvenlyIntoList(nextCandidateCluster.getNumberOfNodesInZone(zoneId),\n targetPartitionsPerZone.get(zoneId));\n numPartitionsPerNode.put(zoneId, partitionsOnNode);\n }\n return numPartitionsPerNode;\n }",
"public static <T> List<T> makeList(T... items) {\r\n List<T> s = new ArrayList<T>(items.length);\r\n for (int i = 0; i < items.length; i++) {\r\n s.add(items[i]);\r\n }\r\n return s;\r\n }",
"public String getDependencyJsonModel() throws IOException {\n final Artifact artifact = DataModelFactory.createArtifact(\"\",\"\",\"\",\"\",\"\",\"\",\"\");\n return JsonUtils.serialize(DataModelFactory.createDependency(artifact, Scope.COMPILE));\n }",
"private Proctor getProctorNotNull() {\n final Proctor proctor = proctorLoader.get();\n if (proctor == null) {\n throw new IllegalStateException(\"Proctor specification and/or text matrix has not been loaded\");\n }\n return proctor;\n }",
"public static base_response update(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey updateresource = new sslcertkey();\n\t\tupdateresource.certkey = resource.certkey;\n\t\tupdateresource.expirymonitor = resource.expirymonitor;\n\t\tupdateresource.notificationperiod = resource.notificationperiod;\n\t\treturn updateresource.update_resource(client);\n\t}"
] |
Converts this IPv6 address segment into smaller segments,
copying them into the given array starting at the given index.
If a segment does not fit into the array because the segment index in the array is out of bounds of the array,
then it is not copied.
@param segs
@param index | [
"public <S extends AddressSegment> void getSplitSegments(S segs[], int index, AddressSegmentCreator<S> creator) {\r\n\t\tif(!isMultiple()) {\r\n\t\t\tint bitSizeSplit = IPv6Address.BITS_PER_SEGMENT >>> 1;\r\n\t\t\tInteger myPrefix = getSegmentPrefixLength();\r\n\t\t\tInteger highPrefixBits = getSplitSegmentPrefix(bitSizeSplit, myPrefix, 0);\r\n\t\t\tInteger lowPrefixBits = getSplitSegmentPrefix(bitSizeSplit, myPrefix, 1);\r\n\t\t\tif(index >= 0 && index < segs.length) {\r\n\t\t\t\tsegs[index] = creator.createSegment(highByte(), highPrefixBits);\r\n\t\t\t}\r\n\t\t\tif(++index >= 0 && index < segs.length) {\r\n\t\t\t\tsegs[index] = creator.createSegment(lowByte(), lowPrefixBits);\r\n\t\t\t}\r\n\t\t} else {\r\n\t\t\tgetSplitSegmentsMultiple(segs, index, creator);\r\n\t\t}\r\n\t}"
] | [
"private static int findNext(boolean reverse, int pos) {\n boolean backwards = IS_BACKWARDS_CHECKBOX.isSelected();\n backwards = backwards ? !reverse : reverse;\n\n String pattern = (String) FIND_FIELD.getSelectedItem();\n if (pattern != null && pattern.length() > 0) {\n try {\n Document doc = textComponent.getDocument();\n doc.getText(0, doc.getLength(), SEGMENT);\n }\n catch (Exception e) {\n // should NEVER reach here\n e.printStackTrace();\n }\n\n pos += textComponent.getSelectedText() == null ?\n (backwards ? -1 : 1) : 0;\n\n char first = backwards ?\n pattern.charAt(pattern.length() - 1) : pattern.charAt(0);\n char oppFirst = Character.isUpperCase(first) ?\n Character.toLowerCase(first) : Character.toUpperCase(first);\n int start = pos;\n boolean wrapped = WRAP_SEARCH_CHECKBOX.isSelected();\n int end = backwards ? 0 : SEGMENT.getEndIndex();\n pos += backwards ? -1 : 1;\n\n int length = textComponent.getDocument().getLength();\n if (pos > length) {\n pos = wrapped ? 0 : length;\n }\n\n boolean found = false;\n while (!found && (backwards ? pos > end : pos < end)) {\n found = !MATCH_CASE_CHECKBOX.isSelected() && SEGMENT.array[pos] == oppFirst;\n found = found ? found : SEGMENT.array[pos] == first;\n\n if (found) {\n pos += backwards ? -(pattern.length() - 1) : 0;\n for (int i = 0; found && i < pattern.length(); i++) {\n char c = pattern.charAt(i);\n found = SEGMENT.array[pos + i] == c;\n if (!MATCH_CASE_CHECKBOX.isSelected() && !found) {\n c = Character.isUpperCase(c) ?\n Character.toLowerCase(c) :\n Character.toUpperCase(c);\n found = SEGMENT.array[pos + i] == c;\n }\n }\n }\n\n if (!found) {\n pos += backwards ? -1 : 1;\n\n if (pos == end && wrapped) {\n pos = backwards ? SEGMENT.getEndIndex() : 0;\n end = start;\n wrapped = false;\n }\n }\n }\n pos = found ? pos : -1;\n }\n\n return pos;\n }",
"public static final String[] getRequiredSolrFields() {\n\n if (null == m_requiredSolrFields) {\n List<Locale> locales = OpenCms.getLocaleManager().getAvailableLocales();\n m_requiredSolrFields = new String[14 + (locales.size() * 6)];\n int count = 0;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_PATH;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_TYPE;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_DATE_CREATED;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_DATE_LASTMODIFIED;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_DATE_EXPIRED;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_DATE_RELEASED;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_SIZE;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_STATE;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_USER_CREATED;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_ID;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_USER_LAST_MODIFIED;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_ADDITIONAL_INFO;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_CONTAINER_TYPES;\n m_requiredSolrFields[count++] = CmsSearchField.FIELD_RESOURCE_LOCALES;\n for (Locale locale : locales) {\n m_requiredSolrFields[count++] = CmsSearchFieldConfiguration.getLocaleExtendedName(\n CmsSearchField.FIELD_TITLE_UNSTORED,\n locale.toString()) + \"_s\";\n m_requiredSolrFields[count++] = CmsSearchFieldConfiguration.getLocaleExtendedName(\n CmsPropertyDefinition.PROPERTY_TITLE,\n locale.toString()) + CmsSearchField.FIELD_DYNAMIC_PROPERTIES_DIRECT + \"_s\";\n m_requiredSolrFields[count++] = CmsPropertyDefinition.PROPERTY_TITLE\n + CmsSearchField.FIELD_DYNAMIC_PROPERTIES_DIRECT\n + \"_s\";\n m_requiredSolrFields[count++] = CmsSearchFieldConfiguration.getLocaleExtendedName(\n CmsSearchField.FIELD_DESCRIPTION,\n locale.toString()) + \"_s\";\n m_requiredSolrFields[count++] = CmsSearchFieldConfiguration.getLocaleExtendedName(\n CmsPropertyDefinition.PROPERTY_DESCRIPTION,\n locale.toString()) + CmsSearchField.FIELD_DYNAMIC_PROPERTIES + \"_s\";\n m_requiredSolrFields[count++] = CmsPropertyDefinition.PROPERTY_DESCRIPTION\n + CmsSearchField.FIELD_DYNAMIC_PROPERTIES\n + \"_s\";\n }\n }\n return m_requiredSolrFields;\n }",
"public void linkOneToMany(Object obj, CollectionDescriptor cod, boolean insert)\n {\n Object referencedObjects = cod.getPersistentField().get(obj);\n storeAndLinkOneToMany(true, obj, cod,referencedObjects, insert);\n }",
"private void deleteBackups() {\n File[] storeDirList = ReadOnlyUtils.getVersionDirs(storeDir, 0L, getCurrentVersionId());\n if(storeDirList != null && storeDirList.length > (numBackups + 1)) {\n // delete ALL old directories asynchronously\n File[] extraBackups = ReadOnlyUtils.findKthVersionedDir(storeDirList,\n 0,\n storeDirList.length\n - (numBackups + 1) - 1);\n if(extraBackups != null) {\n for(File backUpFile: extraBackups) {\n deleteAsync(backUpFile);\n }\n }\n }\n }",
"private void deliverMediaDetailsUpdate(final MediaDetails details) {\n for (MediaDetailsListener listener : getMediaDetailsListeners()) {\n try {\n listener.detailsAvailable(details);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering media details response to listener\", t);\n }\n }\n }",
"public void check(CollectionDescriptorDef collDef, String checkLevel) throws ConstraintException\r\n {\r\n ensureElementClassRef(collDef, checkLevel);\r\n checkInheritedForeignkey(collDef, checkLevel);\r\n ensureCollectionClass(collDef, checkLevel);\r\n checkProxyPrefetchingLimit(collDef, checkLevel);\r\n checkOrderby(collDef, checkLevel);\r\n checkQueryCustomizer(collDef, checkLevel);\r\n }",
"public static final String printExtendedAttributeDate(Date value)\n {\n return (value == null ? null : DATE_FORMAT.get().format(value));\n }",
"public boolean isDeleted(Identity id)\r\n {\r\n ObjectEnvelope envelope = buffer.getByIdentity(id);\r\n\r\n return (envelope != null && envelope.needsDelete());\r\n }",
"public void addBasicSentence(MtasCQLParserBasicSentenceCondition s)\n throws ParseException {\n if (!simplified) {\n List<MtasCQLParserBasicSentencePartCondition> newWordList = s\n .getPartList();\n partList.addAll(newWordList);\n } else {\n throw new ParseException(\"already simplified\");\n }\n }"
] |
Login for a specific authentication, creating a new token.
@param authentication authentication to assign to token
@return token | [
"public String login(Authentication authentication) {\n\t\tString token = getToken();\n\t\treturn login(token, authentication);\n\t}"
] | [
"public static void read(InputStream stream, byte[] buffer) throws IOException {\n int read = 0;\n while(read < buffer.length) {\n int newlyRead = stream.read(buffer, read, buffer.length - read);\n if(newlyRead == -1)\n throw new EOFException(\"Attempt to read \" + buffer.length\n + \" bytes failed due to EOF.\");\n read += newlyRead;\n }\n }",
"public boolean hasRequiredAdminProps() {\n boolean valid = true;\n valid &= hasRequiredClientProps();\n valid &= verifyStringPropSet(ACCUMULO_TABLE_PROP, ADMIN_ACCUMULO_TABLE_PROP);\n return valid;\n }",
"public void seekToMonth(String direction, String seekAmount, String month) {\n int seekAmountInt = Integer.parseInt(seekAmount);\n int monthInt = Integer.parseInt(month);\n assert(direction.equals(DIR_LEFT) || direction.equals(DIR_RIGHT));\n assert(monthInt >= 1 && monthInt <= 12);\n \n markDateInvocation();\n \n // set the day to the first of month. This step is necessary because if we seek to the \n // current day of a month whose number of days is less than the current day, we will \n // pushed into the next month.\n _calendar.set(Calendar.DAY_OF_MONTH, 1);\n \n // seek to the appropriate year\n if(seekAmountInt > 0) {\n int currentMonth = _calendar.get(Calendar.MONTH) + 1;\n int sign = direction.equals(DIR_RIGHT) ? 1 : -1;\n int numYearsToShift = seekAmountInt +\n (currentMonth == monthInt ? 0 : (currentMonth < monthInt ? sign > 0 ? -1 : 0 : sign > 0 ? 0 : -1));\n\n _calendar.add(Calendar.YEAR, (numYearsToShift * sign));\n }\n \n // now set the month\n _calendar.set(Calendar.MONTH, monthInt - 1);\n }",
"public long addAll(final String... members) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.sadd(getKey(), members);\n }\n });\n }",
"protected NodeData createBlockStyle()\n {\n NodeData ret = CSSFactory.createNodeData();\n TermFactory tf = CSSFactory.getTermFactory();\n ret.push(createDeclaration(\"display\", tf.createIdent(\"block\")));\n return ret;\n }",
"public static void addTTLIndex(DBCollection collection, String field, int ttl) {\n if (ttl <= 0) {\n throw new IllegalArgumentException(\"TTL must be positive\");\n }\n collection.createIndex(new BasicDBObject(field, 1), new BasicDBObject(\"expireAfterSeconds\", ttl));\n }",
"public Set<String> getConfiguredWorkplaceBundles() {\n\n CmsADEConfigData configData = internalLookupConfiguration(null, null);\n return configData.getConfiguredWorkplaceBundles();\n }",
"public long getLong(Integer type)\n {\n long result = 0;\n\n byte[] item = m_map.get(type);\n if (item != null)\n {\n result = MPPUtility.getLong6(item, 0);\n }\n\n return (result);\n }",
"public static Type[] getActualTypeArguments(Type type) {\n Type resolvedType = Types.getCanonicalType(type);\n if (resolvedType instanceof ParameterizedType) {\n return ((ParameterizedType) resolvedType).getActualTypeArguments();\n } else {\n return EMPTY_TYPES;\n }\n }"
] |
Resend the confirmation for a user to the given email.
@param email the email of the user.
@return A {@link Task} that completes when the resend request completes/fails. | [
"public Task<Void> resendConfirmationEmail(@NonNull final String email) {\n return dispatcher.dispatchTask(\n new Callable<Void>() {\n @Override\n public Void call() {\n resendConfirmationEmailInternal(email);\n return null;\n }\n });\n }"
] | [
"public void afterDeploymentValidation(@Observes @Priority(1) AfterDeploymentValidation event, BeanManager beanManager) {\n BeanManagerImpl manager = BeanManagerProxy.unwrap(beanManager);\n probe.init(manager);\n if (isJMXSupportEnabled(manager)) {\n try {\n MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();\n mbs.registerMBean(new ProbeDynamicMBean(jsonDataProvider, JsonDataProvider.class), constructProbeJsonDataMBeanName(manager, probe));\n } catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) {\n event.addDeploymentProblem(ProbeLogger.LOG.unableToRegisterMBean(JsonDataProvider.class, manager.getContextId(), e));\n }\n }\n addContainerLifecycleEvent(event, null, beanManager);\n exportDataIfNeeded(manager);\n }",
"public static LinearSolverDense<DMatrixRMaj> general(int numRows , int numCols ) {\n if( numRows == numCols )\n return linear(numRows);\n else\n return leastSquares(numRows,numCols);\n }",
"public int getChunkForKey(byte[] key) throws IllegalStateException {\n if(numChunks == 0) {\n throw new IllegalStateException(\"The ChunkedFileSet is closed.\");\n }\n\n switch(storageFormat) {\n case READONLY_V0: {\n return ReadOnlyUtils.chunk(ByteUtils.md5(key), numChunks);\n }\n case READONLY_V1: {\n if(nodePartitionIds == null) {\n throw new IllegalStateException(\"nodePartitionIds is null.\");\n }\n List<Integer> routingPartitionList = routingStrategy.getPartitionList(key);\n routingPartitionList.retainAll(nodePartitionIds);\n\n if(routingPartitionList.size() != 1) {\n throw new IllegalStateException(\"The key does not belong on this node.\");\n }\n\n return chunkIdToChunkStart.get(routingPartitionList.get(0))\n + ReadOnlyUtils.chunk(ByteUtils.md5(key),\n chunkIdToNumChunks.get(routingPartitionList.get(0)));\n }\n case READONLY_V2: {\n List<Integer> routingPartitionList = routingStrategy.getPartitionList(key);\n\n Pair<Integer, Integer> bucket = null;\n for(int replicaType = 0; replicaType < routingPartitionList.size(); replicaType++) {\n if(nodePartitionIds == null) {\n throw new IllegalStateException(\"nodePartitionIds is null.\");\n }\n if(nodePartitionIds.contains(routingPartitionList.get(replicaType))) {\n if(bucket == null) {\n bucket = Pair.create(routingPartitionList.get(0), replicaType);\n } else {\n throw new IllegalStateException(\"Found more than one replica for a given partition on the current node!\");\n }\n }\n }\n\n if(bucket == null) {\n throw new IllegalStateException(\"The key does not belong on this node.\");\n }\n\n Integer chunkStart = chunkIdToChunkStart.get(bucket);\n\n if (chunkStart == null) {\n throw new IllegalStateException(\"chunkStart is null.\");\n }\n\n return chunkStart + ReadOnlyUtils.chunk(ByteUtils.md5(key), chunkIdToNumChunks.get(bucket));\n }\n default: {\n throw new IllegalStateException(\"Unsupported storageFormat: \" + storageFormat);\n }\n }\n\n }",
"public static <GROUP extends Serializable> ExecutorConfig<GROUP> basicGroupable() {\n return new ExecutorConfig<GROUP>()\n .withTaskIdAdapter((TaskIdAdapter<Groupable<GROUP>, GROUP, ?>) new DefaultGroupableTaskIdAdapter<GROUP>());\n }",
"public void setPropertyDestinationType(Class<?> clazz, String propertyName,\r\n\t\t\tTypeReference<?> destinationType) {\r\n\t\tpropertiesDestinationTypes.put(new ClassProperty(clazz, propertyName), destinationType);\r\n\t}",
"@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 }",
"protected static InstallationModificationImpl.InstallationState load(final InstalledIdentity installedIdentity) throws IOException {\n final InstallationModificationImpl.InstallationState state = new InstallationModificationImpl.InstallationState();\n for (final Layer layer : installedIdentity.getLayers()) {\n state.putLayer(layer);\n }\n for (final AddOn addOn : installedIdentity.getAddOns()) {\n state.putAddOn(addOn);\n }\n return state;\n }",
"private void addResources(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (Resource resource : file.getResources())\n {\n final Resource r = resource;\n MpxjTreeNode childNode = new MpxjTreeNode(resource)\n {\n @Override public String toString()\n {\n return r.getName();\n }\n };\n parentNode.add(childNode);\n }\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 }"
] |
Add the string representation of the given object to this sequence. The given indentation will be prepended to
each line except the first one if the object has a multi-line string representation.
@param object
the appended object.
@param indentation
the indentation string that should be prepended. May not be <code>null</code>. | [
"public void append(Object object, String indentation) {\n\t\tappend(object, indentation, segments.size());\n\t}"
] | [
"public static SimpleMatrix wrap( Matrix internalMat ) {\n SimpleMatrix ret = new SimpleMatrix();\n ret.setMatrix(internalMat);\n return ret;\n }",
"public void disconnect() {\n\t\tif (sendThread != null) {\n\t\t\tsendThread.interrupt();\n\t\t\ttry {\n\t\t\t\tsendThread.join();\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t\tsendThread = null;\n\t\t}\n\t\tif (receiveThread != null) {\n\t\t\treceiveThread.interrupt();\n\t\t\ttry {\n\t\t\t\treceiveThread.join();\n\t\t\t} catch (InterruptedException e) {\n\t\t\t}\n\t\t\treceiveThread = null;\n\t\t}\n\t\tif(transactionCompleted.availablePermits() < 0)\n\t\t\ttransactionCompleted.release(transactionCompleted.availablePermits());\n\t\t\n\t\ttransactionCompleted.drainPermits();\n\t\tlogger.trace(\"Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\tif (this.serialPort != null) {\n\t\t\tthis.serialPort.close();\n\t\t\tthis.serialPort = null;\n\t\t}\n\t\tlogger.info(\"Disconnected from serial port\");\n\t}",
"public void addPostEffect(GVRMaterial postEffectData) {\n GVRContext ctx = getGVRContext();\n\n if (mPostEffects == null)\n {\n mPostEffects = new GVRRenderData(ctx, postEffectData);\n GVRMesh dummyMesh = new GVRMesh(getGVRContext(),\"float3 a_position float2 a_texcoord\");\n mPostEffects.setMesh(dummyMesh);\n NativeCamera.setPostEffect(getNative(), mPostEffects.getNative());\n mPostEffects.setCullFace(GVRRenderPass.GVRCullFaceEnum.None);\n }\n else\n {\n GVRRenderPass rpass = new GVRRenderPass(ctx, postEffectData);\n rpass.setCullFace(GVRRenderPass.GVRCullFaceEnum.None);\n mPostEffects.addPass(rpass);\n }\n }",
"public String getString(Integer offset)\n {\n String result = null;\n\n if (offset != null)\n {\n byte[] value = m_map.get(offset);\n if (value != null)\n {\n result = MPPUtility.getString(value, 0);\n }\n }\n\n return (result);\n }",
"@Override\n public FileModel resolvePayload(GraphRewrite event, EvaluationContext context, WindupVertexFrame payload)\n {\n checkVariableName(event, context);\n if (payload instanceof FileReferenceModel)\n {\n return ((FileReferenceModel) payload).getFile();\n }\n if (payload instanceof FileModel)\n {\n return (FileModel) payload;\n }\n return null;\n }",
"public BoxRetentionPolicyAssignment.Info assignTo(BoxFolder folder) {\r\n return BoxRetentionPolicyAssignment.createAssignmentToFolder(this.getAPI(), this.getID(), folder.getID());\r\n }",
"public synchronized HttpServer<Buffer, Buffer> start() throws Exception {\n\t\tif (server == null) {\n\t\t\tserver = createProtocolListener();\n\t\t}\n\t\treturn server;\n\t}",
"public String putDocument(Document document) {\n\t\tString key = UUID.randomUUID().toString();\n\t\tdocumentMap.put(key, document);\n\t\treturn key;\n\t}",
"private static ModelNode createOperation(ServerIdentity identity) {\n // The server address\n final ModelNode address = new ModelNode();\n address.add(ModelDescriptionConstants.HOST, identity.getHostName());\n address.add(ModelDescriptionConstants.RUNNING_SERVER, identity.getServerName());\n //\n final ModelNode operation = OPERATION.clone();\n operation.get(ModelDescriptionConstants.OP_ADDR).set(address);\n return operation;\n }"
] |
Create an element that represents a horizntal or vertical line.
@param x1
@param y1
@param x2
@param y2
@return the created DOM element | [
"protected Element createLineElement(float x1, float y1, float x2, float y2)\n {\n HtmlDivLine line = new HtmlDivLine(x1, y1, x2, y2);\n String color = colorString(getGraphicsState().getStrokingColor());\n\n StringBuilder pstyle = new StringBuilder(50);\n pstyle.append(\"left:\").append(style.formatLength(line.getLeft())).append(';');\n pstyle.append(\"top:\").append(style.formatLength(line.getTop())).append(';');\n pstyle.append(\"width:\").append(style.formatLength(line.getWidth())).append(';');\n pstyle.append(\"height:\").append(style.formatLength(line.getHeight())).append(';');\n pstyle.append(line.getBorderSide()).append(':').append(style.formatLength(line.getLineStrokeWidth())).append(\" solid \").append(color).append(';');\n if (line.getAngleDegrees() != 0)\n pstyle.append(\"transform:\").append(\"rotate(\").append(line.getAngleDegrees()).append(\"deg);\");\n\n Element el = doc.createElement(\"div\");\n el.setAttribute(\"class\", \"r\");\n el.setAttribute(\"style\", pstyle.toString());\n el.appendChild(doc.createEntityReference(\"nbsp\"));\n return el;\n }"
] | [
"public void setOfflineState(boolean setToOffline) {\n // acquire write lock\n writeLock.lock();\n try {\n String currentState = ByteUtils.getString(get(SERVER_STATE_KEY, null).get(0).getValue(),\n \"UTF-8\");\n if(setToOffline) {\n // from NORMAL_SERVER to OFFLINE_SERVER\n if(currentState.equals(VoldemortState.NORMAL_SERVER.toString())) {\n put(SERVER_STATE_KEY, VoldemortState.OFFLINE_SERVER);\n initCache(SERVER_STATE_KEY);\n put(SLOP_STREAMING_ENABLED_KEY, false);\n initCache(SLOP_STREAMING_ENABLED_KEY);\n put(PARTITION_STREAMING_ENABLED_KEY, false);\n initCache(PARTITION_STREAMING_ENABLED_KEY);\n put(READONLY_FETCH_ENABLED_KEY, false);\n initCache(READONLY_FETCH_ENABLED_KEY);\n } else if(currentState.equals(VoldemortState.OFFLINE_SERVER.toString())) {\n logger.warn(\"Already in OFFLINE_SERVER state.\");\n return;\n } else {\n logger.error(\"Cannot enter OFFLINE_SERVER state from \" + currentState);\n throw new VoldemortException(\"Cannot enter OFFLINE_SERVER state from \"\n + currentState);\n }\n } else {\n // from OFFLINE_SERVER to NORMAL_SERVER\n if(currentState.equals(VoldemortState.NORMAL_SERVER.toString())) {\n logger.warn(\"Already in NORMAL_SERVER state.\");\n return;\n } else if(currentState.equals(VoldemortState.OFFLINE_SERVER.toString())) {\n put(SERVER_STATE_KEY, VoldemortState.NORMAL_SERVER);\n initCache(SERVER_STATE_KEY);\n put(SLOP_STREAMING_ENABLED_KEY, true);\n initCache(SLOP_STREAMING_ENABLED_KEY);\n put(PARTITION_STREAMING_ENABLED_KEY, true);\n initCache(PARTITION_STREAMING_ENABLED_KEY);\n put(READONLY_FETCH_ENABLED_KEY, true);\n initCache(READONLY_FETCH_ENABLED_KEY);\n init();\n initNodeId(getNodeIdNoLock());\n } else {\n logger.error(\"Cannot enter NORMAL_SERVER state from \" + currentState);\n throw new VoldemortException(\"Cannot enter NORMAL_SERVER state from \"\n + currentState);\n }\n }\n } finally {\n writeLock.unlock();\n }\n }",
"public static Cluster greedyShufflePartitions(final Cluster nextCandidateCluster,\n final int greedyAttempts,\n final int greedySwapMaxPartitionsPerNode,\n final int greedySwapMaxPartitionsPerZone,\n List<Integer> greedySwapZoneIds,\n List<StoreDefinition> storeDefs) {\n List<Integer> zoneIds = null;\n if(greedySwapZoneIds.isEmpty()) {\n zoneIds = new ArrayList<Integer>(nextCandidateCluster.getZoneIds());\n } else {\n zoneIds = new ArrayList<Integer>(greedySwapZoneIds);\n }\n\n List<Integer> nodeIds = new ArrayList<Integer>();\n Cluster returnCluster = Cluster.cloneCluster(nextCandidateCluster);\n double currentUtility = new PartitionBalance(returnCluster, storeDefs).getUtility();\n\n for(int i = 0; i < greedyAttempts; i++) {\n\n // Iterate over zone ids to decide which node ids to include for\n // intra-zone swapping.\n // In future, if there is a need to support inter-zone swapping,\n // then just remove the\n // zone specific logic that populates nodeIdSet and add all nodes\n // from across all zones.\n\n int zoneIdOffset = i % zoneIds.size();\n Set<Integer> nodeIdSet = nextCandidateCluster.getNodeIdsInZone(zoneIds.get(zoneIdOffset));\n nodeIds = new ArrayList<Integer>(nodeIdSet);\n\n Collections.shuffle(zoneIds, new Random(System.currentTimeMillis()));\n Cluster shuffleResults = swapGreedyRandomPartitions(returnCluster,\n nodeIds,\n greedySwapMaxPartitionsPerNode,\n greedySwapMaxPartitionsPerZone,\n storeDefs);\n\n double nextUtility = new PartitionBalance(shuffleResults, storeDefs).getUtility();\n System.out.println(\"Swap improved max-min ratio: \" + currentUtility + \" -> \"\n + nextUtility + \" (swap attempt \" + i + \" in zone \"\n + zoneIds.get(zoneIdOffset) + \")\");\n returnCluster = shuffleResults;\n currentUtility = nextUtility;\n }\n return returnCluster;\n }",
"public static servicegroup_stats get(nitro_service service, String servicegroupname) throws Exception{\n\t\tservicegroup_stats obj = new servicegroup_stats();\n\t\tobj.set_servicegroupname(servicegroupname);\n\t\tservicegroup_stats response = (servicegroup_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"private Class getDynamicProxyClass(Class baseClass) {\r\n Class[] m_dynamicProxyClassInterfaces;\r\n if (foundInterfaces.containsKey(baseClass)) {\r\n m_dynamicProxyClassInterfaces = (Class[])foundInterfaces.get(baseClass);\r\n } else {\r\n m_dynamicProxyClassInterfaces = getInterfaces(baseClass);\r\n foundInterfaces.put(baseClass, m_dynamicProxyClassInterfaces);\r\n }\r\n\r\n // return dynymic Proxy Class implementing all interfaces\r\n Class proxyClazz = Proxy.getProxyClass(baseClass.getClassLoader(), m_dynamicProxyClassInterfaces);\r\n return proxyClazz;\r\n }",
"@Override\n\tpublic Object executeJavaScript(String code) throws CrawljaxException {\n\t\ttry {\n\t\t\tJavascriptExecutor js = (JavascriptExecutor) browser;\n\t\t\treturn js.executeScript(code);\n\t\t} catch (WebDriverException e) {\n\t\t\tthrowIfConnectionException(e);\n\t\t\tthrow new CrawljaxException(e);\n\t\t}\n\t}",
"public List<Formation> listFormation(String appName) {\n return connection.execute(new FormationList(appName), apiKey);\n }",
"private void checkObjectCache(ClassDescriptorDef classDef, String checkLevel) throws ConstraintException\r\n {\r\n if (!CHECKLEVEL_STRICT.equals(checkLevel))\r\n {\r\n return;\r\n }\r\n \r\n ObjectCacheDef objCacheDef = classDef.getObjectCache();\r\n\r\n if (objCacheDef == null)\r\n {\r\n return;\r\n }\r\n\r\n String objectCacheName = objCacheDef.getName();\r\n\r\n if ((objectCacheName == null) || (objectCacheName.length() == 0))\r\n {\r\n throw new ConstraintException(\"No class specified for the object-cache of class \"+classDef.getName());\r\n }\r\n\r\n try\r\n {\r\n InheritanceHelper helper = new InheritanceHelper();\r\n\r\n if (!helper.isSameOrSubTypeOf(objectCacheName, OBJECT_CACHE_INTERFACE))\r\n {\r\n throw new ConstraintException(\"The class \"+objectCacheName+\" specified as object-cache of class \"+classDef.getName()+\" does not implement the interface \"+OBJECT_CACHE_INTERFACE);\r\n }\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"Could not find the class \"+ex.getMessage()+\" on the classpath while checking the object-cache class \"+objectCacheName+\" of class \"+classDef.getName());\r\n }\r\n }",
"public static String flatten(String left, String right) {\n\t\treturn left == null || left.isEmpty() ? right : left + \".\" + right;\n\t}",
"private void reconnectFlows() {\n // create the reverse id map:\n for (Entry<Object, List<String>> entry : _outgoingFlows.entrySet()) {\n for (String flowId : entry.getValue()) {\n if (entry.getKey() instanceof SequenceFlow) { // if it is a sequence flow, we can tell its targets\n if (_idMap.get(flowId) instanceof FlowNode) {\n ((SequenceFlow) entry.getKey()).setTargetRef((FlowNode) _idMap.get(flowId));\n }\n if (_idMap.get(flowId) instanceof Association) {\n ((Association) _idMap.get(flowId)).setTargetRef((SequenceFlow) entry.getKey());\n }\n } else if (entry.getKey() instanceof Association) {\n ((Association) entry.getKey()).setTargetRef((BaseElement) _idMap.get(flowId));\n } else { // if it is a node, we can map it to its outgoing sequence flows\n if (_idMap.get(flowId) instanceof SequenceFlow) {\n ((FlowNode) entry.getKey()).getOutgoing().add((SequenceFlow) _idMap.get(flowId));\n } else if (_idMap.get(flowId) instanceof Association) {\n ((Association) _idMap.get(flowId)).setSourceRef((BaseElement) entry.getKey());\n }\n }\n }\n }\n }"
] |
Convenience method to convert a CSV string list to a set. Note that this
will suppress duplicates.
@param str the input String
@return a Set of String entries in the list | [
"public static Set<String> commaDelimitedListToSet(String str) {\n Set<String> set = new TreeSet<String>();\n String[] tokens = commaDelimitedListToStringArray(str);\n Collections.addAll(set, tokens);\n return set;\n }"
] | [
"@JmxGetter(name = \"avgFetchKeysNetworkTimeMs\", description = \"average time spent on network, for fetch keys\")\n public double getAvgFetchKeysNetworkTimeMs() {\n return networkTimeCounterMap.get(Operation.FETCH_KEYS).getAvgEventValue() / Time.NS_PER_MS;\n }",
"static InternationalFixedDate create(int prolepticYear, int month, int dayOfMonth) {\n YEAR_RANGE.checkValidValue(prolepticYear, ChronoField.YEAR_OF_ERA);\n MONTH_OF_YEAR_RANGE.checkValidValue(month, ChronoField.MONTH_OF_YEAR);\n DAY_OF_MONTH_RANGE.checkValidValue(dayOfMonth, ChronoField.DAY_OF_MONTH);\n\n if (dayOfMonth == DAYS_IN_LONG_MONTH && month != 6 && month != MONTHS_IN_YEAR) {\n throw new DateTimeException(\"Invalid date: \" + prolepticYear + '/' + month + '/' + dayOfMonth);\n }\n if (month == 6 && dayOfMonth == DAYS_IN_LONG_MONTH && !INSTANCE.isLeapYear(prolepticYear)) {\n throw new DateTimeException(\"Invalid Leap Day as '\" + prolepticYear + \"' is not a leap year\");\n }\n return new InternationalFixedDate(prolepticYear, month, dayOfMonth);\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 static XMLStreamException unexpectedAttribute(final XMLStreamReader reader, final int index) {\n return SecurityManagerLogger.ROOT_LOGGER.unexpectedAttribute(reader.getAttributeName(index), reader.getLocation());\n }",
"protected void loadEntries(final StorageAwareResource resource, final ZipInputStream zipIn) throws IOException {\n zipIn.getNextEntry();\n BufferedInputStream _bufferedInputStream = new BufferedInputStream(zipIn);\n this.readContents(resource, _bufferedInputStream);\n zipIn.getNextEntry();\n BufferedInputStream _bufferedInputStream_1 = new BufferedInputStream(zipIn);\n this.readResourceDescription(resource, _bufferedInputStream_1);\n if (this.storeNodeModel) {\n zipIn.getNextEntry();\n BufferedInputStream _bufferedInputStream_2 = new BufferedInputStream(zipIn);\n this.readNodeModel(resource, _bufferedInputStream_2);\n }\n }",
"public int getReplaceContextLength() {\n\t\tif (replaceContextLength == null) {\n\t\t\tint replacementOffset = getReplaceRegion().getOffset();\n\t\t\tITextRegion currentRegion = getCurrentNode().getTextRegion();\n\t\t\tint replaceContextLength = currentRegion.getLength() - (replacementOffset - currentRegion.getOffset());\n\t\t\tthis.replaceContextLength = replaceContextLength;\n\t\t\treturn replaceContextLength;\n\t\t}\n\t\treturn replaceContextLength.intValue();\n\t}",
"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 static base_response delete(nitro_service client, String domain) throws Exception {\n\t\tdnstxtrec deleteresource = new dnstxtrec();\n\t\tdeleteresource.domain = domain;\n\t\treturn deleteresource.delete_resource(client);\n\t}",
"public void setFieldByAlias(String alias, Object value)\n {\n set(getParentFile().getCustomFields().getFieldByAlias(FieldTypeClass.TASK, alias), value);\n }"
] |
Boot with the given operations, performing full model and capability registry validation.
@param bootOperations the operations. Cannot be {@code null}
@param rollbackOnRuntimeFailure {@code true} if the boot should fail if operations fail in the runtime stage
@return {@code true} if boot was successful
@throws ConfigurationPersistenceException | [
"protected boolean boot(List<ModelNode> bootOperations, boolean rollbackOnRuntimeFailure) throws ConfigurationPersistenceException {\n return boot(bootOperations, rollbackOnRuntimeFailure, false, ModelControllerImpl.getMutableRootResourceRegistrationProvider());\n }"
] | [
"public static boolean isBadXmlCharacter(char c) {\n boolean cDataCharacter = c < '\\u0020' && c != '\\t' && c != '\\r' && c != '\\n';\n cDataCharacter |= (c >= '\\uD800' && c < '\\uE000');\n cDataCharacter |= (c == '\\uFFFE' || c == '\\uFFFF');\n return cDataCharacter;\n }",
"private void readPage(byte[] buffer, Table table)\n {\n int magicNumber = getShort(buffer, 0);\n if (magicNumber == 0x4400)\n {\n //System.out.println(ByteArrayHelper.hexdump(buffer, 0, 6, true, 16, \"\"));\n int recordSize = m_definition.getRecordSize();\n RowValidator rowValidator = m_definition.getRowValidator();\n String primaryKeyColumnName = m_definition.getPrimaryKeyColumnName();\n\n int index = 6;\n while (index + recordSize <= buffer.length)\n {\n //System.out.println(ByteArrayHelper.hexdump(buffer, index, recordSize, true, 16, \"\"));\n int btrieveValue = getShort(buffer, index);\n if (btrieveValue != 0)\n {\n Map<String, Object> row = new HashMap<String, Object>();\n row.put(\"ROW_VERSION\", Integer.valueOf(btrieveValue));\n for (ColumnDefinition column : m_definition.getColumns())\n {\n Object value = column.read(index, buffer);\n //System.out.println(column.getName() + \": \" + value);\n row.put(column.getName(), value);\n }\n\n if (rowValidator == null || rowValidator.validRow(row))\n {\n table.addRow(primaryKeyColumnName, row);\n }\n }\n index += recordSize;\n }\n }\n }",
"public static Command newQuery(String identifier,\n String name,\n Object[] arguments) {\n return getCommandFactoryProvider().newQuery( identifier,\n name,\n arguments );\n }",
"public Map<String, String> getMapAttribute(String name, String defaultValue) {\n return mapSplit(getAttribute(name), defaultValue);\n }",
"public static authenticationlocalpolicy_authenticationvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationlocalpolicy_authenticationvserver_binding obj = new authenticationlocalpolicy_authenticationvserver_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationlocalpolicy_authenticationvserver_binding response[] = (authenticationlocalpolicy_authenticationvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public CollectionRequest<Task> findByTag(String tag) {\n \n String path = String.format(\"/tags/%s/tasks\", tag);\n return new CollectionRequest<Task>(this, Task.class, path, \"GET\");\n }",
"public static String convertToFileSystemChar(String name) {\n String erg = \"\";\n Matcher m = Pattern.compile(\"[a-z0-9 _#&@\\\\[\\\\(\\\\)\\\\]\\\\-\\\\.]\", Pattern.CASE_INSENSITIVE).matcher(name);\n while (m.find()) {\n erg += name.substring(m.start(), m.end());\n }\n if (erg.length() > 200) {\n erg = erg.substring(0, 200);\n System.out.println(\"cut filename: \" + erg);\n }\n return erg;\n }",
"public void clearSources()\n {\n synchronized (mAudioSources)\n {\n for (GVRAudioSource source : mAudioSources)\n {\n source.setListener(null);\n }\n mAudioSources.clear();\n }\n }",
"protected AbstractColumn buildSimpleBarcodeColumn() {\n\t\tBarCodeColumn column = new BarCodeColumn();\n\t\tpopulateCommonAttributes(column);\n\t\tcolumn.setColumnProperty(columnProperty);\n\t\tcolumn.setExpressionToGroupBy(customExpressionToGroupBy);\n\t\tcolumn.setScaleMode(imageScaleMode);\n\t\tcolumn.setApplicationIdentifier(applicationIdentifier);\n\t\tcolumn.setBarcodeType(barcodeType);\n\t\tcolumn.setShowText(showText);\n\t\tcolumn.setCheckSum(checkSum);\n\t\treturn column;\n\t}"
] |
Retrieves a thumbnail, or smaller image representation, of this file. Sizes of 32x32, 64x64, 128x128,
and 256x256 can be returned in the .png format and sizes of 32x32, 94x94, 160x160, and 320x320 can be returned
in the .jpg format.
@param fileType either PNG of JPG
@param minWidth minimum width
@param minHeight minimum height
@param maxWidth maximum width
@param maxHeight maximum height
@return the byte array of the thumbnail image | [
"public byte[] getThumbnail(ThumbnailFileType fileType, int minWidth, int minHeight, int maxWidth, int maxHeight) {\n QueryStringBuilder builder = new QueryStringBuilder();\n builder.appendParam(\"min_width\", minWidth);\n builder.appendParam(\"min_height\", minHeight);\n builder.appendParam(\"max_width\", maxWidth);\n builder.appendParam(\"max_height\", maxHeight);\n\n URLTemplate template;\n if (fileType == ThumbnailFileType.PNG) {\n template = GET_THUMBNAIL_PNG_TEMPLATE;\n } else if (fileType == ThumbnailFileType.JPG) {\n template = GET_THUMBNAIL_JPG_TEMPLATE;\n } else {\n throw new BoxAPIException(\"Unsupported thumbnail file type\");\n }\n URL url = template.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.getID());\n\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxAPIResponse response = request.send();\n\n ByteArrayOutputStream thumbOut = new ByteArrayOutputStream();\n InputStream body = response.getBody();\n byte[] buffer = new byte[BUFFER_SIZE];\n try {\n int n = body.read(buffer);\n while (n != -1) {\n thumbOut.write(buffer, 0, n);\n n = body.read(buffer);\n }\n } catch (IOException e) {\n throw new BoxAPIException(\"Error reading thumbnail bytes from response body\", e);\n } finally {\n response.disconnect();\n }\n\n return thumbOut.toByteArray();\n }"
] | [
"@Override\n public CopticDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\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 static <InnerT> Observable<InnerT> convertListToInnerAsync(Observable<List<InnerT>> innerList) {\n return innerList.flatMap(new Func1<List<InnerT>, Observable<InnerT>>() {\n @Override\n public Observable<InnerT> call(List<InnerT> inners) {\n return Observable.from(inners);\n }\n });\n }",
"@Override\n public void setBody(String body) {\n super.setBody(body);\n this.jsonValue = JsonValue.readFrom(body);\n }",
"public static void main(String[] args) {\r\n //Adding custom equivalence class generation transformer - NOTE this will get applied during graph traversal-->\r\n //MODEL USAGE EXAMPLE: <assign name=\"var_out_V1_2\" expr=\"%ssn\"/> <dg:transform name=\"EQ\"/>\r\n Map<String, DataTransformer> transformers = new HashMap<String, DataTransformer>();\r\n transformers.put(\"EQ\", new EquivalenceClassTransformer());\r\n Vector<CustomTagExtension> cte = new Vector<CustomTagExtension>();\r\n cte.add(new InLineTransformerExtension(transformers));\r\n Engine engine = new SCXMLEngine(cte);\n\r\n //will default to samplemachine, but you could specify a different file if you choose to\r\n InputStream is = CmdLine.class.getResourceAsStream(\"/\" + (args.length == 0 ? \"samplemachine\" : args[0]) + \".xml\");\n\r\n engine.setModelByInputFileStream(is);\n\r\n // Usually, this should be more than the number of threads you intend to run\r\n engine.setBootstrapMin(1);\n\r\n //Prepare the consumer with the proper writer and transformer\r\n DataConsumer consumer = new DataConsumer();\r\n consumer.addDataTransformer(new SampleMachineTransformer());\n\r\n //Adding custom equivalence class generation transformer - NOTE this will get applied post data generation.\r\n //MODEL USAGE EXAMPLE: <dg:assign name=\"var_out_V2\" set=\"%regex([0-9]{3}[A-Z0-9]{5})\"/>\r\n consumer.addDataTransformer(new EquivalenceClassTransformer());\n\r\n consumer.addDataWriter(new DefaultWriter(System.out,\r\n new String[]{\"var_1_1\", \"var_1_2\", \"var_1_3\", \"var_1_4\", \"var_1_5\", \"var_1_6\", \"var_1_7\",\r\n \"var_2_1\", \"var_2_2\", \"var_2_3\", \"var_2_4\", \"var_2_5\", \"var_2_6\", \"var_2_7\", \"var_2_8\"}));\n\r\n //Prepare the distributor\r\n DefaultDistributor defaultDistributor = new DefaultDistributor();\r\n defaultDistributor.setThreadCount(1);\r\n defaultDistributor.setDataConsumer(consumer);\r\n Logger.getLogger(\"org.apache\").setLevel(Level.WARN);\n\r\n engine.process(defaultDistributor);\r\n }",
"public static base_responses unset(nitro_service client, gslbservice resources[], String[] args) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbservice unsetresources[] = new gslbservice[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tunsetresources[i] = new gslbservice();\n\t\t\t\tunsetresources[i].servicename = resources[i].servicename;\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}",
"public void setOnQueryTextListener(@NonNull final SearchView.OnQueryTextListener listener) {\n if (searchView != null) {\n searchView.setOnQueryTextListener(listener);\n } else if (supportView != null) {\n supportView.setOnQueryTextListener(new android.support.v7.widget.SearchView.OnQueryTextListener() {\n @Override public boolean onQueryTextSubmit(String query) {\n return listener.onQueryTextSubmit(query);\n }\n\n @Override public boolean onQueryTextChange(String newText) {\n return listener.onQueryTextChange(newText);\n }\n });\n } else {\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }\n }",
"public void waitAndRetry() {\n ContinueToSendToBatchSenderAsstManager continueToSendToBatchSenderAsstManager = new ContinueToSendToBatchSenderAsstManager(\n processedWorkerCount);\n\n logger.debug(\"NOW WAIT Another \" + asstManagerRetryIntervalMillis\n + \" MS. at \" + PcDateUtils.getNowDateTimeStrStandard());\n getContext()\n .system()\n .scheduler()\n .scheduleOnce(\n Duration.create(asstManagerRetryIntervalMillis,\n TimeUnit.MILLISECONDS), getSelf(),\n continueToSendToBatchSenderAsstManager,\n getContext().system().dispatcher(), getSelf());\n return;\n }",
"private int indexFor(int hash)\r\n {\r\n // mix the bits to avoid bucket collisions...\r\n hash += ~(hash << 15);\r\n hash ^= (hash >>> 10);\r\n hash += (hash << 3);\r\n hash ^= (hash >>> 6);\r\n hash += ~(hash << 11);\r\n hash ^= (hash >>> 16);\r\n return hash & (table.length - 1);\r\n }"
] |
Write the patch.xml
@param rollbackPatch the patch
@param file the target file
@throws IOException | [
"static void writePatch(final Patch rollbackPatch, final File file) throws IOException {\n final File parent = file.getParentFile();\n if (!parent.isDirectory()) {\n if (!parent.mkdirs() && !parent.exists()) {\n throw PatchLogger.ROOT_LOGGER.cannotCreateDirectory(file.getAbsolutePath());\n }\n }\n try {\n try (final OutputStream os = new FileOutputStream(file)){\n PatchXml.marshal(os, rollbackPatch);\n }\n } catch (XMLStreamException e) {\n throw new IOException(e);\n }\n }"
] | [
"public TwoDHashMap<K2, K3, V> getAs2d(final K1 firstKey) {\n\t\tfinal HashMap<K2, HashMap<K3, V>> innerMap1 = map.get(firstKey);\n\t\tif( innerMap1 != null ) {\n\t\t\treturn new TwoDHashMap<K2, K3, V>(innerMap1);\n\t\t} else {\n\t\t\treturn new TwoDHashMap<K2, K3, V>();\n\t\t}\n\t\t\n\t}",
"@RequestMapping(value = \"/scripts\", method = RequestMethod.GET)\n public String scriptView(Model model) throws Exception {\n return \"script\";\n }",
"public static boolean isClosureDeclaration(ASTNode expression) {\r\n if (expression instanceof DeclarationExpression) {\r\n if (((DeclarationExpression) expression).getRightExpression() instanceof ClosureExpression) {\r\n return true;\r\n }\r\n }\r\n if (expression instanceof FieldNode) {\r\n ClassNode type = ((FieldNode) expression).getType();\r\n if (AstUtil.classNodeImplementsType(type, Closure.class)) {\r\n return true;\r\n } else if (((FieldNode) expression).getInitialValueExpression() instanceof ClosureExpression) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }",
"public static Object newInstance(String className, Class type, Object arg) throws InstantiationException,\r\n IllegalAccessException,\r\n IllegalArgumentException,\r\n InvocationTargetException,\r\n NoSuchMethodException,\r\n SecurityException,\r\n ClassNotFoundException\r\n {\r\n return newInstance(className, new Class[]{type}, new Object[]{arg});\r\n }",
"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 String getHeaderField(String fieldName) {\n // headers map is null for all regular response calls except when made as a batch request\n if (this.headers == null) {\n if (this.connection != null) {\n return this.connection.getHeaderField(fieldName);\n } else {\n return null;\n }\n } else {\n return this.headers.get(fieldName);\n }\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 }",
"public void reformatFile() throws IOException\n {\n List<LineNumberPosition> lineBrokenPositions = new ArrayList<>();\n List<String> brokenLines = breakLines(lineBrokenPositions);\n emitFormatted(brokenLines, lineBrokenPositions);\n }",
"public static void configure(Job conf, SimpleConfiguration props) {\n try {\n\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n props.save(baos);\n\n conf.getConfiguration().set(PROPS_CONF_KEY,\n new String(baos.toByteArray(), StandardCharsets.UTF_8));\n\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }"
] |
Use this API to fetch all the pqbinding resources that are configured on netscaler.
This uses pqbinding_args which is a way to provide additional arguments while fetching the resources. | [
"public static pqbinding[] get(nitro_service service, pqbinding_args args) throws Exception{\n\t\tpqbinding obj = new pqbinding();\n\t\toptions option = new options();\n\t\toption.set_args(nitro_util.object_to_string_withoutquotes(args));\n\t\tpqbinding[] response = (pqbinding[])obj.get_resources(service, option);\n\t\treturn response;\n\t}"
] | [
"public AT_Row setCharTranslator(CharacterTranslator charTranslator) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setCharTranslator(charTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}",
"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 }",
"public MapBounds getRotatedBoundsAdjustedForPreciseRotatedMapSize() {\n Rectangle2D.Double paintAreaPrecise = getRotatedMapSizePrecise();\n Rectangle paintArea = new Rectangle(MapfishMapContext.rectangleDoubleToDimension(paintAreaPrecise));\n return getRotatedBounds(paintAreaPrecise, paintArea);\n }",
"public static void registerTinyTypes(Class<?> head, Class<?>... tail) {\n final Set<HeaderDelegateProvider> systemRegisteredHeaderProviders = stealAcquireRefToHeaderDelegateProviders();\n register(head, systemRegisteredHeaderProviders);\n for (Class<?> tt : tail) {\n register(tt, systemRegisteredHeaderProviders);\n }\n }",
"public static <T> T columnStringToObject(Class<?> objClass, String str, Pattern delimiterPattern, String[] fieldNames)\r\n throws InstantiationException, IllegalAccessException, NoSuchMethodException, NoSuchFieldException, InvocationTargetException\r\n {\r\n String[] fields = delimiterPattern.split(str);\r\n T item = ErasureUtils.<T>uncheckedCast(objClass.newInstance());\r\n for (int i = 0; i < fields.length; i++) {\r\n try {\r\n Field field = objClass.getDeclaredField(fieldNames[i]);\r\n field.set(item, fields[i]);\r\n } catch (IllegalAccessException ex) {\r\n Method method = objClass.getDeclaredMethod(\"set\" + StringUtils.capitalize(fieldNames[i]), String.class);\r\n method.invoke(item, fields[i]);\r\n }\r\n }\r\n return item;\r\n }",
"public static Boolean assertFalse(Boolean value, String message) {\n if (Boolean.valueOf(value))\n throw new IllegalArgumentException(message);\n return value;\n }",
"public static DMatrixRMaj convert(DMatrixRBlock src , DMatrixRMaj dst )\n {\n return ConvertDMatrixStruct.convert(src,dst);\n }",
"public static void createUsers(GreenMailOperations greenMail, InternetAddress... addresses) {\n for (InternetAddress address : addresses) {\n greenMail.setUser(address.getAddress(), address.getAddress());\n }\n }",
"private void addTable(TableDef table)\r\n {\r\n table.setOwner(this);\r\n _tableDefs.put(table.getName(), table);\r\n }"
] |
Adding environment and system variables to build info.
@param builder | [
"@Override\n protected void addBuildInfoProperties(BuildInfoBuilder builder) {\n if (envVars != null) {\n for (Map.Entry<String, String> entry : envVars.entrySet()) {\n builder.addProperty(BuildInfoProperties.BUILD_INFO_ENVIRONMENT_PREFIX + entry.getKey(), entry.getValue());\n }\n }\n\n if (sysVars != null) {\n for (Map.Entry<String, String> entry : sysVars.entrySet()) {\n builder.addProperty(entry.getKey(), entry.getValue());\n }\n }\n }"
] | [
"public void transform(DataPipe cr) {\n for (Map.Entry<String, String> entry : cr.getDataMap().entrySet()) {\n String value = entry.getValue();\n\n if (value.equals(\"#{customplaceholder}\")) {\n // Generate a random number\n int ran = rand.nextInt();\n entry.setValue(String.valueOf(ran));\n }\n }\n }",
"private void writeStringField(String fieldName, Object value) throws IOException\n {\n String val = value.toString();\n if (!val.isEmpty())\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }",
"public static vpnclientlessaccesspolicy_binding get(nitro_service service, String name) throws Exception{\n\t\tvpnclientlessaccesspolicy_binding obj = new vpnclientlessaccesspolicy_binding();\n\t\tobj.set_name(name);\n\t\tvpnclientlessaccesspolicy_binding response = (vpnclientlessaccesspolicy_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public String addDependency(FunctionalTaskItem dependencyTaskItem) {\n IndexableTaskItem dependency = IndexableTaskItem.create(dependencyTaskItem);\n this.addDependency(dependency);\n return dependency.key();\n }",
"public static String get(String url, Map<String, String> customHeaders, Map<String, String> params) throws URISyntaxException, IOException, HTTPException {\n LOGGER.log(Level.INFO, \"Sending GET request to the url {0}\", url);\n\n URIBuilder uriBuilder = new URIBuilder(url);\n\n if (params != null && params.size() > 0) {\n for (Map.Entry<String, String> param : params.entrySet()) {\n uriBuilder.setParameter(param.getKey(), param.getValue());\n }\n }\n\n HttpGet httpGet = new HttpGet(uriBuilder.build());\n\n populateHeaders(httpGet, customHeaders);\n\n HttpClient httpClient = HttpClientBuilder.create().build();\n\n HttpResponse httpResponse = httpClient.execute(httpGet);\n\n int statusCode = httpResponse.getStatusLine().getStatusCode();\n if (isErrorStatus(statusCode)) {\n String jsonErrorResponse = EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);\n throw new HTTPException(statusCode, httpResponse.getStatusLine().getReasonPhrase(), jsonErrorResponse);\n }\n\n return EntityUtils.toString(httpResponse.getEntity(), StandardCharsets.UTF_8);\n }",
"private boolean hasPrimaryKey(T entity) {\n Object pk = getPrimaryKey(entity);\n if (pk == null) {\n return false;\n } else {\n if (pk instanceof Number && ((Number) pk).longValue() == 0) {\n return false;\n }\n }\n return true;\n }",
"public String getAuthorizationUrl(OAuth1RequestToken oAuthRequestToken, Permission permission) {\r\n\r\n OAuth10aService service = new ServiceBuilder(apiKey)\r\n .apiSecret(sharedSecret)\r\n .build(FlickrApi.instance());\r\n String authorizationUrl = service.getAuthorizationUrl(oAuthRequestToken);\r\n return String.format(\"%s&perms=%s\", authorizationUrl, permission.toString());\r\n }",
"protected <T1> void dispatchCommand(final BiConsumer<P, T1> action, final T1 routable1) {\n routingFor(routable1)\n .routees()\n .forEach(routee -> routee.receiveCommand(action, routable1));\n }",
"public final void setFindDetails(boolean findDetails) {\n this.findDetails.set(findDetails);\n if (findDetails) {\n primeCache(); // Get details for any tracks that were already loaded on players.\n } else {\n // Inform our listeners, on the proper thread, that the detailed waveforms are no longer available\n final Set<DeckReference> dyingCache = new HashSet<DeckReference>(detailHotCache.keySet());\n detailHotCache.clear();\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (DeckReference deck : dyingCache) {\n deliverWaveformDetailUpdate(deck.player, null);\n }\n }\n });\n }\n }"
] |
Requests the waveform preview for a specific track ID, given a connection to a player that has already been
set up.
@param rekordboxId the track whose waveform preview is desired
@param slot identifies the media slot we are querying
@param client the dbserver client that is communicating with the appropriate player
@return the retrieved waveform preview, or {@code null} if none was available
@throws IOException if there is a communication problem | [
"WaveformPreview getWaveformPreview(int rekordboxId, SlotReference slot, Client client)\n throws IOException {\n\n final NumberField idField = new NumberField(rekordboxId);\n\n // First try to get the NXS2-style color waveform if we are supposed to.\n if (preferColor.get()) {\n try {\n Message response = client.simpleRequest(Message.KnownType.ANLZ_TAG_REQ, Message.KnownType.ANLZ_TAG,\n client.buildRMST(Message.MenuIdentifier.MAIN_MENU, slot.slot), idField,\n new NumberField(Message.ANLZ_FILE_TAG_COLOR_WAVEFORM_PREVIEW), new NumberField(Message.ALNZ_FILE_TYPE_EXT));\n return new WaveformPreview(new DataReference(slot, rekordboxId), response);\n } catch (Exception e) {\n logger.info(\"No color waveform preview available for slot \" + slot + \", id \" + rekordboxId + \"; requesting blue version.\", e);\n }\n\n }\n\n Message response = client.simpleRequest(Message.KnownType.WAVE_PREVIEW_REQ, Message.KnownType.WAVE_PREVIEW,\n client.buildRMST(Message.MenuIdentifier.DATA, slot.slot), NumberField.WORD_1,\n idField, NumberField.WORD_0);\n return new WaveformPreview(new DataReference(slot, rekordboxId), response);\n }"
] | [
"private static Class<?> extractTypeFromClass(Class<?> clazz, Class<?> source, int typeIndex,\n\t\t\tMap<TypeVariable, Type> typeVariableMap, Map<Integer, Integer> typeIndexesPerLevel,\n\t\t\tint nestingLevel, int currentLevel) {\n\n\t\tif (clazz.getName().startsWith(\"java.util.\")) {\n\t\t\treturn null;\n\t\t}\n\t\tif (clazz.getSuperclass() != null && isIntrospectionCandidate(clazz.getSuperclass())) {\n\t\t\ttry {\n\t\t\t\treturn extractType(clazz.getGenericSuperclass(), source, typeIndex, typeVariableMap,\n\t\t\t\t\t\ttypeIndexesPerLevel, nestingLevel, currentLevel);\n\t\t\t}\n\t\t\tcatch (MalformedParameterizedTypeException ex) {\n\t\t\t\t// from getGenericSuperclass() - ignore and continue with interface introspection\n\t\t\t}\n\t\t}\n\t\tType[] ifcs = clazz.getGenericInterfaces();\n\t\tif (ifcs != null) {\n\t\t\tfor (Type ifc : ifcs) {\n\t\t\t\tType rawType = ifc;\n\t\t\t\tif (ifc instanceof ParameterizedType) {\n\t\t\t\t\trawType = ((ParameterizedType) ifc).getRawType();\n\t\t\t\t}\n\t\t\t\tif (rawType instanceof Class && isIntrospectionCandidate((Class) rawType)) {\n\t\t\t\t\treturn extractType(ifc, source, typeIndex, typeVariableMap, typeIndexesPerLevel, nestingLevel, currentLevel);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn null;\n\t}",
"public T build() throws IllegalAccessException, IOException, InvocationTargetException {\n generatedConfigutation = new CubeContainer();\n\n findContainerName();\n // if needed, prepare prepare resources required to build a docker image\n prepareImageBuild();\n // instantiate container object\n instantiateContainerObject();\n // enrich container object (without cube instance)\n enrichContainerObjectBeforeCube();\n // extract configuration from container object class\n extractConfigurationFromContainerObject();\n // merge received configuration with extracted configuration\n mergeContainerObjectConfiguration();\n // create/start/register associated cube\n initializeCube();\n // enrich container object (with cube instance)\n enrichContainerObjectWithCube();\n // return created container object\n return containerObjectInstance;\n }",
"public static<T> Vendor<T> vendor(Func0<T> f) {\n\treturn j.vendor(f);\n }",
"public void prepareFilter( float transition ) {\n try {\n method.invoke( filter, new Object[] { new Float( transition ) } );\n }\n catch ( Exception e ) {\n throw new IllegalArgumentException(\"Error setting value for property: \"+property);\n }\n\t}",
"@Override\n public final boolean getBool(final int i) {\n try {\n return this.array.getBoolean(i);\n } catch (JSONException e) {\n throw new ObjectMissingException(this, \"[\" + i + \"]\");\n }\n }",
"public static BoxAPIConnection restore(String clientID, String clientSecret, String state) {\n BoxAPIConnection api = new BoxAPIConnection(clientID, clientSecret);\n api.restore(state);\n return api;\n }",
"public static Credential getServiceAccountCredential(String serviceAccountId,\n String privateKeyFile, Collection<String> serviceAccountScopes)\n throws GeneralSecurityException, IOException {\n return getCredentialBuilderWithoutPrivateKey(serviceAccountId, serviceAccountScopes)\n .setServiceAccountPrivateKeyFromP12File(new File(privateKeyFile))\n .build();\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 static base_response add(nitro_service client, vpnsessionaction resource) throws Exception {\n\t\tvpnsessionaction addresource = new vpnsessionaction();\n\t\taddresource.name = resource.name;\n\t\taddresource.httpport = resource.httpport;\n\t\taddresource.winsip = resource.winsip;\n\t\taddresource.dnsvservername = resource.dnsvservername;\n\t\taddresource.splitdns = resource.splitdns;\n\t\taddresource.sesstimeout = resource.sesstimeout;\n\t\taddresource.clientsecurity = resource.clientsecurity;\n\t\taddresource.clientsecuritygroup = resource.clientsecuritygroup;\n\t\taddresource.clientsecuritymessage = resource.clientsecuritymessage;\n\t\taddresource.clientsecuritylog = resource.clientsecuritylog;\n\t\taddresource.splittunnel = resource.splittunnel;\n\t\taddresource.locallanaccess = resource.locallanaccess;\n\t\taddresource.rfc1918 = resource.rfc1918;\n\t\taddresource.spoofiip = resource.spoofiip;\n\t\taddresource.killconnections = resource.killconnections;\n\t\taddresource.transparentinterception = resource.transparentinterception;\n\t\taddresource.windowsclienttype = resource.windowsclienttype;\n\t\taddresource.defaultauthorizationaction = resource.defaultauthorizationaction;\n\t\taddresource.authorizationgroup = resource.authorizationgroup;\n\t\taddresource.clientidletimeout = resource.clientidletimeout;\n\t\taddresource.proxy = resource.proxy;\n\t\taddresource.allprotocolproxy = resource.allprotocolproxy;\n\t\taddresource.httpproxy = resource.httpproxy;\n\t\taddresource.ftpproxy = resource.ftpproxy;\n\t\taddresource.socksproxy = resource.socksproxy;\n\t\taddresource.gopherproxy = resource.gopherproxy;\n\t\taddresource.sslproxy = resource.sslproxy;\n\t\taddresource.proxyexception = resource.proxyexception;\n\t\taddresource.proxylocalbypass = resource.proxylocalbypass;\n\t\taddresource.clientcleanupprompt = resource.clientcleanupprompt;\n\t\taddresource.forcecleanup = resource.forcecleanup;\n\t\taddresource.clientoptions = resource.clientoptions;\n\t\taddresource.clientconfiguration = resource.clientconfiguration;\n\t\taddresource.sso = resource.sso;\n\t\taddresource.ssocredential = resource.ssocredential;\n\t\taddresource.windowsautologon = resource.windowsautologon;\n\t\taddresource.usemip = resource.usemip;\n\t\taddresource.useiip = resource.useiip;\n\t\taddresource.clientdebug = resource.clientdebug;\n\t\taddresource.loginscript = resource.loginscript;\n\t\taddresource.logoutscript = resource.logoutscript;\n\t\taddresource.homepage = resource.homepage;\n\t\taddresource.icaproxy = resource.icaproxy;\n\t\taddresource.wihome = resource.wihome;\n\t\taddresource.citrixreceiverhome = resource.citrixreceiverhome;\n\t\taddresource.wiportalmode = resource.wiportalmode;\n\t\taddresource.clientchoices = resource.clientchoices;\n\t\taddresource.epaclienttype = resource.epaclienttype;\n\t\taddresource.iipdnssuffix = resource.iipdnssuffix;\n\t\taddresource.forcedtimeout = resource.forcedtimeout;\n\t\taddresource.forcedtimeoutwarning = resource.forcedtimeoutwarning;\n\t\taddresource.ntdomain = resource.ntdomain;\n\t\taddresource.clientlessvpnmode = resource.clientlessvpnmode;\n\t\taddresource.emailhome = resource.emailhome;\n\t\taddresource.clientlessmodeurlencoding = resource.clientlessmodeurlencoding;\n\t\taddresource.clientlesspersistentcookie = resource.clientlesspersistentcookie;\n\t\taddresource.allowedlogingroups = resource.allowedlogingroups;\n\t\taddresource.securebrowse = resource.securebrowse;\n\t\taddresource.storefronturl = resource.storefronturl;\n\t\taddresource.kcdaccount = resource.kcdaccount;\n\t\treturn addresource.add_resource(client);\n\t}"
] |
This function computes which reduce task to shuffle a record to. | [
"public int getPartition(byte[] key,\n byte[] value,\n int numReduceTasks) {\n try {\n /**\n * {@link partitionId} is the Voldemort primary partition that this\n * record belongs to.\n */\n int partitionId = ByteUtils.readInt(value, ByteUtils.SIZE_OF_INT);\n\n /**\n * This is the base number we will ultimately mod by {@link numReduceTasks}\n * to determine which reduce task to shuffle to.\n */\n int magicNumber = partitionId;\n\n if (getSaveKeys() && !buildPrimaryReplicasOnly) {\n /**\n * When saveKeys is enabled (which also implies we are generating\n * READ_ONLY_V2 format files), then we are generating files with\n * a replica type, with one file per replica.\n *\n * Each replica is sent to a different reducer, and thus the\n * {@link magicNumber} is scaled accordingly.\n *\n * The downside to this is that it is pretty wasteful. The files\n * generated for each replicas are identical to one another, so\n * there's no point in generating them independently in many\n * reducers.\n *\n * This is one of the reasons why buildPrimaryReplicasOnly was\n * written. In this mode, we only generate the files for the\n * primary replica, which means the number of reducers is\n * minimized and {@link magicNumber} does not need to be scaled.\n */\n int replicaType = (int) ByteUtils.readBytes(value,\n 2 * ByteUtils.SIZE_OF_INT,\n ByteUtils.SIZE_OF_BYTE);\n magicNumber = magicNumber * getStoreDef().getReplicationFactor() + replicaType;\n }\n\n if (!getReducerPerBucket()) {\n /**\n * Partition files can be split in many chunks in order to limit the\n * maximum file size downloaded and handled by Voldemort servers.\n *\n * {@link chunkId} represents which chunk of partition then current\n * record belongs to.\n */\n int chunkId = ReadOnlyUtils.chunk(key, getNumChunks());\n\n /**\n * When reducerPerBucket is disabled, all chunks are sent to a\n * different reducer. This increases parallelism at the expense\n * of adding more load on Hadoop.\n *\n * {@link magicNumber} is thus scaled accordingly, in order to\n * leverage the extra reducers available to us.\n */\n magicNumber = magicNumber * getNumChunks() + chunkId;\n }\n\n /**\n * Finally, we mod {@link magicNumber} by {@link numReduceTasks},\n * since the MapReduce framework expects the return of this function\n * to be bounded by the number of reduce tasks running in the job.\n */\n return magicNumber % numReduceTasks;\n } catch (Exception e) {\n throw new VoldemortException(\"Caught exception in getPartition()!\" +\n \" key: \" + ByteUtils.toHexString(key) +\n \", value: \" + ByteUtils.toHexString(value) +\n \", numReduceTasks: \" + numReduceTasks, e);\n }\n }"
] | [
"public static HashMap<Integer, List<Integer>>\n getBalancedNumberOfPrimaryPartitionsPerNode(final Cluster nextCandidateCluster,\n Map<Integer, Integer> targetPartitionsPerZone) {\n HashMap<Integer, List<Integer>> numPartitionsPerNode = Maps.newHashMap();\n for(Integer zoneId: nextCandidateCluster.getZoneIds()) {\n List<Integer> partitionsOnNode = Utils.distributeEvenlyIntoList(nextCandidateCluster.getNumberOfNodesInZone(zoneId),\n targetPartitionsPerZone.get(zoneId));\n numPartitionsPerNode.put(zoneId, partitionsOnNode);\n }\n return numPartitionsPerNode;\n }",
"public static final String getString(byte[] data, int offset)\n {\n return getString(data, offset, data.length - offset);\n }",
"protected boolean hasPermissions(CmsObject cms, CmsSolrDocument doc, CmsResourceFilter filter) {\r\n\r\n return null != (filter == null ? getResource(cms, doc) : getResource(cms, doc, filter));\r\n }",
"public Collection<License> getInfo() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_INFO);\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 List<License> licenses = new ArrayList<License>();\r\n Element licensesElement = response.getPayload();\r\n NodeList licenseElements = licensesElement.getElementsByTagName(\"license\");\r\n for (int i = 0; i < licenseElements.getLength(); i++) {\r\n Element licenseElement = (Element) licenseElements.item(i);\r\n License license = new License();\r\n license.setId(licenseElement.getAttribute(\"id\"));\r\n license.setName(licenseElement.getAttribute(\"name\"));\r\n license.setUrl(licenseElement.getAttribute(\"url\"));\r\n licenses.add(license);\r\n }\r\n return licenses;\r\n }",
"@Pure\n\tpublic static <K, V> Map<K, V> operator_minus(Map<K, V> map, final K key) {\n\t\treturn Maps.filterKeys(map, new Predicate<K>() {\n\t\t\t@Override\n\t\t\tpublic boolean apply(K input) {\n\t\t\t\treturn !Objects.equal(input, key);\n\t\t\t}\n\t\t});\n\t}",
"public Jar addPackageOf(Class<?> clazz, Filter filter) throws IOException {\n try {\n final String path = clazz.getPackage().getName().replace('.', '/');\n URL dirURL = clazz.getClassLoader().getResource(path);\n if (dirURL != null && dirURL.getProtocol().equals(\"file\"))\n addDir(Paths.get(path), Paths.get(dirURL.toURI()), filter, false);\n else {\n if (dirURL == null) // In case of a jar file, we can't actually find a directory.\n dirURL = clazz.getClassLoader().getResource(clazz.getName().replace('.', '/') + \".class\");\n\n if (dirURL.getProtocol().equals(\"jar\")) {\n final URI jarUri = new URI(dirURL.getPath().substring(0, dirURL.getPath().indexOf('!')));\n try (JarInputStream jis1 = newJarInputStream(Files.newInputStream(Paths.get(jarUri)))) {\n for (JarEntry entry; (entry = jis1.getNextJarEntry()) != null;) {\n try {\n if (entry.getName().startsWith(path + '/')) {\n if (filter == null || filter.filter(entry.getName()))\n addEntryNoClose(jos, entry.getName(), jis1);\n }\n } catch (ZipException e) {\n if (!e.getMessage().startsWith(\"duplicate entry\"))\n throw e;\n }\n }\n }\n } else\n throw new AssertionError();\n }\n return this;\n } catch (URISyntaxException e) {\n throw new AssertionError(e);\n }\n }",
"public LayoutScroller.ScrollableList getPageScrollable() {\n return new LayoutScroller.ScrollableList() {\n\n @Override\n public int getScrollingItemsCount() {\n return MultiPageWidget.super.getScrollingItemsCount();\n }\n\n @Override\n public float getViewPortWidth() {\n return MultiPageWidget.super.getViewPortWidth();\n }\n\n @Override\n public float getViewPortHeight() {\n return MultiPageWidget.super.getViewPortHeight();\n }\n\n @Override\n public float getViewPortDepth() {\n return MultiPageWidget.super.getViewPortDepth();\n }\n\n @Override\n public boolean scrollToPosition(int pos, final LayoutScroller.OnScrollListener listener) {\n return MultiPageWidget.super.scrollToPosition(pos, listener);\n }\n\n @Override\n public boolean scrollByOffset(float xOffset, float yOffset, float zOffset,\n final LayoutScroller.OnScrollListener listener) {\n return MultiPageWidget.super.scrollByOffset(xOffset, yOffset, zOffset, listener);\n }\n\n @Override\n public void registerDataSetObserver(DataSetObserver observer) {\n MultiPageWidget.super.registerDataSetObserver(observer);\n }\n\n @Override\n public void unregisterDataSetObserver(DataSetObserver observer) {\n MultiPageWidget.super.unregisterDataSetObserver(observer);\n }\n\n @Override\n public int getCurrentPosition() {\n return MultiPageWidget.super.getCurrentPosition();\n }\n\n };\n }",
"private void addDownloadButton(final CmsLogFileView view) {\n\n Button button = CmsToolBar.createButton(\n FontOpenCms.DOWNLOAD,\n CmsVaadinUtils.getMessageText(Messages.GUI_LOGFILE_DOWNLOAD_0));\n button.addClickListener(new ClickListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n Window window = CmsBasicDialog.prepareWindow(CmsBasicDialog.DialogWidth.wide);\n window.setCaption(CmsVaadinUtils.getMessageText(Messages.GUI_LOGFILE_DOWNLOAD_0));\n window.setContent(new CmsLogDownloadDialog(window, view.getCurrentFile()));\n A_CmsUI.get().addWindow(window);\n }\n });\n m_uiContext.addToolbarButton(button);\n }",
"public static Map<String,List<Long>> readHints(File hints) throws IOException {\n Map<String,List<Long>> result = new HashMap<>();\n InputStream is = new FileInputStream(hints);\n mergeHints(is, result);\n return result;\n }"
] |
This method is called if the data set has been changed. Subclasses might want to override
this method to add some extra logic.
Go through all items in the list:
- reuse the existing views in the list
- add new views in the list if needed
- trim the unused views
- request re-layout
@param preferableCenterPosition the preferable center position. If it is -1 - keep the
current center position. | [
"private void onChangedImpl(final int preferableCenterPosition) {\n for (ListOnChangedListener listener: mOnChangedListeners) {\n listener.onChangedStart(this);\n }\n\n Log.d(Log.SUBSYSTEM.LAYOUT, TAG, \"onChangedImpl(%s): items [%d] views [%d] mLayouts.size() = %d \" +\n \"preferableCenterPosition = %d\",\n getName(), getDataCount(), getViewCount(), mContent.mLayouts.size(), preferableCenterPosition);\n\n // TODO: selectively recycle data based on the changes in the data set\n mPreferableCenterPosition = preferableCenterPosition;\n recycleChildren();\n }"
] | [
"public static base_response unset(nitro_service client, sslcertkey resource, String[] args) throws Exception{\n\t\tsslcertkey unsetresource = new sslcertkey();\n\t\tunsetresource.certkey = resource.certkey;\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"public void fire(TestCaseStartedEvent event) {\n //init root step in parent thread if needed\n stepStorage.get();\n\n TestCaseResult testCase = testCaseStorage.get();\n event.process(testCase);\n\n synchronized (TEST_SUITE_ADD_CHILD_LOCK) {\n testSuiteStorage.get(event.getSuiteUid()).getTestCases().add(testCase);\n }\n\n notifier.fire(event);\n }",
"public boolean shouldIncrementVersionBasedOnResources(CmsObject cms) throws CmsException {\n\n if (m_checkpointTime == 0) {\n return true;\n }\n\n // adjust the site root, if necessary\n CmsObject cmsClone = adjustSiteRootIfNecessary(cms, this);\n\n // calculate the module resources\n List<CmsResource> moduleResources = calculateModuleResources(cmsClone, this);\n\n for (CmsResource resource : moduleResources) {\n try {\n List<CmsResource> resourcesToCheck = Lists.newArrayList();\n resourcesToCheck.add(resource);\n if (resource.isFolder()) {\n resourcesToCheck.addAll(cms.readResources(resource, CmsResourceFilter.IGNORE_EXPIRATION, true));\n }\n for (CmsResource resourceToCheck : resourcesToCheck) {\n if (resourceToCheck.getDateLastModified() > m_checkpointTime) {\n return true;\n }\n }\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n continue;\n }\n }\n return false;\n }",
"public OperationTransformerRegistry resolveServer(final ModelVersion mgmtVersion, final ModelNode subsystems) {\n return resolveServer(mgmtVersion, resolveVersions(subsystems));\n }",
"private void readAssignment(Resource resource, Assignment assignment)\n {\n Task task = m_activityMap.get(assignment.getActivity());\n if (task != null)\n {\n task.addResourceAssignment(resource);\n }\n }",
"public static base_response unset(nitro_service client, nsconfig resource, String[] args) throws Exception{\n\t\tnsconfig unsetresource = new nsconfig();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}",
"protected void mergeHardcodedResultsFrom(Configuration otherConfiguration) {\r\n Map<Dotted, AnalysisResult> resultsMap = hardcodedResults.build().stream()\r\n .collect(Collectors.toMap(r -> r.className, r -> r));\r\n resultsMap.putAll(otherConfiguration.hardcodedResults());\r\n hardcodedResults = ImmutableSet.<AnalysisResult>builder().addAll(resultsMap.values());\r\n }",
"@Override public Object instantiateItem(ViewGroup parent, int position) {\n T content = getItem(position);\n rendererBuilder.withContent(content);\n rendererBuilder.withParent(parent);\n rendererBuilder.withLayoutInflater(LayoutInflater.from(parent.getContext()));\n Renderer<T> renderer = rendererBuilder.build();\n if (renderer == null) {\n throw new NullRendererBuiltException(\"RendererBuilder have to return a not null Renderer\");\n }\n updateRendererExtraValues(content, renderer, position);\n renderer.render();\n View view = renderer.getRootView();\n parent.addView(view);\n return view;\n }",
"public FastTrackTable getTable(FastTrackTableType type)\n {\n FastTrackTable result = m_tables.get(type);\n if (result == null)\n {\n result = EMPTY_TABLE;\n }\n return result;\n }"
] |
Checks all data sets in IIM records 1, 2 and 3 for constraint violations.
@return list of constraint violations, empty set if IIM file is valid | [
"public Set<ConstraintViolation> validate() {\r\n\t\tSet<ConstraintViolation> errors = new LinkedHashSet<ConstraintViolation>();\r\n\t\tfor (int record = 1; record <= 3; ++record) {\r\n\t\t\terrors.addAll(validate(record));\r\n\t\t}\r\n\t\treturn errors;\r\n\t}"
] | [
"public static base_response add(nitro_service client, linkset resource) throws Exception {\n\t\tlinkset addresource = new linkset();\n\t\taddresource.id = resource.id;\n\t\treturn addresource.add_resource(client);\n\t}",
"private void registerColumns() {\n\t\tfor (int i = 0; i < cols.length; i++) {\n\t\t\tDJCrosstabColumn crosstabColumn = cols[i];\n\n\t\t\tJRDesignCrosstabColumnGroup ctColGroup = new JRDesignCrosstabColumnGroup();\n\t\t\tctColGroup.setName(crosstabColumn.getProperty().getProperty());\n\t\t\tctColGroup.setHeight(crosstabColumn.getHeaderHeight());\n\n\t\t\tJRDesignCrosstabBucket bucket = new JRDesignCrosstabBucket();\n\n bucket.setValueClassName(crosstabColumn.getProperty().getValueClassName());\n\n\t\t\tJRDesignExpression bucketExp = ExpressionUtils.createExpression(\"$F{\"+crosstabColumn.getProperty().getProperty()+\"}\", crosstabColumn.getProperty().getValueClassName());\n\t\t\tbucket.setExpression(bucketExp);\n\n\t\t\tctColGroup.setBucket(bucket);\n\n\t\t\tJRDesignCellContents colHeaerContent = new JRDesignCellContents();\n\t\t\tJRDesignTextField colTitle = new JRDesignTextField();\n\n\t\t\tJRDesignExpression colTitleExp = new JRDesignExpression();\n\t\t\tcolTitleExp.setValueClassName(crosstabColumn.getProperty().getValueClassName());\n\t\t\tcolTitleExp.setText(\"$V{\"+crosstabColumn.getProperty().getProperty()+\"}\");\n\n\n\t\t\tcolTitle.setExpression(colTitleExp);\n\t\t\tcolTitle.setWidth(crosstabColumn.getWidth());\n\t\t\tcolTitle.setHeight(crosstabColumn.getHeaderHeight());\n\n\t\t\t//The height can be the sum of the heights of all the columns starting from the current one, up to the inner most one.\n\t\t\tint auxWidth = calculateRowHeaderMaxWidth(crosstabColumn);\n\t\t\tcolTitle.setWidth(auxWidth);\n\n\t\t\tStyle headerstyle = crosstabColumn.getHeaderStyle() == null ? this.djcross.getColumnHeaderStyle(): crosstabColumn.getHeaderStyle();\n\n\t\t\tif (headerstyle != null){\n\t\t\t\tlayoutManager.applyStyleToElement(headerstyle,colTitle);\n\t\t\t\tcolHeaerContent.setBackcolor(headerstyle.getBackgroundColor());\n\t\t\t}\n\n\n\t\t\tcolHeaerContent.addElement(colTitle);\n\t\t\tcolHeaerContent.setMode( ModeEnum.OPAQUE );\n\n\t\t\tboolean fullBorder = i <= 0; //Only outer most will have full border\n\t\t\tapplyCellBorder(colHeaerContent, fullBorder, false);\n\n\t\t\tctColGroup.setHeader(colHeaerContent);\n\n\t\t\tif (crosstabColumn.isShowTotals())\n\t\t\t\tcreateColumTotalHeader(ctColGroup,crosstabColumn,fullBorder);\n\n\n\t\t\ttry {\n\t\t\t\tjrcross.addColumnGroup(ctColGroup);\n\t\t\t} catch (JRException e) {\n\t\t\t\tlog.error(e.getMessage(),e);\n\t\t\t}\n\t\t}\n\t}",
"public ParallelTaskBuilder prepareHttpGet(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n \n cb.getHttpMeta().setHttpMethod(HttpMethod.GET);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n \n return cb;\n }",
"public static responderglobal_responderpolicy_binding[] get(nitro_service service) throws Exception{\n\t\tresponderglobal_responderpolicy_binding obj = new responderglobal_responderpolicy_binding();\n\t\tresponderglobal_responderpolicy_binding response[] = (responderglobal_responderpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static boolean isValidFqcn(String str) {\n if (isNullOrEmpty(str)) {\n return false;\n }\n final String[] parts = str.split(\"\\\\.\");\n if (parts.length < 2) {\n return false;\n }\n for (String part : parts) {\n if (!isValidJavaIdentifier(part)) {\n return false;\n }\n }\n return true;\n }",
"void fileWritten() throws ConfigurationPersistenceException {\n if (!doneBootup.get() || interactionPolicy.isReadOnly()) {\n return;\n }\n try {\n FilePersistenceUtils.copyFile(mainFile, lastFile);\n } catch (IOException e) {\n throw ControllerLogger.ROOT_LOGGER.failedToBackup(e, mainFile);\n }\n }",
"@RequestMapping(value = \"/api/profile\", method = RequestMethod.DELETE)\n public\n @ResponseBody\n HashMap<String, Object> deleteProfile(Model model, int id) throws Exception {\n profileService.remove(id);\n return Utils.getJQGridJSON(profileService.findAllProfiles(), \"profiles\");\n }",
"private boolean isRedeployAfterRemoval(ModelNode operation) {\n return operation.hasDefined(DEPLOYMENT_OVERLAY_LINK_REMOVAL) &&\n operation.get(DEPLOYMENT_OVERLAY_LINK_REMOVAL).asBoolean();\n }",
"public ProjectCalendarHours getHours(Day day)\n {\n ProjectCalendarHours result = getCalendarHours(day);\n if (result == null)\n {\n //\n // If this is a base calendar and we have no hours, then we\n // have a problem - so we add the default hours and try again\n //\n if (m_parent == null)\n {\n // Only add default hours for the day that is 'missing' to avoid overwriting real calendar hours\n addDefaultCalendarHours(day);\n result = getCalendarHours(day);\n }\n else\n {\n result = m_parent.getHours(day);\n }\n }\n return result;\n }"
] |
Implements getAll by delegating to get. | [
"public static <K, V, T> Map<K, List<Versioned<V>>> getAll(Store<K, V, T> storageEngine,\n Iterable<K> keys,\n Map<K, T> transforms) {\n Map<K, List<Versioned<V>>> result = newEmptyHashMap(keys);\n for(K key: keys) {\n List<Versioned<V>> value = storageEngine.get(key,\n transforms != null ? transforms.get(key)\n : null);\n if(!value.isEmpty())\n result.put(key, value);\n }\n return result;\n }"
] | [
"public void writeTo(File file) throws IOException {\n FileChannel channel = new FileOutputStream(file).getChannel();\n try {\n writeTo(channel);\n } finally {\n channel.close();\n }\n }",
"public static <T> T columnStringToObject(Class objClass, String str, String delimiterRegex, String[] fieldNames)\r\n throws InstantiationException, IllegalAccessException, NoSuchFieldException, NoSuchMethodException, InvocationTargetException\r\n {\r\n Pattern delimiterPattern = Pattern.compile(delimiterRegex);\r\n return StringUtils.<T>columnStringToObject(objClass, str, delimiterPattern, fieldNames);\r\n }",
"public void addColumn(ColumnDef columnDef)\r\n {\r\n columnDef.setOwner(this);\r\n _columns.put(columnDef.getName(), columnDef);\r\n }",
"public void enableUniformSize(final boolean enable) {\n if (mUniformSize != enable) {\n mUniformSize = enable;\n if (mContainer != null) {\n mContainer.onLayoutChanged(this);\n }\n }\n }",
"public List<TimephasedWork> getTimephasedOvertimeWork()\n {\n if (m_timephasedOvertimeWork == null && m_timephasedWork != null && getOvertimeWork() != null)\n {\n double perDayFactor = getRemainingOvertimeWork().getDuration() / (getRemainingWork().getDuration() - getRemainingOvertimeWork().getDuration());\n double totalFactor = getRemainingOvertimeWork().getDuration() / getRemainingWork().getDuration();\n\n perDayFactor = Double.isNaN(perDayFactor) ? 0 : perDayFactor;\n totalFactor = Double.isNaN(totalFactor) ? 0 : totalFactor;\n\n m_timephasedOvertimeWork = new DefaultTimephasedWorkContainer(m_timephasedWork, perDayFactor, totalFactor);\n }\n return m_timephasedOvertimeWork == null ? null : m_timephasedOvertimeWork.getData();\n }",
"@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<JulianDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<JulianDate>) super.zonedDateTime(temporal);\n }",
"protected Class<?> loadClass(String clazz) throws ClassNotFoundException {\n\t\tif (this.classLoader == null){\n\t\t\treturn Class.forName(clazz);\n\t\t}\n\n\t\treturn Class.forName(clazz, true, this.classLoader);\n\n\t}",
"private void populateRecurringTask(Record record, RecurringTask task) throws MPXJException\n {\n //System.out.println(record);\n task.setStartDate(record.getDateTime(1));\n task.setFinishDate(record.getDateTime(2));\n task.setDuration(RecurrenceUtility.getDuration(m_projectFile.getProjectProperties(), record.getInteger(3), record.getInteger(4)));\n task.setOccurrences(record.getInteger(5));\n task.setRecurrenceType(RecurrenceUtility.getRecurrenceType(record.getInteger(6)));\n task.setUseEndDate(NumberHelper.getInt(record.getInteger(8)) == 1);\n task.setWorkingDaysOnly(NumberHelper.getInt(record.getInteger(9)) == 1);\n task.setWeeklyDaysFromBitmap(RecurrenceUtility.getDays(record.getString(10)), RecurrenceUtility.RECURRING_TASK_DAY_MASKS);\n\n RecurrenceType type = task.getRecurrenceType();\n if (type != null)\n {\n switch (task.getRecurrenceType())\n {\n case DAILY:\n {\n task.setFrequency(record.getInteger(13));\n break;\n }\n\n case WEEKLY:\n {\n task.setFrequency(record.getInteger(14));\n break;\n }\n\n case MONTHLY:\n {\n task.setRelative(NumberHelper.getInt(record.getInteger(11)) == 1);\n if (task.getRelative())\n {\n task.setFrequency(record.getInteger(17));\n task.setDayNumber(record.getInteger(15));\n task.setDayOfWeek(RecurrenceUtility.getDay(record.getInteger(16)));\n }\n else\n {\n task.setFrequency(record.getInteger(19));\n task.setDayNumber(record.getInteger(18));\n }\n break;\n }\n\n case YEARLY:\n {\n task.setRelative(NumberHelper.getInt(record.getInteger(12)) != 1);\n if (task.getRelative())\n {\n task.setDayNumber(record.getInteger(20));\n task.setDayOfWeek(RecurrenceUtility.getDay(record.getInteger(21)));\n task.setMonthNumber(record.getInteger(22));\n }\n else\n {\n task.setYearlyAbsoluteFromDate(record.getDateTime(23));\n }\n break;\n }\n }\n }\n\n //System.out.println(task);\n }",
"protected void deliverLifecycleAnnouncement(final Logger logger, final boolean starting) {\n new Thread(new Runnable() {\n @Override\n public void run() {\n for (final LifecycleListener listener : getLifecycleListeners()) {\n try {\n if (starting) {\n listener.started(LifecycleParticipant.this);\n } else {\n listener.stopped(LifecycleParticipant.this);\n }\n } catch (Throwable t) {\n logger.warn(\"Problem delivering lifecycle announcement to listener\", t);\n }\n }\n }\n }, \"Lifecycle announcement delivery\").start();\n }"
] |
Removes a design document from the database.
@param id the document id (optionally prefixed with "_design/")
@return {@link DesignDocument} | [
"public Response remove(String id) {\r\n assertNotEmpty(id, \"id\");\r\n id = ensureDesignPrefix(id);\r\n String revision = null;\r\n // Get the revision ID from ETag, removing leading and trailing \"\r\n revision = client.executeRequest(Http.HEAD(new DatabaseURIHelper(db.getDBUri()\r\n ).documentUri(id))).getConnection().getHeaderField(\"ETag\");\r\n if (revision != null) {\r\n revision = revision.substring(1, revision.length() - 1);\r\n return db.remove(id, revision);\r\n } else {\r\n throw new CouchDbException(\"No ETag header found for design document with id \" + id);\r\n }\r\n }"
] | [
"public boolean classifySentenceStdin(DocumentReaderAndWriter<IN> readerWriter)\r\n throws IOException\r\n {\r\n BufferedReader is = new BufferedReader(new InputStreamReader(System.in, flags.inputEncoding));\r\n String line;\r\n String text = \"\";\r\n String eol = \"\\n\";\r\n String sentence = \"<s>\";\r\n while ((line = is.readLine()) != null) {\r\n \t\r\n if (line.trim().equals(\"\")) {\r\n \t text += sentence + eol;\r\n \t ObjectBank<List<IN>> documents = makeObjectBankFromString(text, readerWriter);\r\n classifyAndWriteAnswers(documents, readerWriter);\r\n text = \"\";\r\n } else {\r\n \t text += line + eol;\r\n }\r\n }\r\n if (text.trim().equals(\"\")) {\r\n \treturn false;\r\n }\r\n return true;\r\n }",
"public static RgbaColor fromHex(String hex) {\n if (hex.length() == 0 || hex.charAt(0) != '#') return getDefaultColor();\n\n // #rgb\n if (hex.length() == 4) {\n\n return new RgbaColor(parseHex(hex, 1, 2),\n parseHex(hex, 2, 3),\n parseHex(hex, 3, 4));\n\n }\n // #rrggbb\n else if (hex.length() == 7) {\n\n return new RgbaColor(parseHex(hex, 1, 3),\n parseHex(hex, 3, 5),\n parseHex(hex, 5, 7));\n\n }\n else {\n return getDefaultColor();\n }\n }",
"public EndpointOverride getPath(int pathId, String clientUUID, String[] filters) throws Exception {\n EndpointOverride endpoint = null;\n PreparedStatement statement = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n String queryString = this.getPathSelectString();\n queryString += \" AND \" + Constants.DB_TABLE_PATH + \".\" + Constants.GENERIC_ID + \"=\" + pathId + \";\";\n statement = sqlConnection.prepareStatement(queryString);\n statement.setString(1, clientUUID);\n\n results = statement.executeQuery();\n\n if (results.next()) {\n endpoint = this.getEndpointOverrideFromResultSet(results);\n endpoint.setFilters(filters);\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 (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n\n return endpoint;\n }",
"public static appfwpolicylabel_binding get(nitro_service service, String labelname) throws Exception{\n\t\tappfwpolicylabel_binding obj = new appfwpolicylabel_binding();\n\t\tobj.set_labelname(labelname);\n\t\tappfwpolicylabel_binding response = (appfwpolicylabel_binding) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public void removeAllAnimations() {\n for (int i = 0, size = mAnimationList.size(); i < size; i++) {\n mAnimationList.get(i).removeAnimationListener(mAnimationListener);\n }\n mAnimationList.clear();\n }",
"@JsonProperty(\"labels\")\n @JsonInclude(Include.NON_EMPTY)\n public Map<String, TermImpl> getLabelUpdates() {\n \treturn getMonolingualUpdatedValues(newLabels);\n }",
"public void read(File file, Table table) throws IOException\n {\n //System.out.println(\"Reading \" + file.getName());\n InputStream is = null;\n try\n {\n is = new FileInputStream(file);\n read(is, table);\n }\n\n finally\n {\n StreamHelper.closeQuietly(is);\n }\n }",
"public int getCurrentPage() {\n int currentPage = 1;\n int count = mScrollable.getScrollingItemsCount();\n if (mSupportScrollByPage && mCurrentItemIndex >= 0 &&\n mCurrentItemIndex < count) {\n currentPage = (Math.min(mCurrentItemIndex + mPageSize - 1, count - 1)/mPageSize);\n }\n return currentPage;\n }",
"private void recordRollbackLoader(final String patchId, PatchableTarget.TargetInfo target) {\n // setup the content loader paths\n final DirectoryStructure structure = target.getDirectoryStructure();\n final InstalledImage image = structure.getInstalledImage();\n final File historyDir = image.getPatchHistoryDir(patchId);\n final File miscRoot = new File(historyDir, PatchContentLoader.MISC);\n final File modulesRoot = structure.getModulePatchDirectory(patchId);\n final File bundlesRoot = structure.getBundlesPatchDirectory(patchId);\n final PatchContentLoader loader = PatchContentLoader.create(miscRoot, bundlesRoot, modulesRoot);\n //\n recordContentLoader(patchId, loader);\n }"
] |
Takes a numeric string value and converts it to a integer between 0 and 100.
returns 0 if the string is not numeric.
@param percentage - A numeric string value
@return a integer between 0 and 100 | [
"public static int getPercentage(String percentage) {\n if (isNotEmpty(percentage) && isNumeric(percentage)) {\n int p = Integer.parseInt(percentage);\n return p;\n } else {\n return 0;\n }\n }"
] | [
"private TransactionManager getTransactionManager()\r\n {\r\n TransactionManager retval = null;\r\n try\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"getTransactionManager called\");\r\n retval = TransactionManagerFactoryFactory.instance().getTransactionManager();\r\n }\r\n catch (TransactionManagerFactoryException e)\r\n {\r\n log.warn(\"Exception trying to obtain TransactionManager from Factory\", e);\r\n e.printStackTrace();\r\n }\r\n return retval;\r\n }",
"public int compareTo(WordLemmaTag wordLemmaTag) {\r\n int first = word().compareTo(wordLemmaTag.word());\r\n if (first != 0)\r\n return first;\r\n int second = lemma().compareTo(wordLemmaTag.lemma());\r\n if (second != 0)\r\n return second;\r\n else\r\n return tag().compareTo(wordLemmaTag.tag());\r\n }",
"private void processFile(InputStream is) throws MPXJException\n {\n int line = 1;\n\n try\n {\n //\n // Test the header and extract the separator. If this is successful,\n // we reset the stream back as far as we can. The design of the\n // BufferedInputStream class means that we can't get back to character\n // zero, so the first record we will read will get \"RMHDR\" rather than\n // \"ERMHDR\" in the first field position.\n //\n BufferedInputStream bis = new BufferedInputStream(is);\n byte[] data = new byte[6];\n data[0] = (byte) bis.read();\n bis.mark(1024);\n bis.read(data, 1, 5);\n\n if (!new String(data).equals(\"ERMHDR\"))\n {\n throw new MPXJException(MPXJException.INVALID_FILE);\n }\n\n bis.reset();\n\n InputStreamReader reader = new InputStreamReader(bis, getCharset());\n Tokenizer tk = new ReaderTokenizer(reader);\n tk.setDelimiter('\\t');\n List<String> record = new ArrayList<String>();\n\n while (tk.getType() != Tokenizer.TT_EOF)\n {\n readRecord(tk, record);\n if (!record.isEmpty())\n {\n if (processRecord(record))\n {\n break;\n }\n }\n ++line;\n }\n }\n\n catch (Exception ex)\n {\n throw new MPXJException(MPXJException.READ_ERROR + \" (failed at line \" + line + \")\", ex);\n }\n }",
"public PartialCollection<BoxItem.Info> getItemsRange(long offset, long limit, String... fields) {\n QueryStringBuilder builder = new QueryStringBuilder()\n .appendParam(\"offset\", offset)\n .appendParam(\"limit\", limit);\n\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields).toString();\n }\n\n URL url = GET_COLLECTION_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> items = new PartialCollection<BoxItem.Info>(offset, limit, fullSize);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue entry : entries) {\n BoxItem.Info entryInfo = (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), entry.asObject());\n if (entryInfo != null) {\n items.add(entryInfo);\n }\n }\n return items;\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 }",
"public GVRShaderId getShaderType(Class<? extends GVRShader> shaderClass)\n {\n GVRShaderId shaderId = mShaderTemplates.get(shaderClass);\n\n if (shaderId == null)\n {\n GVRContext ctx = getGVRContext();\n shaderId = new GVRShaderId(shaderClass);\n mShaderTemplates.put(shaderClass, shaderId);\n shaderId.getTemplate(ctx);\n }\n return shaderId;\n }",
"@Override\n public boolean postExecute(MavenBuildProxy build, MavenProject pom, MojoInfo mojo, BuildListener listener,\n Throwable error) {\n //listener.getLogger().println(\"[MavenDependenciesRecorder] mojo: \" + mojo.getClass() + \":\" + mojo.getGoal());\n //listener.getLogger().println(\"[MavenDependenciesRecorder] dependencies: \" + pom.getArtifacts());\n recordMavenDependencies(pom.getArtifacts());\n return true;\n }",
"private void registerPackageInTypeInterestFactory(String pkg)\n {\n TypeInterestFactory.registerInterest(pkg + \"_pkg\", pkg.replace(\".\", \"\\\\.\"), pkg, TypeReferenceLocation.IMPORT);\n // TODO: Finish the implementation\n }",
"@Override\n public void registerAttributes(ManagementResourceRegistration resourceRegistration) {\n for (AttributeAccess attr : attributes.values()) {\n resourceRegistration.registerReadOnlyAttribute(attr.getAttributeDefinition(), null);\n }\n }"
] |
Use this API to unset the properties of ipv6 resource.
Properties that need to be unset are specified in args array. | [
"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 void dumpKnownFieldMaps(Props props)\n {\n //for (int key=131092; key < 131098; key++)\n for (int key = 50331668; key < 50331674; key++)\n {\n byte[] fieldMapData = props.getByteArray(Integer.valueOf(key));\n if (fieldMapData != null)\n {\n System.out.println(\"KEY: \" + key);\n createFieldMap(fieldMapData);\n System.out.println(toString());\n clear();\n }\n }\n }",
"public static RebalanceTaskInfoMap encodeRebalanceTaskInfoMap(RebalanceTaskInfo stealInfo) {\n return RebalanceTaskInfoMap.newBuilder()\n .setStealerId(stealInfo.getStealerId())\n .setDonorId(stealInfo.getDonorId())\n .addAllPerStorePartitionIds(ProtoUtils.encodeStoreToPartitionsTuple(stealInfo.getStoreToPartitionIds()))\n .setInitialCluster(new ClusterMapper().writeCluster(stealInfo.getInitialCluster()))\n .build();\n }",
"static GVRCollider lookup(long nativePointer)\n {\n synchronized (sColliders)\n {\n WeakReference<GVRCollider> weakReference = sColliders.get(nativePointer);\n return weakReference == null ? null : weakReference.get();\n }\n }",
"public void close() {\n Iterator<SocketDestination> it = getStatsMap().keySet().iterator();\n while(it.hasNext()) {\n try {\n SocketDestination destination = it.next();\n JmxUtils.unregisterMbean(JmxUtils.createObjectName(JmxUtils.getPackageName(ClientRequestExecutor.class),\n \"stats_\"\n + destination.toString()\n .replace(':',\n '_')\n + identifierString));\n } catch(Exception e) {}\n }\n }",
"private void processCalendars() throws IOException\n {\n CalendarReader reader = new CalendarReader(m_data.getTableData(\"Calendars\"));\n reader.read();\n\n for (MapRow row : reader.getRows())\n {\n processCalendar(row);\n }\n\n m_project.setDefaultCalendar(m_calendarMap.get(reader.getDefaultCalendarUUID()));\n }",
"public Style createStyle(final List<Rule> styleRules) {\n final Rule[] rulesArray = styleRules.toArray(new Rule[0]);\n final FeatureTypeStyle featureTypeStyle = this.styleBuilder.createFeatureTypeStyle(null, rulesArray);\n final Style style = this.styleBuilder.createStyle();\n style.featureTypeStyles().add(featureTypeStyle);\n return style;\n }",
"protected void threadWatch(final ConnectionHandle c) {\r\n\t\tthis.threadFinalizableRefs.put(c, new FinalizableWeakReference<Thread>(Thread.currentThread(), this.finalizableRefQueue) {\r\n\t\t\tpublic void finalizeReferent() {\r\n\t\t\t\t\ttry {\r\n\t\t\t\t\t\tif (!CachedConnectionStrategy.this.pool.poolShuttingDown){\r\n\t\t\t\t\t\t\tlogger.debug(\"Monitored thread is dead, closing off allocated connection.\");\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tc.internalClose();\r\n\t\t\t\t\t} catch (SQLException e) {\r\n\t\t\t\t\t\te.printStackTrace();\r\n\t\t\t\t\t}\r\n\t\t\t\t\tCachedConnectionStrategy.this.threadFinalizableRefs.remove(c);\r\n\t\t\t}\r\n\t\t});\r\n\t}",
"public static PredicateExpression all(Object... rhs) {\n PredicateExpression ex = new PredicateExpression( \"$all\", rhs);\n if (rhs.length == 1) {\n ex.single = true;\n }\n return ex;\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 }"
] |
Write the given pattern to given log in given logging level
@param logger
@param level
@param pattern
@param exception | [
"private static void writeToLog(Logger logger, Level level, String pattern, Exception exception) {\n if (level == Level.ERROR) {\n logger.error(pattern, exception);\n } else if (level == Level.INFO) {\n logger.info(pattern);\n } else if (level == Level.DEBUG) {\n logger.debug(pattern);\n }\n }"
] | [
"@Override\n public void begin(String namespace, String name, Attributes attributes) throws Exception {\n\n // not now: 6.0.0\n // digester.setLogger(CmsLog.getLog(digester.getClass()));\n\n // Push an array to capture the parameter values if necessary\n if (m_paramCount > 0) {\n Object[] parameters = new Object[m_paramCount];\n for (int i = 0; i < parameters.length; i++) {\n parameters[i] = null;\n }\n getDigester().pushParams(parameters);\n }\n }",
"okhttp3.Response get(String url, Map<String, Object> params)\n throws RequestException, LocalOperationException {\n\n String fullUrl = getFullUrl(url);\n okhttp3.Request request = new okhttp3.Request.Builder()\n .url(addUrlParams(fullUrl, toPayload(params)))\n .addHeader(\"Transloadit-Client\", version)\n .build();\n\n try {\n return httpClient.newCall(request).execute();\n } catch (IOException e) {\n throw new RequestException(e);\n }\n }",
"public static CmsSearchConfigurationSorting create(\n final String sortParam,\n final List<I_CmsSearchConfigurationSortOption> options,\n final I_CmsSearchConfigurationSortOption defaultOption) {\n\n return (null != sortParam) || ((null != options) && !options.isEmpty()) || (null != defaultOption)\n ? new CmsSearchConfigurationSorting(sortParam, options, defaultOption)\n : null;\n }",
"public ServerSocket createServerSocket() throws IOException {\n final ServerSocket socket = getServerSocketFactory().createServerSocket(name);\n socket.bind(getSocketAddress());\n return socket;\n }",
"public synchronized void shutdown(){\r\n\r\n\t\tif (!this.poolShuttingDown){\r\n\t\t\tlogger.info(\"Shutting down connection pool...\");\r\n\t\t\tthis.poolShuttingDown = true;\r\n\t\t\tthis.shutdownStackTrace = captureStackTrace(SHUTDOWN_LOCATION_TRACE);\r\n\t\t\tthis.keepAliveScheduler.shutdownNow(); // stop threads from firing.\r\n\t\t\tthis.maxAliveScheduler.shutdownNow(); // stop threads from firing.\r\n\t\t\tthis.connectionsScheduler.shutdownNow(); // stop threads from firing.\r\n\t\t\tthis.asyncExecutor.shutdownNow();\r\n\r\n\t\t\ttry {\r\n\t\t\t\tthis.connectionsScheduler.awaitTermination(5, TimeUnit.SECONDS);\r\n\r\n\t\t\t\tthis.maxAliveScheduler.awaitTermination(5, TimeUnit.SECONDS);\r\n\t\t\t\tthis.keepAliveScheduler.awaitTermination(5, TimeUnit.SECONDS);\r\n\t\t\t\tthis.asyncExecutor.awaitTermination(5, TimeUnit.SECONDS);\r\n\t\t\t\t\r\n\t\t\t\tif (this.closeConnectionExecutor != null){\r\n\t\t\t\t\tthis.closeConnectionExecutor.shutdownNow();\r\n\t\t\t\t\tthis.closeConnectionExecutor.awaitTermination(5, TimeUnit.SECONDS);\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t} catch (InterruptedException e) {\r\n\t\t\t\t// do nothing\r\n\t\t\t}\r\n\t\t\tthis.connectionStrategy.terminateAllConnections();\r\n\t\t\tunregisterDriver();\r\n\t\t\tregisterUnregisterJMX(false);\r\n\t\t\tif (finalizableRefQueue != null) {\r\n\t\t\t\tfinalizableRefQueue.close();\r\n\t\t\t}\r\n\t\t\t logger.info(\"Connection pool has been shutdown.\");\r\n\t\t}\r\n\t}",
"public final URI render(\n final MapfishMapContext mapContext,\n final ScalebarAttributeValues scalebarParams,\n final File tempFolder,\n final Template template)\n throws IOException, ParserConfigurationException {\n final double dpi = mapContext.getDPI();\n\n // get the map bounds\n final Rectangle paintArea = new Rectangle(mapContext.getMapSize());\n MapBounds bounds = mapContext.getBounds();\n\n final DistanceUnit mapUnit = getUnit(bounds);\n final Scale scale = bounds.getScale(paintArea, PDF_DPI);\n final double scaleDenominator = scale.getDenominator(scalebarParams.geodetic,\n bounds.getProjection(), dpi, bounds.getCenter());\n\n DistanceUnit scaleUnit = scalebarParams.getUnit();\n if (scaleUnit == null) {\n scaleUnit = mapUnit;\n }\n\n // adjust scalebar width and height to the DPI value\n final double maxLengthInPixel = (scalebarParams.getOrientation().isHorizontal()) ?\n scalebarParams.getSize().width : scalebarParams.getSize().height;\n\n final double maxIntervalLengthInWorldUnits = DistanceUnit.PX.convertTo(maxLengthInPixel, scaleUnit)\n * scaleDenominator / scalebarParams.intervals;\n final double niceIntervalLengthInWorldUnits =\n getNearestNiceValue(maxIntervalLengthInWorldUnits, scaleUnit, scalebarParams.lockUnits);\n\n final ScaleBarRenderSettings settings = new ScaleBarRenderSettings();\n settings.setParams(scalebarParams);\n settings.setMaxSize(scalebarParams.getSize());\n settings.setPadding(getPadding(settings));\n\n // start the rendering\n File path = null;\n if (template.getConfiguration().renderAsSvg(scalebarParams.renderAsSvg)) {\n // render scalebar as SVG\n final SVGGraphics2D graphics2D = CreateMapProcessor.createSvgGraphics(scalebarParams.getSize());\n\n try {\n tryLayout(\n graphics2D, scaleUnit, scaleDenominator,\n niceIntervalLengthInWorldUnits, settings, 0);\n\n path = File.createTempFile(\"scalebar-graphic-\", \".svg\", tempFolder);\n CreateMapProcessor.saveSvgFile(graphics2D, path);\n } finally {\n graphics2D.dispose();\n }\n } else {\n // render scalebar as raster graphic\n double dpiRatio = mapContext.getDPI() / PDF_DPI;\n final BufferedImage bufferedImage = new BufferedImage(\n (int) Math.round(scalebarParams.getSize().width * dpiRatio),\n (int) Math.round(scalebarParams.getSize().height * dpiRatio),\n TYPE_4BYTE_ABGR);\n final Graphics2D graphics2D = bufferedImage.createGraphics();\n\n try {\n AffineTransform saveAF = new AffineTransform(graphics2D.getTransform());\n graphics2D.scale(dpiRatio, dpiRatio);\n tryLayout(\n graphics2D, scaleUnit, scaleDenominator,\n niceIntervalLengthInWorldUnits, settings, 0);\n graphics2D.setTransform(saveAF);\n\n path = File.createTempFile(\"scalebar-graphic-\", \".png\", tempFolder);\n ImageUtils.writeImage(bufferedImage, \"png\", path);\n } finally {\n graphics2D.dispose();\n }\n }\n\n return path.toURI();\n }",
"public BoxFile.Info getFileInfo(String fileID) {\n URL url = FILE_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), fileID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n\n BoxFile file = new BoxFile(this.api, jsonObject.get(\"id\").asString());\n return file.new Info(response.getJSON());\n }",
"public static java.sql.Time toTime(Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (value instanceof java.sql.Time) {\n return (java.sql.Time) value;\n }\n if (value instanceof String) {\n if (\"\".equals((String) value)) {\n return null;\n }\n return new java.sql.Time(IN_TIME_FORMAT.parse((String) value).getTime());\n }\n\n return new java.sql.Time(IN_TIME_FORMAT.parse(value.toString()).getTime());\n }",
"private static Document objectForInsert(Tuple tuple, Document dbObject) {\n\t\tMongoDBTupleSnapshot snapshot = (MongoDBTupleSnapshot) tuple.getSnapshot();\n\t\tfor ( TupleOperation operation : tuple.getOperations() ) {\n\t\t\tString column = operation.getColumn();\n\t\t\tif ( notInIdField( snapshot, column ) ) {\n\t\t\t\tswitch ( operation.getType() ) {\n\t\t\t\t\tcase PUT:\n\t\t\t\t\t\tMongoHelpers.setValue( dbObject, column, operation.getValue() );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase PUT_NULL:\n\t\t\t\t\tcase REMOVE:\n\t\t\t\t\t\tMongoHelpers.resetValue( dbObject, column );\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn dbObject;\n\t}"
] |
Try to extract a numeric version from a collection of strings.
@param versionStrings Collection of string properties.
@return The version string if exists in the collection. | [
"private String extractNumericVersion(Collection<String> versionStrings) {\n if (versionStrings == null) {\n return \"\";\n }\n for (String value : versionStrings) {\n String releaseValue = calculateReleaseVersion(value);\n if (!releaseValue.equals(value)) {\n return releaseValue;\n }\n }\n return \"\";\n }"
] | [
"protected boolean equivalentClaims(Claim claim1, Claim claim2) {\n\t\treturn claim1.getMainSnak().equals(claim2.getMainSnak())\n\t\t\t\t&& isSameSnakSet(claim1.getAllQualifiers(),\n\t\t\t\t\t\tclaim2.getAllQualifiers());\n\t}",
"@Pure\n\tpublic static <T> List<T> reverseView(List<T> list) {\n\t\treturn Lists.reverse(list);\n\t}",
"public static Region create(String name, String label) {\n Region region = VALUES_BY_NAME.get(name.toLowerCase());\n if (region != null) {\n return region;\n } else {\n return new Region(name, label);\n }\n }",
"@Override public void process(MPPReader reader, ProjectFile file, DirectoryEntry root) throws MPXJException, IOException\n {\n try\n {\n populateMemberData(reader, file, root);\n processProjectProperties();\n\n if (!reader.getReadPropertiesOnly())\n {\n processCalendarData();\n processResourceData();\n processTaskData();\n processConstraintData();\n processAssignmentData();\n\n if (reader.getReadPresentationData())\n {\n processViewPropertyData();\n processViewData();\n processTableData();\n }\n }\n }\n\n finally\n {\n clearMemberData();\n }\n }",
"public void store(Object obj, ObjectModification mod) throws PersistenceBrokerException\n {\n obj = extractObjectToStore(obj);\n // null for unmaterialized Proxy\n if (obj == null)\n {\n return;\n }\n\n ClassDescriptor cld = getClassDescriptor(obj.getClass());\n // this call ensures that all autoincremented primary key attributes are filled\n Identity oid = serviceIdentity().buildIdentity(cld, obj);\n // select flag for insert / update selection by checking the ObjectModification\n if (mod.needsInsert())\n {\n store(obj, oid, cld, true);\n }\n else if (mod.needsUpdate())\n {\n store(obj, oid, cld, false);\n }\n /*\n arminw\n TODO: Why we need this behaviour? What about 1:1 relations?\n */\n else\n {\n // just store 1:n and m:n associations\n storeCollections(obj, cld, mod.needsInsert());\n }\n }",
"protected Object getTypedValue(int type, byte[] value)\n {\n Object result;\n\n switch (type)\n {\n case 4: // Date\n {\n result = MPPUtility.getTimestamp(value, 0);\n break;\n }\n\n case 6: // Duration\n {\n TimeUnit units = MPPUtility.getDurationTimeUnits(MPPUtility.getShort(value, 4), m_properties.getDefaultDurationUnits());\n result = MPPUtility.getAdjustedDuration(m_properties, MPPUtility.getInt(value, 0), units);\n break;\n }\n\n case 9: // Cost\n {\n result = Double.valueOf(MPPUtility.getDouble(value, 0) / 100);\n break;\n }\n\n case 15: // Number\n {\n result = Double.valueOf(MPPUtility.getDouble(value, 0));\n break;\n }\n\n case 36058:\n case 21: // Text\n {\n result = MPPUtility.getUnicodeString(value, 0);\n break;\n }\n\n default:\n {\n result = value;\n break;\n }\n }\n\n return result;\n }",
"public void scale(double v){\n\t\tfor(int i = 0; i < this.size(); i++){\n\t\t\tthis.get(i).scale(v);;\n\t\t}\n\t}",
"private void readProject(Project project)\n {\n Task mpxjTask = m_projectFile.addTask();\n //project.getAuthor()\n mpxjTask.setBaselineCost(project.getBaselineCost());\n mpxjTask.setBaselineFinish(project.getBaselineFinishDate());\n mpxjTask.setBaselineStart(project.getBaselineStartDate());\n //project.getBudget();\n //project.getCompany()\n mpxjTask.setFinish(project.getFinishDate());\n //project.getGoal()\n //project.getHyperlinks()\n //project.getMarkerID()\n mpxjTask.setName(project.getName());\n mpxjTask.setNotes(project.getNote());\n mpxjTask.setPriority(project.getPriority());\n // project.getSite()\n mpxjTask.setStart(project.getStartDate());\n // project.getStyleProject()\n // project.getTask()\n // project.getTimeScale()\n // project.getViewProperties()\n\n String projectIdentifier = project.getID().toString();\n mpxjTask.setGUID(UUID.nameUUIDFromBytes(projectIdentifier.getBytes()));\n\n //\n // Sort the tasks into the correct order\n //\n List<Document.Projects.Project.Task> tasks = new ArrayList<Document.Projects.Project.Task>(project.getTask());\n final AlphanumComparator comparator = new AlphanumComparator();\n\n Collections.sort(tasks, new Comparator<Document.Projects.Project.Task>()\n {\n @Override public int compare(Document.Projects.Project.Task o1, Document.Projects.Project.Task o2)\n {\n return comparator.compare(o1.getOutlineNumber(), o2.getOutlineNumber());\n }\n });\n\n Map<String, Task> map = new HashMap<String, Task>();\n map.put(\"\", mpxjTask);\n\n for (Document.Projects.Project.Task task : tasks)\n {\n readTask(projectIdentifier, map, task);\n }\n }",
"public void setColor(int n, int color) {\n\t\tint firstColor = map[0];\n\t\tint lastColor = map[256-1];\n\t\tif (n > 0)\n\t\t\tfor (int i = 0; i < n; i++)\n\t\t\t\tmap[i] = ImageMath.mixColors((float)i/n, firstColor, color);\n\t\tif (n < 256-1)\n\t\t\tfor (int i = n; i < 256; i++)\n\t\t\t\tmap[i] = ImageMath.mixColors((float)(i-n)/(256-n), color, lastColor);\n\t}"
] |
Use this API to unset the properties of snmpalarm resources.
Properties that need to be unset are specified in args array. | [
"public static base_responses unset(nitro_service client, String trapname[], String args[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (trapname != null && trapname.length > 0) {\n\t\t\tsnmpalarm unsetresources[] = new snmpalarm[trapname.length];\n\t\t\tfor (int i=0;i<trapname.length;i++){\n\t\t\t\tunsetresources[i] = new snmpalarm();\n\t\t\t\tunsetresources[i].trapname = trapname[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 void AddLODSceneObject(GVRSceneObject currentSceneObject) {\n if (this.transformLODSceneObject != null) {\n GVRSceneObject levelOfDetailSceneObject = null;\n if ( currentSceneObject.getParent() == this.transformLODSceneObject) {\n levelOfDetailSceneObject = currentSceneObject;\n }\n else {\n GVRSceneObject lodSceneObj = root.getSceneObjectByName((currentSceneObject.getName() + TRANSFORM_TRANSLATION_));\n if ( lodSceneObj != null ) {\n if (lodSceneObj.getParent() == this.transformLODSceneObject) {\n levelOfDetailSceneObject = lodSceneObj;\n }\n }\n if (levelOfDetailSceneObject == null) {\n lodSceneObj = root.getSceneObjectByName((currentSceneObject.getName() + TRANSFORM_ROTATION_));\n if ( lodSceneObj != null ) {\n if (lodSceneObj.getParent() == this.transformLODSceneObject) {\n levelOfDetailSceneObject = lodSceneObj;\n }\n }\n }\n if (levelOfDetailSceneObject == null) {\n lodSceneObj = root.getSceneObjectByName((currentSceneObject.getName() + TRANSFORM_SCALE_));\n if ( lodSceneObj != null ) {\n if (lodSceneObj.getParent() == this.transformLODSceneObject) {\n levelOfDetailSceneObject = lodSceneObj;\n }\n }\n }\n\n }\n if ( levelOfDetailSceneObject != null) {\n final GVRLODGroup lodGroup = (GVRLODGroup) this.transformLODSceneObject.getComponent(GVRLODGroup.getComponentType());\n lodGroup.addRange(this.getMinRange(), levelOfDetailSceneObject);\n this.increment();\n }\n }\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 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 }",
"void writeInterPropertyLinks(PropertyDocument document)\n\t\t\tthrows RDFHandlerException {\n\t\tResource subject = this.rdfWriter.getUri(document.getEntityId()\n\t\t\t\t.getIri());\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_DIRECT_CLAIM_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.DIRECT));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_CLAIM_PROP), Vocabulary.getPropertyUri(\n\t\t\t\tdocument.getEntityId(), PropertyContext.STATEMENT));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_STATEMENT_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.VALUE_SIMPLE));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_STATEMENT_VALUE_PROP),\n\t\t\t\tVocabulary.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.VALUE));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_QUALIFIER_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.QUALIFIER_SIMPLE));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_QUALIFIER_VALUE_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.QUALIFIER));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_REFERENCE_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.REFERENCE_SIMPLE));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_REFERENCE_VALUE_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.REFERENCE));\n\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_NO_VALUE_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.NO_VALUE));\n\t\tthis.rdfWriter.writeTripleUriObject(subject, this.rdfWriter\n\t\t\t\t.getUri(Vocabulary.WB_NO_QUALIFIER_VALUE_PROP), Vocabulary\n\t\t\t\t.getPropertyUri(document.getEntityId(),\n\t\t\t\t\t\tPropertyContext.NO_QUALIFIER_VALUE));\n\t\t// TODO something more with NO_VALUE\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 }",
"private boolean hasPrimaryKey(T entity) {\n Object pk = getPrimaryKey(entity);\n if (pk == null) {\n return false;\n } else {\n if (pk instanceof Number && ((Number) pk).longValue() == 0) {\n return false;\n }\n }\n return true;\n }",
"public void updateLockingValues(Object obj) throws PersistenceBrokerException\r\n {\r\n FieldDescriptor[] fields = getLockingFields();\r\n for (int i = 0; i < fields.length; i++)\r\n {\r\n FieldDescriptor fmd = fields[i];\r\n if (fmd.isUpdateLock())\r\n {\r\n PersistentField f = fmd.getPersistentField();\r\n Object cv = f.get(obj);\r\n // int\r\n if ((f.getType() == int.class) || (f.getType() == Integer.class))\r\n {\r\n int newCv = 0;\r\n if (cv != null)\r\n {\r\n newCv = ((Number) cv).intValue();\r\n }\r\n newCv++;\r\n f.set(obj, new Integer(newCv));\r\n }\r\n // long\r\n else if ((f.getType() == long.class) || (f.getType() == Long.class))\r\n {\r\n long newCv = 0;\r\n if (cv != null)\r\n {\r\n newCv = ((Number) cv).longValue();\r\n }\r\n newCv++;\r\n f.set(obj, new Long(newCv));\r\n }\r\n // Timestamp\r\n else if (f.getType() == Timestamp.class)\r\n {\r\n long newCv = System.currentTimeMillis();\r\n f.set(obj, new Timestamp(newCv));\r\n }\r\n }\r\n }\r\n }",
"public long countByLex(final LexRange lexRange) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.zlexcount(getKey(), lexRange.from(), lexRange.to());\n }\n });\n }",
"public String getGroupNameFromId(int groupId) {\n return (String) sqlService.getFromTable(Constants.GROUPS_GROUP_NAME, Constants.GENERIC_ID, groupId,\n Constants.DB_TABLE_GROUPS);\n }"
] |
Writes all data that was collected about classes to a json file. | [
"private void writeClassData() {\n\t\ttry (PrintStream out = new PrintStream(openResultFileOuputStream(\n\t\t\t\tresultDirectory, \"classes.json\"))) {\n\t\t\tout.println(\"{\");\n\n\t\t\t// Add direct subclass information:\n\t\t\tfor (Entry<Integer, ClassRecord> classEntry : this.classRecords\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tif (classEntry.getValue().subclassCount == 0\n\t\t\t\t\t\t&& classEntry.getValue().itemCount == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfor (Integer superClass : classEntry.getValue().directSuperClasses) {\n\t\t\t\t\tthis.classRecords.get(superClass).nonemptyDirectSubclasses\n\t\t\t\t\t\t\t.add(classEntry.getKey().toString());\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tint count = 0;\n\t\t\tint countNoLabel = 0;\n\t\t\tfor (Entry<Integer, ClassRecord> classEntry : this.classRecords\n\t\t\t\t\t.entrySet()) {\n\t\t\t\tif (classEntry.getValue().subclassCount == 0\n\t\t\t\t\t\t&& classEntry.getValue().itemCount == 0) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tif (classEntry.getValue().label == null) {\n\t\t\t\t\tcountNoLabel++;\n\t\t\t\t}\n\n\t\t\t\tif (count > 0) {\n\t\t\t\t\tout.println(\",\");\n\t\t\t\t}\n\t\t\t\tout.print(\"\\\"\" + classEntry.getKey() + \"\\\":\");\n\t\t\t\tmapper.writeValue(out, classEntry.getValue());\n\t\t\t\tcount++;\n\t\t\t}\n\t\t\tout.println(\"\\n}\");\n\n\t\t\tSystem.out.println(\" Serialized information for \" + count\n\t\t\t\t\t+ \" class items.\");\n\t\t\tSystem.out.println(\" -- class items with missing label: \"\n\t\t\t\t\t+ countNoLabel);\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}"
] | [
"@UiHandler(\"m_dateList\")\r\n void dateListValueChange(ValueChangeEvent<SortedSet<Date>> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setDates(event.getValue());\r\n }\r\n }",
"static void processServerConfig(final Resource root, final RequiredConfigurationHolder requiredConfigurationHolder, final IgnoredNonAffectedServerGroupsUtil.ServerConfigInfo serverConfig, final ExtensionRegistry extensionRegistry) {\n\n final Set<String> serverGroups = requiredConfigurationHolder.serverGroups;\n final Set<String> socketBindings = requiredConfigurationHolder.socketBindings;\n\n String sbg = serverConfig.getSocketBindingGroup();\n if (sbg != null && !socketBindings.contains(sbg)) {\n processSocketBindingGroup(root, sbg, requiredConfigurationHolder);\n }\n\n final String groupName = serverConfig.getServerGroup();\n final PathElement groupElement = PathElement.pathElement(SERVER_GROUP, groupName);\n // Also check the root, since this also gets executed on the slave which may not have the server-group configured yet\n if (!serverGroups.contains(groupName) && root.hasChild(groupElement)) {\n\n final Resource serverGroup = root.getChild(groupElement);\n final ModelNode groupModel = serverGroup.getModel();\n serverGroups.add(groupName);\n\n // Include the socket binding groups\n if (groupModel.hasDefined(SOCKET_BINDING_GROUP)) {\n final String socketBindingGroup = groupModel.get(SOCKET_BINDING_GROUP).asString();\n processSocketBindingGroup(root, socketBindingGroup, requiredConfigurationHolder);\n }\n\n final String profileName = groupModel.get(PROFILE).asString();\n processProfile(root, profileName, requiredConfigurationHolder, extensionRegistry);\n }\n }",
"public static boolean compareAnnotatedTypes(AnnotatedType<?> t1, AnnotatedType<?> t2) {\n if (!t1.getJavaClass().equals(t2.getJavaClass())) {\n return false;\n }\n if (!compareAnnotated(t1, t2)) {\n return false;\n }\n\n if (t1.getFields().size() != t2.getFields().size()) {\n return false;\n }\n Map<Field, AnnotatedField<?>> fields = new HashMap<Field, AnnotatedField<?>>();\n for (AnnotatedField<?> f : t2.getFields()) {\n fields.put(f.getJavaMember(), f);\n }\n for (AnnotatedField<?> f : t1.getFields()) {\n if (fields.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedField(f, fields.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n\n if (t1.getMethods().size() != t2.getMethods().size()) {\n return false;\n }\n Map<Method, AnnotatedMethod<?>> methods = new HashMap<Method, AnnotatedMethod<?>>();\n for (AnnotatedMethod<?> f : t2.getMethods()) {\n methods.put(f.getJavaMember(), f);\n }\n for (AnnotatedMethod<?> f : t1.getMethods()) {\n if (methods.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedCallable(f, methods.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n if (t1.getConstructors().size() != t2.getConstructors().size()) {\n return false;\n }\n Map<Constructor<?>, AnnotatedConstructor<?>> constructors = new HashMap<Constructor<?>, AnnotatedConstructor<?>>();\n for (AnnotatedConstructor<?> f : t2.getConstructors()) {\n constructors.put(f.getJavaMember(), f);\n }\n for (AnnotatedConstructor<?> f : t1.getConstructors()) {\n if (constructors.containsKey(f.getJavaMember())) {\n if (!compareAnnotatedCallable(f, constructors.get(f.getJavaMember()))) {\n return false;\n }\n } else {\n return false;\n }\n }\n return true;\n\n }",
"private void setConstraints(Task task, MapRow row)\n {\n ConstraintType constraintType = null;\n Date constraintDate = null;\n Date lateDate = row.getDate(\"CONSTRAINT_LATE_DATE\");\n Date earlyDate = row.getDate(\"CONSTRAINT_EARLY_DATE\");\n\n switch (row.getInteger(\"CONSTRAINT_TYPE\").intValue())\n {\n case 2: // Cannot Reschedule\n {\n constraintType = ConstraintType.MUST_START_ON;\n constraintDate = task.getStart();\n break;\n }\n\n case 12: //Finish Between\n {\n constraintType = ConstraintType.MUST_FINISH_ON;\n constraintDate = lateDate;\n break;\n }\n\n case 10: // Finish On or After\n {\n constraintType = ConstraintType.FINISH_NO_EARLIER_THAN;\n constraintDate = earlyDate;\n break;\n }\n\n case 11: // Finish On or Before\n {\n constraintType = ConstraintType.FINISH_NO_LATER_THAN;\n constraintDate = lateDate;\n break;\n }\n\n case 13: // Mandatory Start\n case 5: // Start On\n case 9: // Finish On\n {\n constraintType = ConstraintType.MUST_START_ON;\n constraintDate = earlyDate;\n break;\n }\n\n case 14: // Mandatory Finish\n {\n constraintType = ConstraintType.MUST_FINISH_ON;\n constraintDate = earlyDate;\n break;\n }\n\n case 4: // Start As Late As Possible\n {\n constraintType = ConstraintType.AS_LATE_AS_POSSIBLE;\n break;\n }\n\n case 3: // Start As Soon As Possible\n {\n constraintType = ConstraintType.AS_SOON_AS_POSSIBLE;\n break;\n }\n\n case 8: // Start Between\n {\n constraintType = ConstraintType.AS_SOON_AS_POSSIBLE;\n constraintDate = earlyDate;\n break;\n }\n\n case 6: // Start On or Before\n {\n constraintType = ConstraintType.START_NO_LATER_THAN;\n constraintDate = earlyDate;\n break;\n }\n\n case 15: // Work Between\n {\n constraintType = ConstraintType.START_NO_EARLIER_THAN;\n constraintDate = earlyDate;\n break;\n }\n }\n task.setConstraintType(constraintType);\n task.setConstraintDate(constraintDate);\n }",
"private static void reallyValidatePseudoScopedBean(Bean<?> bean, BeanManagerImpl beanManager, Set<Object> dependencyPath, Set<Bean<?>> validatedBeans) {\n // see if we have already seen this bean in the dependency path\n if (dependencyPath.contains(bean)) {\n // create a list that shows the path to the bean\n List<Object> realDependencyPath = new ArrayList<Object>(dependencyPath);\n realDependencyPath.add(bean);\n throw ValidatorLogger.LOG.pseudoScopedBeanHasCircularReferences(WeldCollections.toMultiRowString(realDependencyPath));\n }\n if (validatedBeans.contains(bean)) {\n return;\n }\n dependencyPath.add(bean);\n for (InjectionPoint injectionPoint : bean.getInjectionPoints()) {\n if (!injectionPoint.isDelegate()) {\n dependencyPath.add(injectionPoint);\n validatePseudoScopedInjectionPoint(injectionPoint, beanManager, dependencyPath, validatedBeans);\n dependencyPath.remove(injectionPoint);\n }\n }\n if (bean instanceof DecorableBean<?>) {\n final List<Decorator<?>> decorators = Reflections.<DecorableBean<?>>cast(bean).getDecorators();\n if (!decorators.isEmpty()) {\n for (final Decorator<?> decorator : decorators) {\n reallyValidatePseudoScopedBean(decorator, beanManager, dependencyPath, validatedBeans);\n }\n }\n }\n if (bean instanceof AbstractProducerBean<?, ?, ?> && !(bean instanceof EEResourceProducerField<?, ?>)) {\n AbstractProducerBean<?, ?, ?> producer = (AbstractProducerBean<?, ?, ?>) bean;\n if (!beanManager.isNormalScope(producer.getDeclaringBean().getScope()) && !producer.getAnnotated().isStatic()) {\n reallyValidatePseudoScopedBean(producer.getDeclaringBean(), beanManager, dependencyPath, validatedBeans);\n }\n }\n validatedBeans.add(bean);\n dependencyPath.remove(bean);\n }",
"public static void assertValidMetadata(ByteArray key,\n RoutingStrategy routingStrategy,\n Node currentNode) {\n List<Node> nodes = routingStrategy.routeRequest(key.get());\n for(Node node: nodes) {\n if(node.getId() == currentNode.getId()) {\n return;\n }\n }\n\n throw new InvalidMetadataException(\"Client accessing key belonging to partitions \"\n + routingStrategy.getPartitionList(key.get())\n + \" not present at \" + currentNode);\n }",
"public List<File> getAutoAttachCacheFiles() {\n ArrayList<File> currentFiles = new ArrayList<File>(autoAttachCacheFiles);\n Collections.sort(currentFiles, new Comparator<File>() {\n @Override\n public int compare(File o1, File o2) {\n return o1.getName().compareTo(o2.getName());\n }\n });\n return Collections.unmodifiableList(currentFiles);\n }",
"public Class getPersistentFieldClass()\r\n {\r\n if (m_persistenceClass == null)\r\n {\r\n Properties properties = new Properties();\r\n try\r\n {\r\n this.logWarning(\"Loading properties file: \" + getPropertiesFile());\r\n properties.load(new FileInputStream(getPropertiesFile()));\r\n }\r\n catch (IOException e)\r\n {\r\n this.logWarning(\"Could not load properties file '\" + getPropertiesFile()\r\n + \"'. Using PersistentFieldDefaultImpl.\");\r\n e.printStackTrace();\r\n }\r\n try\r\n {\r\n String className = properties.getProperty(\"PersistentFieldClass\");\r\n\r\n m_persistenceClass = loadClass(className);\r\n }\r\n catch (ClassNotFoundException e)\r\n {\r\n e.printStackTrace();\r\n m_persistenceClass = PersistentFieldPrivilegedImpl.class;\r\n }\r\n logWarning(\"PersistentFieldClass: \" + m_persistenceClass.toString());\r\n }\r\n return m_persistenceClass;\r\n }",
"public FullTypeSignature getTypeErasureSignature() {\r\n\t\tif (typeErasureSignature == null) {\r\n\t\t\ttypeErasureSignature = new ClassTypeSignature(binaryName,\r\n\t\t\t\t\tnew TypeArgSignature[0], ownerTypeSignature == null ? null\r\n\t\t\t\t\t\t\t: (ClassTypeSignature) ownerTypeSignature\r\n\t\t\t\t\t\t\t\t\t.getTypeErasureSignature());\r\n\t\t}\r\n\t\treturn typeErasureSignature;\r\n\t}"
] |
Get a unique reference to the media slot on the network from which the specified data was loaded.
@param dataReference the data whose media slot is of interest
@return the instance that will always represent the slot associated with the specified data | [
"@SuppressWarnings(\"WeakerAccess\")\n public static SlotReference getSlotReference(DataReference dataReference) {\n return getSlotReference(dataReference.player, dataReference.slot);\n }"
] | [
"public static void configure(Job conf, SimpleConfiguration config) {\n try {\n FluoConfiguration fconfig = new FluoConfiguration(config);\n try (Environment env = new Environment(fconfig)) {\n long ts =\n env.getSharedResources().getTimestampTracker().allocateTimestamp().getTxTimestamp();\n conf.getConfiguration().setLong(TIMESTAMP_CONF_KEY, ts);\n\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n config.save(baos);\n conf.getConfiguration().set(PROPS_CONF_KEY,\n new String(baos.toByteArray(), StandardCharsets.UTF_8));\n\n AccumuloInputFormat.setZooKeeperInstance(conf, fconfig.getAccumuloInstance(),\n fconfig.getAccumuloZookeepers());\n AccumuloInputFormat.setConnectorInfo(conf, fconfig.getAccumuloUser(),\n new PasswordToken(fconfig.getAccumuloPassword()));\n AccumuloInputFormat.setInputTableName(conf, env.getTable());\n AccumuloInputFormat.setScanAuthorizations(conf, env.getAuthorizations());\n }\n } catch (Exception e) {\n throw new RuntimeException(e);\n }\n }",
"static String replaceCheckDigit(final String iban, final String checkDigit) {\n return getCountryCode(iban) + checkDigit + getBban(iban);\n }",
"public static String createClassName(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 name;\n }",
"public void close() throws SQLException {\r\n\t\ttry {\r\n\r\n\t\t\tif (this.resetConnectionOnClose /*FIXME: && !getAutoCommit() && !isTxResolved() */){\r\n\t\t\t\t/*if (this.autoCommitStackTrace != null){\r\n\t\t\t\t\t\tlogger.debug(this.autoCommitStackTrace);\r\n\t\t\t\t\t\tthis.autoCommitStackTrace = null; \r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tlogger.debug(DISABLED_AUTO_COMMIT_WARNING);\r\n\t\t\t\t\t}*/\r\n\t\t\t\trollback();\r\n\t\t\t\tif (!getAutoCommit()){\r\n\t\t\t\t\tsetAutoCommit(true);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\tif (this.logicallyClosed.compareAndSet(false, true)) {\r\n\r\n\r\n\t\t\t\tif (this.threadWatch != null){\r\n\t\t\t\t\tthis.threadWatch.interrupt(); // if we returned the connection to the pool, terminate thread watch thread if it's\r\n\t\t\t\t\t// running even if thread is still alive (eg thread has been recycled for use in some\r\n\t\t\t\t\t// container).\r\n\t\t\t\t\tthis.threadWatch = null;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif (this.closeOpenStatements){\r\n\t\t\t\t\tfor (Entry<Statement, String> statementEntry: this.trackedStatement.entrySet()){\r\n\t\t\t\t\t\tstatementEntry.getKey().close();\r\n\t\t\t\t\t\tif (this.detectUnclosedStatements){\r\n\t\t\t\t\t\t\tlogger.warn(String.format(UNCLOSED_LOG_ERROR_MESSAGE, statementEntry.getValue()));\t\t\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tthis.trackedStatement.clear();\r\n\t\t\t\t} \r\n\r\n\t\t\t\tif (!this.connectionTrackingDisabled){\r\n\t\t\t\t\tpool.getFinalizableRefs().remove(this.connection);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tConnectionHandle handle = null;\r\n\r\n\t\t\t\t//recreate can throw a SQLException in constructor on recreation\r\n\t\t\t\ttry {\r\n\t\t\t\t handle = this.recreateConnectionHandle();\r\n\t\t\t\t this.pool.connectionStrategy.cleanupConnection(this, handle);\r\n\t\t\t\t this.pool.releaseConnection(handle);\t\t\t\t \r\n\t\t\t\t} catch(SQLException e) {\r\n\t\t\t\t //check if the connection was already closed by the recreation\r\n\t\t\t\t if (!isClosed()) {\r\n\t\t\t\t \tthis.pool.connectionStrategy.cleanupConnection(this, handle);\r\n\t\t\t\t \tthis.pool.releaseConnection(this);\r\n\t\t\t\t }\r\n\t\t\t\t throw e;\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\tif (this.doubleCloseCheck){\r\n\t\t\t\t\tthis.doubleCloseException = this.pool.captureStackTrace(CLOSED_TWICE_EXCEPTION_MESSAGE);\r\n\t\t\t\t}\r\n\t\t\t} else {\r\n\t\t\t\tif (this.doubleCloseCheck && this.doubleCloseException != null){\r\n\t\t\t\t\tString currentLocation = this.pool.captureStackTrace(\"Last closed trace from thread [\"+Thread.currentThread().getName()+\"]:\\n\");\r\n\t\t\t\t\tlogger.error(String.format(LOG_ERROR_MESSAGE, this.doubleCloseException, currentLocation));\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t} catch (SQLException e) {\r\n\t\t\tthrow markPossiblyBroken(e);\r\n\t\t}\r\n\t}",
"public static ResourceKey key(Enum<?> enumValue, String key) {\n return new ResourceKey(enumValue.getClass().getName(), enumValue.name()).child(key);\n }",
"private boolean shouldWrapMethodCall(String methodName) {\n if (methodList == null) {\n return true; // Wrap all by default\n }\n\n if (methodList.contains(methodName)) {\n return true; //Wrap a specific method\n }\n\n // If I get to this point, I should not wrap the call.\n return false;\n }",
"protected String sourceLineTrimmed(ASTNode node) {\r\n return sourceCode.line(AstUtil.findFirstNonAnnotationLine(node, sourceCode) - 1);\r\n }",
"private Set<String> findResourceNamesFromFileSystem(String classPathRootOnDisk, String scanRootLocation, File folder) {\n LOGGER.debug(\"Scanning for resources in path: {} ({})\", folder.getPath(), scanRootLocation);\n\n File[] files = folder.listFiles();\n if (files == null) {\n return emptySet();\n }\n\n Set<String> resourceNames = new TreeSet<>();\n\n for (File file : files) {\n if (file.canRead()) {\n if (file.isDirectory()) {\n resourceNames.addAll(findResourceNamesFromFileSystem(classPathRootOnDisk, scanRootLocation, file));\n } else {\n resourceNames.add(toResourceNameOnClasspath(classPathRootOnDisk, file));\n }\n }\n }\n\n return resourceNames;\n }",
"public Object getFieldByAlias(String alias)\n {\n return getCachedValue(getParentFile().getCustomFields().getFieldByAlias(FieldTypeClass.TASK, alias));\n }"
] |
handle white spaces. | [
"public static int getBytesToken(ParsingContext ctx) {\n String input = ctx.getInput().substring(ctx.getLocation());\n int tokenOffset = 0;\n int i = 0;\n char[] inputChars = input.toCharArray();\n for (; i < input.length(); i += 1) {\n char c = inputChars[i];\n if (c == ' ') {\n continue;\n }\n if (c != BYTES_TOKEN_CHARS[tokenOffset]) {\n return -1;\n } else {\n tokenOffset += 1;\n if (tokenOffset == BYTES_TOKEN_CHARS.length) {\n // Found the token.\n return i;\n }\n }\n }\n return -1;\n }"
] | [
"public static void transformChar(Reader self, Writer writer, @ClosureParams(value=SimpleType.class, options=\"java.lang.String\") Closure closure) throws IOException {\n int c;\n try {\n char[] chars = new char[1];\n while ((c = self.read()) != -1) {\n chars[0] = (char) c;\n writer.write((String) closure.call(new String(chars)));\n }\n writer.flush();\n\n Writer temp2 = writer;\n writer = null;\n temp2.close();\n Reader temp1 = self;\n self = null;\n temp1.close();\n } finally {\n closeWithWarning(self);\n closeWithWarning(writer);\n }\n }",
"public static base_response add(nitro_service client, nsip6 resource) throws Exception {\n\t\tnsip6 addresource = new nsip6();\n\t\taddresource.ipv6address = resource.ipv6address;\n\t\taddresource.scope = resource.scope;\n\t\taddresource.type = resource.type;\n\t\taddresource.vlan = resource.vlan;\n\t\taddresource.nd = resource.nd;\n\t\taddresource.icmp = resource.icmp;\n\t\taddresource.vserver = resource.vserver;\n\t\taddresource.telnet = resource.telnet;\n\t\taddresource.ftp = resource.ftp;\n\t\taddresource.gui = resource.gui;\n\t\taddresource.ssh = resource.ssh;\n\t\taddresource.snmp = resource.snmp;\n\t\taddresource.mgmtaccess = resource.mgmtaccess;\n\t\taddresource.restrictaccess = resource.restrictaccess;\n\t\taddresource.dynamicrouting = resource.dynamicrouting;\n\t\taddresource.hostroute = resource.hostroute;\n\t\taddresource.ip6hostrtgw = resource.ip6hostrtgw;\n\t\taddresource.metric = resource.metric;\n\t\taddresource.vserverrhilevel = resource.vserverrhilevel;\n\t\taddresource.ospf6lsatype = resource.ospf6lsatype;\n\t\taddresource.ospfarea = resource.ospfarea;\n\t\taddresource.state = resource.state;\n\t\taddresource.map = resource.map;\n\t\taddresource.ownernode = resource.ownernode;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}",
"@Override\n public boolean setA(DMatrixRBlock A) {\n if( A.numRows < A.numCols )\n throw new IllegalArgumentException(\"Number of rows must be more than or equal to the number of columns. \" +\n \"Can't solve an underdetermined system.\");\n\n if( !decomposer.decompose(A))\n return false;\n\n this.QR = decomposer.getQR();\n\n return true;\n }",
"@Pure\n\t@Inline(value = \"$3.union($1, $4.singletonMap($2.getKey(), $2.getValue()))\",\n\t\t\timported = { MapExtensions.class, Collections.class })\n\tpublic static <K, V> Map<K, V> operator_plus(Map<K, V> left, final Pair<? extends K, ? extends V> right) {\n\t\treturn union(left, Collections.singletonMap(right.getKey(), right.getValue()));\n\t}",
"protected String getExpectedMessage() {\r\n StringBuilder syntax = new StringBuilder(\"<tag> \");\r\n syntax.append(getName());\r\n\r\n String args = getArgSyntax();\r\n if (args != null && args.length() > 0) {\r\n syntax.append(' ');\r\n syntax.append(args);\r\n }\r\n\r\n return syntax.toString();\r\n }",
"@Override\r\n public void onBrowserEvent(Event event) {\r\n\r\n super.onBrowserEvent(event);\r\n\r\n switch (DOM.eventGetType(event)) {\r\n case Event.ONMOUSEUP:\r\n Event.releaseCapture(m_slider.getElement());\r\n m_capturedMouse = false;\r\n break;\r\n case Event.ONMOUSEDOWN:\r\n Event.setCapture(m_slider.getElement());\r\n m_capturedMouse = true;\r\n //$FALL-THROUGH$\r\n case Event.ONMOUSEMOVE:\r\n if (m_capturedMouse) {\r\n event.preventDefault();\r\n float x = ((event.getClientX() - (m_colorUnderlay.getAbsoluteLeft())) + Window.getScrollLeft());\r\n float y = ((event.getClientY() - (m_colorUnderlay.getAbsoluteTop())) + Window.getScrollTop());\r\n\r\n if (m_parent != null) {\r\n m_parent.onMapSelected(x, y);\r\n }\r\n\r\n setSliderPosition(x, y);\r\n }\r\n //$FALL-THROUGH$\r\n default:\r\n\r\n }\r\n }",
"@SuppressWarnings(\"unchecked\")\n private void setProxyRequestHeaders(HttpServletRequest httpServletRequest,\n HttpMethod httpMethodProxyRequest) throws Exception {\n RequestInformation requestInfo = requestInformation.get();\n String hostName = HttpUtilities.getHostNameFromURL(httpServletRequest.getRequestURL().toString());\n // Get an Enumeration of all of the header names sent by the client\n Boolean stripTransferEncoding = false;\n Enumeration<String> enumerationOfHeaderNames = httpServletRequest.getHeaderNames();\n while (enumerationOfHeaderNames.hasMoreElements()) {\n String stringHeaderName = enumerationOfHeaderNames.nextElement();\n if (stringHeaderName.equalsIgnoreCase(STRING_CONTENT_LENGTH_HEADER_NAME)) {\n // don't add this header\n continue;\n }\n\n // The forwarding proxy may supply a POST encoding hint in ODO-POST-TYPE\n if (stringHeaderName.equalsIgnoreCase(\"ODO-POST-TYPE\") &&\n httpServletRequest.getHeader(\"ODO-POST-TYPE\").startsWith(\"content-length:\")) {\n stripTransferEncoding = true;\n }\n\n logger.info(\"Current header: {}\", stringHeaderName);\n // As per the Java Servlet API 2.5 documentation:\n // Some headers, such as Accept-Language can be sent by clients\n // as several headers each with a different value rather than\n // sending the header as a comma separated list.\n // Thus, we get an Enumeration of the header values sent by the\n // client\n Enumeration<String> enumerationOfHeaderValues = httpServletRequest.getHeaders(stringHeaderName);\n\n while (enumerationOfHeaderValues.hasMoreElements()) {\n String stringHeaderValue = enumerationOfHeaderValues.nextElement();\n // In case the proxy host is running multiple virtual servers,\n // rewrite the Host header to ensure that we get content from\n // the correct virtual server\n if (stringHeaderName.equalsIgnoreCase(STRING_HOST_HEADER_NAME) &&\n requestInfo.handle) {\n String hostValue = getHostHeaderForHost(hostName);\n if (hostValue != null) {\n stringHeaderValue = hostValue;\n }\n }\n\n Header header = new Header(stringHeaderName, stringHeaderValue);\n // Set the same header on the proxy request\n httpMethodProxyRequest.addRequestHeader(header);\n }\n }\n\n // this strips transfer encoding headers and adds in the appropriate content-length header\n // based on the hint provided in the ODO-POST-TYPE header(sent from BrowserMobProxyHandler)\n if (stripTransferEncoding) {\n httpMethodProxyRequest.removeRequestHeader(\"transfer-encoding\");\n\n // add content length back in based on the ODO information\n String contentLengthHint = httpServletRequest.getHeader(\"ODO-POST-TYPE\");\n String[] contentLengthParts = contentLengthHint.split(\":\");\n httpMethodProxyRequest.addRequestHeader(\"content-length\", contentLengthParts[1]);\n\n // remove the odo-post-type header\n httpMethodProxyRequest.removeRequestHeader(\"ODO-POST-TYPE\");\n }\n\n // bail if we aren't fully handling this request\n if (!requestInfo.handle) {\n return;\n }\n\n // deal with header overrides for the request\n processRequestHeaderOverrides(httpMethodProxyRequest);\n }",
"public int getJdbcType(String ojbType) throws SQLException\r\n {\r\n int result;\r\n if(ojbType == null) ojbType = \"\";\r\n\t\tojbType = ojbType.toLowerCase();\r\n if (ojbType.equals(\"bit\"))\r\n result = Types.BIT;\r\n else if (ojbType.equals(\"tinyint\"))\r\n result = Types.TINYINT;\r\n else if (ojbType.equals(\"smallint\"))\r\n result = Types.SMALLINT;\r\n else if (ojbType.equals(\"integer\"))\r\n result = Types.INTEGER;\r\n else if (ojbType.equals(\"bigint\"))\r\n result = Types.BIGINT;\r\n\r\n else if (ojbType.equals(\"float\"))\r\n result = Types.FLOAT;\r\n else if (ojbType.equals(\"real\"))\r\n result = Types.REAL;\r\n else if (ojbType.equals(\"double\"))\r\n result = Types.DOUBLE;\r\n\r\n else if (ojbType.equals(\"numeric\"))\r\n result = Types.NUMERIC;\r\n else if (ojbType.equals(\"decimal\"))\r\n result = Types.DECIMAL;\r\n\r\n else if (ojbType.equals(\"char\"))\r\n result = Types.CHAR;\r\n else if (ojbType.equals(\"varchar\"))\r\n result = Types.VARCHAR;\r\n else if (ojbType.equals(\"longvarchar\"))\r\n result = Types.LONGVARCHAR;\r\n\r\n else if (ojbType.equals(\"date\"))\r\n result = Types.DATE;\r\n else if (ojbType.equals(\"time\"))\r\n result = Types.TIME;\r\n else if (ojbType.equals(\"timestamp\"))\r\n result = Types.TIMESTAMP;\r\n\r\n else if (ojbType.equals(\"binary\"))\r\n result = Types.BINARY;\r\n else if (ojbType.equals(\"varbinary\"))\r\n result = Types.VARBINARY;\r\n else if (ojbType.equals(\"longvarbinary\"))\r\n result = Types.LONGVARBINARY;\r\n\r\n\t\telse if (ojbType.equals(\"clob\"))\r\n \t\tresult = Types.CLOB;\r\n\t\telse if (ojbType.equals(\"blob\"))\r\n\t\t\tresult = Types.BLOB;\r\n else\r\n throw new SQLException(\r\n \"The type '\"+ ojbType + \"' is not a valid jdbc type.\");\r\n return result;\r\n }",
"public boolean needsRefresh() {\n boolean needsRefresh;\n\n this.refreshLock.readLock().lock();\n long now = System.currentTimeMillis();\n long tokenDuration = (now - this.lastRefresh);\n needsRefresh = (tokenDuration >= this.expires - REFRESH_EPSILON);\n this.refreshLock.readLock().unlock();\n\n return needsRefresh;\n }"
] |
Sets the body filter for this ID
@param pathId ID of path
@param bodyFilter Body filter to set | [
"public void setBodyFilter(int pathId, String bodyFilter) {\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_BODY_FILTER + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, bodyFilter);\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 synchronized int getPartitionStoreMoves() {\n int count = 0;\n for (List<Integer> entry : storeToPartitionIds.values())\n count += entry.size();\n return count;\n }",
"private void writeExceptions(List<ProjectCalendar> records) throws IOException\n {\n for (ProjectCalendar record : records)\n {\n if (!record.getCalendarExceptions().isEmpty())\n {\n // Need to move HOLI up here and get 15 exceptions per line as per USACE spec.\n // for now, we'll write one line for each calendar exception, hope there aren't too many\n //\n // changing this would be a serious upgrade, too much coding to do today....\n for (ProjectCalendarException ex : record.getCalendarExceptions())\n {\n writeCalendarException(record, ex);\n }\n }\n m_eventManager.fireCalendarWrittenEvent(record); // left here from MPX template, maybe not needed???\n }\n }",
"private static Date getSentDate(MimeMessage msg, Date defaultVal) {\r\n if (msg == null) {\r\n return defaultVal;\r\n }\r\n try {\r\n Date sentDate = msg.getSentDate();\r\n if (sentDate == null) {\r\n return defaultVal;\r\n } else {\r\n return sentDate;\r\n }\r\n } catch (MessagingException me) {\r\n return new Date();\r\n }\r\n }",
"public static base_responses update(nitro_service client, snmpuser resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsnmpuser updateresources[] = new snmpuser[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new snmpuser();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].group = resources[i].group;\n\t\t\t\tupdateresources[i].authtype = resources[i].authtype;\n\t\t\t\tupdateresources[i].authpasswd = resources[i].authpasswd;\n\t\t\t\tupdateresources[i].privtype = resources[i].privtype;\n\t\t\t\tupdateresources[i].privpasswd = resources[i].privpasswd;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"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 <InnerT> Observable<InnerT> convertPageToInnerAsync(Observable<Page<InnerT>> innerPage) {\n return innerPage.flatMap(new Func1<Page<InnerT>, Observable<InnerT>>() {\n @Override\n public Observable<InnerT> call(Page<InnerT> pageInner) {\n return Observable.from(pageInner.items());\n }\n });\n }",
"public static base_response sync(nitro_service client, gslbconfig resource) throws Exception {\n\t\tgslbconfig syncresource = new gslbconfig();\n\t\tsyncresource.preview = resource.preview;\n\t\tsyncresource.debug = resource.debug;\n\t\tsyncresource.forcesync = resource.forcesync;\n\t\tsyncresource.nowarn = resource.nowarn;\n\t\tsyncresource.saveconfig = resource.saveconfig;\n\t\tsyncresource.command = resource.command;\n\t\treturn syncresource.perform_operation(client,\"sync\");\n\t}",
"public PreparedStatement getPreparedStatement(ClassDescriptor cds, String sql,\r\n boolean scrollable, int explicitFetchSizeHint, boolean callableStmt)\r\n throws PersistenceBrokerException\r\n {\r\n try\r\n {\r\n return cds.getStatementsForClass(m_conMan).getPreparedStmt(m_conMan.getConnection(), sql, scrollable, explicitFetchSizeHint, callableStmt);\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 static Object toObject(Class<?> clazz, Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (clazz == null) {\n return value;\n }\n\n if (java.sql.Date.class.isAssignableFrom(clazz)) {\n return toDate(value);\n }\n if (java.sql.Time.class.isAssignableFrom(clazz)) {\n return toTime(value);\n }\n if (java.sql.Timestamp.class.isAssignableFrom(clazz)) {\n return toTimestamp(value);\n }\n if (java.util.Date.class.isAssignableFrom(clazz)) {\n return toDateTime(value);\n }\n\n return value;\n }"
] |
Get photos from the user's contacts.
This method requires authentication with 'read' permission.
@param count
The number of photos to return
@param justFriends
Set to true to only show friends photos
@param singlePhoto
Set to true to get a single photo
@param includeSelf
Set to true to include self
@return The Collection of photos
@throws FlickrException | [
"public PhotoList<Photo> getContactsPhotos(int count, boolean justFriends, boolean singlePhoto, boolean includeSelf) 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_CONTACTS_PHOTOS);\r\n\r\n if (count > 0) {\r\n parameters.put(\"count\", Integer.toString(count));\r\n }\r\n if (justFriends) {\r\n parameters.put(\"just_friends\", \"1\");\r\n }\r\n if (singlePhoto) {\r\n parameters.put(\"single_photo\", \"1\");\r\n }\r\n if (includeSelf) {\r\n parameters.put(\"include_self\", \"1\");\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 NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\r\n photos.setPage(\"1\");\r\n photos.setPages(\"1\");\r\n photos.setPerPage(\"\" + photoNodes.getLength());\r\n photos.setTotal(\"\" + photoNodes.getLength());\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 void setDataOffsets(int[] offsets)\n {\n assert(mLevels == offsets.length);\n NativeBitmapImage.updateCompressed(getNative(), mWidth, mHeight, mImageSize, mData, mLevels, offsets);\n mData = null;\n }",
"public PeriodicEvent runEvery(Runnable task, float delay, float period) {\n return runEvery(task, delay, period, null);\n }",
"public void cache(Identity oid, Object obj)\r\n {\r\n if (oid != null && obj != null)\r\n {\r\n ObjectCache cache = getCache(oid, obj, METHOD_CACHE);\r\n if (cache != null)\r\n {\r\n cache.cache(oid, obj);\r\n }\r\n }\r\n }",
"public String getLinkUrl(JSONObject jsonObject){\n if(jsonObject == null) return null;\n try {\n JSONObject urlObject = jsonObject.has(\"url\") ? jsonObject.getJSONObject(\"url\") : null;\n if(urlObject == null) return null;\n JSONObject androidObject = urlObject.has(\"android\") ? urlObject.getJSONObject(\"android\") : null;\n if(androidObject != null){\n return androidObject.has(\"text\") ? androidObject.getString(\"text\") : \"\";\n }else{\n return \"\";\n }\n } catch (JSONException e) {\n Logger.v(\"Unable to get Link URL with JSON - \"+e.getLocalizedMessage());\n return null;\n }\n }",
"public void rollback() throws GeomajasException {\n\t\ttry {\n\t\t\tsetConfigLocations(previousConfigLocations);\n\t\t\trefresh();\n\t\t} catch (Exception e) {\n\t\t\tthrow new GeomajasException(e, ExceptionCode.REFRESH_CONFIGURATION_FAILED);\n\t\t}\n\t}",
"public void delete(Object obj, boolean ignoreReferences) throws PersistenceBrokerException\n {\n if(isTxCheck() && !isInTransaction())\n {\n if(logger.isEnabledFor(Logger.ERROR))\n {\n String msg = \"No running PB-tx found. Please, only delete objects in context of a PB-transaction\" +\n \" to avoid side-effects - e.g. when rollback of complex objects.\";\n try\n {\n throw new Exception(\"** Delete object without active PersistenceBroker transaction **\");\n }\n catch(Exception e)\n {\n logger.error(msg, e);\n }\n }\n }\n try\n {\n doDelete(obj, ignoreReferences);\n }\n finally\n {\n markedForDelete.clear();\n }\n }",
"public static <E> void retainAll(Collection<E> elems, Filter<? super E> filter) {\r\n for (Iterator<E> iter = elems.iterator(); iter.hasNext();) {\r\n E elem = iter.next();\r\n if ( ! filter.accept(elem)) {\r\n iter.remove();\r\n }\r\n }\r\n }",
"@SuppressWarnings({ \"unchecked\", \"rawtypes\" })\n protected void addStoreToSession(String store) {\n\n Exception initializationException = null;\n\n storeNames.add(store);\n\n for(Node node: nodesToStream) {\n\n SocketDestination destination = null;\n SocketAndStreams sands = null;\n\n try {\n destination = new SocketDestination(node.getHost(),\n node.getAdminPort(),\n RequestFormatType.ADMIN_PROTOCOL_BUFFERS);\n sands = streamingSocketPool.checkout(destination);\n DataOutputStream outputStream = sands.getOutputStream();\n DataInputStream inputStream = sands.getInputStream();\n\n nodeIdStoreToSocketRequest.put(new Pair(store, node.getId()), destination);\n nodeIdStoreToOutputStreamRequest.put(new Pair(store, node.getId()), outputStream);\n nodeIdStoreToInputStreamRequest.put(new Pair(store, node.getId()), inputStream);\n nodeIdStoreToSocketAndStreams.put(new Pair(store, node.getId()), sands);\n nodeIdStoreInitialized.put(new Pair(store, node.getId()), false);\n\n remoteStoreDefs = adminClient.metadataMgmtOps.getRemoteStoreDefList(node.getId())\n .getValue();\n\n } catch(Exception e) {\n logger.error(e);\n try {\n close(sands.getSocket());\n streamingSocketPool.checkin(destination, sands);\n } catch(Exception ioE) {\n logger.error(ioE);\n }\n\n if(!faultyNodes.contains(node.getId()))\n faultyNodes.add(node.getId());\n initializationException = e;\n }\n\n }\n\n if(initializationException != null)\n throw new VoldemortException(initializationException);\n\n if(store.equals(\"slop\"))\n return;\n\n boolean foundStore = false;\n\n for(StoreDefinition remoteStoreDef: remoteStoreDefs) {\n if(remoteStoreDef.getName().equals(store)) {\n RoutingStrategyFactory factory = new RoutingStrategyFactory();\n RoutingStrategy storeRoutingStrategy = factory.updateRoutingStrategy(remoteStoreDef,\n adminClient.getAdminClientCluster());\n\n storeToRoutingStrategy.put(store, storeRoutingStrategy);\n validateSufficientNodesAvailable(blackListedNodes, remoteStoreDef);\n foundStore = true;\n break;\n }\n }\n if(!foundStore) {\n logger.error(\"Store Name not found on the cluster\");\n throw new VoldemortException(\"Store Name not found on the cluster\");\n\n }\n\n }",
"public Duration getBaselineDuration()\n {\n Object result = getCachedValue(TaskField.BASELINE_DURATION);\n if (result == null)\n {\n result = getCachedValue(TaskField.BASELINE_ESTIMATED_DURATION);\n }\n\n if (!(result instanceof Duration))\n {\n result = null;\n }\n return (Duration) result;\n }"
] |
Translate the operation address.
@param op the operation
@return the new operation | [
"public ModelNode translateOperationForProxy(final ModelNode op) {\n return translateOperationForProxy(op, PathAddress.pathAddress(op.get(OP_ADDR)));\n }"
] | [
"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 }",
"int add(DownloadRequest request) {\n\t\tint downloadId = getDownloadId();\n\t\t// Tag the request as belonging to this queue and add it to the set of current requests.\n\t\trequest.setDownloadRequestQueue(this);\n\n\t\tsynchronized (mCurrentRequests) {\n\t\t\tmCurrentRequests.add(request);\n\t\t}\n\n\t\t// Process requests in the order they are added.\n\t\trequest.setDownloadId(downloadId);\n\t\tmDownloadQueue.add(request);\n\n\t\treturn downloadId;\n\t}",
"@SafeVarargs\n public static <T> Set<T> of(T... elements) {\n Preconditions.checkNotNull(elements);\n return ImmutableSet.<T> builder().addAll(elements).build();\n }",
"public static List<ObjectModelResolver> getResolvers() {\n if (resolvers == null) {\n synchronized (serviceLoader) {\n if (resolvers == null) {\n List<ObjectModelResolver> foundResolvers = new ArrayList<ObjectModelResolver>();\n for (ObjectModelResolver resolver : serviceLoader) {\n foundResolvers.add(resolver);\n }\n resolvers = foundResolvers;\n }\n }\n }\n\n return resolvers;\n }",
"public CmsSolrQuery getQuery(CmsObject cms) {\n\n final CmsSolrQuery query = new CmsSolrQuery();\n\n // set categories\n query.setCategories(m_categories);\n\n // set container types\n if (null != m_containerTypes) {\n query.addFilterQuery(CmsSearchField.FIELD_CONTAINER_TYPES, m_containerTypes, false, false);\n }\n\n // Set date created time filter\n query.addFilterQuery(\n CmsSearchUtil.getDateCreatedTimeRangeFilterQuery(\n CmsSearchField.FIELD_DATE_CREATED,\n getDateCreatedRange().m_startTime,\n getDateCreatedRange().m_endTime));\n\n // Set date last modified time filter\n query.addFilterQuery(\n CmsSearchUtil.getDateCreatedTimeRangeFilterQuery(\n CmsSearchField.FIELD_DATE_LASTMODIFIED,\n getDateLastModifiedRange().m_startTime,\n getDateLastModifiedRange().m_endTime));\n\n // set scope / folders to search in\n m_foldersToSearchIn = new ArrayList<String>();\n addFoldersToSearchIn(m_folders);\n addFoldersToSearchIn(m_galleries);\n setSearchFolders(cms);\n query.addFilterQuery(\n CmsSearchField.FIELD_PARENT_FOLDERS,\n new ArrayList<String>(m_foldersToSearchIn),\n false,\n true);\n\n if (!m_ignoreSearchExclude) {\n // Reference for the values: CmsGallerySearchIndex.java, field EXCLUDE_PROPERTY_VALUES\n query.addFilterQuery(\n \"-\" + CmsSearchField.FIELD_SEARCH_EXCLUDE,\n Arrays.asList(\n new String[] {\n A_CmsSearchIndex.PROPERTY_SEARCH_EXCLUDE_VALUE_ALL,\n A_CmsSearchIndex.PROPERTY_SEARCH_EXCLUDE_VALUE_GALLERY}),\n false,\n true);\n }\n\n // set matches per page\n query.setRows(new Integer(m_matchesPerPage));\n\n // set resource types\n if (null != m_resourceTypes) {\n List<String> resourceTypes = new ArrayList<>(m_resourceTypes);\n if (m_resourceTypes.contains(CmsResourceTypeFunctionConfig.TYPE_NAME)\n && !m_resourceTypes.contains(CmsXmlDynamicFunctionHandler.TYPE_FUNCTION)) {\n resourceTypes.add(CmsXmlDynamicFunctionHandler.TYPE_FUNCTION);\n }\n query.setResourceTypes(resourceTypes);\n }\n\n // set result page\n query.setStart(new Integer((m_resultPage - 1) * m_matchesPerPage));\n\n // set search locale\n if (null != m_locale) {\n query.setLocales(CmsLocaleManager.getLocale(m_locale));\n }\n\n // set search words\n if (null != m_words) {\n query.setQuery(m_words);\n }\n\n // set sort order\n query.setSort(getSort().getFirst(), getSort().getSecond());\n\n // set result collapsing by id\n query.addFilterQuery(\"{!collapse field=id}\");\n\n query.setFields(CmsGallerySearchResult.getRequiredSolrFields());\n\n if ((m_allowedFunctions != null) && !m_allowedFunctions.isEmpty()) {\n String functionFilter = \"((-type:(\"\n + CmsXmlDynamicFunctionHandler.TYPE_FUNCTION\n + \" OR \"\n + CmsResourceTypeFunctionConfig.TYPE_NAME\n + \")) OR (id:(\";\n Iterator<CmsUUID> it = m_allowedFunctions.iterator();\n while (it.hasNext()) {\n CmsUUID id = it.next();\n functionFilter += id.toString();\n if (it.hasNext()) {\n functionFilter += \" OR \";\n }\n }\n functionFilter += \")))\";\n query.addFilterQuery(functionFilter);\n }\n\n return query;\n }",
"public static DMatrixSparseCSC diag(double... values ) {\n int N = values.length;\n return diag(new DMatrixSparseCSC(N,N,N),values,0,N);\n }",
"public void getDataDTD(Writer output) throws DataTaskException\r\n {\r\n try\r\n {\r\n output.write(\"<!ELEMENT dataset (\\n\");\r\n for (Iterator it = _preparedModel.getElementNames(); it.hasNext();)\r\n {\r\n String elementName = (String)it.next();\r\n\r\n output.write(\" \");\r\n output.write(elementName);\r\n output.write(\"*\");\r\n output.write(it.hasNext() ? \" |\\n\" : \"\\n\");\r\n }\r\n output.write(\")>\\n<!ATTLIST dataset\\n name CDATA #REQUIRED\\n>\\n\");\r\n for (Iterator it = _preparedModel.getElementNames(); it.hasNext();)\r\n {\r\n String elementName = (String)it.next();\r\n List classDescs = _preparedModel.getClassDescriptorsMappingTo(elementName);\r\n\r\n if (classDescs == null)\r\n {\r\n output.write(\"\\n<!-- Indirection table\");\r\n }\r\n else\r\n {\r\n output.write(\"\\n<!-- Mapped to : \");\r\n for (Iterator classDescIt = classDescs.iterator(); classDescIt.hasNext();)\r\n {\r\n ClassDescriptor classDesc = (ClassDescriptor)classDescIt.next();\r\n \r\n output.write(classDesc.getClassNameOfObject());\r\n if (classDescIt.hasNext())\r\n {\r\n output.write(\"\\n \");\r\n }\r\n }\r\n }\r\n output.write(\" -->\\n<!ELEMENT \");\r\n output.write(elementName);\r\n output.write(\" EMPTY>\\n<!ATTLIST \");\r\n output.write(elementName);\r\n output.write(\"\\n\");\r\n\r\n for (Iterator attrIt = _preparedModel.getAttributeNames(elementName); attrIt.hasNext();)\r\n {\r\n String attrName = (String)attrIt.next();\r\n\r\n output.write(\" \");\r\n output.write(attrName);\r\n output.write(\" CDATA #\");\r\n output.write(_preparedModel.isRequired(elementName, attrName) ? \"REQUIRED\" : \"IMPLIED\");\r\n output.write(\"\\n\");\r\n }\r\n output.write(\">\\n\");\r\n }\r\n }\r\n catch (IOException ex)\r\n {\r\n throw new DataTaskException(ex);\r\n }\r\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 openBrowser(URI url) throws IOException {\n if (Desktop.isDesktopSupported()) {\n Desktop.getDesktop().browse(url);\n } else {\n LOGGER.error(\"Can not open browser because this capability is not supported on \" +\n \"your platform. You can use the link below to open the report manually.\");\n }\n }"
] |
Computes the distance from a point p to the plane of this face.
@param p
the point
@return distance from the point to the plane | [
"public double distanceToPlane(Point3d p) {\n return normal.x * p.x + normal.y * p.y + normal.z * p.z - planeOffset;\n }"
] | [
"private void readRelationship(Link link)\n {\n Task sourceTask = m_taskIdMap.get(link.getSourceTaskID());\n Task destinationTask = m_taskIdMap.get(link.getDestinationTaskID());\n if (sourceTask != null && destinationTask != null)\n {\n Duration lag = getDuration(link.getLagUnit(), link.getLag());\n RelationType type = link.getType();\n Relation relation = destinationTask.addPredecessor(sourceTask, type, lag);\n relation.setUniqueID(link.getID());\n }\n }",
"public static boolean isIdentity(DMatrix a , double tol )\n {\n for( int i = 0; i < a.getNumRows(); i++ ) {\n for( int j = 0; j < a.getNumCols(); j++ ) {\n if( i == j ) {\n if( Math.abs(a.get(i,j)-1.0) > tol )\n return false;\n } else {\n if( Math.abs(a.get(i,j)) > tol )\n return false;\n }\n }\n }\n return true;\n }",
"@Override\n protected void _acceptTimestampVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint)\n throws JsonMappingException\n {\n SerializerProvider prov = visitor.getProvider();\n if ((prov != null) && useNanoseconds(prov)) {\n JsonNumberFormatVisitor v2 = visitor.expectNumberFormat(typeHint);\n if (v2 != null) {\n v2.numberType(NumberType.BIG_DECIMAL);\n }\n } else {\n JsonIntegerFormatVisitor v2 = visitor.expectIntegerFormat(typeHint);\n if (v2 != null) {\n v2.numberType(NumberType.LONG);\n }\n }\n }",
"public static gslbdomain_stats[] get(nitro_service service) throws Exception{\n\t\tgslbdomain_stats obj = new gslbdomain_stats();\n\t\tgslbdomain_stats[] response = (gslbdomain_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}",
"private static String convertISO88591toUTF8(String value) {\n try {\n return new String(value.getBytes(CharEncoding.ISO_8859_1), CharEncoding.UTF_8);\n }\n catch (UnsupportedEncodingException ex) {\n // ignore and fallback to original encoding\n return value;\n }\n }",
"List<MwDumpFile> mergeDumpLists(List<MwDumpFile> localDumps,\n\t\t\tList<MwDumpFile> onlineDumps) {\n\t\tList<MwDumpFile> result = new ArrayList<>(localDumps);\n\n\t\tHashSet<String> localDateStamps = new HashSet<>();\n\t\tfor (MwDumpFile dumpFile : localDumps) {\n\t\t\tlocalDateStamps.add(dumpFile.getDateStamp());\n\t\t}\n\t\tfor (MwDumpFile dumpFile : onlineDumps) {\n\t\t\tif (!localDateStamps.contains(dumpFile.getDateStamp())) {\n\t\t\t\tresult.add(dumpFile);\n\t\t\t}\n\t\t}\n\t\tresult.sort(Collections.reverseOrder(new MwDumpFile.DateComparator()));\n\t\treturn result;\n\t}",
"private static boolean implementsMethod(ClassNode classNode, String methodName, Class[] argTypes) {\r\n List methods = classNode.getMethods();\r\n if (argTypes == null || argTypes.length ==0) {\r\n for (Iterator i = methods.iterator(); i.hasNext();) {\r\n MethodNode mn = (MethodNode) i.next();\r\n boolean methodMatch = mn.getName().equals(methodName);\r\n if(methodMatch)return true;\r\n // TODO Implement further parameter analysis\r\n }\r\n }\r\n return false;\r\n }",
"public void generateMapFile(File jarFile, String mapFileName, boolean mapClassMethods) throws XMLStreamException, IOException, ClassNotFoundException, IntrospectionException\n {\n m_responseList = new LinkedList<String>();\n writeMapFile(mapFileName, jarFile, mapClassMethods);\n }",
"public Object[] getForeignKeyValues(Object obj, ClassDescriptor mif)\r\n throws PersistenceBrokerException\r\n {\r\n FieldDescriptor[] fks = getForeignKeyFieldDescriptors(mif);\r\n // materialize object only if FK fields are declared\r\n if(fks.length > 0) obj = ProxyHelper.getRealObject(obj);\r\n Object[] result = new Object[fks.length];\r\n for (int i = 0; i < result.length; i++)\r\n {\r\n FieldDescriptor fmd = fks[i];\r\n PersistentField f = fmd.getPersistentField();\r\n\r\n // BRJ: do NOT convert.\r\n // conversion is done when binding the sql-statement\r\n //\r\n // FieldConversion fc = fmd.getFieldConversion();\r\n // Object val = fc.javaToSql(f.get(obj));\r\n\r\n result[i] = f.get(obj);\r\n }\r\n return result;\r\n }"
] |
Guess the type of the given dump from its filename.
@param fileName
@return dump type, defaulting to JSON if no type was found | [
"private static DumpContentType guessDumpContentType(String fileName) {\n\t\tString lcDumpName = fileName.toLowerCase();\n\t\tif (lcDumpName.contains(\".json.gz\")) {\n\t\t\treturn DumpContentType.JSON;\n\t\t} else if (lcDumpName.contains(\".json.bz2\")) {\n\t\t\treturn DumpContentType.JSON;\n\t\t} else if (lcDumpName.contains(\".sql.gz\")) {\n\t\t\treturn DumpContentType.SITES;\n\t\t} else if (lcDumpName.contains(\".xml.bz2\")) {\n\t\t\tif (lcDumpName.contains(\"daily\")) {\n\t\t\t\treturn DumpContentType.DAILY;\n\t\t\t} else if (lcDumpName.contains(\"current\")) {\n\t\t\t\treturn DumpContentType.CURRENT;\n\t\t\t} else {\n\t\t\t\treturn DumpContentType.FULL;\n\t\t\t}\n\t\t} else {\n\t\t\tlogger.warn(\"Could not guess type of the dump file \\\"\" + fileName\n\t\t\t\t\t+ \"\\\". Defaulting to json.gz.\");\n\t\t\treturn DumpContentType.JSON;\n\t\t}\n\t}"
] | [
"void decodeContentType(String rawLine) {\r\n int slash = rawLine.indexOf('/');\r\n if (slash == -1) {\r\n// if (DEBUG) getLogger().debug(\"decoding ... no slash found\");\r\n return;\r\n } else {\r\n primaryType = rawLine.substring(0, slash).trim();\r\n }\r\n int semicolon = rawLine.indexOf(';');\r\n if (semicolon == -1) {\r\n// if (DEBUG) getLogger().debug(\"decoding ... no semicolon found\");\r\n secondaryType = rawLine.substring(slash + 1).trim();\r\n return;\r\n }\r\n // have parameters\r\n secondaryType = rawLine.substring(slash + 1, semicolon).trim();\r\n Header h = new Header(rawLine);\r\n parameters = h.getParams();\r\n }",
"public boolean destroyDependentInstance(T instance) {\n synchronized (dependentInstances) {\n for (Iterator<ContextualInstance<?>> iterator = dependentInstances.iterator(); iterator.hasNext();) {\n ContextualInstance<?> contextualInstance = iterator.next();\n if (contextualInstance.getInstance() == instance) {\n iterator.remove();\n destroy(contextualInstance);\n return true;\n }\n }\n }\n return false;\n }",
"public static base_responses update(nitro_service client, gslbsite resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tgslbsite updateresources[] = new gslbsite[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new gslbsite();\n\t\t\t\tupdateresources[i].sitename = resources[i].sitename;\n\t\t\t\tupdateresources[i].metricexchange = resources[i].metricexchange;\n\t\t\t\tupdateresources[i].nwmetricexchange = resources[i].nwmetricexchange;\n\t\t\t\tupdateresources[i].sessionexchange = resources[i].sessionexchange;\n\t\t\t\tupdateresources[i].triggermonitor = resources[i].triggermonitor;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static Map<String, String> mapStringToMap(String map) {\r\n String[] m = map.split(\"[,;]\");\r\n Map<String, String> res = new HashMap<String, String>();\r\n for (String str : m) {\r\n int index = str.lastIndexOf('=');\r\n String key = str.substring(0, index);\r\n String val = str.substring(index + 1);\r\n res.put(key.trim(), val.trim());\r\n }\r\n return res;\r\n }",
"public static void setTranslucentNavigationFlag(Activity activity, boolean on) {\n if (Build.VERSION.SDK_INT >= 19) {\n setFlag(activity, WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION, on);\n }\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 static final String printAccrueType(AccrueType value)\n {\n return (Integer.toString(value == null ? AccrueType.PRORATED.getValue() : value.getValue()));\n }",
"private void refreshInstance(Object cachedInstance, Identity oid, ClassDescriptor cld)\n {\n // read in fresh copy from the db, but do not cache it\n Object freshInstance = getPlainDBObject(cld, oid);\n\n // update all primitive typed attributes\n FieldDescriptor[] fields = cld.getFieldDescriptions();\n FieldDescriptor fmd;\n PersistentField fld;\n for (int i = 0; i < fields.length; i++)\n {\n fmd = fields[i];\n fld = fmd.getPersistentField();\n fld.set(cachedInstance, fld.get(freshInstance));\n }\n }",
"public static base_response delete(nitro_service client, String serverip) throws Exception {\n\t\tntpserver deleteresource = new ntpserver();\n\t\tdeleteresource.serverip = serverip;\n\t\treturn deleteresource.delete_resource(client);\n\t}"
] |
This is a convenience method which allows all projects in an
XER file to be read in a single pass.
@param is input stream
@param linkCrossProjectRelations add Relation links that cross ProjectFile boundaries
@return list of ProjectFile instances
@throws MPXJException | [
"public List<ProjectFile> readAll(InputStream is, boolean linkCrossProjectRelations) throws MPXJException\n {\n try\n {\n m_tables = new HashMap<String, List<Row>>();\n m_numberFormat = new DecimalFormat();\n\n processFile(is);\n\n List<Row> rows = getRows(\"project\", null, null);\n List<ProjectFile> result = new ArrayList<ProjectFile>(rows.size());\n List<ExternalPredecessorRelation> externalPredecessors = new ArrayList<ExternalPredecessorRelation>();\n for (Row row : rows)\n {\n setProjectID(row.getInt(\"proj_id\"));\n\n m_reader = new PrimaveraReader(m_taskUdfCounters, m_resourceUdfCounters, m_assignmentUdfCounters, m_resourceFields, m_wbsFields, m_taskFields, m_assignmentFields, m_aliases, m_matchPrimaveraWBS);\n ProjectFile project = m_reader.getProject();\n project.getEventManager().addProjectListeners(m_projectListeners);\n\n processProjectProperties();\n processUserDefinedFields();\n processCalendars();\n processResources();\n processResourceRates();\n processTasks();\n processPredecessors();\n processAssignments();\n\n externalPredecessors.addAll(m_reader.getExternalPredecessors());\n\n m_reader = null;\n project.updateStructure();\n\n result.add(project);\n }\n\n if (linkCrossProjectRelations)\n {\n for (ExternalPredecessorRelation externalRelation : externalPredecessors)\n {\n Task predecessorTask;\n // we could aggregate the project task id maps but that's likely more work\n // than just looping through the projects\n for (ProjectFile proj : result)\n {\n predecessorTask = proj.getTaskByUniqueID(externalRelation.getSourceUniqueID());\n if (predecessorTask != null)\n {\n Relation relation = externalRelation.getTargetTask().addPredecessor(predecessorTask, externalRelation.getType(), externalRelation.getLag());\n relation.setUniqueID(externalRelation.getUniqueID());\n break;\n }\n }\n // if predecessorTask not found the external task is outside of the file so ignore\n }\n }\n\n return result;\n }\n\n finally\n {\n m_reader = null;\n m_tables = null;\n m_currentTableName = null;\n m_currentTable = null;\n m_currentFieldNames = null;\n m_defaultCurrencyName = null;\n m_currencyMap.clear();\n m_numberFormat = null;\n m_defaultCurrencyData = null;\n }\n }"
] | [
"public synchronized void tick() {\n long currentTime = GVRTime.getMilliTime();\n long cutoffTime = currentTime - BUFFER_SECONDS * 1000;\n ListIterator<Long> it = mTimestamps.listIterator();\n while (it.hasNext()) {\n Long timestamp = it.next();\n if (timestamp < cutoffTime) {\n it.remove();\n } else {\n break;\n }\n }\n\n mTimestamps.add(currentTime);\n mStatColumn.addValue(((float)mTimestamps.size()) / BUFFER_SECONDS);\n }",
"public void link(Object targetObject, ClassDescriptor cld, ObjectReferenceDescriptor rds, Object referencedObject, boolean insert)\n {\n // MBAIRD: we have 'disassociated' this object from the referenced object,\n // the object represented by the reference descriptor is now null, so set\n // the fk in the target object to null.\n // arminw: if an insert was done and ref object was null, we should allow\n // to pass FK fields of main object (maybe only the FK fields are set)\n if (referencedObject == null)\n {\n /*\n arminw:\n if update we set FK fields to 'null', because reference was disassociated\n We do nothing on insert, maybe only the FK fields of main object (without\n materialization of the reference object) are set by the user\n */\n if(!insert)\n {\n unlinkFK(targetObject, cld, rds);\n }\n }\n else\n {\n setFKField(targetObject, cld, rds, referencedObject);\n }\n }",
"@Override\n public void writeText(PDDocument doc, Writer outputStream) throws IOException\n {\n try\n {\n DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();\n DOMImplementationLS impl = (DOMImplementationLS)registry.getDOMImplementation(\"LS\");\n LSSerializer writer = impl.createLSSerializer();\n LSOutput output = impl.createLSOutput();\n writer.getDomConfig().setParameter(\"format-pretty-print\", true);\n output.setCharacterStream(outputStream);\n createDOM(doc);\n writer.write(getDocument(), output);\n } catch (ClassCastException e) {\n throw new IOException(\"Error: cannot initialize the DOM serializer\", e);\n } catch (ClassNotFoundException e) {\n throw new IOException(\"Error: cannot initialize the DOM serializer\", e);\n } catch (InstantiationException e) {\n throw new IOException(\"Error: cannot initialize the DOM serializer\", e);\n } catch (IllegalAccessException e) {\n throw new IOException(\"Error: cannot initialize the DOM serializer\", e);\n }\n }",
"public void setWorkingDay(Day day, boolean working)\n {\n setWorkingDay(day, (working ? DayType.WORKING : DayType.NON_WORKING));\n }",
"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 }",
"private ResultAction getFailedResultAction(Throwable cause) {\n if (currentStage == Stage.MODEL || cancelled || isRollbackOnRuntimeFailure() || isRollbackOnly()\n || (cause != null && !(cause instanceof OperationFailedException))) {\n return ResultAction.ROLLBACK;\n }\n return ResultAction.KEEP;\n }",
"public static String paramMapToString(final Map<String, String[]> parameters) {\n\n final StringBuffer result = new StringBuffer();\n for (final String key : parameters.keySet()) {\n String[] values = parameters.get(key);\n if (null == values) {\n result.append(key).append('&');\n } else {\n for (final String value : parameters.get(key)) {\n result.append(key).append('=').append(CmsEncoder.encode(value)).append('&');\n }\n }\n }\n // remove last '&'\n if (result.length() > 0) {\n result.setLength(result.length() - 1);\n }\n return result.toString();\n }",
"protected Iterator<MACAddress> iterator(MACAddress original) {\r\n\t\tMACAddressCreator creator = getAddressCreator();\r\n\t\tboolean isSingle = !isMultiple();\r\n\t\treturn iterator(\r\n\t\t\t\tisSingle ? original : null, \r\n\t\t\t\tcreator,//using a lambda for this one results in a big performance hit\r\n\t\t\t\tisSingle ? null : segmentsIterator(),\r\n\t\t\t\tgetNetwork().getPrefixConfiguration().allPrefixedAddressesAreSubnets() ? null : getPrefixLength());\r\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}"
] |
Creates a resource key defined as a child of key defined by enumeration value.
@see #key(Enum)
@see #child(String)
@param enumValue the enumeration value defining the parent key
@param key the child id
@return the resource key | [
"public static ResourceKey key(Enum<?> enumValue, String key) {\n return new ResourceKey(enumValue.getClass().getName(), enumValue.name()).child(key);\n }"
] | [
"protected void markStatementsForInsertion(\n\t\t\tStatementDocument currentDocument, List<Statement> addStatements) {\n\t\tfor (Statement statement : addStatements) {\n\t\t\taddStatement(statement, true);\n\t\t}\n\n\t\tfor (StatementGroup sg : currentDocument.getStatementGroups()) {\n\t\t\tif (this.toKeep.containsKey(sg.getProperty())) {\n\t\t\t\tfor (Statement statement : sg) {\n\t\t\t\t\tif (!this.toDelete.contains(statement.getStatementId())) {\n\t\t\t\t\t\taddStatement(statement, false);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}",
"public static base_response update(nitro_service client, appfwlearningsettings resource) throws Exception {\n\t\tappfwlearningsettings updateresource = new appfwlearningsettings();\n\t\tupdateresource.profilename = resource.profilename;\n\t\tupdateresource.starturlminthreshold = resource.starturlminthreshold;\n\t\tupdateresource.starturlpercentthreshold = resource.starturlpercentthreshold;\n\t\tupdateresource.cookieconsistencyminthreshold = resource.cookieconsistencyminthreshold;\n\t\tupdateresource.cookieconsistencypercentthreshold = resource.cookieconsistencypercentthreshold;\n\t\tupdateresource.csrftagminthreshold = resource.csrftagminthreshold;\n\t\tupdateresource.csrftagpercentthreshold = resource.csrftagpercentthreshold;\n\t\tupdateresource.fieldconsistencyminthreshold = resource.fieldconsistencyminthreshold;\n\t\tupdateresource.fieldconsistencypercentthreshold = resource.fieldconsistencypercentthreshold;\n\t\tupdateresource.crosssitescriptingminthreshold = resource.crosssitescriptingminthreshold;\n\t\tupdateresource.crosssitescriptingpercentthreshold = resource.crosssitescriptingpercentthreshold;\n\t\tupdateresource.sqlinjectionminthreshold = resource.sqlinjectionminthreshold;\n\t\tupdateresource.sqlinjectionpercentthreshold = resource.sqlinjectionpercentthreshold;\n\t\tupdateresource.fieldformatminthreshold = resource.fieldformatminthreshold;\n\t\tupdateresource.fieldformatpercentthreshold = resource.fieldformatpercentthreshold;\n\t\tupdateresource.xmlwsiminthreshold = resource.xmlwsiminthreshold;\n\t\tupdateresource.xmlwsipercentthreshold = resource.xmlwsipercentthreshold;\n\t\tupdateresource.xmlattachmentminthreshold = resource.xmlattachmentminthreshold;\n\t\tupdateresource.xmlattachmentpercentthreshold = resource.xmlattachmentpercentthreshold;\n\t\treturn updateresource.update_resource(client);\n\t}",
"private void readPredecessors(net.sf.mpxj.planner.schema.Task plannerTask)\n {\n Task mpxjTask = m_projectFile.getTaskByUniqueID(getInteger(plannerTask.getId()));\n\n Predecessors predecessors = plannerTask.getPredecessors();\n if (predecessors != null)\n {\n List<Predecessor> predecessorList = predecessors.getPredecessor();\n for (Predecessor predecessor : predecessorList)\n {\n Integer predecessorID = getInteger(predecessor.getPredecessorId());\n Task predecessorTask = m_projectFile.getTaskByUniqueID(predecessorID);\n if (predecessorTask != null)\n {\n Duration lag = getDuration(predecessor.getLag());\n if (lag == null)\n {\n lag = Duration.getInstance(0, TimeUnit.HOURS);\n }\n Relation relation = mpxjTask.addPredecessor(predecessorTask, RELATIONSHIP_TYPES.get(predecessor.getType()), lag);\n m_eventManager.fireRelationReadEvent(relation);\n }\n }\n }\n\n //\n // Process child tasks\n //\n List<net.sf.mpxj.planner.schema.Task> childTasks = plannerTask.getTask();\n for (net.sf.mpxj.planner.schema.Task childTask : childTasks)\n {\n readPredecessors(childTask);\n }\n }",
"public static base_response add(nitro_service client, snmpmanager resource) throws Exception {\n\t\tsnmpmanager addresource = new snmpmanager();\n\t\taddresource.ipaddress = resource.ipaddress;\n\t\taddresource.netmask = resource.netmask;\n\t\taddresource.domainresolveretry = resource.domainresolveretry;\n\t\treturn addresource.add_resource(client);\n\t}",
"protected static void safeWriteErrorResponse(final Channel channel, final ManagementProtocolHeader header, final Throwable error) {\n if(header.getType() == ManagementProtocol.TYPE_REQUEST) {\n try {\n writeErrorResponse(channel, (ManagementRequestHeader) header, error);\n } catch(IOException ioe) {\n ProtocolLogger.ROOT_LOGGER.tracef(ioe, \"failed to write error response for %s on channel: %s\", header, channel);\n }\n }\n }",
"public static String getJsonDatatypeFromDatatypeIri(String datatypeIri) {\n\t\tswitch (datatypeIri) {\n\t\t\tcase DatatypeIdValue.DT_ITEM:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_ITEM;\n\t\t\tcase DatatypeIdValue.DT_GLOBE_COORDINATES:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_GLOBE_COORDINATES;\n\t\t\tcase DatatypeIdValue.DT_URL:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_URL;\n\t\t\tcase DatatypeIdValue.DT_COMMONS_MEDIA:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_COMMONS_MEDIA;\n\t\t\tcase DatatypeIdValue.DT_TIME:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_TIME;\n\t\t\tcase DatatypeIdValue.DT_QUANTITY:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_QUANTITY;\n\t\t\tcase DatatypeIdValue.DT_STRING:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_STRING;\n\t\t\tcase DatatypeIdValue.DT_MONOLINGUAL_TEXT:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_MONOLINGUAL_TEXT;\n\t\t\tcase DatatypeIdValue.DT_PROPERTY:\n\t\t\t\treturn DatatypeIdImpl.JSON_DT_PROPERTY;\n\t\t\tdefault:\n\t\t\t\t//We apply the reverse algorithm of JacksonDatatypeId::getDatatypeIriFromJsonDatatype\n\t\t\t\tMatcher matcher = DATATYPE_ID_PATTERN.matcher(datatypeIri);\n\t\t\t\tif(!matcher.matches()) {\n\t\t\t\t\tthrow new IllegalArgumentException(\"Unknown datatype: \" + datatypeIri);\n\t\t\t\t}\n\t\t\n\t\t\t\tStringBuilder jsonDatatypeBuilder = new StringBuilder();\n\t\t\t\tfor(char ch : StringUtils.uncapitalize(matcher.group(1)).toCharArray()) {\n\t\t\t\t\tif(Character.isUpperCase(ch)) {\n\t\t\t\t\t\tjsonDatatypeBuilder\n\t\t\t\t\t\t\t\t.append('-')\n\t\t\t\t\t\t\t\t.append(Character.toLowerCase(ch));\n\t\t\t\t\t} else {\n\t\t\t\t\t\tjsonDatatypeBuilder.append(ch);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn jsonDatatypeBuilder.toString();\n\t\t}\n\t}",
"public void handleStateEvent(String callbackKey) {\n if (handlers.containsKey(callbackKey) && handlers.get(callbackKey) instanceof StateEventHandler) {\n ((StateEventHandler) handlers.get(callbackKey)).handle();\n } else {\n System.err.println(\"Error in handle: \" + callbackKey + \" for state handler \");\n }\n }",
"public static void closeWithWarning(Closeable c) {\n if (c != null) {\n try {\n c.close();\n } catch (IOException e) {\n LOG.warning(\"Caught exception during close(): \" + e);\n }\n }\n }",
"private void extractFile(InputStream stream, File dir) throws IOException\n {\n byte[] header = new byte[8];\n byte[] fileName = new byte[13];\n byte[] dataSize = new byte[4];\n\n stream.read(header);\n stream.read(fileName);\n stream.read(dataSize);\n\n int dataSizeValue = getInt(dataSize, 0);\n String fileNameValue = getString(fileName, 0);\n File file = new File(dir, fileNameValue);\n\n if (dataSizeValue == 0)\n {\n FileHelper.createNewFile(file);\n }\n else\n {\n OutputStream os = new FileOutputStream(file);\n FixedLengthInputStream inputStream = new FixedLengthInputStream(stream, dataSizeValue);\n Blast blast = new Blast();\n blast.blast(inputStream, os);\n os.close();\n }\n }"
] |
Use this API to update gslbsite. | [
"public static base_response update(nitro_service client, gslbsite resource) throws Exception {\n\t\tgslbsite updateresource = new gslbsite();\n\t\tupdateresource.sitename = resource.sitename;\n\t\tupdateresource.metricexchange = resource.metricexchange;\n\t\tupdateresource.nwmetricexchange = resource.nwmetricexchange;\n\t\tupdateresource.sessionexchange = resource.sessionexchange;\n\t\tupdateresource.triggermonitor = resource.triggermonitor;\n\t\treturn updateresource.update_resource(client);\n\t}"
] | [
"private void processCustomValueLists() throws IOException\n {\n CustomFieldValueReader9 reader = new CustomFieldValueReader9(m_projectDir, m_file.getProjectProperties(), m_projectProps, m_file.getCustomFields());\n reader.process();\n }",
"protected void doConfigure() {\n if (config != null) {\n for (UserBean user : config.getUsersToCreate()) {\n setUser(user.getEmail(), user.getLogin(), user.getPassword());\n }\n getManagers().getUserManager().setAuthRequired(!config.isAuthenticationDisabled());\n }\n }",
"public void takeNoteOfGradient(IntDoubleVector gradient) {\n gradient.iterate(new FnIntDoubleToVoid() { \n @Override\n public void call(int index, double value) {\n gradSumSquares[index] += value * value;\n assert !Double.isNaN(gradSumSquares[index]);\n }\n });\n }",
"public void awaitStartupCompletion() {\n try {\n Object obj = startedStatusQueue.take();\n if(obj instanceof Throwable)\n throw new VoldemortException((Throwable) obj);\n } catch(InterruptedException e) {\n // this is okay, if we are interrupted we can stop waiting\n }\n }",
"static List<List<String>> handleNewLines( List<List<String>> tableModel ) {\n List<List<String>> result = Lists.newArrayListWithExpectedSize( tableModel.size() );\n\n for( List<String> row : tableModel ) {\n if( hasNewline( row ) ) {\n result.addAll( splitRow( row ) );\n } else {\n result.add( row );\n }\n }\n\n return result;\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}",
"private void writeTask(Task mpxjTask, List<net.sf.mpxj.planner.schema.Task> taskList) throws JAXBException\n {\n net.sf.mpxj.planner.schema.Task plannerTask = m_factory.createTask();\n taskList.add(plannerTask);\n plannerTask.setEnd(getDateTimeString(mpxjTask.getFinish()));\n plannerTask.setId(getIntegerString(mpxjTask.getUniqueID()));\n plannerTask.setName(getString(mpxjTask.getName()));\n plannerTask.setNote(mpxjTask.getNotes());\n plannerTask.setPercentComplete(getIntegerString(mpxjTask.getPercentageWorkComplete()));\n plannerTask.setPriority(mpxjTask.getPriority() == null ? null : getIntegerString(mpxjTask.getPriority().getValue() * 10));\n plannerTask.setScheduling(getScheduling(mpxjTask.getType()));\n plannerTask.setStart(getDateTimeString(DateHelper.getDayStartDate(mpxjTask.getStart())));\n if (mpxjTask.getMilestone())\n {\n plannerTask.setType(\"milestone\");\n }\n else\n {\n plannerTask.setType(\"normal\");\n }\n plannerTask.setWork(getDurationString(mpxjTask.getWork()));\n plannerTask.setWorkStart(getDateTimeString(mpxjTask.getStart()));\n\n ConstraintType mpxjConstraintType = mpxjTask.getConstraintType();\n if (mpxjConstraintType != ConstraintType.AS_SOON_AS_POSSIBLE)\n {\n Constraint plannerConstraint = m_factory.createConstraint();\n plannerTask.setConstraint(plannerConstraint);\n if (mpxjConstraintType == ConstraintType.START_NO_EARLIER_THAN)\n {\n plannerConstraint.setType(\"start-no-earlier-than\");\n }\n else\n {\n if (mpxjConstraintType == ConstraintType.MUST_START_ON)\n {\n plannerConstraint.setType(\"must-start-on\");\n }\n }\n\n plannerConstraint.setTime(getDateTimeString(mpxjTask.getConstraintDate()));\n }\n\n //\n // Write predecessors\n //\n writePredecessors(mpxjTask, plannerTask);\n\n m_eventManager.fireTaskWrittenEvent(mpxjTask);\n\n //\n // Write child tasks\n //\n List<net.sf.mpxj.planner.schema.Task> childTaskList = plannerTask.getTask();\n for (Task task : mpxjTask.getChildTasks())\n {\n writeTask(task, childTaskList);\n }\n }",
"public synchronized int get() {\n if (available == 0) {\n return -1;\n }\n byte value = buffer[idxGet];\n idxGet = (idxGet + 1) % capacity;\n available--;\n return value;\n }",
"public static double elementMin( 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 minimum.\n // Otherwise zero needs to be considered\n double min = 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 < min ) {\n min = val;\n }\n }\n\n return min;\n }"
] |
checkpoint the ObjectModification | [
"public void checkpoint(ObjectEnvelope mod) throws PersistenceBrokerException\r\n {\r\n mod.doInsert();\r\n mod.setModificationState(StateOldClean.getInstance());\r\n }"
] | [
"public static double Y0(double x) {\r\n if (x < 8.0) {\r\n double y = x * x;\r\n\r\n double ans1 = -2957821389.0 + y * (7062834065.0 + y * (-512359803.6\r\n + y * (10879881.29 + y * (-86327.92757 + y * 228.4622733))));\r\n double ans2 = 40076544269.0 + y * (745249964.8 + y * (7189466.438\r\n + y * (47447.26470 + y * (226.1030244 + y * 1.0))));\r\n\r\n return (ans1 / ans2) + 0.636619772 * J0(x) * Math.log(x);\r\n } else {\r\n double z = 8.0 / x;\r\n double y = z * z;\r\n double xx = x - 0.785398164;\r\n\r\n double ans1 = 1.0 + y * (-0.1098628627e-2 + y * (0.2734510407e-4\r\n + y * (-0.2073370639e-5 + y * 0.2093887211e-6)));\r\n double ans2 = -0.1562499995e-1 + y * (0.1430488765e-3\r\n + y * (-0.6911147651e-5 + y * (0.7621095161e-6\r\n + y * (-0.934945152e-7))));\r\n return Math.sqrt(0.636619772 / x) *\r\n (Math.sin(xx) * ans1 + z * Math.cos(xx) * ans2);\r\n }\r\n }",
"public DynamicReportBuilder setProperty(String name, String value) {\n this.report.setProperty(name, value);\n return this;\n }",
"public AirMapViewBuilder builder(AirMapViewTypes mapType) {\n switch (mapType) {\n case NATIVE:\n if (isNativeMapSupported) {\n return new NativeAirMapViewBuilder();\n }\n break;\n case WEB:\n return getWebMapViewBuilder();\n }\n throw new UnsupportedOperationException(\"Requested map type is not supported\");\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 long removeAll(final String... members) {\n return doWithJedis(new JedisCallable<Long>() {\n @Override\n public Long call(Jedis jedis) {\n return jedis.srem(getKey(), members);\n }\n });\n }",
"public static authenticationradiusaction get(nitro_service service, String name) throws Exception{\n\t\tauthenticationradiusaction obj = new authenticationradiusaction();\n\t\tobj.set_name(name);\n\t\tauthenticationradiusaction response = (authenticationradiusaction) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public static cmppolicylabel_stats get(nitro_service service, String labelname) throws Exception{\n\t\tcmppolicylabel_stats obj = new cmppolicylabel_stats();\n\t\tobj.set_labelname(labelname);\n\t\tcmppolicylabel_stats response = (cmppolicylabel_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}",
"protected Object doInvoke(Object proxy, Method methodToBeInvoked, Object[] args)\r\n\t\tthrows Throwable\r\n\t{\r\n\t\tMethod m =\r\n\t\t\tgetRealSubject().getClass().getMethod(\r\n\t\t\t\tmethodToBeInvoked.getName(),\r\n\t\t\t\tmethodToBeInvoked.getParameterTypes());\r\n\t\treturn m.invoke(getRealSubject(), args);\r\n\t}",
"public ByteArray readBytes(int size) throws IOException\n {\n byte[] data = new byte[size];\n m_stream.read(data);\n return new ByteArray(data);\n }"
] |
This is generally only useful for extensions that delegate some of their functionality to other "internal"
extensions of their own that they need to configure.
@param configuration the configuration to be supplied with the returned analysis context.
@return an analysis context that is a clone of this instance but its configuration is replaced with the provided
one. | [
"public AnalysisContext copyWithConfiguration(ModelNode configuration) {\n return new AnalysisContext(this.locale, configuration, this.oldApi, this.newApi, this.data);\n }"
] | [
"public static URL codeLocationFromClass(Class<?> codeLocationClass) {\n String pathOfClass = codeLocationClass.getName().replace(\".\", \"/\") + \".class\";\n URL classResource = codeLocationClass.getClassLoader().getResource(pathOfClass);\n String codeLocationPath = removeEnd(getPathFromURL(classResource), pathOfClass);\n if(codeLocationPath.endsWith(\".jar!/\")) {\n codeLocationPath=removeEnd(codeLocationPath,\"!/\");\n }\n return codeLocationFromPath(codeLocationPath);\n }",
"public ConverterServerBuilder requestTimeout(long timeout, TimeUnit unit) {\n assertNumericArgument(timeout, true);\n this.requestTimeout = unit.toMillis(timeout);\n return this;\n }",
"public static Cluster cloneCluster(Cluster cluster) {\n // Could add a better .clone() implementation that clones the derived\n // data structures. The constructor invoked by this clone implementation\n // can be slow for large numbers of partitions. Probably faster to copy\n // all the maps and stuff.\n return new Cluster(cluster.getName(),\n new ArrayList<Node>(cluster.getNodes()),\n new ArrayList<Zone>(cluster.getZones()));\n /*-\n * Historic \"clone\" code being kept in case this, for some reason, was the \"right\" way to be doing this.\n ClusterMapper mapper = new ClusterMapper();\n return mapper.readCluster(new StringReader(mapper.writeCluster(cluster)));\n */\n }",
"private void initDurationButtonGroup() {\n\n m_groupDuration = new CmsRadioButtonGroup();\n\n m_endsAfterRadioButton = new CmsRadioButton(\n EndType.TIMES.toString(),\n Messages.get().key(Messages.GUI_SERIALDATE_DURATION_ENDTYPE_OCC_0));\n m_endsAfterRadioButton.setGroup(m_groupDuration);\n m_endsAtRadioButton = new CmsRadioButton(\n EndType.DATE.toString(),\n Messages.get().key(Messages.GUI_SERIALDATE_DURATION_ENDTYPE_DATE_0));\n m_endsAtRadioButton.setGroup(m_groupDuration);\n m_groupDuration.addValueChangeHandler(new ValueChangeHandler<String>() {\n\n public void onValueChange(ValueChangeEvent<String> event) {\n\n if (handleChange()) {\n String value = event.getValue();\n if (null != value) {\n m_controller.setEndType(value);\n }\n }\n }\n });\n\n }",
"@Override\n public Object put(List<Map.Entry> batch) throws InterruptedException {\n if (initializeClusterSource()) {\n return clusterSource.put(batch);\n }\n return null;\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 }",
"GVRSceneObject makeParticleMesh(float[] vertices, float[] velocities,\n float[] particleTimeStamps )\n {\n mParticleMesh = new GVRMesh(mGVRContext);\n\n //pass the particle positions as vertices, velocities as normals, and\n //spawning times as texture coordinates.\n mParticleMesh.setVertices(vertices);\n mParticleMesh.setNormals(velocities);\n mParticleMesh.setTexCoords(particleTimeStamps);\n\n particleID = new GVRShaderId(ParticleShader.class);\n material = new GVRMaterial(mGVRContext, particleID);\n\n material.setVec4(\"u_color\", mColorMultiplier.x, mColorMultiplier.y,\n mColorMultiplier.z, mColorMultiplier.w);\n material.setFloat(\"u_particle_age\", mAge);\n material.setVec3(\"u_acceleration\", mAcceleration.x, mAcceleration.y, mAcceleration.z);\n material.setFloat(\"u_particle_size\", mSize);\n material.setFloat(\"u_size_change_rate\", mParticleSizeRate);\n material.setFloat(\"u_fade\", mFadeWithAge);\n material.setFloat(\"u_noise_factor\", mNoiseFactor);\n\n GVRRenderData renderData = new GVRRenderData(mGVRContext);\n renderData.setMaterial(material);\n renderData.setMesh(mParticleMesh);\n material.setMainTexture(mTexture);\n\n GVRSceneObject meshObject = new GVRSceneObject(mGVRContext);\n meshObject.attachRenderData(renderData);\n meshObject.getRenderData().setMaterial(material);\n\n // Set the draw mode to GL_POINTS, disable writing to depth buffer, enable depth testing\n // and set the rendering order to transparent.\n // Disabling writing to depth buffer ensure that the particles blend correctly\n // and keeping the depth test on along with rendering them\n // after the geometry queue makes sure they occlude, and are occluded, correctly.\n\n meshObject.getRenderData().setDrawMode(GL_POINTS);\n meshObject.getRenderData().setDepthTest(true);\n meshObject.getRenderData().setDepthMask(false);\n meshObject.getRenderData().setRenderingOrder(GVRRenderData.GVRRenderingOrder.TRANSPARENT);\n\n return meshObject;\n }",
"public Date toDate(String dateString) {\n Date date = null;\n DateFormat df = new SimpleDateFormat(\"yyyy-MM-dd\");\n try {\n date = df.parse(dateString);\n } catch (ParseException ex) {\n System.out.println(ex.fillInStackTrace());\n }\n return date;\n }",
"@Override\n public void accept(IBinaryType binaryType, PackageBinding packageBinding, AccessRestriction accessRestriction) {\n if (this.options.verbose) {\n this.out.println(\n Messages.bind(Messages.compilation_loadBinary, new String(binaryType.getName())));\n//\t\t\tnew Exception(\"TRACE BINARY\").printStackTrace(System.out);\n//\t\t System.out.println();\n }\n LookupEnvironment env = packageBinding.environment;\n env.createBinaryTypeFrom(binaryType, packageBinding, accessRestriction);\n }"
] |
Calculates the vega of a digital option under a Black-Scholes model
@param initialStockValue The initial value of the underlying, i.e., the spot.
@param riskFreeRate The risk free rate of the bank account numerarie.
@param volatility The Black-Scholes volatility.
@param optionMaturity The option maturity T.
@param optionStrike The option strike.
@return The vega of the digital option | [
"public static double blackScholesDigitalOptionVega(\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 || optionMaturity <= 0.0)\n\t\t{\n\t\t\t// The Black-Scholes model does not consider it being an option\n\t\t\treturn 0.0;\n\t\t}\n\t\telse\n\t\t{\n\t\t\t// Calculate vega\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 vega = - Math.exp(-riskFreeRate * optionMaturity) * Math.exp(-0.5*dMinus*dMinus) / Math.sqrt(2.0 * Math.PI) * dPlus / volatility;\n\n\t\t\treturn vega;\n\t\t}\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 }",
"private static void validateAsMongoDBCollectionName(String collectionName) {\n\t\tContracts.assertStringParameterNotEmpty( collectionName, \"requestedName\" );\n\t\t//Yes it has some strange requirements.\n\t\tif ( collectionName.startsWith( \"system.\" ) ) {\n\t\t\tthrow log.collectionNameHasInvalidSystemPrefix( collectionName );\n\t\t}\n\t\telse if ( collectionName.contains( \"\\u0000\" ) ) {\n\t\t\tthrow log.collectionNameContainsNULCharacter( collectionName );\n\t\t}\n\t\telse if ( collectionName.contains( \"$\" ) ) {\n\t\t\tthrow log.collectionNameContainsDollarCharacter( collectionName );\n\t\t}\n\t}",
"public static int Hamming(String first, String second) {\n\n if (first.length() != second.length())\n throw new IllegalArgumentException(\"The size of string must be the same.\");\n\n int diff = 0;\n for (int i = 0; i < first.length(); i++)\n if (first.charAt(i) != second.charAt(i))\n diff++;\n return diff;\n }",
"private void writeAssignmentTimephasedData(ResourceAssignment mpx, Project.Assignments.Assignment xml)\n {\n if (m_writeTimphasedData && mpx.getHasTimephasedData())\n {\n List<TimephasedDataType> list = xml.getTimephasedData();\n ProjectCalendar calendar = mpx.getCalendar();\n BigInteger assignmentID = xml.getUID();\n\n List<TimephasedWork> complete = mpx.getTimephasedActualWork();\n List<TimephasedWork> planned = mpx.getTimephasedWork();\n\n if (m_splitTimephasedAsDays)\n {\n TimephasedWork lastComplete = null;\n if (complete != null && !complete.isEmpty())\n {\n lastComplete = complete.get(complete.size() - 1);\n }\n\n TimephasedWork firstPlanned = null;\n if (planned != null && !planned.isEmpty())\n {\n firstPlanned = planned.get(0);\n }\n\n if (planned != null)\n {\n planned = splitDays(calendar, mpx.getTimephasedWork(), null, lastComplete);\n }\n\n if (complete != null)\n {\n complete = splitDays(calendar, complete, firstPlanned, null);\n }\n }\n\n if (planned != null)\n {\n writeAssignmentTimephasedData(assignmentID, list, planned, 1);\n }\n\n if (complete != null)\n {\n writeAssignmentTimephasedData(assignmentID, list, complete, 2);\n }\n }\n }",
"public void setRegistrationConfig(RegistrationConfig registrationConfig) {\n this.registrationConfig = registrationConfig;\n\n if (registrationConfig.getDefaultConfig()!=null) {\n for (String key : registrationConfig.getDefaultConfig().keySet()) {\n dynamicConfig.put(key, registrationConfig.getDefaultConfig().get(key));\n }\n }\n }",
"public void setOnKeyboardDone(final IntlPhoneInputListener listener) {\n mPhoneEdit.setOnEditorActionListener(new TextView.OnEditorActionListener() {\n @Override\n public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {\n if (actionId == EditorInfo.IME_ACTION_DONE) {\n listener.done(IntlPhoneInput.this, isValid());\n }\n return false;\n }\n });\n }",
"public Map<Integer, List<Row>> createTimeEntryMap(List<Row> rows)\n {\n Map<Integer, List<Row>> map = new HashMap<Integer, List<Row>>();\n for (Row row : rows)\n {\n Integer workPatternID = row.getInteger(\"TIME_ENTRYID\");\n List<Row> list = map.get(workPatternID);\n if (list == null)\n {\n list = new LinkedList<Row>();\n map.put(workPatternID, list);\n }\n list.add(row);\n }\n return map;\n }",
"private static InterestRateSwapLegProductDescriptor getSwapLegProductDescriptor(Element leg, String forwardCurveName, String discountCurveName,\r\n\t\t\tDayCountConvention daycountConvention) {\r\n\r\n\t\tboolean isFixed = leg.getElementsByTagName(\"interestType\").item(0).getTextContent().equalsIgnoreCase(\"FIX\");\r\n\r\n\t\tArrayList<Period> periods \t\t= new ArrayList<>();\r\n\t\tArrayList<Double> notionalsList\t= new ArrayList<>();\r\n\t\tArrayList<Double> rates\t\t\t= new ArrayList<>();\r\n\r\n\t\t//extracting data for each period\r\n\t\tNodeList periodsXML = leg.getElementsByTagName(\"incomePayment\");\r\n\t\tfor(int periodIndex = 0; periodIndex < periodsXML.getLength(); periodIndex++) {\r\n\r\n\t\t\tElement periodXML = (Element) periodsXML.item(periodIndex);\r\n\r\n\t\t\tLocalDate startDate\t= LocalDate.parse(periodXML.getElementsByTagName(\"startDate\").item(0).getTextContent());\r\n\t\t\tLocalDate endDate\t= LocalDate.parse(periodXML.getElementsByTagName(\"endDate\").item(0).getTextContent());\r\n\r\n\t\t\tLocalDate fixingDate\t= startDate;\r\n\t\t\tLocalDate paymentDate\t= LocalDate.parse(periodXML.getElementsByTagName(\"payDate\").item(0).getTextContent());\r\n\r\n\t\t\tif(! isFixed) {\r\n\t\t\t\tfixingDate = LocalDate.parse(periodXML.getElementsByTagName(\"fixingDate\").item(0).getTextContent());\r\n\t\t\t}\r\n\r\n\t\t\tperiods.add(new Period(fixingDate, paymentDate, startDate, endDate));\r\n\r\n\t\t\tdouble notional\t\t= Double.parseDouble(periodXML.getElementsByTagName(\"nominal\").item(0).getTextContent());\r\n\t\t\tnotionalsList.add(new Double(notional));\r\n\r\n\t\t\tif(isFixed) {\r\n\t\t\t\tdouble fixedRate\t= Double.parseDouble(periodXML.getElementsByTagName(\"fixedRate\").item(0).getTextContent());\r\n\t\t\t\trates.add(new Double(fixedRate));\r\n\t\t\t} else {\r\n\t\t\t\trates.add(new Double(0));\r\n\t\t\t}\r\n\r\n\t\t}\r\n\r\n\t\tScheduleDescriptor schedule = new ScheduleDescriptor(periods, daycountConvention);\r\n\t\tdouble[] notionals\t= notionalsList.stream().mapToDouble(Double::doubleValue).toArray();\r\n\t\tdouble[] spreads\t= rates.stream().mapToDouble(Double::doubleValue).toArray();\r\n\r\n\t\treturn new InterestRateSwapLegProductDescriptor(forwardCurveName, discountCurveName, schedule, notionals, spreads, false);\r\n\t}",
"public ColumnBuilder addFieldProperty(String propertyName, String value) {\n\t\tfieldProperties.put(propertyName, value);\n\t\treturn this;\n\t}"
] |
Use this API to add gslbsite. | [
"public static base_response add(nitro_service client, gslbsite resource) throws Exception {\n\t\tgslbsite addresource = new gslbsite();\n\t\taddresource.sitename = resource.sitename;\n\t\taddresource.sitetype = resource.sitetype;\n\t\taddresource.siteipaddress = resource.siteipaddress;\n\t\taddresource.publicip = resource.publicip;\n\t\taddresource.metricexchange = resource.metricexchange;\n\t\taddresource.nwmetricexchange = resource.nwmetricexchange;\n\t\taddresource.sessionexchange = resource.sessionexchange;\n\t\taddresource.triggermonitor = resource.triggermonitor;\n\t\taddresource.parentsite = resource.parentsite;\n\t\treturn addresource.add_resource(client);\n\t}"
] | [
"public static sslciphersuite[] get(nitro_service service, String ciphername[]) throws Exception{\n\t\tif (ciphername !=null && ciphername.length>0) {\n\t\t\tsslciphersuite response[] = new sslciphersuite[ciphername.length];\n\t\t\tsslciphersuite obj[] = new sslciphersuite[ciphername.length];\n\t\t\tfor (int i=0;i<ciphername.length;i++) {\n\t\t\t\tobj[i] = new sslciphersuite();\n\t\t\t\tobj[i].set_ciphername(ciphername[i]);\n\t\t\t\tresponse[i] = (sslciphersuite) obj[i].get_resource(service);\n\t\t\t}\n\t\t\treturn response;\n\t\t}\n\t\treturn null;\n\t}",
"public static boolean isListLiteralWithOnlyConstantValues(Expression expression) {\r\n if (expression instanceof ListExpression) {\r\n List<Expression> expressions = ((ListExpression) expression).getExpressions();\r\n for (Expression e : expressions) {\r\n if (!isConstantOrConstantLiteral(e)) {\r\n return false;\r\n }\r\n }\r\n return true;\r\n }\r\n return false;\r\n }",
"public static <E> Collection<E> sampleWithoutReplacement(Collection<E> c, int n) {\r\n return sampleWithoutReplacement(c, n, new Random());\r\n }",
"public String read(int numBytes) throws IOException {\n Preconditions.checkArgument(numBytes >= 0);\n Preconditions.checkArgument(numBytes <= MAX_ALLOWABLE_BUFFER_SIZE);\n int numBytesRemaining = numBytes;\n // first read whatever we need from our buffer\n if (!isReadBufferEmpty()) {\n int length = Math.min(end - offset, numBytesRemaining);\n copyToStrBuffer(buffer, offset, length);\n offset += length;\n numBytesRemaining -= length;\n }\n\n // next read the remaining chars directly into our strBuffer\n if (numBytesRemaining > 0) {\n readAmountToStrBuffer(numBytesRemaining);\n }\n\n if (strBufferIndex > 0 && strBuffer[strBufferIndex - 1] != LF) {\n // the last byte doesn't correspond to lf\n return readLine(false);\n }\n\n int strBufferLength = strBufferIndex;\n strBufferIndex = 0;\n return new String(strBuffer, 0, strBufferLength, charset);\n }",
"public static base_responses update(nitro_service client, snmpuser resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsnmpuser updateresources[] = new snmpuser[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new snmpuser();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].group = resources[i].group;\n\t\t\t\tupdateresources[i].authtype = resources[i].authtype;\n\t\t\t\tupdateresources[i].authpasswd = resources[i].authpasswd;\n\t\t\t\tupdateresources[i].privtype = resources[i].privtype;\n\t\t\t\tupdateresources[i].privpasswd = resources[i].privpasswd;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}",
"public static boolean blockAligned( int blockLength , DSubmatrixD1 A ) {\n if( A.col0 % blockLength != 0 )\n return false;\n if( A.row0 % blockLength != 0 )\n return false;\n\n if( A.col1 % blockLength != 0 && A.col1 != A.original.numCols ) {\n return false;\n }\n\n if( A.row1 % blockLength != 0 && A.row1 != A.original.numRows) {\n return false;\n }\n\n return true;\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 void handleChange(Object propertyId) {\n\n if (!m_saveBtn.isEnabled()) {\n m_saveBtn.setEnabled(true);\n m_saveExitBtn.setEnabled(true);\n }\n m_model.handleChange(propertyId);\n\n }",
"public final void notifyHeaderItemRangeInserted(int positionStart, int itemCount) {\n int newHeaderItemCount = getHeaderItemCount();\n if (positionStart < 0 || itemCount < 0 || positionStart + itemCount > newHeaderItemCount) {\n throw new IndexOutOfBoundsException(\"The given range [\" + positionStart + \" - \" + (positionStart + itemCount - 1) + \"] is not within the position bounds for header items [0 - \" + (newHeaderItemCount - 1) + \"].\");\n }\n notifyItemRangeInserted(positionStart, itemCount);\n }"
] |
read data from channel to buffer
@param channel readable channel
@param buffer bytebuffer
@return read size
@throws IOException any io exception | [
"public static int read(ReadableByteChannel channel, ByteBuffer buffer) throws IOException {\n int count = channel.read(buffer);\n if (count == -1) throw new EOFException(\"Received -1 when reading from channel, socket has likely been closed.\");\n return count;\n }"
] | [
"@UiHandler(\"m_currentTillEndCheckBox\")\n void onCurrentTillEndChange(ValueChangeEvent<Boolean> event) {\n\n if (handleChange()) {\n m_controller.setCurrentTillEnd(event.getValue());\n }\n }",
"private Component createConvertToPropertyBundleButton() {\n\n Button addDescriptorButton = CmsToolBar.createButton(\n FontOpenCms.SETTINGS,\n m_messages.key(Messages.GUI_CONVERT_TO_PROPERTY_BUNDLE_0));\n\n addDescriptorButton.setDisableOnClick(true);\n\n addDescriptorButton.addClickListener(new ClickListener() {\n\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n try {\n m_model.saveAsPropertyBundle();\n Notification.show(\"Conversion successful.\");\n } catch (CmsException | IOException e) {\n CmsVaadinUtils.showAlert(\"Conversion failed\", e.getLocalizedMessage(), null);\n }\n }\n });\n addDescriptorButton.setDisableOnClick(true);\n return addDescriptorButton;\n }",
"public void addFieldDescriptor(FieldDescriptor fld)\r\n {\r\n fld.setClassDescriptor(this); // BRJ\r\n if (m_FieldDescriptions == null)\r\n {\r\n m_FieldDescriptions = new FieldDescriptor[1];\r\n m_FieldDescriptions[0] = fld;\r\n }\r\n else\r\n {\r\n int size = m_FieldDescriptions.length;\r\n FieldDescriptor[] tmpArray = new FieldDescriptor[size + 1];\r\n System.arraycopy(m_FieldDescriptions, 0, tmpArray, 0, size);\r\n tmpArray[size] = fld;\r\n m_FieldDescriptions = tmpArray;\r\n // 2. Sort fields according to their getOrder() Property\r\n Arrays.sort(m_FieldDescriptions, FieldDescriptor.getComparator());\r\n }\r\n\r\n m_fieldDescriptorNameMap = null;\r\n m_PkFieldDescriptors = null;\r\n m_nonPkFieldDescriptors = null;\r\n m_lockingFieldDescriptors = null;\r\n m_RwFieldDescriptors = null;\r\n m_RwNonPkFieldDescriptors = null;\r\n }",
"private void readHolidays()\n {\n for (MapRow row : m_tables.get(\"HOL\"))\n {\n ProjectCalendar calendar = m_calendarMap.get(row.getInteger(\"CALENDAR_ID\"));\n if (calendar != null)\n {\n Date date = row.getDate(\"DATE\");\n ProjectCalendarException exception = calendar.addCalendarException(date, date);\n if (row.getBoolean(\"ANNUAL\"))\n {\n RecurringData recurring = new RecurringData();\n recurring.setRecurrenceType(RecurrenceType.YEARLY);\n recurring.setYearlyAbsoluteFromDate(date);\n recurring.setStartDate(date);\n exception.setRecurring(recurring);\n // TODO set end date based on project end date\n }\n }\n }\n }",
"public static double[] getTileLayerSize(TileCode code, Envelope maxExtent, double scale) {\n\t\tdouble div = Math.pow(2, code.getTileLevel());\n\t\tdouble tileWidth = Math.ceil((scale * maxExtent.getWidth()) / div) / scale;\n\t\tdouble tileHeight = Math.ceil((scale * maxExtent.getHeight()) / div) / scale;\n\t\treturn new double[] { tileWidth, tileHeight };\n\t}",
"public static base_responses enable(nitro_service client, String id[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (id != null && id.length > 0) {\n\t\t\tInterface enableresources[] = new Interface[id.length];\n\t\t\tfor (int i=0;i<id.length;i++){\n\t\t\t\tenableresources[i] = new Interface();\n\t\t\t\tenableresources[i].id = id[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}",
"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 }",
"private ProctorContext getProctorContext(final HttpServletRequest request) throws IllegalAccessException, InstantiationException {\n final ProctorContext proctorContext = contextClass.newInstance();\n final BeanWrapper beanWrapper = new BeanWrapperImpl(proctorContext);\n for (final PropertyDescriptor descriptor : beanWrapper.getPropertyDescriptors()) {\n final String propertyName = descriptor.getName();\n if (!\"class\".equals(propertyName)) { // ignore class property which every object has\n final String parameterValue = request.getParameter(propertyName);\n if (parameterValue != null) {\n beanWrapper.setPropertyValue(propertyName, parameterValue);\n }\n }\n }\n return proctorContext;\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}"
] |
Serialize specified object to directory with specified name.
@param directory write to
@param name serialize object with specified name
@param obj object to serialize
@return number of bytes written to directory | [
"public static int serialize(final File directory, String name, Object obj) {\n try (FileOutputStream stream = new FileOutputStream(new File(directory, name))) {\n return serialize(stream, obj);\n } catch (IOException e) {\n throw new ReportGenerationException(e);\n }\n }"
] | [
"public PlacesList<Place> placesForUser(int placeType, String woeId, String placeId, String threshold, Date minUploadDate, Date maxUploadDate,\r\n Date minTakenDate, Date maxTakenDate) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n PlacesList<Place> placesList = new PlacesList<Place>();\r\n parameters.put(\"method\", METHOD_PLACES_FOR_USER);\r\n\r\n parameters.put(\"place_type\", intPlaceTypeToString(placeType));\r\n if (placeId != null) {\r\n parameters.put(\"place_id\", placeId);\r\n }\r\n if (woeId != null) {\r\n parameters.put(\"woe_id\", woeId);\r\n }\r\n if (threshold != null) {\r\n parameters.put(\"threshold\", threshold);\r\n }\r\n if (minUploadDate != null) {\r\n parameters.put(\"min_upload_date\", Long.toString(minUploadDate.getTime() / 1000L));\r\n }\r\n if (maxUploadDate != null) {\r\n parameters.put(\"max_upload_date\", Long.toString(maxUploadDate.getTime() / 1000L));\r\n }\r\n if (minTakenDate != null) {\r\n parameters.put(\"min_taken_date\", ((DateFormat) SearchParameters.MYSQL_DATE_FORMATS.get()).format(minTakenDate));\r\n }\r\n if (maxTakenDate != null) {\r\n parameters.put(\"max_taken_date\", ((DateFormat) SearchParameters.MYSQL_DATE_FORMATS.get()).format(maxTakenDate));\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 placesElement = response.getPayload();\r\n NodeList placesNodes = placesElement.getElementsByTagName(\"place\");\r\n placesList.setPage(\"1\");\r\n placesList.setPages(\"1\");\r\n placesList.setPerPage(\"\" + placesNodes.getLength());\r\n placesList.setTotal(\"\" + placesNodes.getLength());\r\n for (int i = 0; i < placesNodes.getLength(); i++) {\r\n Element placeElement = (Element) placesNodes.item(i);\r\n placesList.add(parsePlace(placeElement));\r\n }\r\n return placesList;\r\n }",
"public void downloadRange(OutputStream output, long rangeStart, long rangeEnd) {\n this.downloadRange(output, rangeStart, rangeEnd, null);\n }",
"public PhotoList<Photo> getContactsPublicPhotos(String userId, int count, boolean justFriends, boolean singlePhoto, boolean includeSelf)\r\n throws FlickrException {\r\n return getContactsPublicPhotos(userId, Extras.MIN_EXTRAS, count, justFriends, singlePhoto, includeSelf);\r\n }",
"private GVRCursorController getUniqueControllerId(int deviceId) {\n GVRCursorController controller = controllerIds.get(deviceId);\n if (controller != null) {\n return controller;\n }\n return null;\n }",
"private boolean hasReceivedHeartbeat() {\n long currentTimeMillis = System.currentTimeMillis();\n boolean result = lastTimeMessageReceived + heartbeatTimeoutMs >= currentTimeMillis;\n\n if (!result)\n Jvm.warn().on(getClass(), Integer.toHexString(hashCode()) + \" missed heartbeat, lastTimeMessageReceived=\" + lastTimeMessageReceived\n + \", currentTimeMillis=\" + currentTimeMillis);\n return result;\n }",
"public void processCalendar(Row calendarRow, Map<Integer, Row> workPatternMap, Map<Integer, List<Row>> workPatternAssignmentMap, Map<Integer, List<Row>> exceptionAssignmentMap, Map<Integer, List<Row>> timeEntryMap, Map<Integer, DayType> exceptionTypeMap)\n {\n //\n // Create the calendar and add the default working hours\n //\n ProjectCalendar calendar = m_project.addCalendar();\n Integer dominantWorkPatternID = calendarRow.getInteger(\"DOMINANT_WORK_PATTERN\");\n calendar.setUniqueID(calendarRow.getInteger(\"CALENDARID\"));\n processWorkPattern(calendar, dominantWorkPatternID, workPatternMap, timeEntryMap, exceptionTypeMap);\n calendar.setName(calendarRow.getString(\"NAMK\"));\n\n //\n // Add any additional working weeks\n //\n List<Row> rows = workPatternAssignmentMap.get(calendar.getUniqueID());\n if (rows != null)\n {\n for (Row row : rows)\n {\n Integer workPatternID = row.getInteger(\"WORK_PATTERN\");\n if (!workPatternID.equals(dominantWorkPatternID))\n {\n ProjectCalendarWeek week = calendar.addWorkWeek();\n week.setDateRange(new DateRange(row.getDate(\"START_DATE\"), row.getDate(\"END_DATE\")));\n processWorkPattern(week, workPatternID, workPatternMap, timeEntryMap, exceptionTypeMap);\n }\n }\n }\n\n //\n // Add exceptions - not sure how exceptions which turn non-working days into working days are handled by Asta - if at all?\n //\n rows = exceptionAssignmentMap.get(calendar.getUniqueID());\n if (rows != null)\n {\n for (Row row : rows)\n {\n Date startDate = row.getDate(\"STARU_DATE\");\n Date endDate = row.getDate(\"ENE_DATE\");\n calendar.addCalendarException(startDate, endDate);\n }\n }\n\n m_eventManager.fireCalendarReadEvent(calendar);\n }",
"public String getURN() throws InvalidRegistrationContentException {\n if (parsedConfig==null || parsedConfig.urn==null || parsedConfig.urn.trim().isEmpty()) {\n throw new InvalidRegistrationContentException(\"Invalid registration config - failed to read mediator URN\");\n }\n return parsedConfig.urn;\n }",
"public void addFkToItemClass(String column)\r\n {\r\n if (fksToItemClass == null)\r\n {\r\n fksToItemClass = new Vector();\r\n }\r\n fksToItemClass.add(column);\r\n fksToItemClassAry = null;\r\n }",
"public List<TimephasedWork> getTimephasedBaselineWork(int index)\n {\n return m_timephasedBaselineWork[index] == null ? null : m_timephasedBaselineWork[index].getData();\n }"
] |
Extract name of the resource from a resource ID.
@param id the resource ID
@return the name of the resource | [
"public static String nameFromResourceId(String id) {\n return (id != null) ? ResourceId.fromString(id).name() : null;\n }"
] | [
"public static base_response update(nitro_service client, nsdiameter resource) throws Exception {\n\t\tnsdiameter updateresource = new nsdiameter();\n\t\tupdateresource.identity = resource.identity;\n\t\tupdateresource.realm = resource.realm;\n\t\tupdateresource.serverclosepropagation = resource.serverclosepropagation;\n\t\treturn updateresource.update_resource(client);\n\t}",
"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 cache(Identity oid, Object obj)\r\n {\r\n if (oid != null && obj != null)\r\n {\r\n ObjectCache cache = getCache(oid, obj, METHOD_CACHE);\r\n if (cache != null)\r\n {\r\n cache.cache(oid, obj);\r\n }\r\n }\r\n }",
"public void setLongAttribute(String name, Long value) {\n\t\tensureValue();\n\t\tAttribute attribute = new LongAttribute(value);\n\t\tattribute.setEditable(isEditable(name));\n\t\tgetValue().getAllAttributes().put(name, attribute);\n\t}",
"public static String getFailureDescriptionAsString(final ModelNode result) {\n if (isSuccessfulOutcome(result)) {\n return \"\";\n }\n final String msg;\n if (result.hasDefined(ClientConstants.FAILURE_DESCRIPTION)) {\n if (result.hasDefined(ClientConstants.OP)) {\n msg = String.format(\"Operation '%s' at address '%s' failed: %s\", result.get(ClientConstants.OP), result.get(ClientConstants.OP_ADDR), result\n .get(ClientConstants.FAILURE_DESCRIPTION));\n } else {\n msg = String.format(\"Operation failed: %s\", result.get(ClientConstants.FAILURE_DESCRIPTION));\n }\n } else {\n msg = String.format(\"An unexpected response was found checking the deployment. Result: %s\", result);\n }\n return msg;\n }",
"public Column getColumn(String columnName) {\n if (columnName == null) {\n return null;\n }\n for (Column column : columns) {\n if (columnName.equals(column.getData())) {\n return column;\n }\n }\n return null;\n }",
"@Pure\n\tpublic static <P1, P2, P3, P4, P5> Procedure4<P2, P3, P4, P5> curry(final Procedure5<? super P1, ? super P2, ? super P3, ? super P4, ? super P5> procedure,\n\t\t\tfinal P1 argument) {\n\t\tif (procedure == null)\n\t\t\tthrow new NullPointerException(\"procedure\");\n\t\treturn new Procedure4<P2, P3, P4, P5>() {\n\t\t\t@Override\n\t\t\tpublic void apply(P2 p2, P3 p3, P4 p4, P5 p5) {\n\t\t\t\tprocedure.apply(argument, p2, p3, p4, p5);\n\t\t\t}\n\t\t};\n\t}",
"public void removeHoursFromDay(ProjectCalendarHours hours)\n {\n if (hours.getParentCalendar() != this)\n {\n throw new IllegalArgumentException();\n }\n m_hours[hours.getDay().getValue() - 1] = null;\n }",
"public static void setTime(Calendar calendar, int hourOfDay, int minute, int second, int millisecond) {\n calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);\n calendar.set(Calendar.MINUTE, minute);\n calendar.set(Calendar.SECOND, second);\n calendar.set(Calendar.MILLISECOND, millisecond);\n }"
] |
A tie-in for subclasses such as AdaGrad. | [
"public void takeNoteOfGradient(IntDoubleVector gradient) {\n gradient.iterate(new FnIntDoubleToVoid() { \n @Override\n public void call(int index, double value) {\n gradSumSquares[index] += value * value;\n assert !Double.isNaN(gradSumSquares[index]);\n }\n });\n }"
] | [
"public void postProcess() {\n\t\tif (foreignColumnName != null) {\n\t\t\tforeignAutoRefresh = true;\n\t\t}\n\t\tif (foreignAutoRefresh && maxForeignAutoRefreshLevel == NO_MAX_FOREIGN_AUTO_REFRESH_LEVEL_SPECIFIED) {\n\t\t\tmaxForeignAutoRefreshLevel = DatabaseField.DEFAULT_MAX_FOREIGN_AUTO_REFRESH_LEVEL;\n\t\t}\n\t}",
"public static Map<String, List<String>> getResponseHeaders(String stringUrl,\n boolean followRedirects) throws IOException {\n URL url = new URL(stringUrl);\n HttpURLConnection conn = (HttpURLConnection) url.openConnection();\n conn.setInstanceFollowRedirects(followRedirects);\n \n InputStream is = conn.getInputStream();\n if (\"gzip\".equals(conn.getContentEncoding())) {\n is = new GZIPInputStream(is);\n }\n\n Map<String, List<String>> headers = new LinkedHashMap<String, List<String>>(conn.getHeaderFields());\n headers.put(\"X-Content\", Arrays.asList(MyStreamUtils.readContent(is)));\n headers.put(\"X-URL\", Arrays.asList(conn.getURL().toString()));\n headers.put(\"X-Status\", Arrays.asList(String.valueOf(conn.getResponseCode())));\n \n return headers;\n }",
"@Override\n public void stopTransition() {\n //call listeners so they can perform their actions first, like modifying this adapter's transitions\n for (int i = 0, size = mListenerList.size(); i < size; i++) {\n mListenerList.get(i).onTransitionEnd(this);\n }\n\n for (int i = 0, size = mTransitionList.size(); i < size; i++) {\n mTransitionList.get(i).stopTransition();\n }\n }",
"@Value(\"${locator.strategy}\")\n public void setDefaultLocatorSelectionStrategy(String defaultLocatorSelectionStrategy) {\n this.defaultLocatorSelectionStrategy = defaultLocatorSelectionStrategy;\n if (LOG.isLoggable(Level.FINE)) {\n LOG.log(Level.FINE, \"Default strategy \" + defaultLocatorSelectionStrategy\n + \" was set for LocatorClientRegistrar.\");\n }\n }",
"public static Statement open(String driverklass, String jdbcuri,\n Properties props) {\n try {\n Driver driver = (Driver) ObjectUtils.instantiate(driverklass);\n Connection conn = driver.connect(jdbcuri, props);\n if (conn == null)\n throw new DukeException(\"Couldn't connect to database at \" +\n jdbcuri);\n return conn.createStatement();\n\n } catch (SQLException e) {\n throw new DukeException(e);\n }\n }",
"public static String compactDump(INode node, boolean showHidden) {\n\t\tStringBuilder result = new StringBuilder();\n\t\ttry {\n\t\t\tcompactDump(node, showHidden, \"\", result);\n\t\t} catch (IOException e) {\n\t\t\treturn e.getMessage();\n\t\t}\n\t\treturn result.toString();\n\t}",
"public synchronized int cancelByTag(String tagToCancel) {\n int i = 0;\n if (taskList.containsKey(tagToCancel)) {\n removeDoneTasks();\n\n for (Future<BlurWorker.Result> future : taskList.get(tagToCancel)) {\n BuilderUtil.logVerbose(Dali.getConfig().logTag, \"Canceling task with tag \" + tagToCancel, Dali.getConfig().debugMode);\n future.cancel(true);\n i++;\n }\n\n //remove all canceled tasks\n Iterator<Future<BlurWorker.Result>> iter = taskList.get(tagToCancel).iterator();\n while (iter.hasNext()) {\n if (iter.next().isCancelled()) {\n iter.remove();\n }\n }\n }\n return i;\n }",
"public static ObjectName registerMbean(String typeName, Object obj) {\n MBeanServer server = ManagementFactory.getPlatformMBeanServer();\n ObjectName name = JmxUtils.createObjectName(JmxUtils.getPackageName(obj.getClass()),\n typeName);\n registerMbean(server, JmxUtils.createModelMBean(obj), name);\n return name;\n }",
"private SiteRecord getSiteRecord(String siteKey) {\n\t\tSiteRecord siteRecord = this.siteRecords.get(siteKey);\n\t\tif (siteRecord == null) {\n\t\t\tsiteRecord = new SiteRecord(siteKey);\n\t\t\tthis.siteRecords.put(siteKey, siteRecord);\n\t\t}\n\t\treturn siteRecord;\n\t}"
] |
Use this API to disable nsfeature. | [
"public static base_response disable(nitro_service client, nsfeature resource) throws Exception {\n\t\tnsfeature disableresource = new nsfeature();\n\t\tdisableresource.feature = resource.feature;\n\t\treturn disableresource.perform_operation(client,\"disable\");\n\t}"
] | [
"public WebSocketContext sendToTagged(String message, String tag, boolean excludeSelf) {\n return sendToConnections(message, tag, manager.tagRegistry(), excludeSelf);\n }",
"public static ResourceDescriptionResolver getResourceDescriptionResolver(final String... keyPrefix) {\n StringBuilder prefix = new StringBuilder(SUBSYSTEM_NAME);\n for (String kp : keyPrefix) {\n prefix.append('.').append(kp);\n }\n return new StandardResourceDescriptionResolver(prefix.toString(), RESOURCE_NAME, LoggingExtension.class.getClassLoader(), true, false) {\n @Override\n public String getOperationParameterDescription(final String operationName, final String paramName, final Locale locale, final ResourceBundle bundle) {\n if (DELEGATE_DESC_OPTS.contains(operationName)) {\n return getResourceAttributeDescription(paramName, locale, bundle);\n }\n return super.getOperationParameterDescription(operationName, paramName, locale, bundle);\n }\n\n @Override\n public String getOperationParameterValueTypeDescription(final String operationName, final String paramName, final Locale locale,\n final ResourceBundle bundle, final String... suffixes) {\n if (DELEGATE_DESC_OPTS.contains(operationName)) {\n return getResourceAttributeDescription(paramName, locale, bundle);\n }\n return super.getOperationParameterValueTypeDescription(operationName, paramName, locale, bundle, suffixes);\n }\n\n @Override\n public String getOperationParameterDeprecatedDescription(final String operationName, final String paramName, final Locale locale, final ResourceBundle bundle) {\n if (DELEGATE_DESC_OPTS.contains(operationName)) {\n return getResourceAttributeDeprecatedDescription(paramName, locale, bundle);\n }\n return super.getOperationParameterDeprecatedDescription(operationName, paramName, locale, bundle);\n }\n };\n }",
"public int getMinutesPerYear()\n {\n return m_minutesPerYear == null ? NumberHelper.getInt(getParentFile().getProjectProperties().getMinutesPerYear()) : m_minutesPerYear.intValue();\n }",
"public static <T> OptionalValue<T> ofNullable(T value) {\n return new GenericOptionalValue<T>(RUNTIME_SOURCE, DEFAULT_KEY, value);\n }",
"public static base_response update(nitro_service client, snmpuser resource) throws Exception {\n\t\tsnmpuser updateresource = new snmpuser();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.group = resource.group;\n\t\tupdateresource.authtype = resource.authtype;\n\t\tupdateresource.authpasswd = resource.authpasswd;\n\t\tupdateresource.privtype = resource.privtype;\n\t\tupdateresource.privpasswd = resource.privpasswd;\n\t\treturn updateresource.update_resource(client);\n\t}",
"@Override\n protected void onLoad() {\n\tsuper.onLoad();\n\n\t// these styles need to be the same for the box and shadow so\n\t// that we can measure properly\n\tmatchStyles(\"display\");\n\tmatchStyles(\"fontSize\");\n\tmatchStyles(\"fontFamily\");\n\tmatchStyles(\"fontWeight\");\n\tmatchStyles(\"lineHeight\");\n\tmatchStyles(\"paddingTop\");\n\tmatchStyles(\"paddingRight\");\n\tmatchStyles(\"paddingBottom\");\n\tmatchStyles(\"paddingLeft\");\n\n\tadjustSize();\n }",
"public static final List<String> listProjectNames(File directory)\n {\n List<String> result = new ArrayList<String>();\n\n File[] files = directory.listFiles(new FilenameFilter()\n {\n @Override public boolean accept(File dir, String name)\n {\n return name.toUpperCase().endsWith(\"STR.P3\");\n }\n });\n\n if (files != null)\n {\n for (File file : files)\n {\n String fileName = file.getName();\n String prefix = fileName.substring(0, fileName.length() - 6);\n result.add(prefix);\n }\n }\n\n Collections.sort(result);\n\n return result;\n }",
"private void makeSingularPositive() {\n numSingular = qralg.getNumberOfSingularValues();\n singularValues = qralg.getSingularValues();\n\n for( int i = 0; i < numSingular; i++ ) {\n double val = qralg.getSingularValue(i);\n\n if( val < 0 ) {\n singularValues[i] = 0.0 - val;\n\n if( computeU ) {\n // compute the results of multiplying it by an element of -1 at this location in\n // a diagonal matrix.\n int start = i* Ut.numCols;\n int stop = start+ Ut.numCols;\n\n for( int j = start; j < stop; j++ ) {\n Ut.set(j, 0.0 - Ut.get(j));\n }\n }\n } else {\n singularValues[i] = val;\n }\n }\n }",
"public static void read(InputStream stream, byte[] buffer) throws IOException {\n int read = 0;\n while(read < buffer.length) {\n int newlyRead = stream.read(buffer, read, buffer.length - read);\n if(newlyRead == -1)\n throw new EOFException(\"Attempt to read \" + buffer.length\n + \" bytes failed due to EOF.\");\n read += newlyRead;\n }\n }"
] |
Get PhoneNumber object
@return PhonenUmber | null on error | [
"@SuppressWarnings(\"unused\")\n public Phonenumber.PhoneNumber getPhoneNumber() {\n try {\n String iso = null;\n if (mSelectedCountry != null) {\n iso = mSelectedCountry.getIso();\n }\n return mPhoneUtil.parse(mPhoneEdit.getText().toString(), iso);\n } catch (NumberParseException ignored) {\n return null;\n }\n }"
] | [
"public static boolean ensureJedisConnection(final Jedis jedis) {\n final boolean jedisOK = testJedisConnection(jedis);\n if (!jedisOK) {\n try {\n jedis.quit();\n } catch (Exception e) {\n } // Ignore\n try {\n jedis.disconnect();\n } catch (Exception e) {\n } // Ignore\n jedis.connect();\n }\n return jedisOK;\n }",
"private boolean hidden(String className) {\n\tclassName = removeTemplate(className);\n\tClassInfo ci = classnames.get(className);\n\treturn ci != null ? ci.hidden : optionProvider.getOptionsFor(className).matchesHideExpression(className);\n }",
"public void splitSpan(int n) {\n\t\tint x = (xKnots[n] + xKnots[n+1])/2;\n\t\taddKnot(x, getColor(x/256.0f), knotTypes[n]);\n\t\trebuildGradient();\n\t}",
"synchronized void removeUserProfile(String id) {\n\n if (id == null) return;\n final String tableName = Table.USER_PROFILES.getName();\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n db.delete(tableName, \"_id = ?\", new String[]{id});\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error removing user profile from \" + tableName + \" Recreating DB\");\n dbHelper.deleteDatabase();\n } finally {\n dbHelper.close();\n }\n }",
"private void processActivities(Storepoint phoenixProject)\n {\n final AlphanumComparator comparator = new AlphanumComparator();\n List<Activity> activities = phoenixProject.getActivities().getActivity();\n Collections.sort(activities, new Comparator<Activity>()\n {\n @Override public int compare(Activity o1, Activity o2)\n {\n Map<UUID, UUID> codes1 = getActivityCodes(o1);\n Map<UUID, UUID> codes2 = getActivityCodes(o2);\n for (UUID code : m_codeSequence)\n {\n UUID codeValue1 = codes1.get(code);\n UUID codeValue2 = codes2.get(code);\n\n if (codeValue1 == null || codeValue2 == null)\n {\n if (codeValue1 == null && codeValue2 == null)\n {\n continue;\n }\n\n if (codeValue1 == null)\n {\n return -1;\n }\n\n if (codeValue2 == null)\n {\n return 1;\n }\n }\n\n if (!codeValue1.equals(codeValue2))\n {\n Integer sequence1 = m_activityCodeSequence.get(codeValue1);\n Integer sequence2 = m_activityCodeSequence.get(codeValue2);\n\n return NumberHelper.compare(sequence1, sequence2);\n }\n }\n\n return comparator.compare(o1.getId(), o2.getId());\n }\n });\n\n for (Activity activity : activities)\n {\n processActivity(activity);\n }\n }",
"public static boolean lower( double[]T , int indexT , int n ) {\n double el_ii;\n double div_el_ii=0;\n\n for( int i = 0; i < n; i++ ) {\n for( int j = i; j < n; j++ ) {\n double sum = T[ indexT + j*n+i];\n\n // todo optimize\n for( int k = 0; k < i; k++ ) {\n sum -= T[ indexT + i*n+k] * T[ indexT + j*n+k];\n }\n\n if( i == j ) {\n // is it positive-definite?\n if( sum <= 0.0 )\n return false;\n\n el_ii = Math.sqrt(sum);\n T[ indexT + i*n+i] = el_ii;\n div_el_ii = 1.0/el_ii;\n } else {\n T[ indexT + j*n+i] = sum*div_el_ii;\n }\n }\n }\n\n return true;\n }",
"public double determinant() {\n if (m != n) {\n throw new IllegalArgumentException(\"Matrix must be square.\");\n }\n double d = (double) pivsign;\n for (int j = 0; j < n; j++) {\n d *= LU[j][j];\n }\n return d;\n }",
"public double distanceSquared(Vector3d v) {\n double dx = x - v.x;\n double dy = y - v.y;\n double dz = z - v.z;\n\n return dx * dx + dy * dy + dz * dz;\n }",
"public static boolean isAlternative(EnhancedAnnotated<?, ?> annotated, MergedStereotypes<?, ?> mergedStereotypes) {\n return annotated.isAnnotationPresent(Alternative.class) || mergedStereotypes.isAlternative();\n }"
] |
Attempt to detect the current platform.
@return The current platform.
@throws UnsupportedPlatformException if the platform cannot be detected. | [
"public static Platform detect() throws UnsupportedPlatformException {\n String osArch = getProperty(\"os.arch\");\n String osName = getProperty(\"os.name\");\n\n for (Arch arch : Arch.values()) {\n if (arch.pattern.matcher(osArch).matches()) {\n for (OS os : OS.values()) {\n if (os.pattern.matcher(osName).matches()) {\n return new Platform(arch, os);\n }\n }\n }\n }\n\n String msg = String.format(\"Unsupported platform %s %s\", osArch, osName);\n throw new UnsupportedPlatformException(msg);\n }"
] | [
"public void setText(String text) {\n span.setText(text);\n\n if (!span.isAttached()) {\n add(span);\n }\n }",
"public void updateGroupName(String newGroupName, int id) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_GROUPS +\n \" SET \" + Constants.GROUPS_GROUP_NAME + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, newGroupName);\n statement.setInt(2, id);\n statement.executeUpdate();\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 static int getLineNumber(Member member) {\n\n if (!(member instanceof Method || member instanceof Constructor)) {\n // We are not able to get this info for fields\n return 0;\n }\n\n // BCEL is an optional dependency, if we cannot load it, simply return 0\n if (!Reflections.isClassLoadable(BCEL_CLASS, WeldClassLoaderResourceLoader.INSTANCE)) {\n return 0;\n }\n\n String classFile = member.getDeclaringClass().getName().replace('.', '/');\n ClassLoaderResourceLoader classFileResourceLoader = new ClassLoaderResourceLoader(member.getDeclaringClass().getClassLoader());\n InputStream in = null;\n\n try {\n URL classFileUrl = classFileResourceLoader.getResource(classFile + \".class\");\n\n if (classFileUrl == null) {\n // The class file is not available\n return 0;\n }\n in = classFileUrl.openStream();\n\n ClassParser cp = new ClassParser(in, classFile);\n JavaClass javaClass = cp.parse();\n\n // First get all declared methods and constructors\n // Note that in bytecode constructor is translated into a method\n org.apache.bcel.classfile.Method[] methods = javaClass.getMethods();\n org.apache.bcel.classfile.Method match = null;\n\n String signature;\n String name;\n if (member instanceof Method) {\n signature = DescriptorUtils.methodDescriptor((Method) member);\n name = member.getName();\n } else if (member instanceof Constructor) {\n signature = DescriptorUtils.makeDescriptor((Constructor<?>) member);\n name = INIT_METHOD_NAME;\n } else {\n return 0;\n }\n\n for (org.apache.bcel.classfile.Method method : methods) {\n // Matching method must have the same name, modifiers and signature\n if (method.getName().equals(name)\n && member.getModifiers() == method.getModifiers()\n && method.getSignature().equals(signature)) {\n match = method;\n }\n }\n if (match != null) {\n // If a method is found, try to obtain the optional LineNumberTable attribute\n LineNumberTable lineNumberTable = match.getLineNumberTable();\n if (lineNumberTable != null) {\n int line = lineNumberTable.getSourceLine(0);\n return line == -1 ? 0 : line;\n }\n }\n // No suitable method found\n return 0;\n\n } catch (Throwable t) {\n return 0;\n } finally {\n if (in != null) {\n try {\n in.close();\n } catch (Exception e) {\n return 0;\n }\n }\n }\n }",
"public static GlobalParameter create(DbConn cnx, String key, String value)\n {\n QueryResult r = cnx.runUpdate(\"globalprm_insert\", key, value);\n GlobalParameter res = new GlobalParameter();\n res.id = r.getGeneratedId();\n res.key = key;\n res.value = value;\n return res;\n }",
"public ArrayList getFields(String fieldNames) throws NoSuchFieldException\r\n {\r\n ArrayList result = new ArrayList();\r\n FieldDescriptorDef fieldDef;\r\n String name;\r\n\r\n for (CommaListIterator it = new CommaListIterator(fieldNames); it.hasNext();)\r\n {\r\n name = it.getNext();\r\n fieldDef = getField(name);\r\n if (fieldDef == null)\r\n {\r\n throw new NoSuchFieldException(name);\r\n }\r\n result.add(fieldDef);\r\n }\r\n return result;\r\n }",
"public static int[] ConcatenateInt(List<int[]> arrays) {\n\n int size = 0;\n for (int i = 0; i < arrays.size(); i++) {\n size += arrays.get(i).length;\n }\n\n int[] all = new int[size];\n int idx = 0;\n\n for (int i = 0; i < arrays.size(); i++) {\n int[] v = arrays.get(i);\n for (int j = 0; j < v.length; j++) {\n all[idx++] = v[i];\n }\n }\n\n return all;\n }",
"public static final MVCArray buildArcPoints(LatLong center, double startBearing, double endBearing, double radius) {\n int points = DEFAULT_ARC_POINTS;\n\n MVCArray res = new MVCArray();\n\n if (startBearing > endBearing) {\n endBearing += 360.0;\n }\n double deltaBearing = endBearing - startBearing;\n deltaBearing = deltaBearing / points;\n for (int i = 0; (i < points + 1); i++) {\n res.push(center.getDestinationPoint(startBearing + i * deltaBearing, radius));\n }\n\n return res;\n\n }",
"public static Integer getDay(Day day)\n {\n Integer result = null;\n if (day != null)\n {\n result = DAY_MAP.get(day);\n }\n return (result);\n }",
"private <T> Observable<PollingState<T>> updateStateFromLocationHeaderOnPutAsync(final PollingState<T> pollingState) {\n return pollAsync(pollingState.locationHeaderLink(), pollingState.loggingContext())\n .flatMap(new Func1<Response<ResponseBody>, Observable<PollingState<T>>>() {\n @Override\n public Observable<PollingState<T>> call(Response<ResponseBody> response) {\n int statusCode = response.code();\n if (statusCode == 202) {\n pollingState.withResponse(response);\n pollingState.withStatus(AzureAsyncOperation.IN_PROGRESS_STATUS, statusCode);\n } else if (statusCode == 200 || statusCode == 201) {\n try {\n pollingState.updateFromResponseOnPutPatch(response);\n } catch (CloudException | IOException e) {\n return Observable.error(e);\n }\n }\n return Observable.just(pollingState);\n }\n });\n }"
] |
Main entry point used to determine the format used to write
calendar exceptions.
@param calendar parent calendar
@param dayList list of calendar days
@param exceptions list of exceptions | [
"private void writeExceptions(Project.Calendars.Calendar calendar, List<Project.Calendars.Calendar.WeekDays.WeekDay> dayList, List<ProjectCalendarException> exceptions)\n {\n // Always write legacy exception data:\n // Powerproject appears not to recognise new format data at all,\n // and legacy data is ignored in preference to new data post MSP 2003\n writeExceptions9(dayList, exceptions);\n\n if (m_saveVersion.getValue() > SaveVersion.Project2003.getValue())\n {\n writeExceptions12(calendar, exceptions);\n }\n }"
] | [
"public int getBoneIndex(GVRSceneObject bone)\n {\n for (int i = 0; i < getNumBones(); ++i)\n if (mBones[i] == bone)\n return i;\n return -1;\n }",
"public void load(File file) {\n try {\n PropertiesConfiguration config = new PropertiesConfiguration();\n // disabled to prevent accumulo classpath value from being shortened\n config.setDelimiterParsingDisabled(true);\n config.load(file);\n ((CompositeConfiguration) internalConfig).addConfiguration(config);\n } catch (ConfigurationException e) {\n throw new IllegalArgumentException(e);\n }\n }",
"public SchedulerDocsResponse.Doc schedulerDoc(String docId) {\n assertNotEmpty(docId, \"docId\");\n return this.get(new DatabaseURIHelper(getBaseUri()).\n path(\"_scheduler\").path(\"docs\").path(\"_replicator\").path(docId).build(),\n SchedulerDocsResponse.Doc.class);\n }",
"private static int findNext(boolean reverse, int pos) {\n boolean backwards = IS_BACKWARDS_CHECKBOX.isSelected();\n backwards = backwards ? !reverse : reverse;\n\n String pattern = (String) FIND_FIELD.getSelectedItem();\n if (pattern != null && pattern.length() > 0) {\n try {\n Document doc = textComponent.getDocument();\n doc.getText(0, doc.getLength(), SEGMENT);\n }\n catch (Exception e) {\n // should NEVER reach here\n e.printStackTrace();\n }\n\n pos += textComponent.getSelectedText() == null ?\n (backwards ? -1 : 1) : 0;\n\n char first = backwards ?\n pattern.charAt(pattern.length() - 1) : pattern.charAt(0);\n char oppFirst = Character.isUpperCase(first) ?\n Character.toLowerCase(first) : Character.toUpperCase(first);\n int start = pos;\n boolean wrapped = WRAP_SEARCH_CHECKBOX.isSelected();\n int end = backwards ? 0 : SEGMENT.getEndIndex();\n pos += backwards ? -1 : 1;\n\n int length = textComponent.getDocument().getLength();\n if (pos > length) {\n pos = wrapped ? 0 : length;\n }\n\n boolean found = false;\n while (!found && (backwards ? pos > end : pos < end)) {\n found = !MATCH_CASE_CHECKBOX.isSelected() && SEGMENT.array[pos] == oppFirst;\n found = found ? found : SEGMENT.array[pos] == first;\n\n if (found) {\n pos += backwards ? -(pattern.length() - 1) : 0;\n for (int i = 0; found && i < pattern.length(); i++) {\n char c = pattern.charAt(i);\n found = SEGMENT.array[pos + i] == c;\n if (!MATCH_CASE_CHECKBOX.isSelected() && !found) {\n c = Character.isUpperCase(c) ?\n Character.toLowerCase(c) :\n Character.toUpperCase(c);\n found = SEGMENT.array[pos + i] == c;\n }\n }\n }\n\n if (!found) {\n pos += backwards ? -1 : 1;\n\n if (pos == end && wrapped) {\n pos = backwards ? SEGMENT.getEndIndex() : 0;\n end = start;\n wrapped = false;\n }\n }\n }\n pos = found ? pos : -1;\n }\n\n return pos;\n }",
"public static base_response update(nitro_service client, dbdbprofile resource) throws Exception {\n\t\tdbdbprofile updateresource = new dbdbprofile();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.interpretquery = resource.interpretquery;\n\t\tupdateresource.stickiness = resource.stickiness;\n\t\tupdateresource.kcdaccount = resource.kcdaccount;\n\t\tupdateresource.conmultiplex = resource.conmultiplex;\n\t\treturn updateresource.update_resource(client);\n\t}",
"public static final Integer parseInteger(String value)\n {\n return (value == null || value.length() == 0 ? null : Integer.valueOf(Integer.parseInt(value)));\n }",
"public Collection<DataSource> getDataSources(int groupno) {\n if (groupno == 1)\n return group1;\n else if (groupno == 2)\n return group2;\n else\n throw new DukeConfigException(\"Invalid group number: \" + groupno);\n }",
"public int findAnimation(GVRAnimation findme)\n {\n int index = 0;\n for (GVRAnimation anim : mAnimations)\n {\n if (anim == findme)\n {\n return index;\n }\n ++index;\n }\n return -1;\n }",
"private void persistDisabledVersion(long version) throws PersistenceFailureException {\n File disabledMarker = getDisabledMarkerFile(version);\n try {\n disabledMarker.createNewFile();\n } catch (IOException e) {\n throw new PersistenceFailureException(\"Failed to create the disabled marker at path: \" +\n disabledMarker.getAbsolutePath() + \"\\nThe store/version \" +\n \"will remain disabled only until the next restart.\", e);\n }\n }"
] |
Get a timer of the given string name for the given thread. If no such
timer exists yet, then it will be newly created.
@param timerName
the name of the timer
@param todoFlags
@param threadId
of the thread to track, or 0 if only system clock should be
tracked
@return timer | [
"public static Timer getNamedTimer(String timerName, int todoFlags,\n\t\t\tlong threadId) {\n\t\tTimer key = new Timer(timerName, todoFlags, threadId);\n\t\tregisteredTimers.putIfAbsent(key, key);\n\t\treturn registeredTimers.get(key);\n\t}"
] | [
"protected void checkVariableName(GraphRewrite event, EvaluationContext context)\n {\n if (getInputVariablesName() == null)\n {\n setInputVariablesName(Iteration.getPayloadVariableName(event, context));\n }\n }",
"private void populateDateTimeSettings(Record record, ProjectProperties properties)\n {\n properties.setDateOrder(record.getDateOrder(0));\n properties.setTimeFormat(record.getTimeFormat(1));\n\n Date time = getTimeFromInteger(record.getInteger(2));\n if (time != null)\n {\n properties.setDefaultStartTime(time);\n }\n\n Character c = record.getCharacter(3);\n if (c != null)\n {\n properties.setDateSeparator(c.charValue());\n }\n\n c = record.getCharacter(4);\n if (c != null)\n {\n properties.setTimeSeparator(c.charValue());\n }\n\n properties.setAMText(record.getString(5));\n properties.setPMText(record.getString(6));\n properties.setDateFormat(record.getDateFormat(7));\n properties.setBarTextDateFormat(record.getDateFormat(8));\n }",
"public static RemoteProxyController create(final TransactionalProtocolClient client, final PathAddress pathAddress,\n final ProxyOperationAddressTranslator addressTranslator,\n final ModelVersion targetKernelVersion) {\n return new RemoteProxyController(client, pathAddress, addressTranslator, targetKernelVersion);\n }",
"public PartitionInfo partitionInfo(String partitionKey) {\n if (partitionKey == null) {\n throw new UnsupportedOperationException(\"Cannot get partition information for null partition key.\");\n }\n URI uri = new DatabaseURIHelper(db.getDBUri()).partition(partitionKey).build();\n return client.couchDbClient.get(uri, PartitionInfo.class);\n }",
"public static int[] Argsort(final float[] array, final boolean ascending) {\n Integer[] indexes = new Integer[array.length];\n for (int i = 0; i < indexes.length; i++) {\n indexes[i] = i;\n }\n Arrays.sort(indexes, new Comparator<Integer>() {\n @Override\n public int compare(final Integer i1, final Integer i2) {\n return (ascending ? 1 : -1) * Float.compare(array[i1], array[i2]);\n }\n });\n return asArray(indexes);\n }",
"public void refreshConnection() throws SQLException{\r\n\t\tthis.connection.close(); // if it's still in use, close it.\r\n\t\ttry{\r\n\t\t\tthis.connection = this.pool.obtainRawInternalConnection();\r\n\t\t} catch(SQLException e){\r\n\t\t\tthrow markPossiblyBroken(e);\r\n\t\t}\r\n\t}",
"@Override\n public AccountingDate dateYearDay(Era era, int yearOfEra, int dayOfYear) {\n return dateYearDay(prolepticYear(era, yearOfEra), dayOfYear);\n }",
"private int indexFor(int hash)\r\n {\r\n // mix the bits to avoid bucket collisions...\r\n hash += ~(hash << 15);\r\n hash ^= (hash >>> 10);\r\n hash += (hash << 3);\r\n hash ^= (hash >>> 6);\r\n hash += ~(hash << 11);\r\n hash ^= (hash >>> 16);\r\n return hash & (table.length - 1);\r\n }",
"private void populateResourceAssignmentWorkgroupFields(Record record, ResourceAssignmentWorkgroupFields workgroup) throws MPXJException\n {\n workgroup.setMessageUniqueID(record.getString(0));\n workgroup.setConfirmed(NumberHelper.getInt(record.getInteger(1)) == 1);\n workgroup.setResponsePending(NumberHelper.getInt(record.getInteger(1)) == 1);\n workgroup.setUpdateStart(record.getDateTime(3));\n workgroup.setUpdateFinish(record.getDateTime(4));\n workgroup.setScheduleID(record.getString(5));\n }"
] |
Used by Pipeline jobs only | [
"public boolean perform(Run<?, ?> build, Launcher launcher, TaskListener listener, EnvVars env, FilePath workDir, FilePath tempDir)\n throws InterruptedException, IOException {\n listener.getLogger().println(\"Jenkins Artifactory Plugin version: \" + ActionableHelper.getArtifactoryPluginVersion());\n FilePath mavenHome = getMavenHome(listener, env, launcher);\n\n if (!mavenHome.exists()) {\n listener.getLogger().println(\"Couldn't find Maven home at \" + mavenHome.getRemote() + \" on agent \" + Utils.getAgentName(workDir) +\n \". This could be because this build is running inside a Docker container.\");\n }\n ArgumentListBuilder cmdLine = buildMavenCmdLine(build, listener, env, launcher, mavenHome, workDir, tempDir);\n String[] cmds = cmdLine.toCommandArray();\n return RunMaven(build, launcher, listener, env, workDir, cmds);\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 void setMenuView(int layoutResId) {\n mMenuContainer.removeAllViews();\n mMenuView = LayoutInflater.from(getContext()).inflate(layoutResId, mMenuContainer, false);\n mMenuContainer.addView(mMenuView);\n }",
"private void setRequestLanguages(WbGetEntitiesActionData properties) {\n\t\tif (this.filter.excludeAllLanguages()\n\t\t\t\t|| this.filter.getLanguageFilter() == null) {\n\t\t\treturn;\n\t\t}\n\t\tproperties.languages = ApiConnection.implodeObjects(this.filter\n\t\t\t\t.getLanguageFilter());\n\t}",
"public static <E extends Enum<E>> EnumStringConverter<E> create(Class<E> enumType) {\n return new EnumStringConverter<E>(enumType);\n }",
"protected String getContextPath(){\n\n if(context != null) return context;\n\n if(get(\"context_path\") == null){\n throw new ViewException(\"context_path missing - red alarm!\");\n }\n return get(\"context_path\").toString();\n }",
"private double convertMaturity(int maturityInMonths) {\r\n\t\tSchedule schedule = fixMetaSchedule.generateSchedule(referenceDate, maturityInMonths, 12);\r\n\t\treturn schedule.getFixing(0);\r\n\t}",
"public synchronized void removeAllSceneObjects() {\n final GVRCameraRig rig = getMainCameraRig();\n final GVRSceneObject head = rig.getOwnerObject();\n rig.removeAllChildren();\n\n NativeScene.removeAllSceneObjects(getNative());\n for (final GVRSceneObject child : mSceneRoot.getChildren()) {\n child.getParent().removeChildObject(child);\n }\n\n if (null != head) {\n mSceneRoot.addChildObject(head);\n }\n\n final int numControllers = getGVRContext().getInputManager().clear();\n if (numControllers > 0)\n {\n getGVRContext().getInputManager().selectController();\n }\n\n getGVRContext().runOnGlThread(new Runnable() {\n @Override\n public void run() {\n NativeScene.deleteLightsAndDepthTextureOnRenderThread(getNative());\n }\n });\n }",
"public static int hash(int input)\n {\n int k1 = mixK1(input);\n int h1 = mixH1(DEFAULT_SEED, k1);\n\n return fmix(h1, SizeOf.SIZE_OF_INT);\n }",
"public boolean uploadConfigurationAndProfile(String fileName, String odoImport) {\n File file = new File(fileName);\n MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();\n FileBody fileBody = new FileBody(file, ContentType.MULTIPART_FORM_DATA);\n multipartEntityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);\n multipartEntityBuilder.addPart(\"fileData\", fileBody);\n multipartEntityBuilder.addTextBody(\"odoImport\", odoImport);\n try {\n JSONObject response = new JSONObject(doMultipartPost(BASE_BACKUP_PROFILE + \"/\" + uriEncode(this._profileName) + \"/\" + this._clientId, multipartEntityBuilder));\n if (response.length() == 0) {\n return true;\n } else {\n return false;\n }\n } catch (Exception e) {\n return false;\n }\n }"
] |
remove a converted object from the pool
@param converter
@param sourceObject
@param destinationType | [
"public void remove(IConverter converter, Object sourceObject,\n\t\t\tTypeReference<?> destinationType) {\n\t\tconvertedObjects.remove(new ConvertedObjectsKey(converter,\n\t\t\t\tsourceObject, destinationType));\n\t}"
] | [
"public Iterable<BoxItem.Info> getChildren(final String... fields) {\n return new Iterable<BoxItem.Info>() {\n @Override\n public Iterator<BoxItem.Info> iterator() {\n String queryString = new QueryStringBuilder().appendParam(\"fields\", fields).toString();\n URL url = GET_ITEMS_URL.buildWithQuery(getAPI().getBaseURL(), queryString, getID());\n return new BoxItemIterator(getAPI(), url);\n }\n };\n }",
"public static LocalDateTime getDateFromFloatingPointDate(LocalDateTime referenceDate, double floatingPointDate) {\n\t\tif(referenceDate == null) {\n\t\t\treturn null;\n\t\t}\n\n\t\tDuration duration = Duration.ofSeconds(Math.round(floatingPointDate * SECONDS_PER_DAY));\n\t\treturn referenceDate.plus(duration);\n\t}",
"public ProjectCalendarException addCalendarException(Date fromDate, Date toDate)\n {\n ProjectCalendarException bce = new ProjectCalendarException(fromDate, toDate);\n m_exceptions.add(bce);\n m_expandedExceptions.clear();\n m_exceptionsSorted = false;\n clearWorkingDateCache();\n return bce;\n }",
"private void processAnalytics() throws SQLException\n {\n allocateConnection();\n\n try\n {\n DatabaseMetaData meta = m_connection.getMetaData();\n String productName = meta.getDatabaseProductName();\n if (productName == null || productName.isEmpty())\n {\n productName = \"DATABASE\";\n }\n else\n {\n productName = productName.toUpperCase();\n }\n\n ProjectProperties properties = m_reader.getProject().getProjectProperties();\n properties.setFileApplication(\"Primavera\");\n properties.setFileType(productName);\n }\n\n finally\n {\n releaseConnection();\n }\n }",
"public static responderpolicylabel_responderpolicy_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tresponderpolicylabel_responderpolicy_binding obj = new responderpolicylabel_responderpolicy_binding();\n\t\tobj.set_labelname(labelname);\n\t\tresponderpolicylabel_responderpolicy_binding response[] = (responderpolicylabel_responderpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public PeriodicEvent runEvery(Runnable task, float delay, float period) {\n return runEvery(task, delay, period, null);\n }",
"public Model interpolateModel(Model model, File projectDir, ModelBuildingRequest config,\n\t\t\tModelProblemCollector problems) {\n\t\tinterpolateObject(model, model, projectDir, config, problems);\n\n\t\treturn model;\n\t}",
"public void forAllIndices(String template, Properties attributes) throws XDocletException\r\n {\r\n boolean processUnique = TypeConversionUtil.stringToBoolean(attributes.getProperty(ATTRIBUTE_UNIQUE), false);\r\n\r\n // first the default index\r\n _curIndexDef = _curTableDef.getIndex(null);\r\n if ((_curIndexDef != null) && (processUnique == _curIndexDef.isUnique()))\r\n {\r\n generate(template);\r\n }\r\n for (Iterator it = _curTableDef.getIndices(); it.hasNext(); )\r\n {\r\n _curIndexDef = (IndexDef)it.next();\r\n if (!_curIndexDef.isDefault() && (processUnique == _curIndexDef.isUnique()))\r\n { \r\n generate(template);\r\n }\r\n }\r\n _curIndexDef = null;\r\n }",
"private static void parseBounds(JSONObject modelJSON,\n Shape current) throws JSONException {\n if (modelJSON.has(\"bounds\")) {\n JSONObject boundsObject = modelJSON.getJSONObject(\"bounds\");\n current.setBounds(new Bounds(new Point(boundsObject.getJSONObject(\"lowerRight\").getDouble(\"x\"),\n boundsObject.getJSONObject(\"lowerRight\").getDouble(\n \"y\")),\n new Point(boundsObject.getJSONObject(\"upperLeft\").getDouble(\"x\"),\n boundsObject.getJSONObject(\"upperLeft\").getDouble(\"y\"))));\n }\n }"
] |
Returns the name under which this dump file. This is the name used online
and also locally when downloading the file.
@param dumpContentType
the type of the dump
@param projectName
the project name, e.g. "wikidatawiki"
@param dateStamp
the date of the dump in format YYYYMMDD
@return file name string | [
"public static String getDumpFileName(DumpContentType dumpContentType,\n\t\t\tString projectName, String dateStamp) {\n\t\tif (dumpContentType == DumpContentType.JSON) {\n\t\t\treturn dateStamp + WmfDumpFile.getDumpFilePostfix(dumpContentType);\n\t\t} else {\n\t\t\treturn projectName + \"-\" + dateStamp\n\t\t\t\t\t+ WmfDumpFile.getDumpFilePostfix(dumpContentType);\n\t\t}\n\t}"
] | [
"private static int skipEndOfLine(String text, int offset)\n {\n char c;\n boolean finished = false;\n\n while (finished == false)\n {\n c = text.charAt(offset);\n switch (c)\n {\n case ' ': // found that OBJDATA could be followed by a space the EOL\n case '\\r':\n case '\\n':\n {\n ++offset;\n break;\n }\n\n case '}':\n {\n offset = -1;\n finished = true;\n break;\n }\n\n default:\n {\n finished = true;\n break;\n }\n }\n }\n\n return (offset);\n }",
"public static void addToListIfNotExists(List<String> list, String value) {\n boolean found = false;\n for (String item : list) {\n if (item.equalsIgnoreCase(value)) {\n found = true;\n break;\n }\n }\n if (!found) {\n list.add(value);\n }\n }",
"protected List<String> getPluginsPath() throws IOException {\n List<String> result = new ArrayList<>();\n Path pluginsDirectory = PROPERTIES.getAllureHome().resolve(\"plugins\").toAbsolutePath();\n if (Files.notExists(pluginsDirectory)) {\n return Collections.emptyList();\n }\n\n try (DirectoryStream<Path> plugins = Files.newDirectoryStream(pluginsDirectory, JAR_FILES)) {\n for (Path plugin : plugins) {\n result.add(plugin.toUri().toURL().toString());\n }\n }\n return result;\n }",
"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 }",
"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 csvserver_cmppolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tcsvserver_cmppolicy_binding obj = new csvserver_cmppolicy_binding();\n\t\tobj.set_name(name);\n\t\tcsvserver_cmppolicy_binding response[] = (csvserver_cmppolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}",
"public static Cluster createUpdatedCluster(Cluster currentCluster,\n int stealerNodeId,\n List<Integer> donatedPartitions) {\n Cluster updatedCluster = Cluster.cloneCluster(currentCluster);\n // Go over every donated partition one by one\n for(int donatedPartition: donatedPartitions) {\n\n // Gets the donor Node that owns this donated partition\n Node donorNode = updatedCluster.getNodeForPartitionId(donatedPartition);\n Node stealerNode = updatedCluster.getNodeById(stealerNodeId);\n\n if(donorNode == stealerNode) {\n // Moving to the same location = No-op\n continue;\n }\n\n // Update the list of partitions for this node\n donorNode = removePartitionFromNode(donorNode, donatedPartition);\n stealerNode = addPartitionToNode(stealerNode, donatedPartition);\n\n // Sort the nodes\n updatedCluster = updateCluster(updatedCluster,\n Lists.newArrayList(donorNode, stealerNode));\n\n }\n\n return updatedCluster;\n }",
"public String getUniqueFilename(String baseFileName, String extension, boolean cleanBaseFileName, String... ancestorFolders)\n {\n if (cleanBaseFileName)\n {\n baseFileName = PathUtil.cleanFileName(baseFileName);\n }\n\n if (ancestorFolders != null)\n {\n Path pathToFile = Paths.get(\"\", Stream.of(ancestorFolders).map(ancestor -> PathUtil.cleanFileName(ancestor)).toArray(String[]::new)).resolve(baseFileName);\n baseFileName = pathToFile.toString();\n }\n String filename = baseFileName + \".\" + extension;\n\n // FIXME this looks nasty\n while (usedFilenames.contains(filename))\n {\n filename = baseFileName + \".\" + index.getAndIncrement() + \".\" + extension;\n }\n usedFilenames.add(filename);\n\n return filename;\n }",
"protected AbstractColumn buildSimpleBarcodeColumn() {\n\t\tBarCodeColumn column = new BarCodeColumn();\n\t\tpopulateCommonAttributes(column);\n\t\tcolumn.setColumnProperty(columnProperty);\n\t\tcolumn.setExpressionToGroupBy(customExpressionToGroupBy);\n\t\tcolumn.setScaleMode(imageScaleMode);\n\t\tcolumn.setApplicationIdentifier(applicationIdentifier);\n\t\tcolumn.setBarcodeType(barcodeType);\n\t\tcolumn.setShowText(showText);\n\t\tcolumn.setCheckSum(checkSum);\n\t\treturn column;\n\t}"
] |
Unilaterally merge an update description into this update description.
@param otherDescription the update description to merge into this
@return this merged update description | [
"public UpdateDescription merge(@Nullable final UpdateDescription otherDescription) {\n if (otherDescription != null) {\n for (final Map.Entry<String, BsonValue> entry : this.updatedFields.entrySet()) {\n if (otherDescription.removedFields.contains(entry.getKey())) {\n this.updatedFields.remove(entry.getKey());\n }\n }\n for (final String removedField : this.removedFields) {\n if (otherDescription.updatedFields.containsKey(removedField)) {\n this.removedFields.remove(removedField);\n }\n }\n\n this.removedFields.addAll(otherDescription.removedFields);\n this.updatedFields.putAll(otherDescription.updatedFields);\n }\n\n return this;\n }"
] | [
"private void gobble(Iterator iter)\n {\n if (eatTheRest)\n {\n while (iter.hasNext())\n {\n tokens.add(iter.next());\n }\n }\n }",
"public static dnsview get(nitro_service service, String viewname) throws Exception{\n\t\tdnsview obj = new dnsview();\n\t\tobj.set_viewname(viewname);\n\t\tdnsview response = (dnsview) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public void addStep(String name, String robot, Map<String, Object> options){\n steps.addStep(name, robot, options);\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 void clearAnnotationData(Class<? extends Annotation> annotationClass) {\n stereotypes.invalidate(annotationClass);\n scopes.invalidate(annotationClass);\n qualifiers.invalidate(annotationClass);\n interceptorBindings.invalidate(annotationClass);\n }",
"public final TagConfiguration.Builder configureTag( Class<? extends Annotation> tagAnnotation ) {\n TagConfiguration configuration = new TagConfiguration( tagAnnotation );\n tagConfigurations.put( tagAnnotation, configuration );\n return new TagConfiguration.Builder( configuration );\n }",
"public void handleConnectOriginal(String pathInContext, String pathParams, HttpRequest request, HttpResponse response) throws HttpException, IOException {\n URI uri = request.getURI();\n\n try {\n LOG.fine(\"CONNECT: \" + uri);\n InetAddrPort addrPort;\n // When logging, we'll attempt to send messages to hosts that don't exist\n if (uri.toString().endsWith(\".selenium.doesnotexist:443\")) {\n // so we have to do set the host to be localhost (you can't new up an IAP with a non-existent hostname)\n addrPort = new InetAddrPort(443);\n } else {\n addrPort = new InetAddrPort(uri.toString());\n }\n\n if (isForbidden(HttpMessage.__SSL_SCHEME, addrPort.getHost(), addrPort.getPort(), false)) {\n sendForbid(request, response, uri);\n } else {\n HttpConnection http_connection = request.getHttpConnection();\n http_connection.forceClose();\n\n HttpServer server = http_connection.getHttpServer();\n\n SslListener listener = getSslRelayOrCreateNewOdo(uri, addrPort, server);\n\n int port = listener.getPort();\n\n // Get the timeout\n int timeoutMs = 30000;\n Object maybesocket = http_connection.getConnection();\n if (maybesocket instanceof Socket) {\n Socket s = (Socket) maybesocket;\n timeoutMs = s.getSoTimeout();\n }\n\n // Create the tunnel\n HttpTunnel tunnel = newHttpTunnel(request, response, InetAddress.getByName(null), port, timeoutMs);\n\n if (tunnel != null) {\n // TODO - need to setup semi-busy loop for IE.\n if (_tunnelTimeoutMs > 0) {\n tunnel.getSocket().setSoTimeout(_tunnelTimeoutMs);\n if (maybesocket instanceof Socket) {\n Socket s = (Socket) maybesocket;\n s.setSoTimeout(_tunnelTimeoutMs);\n }\n }\n tunnel.setTimeoutMs(timeoutMs);\n\n customizeConnection(pathInContext, pathParams, request, tunnel.getSocket());\n request.getHttpConnection().setHttpTunnel(tunnel);\n response.setStatus(HttpResponse.__200_OK);\n response.setContentLength(0);\n }\n request.setHandled(true);\n }\n } catch (Exception e) {\n LOG.fine(\"error during handleConnect\", e);\n response.sendError(HttpResponse.__500_Internal_Server_Error, e.toString());\n }\n }",
"public static cmppolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\tcmppolicylabel obj = new cmppolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\tcmppolicylabel response = (cmppolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}",
"public void unload()\n {\n if (mAudioListener != null)\n {\n Log.d(\"SOUND\", \"unloading audio source %d %s\", getSourceId(), getSoundFile());\n mAudioListener.getAudioEngine().unloadSoundFile(getSoundFile());\n }\n mSoundFile = null;\n mSourceId = GvrAudioEngine.INVALID_ID;\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.