query
stringlengths
7
3.3k
positive
sequencelengths
1
1
negative
sequencelengths
9
9
Put everything smaller than days at 0 @param cal calendar to be cleaned
[ "private Calendar cleanHistCalendar(Calendar cal) {\n cal.set(Calendar.MILLISECOND, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.MINUTE, 0);\n cal.set(Calendar.HOUR, 0);\n return cal;\n }" ]
[ "public void warn(Throwable throwable, String msg, Object[] argArray) {\n\t\tlogIfEnabled(Level.WARNING, throwable, msg, UNKNOWN_ARG, UNKNOWN_ARG, UNKNOWN_ARG, argArray);\n\t}", "public void postLicense(final License license, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.licenseResourcePath());\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, license);\n\n client.destroy();\n if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){\n final String message = \"Failed to POST license\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }", "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 static base_responses delete(nitro_service client, String selectorname[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (selectorname != null && selectorname.length > 0) {\n\t\t\tcacheselector deleteresources[] = new cacheselector[selectorname.length];\n\t\t\tfor (int i=0;i<selectorname.length;i++){\n\t\t\t\tdeleteresources[i] = new cacheselector();\n\t\t\t\tdeleteresources[i].selectorname = selectorname[i];\n\t\t\t}\n\t\t\tresult = delete_bulk_request(client, deleteresources);\n\t\t}\n\t\treturn result;\n\t}", "private static void dumpTree(PrintWriter pw, DirectoryEntry dir, String prefix, boolean showData, boolean hex, String indent) throws Exception\n {\n long byteCount;\n\n for (Iterator<Entry> iter = dir.getEntries(); iter.hasNext();)\n {\n Entry entry = iter.next();\n if (entry instanceof DirectoryEntry)\n {\n String childIndent = indent;\n if (childIndent != null)\n {\n childIndent += \" \";\n }\n\n String childPrefix = prefix + \"[\" + entry.getName() + \"].\";\n pw.println(\"start dir: \" + prefix + entry.getName());\n dumpTree(pw, (DirectoryEntry) entry, childPrefix, showData, hex, childIndent);\n pw.println(\"end dir: \" + prefix + entry.getName());\n }\n else\n if (entry instanceof DocumentEntry)\n {\n if (showData)\n {\n pw.println(\"start doc: \" + prefix + entry.getName());\n if (hex == true)\n {\n byteCount = hexdump(new DocumentInputStream((DocumentEntry) entry), pw);\n }\n else\n {\n byteCount = asciidump(new DocumentInputStream((DocumentEntry) entry), pw);\n }\n pw.println(\"end doc: \" + prefix + entry.getName() + \" (\" + byteCount + \" bytes read)\");\n }\n else\n {\n if (indent != null)\n {\n pw.print(indent);\n }\n pw.println(\"doc: \" + prefix + entry.getName());\n }\n }\n else\n {\n pw.println(\"found unknown: \" + prefix + entry.getName());\n }\n }\n }", "private Optional<? extends SoyMsgBundle> mergeMsgBundles(final Locale locale, final List<SoyMsgBundle> soyMsgBundles) {\n if (soyMsgBundles.isEmpty()) {\n return Optional.absent();\n }\n\n final List<SoyMsg> msgs = Lists.newArrayList();\n for (final SoyMsgBundle smb : soyMsgBundles) {\n for (final Iterator<SoyMsg> it = smb.iterator(); it.hasNext();) {\n msgs.add(it.next());\n }\n }\n\n return Optional.of(new SoyMsgBundleImpl(locale.toString(), msgs));\n }", "private String escapeAndJoin(String[] commandline) {\n // TODO: we should try to escape special characters here, depending on the OS.\n StringBuilder b = new StringBuilder();\n Pattern specials = Pattern.compile(\"[\\\\ ]\");\n for (String arg : commandline) {\n if (b.length() > 0) {\n b.append(\" \");\n }\n\n if (specials.matcher(arg).find()) {\n b.append('\"').append(arg).append('\"');\n } else {\n b.append(arg);\n }\n }\n return b.toString();\n }", "public IPv6AddressSection[] mergeToSequentialBlocks(IPv6AddressSection ...sections) throws SizeMismatchException {\n\t\tList<IPAddressSegmentSeries> blocks = getMergedSequentialBlocks(this, sections, true, createSeriesCreator(getAddressCreator(), getMaxSegmentValue()));\n\t\treturn blocks.toArray(new IPv6AddressSection[blocks.size()]);\n\t}", "public static boolean respondsTo(Object object, String methodName) {\r\n MetaClass metaClass = DefaultGroovyMethods.getMetaClass(object);\r\n if (!metaClass.respondsTo(object, methodName).isEmpty()) {\r\n return true;\r\n }\r\n Map properties = DefaultGroovyMethods.getProperties(object);\r\n return properties.containsKey(methodName);\r\n }" ]
Runs a Story with the given steps factory, applying the given meta filter, and staring from given state. @param configuration the Configuration used to run story @param stepsFactory the InjectableStepsFactory used to created the candidate steps methods @param story the Story to run @param filter the Filter to apply to the story Meta @param beforeStories the State before running any of the stories, if not <code>null</code> @throws Throwable if failures occurred and FailureStrategy dictates it to be re-thrown.
[ "public void run(Configuration configuration, InjectableStepsFactory stepsFactory, Story story, MetaFilter filter,\n State beforeStories) throws Throwable {\n RunContext context = new RunContext(configuration, stepsFactory, story.getPath(), filter);\n if (beforeStories != null) {\n context.stateIs(beforeStories);\n }\n Map<String, String> storyParameters = new HashMap<>();\n run(context, story, storyParameters);\n }" ]
[ "public List<DbLicense> getModuleLicenses(final String moduleId,\n final LicenseMatcher licenseMatcher) {\n final DbModule module = getModule(moduleId);\n\n final List<DbLicense> licenses = new ArrayList<>();\n final FiltersHolder filters = new FiltersHolder();\n final ArtifactHandler artifactHandler = new ArtifactHandler(repositoryHandler, licenseMatcher);\n\n for (final String gavc : DataUtils.getAllArtifacts(module)) {\n licenses.addAll(artifactHandler.getArtifactLicenses(gavc, filters));\n }\n\n return licenses;\n }", "@RequestMapping(value = \"api/edit/disable\", method = RequestMethod.POST)\n public\n @ResponseBody\n String disableResponses(Model model, int path_id, @RequestParam(defaultValue = Constants.PROFILE_CLIENT_DEFAULT_ID) String clientUUID) throws Exception {\n OverrideService.getInstance().disableAllOverrides(path_id, clientUUID);\n //TODO also need to disable custom override if there is one of those\n editService.removeCustomOverride(path_id, clientUUID);\n\n return null;\n }", "public void forAllClassDefinitions(String template, Properties attributes) throws XDocletException\r\n {\r\n for (Iterator it = _model.getClasses(); it.hasNext(); )\r\n {\r\n _curClassDef = (ClassDescriptorDef)it.next();\r\n generate(template);\r\n }\r\n _curClassDef = null;\r\n\r\n LogHelper.debug(true, OjbTagsHandler.class, \"forAllClassDefinitions\", \"Processed \"+_model.getNumClasses()+\" types\");\r\n }", "public void setPickingEnabled(boolean enabled) {\n if (enabled != getPickingEnabled()) {\n if (enabled) {\n attachComponent(new GVRSphereCollider(getGVRContext()));\n } else {\n detachComponent(GVRCollider.getComponentType());\n }\n }\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 }", "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 String getRealm() {\n if (UNDEFINED.equals(realm)) {\n Principal principal = securityIdentity.getPrincipal();\n String realm = null;\n if (principal instanceof RealmPrincipal) {\n realm = ((RealmPrincipal)principal).getRealm();\n }\n this.realm = realm;\n\n }\n\n return this.realm;\n }", "public static float Sum(float[] data) {\r\n float sum = 0;\r\n for (int i = 0; i < data.length; i++) {\r\n sum += data[i];\r\n }\r\n return sum;\r\n }", "final public Boolean checkPositionType(String type) {\n if (tokenPosition == null) {\n return false;\n } else {\n return tokenPosition.checkType(type);\n }\n }" ]
given the groupId, returns the groupName @param groupId ID of group @return name of group
[ "public String getGroupNameFromId(int groupId) {\n return (String) sqlService.getFromTable(Constants.GROUPS_GROUP_NAME, Constants.GENERIC_ID, groupId,\n Constants.DB_TABLE_GROUPS);\n }" ]
[ "@Override\n public String logFile() {\n if(logFile == null) {\n logFile = Config.getTmpDir()+Config.getPathSeparator()+\"aesh.log\";\n }\n return logFile;\n }", "private void throwExceptionIfSafetyRestrictionsAreViolated(CmsObject cms, CmsSolrQuery query, boolean isSpell)\r\n throws CmsSearchException {\r\n\r\n if (!isDebug(cms, query)) {\r\n if (isSpell) {\r\n if (m_handlerSpellDisabled) {\r\n throw new CmsSearchException(Messages.get().container(Messages.GUI_HANDLER_REQUEST_NOT_ALLOWED_0));\r\n }\r\n } else {\r\n if (m_handlerSelectDisabled) {\r\n throw new CmsSearchException(Messages.get().container(Messages.GUI_HANDLER_REQUEST_NOT_ALLOWED_0));\r\n }\r\n int start = null != query.getStart() ? query.getStart().intValue() : 0;\r\n int rows = null != query.getRows() ? query.getRows().intValue() : CmsSolrQuery.DEFAULT_ROWS.intValue();\r\n if ((m_handlerMaxAllowedResultsAtAll >= 0) && ((rows + start) > m_handlerMaxAllowedResultsAtAll)) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_TOO_MANY_RESULTS_REQUESTED_AT_ALL_2,\r\n Integer.valueOf(m_handlerMaxAllowedResultsAtAll),\r\n Integer.valueOf(rows + start)));\r\n }\r\n if ((m_handlerMaxAllowedResultsPerPage >= 0) && (rows > m_handlerMaxAllowedResultsPerPage)) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_TOO_MANY_RESULTS_REQUESTED_PER_PAGE_2,\r\n Integer.valueOf(m_handlerMaxAllowedResultsPerPage),\r\n Integer.valueOf(rows)));\r\n }\r\n if ((null != m_handlerAllowedFields) && (Stream.of(m_handlerAllowedFields).anyMatch(x -> true))) {\r\n if (query.getFields().equals(CmsSolrQuery.ALL_RETURN_FIELDS)) {\r\n query.setFields(m_handlerAllowedFields);\r\n } else {\r\n for (String requestedField : query.getFields().split(\",\")) {\r\n if (Stream.of(m_handlerAllowedFields).noneMatch(\r\n allowedField -> allowedField.equals(requestedField))) {\r\n throw new CmsSearchException(\r\n Messages.get().container(\r\n Messages.GUI_HANDLER_REQUESTED_FIELD_NOT_ALLOWED_2,\r\n requestedField,\r\n Stream.of(m_handlerAllowedFields).reduce(\"\", (a, b) -> a + \",\" + b)));\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\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}", "public static InputStream toStream(String content, Charset charset) {\n byte[] bytes = content.getBytes(charset);\n return new ByteArrayInputStream(bytes);\n }", "protected Map<String, TermImpl> getMonolingualUpdatedValues(Map<String, NameWithUpdate> updates) {\n \tMap<String, TermImpl> updatedValues = new HashMap<>();\n \tfor(NameWithUpdate update : updates.values()) {\n if (!update.write) {\n continue;\n }\n updatedValues.put(update.value.getLanguageCode(), monolingualToJackson(update.value));\n \t}\n \treturn updatedValues;\n }", "public HttpConnection setRequestBody(final InputStream input, final long inputLength) {\n try {\n return setRequestBody(new InputStreamWrappingGenerator(input, inputLength),\n inputLength);\n } catch (IOException e) {\n logger.log(Level.SEVERE, \"Error copying input stream for request body\", e);\n throw new RuntimeException(e);\n }\n }", "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}", "public static MetadataTemplate createMetadataTemplate(BoxAPIConnection api, String scope, String templateKey,\n String displayName, boolean hidden, List<Field> fields) {\n\n JsonObject jsonObject = new JsonObject();\n jsonObject.add(\"scope\", scope);\n jsonObject.add(\"displayName\", displayName);\n jsonObject.add(\"hidden\", hidden);\n\n if (templateKey != null) {\n jsonObject.add(\"templateKey\", templateKey);\n }\n\n JsonArray fieldsArray = new JsonArray();\n if (fields != null && !fields.isEmpty()) {\n for (Field field : fields) {\n JsonObject fieldObj = getFieldJsonObject(field);\n\n fieldsArray.add(fieldObj);\n }\n\n jsonObject.add(\"fields\", fieldsArray);\n }\n\n URL url = METADATA_TEMPLATE_SCHEMA_URL_TEMPLATE.build(api.getBaseURL());\n BoxJSONRequest request = new BoxJSONRequest(api, url, \"POST\");\n request.setBody(jsonObject.toString());\n\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n\n return new MetadataTemplate(responseJSON);\n }", "protected void printFeatures(IN wi, Collection<String> features) {\r\n if (flags.printFeatures == null || writtenNum > flags.printFeaturesUpto) {\r\n return;\r\n }\r\n try {\r\n if (cliqueWriter == null) {\r\n cliqueWriter = new PrintWriter(new FileOutputStream(\"feats\" + flags.printFeatures + \".txt\"), true);\r\n writtenNum = 0;\r\n }\r\n } catch (Exception ioe) {\r\n throw new RuntimeException(ioe);\r\n }\r\n if (writtenNum >= flags.printFeaturesUpto) {\r\n return;\r\n }\r\n if (wi instanceof CoreLabel) {\r\n cliqueWriter.print(wi.get(TextAnnotation.class) + ' ' + wi.get(PartOfSpeechAnnotation.class) + ' '\r\n + wi.get(CoreAnnotations.GoldAnswerAnnotation.class) + '\\t');\r\n } else {\r\n cliqueWriter.print(wi.get(CoreAnnotations.TextAnnotation.class)\r\n + wi.get(CoreAnnotations.GoldAnswerAnnotation.class) + '\\t');\r\n }\r\n boolean first = true;\r\n for (Object feat : features) {\r\n if (first) {\r\n first = false;\r\n } else {\r\n cliqueWriter.print(\" \");\r\n }\r\n cliqueWriter.print(feat);\r\n }\r\n cliqueWriter.println();\r\n writtenNum++;\r\n }" ]
Clear JobContext of current thread
[ "public static void clear() {\n JobContext ctx = current_.get();\n if (null != ctx) {\n ctx.bag_.clear();\n JobContext parent = ctx.parent;\n if (null != parent) {\n current_.set(parent);\n ctx.parent = null;\n } else {\n current_.remove();\n Act.eventBus().trigger(new JobContextDestroyed(ctx));\n }\n }\n }" ]
[ "public int compare(Vector3 o1, Vector3 o2) {\n\t\tint ans = 0;\n\n\t\tif (o1 != null && o2 != null) {\n\t\t\tVector3 d1 = o1;\n\t\t\tVector3 d2 = o2;\n\n\t\t\tif (d1.x > d2.x)\n\t\t\t\treturn 1;\n\t\t\tif (d1.x < d2.x)\n\t\t\t\treturn -1;\n\t\t\t// x1 == x2\n\t\t\tif (d1.y > d2.y)\n\t\t\t\treturn 1;\n\t\t\tif (d1.y < d2.y)\n\t\t\t\treturn -1;\n\t\t} else {\n\t\t\tif (o1 == null && o2 == null)\n\t\t\t\treturn 0;\n\t\t\tif (o1 == null && o2 != null)\n\t\t\t\treturn 1;\n\t\t\tif (o1 != null && o2 == null)\n\t\t\t\treturn -1;\n\t\t}\n\t\t\n\t\treturn ans;\n\t}", "public LuaScriptBlock endBlockReturn(LuaValue value) {\n add(new LuaAstReturnStatement(argument(value)));\n return new LuaScriptBlock(script);\n }", "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}", "public static Operation createDeployOperation(final Set<DeploymentDescription> deployments) {\n Assertions.requiresNotNullOrNotEmptyParameter(\"deployments\", deployments);\n final CompositeOperationBuilder builder = CompositeOperationBuilder.create(true);\n for (DeploymentDescription deployment : deployments) {\n addDeployOperationStep(builder, deployment);\n }\n return builder.build();\n }", "public void setCapacity(int capacity) {\n if (capacity <= 0) {\n throw new IllegalArgumentException(\"capacity must be greater than 0\");\n }\n\n synchronized (queue) {\n // If the capacity was reduced, we remove oldest elements until the\n // queue fits inside the specified capacity\n if (capacity < this.capacity) {\n while (queue.size() > capacity) {\n queue.removeFirst();\n }\n }\n }\n\n this.capacity = capacity;\n }", "public static List<Integer> checkKeyBelongsToPartition(byte[] key,\n Set<Pair<Integer, HashMap<Integer, List<Integer>>>> stealerNodeToMappingTuples,\n Cluster cluster,\n StoreDefinition storeDef) {\n List<Integer> keyPartitions = new RoutingStrategyFactory().updateRoutingStrategy(storeDef,\n cluster)\n .getPartitionList(key);\n List<Integer> nodesToPush = Lists.newArrayList();\n for(Pair<Integer, HashMap<Integer, List<Integer>>> stealNodeToMap: stealerNodeToMappingTuples) {\n List<Integer> nodePartitions = cluster.getNodeById(stealNodeToMap.getFirst())\n .getPartitionIds();\n if(StoreRoutingPlan.checkKeyBelongsToPartition(keyPartitions,\n nodePartitions,\n stealNodeToMap.getSecond())) {\n nodesToPush.add(stealNodeToMap.getFirst());\n }\n }\n return nodesToPush;\n }", "private void addGroups(MpxjTreeNode parentNode, ProjectFile file)\n {\n for (Group group : file.getGroups())\n {\n final Group g = group;\n MpxjTreeNode childNode = new MpxjTreeNode(group)\n {\n @Override public String toString()\n {\n return g.getName();\n }\n };\n parentNode.add(childNode);\n }\n }", "public static List<Object> filterMapToList(final Map<String, ?> map, final String[] nameMapping) {\n\t\tif( map == null ) {\n\t\t\tthrow new NullPointerException(\"map should not be null\");\n\t\t} else if( nameMapping == null ) {\n\t\t\tthrow new NullPointerException(\"nameMapping should not be null\");\n\t\t}\n\t\t\n\t\tfinal List<Object> result = new ArrayList<Object>(nameMapping.length);\n\t\tfor( final String key : nameMapping ) {\n\t\t\tresult.add(map.get(key));\n\t\t}\n\t\treturn result;\n\t}", "public static <T> T notNull(T argument, String argumentName) {\n if (argument == null) {\n throw new IllegalArgumentException(\"Argument \" + argumentName + \" must not be null.\");\n }\n return argument;\n }" ]
Escape text to ensure valid JSON. @param value value @return escaped value
[ "private String escapeString(String value)\n {\n m_buffer.setLength(0);\n m_buffer.append('\"');\n for (int index = 0; index < value.length(); index++)\n {\n char c = value.charAt(index);\n switch (c)\n {\n case '\"':\n {\n m_buffer.append(\"\\\\\\\"\");\n break;\n }\n\n case '\\\\':\n {\n m_buffer.append(\"\\\\\\\\\");\n break;\n }\n\n case '/':\n {\n m_buffer.append(\"\\\\/\");\n break;\n }\n\n case '\\b':\n {\n m_buffer.append(\"\\\\b\");\n break;\n }\n\n case '\\f':\n {\n m_buffer.append(\"\\\\f\");\n break;\n }\n\n case '\\n':\n {\n m_buffer.append(\"\\\\n\");\n break;\n }\n\n case '\\r':\n {\n m_buffer.append(\"\\\\r\");\n break;\n }\n\n case '\\t':\n {\n m_buffer.append(\"\\\\t\");\n break;\n }\n\n default:\n {\n // Append if it's not a control character (0x00 to 0x1f)\n if (c > 0x1f)\n {\n m_buffer.append(c);\n }\n break;\n }\n }\n }\n m_buffer.append('\"');\n return m_buffer.toString();\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 boolean isIPv4Compatible() {\n\t\treturn getSegment(0).isZero() && getSegment(1).isZero() && getSegment(2).isZero() &&\n\t\t\t\tgetSegment(3).isZero() && getSegment(4).isZero() && getSegment(5).isZero();\n\t}", "public WindupConfiguration setOptionValue(String name, Object value)\n {\n configurationOptions.put(name, value);\n return this;\n }", "public void rollback() throws GitAPIException {\n try (Git git = getGit()) {\n git.reset().setMode(ResetCommand.ResetType.HARD).setRef(HEAD).call();\n }\n }", "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 void handleRequestNodeInfoResponse(SerialMessage incomingMessage) {\n\t\tlogger.trace(\"Handle RequestNodeInfo Response\");\n\t\tif(incomingMessage.getMessageBuffer()[2] != 0x00)\n\t\t\tlogger.debug(\"Request node info successfully placed on stack.\");\n\t\telse\n\t\t\tlogger.error(\"Request node info not placed on stack due to error.\");\n\t}", "public Set<String> rangeByLexReverse(final LexRange lexRange) {\n return doWithJedis(new JedisCallable<Set<String>>() {\n @Override\n public Set<String> call(Jedis jedis) {\n if (lexRange.hasLimit()) {\n return jedis.zrevrangeByLex(getKey(), lexRange.fromReverse(), lexRange.toReverse(), lexRange.offset(), lexRange.count());\n } else {\n return jedis.zrevrangeByLex(getKey(), lexRange.fromReverse(), lexRange.toReverse());\n }\n }\n });\n }", "public static aaagroup_vpnsessionpolicy_binding[] get(nitro_service service, String groupname) throws Exception{\n\t\taaagroup_vpnsessionpolicy_binding obj = new aaagroup_vpnsessionpolicy_binding();\n\t\tobj.set_groupname(groupname);\n\t\taaagroup_vpnsessionpolicy_binding response[] = (aaagroup_vpnsessionpolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static void reset() {\n for (Object name : Collections.list(MAP_KEY_TO_SCOPE.keys())) {\n closeScope(name);\n }\n ConfigurationHolder.configuration.onScopeForestReset();\n ScopeImpl.resetUnBoundProviders();\n }" ]
Set an attribute. @param name attribute name. @param value attribute value.
[ "public void set(String name, Object value) {\n hashAttributes.put(name, value);\n\n if (plugin != null) {\n plugin.invalidate();\n }\n }" ]
[ "public static String determineFieldName(@Nonnull final String methodName) {\n\t\tCheck.notEmpty(methodName, \"methodName\");\n\t\tfinal Matcher m = PATTERN.matcher(methodName);\n\t\tCheck.stateIsTrue(m.find(), \"passed method name '%s' is not applicable\", methodName);\n\t\treturn m.group(2).substring(0, 1).toLowerCase() + m.group(2).substring(1);\n\t}", "public String objectToString(T object) {\n\t\tStringBuilder sb = new StringBuilder(64);\n\t\tsb.append(object.getClass().getSimpleName());\n\t\tfor (FieldType fieldType : fieldTypes) {\n\t\t\tsb.append(' ').append(fieldType.getColumnName()).append('=');\n\t\t\ttry {\n\t\t\t\tsb.append(fieldType.extractJavaFieldValue(object));\n\t\t\t} catch (Exception e) {\n\t\t\t\tthrow new IllegalStateException(\"Could not generate toString of field \" + fieldType, e);\n\t\t\t}\n\t\t}\n\t\treturn sb.toString();\n\t}", "public static final String getSelectedValue(ListBox list) {\n\tint index = list.getSelectedIndex();\n\treturn (index >= 0) ? list.getValue(index) : null;\n }", "public void setGroupName(String name, int id) {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_SERVER_GROUPS +\n \" SET \" + Constants.GENERIC_NAME + \" = ?\" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, name);\n statement.setInt(2, id);\n statement.executeUpdate();\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 }", "private void writeAllEnvelopes(boolean reuse)\r\n {\r\n // perform remove of m:n indirection table entries first\r\n performM2NUnlinkEntries();\r\n\r\n Iterator iter;\r\n // using clone to avoid ConcurentModificationException\r\n iter = ((List) mvOrderOfIds.clone()).iterator();\r\n while(iter.hasNext())\r\n {\r\n ObjectEnvelope mod = (ObjectEnvelope) mhtObjectEnvelopes.get(iter.next());\r\n boolean insert = false;\r\n if(needsCommit)\r\n {\r\n insert = mod.needsInsert();\r\n mod.getModificationState().commit(mod);\r\n if(reuse && insert)\r\n {\r\n getTransaction().doSingleLock(mod.getClassDescriptor(), mod.getObject(), mod.getIdentity(), Transaction.WRITE);\r\n }\r\n }\r\n /*\r\n arminw: important to call this cleanup method for each registered\r\n ObjectEnvelope, because this method will e.g. remove proxy listener\r\n objects for registered objects.\r\n */\r\n mod.cleanup(reuse, insert);\r\n }\r\n // add m:n indirection table entries\r\n performM2NLinkEntries();\r\n }", "protected LogContext getOrCreate(final String loggingProfile) {\n LogContext result = profileContexts.get(loggingProfile);\n if (result == null) {\n result = LogContext.create();\n final LogContext current = profileContexts.putIfAbsent(loggingProfile, result);\n if (current != null) {\n result = current;\n }\n }\n return result;\n }", "public static base_response unlink(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey unlinkresource = new sslcertkey();\n\t\tunlinkresource.certkey = resource.certkey;\n\t\treturn unlinkresource.perform_operation(client,\"unlink\");\n\t}", "public ExecutorLoadBalancingConfig<GROUP> useLoadBalancedEnumOrdinalPrioritizer(Class<GROUP> groupClass) {\n if(!groupClass.isEnum()) {\n throw new IllegalArgumentException(\"The group class \"+groupClass+\" is not an enum\");\n }\n groupPrioritizer = new LoadBalancedPriorityPrioritizer<GROUP>(new EnumOrdinalPrioritizer<GROUP>());\n return this;\n }", "public static sslpolicy_lbvserver_binding[] get(nitro_service service, String name) throws Exception{\n\t\tsslpolicy_lbvserver_binding obj = new sslpolicy_lbvserver_binding();\n\t\tobj.set_name(name);\n\t\tsslpolicy_lbvserver_binding response[] = (sslpolicy_lbvserver_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
blocks until there is a connection
[ "public void checkConnection() {\n long start = Time.currentTimeMillis();\n\n while (clientChannel == null) {\n\n tcpSocketConsumer.checkNotShutdown();\n\n if (start + timeoutMs > Time.currentTimeMillis())\n try {\n condition.await(1, TimeUnit.MILLISECONDS);\n\n } catch (InterruptedException e) {\n throw new IORuntimeException(\"Interrupted\");\n }\n else\n throw new IORuntimeException(\"Not connected to \" + socketAddressSupplier);\n }\n\n if (clientChannel == null)\n throw new IORuntimeException(\"Not connected to \" + socketAddressSupplier);\n }" ]
[ "public void useNewSOAPServiceWithOldClientAndRedirection() throws Exception {\n URL wsdlURL = getClass().getResource(\"/CustomerService.wsdl\");\n com.example.customerservice.CustomerServiceService service = \n new com.example.customerservice.CustomerServiceService(wsdlURL);\n \n com.example.customerservice.CustomerService customerService = \n service.getCustomerServiceRedirectPort();\n\n System.out.println(\"Using new SOAP CustomerService with old client and the redirection\");\n \n customer.v1.Customer customer = createOldCustomer(\"Barry Old to New SOAP With Redirection\");\n customerService.updateCustomer(customer);\n customer = customerService.getCustomerByName(\"Barry Old to New SOAP With Redirection\");\n printOldCustomerDetails(customer);\n }", "private void setSearchScopeFilter(CmsObject cms) {\n\n final List<String> searchRoots = CmsSearchUtil.computeScopeFolders(cms, this);\n\n // If the resource types contain the type \"function\" also\n // add \"/system/modules/\" to the search path\n\n if ((null != getResourceTypes()) && containsFunctionType(getResourceTypes())) {\n searchRoots.add(\"/system/modules/\");\n }\n\n addFoldersToSearchIn(searchRoots);\n }", "@Override\n public void accept(ISourceType[] sourceTypes, PackageBinding packageBinding, AccessRestriction accessRestriction) {\n this.problemReporter.abortDueToInternalError(\n Messages.bind(Messages.abort_againstSourceModel, new String[] { String.valueOf(sourceTypes[0].getName()), String.valueOf(sourceTypes[0].getFileName()) }));\n }", "static void initSingleParam(String key, String initValue, DbConn cnx)\n {\n try\n {\n cnx.runSelectSingle(\"globalprm_select_by_key\", 2, String.class, key);\n return;\n }\n catch (NoResultException e)\n {\n GlobalParameter.create(cnx, key, initValue);\n }\n catch (NonUniqueResultException e)\n {\n // It exists! Nothing to do...\n }\n }", "public String getNamefromId(int id) {\n return (String) sqlService.getFromTable(\n Constants.PROFILE_PROFILE_NAME, Constants.GENERIC_ID,\n id, Constants.DB_TABLE_PROFILE);\n }", "private String appendXmlEndingTag(String value) {\r\n StringBuilder sb = new StringBuilder();\r\n sb.append(\"</\").append(value).append(\">\");\n\r\n return sb.toString();\r\n }", "public static void initializeDomainRegistry(final TransformerRegistry registry) {\n\n //The chains for transforming will be as follows\n //For JBoss EAP: 8.0.0 -> 5.0.0 -> 4.0.0 -> 1.8.0 -> 1.7.0 -> 1.6.0 -> 1.5.0\n\n registerRootTransformers(registry);\n registerChainedManagementTransformers(registry);\n registerChainedServerGroupTransformers(registry);\n registerProfileTransformers(registry);\n registerSocketBindingGroupTransformers(registry);\n registerDeploymentTransformers(registry);\n }", "protected void handleExceptions(MessageEvent messageEvent, Exception exception) {\n logger.error(\"Unknown exception. Internal Server Error.\", exception);\n writeErrorResponse(messageEvent,\n HttpResponseStatus.INTERNAL_SERVER_ERROR,\n \"Internal Server Error\");\n }", "public Bitmap drawableToBitmap(Drawable drawable) {\n\t\tif (drawable == null) // Don't do anything without a proper drawable\n\t\t\treturn null;\n\t\telse if (drawable instanceof BitmapDrawable) { // Use the getBitmap() method instead if BitmapDrawable\n\t\t\tLog.i(TAG, \"Bitmap drawable!\");\n\t\t\treturn ((BitmapDrawable) drawable).getBitmap();\n\t\t}\n\n\t\tint intrinsicWidth = drawable.getIntrinsicWidth();\n\t\tint intrinsicHeight = drawable.getIntrinsicHeight();\n\n\t\tif (!(intrinsicWidth > 0 && intrinsicHeight > 0))\n\t\t\treturn null;\n\n\t\ttry {\n\t\t\t// Create Bitmap object out of the drawable\n\t\t\tBitmap bitmap = Bitmap.createBitmap(intrinsicWidth, intrinsicHeight, Bitmap.Config.ARGB_8888);\n\t\t\tCanvas canvas = new Canvas(bitmap);\n\t\t\tdrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());\n\t\t\tdrawable.draw(canvas);\n\t\t\treturn bitmap;\n\t\t} catch (OutOfMemoryError e) {\n\t\t\t// Simply return null of failed bitmap creations\n\t\t\tLog.e(TAG, \"Encountered OutOfMemoryError while generating bitmap!\");\n\t\t\treturn null;\n\t\t}\n\t}" ]
Handles the response of the SendData request. @param incomingMessage the response message to process.
[ "private void handleSendDataResponse(SerialMessage incomingMessage) {\n\t\tlogger.trace(\"Handle Message Send Data Response\");\n\t\tif(incomingMessage.getMessageBuffer()[2] != 0x00)\n\t\t\tlogger.debug(\"Sent Data successfully placed on stack.\");\n\t\telse\n\t\t\tlogger.error(\"Sent Data was not placed on stack due to error.\");\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 }", "private BigInteger getTaskCalendarID(Task mpx)\n {\n BigInteger result = null;\n ProjectCalendar cal = mpx.getCalendar();\n if (cal != null)\n {\n result = NumberHelper.getBigInteger(cal.getUniqueID());\n }\n else\n {\n result = NULL_CALENDAR_ID;\n }\n return (result);\n }", "public static final String removeAmpersands(String name)\n {\n if (name != null)\n {\n if (name.indexOf('&') != -1)\n {\n StringBuilder sb = new StringBuilder();\n int index = 0;\n char c;\n\n while (index < name.length())\n {\n c = name.charAt(index);\n if (c != '&')\n {\n sb.append(c);\n }\n ++index;\n }\n\n name = sb.toString();\n }\n }\n\n return (name);\n }", "public static Document removeTags(Document dom, String tagName) {\n NodeList list;\n try {\n list = XPathHelper.evaluateXpathExpression(dom,\n \"//\" + tagName.toUpperCase());\n\n while (list.getLength() > 0) {\n Node sc = list.item(0);\n\n if (sc != null) {\n sc.getParentNode().removeChild(sc);\n }\n\n list = XPathHelper.evaluateXpathExpression(dom,\n \"//\" + tagName.toUpperCase());\n }\n } catch (XPathExpressionException e) {\n LOGGER.error(\"Error while removing tag \" + tagName, e);\n }\n\n return dom;\n\n }", "public void contextInitialized(ServletContextEvent event) {\n this.context = event.getServletContext();\n\n // Output a simple message to the server's console\n System.out.println(\"The Simple Web App. Is Ready\");\n\n ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(\n \"/client.xml\");\n LocatorService client = (LocatorService) context\n .getBean(\"locatorService\");\n\n String serviceHost = this.context.getInitParameter(\"serviceHost\");\n\n try {\n client.registerEndpoint(new QName(\n \"http://talend.org/esb/examples/\", \"GreeterService\"),\n serviceHost, BindingType.SOAP_11, TransportType.HTTP, null);\n } catch (InterruptedExceptionFault e) {\n e.printStackTrace();\n } catch (ServiceLocatorFault e) {\n e.printStackTrace();\n }\n }", "public static String padOrTrim(String str, int num) {\r\n if (str == null) {\r\n str = \"null\";\r\n }\r\n int leng = str.length();\r\n if (leng < num) {\r\n StringBuilder sb = new StringBuilder(str);\r\n for (int i = 0; i < num - leng; i++) {\r\n sb.append(' ');\r\n }\r\n return sb.toString();\r\n } else if (leng > num) {\r\n return str.substring(0, num);\r\n } else {\r\n return str;\r\n }\r\n }", "public static void acceptsFile(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_F, OPT_FILE), \"file path for input/output\")\n .withRequiredArg()\n .describedAs(\"file-path\")\n .ofType(String.class);\n }", "protected static File platformIndependentUriToFile(final URI fileURI) {\n File file;\n try {\n file = new File(fileURI);\n } catch (IllegalArgumentException e) {\n if (fileURI.toString().startsWith(\"file://\")) {\n file = new File(fileURI.toString().substring(\"file://\".length()));\n } else {\n throw e;\n }\n }\n return file;\n }", "protected List<String> extractWords() throws IOException\n {\n while( true ) {\n lineNumber++;\n String line = in.readLine();\n if( line == null ) {\n return null;\n }\n\n // skip comment lines\n if( hasComment ) {\n if( line.charAt(0) == comment )\n continue;\n }\n\n // extract the words, which are the variables encoded\n return parseWords(line);\n }\n }" ]
Deletes this BoxStoragePolicyAssignment.
[ "public void delete() {\n URL url = STORAGE_POLICY_ASSIGNMENT_WITH_ID_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, HttpMethod.DELETE);\n\n request.send();\n }" ]
[ "private ProjectFile readTextFile(InputStream inputStream) throws MPXJException\n {\n ProjectReader reader = new AstaTextFileReader();\n addListeners(reader);\n return reader.read(inputStream);\n }", "protected void updateFontTable()\n {\n PDResources resources = pdpage.getResources();\n if (resources != null)\n {\n try\n {\n processFontResources(resources, fontTable);\n } catch (IOException e) {\n log.error(\"Error processing font resources: \"\n + \"Exception: {} {}\", e.getMessage(), e.getClass());\n }\n }\n }", "private ProjectFile handleDatabaseInDirectory(File directory) throws Exception\n {\n byte[] buffer = new byte[BUFFER_SIZE];\n File[] files = directory.listFiles();\n if (files != null)\n {\n for (File file : files)\n {\n if (file.isDirectory())\n {\n continue;\n }\n\n FileInputStream fis = new FileInputStream(file);\n int bytesRead = fis.read(buffer);\n fis.close();\n\n //\n // If the file is smaller than the buffer we are peeking into,\n // it's probably not a valid schedule file.\n //\n if (bytesRead != BUFFER_SIZE)\n {\n continue;\n }\n\n if (matchesFingerprint(buffer, BTRIEVE_FINGERPRINT))\n {\n return handleP3BtrieveDatabase(directory);\n }\n\n if (matchesFingerprint(buffer, STW_FINGERPRINT))\n {\n return handleSureTrakDatabase(directory);\n }\n }\n }\n return null;\n }", "public static policydataset_value_binding[] get(nitro_service service, String name) throws Exception{\n\t\tpolicydataset_value_binding obj = new policydataset_value_binding();\n\t\tobj.set_name(name);\n\t\tpolicydataset_value_binding response[] = (policydataset_value_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "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 static <ObjType, Hashable> Collection<ObjType> uniqueNonhashableObjects(Collection<ObjType> objects, Function<ObjType, Hashable> customHasher) {\r\n Map<Hashable, ObjType> hashesToObjects = new HashMap<Hashable, ObjType>();\r\n for (ObjType object : objects) {\r\n hashesToObjects.put(customHasher.apply(object), object);\r\n }\r\n return hashesToObjects.values();\r\n }", "void insertMacros(TokenList tokens ) {\n TokenList.Token t = tokens.getFirst();\n while( t != null ) {\n if( t.getType() == Type.WORD ) {\n Macro v = lookupMacro(t.word);\n if (v != null) {\n TokenList.Token before = t.previous;\n List<TokenList.Token> inputs = new ArrayList<TokenList.Token>();\n t = parseMacroInput(inputs,t.next);\n\n TokenList sniplet = v.execute(inputs);\n tokens.extractSubList(before.next,t);\n tokens.insertAfter(before,sniplet);\n t = sniplet.last;\n }\n }\n t = t.next;\n }\n }", "public void revertWorkingCopy() throws IOException, InterruptedException {\n build.getWorkspace()\n .act(new RevertWorkingCopyCallable(getLocation(), getSvnAuthenticationProvider(build), buildListener));\n }", "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 }" ]
If needed, destroy the remaining conversation contexts after an HTTP session was invalidated within the current request. @param request
[ "private void processDestructionQueue(HttpServletRequest request) {\n Object contextsAttribute = request.getAttribute(DESTRUCTION_QUEUE_ATTRIBUTE_NAME);\n if (contextsAttribute instanceof Map) {\n Map<String, List<ContextualInstance<?>>> contexts = cast(contextsAttribute);\n synchronized (contexts) {\n FastEvent<String> beforeDestroyedEvent = FastEvent.of(String.class, beanManager, BeforeDestroyed.Literal.CONVERSATION);\n FastEvent<String> destroyedEvent = FastEvent.of(String.class, beanManager, Destroyed.Literal.CONVERSATION);\n for (Iterator<Entry<String, List<ContextualInstance<?>>>> iterator = contexts.entrySet().iterator(); iterator.hasNext();) {\n Entry<String, List<ContextualInstance<?>>> entry = iterator.next();\n beforeDestroyedEvent.fire(entry.getKey());\n for (ContextualInstance<?> contextualInstance : entry.getValue()) {\n destroyContextualInstance(contextualInstance);\n }\n // Note that for the attached/current conversation we fire the destroyed event twice because we can't reliably identify such a conversation\n destroyedEvent.fire(entry.getKey());\n iterator.remove();\n }\n }\n }\n }" ]
[ "public void setGamma(float rGamma, float gGamma, float bGamma) {\n\t\tthis.rGamma = rGamma;\n\t\tthis.gGamma = gGamma;\n\t\tthis.bGamma = bGamma;\n\t\tinitialized = false;\n\t}", "public static base_response unset(nitro_service client, protocolhttpband resource, String[] args) throws Exception{\n\t\tprotocolhttpband unsetresource = new protocolhttpband();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public static final String printExtendedAttributeDate(Date value)\n {\n return (value == null ? null : DATE_FORMAT.get().format(value));\n }", "protected void checkVariableName(GraphRewrite event, EvaluationContext context)\n {\n if (variableName == null)\n {\n setVariableName(Iteration.getPayloadVariableName(event, context));\n }\n }", "public static Button createPublishButton(final I_CmsUpdateListener<String> updateListener) {\n\n Button publishButton = CmsToolBar.createButton(\n FontOpenCms.PUBLISH,\n CmsVaadinUtils.getMessageText(Messages.GUI_PUBLISH_BUTTON_TITLE_0));\n if (CmsAppWorkplaceUi.isOnlineProject()) {\n // disable publishing in online project\n publishButton.setEnabled(false);\n publishButton.setDescription(CmsVaadinUtils.getMessageText(Messages.GUI_TOOLBAR_NOT_AVAILABLE_ONLINE_0));\n }\n publishButton.addClickListener(new ClickListener() {\n\n /** Serial version id. */\n private static final long serialVersionUID = 1L;\n\n public void buttonClick(ClickEvent event) {\n\n CmsAppWorkplaceUi.get().disableGlobalShortcuts();\n CmsGwtDialogExtension extension = new CmsGwtDialogExtension(A_CmsUI.get(), updateListener);\n extension.openPublishDialog();\n }\n });\n return publishButton;\n }", "public void printInterceptorChain(InterceptorChain chain) {\n Iterator<Interceptor<? extends Message>> it = chain.iterator();\n String phase = \"\";\n StringBuilder builder = null;\n while (it.hasNext()) {\n Interceptor<? extends Message> interceptor = it.next();\n if (interceptor instanceof DemoInterceptor) {\n continue;\n }\n if (interceptor instanceof PhaseInterceptor) {\n PhaseInterceptor pi = (PhaseInterceptor)interceptor;\n if (!phase.equals(pi.getPhase())) {\n if (builder != null) {\n System.out.println(builder.toString());\n } else {\n builder = new StringBuilder(100);\n }\n builder.setLength(0);\n builder.append(\" \");\n builder.append(pi.getPhase());\n builder.append(\": \");\n phase = pi.getPhase();\n }\n String id = pi.getId();\n int idx = id.lastIndexOf('.');\n if (idx != -1) {\n id = id.substring(idx + 1);\n }\n builder.append(id);\n builder.append(' ');\n }\n }\n\n }", "public void setT(int t) {\r\n this.t = Math.min((radius * 2 + 1) * (radius * 2 + 1) / 2, Math.max(0, t));\r\n }", "@Override\n public DMatrixRMaj getU(DMatrixRMaj U , boolean transpose , boolean compact ) {\n U = handleU(U, transpose, compact,m,n,min);\n CommonOps_DDRM.setIdentity(U);\n\n for( int i = 0; i < m; i++ ) u[i] = 0;\n\n for( int j = min-1; j >= 0; j-- ) {\n u[j] = 1;\n for( int i = j+1; i < m; i++ ) {\n u[i] = UBV.get(i,j);\n }\n if( transpose )\n QrHelperFunctions_DDRM.rank1UpdateMultL(U, u, gammasU[j], j, j, m);\n else\n QrHelperFunctions_DDRM.rank1UpdateMultR(U, u, gammasU[j], j, j, m, this.b);\n }\n\n return U;\n }", "public boolean evaluate(Object feature) {\n\t\t// Checks to ensure that the attribute has been set\n\t\tif (attribute == null) {\n\t\t\treturn false;\n\t\t}\n\t\t// Note that this converts the attribute to a string\n\t\t// for comparison. Unlike the math or geometry filters, which\n\t\t// require specific types to function correctly, this filter\n\t\t// using the mandatory string representation in Java\n\t\t// Of course, this does not guarantee a meaningful result, but it\n\t\t// does guarantee a valid result.\n\t\t// LOGGER.finest(\"pattern: \" + pattern);\n\t\t// LOGGER.finest(\"string: \" + attribute.getValue(feature));\n\t\t// return attribute.getValue(feature).toString().matches(pattern);\n\t\tObject value = attribute.evaluate(feature);\n\n\t\tif (null == value) {\n\t\t\treturn false;\n\t\t}\n\n\t\tMatcher matcher = getMatcher();\n\t\tmatcher.reset(value.toString());\n\n\t\treturn matcher.matches();\n\t}" ]
Makes a CRFDatum by producing features and a label from input data at a specific position, using the provided factory. @param info The input data @param loc The position to build a datum at @param featureFactory The FeatureFactory to use to extract features @return The constructed CRFDatum
[ "public CRFDatum<List<String>, CRFLabel> makeDatum(List<IN> info, int loc,\r\n edu.stanford.nlp.sequences.FeatureFactory<IN> featureFactory) {\r\n pad.set(AnswerAnnotation.class, flags.backgroundSymbol);\r\n PaddedList<IN> pInfo = new PaddedList<IN>(info, pad);\r\n\r\n ArrayList<List<String>> features = new ArrayList<List<String>>();\r\n\r\n // for (int i = 0; i < windowSize; i++) {\r\n // List featuresC = new ArrayList();\r\n // for (int j = 0; j < FeatureFactory.win[i].length; j++) {\r\n // featuresC.addAll(featureFactory.features(info, loc,\r\n // FeatureFactory.win[i][j]));\r\n // }\r\n // features.add(featuresC);\r\n // }\r\n\r\n Collection<Clique> done = new HashSet<Clique>();\r\n for (int i = 0; i < windowSize; i++) {\r\n List<String> featuresC = new ArrayList<String>();\r\n List<Clique> windowCliques = FeatureFactory.getCliques(i, 0);\r\n windowCliques.removeAll(done);\r\n done.addAll(windowCliques);\r\n for (Clique c : windowCliques) {\r\n featuresC.addAll(featureFactory.getCliqueFeatures(pInfo, loc, c)); //todo useless copy because of typing reasons\r\n }\r\n features.add(featuresC);\r\n }\r\n\r\n int[] labels = new int[windowSize];\r\n\r\n for (int i = 0; i < windowSize; i++) {\r\n String answer = pInfo.get(loc + i - windowSize + 1).get(AnswerAnnotation.class);\r\n labels[i] = classIndex.indexOf(answer);\r\n }\r\n\r\n printFeatureLists(pInfo.get(loc), features);\r\n\r\n CRFDatum<List<String>, CRFLabel> d = new CRFDatum<List<String>, CRFLabel>(features, new CRFLabel(labels));\r\n // System.err.println(d);\r\n return d;\r\n }" ]
[ "public static void waitForDomain(final ModelControllerClient client, final long startupTimeout)\n throws InterruptedException, RuntimeException, TimeoutException {\n waitForDomain(null, client, startupTimeout);\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 }", "protected StreamRequestHandlerState determineRequestHandlerState(String itemTag) {\n\n if (keyIterator.hasNext() && !fetchedEnoughForAllPartitions()) {\n return StreamRequestHandlerState.WRITING;\n } else {\n logger.info(\"Finished fetch \" + itemTag + \" for store '\" + storageEngine.getName()\n + \"' with partitions \" + partitionIds);\n progressInfoMessage(\"Fetch \" + itemTag + \" (end of scan)\");\n\n return StreamRequestHandlerState.COMPLETE;\n }\n }", "protected void parseRequest(HttpServletRequest request,\n HttpServletResponse response) {\n requestParams = new HashMap<String, Object>();\n listFiles = new ArrayList<FileItemStream>();\n listFileStreams = new ArrayList<ByteArrayOutputStream>();\n\n // Parse the request\n if (ServletFileUpload.isMultipartContent(request)) {\n // multipart request\n try {\n ServletFileUpload upload = new ServletFileUpload();\n FileItemIterator iter = upload.getItemIterator(request);\n while (iter.hasNext()) {\n FileItemStream item = iter.next();\n String name = item.getFieldName();\n InputStream stream = item.openStream();\n if (item.isFormField()) {\n requestParams.put(name,\n Streams.asString(stream));\n } else {\n String fileName = item.getName();\n if (fileName != null && !\"\".equals(fileName.trim())) {\n listFiles.add(item);\n\n ByteArrayOutputStream os = new ByteArrayOutputStream();\n IOUtils.copy(stream,\n os);\n listFileStreams.add(os);\n }\n }\n }\n } catch (Exception e) {\n logger.error(\"Unexpected error parsing multipart content\",\n e);\n }\n } else {\n // not a multipart\n for (Object mapKey : request.getParameterMap().keySet()) {\n String mapKeyString = (String) mapKey;\n\n if (mapKeyString.endsWith(\"[]\")) {\n // multiple values\n String values[] = request.getParameterValues(mapKeyString);\n List<String> listeValues = new ArrayList<String>();\n for (String value : values) {\n listeValues.add(value);\n }\n requestParams.put(mapKeyString,\n listeValues);\n } else {\n // single value\n String value = request.getParameter(mapKeyString);\n requestParams.put(mapKeyString,\n value);\n }\n }\n }\n }", "protected void afterMaterialization()\r\n\t{\r\n\t\tif (_listeners != null)\r\n\t\t{\r\n\t\t\tMaterializationListener listener;\r\n\r\n\t\t\t// listeners may remove themselves during the afterMaterialization\r\n\t\t\t// callback.\r\n\t\t\t// thus we must iterate through the listeners vector from back to\r\n\t\t\t// front\r\n\t\t\t// to avoid index problems.\r\n\t\t\tfor (int idx = _listeners.size() - 1; idx >= 0; idx--)\r\n\t\t\t{\r\n\t\t\t\tlistener = (MaterializationListener) _listeners.get(idx);\r\n\t\t\t\tlistener.afterMaterialization(this, _realSubject);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "public static Boolean compareMultipleClientConfigAvro(String configAvro1, String configAvro2) {\n Map<String, Properties> mapStoreToProps1 = readMultipleClientConfigAvro(configAvro1);\n Map<String, Properties> mapStoreToProps2 = readMultipleClientConfigAvro(configAvro2);\n Set<String> keySet1 = mapStoreToProps1.keySet();\n Set<String> keySet2 = mapStoreToProps2.keySet();\n if(!keySet1.equals(keySet2)) {\n return false;\n }\n for(String storeName: keySet1) {\n Properties props1 = mapStoreToProps1.get(storeName);\n Properties props2 = mapStoreToProps2.get(storeName);\n if(!props1.equals(props2)) {\n return false;\n }\n }\n return true;\n }", "public String[] getNormalizedLabels() {\n\t\tif(isValid()) {\n\t\t\treturn parsedHost.getNormalizedLabels();\n\t\t}\n\t\tif(host.length() == 0) {\n\t\t\treturn new String[0];\n\t\t}\n\t\treturn new String[] {host};\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 }", "public static void checkFolderForFile(String fileName) throws IOException {\n\n\t\tif (fileName.lastIndexOf(File.separator) > 0) {\n\t\t\tString folder = fileName.substring(0, fileName.lastIndexOf(File.separator));\n\t\t\tdirectoryCheck(folder);\n\t\t}\n\t}" ]
Submits the configured assembly to Transloadit for processing. @param isResumable boolean value that tells the assembly whether or not to use tus. @return {@link AssemblyResponse} the response received from the Transloadit server. @throws RequestException if request to Transloadit server fails. @throws LocalOperationException if something goes wrong while running non-http operations.
[ "public AssemblyResponse save(boolean isResumable)\n throws RequestException, LocalOperationException {\n Request request = new Request(getClient());\n options.put(\"steps\", steps.toMap());\n\n // only do tus uploads if files will be uploaded\n if (isResumable && getFilesCount() > 0) {\n Map<String, String> tusOptions = new HashMap<String, String>();\n tusOptions.put(\"tus_num_expected_upload_files\", Integer.toString(getFilesCount()));\n\n AssemblyResponse response = new AssemblyResponse(\n request.post(\"/assemblies\", options, tusOptions, null, null), true);\n\n // check if the assembly returned an error\n if (response.hasError()) {\n throw new RequestException(\"Request to Assembly failed: \" + response.json().getString(\"error\"));\n }\n\n try {\n handleTusUpload(response);\n } catch (IOException e) {\n throw new LocalOperationException(e);\n } catch (ProtocolException e) {\n throw new RequestException(e);\n }\n return response;\n } else {\n return new AssemblyResponse(request.post(\"/assemblies\", options, null, files, fileStreams));\n }\n }" ]
[ "public <Result> Result process(IUnitOfWork<Result, State> work) {\n\t\treleaseReadLock();\n\t\tacquireWriteLock();\n\t\ttry {\n\t\t\tif (log.isTraceEnabled())\n\t\t\t\tlog.trace(\"process - \" + Thread.currentThread().getName());\n\t\t\treturn modify(work);\n\t\t} finally {\n\t\t\tif (log.isTraceEnabled())\n\t\t\t\tlog.trace(\"Downgrading from write lock to read lock...\");\n\t\t\tacquireReadLock();\n\t\t\treleaseWriteLock();\n\t\t}\n\t}", "public static ClassLoader overrideThreadContextClassLoader(ClassLoader classLoaderToUse) {\n\t\tThread currentThread = Thread.currentThread();\n\t\tClassLoader threadContextClassLoader = currentThread.getContextClassLoader();\n\t\tif (classLoaderToUse != null && !classLoaderToUse.equals(threadContextClassLoader)) {\n\t\t\tcurrentThread.setContextClassLoader(classLoaderToUse);\n\t\t\treturn threadContextClassLoader;\n\t\t}\n\t\telse {\n\t\t\treturn null;\n\t\t}\n\t}", "public ConfigBuilder withMasterName(final String masterName) {\n if (masterName == null || \"\".equals(masterName)) {\n throw new IllegalArgumentException(\"masterName is null or empty: \" + masterName);\n }\n this.masterName = masterName;\n return this;\n }", "@PostConstruct\n public void initDatabase() {\n MongoDBInit.LOGGER.info(\"initializing MongoDB\");\n String dbName = System.getProperty(\"mongodb.name\");\n if (dbName == null) {\n throw new RuntimeException(\"Missing database name; Set system property 'mongodb.name'\");\n }\n MongoDatabase db = this.mongo.getDatabase(dbName);\n\n try {\n PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();\n Resource[] resources = resolver.getResources(\"classpath*:mongodb/*.ndjson\");\n MongoDBInit.LOGGER.info(\"Scanning for collection data\");\n for (Resource res : resources) {\n String filename = res.getFilename();\n String collection = filename.substring(0, filename.length() - 7);\n MongoDBInit.LOGGER.info(\"Found collection file: {}\", collection);\n MongoCollection<DBObject> dbCollection = db.getCollection(collection, DBObject.class);\n try (Scanner scan = new Scanner(res.getInputStream(), \"UTF-8\")) {\n int lines = 0;\n while (scan.hasNextLine()) {\n String json = scan.nextLine();\n Object parse = JSON.parse(json);\n if (parse instanceof DBObject) {\n DBObject dbObject = (DBObject) parse;\n dbCollection.insertOne(dbObject);\n } else {\n MongoDBInit.LOGGER.error(\"Invalid object found: {}\", parse);\n throw new RuntimeException(\"Invalid object\");\n }\n lines++;\n }\n MongoDBInit.LOGGER.info(\"Imported {} objects into collection {}\", lines, collection);\n }\n }\n } catch (IOException e) {\n throw new RuntimeException(\"Error importing objects\", e);\n }\n }", "@JmxOperation\n public String stopAsyncOperation(int requestId) {\n try {\n stopOperation(requestId);\n } catch(VoldemortException e) {\n return e.getMessage();\n }\n\n return \"Stopping operation \" + requestId;\n }", "public static Class<?> loadClass(String className, ClassLoader cl) {\n try {\n return Class.forName(className, false, cl);\n } catch(ClassNotFoundException e) {\n throw new IllegalArgumentException(e);\n }\n }", "public static base_responses add(nitro_service client, sslaction resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tsslaction addresources[] = new sslaction[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new sslaction();\n\t\t\t\taddresources[i].name = resources[i].name;\n\t\t\t\taddresources[i].clientauth = resources[i].clientauth;\n\t\t\t\taddresources[i].clientcert = resources[i].clientcert;\n\t\t\t\taddresources[i].certheader = resources[i].certheader;\n\t\t\t\taddresources[i].clientcertserialnumber = resources[i].clientcertserialnumber;\n\t\t\t\taddresources[i].certserialheader = resources[i].certserialheader;\n\t\t\t\taddresources[i].clientcertsubject = resources[i].clientcertsubject;\n\t\t\t\taddresources[i].certsubjectheader = resources[i].certsubjectheader;\n\t\t\t\taddresources[i].clientcerthash = resources[i].clientcerthash;\n\t\t\t\taddresources[i].certhashheader = resources[i].certhashheader;\n\t\t\t\taddresources[i].clientcertissuer = resources[i].clientcertissuer;\n\t\t\t\taddresources[i].certissuerheader = resources[i].certissuerheader;\n\t\t\t\taddresources[i].sessionid = resources[i].sessionid;\n\t\t\t\taddresources[i].sessionidheader = resources[i].sessionidheader;\n\t\t\t\taddresources[i].cipher = resources[i].cipher;\n\t\t\t\taddresources[i].cipherheader = resources[i].cipherheader;\n\t\t\t\taddresources[i].clientcertnotbefore = resources[i].clientcertnotbefore;\n\t\t\t\taddresources[i].certnotbeforeheader = resources[i].certnotbeforeheader;\n\t\t\t\taddresources[i].clientcertnotafter = resources[i].clientcertnotafter;\n\t\t\t\taddresources[i].certnotafterheader = resources[i].certnotafterheader;\n\t\t\t\taddresources[i].owasupport = resources[i].owasupport;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "public long[] append(MessageSet messages) throws IOException {\n checkMutable();\n long written = 0L;\n while (written < messages.getSizeInBytes())\n written += messages.writeTo(channel, 0, messages.getSizeInBytes());\n long beforeOffset = setSize.getAndAdd(written);\n return new long[]{written, beforeOffset};\n }", "public static ClassLoader resolveClassLoaderForBeanProxy(String contextId, Class<?> proxiedType, TypeInfo typeInfo, ProxyServices proxyServices) {\n Class<?> superClass = typeInfo.getSuperClass();\n if (superClass.getName().startsWith(JAVA)) {\n ClassLoader cl = proxyServices.getClassLoader(proxiedType);\n if (cl == null) {\n cl = Thread.currentThread().getContextClassLoader();\n }\n return cl;\n }\n return Container.instance(contextId).services().get(ProxyServices.class).getClassLoader(superClass);\n }" ]
return the list of FormInputs that match this element @param element @return
[ "private FormInput formInputMatchingNode(Node element) {\n\t\tNamedNodeMap attributes = element.getAttributes();\n\t\tIdentification id;\n\n\t\tif (attributes.getNamedItem(\"id\") != null\n\t\t\t\t&& formFillMode != FormFillMode.XPATH_TRAINING) {\n\t\t\tid = new Identification(Identification.How.id,\n\t\t\t\t\tattributes.getNamedItem(\"id\").getNodeValue());\n\t\t\tFormInput input = this.formInputs.get(id);\n\t\t\tif (input != null) {\n\t\t\t\treturn input;\n\t\t\t}\n\t\t}\n\n\t\tif (attributes.getNamedItem(\"name\") != null\n\t\t\t\t&& formFillMode != FormFillMode.XPATH_TRAINING) {\n\t\t\tid = new Identification(Identification.How.name,\n\t\t\t\t\tattributes.getNamedItem(\"name\").getNodeValue());\n\t\t\tFormInput input = this.formInputs.get(id);\n\t\t\tif (input != null) {\n\t\t\t\treturn input;\n\t\t\t}\n\t\t}\n\n\t\tString xpathExpr = XPathHelper.getXPathExpression(element);\n\t\tif (xpathExpr != null && !xpathExpr.equals(\"\")) {\n\t\t\tid = new Identification(Identification.How.xpath, xpathExpr);\n\t\t\tFormInput input = this.formInputs.get(id);\n\t\t\tif (input != null) {\n\t\t\t\treturn input;\n\t\t\t}\n\t\t}\n\n\t\treturn null;\n\t}" ]
[ "private static <R> RowKey buildRowKey(AssociationKey associationKey, R row, AssociationRowAccessor<R> accessor) {\n\t\tString[] columnNames = associationKey.getMetadata().getRowKeyColumnNames();\n\t\tObject[] columnValues = new Object[columnNames.length];\n\n\t\tfor ( int i = 0; i < columnNames.length; i++ ) {\n\t\t\tString columnName = columnNames[i];\n\t\t\tcolumnValues[i] = associationKey.getMetadata().isKeyColumn( columnName ) ? associationKey.getColumnValue( columnName ) : accessor.get( row, columnName );\n\t\t}\n\n\t\treturn new RowKey( columnNames, columnValues );\n\t}", "public static Type getDeclaredBeanType(Class<?> clazz) {\n Type[] actualTypeArguments = Reflections.getActualTypeArguments(clazz);\n if (actualTypeArguments.length == 1) {\n return actualTypeArguments[0];\n } else {\n return null;\n }\n }", "public void setIsSeries(Boolean isSeries) {\r\n\r\n if (null != isSeries) {\r\n final boolean series = isSeries.booleanValue();\r\n if ((null != m_model.getParentSeriesId()) && series) {\r\n m_removeSeriesBindingConfirmDialog.show(new Command() {\r\n\r\n public void execute() {\r\n\r\n m_model.setParentSeriesId(null);\r\n setPattern(PatternType.DAILY.toString());\r\n\r\n }\r\n });\r\n } else {\r\n setPattern(series ? PatternType.DAILY.toString() : PatternType.NONE.toString());\r\n }\r\n }\r\n }", "static TarArchiveEntry defaultFileEntryWithName( final String fileName ) {\n TarArchiveEntry entry = new TarArchiveEntry(fileName, true);\n entry.setUserId(ROOT_UID);\n entry.setUserName(ROOT_NAME);\n entry.setGroupId(ROOT_UID);\n entry.setGroupName(ROOT_NAME);\n entry.setMode(TarArchiveEntry.DEFAULT_FILE_MODE);\n return entry;\n }", "private LocatorSelectionStrategy getLocatorSelectionStrategy(String locatorSelectionStrategy) {\n if (null == locatorSelectionStrategy) {\n return locatorSelectionStrategyMap.get(DEFAULT_STRATEGY).getInstance();\n }\n\n if (LOG.isLoggable(Level.FINE)) {\n LOG.log(Level.FINE, \"Strategy \" + locatorSelectionStrategy\n + \" was set for LocatorClientRegistrar.\");\n }\n\n if (locatorSelectionStrategyMap.containsKey(locatorSelectionStrategy)) {\n return locatorSelectionStrategyMap.get(locatorSelectionStrategy).getInstance();\n } else {\n if (LOG.isLoggable(Level.WARNING)) {\n LOG.log(Level.WARNING, \"LocatorSelectionStrategy \" + locatorSelectionStrategy\n + \" not registered at LocatorClientEnabler.\");\n }\n return locatorSelectionStrategyMap.get(DEFAULT_STRATEGY).getInstance();\n }\n }", "protected void animateOffsetTo(int position, int velocity, boolean animate) {\n endDrag();\n endPeek();\n\n final int startX = (int) mOffsetPixels;\n final int dx = position - startX;\n if (dx == 0 || !animate) {\n setOffsetPixels(position);\n setDrawerState(position == 0 ? STATE_CLOSED : STATE_OPEN);\n stopLayerTranslation();\n return;\n }\n\n int duration;\n\n velocity = Math.abs(velocity);\n if (velocity > 0) {\n duration = 4 * Math.round(1000.f * Math.abs((float) dx / velocity));\n } else {\n duration = (int) (600.f * Math.abs((float) dx / mMenuSize));\n }\n\n duration = Math.min(duration, mMaxAnimationDuration);\n animateOffsetTo(position, duration);\n }", "public UriComponentsBuilder pathSegment(String... pathSegments) throws IllegalArgumentException {\n\t\tAssert.notNull(pathSegments, \"'segments' must not be null\");\n\t\tthis.pathBuilder.addPathSegments(pathSegments);\n\t\tresetSchemeSpecificPart();\n\t\treturn this;\n\t}", "public static final String printCurrencySymbolPosition(CurrencySymbolPosition value)\n {\n String result;\n\n switch (value)\n {\n default:\n case BEFORE:\n {\n result = \"0\";\n break;\n }\n\n case AFTER:\n {\n result = \"1\";\n break;\n }\n\n case BEFORE_WITH_SPACE:\n {\n result = \"2\";\n break;\n }\n\n case AFTER_WITH_SPACE:\n {\n result = \"3\";\n break;\n }\n }\n\n return (result);\n }", "private List<Bucket> lookup(Record record) {\n List<Bucket> buckets = new ArrayList();\n for (Property p : config.getLookupProperties()) {\n String propname = p.getName();\n Collection<String> values = record.getValues(propname);\n if (values == null)\n continue;\n\n for (String value : values) {\n String[] tokens = StringUtils.split(value);\n for (int ix = 0; ix < tokens.length; ix++) {\n Bucket b = store.lookupToken(propname, tokens[ix]);\n if (b == null || b.records == null)\n continue;\n long[] ids = b.records;\n if (DEBUG)\n System.out.println(propname + \", \" + tokens[ix] + \": \" + b.nextfree + \" (\" + b.getScore() + \")\");\n buckets.add(b);\n }\n }\n }\n\n return buckets;\n }" ]
Translate this rectangle over the specified following distances. @param rect rectangle to move @param dx delta x @param dy delta y
[ "public void translateRectangle(Rectangle rect, float dx, float dy) {\n\t\tfloat width = rect.getWidth();\n\t\tfloat height = rect.getHeight();\n\t\trect.setLeft(rect.getLeft() + dx);\n\t\trect.setBottom(rect.getBottom() + dy);\n\t\trect.setRight(rect.getLeft() + dx + width);\n\t\trect.setTop(rect.getBottom() + dy + height);\n\t}" ]
[ "private void _handleMultiValues(ArrayList<String> values, String key, String command) {\n if (key == null) return;\n\n if (values == null || values.isEmpty()) {\n _generateEmptyMultiValueError(key);\n return;\n }\n\n ValidationResult vr;\n\n // validate the key\n vr = validator.cleanMultiValuePropertyKey(key);\n\n // Check for an error\n if (vr.getErrorCode() != 0) {\n pushValidationResult(vr);\n }\n\n // reset the key\n Object _key = vr.getObject();\n String cleanKey = (_key != null) ? vr.getObject().toString() : null;\n\n // if key is empty generate an error and return\n if (cleanKey == null || cleanKey.isEmpty()) {\n _generateInvalidMultiValueKeyError(key);\n return;\n }\n\n key = cleanKey;\n\n try {\n JSONArray currentValues = _constructExistingMultiValue(key, command);\n JSONArray newValues = _cleanMultiValues(values, key);\n _validateAndPushMultiValue(currentValues, newValues, values, key, command);\n\n } catch (Throwable t) {\n getConfigLogger().verbose(getAccountId(), \"Error handling multi value operation for key \" + key, t);\n }\n }", "public static long convertBytesToLong(byte[] bytes, int offset)\n {\n long value = 0;\n for (int i = offset; i < offset + 8; i++)\n {\n byte b = bytes[i];\n value <<= 8;\n value |= b;\n }\n return value;\n\n }", "private boolean shouldIgnore(String typeReference)\n {\n typeReference = typeReference.replace('/', '.').replace('\\\\', '.');\n return JavaClassIgnoreResolver.singletonInstance().matches(typeReference);\n }", "public byte[] toByteArray() {\n try {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(baos);\n oos.writeObject(this);\n return baos.toByteArray();\n } catch (IOException e) {\n throw E.ioException(e);\n }\n }", "public static base_response Shutdown(nitro_service client, shutdown resource) throws Exception {\n\t\tshutdown Shutdownresource = new shutdown();\n\t\treturn Shutdownresource.perform_operation(client);\n\t}", "private static int weekRange(int weekBasedYear) {\n LocalDate date = LocalDate.of(weekBasedYear, 1, 1);\n // 53 weeks if year starts on Thursday, or Wed in a leap year\n if (date.getDayOfWeek() == THURSDAY || (date.getDayOfWeek() == WEDNESDAY && date.isLeapYear())) {\n return 53;\n }\n return 52;\n }", "public void logAttributeWarning(PathAddress address, ModelNode operation, String message, Set<String> attributes) {\n messageQueue.add(new AttributeLogEntry(address, operation, message, attributes));\n }", "@VisibleForTesting\n @Nullable\n protected LineSymbolizer createLineSymbolizer(final PJsonObject styleJson) {\n final Stroke stroke = createStroke(styleJson, true);\n if (stroke == null) {\n return null;\n } else {\n return this.styleBuilder.createLineSymbolizer(stroke);\n }\n }", "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 }" ]
Map content. @param dh the data handler @return the string
[ "private static String mapContent(DataHandler dh) {\n if (dh == null) {\n return \"\";\n }\n try {\n InputStream is = dh.getInputStream();\n String content = IOUtils.toString(is);\n is.close();\n return content;\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }" ]
[ "public List<Versioned<V>> getWithCustomTimeout(CompositeVoldemortRequest<K, V> requestWrapper) {\n validateTimeout(requestWrapper.getRoutingTimeoutInMs());\n for(int attempts = 0; attempts < this.metadataRefreshAttempts; attempts++) {\n try {\n long startTimeInMs = System.currentTimeMillis();\n String keyHexString = \"\";\n if(logger.isDebugEnabled()) {\n ByteArray key = (ByteArray) requestWrapper.getKey();\n keyHexString = RestUtils.getKeyHexString(key);\n debugLogStart(\"GET\",\n requestWrapper.getRequestOriginTimeInMs(),\n startTimeInMs,\n keyHexString);\n }\n List<Versioned<V>> items = store.get(requestWrapper);\n if(logger.isDebugEnabled()) {\n int vcEntrySize = 0;\n for(Versioned<V> vc: items) {\n vcEntrySize += ((VectorClock) vc.getVersion()).getVersionMap().size();\n }\n debugLogEnd(\"GET\",\n requestWrapper.getRequestOriginTimeInMs(),\n startTimeInMs,\n System.currentTimeMillis(),\n keyHexString,\n vcEntrySize);\n }\n return items;\n } catch(InvalidMetadataException e) {\n logger.info(\"Received invalid metadata exception during get [ \" + e.getMessage()\n + \" ] on store '\" + storeName + \"'. Rebootstrapping\");\n bootStrap();\n }\n }\n throw new VoldemortException(this.metadataRefreshAttempts\n + \" metadata refresh attempts failed.\");\n }", "@SuppressWarnings(\"unused\")\n\t@XmlID\n @XmlAttribute(name = \"id\")\n private String getXmlID(){\n return String.format(\"%s-%s\", this.getClass().getSimpleName(), Long.valueOf(id));\n }", "private Integer mapTaskID(Integer id)\n {\n Integer mappedID = m_clashMap.get(id);\n if (mappedID == null)\n {\n mappedID = id;\n }\n return (mappedID);\n }", "private void removeAllBroadcasts(Set<String> sessionIds) {\n\n if (sessionIds == null) {\n for (CmsSessionInfo info : OpenCms.getSessionManager().getSessionInfos()) {\n OpenCms.getSessionManager().getBroadcastQueue(info.getSessionId().getStringValue()).clear();\n }\n return;\n }\n for (String sessionId : sessionIds) {\n OpenCms.getSessionManager().getBroadcastQueue(sessionId).clear();\n }\n }", "public void addRequiredBundles(String... requiredBundles) {\n\t\tString oldBundles = mainAttributes.get(REQUIRE_BUNDLE);\n\t\tif (oldBundles == null)\n\t\t\toldBundles = \"\";\n\t\tBundleList oldResultList = BundleList.fromInput(oldBundles, newline);\n\t\tBundleList resultList = BundleList.fromInput(oldBundles, newline);\n\t\tfor (String bundle : requiredBundles) {\n\t\t\tBundle newBundle = Bundle.fromInput(bundle);\n\t\t\tif (name != null && name.equals(newBundle.getName()))\n\t\t\t\tcontinue;\n\t\t\tresultList.mergeInto(newBundle);\n\t\t}\n\t\tString result = resultList.toString();\n\t\tboolean changed = !oldResultList.toString().equals(result);\n\t\tmodified |= changed;\n\t\tif (changed)\n\t\t\tmainAttributes.put(REQUIRE_BUNDLE, result);\n\t}", "protected String getUserDefinedFieldName(String field) {\n int index = field.indexOf('-');\n char letter = getUserDefinedFieldLetter();\n\n for (int i = 0; i < index; ++i) {\n if (field.charAt(i) == letter) {\n return field.substring(index + 1);\n }\n }\n\n return null;\n }", "private void initExceptionsPanel() {\n\n m_exceptionsPanel.setLegend(Messages.get().key(Messages.GUI_SERIALDATE_PANEL_EXCEPTIONS_0));\n m_exceptionsPanel.addCloseHandler(this);\n m_exceptionsPanel.setVisible(false);\n }", "public static BoxDeveloperEditionAPIConnection getAppEnterpriseConnection(String enterpriseId, String clientId,\n String clientSecret, JWTEncryptionPreferences encryptionPref, IAccessTokenCache accessTokenCache) {\n\n BoxDeveloperEditionAPIConnection connection = new BoxDeveloperEditionAPIConnection(enterpriseId,\n DeveloperEditionEntityType.ENTERPRISE, clientId, clientSecret, encryptionPref, accessTokenCache);\n\n connection.tryRestoreUsingAccessTokenCache();\n\n return connection;\n }", "private static boolean isAssignableFrom(Type from, GenericArrayType to) {\n\t\tType toGenericComponentType = to.getGenericComponentType();\n\t\tif (toGenericComponentType instanceof ParameterizedType) {\n\t\t\tType t = from;\n\t\t\tif (from instanceof GenericArrayType) {\n\t\t\t\tt = ((GenericArrayType) from).getGenericComponentType();\n\t\t\t} else if (from instanceof Class) {\n\t\t\t\tClass<?> classType = (Class<?>) from;\n\t\t\t\twhile (classType.isArray()) {\n\t\t\t\t\tclassType = classType.getComponentType();\n\t\t\t\t}\n\t\t\t\tt = classType;\n\t\t\t}\n\t\t\treturn isAssignableFrom(t,\n\t\t\t\t\t(ParameterizedType) toGenericComponentType,\n\t\t\t\t\tnew HashMap<String, Type>());\n\t\t}\n\t\t// No generic defined on \"to\"; therefore, return true and let other\n\t\t// checks determine assignability\n\t\treturn true;\n\t}" ]
Whether the given value generation strategy requires to read the value from the database or not.
[ "private boolean isReadRequired(ValueGeneration valueGeneration, GenerationTiming matchTiming) {\n\t\treturn valueGeneration != null && valueGeneration.getValueGenerator() == null &&\n\t\t\t\ttimingsMatch( valueGeneration.getGenerationTiming(), matchTiming );\n\t}" ]
[ "public long[] keys() {\n long[] values = new long[size];\n int idx = 0;\n for (Entry entry : table) {\n while (entry != null) {\n values[idx++] = entry.key;\n entry = entry.next;\n }\n }\n return values;\n }", "public void processStencilSet() throws IOException {\n StringBuilder stencilSetFileContents = new StringBuilder();\n\n Scanner scanner = null;\n try {\n scanner = new Scanner(new File(ssInFile),\n \"UTF-8\");\n String currentLine = \"\";\n String prevLine = \"\";\n while (scanner.hasNextLine()) {\n prevLine = currentLine;\n currentLine = scanner.nextLine();\n\n String trimmedPrevLine = prevLine.trim();\n String trimmedCurrentLine = currentLine.trim();\n\n // First time processing - replace view=\"<file>.svg\" with _view_file=\"<file>.svg\" + view=\"<svg_xml>\"\n if (trimmedCurrentLine.matches(VIEW_PROPERTY_NAME_PATTERN) && trimmedCurrentLine.endsWith(VIEW_PROPERTY_VALUE_SUFFIX)) {\n String newLines = processViewPropertySvgReference(currentLine);\n stencilSetFileContents.append(newLines);\n }\n // Second time processing - replace view=\"<svg_xml>\" with refreshed contents of file referenced by previous line\n else if (trimmedPrevLine.matches(VIEW_FILE_PROPERTY_NAME_PATTERN) && trimmedPrevLine.endsWith(VIEW_PROPERTY_VALUE_SUFFIX)\n && trimmedCurrentLine.matches(VIEW_PROPERTY_NAME_PATTERN)) {\n String newLines = processViewFilePropertySvgReference(prevLine,\n currentLine);\n stencilSetFileContents.append(newLines);\n } else {\n stencilSetFileContents.append(currentLine + LINE_SEPARATOR);\n }\n }\n } finally {\n if (scanner != null) {\n scanner.close();\n }\n }\n\n Writer out = null;\n try {\n out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(ssOutFile),\n \"UTF-8\"));\n out.write(stencilSetFileContents.toString());\n } catch (FileNotFoundException e) {\n\n } catch (UnsupportedEncodingException e) {\n } catch (IOException e) {\n } finally {\n if (out != null) {\n try {\n out.close();\n } catch (IOException e) {\n }\n }\n }\n\n System.out.println(\"SVG files referenced more than once:\");\n for (Map.Entry<String, Integer> stringIntegerEntry : mapSVGCounts.entrySet()) {\n if (stringIntegerEntry.getValue() > 1) {\n System.out.println(\"\\t\" + stringIntegerEntry.getKey() + \"\\t = \" + stringIntegerEntry.getValue());\n }\n }\n }", "private void mapText(String oldText, Map<String, String> replacements)\n {\n char c2 = 0;\n if (oldText != null && oldText.length() != 0 && !replacements.containsKey(oldText))\n {\n StringBuilder newText = new StringBuilder(oldText.length());\n for (int loop = 0; loop < oldText.length(); loop++)\n {\n char c = oldText.charAt(loop);\n if (Character.isUpperCase(c))\n {\n newText.append('X');\n }\n else\n {\n if (Character.isLowerCase(c))\n {\n newText.append('x');\n }\n else\n {\n if (Character.isDigit(c))\n {\n newText.append('0');\n }\n else\n {\n if (Character.isLetter(c))\n {\n // Handle other codepages etc. If possible find a way to\n // maintain the same code page as original.\n // E.g. replace with a character from the same alphabet.\n // This 'should' work for most cases\n if (c2 == 0)\n {\n c2 = c;\n }\n newText.append(c2);\n }\n else\n {\n newText.append(c);\n }\n }\n }\n }\n }\n\n replacements.put(oldText, newText.toString());\n }\n }", "public static void checkEigenvalues() {\n DoubleMatrix A = new DoubleMatrix(new double[][]{\n {3.0, 2.0, 0.0},\n {2.0, 3.0, 2.0},\n {0.0, 2.0, 3.0}\n });\n\n DoubleMatrix E = new DoubleMatrix(3, 1);\n\n NativeBlas.dsyev('N', 'U', 3, A.data, 0, 3, E.data, 0);\n check(\"checking existence of dsyev...\", true);\n }", "public FieldDescriptor getAutoIncrementField()\r\n {\r\n if (m_autoIncrementField == null)\r\n {\r\n FieldDescriptor[] fds = getPkFields();\r\n\r\n for (int i = 0; i < fds.length; i++)\r\n {\r\n FieldDescriptor fd = fds[i];\r\n if (fd.isAutoIncrement())\r\n {\r\n m_autoIncrementField = fd;\r\n break;\r\n }\r\n }\r\n }\r\n if (m_autoIncrementField == null)\r\n {\r\n LoggerFactory.getDefaultLogger().warn(\r\n this.getClass().getName()\r\n + \": \"\r\n + \"Could not find autoincrement attribute for class: \"\r\n + this.getClassNameOfObject());\r\n }\r\n return m_autoIncrementField;\r\n }", "public HostName toHostName() {\n\t\tHostName host = fromHost;\n\t\tif(host == null) {\n\t\t\tfromHost = host = toCanonicalHostName();\n\t\t}\n\t\treturn host;\n\t}", "public static Variable upcastToGeneratedBuilder(\n SourceBuilder code, Datatype datatype, String builder) {\n return code.scope().computeIfAbsent(Declaration.UPCAST, () -> {\n Variable base = new Variable(\"base\");\n code.addLine(UPCAST_COMMENT)\n .addLine(\"%s %s = %s;\", datatype.getGeneratedBuilder(), base, builder);\n return base;\n });\n }", "public SimpleConfiguration getClientConfiguration() {\n SimpleConfiguration clientConfig = new SimpleConfiguration();\n Iterator<String> iter = getKeys();\n while (iter.hasNext()) {\n String key = iter.next();\n if (key.startsWith(CONNECTION_PREFIX) || key.startsWith(ACCUMULO_PREFIX)\n || key.startsWith(CLIENT_PREFIX)) {\n clientConfig.setProperty(key, getRawString(key));\n }\n }\n return clientConfig;\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<DiscordianDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<DiscordianDate>) super.zonedDateTime(temporal);\n }" ]
Post the specified photo to a blog. Note that the Photo.title and Photo.description are used for the blog entry title and body respectively. @param photo The photo metadata @param blogId The blog ID @param blogPassword The blog password @throws FlickrException
[ "public void postPhoto(Photo photo, String blogId, String blogPassword) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_POST_PHOTO);\r\n\r\n parameters.put(\"blog_id\", blogId);\r\n parameters.put(\"photo_id\", photo.getId());\r\n parameters.put(\"title\", photo.getTitle());\r\n parameters.put(\"description\", photo.getDescription());\r\n if (blogPassword != null) {\r\n parameters.put(\"blog_password\", blogPassword);\r\n }\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }" ]
[ "private void updateBaseCalendarNames(List<Pair<ProjectCalendar, Integer>> baseCalendars)\n {\n for (Pair<ProjectCalendar, Integer> pair : baseCalendars)\n {\n ProjectCalendar cal = pair.getFirst();\n Integer baseCalendarID = pair.getSecond();\n ProjectCalendar baseCal = m_calendarMap.get(baseCalendarID);\n if (baseCal != null)\n {\n cal.setParent(baseCal);\n }\n }\n }", "private synchronized void closeIdleClients() {\n List<Client> candidates = new LinkedList<Client>(openClients.values());\n logger.debug(\"Scanning for idle clients; \" + candidates.size() + \" candidates.\");\n for (Client client : candidates) {\n if ((useCounts.get(client) < 1) &&\n ((timestamps.get(client) + idleLimit.get() * 1000) <= System.currentTimeMillis())) {\n logger.debug(\"Idle time reached for unused client {}\", client);\n closeClient(client);\n }\n }\n }", "public static List<Number> findIndexValues(Object self, Number startIndex, Closure closure) {\n List<Number> result = new ArrayList<Number>();\n long count = 0;\n long startCount = startIndex.longValue();\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); count++) {\n Object value = iter.next();\n if (count < startCount) {\n continue;\n }\n if (bcw.call(value)) {\n result.add(count);\n }\n }\n return result;\n }", "protected static Map<Double, Double> doQuantization(double max,\n double min,\n double[] values)\n {\n double range = max - min;\n int noIntervals = 20;\n double intervalSize = range / noIntervals;\n int[] intervals = new int[noIntervals];\n for (double value : values)\n {\n int interval = Math.min(noIntervals - 1,\n (int) Math.floor((value - min) / intervalSize));\n assert interval >= 0 && interval < noIntervals : \"Invalid interval: \" + interval;\n ++intervals[interval];\n }\n Map<Double, Double> discretisedValues = new HashMap<Double, Double>();\n for (int i = 0; i < intervals.length; i++)\n {\n // Correct the value to take into account the size of the interval.\n double value = (1 / intervalSize) * (double) intervals[i];\n discretisedValues.put(min + ((i + 0.5) * intervalSize), value);\n }\n return discretisedValues;\n }", "private void addModuleToGraph(final DbModule module, final AbstractGraph graph, final int depth) {\n if (graph.isTreated(graph.getId(module))) {\n return;\n }\n\n final String moduleElementId = graph.getId(module);\n graph.addElement(moduleElementId, module.getVersion(), depth == 0);\n\n if (filters.getDepthHandler().shouldGoDeeper(depth)) {\n for (final DbDependency dep : DataUtils.getAllDbDependencies(module)) {\n if(filters.shouldBeInReport(dep)){\n addDependencyToGraph(dep, graph, depth + 1, moduleElementId);\n }\n }\n }\n }", "public static String getSolrRangeString(String from, String to) {\n\n // If a parameter is not initialized, use the asterisk '*' operator\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(from)) {\n from = \"*\";\n }\n\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(to)) {\n to = \"*\";\n }\n\n return String.format(\"[%s TO %s]\", from, to);\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 }", "public void deleteFolder(String folderID) {\n URL url = FOLDER_INFO_URL_TEMPLATE.build(this.api.getBaseURL(), folderID);\n BoxAPIRequest request = new BoxAPIRequest(this.api, url, \"DELETE\");\n BoxAPIResponse response = request.send();\n response.disconnect();\n }", "private static boolean mayBeIPv6Address(String input) {\n if (input == null) {\n return false;\n }\n\n boolean result = false;\n int colonsCounter = 0;\n int length = input.length();\n for (int i = 0; i < length; i++) {\n char c = input.charAt(i);\n if (c == '.' || c == '%') {\n // IPv4 in IPv6 or Zone ID detected, end of checking.\n break;\n }\n if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')\n || (c >= 'A' && c <= 'F') || c == ':')) {\n return false;\n } else if (c == ':') {\n colonsCounter++;\n }\n }\n if (colonsCounter >= 2) {\n result = true;\n }\n return result;\n }" ]
Set a status message in the JTextComponent passed to this model. @param message The message that should be displayed.
[ "public void setStatusBarMessage(final String message)\r\n {\r\n // Guaranteed to return a non-null array\r\n Object[] listeners = listenerList.getListenerList();\r\n // Process the listeners last to first, notifying\r\n // those that are interested in this event\r\n for (int i = listeners.length-2; i>=0; i-=2) {\r\n if (listeners[i]==StatusMessageListener.class) \r\n {\r\n ((StatusMessageListener)listeners[i+1]).statusMessageReceived(message);\r\n } \r\n } \r\n }" ]
[ "private void checkExistingTracks() {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (Map.Entry<DeckReference, TrackMetadata> entry : MetadataFinder.getInstance().getLoadedTracks().entrySet()) {\n if (entry.getKey().hotCue == 0) { // The track is currently loaded in a main player deck\n checkIfSignatureReady(entry.getKey().player);\n }\n }\n }\n });\n }", "public void setCharTranslator(CharacterTranslator charTranslator) {\r\n\t\tif(charTranslator!=null){\r\n\t\t\tthis.charTranslator = charTranslator;\r\n\t\t\tthis.htmlElementTranslator = null;\r\n\t\t\tthis.targetTranslator = null;\r\n\t\t}\r\n\t}", "public boolean shouldCompress(String requestUri) {\n\t\tString uri = requestUri.toLowerCase();\n\t\treturn checkSuffixes(uri, zipSuffixes);\n\t}", "public void postArtifact(final Artifact artifact, final String user, final String password) throws GrapesCommunicationException, AuthenticationException {\n final Client client = getClient(user, password);\n final WebResource resource = client.resource(serverURL).path(RequestUtils.artifactResourcePath());\n final ClientResponse response = resource.type(MediaType.APPLICATION_JSON).post(ClientResponse.class, artifact);\n\n client.destroy();\n if(ClientResponse.Status.CREATED.getStatusCode() != response.getStatus()){\n final String message = \"Failed to POST artifact\";\n if(LOG.isErrorEnabled()) {\n LOG.error(String.format(HTTP_STATUS_TEMPLATE_MSG, message, response.getStatus()));\n }\n throw new GrapesCommunicationException(message, response.getStatus());\n }\n }", "private void applyAliases(Map<FieldType, String> aliases)\n {\n CustomFieldContainer fields = m_project.getCustomFields();\n for (Map.Entry<FieldType, String> entry : aliases.entrySet())\n {\n fields.getCustomField(entry.getKey()).setAlias(entry.getValue());\n }\n }", "public static String getCorrelationId(Message message) {\n String correlationId = (String) message.get(CORRELATION_ID_KEY);\n if(null == correlationId) {\n correlationId = readCorrelationId(message);\n }\n if(null == correlationId) {\n correlationId = readCorrelationIdSoap(message);\n }\n return correlationId;\n }", "public static cmppolicylabel_cmppolicy_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tcmppolicylabel_cmppolicy_binding obj = new cmppolicylabel_cmppolicy_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcmppolicylabel_cmppolicy_binding response[] = (cmppolicylabel_cmppolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public HalfEdge getEdge(int i) {\n HalfEdge he = he0;\n while (i > 0) {\n he = he.next;\n i--;\n }\n while (i < 0) {\n he = he.prev;\n i++;\n }\n return he;\n }", "private void doSend(byte[] msg, boolean wait, KNXAddress dst)\r\n\t\tthrows KNXAckTimeoutException, KNXLinkClosedException\r\n\t{\r\n\t\tif (closed)\r\n\t\t\tthrow new KNXLinkClosedException(\"link closed\");\r\n\t\ttry {\r\n\t\t\tlogger.info(\"send message to \" + dst + (wait ? \", wait for ack\" : \"\"));\r\n\t\t\tlogger.trace(\"EMI \" + DataUnitBuilder.toHex(msg, \" \"));\r\n\t\t\tconn.send(msg, wait);\r\n\t\t\tlogger.trace(\"send to \" + dst + \" succeeded\");\r\n\t\t}\r\n\t\tcatch (final KNXPortClosedException e) {\r\n\t\t\tlogger.error(\"send error, closing link\", e);\r\n\t\t\tclose();\r\n\t\t\tthrow new KNXLinkClosedException(\"link closed, \" + e.getMessage());\r\n\t\t}\r\n\t}" ]
Checks if a given number is in the range of a double. @param number a number which should be in the range of a double (positive or negative) @see java.lang.Double#MIN_VALUE @see java.lang.Double#MAX_VALUE @return number as a double
[ "@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static double checkDouble(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInDoubleRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), DOUBLE_MIN, DOUBLE_MAX);\n\t\t}\n\n\t\treturn number.doubleValue();\n\t}" ]
[ "public Replication queryParams(Map<String, Object> queryParams) {\r\n this.replication = replication.queryParams(queryParams);\r\n return this;\r\n }", "static boolean shouldShowRequestPermissionRationale(Activity activity, String... permissions) {\n for (String permission : permissions) {\n if (ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) {\n return true;\n }\n }\n return false;\n }", "public Map<String, String> listConfig(String appName) {\n return connection.execute(new ConfigList(appName), apiKey);\n }", "public ByteBuffer payload() {\n ByteBuffer payload = buffer.duplicate();\n payload.position(headerSize(magic()));\n payload = payload.slice();\n payload.limit(payloadSize());\n payload.rewind();\n return payload;\n }", "private List<CmsGitConfiguration> readConfigFiles() {\n\n List<CmsGitConfiguration> configurations = new LinkedList<CmsGitConfiguration>();\n\n // Default configuration file for backwards compatibility\n addConfigurationIfValid(configurations, new File(DEFAULT_CONFIG_FILE));\n\n // All files in the config folder\n File configFolder = new File(DEFAULT_CONFIG_FOLDER);\n if (configFolder.isDirectory()) {\n for (File configFile : configFolder.listFiles()) {\n addConfigurationIfValid(configurations, configFile);\n }\n }\n return configurations;\n }", "private boolean computeUWV() {\n bidiag.getDiagonal(diag,off);\n qralg.setMatrix(numRowsT,numColsT,diag,off);\n\n// long pointA = System.currentTimeMillis();\n // compute U and V matrices\n if( computeU )\n Ut = bidiag.getU(Ut,true,compact);\n if( computeV )\n Vt = bidiag.getV(Vt,true,compact);\n\n qralg.setFastValues(false);\n if( computeU )\n qralg.setUt(Ut);\n else\n qralg.setUt(null);\n if( computeV )\n qralg.setVt(Vt);\n else\n qralg.setVt(null);\n\n// long pointB = System.currentTimeMillis();\n\n boolean ret = !qralg.process();\n\n// long pointC = System.currentTimeMillis();\n// System.out.println(\" compute UV \"+(pointB-pointA)+\" QR = \"+(pointC-pointB));\n\n return ret;\n }", "void invoke(HttpRequest request) throws Exception {\n bodyConsumer = null;\n Object invokeResult;\n try {\n args[0] = this.request = request;\n invokeResult = method.invoke(handler, args);\n } catch (InvocationTargetException e) {\n exceptionHandler.handle(e.getTargetException(), request, responder);\n return;\n } catch (Throwable t) {\n exceptionHandler.handle(t, request, responder);\n return;\n }\n\n if (isStreaming) {\n // Casting guarantee to be succeeded.\n bodyConsumer = (BodyConsumer) invokeResult;\n }\n }", "public static Command newInsertElements(Collection objects, String outIdentifier, boolean returnObject, String entryPoint) {\n return getCommandFactoryProvider().newInsertElements( objects, outIdentifier, returnObject, entryPoint );\n }", "private File getWorkDir() throws IOException\r\n {\r\n if (_workDir == null)\r\n { \r\n File dummy = File.createTempFile(\"dummy\", \".log\");\r\n String workDir = dummy.getPath().substring(0, dummy.getPath().lastIndexOf(File.separatorChar));\r\n \r\n if ((workDir == null) || (workDir.length() == 0))\r\n {\r\n workDir = \".\";\r\n }\r\n dummy.delete();\r\n _workDir = new File(workDir);\r\n }\r\n return _workDir;\r\n }" ]
Return list of all files in the directory. @param directory target directory on file system @return list of files in the directory or empty list if directory is empty.
[ "@NonNull\n public static File[] listAllFiles(File directory) {\n if (directory == null) {\n return new File[0];\n }\n File[] files = directory.listFiles();\n return files != null ? files : new File[0];\n }" ]
[ "@SuppressWarnings(\"unused\")\n public void selectItem(int position, boolean invokeListeners) {\n IOperationItem item = mOuterAdapter.getItem(position);\n IOperationItem oldHidedItem = mOuterAdapter.getItem(mRealHidedPosition);\n\n int realPosition = mOuterAdapter.normalizePosition(position);\n //do nothing if position not changed\n if (realPosition == mCurrentItemPosition) {\n return;\n }\n int itemToShowAdapterPosition = position - realPosition + mRealHidedPosition;\n\n item.setVisible(false);\n\n startSelectedViewOutAnimation(position);\n\n mOuterAdapter.notifyRealItemChanged(position);\n mRealHidedPosition = realPosition;\n\n oldHidedItem.setVisible(true);\n mFlContainerSelected.requestLayout();\n mOuterAdapter.notifyRealItemChanged(itemToShowAdapterPosition);\n mCurrentItemPosition = realPosition;\n\n if (invokeListeners) {\n notifyItemClickListeners(realPosition);\n }\n\n if (BuildConfig.DEBUG) {\n Log.i(TAG, \"clicked on position =\" + position);\n }\n\n }", "public ItemRequest<Project> update(String project) {\n \n String path = String.format(\"/projects/%s\", project);\n return new ItemRequest<Project>(this, Project.class, path, \"PUT\");\n }", "private Entry getEntry(Object key)\r\n {\r\n if (key == null) return null;\r\n int hash = hashCode(key);\r\n int index = indexFor(hash);\r\n for (Entry entry = table[index]; entry != null; entry = entry.next)\r\n {\r\n if ((entry.hash == hash) && equals(key, entry.getKey()))\r\n {\r\n return entry;\r\n }\r\n }\r\n return null;\r\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 String[] copyArrayAddFirst(String[] arr, String add) {\n String[] arrCopy = new String[arr.length + 1];\n arrCopy[0] = add;\n System.arraycopy(arr, 0, arrCopy, 1, arr.length);\n return arrCopy;\n }", "protected <T, A> ActiveOperation<T, A> registerActiveOperation(final Integer id, A attachment, ActiveOperation.CompletedCallback<T> callback) {\n lock.lock();\n try {\n // Check that we still allow registration\n // TODO WFCORE-199 distinguish client uses from server uses and limit this check to server uses\n // Using id==null may be one way to do this, but we need to consider ops that involve multiple requests\n // TODO WFCORE-845 consider using an IllegalStateException for this\n //assert ! shutdown;\n final Integer operationId;\n if(id == null) {\n // If we did not get an operationId, create a new one\n operationId = operationIdManager.createBatchId();\n } else {\n // Check that the operationId is not already taken\n if(! operationIdManager.lockBatchId(id)) {\n throw ProtocolLogger.ROOT_LOGGER.operationIdAlreadyExists(id);\n }\n operationId = id;\n }\n final ActiveOperationImpl<T, A> request = new ActiveOperationImpl<T, A>(operationId, attachment, getCheckedCallback(callback), this);\n final ActiveOperation<?, ?> existing = activeRequests.putIfAbsent(operationId, request);\n if(existing != null) {\n throw ProtocolLogger.ROOT_LOGGER.operationIdAlreadyExists(operationId);\n }\n ProtocolLogger.ROOT_LOGGER.tracef(\"Registered active operation %d\", operationId);\n activeCount++; // condition.signalAll();\n return request;\n } finally {\n lock.unlock();\n }\n }", "public static Tuple2<Double, Double> getRandomGeographicalLocation() {\r\n return new Tuple2<>(\r\n (double) (RandomHelper.randWithConfiguredSeed().nextInt(999) + 1) / 100,\r\n (double) (RandomHelper.randWithConfiguredSeed().nextInt(999) + 1) / 100);\r\n }", "public JsonTypeDefinition projectionType(String... properties) {\n if(this.getType() instanceof Map<?, ?>) {\n Map<?, ?> type = (Map<?, ?>) getType();\n Arrays.sort(properties);\n Map<String, Object> newType = new LinkedHashMap<String, Object>();\n for(String prop: properties)\n newType.put(prop, type.get(prop));\n return new JsonTypeDefinition(newType);\n } else {\n throw new IllegalArgumentException(\"Cannot take the projection of a type that is not a Map.\");\n }\n }", "public int getMinutesPerWeek()\n {\n return m_minutesPerWeek == null ? NumberHelper.getInt(getParentFile().getProjectProperties().getMinutesPerWeek()) : m_minutesPerWeek.intValue();\n }" ]
Runs a queued task, if the queue is not already empty. Note that this will decrement the request count if there are no queued tasks to be run @param hasPermit If the caller has already called {@link #beginRequest(boolean force)}
[ "private boolean runQueuedTask(boolean hasPermit) {\n if (!hasPermit && beginRequest(paused) == RunResult.REJECTED) {\n return false;\n }\n QueuedTask task = null;\n if (!paused) {\n task = taskQueue.poll();\n } else {\n //the container is suspended, but we still need to run any force queued tasks\n task = findForcedTask();\n }\n if (task != null) {\n if(!task.runRequest()) {\n decrementRequestCount();\n }\n return true;\n } else {\n decrementRequestCount();\n return false;\n }\n }" ]
[ "public QueryBuilder<T, ID> orderByRaw(String rawSql) {\n\t\taddOrderBy(new OrderBy(rawSql, (ArgumentHolder[]) null));\n\t\treturn this;\n\t}", "public List<BoxTask.Info> getTasks(String... fields) {\n QueryStringBuilder builder = new QueryStringBuilder();\n if (fields.length > 0) {\n builder.appendParam(\"fields\", fields).toString();\n }\n URL url = GET_TASKS_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString(), this.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 int totalCount = responseJSON.get(\"total_count\").asInt();\n List<BoxTask.Info> tasks = new ArrayList<BoxTask.Info>(totalCount);\n JsonArray entries = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : entries) {\n JsonObject taskJSON = value.asObject();\n BoxTask task = new BoxTask(this.getAPI(), taskJSON.get(\"id\").asString());\n BoxTask.Info info = task.new Info(taskJSON);\n tasks.add(info);\n }\n\n return tasks;\n }", "public static Set<String> listDeployments(Resource deploymentRootResource, Set<String> runtimeNames) {\n Set<Pattern> set = new HashSet<>();\n for (String wildcardExpr : runtimeNames) {\n Pattern pattern = DeploymentOverlayIndex.getPattern(wildcardExpr);\n set.add(pattern);\n }\n return listDeploymentNames(deploymentRootResource, set);\n }", "public void populateContainer(Class<? extends FieldType> type, FieldContainer container, Integer id, byte[][] fixedData, Var2Data varData)\n {\n //System.out.println(container.getClass().getSimpleName()+\": \" + id);\n for (FieldItem item : m_map.values())\n {\n if (item.getType().getClass().equals(type))\n {\n //System.out.println(item.m_type);\n Object value = item.read(id, fixedData, varData);\n //System.out.println(item.m_type.getClass().getSimpleName() + \".\" + item.m_type + \": \" + value);\n container.set(item.getType(), value);\n }\n }\n }", "private void populateLeaf(String parentName, Row row, Task task)\n {\n if (row.getInteger(\"TASKID\") != null)\n {\n populateTask(row, task);\n }\n else\n {\n populateMilestone(row, task);\n }\n\n String name = task.getName();\n if (name == null || name.isEmpty())\n {\n task.setName(parentName);\n }\n }", "PathAddress toPathAddress(final ObjectName name) {\n return ObjectNameAddressUtil.toPathAddress(rootObjectInstance.getObjectName(), getRootResourceAndRegistration().getRegistration(), name);\n }", "ValidationResult isRestrictedEventName(String name) {\n ValidationResult error = new ValidationResult();\n if (name == null) {\n error.setErrorCode(510);\n error.setErrorDesc(\"Event Name is null\");\n return error;\n }\n for (String x : restrictedNames)\n if (name.equalsIgnoreCase(x)) {\n // The event name is restricted\n\n error.setErrorCode(513);\n error.setErrorDesc(name + \" is a restricted event name. Last event aborted.\");\n Logger.v(name + \" is a restricted system event name. Last event aborted.\");\n return error;\n }\n return error;\n }", "private void init() {\n validatePreSignedUrls();\n\n try {\n conn = new AWSAuthConnection(access_key, secret_access_key);\n // Determine the bucket name if prefix is set or if pre-signed URLs are being used\n if (prefix != null && prefix.length() > 0) {\n ListAllMyBucketsResponse bucket_list = conn.listAllMyBuckets(null);\n List buckets = bucket_list.entries;\n if (buckets != null) {\n boolean found = false;\n for (Object tmp : buckets) {\n if (tmp instanceof Bucket) {\n Bucket bucket = (Bucket) tmp;\n if (bucket.name.startsWith(prefix)) {\n location = bucket.name;\n found = true;\n }\n }\n }\n if (!found) {\n location = prefix + \"-\" + java.util.UUID.randomUUID().toString();\n }\n }\n }\n if (usingPreSignedUrls()) {\n PreSignedUrlParser parsedPut = new PreSignedUrlParser(pre_signed_put_url);\n location = parsedPut.getBucket();\n }\n if (!conn.checkBucketExists(location)) {\n conn.createBucket(location, AWSAuthConnection.LOCATION_DEFAULT, null).connection.getResponseMessage();\n }\n } catch (Exception e) {\n throw HostControllerLogger.ROOT_LOGGER.cannotAccessS3Bucket(location, e.getLocalizedMessage());\n }\n }", "public void setWorkingDay(Day day, boolean working)\n {\n setWorkingDay(day, (working ? DayType.WORKING : DayType.NON_WORKING));\n }" ]
Build and return a foreign collection based on the field settings that matches the id argument. This can return null in certain circumstances. @param parent The parent object that we will set on each item in the collection. @param id The id of the foreign object we will look for. This can be null if we are creating an empty collection.
[ "public <FT, FID> BaseForeignCollection<FT, FID> buildForeignCollection(Object parent, FID id) throws SQLException {\n\t\t// this can happen if we have a foreign-auto-refresh scenario\n\t\tif (foreignFieldType == null) {\n\t\t\treturn null;\n\t\t}\n\t\t@SuppressWarnings(\"unchecked\")\n\t\tDao<FT, FID> castDao = (Dao<FT, FID>) foreignDao;\n\t\tif (!fieldConfig.isForeignCollectionEager()) {\n\t\t\t// we know this won't go recursive so no need for the counters\n\t\t\treturn new LazyForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(), fieldConfig.isForeignCollectionOrderAscending());\n\t\t}\n\n\t\t// try not to create level counter objects unless we have to\n\t\tLevelCounters levelCounters = threadLevelCounters.get();\n\t\tif (levelCounters == null) {\n\t\t\tif (fieldConfig.getForeignCollectionMaxEagerLevel() == 0) {\n\t\t\t\t// then return a lazy collection instead\n\t\t\t\treturn new LazyForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(),\n\t\t\t\t\t\tfieldConfig.isForeignCollectionOrderAscending());\n\t\t\t}\n\t\t\tlevelCounters = new LevelCounters();\n\t\t\tthreadLevelCounters.set(levelCounters);\n\t\t}\n\n\t\tif (levelCounters.foreignCollectionLevel == 0) {\n\t\t\tlevelCounters.foreignCollectionLevelMax = fieldConfig.getForeignCollectionMaxEagerLevel();\n\t\t}\n\t\t// are we over our level limit?\n\t\tif (levelCounters.foreignCollectionLevel >= levelCounters.foreignCollectionLevelMax) {\n\t\t\t// then return a lazy collection instead\n\t\t\treturn new LazyForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(), fieldConfig.isForeignCollectionOrderAscending());\n\t\t}\n\t\tlevelCounters.foreignCollectionLevel++;\n\t\ttry {\n\t\t\treturn new EagerForeignCollection<FT, FID>(castDao, parent, id, foreignFieldType,\n\t\t\t\t\tfieldConfig.getForeignCollectionOrderColumnName(), fieldConfig.isForeignCollectionOrderAscending());\n\t\t} finally {\n\t\t\tlevelCounters.foreignCollectionLevel--;\n\t\t}\n\t}" ]
[ "public ItemRequest<Task> addProject(String task) {\n \n String path = String.format(\"/tasks/%s/addProject\", task);\n return new ItemRequest<Task>(this, Task.class, path, \"POST\");\n }", "protected void fixIntegerPrecisions(ItemIdValue itemIdValue,\n\t\t\tString propertyId) {\n\n\t\tString qid = itemIdValue.getId();\n\n\t\ttry {\n\t\t\t// Fetch the online version of the item to make sure we edit the\n\t\t\t// current version:\n\t\t\tItemDocument currentItemDocument = (ItemDocument) dataFetcher\n\t\t\t\t\t.getEntityDocument(qid);\n\t\t\tif (currentItemDocument == null) {\n\t\t\t\tSystem.out.println(\"*** \" + qid\n\t\t\t\t\t\t+ \" could not be fetched. Maybe it has been deleted.\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t// Get the current statements for the property we want to fix:\n\t\t\tStatementGroup editPropertyStatements = currentItemDocument\n\t\t\t\t\t.findStatementGroup(propertyId);\n\t\t\tif (editPropertyStatements == null) {\n\t\t\t\tSystem.out.println(\"*** \" + qid\n\t\t\t\t\t\t+ \" no longer has any statements for \" + propertyId);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tPropertyIdValue property = Datamodel\n\t\t\t\t\t.makeWikidataPropertyIdValue(propertyId);\n\t\t\tList<Statement> updateStatements = new ArrayList<>();\n\t\t\tfor (Statement s : editPropertyStatements) {\n\t\t\t\tQuantityValue qv = (QuantityValue) s.getValue();\n\t\t\t\tif (qv != null && isPlusMinusOneValue(qv)) {\n\t\t\t\t\tQuantityValue exactValue = Datamodel.makeQuantityValue(\n\t\t\t\t\t\t\tqv.getNumericValue(), qv.getNumericValue(),\n\t\t\t\t\t\t\tqv.getNumericValue());\n\t\t\t\t\tStatement exactStatement = StatementBuilder\n\t\t\t\t\t\t\t.forSubjectAndProperty(itemIdValue, property)\n\t\t\t\t\t\t\t.withValue(exactValue).withId(s.getStatementId())\n\t\t\t\t\t\t\t.withQualifiers(s.getQualifiers())\n\t\t\t\t\t\t\t.withReferences(s.getReferences())\n\t\t\t\t\t\t\t.withRank(s.getRank()).build();\n\t\t\t\t\tupdateStatements.add(exactStatement);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (updateStatements.size() == 0) {\n\t\t\t\tSystem.out.println(\"*** \" + qid + \" quantity values for \"\n\t\t\t\t\t\t+ propertyId + \" already fixed\");\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tlogEntityModification(currentItemDocument.getEntityId(),\n\t\t\t\t\tupdateStatements, propertyId);\n\n\t\t\tdataEditor.updateStatements(currentItemDocument, updateStatements,\n\t\t\t\t\tCollections.<Statement> emptyList(),\n\t\t\t\t\t\"Set exact values for [[Property:\" + propertyId + \"|\"\n\t\t\t\t\t\t\t+ propertyId + \"]] integer quantities (Task MB2)\");\n\n\t\t} catch (MediaWikiApiErrorException e) {\n\t\t\te.printStackTrace();\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "@Override\n public void setActive(boolean active) {\n this.active = active;\n\n if (parent != null) {\n fireCollapsibleHandler();\n removeStyleName(CssName.ACTIVE);\n if (header != null) {\n header.removeStyleName(CssName.ACTIVE);\n }\n if (active) {\n if (parent != null && parent.isAccordion()) {\n parent.clearActive();\n }\n addStyleName(CssName.ACTIVE);\n\n if (header != null) {\n header.addStyleName(CssName.ACTIVE);\n }\n }\n\n if (body != null) {\n body.setDisplay(active ? Display.BLOCK : Display.NONE);\n }\n } else {\n GWT.log(\"Please make sure that the Collapsible parent is attached or existed.\", new IllegalStateException());\n }\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 }", "private void writeCustomInfo(Event event) {\n // insert customInfo (key/value) into DB\n for (Map.Entry<String, String> customInfo : event.getCustomInfo().entrySet()) {\n long cust_id = dbDialect.getIncrementer().nextLongValue();\n getJdbcTemplate()\n .update(\"insert into EVENTS_CUSTOMINFO (ID, EVENT_ID, CUST_KEY, CUST_VALUE)\"\n + \" values (?,?,?,?)\",\n cust_id, event.getPersistedId(), customInfo.getKey(), customInfo.getValue());\n }\n }", "public JsonNode wbSetAliases(String id, String site, String title,\n\t\t\tString newEntity, String language, List<String> add,\n\t\t\tList<String> remove, List<String> set,\n\t\t\tboolean bot, long baserevid, String summary)\n\t\t\t\t\tthrows IOException, MediaWikiApiErrorException {\n\t\tValidate.notNull(language,\n\t\t\t\t\"Language parameter cannot be null when setting aliases\");\n\t\t\n\t\tMap<String, String> parameters = new HashMap<String, String>();\n\t\tparameters.put(\"language\", language);\n\t\tif (set != null) {\n\t\t\tif (add != null || remove != null) {\n\t\t\t\tthrow new IllegalArgumentException(\n\t\t\t\t\t\t\"Cannot use parameters \\\"add\\\" or \\\"remove\\\" when using \\\"set\\\" to edit aliases\");\n\t\t\t}\n\t\t\tparameters.put(\"set\", ApiConnection.implodeObjects(set));\n\t\t}\n\t\tif (add != null) {\n\t\t\tparameters.put(\"add\", ApiConnection.implodeObjects(add));\n\t\t}\n\t\tif (remove != null) {\n\t\t\tparameters.put(\"remove\", ApiConnection.implodeObjects(remove));\n\t\t}\n\t\t\n\t\tJsonNode response = performAPIAction(\"wbsetaliases\", id, site, title, newEntity, parameters, summary, baserevid, bot);\n\t\treturn response;\n\t}", "public IndirectionHandler getIndirectionHandler(Object obj)\r\n {\r\n if(obj == null)\r\n {\r\n return null;\r\n }\r\n else if(isNormalOjbProxy(obj))\r\n {\r\n return getDynamicIndirectionHandler(obj);\r\n }\r\n else if(isVirtualOjbProxy(obj))\r\n {\r\n return VirtualProxy.getIndirectionHandler((VirtualProxy) obj);\r\n }\r\n else\r\n {\r\n return null;\r\n }\r\n\r\n }", "private void validationRelations(Task task)\n {\n List<Relation> predecessors = task.getPredecessors();\n if (!predecessors.isEmpty())\n {\n ArrayList<Relation> invalid = new ArrayList<Relation>();\n for (Relation relation : predecessors)\n {\n Task sourceTask = relation.getSourceTask();\n Task targetTask = relation.getTargetTask();\n\n String sourceOutlineNumber = sourceTask.getOutlineNumber();\n String targetOutlineNumber = targetTask.getOutlineNumber();\n\n if (sourceOutlineNumber != null && targetOutlineNumber != null && sourceOutlineNumber.startsWith(targetOutlineNumber + '.'))\n {\n invalid.add(relation);\n }\n }\n\n for (Relation relation : invalid)\n {\n relation.getSourceTask().removePredecessor(relation.getTargetTask(), relation.getType(), relation.getLag());\n }\n }\n }", "public static DMatrixSparseTriplet uniform(int numRows , int numCols , int nz_total ,\n double min , double max , Random rand ) {\n // Create a list of all the possible element values\n int N = numCols*numRows;\n if( N < 0 )\n throw new IllegalArgumentException(\"matrix size is too large\");\n nz_total = Math.min(N,nz_total);\n\n int selected[] = new int[N];\n for (int i = 0; i < N; i++) {\n selected[i] = i;\n }\n\n for (int i = 0; i < nz_total; i++) {\n int s = rand.nextInt(N);\n int tmp = selected[s];\n selected[s] = selected[i];\n selected[i] = tmp;\n }\n\n // Create a sparse matrix\n DMatrixSparseTriplet ret = new DMatrixSparseTriplet(numRows,numCols,nz_total);\n\n for (int i = 0; i < nz_total; i++) {\n int row = selected[i]/numCols;\n int col = selected[i]%numCols;\n\n double value = rand.nextDouble()*(max-min)+min;\n\n ret.addItem(row,col, value);\n }\n\n return ret;\n }" ]
Maps all views that don't start with "android" namespace. @param names All shared element names. @return The obsolete shared element names.
[ "@NonNull\n private List<String> mapObsoleteElements(List<String> names) {\n List<String> elementsToRemove = new ArrayList<>(names.size());\n for (String name : names) {\n if (name.startsWith(\"android\")) continue;\n elementsToRemove.add(name);\n }\n return elementsToRemove;\n }" ]
[ "protected synchronized void doWriteObjects(boolean isFlush) throws TransactionAbortedException, LockNotGrantedException\r\n {\r\n /*\r\n arminw:\r\n if broker isn't in PB-tx, start tx\r\n */\r\n if (!getBroker().isInTransaction())\r\n {\r\n if (log.isDebugEnabled()) log.debug(\"call beginTransaction() on PB instance\");\r\n broker.beginTransaction();\r\n }\r\n\r\n // Notify objects of impending commits.\r\n performTransactionAwareBeforeCommit();\r\n\r\n // Now perfom the real work\r\n objectEnvelopeTable.writeObjects(isFlush);\r\n // now we have to perform the named objects\r\n namedRootsMap.performDeletion();\r\n namedRootsMap.performInsert();\r\n namedRootsMap.afterWriteCleanup();\r\n }", "private void performSetupExchange() throws IOException {\n Message setupRequest = new Message(0xfffffffeL, Message.KnownType.SETUP_REQ, new NumberField(posingAsPlayer, 4));\n sendMessage(setupRequest);\n Message response = Message.read(is);\n if (response.knownType != Message.KnownType.MENU_AVAILABLE) {\n throw new IOException(\"Did not receive message type 0x4000 in response to setup message, got: \" + response);\n }\n if (response.arguments.size() != 2) {\n throw new IOException(\"Did not receive two arguments in response to setup message, got: \" + response);\n }\n final Field player = response.arguments.get(1);\n if (!(player instanceof NumberField)) {\n throw new IOException(\"Second argument in response to setup message was not a number: \" + response);\n }\n if (((NumberField)player).getValue() != targetPlayer) {\n throw new IOException(\"Expected to connect to player \" + targetPlayer +\n \", but welcome response identified itself as player \" + ((NumberField)player).getValue());\n }\n }", "protected void setRandom(double lower, double upper, Random generator) {\n double range = upper - lower;\n\n x = generator.nextDouble() * range + lower;\n y = generator.nextDouble() * range + lower;\n z = generator.nextDouble() * range + lower;\n }", "protected final void verify() {\n collectInitialisers();\n verifyCandidates();\n verifyInitialisers();\n collectPossibleInitialValues();\n verifyPossibleInitialValues();\n collectEffectiveAssignmentInstructions();\n verifyEffectiveAssignmentInstructions();\n collectAssignmentGuards();\n verifyAssignmentGuards();\n end();\n }", "public Set<String> getTags() {\r\n Set<String> tags = new HashSet<String>(classIndex.objectsList());\r\n tags.remove(flags.backgroundSymbol);\r\n return tags;\r\n }", "@Nullable\n public static LocationEngineResult extractResult(Intent intent) {\n LocationEngineResult result = null;\n if (isOnClasspath(GOOGLE_PLAY_LOCATION_RESULT)) {\n result = extractGooglePlayResult(intent);\n }\n return result == null ? extractAndroidResult(intent) : result;\n }", "public Weld property(String key, Object value) {\n properties.put(key, value);\n return this;\n }", "private static Version getDockerVersion(String serverUrl) {\n try {\n DockerClient client = DockerClientBuilder.getInstance(serverUrl).build();\n return client.versionCmd().exec();\n } catch (Exception e) {\n return null;\n }\n }", "public void addNotBetween(Object attribute, Object value1, Object value2)\r\n {\r\n // PAW\r\n\t\t// addSelectionCriteria(ValueCriteria.buildNotBeweenCriteria(attribute, value1, value2, getAlias()));\r\n\t\taddSelectionCriteria(ValueCriteria.buildNotBeweenCriteria(attribute, value1, value2, getUserAlias(attribute)));\r\n }" ]
Returns a date and time string which is formatted as ISO-8601.
[ "@JsonProperty\n public String timestamp() {\n if (timestampAsText == null) {\n timestampAsText = DateTimeFormatter.ISO_INSTANT.format(timestamp);\n }\n return timestampAsText;\n }" ]
[ "private void addSequence(String sequenceName, HighLowSequence seq)\r\n {\r\n // lookup the sequence map for calling DB\r\n String jcdAlias = getBrokerForClass()\r\n .serviceConnectionManager().getConnectionDescriptor().getJcdAlias();\r\n Map mapForDB = (Map) sequencesDBMap.get(jcdAlias);\r\n if(mapForDB == null)\r\n {\r\n mapForDB = new HashMap();\r\n }\r\n mapForDB.put(sequenceName, seq);\r\n sequencesDBMap.put(jcdAlias, mapForDB);\r\n }", "public static Chart getMSDLineWithActiveTransportModelChart(Trajectory t, int lagMin,\n\t\t\tint lagMax, double timelag, double diffusionCoefficient, double velocity) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tdouble[] modelData = new double[lagMax - lagMin + 1];\n\t\tMeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(\n\t\t\t\tt, lagMin);\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t\tmodelData[i - lagMin] = Math.pow(velocity*(i*timelag), 2) + 4*diffusionCoefficient*(i*timelag);//4 * D * Math.pow(i * timelag, a);\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\t\tchart.addSeries(\"y=4*D*t + (v*t)^2\", xData, modelData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}", "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 }", "public static String make512Safe(StringBuffer input, String newline) {\n\t\tStringBuilder result = new StringBuilder();\n\t\tString content = input.toString();\n\t\tString rest = content;\n\t\twhile (!rest.isEmpty()) {\n\t\t\tif (rest.contains(\"\\n\")) {\n\t\t\t\tString line = rest.substring(0, rest.indexOf(\"\\n\"));\n\t\t\t\trest = rest.substring(rest.indexOf(\"\\n\") + 1);\n\t\t\t\tif (line.length() > 1 && line.charAt(line.length() - 1) == '\\r')\n\t\t\t\t\tline = line.substring(0, line.length() - 1);\n\t\t\t\tappend512Safe(line, result, newline);\n\t\t\t} else {\n\t\t\t\tappend512Safe(rest, result, newline);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn result.toString();\n\t}", "public Widget addControl(String name, int resId, Widget.OnTouchListener listener, int position) {\n Widget control = findChildByName(name);\n if (control == null) {\n control = createControlWidget(resId, name, null);\n }\n setupControl(name, control, listener, position);\n return control;\n }", "public static Method getBridgeMethodTarget(Method someMethod) {\n TraitBridge annotation = someMethod.getAnnotation(TraitBridge.class);\n if (annotation==null) {\n return null;\n }\n Class aClass = annotation.traitClass();\n String desc = annotation.desc();\n for (Method method : aClass.getDeclaredMethods()) {\n String methodDescriptor = BytecodeHelper.getMethodDescriptor(method.getReturnType(), method.getParameterTypes());\n if (desc.equals(methodDescriptor)) {\n return method;\n }\n }\n return null;\n }", "public static base_responses update(nitro_service client, nslimitselector resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnslimitselector updateresources[] = new nslimitselector[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nslimitselector();\n\t\t\t\tupdateresources[i].selectorname = resources[i].selectorname;\n\t\t\t\tupdateresources[i].rule = resources[i].rule;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "private void addException(ProjectCalendar mpxjCalendar, net.sf.mpxj.ganttproject.schema.Date date)\n {\n String year = date.getYear();\n if (year == null || year.isEmpty())\n {\n // In order to process recurring exceptions using MPXJ, we need a start and end date\n // to constrain the number of dates we generate.\n // May need to pre-process the tasks in order to calculate a start and finish date.\n // TODO: handle recurring exceptions\n }\n else\n {\n Calendar calendar = DateHelper.popCalendar();\n calendar.set(Calendar.YEAR, Integer.parseInt(year));\n calendar.set(Calendar.MONTH, NumberHelper.getInt(date.getMonth()));\n calendar.set(Calendar.DAY_OF_MONTH, NumberHelper.getInt(date.getDate()));\n Date exceptionDate = calendar.getTime();\n DateHelper.pushCalendar(calendar);\n ProjectCalendarException exception = mpxjCalendar.addCalendarException(exceptionDate, exceptionDate);\n\n // TODO: not sure how NEUTRAL should be handled\n if (\"WORKING_DAY\".equals(date.getType()))\n {\n exception.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);\n exception.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);\n }\n }\n }", "public void createContainer(String container) {\n\n ContainerController controller = this.platformContainers.get(container);\n if (controller == null) {\n\n // TODO make this configurable\n Profile p = new ProfileImpl();\n p.setParameter(Profile.PLATFORM_ID, PLATFORM_ID);\n p.setParameter(Profile.MAIN_HOST, MAIN_HOST);\n p.setParameter(Profile.MAIN_PORT, MAIN_PORT);\n p.setParameter(Profile.LOCAL_HOST, MAIN_HOST);\n int port = Integer.parseInt(MAIN_PORT);\n port = port + 1 + this.platformContainers.size();\n p.setParameter(Profile.LOCAL_PORT, Integer.toString(port));\n p.setParameter(Profile.CONTAINER_NAME, container);\n logger.fine(\"Creating container \" + container + \"...\");\n ContainerController agentContainer = this.runtime\n .createAgentContainer(p);\n this.platformContainers.put(container, agentContainer);\n logger.fine(\"Container \" + container + \" created successfully.\");\n } else {\n logger.fine(\"Container \" + container + \" is already created.\");\n }\n\n }" ]
Use this API to fetch nstimer_binding resource of given name .
[ "public static nstimer_binding get(nitro_service service, String name) throws Exception{\n\t\tnstimer_binding obj = new nstimer_binding();\n\t\tobj.set_name(name);\n\t\tnstimer_binding response = (nstimer_binding) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "public static boolean isAscii(Slice utf8)\n {\n int length = utf8.length();\n int offset = 0;\n\n // Length rounded to 8 bytes\n int length8 = length & 0x7FFF_FFF8;\n for (; offset < length8; offset += 8) {\n if ((utf8.getLongUnchecked(offset) & TOP_MASK64) != 0) {\n return false;\n }\n }\n // Enough bytes left for 32 bits?\n if (offset + 4 < length) {\n if ((utf8.getIntUnchecked(offset) & TOP_MASK32) != 0) {\n return false;\n }\n\n offset += 4;\n }\n // Do the rest one by one\n for (; offset < length; offset++) {\n if ((utf8.getByteUnchecked(offset) & 0x80) != 0) {\n return false;\n }\n }\n\n return true;\n }", "public static List<String> getStoreNames(List<StoreDefinition> list, boolean ignoreViews) {\n List<String> storeNameSet = new ArrayList<String>();\n for(StoreDefinition def: list)\n if(!def.isView() || !ignoreViews)\n storeNameSet.add(def.getName());\n return storeNameSet;\n }", "private void checkModifications(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 HashMap features = new HashMap();\r\n FeatureDescriptorDef def;\r\n\r\n for (Iterator it = classDef.getFields(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n for (Iterator it = classDef.getReferences(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n for (Iterator it = classDef.getCollections(); it.hasNext();)\r\n {\r\n def = (FeatureDescriptorDef)it.next();\r\n features.put(def.getName(), def);\r\n }\r\n\r\n // now checking the modifications\r\n Properties mods;\r\n String modName;\r\n String propName;\r\n\r\n for (Iterator it = classDef.getModificationNames(); it.hasNext();)\r\n {\r\n modName = (String)it.next();\r\n if (!features.containsKey(modName))\r\n {\r\n throw new ConstraintException(\"Class \"+classDef.getName()+\" contains a modification for an unknown feature \"+modName);\r\n }\r\n def = (FeatureDescriptorDef)features.get(modName);\r\n if (def.getOriginal() == null)\r\n {\r\n throw new ConstraintException(\"Class \"+classDef.getName()+\" contains a modification for a feature \"+modName+\" that is not inherited but defined in the same class\");\r\n }\r\n // checking modification\r\n mods = classDef.getModification(modName);\r\n for (Iterator propIt = mods.keySet().iterator(); propIt.hasNext();)\r\n {\r\n propName = (String)propIt.next();\r\n if (!PropertyHelper.isPropertyAllowed(def.getClass(), propName))\r\n {\r\n throw new ConstraintException(\"The modification of attribute \"+propName+\" in class \"+classDef.getName()+\" is not applicable to the feature \"+modName);\r\n }\r\n }\r\n }\r\n }", "public static final UUID getUUID(InputStream is) throws IOException\n {\n byte[] data = new byte[16];\n is.read(data);\n\n long long1 = 0;\n long1 |= ((long) (data[3] & 0xFF)) << 56;\n long1 |= ((long) (data[2] & 0xFF)) << 48;\n long1 |= ((long) (data[1] & 0xFF)) << 40;\n long1 |= ((long) (data[0] & 0xFF)) << 32;\n long1 |= ((long) (data[5] & 0xFF)) << 24;\n long1 |= ((long) (data[4] & 0xFF)) << 16;\n long1 |= ((long) (data[7] & 0xFF)) << 8;\n long1 |= ((long) (data[6] & 0xFF)) << 0;\n\n long long2 = 0;\n long2 |= ((long) (data[8] & 0xFF)) << 56;\n long2 |= ((long) (data[9] & 0xFF)) << 48;\n long2 |= ((long) (data[10] & 0xFF)) << 40;\n long2 |= ((long) (data[11] & 0xFF)) << 32;\n long2 |= ((long) (data[12] & 0xFF)) << 24;\n long2 |= ((long) (data[13] & 0xFF)) << 16;\n long2 |= ((long) (data[14] & 0xFF)) << 8;\n long2 |= ((long) (data[15] & 0xFF)) << 0;\n\n return new UUID(long1, long2);\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}", "public ValueContainer[] getKeyValues(ClassDescriptor cld, Identity oid) throws PersistenceBrokerException\r\n {\r\n return getKeyValues(cld, oid, true);\r\n }", "public static int toIntWithDefault(String value, int defaultValue) {\n\n int result = defaultValue;\n try {\n result = Integer.parseInt(value);\n } catch (@SuppressWarnings(\"unused\") Exception e) {\n // Do nothing, return default.\n }\n return result;\n }", "synchronized void removeEvents(Table table) {\n final String tName = table.getName();\n\n try {\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n db.delete(tName, null, null);\n } catch (final SQLiteException e) {\n getConfigLogger().verbose(\"Error removing all events from table \" + tName + \" Recreating DB\");\n deleteDB();\n } finally {\n dbHelper.close();\n }\n }", "public void addProducer(Broker broker) {\n Properties props = new Properties();\n props.put(\"host\", broker.host);\n props.put(\"port\", \"\" + broker.port);\n props.putAll(config.getProperties());\n if (sync) {\n SyncProducer producer = new SyncProducer(new SyncProducerConfig(props));\n logger.info(\"Creating sync producer for broker id = \" + broker.id + \" at \" + broker.host + \":\" + broker.port);\n syncProducers.put(broker.id, producer);\n } else {\n AsyncProducer<V> producer = new AsyncProducer<V>(new AsyncProducerConfig(props),//\n new SyncProducer(new SyncProducerConfig(props)),//\n serializer,//\n eventHandler,//\n config.getEventHandlerProperties(),//\n this.callbackHandler, //\n config.getCbkHandlerProperties());\n producer.start();\n logger.info(\"Creating async producer for broker id = \" + broker.id + \" at \" + broker.host + \":\" + broker.port);\n asyncProducers.put(broker.id, producer);\n }\n }" ]
Formats a resource type. @param resource MPXJ resource @return Primavera resource type
[ "private String getResourceType(Resource resource)\n {\n String result;\n net.sf.mpxj.ResourceType type = resource.getType();\n if (type == null)\n {\n type = net.sf.mpxj.ResourceType.WORK;\n }\n\n switch (type)\n {\n case MATERIAL:\n {\n result = \"Material\";\n break;\n }\n\n case COST:\n {\n result = \"Nonlabor\";\n break;\n }\n\n default:\n {\n result = \"Labor\";\n break;\n }\n }\n\n return result;\n }" ]
[ "@NonNull\n @UiThread\n private HashMap<Integer, Boolean> generateExpandedStateMap() {\n HashMap<Integer, Boolean> parentHashMap = new HashMap<>();\n int childCount = 0;\n\n int listItemCount = mFlatItemList.size();\n for (int i = 0; i < listItemCount; i++) {\n if (mFlatItemList.get(i) != null) {\n ExpandableWrapper<P, C> listItem = mFlatItemList.get(i);\n if (listItem.isParent()) {\n parentHashMap.put(i - childCount, listItem.isExpanded());\n } else {\n childCount++;\n }\n }\n }\n\n return parentHashMap;\n }", "public static HashMap<String, JSONObject> flatRessources(JSONObject object) throws JSONException {\n HashMap<String, JSONObject> result = new HashMap<String, JSONObject>();\n\n // no cycle in hierarchies!!\n if (object.has(\"resourceId\") && object.has(\"childShapes\")) {\n result.put(object.getString(\"resourceId\"),\n object);\n JSONArray childShapes = object.getJSONArray(\"childShapes\");\n for (int i = 0; i < childShapes.length(); i++) {\n result.putAll(flatRessources(childShapes.getJSONObject(i)));\n }\n }\n ;\n\n return result;\n }", "public int update(DatabaseConnection databaseConnection, PreparedUpdate<T> preparedUpdate) throws SQLException {\n\t\tCompiledStatement compiledStatement = preparedUpdate.compile(databaseConnection, StatementType.UPDATE);\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}", "public int checkIn() {\n\n try {\n synchronized (STATIC_LOCK) {\n m_logStream = new PrintStream(new FileOutputStream(DEFAULT_LOGFILE_PATH, false));\n CmsObject cms = getCmsObject();\n if (cms != null) {\n return checkInInternal();\n } else {\n m_logStream.println(\"No CmsObject given. Did you call init() first?\");\n return -1;\n }\n }\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n return -2;\n }\n }", "private void readRecurringData(ProjectCalendarException bce, Project.Calendars.Calendar.Exceptions.Exception exception)\n {\n RecurrenceType rt = getRecurrenceType(NumberHelper.getInt(exception.getType()));\n if (rt != null)\n {\n RecurringData rd = new RecurringData();\n rd.setStartDate(bce.getFromDate());\n rd.setFinishDate(bce.getToDate());\n rd.setRecurrenceType(rt);\n rd.setRelative(getRelative(NumberHelper.getInt(exception.getType())));\n rd.setOccurrences(NumberHelper.getInteger(exception.getOccurrences()));\n\n switch (rd.getRecurrenceType())\n {\n case DAILY:\n {\n rd.setFrequency(getFrequency(exception));\n break;\n }\n\n case WEEKLY:\n {\n rd.setWeeklyDaysFromBitmap(NumberHelper.getInteger(exception.getDaysOfWeek()), DAY_MASKS);\n rd.setFrequency(getFrequency(exception));\n break;\n }\n\n case MONTHLY:\n {\n if (rd.getRelative())\n {\n rd.setDayOfWeek(Day.getInstance(NumberHelper.getInt(exception.getMonthItem()) - 2));\n rd.setDayNumber(Integer.valueOf(NumberHelper.getInt(exception.getMonthPosition()) + 1));\n }\n else\n {\n rd.setDayNumber(NumberHelper.getInteger(exception.getMonthDay()));\n }\n rd.setFrequency(getFrequency(exception));\n break;\n }\n\n case YEARLY:\n {\n if (rd.getRelative())\n {\n rd.setDayOfWeek(Day.getInstance(NumberHelper.getInt(exception.getMonthItem()) - 2));\n rd.setDayNumber(Integer.valueOf(NumberHelper.getInt(exception.getMonthPosition()) + 1));\n }\n else\n {\n rd.setDayNumber(NumberHelper.getInteger(exception.getMonthDay()));\n }\n rd.setMonthNumber(Integer.valueOf(NumberHelper.getInt(exception.getMonth()) + 1));\n break;\n }\n }\n\n if (rd.getRecurrenceType() != RecurrenceType.DAILY || rd.getDates().length > 1)\n {\n bce.setRecurring(rd);\n }\n }\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 nstrafficdomain_binding get(nitro_service service, Long td) throws Exception{\n\t\tnstrafficdomain_binding obj = new nstrafficdomain_binding();\n\t\tobj.set_td(td);\n\t\tnstrafficdomain_binding response = (nstrafficdomain_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "private Task findChildTaskByUUID(ChildTaskContainer parent, UUID uuid)\n {\n Task result = null;\n\n for (Task task : parent.getChildTasks())\n {\n if (uuid.equals(task.getGUID()))\n {\n result = task;\n break;\n }\n }\n\n return result;\n }", "protected List<Object> executeProcessors(final List<Object> processedColumns, final CellProcessor[] processors) {\n\t\tUtil.executeCellProcessors(processedColumns, getColumns(), processors, getLineNumber(), getRowNumber());\n\t\treturn processedColumns;\n\t}" ]
Will prompt a user the "Add to Homescreen" feature @param callback A callback function after the method has been executed.
[ "public void installApp(Functions.Func callback) {\n if (isPwaSupported()) {\n appInstaller = new AppInstaller(callback);\n appInstaller.prompt();\n }\n }" ]
[ "public static Node updateNode(Node node, List<Integer> partitionsList) {\n return new Node(node.getId(),\n node.getHost(),\n node.getHttpPort(),\n node.getSocketPort(),\n node.getAdminPort(),\n node.getZoneId(),\n partitionsList);\n }", "public int[] sampleBatchWithoutReplacement() {\n int[] batch = new int[batchSize];\n for (int i=0; i<batch.length; i++) {\n if (cur == indices.length) {\n cur = 0;\n }\n if (cur == 0) {\n IntArrays.shuffle(indices);\n }\n batch[i] = indices[cur++];\n }\n return batch;\n }", "@VisibleForTesting\n @Nullable\n protected LineSymbolizer createLineSymbolizer(final PJsonObject styleJson) {\n final Stroke stroke = createStroke(styleJson, true);\n if (stroke == null) {\n return null;\n } else {\n return this.styleBuilder.createLineSymbolizer(stroke);\n }\n }", "@Override\n public DMatrixRMaj getV(DMatrixRMaj V , boolean transpose , boolean compact ) {\n V = handleV(V, transpose, compact,m,n,min);\n CommonOps_DDRM.setIdentity(V);\n\n// UBV.print();\n\n // todo the very first multiplication can be avoided by setting to the rank1update output\n for( int j = min-1; j >= 0; j-- ) {\n u[j+1] = 1;\n for( int i = j+2; i < n; i++ ) {\n u[i] = UBV.get(j,i);\n }\n if( transpose )\n QrHelperFunctions_DDRM.rank1UpdateMultL(V, u, gammasV[j], j + 1, j + 1, n);\n else\n QrHelperFunctions_DDRM.rank1UpdateMultR(V, u, gammasV[j], j + 1, j + 1, n, this.b);\n }\n\n return V;\n }", "protected void endDragging(MouseUpEvent event) {\n\n m_dragging = false;\n DOM.releaseCapture(getElement());\n removeStyleName(I_CmsLayoutBundle.INSTANCE.dialogCss().dragging());\n }", "public static void indexResourceRoot(final ResourceRoot resourceRoot) throws DeploymentUnitProcessingException {\n if (resourceRoot.getAttachment(Attachments.ANNOTATION_INDEX) != null) {\n return;\n }\n\n VirtualFile indexFile = resourceRoot.getRoot().getChild(ModuleIndexBuilder.INDEX_LOCATION);\n if (indexFile.exists()) {\n try {\n IndexReader reader = new IndexReader(indexFile.openStream());\n resourceRoot.putAttachment(Attachments.ANNOTATION_INDEX, reader.read());\n ServerLogger.DEPLOYMENT_LOGGER.tracef(\"Found and read index at: %s\", indexFile);\n return;\n } catch (Exception e) {\n ServerLogger.DEPLOYMENT_LOGGER.cannotLoadAnnotationIndex(indexFile.getPathName());\n }\n }\n\n // if this flag is present and set to false then do not index the resource\n Boolean shouldIndexResource = resourceRoot.getAttachment(Attachments.INDEX_RESOURCE_ROOT);\n if (shouldIndexResource != null && !shouldIndexResource) {\n return;\n }\n\n final List<String> indexIgnorePathList = resourceRoot.getAttachment(Attachments.INDEX_IGNORE_PATHS);\n final Set<String> indexIgnorePaths;\n if (indexIgnorePathList != null && !indexIgnorePathList.isEmpty()) {\n indexIgnorePaths = new HashSet<String>(indexIgnorePathList);\n } else {\n indexIgnorePaths = null;\n }\n\n final VirtualFile virtualFile = resourceRoot.getRoot();\n final Indexer indexer = new Indexer();\n try {\n final VisitorAttributes visitorAttributes = new VisitorAttributes();\n visitorAttributes.setLeavesOnly(true);\n visitorAttributes.setRecurseFilter(new VirtualFileFilter() {\n public boolean accepts(VirtualFile file) {\n return indexIgnorePaths == null || !indexIgnorePaths.contains(file.getPathNameRelativeTo(virtualFile));\n }\n });\n\n final List<VirtualFile> classChildren = virtualFile.getChildren(new SuffixMatchFilter(\".class\", visitorAttributes));\n for (VirtualFile classFile : classChildren) {\n InputStream inputStream = null;\n try {\n inputStream = classFile.openStream();\n indexer.index(inputStream);\n } catch (Exception e) {\n ServerLogger.DEPLOYMENT_LOGGER.cannotIndexClass(classFile.getPathNameRelativeTo(virtualFile), virtualFile.getPathName(), e);\n } finally {\n VFSUtils.safeClose(inputStream);\n }\n }\n final Index index = indexer.complete();\n resourceRoot.putAttachment(Attachments.ANNOTATION_INDEX, index);\n ServerLogger.DEPLOYMENT_LOGGER.tracef(\"Generated index for archive %s\", virtualFile);\n } catch (Throwable t) {\n throw ServerLogger.ROOT_LOGGER.deploymentIndexingFailed(t);\n }\n }", "private MBeanServer getServerForName(String name) {\n try {\n MBeanServer mbeanServer = null;\n final ObjectName objectNameQuery = new ObjectName(name + \":type=Service,*\");\n\n for (final MBeanServer server : MBeanServerFactory.findMBeanServer(null)) {\n if (server.queryNames(objectNameQuery, null).size() > 0) {\n mbeanServer = server;\n // we found it, bail out\n break;\n }\n }\n\n return mbeanServer;\n } catch (Exception e) {\n }\n\n return null;\n }", "public static final Double getPercentage(byte[] data, int offset)\n {\n int value = MPPUtility.getShort(data, offset);\n Double result = null;\n if (value >= 0 && value <= 100)\n {\n result = NumberHelper.getDouble(value);\n }\n return result;\n }", "private void setTasks(String tasks) {\n\t\tfor (String task : tasks.split(\",\")) {\n\t\t\tif (KNOWN_TASKS.containsKey(task)) {\n\t\t\t\tthis.tasks |= KNOWN_TASKS.get(task);\n\t\t\t\tthis.taskName += (this.taskName.isEmpty() ? \"\" : \"-\") + task;\n\t\t\t} else {\n\t\t\t\tlogger.warn(\"Unsupported RDF serialization task \\\"\" + task\n\t\t\t\t\t\t+ \"\\\". Run without specifying any tasks for help.\");\n\t\t\t}\n\t\t}\n\t}" ]
Stops the compressor.
[ "final void end() {\n final Thread thread = this.threadRef;\n this.keepRunning.set(false);\n if (thread != null) {\n // thread.interrupt();\n try {\n thread.join();\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n }\n this.threadRef = null;\n }" ]
[ "public Collection<Locale> getCountries() {\n Collection<Locale> result = get(KEY_QUERY_COUNTRIES, Collection.class);\n if (result == null) {\n return Collections.emptySet();\n }\n return result;\n }", "private void writeTasks(Project project)\n {\n Project.Tasks tasks = m_factory.createProjectTasks();\n project.setTasks(tasks);\n List<Project.Tasks.Task> list = tasks.getTask();\n\n for (Task task : m_projectFile.getTasks())\n {\n list.add(writeTask(task));\n }\n }", "private LoginContext getClientLoginContext() throws LoginException {\n Configuration config = new Configuration() {\n @Override\n public AppConfigurationEntry[] getAppConfigurationEntry(String name) {\n Map<String, String> options = new HashMap<String, String>();\n options.put(\"multi-threaded\", \"true\");\n options.put(\"restore-login-identity\", \"true\");\n\n AppConfigurationEntry clmEntry = new AppConfigurationEntry(ClientLoginModule.class.getName(), LoginModuleControlFlag.REQUIRED, options);\n return new AppConfigurationEntry[] { clmEntry };\n }\n };\n return getLoginContext(config);\n }", "public static void init(String jobId) {\n JobContext parent = current_.get();\n JobContext ctx = new JobContext(parent);\n current_.set(ctx);\n // don't call setJobId(String)\n // as it will trigger listeners -- TODO fix me\n ctx.jobId = jobId;\n if (null == parent) {\n Act.eventBus().trigger(new JobContextInitialized(ctx));\n }\n }", "public static base_response add(nitro_service client, policydataset resource) throws Exception {\n\t\tpolicydataset addresource = new policydataset();\n\t\taddresource.name = resource.name;\n\t\taddresource.type = resource.type;\n\t\taddresource.indextype = resource.indextype;\n\t\treturn addresource.add_resource(client);\n\t}", "public static Chart getMSDLineChart(Trajectory t, int lagMin, int lagMax,\n\t\t\tAbstractMeanSquaredDisplacmentEvaluator msdeval) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}", "public static Bitmap decodeStream(InputStream stream, boolean closeStream) {\n return AsyncBitmapTexture.decodeStream(stream,\n AsyncBitmapTexture.glMaxTextureSize,\n AsyncBitmapTexture.glMaxTextureSize, true, null, closeStream);\n }", "public List<Dependency> getModuleDependencies(final String moduleId, final FiltersHolder filters){\n final DbModule module = moduleHandler.getModule(moduleId);\n final DbOrganization organization = moduleHandler.getOrganization(module);\n filters.setCorporateFilter(new CorporateFilter(organization));\n\n return getModuleDependencies(module, filters, 1, new ArrayList<String>());\n }", "public static String truncate(int n, int smallestDigit, int biggestDigit) {\r\n int numDigits = biggestDigit - smallestDigit + 1;\r\n char[] result = new char[numDigits];\r\n for (int j = 1; j < smallestDigit; j++) {\r\n n = n / 10;\r\n }\r\n for (int j = numDigits - 1; j >= 0; j--) {\r\n result[j] = Character.forDigit(n % 10, 10);\r\n n = n / 10;\r\n }\r\n return new String(result);\r\n }" ]
Populate a sorted list of custom fields to ensure that these fields are written to the file in a consistent order.
[ "private void populateSortedCustomFieldsList ()\n {\n m_sortedCustomFieldsList = new ArrayList<CustomField>();\n for (CustomField field : m_projectFile.getCustomFields())\n {\n FieldType fieldType = field.getFieldType();\n if (fieldType != null)\n {\n m_sortedCustomFieldsList.add(field);\n }\n }\n\n // Sort to ensure consistent order in file\n Collections.sort(m_sortedCustomFieldsList, new Comparator<CustomField>()\n {\n @Override public int compare(CustomField customField1, CustomField customField2)\n {\n FieldType o1 = customField1.getFieldType();\n FieldType o2 = customField2.getFieldType();\n String name1 = o1.getClass().getSimpleName() + \".\" + o1.getName() + \" \" + customField1.getAlias();\n String name2 = o2.getClass().getSimpleName() + \".\" + o2.getName() + \" \" + customField2.getAlias();\n return name1.compareTo(name2);\n }\n });\n }" ]
[ "@SafeVarargs\n public static <T> Set<T> create(final T... values) {\n Set<T> result = new HashSet<>(values.length);\n Collections.addAll(result, values);\n return result;\n }", "public Set<RGBColor> colours() {\n return stream().map(Pixel::toColor).collect(Collectors.toSet());\n }", "@Override\n public List<String> setTargetHostsFromLineByLineText(String sourcePath,\n HostsSourceType sourceType) throws TargetHostsLoadException {\n\n List<String> targetHosts = new ArrayList<String>();\n try {\n String content = getContentFromPath(sourcePath, sourceType);\n\n targetHosts = setTargetHostsFromString(content);\n\n } catch (IOException e) {\n throw new TargetHostsLoadException(\"IEException when reading \"\n + sourcePath, e);\n }\n\n return targetHosts;\n\n }", "public void updatePathOrder(int profileId, int[] pathOrder) {\n for (int i = 0; i < pathOrder.length; i++) {\n EditService.updatePathTable(Constants.PATH_PROFILE_PATH_ORDER, (i + 1), pathOrder[i]);\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 double[] formatTargetValuesForOptimizer() {\n\t\t//Put all values in an array for the optimizer.\n\t\tint numberOfMaturities = surface.getMaturities().length;\n\t\tdouble mats[] = surface.getMaturities();\n\n\t\tArrayList<Double> vals = new ArrayList<Double>();\n\n\t\tfor(int t = 0; t<numberOfMaturities; t++) {\n\t\t\tdouble mat = mats[t];\n\t\t\tdouble[] myStrikes = surface.getSurface().get(mat).getStrikes();\n\n\t\t\tOptionSmileData smileOfInterest = surface.getSurface().get(mat);\n\n\t\t\tfor(int k = 0; k < myStrikes.length; k++) {\n\t\t\t\tvals.add(smileOfInterest.getSmile().get(myStrikes[k]).getValue());\n\t\t\t}\n\n\t\t}\n\t\tDouble[] targetVals = new Double[vals.size()];\n\t\treturn ArrayUtils.toPrimitive(vals.toArray(targetVals));\n\t}", "public boolean canUpdateServer(ServerIdentity server) {\n if (!serverGroupName.equals(server.getServerGroupName()) || !servers.contains(server)) {\n throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.unknownServer(server);\n }\n\n if (!parent.canChildProceed())\n return false;\n\n synchronized (this) {\n return failureCount <= maxFailed;\n }\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 boolean decomposeSafe(DecompositionInterface<ZMatrixRMaj> decomposition, ZMatrixRMaj a) {\n\n if( decomposition.inputModified() ) {\n a = a.copy();\n }\n return decomposition.decompose(a);\n }" ]
Check if the current node is part of routing request based on cluster.xml or throw an exception. @param key The key we are checking @param routingStrategy The routing strategy @param currentNode Current node
[ "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 }" ]
[ "private void countGender(EntityIdValue gender, SiteRecord siteRecord) {\n\t\tInteger curValue = siteRecord.genderCounts.get(gender);\n\t\tif (curValue == null) {\n\t\t\tsiteRecord.genderCounts.put(gender, 1);\n\t\t} else {\n\t\t\tsiteRecord.genderCounts.put(gender, curValue + 1);\n\t\t}\n\t}", "public String getHostName() {\n if( addr instanceof NbtAddress ) {\n return ((NbtAddress)addr).getHostName();\n }\n return ((InetAddress)addr).getHostName();\n }", "private static void filter(String filename, String filtername) throws Exception\n {\n ProjectFile project = new UniversalProjectReader().read(filename);\n Filter filter = project.getFilters().getFilterByName(filtername);\n\n if (filter == null)\n {\n displayAvailableFilters(project);\n }\n else\n {\n System.out.println(filter);\n System.out.println();\n\n if (filter.isTaskFilter())\n {\n processTaskFilter(project, filter);\n }\n else\n {\n processResourceFilter(project, filter);\n }\n }\n }", "public void setPadding(float padding, Layout.Axis axis) {\n OrientedLayout layout = null;\n switch(axis) {\n case X:\n layout = mShiftLayout;\n break;\n case Y:\n layout = mShiftLayout;\n break;\n case Z:\n layout = mStackLayout;\n break;\n }\n if (layout != null) {\n if (!equal(layout.getDividerPadding(axis), padding)) {\n layout.setDividerPadding(padding, axis);\n\n if (layout.getOrientationAxis() == axis) {\n requestLayout();\n }\n }\n }\n\n }", "public List<Message> requestFolderMenuFrom(final SlotReference slotReference, final int sortOrder, final int folderId)\n throws Exception {\n\n ConnectionManager.ClientTask<List<Message>> task = new ConnectionManager.ClientTask<List<Message>>() {\n @Override\n public List<Message> useClient(Client client) throws Exception {\n if (client.tryLockingForMenuOperations(MetadataFinder.MENU_TIMEOUT, TimeUnit.SECONDS)) {\n try {\n logger.debug(\"Requesting Key menu.\");\n Message response = client.menuRequestTyped(Message.KnownType.FOLDER_MENU_REQ, Message.MenuIdentifier.MAIN_MENU, slotReference.slot,\n CdjStatus.TrackType.UNANALYZED, new NumberField(sortOrder), new NumberField(folderId), new NumberField(0xffffff));\n return client.renderMenuItems(Message.MenuIdentifier.MAIN_MENU, slotReference.slot, CdjStatus.TrackType.UNANALYZED, response);\n } finally {\n client.unlockForMenuOperations();\n }\n } else {\n throw new TimeoutException(\"Unable to lock player for menu operations.\");\n }\n }\n };\n\n return ConnectionManager.getInstance().invokeWithClientSession(slotReference.player, task, \"requesting folder menu\");\n }", "private void initDefaultScopeType(EnhancedAnnotation<T> annotatedAnnotation) {\n Set<Annotation> scopeTypes = new HashSet<Annotation>();\n scopeTypes.addAll(annotatedAnnotation.getMetaAnnotations(Scope.class));\n scopeTypes.addAll(annotatedAnnotation.getMetaAnnotations(NormalScope.class));\n if (scopeTypes.size() > 1) {\n throw MetadataLogger.LOG.multipleScopes(annotatedAnnotation);\n } else if (scopeTypes.size() == 1) {\n this.defaultScopeType = scopeTypes.iterator().next();\n }\n }", "public static void doExtendTraits(final ClassNode cNode, final SourceUnit unit, final CompilationUnit cu) {\n if (cNode.isInterface()) return;\n boolean isItselfTrait = Traits.isTrait(cNode);\n SuperCallTraitTransformer superCallTransformer = new SuperCallTraitTransformer(unit);\n if (isItselfTrait) {\n checkTraitAllowed(cNode, unit);\n return;\n }\n if (!cNode.getNameWithoutPackage().endsWith(Traits.TRAIT_HELPER)) {\n List<ClassNode> traits = findTraits(cNode);\n for (ClassNode trait : traits) {\n TraitHelpersTuple helpers = Traits.findHelpers(trait);\n applyTrait(trait, cNode, helpers);\n superCallTransformer.visitClass(cNode);\n if (unit!=null) {\n ASTTransformationCollectorCodeVisitor collector = new ASTTransformationCollectorCodeVisitor(unit, cu.getTransformLoader());\n collector.visitClass(cNode);\n }\n }\n }\n }", "public void setFieldConversionClassName(String fieldConversionClassName)\r\n {\r\n try\r\n {\r\n this.fieldConversion = (FieldConversion) ClassHelper.newInstance(fieldConversionClassName);\r\n }\r\n catch (Exception e)\r\n {\r\n throw new MetadataException(\r\n \"Could not instantiate FieldConversion class using default constructor\", e);\r\n }\r\n }", "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}" ]
Use this API to update Interface resources.
[ "public static base_responses update(nitro_service client, Interface resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tInterface updateresources[] = new Interface[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new Interface();\n\t\t\t\tupdateresources[i].id = resources[i].id;\n\t\t\t\tupdateresources[i].speed = resources[i].speed;\n\t\t\t\tupdateresources[i].duplex = resources[i].duplex;\n\t\t\t\tupdateresources[i].flowctl = resources[i].flowctl;\n\t\t\t\tupdateresources[i].autoneg = resources[i].autoneg;\n\t\t\t\tupdateresources[i].hamonitor = resources[i].hamonitor;\n\t\t\t\tupdateresources[i].tagall = resources[i].tagall;\n\t\t\t\tupdateresources[i].trunk = resources[i].trunk;\n\t\t\t\tupdateresources[i].lacpmode = resources[i].lacpmode;\n\t\t\t\tupdateresources[i].lacpkey = resources[i].lacpkey;\n\t\t\t\tupdateresources[i].lagtype = resources[i].lagtype;\n\t\t\t\tupdateresources[i].lacppriority = resources[i].lacppriority;\n\t\t\t\tupdateresources[i].lacptimeout = resources[i].lacptimeout;\n\t\t\t\tupdateresources[i].ifalias = resources[i].ifalias;\n\t\t\t\tupdateresources[i].throughput = resources[i].throughput;\n\t\t\t\tupdateresources[i].bandwidthhigh = resources[i].bandwidthhigh;\n\t\t\t\tupdateresources[i].bandwidthnormal = resources[i].bandwidthnormal;\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 isFinalVariable(DeclarationExpression declarationExpression, SourceCode sourceCode) {\r\n if (isFromGeneratedSourceCode(declarationExpression)) {\r\n return false;\r\n }\r\n List<Expression> variableExpressions = getVariableExpressions(declarationExpression);\r\n if (!variableExpressions.isEmpty()) {\r\n Expression variableExpression = variableExpressions.get(0);\r\n int startOfDeclaration = declarationExpression.getColumnNumber();\r\n int startOfVariableName = variableExpression.getColumnNumber();\r\n int sourceLineNumber = findFirstNonAnnotationLine(declarationExpression, sourceCode);\r\n String sourceLine = sourceCode.getLines().get(sourceLineNumber-1);\r\n\r\n String modifiers = (startOfDeclaration >= 0 && startOfVariableName >= 0 && sourceLine.length() >= startOfVariableName) ?\r\n sourceLine.substring(startOfDeclaration - 1, startOfVariableName - 1) : \"\";\r\n return modifiers.contains(\"final\");\r\n }\r\n return false;\r\n }", "public RandomVariable[] getGradient(){\r\n\r\n\t\t// for now let us take the case for output-dimension equal to one!\r\n\t\tint numberOfVariables = getNumberOfVariablesInList();\r\n\t\tint numberOfCalculationSteps = factory.getNumberOfEntriesInList();\r\n\r\n\t\tRandomVariable[] omega_hat = new RandomVariable[numberOfCalculationSteps];\r\n\r\n\t\t// first entry gets initialized\r\n\t\tomega_hat[numberOfCalculationSteps-1] = new RandomVariableFromDoubleArray(1.0);\r\n\r\n\t\t/*\r\n\t\t * TODO: Find way that calculations form here on are not 'recorded' by the factory\r\n\t\t * IDEA: Let the calculation below run on {@link RandomVariableFromDoubleArray}, ie cast everything down!\r\n\t\t * */\r\n\r\n\t\tfor(int functionIndex = numberOfCalculationSteps - 2; functionIndex > 0; functionIndex--){\r\n\t\t\t// apply chain rule\r\n\t\t\tomega_hat[functionIndex] = new RandomVariableFromDoubleArray(0.0);\r\n\r\n\t\t\t/*TODO: save all D_{i,j}*\\omega_j in vector and sum up later */\r\n\t\t\tfor(RandomVariableUniqueVariable parent:parentsVariables){\r\n\r\n\t\t\t\tint variableIndex = parent.getVariableID();\r\n\r\n\t\t\t\tomega_hat[functionIndex] = omega_hat[functionIndex].add(getPartialDerivative(functionIndex, variableIndex).mult(omega_hat[variableIndex]));\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t/* Due to the fact that we can still introduce 'new' true variables on the fly they are NOT the last couple of indices!\r\n\t\t * Thus save the indices of the true variables and recover them after finalizing all the calculations\r\n\t\t * IDEA: quit calculation after minimal true variable index is reached */\r\n\t\tRandomVariable[] gradient = new RandomVariable[numberOfVariables];\r\n\r\n\t\t/* TODO: sort array in correct manner! */\r\n\t\tint[] indicesOfVariables = getIDsOfVariablesInList();\r\n\r\n\t\tfor(int i = 0; i < numberOfVariables; i++){\r\n\t\t\tgradient[i] = omega_hat[numberOfCalculationSteps - numberOfVariables + indicesOfVariables[i]];\r\n\t\t}\r\n\r\n\t\treturn gradient;\r\n\t}", "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 StringConsumers buildConsumer(\n final String zookeeperConfig,//\n final String topic,//\n final String groupId, //\n final IMessageListener<String> listener) {\n return buildConsumer(zookeeperConfig, topic, groupId, listener, 2);\n }", "public double getProgressFromResponse(ResponseOnSingeRequest myResponse) {\n\n double progress = 0.0;\n try {\n\n if (myResponse == null || myResponse.isFailObtainResponse()) {\n return progress;\n }\n\n String responseBody = myResponse.getResponseBody();\n Pattern regex = Pattern.compile(progressRegex);\n Matcher matcher = regex.matcher(responseBody);\n if (matcher.matches()) {\n String progressStr = matcher.group(1);\n progress = Double.parseDouble(progressStr);\n }\n\n } catch (Exception t) {\n logger.error(\"fail \" + t);\n\n }\n\n return progress;\n }", "protected void deleteConflictingResources(CmsObject cms, CmsModule module, Map<CmsUUID, CmsUUID> conflictingIds)\n throws CmsException, Exception {\n\n CmsProject conflictProject = cms.createProject(\n \"Deletion of conflicting resources for \" + module.getName(),\n \"Deletion of conflicting resources for \" + module.getName(),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n OpenCms.getDefaultUsers().getGroupAdministrators(),\n CmsProject.PROJECT_TYPE_TEMPORARY);\n CmsObject deleteCms = OpenCms.initCmsObject(cms);\n deleteCms.getRequestContext().setCurrentProject(conflictProject);\n for (CmsUUID vfsId : conflictingIds.values()) {\n CmsResource toDelete = deleteCms.readResource(vfsId, CmsResourceFilter.ALL);\n lock(deleteCms, toDelete);\n deleteCms.deleteResource(toDelete, CmsResource.DELETE_PRESERVE_SIBLINGS);\n }\n OpenCms.getPublishManager().publishProject(deleteCms);\n OpenCms.getPublishManager().waitWhileRunning();\n }", "protected boolean isFirstVisit(Object expression) {\r\n if (visited.contains(expression)) {\r\n return false;\r\n }\r\n visited.add(expression);\r\n return true;\r\n }", "public void seekToDayOfMonth(String dayOfMonth) {\n int dayOfMonthInt = Integer.parseInt(dayOfMonth);\n assert(dayOfMonthInt >= 1 && dayOfMonthInt <= 31);\n \n markDateInvocation();\n \n dayOfMonthInt = Math.min(dayOfMonthInt, _calendar.getActualMaximum(Calendar.DAY_OF_MONTH));\n _calendar.set(Calendar.DAY_OF_MONTH, dayOfMonthInt);\n }", "private void readCalendar(Gantt gantt)\n {\n Gantt.Calendar ganttCalendar = gantt.getCalendar();\n m_projectFile.getProjectProperties().setWeekStartDay(ganttCalendar.getWeekStart());\n\n ProjectCalendar calendar = m_projectFile.addCalendar();\n calendar.setName(\"Standard\");\n m_projectFile.setDefaultCalendar(calendar);\n\n String workingDays = ganttCalendar.getWorkDays();\n calendar.setWorkingDay(Day.SUNDAY, workingDays.charAt(0) == '1');\n calendar.setWorkingDay(Day.MONDAY, workingDays.charAt(1) == '1');\n calendar.setWorkingDay(Day.TUESDAY, workingDays.charAt(2) == '1');\n calendar.setWorkingDay(Day.WEDNESDAY, workingDays.charAt(3) == '1');\n calendar.setWorkingDay(Day.THURSDAY, workingDays.charAt(4) == '1');\n calendar.setWorkingDay(Day.FRIDAY, workingDays.charAt(5) == '1');\n calendar.setWorkingDay(Day.SATURDAY, workingDays.charAt(6) == '1');\n\n for (int i = 1; i <= 7; i++)\n {\n Day day = Day.getInstance(i);\n ProjectCalendarHours hours = calendar.addCalendarHours(day);\n if (calendar.isWorkingDay(day))\n {\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);\n }\n }\n\n for (Gantt.Holidays.Holiday holiday : gantt.getHolidays().getHoliday())\n {\n ProjectCalendarException exception = calendar.addCalendarException(holiday.getDate(), holiday.getDate());\n exception.setName(holiday.getContent());\n }\n }" ]
Sets up this object to represent an argument that will be set to a constant value. @param constantValue the constant value.
[ "public void setValue(String constantValue)\r\n {\r\n this.fieldSource = SOURCE_VALUE;\r\n this.fieldRefName = null;\r\n this.returnedByProcedure = false;\r\n this.constantValue = constantValue;\r\n }" ]
[ "public static double normP1( DMatrixRMaj A ) {\n if( MatrixFeatures_DDRM.isVector(A)) {\n return CommonOps_DDRM.elementSumAbs(A);\n } else {\n return inducedP1(A);\n }\n }", "private Pair<Cluster, List<StoreDefinition>> getCurrentClusterState() {\n\n // Retrieve the latest cluster metadata from the existing nodes\n Versioned<Cluster> currentVersionedCluster = adminClient.rebalanceOps.getLatestCluster(Utils.nodeListToNodeIdList(Lists.newArrayList(adminClient.getAdminClientCluster()\n .getNodes())));\n Cluster cluster = currentVersionedCluster.getValue();\n List<StoreDefinition> storeDefs = adminClient.rebalanceOps.getCurrentStoreDefinitions(cluster);\n return new Pair<Cluster, List<StoreDefinition>>(cluster, storeDefs);\n }", "public static base_response add(nitro_service client, route6 resource) throws Exception {\n\t\troute6 addresource = new route6();\n\t\taddresource.network = resource.network;\n\t\taddresource.gateway = resource.gateway;\n\t\taddresource.vlan = resource.vlan;\n\t\taddresource.weight = resource.weight;\n\t\taddresource.distance = resource.distance;\n\t\taddresource.cost = resource.cost;\n\t\taddresource.advertise = resource.advertise;\n\t\taddresource.msr = resource.msr;\n\t\taddresource.monitor = resource.monitor;\n\t\taddresource.td = resource.td;\n\t\treturn addresource.add_resource(client);\n\t}", "public ThumborUrlBuilder resize(int width, int height) {\n if (width < 0 && width != ORIGINAL_SIZE) {\n throw new IllegalArgumentException(\"Width must be a positive number.\");\n }\n if (height < 0 && height != ORIGINAL_SIZE) {\n throw new IllegalArgumentException(\"Height must be a positive number.\");\n }\n if (width == 0 && height == 0) {\n throw new IllegalArgumentException(\"Both width and height must not be zero.\");\n }\n hasResize = true;\n resizeWidth = width;\n resizeHeight = height;\n return this;\n }", "static void tryAutoAttaching(final SlotReference slot) {\n if (!MetadataFinder.getInstance().getMountedMediaSlots().contains(slot)) {\n logger.error(\"Unable to auto-attach cache to empty slot {}\", slot);\n return;\n }\n if (MetadataFinder.getInstance().getMetadataCache(slot) != null) {\n logger.info(\"Not auto-attaching to slot {}; already has a cache attached.\", slot);\n return;\n }\n if (MetadataFinder.getInstance().getAutoAttachCacheFiles().isEmpty()) {\n logger.debug(\"No auto-attach files configured.\");\n return;\n }\n\n new Thread(new Runnable() {\n @Override\n public void run() {\n try {\n Thread.sleep(5); // Give us a chance to find out what type of media is in the new mount.\n final MediaDetails details = MetadataFinder.getInstance().getMediaDetailsFor(slot);\n if (details != null && details.mediaType == CdjStatus.TrackType.REKORDBOX) {\n // First stage attempt: See if we can match based on stored media details, which is both more reliable and\n // less disruptive than trying to sample the player database to compare entries.\n boolean attached = false;\n for (File file : MetadataFinder.getInstance().getAutoAttachCacheFiles()) {\n final MetadataCache cache = new MetadataCache(file);\n try {\n if (cache.sourceMedia != null && cache.sourceMedia.hashKey().equals(details.hashKey())) {\n // We found a solid match, no need to probe tracks.\n final boolean changed = cache.sourceMedia.hasChanged(details);\n logger.info(\"Auto-attaching metadata cache \" + cache.getName() + \" to slot \" + slot +\n \" based on media details \" + (changed? \"(changed since created)!\" : \"(unchanged).\"));\n MetadataFinder.getInstance().attachMetadataCacheInternal(slot, cache);\n attached = true;\n return;\n }\n } finally {\n if (!attached) {\n cache.close();\n }\n }\n }\n\n // Could not match based on media details; fall back to older method based on probing track metadata.\n ConnectionManager.ClientTask<Object> task = new ConnectionManager.ClientTask<Object>() {\n @Override\n public Object useClient(Client client) throws Exception {\n tryAutoAttachingWithConnection(slot, client);\n return null;\n }\n };\n ConnectionManager.getInstance().invokeWithClientSession(slot.player, task, \"trying to auto-attach metadata cache\");\n }\n } catch (Exception e) {\n logger.error(\"Problem trying to auto-attach metadata cache for slot \" + slot, e);\n }\n\n }\n }, \"Metadata cache file auto-attachment attempt\").start();\n }", "private void executeBatch(int batchId, final RebalanceBatchPlan batchPlan) {\n final Cluster batchCurrentCluster = batchPlan.getCurrentCluster();\n final List<StoreDefinition> batchCurrentStoreDefs = batchPlan.getCurrentStoreDefs();\n final Cluster batchFinalCluster = batchPlan.getFinalCluster();\n final List<StoreDefinition> batchFinalStoreDefs = batchPlan.getFinalStoreDefs();\n\n try {\n final List<RebalanceTaskInfo> rebalanceTaskInfoList = batchPlan.getBatchPlan();\n\n if(rebalanceTaskInfoList.isEmpty()) {\n RebalanceUtils.printBatchLog(batchId, logger, \"Skipping batch \"\n + batchId + \" since it is empty.\");\n // Even though there is no rebalancing work to do, cluster\n // metadata must be updated so that the server is aware of the\n // new cluster xml.\n adminClient.rebalanceOps.rebalanceStateChange(batchCurrentCluster,\n batchFinalCluster,\n batchCurrentStoreDefs,\n batchFinalStoreDefs,\n rebalanceTaskInfoList,\n false,\n true,\n false,\n false,\n true);\n return;\n }\n\n RebalanceUtils.printBatchLog(batchId, logger, \"Starting batch \"\n + batchId + \".\");\n\n // Split the store definitions\n List<StoreDefinition> readOnlyStoreDefs = StoreDefinitionUtils.filterStores(batchFinalStoreDefs,\n true);\n List<StoreDefinition> readWriteStoreDefs = StoreDefinitionUtils.filterStores(batchFinalStoreDefs,\n false);\n boolean hasReadOnlyStores = readOnlyStoreDefs != null\n && readOnlyStoreDefs.size() > 0;\n boolean hasReadWriteStores = readWriteStoreDefs != null\n && readWriteStoreDefs.size() > 0;\n\n // STEP 1 - Cluster state change\n boolean finishedReadOnlyPhase = false;\n List<RebalanceTaskInfo> filteredRebalancePartitionPlanList = RebalanceUtils.filterTaskPlanWithStores(rebalanceTaskInfoList,\n readOnlyStoreDefs);\n\n rebalanceStateChange(batchId,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n batchFinalCluster,\n batchFinalStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n\n // STEP 2 - Move RO data\n if(hasReadOnlyStores) {\n RebalanceBatchPlanProgressBar progressBar = batchPlan.getProgressBar(batchId);\n executeSubBatch(batchId,\n progressBar,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n }\n\n // STEP 3 - Cluster change state\n finishedReadOnlyPhase = true;\n filteredRebalancePartitionPlanList = RebalanceUtils.filterTaskPlanWithStores(rebalanceTaskInfoList,\n readWriteStoreDefs);\n\n rebalanceStateChange(batchId,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n batchFinalCluster,\n batchFinalStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n\n // STEP 4 - Move RW data\n if(hasReadWriteStores) {\n proxyPause();\n RebalanceBatchPlanProgressBar progressBar = batchPlan.getProgressBar(batchId);\n executeSubBatch(batchId,\n progressBar,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n }\n\n RebalanceUtils.printBatchLog(batchId,\n logger,\n \"Successfully terminated batch \"\n + batchId + \".\");\n\n } catch(Exception e) {\n RebalanceUtils.printErrorLog(batchId, logger, \"Error in batch \"\n + batchId + \" - \" + e.getMessage(), e);\n throw new VoldemortException(\"Rebalance failed on batch \" + batchId,\n e);\n }\n }", "private String appendXmlEndingTag(String value) {\r\n StringBuilder sb = new StringBuilder();\r\n sb.append(\"</\").append(value).append(\">\");\n\r\n return sb.toString();\r\n }", "public byte[] getByteArray(Integer id, Integer type)\n {\n return (getByteArray(m_meta.getOffset(id, type)));\n }", "public BlurBuilder contrast(float contrast) {\n data.preProcessors.add(new ContrastProcessor(data.contextWrapper.getRenderScript(), Math.max(Math.min(1500.f, contrast), -1500.f)));\n return this;\n }" ]
Adds a parameter to the argument list if the given integer is non-null. If the value is null, then the argument list remains unchanged.
[ "ArgumentsBuilder param(String param, Integer value) {\n if (value != null) {\n args.add(param);\n args.add(value.toString());\n }\n return this;\n }" ]
[ "public static int cudnnSoftmaxBackward(\n cudnnHandle handle, \n int algo, \n int mode, \n Pointer alpha, \n cudnnTensorDescriptor yDesc, \n Pointer y, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n Pointer beta, \n cudnnTensorDescriptor dxDesc, \n Pointer dx)\n {\n return checkResult(cudnnSoftmaxBackwardNative(handle, algo, mode, alpha, yDesc, y, dyDesc, dy, beta, dxDesc, dx));\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 void setDates(SortedSet<Date> dates) {\n\n if (!m_model.getIndividualDates().equals(dates)) {\n m_model.setIndividualDates(dates);\n onValueChange();\n }\n\n }", "private WeekDay readWeekDay(JSONValue val) throws IllegalArgumentException {\n\n String str = readOptionalString(val);\n if (null != str) {\n return WeekDay.valueOf(str);\n }\n throw new IllegalArgumentException();\n }", "@Override\n public CompletableFuture<Map<String, Change<?>>> diff(Revision from, Revision to, String pathPattern) {\n final ServiceRequestContext ctx = context();\n return CompletableFuture.supplyAsync(() -> {\n requireNonNull(from, \"from\");\n requireNonNull(to, \"to\");\n requireNonNull(pathPattern, \"pathPattern\");\n\n failFastIfTimedOut(this, logger, ctx, \"diff\", from, to, pathPattern);\n\n final RevisionRange range = normalizeNow(from, to).toAscending();\n readLock();\n try (RevWalk rw = new RevWalk(jGitRepository)) {\n final RevTree treeA = rw.parseTree(commitIdDatabase.get(range.from()));\n final RevTree treeB = rw.parseTree(commitIdDatabase.get(range.to()));\n\n // Compare the two Git trees.\n // Note that we do not cache here because CachingRepository caches the final result already.\n return toChangeMap(blockingCompareTreesUncached(treeA, treeB,\n pathPatternFilterOrTreeFilter(pathPattern)));\n } catch (StorageException e) {\n throw e;\n } catch (Exception e) {\n throw new StorageException(\"failed to parse two trees: range=\" + range, e);\n } finally {\n readUnlock();\n }\n }, repositoryWorker);\n }", "public static base_responses unset(nitro_service client, bridgetable resources[], String[] args) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tbridgetable unsetresources[] = new bridgetable[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tunsetresources[i] = new bridgetable();\n\t\t\t}\n\t\t\tresult = unset_bulk_request(client, unsetresources,args);\n\t\t}\n\t\treturn result;\n\t}", "protected final void setParentNode(final DiffNode parentNode)\n\t{\n\t\tif (this.parentNode != null && this.parentNode != parentNode)\n\t\t{\n\t\t\tthrow new IllegalStateException(\"The parent of a node cannot be changed, once it's set.\");\n\t\t}\n\t\tthis.parentNode = parentNode;\n\t}", "public static base_responses add(nitro_service client, clusterinstance resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tclusterinstance addresources[] = new clusterinstance[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\taddresources[i] = new clusterinstance();\n\t\t\t\taddresources[i].clid = resources[i].clid;\n\t\t\t\taddresources[i].deadinterval = resources[i].deadinterval;\n\t\t\t\taddresources[i].hellointerval = resources[i].hellointerval;\n\t\t\t\taddresources[i].preemption = resources[i].preemption;\n\t\t\t}\n\t\t\tresult = add_bulk_request(client, addresources);\n\t\t}\n\t\treturn result;\n\t}", "private void readAssignmentBaselines(Project.Assignments.Assignment assignment, ResourceAssignment mpx)\n {\n for (Project.Assignments.Assignment.Baseline baseline : assignment.getBaseline())\n {\n int number = NumberHelper.getInt(baseline.getNumber());\n\n //baseline.getBCWP()\n //baseline.getBCWS()\n Number cost = DatatypeConverter.parseExtendedAttributeCurrency(baseline.getCost());\n Date finish = DatatypeConverter.parseExtendedAttributeDate(baseline.getFinish());\n //baseline.getNumber()\n Date start = DatatypeConverter.parseExtendedAttributeDate(baseline.getStart());\n Duration work = DatatypeConverter.parseDuration(m_projectFile, TimeUnit.HOURS, baseline.getWork());\n\n if (number == 0)\n {\n mpx.setBaselineCost(cost);\n mpx.setBaselineFinish(finish);\n mpx.setBaselineStart(start);\n mpx.setBaselineWork(work);\n }\n else\n {\n mpx.setBaselineCost(number, cost);\n mpx.setBaselineWork(number, work);\n mpx.setBaselineStart(number, start);\n mpx.setBaselineFinish(number, finish);\n }\n }\n }" ]
Get a lower-scoped token restricted to a resource for the list of scopes that are passed. @param scopes the list of scopes to which the new token should be restricted for @param resource the resource for which the new token has to be obtained @return scopedToken which has access token and other details
[ "public ScopedToken getLowerScopedToken(List<String> scopes, String resource) {\n assert (scopes != null);\n assert (scopes.size() > 0);\n URL url = null;\n try {\n url = new URL(this.getTokenURL());\n } catch (MalformedURLException e) {\n assert false : \"An invalid refresh URL indicates a bug in the SDK.\";\n throw new RuntimeException(\"An invalid refresh URL indicates a bug in the SDK.\", e);\n }\n\n StringBuilder spaceSeparatedScopes = new StringBuilder();\n for (int i = 0; i < scopes.size(); i++) {\n spaceSeparatedScopes.append(scopes.get(i));\n if (i < scopes.size() - 1) {\n spaceSeparatedScopes.append(\" \");\n }\n }\n\n String urlParameters = null;\n\n if (resource != null) {\n //this.getAccessToken() ensures we have a valid access token\n urlParameters = String.format(\"grant_type=urn:ietf:params:oauth:grant-type:token-exchange\"\n + \"&subject_token_type=urn:ietf:params:oauth:token-type:access_token&subject_token=%s\"\n + \"&scope=%s&resource=%s\",\n this.getAccessToken(), spaceSeparatedScopes, resource);\n } else {\n //this.getAccessToken() ensures we have a valid access token\n urlParameters = String.format(\"grant_type=urn:ietf:params:oauth:grant-type:token-exchange\"\n + \"&subject_token_type=urn:ietf:params:oauth:token-type:access_token&subject_token=%s\"\n + \"&scope=%s\",\n this.getAccessToken(), spaceSeparatedScopes);\n }\n\n BoxAPIRequest request = new BoxAPIRequest(this, url, \"POST\");\n request.shouldAuthenticate(false);\n request.setBody(urlParameters);\n\n String json;\n try {\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n json = response.getJSON();\n } catch (BoxAPIException e) {\n this.notifyError(e);\n throw e;\n }\n\n JsonObject jsonObject = JsonObject.readFrom(json);\n ScopedToken token = new ScopedToken(jsonObject);\n token.setObtainedAt(System.currentTimeMillis());\n token.setExpiresIn(jsonObject.get(\"expires_in\").asLong() * 1000);\n return token;\n }" ]
[ "public static List<QuotaType> getQuotaTypes(List<String> strQuotaTypes) {\n if(strQuotaTypes.size() < 1) {\n throw new VoldemortException(\"Quota type not specified.\");\n }\n List<QuotaType> quotaTypes;\n if(strQuotaTypes.size() == 1 && strQuotaTypes.get(0).equals(AdminToolUtils.QUOTATYPE_ALL)) {\n quotaTypes = Arrays.asList(QuotaType.values());\n } else {\n quotaTypes = new ArrayList<QuotaType>();\n for(String strQuotaType: strQuotaTypes) {\n QuotaType type = QuotaType.valueOf(strQuotaType);\n quotaTypes.add(type);\n }\n }\n return quotaTypes;\n }", "public static void configureLogging() {\n\t\t// Create the appender that will write log messages to the console.\n\t\tConsoleAppender consoleAppender = new ConsoleAppender();\n\t\t// Define the pattern of log messages.\n\t\t// Insert the string \"%c{1}:%L\" to also show class name and line.\n\t\tString pattern = \"%d{yyyy-MM-dd HH:mm:ss} %-5p - %m%n\";\n\t\tconsoleAppender.setLayout(new PatternLayout(pattern));\n\t\t// Change to Level.ERROR for fewer messages:\n\t\tconsoleAppender.setThreshold(Level.INFO);\n\n\t\tconsoleAppender.activateOptions();\n\t\tLogger.getRootLogger().addAppender(consoleAppender);\n\t}", "public static nd6ravariables get(nitro_service service, Long vlan) throws Exception{\n\t\tnd6ravariables obj = new nd6ravariables();\n\t\tobj.set_vlan(vlan);\n\t\tnd6ravariables response = (nd6ravariables) obj.get_resource(service);\n\t\treturn response;\n\t}", "private void readTasks(Integer id)\n {\n Integer currentID = id;\n Table table = getTable(\"WBSTAB\");\n\n while (currentID.intValue() != 0)\n {\n MapRow row = table.find(currentID);\n Task task = m_projectFile.getTaskByUniqueID(row.getInteger(\"TASK_ID\"));\n readLeafTasks(task, row.getInteger(\"FIRST_CHILD_TASK_ID\"));\n Integer childID = row.getInteger(\"CHILD_ID\");\n if (childID.intValue() != 0)\n {\n readTasks(childID);\n }\n currentID = row.getInteger(\"NEXT_ID\");\n }\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 }", "@Override\n\tpublic List<String> contentTypes() {\n\t\tList<String> contentTypes = null;\n\t\tfinal HttpServletRequest request = getHttpRequest();\n\n\t\tif (favorParameterOverAcceptHeader) {\n\t\t\tcontentTypes = getFavoredParameterValueAsList(request);\n\t\t} else {\n\t\t\tcontentTypes = getAcceptHeaderValues(request);\n\t\t}\n\n\t\tif (isEmpty(contentTypes)) {\n\t\t\tlogger.debug(\"Setting content types to default: {}.\", DEFAULT_SUPPORTED_CONTENT_TYPES);\n\n\t\t\tcontentTypes = DEFAULT_SUPPORTED_CONTENT_TYPES;\n\t\t}\n\n\t\treturn unmodifiableList(contentTypes);\n\t}", "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 Script updateName(int id, String name) throws Exception {\n PreparedStatement statement = null;\n\n try (Connection sqlConnection = SQLService.getInstance().getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_SCRIPT +\n \" SET \" + Constants.SCRIPT_NAME + \" = ? \" +\n \" WHERE \" + Constants.GENERIC_ID + \" = ?\"\n );\n statement.setString(1, name);\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\n return this.getScript(id);\n }", "public static server_service_binding[] get(nitro_service service, String name) throws Exception{\n\t\tserver_service_binding obj = new server_service_binding();\n\t\tobj.set_name(name);\n\t\tserver_service_binding response[] = (server_service_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
Loads the favorite list. @return the list of favorites @throws CmsException if something goes wrong
[ "public List<CmsFavoriteEntry> loadFavorites() throws CmsException {\n\n List<CmsFavoriteEntry> result = new ArrayList<>();\n try {\n CmsUser user = readUser();\n String data = (String)user.getAdditionalInfo(ADDINFO_KEY);\n if (CmsStringUtil.isEmptyOrWhitespaceOnly(data)) {\n return new ArrayList<>();\n }\n JSONObject json = new JSONObject(data);\n JSONArray array = json.getJSONArray(BASE_KEY);\n for (int i = 0; i < array.length(); i++) {\n JSONObject fav = array.getJSONObject(i);\n try {\n CmsFavoriteEntry entry = new CmsFavoriteEntry(fav);\n if (validate(entry)) {\n result.add(entry);\n }\n } catch (Exception e) {\n LOG.warn(e.getLocalizedMessage(), e);\n }\n\n }\n } catch (JSONException e) {\n LOG.error(e.getLocalizedMessage(), e);\n }\n return result;\n }" ]
[ "private int[] readTypeAnnotations(final MethodVisitor mv,\n final Context context, int u, boolean visible) {\n char[] c = context.buffer;\n int[] offsets = new int[readUnsignedShort(u)];\n u += 2;\n for (int i = 0; i < offsets.length; ++i) {\n offsets[i] = u;\n int target = readInt(u);\n switch (target >>> 24) {\n case 0x00: // CLASS_TYPE_PARAMETER\n case 0x01: // METHOD_TYPE_PARAMETER\n case 0x16: // METHOD_FORMAL_PARAMETER\n u += 2;\n break;\n case 0x13: // FIELD\n case 0x14: // METHOD_RETURN\n case 0x15: // METHOD_RECEIVER\n u += 1;\n break;\n case 0x40: // LOCAL_VARIABLE\n case 0x41: // RESOURCE_VARIABLE\n for (int j = readUnsignedShort(u + 1); j > 0; --j) {\n int start = readUnsignedShort(u + 3);\n int length = readUnsignedShort(u + 5);\n createLabel(start, context.labels);\n createLabel(start + length, context.labels);\n u += 6;\n }\n u += 3;\n break;\n case 0x47: // CAST\n case 0x48: // CONSTRUCTOR_INVOCATION_TYPE_ARGUMENT\n case 0x49: // METHOD_INVOCATION_TYPE_ARGUMENT\n case 0x4A: // CONSTRUCTOR_REFERENCE_TYPE_ARGUMENT\n case 0x4B: // METHOD_REFERENCE_TYPE_ARGUMENT\n u += 4;\n break;\n // case 0x10: // CLASS_EXTENDS\n // case 0x11: // CLASS_TYPE_PARAMETER_BOUND\n // case 0x12: // METHOD_TYPE_PARAMETER_BOUND\n // case 0x17: // THROWS\n // case 0x42: // EXCEPTION_PARAMETER\n // case 0x43: // INSTANCEOF\n // case 0x44: // NEW\n // case 0x45: // CONSTRUCTOR_REFERENCE\n // case 0x46: // METHOD_REFERENCE\n default:\n u += 3;\n break;\n }\n int pathLength = readByte(u);\n if ((target >>> 24) == 0x42) {\n TypePath path = pathLength == 0 ? null : new TypePath(b, u);\n u += 1 + 2 * pathLength;\n u = readAnnotationValues(u + 2, c, true,\n mv.visitTryCatchAnnotation(target, path,\n readUTF8(u, c), visible));\n } else {\n u = readAnnotationValues(u + 3 + 2 * pathLength, c, true, null);\n }\n }\n return offsets;\n }", "public T modifyBundle(final String moduleName, final String slot, final byte[] existingHash, final byte[] newHash) {\n final ContentItem item = createBundleItem(moduleName, slot, newHash);\n addContentModification(createContentModification(item, ModificationType.MODIFY, existingHash));\n return returnThis();\n }", "private CmsFavoriteEntry getEntry(Component row) {\n\n if (row instanceof CmsFavInfo) {\n\n return ((CmsFavInfo)row).getEntry();\n\n }\n return null;\n\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 String toDottedString() {\r\n\t\tString result = null;\r\n\t\tif(hasNoStringCache() || (result = getStringCache().dottedString) == null) {\r\n\t\t\tAddressDivisionGrouping dottedGrouping = getDottedGrouping();\r\n\t\t\tgetStringCache().dottedString = result = toNormalizedString(MACStringCache.dottedParams, dottedGrouping);\r\n\t\t}\r\n\t\treturn result;\r\n\t}", "static DefaultContainerDescription lookup(final ModelControllerClient client) throws IOException, OperationExecutionException {\n final ModelNode op = Operations.createReadResourceOperation(new ModelNode().setEmptyList());\n op.get(ClientConstants.INCLUDE_RUNTIME).set(true);\n final ModelNode result = client.execute(op);\n if (Operations.isSuccessfulOutcome(result)) {\n final ModelNode model = Operations.readResult(result);\n final String productName = getValue(model, \"product-name\", \"WildFly\");\n final String productVersion = getValue(model, \"product-version\");\n final String releaseVersion = getValue(model, \"release-version\");\n final String launchType = getValue(model, \"launch-type\");\n return new DefaultContainerDescription(productName, productVersion, releaseVersion, launchType, \"DOMAIN\".equalsIgnoreCase(launchType));\n }\n throw new OperationExecutionException(op, result);\n }", "public static boolean isSafe(Expression expression) {\r\n if (expression instanceof MethodCallExpression) {\r\n return ((MethodCallExpression) expression).isSafe();\r\n }\r\n if (expression instanceof PropertyExpression) {\r\n return ((PropertyExpression) expression).isSafe();\r\n }\r\n return false;\r\n }", "public static final String printAccrueType(AccrueType value)\n {\n return (Integer.toString(value == null ? AccrueType.PRORATED.getValue() : value.getValue()));\n }", "private void precheckStateAllNull() throws IllegalStateException {\n if ((doubleValue != null) || (doubleArray != null)\n || (longValue != null) || (longArray != null)\n || (stringValue != null) || (stringArray != null)\n || (map != null)) {\n throw new IllegalStateException(\"Expected all properties to be empty: \" + this);\n }\n }" ]
Process a beat packet, potentially updating the master tempo and sending our listeners a master beat notification. Does nothing if we are not active.
[ "void processBeat(Beat beat) {\n if (isRunning() && beat.isTempoMaster()) {\n setMasterTempo(beat.getEffectiveTempo());\n deliverBeatAnnouncement(beat);\n }\n }" ]
[ "protected static boolean isMaskCompatibleWithRange(long value, long upperValue, long maskValue, long maxValue) {\n\t\tif(value == upperValue || maskValue == maxValue || maskValue == 0) {\n\t\t\treturn true;\n\t\t}\n\n\t\t//algorithm:\n\t\t//here we find the highest bit that is part of the range, highestDifferingBitInRange (ie changes from lower to upper)\n\t\t//then we find the highest bit in the mask that is 1 that is the same or below highestDifferingBitInRange (if such a bit exists)\n\t\t\n\t\t//this gives us the highest bit that is part of the masked range (ie changes from lower to upper after applying the mask)\n\t\t//if this latter bit exists, then any bit below it in the mask must be 1 to include the entire range.\n\t\t\n\t\tlong differing = value ^ upperValue;\n\t\tboolean foundDiffering = (differing != 0);\n\t\tboolean differingIsLowestBit = (differing == 1);\n\t\tif(foundDiffering && !differingIsLowestBit) {\n\t\t\tint highestDifferingBitInRange = Long.numberOfLeadingZeros(differing);\n\t\t\tlong maskMask = ~0L >>> highestDifferingBitInRange;\n\t\t\tlong differingMasked = maskValue & maskMask;\n\t\t\tfoundDiffering = (differingMasked != 0);\n\t\t\tdifferingIsLowestBit = (differingMasked == 1);\n\t\t\tif(foundDiffering && !differingIsLowestBit) {\n\t\t\t\t//anything below highestDifferingBitMasked in the mask must be ones\n\t\t\t\t//Also, if we have masked out any 1 bit in the original, then anything that we do not mask out that follows must be all 1s\n\t\t\t\tint highestDifferingBitMasked = Long.numberOfLeadingZeros(differingMasked);\n\t\t\t\tlong hostMask = ~0L >>> (highestDifferingBitMasked + 1);//for the first mask bit that is 1, all bits that follow must also be 1\n\t\t\t\tif((maskValue & hostMask) != hostMask) { //check if all ones below\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tif(highestDifferingBitMasked > highestDifferingBitInRange) {\n\t\t\t\t\t//We have masked out a 1 bit, so we need to check that all bits in upper value that we do not mask out are also 1 bits, otherwise we end up missing values in the masked range\n\t\t\t\t\t//This check is unnecessary for prefix-length subnets, only non-standard ranges might fail this check.\n\t\t\t\t\t//For instance, if we have range 0000 to 1010\n\t\t\t\t\t//and we mask upper and lower with 0111\n\t\t\t\t\t//we get 0000 to 0010, but 0111 was in original range, and the mask of that value retains that value\n\t\t\t\t\t//so that value needs to be in final range, and it's not.\n\t\t\t\t\t//What went wrong is that we masked out the top bit, and any other bit that is not masked out must be 1.\n\t\t\t\t\t//To work, our original range needed to be 0000 to 1111, with the three 1s following the first masked-out 1\n\t\t\t\t\tlong hostMaskUpper = ~0L >>> highestDifferingBitMasked;\n\t\t\t\t\tif((upperValue & hostMaskUpper) != hostMaskUpper) {\n\t\t\t\t\t\treturn false;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}", "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 void unzip(Path zip, Path target) throws IOException {\n try (final ZipFile zipFile = new ZipFile(zip.toFile())){\n unzip(zipFile, target);\n }\n }", "protected boolean isSecureLink(CmsObject cms, String vfsName, CmsSite targetSite, boolean secureRequest) {\n\n return OpenCms.getStaticExportManager().isSecureLink(cms, vfsName, targetSite.getSiteRoot(), secureRequest);\n }", "private void processActivity(Activity activity)\n {\n Task task = getParentTask(activity).addTask();\n task.setText(1, activity.getId());\n\n task.setActualDuration(activity.getActualDuration());\n task.setActualFinish(activity.getActualFinish());\n task.setActualStart(activity.getActualStart());\n //activity.getBaseunit()\n //activity.getBilled()\n //activity.getCalendar()\n //activity.getCostAccount()\n task.setCreateDate(activity.getCreationTime());\n task.setFinish(activity.getCurrentFinish());\n task.setStart(activity.getCurrentStart());\n task.setName(activity.getDescription());\n task.setDuration(activity.getDurationAtCompletion());\n task.setEarlyFinish(activity.getEarlyFinish());\n task.setEarlyStart(activity.getEarlyStart());\n task.setFreeSlack(activity.getFreeFloat());\n task.setLateFinish(activity.getLateFinish());\n task.setLateStart(activity.getLateStart());\n task.setNotes(activity.getNotes());\n task.setBaselineDuration(activity.getOriginalDuration());\n //activity.getPathFloat()\n task.setPhysicalPercentComplete(activity.getPhysicalPercentComplete());\n task.setRemainingDuration(activity.getRemainingDuration());\n task.setCost(activity.getTotalCost());\n task.setTotalSlack(activity.getTotalFloat());\n task.setMilestone(activityIsMilestone(activity));\n //activity.getUserDefined()\n task.setGUID(activity.getUuid());\n\n if (task.getMilestone())\n {\n if (activityIsStartMilestone(activity))\n {\n task.setFinish(task.getStart());\n }\n else\n {\n task.setStart(task.getFinish());\n }\n }\n\n if (task.getActualStart() == null)\n {\n task.setPercentageComplete(Integer.valueOf(0));\n }\n else\n {\n if (task.getActualFinish() != null)\n {\n task.setPercentageComplete(Integer.valueOf(100));\n }\n else\n {\n Duration remaining = activity.getRemainingDuration();\n Duration total = activity.getDurationAtCompletion();\n if (remaining != null && total != null && total.getDuration() != 0)\n {\n double percentComplete = ((total.getDuration() - remaining.getDuration()) * 100.0) / total.getDuration();\n task.setPercentageComplete(Double.valueOf(percentComplete));\n }\n }\n }\n\n m_activityMap.put(activity.getId(), task);\n }", "@Override\n public DMatrixRMaj getA() {\n if( A.data.length < numRows*numCols ) {\n A = new DMatrixRMaj(numRows,numCols);\n }\n A.reshape(numRows,numCols, false);\n CommonOps_DDRM.mult(Q,R,A);\n\n return A;\n }", "public static void mergeHints(InputStream is, Map<String,List<Long>> hints) throws IOException {\n final BufferedReader reader = new BufferedReader(\n new InputStreamReader(is, Charsets.UTF_8));\n \n String line;\n while ((line = reader.readLine()) != null) {\n line = line.trim();\n if (line.isEmpty() || line.startsWith(\"#\"))\n continue;\n\n final int equals = line.indexOf('=');\n if (equals <= 0) {\n throw new IOException(\"No '=' character on a non-comment line?: \" + line);\n } else {\n String key = line.substring(0, equals);\n List<Long> values = hints.get(key);\n if (values == null) {\n hints.put(key, values = new ArrayList<>());\n }\n for (String v : line.substring(equals + 1).split(\"[\\\\,]\")) {\n if (!v.isEmpty()) values.add(Long.parseLong(v));\n }\n }\n }\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 }", "public static int[] convertBytesToInts(byte[] bytes)\n {\n if (bytes.length % 4 != 0)\n {\n throw new IllegalArgumentException(\"Number of input bytes must be a multiple of 4.\");\n }\n int[] ints = new int[bytes.length / 4];\n for (int i = 0; i < ints.length; i++)\n {\n ints[i] = convertBytesToInt(bytes, i * 4);\n }\n return ints;\n }" ]
Add an appliable "post-run" dependent for this task item. @param appliable the appliable "post-run" dependent. @return the key to be used as parameter to taskResult(string) method to retrieve updated "post-run" dependent
[ "@SuppressWarnings(\"unchecked\")\n protected String addPostRunDependent(Appliable<? extends Indexable> appliable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) appliable;\n return this.addPostRunDependent(dependency);\n }" ]
[ "protected void processAliases(List<MonolingualTextValue> addAliases, List<MonolingualTextValue> deleteAliases) {\n for(MonolingualTextValue val : addAliases) {\n addAlias(val);\n }\n for(MonolingualTextValue val : deleteAliases) {\n deleteAlias(val);\n }\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 String getResourcePath()\n {\n switch (resourceType)\n {\n case ANDROID_ASSETS: return assetPath;\n\n case ANDROID_RESOURCE: return resourceFilePath;\n\n case LINUX_FILESYSTEM: return filePath;\n\n case NETWORK: return url.getPath();\n\n case INPUT_STREAM: return inputStreamName;\n\n default: return null;\n }\n }", "public static TextEncryptor queryableText(CharSequence password, CharSequence salt) {\n\t\treturn new HexEncodingTextEncryptor(new AndroidAesBytesEncryptor(password.toString(), salt, AndroidKeyGenerators.shared(16)));\n\t}", "@Override\n synchronized public V put(K key, V value) {\n V oldValue = this.get(key);\n try {\n super.put(key, value);\n writeBack(key, value);\n return oldValue;\n } catch(Exception e) {\n super.put(key, oldValue);\n writeBack(key, oldValue);\n throw new VoldemortException(\"Failed to put(\" + key + \", \" + value\n + \") in write through cache\", e);\n }\n }", "public static float gain(float a, float b) {\n/*\n\t\tfloat p = (float)Math.log(1.0 - b) / (float)Math.log(0.5);\n\n\t\tif (a < .001)\n\t\t\treturn 0.0f;\n\t\telse if (a > .999)\n\t\t\treturn 1.0f;\n\t\tif (a < 0.5)\n\t\t\treturn (float)Math.pow(2 * a, p) / 2;\n\t\telse\n\t\t\treturn 1.0f - (float)Math.pow(2 * (1. - a), p) / 2;\n*/\n\t\tfloat c = (1.0f/b-2.0f) * (1.0f-2.0f*a);\n\t\tif (a < 0.5)\n\t\t\treturn a/(c+1.0f);\n\t\telse\n\t\t\treturn (c-a)/(c-1.0f);\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 }", "protected void validateRIBean(CommonBean<?> bean, BeanManagerImpl beanManager, Collection<CommonBean<?>> specializedBeans) {\n validateGeneralBean(bean, beanManager);\n if (bean instanceof NewBean) {\n return;\n }\n if (bean instanceof DecorableBean) {\n validateDecorators(beanManager, (DecorableBean<?>) bean);\n }\n if ((bean instanceof AbstractClassBean<?>)) {\n AbstractClassBean<?> classBean = (AbstractClassBean<?>) bean;\n // validate CDI-defined interceptors\n if (classBean.hasInterceptors()) {\n validateInterceptors(beanManager, classBean);\n }\n }\n // for each producer bean validate its disposer method\n if (bean instanceof AbstractProducerBean<?, ?, ?>) {\n AbstractProducerBean<?, ?, ?> producerBean = Reflections.<AbstractProducerBean<?, ?, ?>> cast(bean);\n if (producerBean.getProducer() instanceof AbstractMemberProducer<?, ?>) {\n AbstractMemberProducer<?, ?> producer = Reflections.<AbstractMemberProducer<?, ?>> cast(producerBean\n .getProducer());\n if (producer.getDisposalMethod() != null) {\n for (InjectionPoint ip : producer.getDisposalMethod().getInjectionPoints()) {\n // pass the producer bean instead of the disposal method bean\n validateInjectionPointForDefinitionErrors(ip, null, beanManager);\n validateMetadataInjectionPoint(ip, null, ValidatorLogger.INJECTION_INTO_DISPOSER_METHOD);\n validateEventMetadataInjectionPoint(ip);\n validateInjectionPointForDeploymentProblems(ip, null, beanManager);\n }\n }\n }\n }\n }", "private static String formatDirName(final String prefix, final String suffix) {\n // Replace all invalid characters with '-'\n final CharMatcher invalidCharacters = VALID_SUFFIX_CHARS.negate();\n return String.format(\"%s-%s\", prefix, invalidCharacters.trimAndCollapseFrom(suffix.toLowerCase(), '-'));\n }" ]
Removes and returns a random element from the set. @return the removed element, or <code>null</code> when the key does not exist.
[ "public String pop() {\n return doWithJedis(new JedisCallable<String>() {\n @Override\n public String call(Jedis jedis) {\n return jedis.spop(getKey());\n }\n });\n }" ]
[ "public static void validate(final ArtifactQuery artifactQuery) {\n final Pattern invalidChars = Pattern.compile(\"[^A-Fa-f0-9]\");\n if(artifactQuery.getUser() == null ||\n \t\tartifactQuery.getUser().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [user] missing\")\n .build());\n }\n if( artifactQuery.getStage() != 0 && artifactQuery.getStage() !=1 ){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Invalid [stage] value (supported 0 | 1)\")\n .build());\n }\n if(artifactQuery.getName() == null ||\n \t\tartifactQuery.getName().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [name] missing, it should be the file name\")\n .build());\n }\n if(artifactQuery.getSha256() == null ||\n artifactQuery.getSha256().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [sha256] missing\")\n .build());\n }\n if(artifactQuery.getSha256().length() < 64 || invalidChars.matcher(artifactQuery.getSha256()).find()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Invalid file checksum value\")\n .build());\n }\n if(artifactQuery.getType() == null ||\n \t\tartifactQuery.getType().isEmpty()){\n throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST)\n .entity(\"Mandatory field [type] missing\")\n .build());\n }\n }", "@Override\n @SuppressWarnings(\"unchecked\")\n public ChronoZonedDateTime<BritishCutoverDate> zonedDateTime(TemporalAccessor temporal) {\n return (ChronoZonedDateTime<BritishCutoverDate>) super.zonedDateTime(temporal);\n }", "private void toNextDate(Calendar date, int interval) {\n\n long previousDate = date.getTimeInMillis();\n if (!m_weekOfMonthIterator.hasNext()) {\n date.add(Calendar.MONTH, interval);\n m_weekOfMonthIterator = m_weeksOfMonth.iterator();\n }\n toCorrectDateWithDay(date, m_weekOfMonthIterator.next());\n if (previousDate == date.getTimeInMillis()) { // this can happen if the fourth and the last week are checked.\n toNextDate(date);\n }\n\n }", "synchronized boolean markReadMessageForId(String messageId, String userId){\n if(messageId == null || userId == null) return false;\n\n final String tName = Table.INBOX_MESSAGES.getName();\n try{\n final SQLiteDatabase db = dbHelper.getWritableDatabase();\n ContentValues cv = new ContentValues();\n cv.put(IS_READ,1);\n db.update(Table.INBOX_MESSAGES.getName(), cv,_ID + \" = ? AND \" + USER_ID + \" = ?\",new String[]{messageId,userId});\n return true;\n }catch (final SQLiteException e){\n getConfigLogger().verbose(\"Error removing stale records from \" + tName, e);\n return false;\n } finally {\n dbHelper.close();\n }\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 }", "protected void checkVariableName(GraphRewrite event, EvaluationContext context)\n {\n if (getInputVariablesName() == null)\n {\n setInputVariablesName(Iteration.getPayloadVariableName(event, context));\n }\n }", "public static void append(File file, Object text, String charset) throws IOException {\n Writer writer = null;\n try {\n FileOutputStream out = new FileOutputStream(file, true);\n if (!file.exists()) {\n writeUTF16BomIfRequired(charset, out);\n }\n writer = new OutputStreamWriter(out, charset);\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 void setHeader(String header) {\n headerLabel.getElement().setInnerSafeHtml(SafeHtmlUtils.fromString(header));\n addStyleName(CssName.WITH_HEADER);\n ListItem item = new ListItem(headerLabel);\n UiHelper.addMousePressedHandlers(item);\n item.setStyleName(CssName.COLLECTION_HEADER);\n insert(item, 0);\n }", "public JaCoCoReportReader readJacocoReport(IExecutionDataVisitor executionDataVisitor, ISessionInfoVisitor sessionInfoStore) {\n if (jacocoExecutionData == null) {\n return this;\n }\n\n JaCoCoExtensions.logger().info(\"Analysing {}\", jacocoExecutionData);\n try (InputStream inputStream = new BufferedInputStream(new FileInputStream(jacocoExecutionData))) {\n if (useCurrentBinaryFormat) {\n ExecutionDataReader reader = new ExecutionDataReader(inputStream);\n reader.setSessionInfoVisitor(sessionInfoStore);\n reader.setExecutionDataVisitor(executionDataVisitor);\n reader.read();\n } else {\n org.jacoco.previous.core.data.ExecutionDataReader reader = new org.jacoco.previous.core.data.ExecutionDataReader(inputStream);\n reader.setSessionInfoVisitor(sessionInfoStore);\n reader.setExecutionDataVisitor(executionDataVisitor);\n reader.read();\n }\n } catch (IOException e) {\n throw new IllegalArgumentException(String.format(\"Unable to read %s\", jacocoExecutionData.getAbsolutePath()), e);\n }\n return this;\n }" ]
Lift a Java Func0 to a Scala Function0 @param f the function to lift @returns the Scala function
[ "public static<Z> Function0<Z> lift(Func0<Z> f) {\n\treturn bridge.lift(f);\n }" ]
[ "public void alias(DMatrixRMaj variable , String name ) {\n if( isReserved(name))\n throw new RuntimeException(\"Reserved word or contains a reserved character\");\n VariableMatrix old = (VariableMatrix)variables.get(name);\n if( old == null ) {\n variables.put(name, new VariableMatrix(variable));\n }else {\n old.matrix = variable;\n }\n }", "protected void removeSequence(String sequenceName)\r\n {\r\n // lookup the sequence map for calling DB\r\n Map mapForDB = (Map) sequencesDBMap.get(getBrokerForClass()\r\n .serviceConnectionManager().getConnectionDescriptor().getJcdAlias());\r\n if(mapForDB != null)\r\n {\r\n synchronized(SequenceManagerHighLowImpl.class)\r\n {\r\n mapForDB.remove(sequenceName);\r\n }\r\n }\r\n }", "private void readHeader(InputStream is) throws IOException\n {\n byte[] header = new byte[20];\n is.read(header);\n m_offset += 20;\n SynchroLogger.log(\"HEADER\", header); \n }", "public ServerGroup addServerGroup(String groupName) {\n ServerGroup group = new ServerGroup();\n\n BasicNameValuePair[] params = {\n new BasicNameValuePair(\"name\", groupName),\n new BasicNameValuePair(\"profileIdentifier\", this._profileName)\n };\n try {\n JSONObject response = new JSONObject(doPost(BASE_SERVERGROUP, params));\n group = getServerGroupFromJSON(response);\n } catch (Exception e) {\n e.printStackTrace();\n return null;\n }\n return group;\n }", "private void cleanStaleFiles(File backupDir, AsyncOperationStatus status) {\n String[] filesInEnv = env.getHome().list();\n String[] filesInBackupDir = backupDir.list();\n if(filesInEnv != null && filesInBackupDir != null) {\n HashSet<String> envFileSet = new HashSet<String>();\n for(String file: filesInEnv)\n envFileSet.add(file);\n // delete all files in backup which are currently not in environment\n for(String file: filesInBackupDir) {\n if(file.endsWith(BDB_EXT) && !envFileSet.contains(file)) {\n status.setStatus(\"Deleting stale jdb file :\" + file);\n File staleJdbFile = new File(backupDir, file);\n staleJdbFile.delete();\n }\n }\n }\n }", "public ParallelTaskBuilder prepareHttpPut(String url) {\n reinitIfClosed();\n ParallelTaskBuilder cb = new ParallelTaskBuilder();\n cb.getHttpMeta().setHttpMethod(HttpMethod.PUT);\n cb.getHttpMeta().setRequestUrlPostfix(url);\n return cb;\n\n }", "private void readDefinitions()\n {\n for (MapRow row : m_tables.get(\"TTL\"))\n {\n Integer id = row.getInteger(\"DEFINITION_ID\");\n List<MapRow> list = m_definitions.get(id);\n if (list == null)\n {\n list = new ArrayList<MapRow>();\n m_definitions.put(id, list);\n }\n list.add(row);\n }\n\n List<MapRow> rows = m_definitions.get(WBS_FORMAT_ID);\n if (rows != null)\n {\n m_wbsFormat = new SureTrakWbsFormat(rows.get(0));\n }\n }", "private GVRCursorController getUniqueControllerId(int deviceId) {\n GVRCursorController controller = controllerIds.get(deviceId);\n if (controller != null) {\n return controller;\n }\n return null;\n }", "public Object getRealValue()\r\n {\r\n if(valueRealSubject != null)\r\n {\r\n return valueRealSubject;\r\n }\r\n else\r\n {\r\n TransactionExt tx = getTransaction();\r\n\r\n if((tx != null) && tx.isOpen())\r\n {\r\n prepareValueRealSubject(tx.getBroker());\r\n }\r\n else\r\n {\r\n if(getPBKey() != null)\r\n {\r\n PBCapsule capsule = new PBCapsule(getPBKey(), null);\r\n\r\n try\r\n {\r\n prepareValueRealSubject(capsule.getBroker());\r\n }\r\n finally\r\n {\r\n capsule.destroy();\r\n }\r\n }\r\n else\r\n {\r\n getLog().warn(\"No tx, no PBKey - can't materialise value with Identity \" + getKeyOid());\r\n }\r\n }\r\n }\r\n return valueRealSubject;\r\n }" ]
Move sections relative to each other in a board view. One of `before_section` or `after_section` is required. Sections cannot be moved between projects. At this point in time, moving sections is not supported in list views, only board views. Returns an empty data block. @param project The project in which to reorder the given section @return Request object
[ "public ItemRequest<Section> insertInProject(String project) {\n \n String path = String.format(\"/projects/%s/sections/insert\", project);\n return new ItemRequest<Section>(this, Section.class, path, \"POST\");\n }" ]
[ "private void prepare() throws IOException, DocumentException, PrintingException {\n\t\tif (baos == null) {\n\t\t\tbaos = new ByteArrayOutputStream(); // let it grow as much as needed\n\t\t}\n\t\tbaos.reset();\n\t\tboolean resize = false;\n\t\tif (page.getConstraint().getWidth() == 0 || page.getConstraint().getHeight() == 0) {\n\t\t\tresize = true;\n\t\t}\n\t\t// Create a document in the requested ISO scale.\n\t\tDocument document = new Document(page.getBounds(), 0, 0, 0, 0);\n\t\tPdfWriter writer;\n\t\twriter = PdfWriter.getInstance(document, baos);\n\n\t\t// Render in correct colors for transparent rasters\n\t\twriter.setRgbTransparencyBlending(true);\n\n\t\t// The mapView is not scaled to the document, we assume the mapView\n\t\t// has the right ratio.\n\n\t\t// Write document title and metadata\n\t\tdocument.open();\n\t\tPdfContext context = new PdfContext(writer);\n\t\tcontext.initSize(page.getBounds());\n\t\t// first pass of all children to calculate size\n\t\tpage.calculateSize(context);\n\t\tif (resize) {\n\t\t\t// we now know the bounds of the document\n\t\t\t// round 'm up and restart with a new document\n\t\t\tint width = (int) Math.ceil(page.getBounds().getWidth());\n\t\t\tint height = (int) Math.ceil(page.getBounds().getHeight());\n\t\t\tpage.getConstraint().setWidth(width);\n\t\t\tpage.getConstraint().setHeight(height);\n\n\t\t\tdocument = new Document(new Rectangle(width, height), 0, 0, 0, 0);\n\t\t\twriter = PdfWriter.getInstance(document, baos);\n\t\t\t// Render in correct colors for transparent rasters\n\t\t\twriter.setRgbTransparencyBlending(true);\n\n\t\t\tdocument.open();\n\t\t\tbaos.reset();\n\t\t\tcontext = new PdfContext(writer);\n\t\t\tcontext.initSize(page.getBounds());\n\t\t}\n\t\t// int compressionLevel = writer.getCompressionLevel(); // For testing\n\t\t// writer.setCompressionLevel(0);\n\n\t\t// Actual drawing\n\t\tdocument.addTitle(\"Geomajas\");\n\t\t// second pass to layout\n\t\tpage.layout(context);\n\t\t// finally render (uses baos)\n\t\tpage.render(context);\n\n\t\tdocument.add(context.getImage());\n\t\t// Now close the document\n\t\tdocument.close();\n\t}", "private static void writeNumber(Class<?> numberClass, Number value, CharBuf buffer) {\n if (numberClass == Integer.class) {\n buffer.addInt((Integer) value);\n } else if (numberClass == Long.class) {\n buffer.addLong((Long) value);\n } else if (numberClass == BigInteger.class) {\n buffer.addBigInteger((BigInteger) value);\n } else if (numberClass == BigDecimal.class) {\n buffer.addBigDecimal((BigDecimal) value);\n } else if (numberClass == Double.class) {\n Double doubleValue = (Double) value;\n if (doubleValue.isInfinite()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: infinite are not allowed in JSON.\");\n }\n if (doubleValue.isNaN()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: NaN are not allowed in JSON.\");\n }\n\n buffer.addDouble(doubleValue);\n } else if (numberClass == Float.class) {\n Float floatValue = (Float) value;\n if (floatValue.isInfinite()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: infinite are not allowed in JSON.\");\n }\n if (floatValue.isNaN()) {\n throw new JsonException(\"Number \" + value + \" can't be serialized as JSON: NaN are not allowed in JSON.\");\n }\n\n buffer.addFloat(floatValue);\n } else if (numberClass == Byte.class) {\n buffer.addByte((Byte) value);\n } else if (numberClass == Short.class) {\n buffer.addShort((Short) value);\n } else { // Handle other Number implementations\n buffer.addString(value.toString());\n }\n }", "public static String getTokenText(INode node) {\n\t\tif (node instanceof ILeafNode)\n\t\t\treturn ((ILeafNode) node).getText();\n\t\telse {\n\t\t\tStringBuilder builder = new StringBuilder(Math.max(node.getTotalLength(), 1));\n\t\t\tboolean hiddenSeen = false;\n\t\t\tfor (ILeafNode leaf : node.getLeafNodes()) {\n\t\t\t\tif (!leaf.isHidden()) {\n\t\t\t\t\tif (hiddenSeen && builder.length() > 0)\n\t\t\t\t\t\tbuilder.append(' ');\n\t\t\t\t\tbuilder.append(leaf.getText());\n\t\t\t\t\thiddenSeen = false;\n\t\t\t\t} else {\n\t\t\t\t\thiddenSeen = true;\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn builder.toString();\n\t\t}\n\t}", "public Operation.Info create( Symbol op , Variable left , Variable right ) {\n switch( op ) {\n case PLUS:\n return Operation.add(left, right, managerTemp);\n\n case MINUS:\n return Operation.subtract(left, right, managerTemp);\n\n case TIMES:\n return Operation.multiply(left, right, managerTemp);\n\n case RDIVIDE:\n return Operation.divide(left, right, managerTemp);\n\n case LDIVIDE:\n return Operation.divide(right, left, managerTemp);\n\n case POWER:\n return Operation.pow(left, right, managerTemp);\n\n case ELEMENT_DIVIDE:\n return Operation.elementDivision(left, right, managerTemp);\n\n case ELEMENT_TIMES:\n return Operation.elementMult(left, right, managerTemp);\n\n case ELEMENT_POWER:\n return Operation.elementPow(left, right, managerTemp);\n\n default:\n throw new RuntimeException(\"Unknown operation \" + op);\n }\n }", "public static base_response delete(nitro_service client, route6 resource) throws Exception {\n\t\troute6 deleteresource = new route6();\n\t\tdeleteresource.network = resource.network;\n\t\tdeleteresource.gateway = resource.gateway;\n\t\tdeleteresource.vlan = resource.vlan;\n\t\tdeleteresource.td = resource.td;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public void propagateIfCancelException(final Throwable t) {\n final RuntimeException cancelException = this.getPlatformOperationCanceledException(t);\n if ((cancelException != null)) {\n throw cancelException;\n }\n }", "public static ClassLoader overrideThreadContextClassLoader(ClassLoader classLoaderToUse) {\n\t\tThread currentThread = Thread.currentThread();\n\t\tClassLoader threadContextClassLoader = currentThread.getContextClassLoader();\n\t\tif (classLoaderToUse != null && !classLoaderToUse.equals(threadContextClassLoader)) {\n\t\t\tcurrentThread.setContextClassLoader(classLoaderToUse);\n\t\t\treturn threadContextClassLoader;\n\t\t}\n\t\telse {\n\t\t\treturn null;\n\t\t}\n\t}", "private void setSiteFilters(String filters) {\n\t\tthis.filterSites = new HashSet<>();\n\t\tif (!\"-\".equals(filters)) {\n\t\t\tCollections.addAll(this.filterSites, filters.split(\",\"));\n\t\t}\n\t}", "public Photoset create(String title, String description, String primaryPhotoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_CREATE);\r\n\r\n parameters.put(\"title\", title);\r\n parameters.put(\"description\", description);\r\n parameters.put(\"primary_photo_id\", primaryPhotoId);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n Element photosetElement = response.getPayload();\r\n Photoset photoset = new Photoset();\r\n photoset.setId(photosetElement.getAttribute(\"id\"));\r\n photoset.setUrl(photosetElement.getAttribute(\"url\"));\r\n return photoset;\r\n }" ]
Use this API to fetch systemuser resource of given name .
[ "public static systemuser get(nitro_service service, String username) throws Exception{\n\t\tsystemuser obj = new systemuser();\n\t\tobj.set_username(username);\n\t\tsystemuser response = (systemuser) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "public void set( T a ) {\n if( a.getType() == getType() )\n mat.set(a.getMatrix());\n else {\n setMatrix(a.mat.copy());\n }\n }", "@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 final String getString(byte[] data, int offset)\n {\n StringBuilder buffer = new StringBuilder();\n char c;\n\n for (int loop = 0; offset + loop < data.length; loop++)\n {\n c = (char) data[offset + loop];\n\n if (c == 0)\n {\n break;\n }\n\n buffer.append(c);\n }\n\n return (buffer.toString());\n }", "public static String resolveSvnMigratedRevision(final Revision revision, final String branch) {\n if (revision == null) {\n return null;\n }\n final Pattern pattern = Pattern.compile(\"^git-svn-id: .*\" + branch + \"@([0-9]+) \", Pattern.MULTILINE);\n final Matcher matcher = pattern.matcher(revision.getMessage());\n if (matcher.find()) {\n return matcher.group(1);\n } else {\n return revision.getRevision();\n }\n }", "void handleAddKey() {\n\n String key = m_addKeyInput.getValue();\n if (m_listener.handleAddKey(key)) {\n Notification.show(\n key.isEmpty()\n ? m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_EMPTY_KEY_SUCCESSFULLY_ADDED_0)\n : m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_SUCCESSFULLY_ADDED_1, key));\n } else {\n CmsMessageBundleEditorTypes.showWarning(\n m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_ALREADEY_EXISTS_CAPTION_0),\n m_messages.key(Messages.GUI_NOTIFICATION_MESSAGEBUNDLEEDITOR_KEY_ALREADEY_EXISTS_DESCRIPTION_1, key));\n\n }\n m_addKeyInput.focus();\n m_addKeyInput.selectAll();\n }", "@RequestMapping(value = \"/profiles\", method = RequestMethod.GET)\n public String list(Model model) {\n Profile profiles = new Profile();\n model.addAttribute(\"addNewProfile\", profiles);\n model.addAttribute(\"version\", Constants.VERSION);\n logger.info(\"Loading initial page\");\n\n return \"profiles\";\n }", "protected void readUUID(StreamReader stream, Map<String, Object> map) throws IOException\n {\n int unknown0Size = stream.getMajorVersion() > 5 ? 8 : 16;\n map.put(\"UNKNOWN0\", stream.readBytes(unknown0Size));\n map.put(\"UUID\", stream.readUUID()); \n }", "public static base_response update(nitro_service client, systemuser resource) throws Exception {\n\t\tsystemuser updateresource = new systemuser();\n\t\tupdateresource.username = resource.username;\n\t\tupdateresource.password = resource.password;\n\t\tupdateresource.externalauth = resource.externalauth;\n\t\tupdateresource.promptstring = resource.promptstring;\n\t\tupdateresource.timeout = resource.timeout;\n\t\treturn updateresource.update_resource(client);\n\t}", "public static ConsistencyLevel determineConsistency(Map<Value, Set<ClusterNode>> versionNodeSetMap,\n int replicationFactor) {\n boolean fullyConsistent = true;\n Value latestVersion = null;\n for (Map.Entry<Value, Set<ClusterNode>> versionNodeSetEntry : versionNodeSetMap.entrySet()) {\n Value value = versionNodeSetEntry.getKey();\n if (latestVersion == null) {\n latestVersion = value;\n } else if (value.isTimeStampLaterThan(latestVersion)) {\n latestVersion = value;\n }\n Set<ClusterNode> nodeSet = versionNodeSetEntry.getValue();\n fullyConsistent = fullyConsistent && (nodeSet.size() == replicationFactor);\n }\n if (fullyConsistent) {\n return ConsistencyLevel.FULL;\n } else {\n // latest write consistent, effectively consistent\n if (latestVersion != null && versionNodeSetMap.get(latestVersion).size() == replicationFactor) {\n return ConsistencyLevel.LATEST_CONSISTENT;\n }\n // all other states inconsistent\n return ConsistencyLevel.INCONSISTENT;\n }\n }" ]
Rehashes the contents of the receiver into a new table with a smaller or larger capacity. This method is called automatically when the number of keys in the receiver exceeds the high water mark or falls below the low water mark.
[ "protected void rehash(int newCapacity) {\r\n\tint oldCapacity = table.length;\r\n\t//if (oldCapacity == newCapacity) return;\r\n\t\r\n\tlong oldTable[] = table;\r\n\tint oldValues[] = values;\r\n\tbyte oldState[] = state;\r\n\r\n\tlong newTable[] = new long[newCapacity];\r\n\tint newValues[] = new int[newCapacity];\r\n\tbyte newState[] = new byte[newCapacity];\r\n\r\n\tthis.lowWaterMark = chooseLowWaterMark(newCapacity,this.minLoadFactor);\r\n\tthis.highWaterMark = chooseHighWaterMark(newCapacity,this.maxLoadFactor);\r\n\r\n\tthis.table = newTable;\r\n\tthis.values = newValues;\r\n\tthis.state = newState;\r\n\tthis.freeEntries = newCapacity-this.distinct; // delta\r\n\t\r\n\tfor (int i = oldCapacity ; i-- > 0 ;) {\r\n\t\tif (oldState[i]==FULL) {\r\n\t\t\tlong element = oldTable[i];\r\n\t\t\tint index = indexOfInsertion(element);\r\n\t\t\tnewTable[index]=element;\r\n\t\t\tnewValues[index]=oldValues[i];\r\n\t\t\tnewState[index]=FULL;\r\n\t\t}\r\n\t}\r\n}" ]
[ "@Override\n\tpublic Result getResult() throws Exception {\n\t\tResult returnResult = result;\n\n\t\t// If we've chained to other Actions, we need to find the last result\n\t\twhile (returnResult instanceof ActionChainResult) {\n\t\t\tActionProxy aProxy = ((ActionChainResult) returnResult).getProxy();\n\n\t\t\tif (aProxy != null) {\n\t\t\t\tResult proxyResult = aProxy.getInvocation().getResult();\n\n\t\t\t\tif ((proxyResult != null) && (aProxy.getExecuteResult())) {\n\t\t\t\t\treturnResult = proxyResult;\n\t\t\t\t} else {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\treturn returnResult;\n\t}", "public void addPartialFieldAssignment(\n SourceBuilder code, Excerpt finalField, String builder) {\n addFinalFieldAssignment(code, finalField, builder);\n }", "public Character getCharacter(int field)\n {\n Character result;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = Character.valueOf(m_fields[field].charAt(0));\n }\n else\n {\n result = null;\n }\n\n return (result);\n }", "@JmxGetter(name = \"lastSwapped\", description = \"Time in milliseconds since the store was swapped\")\n public long getLastSwapped() {\n long timeSinceLastSwap = System.currentTimeMillis() - lastSwapped;\n return timeSinceLastSwap > 0 ? timeSinceLastSwap : 0;\n }", "public static Deployment of(final URL url) {\n final DeploymentContent deploymentContent = DeploymentContent.of(Assert.checkNotNullParam(\"url\", url));\n return new Deployment(deploymentContent, null);\n }", "public static int wavelengthToRGB(float wavelength) {\n\t\tfloat gamma = 0.80f;\n\t\tfloat r, g, b, factor;\n\n\t\tint w = (int)wavelength;\n\t\tif (w < 380) {\n\t\t\tr = 0.0f;\n\t\t\tg = 0.0f;\n\t\t\tb = 0.0f;\n\t\t} else if (w < 440) {\n\t\t\tr = -(wavelength - 440) / (440 - 380);\n\t\t\tg = 0.0f;\n\t\t\tb = 1.0f;\n\t\t} else if (w < 490) {\n\t\t\tr = 0.0f;\n\t\t\tg = (wavelength - 440) / (490 - 440);\n\t\t\tb = 1.0f;\n\t\t} else if (w < 510) {\n\t\t\tr = 0.0f;\n\t\t\tg = 1.0f;\n\t\t\tb = -(wavelength - 510) / (510 - 490);\n\t\t} else if (w < 580) {\n\t\t\tr = (wavelength - 510) / (580 - 510);\n\t\t\tg = 1.0f;\n\t\t\tb = 0.0f;\n\t\t} else if (w < 645) {\n\t\t\tr = 1.0f;\n\t\t\tg = -(wavelength - 645) / (645 - 580);\n\t\t\tb = 0.0f;\n\t\t} else if (w <= 780) {\n\t\t\tr = 1.0f;\n\t\t\tg = 0.0f;\n\t\t\tb = 0.0f;\n\t\t} else {\n\t\t\tr = 0.0f;\n\t\t\tg = 0.0f;\n\t\t\tb = 0.0f;\n\t\t}\n\n\t\t// Let the intensity fall off near the vision limits\n\t\tif (380 <= w && w <= 419)\n\t\t\tfactor = 0.3f + 0.7f*(wavelength - 380) / (420 - 380);\n\t\telse if (420 <= w && w <= 700)\n\t\t\tfactor = 1.0f;\n\t\telse if (701 <= w && w <= 780)\n\t\t\tfactor = 0.3f + 0.7f*(780 - wavelength) / (780 - 700);\n\t\telse\n\t\t\tfactor = 0.0f;\n\n\t\tint ir = adjust(r, factor, gamma);\n\t\tint ig = adjust(g, factor, gamma);\n\t\tint ib = adjust(b, factor, gamma);\n\n\t\treturn 0xff000000 | (ir << 16) | (ig << 8) | ib;\n\t}", "protected Collection loadData() throws PersistenceBrokerException\r\n {\r\n PersistenceBroker broker = getBroker();\r\n try\r\n {\r\n Collection result;\r\n\r\n if (_data != null) // could be set by listener\r\n {\r\n result = _data;\r\n }\r\n else if (_size != 0)\r\n {\r\n // TODO: returned ManageableCollection should extend Collection to avoid\r\n // this cast\r\n result = (Collection) broker.getCollectionByQuery(getCollectionClass(), getQuery());\r\n }\r\n else\r\n {\r\n result = (Collection)getCollectionClass().newInstance();\r\n }\r\n return result;\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new PersistenceBrokerException(ex);\r\n }\r\n finally\r\n {\r\n releaseBroker(broker);\r\n }\r\n }", "public void setSchema(String schema)\n {\n if (schema == null)\n {\n schema = \"\";\n }\n else\n {\n if (!schema.isEmpty() && !schema.endsWith(\".\"))\n {\n schema = schema + '.';\n }\n }\n m_schema = schema;\n }", "protected static PatchElement createPatchElement(final PatchEntry entry, String patchId, final List<ContentModification> modifications) {\n final PatchElement patchElement = entry.element;\n final PatchElementImpl element = new PatchElementImpl(patchId);\n element.setProvider(patchElement.getProvider());\n // Add all the rollback actions\n element.getModifications().addAll(modifications);\n element.setDescription(patchElement.getDescription());\n return element;\n }" ]
Serializes descriptor instance to XML @param descriptor descriptor to be serialized @return xml representation of descriptor as string
[ "public static String toXml(DeploymentDescriptor descriptor) {\n try {\n\n Marshaller marshaller = getContext().createMarshaller();\n marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);\n marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, \"http://www.jboss.org/jbpm deployment-descriptor.xsd\");\n marshaller.setSchema(schema);\n StringWriter stringWriter = new StringWriter();\n\n // clone the object and cleanup transients\n DeploymentDescriptor clone = ((DeploymentDescriptorImpl) descriptor).clearClone();\n\n marshaller.marshal(clone, stringWriter);\n String output = stringWriter.toString();\n\n return output;\n } catch (Exception e) {\n throw new RuntimeException(\"Unable to generate xml from deployment descriptor\", e);\n }\n }" ]
[ "private SortedSet<Date> calculateDates() {\n\n if (null == m_allDates) {\n SortedSet<Date> result = new TreeSet<>();\n if (isAnyDatePossible()) {\n Calendar date = getFirstDate();\n int previousOccurrences = 0;\n while (showMoreEntries(date, previousOccurrences)) {\n result.add(date.getTime());\n toNextDate(date);\n previousOccurrences++;\n }\n }\n m_allDates = result;\n }\n return m_allDates;\n }", "public boolean process( int sideLength,\n double diag[] ,\n double off[] ,\n double eigenvalues[] ) {\n if( diag != null )\n helper.init(diag,off,sideLength);\n if( Q == null )\n Q = CommonOps_DDRM.identity(helper.N);\n helper.setQ(Q);\n\n this.followingScript = true;\n this.eigenvalues = eigenvalues;\n this.fastEigenvalues = false;\n\n return _process();\n }", "public StitchObjectMapper withCodecRegistry(final CodecRegistry codecRegistry) {\n // We can't detect if their codecRegistry has any duplicate providers. There's also a chance\n // that putting ours first may prevent decoding of some of their classes if for example they\n // have their own way of decoding an Integer.\n final CodecRegistry newReg =\n CodecRegistries.fromRegistries(BsonUtils.DEFAULT_CODEC_REGISTRY, codecRegistry);\n return new StitchObjectMapper(this, newReg);\n }", "public DocumentReaderAndWriter<IN> makeReaderAndWriter() {\r\n DocumentReaderAndWriter<IN> readerAndWriter;\r\n try {\r\n readerAndWriter = ((DocumentReaderAndWriter<IN>)\r\n Class.forName(flags.readerAndWriter).newInstance());\r\n } catch (Exception e) {\r\n throw new RuntimeException(String.format(\"Error loading flags.readerAndWriter: '%s'\", flags.readerAndWriter), e);\r\n }\r\n readerAndWriter.init(flags);\r\n return readerAndWriter;\r\n }", "private void readCalendar(Calendar calendar)\n {\n // Create the calendar\n ProjectCalendar mpxjCalendar = m_projectFile.addCalendar();\n mpxjCalendar.setName(calendar.getName());\n\n // Default all days to working\n for (Day day : Day.values())\n {\n mpxjCalendar.setWorkingDay(day, true);\n }\n\n // Mark non-working days\n List<NonWork> nonWorkingDays = calendar.getNonWork();\n for (NonWork nonWorkingDay : nonWorkingDays)\n {\n // TODO: handle recurring exceptions\n if (nonWorkingDay.getType().equals(\"internal_weekly\"))\n {\n mpxjCalendar.setWorkingDay(nonWorkingDay.getWeekday(), false);\n }\n }\n\n // Add default working hours for working days\n for (Day day : Day.values())\n {\n if (mpxjCalendar.isWorkingDay(day))\n {\n ProjectCalendarHours hours = mpxjCalendar.addCalendarHours(day);\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_MORNING);\n hours.addRange(ProjectCalendarWeek.DEFAULT_WORKING_AFTERNOON);\n }\n }\n }", "public final Template getTemplate(final String name) {\n final Template template = this.templates.get(name);\n if (template != null) {\n this.accessAssertion.assertAccess(\"Configuration\", this);\n template.assertAccessible(name);\n } else {\n throw new IllegalArgumentException(String.format(\"Template '%s' does not exist. Options are: \" +\n \"%s\", name, this.templates.keySet()));\n }\n return template;\n }", "private String toLengthText(long bytes) {\n if (bytes < 1024) {\n return bytes + \" B\";\n } else if (bytes < 1024 * 1024) {\n return (bytes / 1024) + \" KB\";\n } else if (bytes < 1024 * 1024 * 1024) {\n return String.format(\"%.2f MB\", bytes / (1024.0 * 1024.0));\n } else {\n return String.format(\"%.2f GB\", bytes / (1024.0 * 1024.0 * 1024.0));\n }\n }", "protected void parseSequencesWithColons(TokenList tokens , Sequence sequence ) {\n\n TokenList.Token t = tokens.getFirst();\n if( t == null )\n return;\n\n int state = 0;\n\n TokenList.Token start = null;\n TokenList.Token middle = null;\n TokenList.Token prev = t;\n\n boolean last = false;\n while( true ) {\n if( state == 0 ) {\n if( isVariableInteger(t) && (t.next != null && t.next.getSymbol() == Symbol.COLON) ) {\n start = t;\n state = 1;\n t = t.next;\n } else if( t != null && t.getSymbol() == Symbol.COLON ) {\n // If it starts with a colon then it must be 'all' or a type-o\n IntegerSequence range = new IntegerSequence.Range(null,null);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(range);\n TokenList.Token n = new TokenList.Token(varSequence);\n tokens.insert(t.previous, n);\n tokens.remove(t);\n t = n;\n }\n } else if( state == 1 ) {\n // var : ?\n if (isVariableInteger(t)) {\n state = 2;\n } else {\n // array range\n IntegerSequence range = new IntegerSequence.Range(start,null);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(range);\n replaceSequence(tokens, varSequence, start, prev);\n state = 0;\n }\n } else if ( state == 2 ) {\n // var:var ?\n if( t != null && t.getSymbol() == Symbol.COLON ) {\n middle = prev;\n state = 3;\n } else {\n // create for sequence with start and stop elements only\n IntegerSequence numbers = new IntegerSequence.For(start,null,prev);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(numbers);\n replaceSequence(tokens, varSequence, start, prev );\n if( t != null )\n t = t.previous;\n state = 0;\n }\n } else if ( state == 3 ) {\n // var:var: ?\n if( isVariableInteger(t) ) {\n // create 'for' sequence with three variables\n IntegerSequence numbers = new IntegerSequence.For(start,middle,t);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(numbers);\n t = replaceSequence(tokens, varSequence, start, t);\n } else {\n // array range with 2 elements\n IntegerSequence numbers = new IntegerSequence.Range(start,middle);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(numbers);\n replaceSequence(tokens, varSequence, start, prev);\n }\n state = 0;\n }\n\n if( last ) {\n break;\n } else if( t.next == null ) {\n // handle the case where it is the last token in the sequence\n last = true;\n }\n prev = t;\n t = t.next;\n }\n }", "public static void acceptsNodeMultiple(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_N, OPT_NODE), \"node id list\")\n .withRequiredArg()\n .describedAs(\"node-id-list\")\n .withValuesSeparatedBy(',')\n .ofType(Integer.class);\n }" ]
Adds a patch operation. @param op the operation type. Must be add, replace, remove, or test. @param path the path that designates the key. Must be prefixed with a "/". @param value the value to be set.
[ "private void addOp(String op, String path, String value) {\n if (this.operations == null) {\n this.operations = new JsonArray();\n }\n\n this.operations.add(new JsonObject()\n .add(\"op\", op)\n .add(\"path\", path)\n .add(\"value\", value));\n }" ]
[ "public static base_response update(nitro_service client, tmtrafficaction resource) throws Exception {\n\t\ttmtrafficaction updateresource = new tmtrafficaction();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.apptimeout = resource.apptimeout;\n\t\tupdateresource.sso = resource.sso;\n\t\tupdateresource.formssoaction = resource.formssoaction;\n\t\tupdateresource.persistentcookie = resource.persistentcookie;\n\t\tupdateresource.initiatelogout = resource.initiatelogout;\n\t\tupdateresource.kcdaccount = resource.kcdaccount;\n\t\tupdateresource.samlssoprofile = resource.samlssoprofile;\n\t\treturn updateresource.update_resource(client);\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 }", "public List<TimephasedWork> getCompleteWork(ProjectCalendar calendar, ResourceAssignment resourceAssignment, byte[] data)\n {\n LinkedList<TimephasedWork> list = new LinkedList<TimephasedWork>();\n\n if (calendar != null && data != null && data.length > 2 && MPPUtility.getShort(data, 0) > 0)\n {\n Date startDate = resourceAssignment.getStart();\n double finishTime = MPPUtility.getInt(data, 24);\n\n int blockCount = MPPUtility.getShort(data, 0);\n double previousCumulativeWork = 0;\n TimephasedWork previousAssignment = null;\n\n int index = 32;\n int currentBlock = 0;\n while (currentBlock < blockCount && index + 20 <= data.length)\n {\n double time = MPPUtility.getInt(data, index + 0);\n\n // If the start of this block is before the start of the assignment, or after the end of the assignment\n // the values don't make sense, so we'll just set the start of this block to be the start of the assignment.\n // This deals with an issue where odd timephased data like this was causing an MPP file to be read\n // extremely slowly.\n if (time < 0 || time > finishTime)\n {\n time = 0;\n }\n else\n {\n time /= 80;\n }\n Duration startWork = Duration.getInstance(time, TimeUnit.MINUTES);\n\n double currentCumulativeWork = (long) MPPUtility.getDouble(data, index + 4);\n double assignmentDuration = currentCumulativeWork - previousCumulativeWork;\n previousCumulativeWork = currentCumulativeWork;\n assignmentDuration /= 1000;\n Duration totalWork = Duration.getInstance(assignmentDuration, TimeUnit.MINUTES);\n time = (long) MPPUtility.getDouble(data, index + 12);\n time /= 125;\n time *= 6;\n Duration workPerDay = Duration.getInstance(time, TimeUnit.MINUTES);\n\n Date start;\n if (startWork.getDuration() == 0)\n {\n start = startDate;\n }\n else\n {\n start = calendar.getDate(startDate, startWork, true);\n }\n\n TimephasedWork assignment = new TimephasedWork();\n assignment.setStart(start);\n assignment.setAmountPerDay(workPerDay);\n assignment.setTotalAmount(totalWork);\n\n if (previousAssignment != null)\n {\n Date finish = calendar.getDate(startDate, startWork, false);\n previousAssignment.setFinish(finish);\n if (previousAssignment.getStart().getTime() == previousAssignment.getFinish().getTime())\n {\n list.removeLast();\n }\n }\n\n list.add(assignment);\n previousAssignment = assignment;\n\n index += 20;\n ++currentBlock;\n }\n\n if (previousAssignment != null)\n {\n Duration finishWork = Duration.getInstance(finishTime / 80, TimeUnit.MINUTES);\n Date finish = calendar.getDate(startDate, finishWork, false);\n previousAssignment.setFinish(finish);\n if (previousAssignment.getStart().getTime() == previousAssignment.getFinish().getTime())\n {\n list.removeLast();\n }\n }\n }\n\n return list;\n }", "public PeriodicEvent runAfter(Runnable task, float delay) {\n validateDelay(delay);\n return new Event(task, delay);\n }", "public double[] Kernel1D(int size) {\n if (((size % 2) == 0) || (size < 3) || (size > 101)) {\n try {\n throw new Exception(\"Wrong size\");\n } catch (Exception e) {\n e.printStackTrace();\n }\n }\n int r = size / 2;\n // kernel\n double[] kernel = new double[size];\n\n // compute kernel\n for (int x = -r, i = 0; i < size; x++, i++) {\n kernel[i] = Function1D(x);\n }\n\n return kernel;\n }", "public static InternetPrintWriter createForEncoding(OutputStream outputStream, boolean autoFlush, Charset charset) {\r\n return new InternetPrintWriter(new OutputStreamWriter(outputStream, charset), autoFlush);\r\n }", "@Override\n public Response doRequest(final StitchRequest stitchReq) {\n initAppMetadata(clientAppId);\n\n return super.doRequestUrl(stitchReq, getHostname());\n }", "public static int Mode( int[] values ){\n int mode = 0, curMax = 0;\n\n for ( int i = 0, length = values.length; i < length; i++ )\n {\n if ( values[i] > curMax )\n {\n curMax = values[i];\n mode = i;\n }\n }\n return mode;\n }", "private <T extends Index> List<T> listIndexType(String type, Class<T> modelType) {\n List<T> indexesOfType = new ArrayList<T>();\n Gson g = new Gson();\n for (JsonElement index : indexes) {\n if (index.isJsonObject()) {\n JsonObject indexDefinition = index.getAsJsonObject();\n JsonElement indexType = indexDefinition.get(\"type\");\n if (indexType != null && indexType.isJsonPrimitive()) {\n JsonPrimitive indexTypePrimitive = indexType.getAsJsonPrimitive();\n if (type == null || (indexTypePrimitive.isString() && indexTypePrimitive\n .getAsString().equals(type))) {\n indexesOfType.add(g.fromJson(indexDefinition, modelType));\n }\n }\n }\n }\n return indexesOfType;\n }" ]
called periodically to check that the heartbeat has been received @return {@code true} if we have received a heartbeat recently
[ "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 static responderpolicylabel_binding get(nitro_service service, String labelname) throws Exception{\n\t\tresponderpolicylabel_binding obj = new responderpolicylabel_binding();\n\t\tobj.set_labelname(labelname);\n\t\tresponderpolicylabel_binding response = (responderpolicylabel_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "private ResourceAssignment getExistingResourceAssignment(Resource resource)\n {\n ResourceAssignment assignment = null;\n Integer resourceUniqueID = null;\n\n if (resource != null)\n {\n Iterator<ResourceAssignment> iter = m_assignments.iterator();\n resourceUniqueID = resource.getUniqueID();\n\n while (iter.hasNext() == true)\n {\n assignment = iter.next();\n Integer uniqueID = assignment.getResourceUniqueID();\n if (uniqueID != null && uniqueID.equals(resourceUniqueID) == true)\n {\n break;\n }\n assignment = null;\n }\n }\n\n return assignment;\n }", "public void add(String photoId) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_ADD);\r\n parameters.put(\"photo_id\", photoId);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }", "public static int getIbanLength(final CountryCode countryCode) {\n final BbanStructure structure = getBbanStructure(countryCode);\n return COUNTRY_CODE_LENGTH + CHECK_DIGIT_LENGTH + structure.getBbanLength();\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 }", "public static LBuffer loadFrom(File file) throws IOException {\n FileChannel fin = new FileInputStream(file).getChannel();\n long fileSize = fin.size();\n if (fileSize > Integer.MAX_VALUE)\n throw new IllegalArgumentException(\"Cannot load from file more than 2GB: \" + file);\n LBuffer b = new LBuffer((int) fileSize);\n long pos = 0L;\n WritableChannelWrap ch = new WritableChannelWrap(b);\n while (pos < fileSize) {\n pos += fin.transferTo(0, fileSize, ch);\n }\n return b;\n }", "@Deprecated public Duration getDuration(String calendarName, Date startDate, Date endDate) throws MPXJException\n {\n ProjectCalendar calendar = getCalendarByName(calendarName);\n\n if (calendar == null)\n {\n throw new MPXJException(MPXJException.CALENDAR_ERROR + \": \" + calendarName);\n }\n\n return (calendar.getDuration(startDate, endDate));\n }", "public void setControllerModel(GVRSceneObject controllerModel)\n {\n if (mControllerModel != null)\n {\n mControllerGroup.removeChildObject(mControllerModel);\n }\n mControllerModel = controllerModel;\n mControllerGroup.addChildObject(mControllerModel);\n mControllerModel.setEnable(mShowControllerModel);\n }", "public static spilloverpolicy[] get(nitro_service service, options option) throws Exception{\n\t\tspilloverpolicy obj = new spilloverpolicy();\n\t\tspilloverpolicy[] response = (spilloverpolicy[])obj.get_resources(service,option);\n\t\treturn response;\n\t}" ]
Append field with quotes and escape characters added, if required. @return this
[ "SimpleJsonEncoder appendToJSON(final String key, final Object value) {\n if (closed) {\n throw new IllegalStateException(\"Encoder already closed\");\n }\n if (value != null) {\n appendKey(key);\n if (value instanceof Number) {\n sb.append(value.toString());\n } else {\n sb.append(QUOTE).append(escapeString(value.toString())).append(QUOTE);\n }\n }\n return this;\n }" ]
[ "protected ViewPort load() {\n resize = Window.addResizeHandler(event -> {\n execute(event.getWidth(), event.getHeight());\n });\n\n execute(window().width(), (int)window().height());\n return viewPort;\n }", "public boolean isMaterialized(Object object)\r\n {\r\n IndirectionHandler handler = getIndirectionHandler(object);\r\n\r\n return handler == null || handler.alreadyMaterialized();\r\n }", "private void executeResult() throws Exception {\n\t\tresult = createResult();\n\n\t\tString timerKey = \"executeResult: \" + getResultCode();\n\t\ttry {\n\t\t\tUtilTimerStack.push(timerKey);\n\t\t\tif (result != null) {\n\t\t\t\tresult.execute(this);\n\t\t\t} else if (resultCode != null && !Action.NONE.equals(resultCode)) {\n\t\t\t\tthrow new ConfigurationException(\"No result defined for action \" + getAction().getClass().getName()\n\t\t\t\t\t\t+ \" and result \" + getResultCode(), proxy.getConfig());\n\t\t\t} else {\n\t\t\t\tif (LOG.isDebugEnabled()) {\n\t\t\t\t\tLOG.debug(\"No result returned for action \" + getAction().getClass().getName() + \" at \"\n\t\t\t\t\t\t\t+ proxy.getConfig().getLocation());\n\t\t\t\t}\n\t\t\t}\n\t\t} finally {\n\t\t\tUtilTimerStack.pop(timerKey);\n\t\t}\n\t}", "public synchronized void bindShader(GVRScene scene, boolean isMultiview)\n {\n GVRRenderPass pass = mRenderPassList.get(0);\n GVRShaderId shader = pass.getMaterial().getShaderType();\n GVRShader template = shader.getTemplate(getGVRContext());\n if (template != null)\n {\n template.bindShader(getGVRContext(), this, scene, isMultiview);\n }\n for (int i = 1; i < mRenderPassList.size(); ++i)\n {\n pass = mRenderPassList.get(i);\n shader = pass.getMaterial().getShaderType();\n template = shader.getTemplate(getGVRContext());\n if (template != null)\n {\n template.bindShader(getGVRContext(), pass, scene, isMultiview);\n }\n }\n }", "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 }", "@Override\n public void preStateCrawling(CrawlerContext context,\n ImmutableList<CandidateElement> candidateElements, StateVertex state) {\n LOG.debug(\"preStateCrawling\");\n List<CandidateElementPosition> newElements = Lists.newLinkedList();\n LOG.info(\"Prestate found new state {} with {} candidates\", state.getName(),\n candidateElements.size());\n for (CandidateElement element : candidateElements) {\n try {\n WebElement webElement = getWebElement(context.getBrowser(), element);\n if (webElement != null) {\n newElements.add(findElement(webElement, element));\n }\n } catch (WebDriverException e) {\n LOG.info(\"Could not get position for {}\", element, e);\n }\n }\n\n StateBuilder stateOut = outModelCache.addStateIfAbsent(state);\n stateOut.addCandidates(newElements);\n LOG.trace(\"preState finished, elements added to state\");\n }", "private static MonetaryFormatsSingletonSpi loadMonetaryFormatsSingletonSpi() {\n try {\n return Optional.ofNullable(Bootstrap.getService(MonetaryFormatsSingletonSpi.class))\n .orElseGet(DefaultMonetaryFormatsSingletonSpi::new);\n } catch (Exception e) {\n Logger.getLogger(MonetaryFormats.class.getName())\n .log(Level.WARNING, \"Failed to load MonetaryFormatsSingletonSpi, using default.\", e);\n return new DefaultMonetaryFormatsSingletonSpi();\n }\n }", "@SuppressWarnings(\"deprecation\")\n\tpublic static boolean timeEquals(java.util.Date d1, java.util.Date d2) {\n if (d1 == null || d2 == null) {\n return false;\n }\n\n return d1.getHours() == d2.getHours()\n && d1.getMinutes() == d2.getMinutes()\n && d1.getSeconds() == d2.getSeconds();\n }", "public void clear() {\n if (arrMask != null) {\n for (int y = 0; y < height; y++) {\n for (int x = 0; x < width; x++) {\n arrMask[x][y] = false;\n }\n }\n }\n }" ]
Creates a new instance from the given configuration file. @throws IOException if failed to load the configuration from the specified file
[ "public static CentralDogma forConfig(File configFile) throws IOException {\n requireNonNull(configFile, \"configFile\");\n return new CentralDogma(Jackson.readValue(configFile, CentralDogmaConfig.class));\n }" ]
[ "public static <E> Set<E> diff(Set<E> s1, Set<E> s2) {\r\n Set<E> s = new HashSet<E>();\r\n for (E o : s1) {\r\n if (!s2.contains(o)) {\r\n s.add(o);\r\n }\r\n }\r\n return s;\r\n }", "public static String createFolderPath(String path) {\n\n String[] pathParts = path.split(\"\\\\.\");\n String path2 = \"\";\n for (String part : pathParts) {\n if (path2.equals(\"\")) {\n path2 = part;\n } else {\n path2 = path2 + File.separator\n + changeFirstLetterToLowerCase(createClassName(part));\n }\n }\n\n return path2;\n }", "public static List<Integer> getStolenPrimaryPartitions(final Cluster currentCluster,\n final Cluster finalCluster,\n final int stealNodeId) {\n List<Integer> finalList = new ArrayList<Integer>(finalCluster.getNodeById(stealNodeId)\n .getPartitionIds());\n\n List<Integer> currentList = new ArrayList<Integer>();\n if(currentCluster.hasNodeWithId(stealNodeId)) {\n currentList = currentCluster.getNodeById(stealNodeId).getPartitionIds();\n } else {\n if(logger.isDebugEnabled()) {\n logger.debug(\"Current cluster does not contain stealer node (cluster : [[[\"\n + currentCluster + \"]]], node id \" + stealNodeId + \")\");\n }\n }\n finalList.removeAll(currentList);\n\n return finalList;\n }", "@SuppressWarnings(\"unchecked\")\n public static <T> Serializer<T> unsafeGetSerializer(SerializerFactory serializerFactory,\n SerializerDefinition serializerDefinition) {\n return (Serializer<T>) serializerFactory.getSerializer(serializerDefinition);\n }", "public void buttonClick(View v) {\n switch (v.getId()) {\n case R.id.show:\n showAppMsg();\n break;\n case R.id.cancel_all:\n AppMsg.cancelAll(this);\n break;\n default:\n return;\n }\n }", "private Optional<String> getXsrfFromHtmlBody(HttpResponse loginResponse) throws IOException {\n Optional<Cookie> gerritAccountCookie = findGerritAccountCookie();\n if (gerritAccountCookie.isPresent()) {\n Matcher matcher = GERRIT_AUTH_PATTERN.matcher(EntityUtils.toString(loginResponse.getEntity(), Consts.UTF_8));\n if (matcher.find()) {\n return Optional.of(matcher.group(1));\n }\n }\n return Optional.absent();\n }", "@SuppressWarnings(\"unchecked\")\n public Map<BsonValue, ChangeEvent<BsonDocument>> getEvents() {\n nsLock.readLock().lock();\n final Map<BsonValue, ChangeEvent<BsonDocument>> events;\n try {\n events = new HashMap<>(this.events);\n } finally {\n nsLock.readLock().unlock();\n }\n\n nsLock.writeLock().lock();\n try {\n this.events.clear();\n return events;\n } finally {\n nsLock.writeLock().unlock();\n }\n }", "protected ZipEntry getZipEntry(String filename) throws ZipException {\n\n // yes\n ZipEntry entry = getZipFile().getEntry(filename);\n // path to file might be relative, too\n if ((entry == null) && filename.startsWith(\"/\")) {\n entry = m_zipFile.getEntry(filename.substring(1));\n }\n if (entry == null) {\n throw new ZipException(\n Messages.get().getBundle().key(Messages.LOG_IMPORTEXPORT_FILE_NOT_FOUND_IN_ZIP_1, filename));\n }\n return entry;\n }", "public static List<ContentRepositoryElement> listFiles(final Path rootPath, Path tempDir, final ContentFilter filter) throws IOException {\n List<ContentRepositoryElement> result = new ArrayList<>();\n if (Files.exists(rootPath)) {\n if(isArchive(rootPath)) {\n return listZipContent(rootPath, filter);\n }\n Files.walkFileTree(rootPath, new FileVisitor<Path>() {\n @Override\n public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n if (filter.acceptFile(rootPath, file)) {\n result.add(ContentRepositoryElement.createFile(formatPath(rootPath.relativize(file)), Files.size(file)));\n }\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n if (filter.acceptDirectory(rootPath, dir)) {\n String directoryPath = formatDirectoryPath(rootPath.relativize(dir));\n if(! \"/\".equals(directoryPath)) {\n result.add(ContentRepositoryElement.createFolder(directoryPath));\n }\n }\n return FileVisitResult.CONTINUE;\n }\n\n private String formatDirectoryPath(Path path) {\n return formatPath(path) + '/';\n }\n\n private String formatPath(Path path) {\n return path.toString().replace(File.separatorChar, '/');\n }\n });\n } else {\n Path file = getFile(rootPath);\n if(isArchive(file)) {\n Path relativePath = file.relativize(rootPath);\n Path target = createTempDirectory(tempDir, \"unarchive\");\n unzip(file, target);\n return listFiles(target.resolve(relativePath), tempDir, filter);\n } else {\n throw new FileNotFoundException(rootPath.toString());\n }\n }\n return result;\n }" ]
Image scale method @param imageToScale The image to be scaled @param dWidth Desired width, the new image object is created to this size @param dHeight Desired height, the new image object is created to this size @param fWidth What to multiply the width by. value < 1 scales down, and value > one scales up @param fHeight What to multiply the height by. value < 1 scales down, and value > one scales up @return A scaled image
[ "private static BufferedImage scale(BufferedImage imageToScale, int dWidth, int dHeight, double fWidth, double fHeight) {\n BufferedImage dbi = null;\n // Needed to create a new BufferedImage object\n int imageType = imageToScale.getType();\n if (imageToScale != null) {\n dbi = new BufferedImage(dWidth, dHeight, imageType);\n Graphics2D g = dbi.createGraphics();\n AffineTransform at = AffineTransform.getScaleInstance(fWidth, fHeight);\n g.drawRenderedImage(imageToScale, at);\n }\n return dbi;\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 }", "public Pixel[] pixels() {\n Pixel[] pixels = new Pixel[count()];\n Point[] points = points();\n for (int k = 0; k < points.length; k++) {\n pixels[k] = pixel(points[k]);\n }\n return pixels;\n }", "public AsciiTable setPaddingBottom(int paddingBottom) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setPaddingBottom(paddingBottom);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "private void executeRequest(HttpMethod httpMethodProxyRequest,\n HttpServletRequest httpServletRequest,\n PluginResponse httpServletResponse,\n History history) throws Exception {\n int intProxyResponseCode = 999;\n // Create a default HttpClient\n HttpClient httpClient = new HttpClient();\n HttpState state = new HttpState();\n\n try {\n httpMethodProxyRequest.setFollowRedirects(false);\n ArrayList<String> headersToRemove = getRemoveHeaders();\n\n httpClient.getParams().setSoTimeout(60000);\n\n httpServletRequest.setAttribute(\"com.groupon.odo.removeHeaders\", headersToRemove);\n\n // exception handling for httpclient\n HttpMethodRetryHandler noretryhandler = new HttpMethodRetryHandler() {\n public boolean retryMethod(\n final HttpMethod method,\n final IOException exception,\n int executionCount) {\n return false;\n }\n };\n\n httpMethodProxyRequest.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, noretryhandler);\n\n intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest.getHostConfiguration(), httpMethodProxyRequest, state);\n } catch (Exception e) {\n // Return a gateway timeout\n httpServletResponse.setStatus(504);\n httpServletResponse.setHeader(Constants.HEADER_STATUS, \"504\");\n httpServletResponse.flushBuffer();\n return;\n }\n logger.info(\"Response code: {}, {}\", intProxyResponseCode,\n HttpUtilities.getURL(httpMethodProxyRequest.getURI().toString()));\n\n // Pass the response code back to the client\n httpServletResponse.setStatus(intProxyResponseCode);\n\n // Pass response headers back to the client\n Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();\n for (Header header : headerArrayResponse) {\n // remove transfer-encoding header. The http libraries will handle this encoding\n if (header.getName().toLowerCase().equals(\"transfer-encoding\")) {\n continue;\n }\n\n httpServletResponse.setHeader(header.getName(), header.getValue());\n }\n\n // there is no data for a HTTP 304 or 204\n if (intProxyResponseCode != HttpServletResponse.SC_NOT_MODIFIED &&\n intProxyResponseCode != HttpServletResponse.SC_NO_CONTENT) {\n // Send the content to the client\n httpServletResponse.resetBuffer();\n httpServletResponse.getOutputStream().write(httpMethodProxyRequest.getResponseBody());\n }\n\n // copy cookies to servlet response\n for (Cookie cookie : state.getCookies()) {\n javax.servlet.http.Cookie servletCookie = new javax.servlet.http.Cookie(cookie.getName(), cookie.getValue());\n\n if (cookie.getPath() != null) {\n servletCookie.setPath(cookie.getPath());\n }\n\n if (cookie.getDomain() != null) {\n servletCookie.setDomain(cookie.getDomain());\n }\n\n // convert expiry date to max age\n if (cookie.getExpiryDate() != null) {\n servletCookie.setMaxAge((int) ((cookie.getExpiryDate().getTime() - System.currentTimeMillis()) / 1000));\n }\n\n servletCookie.setSecure(cookie.getSecure());\n\n servletCookie.setVersion(cookie.getVersion());\n\n if (cookie.getComment() != null) {\n servletCookie.setComment(cookie.getComment());\n }\n\n httpServletResponse.addCookie(servletCookie);\n }\n }", "public PhotoList<Photo> getPhotos(String photosetId, Set<String> extras, int privacy_filter, int perPage, int page) throws FlickrException {\r\n PhotoList<Photo> photos = new PhotoList<Photo>();\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_PHOTOS);\r\n\r\n parameters.put(\"photoset_id\", photosetId);\r\n\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", String.valueOf(perPage));\r\n }\r\n\r\n if (page > 0) {\r\n parameters.put(\"page\", String.valueOf(page));\r\n }\r\n\r\n if (privacy_filter > 0) {\r\n parameters.put(\"privacy_filter\", \"\" + privacy_filter);\r\n }\r\n\r\n if (extras != null && !extras.isEmpty()) {\r\n parameters.put(Extras.KEY_EXTRAS, StringUtilities.join(extras, \",\"));\r\n }\r\n\r\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n\r\n Element photoset = response.getPayload();\r\n NodeList photoElements = photoset.getElementsByTagName(\"photo\");\r\n photos.setPage(photoset.getAttribute(\"page\"));\r\n photos.setPages(photoset.getAttribute(\"pages\"));\r\n photos.setPerPage(photoset.getAttribute(\"per_page\"));\r\n photos.setTotal(photoset.getAttribute(\"total\"));\r\n\r\n for (int i = 0; i < photoElements.getLength(); i++) {\r\n Element photoElement = (Element) photoElements.item(i);\r\n photos.add(PhotoUtils.createPhoto(photoElement, photoset));\r\n }\r\n\r\n return photos;\r\n }", "private MapRow getRow(int index)\n {\n MapRow result;\n\n if (index == m_rows.size())\n {\n result = new MapRow(this, new HashMap<FastTrackField, Object>());\n m_rows.add(result);\n }\n else\n {\n result = m_rows.get(index);\n }\n\n return result;\n }", "public boolean exists() {\n\t\t// Try file existence: can we find the file in the file system?\n\t\ttry {\n\t\t\treturn getFile().exists();\n\t\t}\n\t\tcatch (IOException ex) {\n\t\t\t// Fall back to stream existence: can we open the stream?\n\t\t\ttry {\n\t\t\t\tInputStream is = getInputStream();\n\t\t\t\tis.close();\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tcatch (Throwable isEx) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t}", "private SubProject readSubProject(byte[] data, int uniqueIDOffset, int filePathOffset, int fileNameOffset, int subprojectIndex)\n {\n try\n {\n SubProject sp = new SubProject();\n int type = SUBPROJECT_TASKUNIQUEID0;\n\n if (uniqueIDOffset != -1)\n {\n int value = MPPUtility.getInt(data, uniqueIDOffset);\n type = MPPUtility.getInt(data, uniqueIDOffset + 4);\n switch (type)\n {\n case SUBPROJECT_TASKUNIQUEID0:\n case SUBPROJECT_TASKUNIQUEID1:\n case SUBPROJECT_TASKUNIQUEID2:\n case SUBPROJECT_TASKUNIQUEID3:\n case SUBPROJECT_TASKUNIQUEID4:\n case SUBPROJECT_TASKUNIQUEID5:\n case SUBPROJECT_TASKUNIQUEID6:\n {\n sp.setTaskUniqueID(Integer.valueOf(value));\n m_taskSubProjects.put(sp.getTaskUniqueID(), sp);\n break;\n }\n\n default:\n {\n if (value != 0)\n {\n sp.addExternalTaskUniqueID(Integer.valueOf(value));\n m_taskSubProjects.put(Integer.valueOf(value), sp);\n }\n break;\n }\n }\n\n // Now get the unique id offset for this subproject\n value = 0x00800000 + ((subprojectIndex - 1) * 0x00400000);\n sp.setUniqueIDOffset(Integer.valueOf(value));\n }\n\n if (type == SUBPROJECT_TASKUNIQUEID4)\n {\n sp.setFullPath(MPPUtility.getUnicodeString(data, filePathOffset));\n }\n else\n {\n //\n // First block header\n //\n filePathOffset += 18;\n\n //\n // String size as a 4 byte int\n //\n filePathOffset += 4;\n\n //\n // Full DOS path\n //\n sp.setDosFullPath(MPPUtility.getString(data, filePathOffset));\n filePathOffset += (sp.getDosFullPath().length() + 1);\n\n //\n // 24 byte block\n //\n filePathOffset += 24;\n\n //\n // 4 byte block size\n //\n int size = MPPUtility.getInt(data, filePathOffset);\n filePathOffset += 4;\n if (size == 0)\n {\n sp.setFullPath(sp.getDosFullPath());\n }\n else\n {\n //\n // 4 byte unicode string size in bytes\n //\n size = MPPUtility.getInt(data, filePathOffset);\n filePathOffset += 4;\n\n //\n // 2 byte data\n //\n filePathOffset += 2;\n\n //\n // Unicode string\n //\n sp.setFullPath(MPPUtility.getUnicodeString(data, filePathOffset, size));\n //filePathOffset += size;\n }\n\n //\n // Second block header\n //\n fileNameOffset += 18;\n\n //\n // String size as a 4 byte int\n //\n fileNameOffset += 4;\n\n //\n // DOS file name\n //\n sp.setDosFileName(MPPUtility.getString(data, fileNameOffset));\n fileNameOffset += (sp.getDosFileName().length() + 1);\n\n //\n // 24 byte block\n //\n fileNameOffset += 24;\n\n //\n // 4 byte block size\n //\n size = MPPUtility.getInt(data, fileNameOffset);\n fileNameOffset += 4;\n\n if (size == 0)\n {\n sp.setFileName(sp.getDosFileName());\n }\n else\n {\n //\n // 4 byte unicode string size in bytes\n //\n size = MPPUtility.getInt(data, fileNameOffset);\n fileNameOffset += 4;\n\n //\n // 2 byte data\n //\n fileNameOffset += 2;\n\n //\n // Unicode string\n //\n sp.setFileName(MPPUtility.getUnicodeString(data, fileNameOffset, size));\n //fileNameOffset += size;\n }\n }\n\n //System.out.println(sp.toString());\n\n // Add to the list of subprojects\n m_file.getSubProjects().add(sp);\n\n return (sp);\n }\n\n //\n // Admit defeat at this point - we have probably stumbled\n // upon a data format we don't understand, so we'll fail\n // gracefully here. This will now be reported as a missing\n // sub project error by end users of the library, rather\n // than as an exception being thrown.\n //\n catch (ArrayIndexOutOfBoundsException ex)\n {\n return (null);\n }\n }", "protected void checkConflictingRoles() {\n if (getType().isAnnotationPresent(Interceptor.class)) {\n throw BeanLogger.LOG.ejbCannotBeInterceptor(getType());\n }\n if (getType().isAnnotationPresent(Decorator.class)) {\n throw BeanLogger.LOG.ejbCannotBeDecorator(getType());\n }\n }" ]
Initialize the pattern choice button group.
[ "private void initPatternButtonGroup() {\n\n m_groupPattern = new CmsRadioButtonGroup();\n m_patternButtons = new HashMap<>();\n\n createAndAddButton(PatternType.DAILY, Messages.GUI_SERIALDATE_TYPE_DAILY_0);\n m_patternButtons.put(PatternType.NONE, m_patternButtons.get(PatternType.DAILY));\n createAndAddButton(PatternType.WEEKLY, Messages.GUI_SERIALDATE_TYPE_WEEKLY_0);\n createAndAddButton(PatternType.MONTHLY, Messages.GUI_SERIALDATE_TYPE_MONTHLY_0);\n createAndAddButton(PatternType.YEARLY, Messages.GUI_SERIALDATE_TYPE_YEARLY_0);\n // createAndAddButton(PatternType.INDIVIDUAL, Messages.GUI_SERIALDATE_TYPE_INDIVIDUAL_0);\n\n m_groupPattern.addValueChangeHandler(new ValueChangeHandler<String>() {\n\n public void onValueChange(ValueChangeEvent<String> event) {\n\n if (handleChange()) {\n String value = event.getValue();\n if (value != null) {\n m_controller.setPattern(value);\n }\n }\n }\n });\n\n }" ]
[ "public static void waitForStandalone(final ModelControllerClient client, final long startupTimeout)\n throws InterruptedException, RuntimeException, TimeoutException {\n waitForStandalone(null, client, startupTimeout);\n }", "public void rotateToFront() {\n GVRTransform transform = mSceneRootObject.getTransform();\n transform.setRotation(1, 0, 0, 0);\n transform.rotateByAxisWithPivot(-frontFacingRotation + 180, 0, 1, 0, 0, 0, 0);\n }", "public static <T, R extends Resource<T>> T getEntity(R resource) {\n return resource.getEntity();\n }", "public static Bytes toBytes(Text t) {\n return Bytes.of(t.getBytes(), 0, t.getLength());\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}", "public MessageSet read(long readOffset, long size) throws IOException {\n return new FileMessageSet(channel, this.offset + readOffset, //\n Math.min(this.offset + readOffset + size, highWaterMark()), false, new AtomicBoolean(false));\n }", "private Envelope getBoundsLocal(Filter filter) throws LayerException {\n\t\ttry {\n\t\t\tSession session = getSessionFactory().getCurrentSession();\n\t\t\tCriteria criteria = session.createCriteria(getFeatureInfo().getDataSourceName());\n\t\t\tCriteriaVisitor visitor = new CriteriaVisitor((HibernateFeatureModel) getFeatureModel(), dateFormat);\n\t\t\tCriterion c = (Criterion) filter.accept(visitor, criteria);\n\t\t\tif (c != null) {\n\t\t\t\tcriteria.add(c);\n\t\t\t}\n\t\t\tcriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);\n\t\t\tList<?> features = criteria.list();\n\t\t\tEnvelope bounds = new Envelope();\n\t\t\tfor (Object f : features) {\n\t\t\t\tEnvelope geomBounds = getFeatureModel().getGeometry(f).getEnvelopeInternal();\n\t\t\t\tif (!geomBounds.isNull()) {\n\t\t\t\t\tbounds.expandToInclude(geomBounds);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn bounds;\n\t\t} catch (HibernateException he) {\n\t\t\tthrow new HibernateLayerException(he, ExceptionCode.HIBERNATE_LOAD_FILTER_FAIL, getFeatureInfo()\n\t\t\t\t\t.getDataSourceName(), filter.toString());\n\t\t}\n\t}", "public synchronized void setSendingStatus(boolean send) throws IOException {\n if (isSendingStatus() == send) {\n return;\n }\n\n if (send) { // Start sending status packets.\n ensureRunning();\n if ((getDeviceNumber() < 1) || (getDeviceNumber() > 4)) {\n throw new IllegalStateException(\"Can only send status when using a standard player number, 1 through 4.\");\n }\n\n BeatFinder.getInstance().start();\n BeatFinder.getInstance().addLifecycleListener(beatFinderLifecycleListener);\n\n final AtomicBoolean stillRunning = new AtomicBoolean(true);\n sendingStatus = stillRunning; // Allow other threads to stop us when necessary.\n\n Thread sender = new Thread(null, new Runnable() {\n @Override\n public void run() {\n while (stillRunning.get()) {\n sendStatus();\n try {\n Thread.sleep(getStatusInterval());\n } catch (InterruptedException e) {\n logger.warn(\"beat-link VirtualCDJ status sender thread was interrupted; continuing\");\n }\n }\n }\n }, \"beat-link VirtualCdj status sender\");\n sender.setDaemon(true);\n sender.start();\n\n if (isSynced()) { // If we are supposed to be synced, we need to respond to master beats and tempo changes.\n addMasterListener(ourSyncMasterListener);\n }\n\n if (isPlaying()) { // Start the beat sender too, if we are supposed to be playing.\n beatSender.set(new BeatSender(metronome));\n }\n } else { // Stop sending status packets, and responding to master beats and tempo changes if we were synced.\n BeatFinder.getInstance().removeLifecycleListener(beatFinderLifecycleListener);\n removeMasterListener(ourSyncMasterListener);\n\n sendingStatus.set(false); // Stop the status sending thread.\n sendingStatus = null; // Indicate that we are no longer sending status.\n final BeatSender activeSender = beatSender.get(); // And stop the beat sender if we have one.\n if (activeSender != null) {\n activeSender.shutDown();\n beatSender.set(null);\n }\n }\n }", "public static void logBeforeExit(ExitLogger logger) {\n try {\n if (logged.compareAndSet(false, true)) {\n logger.logExit();\n }\n } catch (Throwable ignored){\n // ignored\n }\n }" ]
Copies the non-zero structure of orig into "this" @param orig Matrix who's structure is to be copied
[ "public void copyStructure( DMatrixSparseCSC orig ) {\n reshape(orig.numRows, orig.numCols, orig.nz_length);\n this.nz_length = orig.nz_length;\n System.arraycopy(orig.col_idx,0,col_idx,0,orig.numCols+1);\n System.arraycopy(orig.nz_rows,0,nz_rows,0,orig.nz_length);\n }" ]
[ "private URL[] getClasspath(JobInstance ji, JobRunnerCallback cb) throws JqmPayloadException\n {\n switch (ji.getJD().getPathType())\n {\n case MAVEN:\n return mavenResolver.resolve(ji);\n case MEMORY:\n return new URL[0];\n case FS:\n default:\n return fsResolver.getLibraries(ji.getNode(), ji.getJD());\n }\n }", "public void setDividerPadding(float padding, final Axis axis) {\n if (!equal(mDividerPadding.get(axis), padding)) {\n mDividerPadding.set(padding, axis);\n if (mContainer != null) {\n mContainer.onLayoutChanged(this);\n }\n }\n }", "public static server_service_binding[] get(nitro_service service, String name) throws Exception{\n\t\tserver_service_binding obj = new server_service_binding();\n\t\tobj.set_name(name);\n\t\tserver_service_binding response[] = (server_service_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static String fromClassPath() {\n Set<String> versions = new HashSet<>();\n try {\n ClassLoader classLoader = Thread.currentThread().getContextClassLoader();\n Enumeration<URL> manifests = classLoader.getResources(\"META-INF/MANIFEST.MF\");\n\n while (manifests.hasMoreElements()) {\n URL manifestURL = manifests.nextElement();\n try (InputStream is = manifestURL.openStream()) {\n Manifest manifest = new Manifest();\n manifest.read(is);\n\n Attributes buildInfo = manifest.getAttributes(\"Build-Info\");\n if (buildInfo != null) {\n if (buildInfo.getValue(\"Selenium-Version\") != null) {\n versions.add(buildInfo.getValue(\"Selenium-Version\"));\n } else {\n // might be in build-info part\n if (manifest.getEntries() != null) {\n if (manifest.getEntries().containsKey(\"Build-Info\")) {\n final Attributes attributes = manifest.getEntries().get(\"Build-Info\");\n\n if (attributes.getValue(\"Selenium-Version\") != null) {\n versions.add(attributes.getValue(\"Selenium-Version\"));\n }\n }\n }\n }\n }\n }\n }\n } catch (Exception e) {\n logger.log(Level.WARNING,\n \"Exception {0} occurred while resolving selenium version and latest image is going to be used.\",\n e.getMessage());\n return SELENIUM_VERSION;\n }\n\n if (versions.isEmpty()) {\n logger.log(Level.INFO, \"No version of Selenium found in classpath. Using latest image.\");\n return SELENIUM_VERSION;\n }\n\n String foundVersion = versions.iterator().next();\n if (versions.size() > 1) {\n logger.log(Level.WARNING, \"Multiple versions of Selenium found in classpath. Using the first one found {0}.\",\n foundVersion);\n }\n\n return foundVersion;\n }", "public static void handleDomainOperationResponseStreams(final OperationContext context,\n final ModelNode responseNode,\n final List<OperationResponse.StreamEntry> streams) {\n\n if (responseNode.hasDefined(RESPONSE_HEADERS)) {\n ModelNode responseHeaders = responseNode.get(RESPONSE_HEADERS);\n // Strip out any stream header as the header created by this process is what counts\n responseHeaders.remove(ATTACHED_STREAMS);\n if (responseHeaders.asInt() == 0) {\n responseNode.remove(RESPONSE_HEADERS);\n }\n }\n\n for (OperationResponse.StreamEntry streamEntry : streams) {\n context.attachResultStream(streamEntry.getUUID(), streamEntry.getMimeType(), streamEntry.getStream());\n }\n }", "public void recordServerResult(ServerIdentity server, ModelNode response) {\n\n if (!serverGroupName.equals(server.getServerGroupName()) || !servers.contains(server)) {\n throw DomainControllerLogger.HOST_CONTROLLER_LOGGER.unknownServer(server);\n }\n\n boolean serverFailed = response.has(FAILURE_DESCRIPTION);\n\n\n DomainControllerLogger.HOST_CONTROLLER_LOGGER.tracef(\"Recording server result for '%s': failed = %s\",\n server, server);\n\n synchronized (this) {\n int previousFailed = failureCount;\n if (serverFailed) {\n failureCount++;\n }\n else {\n successCount++;\n }\n if (previousFailed <= maxFailed) {\n if (!serverFailed && (successCount + failureCount) == servers.size()) {\n // All results are in; notify parent of success\n parent.recordServerGroupResult(serverGroupName, false);\n }\n else if (serverFailed && failureCount > maxFailed) {\n parent.recordServerGroupResult(serverGroupName, true);\n }\n }\n }\n }", "public static 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 }", "private static boolean waitTillNoNotifications(Environment env, TableRange range)\n throws TableNotFoundException {\n boolean sawNotifications = false;\n long retryTime = MIN_SLEEP_MS;\n\n log.debug(\"Scanning tablet {} for notifications\", range);\n\n long start = System.currentTimeMillis();\n while (hasNotifications(env, range)) {\n sawNotifications = true;\n long sleepTime = Math.max(System.currentTimeMillis() - start, retryTime);\n log.debug(\"Tablet {} had notfications, will rescan in {}ms\", range, sleepTime);\n UtilWaitThread.sleep(sleepTime);\n retryTime = Math.min(MAX_SLEEP_MS, (long) (retryTime * 1.5));\n start = System.currentTimeMillis();\n }\n\n return sawNotifications;\n }", "public static void pullImage(String imageTag, String username, String password, String host) throws IOException {\n final AuthConfig authConfig = new AuthConfig();\n authConfig.withUsername(username);\n authConfig.withPassword(password);\n\n DockerClient dockerClient = null;\n try {\n dockerClient = getDockerClient(host);\n dockerClient.pullImageCmd(imageTag).withAuthConfig(authConfig).exec(new PullImageResultCallback()).awaitSuccess();\n } finally {\n closeQuietly(dockerClient);\n }\n }" ]
Returns the property value read from the given JavaBean. @param bean the JavaBean to read the property from @param property the property to read @return the property value read from the given JavaBean
[ "protected Object getMacroBeanValue(Object bean, String property) {\n\n Object result = null;\n if ((bean != null) && CmsStringUtil.isNotEmptyOrWhitespaceOnly(property)) {\n try {\n PropertyUtilsBean propBean = BeanUtilsBean.getInstance().getPropertyUtils();\n result = propBean.getProperty(bean, property);\n } catch (Exception e) {\n LOG.error(\"Unable to access property '\" + property + \"' of '\" + bean + \"'.\", e);\n }\n } else {\n LOG.info(\"Invalid parameters: property='\" + property + \"' bean='\" + bean + \"'.\");\n }\n return result;\n }" ]
[ "@SuppressWarnings(\"unchecked\")\n private static synchronized Map<String, Boolean> getCache(GraphRewrite event)\n {\n Map<String, Boolean> result = (Map<String, Boolean>)event.getRewriteContext().get(ClassificationServiceCache.class);\n if (result == null)\n {\n result = Collections.synchronizedMap(new LRUMap(30000));\n event.getRewriteContext().put(ClassificationServiceCache.class, result);\n }\n return result;\n }", "private static void loadFile(String filePath) {\n final Path path = FileSystems.getDefault().getPath(filePath);\n\n try {\n data.clear();\n data.load(Files.newBufferedReader(path));\n } catch(IOException e) {\n LOG.warn(\"Exception while loading \" + path.toString(), e);\n }\n }", "public void setAll() {\n\tshowAttributes = true;\n\tshowEnumerations = true;\n\tshowEnumConstants = true;\n\tshowOperations = true;\n\tshowConstructors = true;\n\tshowVisibility = true;\n\tshowType = true;\n }", "private void updateScheduleSource(ProjectProperties properties)\n {\n // Rudimentary identification of schedule source\n if (properties.getCompany() != null && properties.getCompany().equals(\"Synchro Software Ltd\"))\n {\n properties.setFileApplication(\"Synchro\");\n }\n else\n {\n if (properties.getAuthor() != null && properties.getAuthor().equals(\"SG Project\"))\n {\n properties.setFileApplication(\"Simple Genius\");\n }\n else\n {\n properties.setFileApplication(\"Microsoft\");\n }\n }\n properties.setFileType(\"MSPDI\");\n }", "private static Point findMidnormalPoint(Point center, Point a, Point b, Rect area, int radius) {\n if (a.y == b.y) {\n //top\n if (a.y < center.y) {\n return new Point((a.x + b.x) / 2, center.y + radius);\n }\n //bottom\n return new Point((a.x + b.x) / 2, center.y - radius);\n }\n if (a.x == b.x) {\n //left\n if (a.x < center.x) {\n return new Point(center.x + radius, (a.y + b.y) / 2);\n }\n //right\n return new Point(center.x - radius, (a.y + b.y) / 2);\n }\n //slope of line ab\n double abSlope = (a.y - b.y) / (a.x - b.x * 1.0);\n //slope of midnormal\n double midnormalSlope = -1.0 / abSlope;\n\n double radian = Math.tan(midnormalSlope);\n int dy = (int) (radius * Math.sin(radian));\n int dx = (int) (radius * Math.cos(radian));\n Point point = new Point(center.x + dx, center.y + dy);\n if (!inArea(point, area, 0)) {\n point = new Point(center.x - dx, center.y - dy);\n }\n return point;\n }", "public Set<RGBColor> colours() {\n return stream().map(Pixel::toColor).collect(Collectors.toSet());\n }", "private void setCalendarToLastRelativeDay(Calendar calendar)\n {\n calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));\n int currentDayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);\n int requiredDayOfWeek = getDayOfWeek().getValue();\n int dayOfWeekOffset = 0;\n\n if (currentDayOfWeek > requiredDayOfWeek)\n {\n dayOfWeekOffset = requiredDayOfWeek - currentDayOfWeek;\n }\n else\n {\n if (currentDayOfWeek < requiredDayOfWeek)\n {\n dayOfWeekOffset = -7 + (requiredDayOfWeek - currentDayOfWeek);\n }\n }\n\n if (dayOfWeekOffset != 0)\n {\n calendar.add(Calendar.DAY_OF_YEAR, dayOfWeekOffset);\n }\n }", "protected Violation createViolationForImport(SourceCode sourceCode, String className, String alias, String violationMessage) {\n Map importInfo = ImportUtil.sourceLineAndNumberForImport(sourceCode, className, alias);\n Violation violation = new Violation();\n violation.setRule(this);\n violation.setSourceLine((String) importInfo.get(\"sourceLine\"));\n violation.setLineNumber((Integer) importInfo.get(\"lineNumber\"));\n violation.setMessage(violationMessage);\n return violation;\n }", "public JsonTypeDefinition projectionType(String... properties) {\n if(this.getType() instanceof Map<?, ?>) {\n Map<?, ?> type = (Map<?, ?>) getType();\n Arrays.sort(properties);\n Map<String, Object> newType = new LinkedHashMap<String, Object>();\n for(String prop: properties)\n newType.put(prop, type.get(prop));\n return new JsonTypeDefinition(newType);\n } else {\n throw new IllegalArgumentException(\"Cannot take the projection of a type that is not a Map.\");\n }\n }" ]
Returns the export format indicated in the result-type parameter "layoutManager" @param _invocation @return
[ "protected LayoutManager getLayOutManagerObj(ActionInvocation _invocation) {\n\t\tif (layoutManager == null || \"\".equals(layoutManager)){\n\t\t\tLOG.warn(\"No valid LayoutManager, using ClassicLayoutManager\");\n\t\t\treturn new ClassicLayoutManager();\n\t\t}\n\n\t\tObject los = conditionalParse(layoutManager, _invocation);\n\n\t\tif (los instanceof LayoutManager){\n\t\t\treturn (LayoutManager) los;\n\t\t}\n\n\t\tLayoutManager lo = null;\n\t\tif (los instanceof String){\n\t\t\tif (LAYOUT_CLASSIC.equalsIgnoreCase((String) los))\n\t\t\t\tlo = new ClassicLayoutManager();\n\t\t\telse if (LAYOUT_LIST.equalsIgnoreCase((String) los))\n\t\t\t\tlo = new ListLayoutManager();\n\t\t\telse {\n\t\t\t\ttry {\n\t\t\t\t\tlo = (LayoutManager) Class.forName((String) los).newInstance();\n\t\t\t\t} catch (Exception e) {\n\t\t\t\t\tLOG.warn(\"No valid LayoutManager: \" + e.getMessage(),e);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn lo;\n\t}" ]
[ "public static sslpolicylabel[] get(nitro_service service) throws Exception{\n\t\tsslpolicylabel obj = new sslpolicylabel();\n\t\tsslpolicylabel[] response = (sslpolicylabel[])obj.get_resources(service);\n\t\treturn response;\n\t}", "@SuppressWarnings(\"unchecked\")\n protected String addPostRunDependent(Appliable<? extends Indexable> appliable) {\n TaskGroup.HasTaskGroup dependency = (TaskGroup.HasTaskGroup) appliable;\n return this.addPostRunDependent(dependency);\n }", "public static final TimeUnit parseWorkUnits(BigInteger value)\n {\n TimeUnit result = TimeUnit.HOURS;\n\n if (value != null)\n {\n switch (value.intValue())\n {\n case 1:\n {\n result = TimeUnit.MINUTES;\n break;\n }\n\n case 3:\n {\n result = TimeUnit.DAYS;\n break;\n }\n\n case 4:\n {\n result = TimeUnit.WEEKS;\n break;\n }\n\n case 5:\n {\n result = TimeUnit.MONTHS;\n break;\n }\n\n case 7:\n {\n result = TimeUnit.YEARS;\n break;\n }\n\n default:\n case 2:\n {\n result = TimeUnit.HOURS;\n break;\n }\n }\n }\n\n return (result);\n }", "public GroovyFieldDoc[] enumConstants() {\n Collections.sort(enumConstants);\n return enumConstants.toArray(new GroovyFieldDoc[enumConstants.size()]);\n }", "public static void createUsers(GreenMailOperations greenMail, InternetAddress... addresses) {\n for (InternetAddress address : addresses) {\n greenMail.setUser(address.getAddress(), address.getAddress());\n }\n }", "private Criteria buildPrefetchCriteriaMultipleKeys(Collection ids, FieldDescriptor fields[])\r\n {\r\n Criteria crit = new Criteria();\r\n Iterator iter = ids.iterator();\r\n Object[] val;\r\n Identity id;\r\n\r\n while (iter.hasNext())\r\n {\r\n Criteria c = new Criteria();\r\n id = (Identity) iter.next();\r\n val = id.getPrimaryKeyValues();\r\n for (int i = 0; i < val.length; i++)\r\n {\r\n if (val[i] == null)\r\n {\r\n c.addIsNull(fields[i].getAttributeName());\r\n }\r\n else\r\n {\r\n c.addEqualTo(fields[i].getAttributeName(), val[i]);\r\n }\r\n }\r\n crit.addOrCriteria(c);\r\n }\r\n\r\n return crit;\r\n }", "public static boolean check(String passwd, String hashed) {\n try {\n String[] parts = hashed.split(\"\\\\$\");\n\n if (parts.length != 5 || !parts[1].equals(\"s0\")) {\n throw new IllegalArgumentException(\"Invalid hashed value\");\n }\n\n long params = Long.parseLong(parts[2], 16);\n byte[] salt = decode(parts[3].toCharArray());\n byte[] derived0 = decode(parts[4].toCharArray());\n\n int N = (int) Math.pow(2, params >> 16 & 0xffff);\n int r = (int) params >> 8 & 0xff;\n int p = (int) params & 0xff;\n\n byte[] derived1 = SCrypt.scrypt(passwd.getBytes(\"UTF-8\"), salt, N, r, p, 32);\n\n if (derived0.length != derived1.length) return false;\n\n int result = 0;\n for (int i = 0; i < derived0.length; i++) {\n result |= derived0[i] ^ derived1[i];\n }\n return result == 0;\n } catch (UnsupportedEncodingException e) {\n throw new IllegalStateException(\"JVM doesn't support UTF-8?\");\n } catch (GeneralSecurityException e) {\n throw new IllegalStateException(\"JVM doesn't support SHA1PRNG or HMAC_SHA256?\");\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 }", "public void onCreate(T content, LayoutInflater layoutInflater, ViewGroup parent) {\n this.content = content;\n this.rootView = inflate(layoutInflater, parent);\n if (rootView == null) {\n throw new NotInflateViewException(\n \"Renderer instances have to return a not null view in inflateView method\");\n }\n this.rootView.setTag(this);\n setUpView(rootView);\n hookListeners(rootView);\n }" ]
Unregister the mbean with the given name from the platform mbean server @param name The name of the mbean to unregister
[ "public static void unregisterMbean(ObjectName name) {\n try {\n ManagementFactory.getPlatformMBeanServer().unregisterMBean(name);\n } catch(Exception e) {\n logger.error(\"Error unregistering mbean\", e);\n }\n }" ]
[ "public int getFaceNumIndices(int face) {\n if (null == m_faceOffsets) {\n if (face >= m_numFaces || face < 0) {\n throw new IndexOutOfBoundsException(\"Index: \" + face + \n \", Size: \" + m_numFaces);\n }\n return 3;\n }\n else {\n /* \n * no need to perform bound checks here as the array access will\n * throw IndexOutOfBoundsExceptions if the index is invalid\n */\n \n if (face == m_numFaces - 1) {\n return m_faces.capacity() / 4 - m_faceOffsets.getInt(face * 4);\n }\n \n return m_faceOffsets.getInt((face + 1) * 4) - \n m_faceOffsets.getInt(face * 4);\n }\n }", "private static Map<String, List<String>> getOrCreateProtocolHeader(\n Message message) {\n Map<String, List<String>> headers = CastUtils.cast((Map<?, ?>) message\n .get(Message.PROTOCOL_HEADERS));\n if (headers == null) {\n headers = new HashMap<String, List<String>>();\n message.put(Message.PROTOCOL_HEADERS, headers);\n }\n return headers;\n }", "public byte[] toByteArray() {\n try {\n ByteArrayOutputStream baos = new ByteArrayOutputStream();\n ObjectOutputStream oos = new ObjectOutputStream(baos);\n oos.writeObject(this);\n return baos.toByteArray();\n } catch (IOException e) {\n throw E.ioException(e);\n }\n }", "public static <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 static base_responses clear(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 clearresources[] = new route6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tclearresources[i] = new route6();\n\t\t\t\tclearresources[i].routetype = resources[i].routetype;\n\t\t\t}\n\t\t\tresult = perform_operation_bulk_request(client, clearresources,\"clear\");\n\t\t}\n\t\treturn result;\n\t}", "public static AT_Row createContentRow(Object[] content, TableRowStyle style){\r\n\t\tValidate.notNull(content);\r\n\t\tValidate.notNull(style);\r\n\t\tValidate.validState(style!=TableRowStyle.UNKNOWN);\r\n\r\n\t\tLinkedList<AT_Cell> cells = new LinkedList<AT_Cell>();\r\n\t\tfor(Object o : content){\r\n\t\t\tcells.add(new AT_Cell(o));\r\n\t\t}\r\n\r\n\t\treturn new AT_Row(){\r\n\t\t\t@Override\r\n\t\t\tpublic TableRowType getType(){\r\n\t\t\t\treturn TableRowType.CONTENT;\r\n\t\t\t}\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic TableRowStyle getStyle(){\r\n\t\t\t\treturn style;\r\n\t\t\t}\r\n\r\n\t\t\t@Override\r\n\t\t\tpublic LinkedList<AT_Cell> getCells(){\r\n\t\t\t\treturn cells;\r\n\t\t\t}\r\n\t\t};\r\n\t}", "public static ModelControllerClient createReceiving(final Channel channel, final ExecutorService executorService) {\n final ManagementClientChannelStrategy strategy = ManagementClientChannelStrategy.create(channel);\n final ManagementChannelHandler handler = new ManagementChannelHandler(strategy, executorService);\n final ExistingChannelModelControllerClient client = new ExistingChannelModelControllerClient(handler);\n handler.addHandlerFactory(client);\n channel.addCloseHandler(new CloseHandler<Channel>() {\n @Override\n public void handleClose(Channel closed, IOException exception) {\n handler.shutdown();\n try {\n handler.awaitCompletion(1, TimeUnit.SECONDS);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n } finally {\n handler.shutdownNow();\n }\n }\n });\n channel.receiveMessage(handler.getReceiver());\n return client;\n }", "public Counter<K1> sumInnerCounter() {\r\n Counter<K1> summed = new ClassicCounter<K1>();\r\n for (K1 key : this.firstKeySet()) {\r\n summed.incrementCount(key, this.getCounter(key).totalCount());\r\n }\r\n return summed;\r\n }", "private TreeMap<Integer, Integer> createResourceMap(FieldMap fieldMap, FixedMeta rscFixedMeta, FixedData rscFixedData)\n {\n TreeMap<Integer, Integer> resourceMap = new TreeMap<Integer, Integer>();\n int itemCount = rscFixedMeta.getAdjustedItemCount();\n\n for (int loop = 0; loop < itemCount; loop++)\n {\n byte[] data = rscFixedData.getByteArrayValue(loop);\n if (data == null || data.length < fieldMap.getMaxFixedDataSize(0))\n {\n continue;\n }\n\n Integer uniqueID = Integer.valueOf(MPPUtility.getShort(data, 0));\n resourceMap.put(uniqueID, Integer.valueOf(loop));\n }\n\n return (resourceMap);\n }" ]
Return a list of websocket connection by key @param key the key to find the websocket connection list @return a list of websocket connection or an empty list if no websocket connection found by key
[ "public List<WebSocketConnection> get(String key) {\n final List<WebSocketConnection> retList = new ArrayList<>();\n accept(key, C.F.addTo(retList));\n return retList;\n }" ]
[ "public ProgressBar stop() {\n target.kill();\n try {\n thread.join();\n target.consoleStream.print(\"\\n\");\n target.consoleStream.flush();\n }\n catch (InterruptedException ex) { }\n return this;\n }", "@Pure\n\t@Inline(value = \"$3.union($1, $2)\", imported = MapExtensions.class)\n\tpublic static <K, V> Map<K, V> operator_plus(Map<K, V> left, Map<? extends K, ? extends V> right) {\n\t\treturn union(left, right);\n\t}", "public static appfwpolicy_stats get(nitro_service service, String name) throws Exception{\n\t\tappfwpolicy_stats obj = new appfwpolicy_stats();\n\t\tobj.set_name(name);\n\t\tappfwpolicy_stats response = (appfwpolicy_stats) obj.stat_resource(service);\n\t\treturn response;\n\t}", "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 static int getActionBarHeight(Context context) {\n int actionBarHeight = UIUtils.getThemeAttributeDimensionSize(context, R.attr.actionBarSize);\n if (actionBarHeight == 0) {\n actionBarHeight = context.getResources().getDimensionPixelSize(R.dimen.abc_action_bar_default_height_material);\n }\n return actionBarHeight;\n }", "public static lbmonbindings_servicegroup_binding[] get(nitro_service service, String monitorname) throws Exception{\n\t\tlbmonbindings_servicegroup_binding obj = new lbmonbindings_servicegroup_binding();\n\t\tobj.set_monitorname(monitorname);\n\t\tlbmonbindings_servicegroup_binding response[] = (lbmonbindings_servicegroup_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public int expect(String pattern) throws MalformedPatternException, Exception {\n logger.trace(\"Searching for '\" + pattern + \"' in the reader stream\");\n return expect(pattern, null);\n }", "void merge(Archetype flatParent, Archetype specialized) {\n expandAttributeNodes(specialized.getDefinition());\n\n flattenCObject(RmPath.ROOT, null, flatParent.getDefinition(), specialized.getDefinition());\n\n\n mergeOntologies(flatParent.getTerminology(), specialized.getTerminology());\n if (flatParent.getAnnotations() != null) {\n if (specialized.getAnnotations() == null) {\n specialized.setAnnotations(new ResourceAnnotations());\n }\n annotationsMerger.merge(flatParent.getAnnotations().getItems(), specialized.getAnnotations().getItems());\n }\n }", "private void performDownload(HttpResponse response, File destFile)\n throws IOException {\n HttpEntity entity = response.getEntity();\n if (entity == null) {\n return;\n }\n \n //get content length\n long contentLength = entity.getContentLength();\n if (contentLength >= 0) {\n size = toLengthText(contentLength);\n }\n \n processedBytes = 0;\n loggedKb = 0;\n \n //open stream and start downloading\n InputStream is = entity.getContent();\n streamAndMove(is, destFile);\n }" ]
Checks whether a String satisfies the number range selection filter. The test is evaluated based on the rightmost natural number found in the String. Note that this is just evaluated on the String as given. It is not trying to interpret it as a filename and to decide whether the file exists, is a directory or anything like that. @param str The String to check for a number in @return true If the String is within the ranges filtered for
[ "public boolean accept(String str) {\r\n int k = str.length() - 1;\r\n char c = str.charAt(k);\r\n while (k >= 0 && !Character.isDigit(c)) {\r\n k--;\r\n if (k >= 0) {\r\n c = str.charAt(k);\r\n }\r\n }\r\n if (k < 0) {\r\n return false;\r\n }\r\n int j = k;\r\n c = str.charAt(j);\r\n while (j >= 0 && Character.isDigit(c)) {\r\n j--;\r\n if (j >= 0) {\r\n c = str.charAt(j);\r\n }\r\n }\r\n j++;\r\n k++;\r\n String theNumber = str.substring(j, k);\r\n int number = Integer.parseInt(theNumber);\r\n for (Pair<Integer,Integer> p : ranges) {\r\n int low = p.first().intValue();\r\n int high = p.second().intValue();\r\n if (number >= low && number <= high) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n }" ]
[ "protected String toHexString(boolean with0xPrefix, CharSequence zone) {\n\t\tif(isDualString()) {\n\t\t\treturn toNormalizedStringRange(toIPParams(with0xPrefix ? IPStringCache.hexPrefixedParams : IPStringCache.hexParams), getLower(), getUpper(), zone);\n\t\t}\n\t\treturn toIPParams(with0xPrefix ? IPStringCache.hexPrefixedParams : IPStringCache.hexParams).toString(this, zone);\n\t}", "public static final String printAccrueType(AccrueType value)\n {\n return (Integer.toString(value == null ? AccrueType.PRORATED.getValue() : value.getValue()));\n }", "private File getWorkDir() throws IOException\r\n {\r\n if (_workDir == null)\r\n { \r\n File dummy = File.createTempFile(\"dummy\", \".log\");\r\n String workDir = dummy.getPath().substring(0, dummy.getPath().lastIndexOf(File.separatorChar));\r\n \r\n if ((workDir == null) || (workDir.length() == 0))\r\n {\r\n workDir = \".\";\r\n }\r\n dummy.delete();\r\n _workDir = new File(workDir);\r\n }\r\n return _workDir;\r\n }", "public Object selectElement(String predicate) throws org.odmg.QueryInvalidException\r\n {\r\n return ((DList) this.query(predicate)).get(0);\r\n }", "private void processCustomFieldValues()\n {\n byte[] data = m_projectProps.getByteArray(Props.TASK_FIELD_ATTRIBUTES);\n if (data != null)\n {\n int index = 0;\n int offset = 0;\n // First the length\n int length = MPPUtility.getInt(data, offset);\n offset += 4;\n // Then the number of custom value lists\n int numberOfValueLists = MPPUtility.getInt(data, offset);\n offset += 4;\n\n // Then the value lists themselves\n FieldType field;\n int valueListOffset = 0;\n while (index < numberOfValueLists && offset < length)\n {\n // Each item consists of the Field ID (4 bytes) and the offset to the value list (4 bytes)\n\n // Get the Field\n field = FieldTypeHelper.getInstance(MPPUtility.getInt(data, offset));\n offset += 4;\n\n // Get the value list offset\n valueListOffset = MPPUtility.getInt(data, offset);\n offset += 4;\n // Read the value list itself\n if (valueListOffset < data.length)\n {\n int tempOffset = valueListOffset;\n tempOffset += 8;\n // Get the data offset\n int dataOffset = MPPUtility.getInt(data, tempOffset) + valueListOffset;\n tempOffset += 4;\n // Get the end of the data offset\n int endDataOffset = MPPUtility.getInt(data, tempOffset) + valueListOffset;\n tempOffset += 4;\n // Get the end of the description\n int endDescriptionOffset = MPPUtility.getInt(data, tempOffset) + valueListOffset;\n\n // Get the values themselves\n int valuesLength = endDataOffset - dataOffset;\n byte[] values = new byte[valuesLength];\n MPPUtility.getByteArray(data, dataOffset, valuesLength, values, 0);\n\n // Get the descriptions\n int descriptionsLength = endDescriptionOffset - endDataOffset;\n byte[] descriptions = new byte[descriptionsLength];\n MPPUtility.getByteArray(data, endDataOffset, descriptionsLength, descriptions, 0);\n\n populateContainer(field, values, descriptions);\n }\n index++;\n }\n }\n }", "public ItemRequest<CustomField> findById(String customField) {\n \n String path = String.format(\"/custom_fields/%s\", customField);\n return new ItemRequest<CustomField>(this, CustomField.class, path, \"GET\");\n }", "@Override\n\tpublic int getMinPrefixLengthForBlock() {\n\t\tint count = getDivisionCount();\n\t\tint totalPrefix = getBitCount();\n\t\tfor(int i = count - 1; i >= 0 ; i--) {\n\t\t\tAddressDivisionBase div = getDivision(i);\n\t\t\tint segBitCount = div.getBitCount();\n\t\t\tint segPrefix = div.getMinPrefixLengthForBlock();\n\t\t\tif(segPrefix == segBitCount) {\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\ttotalPrefix -= segBitCount;\n\t\t\t\tif(segPrefix != 0) {\n\t\t\t\t\ttotalPrefix += segPrefix;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn totalPrefix;\n\t}", "public List<ProjectListType.Project> getProject()\n {\n if (project == null)\n {\n project = new ArrayList<ProjectListType.Project>();\n }\n return this.project;\n }", "public Collection<V> put(K key, Collection<V> collection) {\r\n return map.put(key, collection);\r\n }" ]
Check given class modifiers. Plugin with resources plugin should not be private or abstract or interface.
[ "private static boolean checkModifiers(Class<? extends AbstractPlugin> pluginClass) {\n int modifiers = pluginClass.getModifiers();\n return !Modifier.isAbstract(modifiers) &&\n !Modifier.isInterface(modifiers) &&\n !Modifier.isPrivate(modifiers);\n }" ]
[ "public boolean doSyncPass() {\n if (!this.isConfigured || !syncLock.tryLock()) {\n return false;\n }\n try {\n if (logicalT == Long.MAX_VALUE) {\n if (logger.isInfoEnabled()) {\n logger.info(\"reached max logical time; resetting back to 0\");\n }\n logicalT = 0;\n }\n logicalT++;\n\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass START\",\n logicalT));\n }\n if (networkMonitor == null || !networkMonitor.isConnected()) {\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass END - Network disconnected\",\n logicalT));\n }\n return false;\n }\n if (authMonitor == null || !authMonitor.tryIsLoggedIn()) {\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass END - Logged out\",\n logicalT));\n }\n return false;\n }\n\n syncRemoteToLocal();\n syncLocalToRemote();\n\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass END\",\n logicalT));\n }\n } catch (InterruptedException e) {\n if (logger.isInfoEnabled()) {\n logger.info(String.format(\n Locale.US,\n \"t='%d': doSyncPass INTERRUPTED\",\n logicalT));\n }\n return false;\n } finally {\n syncLock.unlock();\n }\n return true;\n }", "public static int cudnnGetCTCLossWorkspaceSize(\n cudnnHandle handle, \n cudnnTensorDescriptor probsDesc, /** Tensor descriptor for probabilities, the dimensions are T,N,A (T is the\n timing steps, N is the mini batch size, A is the alphabet size) */\n cudnnTensorDescriptor gradientsDesc, /** Tensor descriptor for gradients, the\n dimensions are T,N,A. To compute costs\n only, set it to NULL */\n int[] labels, /** labels, in CPU memory */\n int[] labelLengths, /** the length of each label, in CPU memory */\n int[] inputLengths, /** the lengths of timing steps in each batch, in CPU memory */\n int algo, /** algorithm selected, supported now 0 and 1 */\n cudnnCTCLossDescriptor ctcLossDesc, \n long[] sizeInBytes)/** pointer to the returned workspace size */\n {\n return checkResult(cudnnGetCTCLossWorkspaceSizeNative(handle, probsDesc, gradientsDesc, labels, labelLengths, inputLengths, algo, ctcLossDesc, sizeInBytes));\n }", "private Map<StandardMethod, UnderrideLevel> findUnderriddenMethods(\n Iterable<ExecutableElement> methods) {\n Map<StandardMethod, ExecutableElement> standardMethods = new LinkedHashMap<>();\n for (ExecutableElement method : methods) {\n Optional<StandardMethod> standardMethod = maybeStandardMethod(method);\n if (standardMethod.isPresent() && isUnderride(method)) {\n standardMethods.put(standardMethod.get(), method);\n }\n }\n if (standardMethods.containsKey(StandardMethod.EQUALS)\n != standardMethods.containsKey(StandardMethod.HASH_CODE)) {\n ExecutableElement underriddenMethod = standardMethods.containsKey(StandardMethod.EQUALS)\n ? standardMethods.get(StandardMethod.EQUALS)\n : standardMethods.get(StandardMethod.HASH_CODE);\n messager.printMessage(ERROR,\n \"hashCode and equals must be implemented together on FreeBuilder types\",\n underriddenMethod);\n }\n ImmutableMap.Builder<StandardMethod, UnderrideLevel> result = ImmutableMap.builder();\n for (StandardMethod standardMethod : standardMethods.keySet()) {\n if (standardMethods.get(standardMethod).getModifiers().contains(Modifier.FINAL)) {\n result.put(standardMethod, UnderrideLevel.FINAL);\n } else {\n result.put(standardMethod, UnderrideLevel.OVERRIDEABLE);\n }\n }\n return result.build();\n }", "public void setAlias(String alias)\r\n\t{\r\n\t\tif (alias == null || alias.trim().equals(\"\"))\r\n\t\t{\r\n\t\t\tm_alias = null;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tm_alias = alias;\r\n\t\t}\r\n\r\n\t\t// propagate to SelectionCriteria,not to Criteria\r\n\t\tfor (int i = 0; i < m_criteria.size(); i++)\r\n\t\t{\r\n\t\t\tif (!(m_criteria.elementAt(i) instanceof Criteria))\r\n\t\t\t{\r\n\t\t\t\t((SelectionCriteria) m_criteria.elementAt(i)).setAlias(m_alias);\r\n\t\t\t}\r\n\t\t}\r\n\t}", "private void deselectChildren(CmsTreeItem item) {\r\n\r\n for (String childId : m_childrens.get(item.getId())) {\r\n CmsTreeItem child = m_categories.get(childId);\r\n deselectChildren(child);\r\n child.getCheckBox().setChecked(false);\r\n if (m_selectedCategories.contains(childId)) {\r\n m_selectedCategories.remove(childId);\r\n }\r\n }\r\n }", "private EditorState getMasterState() {\n\n List<TableProperty> cols = new ArrayList<TableProperty>(4);\n cols.add(TableProperty.KEY);\n cols.add(TableProperty.DESCRIPTION);\n cols.add(TableProperty.DEFAULT);\n cols.add(TableProperty.TRANSLATION);\n return new EditorState(cols, true);\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}", "public static <T> OptionalValue<T> ofNullable(ResourceKey key, T value) {\n return new GenericOptionalValue<T>(RUNTIME_SOURCE, key, value);\n }", "protected void copyStream(File outputDirectory,\n InputStream stream,\n String targetFileName) throws IOException\n {\n File resourceFile = new File(outputDirectory, targetFileName);\n BufferedReader reader = null;\n Writer writer = null;\n try\n {\n reader = new BufferedReader(new InputStreamReader(stream, ENCODING));\n writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(resourceFile), ENCODING));\n\n String line = reader.readLine();\n while (line != null)\n {\n writer.write(line);\n writer.write('\\n');\n line = reader.readLine();\n }\n writer.flush();\n }\n finally\n {\n if (reader != null)\n {\n reader.close();\n }\n if (writer != null)\n {\n writer.close();\n }\n }\n }" ]
Create a new remote proxy controller. @param client the transactional protocol client @param pathAddress the path address @param addressTranslator the address translator @param targetKernelVersion the {@link ModelVersion} of the kernel management API exposed by the proxied process @return the proxy controller
[ "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 static <T> T[] sort(T[] self, Comparator<T> comparator) {\n return sort(self, true, comparator);\n }", "public Collection<String> getMethods() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_METHODS);\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\r\n Element methodsElement = response.getPayload();\r\n\r\n List<String> methods = new ArrayList<String>();\r\n NodeList methodElements = methodsElement.getElementsByTagName(\"method\");\r\n for (int i = 0; i < methodElements.getLength(); i++) {\r\n Element methodElement = (Element) methodElements.item(i);\r\n methods.add(XMLUtilities.getValue(methodElement));\r\n }\r\n return methods;\r\n }", "private static <T> void readFields(BufferedReader reader, DatabaseTableConfig<T> config) throws SQLException {\n\t\tList<DatabaseFieldConfig> fields = new ArrayList<DatabaseFieldConfig>();\n\t\twhile (true) {\n\t\t\tString line;\n\t\t\ttry {\n\t\t\t\tline = reader.readLine();\n\t\t\t} catch (IOException e) {\n\t\t\t\tthrow SqlExceptionUtil.create(\"Could not read next field from config file\", e);\n\t\t\t}\n\t\t\tif (line == null || line.equals(CONFIG_FILE_FIELDS_END)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tDatabaseFieldConfig fieldConfig = DatabaseFieldConfigLoader.fromReader(reader);\n\t\t\tif (fieldConfig == null) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tfields.add(fieldConfig);\n\t\t}\n\t\tconfig.setFieldConfigs(fields);\n\t}", "public static BufferedImage cloneImage( BufferedImage image ) {\n\t\tBufferedImage newImage = new BufferedImage( image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB );\n\t\tGraphics2D g = newImage.createGraphics();\n\t\tg.drawRenderedImage( image, null );\n\t\tg.dispose();\n\t\treturn newImage;\n\t}", "@Override\n public void invert(DMatrixRMaj A_inv) {\n blockB.reshape(A_inv.numRows,A_inv.numCols,false);\n\n alg.invert(blockB);\n\n MatrixOps_DDRB.convert(blockB,A_inv);\n }", "public static boolean isLogDownloadAvailable(CliGuiContext cliGuiCtx) {\n ModelNode readOps = null;\n try {\n readOps = cliGuiCtx.getExecutor().doCommand(\"/subsystem=logging:read-children-types\");\n } catch (CommandFormatException | IOException e) {\n return false;\n }\n if (!readOps.get(\"result\").isDefined()) return false;\n for (ModelNode op: readOps.get(\"result\").asList()) {\n if (\"log-file\".equals(op.asString())) return true;\n }\n return false;\n }", "protected String getFormattedDatatypeValue(ICompositeNode node, AbstractRule rule, String text) throws ValueConverterException {\n\t\tObject value = valueConverter.toValue(text, rule.getName(), node);\n\t\ttext = valueConverter.toString(value, rule.getName());\n\t\treturn text;\n\t}", "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 }", "static void backupDirectory(final File source, final File target) throws IOException {\n if (!target.exists()) {\n if (!target.mkdirs()) {\n throw PatchLogger.ROOT_LOGGER.cannotCreateDirectory(target.getAbsolutePath());\n }\n }\n final File[] files = source.listFiles(CONFIG_FILTER);\n for (final File file : files) {\n final File t = new File(target, file.getName());\n IoUtils.copyFile(file, t);\n }\n }" ]
Start the drag of the pivot object. @param dragMe Scene object with a rigid body. @param relX rel position in x-axis. @param relY rel position in y-axis. @param relZ rel position in z-axis. @return Pivot instance if success, otherwise returns null.
[ "public GVRSceneObject startDrag(GVRSceneObject dragMe, float relX, float relY, float relZ) {\n synchronized (mLock) {\n if (mCursorController == null) {\n Log.w(TAG, \"Physics drag failed: Cursor controller not found!\");\n return null;\n }\n\n if (mDragMe != null) {\n Log.w(TAG, \"Physics drag failed: Previous drag wasn't finished!\");\n return null;\n }\n\n if (mPivotObject == null) {\n mPivotObject = onCreatePivotObject(mContext);\n }\n\n mDragMe = dragMe;\n\n GVRTransform t = dragMe.getTransform();\n\n /* It is not possible to drag a rigid body directly, we need a pivot object.\n We are using the pivot object's position as pivot of the dragging's physics constraint.\n */\n mPivotObject.getTransform().setPosition(t.getPositionX() + relX,\n t.getPositionY() + relY, t.getPositionZ() + relZ);\n\n mCursorController.startDrag(mPivotObject);\n }\n\n return mPivotObject;\n }" ]
[ "public PhotoList<Photo> getClusterPhotos(String tag, String clusterId) throws FlickrException {\n\n PhotoList<Photo> photos = new PhotoList<Photo>();\n Map<String, Object> parameters = new HashMap<String, Object>();\n parameters.put(\"method\", METHOD_GET_CLUSTER_PHOTOS);\n\n parameters.put(\"tag\", tag);\n parameters.put(\"cluster_id\", clusterId);\n\n Response response = transportAPI.get(transportAPI.getPath(), parameters, apiKey, sharedSecret);\n if (response.isError()) {\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\n }\n\n Element photosElement = response.getPayload();\n NodeList photoNodes = photosElement.getElementsByTagName(\"photo\");\n photos.setPage(\"1\");\n photos.setPages(\"1\");\n photos.setPerPage(\"\" + photoNodes.getLength());\n photos.setTotal(\"\" + photoNodes.getLength());\n for (int i = 0; i < photoNodes.getLength(); i++) {\n Element photoElement = (Element) photoNodes.item(i);\n photos.add(PhotoUtils.createPhoto(photoElement));\n }\n return photos;\n }", "public CredentialsConfig getResolvingCredentialsConfig() {\n if (resolverCredentialsConfig != null && resolverCredentialsConfig.isCredentialsProvided()) {\n return getResolverCredentialsConfig();\n }\n if (deployerCredentialsConfig != null) {\n return getDeployerCredentialsConfig();\n }\n\n return CredentialsConfig.EMPTY_CREDENTIALS_CONFIG;\n }", "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 static URL classFileUrl(Class<?> clazz) throws IOException {\n ClassLoader cl = clazz.getClassLoader();\n if (cl == null) {\n cl = ClassLoader.getSystemClassLoader();\n }\n URL res = cl.getResource(clazz.getName().replace('.', '/') + \".class\");\n if (res == null) {\n throw new IllegalArgumentException(\"Unable to locate class file for \" + clazz);\n }\n return res;\n }", "protected void handleDeadSlop(SlopStorageEngine slopStorageEngine,\n Pair<ByteArray, Versioned<Slop>> keyAndVal) {\n Versioned<Slop> versioned = keyAndVal.getSecond();\n // If configured to delete the dead slop\n if(voldemortConfig.getAutoPurgeDeadSlops()) {\n slopStorageEngine.delete(keyAndVal.getFirst(), versioned.getVersion());\n\n if(getLogger().isDebugEnabled()) {\n getLogger().debug(\"Auto purging dead slop :\" + versioned.getValue());\n }\n } else {\n // Keep ignoring the dead slops\n if(getLogger().isDebugEnabled()) {\n getLogger().debug(\"Ignoring dead slop :\" + versioned.getValue());\n }\n }\n }", "protected boolean isSingleConnection(DatabaseConnection conn1, DatabaseConnection conn2) throws SQLException {\n\t\t// initialize the connections auto-commit flags\n\t\tconn1.setAutoCommit(true);\n\t\tconn2.setAutoCommit(true);\n\t\ttry {\n\t\t\t// change conn1's auto-commit to be false\n\t\t\tconn1.setAutoCommit(false);\n\t\t\tif (conn2.isAutoCommit()) {\n\t\t\t\t// if the 2nd connection's auto-commit is still true then we have multiple connections\n\t\t\t\treturn false;\n\t\t\t} else {\n\t\t\t\t// if the 2nd connection's auto-commit is also false then we have a single connection\n\t\t\t\treturn true;\n\t\t\t}\n\t\t} finally {\n\t\t\t// restore its auto-commit\n\t\t\tconn1.setAutoCommit(true);\n\t\t}\n\t}", "public static base_response delete(nitro_service client, String sitename) throws Exception {\n\t\tgslbsite deleteresource = new gslbsite();\n\t\tdeleteresource.sitename = sitename;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public void setWidth(int width) {\n this.width = width;\n getElement().getStyle().setWidth(width, Style.Unit.PX);\n }", "public void finished() throws Throwable {\n if( state == FINISHED ) {\n return;\n }\n\n State previousState = state;\n\n state = FINISHED;\n methodInterceptor.enableMethodInterception( false );\n\n try {\n if( previousState == STARTED ) {\n callFinishLifeCycleMethods();\n }\n } finally {\n listener.scenarioFinished();\n }\n }" ]
Use this API to fetch lbvserver_cachepolicy_binding resources of given name .
[ "public static lbvserver_cachepolicy_binding[] get(nitro_service service, String name) throws Exception{\n\t\tlbvserver_cachepolicy_binding obj = new lbvserver_cachepolicy_binding();\n\t\tobj.set_name(name);\n\t\tlbvserver_cachepolicy_binding response[] = (lbvserver_cachepolicy_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "public static String getAt(String text, Range range) {\n RangeInfo info = subListBorders(text.length(), range);\n String answer = text.substring(info.from, info.to);\n if (info.reverse) {\n answer = reverse(answer);\n }\n return answer;\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 Collection<BoxGroupMembership.Info> getMemberships() {\n final BoxAPIConnection api = this.getAPI();\n final String groupID = this.getID();\n\n Iterable<BoxGroupMembership.Info> iter = new Iterable<BoxGroupMembership.Info>() {\n public Iterator<BoxGroupMembership.Info> iterator() {\n URL url = MEMBERSHIPS_URL_TEMPLATE.build(api.getBaseURL(), groupID);\n return new BoxGroupMembershipIterator(api, url);\n }\n };\n\n // We need to iterate all results because this method must return a Collection. This logic should be removed in\n // the next major version, and instead return the Iterable directly.\n Collection<BoxGroupMembership.Info> memberships = new ArrayList<BoxGroupMembership.Info>();\n for (BoxGroupMembership.Info membership : iter) {\n memberships.add(membership);\n }\n return memberships;\n }", "@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 addCommandClass(ZWaveCommandClass commandClass) {\r\n\t\tZWaveCommandClass.CommandClass key = commandClass.getCommandClass();\r\n\t\tif (!supportedCommandClasses.containsKey(key)) {\r\n\t\t\tsupportedCommandClasses.put(key, commandClass);\r\n\t\t}\r\n\t}", "private void readExceptionDay(ProjectCalendar mpxjCalendar, ExceptedDay day)\n {\n ProjectCalendarException mpxjException = mpxjCalendar.addCalendarException(day.getDate(), day.getDate());\n if (day.isIsDayWorking())\n {\n for (Document.Calendars.Calendar.ExceptedDays.ExceptedDay.TimePeriods.TimePeriod period : day.getTimePeriods().getTimePeriod())\n {\n mpxjException.addRange(new DateRange(period.getFrom(), period.getTo()));\n }\n }\n }", "public static authenticationtacacspolicy_systemglobal_binding[] get(nitro_service service, String name) throws Exception{\n\t\tauthenticationtacacspolicy_systemglobal_binding obj = new authenticationtacacspolicy_systemglobal_binding();\n\t\tobj.set_name(name);\n\t\tauthenticationtacacspolicy_systemglobal_binding response[] = (authenticationtacacspolicy_systemglobal_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private void readCalendars(Project project, HashMap<BigInteger, ProjectCalendar> map)\n {\n Project.Calendars calendars = project.getCalendars();\n if (calendars != null)\n {\n LinkedList<Pair<ProjectCalendar, BigInteger>> baseCalendars = new LinkedList<Pair<ProjectCalendar, BigInteger>>();\n for (Project.Calendars.Calendar cal : calendars.getCalendar())\n {\n readCalendar(cal, map, baseCalendars);\n }\n updateBaseCalendarNames(baseCalendars, map);\n }\n\n try\n {\n ProjectProperties properties = m_projectFile.getProjectProperties();\n BigInteger calendarID = new BigInteger(properties.getDefaultCalendarName());\n ProjectCalendar calendar = map.get(calendarID);\n m_projectFile.setDefaultCalendar(calendar);\n }\n\n catch (Exception ex)\n {\n // Ignore exceptions\n }\n }", "public static boolean isSinglePositionPrefix(FieldInfo fieldInfo,\n String prefix) throws IOException {\n if (fieldInfo == null) {\n throw new IOException(\"no fieldInfo\");\n } else {\n String info = fieldInfo.getAttribute(\n MtasCodecPostingsFormat.MTAS_FIELDINFO_ATTRIBUTE_PREFIX_SINGLE_POSITION);\n if (info == null) {\n throw new IOException(\"no \"\n + MtasCodecPostingsFormat.MTAS_FIELDINFO_ATTRIBUTE_PREFIX_SINGLE_POSITION);\n } else {\n return Arrays.asList(info.split(Pattern.quote(MtasToken.DELIMITER)))\n .contains(prefix);\n }\n }\n }" ]
Start the operation by instantiating the first job instance in a separate Thread. @param arguments {@inheritDoc}
[ "@Override\n public void start(String[] arguments) {\n boolean notStarted = !started.getAndSet(true);\n if (notStarted) {\n start(new MultiInstanceWorkloadStrategy(factory, name, arguments, endpointRegistry, execService));\n }\n }" ]
[ "public static boolean isAssignableFrom(TypeReference<?> from, TypeReference<?> to) {\n\t\tif (from == null) {\n\t\t\treturn false;\n\t\t}\n\n\t\tif (to.equals(from)) {\n\t\t\treturn true;\n\t\t}\n\n\t\tif (to.getType() instanceof Class) {\n\t\t\treturn to.getRawType().isAssignableFrom(from.getRawType());\n\t\t} else if (to.getType() instanceof ParameterizedType) {\n\t\t\treturn isAssignableFrom(from.getType(), (ParameterizedType) to\n\t\t\t\t\t.getType(), new HashMap<String, Type>());\n\t\t} else if (to.getType() instanceof GenericArrayType) {\n\t\t\treturn to.getRawType().isAssignableFrom(from.getRawType())\n\t\t\t\t\t&& isAssignableFrom(from.getType(), (GenericArrayType) to\n\t\t\t\t\t\t\t.getType());\n\t\t} else {\n\t\t\tthrow new AssertionError(\"Unexpected Type : \" + to);\n\t\t}\n\t}", "private ServerBootstrap createBootstrap(final ChannelGroup channelGroup) throws Exception {\n EventLoopGroup bossGroup = new NioEventLoopGroup(bossThreadPoolSize,\n createDaemonThreadFactory(serviceName + \"-boss-thread-%d\"));\n EventLoopGroup workerGroup = new NioEventLoopGroup(workerThreadPoolSize,\n createDaemonThreadFactory(serviceName + \"-worker-thread-%d\"));\n ServerBootstrap bootstrap = new ServerBootstrap();\n bootstrap\n .group(bossGroup, workerGroup)\n .channel(NioServerSocketChannel.class)\n .childHandler(new ChannelInitializer<SocketChannel>() {\n @Override\n protected void initChannel(SocketChannel ch) throws Exception {\n channelGroup.add(ch);\n\n ChannelPipeline pipeline = ch.pipeline();\n if (sslHandlerFactory != null) {\n // Add SSLHandler if SSL is enabled\n pipeline.addLast(\"ssl\", sslHandlerFactory.create(ch.alloc()));\n }\n pipeline.addLast(\"codec\", new HttpServerCodec());\n pipeline.addLast(\"compressor\", new HttpContentCompressor());\n pipeline.addLast(\"chunkedWriter\", new ChunkedWriteHandler());\n pipeline.addLast(\"keepAlive\", new HttpServerKeepAliveHandler());\n pipeline.addLast(\"router\", new RequestRouter(resourceHandler, httpChunkLimit, sslHandlerFactory != null));\n if (eventExecutorGroup == null) {\n pipeline.addLast(\"dispatcher\", new HttpDispatcher());\n } else {\n pipeline.addLast(eventExecutorGroup, \"dispatcher\", new HttpDispatcher());\n }\n\n if (pipelineModifier != null) {\n pipelineModifier.modify(pipeline);\n }\n }\n });\n\n for (Map.Entry<ChannelOption, Object> entry : channelConfigs.entrySet()) {\n bootstrap.option(entry.getKey(), entry.getValue());\n }\n for (Map.Entry<ChannelOption, Object> entry : childChannelConfigs.entrySet()) {\n bootstrap.childOption(entry.getKey(), entry.getValue());\n }\n\n return bootstrap;\n }", "public void setValue(Vector3f scale) {\n mX = scale.x;\n mY = scale.y;\n mZ = scale.z;\n }", "public void commandLoop() throws IOException {\n for (Object handler : allHandlers) {\n if (handler instanceof ShellManageable) {\n ((ShellManageable)handler).cliEnterLoop();\n }\n }\n output.output(appName, outputConverter);\n String command = \"\";\n while (true) {\n try {\n command = input.readCommand(path);\n if (command.trim().equals(\"exit\")) {\n if (lineProcessor == null)\n break;\n else {\n path = savedPath;\n lineProcessor = null;\n }\n }\n\n processLine(command);\n } catch (TokenException te) {\n lastException = te;\n output.outputException(command, te);\n } catch (CLIException clie) {\n lastException = clie;\n if (!command.trim().equals(\"exit\")) {\n output.outputException(clie);\n }\n }\n }\n for (Object handler : allHandlers) {\n if (handler instanceof ShellManageable) {\n ((ShellManageable)handler).cliLeaveLoop();\n }\n }\n }", "public static void validateAllAvroSchemas(SerializerDefinition avroSerDef) {\n Map<Integer, String> schemaVersions = avroSerDef.getAllSchemaInfoVersions();\n if(schemaVersions.size() < 1) {\n throw new VoldemortException(\"No schema specified\");\n }\n for(Map.Entry<Integer, String> entry: schemaVersions.entrySet()) {\n Integer schemaVersionNumber = entry.getKey();\n String schemaStr = entry.getValue();\n try {\n Schema.parse(schemaStr);\n } catch(Exception e) {\n throw new VoldemortException(\"Unable to parse Avro schema version :\"\n + schemaVersionNumber + \", schema string :\"\n + schemaStr);\n }\n }\n }", "private void queryDatabaseMetaData()\n {\n ResultSet rs = null;\n\n try\n {\n Set<String> tables = new HashSet<String>();\n DatabaseMetaData dmd = m_connection.getMetaData();\n rs = dmd.getTables(null, null, null, null);\n while (rs.next())\n {\n tables.add(rs.getString(\"TABLE_NAME\"));\n }\n\n m_hasResourceBaselines = tables.contains(\"MSP_RESOURCE_BASELINES\");\n m_hasTaskBaselines = tables.contains(\"MSP_TASK_BASELINES\");\n m_hasAssignmentBaselines = tables.contains(\"MSP_ASSIGNMENT_BASELINES\");\n }\n\n catch (Exception ex)\n {\n // Ignore errors when reading meta data\n }\n\n finally\n {\n if (rs != null)\n {\n try\n {\n rs.close();\n }\n\n catch (SQLException ex)\n {\n // Ignore errors when closing result set\n }\n rs = null;\n }\n }\n }", "public static int validateGeohashMaxLevels(Integer userMaxLevels, int defaultMaxLevels) {\n int maxLevels = userMaxLevels == null ? defaultMaxLevels : userMaxLevels;\n if (maxLevels < 1 || maxLevels > GeohashPrefixTree.getMaxLevelsPossible()) {\n throw new IndexException(\"max_levels must be in range [1, {}], but found {}\",\n GeohashPrefixTree.getMaxLevelsPossible(),\n maxLevels);\n }\n return maxLevels;\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 static base_responses update(nitro_service client, autoscaleprofile resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tautoscaleprofile updateresources[] = new autoscaleprofile[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new autoscaleprofile();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].url = resources[i].url;\n\t\t\t\tupdateresources[i].apikey = resources[i].apikey;\n\t\t\t\tupdateresources[i].sharedsecret = resources[i].sharedsecret;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}" ]
Deletes a FilePath file. @param workspace The build workspace. @param path The path in the workspace. @throws IOException In case of missing file.
[ "public static void deleteFilePath(FilePath workspace, String path) throws IOException {\n if (StringUtils.isNotBlank(path)) {\n try {\n FilePath propertiesFile = new FilePath(workspace, path);\n propertiesFile.delete();\n } catch (Exception e) {\n throw new IOException(\"Could not delete temp file: \" + path);\n }\n }\n }" ]
[ "protected void parseCombineIntegerLists(TokenList tokens) {\n TokenList.Token t = tokens.getFirst();\n if( t == null || t.next == null )\n return;\n\n int numFound = 0;\n\n TokenList.Token start = null;\n TokenList.Token end = null;\n\n while( t != null ) {\n if( t.getType() == Type.VARIABLE && (isVariableInteger(t) ||\n t.getVariable().getType() == VariableType.INTEGER_SEQUENCE )) {\n if( numFound == 0 ) {\n numFound = 1;\n start = end = t;\n } else {\n numFound++;\n end = t;\n }\n } else if( numFound > 1 ) {\n IntegerSequence sequence = new IntegerSequence.Combined(start,end);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, end);\n numFound = 0;\n } else {\n numFound = 0;\n }\n t = t.next;\n }\n\n if( numFound > 1 ) {\n IntegerSequence sequence = new IntegerSequence.Combined(start,end);\n VariableIntegerSequence varSequence = functions.getManagerTemp().createIntegerSequence(sequence);\n replaceSequence(tokens, varSequence, start, end);\n }\n }", "private void writePropertyData() {\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(\"properties.csv\"))) {\n\n\t\t\tout.println(\"Id\" + \",Label\" + \",Description\" + \",URL\" + \",Datatype\"\n\t\t\t\t\t+ \",Uses in statements\" + \",Items with such statements\"\n\t\t\t\t\t+ \",Uses in statements with qualifiers\"\n\t\t\t\t\t+ \",Uses in qualifiers\" + \",Uses in references\"\n\t\t\t\t\t+ \",Uses total\" + \",Related properties\");\n\n\t\t\tList<Entry<PropertyIdValue, PropertyRecord>> list = new ArrayList<Entry<PropertyIdValue, PropertyRecord>>(\n\t\t\t\t\tthis.propertyRecords.entrySet());\n\t\t\tCollections.sort(list, new UsageRecordComparator());\n\t\t\tfor (Entry<PropertyIdValue, PropertyRecord> entry : list) {\n\t\t\t\tprintPropertyRecord(out, entry.getValue(), entry.getKey());\n\t\t\t}\n\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "public AT_Row setPaddingLeft(int paddingLeft) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setPaddingLeft(paddingLeft);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public static AccumuloClient getClient(FluoConfiguration config) {\n return Accumulo.newClient().to(config.getAccumuloInstance(), config.getAccumuloZookeepers())\n .as(config.getAccumuloUser(), config.getAccumuloPassword()).build();\n }", "public void registerDropPasteWorker(DropPasteWorkerInterface worker)\r\n {\r\n this.dropPasteWorkerSet.add(worker);\r\n defaultDropTarget.setDefaultActions( \r\n defaultDropTarget.getDefaultActions() \r\n | worker.getAcceptableActions(defaultDropTarget.getComponent())\r\n );\r\n }", "private boolean isRecyclable(View convertView, T content) {\n boolean isRecyclable = false;\n if (convertView != null && convertView.getTag() != null) {\n Class prototypeClass = getPrototypeClass(content);\n validatePrototypeClass(prototypeClass);\n isRecyclable = prototypeClass.equals(convertView.getTag().getClass());\n }\n return isRecyclable;\n }", "public <Result> Result process(IUnitOfWork<Result, State> work) {\n\t\treleaseReadLock();\n\t\tacquireWriteLock();\n\t\ttry {\n\t\t\tif (log.isTraceEnabled())\n\t\t\t\tlog.trace(\"process - \" + Thread.currentThread().getName());\n\t\t\treturn modify(work);\n\t\t} finally {\n\t\t\tif (log.isTraceEnabled())\n\t\t\t\tlog.trace(\"Downgrading from write lock to read lock...\");\n\t\t\tacquireReadLock();\n\t\t\treleaseWriteLock();\n\t\t}\n\t}", "public static CredentialsConfig getPreferredDeployer(DeployerOverrider deployerOverrider, ArtifactoryServer server) {\n if (deployerOverrider.isOverridingDefaultDeployer()) {\n CredentialsConfig deployerCredentialsConfig = deployerOverrider.getDeployerCredentialsConfig();\n if (deployerCredentialsConfig != null) {\n return deployerCredentialsConfig;\n }\n }\n\n if (server != null) {\n CredentialsConfig deployerCredentials = server.getDeployerCredentialsConfig();\n if (deployerCredentials != null) {\n return deployerCredentials;\n }\n }\n\n return CredentialsConfig.EMPTY_CREDENTIALS_CONFIG;\n }", "public List<BindingInfo> getQueueBindings(String vhost, String queue) {\n final URI uri = uriWithPath(\"./queues/\" + encodePathSegment(vhost) +\n \"/\" + encodePathSegment(queue) + \"/bindings\");\n final BindingInfo[] result = this.rt.getForObject(uri, BindingInfo[].class);\n return asListOrNull(result);\n }" ]
Compute the offset for the item in the layout based on the offsets of neighbors in the layout. The other offsets are not patched. If neighbors offsets have not been computed the offset of the item will not be set. @return true if the item fits the container, false otherwise
[ "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 static ModelNode getAccessControl(ModelControllerClient client, OperationRequestAddress address, boolean operations) {\n return getAccessControl(client, null, address, operations);\n }", "public static void acceptsHex(OptionParser parser) {\n parser.acceptsAll(Arrays.asList(OPT_X, OPT_HEX), \"fetch key/entry by key value of hex type\")\n .withRequiredArg()\n .describedAs(\"key-list\")\n .withValuesSeparatedBy(',')\n .ofType(String.class);\n }", "public Where<T, ID> or() {\n\t\tManyClause clause = new ManyClause(pop(\"OR\"), ManyClause.OR_OPERATION);\n\t\tpush(clause);\n\t\taddNeedsFuture(clause);\n\t\treturn this;\n\t}", "private void writeAssignments()\n {\n for (ResourceAssignment assignment : m_projectFile.getResourceAssignments())\n {\n Resource resource = assignment.getResource();\n if (resource != null)\n {\n Task task = assignment.getTask();\n if (task != null && task.getUniqueID().intValue() != 0 && !task.getSummary())\n {\n writeAssignment(assignment);\n }\n }\n }\n }", "public final void configureAccess(final Template template, final ApplicationContext context) {\n final Configuration configuration = template.getConfiguration();\n\n AndAccessAssertion accessAssertion = context.getBean(AndAccessAssertion.class);\n accessAssertion.setPredicates(configuration.getAccessAssertion(), template.getAccessAssertion());\n this.access = accessAssertion;\n }", "protected boolean determineFeatureState(final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, boolean defaultState) {\n final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(context.getConfiguration());\n final IStandardExpression expression = expressionParser.parseExpression(context, attributeValue);\n final Object value = expression.execute(context);\n if (value != null) {\n return isFeatureActive(value.toString());\n }\n else {\n return defaultState;\n }\n }", "public static void showErrorDialog(String message, String details) {\n\n Window window = prepareWindow(DialogWidth.wide);\n window.setCaption(\"Error\");\n window.setContent(new CmsSetupErrorDialog(message, details, null, window));\n A_CmsUI.get().addWindow(window);\n\n }", "public float getNormalX(int vertex) {\n if (!hasNormals()) {\n throw new IllegalStateException(\"mesh has no normals\");\n }\n \n checkVertexIndexBounds(vertex);\n \n return m_normals.getFloat(vertex * 3 * SIZEOF_FLOAT);\n }", "public void setAmbientIntensity(float r, float g, float b, float a) {\n setVec4(\"ambient_intensity\", r, g, b, a);\n }" ]
Takes the specified object and converts the argument to a String. @param arg The object to convert @return A String representation of the argument.
[ "protected String getArgString(Object arg) {\n //if (arg instanceof LatLong) {\n // return ((LatLong) arg).getVariableName();\n //} else \n if (arg instanceof JavascriptObject) {\n return ((JavascriptObject) arg).getVariableName();\n // return ((JavascriptObject) arg).getPropertiesAsString();\n } else if( arg instanceof JavascriptEnum ) {\n return ((JavascriptEnum) arg).getEnumValue().toString();\n } else {\n return arg.toString();\n }\n }" ]
[ "public boolean getFlag(int index)\n {\n return BooleanHelper.getBoolean((Boolean) getCachedValue(selectField(ResourceFieldLists.CUSTOM_FLAG, index)));\n }", "public static TaskField getMpxjField(int value)\n {\n TaskField result = null;\n\n if (value >= 0 && value < MPX_MPXJ_ARRAY.length)\n {\n result = MPX_MPXJ_ARRAY[value];\n }\n\n return (result);\n }", "public void removeVariable(String name)\n {\n Map<String, Iterable<? extends WindupVertexFrame>> frame = peek();\n frame.remove(name);\n }", "private void executeBatch(int batchId, final RebalanceBatchPlan batchPlan) {\n final Cluster batchCurrentCluster = batchPlan.getCurrentCluster();\n final List<StoreDefinition> batchCurrentStoreDefs = batchPlan.getCurrentStoreDefs();\n final Cluster batchFinalCluster = batchPlan.getFinalCluster();\n final List<StoreDefinition> batchFinalStoreDefs = batchPlan.getFinalStoreDefs();\n\n try {\n final List<RebalanceTaskInfo> rebalanceTaskInfoList = batchPlan.getBatchPlan();\n\n if(rebalanceTaskInfoList.isEmpty()) {\n RebalanceUtils.printBatchLog(batchId, logger, \"Skipping batch \"\n + batchId + \" since it is empty.\");\n // Even though there is no rebalancing work to do, cluster\n // metadata must be updated so that the server is aware of the\n // new cluster xml.\n adminClient.rebalanceOps.rebalanceStateChange(batchCurrentCluster,\n batchFinalCluster,\n batchCurrentStoreDefs,\n batchFinalStoreDefs,\n rebalanceTaskInfoList,\n false,\n true,\n false,\n false,\n true);\n return;\n }\n\n RebalanceUtils.printBatchLog(batchId, logger, \"Starting batch \"\n + batchId + \".\");\n\n // Split the store definitions\n List<StoreDefinition> readOnlyStoreDefs = StoreDefinitionUtils.filterStores(batchFinalStoreDefs,\n true);\n List<StoreDefinition> readWriteStoreDefs = StoreDefinitionUtils.filterStores(batchFinalStoreDefs,\n false);\n boolean hasReadOnlyStores = readOnlyStoreDefs != null\n && readOnlyStoreDefs.size() > 0;\n boolean hasReadWriteStores = readWriteStoreDefs != null\n && readWriteStoreDefs.size() > 0;\n\n // STEP 1 - Cluster state change\n boolean finishedReadOnlyPhase = false;\n List<RebalanceTaskInfo> filteredRebalancePartitionPlanList = RebalanceUtils.filterTaskPlanWithStores(rebalanceTaskInfoList,\n readOnlyStoreDefs);\n\n rebalanceStateChange(batchId,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n batchFinalCluster,\n batchFinalStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n\n // STEP 2 - Move RO data\n if(hasReadOnlyStores) {\n RebalanceBatchPlanProgressBar progressBar = batchPlan.getProgressBar(batchId);\n executeSubBatch(batchId,\n progressBar,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n }\n\n // STEP 3 - Cluster change state\n finishedReadOnlyPhase = true;\n filteredRebalancePartitionPlanList = RebalanceUtils.filterTaskPlanWithStores(rebalanceTaskInfoList,\n readWriteStoreDefs);\n\n rebalanceStateChange(batchId,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n batchFinalCluster,\n batchFinalStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n\n // STEP 4 - Move RW data\n if(hasReadWriteStores) {\n proxyPause();\n RebalanceBatchPlanProgressBar progressBar = batchPlan.getProgressBar(batchId);\n executeSubBatch(batchId,\n progressBar,\n batchCurrentCluster,\n batchCurrentStoreDefs,\n filteredRebalancePartitionPlanList,\n hasReadOnlyStores,\n hasReadWriteStores,\n finishedReadOnlyPhase);\n }\n\n RebalanceUtils.printBatchLog(batchId,\n logger,\n \"Successfully terminated batch \"\n + batchId + \".\");\n\n } catch(Exception e) {\n RebalanceUtils.printErrorLog(batchId, logger, \"Error in batch \"\n + batchId + \" - \" + e.getMessage(), e);\n throw new VoldemortException(\"Rebalance failed on batch \" + batchId,\n e);\n }\n }", "@SuppressWarnings(\"unchecked\")\n public static <T extends Serializable> T makeClone(T from) {\n return (T) SerializationUtils.clone(from);\n }", "public static wisite_accessmethod_binding[] get(nitro_service service, String sitepath) throws Exception{\n\t\twisite_accessmethod_binding obj = new wisite_accessmethod_binding();\n\t\tobj.set_sitepath(sitepath);\n\t\twisite_accessmethod_binding response[] = (wisite_accessmethod_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "private void populateResource(Resource resource, Record record) throws MPXJException\n {\n String falseText = LocaleData.getString(m_locale, LocaleData.NO);\n\n int length = record.getLength();\n int[] model = m_resourceModel.getModel();\n\n for (int i = 0; i < length; i++)\n {\n int mpxFieldType = model[i];\n if (mpxFieldType == -1)\n {\n break;\n }\n\n String field = record.getString(i);\n\n if (field == null || field.length() == 0)\n {\n continue;\n }\n\n ResourceField resourceField = MPXResourceField.getMpxjField(mpxFieldType);\n switch (resourceField)\n {\n case OBJECTS:\n {\n resource.set(resourceField, record.getInteger(i));\n break;\n }\n\n case ID:\n {\n resource.setID(record.getInteger(i));\n break;\n }\n\n case UNIQUE_ID:\n {\n resource.setUniqueID(record.getInteger(i));\n break;\n }\n\n case MAX_UNITS:\n {\n resource.set(resourceField, record.getUnits(i));\n break;\n }\n\n case PERCENT_WORK_COMPLETE:\n case PEAK:\n {\n resource.set(resourceField, record.getPercentage(i));\n break;\n }\n\n case COST:\n case COST_PER_USE:\n case COST_VARIANCE:\n case BASELINE_COST:\n case ACTUAL_COST:\n case REMAINING_COST:\n {\n resource.set(resourceField, record.getCurrency(i));\n break;\n }\n\n case OVERTIME_RATE:\n case STANDARD_RATE:\n {\n resource.set(resourceField, record.getRate(i));\n break;\n }\n\n case REMAINING_WORK:\n case OVERTIME_WORK:\n case BASELINE_WORK:\n case ACTUAL_WORK:\n case WORK:\n case WORK_VARIANCE:\n {\n resource.set(resourceField, record.getDuration(i));\n break;\n }\n\n case ACCRUE_AT:\n {\n resource.set(resourceField, record.getAccrueType(i));\n break;\n }\n\n case LINKED_FIELDS:\n case OVERALLOCATED:\n {\n resource.set(resourceField, record.getBoolean(i, falseText));\n break;\n }\n\n default:\n {\n resource.set(resourceField, field);\n break;\n }\n }\n }\n\n if (m_projectConfig.getAutoResourceUniqueID() == true)\n {\n resource.setUniqueID(Integer.valueOf(m_projectConfig.getNextResourceUniqueID()));\n }\n\n if (m_projectConfig.getAutoResourceID() == true)\n {\n resource.setID(Integer.valueOf(m_projectConfig.getNextResourceID()));\n }\n\n //\n // Handle malformed MPX files - ensure we have a unique ID\n //\n if (resource.getUniqueID() == null)\n {\n resource.setUniqueID(resource.getID());\n }\n }", "@Override\n public final Integer optInt(final String key, final Integer defaultValue) {\n Integer result = optInt(key);\n return result == null ? defaultValue : result;\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 }" ]
Get the filters ExporterServiceFilter and ExportDeclarationFilter from the properties, stop the instance if one of. them is invalid.
[ "private void processProperties() {\n state = true;\n try {\n exporterServiceFilter = getFilter(exporterServiceFilterProperty);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.debug(\"The value of the Property \" + FILTER_EXPORTERSERVICE_PROPERTY + \" is invalid,\"\n + \" the recuperation of the Filter has failed. The instance gonna stop.\", invalidFilterException);\n state = false;\n return;\n }\n\n try {\n exportDeclarationFilter = getFilter(exportDeclarationFilterProperty);\n } catch (InvalidFilterException invalidFilterException) {\n LOG.debug(\"The value of the Property \" + FILTER_EXPORTDECLARATION_PROPERTY + \" is invalid,\"\n + \" the recuperation of the Filter has failed. The instance gonna stop.\", invalidFilterException);\n state = false;\n return;\n }\n }" ]
[ "private HashMap<String, StoreDefinition> makeStoreDefinitionMap(List<StoreDefinition> storeDefs) {\n HashMap<String, StoreDefinition> storeDefMap = new HashMap<String, StoreDefinition>();\n for(StoreDefinition storeDef: storeDefs)\n storeDefMap.put(storeDef.getName(), storeDef);\n return storeDefMap;\n }", "public SerialMessage getNoMoreInformationMessage() {\r\n\t\tlogger.debug(\"Creating new message for application command WAKE_UP_NO_MORE_INFORMATION for node {}\", this.getNode().getNodeId());\r\n\t\tSerialMessage result = new SerialMessage(this.getNode().getNodeId(), SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessageType.Request, SerialMessage.SerialMessageClass.SendData, SerialMessage.SerialMessagePriority.Low);\r\n \tbyte[] newPayload = { \t(byte) this.getNode().getNodeId(), \r\n \t\t\t\t\t\t\t2, \r\n\t\t\t\t\t\t\t\t(byte) getCommandClass().getKey(), \r\n\t\t\t\t\t\t\t\t(byte) WAKE_UP_NO_MORE_INFORMATION };\r\n \tresult.setMessagePayload(newPayload);\r\n\r\n \treturn result;\r\n\t}", "private void setPropertyFilters(String filters) {\n\t\tthis.filterProperties = new HashSet<>();\n\t\tif (!\"-\".equals(filters)) {\n\t\t\tfor (String pid : filters.split(\",\")) {\n\t\t\t\tthis.filterProperties.add(Datamodel\n\t\t\t\t\t\t.makeWikidataPropertyIdValue(pid));\n\t\t\t}\n\t\t}\n\t}", "public AsciiTable setTargetTranslator(TargetTranslator targetTranslator) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setTargetTranslator(targetTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "@SuppressWarnings(\"unchecked\")\n protected Class<? extends Annotation> annotationTypeForName(String name) {\n try {\n return (Class<? extends Annotation>) resourceLoader.classForName(name);\n } catch (ResourceLoadingException cnfe) {\n return DUMMY_ANNOTATION;\n }\n }", "private JSONObject getConvertedResponseAsJson(SpellCheckResponse response) {\n\n if (null == response) {\n return null;\n }\n\n final JSONObject suggestions = new JSONObject();\n final Map<String, Suggestion> solrSuggestions = response.getSuggestionMap();\n\n // Add suggestions to the response\n for (final String key : solrSuggestions.keySet()) {\n\n // Indicator to ignore words that are erroneously marked as misspelled.\n boolean ignoreWord = false;\n\n // Suggestions that are in the form \"Xxxx\" -> \"xxxx\" should be ignored.\n if (Character.isUpperCase(key.codePointAt(0))) {\n final String lowercaseKey = key.toLowerCase();\n // If the suggestion map doesn't contain the lowercased word, ignore this entry.\n if (!solrSuggestions.containsKey(lowercaseKey)) {\n ignoreWord = true;\n }\n }\n\n if (!ignoreWord) {\n try {\n // Get suggestions as List\n final List<String> l = solrSuggestions.get(key).getAlternatives();\n suggestions.put(key, l);\n } catch (JSONException e) {\n LOG.debug(\"Exception while converting Solr spellcheckresponse to JSON. \", e);\n }\n }\n }\n\n return suggestions;\n }", "private static int getTrimmedYStart(BufferedImage img) {\n int width = img.getWidth();\n int height = img.getHeight();\n int yStart = height;\n\n for (int i = 0; i < width; i++) {\n for (int j = 0; j < height; j++) {\n if (img.getRGB(i, j) != Color.WHITE.getRGB() && j < yStart) {\n yStart = j;\n break;\n }\n }\n }\n\n return yStart;\n }", "private void checkInitializationMethod(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 String initMethodName = classDef.getProperty(PropertyHelper.OJB_PROPERTY_INITIALIZATION_METHOD);\r\n\r\n if (initMethodName == null)\r\n {\r\n return;\r\n }\r\n\r\n Class initClass;\r\n Method initMethod;\r\n\r\n try\r\n {\r\n initClass = InheritanceHelper.getClass(classDef.getName());\r\n }\r\n catch (ClassNotFoundException ex)\r\n {\r\n throw new ConstraintException(\"The class \"+classDef.getName()+\" was not found on the classpath\");\r\n }\r\n try\r\n {\r\n initMethod = initClass.getDeclaredMethod(initMethodName, new Class[0]);\r\n }\r\n catch (NoSuchMethodException ex)\r\n {\r\n initMethod = null;\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new ConstraintException(\"Exception while checking the class \"+classDef.getName()+\": \"+ex.getMessage());\r\n }\r\n if (initMethod == null)\r\n { \r\n try\r\n {\r\n initMethod = initClass.getMethod(initMethodName, new Class[0]);\r\n }\r\n catch (NoSuchMethodException ex)\r\n {\r\n throw new ConstraintException(\"No suitable initialization-method \"+initMethodName+\" found in class \"+classDef.getName());\r\n }\r\n catch (Exception ex)\r\n {\r\n throw new ConstraintException(\"Exception while checking the class \"+classDef.getName()+\": \"+ex.getMessage());\r\n }\r\n }\r\n\r\n // checking modifiers\r\n int mods = initMethod.getModifiers();\r\n\r\n if (Modifier.isStatic(mods) || Modifier.isAbstract(mods))\r\n {\r\n throw new ConstraintException(\"The initialization-method \"+initMethodName+\" in class \"+classDef.getName()+\" must be a concrete instance method\");\r\n }\r\n }", "public void addProcedure(ProcedureDef procDef)\r\n {\r\n procDef.setOwner(this);\r\n _procedures.put(procDef.getName(), procDef);\r\n }" ]
returns a sorted array of properties
[ "public GroovyFieldDoc[] properties() {\n Collections.sort(properties);\n return properties.toArray(new GroovyFieldDoc[properties.size()]);\n }" ]
[ "public String getKeyValue(String key){\n String keyName = keysMap.get(key);\n if (keyName != null){\n return keyName;\n }\n return \"\"; //key wasn't defined in keys properties file\n }", "@Override\n public void setJobQueue(int jobId, Queue queue)\n {\n JqmClientFactory.getClient().setJobQueue(jobId, queue);\n }", "private CompiledStatement assignStatementArguments(CompiledStatement stmt) throws SQLException {\n\t\tboolean ok = false;\n\t\ttry {\n\t\t\tif (limit != null) {\n\t\t\t\t// we use this if SQL statement LIMITs are not supported by this database type\n\t\t\t\tstmt.setMaxRows(limit.intValue());\n\t\t\t}\n\t\t\t// set any arguments if we are logging our object\n\t\t\tObject[] argValues = null;\n\t\t\tif (logger.isLevelEnabled(Level.TRACE) && argHolders.length > 0) {\n\t\t\t\targValues = new Object[argHolders.length];\n\t\t\t}\n\t\t\tfor (int i = 0; i < argHolders.length; i++) {\n\t\t\t\tObject argValue = argHolders[i].getSqlArgValue();\n\t\t\t\tFieldType fieldType = argFieldTypes[i];\n\t\t\t\tSqlType sqlType;\n\t\t\t\tif (fieldType == null) {\n\t\t\t\t\tsqlType = argHolders[i].getSqlType();\n\t\t\t\t} else {\n\t\t\t\t\tsqlType = fieldType.getSqlType();\n\t\t\t\t}\n\t\t\t\tstmt.setObject(i, argValue, sqlType);\n\t\t\t\tif (argValues != null) {\n\t\t\t\t\targValues[i] = argValue;\n\t\t\t\t}\n\t\t\t}\n\t\t\tlogger.debug(\"prepared statement '{}' with {} args\", statement, argHolders.length);\n\t\t\tif (argValues != null) {\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(\"prepared statement arguments: {}\", (Object) argValues);\n\t\t\t}\n\t\t\tok = true;\n\t\t\treturn stmt;\n\t\t} finally {\n\t\t\tif (!ok) {\n\t\t\t\tIOUtils.closeThrowSqlException(stmt, \"statement\");\n\t\t\t}\n\t\t}\n\t}", "public static base_response delete(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey deleteresource = new sslcertkey();\n\t\tdeleteresource.certkey = resource.certkey;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "public void addArtifact(final Artifact artifact) {\n if (!artifacts.contains(artifact)) {\n if (promoted) {\n artifact.setPromoted(promoted);\n }\n\n artifacts.add(artifact);\n }\n }", "public static transformpolicylabel get(nitro_service service, String labelname) throws Exception{\n\t\ttransformpolicylabel obj = new transformpolicylabel();\n\t\tobj.set_labelname(labelname);\n\t\ttransformpolicylabel response = (transformpolicylabel) obj.get_resource(service);\n\t\treturn response;\n\t}", "public static cmppolicylabel_policybinding_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tcmppolicylabel_policybinding_binding obj = new cmppolicylabel_policybinding_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcmppolicylabel_policybinding_binding response[] = (cmppolicylabel_policybinding_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public static JasperPrint generateJasperPrint(DynamicReport dr, LayoutManager layoutManager, JRDataSource ds, Map<String, Object> _parameters) throws JRException {\n log.info(\"generating JasperPrint\");\n JasperPrint jp;\n\n\n JasperReport jr = DynamicJasperHelper.generateJasperReport(dr, layoutManager, _parameters);\n jp = JasperFillManager.fillReport(jr, _parameters, ds);\n\n return jp;\n }", "public static cachecontentgroup get(nitro_service service, String name) throws Exception{\n\t\tcachecontentgroup obj = new cachecontentgroup();\n\t\tobj.set_name(name);\n\t\tcachecontentgroup response = (cachecontentgroup) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
Use this API to delete locationfile.
[ "public static base_response delete(nitro_service client) throws Exception {\n\t\tlocationfile deleteresource = new locationfile();\n\t\treturn deleteresource.delete_resource(client);\n\t}" ]
[ "private void lockLocalization(Locale l) throws CmsException {\n\n if (null == m_lockedBundleFiles.get(l)) {\n LockedFile lf = LockedFile.lockResource(m_cms, m_bundleFiles.get(l));\n m_lockedBundleFiles.put(l, lf);\n }\n\n }", "public static URL asUrlOrResource(String s) {\n if (Strings.isNullOrEmpty(s)) {\n return null;\n }\n\n try {\n return new URL(s);\n } catch (MalformedURLException e) {\n //If its not a valid URL try to treat it as a local resource.\n return findConfigResource(s);\n }\n }", "public static String getPunctClass(String punc) {\r\n if(punc.equals(\"%\") || punc.equals(\"-PLUS-\"))//-PLUS- is an escape for \"+\" in the ATB\r\n return \"perc\";\r\n else if(punc.startsWith(\"*\"))\r\n return \"bullet\";\r\n else if(sfClass.contains(punc))\r\n return \"sf\";\r\n else if(colonClass.contains(punc) || pEllipsis.matcher(punc).matches())\r\n return \"colon\";\r\n else if(commaClass.contains(punc))\r\n return \"comma\";\r\n else if(currencyClass.contains(punc))\r\n return \"curr\";\r\n else if(slashClass.contains(punc))\r\n return \"slash\";\r\n else if(lBracketClass.contains(punc))\r\n return \"lrb\";\r\n else if(rBracketClass.contains(punc))\r\n return \"rrb\";\r\n else if(quoteClass.contains(punc))\r\n return \"quote\";\r\n \r\n return \"\";\r\n }", "private void handleMultiChannelEncapResponse(\r\n\t\t\tSerialMessage serialMessage, int offset) {\r\n\t\tlogger.trace(\"Process Multi-channel Encapsulation\");\r\n\t\tCommandClass commandClass;\r\n\t\tZWaveCommandClass zwaveCommandClass;\r\n\t\tint endpointId = serialMessage.getMessagePayloadByte(offset);\r\n\t\tint commandClassCode = serialMessage.getMessagePayloadByte(offset + 2);\r\n\t\tcommandClass = CommandClass.getCommandClass(commandClassCode);\r\n\t\t\r\n\t\tif (commandClass == null) {\r\n\t\t\tlogger.error(String.format(\"Unsupported command class 0x%02x\", commandClassCode));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tlogger.debug(String.format(\"Node %d Requested Command Class = %s (0x%02x)\", this.getNode().getNodeId(), commandClass.getLabel() , commandClassCode));\r\n\t\tZWaveEndpoint endpoint = this.endpoints.get(endpointId);\r\n\t\t\r\n\t\tif (endpoint == null){\r\n\t\t\tlogger.error(\"Endpoint {} not found on node {}. Cannot set command classes.\", endpoint, this.getNode().getNodeId());\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tzwaveCommandClass = endpoint.getCommandClass(commandClass);\r\n\t\t\r\n\t\tif (zwaveCommandClass == null) {\r\n\t\t\tlogger.warn(String.format(\"CommandClass %s (0x%02x) not implemented by endpoint %d, fallback to main node.\", commandClass.getLabel(), commandClassCode, endpointId));\r\n\t\t\tzwaveCommandClass = this.getNode().getCommandClass(commandClass);\r\n\t\t}\r\n\t\t\r\n\t\tif (zwaveCommandClass == null) {\r\n\t\t\tlogger.error(String.format(\"CommandClass %s (0x%02x) not implemented by node %d.\", commandClass.getLabel(), commandClassCode, this.getNode().getNodeId()));\r\n\t\t\treturn;\r\n\t\t}\r\n\t\t\r\n\t\tlogger.debug(String.format(\"Node %d, Endpoint = %d, calling handleApplicationCommandRequest.\", this.getNode().getNodeId(), endpointId));\r\n\t\tzwaveCommandClass.handleApplicationCommandRequest(serialMessage, offset + 3, endpointId);\r\n\t}", "public static Method getGetterPropertyMethod(Class<?> type,\r\n\t\t\tString propertyName) {\r\n\t\tString sourceMethodName = \"get\"\r\n\t\t\t\t+ BeanUtils.capitalizePropertyName(propertyName);\r\n\r\n\t\tMethod sourceMethod = BeanUtils.getMethod(type, sourceMethodName);\r\n\r\n\t\tif (sourceMethod == null) {\r\n\t\t\tsourceMethodName = \"is\"\r\n\t\t\t\t\t+ BeanUtils.capitalizePropertyName(propertyName);\r\n\t\t\tsourceMethod = BeanUtils.getMethod(type, sourceMethodName);\r\n\t\t\tif (sourceMethod != null\r\n\t\t\t\t\t&& sourceMethod.getReturnType() != Boolean.TYPE) {\r\n\t\t\t\tsourceMethod = null;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn sourceMethod;\r\n\t}", "public static Date parseEpochTimestamp(String value)\n {\n Date result = null;\n\n if (value.length() > 0)\n {\n if (!value.equals(\"-1 -1\"))\n {\n Calendar cal = DateHelper.popCalendar(JAVA_EPOCH);\n\n int index = value.indexOf(' ');\n if (index == -1)\n {\n if (value.length() < 6)\n {\n value = \"000000\" + value;\n value = value.substring(value.length() - 6);\n }\n\n int hours = Integer.parseInt(value.substring(0, 2));\n int minutes = Integer.parseInt(value.substring(2, 4));\n int seconds = Integer.parseInt(value.substring(4));\n\n cal.set(Calendar.HOUR, hours);\n cal.set(Calendar.MINUTE, minutes);\n cal.set(Calendar.SECOND, seconds);\n }\n else\n {\n long astaDays = Long.parseLong(value.substring(0, index));\n int astaSeconds = Integer.parseInt(value.substring(index + 1));\n\n cal.add(Calendar.DAY_OF_YEAR, (int) (astaDays - ASTA_EPOCH));\n cal.set(Calendar.MILLISECOND, 0);\n cal.set(Calendar.SECOND, 0);\n cal.set(Calendar.HOUR, 0);\n cal.add(Calendar.SECOND, astaSeconds);\n }\n\n result = cal.getTime();\n DateHelper.pushCalendar(cal);\n }\n }\n\n return result;\n }", "protected void appendSQLClause(SelectionCriteria c, StringBuffer buf)\r\n {\r\n // BRJ : handle SqlCriteria\r\n if (c instanceof SqlCriteria)\r\n {\r\n buf.append(c.getAttribute());\r\n return;\r\n }\r\n \r\n // BRJ : criteria attribute is a query\r\n if (c.getAttribute() instanceof Query)\r\n {\r\n Query q = (Query) c.getAttribute();\r\n buf.append(\"(\");\r\n buf.append(getSubQuerySQL(q));\r\n buf.append(\")\");\r\n buf.append(c.getClause());\r\n appendParameter(c.getValue(), buf);\r\n return;\r\n }\r\n\r\n\t\tAttributeInfo attrInfo = getAttributeInfo((String) c.getAttribute(), false, c.getUserAlias(), c.getPathClasses());\r\n TableAlias alias = attrInfo.tableAlias;\r\n\r\n if (alias != null)\r\n {\r\n boolean hasExtents = alias.hasExtents();\r\n\r\n if (hasExtents)\r\n {\r\n // BRJ : surround with braces if alias has extents\r\n buf.append(\"(\");\r\n appendCriteria(alias, attrInfo.pathInfo, c, buf);\r\n\r\n c.setNumberOfExtentsToBind(alias.extents.size());\r\n Iterator iter = alias.iterateExtents();\r\n while (iter.hasNext())\r\n {\r\n TableAlias tableAlias = (TableAlias) iter.next();\r\n buf.append(\" OR \");\r\n appendCriteria(tableAlias, attrInfo.pathInfo, c, buf);\r\n }\r\n buf.append(\")\");\r\n }\r\n else\r\n {\r\n // no extents\r\n appendCriteria(alias, attrInfo.pathInfo, c, buf);\r\n }\r\n }\r\n else\r\n {\r\n // alias null\r\n appendCriteria(alias, attrInfo.pathInfo, c, buf);\r\n }\r\n\r\n }", "private String resolveExpressionString(final String unresolvedString) throws OperationFailedException {\n\n // parseAndResolve should only be providing expressions with no leading or trailing chars\n assert unresolvedString.startsWith(\"${\") && unresolvedString.endsWith(\"}\");\n\n // Default result is no change from input\n String result = unresolvedString;\n\n ModelNode resolveNode = new ModelNode(new ValueExpression(unresolvedString));\n\n // Try plug-in resolution; i.e. vault\n resolvePluggableExpression(resolveNode);\n\n if (resolveNode.getType() == ModelType.EXPRESSION ) {\n // resolvePluggableExpression did nothing. Try standard resolution\n String resolvedString = resolveStandardExpression(resolveNode);\n if (!unresolvedString.equals(resolvedString)) {\n // resolveStandardExpression made progress\n result = resolvedString;\n } // else there is nothing more we can do with this string\n } else {\n // resolvePluggableExpression made progress\n result = resolveNode.asString();\n }\n\n return result;\n }", "public MathTransform calculateLabelTransform(final CoordinateReferenceSystem mapCrs) {\n MathTransform labelTransform;\n if (this.labelProjection != null) {\n try {\n labelTransform = CRS.findMathTransform(mapCrs, this.labelCRS, true);\n } catch (FactoryException e) {\n throw new RuntimeException(e);\n }\n } else {\n labelTransform = IdentityTransform.create(2);\n }\n\n return labelTransform;\n }" ]
Given the comma separated list of properties as a string, splits it multiple strings @param paramValue Concatenated string @param type Type of parameter ( to throw exception ) @return List of string properties
[ "public static List<String> getCommaSeparatedStringValues(String paramValue, String type) {\n List<String> commaSeparatedProps = Lists.newArrayList();\n for(String url: Utils.COMMA_SEP.split(paramValue.trim()))\n if(url.trim().length() > 0)\n commaSeparatedProps.add(url);\n\n if(commaSeparatedProps.size() == 0) {\n throw new RuntimeException(\"Number of \" + type + \" should be greater than zero\");\n }\n return commaSeparatedProps;\n }" ]
[ "public EventBus emit(String event, Object... args) {\n return _emitWithOnceBus(eventContext(event, args));\n }", "public B importContext(AbstractContext context, boolean overwriteDuplicates){\n for (Map.Entry<String, Object> en : context.data.entrySet()) {\n if (overwriteDuplicates) {\n this.data.put(en.getKey(), en.getValue());\n }else{\n this.data.putIfAbsent(en.getKey(), en.getValue());\n }\n }\n return (B) this;\n }", "public void enableCustomResponse(String custom, int path_id, String client_uuid) throws Exception {\n\n updateRequestResponseTables(\"custom_response\", custom, getProfileIdFromPathID(path_id), client_uuid, path_id);\n }", "public static appfwprofile_denyurl_binding[] get(nitro_service service, String name) throws Exception{\n\t\tappfwprofile_denyurl_binding obj = new appfwprofile_denyurl_binding();\n\t\tobj.set_name(name);\n\t\tappfwprofile_denyurl_binding response[] = (appfwprofile_denyurl_binding[]) obj.get_resources(service);\n\t\treturn response;\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 service_stats[] get(nitro_service service) throws Exception{\n\t\tservice_stats obj = new service_stats();\n\t\tservice_stats[] response = (service_stats[])obj.stat_resources(service);\n\t\treturn response;\n\t}", "public static Chart getMSDLineWithConfinedModelChart(Trajectory t, int lagMin,\n\t\t\tint lagMax, double timelag, double a, double b, double c, double d) {\n\n\t\tdouble[] xData = new double[lagMax - lagMin + 1];\n\t\tdouble[] yData = new double[lagMax - lagMin + 1];\n\t\tdouble[] modelData = new double[lagMax - lagMin + 1];\n\t\tMeanSquaredDisplacmentFeature msdeval = new MeanSquaredDisplacmentFeature(\n\t\t\t\tt, lagMin);\n\t\tmsdeval.setTrajectory(t);\n\t\tmsdeval.setTimelag(lagMin);\n\t\tfor (int i = lagMin; i < lagMax + 1; i++) {\n\t\t\tmsdeval.setTimelag(i);\n\t\t\tdouble msdhelp = msdeval.evaluate()[0];\n\t\t\txData[i - lagMin] = i;\n\t\t\tyData[i - lagMin] = msdhelp;\n\t\t\tmodelData[i - lagMin] = a\n\t\t\t\t\t* (1 - b * Math.exp((-4 * d) * ((i * timelag) / a) * c));\n\t\t}\n\n\t\t// Create Chart\n\t\tChart chart = QuickChart.getChart(\"MSD Line\", \"LAG\", \"MSD\", \"MSD\",\n\t\t\t\txData, yData);\n\t\tif(Math.abs(1-b)<0.00001 && Math.abs(1-a)<0.00001){\n\t\t\tchart.addSeries(\"y=a*(1-exp(-4*D*t/a))\", xData, modelData);\n\t\t}else{\n\t\t\tchart.addSeries(\"y=a*(1-b*exp(-4*c*D*t/a))\", xData, modelData);\n\t\t}\n\n\t\t// Show it\n\t\t//new SwingWrapper(chart).displayChart();\n\t\treturn chart;\n\t}", "public float[] getFloatArray(String attributeName)\n {\n float[] array = NativeVertexBuffer.getFloatArray(getNative(), attributeName);\n if (array == null)\n {\n throw new IllegalArgumentException(\"Attribute name \" + attributeName + \" cannot be accessed\");\n }\n return array;\n }", "public final static int readXMLUntil(final StringBuilder out, final String in, final int start, final char... end)\n {\n int pos = start;\n boolean inString = false;\n char stringChar = 0;\n while (pos < in.length())\n {\n final char ch = in.charAt(pos);\n if (inString)\n {\n if (ch == '\\\\')\n {\n out.append(ch);\n pos++;\n if (pos < in.length())\n {\n out.append(ch);\n pos++;\n }\n continue;\n }\n if (ch == stringChar)\n {\n inString = false;\n out.append(ch);\n pos++;\n continue;\n }\n }\n switch (ch)\n {\n case '\"':\n case '\\'':\n inString = true;\n stringChar = ch;\n break;\n }\n if (!inString)\n {\n boolean endReached = false;\n for (int n = 0; n < end.length; n++)\n {\n if (ch == end[n])\n {\n endReached = true;\n break;\n }\n }\n if (endReached)\n {\n break;\n }\n }\n out.append(ch);\n pos++;\n }\n\n return (pos == in.length()) ? -1 : pos;\n }" ]
Use this API to fetch dospolicy resource of given name .
[ "public static dospolicy get(nitro_service service, String name) throws Exception{\n\t\tdospolicy obj = new dospolicy();\n\t\tobj.set_name(name);\n\t\tdospolicy response = (dospolicy) obj.get_resource(service);\n\t\treturn response;\n\t}" ]
[ "public void seekToSeasonYear(String seasonString, String yearString) {\n Season season = Season.valueOf(seasonString);\n assert(season != null);\n \n seekToIcsEventYear(SEASON_ICS_FILE, yearString, season.getSummary());\n }", "public void setIssueTrackerInfo(BuildInfoBuilder builder) {\n Issues issues = new Issues();\n issues.setAggregateBuildIssues(aggregateBuildIssues);\n issues.setAggregationBuildStatus(aggregationBuildStatus);\n issues.setTracker(new IssueTracker(\"JIRA\", issueTrackerVersion));\n Set<Issue> affectedIssuesSet = IssuesTrackerUtils.getAffectedIssuesSet(affectedIssues);\n if (!affectedIssuesSet.isEmpty()) {\n issues.setAffectedIssues(affectedIssuesSet);\n }\n builder.issues(issues);\n }", "MACAddressSegment[] toEUISegments(boolean extended) {\n\t\tIPv6AddressSegment seg0, seg1, seg2, seg3;\n\t\tint start = addressSegmentIndex;\n\t\tint segmentCount = getSegmentCount();\n\t\tint segmentIndex;\n\t\tif(start < 4) {\n\t\t\tstart = 0;\n\t\t\tsegmentIndex = 4 - start;\n\t\t} else {\n\t\t\tstart -= 4;\n\t\t\tsegmentIndex = 0;\n\t\t}\n\t\tint originalSegmentIndex = segmentIndex;\n\t\tseg0 = (start == 0 && segmentIndex < segmentCount) ? getSegment(segmentIndex++) : null;\n\t\tseg1 = (start <= 1 && segmentIndex < segmentCount) ? getSegment(segmentIndex++) : null;\n\t\tseg2 = (start <= 2 && segmentIndex < segmentCount) ? getSegment(segmentIndex++) : null;\n\t\tseg3 = (start <= 3 && segmentIndex < segmentCount) ? getSegment(segmentIndex++) : null;\n\t\tint macSegCount = (segmentIndex - originalSegmentIndex) << 1;\n\t\tif(!extended) {\n\t\t\tmacSegCount -= 2;\n\t\t}\n\t\tif((seg1 != null && !seg1.matchesWithMask(0xff, 0xff)) || (seg2 != null && !seg2.matchesWithMask(0xfe00, 0xff00)) || macSegCount == 0) {\n\t\t\treturn null;\n\t\t}\n\t\tMACAddressCreator creator = getMACNetwork().getAddressCreator();\n\t\tMACAddressSegment ZERO_SEGMENT = creator.createSegment(0);\n\t\tMACAddressSegment newSegs[] = creator.createSegmentArray(macSegCount);\n\t\tint macStartIndex = 0;\n\t\tif(seg0 != null) {\n\t\t\tseg0.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t\t//toggle the u/l bit\n\t\t\tMACAddressSegment macSegment0 = newSegs[0];\n\t\t\tint lower0 = macSegment0.getSegmentValue();\n\t\t\tint upper0 = macSegment0.getUpperSegmentValue();\n\t\t\tint mask2ndBit = 0x2;\n\t\t\tif(!macSegment0.matchesWithMask(mask2ndBit & lower0, mask2ndBit)) {\n\t\t\t\treturn null;\n\t\t\t}\n\t\t\t//you can use matches with mask\n\t\t\tlower0 ^= mask2ndBit;//flip the universal/local bit\n\t\t\tupper0 ^= mask2ndBit;\n\t\t\tnewSegs[0] = creator.createSegment(lower0, upper0, null);\n\t\t\tmacStartIndex += 2;\n\t\t}\n\t\tif(seg1 != null) {\n\t\t\tseg1.getSplitSegments(newSegs, macStartIndex, creator); //a ff fe b\n\t\t\tif(!extended) {\n\t\t\t\tnewSegs[macStartIndex + 1] = ZERO_SEGMENT;\n\t\t\t}\n\t\t\tmacStartIndex += 2;\n\t\t}\n\t\tif(seg2 != null) {\n\t\t\tif(!extended) {\n\t\t\t\tif(seg1 != null) {\n\t\t\t\t\tmacStartIndex -= 2;\n\t\t\t\t\tMACAddressSegment first = newSegs[macStartIndex];\n\t\t\t\t\tseg2.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t\t\t\tnewSegs[macStartIndex] = first;\n\t\t\t\t} else {\n\t\t\t\t\tseg2.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t\t\t\tnewSegs[macStartIndex] = ZERO_SEGMENT;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tseg2.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t\t}\n\t\t\tmacStartIndex += 2;\n\t\t}\n\t\tif(seg3 != null) {\n\t\t\tseg3.getSplitSegments(newSegs, macStartIndex, creator);\n\t\t}\n\t\treturn newSegs;\n\t}", "private static Originator mapOriginatorType(OriginatorType originatorType) {\n Originator originator = new Originator();\n if (originatorType != null) {\n originator.setCustomId(originatorType.getCustomId());\n originator.setHostname(originatorType.getHostname());\n originator.setIp(originatorType.getIp());\n originator.setProcessId(originatorType.getProcessId());\n originator.setPrincipal(originatorType.getPrincipal());\n }\n return originator;\n }", "public PropertiesEnvelope createUserProperties(String userId, AppProperties properties, String aid) throws ApiException {\n ApiResponse<PropertiesEnvelope> resp = createUserPropertiesWithHttpInfo(userId, properties, aid);\n return resp.getData();\n }", "public Boolean invoke(File pomFile, VirtualChannel channel) throws IOException, InterruptedException {\n\n org.jfrog.build.extractor.maven.reader.ModuleName current = new org.jfrog.build.extractor.maven.reader.ModuleName(\n currentModule.groupId, currentModule.artifactId);\n\n Map<org.jfrog.build.extractor.maven.reader.ModuleName, String> modules = Maps.newLinkedHashMap();\n for (Map.Entry<ModuleName, String> entry : versionsByModule.entrySet()) {\n modules.put(new org.jfrog.build.extractor.maven.reader.ModuleName(\n entry.getKey().groupId, entry.getKey().artifactId), entry.getValue());\n }\n\n org.jfrog.build.extractor.maven.transformer.PomTransformer transformer =\n new org.jfrog.build.extractor.maven.transformer.PomTransformer(current, modules, scmUrl,\n failOnSnapshot);\n\n return transformer.transform(pomFile);\n }", "private static Set<ProjectModel> getAllApplications(GraphContext graphContext)\n {\n Set<ProjectModel> apps = new HashSet<>();\n Iterable<ProjectModel> appProjects = graphContext.findAll(ProjectModel.class);\n for (ProjectModel appProject : appProjects)\n apps.add(appProject);\n return apps;\n }", "@SuppressWarnings(\"serial\")\n private Button createSaveExitButton() {\n\n Button saveExitBtn = CmsToolBar.createButton(\n FontOpenCms.SAVE_EXIT,\n m_messages.key(Messages.GUI_BUTTON_SAVE_AND_EXIT_0));\n saveExitBtn.addClickListener(new ClickListener() {\n\n public void buttonClick(ClickEvent event) {\n\n saveAction();\n closeAction();\n\n }\n });\n saveExitBtn.setEnabled(false);\n return saveExitBtn;\n }", "public void leave(String groupId, Boolean deletePhotos) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_LEAVE);\r\n parameters.put(\"group_id\", groupId);\r\n parameters.put(\"delete_photos\", deletePhotos);\r\n\r\n Response response = transportAPI.post(transportAPI.getPath(), parameters, apiKey, sharedSecret);\r\n if (response.isError()) {\r\n throw new FlickrException(response.getErrorCode(), response.getErrorMessage());\r\n }\r\n }" ]
Use this API to delete onlinkipv6prefix of given name.
[ "public static base_response delete(nitro_service client, String ipv6prefix) throws Exception {\n\t\tonlinkipv6prefix deleteresource = new onlinkipv6prefix();\n\t\tdeleteresource.ipv6prefix = ipv6prefix;\n\t\treturn deleteresource.delete_resource(client);\n\t}" ]
[ "public OperationTransformerEntry resolveOperationTransformer(final PathAddress address, final String operationName, PlaceholderResolver placeholderResolver) {\n final Iterator<PathElement> iterator = address.iterator();\n final OperationTransformerEntry entry = resolveOperationTransformer(iterator, operationName, placeholderResolver);\n if(entry != null) {\n return entry;\n }\n // Default is forward unchanged\n return FORWARD;\n }", "public void animate(GVRHybridObject object, float animationTime)\n {\n GVRMeshMorph morph = (GVRMeshMorph) mTarget;\n\n mKeyInterpolator.animate(animationTime * mDuration, mCurrentValues);\n morph.setWeights(mCurrentValues);\n\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 }", "private static MonetaryFormatsSingletonSpi loadMonetaryFormatsSingletonSpi() {\n try {\n return Optional.ofNullable(Bootstrap.getService(MonetaryFormatsSingletonSpi.class))\n .orElseGet(DefaultMonetaryFormatsSingletonSpi::new);\n } catch (Exception e) {\n Logger.getLogger(MonetaryFormats.class.getName())\n .log(Level.WARNING, \"Failed to load MonetaryFormatsSingletonSpi, using default.\", e);\n return new DefaultMonetaryFormatsSingletonSpi();\n }\n }", "private boolean isNullOrEmpty(Object paramValue) {\n boolean isNullOrEmpty = false;\n if (paramValue == null) {\n isNullOrEmpty = true;\n }\n if (paramValue instanceof String) {\n if (((String) paramValue).trim().equalsIgnoreCase(\"\")) {\n isNullOrEmpty = true;\n }\n } else if (paramValue instanceof List) {\n return ((List) paramValue).isEmpty();\n }\n return isNullOrEmpty;\n }", "public void applyToPrimaryClassNodes(PrimaryClassNodeOperation body) throws CompilationFailedException {\n Iterator classNodes = getPrimaryClassNodes(body.needSortedInput()).iterator();\n while (classNodes.hasNext()) {\n SourceUnit context = null;\n try {\n ClassNode classNode = (ClassNode) classNodes.next();\n context = classNode.getModule().getContext();\n if (context == null || context.phase < phase || (context.phase == phase && !context.phaseComplete)) {\n int offset = 1;\n Iterator<InnerClassNode> iterator = classNode.getInnerClasses();\n while (iterator.hasNext()) {\n iterator.next();\n offset++;\n }\n body.call(context, new GeneratorContext(this.ast, offset), classNode);\n }\n } catch (CompilationFailedException e) {\n // fall through, getErrorReporter().failIfErrors() will trigger\n } catch (NullPointerException npe) {\n GroovyBugError gbe = new GroovyBugError(\"unexpected NullpointerException\", npe);\n changeBugText(gbe, context);\n throw gbe;\n } catch (GroovyBugError e) {\n changeBugText(e, context);\n throw e;\n } catch (NoClassDefFoundError e) {\n // effort to get more logging in case a dependency of a class is loaded\n // although it shouldn't have\n convertUncaughtExceptionToCompilationError(e);\n } catch (Exception e) {\n convertUncaughtExceptionToCompilationError(e);\n }\n }\n\n getErrorCollector().failIfErrors();\n }", "private void tryToSetParsedValue(String value) throws Exception {\n\n JSONObject json = JSONParser.parseStrict(value).isObject();\n JSONValue val = json.get(JsonKey.START);\n setStart(readOptionalDate(val));\n val = json.get(JsonKey.END);\n setEnd(readOptionalDate(val));\n setWholeDay(readOptionalBoolean(json.get(JsonKey.WHOLE_DAY)));\n JSONObject patternJson = json.get(JsonKey.PATTERN).isObject();\n readPattern(patternJson);\n setExceptions(readDates(json.get(JsonKey.EXCEPTIONS)));\n setSeriesEndDate(readOptionalDate(json.get(JsonKey.SERIES_ENDDATE)));\n setOccurrences(readOptionalInt(json.get(JsonKey.SERIES_OCCURRENCES)));\n setDerivedEndType();\n setCurrentTillEnd(readOptionalBoolean(json.get(JsonKey.CURRENT_TILL_END)));\n setParentSeriesId(readOptionalUUID(json.get(JsonKey.PARENT_SERIES)));\n\n }", "@NonNull public Context getContext() {\n if (searchView != null) {\n return searchView.getContext();\n } else if (supportView != null) {\n return supportView.getContext();\n }\n throw new IllegalStateException(ERROR_NO_SEARCHVIEW);\n }", "public void render(OutputStream outputStream, Format format, int dpi) throws PrintingException {\n\t\ttry {\n\t\t\tif (baos == null) {\n\t\t\t\tprepare();\n\t\t\t}\n\t\t\twriteDocument(outputStream, format, dpi);\n\t\t} catch (Exception e) { // NOSONAR\n\t\t\tthrow new PrintingException(e, PrintingException.DOCUMENT_RENDER_PROBLEM);\n\t\t}\n\t}" ]
Read the metadata from a hadoop SequenceFile @param fs The filesystem to read from @param path The file to read from @return The metadata from this file
[ "public static Map<String, String> getMetadataFromSequenceFile(FileSystem fs, Path path) {\n try {\n Configuration conf = new Configuration();\n conf.setInt(\"io.file.buffer.size\", 4096);\n SequenceFile.Reader reader = new SequenceFile.Reader(fs, path, new Configuration());\n SequenceFile.Metadata meta = reader.getMetadata();\n reader.close();\n TreeMap<Text, Text> map = meta.getMetadata();\n Map<String, String> values = new HashMap<String, String>();\n for(Map.Entry<Text, Text> entry: map.entrySet())\n values.put(entry.getKey().toString(), entry.getValue().toString());\n\n return values;\n } catch(IOException e) {\n throw new RuntimeException(e);\n }\n }" ]
[ "public ArtifactName build() {\n String groupId = this.groupId;\n String artifactId = this.artifactId;\n String classifier = this.classifier;\n String packaging = this.packaging;\n String version = this.version;\n if (artifact != null && !artifact.isEmpty()) {\n final String[] artifactSegments = artifact.split(\":\");\n // groupId:artifactId:version[:packaging][:classifier].\n String value;\n switch (artifactSegments.length) {\n case 5:\n value = artifactSegments[4].trim();\n if (!value.isEmpty()) {\n classifier = value;\n }\n case 4:\n value = artifactSegments[3].trim();\n if (!value.isEmpty()) {\n packaging = value;\n }\n case 3:\n value = artifactSegments[2].trim();\n if (!value.isEmpty()) {\n version = value;\n }\n case 2:\n value = artifactSegments[1].trim();\n if (!value.isEmpty()) {\n artifactId = value;\n }\n case 1:\n value = artifactSegments[0].trim();\n if (!value.isEmpty()) {\n groupId = value;\n }\n }\n }\n return new ArtifactNameImpl(groupId, artifactId, classifier, packaging, version);\n }", "private void debugLogStart(String operationType,\n Long originTimeInMS,\n Long requestReceivedTimeInMs,\n String keyString) {\n long durationInMs = requestReceivedTimeInMs - originTimeInMS;\n logger.debug(\"Received a new request. Operation Type: \" + operationType + \" , key(s): \"\n + keyString + \" , Store: \" + this.storeName + \" , Origin time (in ms): \"\n + originTimeInMS + \" . Request received at time(in ms): \"\n + requestReceivedTimeInMs\n + \" , Duration from RESTClient to CoordinatorFatClient(in ms): \"\n + durationInMs);\n\n }", "public void revertWorkingCopy() throws IOException, InterruptedException {\n build.getWorkspace()\n .act(new RevertWorkingCopyCallable(getLocation(), getSvnAuthenticationProvider(build), buildListener));\n }", "public void release(Contextual<T> contextual, T instance) {\n synchronized (dependentInstances) {\n for (ContextualInstance<?> dependentInstance : dependentInstances) {\n // do not destroy contextual again, since it's just being destroyed\n if (contextual == null || !(dependentInstance.getContextual().equals(contextual))) {\n destroy(dependentInstance);\n }\n }\n }\n if (resourceReferences != null) {\n for (ResourceReference<?> reference : resourceReferences) {\n reference.release();\n }\n }\n }", "@SuppressWarnings(\"unchecked\")\n @Nonnull\n public final java.util.Optional<Style> getStyle(final String styleName) {\n final String styleRef = this.styles.get(styleName);\n Optional<Style> style;\n if (styleRef != null) {\n style = (Optional<Style>) this.styleParser\n .loadStyle(getConfiguration(), this.httpRequestFactory, styleRef);\n } else {\n style = Optional.empty();\n }\n return or(style, this.configuration.getStyle(styleName));\n }", "public String updateClassification(String classificationType) {\n Metadata metadata = new Metadata(\"enterprise\", Metadata.CLASSIFICATION_TEMPLATE_KEY);\n metadata.add(\"/Box__Security__Classification__Key\", classificationType);\n Metadata classification = this.updateMetadata(metadata);\n\n return classification.getString(Metadata.CLASSIFICATION_KEY);\n }", "private void parseMacro( TokenList tokens , Sequence sequence ) {\n Macro macro = new Macro();\n\n TokenList.Token t = tokens.getFirst().next;\n\n if( t.word == null ) {\n throw new ParseError(\"Expected the macro's name after \"+tokens.getFirst().word);\n }\n List<TokenList.Token> variableTokens = new ArrayList<TokenList.Token>();\n\n macro.name = t.word;\n t = t.next;\n t = parseMacroInput(variableTokens, t);\n for( TokenList.Token a : variableTokens ) {\n if( a.word == null) throw new ParseError(\"expected word in macro header\");\n macro.inputs.add(a.word);\n }\n t = t.next;\n if( t == null || t.getSymbol() != Symbol.ASSIGN)\n throw new ParseError(\"Expected assignment\");\n t = t.next;\n macro.tokens = new TokenList(t,tokens.last);\n\n sequence.addOperation(macro.createOperation(macros));\n }", "public Task<Long> count() {\n return dispatcher.dispatchTask(new Callable<Long>() {\n @Override\n public Long call() {\n return proxy.count();\n }\n });\n }", "public void onSplashScreenCreated(GVRSceneObject splashScreen) {\n GVRTransform transform = splashScreen.getTransform();\n transform.setPosition(0, 0, DEFAULT_SPLASH_Z);\n }" ]
Creates a bridge accessory, capable of holding multiple child accessories. This has the advantage over multiple standalone accessories of only requiring a single pairing from iOS for the bridge. @param authInfo authentication information for this accessory. These values should be persisted and re-supplied on re-start of your application. @param label label for the bridge. This will show in iOS during pairing. @param manufacturer manufacturer of the bridge. This information is exposed to iOS for unknown purposes. @param model model of the bridge. This is also exposed to iOS for unknown purposes. @param serialNumber serial number of the bridge. Also exposed. Purposes also unknown. @return the bridge, from which you can {@link HomekitRoot#addAccessory add accessories} and then {@link HomekitRoot#start start} handling requests. @throws IOException when mDNS cannot connect to the network
[ "public HomekitRoot createBridge(\n HomekitAuthInfo authInfo,\n String label,\n String manufacturer,\n String model,\n String serialNumber)\n throws IOException {\n HomekitRoot root = new HomekitRoot(label, http, localAddress, authInfo);\n root.addAccessory(new HomekitBridge(label, serialNumber, model, manufacturer));\n return root;\n }" ]
[ "protected AbsoluteURI getGeneratedLocation(PersistedTrace trace) {\n\t\tAbsoluteURI path = trace.getPath();\n\t\tString fileName = traceFileNameProvider.getJavaFromTrace(path.getURI().toString());\n\t\treturn new AbsoluteURI(fileName);\n\t}", "public FluoMutationGenerator put(Column col, CharSequence value) {\n return put(col, value.toString().getBytes(StandardCharsets.UTF_8));\n }", "public static String getDefaultConversionFor(String javaType)\r\n {\r\n return _jdbcConversions.containsKey(javaType) ? (String)_jdbcConversions.get(javaType) : null;\r\n }", "@Override\n\tpublic String toCanonicalString() {\n\t\tString result;\n\t\tif(hasNoStringCache() || (result = stringCache.canonicalString) == null) {\n\t\t\tstringCache.canonicalString = result = toNormalizedString(IPv6StringCache.canonicalParams);\n\t\t}\n\t\treturn result;\n\t}", "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 }", "@ViewChanged\n\tpublic synchronized void onViewChangeEvent(ViewChangedEvent event) {\n\t\t\n\t\tif (logger.isDebugEnabled()) {\n\t\t\tlogger.debug(\"onViewChangeEvent : pre[\" + event.isPre() + \"] : event local address[\" + event.getCache().getLocalAddress() + \"]\");\n\t\t}\n\t\t\n\t\tfinal List<Address> oldView = currentView;\n\t\tcurrentView = new ArrayList<Address>(event.getNewView().getMembers());\n\t\tfinal Address localAddress = getLocalAddress();\n\t\t\n\t\t//just a precaution, it can be null!\n\t\tif (oldView != null) {\n\t\t\tfinal Cache jbossCache = mobicentsCache.getJBossCache();\n\t\t\tfinal Configuration config = jbossCache.getConfiguration();\t\t\n\n\t\t\tfinal boolean isBuddyReplicationEnabled = config.getBuddyReplicationConfig() != null && config.getBuddyReplicationConfig().isEnabled();\n\t\t\t// recover stuff from lost members\n\t\t\tRunnable runnable = new Runnable() {\n\t\t\t\tpublic void run() {\n\t\t\t\t\tfor (Address oldMember : oldView) {\n\t\t\t\t\t\tif (!currentView.contains(oldMember)) {\n\t\t\t\t\t\t\tif (logger.isDebugEnabled()) {\n\t\t\t\t\t\t\t\tlogger.debug(\"onViewChangeEvent : processing lost member \" + oldMember);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tfor (FailOverListener localListener : failOverListeners) {\n\t\t\t\t\t\t\t\tClientLocalListenerElector localListenerElector = localListener.getElector();\n\t\t\t\t\t\t\t\tif (localListenerElector != null && !isBuddyReplicationEnabled) {\n\t\t\t\t\t\t\t\t\t// going to use the local listener elector instead, which gives results based on data\n\t\t\t\t\t\t\t\t\tperformTakeOver(localListener,oldMember,localAddress, true, isBuddyReplicationEnabled);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tList<Address> electionView = getElectionView(oldMember);\n\t\t\t\t\t\t\t\t\tif(electionView!=null && elector.elect(electionView).equals(localAddress))\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\tperformTakeOver(localListener, oldMember, localAddress, false, isBuddyReplicationEnabled);\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\tcleanAfterTakeOver(localListener, oldMember);\n\t\t\t\t\t\t\t\t}\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\tThread t = new Thread(runnable);\n\t\t\tt.start();\n\t\t}\n\t\t\n\t}", "public CmsJspDateSeriesBean getToDateSeries() {\n\n if (m_dateSeries == null) {\n m_dateSeries = new CmsJspDateSeriesBean(this, m_cms.getRequestContext().getLocale());\n }\n return m_dateSeries;\n }", "public void process(InputStream is) throws Exception\n {\n readHeader(is);\n readVersion(is);\n readTableData(readTableHeaders(is), is);\n }", "public List<ConnectionInfo> getConnections() {\n final URI uri = uriWithPath(\"./connections/\");\n return Arrays.asList(this.rt.getForObject(uri, ConnectionInfo[].class));\n }" ]
Updates the path_order column in the table, loops though the pathOrder array, and changes the value to the loop index+1 for the specified pathId @param profileId ID of profile @param pathOrder array containing new order of paths
[ "public void updatePathOrder(int profileId, int[] pathOrder) {\n for (int i = 0; i < pathOrder.length; i++) {\n EditService.updatePathTable(Constants.PATH_PROFILE_PATH_ORDER, (i + 1), pathOrder[i]);\n }\n }" ]
[ "private LinkedList<TimephasedWork> readTimephasedAssignment(ProjectCalendar calendar, Project.Assignments.Assignment assignment, int type)\n {\n LinkedList<TimephasedWork> result = new LinkedList<TimephasedWork>();\n\n for (TimephasedDataType item : assignment.getTimephasedData())\n {\n if (NumberHelper.getInt(item.getType()) != type)\n {\n continue;\n }\n\n Date startDate = item.getStart();\n Date finishDate = item.getFinish();\n\n // Exclude ranges which don't have a start and end date.\n // These seem to be generated by Synchro and have a zero duration.\n if (startDate == null && finishDate == null)\n {\n continue;\n }\n\n Duration work = DatatypeConverter.parseDuration(m_projectFile, TimeUnit.MINUTES, item.getValue());\n if (work == null)\n {\n work = Duration.getInstance(0, TimeUnit.MINUTES);\n }\n else\n {\n work = Duration.getInstance(NumberHelper.round(work.getDuration(), 2), TimeUnit.MINUTES);\n }\n\n TimephasedWork tra = new TimephasedWork();\n tra.setStart(startDate);\n tra.setFinish(finishDate);\n tra.setTotalAmount(work);\n\n result.add(tra);\n }\n\n return result;\n }", "public String getInvalidMessage(String key) {\n return invalidMessageOverride == null ? messageMixin.lookup(key, messageValueArgs) : MessageFormat.format(\n invalidMessageOverride, messageValueArgs);\n }", "private static int getTrimmedHeight(BufferedImage img) {\n int width = img.getWidth();\n int height = img.getHeight();\n int trimmedHeight = 0;\n\n for (int i = 0; i < width; i++) {\n for (int j = height - 1; j >= 0; j--) {\n if (img.getRGB(i, j) != Color.WHITE.getRGB() && j > trimmedHeight) {\n trimmedHeight = j;\n break;\n }\n }\n }\n\n return trimmedHeight;\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 }", "private InputStream getErrorStream() {\n InputStream errorStream = this.connection.getErrorStream();\n if (errorStream != null) {\n final String contentEncoding = this.connection.getContentEncoding();\n if (contentEncoding != null && contentEncoding.equalsIgnoreCase(\"gzip\")) {\n try {\n errorStream = new GZIPInputStream(errorStream);\n } catch (IOException e) {\n // just return the error stream as is\n }\n }\n }\n\n return errorStream;\n }", "private void doSend(byte[] msg, boolean wait, KNXAddress dst)\r\n\t\tthrows KNXAckTimeoutException, KNXLinkClosedException\r\n\t{\r\n\t\tif (closed)\r\n\t\t\tthrow new KNXLinkClosedException(\"link closed\");\r\n\t\ttry {\r\n\t\t\tlogger.info(\"send message to \" + dst + (wait ? \", wait for ack\" : \"\"));\r\n\t\t\tlogger.trace(\"EMI \" + DataUnitBuilder.toHex(msg, \" \"));\r\n\t\t\tconn.send(msg, wait);\r\n\t\t\tlogger.trace(\"send to \" + dst + \" succeeded\");\r\n\t\t}\r\n\t\tcatch (final KNXPortClosedException e) {\r\n\t\t\tlogger.error(\"send error, closing link\", e);\r\n\t\t\tclose();\r\n\t\t\tthrow new KNXLinkClosedException(\"link closed, \" + e.getMessage());\r\n\t\t}\r\n\t}", "public static boolean any(Object self, Closure closure) {\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext();) {\n if (bcw.call(iter.next())) return true;\n }\n return false;\n }", "public void addFile(String description, FileModel fileModel)\n {\n Map<FileModel, ProblemFileSummary> files = addDescription(description);\n\n if (files.containsKey(fileModel))\n {\n files.get(fileModel).addOccurrence();\n } else {\n files.put(fileModel, new ProblemFileSummary(fileModel, 1));\n }\n }", "public static Variable upcastToGeneratedBuilder(\n SourceBuilder code, Datatype datatype, String builder) {\n return code.scope().computeIfAbsent(Declaration.UPCAST, () -> {\n Variable base = new Variable(\"base\");\n code.addLine(UPCAST_COMMENT)\n .addLine(\"%s %s = %s;\", datatype.getGeneratedBuilder(), base, builder);\n return base;\n });\n }" ]
Send ourselves "updates" about any tracks that were loaded before we started, since we missed them.
[ "private void checkExistingTracks() {\n SwingUtilities.invokeLater(new Runnable() {\n @Override\n public void run() {\n for (Map.Entry<DeckReference, TrackMetadata> entry : MetadataFinder.getInstance().getLoadedTracks().entrySet()) {\n if (entry.getKey().hotCue == 0) { // The track is currently loaded in a main player deck\n checkIfSignatureReady(entry.getKey().player);\n }\n }\n }\n });\n }" ]
[ "boolean lock(final Integer permit, final long timeout, final TimeUnit unit) {\n boolean result = false;\n try {\n result = lockInterruptibly(permit, timeout, unit);\n } catch (InterruptedException e) {\n Thread.currentThread().interrupt();\n }\n return result;\n }", "public void BuildInteractiveObjectFromAnchor(Sensor anchorSensor, String anchorDestination) {\n InteractiveObject interactiveObject = new InteractiveObject();\n interactiveObject.setSensor(anchorSensor, anchorDestination);\n interactiveObjects.add(interactiveObject);\n }", "private byte[] getData(List<byte[]> blocks, int length)\n {\n byte[] result;\n\n if (blocks.isEmpty() == false)\n {\n if (length < 4)\n {\n length = 4;\n }\n\n result = new byte[length];\n int offset = 0;\n byte[] data;\n\n while (offset < length)\n {\n data = blocks.remove(0);\n System.arraycopy(data, 0, result, offset, data.length);\n offset += data.length;\n }\n }\n else\n {\n result = null;\n }\n\n return (result);\n }", "public List<CmsProject> getAllAccessibleProjects(CmsObject cms, String ouFqn, boolean includeSubOus)\n throws CmsException {\n\n CmsOrganizationalUnit orgUnit = readOrganizationalUnit(cms, ouFqn);\n return (m_securityManager.getAllAccessibleProjects(cms.getRequestContext(), orgUnit, includeSubOus));\n }", "private void processWorkWeeks(byte[] data, int offset, ProjectCalendar cal)\n {\n // System.out.println(\"Calendar=\" + cal.getName());\n // System.out.println(\"Work week block start offset=\" + offset);\n // System.out.println(ByteArrayHelper.hexdump(data, true, 16, \"\"));\n\n // skip 4 byte header\n offset += 4;\n\n while (data.length >= offset + ((7 * 60) + 2 + 2 + 8 + 4))\n {\n //System.out.println(\"Week start offset=\" + offset);\n ProjectCalendarWeek week = cal.addWorkWeek();\n for (Day day : Day.values())\n {\n // 60 byte block per day\n processWorkWeekDay(data, offset, week, day);\n offset += 60;\n }\n\n Date startDate = DateHelper.getDayStartDate(MPPUtility.getDate(data, offset));\n offset += 2;\n\n Date finishDate = DateHelper.getDayEndDate(MPPUtility.getDate(data, offset));\n offset += 2;\n\n // skip unknown 8 bytes\n //System.out.println(ByteArrayHelper.hexdump(data, offset, 8, false));\n offset += 8;\n\n //\n // Extract the name length - ensure that it is aligned to a 4 byte boundary\n //\n int nameLength = MPPUtility.getInt(data, offset);\n if (nameLength % 4 != 0)\n {\n nameLength = ((nameLength / 4) + 1) * 4;\n }\n offset += 4;\n\n if (nameLength != 0)\n {\n String name = MPPUtility.getUnicodeString(data, offset, nameLength);\n offset += nameLength;\n week.setName(name);\n }\n\n week.setDateRange(new DateRange(startDate, finishDate));\n // System.out.println(week);\n }\n }", "public static base_response unset(nitro_service client, inatparam resource, String[] args) throws Exception{\n\t\tinatparam unsetresource = new inatparam();\n\t\treturn unsetresource.unset_resource(client,args);\n\t}", "public void sort(ChildTaskContainer container)\n {\n // Do we have any tasks?\n List<Task> tasks = container.getChildTasks();\n if (!tasks.isEmpty())\n {\n for (Task task : tasks)\n {\n //\n // Sort child activities\n //\n sort(task);\n\n //\n // Sort Order:\n // 1. Activities come first\n // 2. WBS come last\n // 3. Activities ordered by activity ID\n // 4. WBS ordered by ID\n //\n Collections.sort(tasks, new Comparator<Task>()\n {\n @Override public int compare(Task t1, Task t2)\n {\n boolean t1IsWbs = m_wbsTasks.contains(t1);\n boolean t2IsWbs = m_wbsTasks.contains(t2);\n\n // Both are WBS\n if (t1IsWbs && t2IsWbs)\n {\n return t1.getID().compareTo(t2.getID());\n }\n\n // Both are activities\n if (!t1IsWbs && !t2IsWbs)\n {\n String activityID1 = (String) t1.getCurrentValue(m_activityIDField);\n String activityID2 = (String) t2.getCurrentValue(m_activityIDField);\n\n if (activityID1 == null || activityID2 == null)\n {\n return (activityID1 == null && activityID2 == null ? 0 : (activityID1 == null ? 1 : -1));\n }\n\n return activityID1.compareTo(activityID2);\n }\n\n // One activity one WBS\n return t1IsWbs ? 1 : -1;\n }\n });\n }\n }\n }", "private void writePropertyData() {\n\t\ttry (PrintStream out = new PrintStream(\n\t\t\t\tExampleHelpers.openExampleFileOuputStream(\"properties.csv\"))) {\n\n\t\t\tout.println(\"Id\" + \",Label\" + \",Description\" + \",URL\" + \",Datatype\"\n\t\t\t\t\t+ \",Uses in statements\" + \",Items with such statements\"\n\t\t\t\t\t+ \",Uses in statements with qualifiers\"\n\t\t\t\t\t+ \",Uses in qualifiers\" + \",Uses in references\"\n\t\t\t\t\t+ \",Uses total\" + \",Related properties\");\n\n\t\t\tList<Entry<PropertyIdValue, PropertyRecord>> list = new ArrayList<Entry<PropertyIdValue, PropertyRecord>>(\n\t\t\t\t\tthis.propertyRecords.entrySet());\n\t\t\tCollections.sort(list, new UsageRecordComparator());\n\t\t\tfor (Entry<PropertyIdValue, PropertyRecord> entry : list) {\n\t\t\t\tprintPropertyRecord(out, entry.getValue(), entry.getKey());\n\t\t\t}\n\n\t\t} catch (IOException e) {\n\t\t\te.printStackTrace();\n\t\t}\n\t}", "public List<Integer> getAsyncOperationList(boolean showCompleted) {\n /**\n * Create a copy using an immutable set to avoid a\n * {@link java.util.ConcurrentModificationException}\n */\n Set<Integer> keySet = ImmutableSet.copyOf(operations.keySet());\n\n if(showCompleted)\n return new ArrayList<Integer>(keySet);\n\n List<Integer> keyList = new ArrayList<Integer>();\n for(int key: keySet) {\n AsyncOperation operation = operations.get(key);\n if(operation != null && !operation.getStatus().isComplete())\n keyList.add(key);\n }\n return keyList;\n }" ]
Request a scoped transactional token. @param accessToken application access token. @param scope scope of transactional token. @return a BoxAPIConnection which can be used to perform transactional requests.
[ "public static BoxAPIConnection getTransactionConnection(String accessToken, String scope) {\n return BoxTransactionalAPIConnection.getTransactionConnection(accessToken, scope, null);\n }" ]
[ "public void addPartialFieldAssignment(\n SourceBuilder code, Excerpt finalField, String builder) {\n addFinalFieldAssignment(code, finalField, builder);\n }", "public int getGeoPerms() throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n parameters.put(\"method\", METHOD_GET_GEO_PERMS);\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 int perm = -1;\r\n Element personElement = response.getPayload();\r\n String geoPerms = personElement.getAttribute(\"geoperms\");\r\n try {\r\n perm = Integer.parseInt(geoPerms);\r\n } catch (NumberFormatException e) {\r\n throw new FlickrException(\"0\", \"Unable to parse geoPermission\");\r\n }\r\n return perm;\r\n }", "private ProjectCalendar deriveResourceCalendar(Integer parentCalendarID)\n {\n ProjectCalendar calendar = m_project.addDefaultDerivedCalendar();\n calendar.setUniqueID(Integer.valueOf(m_project.getProjectConfig().getNextCalendarUniqueID()));\n calendar.setParent(m_project.getCalendarByUniqueID(parentCalendarID));\n return calendar;\n }", "public static boolean isResourceTypeIdFree(int id) {\n\n try {\n OpenCms.getResourceManager().getResourceType(id);\n } catch (CmsLoaderException e) {\n return true;\n }\n return false;\n }", "public void run() {\r\n\t\tConnectionHandle connection = null;\r\n\t\tlong tmp;\r\n\t\tlong nextCheckInMs = this.maxAgeInMs;\r\n\r\n\t\tint partitionSize= this.partition.getAvailableConnections();\r\n\t\tlong currentTime = System.currentTimeMillis();\r\n\t\tfor (int i=0; i < partitionSize; i++){\r\n\t\t\ttry {\r\n\t\t\t\tconnection = this.partition.getFreeConnections().poll();\r\n\r\n\t\t\t\tif (connection != null){\r\n\t\t\t\t\tconnection.setOriginatingPartition(this.partition);\r\n\r\n\t\t\t\t\ttmp = this.maxAgeInMs - (currentTime - connection.getConnectionCreationTimeInMs()); \r\n\r\n\t\t\t\t\tif (tmp < nextCheckInMs){\r\n\t\t\t\t\t\tnextCheckInMs = tmp; \r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif (connection.isExpired(currentTime)){\r\n\t\t\t\t\t\t// kill off this connection\r\n\t\t\t\t\t\tcloseConnection(connection);\r\n\t\t\t\t\t\tcontinue;\r\n\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\t\r\n\t\t\t\t\tif (this.lifoMode){\r\n\t\t\t\t\t\t// we can't put it back normally or it will end up in front again.\r\n\t\t\t\t\t\tif (!(connection.getOriginatingPartition().getFreeConnections().offer(connection))){\r\n\t\t\t\t\t\t\tconnection.internalClose();\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\tthis.pool.putConnectionBackInPartition(connection);\r\n\t\t\t\t\t}\r\n\r\n\r\n\t\t\t\t\tThread.sleep(20L); // test slowly, this is not an operation that we're in a hurry to deal with (avoid CPU spikes)...\r\n\t\t\t\t}\r\n\t\t\t} catch (Throwable e) {\r\n\t\t\t\t\tlogger.error(\"Connection max age thread exception.\", e);\r\n\t\t\t}\r\n\r\n\t\t} // throw it back on the queue\r\n\r\n\t}", "private void writeBooleanField(String fieldName, Object value) throws IOException\n {\n boolean val = ((Boolean) value).booleanValue();\n if (val)\n {\n m_writer.writeNameValuePair(fieldName, val);\n }\n }", "public static base_response update(nitro_service client, spilloverpolicy resource) throws Exception {\n\t\tspilloverpolicy updateresource = new spilloverpolicy();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.rule = resource.rule;\n\t\tupdateresource.action = resource.action;\n\t\tupdateresource.comment = resource.comment;\n\t\treturn updateresource.update_resource(client);\n\t}", "private boolean checkTagAndParam(XDoc doc, String tagName, String paramName, String paramValue)\r\n {\r\n if (tagName == null) {\r\n return true;\r\n }\r\n if (!doc.hasTag(tagName)) {\r\n return false;\r\n }\r\n if (paramName == null) {\r\n return true;\r\n }\r\n if (!doc.getTag(tagName).getAttributeNames().contains(paramName)) {\r\n return false;\r\n }\r\n return (paramValue == null) || paramValue.equals(doc.getTagAttributeValue(tagName, paramName));\r\n }", "@Override\n public int read(char[] cbuf, int off, int len) throws IOException {\n int numChars = super.read(cbuf, off, len);\n replaceBadXmlCharactersBySpace(cbuf, off, len);\n return numChars;\n }" ]
Use this API to renumber nspbr6.
[ "public static base_response renumber(nitro_service client) throws Exception {\n\t\tnspbr6 renumberresource = new nspbr6();\n\t\treturn renumberresource.perform_operation(client,\"renumber\");\n\t}" ]
[ "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 static GVRTexture loadFutureCubemapTexture(\n GVRContext gvrContext, ResourceCache<GVRImage> textureCache,\n GVRAndroidResource resource, int priority,\n Map<String, Integer> faceIndexMap) {\n GVRTexture tex = new GVRTexture(gvrContext);\n GVRImage cached = textureCache.get(resource);\n if (cached != null)\n {\n Log.v(\"ASSET\", \"Future Texture: %s loaded from cache\", cached.getFileName());\n tex.setImage(cached);\n }\n else\n {\n AsyncCubemapTexture.get().loadTexture(gvrContext,\n CancelableCallbackWrapper.wrap(GVRCubemapImage.class, tex),\n resource, priority, faceIndexMap);\n\n }\n return tex;\n }", "public static int getPrecedence( int type, boolean throwIfInvalid ) {\n\n switch( type ) {\n\n case LEFT_PARENTHESIS:\n return 0;\n\n case EQUAL:\n case PLUS_EQUAL:\n case MINUS_EQUAL:\n case MULTIPLY_EQUAL:\n case DIVIDE_EQUAL:\n case INTDIV_EQUAL:\n case MOD_EQUAL:\n case POWER_EQUAL:\n case LOGICAL_OR_EQUAL:\n case LOGICAL_AND_EQUAL:\n case LEFT_SHIFT_EQUAL:\n case RIGHT_SHIFT_EQUAL:\n case RIGHT_SHIFT_UNSIGNED_EQUAL:\n case BITWISE_OR_EQUAL:\n case BITWISE_AND_EQUAL:\n case BITWISE_XOR_EQUAL:\n return 5;\n\n case QUESTION:\n return 10;\n\n case LOGICAL_OR:\n return 15;\n\n case LOGICAL_AND:\n return 20;\n\n case BITWISE_OR:\n case BITWISE_AND:\n case BITWISE_XOR:\n return 22;\n\n case COMPARE_IDENTICAL:\n case COMPARE_NOT_IDENTICAL:\n return 24;\n\n case COMPARE_NOT_EQUAL:\n case COMPARE_EQUAL:\n case COMPARE_LESS_THAN:\n case COMPARE_LESS_THAN_EQUAL:\n case COMPARE_GREATER_THAN:\n case COMPARE_GREATER_THAN_EQUAL:\n case COMPARE_TO:\n case FIND_REGEX:\n case MATCH_REGEX:\n case KEYWORD_INSTANCEOF:\n return 25;\n\n case DOT_DOT:\n case DOT_DOT_DOT:\n return 30;\n\n case LEFT_SHIFT:\n case RIGHT_SHIFT:\n case RIGHT_SHIFT_UNSIGNED:\n return 35;\n\n case PLUS:\n case MINUS:\n return 40;\n\n case MULTIPLY:\n case DIVIDE:\n case INTDIV:\n case MOD:\n return 45;\n\n case NOT:\n case REGEX_PATTERN:\n return 50;\n\n case SYNTH_CAST:\n return 55;\n\n case PLUS_PLUS:\n case MINUS_MINUS:\n case PREFIX_PLUS_PLUS:\n case PREFIX_MINUS_MINUS:\n case POSTFIX_PLUS_PLUS:\n case POSTFIX_MINUS_MINUS:\n return 65;\n\n case PREFIX_PLUS:\n case PREFIX_MINUS:\n return 70;\n\n case POWER:\n return 72;\n\n case SYNTH_METHOD:\n case LEFT_SQUARE_BRACKET:\n return 75;\n\n case DOT:\n case NAVIGATE:\n return 80;\n\n case KEYWORD_NEW:\n return 85;\n }\n\n if( throwIfInvalid ) {\n throw new GroovyBugError( \"precedence requested for non-operator\" );\n }\n\n return -1;\n }", "public static boolean pullImage(Launcher launcher, final String imageTag, final String username, final String password, final String host)\n throws IOException, InterruptedException {\n\n return launcher.getChannel().call(new MasterToSlaveCallable<Boolean, IOException>() {\n public Boolean call() throws IOException {\n DockerUtils.pullImage(imageTag, username, password, host);\n return true;\n }\n });\n }", "public IGoal[] getAgentGoals(final String agent_name, Connector connector) {\n ((IExternalAccess) connector.getAgentsExternalAccess(agent_name))\n .scheduleStep(new IComponentStep<Plan>() {\n\n public IFuture<Plan> execute(IInternalAccess ia) {\n IBDIInternalAccess bia = (IBDIInternalAccess) ia;\n\n goals = bia.getGoalbase().getGoals();\n return null;\n }\n }).get(new ThreadSuspendable());\n\n return goals;\n }", "public boolean getNumericBoolean(int field)\n {\n boolean result = false;\n\n if ((field < m_fields.length) && (m_fields[field].length() != 0))\n {\n result = Integer.parseInt(m_fields[field]) == 1;\n }\n\n return (result);\n }", "@Override\n public <T> Producer<T> createProducer(final Bean<X> declaringBean, final Bean<T> bean, DisposalMethod<X, T> disposalMethod) {\n EnhancedAnnotatedField<T, X> enhancedField = getManager().getServices().get(MemberTransformer.class).loadEnhancedMember(field, getManager().getId());\n return new ProducerFieldProducer<X, T>(enhancedField, disposalMethod) {\n\n @Override\n public AnnotatedField<X> getAnnotated() {\n return field;\n }\n\n @Override\n public BeanManagerImpl getBeanManager() {\n return getManager();\n }\n\n @Override\n public Bean<X> getDeclaringBean() {\n return declaringBean;\n }\n\n @Override\n public Bean<T> getBean() {\n return bean;\n }\n };\n }", "protected boolean setFieldIfNecessary(String field, Object value) {\n\t\tif (!isOpen())\n\t\t\tthrow new ClosedObjectException(\"The Document object is closed.\");\n\n\t\tif (!compareFieldValue(field, value)) {\n\t\t\t_doc.setField(field, value);\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}", "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 }" ]
Processes a procedure tag. @param template The template @param attributes The attributes of the tag @exception XDocletException If an error occurs @doc.tag type="content" @doc.param name="arguments" optional="true" description="The arguments of the procedure as a comma-separated list of names of procedure attribute tags" @doc.param name="attributes" optional="true" description="Attributes of the procedure as name-value pairs 'name=value', separated by commas" @doc.param name="documentation" optional="true" description="Documentation on the procedure" @doc.param name="include-all-fields" optional="true" description="For insert/update: whether all fields of the current class shall be included (arguments is ignored then)" values="true,false" @doc.param name="include-pk-only" optional="true" description="For delete: whether all primary key fields shall be included (arguments is ignored then)" values="true,false" @doc.param name="name" optional="false" description="The name of the procedure" @doc.param name="return-field-ref" optional="true" description="Identifies the field that receives the return value" @doc.param name="type" optional="false" description="The type of the procedure" values="delete,insert,update"
[ "public String processProcedure(Properties attributes) throws XDocletException\r\n {\r\n String type = attributes.getProperty(ATTRIBUTE_TYPE);\r\n ProcedureDef procDef = _curClassDef.getProcedure(type);\r\n String attrName;\r\n\r\n if (procDef == null)\r\n { \r\n procDef = new ProcedureDef(type);\r\n _curClassDef.addProcedure(procDef);\r\n }\r\n\r\n for (Enumeration attrNames = attributes.propertyNames(); attrNames.hasMoreElements(); )\r\n {\r\n attrName = (String)attrNames.nextElement();\r\n procDef.setProperty(attrName, attributes.getProperty(attrName));\r\n }\r\n return \"\";\r\n }" ]
[ "public void addRow(Component component) {\n\n Component actualComponent = component == null ? m_newComponentFactory.get() : component;\n I_CmsEditableGroupRow row = m_rowBuilder.buildRow(this, actualComponent);\n m_container.addComponent(row);\n updatePlaceholder();\n updateButtonBars();\n updateGroupValidation();\n }", "public static int forceCleanup(Thread t)\n {\n int i = 0;\n for (Map.Entry<ConnectionPool, Set<ConnPair>> e : conns.entrySet())\n {\n for (ConnPair c : e.getValue())\n {\n if (c.thread.equals(t))\n {\n try\n {\n // This will in turn remove it from the static Map.\n c.conn.getHandler().invoke(c.conn, Connection.class.getMethod(\"close\"), null);\n }\n catch (Throwable e1)\n {\n e1.printStackTrace();\n }\n i++;\n }\n }\n }\n return i;\n }", "public static int findSpace(String haystack, int begin) {\r\n int space = haystack.indexOf(' ', begin);\r\n int nbsp = haystack.indexOf('\\u00A0', begin);\r\n if (space == -1 && nbsp == -1) {\r\n return -1;\r\n } else if (space >= 0 && nbsp >= 0) {\r\n return Math.min(space, nbsp);\r\n } else {\r\n // eg one is -1, and the other is >= 0\r\n return Math.max(space, nbsp);\r\n }\r\n }", "private void cascadeDeleteFor(ObjectEnvelope mod, List alreadyPrepared)\r\n {\r\n // avoid endless recursion\r\n if(alreadyPrepared.contains(mod.getIdentity())) return;\r\n\r\n alreadyPrepared.add(mod.getIdentity());\r\n\r\n ClassDescriptor cld = getTransaction().getBroker().getClassDescriptor(mod.getObject().getClass());\r\n\r\n List refs = cld.getObjectReferenceDescriptors(true);\r\n cascadeDeleteSingleReferences(mod, refs, alreadyPrepared);\r\n\r\n List colls = cld.getCollectionDescriptors(true);\r\n cascadeDeleteCollectionReferences(mod, colls, alreadyPrepared);\r\n }", "public int getLinkId(@NotNull final PersistentStoreTransaction txn, @NotNull final String linkName, final boolean allowCreate) {\n return allowCreate ? linkIds.getOrAllocateId(txn, linkName) : linkIds.getId(txn, linkName);\n }", "public synchronized Response<ByteArray, Object> responseQueuePoll(long timeout,\n TimeUnit timeUnit)\n throws InterruptedException {\n long timeoutMs = timeUnit.toMillis(timeout);\n long timeoutWallClockMs = System.currentTimeMillis() + timeoutMs;\n while(responseQueue.isEmpty() && System.currentTimeMillis() < timeoutWallClockMs) {\n long remainingMs = Math.max(0, timeoutWallClockMs - System.currentTimeMillis());\n if(logger.isDebugEnabled()) {\n logger.debug(\"Start waiting for response queue with timeoutMs: \" + timeoutMs);\n }\n this.wait(remainingMs);\n if(logger.isDebugEnabled()) {\n logger.debug(\"End waiting for response queue with timeoutMs: \" + timeoutMs);\n }\n }\n return responseQueue.poll();\n }", "public int checkIn() {\n\n try {\n synchronized (STATIC_LOCK) {\n m_logStream = new PrintStream(new FileOutputStream(DEFAULT_LOGFILE_PATH, false));\n CmsObject cms = getCmsObject();\n if (cms != null) {\n return checkInInternal();\n } else {\n m_logStream.println(\"No CmsObject given. Did you call init() first?\");\n return -1;\n }\n }\n } catch (FileNotFoundException e) {\n e.printStackTrace();\n return -2;\n }\n }", "public Collection<BoxFileVersion> getVersions() {\n URL url = VERSIONS_URL_TEMPLATE.build(this.getAPI().getBaseURL(), this.getID());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n\n JsonObject jsonObject = JsonObject.readFrom(response.getJSON());\n JsonArray entries = jsonObject.get(\"entries\").asArray();\n Collection<BoxFileVersion> versions = new ArrayList<BoxFileVersion>();\n for (JsonValue entry : entries) {\n versions.add(new BoxFileVersion(this.getAPI(), entry.asObject(), this.getID()));\n }\n\n return versions;\n }", "public CSTNode get( int index ) \n {\n CSTNode element = null;\n\n if( index < size() ) \n {\n element = (CSTNode)elements.get( index );\n }\n\n return element;\n }" ]
Returns a unique file name @param baseFileName the requested base name for the file @param extension the requested extension for the file @param cleanBaseFileName specify if the <code>baseFileName</code> has to be cleaned before being used (i.e. 'jboss-web' should not be cleaned to avoid '-' to become '_') @param ancestorFolders specify the ancestor folders for the file (if there's no ancestor folder, just pass 'null' value) @return a String representing the unique file generated
[ "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 }" ]
[ "static Type parseType(String value, ResourceLoader resourceLoader) {\n value = value.trim();\n // Wildcards\n if (value.equals(WILDCARD)) {\n return WildcardTypeImpl.defaultInstance();\n }\n if (value.startsWith(WILDCARD_EXTENDS)) {\n Type upperBound = parseType(value.substring(WILDCARD_EXTENDS.length(), value.length()), resourceLoader);\n if (upperBound == null) {\n return null;\n }\n return WildcardTypeImpl.withUpperBound(upperBound);\n }\n if (value.startsWith(WILDCARD_SUPER)) {\n Type lowerBound = parseType(value.substring(WILDCARD_SUPER.length(), value.length()), resourceLoader);\n if (lowerBound == null) {\n return null;\n }\n return WildcardTypeImpl.withLowerBound(lowerBound);\n }\n // Array\n if (value.contains(ARRAY)) {\n Type componentType = parseType(value.substring(0, value.indexOf(ARRAY)), resourceLoader);\n if (componentType == null) {\n return null;\n }\n return new GenericArrayTypeImpl(componentType);\n }\n int chevLeft = value.indexOf(CHEVRONS_LEFT);\n String rawValue = chevLeft < 0 ? value : value.substring(0, chevLeft);\n Class<?> rawRequiredType = tryLoadClass(rawValue, resourceLoader);\n if (rawRequiredType == null) {\n return null;\n }\n if (rawRequiredType.getTypeParameters().length == 0) {\n return rawRequiredType;\n }\n // Parameterized type\n int chevRight = value.lastIndexOf(CHEVRONS_RIGHT);\n if (chevRight < 0) {\n return null;\n }\n List<String> parts = split(value.substring(chevLeft + 1, chevRight), ',', CHEVRONS_LEFT.charAt(0), CHEVRONS_RIGHT.charAt(0));\n Type[] typeParameters = new Type[parts.size()];\n for (int i = 0; i < typeParameters.length; i++) {\n Type typeParam = parseType(parts.get(i), resourceLoader);\n if (typeParam == null) {\n return null;\n }\n typeParameters[i] = typeParam;\n }\n return new ParameterizedTypeImpl(rawRequiredType, typeParameters);\n }", "private Component createMainComponent() throws IOException, CmsException {\n\n VerticalLayout mainComponent = new VerticalLayout();\n mainComponent.setSizeFull();\n mainComponent.addStyleName(\"o-message-bundle-editor\");\n m_table = createTable();\n Panel navigator = new Panel();\n navigator.setSizeFull();\n navigator.setContent(m_table);\n navigator.addActionHandler(new CmsMessageBundleEditorTypes.TableKeyboardHandler(m_table));\n navigator.addStyleName(\"v-panel-borderless\");\n\n mainComponent.addComponent(m_options.getOptionsComponent());\n mainComponent.addComponent(navigator);\n mainComponent.setExpandRatio(navigator, 1f);\n m_options.updateShownOptions(m_model.hasMasterMode(), m_model.canAddKeys());\n return mainComponent;\n }", "@Override\n\tpublic Trajectory subList(int fromIndex, int toIndex) {\n\t\tTrajectory t = new Trajectory(dimension);\n\t\t\n\t\tfor(int i = fromIndex; i < toIndex; i++){\n\t\t\tt.add(this.get(i));\n\t\t}\n\t\treturn t;\n\t}", "public void bindMappers()\n {\n JacksonXmlModule xmlModule = new JacksonXmlModule();\n\n xmlModule.setDefaultUseWrapper(false);\n\n XmlMapper xmlMapper = new XmlMapper(xmlModule);\n\n xmlMapper.enable(ToXmlGenerator.Feature.WRITE_XML_DECLARATION);\n\n this.bind(XmlMapper.class).toInstance(xmlMapper);\n\n ObjectMapper objectMapper = new ObjectMapper();\n\n objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);\n objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true);\n objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);\n objectMapper.configure(DeserializationFeature.EAGER_DESERIALIZER_FETCH, true);\n objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);\n objectMapper.configure(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS, true);\n objectMapper.registerModule(new AfterburnerModule());\n objectMapper.registerModule(new Jdk8Module());\n\n this.bind(ObjectMapper.class).toInstance(objectMapper);\n this.requestStaticInjection(Extractors.class);\n this.requestStaticInjection(ServerResponse.class);\n }", "private void deliverOnAirUpdate(Set<Integer> audibleChannels) {\n for (final OnAirListener listener : getOnAirListeners()) {\n try {\n listener.channelsOnAir(audibleChannels);\n } catch (Throwable t) {\n logger.warn(\"Problem delivering channels on-air update to listener\", t);\n }\n }\n }", "private boolean isInInnerCircle(float x, float y) {\n return GearWearableUtility.isInCircle(x, y, CENTER_X, CENTER_Y, INNER_RADIUS);\n }", "public void loadClassifier(File file, Properties props) throws ClassCastException, IOException,\r\n ClassNotFoundException {\r\n Timing.startDoing(\"Loading classifier from \" + file.getAbsolutePath());\r\n BufferedInputStream bis;\r\n if (file.getName().endsWith(\".gz\")) {\r\n bis = new BufferedInputStream(new GZIPInputStream(new FileInputStream(file)));\r\n } else {\r\n bis = new BufferedInputStream(new FileInputStream(file));\r\n }\r\n loadClassifier(bis, props);\r\n bis.close();\r\n Timing.endDoing();\r\n }", "public static String getFilename(String path) throws IllegalArgumentException {\n if (Pattern.matches(sPatternUrl, path))\n return getURLFilename(path);\n\n return new File(path).getName();\n }", "public static AppDescriptor of(String appName, String packageName) {\n String[] packages = packageName.split(S.COMMON_SEP);\n return of(appName, packageName, Version.ofPackage(packages[0]));\n }" ]
Start timing an operation with the given identifier.
[ "public void begin(String key)\n {\n if (key == null)\n {\n return;\n }\n TimingData data = executionInfo.get(key);\n if (data == null)\n {\n data = new TimingData(key);\n executionInfo.put(key, data);\n }\n data.begin();\n }" ]
[ "public static int cudnnPoolingBackward(\n cudnnHandle handle, \n cudnnPoolingDescriptor poolingDesc, \n Pointer alpha, \n cudnnTensorDescriptor yDesc, \n Pointer y, \n cudnnTensorDescriptor dyDesc, \n Pointer dy, \n cudnnTensorDescriptor xDesc, \n Pointer x, \n Pointer beta, \n cudnnTensorDescriptor dxDesc, \n Pointer dx)\n {\n return checkResult(cudnnPoolingBackwardNative(handle, poolingDesc, alpha, yDesc, y, dyDesc, dy, xDesc, x, beta, dxDesc, dx));\n }", "public Map<String, CmsJspCategoryAccessBean> getReadResourceCategories() {\n\n if (null == m_resourceCategories) {\n m_resourceCategories = CmsCollectionsGenericWrapper.createLazyMap(new Transformer() {\n\n public Object transform(Object resourceName) {\n\n try {\n CmsResource resource = m_cms.readResource(\n getRequestContext().removeSiteRoot((String)resourceName));\n return new CmsJspCategoryAccessBean(m_cms, resource);\n } catch (CmsException e) {\n LOG.warn(e.getLocalizedMessage(), e);\n return null;\n }\n }\n });\n }\n return m_resourceCategories;\n }", "public static void copy(String in, Writer out) throws IOException {\n\t\tAssert.notNull(in, \"No input String specified\");\n\t\tAssert.notNull(out, \"No Writer specified\");\n\t\ttry {\n\t\t\tout.write(in);\n\t\t}\n\t\tfinally {\n\t\t\ttry {\n\t\t\t\tout.close();\n\t\t\t}\n\t\t\tcatch (IOException ex) {\n\t\t\t}\n\t\t}\n\t}", "public static java.sql.Timestamp toTimestamp(Object value) throws ParseException {\n if (value == null) {\n return null;\n }\n if (value instanceof java.sql.Timestamp) {\n return (java.sql.Timestamp) value;\n }\n if (value instanceof String) {\n\n if (\"\".equals((String) value)) {\n return null;\n }\n return new java.sql.Timestamp(IN_TIMESTAMP_FORMAT.parse((String) value).getTime());\n }\n\n return new java.sql.Timestamp(IN_TIMESTAMP_FORMAT.parse(value.toString()).getTime());\n }", "public static <T> void filterListToMap(final Map<String, T> destinationMap, final String[] nameMapping,\n\t\tfinal List<? extends T> sourceList) {\n\t\tif( destinationMap == null ) {\n\t\t\tthrow new NullPointerException(\"destinationMap should not be null\");\n\t\t} else if( nameMapping == null ) {\n\t\t\tthrow new NullPointerException(\"nameMapping should not be null\");\n\t\t} else if( sourceList == null ) {\n\t\t\tthrow new NullPointerException(\"sourceList should not be null\");\n\t\t} else if( nameMapping.length != sourceList.size() ) {\n\t\t\tthrow new SuperCsvException(\n\t\t\t\tString\n\t\t\t\t\t.format(\n\t\t\t\t\t\t\"the nameMapping array and the sourceList should be the same size (nameMapping length = %d, sourceList size = %d)\",\n\t\t\t\t\t\tnameMapping.length, sourceList.size()));\n\t\t}\n\t\t\n\t\tdestinationMap.clear();\n\t\t\n\t\tfor( int i = 0; i < nameMapping.length; i++ ) {\n\t\t\tfinal String key = nameMapping[i];\n\t\t\t\n\t\t\tif( key == null ) {\n\t\t\t\tcontinue; // null's in the name mapping means skip column\n\t\t\t}\n\t\t\t\n\t\t\t// no duplicates allowed\n\t\t\tif( destinationMap.containsKey(key) ) {\n\t\t\t\tthrow new SuperCsvException(String.format(\"duplicate nameMapping '%s' at index %d\", key, i));\n\t\t\t}\n\t\t\t\n\t\t\tdestinationMap.put(key, sourceList.get(i));\n\t\t}\n\t}", "public Date getCompleteThrough()\n {\n Date value = (Date) getCachedValue(TaskField.COMPLETE_THROUGH);\n if (value == null)\n {\n int percentComplete = NumberHelper.getInt(getPercentageComplete());\n switch (percentComplete)\n {\n case 0:\n {\n break;\n }\n\n case 100:\n {\n value = getActualFinish();\n break;\n }\n\n default:\n {\n Date actualStart = getActualStart();\n Duration duration = getDuration();\n if (actualStart != null && duration != null)\n {\n double durationValue = (duration.getDuration() * percentComplete) / 100d;\n duration = Duration.getInstance(durationValue, duration.getUnits());\n ProjectCalendar calendar = getEffectiveCalendar();\n value = calendar.getDate(actualStart, duration, true);\n }\n break;\n }\n }\n\n set(TaskField.COMPLETE_THROUGH, value);\n }\n return value;\n }", "public JaCoCoReportReader readJacocoReport(IExecutionDataVisitor executionDataVisitor, ISessionInfoVisitor sessionInfoStore) {\n if (jacocoExecutionData == null) {\n return this;\n }\n\n JaCoCoExtensions.logger().info(\"Analysing {}\", jacocoExecutionData);\n try (InputStream inputStream = new BufferedInputStream(new FileInputStream(jacocoExecutionData))) {\n if (useCurrentBinaryFormat) {\n ExecutionDataReader reader = new ExecutionDataReader(inputStream);\n reader.setSessionInfoVisitor(sessionInfoStore);\n reader.setExecutionDataVisitor(executionDataVisitor);\n reader.read();\n } else {\n org.jacoco.previous.core.data.ExecutionDataReader reader = new org.jacoco.previous.core.data.ExecutionDataReader(inputStream);\n reader.setSessionInfoVisitor(sessionInfoStore);\n reader.setExecutionDataVisitor(executionDataVisitor);\n reader.read();\n }\n } catch (IOException e) {\n throw new IllegalArgumentException(String.format(\"Unable to read %s\", jacocoExecutionData.getAbsolutePath()), e);\n }\n return this;\n }", "public void handleChannelClosed(final Channel closed, final IOException e) {\n for(final ActiveOperationImpl<?, ?> activeOperation : activeRequests.values()) {\n if (activeOperation.getChannel() == closed) {\n // Only call cancel, to also interrupt still active threads\n activeOperation.getResultHandler().cancel();\n }\n }\n }", "@Override\n public void join(final long millis) throws InterruptedException {\n for (final Thread thread : this.threads) {\n thread.join(millis);\n }\n }" ]
Loads the rules from files in the class loader, often jar files. @return the list of loaded rules, not null @throws Exception if an error occurs
[ "private static Data loadLeapSeconds() {\n Data bestData = null;\n URL url = null;\n try {\n // this is the new location of the file, working on Java 8, Java 9 class path and Java 9 module path\n Enumeration<URL> en = Thread.currentThread().getContextClassLoader().getResources(\"META-INF/\" + LEAP_SECONDS_TXT);\n while (en.hasMoreElements()) {\n url = en.nextElement();\n Data candidate = loadLeapSeconds(url);\n if (bestData == null || candidate.getNewestDate() > bestData.getNewestDate()) {\n bestData = candidate;\n }\n }\n // this location does not work on Java 9 module path because the resource is encapsulated\n en = Thread.currentThread().getContextClassLoader().getResources(LEAP_SECONDS_TXT);\n while (en.hasMoreElements()) {\n url = en.nextElement();\n Data candidate = loadLeapSeconds(url);\n if (bestData == null || candidate.getNewestDate() > bestData.getNewestDate()) {\n bestData = candidate;\n }\n }\n // this location is the canonical one, and class-based loading works on Java 9 module path\n url = SystemUtcRules.class.getResource(\"/\" + LEAP_SECONDS_TXT);\n if (url != null) {\n Data candidate = loadLeapSeconds(url);\n if (bestData == null || candidate.getNewestDate() > bestData.getNewestDate()) {\n bestData = candidate;\n }\n }\n } catch (Exception ex) {\n throw new RuntimeException(\"Unable to load time-zone rule data: \" + url, ex);\n }\n if (bestData == null) {\n // no data on classpath, but we allow manual registration of leap seconds\n // setup basic known data - MJD 1972-01-01 is 41317L, where offset was 10\n bestData = new Data(new long[] {41317L}, new int[] {10}, new long[] {tai(41317L, 10)});\n }\n return bestData;\n }" ]
[ "private FieldDescriptor[] getExtentFieldDescriptors(TableAlias extAlias, FieldDescriptor[] fds)\r\n {\r\n FieldDescriptor[] result = new FieldDescriptor[fds.length];\r\n\r\n for (int i = 0; i < fds.length; i++)\r\n {\r\n result[i] = extAlias.cld.getFieldDescriptorByName(fds[i].getAttributeName());\r\n }\r\n\r\n return result;\r\n }", "public int getMinutesPerWeek()\n {\n return m_minutesPerWeek == null ? NumberHelper.getInt(getParentFile().getProjectProperties().getMinutesPerWeek()) : m_minutesPerWeek.intValue();\n }", "public static base_response add(nitro_service client, cachepolicylabel resource) throws Exception {\n\t\tcachepolicylabel addresource = new cachepolicylabel();\n\t\taddresource.labelname = resource.labelname;\n\t\taddresource.evaluates = resource.evaluates;\n\t\treturn addresource.add_resource(client);\n\t}", "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 }", "protected void sendMessage(DataOutputStream outputStream, Message message) throws IOException {\n long startNs = System.nanoTime();\n ProtoUtils.writeMessage(outputStream, message);\n if(streamStats != null) {\n streamStats.reportNetworkTime(operation,\n Utils.elapsedTimeNs(startNs, System.nanoTime()));\n }\n }", "public static Range toRange(Span span) {\n return new Range(toKey(span.getStart()), span.isStartInclusive(), toKey(span.getEnd()),\n span.isEndInclusive());\n }", "public T find(AbstractProject<?, ?> project, Class<T> type) {\n // First check that the Flexible Publish plugin is installed:\n if (Jenkins.getInstance().getPlugin(FLEXIBLE_PUBLISH_PLUGIN) != null) {\n // Iterate all the project's publishers and find the flexible publisher:\n for (Publisher publisher : project.getPublishersList()) {\n // Found the flexible publisher:\n if (publisher instanceof FlexiblePublisher) {\n // See if it wraps a publisher of the specified type and if it does, return it:\n T pub = getWrappedPublisher(publisher, type);\n if (pub != null) {\n return pub;\n }\n }\n }\n }\n\n return null;\n }", "public CRFDatum<List<String>, CRFLabel> makeDatum(List<IN> info, int loc,\r\n edu.stanford.nlp.sequences.FeatureFactory<IN> featureFactory) {\r\n pad.set(AnswerAnnotation.class, flags.backgroundSymbol);\r\n PaddedList<IN> pInfo = new PaddedList<IN>(info, pad);\r\n\r\n ArrayList<List<String>> features = new ArrayList<List<String>>();\r\n\r\n // for (int i = 0; i < windowSize; i++) {\r\n // List featuresC = new ArrayList();\r\n // for (int j = 0; j < FeatureFactory.win[i].length; j++) {\r\n // featuresC.addAll(featureFactory.features(info, loc,\r\n // FeatureFactory.win[i][j]));\r\n // }\r\n // features.add(featuresC);\r\n // }\r\n\r\n Collection<Clique> done = new HashSet<Clique>();\r\n for (int i = 0; i < windowSize; i++) {\r\n List<String> featuresC = new ArrayList<String>();\r\n List<Clique> windowCliques = FeatureFactory.getCliques(i, 0);\r\n windowCliques.removeAll(done);\r\n done.addAll(windowCliques);\r\n for (Clique c : windowCliques) {\r\n featuresC.addAll(featureFactory.getCliqueFeatures(pInfo, loc, c)); //todo useless copy because of typing reasons\r\n }\r\n features.add(featuresC);\r\n }\r\n\r\n int[] labels = new int[windowSize];\r\n\r\n for (int i = 0; i < windowSize; i++) {\r\n String answer = pInfo.get(loc + i - windowSize + 1).get(AnswerAnnotation.class);\r\n labels[i] = classIndex.indexOf(answer);\r\n }\r\n\r\n printFeatureLists(pInfo.get(loc), features);\r\n\r\n CRFDatum<List<String>, CRFLabel> d = new CRFDatum<List<String>, CRFLabel>(features, new CRFLabel(labels));\r\n // System.err.println(d);\r\n return d;\r\n }", "public void awaitPodReadinessOrFail(Predicate<Pod> filter) {\n await().atMost(5, TimeUnit.MINUTES).until(() -> {\n List<Pod> list = client.pods().inNamespace(namespace).list().getItems();\n return list.stream()\n .filter(filter)\n .filter(Readiness::isPodReady)\n .collect(Collectors.toList()).size() >= 1;\n }\n );\n }" ]
FOR internal use. This method was called before the external transaction was completed. This method was called by the JTA-TxManager before the JTA-tx prepare call. Within this method we prepare odmg for commit and pass all modified persistent objects to DB and release/close the used connection. We have to close the connection in this method, because the TxManager does prepare for commit after this method and all used DataSource-connections have to be closed before. @see javax.transaction.Synchronization
[ "public void beforeCompletion()\r\n {\r\n // avoid redundant calls\r\n if(beforeCompletionCall) return;\r\n\r\n log.info(\"Method beforeCompletion was called\");\r\n int status = Status.STATUS_UNKNOWN;\r\n try\r\n {\r\n JTATxManager mgr = (JTATxManager) getImplementation().getTxManager();\r\n status = mgr.getJTATransaction().getStatus();\r\n // ensure proper work, check all possible status\r\n // normally only check for 'STATUS_MARKED_ROLLBACK' is necessary\r\n if(status == Status.STATUS_MARKED_ROLLBACK\r\n || status == Status.STATUS_ROLLEDBACK\r\n || status == Status.STATUS_ROLLING_BACK\r\n || status == Status.STATUS_UNKNOWN\r\n || status == Status.STATUS_NO_TRANSACTION)\r\n {\r\n log.error(\"Synchronization#beforeCompletion: Can't prepare for commit, because tx status was \"\r\n + TxUtil.getStatusString(status) + \". Do internal cleanup only.\");\r\n }\r\n else\r\n {\r\n if(log.isDebugEnabled())\r\n {\r\n log.debug(\"Synchronization#beforeCompletion: Prepare for commit\");\r\n }\r\n // write objects to database\r\n prepareCommit();\r\n }\r\n }\r\n catch(Exception e)\r\n {\r\n log.error(\"Synchronization#beforeCompletion: Error while prepare for commit\", e);\r\n if(e instanceof LockNotGrantedException)\r\n {\r\n throw (LockNotGrantedException) e;\r\n }\r\n else if(e instanceof TransactionAbortedException)\r\n {\r\n throw (TransactionAbortedException) e;\r\n }\r\n else if(e instanceof ODMGRuntimeException)\r\n {\r\n throw (ODMGRuntimeException) e;\r\n }\r\n else\r\n { \r\n throw new ODMGRuntimeException(\"Method beforeCompletion() fails, status of JTA-tx was \"\r\n + TxUtil.getStatusString(status) + \", message: \" + e.getMessage());\r\n }\r\n\r\n }\r\n finally\r\n {\r\n beforeCompletionCall = true;\r\n setInExternTransaction(false);\r\n internalCleanup();\r\n }\r\n }" ]
[ "private List<File> getConfigFiles() {\n\n String[] filenames = {\n \"opencms-modules.xml\",\n \"opencms-system.xml\",\n \"opencms-vfs.xml\",\n \"opencms-importexport.xml\",\n \"opencms-sites.xml\",\n \"opencms-variables.xml\",\n \"opencms-scheduler.xml\",\n \"opencms-workplace.xml\",\n \"opencms-search.xml\"};\n List<File> result = new ArrayList<>();\n for (String fn : filenames) {\n File file = new File(m_configDir, fn);\n if (file.exists()) {\n result.add(file);\n }\n }\n return result;\n }", "public void addColumn(ColumnDef columnDef)\r\n {\r\n columnDef.setOwner(this);\r\n _columns.put(columnDef.getName(), columnDef);\r\n }", "protected void addLineContent(BufferedReader bufferedFileReader, List<String> content, String line) throws IOException {\n content.add(line);\n }", "public void setEndType(final String value) {\r\n\r\n final EndType endType = EndType.valueOf(value);\r\n if (!endType.equals(m_model.getEndType())) {\r\n removeExceptionsOnChange(new Command() {\r\n\r\n public void execute() {\r\n\r\n switch (endType) {\r\n case SINGLE:\r\n m_model.setOccurrences(0);\r\n m_model.setSeriesEndDate(null);\r\n break;\r\n case TIMES:\r\n m_model.setOccurrences(10);\r\n m_model.setSeriesEndDate(null);\r\n break;\r\n case DATE:\r\n m_model.setOccurrences(0);\r\n m_model.setSeriesEndDate(m_model.getStart() == null ? new Date() : m_model.getStart());\r\n break;\r\n default:\r\n break;\r\n }\r\n m_model.setEndType(endType);\r\n valueChanged();\r\n }\r\n });\r\n }\r\n\r\n }", "private void setUserFieldValue(UDFAssignmentType udf, DataType dataType, Object value)\n {\n switch (dataType)\n {\n case DURATION:\n {\n udf.setTextValue(((Duration) value).toString());\n break;\n }\n\n case CURRENCY:\n {\n if (!(value instanceof Double))\n {\n value = Double.valueOf(((Number) value).doubleValue());\n }\n udf.setCostValue((Double) value);\n break;\n }\n\n case BINARY:\n {\n udf.setTextValue(\"\");\n break;\n }\n\n case STRING:\n {\n udf.setTextValue((String) value);\n break;\n }\n\n case DATE:\n {\n udf.setStartDateValue((Date) value);\n break;\n }\n\n case NUMERIC:\n {\n if (!(value instanceof Double))\n {\n value = Double.valueOf(((Number) value).doubleValue());\n }\n udf.setDoubleValue((Double) value);\n break;\n }\n\n case BOOLEAN:\n {\n udf.setIntegerValue(BooleanHelper.getBoolean((Boolean) value) ? Integer.valueOf(1) : Integer.valueOf(0));\n break;\n }\n\n case INTEGER:\n case SHORT:\n {\n udf.setIntegerValue(NumberHelper.getInteger((Number) value));\n break;\n }\n\n default:\n {\n throw new RuntimeException(\"Unconvertible data type: \" + dataType);\n }\n }\n }", "public static void installDomainConnectorServices(final OperationContext context,\n final ServiceTarget serviceTarget,\n final ServiceName endpointName,\n final ServiceName networkInterfaceBinding,\n final int port,\n final OptionMap options,\n final ServiceName securityRealm,\n final ServiceName saslAuthenticationFactory,\n final ServiceName sslContext) {\n String sbmCap = \"org.wildfly.management.socket-binding-manager\";\n ServiceName sbmName = context.hasOptionalCapability(sbmCap, NATIVE_MANAGEMENT_RUNTIME_CAPABILITY.getName(), null)\n ? context.getCapabilityServiceName(sbmCap, SocketBindingManager.class) : null;\n installConnectorServicesForNetworkInterfaceBinding(serviceTarget, endpointName, MANAGEMENT_CONNECTOR,\n networkInterfaceBinding, port, options, securityRealm, saslAuthenticationFactory, sslContext, sbmName);\n }", "public synchronized int getPartitionStoreCount() {\n int count = 0;\n for (String store : storeToPartitionIds.keySet()) {\n count += storeToPartitionIds.get(store).size();\n }\n return count;\n }", "@Override\n public boolean minimize(DifferentiableBatchFunction function, IntDoubleVector point) {\n return minimize(function, point, null);\n }", "public void poseFromBones()\n {\n for (int i = 0; i < getNumBones(); ++i)\n {\n GVRSceneObject bone = mBones[i];\n if (bone == null)\n {\n continue;\n }\n if ((mBoneOptions[i] & BONE_LOCK_ROTATION) != 0)\n {\n continue;\n }\n GVRTransform trans = bone.getTransform();\n mPose.setLocalMatrix(i, trans.getLocalModelMatrix4f());\n }\n mPose.sync();\n updateBonePose();\n }" ]
The CommandContext can be retrieved thatnks to the ExecutableBuilder.
[ "void execute(ExecutableBuilder builder,\n int timeout,\n TimeUnit unit) throws\n CommandLineException,\n InterruptedException, ExecutionException, TimeoutException {\n Future<Void> task = executorService.submit(() -> {\n builder.build().execute();\n return null;\n });\n try {\n if (timeout <= 0) { //Synchronous\n task.get();\n } else { // Guarded execution\n try {\n task.get(timeout, unit);\n } catch (TimeoutException ex) {\n // First make the context unusable\n CommandContext c = builder.getCommandContext();\n if (c instanceof TimeoutCommandContext) {\n ((TimeoutCommandContext) c).timeout();\n }\n // Then cancel the task.\n task.cancel(true);\n throw ex;\n }\n }\n } catch (InterruptedException ex) {\n // Could have been interrupted by user (Ctrl-C)\n Thread.currentThread().interrupt();\n cancelTask(task, builder.getCommandContext(), null);\n // Interrupt running operation.\n CommandContext c = builder.getCommandContext();\n if (c instanceof TimeoutCommandContext) {\n ((TimeoutCommandContext) c).interrupted();\n }\n throw ex;\n }\n }" ]
[ "public static tunneltrafficpolicy[] get(nitro_service service, options option) throws Exception{\n\t\ttunneltrafficpolicy obj = new tunneltrafficpolicy();\n\t\ttunneltrafficpolicy[] response = (tunneltrafficpolicy[])obj.get_resources(service,option);\n\t\treturn response;\n\t}", "public void fillTile(InternalTile tile, Envelope maxTileExtent)\n\t\t\tthrows GeomajasException {\n\t\tList<InternalFeature> origFeatures = tile.getFeatures();\n\t\ttile.setFeatures(new ArrayList<InternalFeature>());\n\t\tfor (InternalFeature feature : origFeatures) {\n\t\t\tif (!addTileCode(tile, maxTileExtent, feature.getGeometry())) {\n\t\t\t\tlog.debug(\"add feature\");\n\t\t\t\ttile.addFeature(feature);\n\t\t\t}\n\t\t}\n\t}", "@Inject(optional = true)\n protected Pattern setEndTag(@Named(AbstractMultiLineCommentProvider.END_TAG) final String endTag) {\n return this.endTagPattern = Pattern.compile((endTag + \"\\\\z\"));\n }", "public static clusternodegroup_nslimitidentifier_binding[] get(nitro_service service, String name) throws Exception{\n\t\tclusternodegroup_nslimitidentifier_binding obj = new clusternodegroup_nslimitidentifier_binding();\n\t\tobj.set_name(name);\n\t\tclusternodegroup_nslimitidentifier_binding response[] = (clusternodegroup_nslimitidentifier_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}", "public void updateActive(int profileId, String clientUUID, Boolean active) throws Exception {\n PreparedStatement statement = null;\n try (Connection sqlConnection = sqlService.getConnection()) {\n statement = sqlConnection.prepareStatement(\n \"UPDATE \" + Constants.DB_TABLE_CLIENT +\n \" SET \" + Constants.CLIENT_IS_ACTIVE + \"= ?\" +\n \" WHERE \" + Constants.GENERIC_CLIENT_UUID + \"= ? \" +\n \" AND \" + Constants.GENERIC_PROFILE_ID + \"= ?\"\n );\n statement.setBoolean(1, active);\n statement.setString(2, clientUUID);\n statement.setInt(3, profileId);\n statement.executeUpdate();\n } catch (Exception e) {\n // ok to swallow this.. just means there wasn't any\n } finally {\n try {\n if (statement != null) {\n statement.close();\n }\n } catch (Exception e) {\n }\n }\n }", "private static Version getDockerVersion(String serverUrl) {\n try {\n DockerClient client = DockerClientBuilder.getInstance(serverUrl).build();\n return client.versionCmd().exec();\n } catch (Exception e) {\n return null;\n }\n }", "public void cleanup() {\n synchronized (_sslMap) {\n for (SslRelayOdo relay : _sslMap.values()) {\n if (relay.getHttpServer() != null && relay.isStarted()) {\n relay.getHttpServer().removeListener(relay);\n }\n }\n\n sslRelays.clear();\n }\n }", "private static boolean isWideningPrimitive(Class<?> argumentClass, Class<?> targetClass) {\n return WIDENING_TABLE.containsKey(argumentClass) && WIDENING_TABLE.get(argumentClass).contains(targetClass);\n }", "public static dnszone_domain_binding[] get(nitro_service service, String zonename) throws Exception{\n\t\tdnszone_domain_binding obj = new dnszone_domain_binding();\n\t\tobj.set_zonename(zonename);\n\t\tdnszone_domain_binding response[] = (dnszone_domain_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
This method will add a DemoInterceptor into every in and every out phase of the interceptor chains. @param provider
[ "public static void addInterceptors(InterceptorProvider provider) {\n PhaseManager phases = BusFactory.getDefaultBus().getExtension(PhaseManager.class);\n for (Phase p : phases.getInPhases()) {\n provider.getInInterceptors().add(new DemoInterceptor(p.getName()));\n provider.getInFaultInterceptors().add(new DemoInterceptor(p.getName()));\n }\n for (Phase p : phases.getOutPhases()) {\n provider.getOutInterceptors().add(new DemoInterceptor(p.getName()));\n provider.getOutFaultInterceptors().add(new DemoInterceptor(p.getName()));\n }\n }" ]
[ "@SuppressWarnings(\"StringEquality\")\n public static MatchInfo fromAuthScope(final AuthScope authscope) {\n String newScheme = StringUtils.equals(authscope.getScheme(), AuthScope.ANY_SCHEME) ? ANY_SCHEME :\n authscope.getScheme();\n String newHost = StringUtils.equals(authscope.getHost(), AuthScope.ANY_HOST) ? ANY_HOST :\n authscope.getHost();\n int newPort = authscope.getPort() == AuthScope.ANY_PORT ? ANY_PORT : authscope.getPort();\n String newRealm = StringUtils.equals(authscope.getRealm(), AuthScope.ANY_REALM) ? ANY_REALM :\n authscope.getRealm();\n\n return new MatchInfo(newScheme, newHost, newPort, ANY_PATH, ANY_QUERY,\n ANY_FRAGMENT, newRealm, ANY_METHOD);\n }", "private void handleApplicationCommandRequest(SerialMessage incomingMessage) {\n\t\tlogger.trace(\"Handle Message Application Command Request\");\n\t\tint nodeId = incomingMessage.getMessagePayloadByte(1);\n\t\tlogger.debug(\"Application Command Request from Node \" + nodeId);\n\t\tZWaveNode node = getNode(nodeId);\n\t\t\n\t\tif (node == null) {\n\t\t\tlogger.warn(\"Node {} not initialized yet, ignoring message.\", nodeId);\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tnode.resetResendCount();\n\t\t\n\t\tint commandClassCode = incomingMessage.getMessagePayloadByte(3);\n\t\tZWaveCommandClass.CommandClass commandClass = ZWaveCommandClass.CommandClass.getCommandClass(commandClassCode);\n\n\t\tif (commandClass == null) {\n\t\t\tlogger.error(String.format(\"Unsupported command class 0x%02x\", commandClassCode));\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tlogger.debug(String.format(\"Incoming command class %s (0x%02x)\", commandClass.getLabel(), commandClass.getKey()));\n\t\tZWaveCommandClass zwaveCommandClass = node.getCommandClass(commandClass);\n\t\t\n\t\t// We got an unsupported command class, return.\n\t\tif (zwaveCommandClass == null) {\n\t\t\tlogger.error(String.format(\"Unsupported command class %s (0x%02x)\", commandClass.getLabel(), commandClassCode));\n\t\t\treturn;\n\t\t}\n\t\t\n\t\tlogger.trace(\"Found Command Class {}, passing to handleApplicationCommandRequest\", zwaveCommandClass.getCommandClass().getLabel());\n\t\tzwaveCommandClass.handleApplicationCommandRequest(incomingMessage, 4, 1);\n\n\t\tif (incomingMessage.getMessageClass() == this.lastSentMessage.getExpectedReply() && nodeId == this.lastSentMessage.getMessageNode() && !incomingMessage.isTransActionCanceled()) {\n\t\t\t\tnotifyEventListeners(new ZWaveEvent(ZWaveEventType.TRANSACTION_COMPLETED_EVENT, this.lastSentMessage.getMessageNode(), 1, this.lastSentMessage));\n\t\t\t\ttransactionCompleted.release();\n\t\t\t\tlogger.trace(\"Released. Transaction completed permit count -> {}\", transactionCompleted.availablePermits());\n\t\t}\n\t}", "public AccessAssertion unmarshal(final JSONObject encodedAssertion) {\n final String className;\n try {\n className = encodedAssertion.getString(JSON_CLASS_NAME);\n final Class<?> assertionClass =\n Thread.currentThread().getContextClassLoader().loadClass(className);\n final AccessAssertion assertion =\n (AccessAssertion) this.applicationContext.getBean(assertionClass);\n assertion.unmarshal(encodedAssertion);\n\n return assertion;\n } catch (JSONException | ClassNotFoundException e) {\n throw new RuntimeException(e);\n }\n }", "public static void writeDocumentToFile(Document document,\n String filePathname, String method, int indent)\n throws TransformerException, IOException {\n\n Transformer transformer = TransformerFactory.newInstance()\n .newTransformer();\n transformer.setOutputProperty(OutputKeys.INDENT, \"yes\");\n transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, \"no\");\n transformer.setOutputProperty(OutputKeys.METHOD, method);\n\n transformer.transform(new DOMSource(document), new StreamResult(\n new FileOutputStream(filePathname)));\n }", "private static char[] buildTable() {\n char[] table = new char[26];\n for (int ix = 0; ix < table.length; ix++)\n table[ix] = '0';\n table['B' - 'A'] = '1';\n table['P' - 'A'] = '1';\n table['F' - 'A'] = '1';\n table['V' - 'A'] = '1';\n table['C' - 'A'] = '2';\n table['S' - 'A'] = '2';\n table['K' - 'A'] = '2';\n table['G' - 'A'] = '2';\n table['J' - 'A'] = '2';\n table['Q' - 'A'] = '2';\n table['X' - 'A'] = '2';\n table['Z' - 'A'] = '2';\n table['D' - 'A'] = '3';\n table['T' - 'A'] = '3';\n table['L' - 'A'] = '4';\n table['M' - 'A'] = '5';\n table['N' - 'A'] = '5';\n table['R' - 'A'] = '6';\n return table;\n }", "public static boolean isTypesProxyable(Iterable<? extends Type> types, ServiceRegistry services) {\n return getUnproxyableTypesException(types, services) == null;\n }", "protected boolean isPrefixBlock(long divisionValue, long upperValue, int divisionPrefixLen) {\n\t\tif(divisionPrefixLen == 0) {\n\t\t\treturn divisionValue == 0 && upperValue == getMaxValue();\n\t\t}\n\t\tlong ones = ~0L;\n\t\tlong divisionBitMask = ~(ones << getBitCount());\n\t\tlong divisionPrefixMask = ones << (getBitCount() - divisionPrefixLen);\n\t\tlong divisionNonPrefixMask = ~divisionPrefixMask;\n\t\treturn testRange(divisionValue,\n\t\t\t\tupperValue,\n\t\t\t\tupperValue,\n\t\t\t\tdivisionPrefixMask & divisionBitMask,\n\t\t\t\tdivisionNonPrefixMask);\n\t}", "@Override\n public void registerAttributes(ManagementResourceRegistration resourceRegistration) {\n for (AttributeAccess attr : attributes.values()) {\n resourceRegistration.registerReadOnlyAttribute(attr.getAttributeDefinition(), null);\n }\n }", "public static void ensureXPathNotEmpty(NodeList nodeList, String expression) {\n if (nodeList == null || nodeList.getLength() == 0) {\n throw LOG.unableToFindXPathExpression(expression);\n }\n }" ]
Sets the currency code, or the regular expression to select codes. @param codes the currency codes or code expressions, not null. @return the query for chaining.
[ "public CurrencyQueryBuilder setCurrencyCodes(String... codes) {\n return set(CurrencyQuery.KEY_QUERY_CURRENCY_CODES, Arrays.asList(codes));\n }" ]
[ "public AssemblyResponse save(boolean isResumable)\n throws RequestException, LocalOperationException {\n Request request = new Request(getClient());\n options.put(\"steps\", steps.toMap());\n\n // only do tus uploads if files will be uploaded\n if (isResumable && getFilesCount() > 0) {\n Map<String, String> tusOptions = new HashMap<String, String>();\n tusOptions.put(\"tus_num_expected_upload_files\", Integer.toString(getFilesCount()));\n\n AssemblyResponse response = new AssemblyResponse(\n request.post(\"/assemblies\", options, tusOptions, null, null), true);\n\n // check if the assembly returned an error\n if (response.hasError()) {\n throw new RequestException(\"Request to Assembly failed: \" + response.json().getString(\"error\"));\n }\n\n try {\n handleTusUpload(response);\n } catch (IOException e) {\n throw new LocalOperationException(e);\n } catch (ProtocolException e) {\n throw new RequestException(e);\n }\n return response;\n } else {\n return new AssemblyResponse(request.post(\"/assemblies\", options, null, files, fileStreams));\n }\n }", "protected static void captureSystemStreams(boolean captureOut, boolean captureErr){\r\n if(captureOut){\r\n System.setOut(new RedwoodPrintStream(STDOUT, realSysOut));\r\n }\r\n if(captureErr){\r\n System.setErr(new RedwoodPrintStream(STDERR, realSysErr));\r\n }\r\n }", "public boolean detectBlackBerryHigh() {\r\n\r\n //Disambiguate for BlackBerry OS 6 or 7 (WebKit) browser\r\n if (detectBlackBerryWebKit()) {\r\n return false;\r\n }\r\n if (detectBlackBerry()) {\r\n if (detectBlackBerryTouch()\r\n || (userAgent.indexOf(deviceBBBold) != -1)\r\n || (userAgent.indexOf(deviceBBTour) != -1)\r\n || (userAgent.indexOf(deviceBBCurve) != -1)) {\r\n return true;\r\n } else {\r\n return false;\r\n }\r\n } else {\r\n return false;\r\n }\r\n }", "public static SimpleDeploymentDescription of(final String name, @SuppressWarnings(\"TypeMayBeWeakened\") final Set<String> serverGroups) {\n final SimpleDeploymentDescription result = of(name);\n if (serverGroups != null) {\n result.addServerGroups(serverGroups);\n }\n return result;\n }", "public BoxFileUploadSessionPart uploadPart(InputStream stream, long offset, int partSize,\n long totalSizeOfFile) {\n\n URL uploadPartURL = this.sessionInfo.getSessionEndpoints().getUploadPartEndpoint();\n\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), uploadPartURL, HttpMethod.PUT);\n request.addHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_OCTET_STREAM);\n\n //Read the partSize bytes from the stream\n byte[] bytes = new byte[partSize];\n try {\n stream.read(bytes);\n } catch (IOException ioe) {\n throw new BoxAPIException(\"Reading data from stream failed.\", ioe);\n }\n\n return this.uploadPart(bytes, offset, partSize, totalSizeOfFile);\n }", "public static final Bytes of(byte[] array) {\n Objects.requireNonNull(array);\n if (array.length == 0) {\n return EMPTY;\n }\n byte[] copy = new byte[array.length];\n System.arraycopy(array, 0, copy, 0, array.length);\n return new Bytes(copy);\n }", "public static double huntKennedyCMSFloorValue(\n\t\t\tdouble forwardSwaprate,\n\t\t\tdouble volatility,\n\t\t\tdouble swapAnnuity,\n\t\t\tdouble optionMaturity,\n\t\t\tdouble swapMaturity,\n\t\t\tdouble payoffUnit,\n\t\t\tdouble optionStrike)\n\t{\n\t\tdouble huntKennedyCMSOptionValue = huntKennedyCMSOptionValue(forwardSwaprate, volatility, swapAnnuity, optionMaturity, swapMaturity, payoffUnit, optionStrike);\n\n\t\t// A floor is an option plus the strike (max(X,K) = max(X-K,0) + K)\n\t\treturn huntKennedyCMSOptionValue + optionStrike * payoffUnit;\n\t}", "public FloatBuffer getFloatVec(String attributeName)\n {\n int size = getAttributeSize(attributeName);\n if (size <= 0)\n {\n return null;\n }\n size *= 4 * getVertexCount();\n ByteBuffer buffer = ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder());\n FloatBuffer data = buffer.asFloatBuffer();\n if (!NativeVertexBuffer.getFloatVec(getNative(), attributeName, data, 0, 0))\n {\n throw new IllegalArgumentException(\"Attribute name \" + attributeName + \" cannot be accessed\");\n }\n return data;\n }", "@SuppressWarnings({ \"rawtypes\", \"unchecked\" })\n public void blacklistNode(int nodeId) {\n Collection<Node> nodesInCluster = adminClient.getAdminClientCluster().getNodes();\n\n if(blackListedNodes == null) {\n blackListedNodes = new ArrayList();\n }\n blackListedNodes.add(nodeId);\n\n for(Node node: nodesInCluster) {\n\n if(node.getId() == nodeId) {\n nodesToStream.remove(node);\n break;\n }\n\n }\n\n for(String store: storeNames) {\n try {\n SocketAndStreams sands = nodeIdStoreToSocketAndStreams.get(new Pair(store, nodeId));\n close(sands.getSocket());\n SocketDestination destination = nodeIdStoreToSocketRequest.get(new Pair(store,\n nodeId));\n streamingSocketPool.checkin(destination, sands);\n } catch(Exception ioE) {\n logger.error(ioE);\n }\n }\n }" ]
Assign FK value of main object with PK values of the reference object. @param obj real object with reference (proxy) object (or real object with set FK values on insert) @param cld {@link ClassDescriptor} of the real object @param rds An {@link ObjectReferenceDescriptor} of real object. @param insert Show if "linking" is done while insert or update.
[ "public void linkOneToOne(Object obj, ClassDescriptor cld, ObjectReferenceDescriptor rds, boolean insert)\n {\n storeAndLinkOneToOne(true, obj, cld, rds, true);\n }" ]
[ "public PartialCollection<BoxItem.Info> searchRange(long offset, long limit, final BoxSearchParameters bsp) {\n QueryStringBuilder builder = bsp.getQueryParameters()\n .appendParam(\"limit\", limit)\n .appendParam(\"offset\", offset);\n URL url = SEARCH_URL_TEMPLATE.buildWithQuery(this.getAPI().getBaseURL(), builder.toString());\n BoxAPIRequest request = new BoxAPIRequest(this.getAPI(), url, \"GET\");\n BoxJSONResponse response = (BoxJSONResponse) request.send();\n JsonObject responseJSON = JsonObject.readFrom(response.getJSON());\n String totalCountString = responseJSON.get(\"total_count\").toString();\n long fullSize = Double.valueOf(totalCountString).longValue();\n PartialCollection<BoxItem.Info> results = new PartialCollection<BoxItem.Info>(offset, limit, fullSize);\n JsonArray jsonArray = responseJSON.get(\"entries\").asArray();\n for (JsonValue value : jsonArray) {\n JsonObject jsonObject = value.asObject();\n BoxItem.Info parsedItemInfo = (BoxItem.Info) BoxResource.parseInfo(this.getAPI(), jsonObject);\n if (parsedItemInfo != null) {\n results.add(parsedItemInfo);\n }\n }\n return results;\n }", "private MavenProjectModel getMavenStubProject(MavenProjectService mavenProjectService, String groupId, String artifactId, String version)\n {\n Iterable<MavenProjectModel> mavenProjectModels = mavenProjectService.findByGroupArtifactVersion(groupId, artifactId, version);\n if (!mavenProjectModels.iterator().hasNext())\n {\n return null;\n }\n for (MavenProjectModel mavenProjectModel : mavenProjectModels)\n {\n if (mavenProjectModel.getRootFileModel() == null)\n {\n // this is a stub... we can fill it in with details\n return mavenProjectModel;\n }\n }\n return null;\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}", "public static Object xmlToObject(String fileName) throws FileNotFoundException {\r\n\t\tFileInputStream fi = new FileInputStream(fileName);\r\n\t\tXMLDecoder decoder = new XMLDecoder(fi);\r\n\t\tObject object = decoder.readObject();\r\n\t\tdecoder.close();\r\n\t\treturn object;\r\n\t}", "public AT_Row setHtmlElementTranslator(HtmlElementTranslator htmlElementTranslator) {\r\n\t\tif(this.hasCells()){\r\n\t\t\tfor(AT_Cell cell : this.getCells()){\r\n\t\t\t\tcell.getContext().setHtmlElementTranslator(htmlElementTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public static List<ContentRepositoryElement> listFiles(final Path rootPath, Path tempDir, final ContentFilter filter) throws IOException {\n List<ContentRepositoryElement> result = new ArrayList<>();\n if (Files.exists(rootPath)) {\n if(isArchive(rootPath)) {\n return listZipContent(rootPath, filter);\n }\n Files.walkFileTree(rootPath, new FileVisitor<Path>() {\n @Override\n public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {\n if (filter.acceptFile(rootPath, file)) {\n result.add(ContentRepositoryElement.createFile(formatPath(rootPath.relativize(file)), Files.size(file)));\n }\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {\n return FileVisitResult.CONTINUE;\n }\n\n @Override\n public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {\n if (filter.acceptDirectory(rootPath, dir)) {\n String directoryPath = formatDirectoryPath(rootPath.relativize(dir));\n if(! \"/\".equals(directoryPath)) {\n result.add(ContentRepositoryElement.createFolder(directoryPath));\n }\n }\n return FileVisitResult.CONTINUE;\n }\n\n private String formatDirectoryPath(Path path) {\n return formatPath(path) + '/';\n }\n\n private String formatPath(Path path) {\n return path.toString().replace(File.separatorChar, '/');\n }\n });\n } else {\n Path file = getFile(rootPath);\n if(isArchive(file)) {\n Path relativePath = file.relativize(rootPath);\n Path target = createTempDirectory(tempDir, \"unarchive\");\n unzip(file, target);\n return listFiles(target.resolve(relativePath), tempDir, filter);\n } else {\n throw new FileNotFoundException(rootPath.toString());\n }\n }\n return result;\n }", "public static <V> V doWorkInPool(final Pool<Jedis> pool, final PoolWork<Jedis, V> work) throws Exception {\n if (pool == null) {\n throw new IllegalArgumentException(\"pool must not be null\");\n }\n if (work == null) {\n throw new IllegalArgumentException(\"work must not be null\");\n }\n final V result;\n final Jedis poolResource = pool.getResource();\n try {\n result = work.doWork(poolResource);\n } finally {\n poolResource.close();\n }\n return result;\n }", "private void serializeEPR(EndpointReferenceType wsAddr, Node parent) throws ServiceLocatorException {\n try {\n JAXBElement<EndpointReferenceType> ep =\n WSA_OBJECT_FACTORY.createEndpointReference(wsAddr);\n createMarshaller().marshal(ep, parent);\n } catch (JAXBException e) {\n if (LOG.isLoggable(Level.SEVERE)) {\n LOG.log(Level.SEVERE,\n \"Failed to serialize endpoint data\", e);\n }\n throw new ServiceLocatorException(\"Failed to serialize endpoint data\", e);\n }\n }", "public static void executeCommand(String[] args) throws IOException {\n\n OptionParser parser = getParser();\n String url = null;\n Boolean confirm = false;\n\n // parse command-line input\n OptionSet options = parser.parse(args);\n if(options.has(AdminParserUtils.OPT_HELP)) {\n printHelp(System.out);\n return;\n }\n\n AdminParserUtils.checkRequired(options, AdminParserUtils.OPT_URL);\n\n url = (String) options.valueOf(AdminParserUtils.OPT_URL);\n if(options.has(AdminParserUtils.OPT_CONFIRM)) {\n confirm = true;\n }\n\n // print summary\n System.out.println(\"Synchronize metadata versions across all nodes\");\n System.out.println(\"Location:\");\n System.out.println(\" bootstrap url = \" + url);\n System.out.println(\" node = all nodes\");\n\n AdminClient adminClient = AdminToolUtils.getAdminClient(url);\n\n AdminToolUtils.assertServerNotInRebalancingState(adminClient);\n\n Versioned<Properties> versionedProps = mergeAllVersions(adminClient);\n\n printVersions(versionedProps);\n\n // execute command\n if(!AdminToolUtils.askConfirm(confirm,\n \"do you want to synchronize metadata versions to all node\"))\n return;\n\n adminClient.metadataMgmtOps.setMetadataVersion(versionedProps);\n }" ]
Sets up internal data structures and creates a copy of the input matrix. @param A The input matrix. Not modified.
[ "protected void init(DMatrixRMaj A ) {\n UBV = A;\n\n m = UBV.numRows;\n n = UBV.numCols;\n\n min = Math.min(m,n);\n int max = Math.max(m,n);\n\n if( b.length < max+1 ) {\n b = new double[ max+1 ];\n u = new double[ max+1 ];\n }\n if( gammasU.length < m ) {\n gammasU = new double[ m ];\n }\n if( gammasV.length < n ) {\n gammasV = new double[ n ];\n }\n }" ]
[ "private static <T> void writeConfig(BufferedWriter writer, DatabaseTableConfig<T> config) throws IOException,\n\t\t\tSQLException {\n\t\twriter.append(CONFIG_FILE_START_MARKER);\n\t\twriter.newLine();\n\t\tif (config.getDataClass() != null) {\n\t\t\twriter.append(FIELD_NAME_DATA_CLASS).append('=').append(config.getDataClass().getName());\n\t\t\twriter.newLine();\n\t\t}\n\t\tif (config.getTableName() != null) {\n\t\t\twriter.append(FIELD_NAME_TABLE_NAME).append('=').append(config.getTableName());\n\t\t\twriter.newLine();\n\t\t}\n\t\twriter.append(CONFIG_FILE_FIELDS_START);\n\t\twriter.newLine();\n\t\tif (config.getFieldConfigs() != null) {\n\t\t\tfor (DatabaseFieldConfig field : config.getFieldConfigs()) {\n\t\t\t\tDatabaseFieldConfigLoader.write(writer, field, config.getTableName());\n\t\t\t}\n\t\t}\n\t\twriter.append(CONFIG_FILE_FIELDS_END);\n\t\twriter.newLine();\n\t\twriter.append(CONFIG_FILE_END_MARKER);\n\t\twriter.newLine();\n\t}", "public static int cudnnCTCLoss(\n cudnnHandle handle, \n cudnnTensorDescriptor probsDesc, /** Tensor descriptor for probabilities, the dimensions are T,N,A (T is the timing steps, N is the\n mini batch size, A is the alphabet size) */\n Pointer probs, /** probabilities after softmax, in GPU memory */\n int[] labels, /** labels, in CPU memory */\n int[] labelLengths, /** the length of each label, in CPU memory */\n int[] inputLengths, /** the lengths of timing steps in each batch, in CPU memory */\n Pointer costs, /** the returned costs of CTC, in GPU memory */\n cudnnTensorDescriptor gradientsDesc, /** Tensor descriptor for gradients, the dimensions are T,N,A */\n Pointer gradients, /** the returned CTC gradients, in GPU memory, to compute costs only, set it to NULL */\n int algo, /** algorithm selected, supported now 0 and 1 */\n cudnnCTCLossDescriptor ctcLossDesc, \n Pointer workspace, /** pointer to the workspace, in GPU memory */\n long workSpaceSizeInBytes)/** the workspace size needed */\n {\n return checkResult(cudnnCTCLossNative(handle, probsDesc, probs, labels, labelLengths, inputLengths, costs, gradientsDesc, gradients, algo, ctcLossDesc, workspace, workSpaceSizeInBytes));\n }", "@Override\n protected void initBuilderSpecific() throws Exception {\n reset();\n FilePath workspace = getModuleRoot(EnvVars.masterEnvVars);\n FilePath gradlePropertiesPath = new FilePath(workspace, \"gradle.properties\");\n if (releaseProps == null) {\n releaseProps = PropertyUtils.getModulesPropertiesFromPropFile(gradlePropertiesPath, getReleaseProperties());\n }\n if (nextIntegProps == null) {\n nextIntegProps =\n PropertyUtils.getModulesPropertiesFromPropFile(gradlePropertiesPath, getNextIntegProperties());\n }\n }", "@ArgumentsChecked\n\t@Throws(IllegalNullArgumentException.class)\n\tpublic static short checkShort(@Nonnull final Number number) {\n\t\tCheck.notNull(number, \"number\");\n\t\tif (!isInShortRange(number)) {\n\t\t\tthrow new IllegalNumberRangeException(number.toString(), SHORT_MIN, SHORT_MAX);\n\t\t}\n\n\t\treturn number.shortValue();\n\t}", "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 int getVersion() {\n ResultSet resultSet = session.execute(format(VERSION_QUERY, getTableName()));\n Row result = resultSet.one();\n if (result == null) {\n return 0;\n }\n return result.getInt(0);\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}", "public static Filter.Builder makeAncestorFilter(Key ancestor) {\n return makeFilter(\n DatastoreHelper.KEY_PROPERTY_NAME, PropertyFilter.Operator.HAS_ANCESTOR,\n makeValue(ancestor));\n }", "public void sendJsonToTagged(Object data, String ... labels) {\n for (String label : labels) {\n sendJsonToTagged(data, label);\n }\n }" ]
Use this API to fetch a vpnglobal_appcontroller_binding resources.
[ "public static vpnglobal_appcontroller_binding[] get(nitro_service service) throws Exception{\n\t\tvpnglobal_appcontroller_binding obj = new vpnglobal_appcontroller_binding();\n\t\tvpnglobal_appcontroller_binding response[] = (vpnglobal_appcontroller_binding[]) obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "private void debugLogStart(String operationType,\n Long originTimeInMS,\n Long requestReceivedTimeInMs,\n String keyString) {\n long durationInMs = requestReceivedTimeInMs - originTimeInMS;\n logger.debug(\"Received a new request. Operation Type: \" + operationType + \" , key(s): \"\n + keyString + \" , Store: \" + this.storeName + \" , Origin time (in ms): \"\n + originTimeInMS + \" . Request received at time(in ms): \"\n + requestReceivedTimeInMs\n + \" , Duration from RESTClient to CoordinatorFatClient(in ms): \"\n + durationInMs);\n\n }", "public static base_response update(nitro_service client, tmtrafficaction resource) throws Exception {\n\t\ttmtrafficaction updateresource = new tmtrafficaction();\n\t\tupdateresource.name = resource.name;\n\t\tupdateresource.apptimeout = resource.apptimeout;\n\t\tupdateresource.sso = resource.sso;\n\t\tupdateresource.formssoaction = resource.formssoaction;\n\t\tupdateresource.persistentcookie = resource.persistentcookie;\n\t\tupdateresource.initiatelogout = resource.initiatelogout;\n\t\tupdateresource.kcdaccount = resource.kcdaccount;\n\t\tupdateresource.samlssoprofile = resource.samlssoprofile;\n\t\treturn updateresource.update_resource(client);\n\t}", "public char pollChar() {\n if(hasNextChar()) {\n if(hasNextWord() &&\n character+1 >= parsedLine.words().get(word).lineIndex()+\n parsedLine.words().get(word).word().length())\n word++;\n return parsedLine.line().charAt(character++);\n }\n return '\\u0000';\n }", "public static final boolean setSelectedValue(ListBox list, String value, boolean addMissingValues) {\n\tif (value == null) {\n\t list.setSelectedIndex(0);\n\t return false;\n\t}\n\telse {\n\t int index = findValueInListBox(list, value);\n\t if (index >= 0) {\n\t\tlist.setSelectedIndex(index);\n\t\treturn true;\n\t }\n\n\t if (addMissingValues) {\n\t\tlist.addItem(value, value);\n\n\t\t// now that it's there, search again\n\t\tindex = findValueInListBox(list, value);\n\t\tlist.setSelectedIndex(index);\n\t\treturn true;\n\t }\n\n\t return false;\n\t}\n }", "public static void extractHouseholderRow( ZMatrixRMaj A ,\n int row ,\n int col0, int col1 , double u[], int offsetU )\n {\n int indexU = (offsetU+col0)*2;\n u[indexU] = 1;\n u[indexU+1] = 0;\n\n int indexA = (row*A.numCols + (col0+1))*2;\n System.arraycopy(A.data,indexA,u,indexU+2,(col1-col0-1)*2);\n }", "public static boolean promoteAndCheckResponse(Promotion promotion, ArtifactoryBuildInfoClient client, TaskListener listener,\n String buildName, String buildNumber) throws IOException {\n // If failFast is true, perform dry run first\n if (promotion.isFailFast()) {\n promotion.setDryRun(true);\n listener.getLogger().println(\"Performing dry run promotion (no changes are made during dry run) ...\");\n HttpResponse dryResponse = client.stageBuild(buildName, buildNumber, promotion);\n try {\n validatePromotionSuccessful(dryResponse, true, promotion.isFailFast(), listener);\n } catch (IOException e) {\n listener.error(e.getMessage());\n return false;\n }\n listener.getLogger().println(\"Dry run finished successfully.\\nPerforming promotion ...\");\n }\n\n // Perform promotion\n promotion.setDryRun(false);\n HttpResponse response = client.stageBuild(buildName, buildNumber, promotion);\n try {\n validatePromotionSuccessful(response, false, promotion.isFailFast(), listener);\n } catch (IOException e) {\n listener.error(e.getMessage());\n return false;\n }\n listener.getLogger().println(\"Promotion completed successfully!\");\n\n return true;\n }", "protected void addConstructors(ClassFile proxyClassType, List<DeferredBytecode> initialValueBytecode) {\n try {\n if (getBeanType().isInterface()) {\n ConstructorUtils.addDefaultConstructor(proxyClassType, initialValueBytecode, !useConstructedFlag());\n } else {\n boolean constructorFound = false;\n for (Constructor<?> constructor : AccessController.doPrivileged(new GetDeclaredConstructorsAction(getBeanType()))) {\n if ((constructor.getModifiers() & Modifier.PRIVATE) == 0) {\n constructorFound = true;\n String[] exceptions = new String[constructor.getExceptionTypes().length];\n for (int i = 0; i < exceptions.length; ++i) {\n exceptions[i] = constructor.getExceptionTypes()[i].getName();\n }\n ConstructorUtils.addConstructor(BytecodeUtils.VOID_CLASS_DESCRIPTOR, DescriptorUtils.parameterDescriptors(constructor.getParameterTypes()), exceptions, proxyClassType, initialValueBytecode, !useConstructedFlag());\n }\n }\n if (!constructorFound) {\n // the bean only has private constructors, we need to generate\n // two fake constructors that call each other\n addConstructorsForBeanWithPrivateConstructors(proxyClassType);\n }\n }\n } catch (Exception e) {\n throw new WeldException(e);\n }\n }", "protected Boolean getSearchForEmptyQuery() {\n\n Boolean isSearchForEmptyQuery = parseOptionalBooleanValue(m_configObject, JSON_KEY_SEARCH_FOR_EMPTY_QUERY);\n return (isSearchForEmptyQuery == null) && (null != m_baseConfig)\n ? Boolean.valueOf(m_baseConfig.getGeneralConfig().getSearchForEmptyQueryParam())\n : isSearchForEmptyQuery;\n }", "public static void withInstance(String url, Closure c) throws SQLException {\n Sql sql = null;\n try {\n sql = newInstance(url);\n c.call(sql);\n } finally {\n if (sql != null) sql.close();\n }\n }" ]
try to find a field in class c, recurse through class hierarchy if necessary @throws NoSuchFieldException if no Field was found into the class hierarchy
[ "private Field getFieldRecursive(Class c, String name) throws NoSuchFieldException\r\n {\r\n try\r\n {\r\n return c.getDeclaredField(name);\r\n }\r\n catch (NoSuchFieldException e)\r\n {\r\n // if field could not be found in the inheritance hierarchy, signal error\r\n if ((c == Object.class) || (c.getSuperclass() == null) || c.isInterface())\r\n {\r\n throw e;\r\n }\r\n // if field could not be found in class c try in superclass\r\n else\r\n {\r\n return getFieldRecursive(c.getSuperclass(), name);\r\n }\r\n }\r\n }" ]
[ "private LinkedList<TimephasedWork> readTimephasedAssignment(ProjectCalendar calendar, Project.Assignments.Assignment assignment, int type)\n {\n LinkedList<TimephasedWork> result = new LinkedList<TimephasedWork>();\n\n for (TimephasedDataType item : assignment.getTimephasedData())\n {\n if (NumberHelper.getInt(item.getType()) != type)\n {\n continue;\n }\n\n Date startDate = item.getStart();\n Date finishDate = item.getFinish();\n\n // Exclude ranges which don't have a start and end date.\n // These seem to be generated by Synchro and have a zero duration.\n if (startDate == null && finishDate == null)\n {\n continue;\n }\n\n Duration work = DatatypeConverter.parseDuration(m_projectFile, TimeUnit.MINUTES, item.getValue());\n if (work == null)\n {\n work = Duration.getInstance(0, TimeUnit.MINUTES);\n }\n else\n {\n work = Duration.getInstance(NumberHelper.round(work.getDuration(), 2), TimeUnit.MINUTES);\n }\n\n TimephasedWork tra = new TimephasedWork();\n tra.setStart(startDate);\n tra.setFinish(finishDate);\n tra.setTotalAmount(work);\n\n result.add(tra);\n }\n\n return result;\n }", "public static final double round(double value, double precision)\n {\n precision = Math.pow(10, precision);\n return Math.round(value * precision) / precision;\n }", "public AsciiTable setTargetTranslator(TargetTranslator targetTranslator) {\r\n\t\tfor(AT_Row row : this.rows){\r\n\t\t\tif(row.getType()==TableRowType.CONTENT){\r\n\t\t\t\trow.setTargetTranslator(targetTranslator);\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn this;\r\n\t}", "public static cmppolicylabel_cmppolicy_binding[] get(nitro_service service, String labelname) throws Exception{\n\t\tcmppolicylabel_cmppolicy_binding obj = new cmppolicylabel_cmppolicy_binding();\n\t\tobj.set_labelname(labelname);\n\t\tcmppolicylabel_cmppolicy_binding response[] = (cmppolicylabel_cmppolicy_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 }", "public void shutdown() {\n\n for (Entry<HttpClientType, AsyncHttpClient> entry : map.entrySet()) {\n AsyncHttpClient client = entry.getValue();\n if (client != null)\n client.close();\n }\n\n }", "public static <T> SessionBean<T> of(BeanAttributes<T> attributes, InternalEjbDescriptor<T> ejbDescriptor, BeanManagerImpl beanManager, EnhancedAnnotatedType<T> type) {\n return new SessionBeanImpl<T>(attributes, type, ejbDescriptor, new StringBeanIdentifier(SessionBeans.createIdentifier(type, ejbDescriptor)), beanManager);\n }", "@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 String getString(Integer id, Integer type)\n {\n return (getString(m_meta.getOffset(id, type)));\n }" ]
Returns the class of datatype URI that best characterizes the range of the given property based on its datatype. @param propertyIdValue the property for which to get a range @return the range URI or null if the datatype could not be identified.
[ "String getRangeUri(PropertyIdValue propertyIdValue) {\n\t\tString datatype = this.propertyRegister\n\t\t\t\t.getPropertyType(propertyIdValue);\n\n\t\tif (datatype == null)\n\t\t\treturn null;\n\n\t\tswitch (datatype) {\n\t\tcase DatatypeIdValue.DT_MONOLINGUAL_TEXT:\n\t\t\tthis.rdfConversionBuffer.addDatatypeProperty(propertyIdValue);\n\t\t\treturn Vocabulary.RDF_LANG_STRING;\n\t\tcase DatatypeIdValue.DT_STRING:\n\t\tcase DatatypeIdValue.DT_EXTERNAL_ID:\n\t\tcase DatatypeIdValue.DT_MATH:\n\t\t\tthis.rdfConversionBuffer.addDatatypeProperty(propertyIdValue);\n\t\t\treturn Vocabulary.XSD_STRING;\n\t\tcase DatatypeIdValue.DT_COMMONS_MEDIA:\n\t\tcase DatatypeIdValue.DT_GLOBE_COORDINATES:\n\t\tcase DatatypeIdValue.DT_ITEM:\n\t\tcase DatatypeIdValue.DT_PROPERTY:\n\t\tcase DatatypeIdValue.DT_LEXEME:\n\t\tcase DatatypeIdValue.DT_FORM:\n\t\tcase DatatypeIdValue.DT_SENSE:\n\t\tcase DatatypeIdValue.DT_TIME:\n\t\tcase DatatypeIdValue.DT_URL:\n\t\tcase DatatypeIdValue.DT_GEO_SHAPE:\n\t\tcase DatatypeIdValue.DT_TABULAR_DATA:\n\t\tcase DatatypeIdValue.DT_QUANTITY:\n\t\t\tthis.rdfConversionBuffer.addObjectProperty(propertyIdValue);\n\t\t\treturn Vocabulary.OWL_THING;\n\t\tdefault:\n\t\t\treturn null;\n\t\t}\n\t}" ]
[ "public static void dumpMaterial(AiMaterial material) {\n for (AiMaterial.Property prop : material.getProperties()) {\n dumpMaterialProperty(prop);\n }\n }", "public static base_responses update(nitro_service client, clusternodegroup resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tclusternodegroup updateresources[] = new clusternodegroup[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new clusternodegroup();\n\t\t\t\tupdateresources[i].name = resources[i].name;\n\t\t\t\tupdateresources[i].strict = resources[i].strict;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "@IntRange(from = 0, to = OPAQUE)\n private static int resolveLineAlpha(\n @IntRange(from = 0, to = OPAQUE) final int sceneAlpha,\n final float maxDistance,\n final float distance) {\n final float alphaPercent = 1f - distance / maxDistance;\n final int alpha = (int) ((float) OPAQUE * alphaPercent);\n return alpha * sceneAlpha / OPAQUE;\n }", "public List<CmsJspNavElement> getSubNavigation() {\n\n if (m_subNavigation == null) {\n if (m_resource.isFile()) {\n m_subNavigation = Collections.emptyList();\n } else if (m_navContext == null) {\n try {\n throw new Exception(\"Can not get subnavigation because navigation context is not set.\");\n } catch (Exception e) {\n LOG.warn(e.getLocalizedMessage(), e);\n m_subNavigation = Collections.emptyList();\n }\n } else {\n CmsJspNavBuilder navBuilder = m_navContext.getNavBuilder();\n m_subNavigation = navBuilder.getNavigationForFolder(\n navBuilder.getCmsObject().getSitePath(m_resource),\n m_navContext.getVisibility(),\n m_navContext.getFilter());\n }\n\n }\n return m_subNavigation;\n\n }", "@UiHandler({\"m_atMonth\", \"m_everyMonth\"})\r\n void onMonthChange(ValueChangeEvent<String> event) {\r\n\r\n if (handleChange()) {\r\n m_controller.setMonth(event.getValue());\r\n }\r\n }", "private String getFullUrl(String url) {\n return url.startsWith(\"https://\") || url.startsWith(\"http://\") ? url : transloadit.getHostUrl() + url;\n }", "public int getCostRateTableIndex()\n {\n Integer value = (Integer) getCachedValue(AssignmentField.COST_RATE_TABLE);\n return value == null ? 0 : value.intValue();\n }", "protected void doSplitTokenImpl(Token token, ITokenAcceptor result) {\n\t\tString text = token.getText();\n\t\tint indentation = computeIndentation(text);\n\t\tif (indentation == -1 || indentation == currentIndentation) {\n\t\t\t// no change of indentation level detected simply process the token\n\t\t\tresult.accept(token);\n\t\t} else if (indentation > currentIndentation) {\n\t\t\t// indentation level increased\n\t\t\tsplitIntoBeginToken(token, indentation, result);\n\t\t} else if (indentation < currentIndentation) {\n\t\t\t// indentation level decreased\n\t\t\tint charCount = computeIndentationRelevantCharCount(text);\n\t\t\tif (charCount > 0) {\n\t\t\t\t// emit whitespace including newline\n\t\t\t\tsplitWithText(token, text.substring(0, charCount), result);\t\n\t\t\t}\n\t\t\t// emit end tokens at the beginning of the line\n\t\t\tdecreaseIndentation(indentation, result);\n\t\t\tif (charCount != text.length()) {\n\t\t\t\thandleRemainingText(token, text.substring(charCount), indentation, result);\n\t\t\t}\n\t\t} else {\n\t\t\tthrow new IllegalStateException(String.valueOf(indentation));\n\t\t}\n\t}", "public static void printHelp(PrintStream stream) {\n stream.println();\n stream.println(\"Voldemort Admin Tool Async-Job Commands\");\n stream.println(\"---------------------------------------\");\n stream.println(\"list Get async job list from nodes.\");\n stream.println(\"stop Stop async jobs on one node.\");\n stream.println();\n stream.println(\"To get more information on each command,\");\n stream.println(\"please try \\'help async-job <command-name>\\'.\");\n stream.println();\n }" ]
Recycle all views in the list. The host views might be reused for other data to save resources on creating new widgets.
[ "protected void recycleChildren() {\n for (ListItemHostWidget host: getAllHosts()) {\n recycle(host);\n }\n mContent.onTransformChanged();\n mContent.requestLayout();\n }" ]
[ "public int getCrossZonePartitionStoreMoves() {\n int xzonePartitionStoreMoves = 0;\n for (RebalanceTaskInfo info : batchPlan) {\n Node donorNode = finalCluster.getNodeById(info.getDonorId());\n Node stealerNode = finalCluster.getNodeById(info.getStealerId());\n\n if(donorNode.getZoneId() != stealerNode.getZoneId()) {\n xzonePartitionStoreMoves += info.getPartitionStoreMoves();\n }\n }\n\n return xzonePartitionStoreMoves;\n }", "public Association getAssociation(String collectionRole) {\n\t\tif ( associations == null ) {\n\t\t\treturn null;\n\t\t}\n\t\treturn associations.get( collectionRole );\n\t}", "public void addStep(String name, String robot, Map<String, Object> options){\n steps.addStep(name, robot, options);\n }", "@Deprecated\n public static OptionMap create(final ExpressionResolver resolver, final ModelNode model, final OptionMap defaults) throws OperationFailedException {\n final OptionMap map = OptionMap.builder()\n .addAll(defaults)\n .set(Options.WORKER_READ_THREADS, RemotingSubsystemRootResource.WORKER_READ_THREADS.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_TASK_CORE_THREADS, RemotingSubsystemRootResource.WORKER_TASK_CORE_THREADS.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_TASK_KEEPALIVE, RemotingSubsystemRootResource.WORKER_TASK_KEEPALIVE.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_TASK_LIMIT, RemotingSubsystemRootResource.WORKER_TASK_LIMIT.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_TASK_MAX_THREADS, RemotingSubsystemRootResource.WORKER_TASK_MAX_THREADS.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_WRITE_THREADS, RemotingSubsystemRootResource.WORKER_WRITE_THREADS.resolveModelAttribute(resolver, model).asInt())\n .set(Options.WORKER_READ_THREADS, RemotingSubsystemRootResource.WORKER_READ_THREADS.resolveModelAttribute(resolver, model).asInt())\n .getMap();\n return map;\n }", "public void addLicense(final String gavc, final String licenseId) {\n final DbArtifact dbArtifact = getArtifact(gavc);\n\n // Try to find an existing license that match the new one\n final LicenseHandler licenseHandler = new LicenseHandler(repositoryHandler);\n final DbLicense license = licenseHandler.resolve(licenseId);\n\n // If there is no existing license that match this one let's use the provided value but\n // only if the artifact has no license yet. Otherwise it could mean that users has already\n // identify the license manually.\n if(license == null){\n if(dbArtifact.getLicenses().isEmpty()){\n LOG.warn(\"Add reference to a non existing license called \" + licenseId + \" in artifact \" + dbArtifact.getGavc());\n repositoryHandler.addLicenseToArtifact(dbArtifact, licenseId);\n }\n }\n // Add only if the license is not already referenced\n else if(!dbArtifact.getLicenses().contains(license.getName())){\n repositoryHandler.addLicenseToArtifact(dbArtifact, license.getName());\n }\n }", "public static Type boxedType(Type type) {\n if (type instanceof Class<?>) {\n return boxedClass((Class<?>) type);\n } else {\n return type;\n }\n }", "public void addLicense(final String gavc, final String licenseId) {\n final DbArtifact dbArtifact = getArtifact(gavc);\n\n // Try to find an existing license that match the new one\n final LicenseHandler licenseHandler = new LicenseHandler(repositoryHandler);\n final DbLicense license = licenseHandler.resolve(licenseId);\n\n // If there is no existing license that match this one let's use the provided value but\n // only if the artifact has no license yet. Otherwise it could mean that users has already\n // identify the license manually.\n if(license == null){\n if(dbArtifact.getLicenses().isEmpty()){\n LOG.warn(\"Add reference to a non existing license called \" + licenseId + \" in artifact \" + dbArtifact.getGavc());\n repositoryHandler.addLicenseToArtifact(dbArtifact, licenseId);\n }\n }\n // Add only if the license is not already referenced\n else if(!dbArtifact.getLicenses().contains(license.getName())){\n repositoryHandler.addLicenseToArtifact(dbArtifact, license.getName());\n }\n }", "public static base_response delete(nitro_service client, String servicename) throws Exception {\n\t\tgslbservice deleteresource = new gslbservice();\n\t\tdeleteresource.servicename = servicename;\n\t\treturn deleteresource.delete_resource(client);\n\t}", "private ResourceReport getResourceReport(TwillController controller, int maxWaitMs) {\n ResourceReport report = controller.getResourceReport();\n int elapsed = 0;\n while (report == null) {\n report = controller.getResourceReport();\n try {\n Thread.sleep(500);\n } catch (InterruptedException e) {\n throw new IllegalStateException(e);\n }\n elapsed += 500;\n if ((maxWaitMs != -1) && (elapsed > maxWaitMs)) {\n String msg = String.format(\"Exceeded max wait time to retrieve ResourceReport from Twill.\"\n + \" Elapsed time = %s ms\", elapsed);\n log.error(msg);\n throw new IllegalStateException(msg);\n }\n if ((elapsed % 10000) == 0) {\n log.info(\"Waiting for ResourceReport from Twill. Elapsed time = {} ms\", elapsed);\n }\n }\n return report;\n }" ]
BuildInteractiveObjectFromAnchor is a special type of interactive object in that it does not get built using ROUTE's. @param anchorSensor is the Sensor that describes the sensor set to an Anchor @param anchorDestination is either another Viewpoint, url to a web site or another x3d scene
[ "public void BuildInteractiveObjectFromAnchor(Sensor anchorSensor, String anchorDestination) {\n InteractiveObject interactiveObject = new InteractiveObject();\n interactiveObject.setSensor(anchorSensor, anchorDestination);\n interactiveObjects.add(interactiveObject);\n }" ]
[ "private boolean evaluateLogicalOperator(FieldContainer container, Map<GenericCriteriaPrompt, Object> promptValues)\n {\n boolean result = false;\n\n if (m_criteriaList.size() == 0)\n {\n result = true;\n }\n else\n {\n for (GenericCriteria criteria : m_criteriaList)\n {\n result = criteria.evaluate(container, promptValues);\n if ((m_operator == TestOperator.AND && !result) || (m_operator == TestOperator.OR && result))\n {\n break;\n }\n }\n }\n\n return result;\n }", "private String getParentWBS(String wbs)\n {\n String result;\n int index = wbs.lastIndexOf('.');\n if (index == -1)\n {\n result = null;\n }\n else\n {\n result = wbs.substring(0, index);\n }\n return result;\n }", "public Object convertJavaFieldToSqlArgValue(Object fieldVal) throws SQLException {\n\t\t/*\n\t\t * Limitation here. Some people may want to override the null with their own value in the converter but we\n\t\t * currently don't allow that. Specifying a default value I guess is a better mechanism.\n\t\t */\n\t\tif (fieldVal == null) {\n\t\t\treturn null;\n\t\t} else {\n\t\t\treturn fieldConverter.javaToSqlArg(this, fieldVal);\n\t\t}\n\t}", "public static dnsglobal_binding get(nitro_service service) throws Exception{\n\t\tdnsglobal_binding obj = new dnsglobal_binding();\n\t\tdnsglobal_binding response = (dnsglobal_binding) obj.get_resource(service);\n\t\treturn response;\n\t}", "public NamespacesList<Namespace> getNamespaces(String predicate, int perPage, int page) throws FlickrException {\r\n Map<String, Object> parameters = new HashMap<String, Object>();\r\n NamespacesList<Namespace> nsList = new NamespacesList<Namespace>();\r\n parameters.put(\"method\", METHOD_GET_NAMESPACES);\r\n\r\n if (predicate != null) {\r\n parameters.put(\"predicate\", predicate);\r\n }\r\n if (perPage > 0) {\r\n parameters.put(\"per_page\", \"\" + perPage);\r\n }\r\n if (page > 0) {\r\n parameters.put(\"page\", \"\" + page);\r\n }\r\n\r\n 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 nsElement = response.getPayload();\r\n NodeList nsNodes = nsElement.getElementsByTagName(\"namespace\");\r\n nsList.setPage(\"1\");\r\n nsList.setPages(\"1\");\r\n nsList.setPerPage(\"\" + nsNodes.getLength());\r\n nsList.setTotal(\"\" + nsNodes.getLength());\r\n for (int i = 0; i < nsNodes.getLength(); i++) {\r\n Element element = (Element) nsNodes.item(i);\r\n nsList.add(parseNamespace(element));\r\n }\r\n return nsList;\r\n }", "private void registerRequirement(RuntimeRequirementRegistration requirement) {\n assert writeLock.isHeldByCurrentThread();\n CapabilityId dependentId = requirement.getDependentId();\n if (!capabilities.containsKey(dependentId)) {\n throw ControllerLogger.MGMT_OP_LOGGER.unknownCapabilityInContext(dependentId.getName(),\n dependentId.getScope().getName());\n }\n Map<CapabilityId, Map<String, RuntimeRequirementRegistration>> requirementMap =\n requirement.isRuntimeOnly() ? runtimeOnlyRequirements : requirements;\n\n Map<String, RuntimeRequirementRegistration> dependents = requirementMap.get(dependentId);\n if (dependents == null) {\n dependents = new HashMap<>();\n requirementMap.put(dependentId, dependents);\n }\n RuntimeRequirementRegistration existing = dependents.get(requirement.getRequiredName());\n if (existing == null) {\n dependents.put(requirement.getRequiredName(), requirement);\n } else {\n existing.addRegistrationPoint(requirement.getOldestRegistrationPoint());\n }\n modified = true;\n }", "public static dospolicy[] get(nitro_service service) throws Exception{\n\t\tdospolicy obj = new dospolicy();\n\t\tdospolicy[] response = (dospolicy[])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 }", "private Duration getAssignmentWork(ProjectCalendar calendar, TimephasedWork assignment)\n {\n Date assignmentStart = assignment.getStart();\n\n Date splitStart = assignmentStart;\n Date splitFinishTime = calendar.getFinishTime(splitStart);\n Date splitFinish = DateHelper.setTime(splitStart, splitFinishTime);\n\n Duration calendarSplitWork = calendar.getWork(splitStart, splitFinish, TimeUnit.MINUTES);\n Duration assignmentWorkPerDay = assignment.getAmountPerDay();\n Duration splitWork;\n\n double splitMinutes = assignmentWorkPerDay.getDuration();\n splitMinutes *= calendarSplitWork.getDuration();\n splitMinutes /= (8 * 60); // this appears to be a fixed value\n splitWork = Duration.getInstance(splitMinutes, TimeUnit.MINUTES);\n return splitWork;\n }" ]
Parse a string representation of a Boolean value. XER files sometimes have "N" and "Y" to indicate boolean @param value string representation @return Boolean value
[ "private final boolean parseBoolean(String value)\n {\n return value != null && (value.equalsIgnoreCase(\"true\") || value.equalsIgnoreCase(\"y\") || value.equalsIgnoreCase(\"yes\"));\n }" ]
[ "private void beforeBatch(BatchBackend backend) {\n\t\tif ( this.purgeAtStart ) {\n\t\t\t// purgeAll for affected entities\n\t\t\tIndexedTypeSet targetedTypes = searchFactoryImplementor.getIndexedTypesPolymorphic( rootIndexedTypes );\n\t\t\tfor ( IndexedTypeIdentifier type : targetedTypes ) {\n\t\t\t\t// needs do be in-sync work to make sure we wait for the end of it.\n\t\t\t\tbackend.doWorkInSync( new PurgeAllLuceneWork( tenantId, type ) );\n\t\t\t}\n\t\t\tif ( this.optimizeAfterPurge ) {\n\t\t\t\tbackend.optimize( targetedTypes );\n\t\t\t}\n\t\t}\n\t}", "public static Broker createBroker(int id, String brokerInfoString) {\n String[] brokerInfo = brokerInfoString.split(\":\");\n String creator = brokerInfo[0].replace('#', ':');\n String hostname = brokerInfo[1].replace('#', ':');\n String port = brokerInfo[2];\n boolean autocreated = Boolean.valueOf(brokerInfo.length > 3 ? brokerInfo[3] : \"true\");\n return new Broker(id, creator, hostname, Integer.parseInt(port), autocreated);\n }", "public void addFile(String description, FileModel fileModel)\n {\n Map<FileModel, ProblemFileSummary> files = addDescription(description);\n\n if (files.containsKey(fileModel))\n {\n files.get(fileModel).addOccurrence();\n } else {\n files.put(fileModel, new ProblemFileSummary(fileModel, 1));\n }\n }", "public void removePropertyChangeListener (String propertyName, java.beans.PropertyChangeListener listener)\r\n {\r\n this.propertyChangeDelegate.removePropertyChangeListener(propertyName, listener);\r\n }", "public Collection getAllObjects(Class target)\r\n {\r\n PersistenceBroker broker = getBroker();\r\n Collection result;\r\n try\r\n {\r\n Query q = new QueryByCriteria(target);\r\n result = broker.getCollectionByQuery(q);\r\n }\r\n finally\r\n {\r\n if (broker != null) broker.close();\r\n }\r\n return result;\r\n }", "public static DMatrixSparseTriplet uniform(int numRows , int numCols , int nz_total ,\n double min , double max , Random rand ) {\n // Create a list of all the possible element values\n int N = numCols*numRows;\n if( N < 0 )\n throw new IllegalArgumentException(\"matrix size is too large\");\n nz_total = Math.min(N,nz_total);\n\n int selected[] = new int[N];\n for (int i = 0; i < N; i++) {\n selected[i] = i;\n }\n\n for (int i = 0; i < nz_total; i++) {\n int s = rand.nextInt(N);\n int tmp = selected[s];\n selected[s] = selected[i];\n selected[i] = tmp;\n }\n\n // Create a sparse matrix\n DMatrixSparseTriplet ret = new DMatrixSparseTriplet(numRows,numCols,nz_total);\n\n for (int i = 0; i < nz_total; i++) {\n int row = selected[i]/numCols;\n int col = selected[i]%numCols;\n\n double value = rand.nextDouble()*(max-min)+min;\n\n ret.addItem(row,col, value);\n }\n\n return ret;\n }", "@Override\n\tpublic String getInputToParse(String completeInput, int offset, int completionOffset) {\n\t\tint fixedOffset = getOffsetIncludingWhitespace(completeInput, offset, Math.min(completeInput.length(), completionOffset));\n\t\treturn super.getInputToParse(completeInput, fixedOffset, completionOffset);\n\t}", "protected void countStatements(UsageStatistics usageStatistics,\n\t\t\tStatementDocument statementDocument) {\n\t\t// Count Statement data:\n\t\tfor (StatementGroup sg : statementDocument.getStatementGroups()) {\n\t\t\t// Count Statements:\n\t\t\tusageStatistics.countStatements += sg.size();\n\n\t\t\t// Count uses of properties in Statements:\n\t\t\tcountPropertyMain(usageStatistics, sg.getProperty(), sg.size());\n\t\t\tfor (Statement s : sg) {\n\t\t\t\tfor (SnakGroup q : s.getQualifiers()) {\n\t\t\t\t\tcountPropertyQualifier(usageStatistics, q.getProperty(), q.size());\n\t\t\t\t}\n\t\t\t\tfor (Reference r : s.getReferences()) {\n\t\t\t\t\tusageStatistics.countReferencedStatements++;\n\t\t\t\t\tfor (SnakGroup snakGroup : r.getSnakGroups()) {\n\t\t\t\t\t\tcountPropertyReference(usageStatistics,\n\t\t\t\t\t\t\t\tsnakGroup.getProperty(), snakGroup.size());\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}", "public int count(String key) {\n ConcurrentMap<WebSocketConnection, WebSocketConnection> bag = registry.get(key);\n return null == bag ? 0 : bag.size();\n }" ]
Resumes a given entry point type; @param entryPoint The entry point
[ "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 }" ]
[ "public static java.sql.Date rollYears(java.util.Date startDate, int years) {\n return rollDate(startDate, Calendar.YEAR, years);\n }", "public static List<Number> findIndexValues(Object self, Number startIndex, Closure closure) {\n List<Number> result = new ArrayList<Number>();\n long count = 0;\n long startCount = startIndex.longValue();\n BooleanClosureWrapper bcw = new BooleanClosureWrapper(closure);\n for (Iterator iter = InvokerHelper.asIterator(self); iter.hasNext(); count++) {\n Object value = iter.next();\n if (count < startCount) {\n continue;\n }\n if (bcw.call(value)) {\n result.add(count);\n }\n }\n return result;\n }", "public void _solveVectorInternal( double []vv )\n {\n // Solve L*Y = B\n int ii = 0;\n\n for( int i = 0; i < n; i++ ) {\n int ip = indx[i];\n double sum = vv[ip];\n vv[ip] = vv[i];\n if( ii != 0 ) {\n// for( int j = ii-1; j < i; j++ )\n// sum -= dataLU[i* n +j]*vv[j];\n int index = i*n + ii-1;\n for( int j = ii-1; j < i; j++ )\n sum -= dataLU[index++]*vv[j];\n } else if( sum != 0.0 ) {\n ii=i+1;\n }\n vv[i] = sum;\n }\n\n // Solve U*X = Y;\n TriangularSolver_DDRM.solveU(dataLU,vv,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 List<T> nextPermutationAsList()\n {\n List<T> permutation = new ArrayList<T>(elements.length);\n return nextPermutationAsList(permutation);\n }", "public boolean containsIteratorForTable(String aTable)\r\n {\r\n boolean result = false;\r\n\r\n if (m_rsIterators != null)\r\n {\r\n for (int i = 0; i < m_rsIterators.size(); i++)\r\n {\r\n OJBIterator it = (OJBIterator) m_rsIterators.get(i);\r\n if (it instanceof RsIterator)\r\n {\r\n if (((RsIterator) it).getClassDescriptor().getFullTableName().equals(aTable))\r\n {\r\n result = true;\r\n break;\r\n }\r\n }\r\n else if (it instanceof ChainingIterator)\r\n {\r\n result = ((ChainingIterator) it).containsIteratorForTable(aTable);\r\n }\r\n }\r\n }\r\n\r\n return result;\r\n }", "public void writeAnswers(List<IN> doc, PrintWriter printWriter,\r\n DocumentReaderAndWriter<IN> readerAndWriter)\r\n throws IOException {\r\n if (flags.lowerNewgeneThreshold) {\r\n return;\r\n }\r\n if (flags.numRuns <= 1) {\r\n readerAndWriter.printAnswers(doc, printWriter);\r\n // out.println();\r\n printWriter.flush();\r\n }\r\n }", "public Set<Tag> getAncestorTags(Tag tag)\n {\n Set<Tag> ancestors = new HashSet<>();\n getAncestorTags(tag, ancestors);\n return ancestors;\n }", "public static base_response delete(nitro_service client, sslcertkey resource) throws Exception {\n\t\tsslcertkey deleteresource = new sslcertkey();\n\t\tdeleteresource.certkey = resource.certkey;\n\t\treturn deleteresource.delete_resource(client);\n\t}" ]
Create a ModelNode representing the operating system the instance is running on. @return a ModelNode representing the operating system the instance is running on. @throws OperationFailedException
[ "private ModelNode createOSNode() throws OperationFailedException {\n String osName = getProperty(\"os.name\");\n final ModelNode os = new ModelNode();\n if (osName != null && osName.toLowerCase().contains(\"linux\")) {\n try {\n os.set(GnuLinuxDistribution.discover());\n } catch (IOException ex) {\n throw new OperationFailedException(ex);\n }\n } else {\n os.set(osName);\n }\n return os;\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}", "private void init(AttributeSet attrs) {\n inflate(getContext(), R.layout.intl_phone_input, this);\n\n /**+\n * Country spinner\n */\n mCountrySpinner = (Spinner) findViewById(R.id.intl_phone_edit__country);\n mCountrySpinnerAdapter = new CountrySpinnerAdapter(getContext());\n mCountrySpinner.setAdapter(mCountrySpinnerAdapter);\n\n mCountries = CountriesFetcher.getCountries(getContext());\n mCountrySpinnerAdapter.addAll(mCountries);\n mCountrySpinner.setOnItemSelectedListener(mCountrySpinnerListener);\n\n setFlagDefaults(attrs);\n\n /**\n * Phone text field\n */\n mPhoneEdit = (EditText) findViewById(R.id.intl_phone_edit__phone);\n mPhoneEdit.addTextChangedListener(mPhoneNumberWatcher);\n\n setDefault();\n setEditTextDefaults(attrs);\n }", "static ChangeEvent<BsonDocument> changeEventForLocalReplace(\n final MongoNamespace namespace,\n final BsonValue documentId,\n final BsonDocument document,\n final boolean writePending\n ) {\n return new ChangeEvent<>(\n new BsonDocument(),\n OperationType.REPLACE,\n document,\n namespace,\n new BsonDocument(\"_id\", documentId),\n null,\n writePending);\n }", "public Integer getOverrideIdForMethod(String className, String methodName) {\n Integer overrideId = null;\n PreparedStatement query = null;\n ResultSet results = null;\n\n try (Connection sqlConnection = sqlService.getConnection()) {\n query = sqlConnection.prepareStatement(\n \"SELECT * FROM \" + Constants.DB_TABLE_OVERRIDE +\n \" WHERE \" + Constants.OVERRIDE_CLASS_NAME + \" = ?\" +\n \" AND \" + Constants.OVERRIDE_METHOD_NAME + \" = ?\"\n );\n query.setString(1, className);\n query.setString(2, methodName);\n results = query.executeQuery();\n\n if (results.next()) {\n overrideId = results.getInt(Constants.GENERIC_ID);\n }\n } catch (SQLException e) {\n e.printStackTrace();\n return null;\n } finally {\n try {\n if (results != null) {\n results.close();\n }\n } catch (Exception e) {\n }\n try {\n if (query != null) {\n query.close();\n }\n } catch (Exception e) {\n }\n }\n\n return overrideId;\n }", "public static String workDays(ProjectCalendar input)\n {\n StringBuilder result = new StringBuilder();\n DayType[] test = input.getDays(); // get the array from MPXJ ProjectCalendar\n for (DayType i : test)\n { // go through every day in the given array\n if (i == DayType.NON_WORKING)\n {\n result.append(\"N\"); // only put N for non-working day of the week\n }\n else\n {\n result.append(\"Y\"); // Assume WORKING day unless NON_WORKING\n }\n }\n return result.toString(); // According to USACE specs., exceptions will be specified in HOLI records\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 QueryBuilder<T, ID> groupBy(String columnName) {\n\t\tFieldType fieldType = verifyColumnName(columnName);\n\t\tif (fieldType.isForeignCollection()) {\n\t\t\tthrow new IllegalArgumentException(\"Can't groupBy foreign collection field: \" + columnName);\n\t\t}\n\t\taddGroupBy(ColumnNameOrRawSql.withColumnName(columnName));\n\t\treturn this;\n\t}", "public static appqoepolicy get(nitro_service service, String name) throws Exception{\n\t\tappqoepolicy obj = new appqoepolicy();\n\t\tobj.set_name(name);\n\t\tappqoepolicy response = (appqoepolicy) obj.get_resource(service);\n\t\treturn response;\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}" ]
Helper method to get a list of node ids. @param nodeList
[ "private static List<Integer> stripNodeIds(List<Node> nodeList) {\n List<Integer> nodeidList = new ArrayList<Integer>();\n if(nodeList != null) {\n for(Node node: nodeList) {\n nodeidList.add(node.getId());\n }\n }\n return nodeidList;\n }" ]
[ "public static PacketType validateHeader(DatagramPacket packet, int port) {\n byte[] data = packet.getData();\n\n if (data.length < PACKET_TYPE_OFFSET) {\n logger.warn(\"Packet is too short to be a Pro DJ Link packet; must be at least \" + PACKET_TYPE_OFFSET +\n \" bytes long, was only \" + data.length + \".\");\n return null;\n }\n\n if (!getMagicHeader().equals(ByteBuffer.wrap(data, 0, MAGIC_HEADER.length))) {\n logger.warn(\"Packet did not have correct nine-byte header for the Pro DJ Link protocol.\");\n return null;\n }\n\n final Map<Byte, PacketType> portMap = PACKET_TYPE_MAP.get(port);\n if (portMap == null) {\n logger.warn(\"Do not know any Pro DJ Link packets that are received on port \" + port + \".\");\n return null;\n }\n\n final PacketType result = portMap.get(data[PACKET_TYPE_OFFSET]);\n if (result == null) {\n logger.warn(\"Do not know any Pro DJ Link packets received on port \" + port + \" with type \" +\n String.format(\"0x%02x\", data[PACKET_TYPE_OFFSET]) + \".\");\n }\n\n return result;\n }", "private void createStringMappings(MtasTokenIdFactory mtasTokenIdFactory,\n Level level, String stringValue, int offsetStart, int offsetEnd,\n int position) throws IOException {\n // System.out.println(\"createStringMappings string \");\n String[] stringValues = MtasPennTreebankReader.createStrings(stringValue,\n Pattern.quote(STRING_SPLITTER));\n if (stringValues.length > 0 && !stringValues[0].trim().isEmpty()) {\n MtasToken token = new MtasTokenString(mtasTokenIdFactory.createTokenId(),\n \"t\", filterString(stringValues[0].trim()), position);\n token.setOffset(offsetStart, offsetEnd);\n tokenCollection.add(token);\n level.tokens.add(token);\n }\n if (stringValues.length > 1 && !stringValues[1].trim().isEmpty()) {\n MtasToken token = new MtasTokenString(mtasTokenIdFactory.createTokenId(),\n \"lemma\", filterString(stringValues[1].trim()), position);\n token.setOffset(offsetStart, offsetEnd);\n tokenCollection.add(token);\n level.tokens.add(token);\n }\n }", "public List<BindingInfo> getQueueBindings(String vhost, String queue) {\n final URI uri = uriWithPath(\"./queues/\" + encodePathSegment(vhost) +\n \"/\" + encodePathSegment(queue) + \"/bindings\");\n final BindingInfo[] result = this.rt.getForObject(uri, BindingInfo[].class);\n return asListOrNull(result);\n }", "public void retrieveProxyCollections(Object newObj, ClassDescriptor cld, boolean forced) throws PersistenceBrokerException\r\n {\r\n doRetrieveCollections(newObj, cld, forced, true);\r\n }", "public V get(K key) {\n ManagedReference<V> ref = internalMap.get(key);\n if (ref!=null) return ref.get();\n return null;\n }", "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}", "public static void createEphemeralPath(ZkClient zkClient, String path, String data) {\n try {\n zkClient.createEphemeral(path, Utils.getBytes(data));\n } catch (ZkNoNodeException e) {\n createParentPath(zkClient, path);\n zkClient.createEphemeral(path, Utils.getBytes(data));\n }\n }", "@Override\n protected void denyImportDeclaration(ImportDeclaration importDeclaration) {\n LOG.debug(\"CXFImporter destroy a proxy for \" + importDeclaration);\n ServiceRegistration serviceRegistration = map.get(importDeclaration);\n serviceRegistration.unregister();\n\n // set the importDeclaration has unhandled\n super.unhandleImportDeclaration(importDeclaration);\n\n map.remove(importDeclaration);\n }", "public void process(Connection connection, String directory) throws Exception\n {\n connection.setAutoCommit(true);\n\n //\n // Retrieve meta data about the connection\n //\n DatabaseMetaData dmd = connection.getMetaData();\n\n String[] types =\n {\n \"TABLE\"\n };\n\n FileWriter fw = new FileWriter(directory);\n PrintWriter pw = new PrintWriter(fw);\n\n pw.println(\"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\");\n pw.println();\n pw.println(\"<database>\");\n\n ResultSet tables = dmd.getTables(null, null, null, types);\n while (tables.next() == true)\n {\n processTable(pw, connection, tables.getString(\"TABLE_NAME\"));\n }\n\n pw.println(\"</database>\");\n\n pw.close();\n\n tables.close();\n }" ]
Returns the JMX connector address of a child process. @param p the process to which to connect @param startAgent whether to installed the JMX agent in the target process if not already in place @return a {@link JMXServiceURL} to the process's MBean server
[ "public static JMXServiceURL getLocalConnectorAddress(Process p, boolean startAgent) {\n return getLocalConnectorAddress(Integer.toString(getPid(p)), startAgent);\n }" ]
[ "public static void addIndex(DBCollection collection, String field, boolean asc, boolean background) {\n int dir = (asc) ? 1 : -1;\n collection.createIndex(new BasicDBObject(field, dir), new BasicDBObject(\"background\", background));\n }", "public static String unexpandLine(CharSequence self, int tabStop) {\n StringBuilder builder = new StringBuilder(self.toString());\n int index = 0;\n while (index + tabStop < builder.length()) {\n // cut original string in tabstop-length pieces\n String piece = builder.substring(index, index + tabStop);\n // count trailing whitespace characters\n int count = 0;\n while ((count < tabStop) && (Character.isWhitespace(piece.charAt(tabStop - (count + 1)))))\n count++;\n // replace if whitespace was found\n if (count > 0) {\n piece = piece.substring(0, tabStop - count) + '\\t';\n builder.replace(index, index + tabStop, piece);\n index = index + tabStop - (count - 1);\n } else\n index = index + tabStop;\n }\n return builder.toString();\n }", "private void setFileNotWorldReadablePermissions(File file) {\n file.setReadable(false, false);\n file.setWritable(false, false);\n file.setExecutable(false, false);\n file.setReadable(true, true);\n file.setWritable(true, true);\n }", "@Override\n public void updateStoreDefinition(StoreDefinition storeDef) {\n this.storeDef = storeDef;\n if(storeDef.hasRetentionPeriod())\n this.retentionTimeMs = storeDef.getRetentionDays() * Time.MS_PER_DAY;\n }", "protected void addNeighbor(Queue<ColorPoint> queue, int px, int py, int color, Feature component) {\n if (!inBoundary(px, py, component)) {\n return;\n }\n\n if (!mask.isTouched(px, py)) {\n queue.add(new ColorPoint(px, py, color));\n }\n }", "protected MethodVisitor makeDelegateCall(final String name, final String desc, final String signature, final String[] exceptions, final int accessFlags) {\n MethodVisitor mv = super.visitMethod(accessFlags, name, desc, signature, exceptions);\n mv.visitVarInsn(ALOAD, 0); // load this\n mv.visitFieldInsn(GETFIELD, proxyName, DELEGATE_OBJECT_FIELD, BytecodeHelper.getTypeDescription(delegateClass)); // load delegate\n // using InvokerHelper to allow potential intercepted calls\n int size;\n mv.visitLdcInsn(name); // method name\n Type[] args = Type.getArgumentTypes(desc);\n BytecodeHelper.pushConstant(mv, args.length);\n mv.visitTypeInsn(ANEWARRAY, \"java/lang/Object\");\n size = 6;\n int idx = 1;\n for (int i = 0; i < args.length; i++) {\n Type arg = args[i];\n mv.visitInsn(DUP);\n BytecodeHelper.pushConstant(mv, i);\n // primitive types must be boxed\n if (isPrimitive(arg)) {\n mv.visitIntInsn(getLoadInsn(arg), idx);\n String wrappedType = getWrappedClassDescriptor(arg);\n mv.visitMethodInsn(INVOKESTATIC, wrappedType, \"valueOf\", \"(\" + arg.getDescriptor() + \")L\" + wrappedType + \";\", false);\n } else {\n mv.visitVarInsn(ALOAD, idx); // load argument i\n }\n size = Math.max(size, 5+registerLen(arg));\n idx += registerLen(arg);\n mv.visitInsn(AASTORE); // store value into array\n }\n mv.visitMethodInsn(INVOKESTATIC, \"org/codehaus/groovy/runtime/InvokerHelper\", \"invokeMethod\", \"(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;)Ljava/lang/Object;\", false);\n unwrapResult(mv, desc);\n mv.visitMaxs(size, registerLen(args) + 1);\n\n return mv;\n }", "public TransformersSubRegistration getHostRegistration(final ModelVersionRange range) {\n final PathAddress address = PathAddress.EMPTY_ADDRESS.append(HOST);\n return new TransformersSubRegistrationImpl(range, domain, address);\n }", "public static nsconfig diff(nitro_service client, nsconfig resource) throws Exception {\n\t\tnsconfig diffresource = new nsconfig();\n\t\tdiffresource.config1 = resource.config1;\n\t\tdiffresource.config2 = resource.config2;\n\t\tdiffresource.outtype = resource.outtype;\n\t\tdiffresource.template = resource.template;\n\t\tdiffresource.ignoredevicespecific = resource.ignoredevicespecific;\n\t\treturn (nsconfig)diffresource.perform_operationEx(client,\"diff\");\n\t}", "public T mapRow(ResultSet rs) throws SQLException {\n Map<String, Object> map = new HashMap<String, Object>();\n ResultSetMetaData metadata = rs.getMetaData();\n\n for (int i = 1; i <= metadata.getColumnCount(); ++i) {\n String label = metadata.getColumnLabel(i);\n\n final Object value;\n // calling getObject on a BLOB/CLOB produces weird results\n switch (metadata.getColumnType(i)) {\n case Types.BLOB:\n value = rs.getBytes(i);\n break;\n case Types.CLOB:\n value = rs.getString(i);\n break;\n default:\n value = rs.getObject(i);\n }\n\n // don't use table name extractor because we don't want aliased table name\n boolean overwrite = this.tableName != null && this.tableName.equals(metadata.getTableName(i));\n String tableName = TABLE_NAME_EXTRACTOR.getTableName(metadata, i);\n if (tableName != null && !tableName.isEmpty()) {\n String qualifiedName = tableName + \".\" + metadata.getColumnName(i);\n add(map, qualifiedName, value, overwrite);\n }\n\n add(map, label, value, overwrite);\n }\n\n return objectMapper.convertValue(map, type);\n }" ]
Zeros an inner rectangle inside the matrix. @param A Matrix that is to be modified. @param row0 Start row. @param row1 Stop row+1. @param col0 Start column. @param col1 Stop column+1.
[ "public static void zero( DMatrixSparseCSC A , int row0, int row1, int col0, int col1 ) {\n for (int col = col1-1; col >= col0; col--) {\n int numRemoved = 0;\n\n int idx0 = A.col_idx[col], idx1 = A.col_idx[col+1];\n for (int i = idx0; i < idx1; i++) {\n int row = A.nz_rows[i];\n\n // if sorted a faster technique could be used\n if( row >= row0 && row < row1 ) {\n numRemoved++;\n } else if( numRemoved > 0 ){\n A.nz_rows[i-numRemoved]=row;\n A.nz_values[i-numRemoved]=A.nz_values[i];\n }\n }\n\n if( numRemoved > 0 ) {\n // this could be done more intelligently. Each time a column is adjusted all the columns are adjusted\n // after it. Maybe accumulate the changes in each column and do it in one pass? Need an array to store\n // those results though\n\n for (int i = idx1; i < A.nz_length; i++) {\n A.nz_rows[i - numRemoved] = A.nz_rows[i];\n A.nz_values[i - numRemoved] = A.nz_values[i];\n }\n A.nz_length -= numRemoved;\n\n for (int i = col+1; i <= A.numCols; i++) {\n A.col_idx[i] -= numRemoved;\n }\n }\n }\n }" ]
[ "private void writeAssignmentExtendedAttributes(Project.Assignments.Assignment xml, ResourceAssignment mpx)\n {\n Project.Assignments.Assignment.ExtendedAttribute attrib;\n List<Project.Assignments.Assignment.ExtendedAttribute> extendedAttributes = xml.getExtendedAttribute();\n\n for (AssignmentField mpxFieldID : getAllAssignmentExtendedAttributes())\n {\n Object value = mpx.getCachedValue(mpxFieldID);\n\n if (FieldTypeHelper.valueIsNotDefault(mpxFieldID, value))\n {\n m_extendedAttributesInUse.add(mpxFieldID);\n\n Integer xmlFieldID = Integer.valueOf(MPPAssignmentField.getID(mpxFieldID) | MPPAssignmentField.ASSIGNMENT_FIELD_BASE);\n\n attrib = m_factory.createProjectAssignmentsAssignmentExtendedAttribute();\n extendedAttributes.add(attrib);\n attrib.setFieldID(xmlFieldID.toString());\n attrib.setValue(DatatypeConverter.printExtendedAttribute(this, value, mpxFieldID.getDataType()));\n attrib.setDurationFormat(printExtendedAttributeDurationFormat(value));\n }\n }\n }", "private void clearWaveforms(DeviceAnnouncement announcement) {\n final int player = announcement.getNumber();\n // Iterate over a copy to avoid concurrent modification issues\n for (DeckReference deck : new HashSet<DeckReference>(previewHotCache.keySet())) {\n if (deck.player == player) {\n previewHotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverWaveformPreviewUpdate(player, null); // Inform listeners that preview is gone.\n }\n }\n }\n // Again iterate over a copy to avoid concurrent modification issues\n for (DeckReference deck : new HashSet<DeckReference>(detailHotCache.keySet())) {\n if (deck.player == player) {\n detailHotCache.remove(deck);\n if (deck.hotCue == 0) {\n deliverWaveformDetailUpdate(player, null); // Inform listeners that detail is gone.\n }\n }\n }\n }", "private final void processMainRequest() {\n\n sender = getSender();\n startTimeMillis = System.currentTimeMillis();\n timeoutDuration = Duration.create(\n request.getActorMaxOperationTimeoutSec(), TimeUnit.SECONDS);\n\n actorMaxOperationTimeoutSec = request.getActorMaxOperationTimeoutSec();\n\n if (request.getProtocol() == RequestProtocol.HTTP \n || request.getProtocol() == RequestProtocol.HTTPS) {\n String urlComplete = String.format(\"%s://%s:%d%s\", request\n .getProtocol().toString(), trueTargetNode, request\n .getPort(), request.getResourcePath());\n\n // http://stackoverflow.com/questions/1600291/validating-url-in-java\n if (!PcHttpUtils.isUrlValid(urlComplete.trim())) {\n String errMsg = \"INVALID_URL\";\n logger.error(\"INVALID_URL: \" + urlComplete + \" return..\");\n replyErrors(errMsg, errMsg, PcConstants.NA, PcConstants.NA_INT);\n return;\n } else {\n logger.debug(\"url pass validation: \" + urlComplete);\n }\n\n asyncWorker = getContext().actorOf(\n Props.create(HttpWorker.class, actorMaxOperationTimeoutSec,\n client, urlComplete, request.getHttpMethod(),\n request.getPostData(), request.getHttpHeaderMap(), request.getResponseHeaderMeta()));\n\n } else if (request.getProtocol() == RequestProtocol.SSH ){\n asyncWorker = getContext().actorOf(\n Props.create(SshWorker.class, actorMaxOperationTimeoutSec,\n request.getSshMeta(), trueTargetNode));\n } else if (request.getProtocol() == RequestProtocol.TCP ){\n asyncWorker = getContext().actorOf(\n Props.create(TcpWorker.class, actorMaxOperationTimeoutSec,\n request.getTcpMeta(), trueTargetNode)); \n } else if (request.getProtocol() == RequestProtocol.UDP ){\n asyncWorker = getContext().actorOf(\n Props.create(UdpWorker.class, actorMaxOperationTimeoutSec,\n request.getUdpMeta(), trueTargetNode)); \n } else if (request.getProtocol() == RequestProtocol.PING ){\n asyncWorker = getContext().actorOf(\n Props.create(PingWorker.class, actorMaxOperationTimeoutSec, request.getPingMeta(),\n trueTargetNode));\n }\n\n asyncWorker.tell(RequestWorkerMsgType.PROCESS_REQUEST, getSelf());\n\n cancelExistingIfAnyAndScheduleTimeoutCall();\n\n }", "public void setSizes(Collection<Size> sizes) {\r\n for (Size size : sizes) {\r\n if (size.getLabel() == Size.SMALL) {\r\n smallSize = size;\r\n } else if (size.getLabel() == Size.SQUARE) {\r\n squareSize = size;\r\n } else if (size.getLabel() == Size.THUMB) {\r\n thumbnailSize = size;\r\n } else if (size.getLabel() == Size.MEDIUM) {\r\n mediumSize = size;\r\n } else if (size.getLabel() == Size.LARGE) {\r\n largeSize = size;\r\n } else if (size.getLabel() == Size.LARGE_1600) {\r\n large1600Size = size;\r\n } else if (size.getLabel() == Size.LARGE_2048) {\r\n large2048Size = size;\r\n } else if (size.getLabel() == Size.ORIGINAL) {\r\n originalSize = size;\r\n } else if (size.getLabel() == Size.SQUARE_LARGE) {\r\n squareLargeSize = size;\r\n } else if (size.getLabel() == Size.SMALL_320) {\r\n small320Size = size;\r\n } else if (size.getLabel() == Size.MEDIUM_640) {\r\n medium640Size = size;\r\n } else if (size.getLabel() == Size.MEDIUM_800) {\r\n medium800Size = size;\r\n } else if (size.getLabel() == Size.VIDEO_PLAYER) {\r\n videoPlayer = size;\r\n } else if (size.getLabel() == Size.SITE_MP4) {\r\n siteMP4 = size;\r\n } else if (size.getLabel() == Size.VIDEO_ORIGINAL) {\r\n videoOriginal = size;\r\n }\r\n else if (size.getLabel() == Size.MOBILE_MP4) {\r\n \tmobileMP4 = size;\r\n }\r\n else if (size.getLabel() == Size.HD_MP4) {\r\n \thdMP4 = size;\r\n }\r\n }\r\n }", "private void readAssignmentExtendedAttributes(Project.Assignments.Assignment xml, ResourceAssignment mpx)\n {\n for (Project.Assignments.Assignment.ExtendedAttribute attrib : xml.getExtendedAttribute())\n {\n int xmlFieldID = Integer.parseInt(attrib.getFieldID()) & 0x0000FFFF;\n AssignmentField mpxFieldID = MPPAssignmentField.getInstance(xmlFieldID);\n TimeUnit durationFormat = DatatypeConverter.parseDurationTimeUnits(attrib.getDurationFormat(), null);\n DatatypeConverter.parseExtendedAttribute(m_projectFile, mpx, attrib.getValue(), mpxFieldID, durationFormat);\n }\n }", "public MathTransform calculateLabelTransform(final CoordinateReferenceSystem mapCrs) {\n MathTransform labelTransform;\n if (this.labelProjection != null) {\n try {\n labelTransform = CRS.findMathTransform(mapCrs, this.labelCRS, true);\n } catch (FactoryException e) {\n throw new RuntimeException(e);\n }\n } else {\n labelTransform = IdentityTransform.create(2);\n }\n\n return labelTransform;\n }", "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 }", "private void adjustVisibleColumns() {\n\n if (m_table.isColumnCollapsingAllowed()) {\n if ((m_model.hasDefaultValues()) || m_model.getBundleType().equals(BundleType.DESCRIPTOR)) {\n m_table.setColumnCollapsed(TableProperty.DEFAULT, false);\n } else {\n m_table.setColumnCollapsed(TableProperty.DEFAULT, true);\n }\n\n if (((m_model.getEditMode().equals(EditMode.MASTER) || m_model.hasDescriptionValues()))\n || m_model.getBundleType().equals(BundleType.DESCRIPTOR)) {\n m_table.setColumnCollapsed(TableProperty.DESCRIPTION, false);\n } else {\n m_table.setColumnCollapsed(TableProperty.DESCRIPTION, true);\n }\n }\n }", "private void addIndex(IndexDescriptorDef indexDescDef, TableDef tableDef)\r\n {\r\n IndexDef indexDef = tableDef.getIndex(indexDescDef.getName());\r\n\r\n if (indexDef == null)\r\n {\r\n indexDef = new IndexDef(indexDescDef.getName(),\r\n indexDescDef.getBooleanProperty(PropertyHelper.OJB_PROPERTY_UNIQUE, false));\r\n tableDef.addIndex(indexDef);\r\n }\r\n\r\n try\r\n {\r\n String fieldNames = indexDescDef.getProperty(PropertyHelper.OJB_PROPERTY_FIELDS);\r\n ArrayList fields = ((ClassDescriptorDef)indexDescDef.getOwner()).getFields(fieldNames);\r\n FieldDescriptorDef fieldDef;\r\n\r\n for (Iterator it = fields.iterator(); it.hasNext();)\r\n {\r\n fieldDef = (FieldDescriptorDef)it.next();\r\n indexDef.addColumn(fieldDef.getProperty(PropertyHelper.OJB_PROPERTY_COLUMN));\r\n }\r\n }\r\n catch (NoSuchFieldException ex)\r\n {\r\n // won't happen if we already checked the constraints\r\n }\r\n }" ]
Parses the given Reader for PmdRuleSets. @return The extracted PmdRuleSet - empty in case of problems, never null.
[ "@Override\n public PmdRuleSet create() {\n final SAXBuilder parser = new SAXBuilder();\n final Document dom;\n try {\n dom = parser.build(source);\n } catch (JDOMException | IOException e) {\n if (messages != null) {\n messages.addErrorText(INVALID_INPUT + \" : \" + e.getMessage());\n }\n LOG.error(INVALID_INPUT, e);\n return new PmdRuleSet();\n }\n\n final Element eltResultset = dom.getRootElement();\n final Namespace namespace = eltResultset.getNamespace();\n final PmdRuleSet result = new PmdRuleSet();\n\n final String name = eltResultset.getAttributeValue(\"name\");\n final Element descriptionElement = getChild(eltResultset, namespace);\n\n result.setName(name);\n\n if (descriptionElement != null) {\n result.setDescription(descriptionElement.getValue());\n }\n\n for (Element eltRule : getChildren(eltResultset, \"rule\", namespace)) {\n PmdRule pmdRule = new PmdRule(eltRule.getAttributeValue(\"ref\"));\n pmdRule.setClazz(eltRule.getAttributeValue(\"class\"));\n pmdRule.setName(eltRule.getAttributeValue(\"name\"));\n pmdRule.setMessage(eltRule.getAttributeValue(\"message\"));\n parsePmdPriority(eltRule, pmdRule, namespace);\n parsePmdProperties(eltRule, pmdRule, namespace);\n result.addRule(pmdRule);\n }\n return result;\n }" ]
[ "public static base_responses update(nitro_service client, nsip6 resources[]) throws Exception {\n\t\tbase_responses result = null;\n\t\tif (resources != null && resources.length > 0) {\n\t\t\tnsip6 updateresources[] = new nsip6[resources.length];\n\t\t\tfor (int i=0;i<resources.length;i++){\n\t\t\t\tupdateresources[i] = new nsip6();\n\t\t\t\tupdateresources[i].ipv6address = resources[i].ipv6address;\n\t\t\t\tupdateresources[i].td = resources[i].td;\n\t\t\t\tupdateresources[i].nd = resources[i].nd;\n\t\t\t\tupdateresources[i].icmp = resources[i].icmp;\n\t\t\t\tupdateresources[i].vserver = resources[i].vserver;\n\t\t\t\tupdateresources[i].telnet = resources[i].telnet;\n\t\t\t\tupdateresources[i].ftp = resources[i].ftp;\n\t\t\t\tupdateresources[i].gui = resources[i].gui;\n\t\t\t\tupdateresources[i].ssh = resources[i].ssh;\n\t\t\t\tupdateresources[i].snmp = resources[i].snmp;\n\t\t\t\tupdateresources[i].mgmtaccess = resources[i].mgmtaccess;\n\t\t\t\tupdateresources[i].restrictaccess = resources[i].restrictaccess;\n\t\t\t\tupdateresources[i].state = resources[i].state;\n\t\t\t\tupdateresources[i].map = resources[i].map;\n\t\t\t\tupdateresources[i].dynamicrouting = resources[i].dynamicrouting;\n\t\t\t\tupdateresources[i].hostroute = resources[i].hostroute;\n\t\t\t\tupdateresources[i].ip6hostrtgw = resources[i].ip6hostrtgw;\n\t\t\t\tupdateresources[i].metric = resources[i].metric;\n\t\t\t\tupdateresources[i].vserverrhilevel = resources[i].vserverrhilevel;\n\t\t\t\tupdateresources[i].ospf6lsatype = resources[i].ospf6lsatype;\n\t\t\t\tupdateresources[i].ospfarea = resources[i].ospfarea;\n\t\t\t}\n\t\t\tresult = update_bulk_request(client, updateresources);\n\t\t}\n\t\treturn result;\n\t}", "public static StringBuffer leftShift(String self, Object value) {\n return new StringBuffer(self).append(value);\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 ApiClient setHttpClient(OkHttpClient newHttpClient) {\n if (!httpClient.equals(newHttpClient)) {\n newHttpClient.networkInterceptors().addAll(httpClient.networkInterceptors());\n httpClient.networkInterceptors().clear();\n newHttpClient.interceptors().addAll(httpClient.interceptors());\n httpClient.interceptors().clear();\n this.httpClient = newHttpClient;\n }\n return this;\n }", "private boolean initRequestHandler(SelectionKey selectionKey) {\n ByteBuffer inputBuffer = inputStream.getBuffer();\n int remaining = inputBuffer.remaining();\n\n // Don't have enough bytes to determine the protocol yet...\n if(remaining < 3)\n return true;\n\n byte[] protoBytes = { inputBuffer.get(0), inputBuffer.get(1), inputBuffer.get(2) };\n\n try {\n String proto = ByteUtils.getString(protoBytes, \"UTF-8\");\n inputBuffer.clear();\n RequestFormatType requestFormatType = RequestFormatType.fromCode(proto);\n requestHandler = requestHandlerFactory.getRequestHandler(requestFormatType);\n\n if(logger.isInfoEnabled())\n logger.info(\"Protocol negotiated for \" + socketChannel.socket() + \": \"\n + requestFormatType.getDisplayName());\n\n // The protocol negotiation is the first request, so respond by\n // sticking the bytes in the output buffer, signaling the Selector,\n // and returning false to denote no further processing is needed.\n outputStream.getBuffer().put(ByteUtils.getBytes(\"ok\", \"UTF-8\"));\n prepForWrite(selectionKey);\n\n return false;\n } catch(IllegalArgumentException e) {\n // okay we got some nonsense. For backwards compatibility,\n // assume this is an old client who does not know how to negotiate\n RequestFormatType requestFormatType = RequestFormatType.VOLDEMORT_V0;\n requestHandler = requestHandlerFactory.getRequestHandler(requestFormatType);\n\n if(logger.isInfoEnabled())\n logger.info(\"No protocol proposal given for \" + socketChannel.socket()\n + \", assuming \" + requestFormatType.getDisplayName());\n\n return true;\n }\n }", "public static void scale(GVRMesh mesh, float x, float y, float z) {\n final float [] vertices = mesh.getVertices();\n final int vsize = vertices.length;\n\n for (int i = 0; i < vsize; i += 3) {\n vertices[i] *= x;\n vertices[i + 1] *= y;\n vertices[i + 2] *= z;\n }\n\n mesh.setVertices(vertices);\n }", "private void addObjectReferenceEdges(Vertex vertex, ObjectReferenceDescriptor rds)\r\n {\r\n Object refObject = rds.getPersistentField().get(vertex.getEnvelope().getRealObject());\r\n Class refClass = rds.getItemClass();\r\n for (int i = 0; i < vertices.length; i++)\r\n {\r\n Edge edge = null;\r\n // ObjectEnvelope envelope = vertex.getEnvelope();\r\n Vertex refVertex = vertices[i];\r\n ObjectEnvelope refEnvelope = refVertex.getEnvelope();\r\n if (refObject == refEnvelope.getRealObject())\r\n {\r\n edge = buildConcrete11Edge(vertex, refVertex, rds.hasConstraint());\r\n }\r\n else if (refClass.isInstance(refVertex.getEnvelope().getRealObject()))\r\n {\r\n edge = buildPotential11Edge(vertex, refVertex, rds.hasConstraint());\r\n }\r\n if (edge != null)\r\n {\r\n if (!edgeList.contains(edge))\r\n {\r\n edgeList.add(edge);\r\n }\r\n else\r\n {\r\n edge.increaseWeightTo(edge.getWeight());\r\n }\r\n }\r\n }\r\n }", "public BsonDocument toBsonDocument() {\n final BsonDocument updateDescDoc = new BsonDocument();\n updateDescDoc.put(\n Fields.UPDATED_FIELDS_FIELD,\n this.getUpdatedFields());\n\n final BsonArray removedFields = new BsonArray();\n for (final String field : this.getRemovedFields()) {\n removedFields.add(new BsonString(field));\n }\n updateDescDoc.put(\n Fields.REMOVED_FIELDS_FIELD,\n removedFields);\n\n return updateDescDoc;\n }", "protected void closeServerSocket() {\n // Close server socket, we do not accept new requests anymore.\n // This also terminates the server thread if blocking on socket.accept.\n if (null != serverSocket) {\n try {\n if (!serverSocket.isClosed()) {\n serverSocket.close();\n if (log.isTraceEnabled()) {\n log.trace(\"Closed server socket \" + serverSocket + \"/ref=\"\n + Integer.toHexString(System.identityHashCode(serverSocket))\n + \" for \" + getName());\n }\n }\n } catch (IOException e) {\n throw new IllegalStateException(\"Failed to successfully quit server \" + getName(), e);\n }\n }\n }" ]
Use this API to fetch all the nsip6 resources that are configured on netscaler.
[ "public static nsip6[] get(nitro_service service) throws Exception{\n\t\tnsip6 obj = new nsip6();\n\t\tnsip6[] response = (nsip6[])obj.get_resources(service);\n\t\treturn response;\n\t}" ]
[ "private void initDescriptor() throws CmsXmlException, CmsException {\n\n if (m_bundleType.equals(CmsMessageBundleEditorTypes.BundleType.DESCRIPTOR)) {\n m_desc = m_resource;\n } else {\n //First try to read from same folder like resource, if it fails use CmsMessageBundleEditorTypes.getDescriptor()\n try {\n m_desc = m_cms.readResource(m_sitepath + m_basename + CmsMessageBundleEditorTypes.Descriptor.POSTFIX);\n } catch (CmsVfsResourceNotFoundException e) {\n m_desc = CmsMessageBundleEditorTypes.getDescriptor(m_cms, m_basename);\n }\n }\n unmarshalDescriptor();\n\n }", "public List<ProjectListType.Project> getProject()\n {\n if (project == null)\n {\n project = new ArrayList<ProjectListType.Project>();\n }\n return this.project;\n }", "void close(Supplier<CentralDogmaException> failureCauseSupplier) {\n requireNonNull(failureCauseSupplier, \"failureCauseSupplier\");\n if (closePending.compareAndSet(null, failureCauseSupplier)) {\n repositoryWorker.execute(() -> {\n rwLock.writeLock().lock();\n try {\n if (commitIdDatabase != null) {\n try {\n commitIdDatabase.close();\n } catch (Exception e) {\n logger.warn(\"Failed to close a commitId database:\", e);\n }\n }\n\n if (jGitRepository != null) {\n try {\n jGitRepository.close();\n } catch (Exception e) {\n logger.warn(\"Failed to close a Git repository: {}\",\n jGitRepository.getDirectory(), e);\n }\n }\n } finally {\n rwLock.writeLock().unlock();\n commitWatchers.close(failureCauseSupplier);\n closeFuture.complete(null);\n }\n });\n }\n\n closeFuture.join();\n }", "public String[] getAttributeNames()\r\n {\r\n Set keys = (attributeMap == null ? new HashSet() : attributeMap.keySet());\r\n String[] result = new String[keys.size()];\r\n\r\n keys.toArray(result);\r\n return result;\r\n }", "public double getCouponPayment(int periodIndex, AnalyticModel model) {\n\n\t\tForwardCurve forwardCurve = model.getForwardCurve(forwardCurveName);\n\t\tif(forwardCurve == null && forwardCurveName != null && forwardCurveName.length() > 0) {\n\t\t\tthrow new IllegalArgumentException(\"No forward curve with name '\" + forwardCurveName + \"' was found in the model:\\n\" + model.toString());\n\t\t}\n\n\t\tdouble periodLength\t= schedule.getPeriodLength(periodIndex);\n\t\tdouble couponPayment=fixedCoupon ;\n\t\tif(forwardCurve != null ) {\n\t\t\tcouponPayment = floatingSpread+forwardCurve.getForward(model, schedule.getFixing(periodIndex));\n\t\t}\n\t\treturn couponPayment*periodLength;\n\t}", "public boolean hasNodeWithId(int nodeId) {\n Node node = nodesById.get(nodeId);\n if(node == null) {\n return false;\n }\n return true;\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 T[] toArray(T[] tArray) {\n List<T> array = new ArrayList<T>(100);\n for (Iterator<T> it = iterator(); it.hasNext();) {\n T val = it.next();\n if (val != null) array.add(val);\n }\n return array.toArray(tArray);\n }", "public static SpinXmlElement XML(Object input) {\n return SpinFactory.INSTANCE.createSpin(input, DataFormats.xml());\n }" ]
Detaches or removes the value from this context. @param key the key to the attachment. @param <V> the value type of the attachment. @return the attachment if found otherwise {@code null}.
[ "public <V> V detach(final AttachmentKey<V> key) {\n assert key != null;\n return key.cast(contextAttachments.remove(key));\n }" ]
[ "private boolean contentEqualsUnchecked(byte[] bytes, int offset, int len) {\n if (length != len) {\n return false;\n }\n\n return compareToUnchecked(bytes, offset, len) == 0;\n }", "public void recordCheckoutTimeUs(SocketDestination dest, long checkoutTimeUs) {\n if(dest != null) {\n getOrCreateNodeStats(dest).recordCheckoutTimeUs(null, checkoutTimeUs);\n recordCheckoutTimeUs(null, checkoutTimeUs);\n } else {\n this.checkoutTimeRequestCounter.addRequest(checkoutTimeUs * Time.NS_PER_US);\n }\n }", "public Widget findChildByName(final String name) {\n final List<Widget> groups = new ArrayList<>();\n groups.add(this);\n\n return findChildByNameInAllGroups(name, groups);\n }", "protected Collection provideStateManagers(Collection pojos)\r\n {\r\n \tPersistenceCapable pc;\r\n \tint [] fieldNums;\r\n \tIterator iter = pojos.iterator();\r\n \tCollection result = new ArrayList();\r\n \t\r\n \twhile (iter.hasNext())\r\n \t{\r\n \t\t// obtain a StateManager\r\n \t\tpc = (PersistenceCapable) iter.next();\r\n \t\tIdentity oid = new Identity(pc, broker);\r\n \t\tStateManagerInternal smi = pmi.getStateManager(oid, pc.getClass()); \r\n \t\t\r\n \t\t// fetch attributes into StateManager\r\n\t\t\tJDOClass jdoClass = Helper.getJDOClass(pc.getClass());\r\n\t\t\tfieldNums = jdoClass.getManagedFieldNumbers();\r\n\r\n\t\t\tFieldManager fm = new OjbFieldManager(pc, broker);\r\n\t\t\tsmi.replaceFields(fieldNums, fm);\r\n\t\t\tsmi.retrieve();\r\n\t\t\t\r\n\t\t\t// get JDO PersistencecCapable instance from SM and add it to result collection\r\n\t\t\tObject instance = smi.getObject();\r\n\t\t\tresult.add(instance);\r\n \t}\r\n \treturn result; \r\n\t}", "@UiThread\n public int getParentAdapterPosition() {\n int flatPosition = getAdapterPosition();\n if (flatPosition == RecyclerView.NO_POSITION) {\n return flatPosition;\n }\n\n return mExpandableAdapter.getNearestParentPosition(flatPosition);\n }", "private void addListeners(ProjectReader reader)\n {\n if (m_projectListeners != null)\n {\n for (ProjectListener listener : m_projectListeners)\n {\n reader.addProjectListener(listener);\n }\n }\n }", "protected Object getObjectFromResultSet() throws PersistenceBrokerException\r\n {\r\n\r\n try\r\n {\r\n // if all primitive attributes of the object are contained in the ResultSet\r\n // the fast direct mapping can be used\r\n return super.getObjectFromResultSet();\r\n }\r\n // if the full loading failed we assume that at least PK attributes are contained\r\n // in the ResultSet and perform a slower Identity based loading...\r\n // This may of course also fail and can throw another PersistenceBrokerException\r\n catch (PersistenceBrokerException e)\r\n {\r\n Identity oid = getIdentityFromResultSet();\r\n return getBroker().getObjectByIdentity(oid);\r\n }\r\n\r\n }", "public String updateClassification(String classificationType) {\n Metadata metadata = new Metadata(\"enterprise\", Metadata.CLASSIFICATION_TEMPLATE_KEY);\n metadata.add(\"/Box__Security__Classification__Key\", classificationType);\n Metadata classification = this.updateMetadata(metadata);\n\n return classification.getString(Metadata.CLASSIFICATION_KEY);\n }", "public Iterator select(String predicate) throws org.odmg.QueryInvalidException\r\n {\r\n return this.query(predicate).iterator();\r\n }" ]
Returns the compact task records for all tasks with the given tag. @param tag The tag in which to search for tasks. @return Request object
[ "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 }" ]
[ "private int decode(Huffman h) throws IOException\n {\n int len; /* current number of bits in code */\n int code; /* len bits being decoded */\n int first; /* first code of length len */\n int count; /* number of codes of length len */\n int index; /* index of first code of length len in symbol table */\n int bitbuf; /* bits from stream */\n int left; /* bits left in next or left to process */\n //short *next; /* next number of codes */\n\n bitbuf = m_bitbuf;\n left = m_bitcnt;\n code = first = index = 0;\n len = 1;\n int nextIndex = 1; // next = h->count + 1;\n while (true)\n {\n while (left-- != 0)\n {\n code |= (bitbuf & 1) ^ 1; /* invert code */\n bitbuf >>= 1;\n //count = *next++;\n count = h.m_count[nextIndex++];\n if (code < first + count)\n { /* if length len, return symbol */\n m_bitbuf = bitbuf;\n m_bitcnt = (m_bitcnt - len) & 7;\n return h.m_symbol[index + (code - first)];\n }\n index += count; /* else update for next length */\n first += count;\n first <<= 1;\n code <<= 1;\n len++;\n }\n left = (MAXBITS + 1) - len;\n if (left == 0)\n {\n break;\n }\n if (m_left == 0)\n {\n m_in = m_input.read();\n m_left = m_in == -1 ? 0 : 1;\n if (m_left == 0)\n {\n throw new IOException(\"out of input\"); /* out of input */\n }\n }\n bitbuf = m_in;\n m_left--;\n if (left > 8)\n {\n left = 8;\n }\n }\n return -9; /* ran out of codes */\n }", "private String generatedBuilderSimpleName(TypeElement type) {\n String packageName = elements.getPackageOf(type).getQualifiedName().toString();\n String originalName = type.getQualifiedName().toString();\n checkState(originalName.startsWith(packageName + \".\"));\n String nameWithoutPackage = originalName.substring(packageName.length() + 1);\n return String.format(BUILDER_SIMPLE_NAME_TEMPLATE, nameWithoutPackage.replaceAll(\"\\\\.\", \"_\"));\n }", "private String escapeText(StringBuilder sb, String text)\n {\n int length = text.length();\n char c;\n\n sb.setLength(0);\n\n for (int loop = 0; loop < length; loop++)\n {\n c = text.charAt(loop);\n\n switch (c)\n {\n case '<':\n {\n sb.append(\"&lt;\");\n break;\n }\n\n case '>':\n {\n sb.append(\"&gt;\");\n break;\n }\n\n case '&':\n {\n sb.append(\"&amp;\");\n break;\n }\n\n default:\n {\n if (validXMLCharacter(c))\n {\n if (c > 127)\n {\n sb.append(\"&#\" + (int) c + \";\");\n }\n else\n {\n sb.append(c);\n }\n }\n\n break;\n }\n }\n }\n\n return (sb.toString());\n }", "private void addEntriesFromTag(List<Entry> entries, RekordboxAnlz.CueTag tag) {\n for (RekordboxAnlz.CueEntry cueEntry : tag.cues()) { // TODO: Need to figure out how to identify deleted entries to ignore.\n if (cueEntry.type() == RekordboxAnlz.CueEntryType.LOOP) {\n entries.add(new Entry((int)cueEntry.hotCue(), Util.timeToHalfFrame(cueEntry.time()),\n Util.timeToHalfFrame(cueEntry.loopTime())));\n } else {\n entries.add(new Entry((int)cueEntry.hotCue(), Util.timeToHalfFrame(cueEntry.time())));\n }\n }\n }", "private Statement createStatement(Connection con, boolean scrollable, int explicitFetchSizeHint)\r\n throws java.sql.SQLException\r\n {\r\n Statement result;\r\n try\r\n {\r\n // if necessary use JDBC1.0 methods\r\n if (!FORCEJDBC1_0)\r\n {\r\n result =\r\n con.createStatement(\r\n scrollable\r\n ? ResultSet.TYPE_SCROLL_INSENSITIVE\r\n : ResultSet.TYPE_FORWARD_ONLY,\r\n ResultSet.CONCUR_READ_ONLY);\r\n afterJdbc2CapableStatementCreate(result, explicitFetchSizeHint);\r\n }\r\n else\r\n {\r\n result = con.createStatement();\r\n }\r\n }\r\n catch (AbstractMethodError err)\r\n {\r\n // if a JDBC1.0 driver is used, the signature\r\n // createStatement(int, int) is not defined.\r\n // we then call the JDBC1.0 variant createStatement()\r\n log.warn(\"Used driver seems not JDBC 2.0 compatible, use the JDBC 1.0 mode\", err);\r\n result = con.createStatement();\r\n FORCEJDBC1_0 = true;\r\n }\r\n catch (SQLException eSql)\r\n {\r\n // there are JDBC Driver that nominally implement JDBC 2.0, but\r\n // throw DriverNotCapableExceptions. If we catch one of these\r\n // we force usage of JDBC 1.0\r\n if (eSql.getClass().getName()\r\n .equals(\"interbase.interclient.DriverNotCapableException\"))\r\n {\r\n log.warn(\"JDBC 2.0 problems with this interbase driver, we use the JDBC 1.0 mode\");\r\n FORCEJDBC1_0 = true;\r\n result = con.createStatement();\r\n }\r\n else\r\n {\r\n throw eSql;\r\n }\r\n }\r\n try\r\n {\r\n platform.afterStatementCreate(result);\r\n }\r\n catch (PlatformException e)\r\n {\r\n log.error(\"Platform dependend failure\", e);\r\n }\r\n return result;\r\n }", "public void serializeTimingData(Path outputPath)\n {\n //merge subThreads instances into the main instance\n merge();\n\n try (FileWriter fw = new FileWriter(outputPath.toFile()))\n {\n fw.write(\"Number Of Executions, Total Milliseconds, Milliseconds per execution, Type\\n\");\n for (Map.Entry<String, TimingData> timing : executionInfo.entrySet())\n {\n TimingData data = timing.getValue();\n long totalMillis = (data.totalNanos / 1000000);\n double millisPerExecution = (double) totalMillis / (double) data.numberOfExecutions;\n fw.write(String.format(\"%6d, %6d, %8.2f, %s\\n\",\n data.numberOfExecutions, totalMillis, millisPerExecution,\n StringEscapeUtils.escapeCsv(timing.getKey())\n ));\n }\n }\n catch (Exception e)\n {\n e.printStackTrace();\n }\n }", "private long getTotalTime(ProjectCalendarDateRanges exception, Date date, boolean after)\n {\n long currentTime = DateHelper.getCanonicalTime(date).getTime();\n long total = 0;\n for (DateRange range : exception)\n {\n total += getTime(range.getStart(), range.getEnd(), currentTime, after);\n }\n return (total);\n }", "public String getBaselineDurationText()\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 String))\n {\n result = null;\n }\n return (String) result;\n }", "public static LayersConfig getLayersConfig(final File repoRoot) throws IOException {\n final File layersList = new File(repoRoot, LAYERS_CONF);\n if (!layersList.exists()) {\n return new LayersConfig();\n }\n final Properties properties = PatchUtils.loadProperties(layersList);\n return new LayersConfig(properties);\n }" ]