idx int32 46 1.86M | input stringlengths 321 6.6k | target stringlengths 9 1.24k |
|---|---|---|
893,540 | public void onClick(View v) {<NEW_LINE>final Context context = v.getContext();<NEW_LINE>if (v == developer) {<NEW_LINE>// open dev settings<NEW_LINE>Intent devIntent = new Intent(Settings.ACTION_APPLICATION_DEVELOPMENT_SETTINGS);<NEW_LINE>devIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);<NEW_LINE>ResolveInfo resolveInfo = context.getPackageManager().resolveActivity(devIntent, 0);<NEW_LINE>if (resolveInfo != null) {<NEW_LINE>context.startActivity(devIntent);<NEW_LINE>} else {<NEW_LINE>Toast.makeText(context, "Developer settings not available on device", Toast.LENGTH_SHORT).show();<NEW_LINE>}<NEW_LINE>} else if (v == battery) {<NEW_LINE>// try to find an app to handle battery settings<NEW_LINE>Intent batteryIntent = new Intent(Intent.ACTION_POWER_USAGE_SUMMARY);<NEW_LINE>batteryIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);<NEW_LINE>ResolveInfo resolveInfo = context.getPackageManager().resolveActivity(batteryIntent, 0);<NEW_LINE>if (resolveInfo != null) {<NEW_LINE>context.startActivity(batteryIntent);<NEW_LINE>} else {<NEW_LINE>Toast.makeText(context, "No app found to handle power usage intent", <MASK><NEW_LINE>}<NEW_LINE>} else if (v == settings) {<NEW_LINE>// open android settings<NEW_LINE>Intent settingsIntent = new Intent(Settings.ACTION_SETTINGS);<NEW_LINE>settingsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);<NEW_LINE>context.startActivity(settingsIntent);<NEW_LINE>} else if (v == info) {<NEW_LINE>Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);<NEW_LINE>intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);<NEW_LINE>intent.setData(Uri.parse("package:" + context.getPackageName()));<NEW_LINE>context.startActivity(intent);<NEW_LINE>} else if (v == uninstall) {<NEW_LINE>// open dialog to uninstall app<NEW_LINE>Uri packageURI = Uri.parse("package:" + context.getPackageName());<NEW_LINE>Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);<NEW_LINE>context.startActivity(uninstallIntent);<NEW_LINE>} else if (v == location) {<NEW_LINE>Intent locationIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);<NEW_LINE>locationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);<NEW_LINE>context.startActivity(locationIntent);<NEW_LINE>}<NEW_LINE>} | Toast.LENGTH_SHORT).show(); |
967,659 | // TODO unify this method with `runWithPartitionScan`<NEW_LINE>private void runWithPartitionScanForNative() {<NEW_LINE>// if we reach here, it means we didn't manage to leverage index and we fall-back to full-partition scan<NEW_LINE>int totalEntryCount = recordStore.size();<NEW_LINE>responses = new MapEntries(totalEntryCount);<NEW_LINE>Queue<Object> outComes = new LinkedList<>();<NEW_LINE>operator = operator(this, entryProcessor, getPredicate());<NEW_LINE>recordStore.forEach((key, record) -> {<NEW_LINE>Data dataKey = toHeapData(key);<NEW_LINE>Data response = operator.operateOnKey(dataKey).getResult();<NEW_LINE>if (response != null) {<NEW_LINE>responses.add(dataKey, response);<NEW_LINE>}<NEW_LINE>EntryEventType eventType = operator.getEventType();<NEW_LINE>if (eventType != null) {<NEW_LINE>outComes.add(dataKey);<NEW_LINE>outComes.add(operator.getOldValue());<NEW_LINE>outComes.add(operator.getByPreferringDataNewValue());<NEW_LINE>outComes.add(eventType);<NEW_LINE>outComes.add(operator.getEntry().getNewTtl());<NEW_LINE>}<NEW_LINE>}, false);<NEW_LINE>// This iteration is needed to work around an issue<NEW_LINE>// related with binary elastic hash map (BEHM). Removal<NEW_LINE>// via map#remove() while iterating on BEHM distorts<NEW_LINE>// it and we can see some entries remain in the map<NEW_LINE>// even we know that iteration is finished. Because<NEW_LINE>// in this case, iteration can miss some entries.<NEW_LINE>while (!outComes.isEmpty()) {<NEW_LINE>Data dataKey = (Data) outComes.poll();<NEW_LINE>Object oldValue = outComes.poll();<NEW_LINE>Object newValue = outComes.poll();<NEW_LINE>EntryEventType eventType = (EntryEventType) outComes.poll();<NEW_LINE>long newTtl = (long) outComes.poll();<NEW_LINE>operator.init(dataKey, oldValue, newValue, null, eventType, <MASK><NEW_LINE>}<NEW_LINE>} | null, newTtl).doPostOperateOps(); |
228,045 | public DatabaseSet adapt(DatabaseSet original) {<NEW_LINE>if (connectionStrings == null || connectionStrings.isEmpty())<NEW_LINE>return original;<NEW_LINE>if (original instanceof DefaultDatabaseSet) {<NEW_LINE>try {<NEW_LINE>boolean dbShardingDisabled = true;<NEW_LINE>boolean tableShardingDisabled = true;<NEW_LINE>String masterConnUrl = null;<NEW_LINE>String slaveConnUrl = null;<NEW_LINE>for (DataBase db : original.getDatabases().values()) {<NEW_LINE>String databaseKey = db.getConnectionString().toLowerCase();<NEW_LINE>DalConnectionString connStr = connectionStrings.get(databaseKey);<NEW_LINE>String connUrl = connStr.getIPConnectionStringConfigure().getConnectionUrl();<NEW_LINE>if (db.isMaster()) {<NEW_LINE>dbShardingDisabled &= !checkMultiHosts(connUrl, masterConnUrl);<NEW_LINE>masterConnUrl = connUrl;<NEW_LINE>} else {<NEW_LINE>dbShardingDisabled &= !checkMultiHosts(connUrl, slaveConnUrl);<NEW_LINE>slaveConnUrl = connUrl;<NEW_LINE>}<NEW_LINE>if (connStr instanceof DalLocalConnectionString)<NEW_LINE>tableShardingDisabled &= ((DalLocalConnectionString) connStr).tableShardingDisabled();<NEW_LINE>else<NEW_LINE>return original;<NEW_LINE>}<NEW_LINE>String msg = String.format("DatabaseSet '%s' adapted to LocalDatabaseSet", original.getName());<NEW_LINE>if (tableShardingDisabled)<NEW_LINE>msg += ", tableSharding is disabled";<NEW_LINE>LOGGER.info(msg);<NEW_LINE>return new LocalDefaultDatabaseSet((DefaultDatabaseSet) original, dbShardingDisabled, tableShardingDisabled);<NEW_LINE>} catch (Throwable t) {<NEW_LINE><MASK><NEW_LINE>}<NEW_LINE>}<NEW_LINE>return original;<NEW_LINE>} | LOGGER.warn("Adapt DefaultDatabaseSet to LocalDefaultDatabaseSet exception", t); |
1,426,642 | public static <T> T clone(T object) throws CloneNotSupportedException {<NEW_LINE>if (object == null) {<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>if (object instanceof PublicCloneable) {<NEW_LINE>PublicCloneable pc = (PublicCloneable) object;<NEW_LINE>return <MASK><NEW_LINE>} else {<NEW_LINE>try {<NEW_LINE>Method method = object.getClass().getMethod("clone", (Class[]) null);<NEW_LINE>if (Modifier.isPublic(method.getModifiers())) {<NEW_LINE>return (T) method.invoke(object, (Object[]) null);<NEW_LINE>}<NEW_LINE>} catch (NoSuchMethodException e) {<NEW_LINE>throw new CloneNotSupportedException("Object without clone() method is impossible.");<NEW_LINE>} catch (IllegalAccessException e) {<NEW_LINE>throw new CloneNotSupportedException("Object.clone(): unable to call method.");<NEW_LINE>} catch (InvocationTargetException e) {<NEW_LINE>throw new CloneNotSupportedException("Object without clone() method is impossible.");<NEW_LINE>}<NEW_LINE>}<NEW_LINE>throw new CloneNotSupportedException("Failed to clone.");<NEW_LINE>} | (T) pc.clone(); |
1,284,976 | private static int exportAttachment(@NonNull AttachmentSecret attachmentSecret, @NonNull Cursor cursor, @NonNull BackupFrameOutputStream outputStream, int count, long estimatedCount) {<NEW_LINE>try {<NEW_LINE>long rowId = cursor.getLong(cursor.getColumnIndexOrThrow(AttachmentDatabase.ROW_ID));<NEW_LINE>long uniqueId = cursor.getLong(cursor.getColumnIndexOrThrow(AttachmentDatabase.UNIQUE_ID));<NEW_LINE>long size = cursor.getLong(cursor.getColumnIndexOrThrow(AttachmentDatabase.SIZE));<NEW_LINE>String data = cursor.getString(cursor.getColumnIndexOrThrow(AttachmentDatabase.DATA));<NEW_LINE>byte[] random = cursor.getBlob(cursor.getColumnIndexOrThrow(AttachmentDatabase.DATA_RANDOM));<NEW_LINE>if (!TextUtils.isEmpty(data) && size > 0) {<NEW_LINE>InputStream inputStream;<NEW_LINE>inputStream = ModernDecryptingPartInputStream.createFor(attachmentSecret, random, new File(data), 0);<NEW_LINE>EventBus.getDefault().post(new BackupEvent(BackupEvent.Type.PROGRESS, ++count, estimatedCount));<NEW_LINE>outputStream.write(new AttachmentId(rowId<MASK><NEW_LINE>}<NEW_LINE>} catch (IOException e) {<NEW_LINE>Log.w(TAG, e);<NEW_LINE>}<NEW_LINE>return count;<NEW_LINE>} | , uniqueId), inputStream, size); |
1,696,956 | private static void parseAssertions(Element element, AnnotationMirror mirror, TypeElement type, LibraryData model) {<NEW_LINE>TypeMirror assertions = ElementUtils.getAnnotationValue(TypeMirror.<MASK><NEW_LINE>if (assertions != null) {<NEW_LINE>AnnotationValue value = ElementUtils.getAnnotationValue(mirror, "assertions");<NEW_LINE>TypeElement assertionsType = ElementUtils.castTypeElement(assertions);<NEW_LINE>if (assertionsType.getModifiers().contains(Modifier.ABSTRACT)) {<NEW_LINE>model.addError(value, "Assertions type must not be abstract.");<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>if (!ElementUtils.isVisible(element, assertionsType)) {<NEW_LINE>model.addError(value, "Assertions type must be visible.");<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>if (!ElementUtils.isAssignable(assertions, type.asType())) {<NEW_LINE>model.addError(value, "Assertions type must be a subclass of the library type '%s'.", ElementUtils.getSimpleName(model.getTemplateType()));<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>ExecutableElement foundConstructor = null;<NEW_LINE>for (ExecutableElement constructor : ElementFilter.constructorsIn(assertionsType.getEnclosedElements())) {<NEW_LINE>if (constructor.getParameters().size() == 1) {<NEW_LINE>if (ElementUtils.typeEquals(constructor.getParameters().get(0).asType(), model.getTemplateType().asType())) {<NEW_LINE>foundConstructor = constructor;<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (foundConstructor == null) {<NEW_LINE>model.addError(value, "No constructor with single delegate parameter of type %s found.", ElementUtils.getSimpleName(model.getTemplateType()));<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>if (!ElementUtils.isVisible(model.getTemplateType(), foundConstructor)) {<NEW_LINE>model.addError(value, "Assertions constructor is not visible.");<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>model.setAssertions(assertions);<NEW_LINE>}<NEW_LINE>} | class, mirror, "assertions", false); |
685,480 | public void claimJob(final ClaimJobRequest request, final StreamObserver<ClaimJobResponse> responseObserver) {<NEW_LINE>final Set<Tag> tags = Sets.newHashSet();<NEW_LINE>final long start = System.nanoTime();<NEW_LINE>try {<NEW_LINE>final String id = request.getId();<NEW_LINE>final AgentClientMetadata clientMetadata = jobServiceProtoConverter.toAgentClientMetadataDto(request.getAgentMetadata());<NEW_LINE>tags.add(Tag.of(AGENT_VERSION_TAG, clientMetadata.getVersion().orElse(UNKNOWN_VERSION)));<NEW_LINE>this.agentJobService.claimJob(id, clientMetadata);<NEW_LINE>responseObserver.onNext(ClaimJobResponse.newBuilder().setSuccessful(true).build());<NEW_LINE>MetricsUtils.addSuccessTags(tags);<NEW_LINE>} catch (final Exception e) {<NEW_LINE>log.error("Error claiming job for request " + request, e);<NEW_LINE>MetricsUtils.addFailureTagsWithException(tags, e);<NEW_LINE>responseObserver.onNext(this.protoErrorComposer.toProtoClaimJobResponse(e));<NEW_LINE>} finally {<NEW_LINE>meterRegistry.timer(CLAIM_TIMER, tags).record(System.nanoTime(<MASK><NEW_LINE>}<NEW_LINE>responseObserver.onCompleted();<NEW_LINE>} | ) - start, TimeUnit.NANOSECONDS); |
1,240,218 | public com.amazonaws.services.managedgrafana.model.ThrottlingException unmarshallFromContext(JsonUnmarshallerContext context) throws Exception {<NEW_LINE>com.amazonaws.services.managedgrafana.model.ThrottlingException throttlingException = new com.amazonaws.services.managedgrafana.model.ThrottlingException(null);<NEW_LINE>if (context.isStartOfDocument()) {<NEW_LINE>if (context.getHeader("Retry-After") != null) {<NEW_LINE>context.setCurrentHeader("Retry-After");<NEW_LINE>throttlingException.setRetryAfterSeconds(context.getUnmarshaller(Integer.class).unmarshall(context));<NEW_LINE>}<NEW_LINE>}<NEW_LINE><MASK><NEW_LINE>String currentParentElement = context.getCurrentParentElement();<NEW_LINE>int targetDepth = originalDepth + 1;<NEW_LINE>JsonToken token = context.getCurrentToken();<NEW_LINE>if (token == null)<NEW_LINE>token = context.nextToken();<NEW_LINE>if (token == VALUE_NULL) {<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>while (true) {<NEW_LINE>if (token == null)<NEW_LINE>break;<NEW_LINE>if (token == FIELD_NAME || token == START_OBJECT) {<NEW_LINE>if (context.testExpression("quotaCode", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>throttlingException.setQuotaCode(context.getUnmarshaller(String.class).unmarshall(context));<NEW_LINE>}<NEW_LINE>if (context.testExpression("serviceCode", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>throttlingException.setServiceCode(context.getUnmarshaller(String.class).unmarshall(context));<NEW_LINE>}<NEW_LINE>} else if (token == END_ARRAY || token == END_OBJECT) {<NEW_LINE>if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {<NEW_LINE>if (context.getCurrentDepth() <= originalDepth)<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>token = context.nextToken();<NEW_LINE>}<NEW_LINE>return throttlingException;<NEW_LINE>} | int originalDepth = context.getCurrentDepth(); |
1,426,021 | public void initChannel(SocketChannel channel) {<NEW_LINE><MASK><NEW_LINE>boolean secure = channel.attr(SECURE) != null && channel.attr(SECURE).get() != null && channel.attr(SECURE).get();<NEW_LINE>if (proxyConfigurations != null) {<NEW_LINE>if (secure && proxyConfigurations.containsKey(ProxyConfiguration.Type.HTTPS)) {<NEW_LINE>ProxyConfiguration proxyConfiguration = proxyConfigurations.get(ProxyConfiguration.Type.HTTPS);<NEW_LINE>if (isNotBlank(proxyConfiguration.getUsername()) && isNotBlank(proxyConfiguration.getPassword())) {<NEW_LINE>pipeline.addLast(new HttpProxyHandler(proxyConfiguration.getProxyAddress(), proxyConfiguration.getUsername(), proxyConfiguration.getPassword()));<NEW_LINE>} else {<NEW_LINE>pipeline.addLast(new HttpProxyHandler(proxyConfiguration.getProxyAddress()));<NEW_LINE>}<NEW_LINE>} else if (proxyConfigurations.containsKey(ProxyConfiguration.Type.SOCKS5)) {<NEW_LINE>ProxyConfiguration proxyConfiguration = proxyConfigurations.get(ProxyConfiguration.Type.SOCKS5);<NEW_LINE>if (isNotBlank(proxyConfiguration.getUsername()) && isNotBlank(proxyConfiguration.getPassword())) {<NEW_LINE>pipeline.addLast(new Socks5ProxyHandler(proxyConfiguration.getProxyAddress(), proxyConfiguration.getUsername(), proxyConfiguration.getPassword()));<NEW_LINE>} else {<NEW_LINE>pipeline.addLast(new Socks5ProxyHandler(proxyConfiguration.getProxyAddress()));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>pipeline.addLast(httpClientConnectionHandler);<NEW_LINE>if (secure) {<NEW_LINE>InetSocketAddress remoteAddress = channel.attr(REMOTE_SOCKET).get();<NEW_LINE>pipeline.addLast(nettySslContextFactory.createClientSslContext(forwardProxyClient).newHandler(channel.alloc(), remoteAddress.getHostName(), remoteAddress.getPort()));<NEW_LINE>}<NEW_LINE>// add logging<NEW_LINE>if (MockServerLogger.isEnabled(TRACE)) {<NEW_LINE>pipeline.addLast(new LoggingHandler(HttpClientHandler.class.getName()));<NEW_LINE>}<NEW_LINE>if (isHttp) {<NEW_LINE>pipeline.addLast(new HttpClientCodec());<NEW_LINE>pipeline.addLast(new HttpContentDecompressor());<NEW_LINE>pipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));<NEW_LINE>pipeline.addLast(new MockServerHttpClientCodec(mockServerLogger, proxyConfigurations));<NEW_LINE>} else {<NEW_LINE>pipeline.addLast(new MockServerBinaryClientCodec());<NEW_LINE>}<NEW_LINE>pipeline.addLast(httpClientHandler);<NEW_LINE>} | ChannelPipeline pipeline = channel.pipeline(); |
134,243 | public static List<String> extractZipFolderToFolder(final File zipFile, final String path, final String destination, String encoding) {<NEW_LINE>List<String> fileNames = new ArrayList<String>();<NEW_LINE>String dest = destination;<NEW_LINE>if (!destination.endsWith(File.separator)) {<NEW_LINE>dest = destination + File.separator;<NEW_LINE>}<NEW_LINE>ZipFile file;<NEW_LINE>try {<NEW_LINE>file = null;<NEW_LINE>if (null == encoding) {<NEW_LINE>file = new ZipFile(zipFile);<NEW_LINE>} else {<NEW_LINE>file = new ZipFile(zipFile, encoding);<NEW_LINE>}<NEW_LINE>Enumeration<ZipArchiveEntry> en = file.getEntries();<NEW_LINE>ZipArchiveEntry ze = null;<NEW_LINE>while (en.hasMoreElements()) {<NEW_LINE>ze = en.nextElement();<NEW_LINE>String name = ze.getName();<NEW_LINE>if (name.startsWith(path)) {<NEW_LINE>File f = new File(dest<MASK><NEW_LINE>if (ze.isDirectory()) {<NEW_LINE>f.mkdirs();<NEW_LINE>continue;<NEW_LINE>} else {<NEW_LINE>f.getParentFile().mkdirs();<NEW_LINE>InputStream is = file.getInputStream(ze);<NEW_LINE>OutputStream os = new FileOutputStream(f);<NEW_LINE>IOUtils.copy(is, os);<NEW_LINE>is.close();<NEW_LINE>os.close();<NEW_LINE>fileNames.add(f.getAbsolutePath());<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>file.close();<NEW_LINE>} catch (IOException e) {<NEW_LINE>e.printStackTrace();<NEW_LINE>}<NEW_LINE>return fileNames;<NEW_LINE>} | , FilenameUtils.getName(name)); |
1,258,559 | protected Schema processAsId(String propertyName, JavaType type, ModelConverterContext context, ObjectMapper mapper) {<NEW_LINE>final BeanDescription beanDesc = mapper.getSerializationConfig().introspect(type);<NEW_LINE>for (BeanPropertyDefinition def : beanDesc.findProperties()) {<NEW_LINE>final String name = def.getName();<NEW_LINE>if (name != null && name.equals(propertyName)) {<NEW_LINE>final AnnotatedMember propMember = def.getPrimaryMember();<NEW_LINE>final JavaType propType = propMember.getType();<NEW_LINE>if (PrimitiveType.fromType(propType) != null) {<NEW_LINE>return PrimitiveType.createProperty(propType);<NEW_LINE>} else {<NEW_LINE>List<Annotation> anns = new ArrayList<>();<NEW_LINE>for (Annotation annotation : propMember.annotations()) {<NEW_LINE>anns.add(annotation);<NEW_LINE>}<NEW_LINE>Annotation[] annotations = new <MASK><NEW_LINE>annotations = anns.toArray(annotations);<NEW_LINE>return context.resolve(propType, annotations);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return null;<NEW_LINE>} | Annotation[anns.size()]; |
161,002 | public void updateDefaultHost(Host host, User user, boolean respectFrontendRoles) throws DotDataException, DotSecurityException {<NEW_LINE>// If host is marked as default make sure that no other host is already set to be the default<NEW_LINE>if (host.isDefault()) {<NEW_LINE>ContentletAPI conAPI = APILocator.getContentletAPI();<NEW_LINE>List<Host> hosts = findAllFromDB(user, respectFrontendRoles);<NEW_LINE>Host otherHost;<NEW_LINE>Contentlet otherHostContentlet;<NEW_LINE>for (Host h : hosts) {<NEW_LINE>if (h.getIdentifier().equals(host.getIdentifier())) {<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>// if this host is the default as well then ours should become the only one<NEW_LINE>if (h.isDefault()) {<NEW_LINE>boolean isHostRunning = h.isLive();<NEW_LINE>otherHostContentlet = APILocator.getContentletAPI().checkout(h.getInode(), user, respectFrontendRoles);<NEW_LINE>otherHost = new Host(otherHostContentlet);<NEW_LINE>hostCache.remove(otherHost);<NEW_LINE>otherHost.setDefault(false);<NEW_LINE>if (host.getMap().containsKey(Contentlet.DONT_VALIDATE_ME))<NEW_LINE>otherHost.setProperty(Contentlet.DONT_VALIDATE_ME, true);<NEW_LINE>if (host.getMap().containsKey(Contentlet.DISABLE_WORKFLOW))<NEW_LINE>otherHost.setProperty(Contentlet.DISABLE_WORKFLOW, true);<NEW_LINE>Contentlet cont = conAPI.<MASK><NEW_LINE>if (isHostRunning) {<NEW_LINE>otherHost = new Host(cont);<NEW_LINE>publish(otherHost, user, respectFrontendRoles);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | checkin(otherHost, user, respectFrontendRoles); |
705,427 | private void fillRequestSettings(HttpRequestBase request, String path) {<NEW_LINE>MlflowHostCreds hostCreds = hostCredsProvider.getHostCreds();<NEW_LINE>createHttpClientIfNecessary(hostCreds.shouldIgnoreTlsVerification());<NEW_LINE>String uri = hostCreds.getHost() + "/" + BASE_API_PATH + "/" + path;<NEW_LINE>request.setURI<MASK><NEW_LINE>String username = hostCreds.getUsername();<NEW_LINE>String password = hostCreds.getPassword();<NEW_LINE>String token = hostCreds.getToken();<NEW_LINE>if (username != null && password != null) {<NEW_LINE>String authHeader = Base64.getEncoder().encodeToString((username + ":" + password).getBytes(StandardCharsets.UTF_8));<NEW_LINE>request.addHeader("Authorization", "Basic " + authHeader);<NEW_LINE>} else if (token != null) {<NEW_LINE>request.addHeader("Authorization", "Bearer " + token);<NEW_LINE>}<NEW_LINE>String userAgent = "mlflow-java-client";<NEW_LINE>String clientVersion = MlflowClientVersion.getClientVersion();<NEW_LINE>if (!clientVersion.isEmpty()) {<NEW_LINE>userAgent += "/" + clientVersion;<NEW_LINE>}<NEW_LINE>request.addHeader("User-Agent", userAgent);<NEW_LINE>} | (URI.create(uri)); |
630,757 | private void collectExtensionDependencies(Project project, Configuration deploymentConfiguration, Map<ArtifactKey, ResolvedDependencyBuilder> appDependencies) {<NEW_LINE>final <MASK><NEW_LINE>for (ResolvedArtifact a : rc.getResolvedArtifacts()) {<NEW_LINE>if (a.getId().getComponentIdentifier() instanceof ProjectComponentIdentifier) {<NEW_LINE>final Project projectDep = project.getRootProject().findProject(((ProjectComponentIdentifier) a.getId().getComponentIdentifier()).getProjectPath());<NEW_LINE>final JavaPluginConvention javaExtension = projectDep == null ? null : projectDep.getConvention().findPlugin(JavaPluginConvention.class);<NEW_LINE>SourceSet mainSourceSet = javaExtension.getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME);<NEW_LINE>final ResolvedDependencyBuilder dep = appDependencies.computeIfAbsent(toAppDependenciesKey(a.getModuleVersion().getId().getGroup(), a.getName(), a.getClassifier()), k -> toDependency(a, mainSourceSet));<NEW_LINE>dep.setDeploymentCp();<NEW_LINE>dep.clearFlag(DependencyFlags.RELOADABLE);<NEW_LINE>} else if (isDependency(a)) {<NEW_LINE>final ResolvedDependencyBuilder dep = appDependencies.computeIfAbsent(toAppDependenciesKey(a.getModuleVersion().getId().getGroup(), a.getName(), a.getClassifier()), k -> toDependency(a));<NEW_LINE>dep.setDeploymentCp();<NEW_LINE>dep.clearFlag(DependencyFlags.RELOADABLE);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | ResolvedConfiguration rc = deploymentConfiguration.getResolvedConfiguration(); |
1,192,434 | protected void deleteInvalidUser(final RealmModel realm, final UserModel user) {<NEW_LINE>String userId = user.getId();<NEW_LINE>String userName = user.getUsername();<NEW_LINE>UserCache userCache = session.userCache();<NEW_LINE>if (userCache != null) {<NEW_LINE>userCache.evict(realm, user);<NEW_LINE>}<NEW_LINE>// This needs to be running in separate transaction because removing the user may end up with throwing<NEW_LINE>// PessimisticLockException which also rollbacks Jpa transaction, hence when it is running in current transaction<NEW_LINE>// it will become not usable for all consequent jpa calls. It will end up with Transaction is in rolled back<NEW_LINE>// state error<NEW_LINE>runJobInTransaction(session.getKeycloakSessionFactory(), session -> {<NEW_LINE>RealmModel realmModel = session.realms().getRealm(realm.getId());<NEW_LINE>if (realmModel == null)<NEW_LINE>return;<NEW_LINE>UserModel deletedUser = session.userLocalStorage().getUserById(realmModel, userId);<NEW_LINE>if (deletedUser != null) {<NEW_LINE>try {<NEW_LINE>new UserManager(session).removeUser(realmModel, deletedUser, session.userLocalStorage());<NEW_LINE><MASK><NEW_LINE>} catch (ModelException ex) {<NEW_LINE>// Ignore exception, possible cause may be concurrent deleteInvalidUser calls which means<NEW_LINE>// ModelException exception may be ignored because users will be removed with next call or is<NEW_LINE>// already removed<NEW_LINE>logger.debugf(ex, "ModelException thrown during deleteInvalidUser with username '%s'", userName);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>});<NEW_LINE>} | logger.debugf("Removed invalid user '%s'", userName); |
75,306 | public void run(final SyncTaskChain chain) {<NEW_LINE>checkState();<NEW_LINE>if (msg.isSkipIfHostConnected() && HostStatus.Connected == self.getStatus()) {<NEW_LINE>finish(chain);<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>ConnectHostMsg connectMsg = new ConnectHostMsg(self.getUuid());<NEW_LINE>connectMsg.setNewAdd(false);<NEW_LINE>bus.makeTargetServiceIdByResourceUuid(connectMsg, HostConstant.SERVICE_ID, self.getUuid());<NEW_LINE>bus.send(connectMsg, new CloudBusCallBack(msg, chain, completion) {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void run(MessageReply reply) {<NEW_LINE>ReconnectHostReply r = new ReconnectHostReply();<NEW_LINE>if (reply.isSuccess()) {<NEW_LINE>logger.debug(String.format("Successfully reconnect host[uuid:%s]", self.getUuid()));<NEW_LINE>} else {<NEW_LINE>r.setError(err(HostErrors.UNABLE_TO_RECONNECT_HOST, reply.getError(), reply.getError().getDetails()));<NEW_LINE>logger.debug(String.format("Failed to reconnect host[uuid:%s] because %s", self.getUuid()<MASK><NEW_LINE>}<NEW_LINE>bus.reply(msg, r);<NEW_LINE>}<NEW_LINE>});<NEW_LINE>// no need to block the queue, because the ConnectHostMsg will be queued as well<NEW_LINE>finish(chain);<NEW_LINE>} | , reply.getError())); |
1,490,722 | JSONObject writeItemsToJson(@NonNull JSONObject json) {<NEW_LINE>JSONArray jsonArray = new JSONArray();<NEW_LINE>if (!items.isEmpty()) {<NEW_LINE>try {<NEW_LINE>for (ITileSource template : items) {<NEW_LINE>JSONObject jsonObject = new JSONObject();<NEW_LINE>boolean sql = template instanceof SQLiteTileSource;<NEW_LINE>jsonObject.put("sql", sql);<NEW_LINE>jsonObject.put("name", template.getName());<NEW_LINE>jsonObject.put("minZoom", template.getMinimumZoomSupported());<NEW_LINE>jsonObject.put("maxZoom", template.getMaximumZoomSupported());<NEW_LINE>jsonObject.put("url", template.getUrlTemplate());<NEW_LINE>jsonObject.put("randoms", template.getRandoms());<NEW_LINE>jsonObject.put("ellipsoid", template.isEllipticYTile());<NEW_LINE>jsonObject.put("inverted_y", template.isInvertedYTile());<NEW_LINE>jsonObject.put("referer", template.getReferer());<NEW_LINE>jsonObject.put("userAgent", template.getUserAgent());<NEW_LINE>jsonObject.put("timesupported", template.isTimeSupported());<NEW_LINE>jsonObject.put("expire", template.getExpirationTimeMinutes());<NEW_LINE>jsonObject.put("inversiveZoom", template.getInversiveZoom());<NEW_LINE>jsonObject.put("ext", template.getTileFormat());<NEW_LINE>jsonObject.put("tileSize", template.getTileSize());<NEW_LINE>jsonObject.put("bitDensity", template.getBitDensity());<NEW_LINE>jsonObject.put("avgSize", template.getAvgSize());<NEW_LINE>jsonObject.put("rule", template.getRule());<NEW_LINE>jsonArray.put(jsonObject);<NEW_LINE>}<NEW_LINE>json.put("items", jsonArray);<NEW_LINE>} catch (JSONException e) {<NEW_LINE>warnings.add(app.getString(R.string.settings_item_write_error, String.valueOf(getType())));<NEW_LINE>SettingsHelper.<MASK><NEW_LINE>}<NEW_LINE>}<NEW_LINE>return json;<NEW_LINE>} | LOG.error("Failed write to json", e); |
1,077,909 | public void onCreate(Bundle savedInstanceState) {<NEW_LINE>super.onCreate(savedInstanceState);<NEW_LINE>overridePendingTransition(R.anim.activity_slide_up, R.anim.activity_slide_down);<NEW_LINE>slug = getIntent().getStringExtra("slug");<NEW_LINE>context = this;<NEW_LINE>sharedPrefs = context.getSharedPreferences("com.klinker.android.twitter_world_preferences", 0);<NEW_LINE>settings = AppSettings.getInstance(this);<NEW_LINE>setUpWindow();<NEW_LINE>Utils.setUpPopupTheme(this, settings);<NEW_LINE>actionBar = getActionBar();<NEW_LINE>setContentView(R.layout.ptr_list_layout);<NEW_LINE>if (!settings.isTwitterLoggedIn) {<NEW_LINE>Intent login = new Intent(context, LoginActivity.class);<NEW_LINE>startActivity(login);<NEW_LINE>finish();<NEW_LINE>}<NEW_LINE>spinner = (LinearLayout) findViewById(R.id.list_progress);<NEW_LINE>listView = (AsyncListView) findViewById(R.id.listView);<NEW_LINE>BitmapLruCache cache = App.getInstance(context).getBitmapCache();<NEW_LINE>ArrayListLoader loader = new ArrayListLoader(cache, context);<NEW_LINE>ItemManager.Builder builder = new ItemManager.Builder(loader);<NEW_LINE>builder.setPreloadItemsEnabled(true).setPreloadItemsCount(50);<NEW_LINE>builder.setThreadPoolSize(4);<NEW_LINE>listView.<MASK><NEW_LINE>getPeople();<NEW_LINE>} | setItemManager(builder.build()); |
476,471 | protected List<Cluster<M>> splitCluster(Cluster<M> parentCluster, Relation<V> relation) {<NEW_LINE>// Transform parent cluster into a clustering<NEW_LINE>if (parentCluster.size() <= 1) {<NEW_LINE>// Split is not possible<NEW_LINE>return Arrays.asList(parentCluster);<NEW_LINE>}<NEW_LINE>splitInitializer.setInitialMeans(splitCentroid(parentCluster, relation));<NEW_LINE>innerKMeans.setK(2);<NEW_LINE>List<Cluster<M>> childClustering = innerKMeans.run(new ProxyView<>(parentCluster.getIDs(), relation)).getAllClusters();<NEW_LINE>assert childClustering.size() == 2;<NEW_LINE>// Evaluation via projection to v = c2 - c1 = 2m<NEW_LINE>double[] v = minus(childClustering.get(0).getModel().getMean(), childClustering.get(1).getModel().getMean());<NEW_LINE>double[] projectedValues = new double[parentCluster.size()];<NEW_LINE>int i = 0;<NEW_LINE>for (DBIDIter it = parentCluster.getIDs().iter(); it.valid(); it.advance()) {<NEW_LINE>projectedValues[i++] = VectorUtil.dot(relation<MASK><NEW_LINE>}<NEW_LINE>// Test for normality:<NEW_LINE>Arrays.sort(projectedValues);<NEW_LINE>double A2 = AndersonDarlingTest.A2Noncentral(projectedValues);<NEW_LINE>A2 = AndersonDarlingTest.removeBiasNormalDistribution(A2, projectedValues.length);<NEW_LINE>// Check if split is an improvement:<NEW_LINE>return A2 > critical ? childClustering : Arrays.asList(parentCluster);<NEW_LINE>} | .get(it), v); |
693,113 | public Response handleRequest(final ManagementRequest request) {<NEW_LINE>final PluginManagementRequest concreteRequest = (PluginManagementRequest) request;<NEW_LINE>logger.log(Level.SEVERE, "Executing PluginOperation for action " + concreteRequest.getOptions().getAction() + " ...");<NEW_LINE>Thread pluginThread = new Thread(new Runnable() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void run() {<NEW_LINE>try {<NEW_LINE>PluginOperation pluginOperation = new PluginOperation(null, concreteRequest.getOptions());<NEW_LINE>PluginOperationResult operationResult = pluginOperation.execute();<NEW_LINE>switch(operationResult.getResultCode()) {<NEW_LINE>case OK:<NEW_LINE>eventBus.post(new PluginManagementResponse(PluginManagementResponse.OK, operationResult<MASK><NEW_LINE>break;<NEW_LINE>case NOK:<NEW_LINE>eventBus.post(new PluginManagementResponse(PluginManagementResponse.NOK_FAILED_UNKNOWN, operationResult, request.getId()));<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>} catch (Exception e) {<NEW_LINE>logger.log(Level.WARNING, "Error executing plugin management request.", e);<NEW_LINE>eventBus.post(new PluginManagementResponse(PluginManagementResponse.NOK_OPERATION_FAILED, new PluginOperationResult(), request.getId()));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}, "PlugRq/" + concreteRequest.getOptions().getAction());<NEW_LINE>pluginThread.start();<NEW_LINE>return null;<NEW_LINE>} | , request.getId())); |
1,141,505 | public ValidationHandlerImpl create(OperationImpl operation) {<NEW_LINE>// TODO error handling of this function?<NEW_LINE>Map<ParameterLocation, List<ParameterProcessor>> parameterProcessors = new HashMap<>();<NEW_LINE>List<BodyProcessor> bodyProcessors = new ArrayList<>();<NEW_LINE>GeneratorContext context = new GeneratorContext(this.schemaParser, holder, operation);<NEW_LINE>// Parse parameter processors<NEW_LINE>for (Map.Entry<JsonPointer, JsonObject> pe : operation.getParameters().entrySet()) {<NEW_LINE>ParameterLocation parsedLocation = ParameterLocation.valueOf(pe.getValue().getString("in").toUpperCase());<NEW_LINE>String parsedStyle = OpenAPI3Utils.<MASK><NEW_LINE>if (pe.getValue().getBoolean("allowReserved", false))<NEW_LINE>throw RouterBuilderException.createUnsupportedSpecFeature("You are using allowReserved keyword in parameter " + pe.getKey() + " which " + "is not supported");<NEW_LINE>JsonObject fakeSchema = context.fakeSchema(pe.getValue().getJsonObject("schema", new JsonObject()));<NEW_LINE>ParameterProcessorGenerator generator = parameterProcessorGenerators.stream().filter(g -> g.canGenerate(pe.getValue(), fakeSchema, parsedLocation, parsedStyle)).findFirst().orElseThrow(() -> RouterBuilderException.cannotFindParameterProcessorGenerator(pe.getKey(), pe.getValue()));<NEW_LINE>try {<NEW_LINE>ParameterProcessor generated = generator.generate(pe.getValue(), fakeSchema, pe.getKey(), parsedLocation, parsedStyle, context);<NEW_LINE>if (!parameterProcessors.containsKey(generated.getLocation()))<NEW_LINE>parameterProcessors.put(generated.getLocation(), new ArrayList<>());<NEW_LINE>parameterProcessors.get(generated.getLocation()).add(generated);<NEW_LINE>} catch (Exception e) {<NEW_LINE>throw RouterBuilderException.createErrorWhileGeneratingValidationHandler(String.format("Cannot generate parameter validator for parameter %s in %s", pe.getKey().toURI(), parsedLocation), e);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// Parse body required predicate<NEW_LINE>if (parseIsBodyRequired(operation))<NEW_LINE>context.addPredicate(RequestPredicate.BODY_REQUIRED);<NEW_LINE>// Parse body processors<NEW_LINE>for (Map.Entry<String, Object> mediaType : (JsonObject) REQUEST_BODY_CONTENT_POINTER.queryOrDefault(operation.getOperationModel(), iteratorWithLoader, new JsonObject())) {<NEW_LINE>JsonObject mediaTypeModel = (JsonObject) mediaType.getValue();<NEW_LINE>JsonPointer mediaTypePointer = operation.getPointer().copy().append("requestBody").append("content").append(mediaType.getKey());<NEW_LINE>BodyProcessor generated = bodyProcessorGenerators.stream().filter(g -> g.canGenerate(mediaType.getKey(), mediaTypeModel)).findFirst().orElse(NoopBodyProcessorGenerator.INSTANCE).generate(mediaType.getKey(), mediaTypeModel, mediaTypePointer, context);<NEW_LINE>bodyProcessors.add(generated);<NEW_LINE>}<NEW_LINE>return new ValidationHandlerImpl(parameterProcessors, bodyProcessors, context.getPredicates());<NEW_LINE>} | resolveStyle(pe.getValue()); |
998,331 | public static void yv12ToPlanarRgb_U8(byte[] dataYV, Planar<GrayU8> output) {<NEW_LINE>GrayU8 R = output.getBand(0);<NEW_LINE>GrayU8 G = output.getBand(1);<NEW_LINE>GrayU8 B = output.getBand(2);<NEW_LINE>final int yStride = output.width;<NEW_LINE>final int uvStride = output.width / 2;<NEW_LINE>final int startU = yStride * output.height;<NEW_LINE>final int offsetV = uvStride * (output.height / 2);<NEW_LINE>// CONCURRENT_BELOW BoofConcurrency.loopFor(0, output.height, row -> {<NEW_LINE>for (int row = 0; row < output.height; row++) {<NEW_LINE>int indexY = row * yStride;<NEW_LINE>int indexU = startU + (row / 2) * uvStride;<NEW_LINE>int indexOut = output.startIndex + row * output.stride;<NEW_LINE>for (int col = 0; col < output.width; col++, indexOut++) {<NEW_LINE>int y = 1191 * ((dataYV[indexY++] & 0xFF) - 16);<NEW_LINE>int cb = (dataYV[indexU] & 0xFF) - 128;<NEW_LINE>int cr = (dataYV[indexU + offsetV] & 0xFF) - 128;<NEW_LINE>// if( y < 0 ) y = 0;<NEW_LINE>y = ((y >>> 31) ^ 1) * y;<NEW_LINE>int r = (y + 1836 * cr) >> 10;<NEW_LINE>int g = (y - 547 * cr - 218 * cb) >> 10;<NEW_LINE>int b = (y <MASK><NEW_LINE>// if( r < 0 ) r = 0; else if( r > 255 ) r = 255;<NEW_LINE>// if( g < 0 ) g = 0; else if( g > 255 ) g = 255;<NEW_LINE>// if( b < 0 ) b = 0; else if( b > 255 ) b = 255;<NEW_LINE>r *= ((r >>> 31) ^ 1);<NEW_LINE>g *= ((g >>> 31) ^ 1);<NEW_LINE>b *= ((b >>> 31) ^ 1);<NEW_LINE>// The bitwise code below isn't faster than than the if statement below<NEW_LINE>// r |= (((255-r) >>> 31)*0xFF);<NEW_LINE>// g |= (((255-g) >>> 31)*0xFF);<NEW_LINE>// b |= (((255-b) >>> 31)*0xFF);<NEW_LINE>if (r > 255)<NEW_LINE>r = 255;<NEW_LINE>if (g > 255)<NEW_LINE>g = 255;<NEW_LINE>if (b > 255)<NEW_LINE>b = 255;<NEW_LINE>R.data[indexOut] = (byte) r;<NEW_LINE>G.data[indexOut] = (byte) g;<NEW_LINE>B.data[indexOut] = (byte) b;<NEW_LINE>indexU += col & 0x1;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// CONCURRENT_ABOVE });<NEW_LINE>} | + 2165 * cb) >> 10; |
618,391 | private void afterRestoreStarted(Client clientWithHeaders, PutFollowAction.Request request, ActionListener<PutFollowAction.Response> originalListener, RestoreService.RestoreCompletionResponse response) {<NEW_LINE>final ActionListener<PutFollowAction.Response> listener;<NEW_LINE>if (ActiveShardCount.NONE.equals(request.waitForActiveShards())) {<NEW_LINE>originalListener.onResponse(new PutFollowAction.Response(true, false, false));<NEW_LINE>listener = new ActionListener<>() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void onResponse(PutFollowAction.Response response) {<NEW_LINE>logger.debug("put follow {} completed with {}", request, response);<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void onFailure(Exception e) {<NEW_LINE>logger.debug(() -> new ParameterizedMessage("put follow {} failed during the restore process", request), e);<NEW_LINE>}<NEW_LINE>};<NEW_LINE>} else {<NEW_LINE>listener = originalListener;<NEW_LINE>}<NEW_LINE>RestoreClusterStateListener.createAndRegisterListener(clusterService, response, listener.delegateFailure((delegatedListener, restoreSnapshotResponse) -> {<NEW_LINE><MASK><NEW_LINE>if (restoreInfo == null) {<NEW_LINE>// If restoreInfo is null then it is possible there was a master failure during the<NEW_LINE>// restore.<NEW_LINE>delegatedListener.onResponse(new PutFollowAction.Response(true, false, false));<NEW_LINE>} else if (restoreInfo.failedShards() == 0) {<NEW_LINE>initiateFollowing(clientWithHeaders, request, delegatedListener);<NEW_LINE>} else {<NEW_LINE>assert restoreInfo.failedShards() > 0 : "Should have failed shards";<NEW_LINE>delegatedListener.onResponse(new PutFollowAction.Response(true, false, false));<NEW_LINE>}<NEW_LINE>}), threadPool.getThreadContext());<NEW_LINE>} | RestoreInfo restoreInfo = restoreSnapshotResponse.getRestoreInfo(); |
424,477 | private static void panoseDebugReportOnPhysicalFonts(Map<String, PhysicalFont> physicalFontMap) {<NEW_LINE>Iterator fontIterator = physicalFontMap<MASK><NEW_LINE>while (fontIterator.hasNext()) {<NEW_LINE>Map.Entry pairs = (Map.Entry) fontIterator.next();<NEW_LINE>if (pairs.getKey() == null) {<NEW_LINE>log.info("Skipped null key");<NEW_LINE>if (pairs.getValue() != null) {<NEW_LINE>log.error(((PhysicalFont) pairs.getValue()).getEmbeddedURI().toString());<NEW_LINE>}<NEW_LINE>if (fontIterator.hasNext()) {<NEW_LINE>pairs = (Map.Entry) fontIterator.next();<NEW_LINE>} else {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>String fontName = (String) pairs.getKey();<NEW_LINE>PhysicalFont pf = (PhysicalFont) pairs.getValue();<NEW_LINE>org.docx4j.fonts.foray.font.format.Panose fopPanose = pf.getPanose();<NEW_LINE>if (fopPanose == null) {<NEW_LINE>log.warn(fontName + " .. lacks Panose!");<NEW_LINE>} else if (fopPanose != null) {<NEW_LINE>log.debug(fontName + " .. " + fopPanose);<NEW_LINE>}<NEW_LINE>// long pd = fopPanose.difference(nfontInfo.getPanose().getPanoseArray());<NEW_LINE>// System.out.println(".. panose distance: " + pd);<NEW_LINE>}<NEW_LINE>} | .entrySet().iterator(); |
379,153 | private List<I_M_HU> retrieveTopLevelHUsForModel(final Properties ctx, final int adTableId, final int recordId, final String trxName) {<NEW_LINE>final IQueryBuilder<I_M_HU> queryBuilder = //<NEW_LINE>queryBL.createQueryBuilder(I_M_HU_Assignment.class, ctx, trxName).addEqualsFilter(I_M_HU_Assignment.COLUMNNAME_AD_Table_ID, adTableId).addEqualsFilter(I_M_HU_Assignment.COLUMNNAME_Record_ID, recordId).addOnlyActiveRecordsFilter().// Collect top level HUs<NEW_LINE>andCollect(I_M_HU_Assignment.COLUMN_M_HU_ID);<NEW_LINE>//<NEW_LINE>// 07612: Order by HU ID to preserve allocation order (i.e highest HU quantities / full HUs first)<NEW_LINE>queryBuilder.orderBy().addColumn(I_M_HU.COLUMN_M_HU_ID);<NEW_LINE>final List<I_M_HU> husTopLevel = queryBuilder.create(<MASK><NEW_LINE>//<NEW_LINE>// Guard: make sure all those HUs are really top level<NEW_LINE>// Normally, this shall not happen. But we could have the case when the TU was joined to a LU later and the HU assignment was not updated.<NEW_LINE>final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class);<NEW_LINE>husTopLevel.removeIf(hu -> !handlingUnitsBL.isTopLevel(hu));<NEW_LINE>// NOTE: this method will NOT exclude destroyed HUs.<NEW_LINE>// Before changing this, please carefully check the depending API.<NEW_LINE>return husTopLevel;<NEW_LINE>} | ).list(I_M_HU.class); |
1,540,019 | public NodeIndicesStats stats(CommonStatsFlags flags) {<NEW_LINE>CommonStats commonStats = new CommonStats(flags);<NEW_LINE>// the cumulative statistics also account for shards that are no longer on this node, which is tracked by oldShardsStats<NEW_LINE>for (Flag flag : flags.getFlags()) {<NEW_LINE>switch(flag) {<NEW_LINE>case Get:<NEW_LINE>commonStats.get.add(oldShardsStats.getStats);<NEW_LINE>break;<NEW_LINE>case Indexing:<NEW_LINE>commonStats.indexing.add(oldShardsStats.indexingStats);<NEW_LINE>break;<NEW_LINE>case Search:<NEW_LINE>commonStats.<MASK><NEW_LINE>break;<NEW_LINE>case Merge:<NEW_LINE>commonStats.merge.add(oldShardsStats.mergeStats);<NEW_LINE>break;<NEW_LINE>case Refresh:<NEW_LINE>commonStats.refresh.add(oldShardsStats.refreshStats);<NEW_LINE>break;<NEW_LINE>case Recovery:<NEW_LINE>commonStats.recoveryStats.add(oldShardsStats.recoveryStats);<NEW_LINE>break;<NEW_LINE>case Flush:<NEW_LINE>commonStats.flush.add(oldShardsStats.flushStats);<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return new NodeIndicesStats(commonStats, statsByShard(this, flags));<NEW_LINE>} | search.add(oldShardsStats.searchStats); |
952,654 | private Mono<Response<Flux<ByteBuffer>>> migrateCassandraKeyspaceToManualThroughputWithResponseAsync(String resourceGroupName, String accountName, String keyspaceName, Context context) {<NEW_LINE>if (this.client.getEndpoint() == null) {<NEW_LINE>return Mono.<MASK><NEW_LINE>}<NEW_LINE>if (this.client.getSubscriptionId() == null) {<NEW_LINE>return Mono.error(new IllegalArgumentException("Parameter this.client.getSubscriptionId() is required and cannot be null."));<NEW_LINE>}<NEW_LINE>if (resourceGroupName == null) {<NEW_LINE>return Mono.error(new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."));<NEW_LINE>}<NEW_LINE>if (accountName == null) {<NEW_LINE>return Mono.error(new IllegalArgumentException("Parameter accountName is required and cannot be null."));<NEW_LINE>}<NEW_LINE>if (keyspaceName == null) {<NEW_LINE>return Mono.error(new IllegalArgumentException("Parameter keyspaceName is required and cannot be null."));<NEW_LINE>}<NEW_LINE>final String accept = "application/json";<NEW_LINE>context = this.client.mergeContext(context);<NEW_LINE>return service.migrateCassandraKeyspaceToManualThroughput(this.client.getEndpoint(), this.client.getSubscriptionId(), resourceGroupName, accountName, keyspaceName, this.client.getApiVersion(), accept, context);<NEW_LINE>} | error(new IllegalArgumentException("Parameter this.client.getEndpoint() is required and cannot be null.")); |
496,950 | public ClientAuthentication unmarshall(JsonUnmarshallerContext context) throws Exception {<NEW_LINE>ClientAuthentication clientAuthentication = new ClientAuthentication();<NEW_LINE>int originalDepth = context.getCurrentDepth();<NEW_LINE><MASK><NEW_LINE>int targetDepth = originalDepth + 1;<NEW_LINE>JsonToken token = context.getCurrentToken();<NEW_LINE>if (token == null)<NEW_LINE>token = context.nextToken();<NEW_LINE>if (token == VALUE_NULL) {<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>while (true) {<NEW_LINE>if (token == null)<NEW_LINE>break;<NEW_LINE>if (token == FIELD_NAME || token == START_OBJECT) {<NEW_LINE>if (context.testExpression("sasl", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>clientAuthentication.setSasl(SaslJsonUnmarshaller.getInstance().unmarshall(context));<NEW_LINE>}<NEW_LINE>if (context.testExpression("tls", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>clientAuthentication.setTls(TlsJsonUnmarshaller.getInstance().unmarshall(context));<NEW_LINE>}<NEW_LINE>if (context.testExpression("unauthenticated", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>clientAuthentication.setUnauthenticated(UnauthenticatedJsonUnmarshaller.getInstance().unmarshall(context));<NEW_LINE>}<NEW_LINE>} else if (token == END_ARRAY || token == END_OBJECT) {<NEW_LINE>if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {<NEW_LINE>if (context.getCurrentDepth() <= originalDepth)<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>token = context.nextToken();<NEW_LINE>}<NEW_LINE>return clientAuthentication;<NEW_LINE>} | String currentParentElement = context.getCurrentParentElement(); |
747,968 | public Object execute(final Map<Object, Object> iArgs) {<NEW_LINE>if (clazz == null)<NEW_LINE>throw new OCommandExecutionException("Cannot execute the command because it has not been parsed yet");<NEW_LINE>// CREATE VERTEX DOES NOT HAVE TO BE IN TX<NEW_LINE>final OVertex vertex = getDatabase().newVertex(clazz);<NEW_LINE>if (fields != null)<NEW_LINE>// EVALUATE FIELDS<NEW_LINE>for (final OPair<String, Object> f : fields) {<NEW_LINE>if (f.getValue() instanceof OSQLFunctionRuntime)<NEW_LINE>f.setValue(((OSQLFunctionRuntime) f.getValue()).getValue(vertex.getRecord(), null, context));<NEW_LINE>}<NEW_LINE>OSQLHelper.bindParameters(vertex.getRecord(), fields, <MASK><NEW_LINE>if (content != null)<NEW_LINE>((ODocument) vertex.getRecord()).merge(content, true, false);<NEW_LINE>if (clusterName != null)<NEW_LINE>vertex.save(clusterName);<NEW_LINE>else<NEW_LINE>vertex.save();<NEW_LINE>return vertex.getRecord();<NEW_LINE>} | new OCommandParameters(iArgs), context); |
674,522 | public static <T extends BaseVertex, E extends BaseEdge> boolean graphEquals(final BaseGraph<T, E> g1, final BaseGraph<T, E> g2) {<NEW_LINE>Utils.nonNull(g1, "g1");<NEW_LINE><MASK><NEW_LINE>final Set<T> vertices1 = g1.vertexSet();<NEW_LINE>final Set<T> vertices2 = g2.vertexSet();<NEW_LINE>final Set<E> edges1 = g1.edgeSet();<NEW_LINE>final Set<E> edges2 = g2.edgeSet();<NEW_LINE>if (vertices1.size() != vertices2.size() || edges1.size() != edges2.size()) {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>// for every vertex in g1 there is a vertex in g2 with an equal getSequenceString<NEW_LINE>final boolean ok = vertices1.stream().map(v1 -> v1.getSequenceString()).allMatch(v1seqString -> vertices2.stream().anyMatch(v2 -> v1seqString.equals(v2.getSequenceString())));<NEW_LINE>if (!ok) {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>// for every edge in g1 there is an equal edge in g2<NEW_LINE>final boolean okG1 = edges1.stream().allMatch(e1 -> edges2.stream().anyMatch(e2 -> g1.seqEquals(e1, e2, g2)));<NEW_LINE>if (!okG1) {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>// for every edge in g2 there is an equal edge in g1<NEW_LINE>return edges2.stream().allMatch(e2 -> edges1.stream().anyMatch(e1 -> g2.seqEquals(e2, e1, g1)));<NEW_LINE>} | Utils.nonNull(g2, "g2"); |
360,158 | private static void resolveJUnitDependencies(NbModuleProject project, ModuleList moduleList, String testType, boolean addNBJUnit) throws IOException {<NEW_LINE>ModuleEntry <MASK><NEW_LINE>if (junit4 == null) {<NEW_LINE>IOException e = new IOException("no libs.junit4");<NEW_LINE>Exceptions.attachLocalizedMessage(e, ERR_could_not_find_junit4());<NEW_LINE>throw e;<NEW_LINE>}<NEW_LINE>ModuleEntry nbjunit = moduleList.getEntry(NBJUNIT_MODULE);<NEW_LINE>if (addNBJUnit && nbjunit == null) {<NEW_LINE>IOException e = new IOException("no nbjunit");<NEW_LINE>Exceptions.attachLocalizedMessage(e, ERR_could_not_find_nbjunit());<NEW_LINE>throw e;<NEW_LINE>}<NEW_LINE>ProjectXMLManager pxm = new ProjectXMLManager(project);<NEW_LINE>pxm.addTestDependency(testType, new TestModuleDependency(junit4, false, false, true));<NEW_LINE>if (addNBJUnit) {<NEW_LINE>pxm.addTestDependency(testType, new TestModuleDependency(nbjunit, false, true, true));<NEW_LINE>}<NEW_LINE>} | junit4 = moduleList.getEntry(JUNIT_MODULE); |
1,152,105 | public LayersListItem unmarshall(JsonUnmarshallerContext context) throws Exception {<NEW_LINE>LayersListItem layersListItem = new LayersListItem();<NEW_LINE>int originalDepth = context.getCurrentDepth();<NEW_LINE><MASK><NEW_LINE>int targetDepth = originalDepth + 1;<NEW_LINE>JsonToken token = context.getCurrentToken();<NEW_LINE>if (token == null)<NEW_LINE>token = context.nextToken();<NEW_LINE>if (token == VALUE_NULL) {<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>while (true) {<NEW_LINE>if (token == null)<NEW_LINE>break;<NEW_LINE>if (token == FIELD_NAME || token == START_OBJECT) {<NEW_LINE>if (context.testExpression("LayerName", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>layersListItem.setLayerName(context.getUnmarshaller(String.class).unmarshall(context));<NEW_LINE>}<NEW_LINE>if (context.testExpression("LayerArn", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>layersListItem.setLayerArn(context.getUnmarshaller(String.class).unmarshall(context));<NEW_LINE>}<NEW_LINE>if (context.testExpression("LatestMatchingVersion", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>layersListItem.setLatestMatchingVersion(LayerVersionsListItemJsonUnmarshaller.getInstance().unmarshall(context));<NEW_LINE>}<NEW_LINE>} else if (token == END_ARRAY || token == END_OBJECT) {<NEW_LINE>if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {<NEW_LINE>if (context.getCurrentDepth() <= originalDepth)<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>token = context.nextToken();<NEW_LINE>}<NEW_LINE>return layersListItem;<NEW_LINE>} | String currentParentElement = context.getCurrentParentElement(); |
988,720 | public static void horizontal3(Kernel1D_S32 kernel, GrayS32 image, GrayS32 dest, int divisor) {<NEW_LINE>final int[] dataSrc = image.data;<NEW_LINE>final int[] dataDst = dest.data;<NEW_LINE>final int k1 = kernel.data[0];<NEW_LINE>final int k2 = kernel.data[1];<NEW_LINE>final int k3 = kernel.data[2];<NEW_LINE>final int radius = kernel.getRadius();<NEW_LINE>final int width = image.getWidth();<NEW_LINE>final int halfDivisor = divisor / 2;<NEW_LINE>// CONCURRENT_BELOW BoofConcurrency.loopFor(0, image.height, i -> {<NEW_LINE>for (int i = 0; i < image.height; i++) {<NEW_LINE>int indexDst = dest.startIndex <MASK><NEW_LINE>int j = image.startIndex + i * image.stride - radius;<NEW_LINE>final int jEnd = j + width - radius;<NEW_LINE>for (j += radius; j < jEnd; j++) {<NEW_LINE>int indexSrc = j;<NEW_LINE>int total = (dataSrc[indexSrc++]) * k1;<NEW_LINE>total += (dataSrc[indexSrc++]) * k2;<NEW_LINE>total += (dataSrc[indexSrc]) * k3;<NEW_LINE>dataDst[indexDst++] = ((total + halfDivisor) / divisor);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// CONCURRENT_ABOVE });<NEW_LINE>} | + i * dest.stride + radius; |
1,417,780 | public IRubyObject newMethod(IRubyObject receiver, final String methodName, boolean bound, Visibility visibility, boolean respondToMissing, boolean priv) {<NEW_LINE>CacheEntry entry = searchWithCache(methodName);<NEW_LINE>if (entry.method.isUndefined() || (visibility != null && entry.method.getVisibility() != visibility)) {<NEW_LINE>if (respondToMissing) {<NEW_LINE>// 1.9 behavior<NEW_LINE>if (receiver.respondsToMissing(methodName, priv)) {<NEW_LINE>entry = new CacheEntry(new RespondToMissingMethod(this, PUBLIC, methodName), entry.sourceModule, entry.token);<NEW_LINE>} else {<NEW_LINE>throw getRuntime().newNameError("undefined method `" + methodName + "' for class `" + getName() + '\'', methodName);<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>throw getRuntime().newNameError("undefined method `" + methodName + "' for class `" + getName() + '\'', methodName);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>RubyModule implementationModule = entry.method.getDefinedClass();<NEW_LINE>RubyModule originModule = this;<NEW_LINE>while (originModule != implementationModule && (originModule.isSingleton() || originModule.isIncluded())) {<NEW_LINE>originModule = originModule.getSuperClass();<NEW_LINE>}<NEW_LINE>AbstractRubyMethod newMethod;<NEW_LINE>if (bound) {<NEW_LINE>newMethod = RubyMethod.newMethod(implementationModule, methodName, <MASK><NEW_LINE>} else {<NEW_LINE>newMethod = RubyUnboundMethod.newUnboundMethod(implementationModule, methodName, originModule, methodName, entry);<NEW_LINE>}<NEW_LINE>return newMethod;<NEW_LINE>} | originModule, methodName, entry, receiver); |
1,689,560 | private static WebServiceRefPartialInfo buildPartialInfoFromWebServiceClient(Class<?> serviceInterfaceClass) {<NEW_LINE>WebServiceClient webServiceClient = serviceInterfaceClass.getAnnotation(WebServiceClient.class);<NEW_LINE>if (webServiceClient == null) {<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>String className = serviceInterfaceClass.getName();<NEW_LINE>String wsdlLocation = webServiceClient.wsdlLocation();<NEW_LINE>QName serviceQName = null;<NEW_LINE>String localPart = webServiceClient.name();<NEW_LINE>if (localPart != null) {<NEW_LINE>serviceQName = new QName(<MASK><NEW_LINE>}<NEW_LINE>String handlerChainDeclaringClassName = null;<NEW_LINE>javax.jws.HandlerChain handlerChainAnnotation = serviceInterfaceClass.getAnnotation(javax.jws.HandlerChain.class);<NEW_LINE>if (handlerChainAnnotation != null)<NEW_LINE>handlerChainDeclaringClassName = serviceInterfaceClass.getName();<NEW_LINE>WebServiceRefPartialInfo partialInfo = new WebServiceRefPartialInfo(className, wsdlLocation, serviceQName, null, handlerChainDeclaringClassName, handlerChainAnnotation);<NEW_LINE>return partialInfo;<NEW_LINE>} | webServiceClient.targetNamespace(), localPart); |
1,035,825 | public static StatsGroup createStatsGroup(String groupName, String statsTemplate, StatsInstance parentInstance, ObjectName mBean, StatisticActions actionLsnr) throws StatsFactoryException {<NEW_LINE>if (tc.isEntryEnabled())<NEW_LINE>Tr.entry(tc, new StringBuffer("createStatsGroup:name=").append(groupName).append(";parent instance=").append(parentInstance.getName()).append(";template=").append(statsTemplate).append(";mBean=").append((mBean == null) ? null : mBean.toString()).toString());<NEW_LINE>checkPMIService(groupName);<NEW_LINE>StatsGroup group;<NEW_LINE>try {<NEW_LINE>group = StatsGroupImpl.createGroup(groupName, parentInstance, statsTemplate, mBean, false, actionLsnr);<NEW_LINE>} catch (StatsFactoryException e) {<NEW_LINE>if (tc.isDebugEnabled())<NEW_LINE>Tr.<MASK><NEW_LINE>if (tc.isEntryEnabled())<NEW_LINE>Tr.exit(tc, "createStatsGroup");<NEW_LINE>throw e;<NEW_LINE>}<NEW_LINE>if (tc.isEntryEnabled())<NEW_LINE>Tr.exit(tc, "createStatsGroup");<NEW_LINE>return group;<NEW_LINE>} | debug(tc, "Exception:", e); |
1,011,302 | public void resolvePackageDirectives(CompilationUnitScope cuScope) {<NEW_LINE>if (this.binding == null) {<NEW_LINE>this.ignoreFurtherInvestigation = true;<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>if (this.hasResolvedPackageDirectives)<NEW_LINE>return;<NEW_LINE>this.hasResolvedPackageDirectives = true;<NEW_LINE>Set<PackageBinding> exportedPkgs = new HashSet<>();<NEW_LINE>for (int i = 0; i < this.exportsCount; i++) {<NEW_LINE>ExportsStatement ref = this.exports[i];<NEW_LINE>if (ref != null && ref.resolve(cuScope)) {<NEW_LINE>if (!exportedPkgs.add(ref.resolvedPackage)) {<NEW_LINE>cuScope.problemReporter().invalidPackageReference(IProblem.DuplicateExports, ref);<NEW_LINE>}<NEW_LINE>char[][] targets = null;<NEW_LINE>if (ref.targets != null) {<NEW_LINE>targets = new char[<MASK><NEW_LINE>for (int j = 0; j < targets.length; j++) targets[j] = ref.targets[j].moduleName;<NEW_LINE>}<NEW_LINE>this.binding.addResolvedExport(ref.resolvedPackage, targets);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>HashtableOfObject openedPkgs = new HashtableOfObject();<NEW_LINE>for (int i = 0; i < this.opensCount; i++) {<NEW_LINE>OpensStatement ref = this.opens[i];<NEW_LINE>if (isOpen()) {<NEW_LINE>cuScope.problemReporter().invalidOpensStatement(ref, this);<NEW_LINE>} else {<NEW_LINE>if (openedPkgs.containsKey(ref.pkgName)) {<NEW_LINE>cuScope.problemReporter().invalidPackageReference(IProblem.DuplicateOpens, ref);<NEW_LINE>} else {<NEW_LINE>openedPkgs.put(ref.pkgName, ref);<NEW_LINE>ref.resolve(cuScope);<NEW_LINE>}<NEW_LINE>char[][] targets = null;<NEW_LINE>if (ref.targets != null) {<NEW_LINE>targets = new char[ref.targets.length][];<NEW_LINE>for (int j = 0; j < targets.length; j++) targets[j] = ref.targets[j].moduleName;<NEW_LINE>}<NEW_LINE>this.binding.addResolvedOpens(ref.resolvedPackage, targets);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | ref.targets.length][]; |
991,798 | public static boolean contentHasVisibleContentChildren(Content c) {<NEW_LINE>if (c != null) {<NEW_LINE>try {<NEW_LINE>if (!c.hasChildren()) {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>} catch (TskCoreException ex) {<NEW_LINE>// NON-NLS<NEW_LINE>logger.log(Level.SEVERE, "Error checking if the node has children, for content: " + c, ex);<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>String query = // NON-NLS;<NEW_LINE>"SELECT COUNT(obj_id) AS count FROM " + " ( SELECT obj_id FROM tsk_objects WHERE par_obj_id = " + c.getId() + " AND type = " + TskData.ObjectType.ARTIFACT.getObjectType() + " INTERSECT SELECT artifact_obj_id FROM blackboard_artifacts WHERE obj_id = " + c.getId() + " AND (artifact_type_id = " + ARTIFACT_TYPE.TSK_EMAIL_MSG.getTypeID() + " OR artifact_type_id = " + ARTIFACT_TYPE.TSK_MESSAGE.getTypeID() + ") " + " UNION SELECT obj_id FROM tsk_objects WHERE par_obj_id = " + c.getId() + " AND type = " + TskData.ObjectType<MASK><NEW_LINE>try (SleuthkitCase.CaseDbQuery dbQuery = Case.getCurrentCaseThrows().getSleuthkitCase().executeQuery(query)) {<NEW_LINE>ResultSet resultSet = dbQuery.getResultSet();<NEW_LINE>if (resultSet.next()) {<NEW_LINE>return (0 < resultSet.getInt("count"));<NEW_LINE>}<NEW_LINE>} catch (TskCoreException | SQLException | NoCurrentCaseException ex) {<NEW_LINE>// NON-NLS<NEW_LINE>logger.log(Level.SEVERE, "Error checking if the node has children, for content: " + c, ex);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return false;<NEW_LINE>} | .ABSTRACTFILE.getObjectType() + ") AS OBJECT_IDS"; |
1,231,926 | public void execute(AdminCommandContext context) {<NEW_LINE>if (appName != null) {<NEW_LINE>if (!isValidApplication(appName)) {<NEW_LINE>ActionReport report = context.getActionReport();<NEW_LINE>report.setActionExitCode(ActionReport.ExitCode.FAILURE);<NEW_LINE>ActionReport.MessagePart messagePart = report.getTopMessagePart();<NEW_LINE>messagePart.setMessage("Invalid application [" + appName + "]");<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (moduleName != null) {<NEW_LINE>if (!isValidModule(appName, moduleName)) {<NEW_LINE>ActionReport report = context.getActionReport();<NEW_LINE>report.setActionExitCode(ActionReport.ExitCode.FAILURE);<NEW_LINE>ActionReport.MessagePart messagePart = report.getTopMessagePart();<NEW_LINE>messagePart.setMessage("Invalid module [" + moduleName + "] in application [" + appName + "]");<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (appName != null && moduleName != null) {<NEW_LINE>Application application = applications.getApplication(appName);<NEW_LINE>Module module = application.getModule(moduleName);<NEW_LINE>Resources moduleScopedResources = module.getResources();<NEW_LINE>if (moduleScopedResources != null) {<NEW_LINE>ActionReport report = context.getActionReport();<NEW_LINE>ActionReport.MessagePart messagePart = report.getTopMessagePart();<NEW_LINE>generateResourcesList(messagePart, moduleScopedResources.getResources());<NEW_LINE>}<NEW_LINE>} else if (appName != null) {<NEW_LINE>Application application = applications.getApplication(appName);<NEW_LINE><MASK><NEW_LINE>if (appScopedResources != null) {<NEW_LINE>ActionReport report = context.getActionReport();<NEW_LINE>ActionReport.MessagePart messagePart = report.getTopMessagePart();<NEW_LINE>generateResourcesList(messagePart, appScopedResources.getResources());<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | Resources appScopedResources = application.getResources(); |
1,836,853 | public void start() throws Throwable {<NEW_LINE>if (!started.compareAndSet(false, true)) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>boss = new NioEventLoopGroup(1, <MASK><NEW_LINE>worker = new NioEventLoopGroup(0, new DefaultThreadFactory("qos-worker", true));<NEW_LINE>ServerBootstrap serverBootstrap = new ServerBootstrap();<NEW_LINE>serverBootstrap.group(boss, worker);<NEW_LINE>serverBootstrap.channel(NioServerSocketChannel.class);<NEW_LINE>serverBootstrap.option(ChannelOption.SO_REUSEADDR, true);<NEW_LINE>serverBootstrap.childOption(ChannelOption.TCP_NODELAY, true);<NEW_LINE>serverBootstrap.childHandler(new ChannelInitializer<Channel>() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>protected void initChannel(Channel ch) throws Exception {<NEW_LINE>ch.pipeline().addLast(new QosProcessHandler(frameworkModel, welcome, acceptForeignIp));<NEW_LINE>}<NEW_LINE>});<NEW_LINE>try {<NEW_LINE>if (StringUtils.isBlank(host)) {<NEW_LINE>serverBootstrap.bind(port).sync();<NEW_LINE>} else {<NEW_LINE>serverBootstrap.bind(host, port).sync();<NEW_LINE>}<NEW_LINE>logger.info("qos-server bind localhost:" + port);<NEW_LINE>} catch (Throwable throwable) {<NEW_LINE>logger.error("qos-server can not bind localhost:" + port, throwable);<NEW_LINE>throw throwable;<NEW_LINE>}<NEW_LINE>} | new DefaultThreadFactory("qos-boss", true)); |
1,771,000 | public void processStartupAnswer(final Answer answer, final Response response, final Link link) {<NEW_LINE>boolean cancelled = false;<NEW_LINE>synchronized (this) {<NEW_LINE>if (_startup != null) {<NEW_LINE>_startup.cancel();<NEW_LINE>_startup = null;<NEW_LINE>} else {<NEW_LINE>cancelled = true;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>final StartupAnswer startup = (StartupAnswer) answer;<NEW_LINE>if (!startup.getResult()) {<NEW_LINE>s_logger.error("Not allowed to connect to the server: " + answer.getDetails());<NEW_LINE>System.exit(1);<NEW_LINE>}<NEW_LINE>if (cancelled) {<NEW_LINE>s_logger.warn("Threw away a startup answer because we're reconnecting.");<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>s_logger.info("Process agent startup answer, agent id = " + startup.getHostId());<NEW_LINE>setId(startup.getHostId());<NEW_LINE>// change to ms.<NEW_LINE>_pingInterval = (long) startup.getPingInterval() * 1000;<NEW_LINE>setLastPingResponseTime();<NEW_LINE>scheduleWatch(link, response, _pingInterval, _pingInterval);<NEW_LINE>_ugentTaskPool.setKeepAliveTime(<MASK><NEW_LINE>s_logger.info("Startup Response Received: agent id = " + getId());<NEW_LINE>} | 2 * _pingInterval, TimeUnit.MILLISECONDS); |
1,341,298 | public void registry() {<NEW_LINE>String address = NetUtils.getAddr(masterConfig.getListenPort());<NEW_LINE>localNodePath = getMasterPath();<NEW_LINE>int masterHeartbeatInterval = masterConfig.getHeartbeatInterval();<NEW_LINE>HeartBeatTask heartBeatTask = new HeartBeatTask(startupTime, masterConfig.getMaxCpuLoadAvg(), masterConfig.getReservedMemory(), Sets.newHashSet(getMasterPath()), Constants.MASTER_TYPE, registryClient);<NEW_LINE>// remove before persist<NEW_LINE>registryClient.remove(localNodePath);<NEW_LINE>registryClient.persistEphemeral(localNodePath, heartBeatTask.getHeartBeatInfo());<NEW_LINE>while (!registryClient.checkNodeExists(NetUtils.getHost(), NodeType.MASTER)) {<NEW_LINE>ThreadUtils.sleep(SLEEP_TIME_MILLIS);<NEW_LINE>}<NEW_LINE>// sleep 1s, waiting master failover remove<NEW_LINE>ThreadUtils.sleep(SLEEP_TIME_MILLIS);<NEW_LINE>// delete dead server<NEW_LINE>registryClient.handleDeadServer(Collections.singleton(localNodePath), NodeType.MASTER, Constants.DELETE_OP);<NEW_LINE><MASK><NEW_LINE>this.heartBeatExecutor.scheduleAtFixedRate(heartBeatTask, masterHeartbeatInterval, masterHeartbeatInterval, TimeUnit.SECONDS);<NEW_LINE>logger.info("master node : {} registry to ZK successfully with heartBeatInterval : {}s", address, masterHeartbeatInterval);<NEW_LINE>} | registryClient.addConnectionStateListener(this::handleConnectionState); |
1,062,007 | public static HystrixObservableCommand.Setter build(final HystrixHandle hystrixHandle) {<NEW_LINE>initHystrixHandleOnRequire(hystrixHandle);<NEW_LINE>HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.<MASK><NEW_LINE>HystrixCommandKey commandKey = HystrixCommandKey.Factory.asKey(hystrixHandle.getCommandKey());<NEW_LINE>HystrixCommandProperties.Setter propertiesSetter = HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds((int) hystrixHandle.getTimeout()).withCircuitBreakerEnabled(true).withExecutionIsolationStrategy(HystrixCommandProperties.ExecutionIsolationStrategy.SEMAPHORE).withExecutionIsolationSemaphoreMaxConcurrentRequests(hystrixHandle.getMaxConcurrentRequests()).withCircuitBreakerErrorThresholdPercentage(hystrixHandle.getErrorThresholdPercentage()).withCircuitBreakerRequestVolumeThreshold(hystrixHandle.getRequestVolumeThreshold()).withCircuitBreakerSleepWindowInMilliseconds(hystrixHandle.getSleepWindowInMilliseconds());<NEW_LINE>return HystrixObservableCommand.Setter.withGroupKey(groupKey).andCommandKey(commandKey).andCommandPropertiesDefaults(propertiesSetter);<NEW_LINE>} | asKey(hystrixHandle.getGroupKey()); |
581,388 | boolean serialize(StringBuilder destination, EquivItem item) {<NEW_LINE>String annotations = leafAnnotations(item);<NEW_LINE>destination.append(getIndexName(item.getItem(0))).append(" contains ");<NEW_LINE>if (annotations.length() > 0) {<NEW_LINE>destination.append("([{").append(annotations).append("}]");<NEW_LINE>}<NEW_LINE>destination.append(EQUIV).append('(');<NEW_LINE>int initLen = destination.length();<NEW_LINE>for (Iterator<Item> i = item.getItemIterator(); i.hasNext(); ) {<NEW_LINE>Item x = i.next();<NEW_LINE>if (destination.length() > initLen) {<NEW_LINE>destination.append(", ");<NEW_LINE>}<NEW_LINE>if (x instanceof PhraseItem) {<NEW_LINE>PhraseSerializer.serialize(destination, (PhraseItem) x, false);<NEW_LINE>} else {<NEW_LINE>destination.append('"');<NEW_LINE>escape(((IndexedItem) x<MASK><NEW_LINE>destination.append('"');<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (annotations.length() > 0) {<NEW_LINE>destination.append(')');<NEW_LINE>}<NEW_LINE>destination.append(')');<NEW_LINE>return false;<NEW_LINE>} | ).getIndexedString(), destination); |
1,676,140 | static void paintNot(InstancePainter painter) {<NEW_LINE>final var g = painter.getGraphics();<NEW_LINE>GraphicsUtil.switchToWidth(g, 2);<NEW_LINE>if (painter.getAttributeValue(NotGate.ATTR_SIZE) == NotGate.SIZE_NARROW) {<NEW_LINE>GraphicsUtil.switchToWidth(g, 2);<NEW_LINE>int[] xp = new int[4];<NEW_LINE>int[] yp = new int[4];<NEW_LINE>xp[0] = -6;<NEW_LINE>yp[0] = 0;<NEW_LINE>xp[1] = -19;<NEW_LINE>yp[1] = -6;<NEW_LINE>xp[2] = -19;<NEW_LINE>yp[2] = 6;<NEW_LINE>xp[3] = -6;<NEW_LINE>yp[3] = 0;<NEW_LINE>g.drawPolyline(xp, yp, 4);<NEW_LINE>g.drawOval(-6, -3, 6, 6);<NEW_LINE>} else {<NEW_LINE>int[] xp = new int[4];<NEW_LINE>int[] yp = new int[4];<NEW_LINE>xp[0] = -10;<NEW_LINE>yp[0] = 0;<NEW_LINE>xp[1] = -29;<NEW_LINE>yp[1] = -7;<NEW_LINE>xp[2] = -29;<NEW_LINE>yp[2] = 7;<NEW_LINE>xp[3] = -10;<NEW_LINE>yp[3] = 0;<NEW_LINE>g.<MASK><NEW_LINE>g.drawOval(-9, -4, 9, 9);<NEW_LINE>}<NEW_LINE>} | drawPolyline(xp, yp, 4); |
1,802,530 | static void createModelMap() {<NEW_LINE>if (modelMap != null)<NEW_LINE>return;<NEW_LINE>modelMap = new HashMap<String, DiodeModel>();<NEW_LINE>addDefaultModel("spice-default", new DiodeModel(1e-14, 0, 1, 0, null));<NEW_LINE>addDefaultModel("default", new DiodeModel(1.7143528192808883e-7, 0, 2, 0, null));<NEW_LINE>addDefaultModel("default-zener", new DiodeModel(1.7143528192808883e-7, 0, 2, 5.6, null));<NEW_LINE>// old default LED with saturation current that is way too small (causes numerical errors)<NEW_LINE>addDefaultModel("old-default-led", new DiodeModel(2.2349907006671927e-18, 0<MASK><NEW_LINE>// default for newly created LEDs, https://www.diyaudio.com/forums/software-tools/25884-spice-models-led.html<NEW_LINE>addDefaultModel("default-led", new DiodeModel(93.2e-12, .042, 3.73, 0, null));<NEW_LINE>// https://www.allaboutcircuits.com/textbook/semiconductors/chpt-3/spice-models/<NEW_LINE>addDefaultModel("1N5711", new DiodeModel(315e-9, 2.8, 2.03, 70, "Schottky"));<NEW_LINE>addDefaultModel("1N5712", new DiodeModel(680e-12, 12, 1.003, 20, "Schottky"));<NEW_LINE>addDefaultModel("1N34", new DiodeModel(200e-12, 84e-3, 2.19, 60, "germanium"));<NEW_LINE>addDefaultModel("1N4004", new DiodeModel(18.8e-9, 28.6e-3, 2, 400, "general purpose"));<NEW_LINE>// addDefaultModel("1N3891", new DiodeModel(63e-9, 9.6e-3, 2, 0)); // doesn't match datasheet very well<NEW_LINE>// http://users.skynet.be/hugocoolens/spice/diodes/1n4148.htm<NEW_LINE>addDefaultModel("1N4148", new DiodeModel(4.352e-9, .6458, 1.906, 75, "switching"));<NEW_LINE>} | , 2, 0, null)); |
241,190 | public void addArgs(List<String> args) throws Exception {<NEW_LINE>ArgumentWriter writer = new ArgumentWriter(instance);<NEW_LINE>writer.writeIfSet("-ORBListenEndpoints", ORB_LISTEN_ENDPOINTS);<NEW_LINE>writer.writeIfSet("-ORBDebugLevel", ORB_DEBUG_LEVEL);<NEW_LINE>writer.writeIfSet("-ORBLogFile", ORB_LOG_FILE);<NEW_LINE>writer.writeDelimitedIfSet(ORB_ARGS);<NEW_LINE>writer.writeMultiLineIfSet(SvcConfDirective.ARGUMENT_NAME, ORB_DIRECTIVES);<NEW_LINE>Boolean disableNestedUpcalls = (Boolean) instance.getAttribute(ORB_DISABLE_NESTED_UPCALLS);<NEW_LINE>if (disableNestedUpcalls != null && disableNestedUpcalls) {<NEW_LINE>SvcConfDirective directive;<NEW_LINE>directive = new SvcConfDirective();<NEW_LINE>directive.setServiceName("Client_Strategy_Factory");<NEW_LINE>directive.addOptions("-ORBWaitStrategy", "rw");<NEW_LINE>directive.addOptions("-ORBTransportMuxStrategy", "exclusive");<NEW_LINE>directive.addOptions("-ORBConnectStrategy", "blocked");<NEW_LINE><MASK><NEW_LINE>directive.writeTo(writer);<NEW_LINE>directive = new SvcConfDirective();<NEW_LINE>directive.setServiceName("Resource_Factory");<NEW_LINE>directive.addOptions("-ORBFlushingStrategy", "blocking");<NEW_LINE>directive.writeTo(writer);<NEW_LINE>}<NEW_LINE>writer.writeTo(args);<NEW_LINE>} | directive.addOptions("-ORBConnectionHandlerCleanup", "1"); |
155,431 | public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) throws SAXException {<NEW_LINE>if (qName.equals("entry")) {<NEW_LINE>entryElement = true;<NEW_LINE>String type = attributes.getValue("type");<NEW_LINE>if (type.equals("file")) {<NEW_LINE>directory = false;<NEW_LINE>size = Long.parseLong(attributes.getValue("size"));<NEW_LINE><MASK><NEW_LINE>jarFile = Boolean.parseBoolean(attributes.getValue("jar"));<NEW_LINE>if (jarFile) {<NEW_LINE>packed = Boolean.parseBoolean(attributes.getValue("packed"));<NEW_LINE>signed = Boolean.parseBoolean(attributes.getValue("signed"));<NEW_LINE>} else {<NEW_LINE>packed = false;<NEW_LINE>signed = false;<NEW_LINE>}<NEW_LINE>modified = Long.parseLong(attributes.getValue("modified"));<NEW_LINE>permissions = Integer.parseInt(attributes.getValue("permissions"), 8);<NEW_LINE>} else {<NEW_LINE>directory = true;<NEW_LINE>empty = Boolean.parseBoolean(attributes.getValue("empty"));<NEW_LINE>modified = Long.parseLong(attributes.getValue("modified"));<NEW_LINE>permissions = Integer.parseInt(attributes.getValue("permissions"), 8);<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>entryElement = false;<NEW_LINE>}<NEW_LINE>} | md5 = attributes.getValue("md5"); |
436,183 | public ReadableShopOrder populate(ShopOrder source, ReadableShopOrder target, MerchantStore store, Language language) throws ConversionException {<NEW_LINE>// not that much is required<NEW_LINE>// customer<NEW_LINE>try {<NEW_LINE>ReadableCustomer customer = new ReadableCustomer();<NEW_LINE>PersistableCustomer persistableCustomer = source.getCustomer();<NEW_LINE>customer.setEmailAddress(persistableCustomer.getEmailAddress());<NEW_LINE>if (persistableCustomer.getBilling() != null) {<NEW_LINE>Address address = new Address();<NEW_LINE>address.setCity(persistableCustomer.getBilling().getCity());<NEW_LINE>address.setCompany(persistableCustomer.getBilling().getCompany());<NEW_LINE>address.setFirstName(persistableCustomer.getBilling().getFirstName());<NEW_LINE>address.setLastName(persistableCustomer.getBilling().getLastName());<NEW_LINE>address.setPostalCode(persistableCustomer.getBilling().getPostalCode());<NEW_LINE>address.setPhone(persistableCustomer.getBilling().getPhone());<NEW_LINE>if (persistableCustomer.getBilling().getCountry() != null) {<NEW_LINE>address.setCountry(persistableCustomer.getBilling().getCountry());<NEW_LINE>}<NEW_LINE>if (persistableCustomer.getBilling().getZone() != null) {<NEW_LINE>address.setZone(persistableCustomer.getBilling().getZone());<NEW_LINE>}<NEW_LINE>customer.setBilling(address);<NEW_LINE>}<NEW_LINE>if (persistableCustomer.getDelivery() != null) {<NEW_LINE>Address address = new Address();<NEW_LINE>address.setCity(persistableCustomer.getDelivery().getCity());<NEW_LINE>address.setCompany(persistableCustomer.getDelivery().getCompany());<NEW_LINE>address.setFirstName(persistableCustomer.getDelivery().getFirstName());<NEW_LINE>address.setLastName(persistableCustomer.getDelivery().getLastName());<NEW_LINE>address.setPostalCode(persistableCustomer.<MASK><NEW_LINE>address.setPhone(persistableCustomer.getDelivery().getPhone());<NEW_LINE>if (persistableCustomer.getDelivery().getCountry() != null) {<NEW_LINE>address.setCountry(persistableCustomer.getDelivery().getCountry());<NEW_LINE>}<NEW_LINE>if (persistableCustomer.getDelivery().getZone() != null) {<NEW_LINE>address.setZone(persistableCustomer.getDelivery().getZone());<NEW_LINE>}<NEW_LINE>customer.setDelivery(address);<NEW_LINE>}<NEW_LINE>// TODO if ship to billing enabled, set delivery = billing<NEW_LINE>target.setCustomer(customer);<NEW_LINE>} catch (Exception e) {<NEW_LINE>throw new ConversionException(e);<NEW_LINE>}<NEW_LINE>return target;<NEW_LINE>} | getDelivery().getPostalCode()); |
1,606,386 | public void parseSelectFields(JoinInfo joinInfo) {<NEW_LINE>String sideTableName = joinInfo.getSideTableName();<NEW_LINE>String nonSideTableName = joinInfo.getNonSideTable();<NEW_LINE>List<String> fields = Lists.newArrayList();<NEW_LINE>int sideTableFieldIndex = 0;<NEW_LINE>for (int i = 0; i < outFieldInfoList.size(); i++) {<NEW_LINE>FieldInfo fieldInfo = outFieldInfoList.get(i);<NEW_LINE>if (fieldInfo.getTable().equalsIgnoreCase(sideTableName)) {<NEW_LINE>String sideFieldName = sideTableInfo.getPhysicalFields().getOrDefault(fieldInfo.getFieldName(), fieldInfo.getFieldName());<NEW_LINE>fields.add(sideFieldName);<NEW_LINE>sideSelectFieldsType.put(sideTableFieldIndex, getTargetFieldType(fieldInfo.getFieldName()));<NEW_LINE>sideFieldIndex.put(i, sideTableFieldIndex);<NEW_LINE>sideFieldNameIndex.put(i, sideFieldName);<NEW_LINE>sideTableFieldIndex++;<NEW_LINE>} else if (fieldInfo.getTable().equalsIgnoreCase(nonSideTableName)) {<NEW_LINE>int nonSideIndex = rowTypeInfo.getFieldIndex(fieldInfo.getFieldName());<NEW_LINE><MASK><NEW_LINE>} else {<NEW_LINE>throw new RuntimeException("unknown table " + fieldInfo.getTable());<NEW_LINE>}<NEW_LINE>}<NEW_LINE>sideSelectFields = String.join(",", fields);<NEW_LINE>} | inFieldIndex.put(i, nonSideIndex); |
1,049,048 | private void replayResponseToBrowser(CrawlURI curi, InterceptedRequest interceptedRequest) {<NEW_LINE>// There seems to be no easy way to stream the body to the browser so we slurp it into<NEW_LINE>// memory with a size limit. The one way I can see to achieve streaming is to have Heritrix<NEW_LINE>// serve the request over its HTTP server and pass a Heritrix URL to Fetch.fulfillRequest<NEW_LINE>// instead of the body directly. We might need to do that if memory pressure becomes a<NEW_LINE>// problem but for now just keep it simple.<NEW_LINE>long bodyLength = curi.getRecorder().getResponseContentLength();<NEW_LINE>if (bodyLength > maxReplayLength) {<NEW_LINE>logger.log(FINE, <MASK><NEW_LINE>interceptedRequest.continueNormally();<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>byte[] body = new byte[(int) bodyLength];<NEW_LINE>try (InputStream stream = curi.getRecorder().getContentReplayInputStream()) {<NEW_LINE>IOUtils.readFully(stream, body);<NEW_LINE>} catch (IOException e) {<NEW_LINE>logger.log(WARNING, "Error reading back page body: " + curi.getURI(), e);<NEW_LINE>interceptedRequest.continueNormally();<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>Map<String, String> headers = (Map<String, String>) curi.getData().get(A_HTTP_RESPONSE_HEADERS);<NEW_LINE>if (headers == null) {<NEW_LINE>logger.log(WARNING, "Response headers unavailable in CrawlURI. Letting the browser " + "refetch {0}", curi.getURI());<NEW_LINE>interceptedRequest.continueNormally();<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>interceptedRequest.fulfill(curi.getFetchStatus(), headers.entrySet(), body);<NEW_LINE>} | "Page body too large to replay: {0}", curi.getURI()); |
1,082,497 | private void insertDraggedEntities(MouseEvent me) {<NEW_LINE>GridElement entity = handler.getDrawPanel().getElementToComponent(me.getComponent());<NEW_LINE>DrawPanel currentDiagram = CurrentGui.getInstance().getGui().getCurrentDiagram();<NEW_LINE>List<GridElement> selectedEntities = handler.getDrawPanel().getSelector().getSelectedElements();<NEW_LINE>if (!allowCopyEntity()) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>copiedEntities.clear();<NEW_LINE>// We save the actual zoom level of the diagram and the palette<NEW_LINE>int oldZoomDiagram = currentDiagram.getHandler().getGridSize();<NEW_LINE>int oldZoomPalette = handler.getGridSize();<NEW_LINE>// and reset the zoom level of both to default before inserting the new entity (to avoid problems with entity-size)<NEW_LINE>currentDiagram.getHandler().setGridAndZoom(Constants.DEFAULTGRIDSIZE, false);<NEW_LINE>handler.setGridAndZoom(Constants.DEFAULTGRIDSIZE, false);<NEW_LINE>IS_DRAGGING = false;<NEW_LINE>IS_DRAGGED_FROM_PALETTE = true;<NEW_LINE>for (GridElement currentEntity : selectedEntities) {<NEW_LINE>GridElement copiedEntity = copyEntity(currentEntity);<NEW_LINE>copiedEntities.add(copiedEntity);<NEW_LINE>int x = currentEntity.getRectangle().x <MASK><NEW_LINE>int y = currentEntity.getRectangle().y - entity.getRectangle().y;<NEW_LINE>x -= entity.getRectangle().width / 2;<NEW_LINE>y -= entity.getRectangle().height / 2;<NEW_LINE>copiedEntity.setLocation(x, y);<NEW_LINE>}<NEW_LINE>Selector.replaceGroupsWithNewGroups(copiedEntities, selector);<NEW_LINE>// After inserting the new entity we restore the old zoom level of both diagrams<NEW_LINE>currentDiagram.getHandler().setGridAndZoom(oldZoomDiagram, false);<NEW_LINE>handler.setGridAndZoom(oldZoomPalette, false);<NEW_LINE>// set entity positions relative to current mouse pointer location on screen<NEW_LINE>updateEntityPositions(me);<NEW_LINE>} | - entity.getRectangle().x; |
1,390,294 | public static <T> void quickSort(long[] ids, T[] values, int low, int high) {<NEW_LINE>if (low < high) {<NEW_LINE>int mid = (low + high) / 2;<NEW_LINE>long tmp = ids[mid];<NEW_LINE>T tmpValue = values[mid];<NEW_LINE>ids[mid] = ids[low];<NEW_LINE>values[mid] = values[low];<NEW_LINE>ids[low] = tmp;<NEW_LINE>values[low] = tmpValue;<NEW_LINE>int ii = low, jj = high;<NEW_LINE>while (ii < jj) {<NEW_LINE>while (ii < jj && ids[jj] >= tmp) {<NEW_LINE>jj--;<NEW_LINE>}<NEW_LINE>ids<MASK><NEW_LINE>values[ii] = values[jj];<NEW_LINE>while (ii < jj && ids[ii] <= tmp) {<NEW_LINE>ii++;<NEW_LINE>}<NEW_LINE>ids[jj] = ids[ii];<NEW_LINE>values[jj] = values[ii];<NEW_LINE>}<NEW_LINE>ids[ii] = tmp;<NEW_LINE>values[ii] = tmpValue;<NEW_LINE>quickSort(ids, values, low, ii - 1);<NEW_LINE>quickSort(ids, values, ii + 1, high);<NEW_LINE>}<NEW_LINE>} | [ii] = ids[jj]; |
1,360,120 | private void citationNotExists(EntityManagerContainerBasic emc, Field field, String value, JpaObject jpa, CheckPersist checkPersist, CheckPersistType checkPersistType) throws Exception {<NEW_LINE>if (StringUtils.isNotEmpty(value) && (!ArrayUtils.contains(checkPersist.excludes(), value))) {<NEW_LINE>for (CitationNotExist citationNotExist : checkPersist.citationNotExists()) {<NEW_LINE>EntityManager em = emc.get(citationNotExist.type());<NEW_LINE>CriteriaBuilder cb = em.getCriteriaBuilder();<NEW_LINE>CriteriaQuery<Long> cq = cb.createQuery(Long.class);<NEW_LINE>Root<? extends JpaObject> root = cq.from(citationNotExist.type());<NEW_LINE>Predicate p = cb.disjunction();<NEW_LINE>for (String str : citationNotExist.fields()) {<NEW_LINE>Path<?> path = root.get(str);<NEW_LINE>if (JpaObjectTools.isList(path)) {<NEW_LINE>p = cb.or(p, cb.isMember(value, (Path<List<String>>) path));<NEW_LINE>} else {<NEW_LINE>p = cb.or(p, cb.equal(path, value));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>p = cb.and(p, cb.notEqual(root.get("id"), jpa.getId()));<NEW_LINE>for (Equal o : citationNotExist.equals()) {<NEW_LINE>p = cb.and(p, cb.equal(root.get(o.field()), jpa.get(o.property())));<NEW_LINE>}<NEW_LINE>for (NotEqual o : citationNotExist.notEquals()) {<NEW_LINE>p = cb.and(p, cb.notEqual(root.get(o.field()), jpa.get(o.property())));<NEW_LINE>}<NEW_LINE>cq.select(cb.count(root)).where(p);<NEW_LINE>Long count = em.createQuery(cq).getSingleResult();<NEW_LINE>if (count != 0) {<NEW_LINE>throw new Exception("check persist stirngValue citationNotExists error, class:" + jpa.getClass().getName() + ", field:" + field.getName() + ", value: " + value + " must be a not existed in class:" + citationNotExist.type() + ", fields:" + StringUtils.join(citationNotExist.fields<MASK><NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | (), ",") + "."); |
146,716 | public ErrorCode action(ByteBuf ackPayload, String clientID, String fromUser, ProtoConstants.RequestSourceType requestSourceType, WFCMessage.RouteRequest request, Qos1PublishHandler.IMCallback callback) {<NEW_LINE>MemorySessionStore.Session session = m_sessionsStore.sessionForClientAndUser(fromUser, clientID);<NEW_LINE>if (session == null) {<NEW_LINE>ErrorCode errorCode = m_sessionsStore.loadActiveSession(fromUser, clientID);<NEW_LINE>if (errorCode != ErrorCode.ERROR_CODE_SUCCESS) {<NEW_LINE>return errorCode;<NEW_LINE>}<NEW_LINE>session = m_sessionsStore.sessionForClientAndUser(fromUser, clientID);<NEW_LINE>}<NEW_LINE>if (session == null || session.getDeleted() > 0) {<NEW_LINE>if (session == null) {<NEW_LINE>LOG.error("Session for <{}, {}> not exist", fromUser, clientID);<NEW_LINE>} else {<NEW_LINE>LOG.error("Session for <{}, {}> deleted", fromUser, clientID);<NEW_LINE>}<NEW_LINE>return ErrorCode.ERROR_CODE_SECRECT_KEY_MISMATCH;<NEW_LINE>}<NEW_LINE><MASK><NEW_LINE>String longPort = mServer.getLongPort();<NEW_LINE>String shortPort = mServer.getShortPort();<NEW_LINE>ClientSession clientSession = m_sessionsStore.sessionForClient(clientID);<NEW_LINE>boolean isSessionAlreadyStored = clientSession != null;<NEW_LINE>if (!isSessionAlreadyStored) {<NEW_LINE>m_sessionsStore.loadActiveSession(fromUser, clientID);<NEW_LINE>} else {<NEW_LINE>m_sessionsStore.updateExistSession(fromUser, clientID, request, true);<NEW_LINE>}<NEW_LINE>WFCMessage.RouteResponse response = WFCMessage.RouteResponse.newBuilder().setHost(serverIp).setLongPort(Integer.parseInt(longPort)).setShortPort(Integer.parseInt(shortPort)).build();<NEW_LINE>byte[] data = response.toByteArray();<NEW_LINE>ackPayload.ensureWritable(data.length).writeBytes(data);<NEW_LINE>return ErrorCode.ERROR_CODE_SUCCESS;<NEW_LINE>} | String serverIp = mServer.getServerIp(); |
1,010,619 | private synchronized boolean moveProperties(String oldPath, String newPath) throws IOException {<NEW_LINE>String oldSubListPath = oldPath + ".";<NEW_LINE>String newSubListPath = newPath + ".";<NEW_LINE>// check for move conflict<NEW_LINE>if (propertyTable.getRecord(new StringField(newPath)) != null) {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>RecordIterator iterator = propertyTable.iterator(new StringField(newSubListPath));<NEW_LINE>DBRecord rec = iterator.next();<NEW_LINE>if (rec != null) {<NEW_LINE>String keyName = ((StringField) rec.getKeyField()).getString();<NEW_LINE>if (keyName.startsWith(newSubListPath)) {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// move records<NEW_LINE>ArrayList<DBRecord> list = new ArrayList<>();<NEW_LINE>rec = propertyTable.getRecord(new StringField(oldPath));<NEW_LINE>if (rec != null) {<NEW_LINE>propertyTable.deleteRecord(new StringField(oldPath));<NEW_LINE>rec.setKey(new StringField(newPath));<NEW_LINE>list.add(rec);<NEW_LINE>}<NEW_LINE>iterator = propertyTable.iterator(new StringField(oldSubListPath));<NEW_LINE>while (iterator.hasNext()) {<NEW_LINE>rec = iterator.next();<NEW_LINE>String keyName = ((StringField) rec.getKeyField()).getString();<NEW_LINE>if (keyName.startsWith(oldSubListPath)) {<NEW_LINE>iterator.delete();<NEW_LINE>rec.setKey(new StringField(newSubListPath + keyName.substring(<MASK><NEW_LINE>list.add(rec);<NEW_LINE>} else {<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>for (DBRecord updatedRec : list) {<NEW_LINE>propertyTable.putRecord(updatedRec);<NEW_LINE>}<NEW_LINE>return true;<NEW_LINE>} | oldSubListPath.length()))); |
1,403,878 | public void aesDecrypt(final byte[] key, InputStream in, OutputStream out, long inputSize) throws IOException, CryptoError {<NEW_LINE>InputStream decrypted = null;<NEW_LINE>try {<NEW_LINE>byte[] cKey = key;<NEW_LINE>boolean macIncluded = inputSize % 2 == 1;<NEW_LINE>if (macIncluded) {<NEW_LINE>SubKeys subKeys = getSubKeys(bytesToKey(key), true);<NEW_LINE>cKey = subKeys.cKey.getEncoded();<NEW_LINE>ByteArrayOutputStream tempOut = new ByteArrayOutputStream();<NEW_LINE>IOUtils.copyLarge(in, tempOut);<NEW_LINE>byte[] cipherText = tempOut.toByteArray();<NEW_LINE>byte[] cipherTextWithoutMac = Arrays.copyOfRange(cipherText, 1, cipherText.length - 32);<NEW_LINE>byte[] providedMacBytes = Arrays.copyOfRange(cipherText, cipherText.length - 32, cipherText.length);<NEW_LINE>byte[] computedMacBytes = hmac256(subKeys.mKey, cipherTextWithoutMac);<NEW_LINE>if (!Arrays.equals(computedMacBytes, providedMacBytes)) {<NEW_LINE>throw new CryptoError("invalid mac");<NEW_LINE>}<NEW_LINE>in = new ByteArrayInputStream(cipherTextWithoutMac);<NEW_LINE>}<NEW_LINE>byte[] iv = new byte[AES_KEY_LENGTH_BYTES];<NEW_LINE><MASK><NEW_LINE>Cipher cipher = Cipher.getInstance(AES_MODE_PADDING);<NEW_LINE>IvParameterSpec params = new IvParameterSpec(iv);<NEW_LINE>cipher.init(Cipher.DECRYPT_MODE, bytesToKey(cKey), params);<NEW_LINE>decrypted = getCipherInputStream(in, cipher);<NEW_LINE>IOUtils.copyLarge(decrypted, out, new byte[1024 * 1000]);<NEW_LINE>} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidAlgorithmParameterException e) {<NEW_LINE>throw new RuntimeException(e);<NEW_LINE>} catch (InvalidKeyException e) {<NEW_LINE>throw new CryptoError(e);<NEW_LINE>} finally {<NEW_LINE>IOUtils.closeQuietly(in);<NEW_LINE>IOUtils.closeQuietly(decrypted);<NEW_LINE>IOUtils.closeQuietly(out);<NEW_LINE>}<NEW_LINE>} | IOUtils.read(in, iv); |
1,827,251 | protected int doWork() {<NEW_LINE>final List<Path> <MASK><NEW_LINE>if (TEST_INPUT_READABILITY) {<NEW_LINE>IOUtil.assertPathsAreReadable(inputPaths);<NEW_LINE>}<NEW_LINE>IOUtil.assertFileIsReadable(HAPLOTYPE_MAP);<NEW_LINE>IOUtil.assertFileIsWritable(OUTPUT);<NEW_LINE>final FingerprintChecker checker = new FingerprintChecker(HAPLOTYPE_MAP);<NEW_LINE>final MetricsFile<FingerprintMetrics, ?> metricsFile = getMetricsFile();<NEW_LINE>final Map<FingerprintIdDetails, Fingerprint> fpMap = checker.fingerprintFiles(inputPaths, 1, 1, TimeUnit.DAYS);<NEW_LINE>final Map<FingerprintIdDetails, Fingerprint> mergedFpMap = Fingerprint.mergeFingerprintsBy(fpMap, Fingerprint.getFingerprintIdDetailsStringFunction(CALCULATE_BY));<NEW_LINE>metricsFile.addAllMetrics(mergedFpMap.values().stream().map(this::getFingerprintMetrics).collect(Collectors.toList()));<NEW_LINE>metricsFile.write(OUTPUT);<NEW_LINE>return 0;<NEW_LINE>} | inputPaths = IOUtil.getPaths(INPUT); |
737,753 | public static void copyHtmlInputTextAttributes(HtmlInputText src, HtmlInputText dest) {<NEW_LINE>dest.setId(src.getId());<NEW_LINE>boolean forceId = getBooleanValue(JSFAttr.FORCE_ID_ATTR, src.getAttributes().get(JSFAttr.FORCE_ID_ATTR), false);<NEW_LINE>if (forceId) {<NEW_LINE>dest.getAttributes().put(JSFAttr.FORCE_ID_ATTR, Boolean.TRUE);<NEW_LINE>}<NEW_LINE>dest.setImmediate(src.isImmediate());<NEW_LINE>dest.setTransient(src.isTransient());<NEW_LINE>dest.<MASK><NEW_LINE>dest.setAlt(src.getAlt());<NEW_LINE>dest.setConverter(src.getConverter());<NEW_LINE>dest.setDir(src.getDir());<NEW_LINE>dest.setDisabled(src.isDisabled());<NEW_LINE>dest.setLang(src.getLang());<NEW_LINE>dest.setLocalValueSet(src.isLocalValueSet());<NEW_LINE>dest.setMaxlength(src.getMaxlength());<NEW_LINE>dest.setOnblur(src.getOnblur());<NEW_LINE>dest.setOnchange(src.getOnchange());<NEW_LINE>dest.setOnclick(src.getOnclick());<NEW_LINE>dest.setOndblclick(src.getOndblclick());<NEW_LINE>dest.setOnfocus(src.getOnfocus());<NEW_LINE>dest.setOnkeydown(src.getOnkeydown());<NEW_LINE>dest.setOnkeypress(src.getOnkeypress());<NEW_LINE>dest.setOnkeyup(src.getOnkeyup());<NEW_LINE>dest.setOnmousedown(src.getOnmousedown());<NEW_LINE>dest.setOnmousemove(src.getOnmousemove());<NEW_LINE>dest.setOnmouseout(src.getOnmouseout());<NEW_LINE>dest.setOnmouseover(src.getOnmouseover());<NEW_LINE>dest.setOnmouseup(src.getOnmouseup());<NEW_LINE>dest.setOnselect(src.getOnselect());<NEW_LINE>dest.setReadonly(src.isReadonly());<NEW_LINE>dest.setRendered(src.isRendered());<NEW_LINE>dest.setRequired(src.isRequired());<NEW_LINE>dest.setSize(src.getSize());<NEW_LINE>dest.setStyle(src.getStyle());<NEW_LINE>dest.setStyleClass(src.getStyleClass());<NEW_LINE>dest.setTabindex(src.getTabindex());<NEW_LINE>dest.setTitle(src.getTitle());<NEW_LINE>dest.setValidator(src.getValidator());<NEW_LINE>} | setAccesskey(src.getAccesskey()); |
749,146 | public Function newInstance(int position, ObjList<Function> args, IntList argPositions, CairoConfiguration configuration, SqlExecutionContext sqlExecutionContext) throws SqlException {<NEW_LINE>final char c = args.getQuick(0).getChar(null);<NEW_LINE>switch(c) {<NEW_LINE>case 'd':<NEW_LINE>return new TimestampFloorDDFunction<MASK><NEW_LINE>case 'M':<NEW_LINE>return new TimestampFloorMMFunction(args.getQuick(1));<NEW_LINE>case 'y':<NEW_LINE>return new TimestampFloorYYYYFunction(args.getQuick(1));<NEW_LINE>case 'h':<NEW_LINE>return new TimestampFloorHHFunction(args.getQuick(1));<NEW_LINE>case 'm':<NEW_LINE>return new TimestampFloorMIFunction(args.getQuick(1));<NEW_LINE>case 's':<NEW_LINE>return new TimestampFloorSSFunction(args.getQuick(1));<NEW_LINE>case 'T':<NEW_LINE>return new TimestampFloorMSFunction(args.getQuick(1));<NEW_LINE>case 0:<NEW_LINE>throw SqlException.position(argPositions.getQuick(0)).put("invalid kind 'null'");<NEW_LINE>default:<NEW_LINE>throw SqlException.position(argPositions.getQuick(0)).put("invalid kind '").put(c).put('\'');<NEW_LINE>}<NEW_LINE>} | (args.getQuick(1)); |
765,987 | public DomainSettings unmarshall(JsonUnmarshallerContext context) throws Exception {<NEW_LINE>DomainSettings domainSettings = new DomainSettings();<NEW_LINE>int originalDepth = context.getCurrentDepth();<NEW_LINE>String currentParentElement = context.getCurrentParentElement();<NEW_LINE>int targetDepth = originalDepth + 1;<NEW_LINE>JsonToken token = context.getCurrentToken();<NEW_LINE>if (token == null)<NEW_LINE>token = context.nextToken();<NEW_LINE>if (token == VALUE_NULL) {<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>while (true) {<NEW_LINE>if (token == null)<NEW_LINE>break;<NEW_LINE>if (token == FIELD_NAME || token == START_OBJECT) {<NEW_LINE>if (context.testExpression("SecurityGroupIds", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>domainSettings.setSecurityGroupIds(new ListUnmarshaller<String>(context.getUnmarshaller(String.class)).unmarshall(context));<NEW_LINE>}<NEW_LINE>if (context.testExpression("RStudioServerProDomainSettings", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>domainSettings.setRStudioServerProDomainSettings(RStudioServerProDomainSettingsJsonUnmarshaller.getInstance<MASK><NEW_LINE>}<NEW_LINE>} else if (token == END_ARRAY || token == END_OBJECT) {<NEW_LINE>if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {<NEW_LINE>if (context.getCurrentDepth() <= originalDepth)<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>token = context.nextToken();<NEW_LINE>}<NEW_LINE>return domainSettings;<NEW_LINE>} | ().unmarshall(context)); |
529,101 | public void actionPerformedImpl(ActionEvent e, RTextArea textArea) {<NEW_LINE>try {<NEW_LINE>// find current color at caret<NEW_LINE>int caretPosition = textArea.getCaretPosition();<NEW_LINE>int start;<NEW_LINE>int len = 0;<NEW_LINE>String oldStr;<NEW_LINE>int[] result = findColorAt(textArea, caretPosition);<NEW_LINE>if (result != null) {<NEW_LINE>start = result[0];<NEW_LINE>len = result[1];<NEW_LINE>oldStr = textArea.getText(start, len);<NEW_LINE>} else {<NEW_LINE>start = caretPosition;<NEW_LINE>oldStr = "";<NEW_LINE>}<NEW_LINE>AtomicInteger length = new AtomicInteger(len);<NEW_LINE>AtomicBoolean changed = new AtomicBoolean();<NEW_LINE>// show pipette color picker<NEW_LINE>Window window = SwingUtilities.windowForComponent(textArea);<NEW_LINE>FlatColorPipette.pick(window, true, color -> {<NEW_LINE>// update editor immediately for live preview<NEW_LINE>String str = colorToString(color);<NEW_LINE>((FlatSyntaxTextArea) textArea).runWithoutUndo(() -> {<NEW_LINE>textArea.replaceRange(str, start, start + length.get());<NEW_LINE>});<NEW_LINE>length.set(str.length());<NEW_LINE>changed.set(true);<NEW_LINE>}, color -> {<NEW_LINE>// restore original string<NEW_LINE>((FlatSyntaxTextArea) textArea).runWithoutUndo(() -> {<NEW_LINE>textArea.replaceRange(oldStr, start, <MASK><NEW_LINE>});<NEW_LINE>length.set(oldStr.length());<NEW_LINE>// update editor<NEW_LINE>if (color != null) {<NEW_LINE>String newStr = colorToString(color);<NEW_LINE>try {<NEW_LINE>if (!newStr.equals(textArea.getText(start, length.get())))<NEW_LINE>textArea.replaceRange(newStr, start, start + length.get());<NEW_LINE>} catch (BadLocationException ex) {<NEW_LINE>ex.printStackTrace();<NEW_LINE>}<NEW_LINE>}<NEW_LINE>});<NEW_LINE>} catch (BadLocationException | IndexOutOfBoundsException | NumberFormatException | UnsupportedOperationException | AWTException ex) {<NEW_LINE>ex.printStackTrace();<NEW_LINE>}<NEW_LINE>} | start + length.get()); |
1,508,818 | public EnableVpcClassicLinkResult unmarshall(StaxUnmarshallerContext context) throws Exception {<NEW_LINE>EnableVpcClassicLinkResult enableVpcClassicLinkResult = new EnableVpcClassicLinkResult();<NEW_LINE><MASK><NEW_LINE>int targetDepth = originalDepth + 1;<NEW_LINE>if (context.isStartOfDocument())<NEW_LINE>targetDepth += 1;<NEW_LINE>while (true) {<NEW_LINE>int xmlEvent = context.nextEvent();<NEW_LINE>if (xmlEvent == XmlPullParser.END_DOCUMENT)<NEW_LINE>return enableVpcClassicLinkResult;<NEW_LINE>if (xmlEvent == XmlPullParser.START_TAG) {<NEW_LINE>if (context.testExpression("return", targetDepth)) {<NEW_LINE>enableVpcClassicLinkResult.setReturn(BooleanStaxUnmarshaller.getInstance().unmarshall(context));<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>} else if (xmlEvent == XmlPullParser.END_TAG) {<NEW_LINE>if (context.getCurrentDepth() < originalDepth) {<NEW_LINE>return enableVpcClassicLinkResult;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | int originalDepth = context.getCurrentDepth(); |
281,514 | protected void onSaveInstanceState(@NonNull Bundle outState) {<NEW_LINE>// responsibility of restore is preferred in onCreate() before than in<NEW_LINE>// onRestoreInstanceState when there are Fragments involved<NEW_LINE>Log_OC.v(TAG, "onSaveInstanceState() start");<NEW_LINE>super.onSaveInstanceState(outState);<NEW_LINE>outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_PREVIEW, mWaitingToPreview);<NEW_LINE>outState.<MASK><NEW_LINE>// outState.putBoolean(FileDisplayActivity.KEY_REFRESH_SHARES_IN_PROGRESS,<NEW_LINE>// mRefreshSharesInProgress);<NEW_LINE>outState.putParcelable(FileDisplayActivity.KEY_WAITING_TO_SEND, mWaitingToSend);<NEW_LINE>if (searchView != null) {<NEW_LINE>outState.putBoolean(KEY_IS_SEARCH_OPEN, !searchView.isIconified());<NEW_LINE>}<NEW_LINE>outState.putString(KEY_SEARCH_QUERY, searchQuery);<NEW_LINE>Log_OC.v(TAG, "onSaveInstanceState() end");<NEW_LINE>} | putBoolean(FileDisplayActivity.KEY_SYNC_IN_PROGRESS, mSyncInProgress); |
1,282,269 | private boolean matchArg(String arg, IKey key) {<NEW_LINE>String kn = options.caseSensitiveOptions ? key.getName() : key.getName().toLowerCase();<NEW_LINE>if (options.allowAbbreviatedOptions) {<NEW_LINE>if (kn.startsWith(arg))<NEW_LINE>return true;<NEW_LINE>} else {<NEW_LINE>ParameterDescription <MASK><NEW_LINE>if (pd != null) {<NEW_LINE>// It's an option. If the option has a separator (e.g. -author==foo) then<NEW_LINE>// we only do a beginsWith match<NEW_LINE>String separator = getSeparatorFor(arg);<NEW_LINE>if (!" ".equals(separator)) {<NEW_LINE>if (arg.startsWith(kn))<NEW_LINE>return true;<NEW_LINE>} else {<NEW_LINE>if (kn.equals(arg))<NEW_LINE>return true;<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>// It's a command do a strict equality check<NEW_LINE>if (kn.equals(arg))<NEW_LINE>return true;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return false;<NEW_LINE>} | pd = descriptions.get(key); |
532,444 | public boolean doMonitor(ServiceEmitter emitter) {<NEW_LINE>if (cache != null) {<NEW_LINE>final CacheStats currCacheStats = cache.getStats();<NEW_LINE>final CacheStats deltaCacheStats = currCacheStats.delta(prevCacheStats);<NEW_LINE>final CachePopulatorStats.Snapshot currCachePopulatorStats = cachePopulatorStats.snapshot();<NEW_LINE>final CachePopulatorStats.Snapshot <MASK><NEW_LINE>final ServiceMetricEvent.Builder builder = new ServiceMetricEvent.Builder();<NEW_LINE>emitStats(emitter, "query/cache/delta", deltaCachePopulatorStats, deltaCacheStats, builder);<NEW_LINE>emitStats(emitter, "query/cache/total", currCachePopulatorStats, currCacheStats, builder);<NEW_LINE>prevCachePopulatorStats = currCachePopulatorStats;<NEW_LINE>prevCacheStats = currCacheStats;<NEW_LINE>// Any custom cache statistics that need monitoring<NEW_LINE>cache.doMonitor(emitter);<NEW_LINE>}<NEW_LINE>return true;<NEW_LINE>} | deltaCachePopulatorStats = currCachePopulatorStats.delta(prevCachePopulatorStats); |
1,573,789 | public void init(boolean forEncryption, CipherParameters params) throws IllegalArgumentException {<NEW_LINE>if (params instanceof ParametersWithIV) {<NEW_LINE>ParametersWithIV ivParam = (ParametersWithIV) params;<NEW_LINE>byte[] iv = ivParam.getIV();<NEW_LINE>if (iv.length < blockSize) {<NEW_LINE>throw new IllegalArgumentException("Parameter m must blockSize <= m");<NEW_LINE>}<NEW_LINE>this.m = iv.length;<NEW_LINE>initArrays();<NEW_LINE>R_init = Arrays.clone(iv);<NEW_LINE>System.arraycopy(R_init, 0, R, 0, R_init.length);<NEW_LINE>// if null it's an IV changed only.<NEW_LINE>if (ivParam.getParameters() != null) {<NEW_LINE>cipher.init(<MASK><NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>setupDefaultParams();<NEW_LINE>initArrays();<NEW_LINE>System.arraycopy(R_init, 0, R, 0, R_init.length);<NEW_LINE>// if it's null, key is to be reused.<NEW_LINE>if (params != null) {<NEW_LINE>cipher.init(true, params);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>initialized = true;<NEW_LINE>} | true, ivParam.getParameters()); |
389,580 | public static byte[] calculateSSLMac(byte[] input, byte[] macWriteSecret, MacAlgorithm macAlgorithm) {<NEW_LINE>final byte[] pad1 = SSLUtils.getPad1(macAlgorithm);<NEW_LINE>final byte[] pad2 = SSLUtils.getPad2(macAlgorithm);<NEW_LINE>try {<NEW_LINE>final String hashName = getHashAlgorithm(macAlgorithm);<NEW_LINE>final MessageDigest <MASK><NEW_LINE>final byte[] innerInput = ArrayConverter.concatenate(macWriteSecret, pad1, input);<NEW_LINE>final byte[] innerHash = hashFunction.digest(innerInput);<NEW_LINE>final byte[] outerInput = ArrayConverter.concatenate(macWriteSecret, pad2, innerHash);<NEW_LINE>final byte[] outerHash = hashFunction.digest(outerInput);<NEW_LINE>return outerHash;<NEW_LINE>} catch (NoSuchAlgorithmException e) {<NEW_LINE>throw new IllegalArgumentException(ILLEGAL_MAC_ALGORITHM.format(macAlgorithm.getJavaName()));<NEW_LINE>}<NEW_LINE>} | hashFunction = MessageDigest.getInstance(hashName); |
820,449 | void move(FragmentDB destFrag, Address min, Address max) throws NotFoundException {<NEW_LINE>lock.acquire();<NEW_LINE>try {<NEW_LINE>if (!getProgram().getMemory().contains(min, max)) {<NEW_LINE>throw new NotFoundException("Address range for " + min + ", " + max + " is not contained in memory");<NEW_LINE>}<NEW_LINE>AddressSet set = new AddressSet();<NEW_LINE>AddressRangeIterator iter = fragMap.getAddressRanges(min, max);<NEW_LINE>AddressSet addrSet = new AddressSet(min, max);<NEW_LINE>while (iter.hasNext() && !addrSet.isEmpty()) {<NEW_LINE>AddressRange range = iter.next();<NEW_LINE>Field field = fragMap.getValue(range.getMinAddress());<NEW_LINE>try {<NEW_LINE>FragmentDB frag = getFragmentDB(field.getLongValue());<NEW_LINE>if (frag != destFrag) {<NEW_LINE>AddressSet intersection = addrSet.intersect(frag);<NEW_LINE>AddressRangeIterator fragRangeIter = intersection.getAddressRanges();<NEW_LINE>while (fragRangeIter.hasNext()) {<NEW_LINE>AddressRange fragRange = fragRangeIter.next();<NEW_LINE>set.add(fragRange);<NEW_LINE>frag.removeRange(fragRange);<NEW_LINE>}<NEW_LINE>addrSet = addrSet.subtract(intersection);<NEW_LINE>}<NEW_LINE>} catch (IOException e) {<NEW_LINE>errHandler.dbError(e);<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>Field field = new LongField(destFrag.getKey());<NEW_LINE>AddressRangeIterator rangeIter = set.getAddressRanges();<NEW_LINE>while (rangeIter.hasNext()) {<NEW_LINE>AddressRange range = rangeIter.next();<NEW_LINE>fragMap.paintRange(range.getMinAddress(), range.getMaxAddress(), field);<NEW_LINE>destFrag.addRange(range);<NEW_LINE>}<NEW_LINE>treeMgr.updateTreeRecord(record);<NEW_LINE>getProgram().programTreeChanged(treeID, ChangeManager.<MASK><NEW_LINE>} finally {<NEW_LINE>lock.release();<NEW_LINE>}<NEW_LINE>} | DOCR_CODE_MOVED, null, min, max); |
1,066,291 | public Map<String, INDArray> init(NeuralNetConfiguration conf, INDArray paramsView, boolean initializeParams) {<NEW_LINE>SeparableConvolution2D layer = (SeparableConvolution2D) conf.getLayer();<NEW_LINE>if (layer.getKernelSize().length != 2)<NEW_LINE>throw new IllegalArgumentException("Filter size must be == 2");<NEW_LINE>Map<String, INDArray> params = Collections.synchronizedMap(new LinkedHashMap<String, INDArray>());<NEW_LINE>SeparableConvolution2D layerConf = (SeparableConvolution2D) conf.getLayer();<NEW_LINE>val depthWiseParams = numDepthWiseParams(layerConf);<NEW_LINE>val biasParams = numBiasParams(layerConf);<NEW_LINE>INDArray depthWiseWeightView = paramsView.get(NDArrayIndex.interval(0, 0, true), NDArrayIndex.interval(biasParams, biasParams + depthWiseParams));<NEW_LINE>INDArray pointWiseWeightView = paramsView.get(NDArrayIndex.interval(0, 0, true), NDArrayIndex.interval(biasParams + depthWiseParams, numParams(conf)));<NEW_LINE>params.put(DEPTH_WISE_WEIGHT_KEY, createDepthWiseWeightMatrix<MASK><NEW_LINE>conf.addVariable(DEPTH_WISE_WEIGHT_KEY);<NEW_LINE>params.put(POINT_WISE_WEIGHT_KEY, createPointWiseWeightMatrix(conf, pointWiseWeightView, initializeParams));<NEW_LINE>conf.addVariable(POINT_WISE_WEIGHT_KEY);<NEW_LINE>if (layer.hasBias()) {<NEW_LINE>INDArray biasView = paramsView.get(NDArrayIndex.interval(0, 0, true), NDArrayIndex.interval(0, biasParams));<NEW_LINE>params.put(BIAS_KEY, createBias(conf, biasView, initializeParams));<NEW_LINE>conf.addVariable(BIAS_KEY);<NEW_LINE>}<NEW_LINE>return params;<NEW_LINE>} | (conf, depthWiseWeightView, initializeParams)); |
929,085 | private void processType(TypeElement autoBuilderType, TypeElement ofClass, String callMethod) {<NEW_LINE>ImmutableSet<ExecutableElement> methods = abstractMethodsIn(getLocalAndInheritedMethods(autoBuilderType, typeUtils(), elementUtils()));<NEW_LINE>Executable executable = findExecutable(ofClass, callMethod, autoBuilderType, methods);<NEW_LINE>BuilderSpec builderSpec = new BuilderSpec(ofClass, processingEnv, errorReporter());<NEW_LINE>BuilderSpec.Builder builder = builderSpec.new Builder(autoBuilderType);<NEW_LINE><MASK><NEW_LINE>ImmutableMap<String, String> propertyInitializers = propertyInitializers(autoBuilderType, executable);<NEW_LINE>Optional<BuilderMethodClassifier<VariableElement>> maybeClassifier = BuilderMethodClassifierForAutoBuilder.classify(methods, errorReporter(), processingEnv, executable, builtType, autoBuilderType, propertyInitializers.keySet());<NEW_LINE>if (!maybeClassifier.isPresent() || errorReporter().errorCount() > 0) {<NEW_LINE>// We've already output one or more error messages.<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>BuilderMethodClassifier<VariableElement> classifier = maybeClassifier.get();<NEW_LINE>Map<String, String> propertyToGetterName = Maps.transformValues(classifier.builderGetters(), PropertyGetter::getName);<NEW_LINE>AutoBuilderTemplateVars vars = new AutoBuilderTemplateVars();<NEW_LINE>vars.props = propertySet(executable, propertyToGetterName, propertyInitializers);<NEW_LINE>builder.defineVars(vars, classifier);<NEW_LINE>vars.identifiers = !processingEnv.getOptions().containsKey(OMIT_IDENTIFIERS_OPTION);<NEW_LINE>String generatedClassName = generatedClassName(autoBuilderType, "AutoBuilder_");<NEW_LINE>vars.builderName = TypeSimplifier.simpleNameOf(generatedClassName);<NEW_LINE>vars.builtType = TypeEncoder.encode(builtType);<NEW_LINE>Optional<String> forwardingClassName = maybeForwardingClass(autoBuilderType, executable);<NEW_LINE>vars.build = forwardingClassName.map(n -> TypeSimplifier.simpleNameOf(n) + ".of").orElseGet(executable::invoke);<NEW_LINE>vars.toBuilderConstructor = false;<NEW_LINE>vars.toBuilderMethods = ImmutableList.of();<NEW_LINE>defineSharedVarsForType(autoBuilderType, ImmutableSet.of(), vars);<NEW_LINE>String text = vars.toText();<NEW_LINE>text = TypeEncoder.decode(text, processingEnv, vars.pkg, autoBuilderType.asType());<NEW_LINE>text = Reformatter.fixup(text);<NEW_LINE>writeSourceFile(generatedClassName, text, autoBuilderType);<NEW_LINE>forwardingClassName.ifPresent(n -> generateForwardingClass(n, executable, builtType, autoBuilderType));<NEW_LINE>} | TypeMirror builtType = executable.builtType(); |
201,206 | private void calculateDampingMoments(FlightConfiguration configuration, FlightConditions conditions, AerodynamicForces total) {<NEW_LINE>// Calculate pitch and yaw damping moments<NEW_LINE>double mul = getDampingMultiplier(configuration, conditions, conditions.getPitchCenter().x);<NEW_LINE>double pitchRate = conditions.getPitchRate();<NEW_LINE>double yawRate = conditions.getYawRate();<NEW_LINE>double velocity = conditions.getVelocity();<NEW_LINE>// TODO: Higher damping yields much more realistic apogee turn<NEW_LINE>mul *= 3;<NEW_LINE>// find magnitude of damping moments, and clamp so they can't<NEW_LINE>// exceed magnitude of pitch and yaw moments<NEW_LINE>double pitchDampingMomentMagnitude = MathUtil.min(mul * pow2(pitchRate / velocity), total.getCm());<NEW_LINE>double yawDampingMomentMagnitude = MathUtil.min(mul * pow2(yawRate / velocity<MASK><NEW_LINE>// multiply by sign of pitch and yaw rates<NEW_LINE>total.setPitchDampingMoment(MathUtil.sign(pitchRate) * pitchDampingMomentMagnitude);<NEW_LINE>total.setYawDampingMoment(MathUtil.sign(yawRate) * yawDampingMomentMagnitude);<NEW_LINE>} | ), total.getCyaw()); |
79,661 | private boolean validateReplicationTrx(final Mutable<Integer> candidatesUpdated) {<NEW_LINE>final IQueryBuilder<I_C_OLCand> queryBuilder = createOLCandQueryBuilder();<NEW_LINE>final Iterator<I_C_OLCand> selectedCands = queryBuilder.create().iterate(I_C_OLCand.class);<NEW_LINE>int candidatesWithErorr = 0;<NEW_LINE>// avoid the InterfaceWrapperHelper.save to trigger another validation from a MV.<NEW_LINE>olCandValidatorService.setValidationProcessInProgress(true);<NEW_LINE>try {<NEW_LINE>for (final I_C_OLCand cand : IteratorUtils.asIterable(selectedCands)) {<NEW_LINE>olCandValidatorService.validate(cand);<NEW_LINE>if (InterfaceWrapperHelper.hasChanges(cand)) {<NEW_LINE>candidatesUpdated.setValue(<MASK><NEW_LINE>InterfaceWrapperHelper.save(cand);<NEW_LINE>}<NEW_LINE>if (cand.isError()) {<NEW_LINE>candidatesWithErorr++;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (candidatesWithErorr != 0) {<NEW_LINE>addLog(msgBL.getMsg(getCtx(), OLCandValidatorService.MSG_ERRORS_FOUND, new Object[] { candidatesWithErorr }));<NEW_LINE>}<NEW_LINE>// return true if there were no errors<NEW_LINE>return (candidatesWithErorr == 0);<NEW_LINE>} finally {<NEW_LINE>olCandValidatorService.setValidationProcessInProgress(false);<NEW_LINE>}<NEW_LINE>} | candidatesUpdated.getValue() + 1); |
1,652,682 | public void doSetup() {<NEW_LINE>delT = 0.005f;<NEW_LINE>espSqr = 500.0f;<NEW_LINE>float[] auxPositionRandom = new float[numBodies * 4];<NEW_LINE>float[] auxVelocityZero = new float[numBodies * 3];<NEW_LINE>for (int i = 0; i < auxPositionRandom.length; i++) {<NEW_LINE>auxPositionRandom[i] = (float) Math.random();<NEW_LINE>}<NEW_LINE>Arrays.fill(auxVelocityZero, 0.0f);<NEW_LINE>posSeq = new float[numBodies * 4];<NEW_LINE>velSeq = new float[numBodies * 4];<NEW_LINE>if (auxPositionRandom.length >= 0) {<NEW_LINE>System.arraycopy(auxPositionRandom, 0, <MASK><NEW_LINE>}<NEW_LINE>if (auxVelocityZero.length >= 0) {<NEW_LINE>System.arraycopy(auxVelocityZero, 0, velSeq, 0, auxVelocityZero.length);<NEW_LINE>}<NEW_LINE>//<NEW_LINE>ts = //<NEW_LINE>new TaskSchedule("benchmark").//<NEW_LINE>streamIn(//<NEW_LINE>velSeq, posSeq).task("t0", ComputeKernels::nBody, numBodies, posSeq, velSeq, delT, espSqr);<NEW_LINE>ts.warmup();<NEW_LINE>} | posSeq, 0, auxPositionRandom.length); |
969,314 | public int numberOfArithmeticSlices(int[] A) {<NEW_LINE>int res = 0;<NEW_LINE>Map<Integer, Integer>[] map = new Map[A.length];<NEW_LINE>for (int i = 0; i < A.length; i++) {<NEW_LINE>map[i] = new HashMap<>(i);<NEW_LINE>for (int j = 0; j < i; j++) {<NEW_LINE>long diff = (long) A<MASK><NEW_LINE>if (diff <= Integer.MIN_VALUE || diff > Integer.MAX_VALUE) {<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>int d = (int) diff;<NEW_LINE>int c1 = map[i].getOrDefault(d, 0);<NEW_LINE>int c2 = map[j].getOrDefault(d, 0);<NEW_LINE>res += c2;<NEW_LINE>map[i].put(d, c1 + c2 + 1);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return res;<NEW_LINE>} | [i] - A[j]; |
1,089,616 | private Icon runInGraphicsContext(TripleFunction<BufferedImage, Graphics2D, FontRenderContext, Icon> callback) {<NEW_LINE>Icon result = null;<NEW_LINE>Graphics2D graphics = null;<NEW_LINE>// noinspection UndesirableClassUsage<NEW_LINE>BufferedImage image = new BufferedImage(iconSize, iconSize, BufferedImage.TYPE_4BYTE_ABGR);<NEW_LINE>try (InputStream inputStream = new FileInputStream(fontFilePath)) {<NEW_LINE>Font font = Font.createFont(Font.TRUETYPE_FONT, inputStream).<MASK><NEW_LINE>graphics = image.createGraphics();<NEW_LINE>graphics.setFont(font);<NEW_LINE>graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);<NEW_LINE>FontRenderContext frc = new FontRenderContext(new AffineTransform(), true, true);<NEW_LINE>result = callback.fun(image, graphics, frc);<NEW_LINE>} catch (IOException | FontFormatException ex) {<NEW_LINE>FlutterUtils.warn(LOG, ex);<NEW_LINE>} finally {<NEW_LINE>if (graphics != null)<NEW_LINE>graphics.dispose();<NEW_LINE>}<NEW_LINE>return result;<NEW_LINE>} | deriveFont(Font.PLAIN, fontSize); |
1,587,077 | private void saveAllEntities() {<NEW_LINE>// use ImmutableObject instead of Registry so that the Key generation doesn't break<NEW_LINE>ImmutableList<Registry> registries = ImmutableList.of(sunriseTld, gaTld, eapTld);<NEW_LINE>ImmutableList<RegistrarContact> contacts = contactsBuilder.build();<NEW_LINE>tm().transact(() -> {<NEW_LINE>if (!replaceExisting) {<NEW_LINE>ImmutableList<VKey<? extends ImmutableObject>> keys = Streams.concat(registries.stream().map(registry -> Registry.createVKey(registry.getTldStr())), registrars.stream().map(Registrar::createVKey), contacts.stream().map(RegistrarContact::createVKey)).collect(toImmutableList());<NEW_LINE>ImmutableMap<VKey<? extends ImmutableObject>, ImmutableObject> existingObjects = tm().loadByKeysIfPresent(keys);<NEW_LINE>checkState(existingObjects.isEmpty(), "Found existing object(s) conflicting with OT&E objects: %s", existingObjects.keySet());<NEW_LINE>}<NEW_LINE>// Save the Registries (TLDs) first<NEW_LINE>tm().putAll(registries);<NEW_LINE>});<NEW_LINE>// Now we can set the allowedTlds for the registrars in a new transaction<NEW_LINE>tm().transact(() -> {<NEW_LINE>registrars = registrars.stream().map(this::addAllowedTld).collect(toImmutableList());<NEW_LINE>// and we can save the registrars and contacts!<NEW_LINE><MASK><NEW_LINE>tm().putAll(contacts);<NEW_LINE>});<NEW_LINE>} | tm().putAll(registrars); |
433,519 | private // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents<NEW_LINE>void initComponents() {<NEW_LINE>java.awt.GridBagConstraints gridBagConstraints;<NEW_LINE>jLabel1 = new javax.swing.JLabel();<NEW_LINE>changeNameTextField = new javax.swing.JTextField();<NEW_LINE>renameCommentsCheckBox = new javax.swing.JCheckBox();<NEW_LINE>spacerLabel = new javax.swing.JLabel();<NEW_LINE>setLayout(new java.awt.GridBagLayout());<NEW_LINE>jLabel1.setLabelFor(changeNameTextField);<NEW_LINE>// NOI18N<NEW_LINE>jLabel1.setText(org.openide.util.NbBundle.getMessage(RenameClassForm.class, "LBL_NewName"));<NEW_LINE>gridBagConstraints = new java.awt.GridBagConstraints();<NEW_LINE>gridBagConstraints.gridx = 0;<NEW_LINE>gridBagConstraints.gridy = 0;<NEW_LINE>gridBagConstraints.fill <MASK><NEW_LINE>gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);<NEW_LINE>add(jLabel1, gridBagConstraints);<NEW_LINE>gridBagConstraints = new java.awt.GridBagConstraints();<NEW_LINE>gridBagConstraints.gridx = 1;<NEW_LINE>gridBagConstraints.gridy = 0;<NEW_LINE>gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;<NEW_LINE>gridBagConstraints.weightx = 1.0;<NEW_LINE>gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);<NEW_LINE>add(changeNameTextField, gridBagConstraints);<NEW_LINE>// NOI18N<NEW_LINE>changeNameTextField.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(RenameClassForm.class, "ACSD_New_Name"));<NEW_LINE>// NOI18N<NEW_LINE>renameCommentsCheckBox.setText(org.openide.util.NbBundle.getMessage(RenameClassForm.class, "LBL_RenameComments"));<NEW_LINE>gridBagConstraints = new java.awt.GridBagConstraints();<NEW_LINE>gridBagConstraints.gridx = 0;<NEW_LINE>gridBagConstraints.gridy = 1;<NEW_LINE>gridBagConstraints.gridwidth = 2;<NEW_LINE>gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;<NEW_LINE>gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 5);<NEW_LINE>add(renameCommentsCheckBox, gridBagConstraints);<NEW_LINE>// NOI18N<NEW_LINE>renameCommentsCheckBox.getAccessibleContext().setAccessibleDescription(org.openide.util.NbBundle.getMessage(RenameClassForm.class, "ACSD_Ren_In_Commts"));<NEW_LINE>gridBagConstraints = new java.awt.GridBagConstraints();<NEW_LINE>gridBagConstraints.gridx = 0;<NEW_LINE>gridBagConstraints.gridy = 2;<NEW_LINE>gridBagConstraints.weighty = 1.0;<NEW_LINE>add(spacerLabel, gridBagConstraints);<NEW_LINE>} | = java.awt.GridBagConstraints.HORIZONTAL; |
840,518 | public static DescribeNetworkAnalyticsPacketLossResponse unmarshall(DescribeNetworkAnalyticsPacketLossResponse describeNetworkAnalyticsPacketLossResponse, UnmarshallerContext context) {<NEW_LINE>describeNetworkAnalyticsPacketLossResponse.setRequestId(context.stringValue("DescribeNetworkAnalyticsPacketLossResponse.RequestId"));<NEW_LINE>describeNetworkAnalyticsPacketLossResponse.setTotalCount(context.integerValue("DescribeNetworkAnalyticsPacketLossResponse.TotalCount"));<NEW_LINE>describeNetworkAnalyticsPacketLossResponse.setPageNumber(context.integerValue("DescribeNetworkAnalyticsPacketLossResponse.PageNumber"));<NEW_LINE>describeNetworkAnalyticsPacketLossResponse.setPageSize(context.integerValue("DescribeNetworkAnalyticsPacketLossResponse.PageSize"));<NEW_LINE>List<PacketLossInfo> packetLossInfos = new ArrayList<PacketLossInfo>();<NEW_LINE>for (int i = 0; i < context.lengthValue("DescribeNetworkAnalyticsPacketLossResponse.PacketLossInfos.Length"); i++) {<NEW_LINE>PacketLossInfo packetLossInfo = new PacketLossInfo();<NEW_LINE>packetLossInfo.setInBoundTotalPacket(context.stringValue("DescribeNetworkAnalyticsPacketLossResponse.PacketLossInfos[" + i + "].InBoundTotalPacket"));<NEW_LINE>packetLossInfo.setOutBoundTotalPacket(context.stringValue("DescribeNetworkAnalyticsPacketLossResponse.PacketLossInfos[" + i + "].OutBoundTotalPacket"));<NEW_LINE>packetLossInfo.setDataType(context.stringValue("DescribeNetworkAnalyticsPacketLossResponse.PacketLossInfos[" + i + "].DataType"));<NEW_LINE>packetLossInfo.setDateTime(context.stringValue("DescribeNetworkAnalyticsPacketLossResponse.PacketLossInfos[" + i + "].DateTime"));<NEW_LINE>packetLossInfo.setIp(context.stringValue("DescribeNetworkAnalyticsPacketLossResponse.PacketLossInfos[" + i + "].Ip"));<NEW_LINE>Country country = new Country();<NEW_LINE>country.setCountryCode(context.stringValue("DescribeNetworkAnalyticsPacketLossResponse.PacketLossInfos[" + i + "].Country.CountryCode"));<NEW_LINE>country.setCountryCn(context.booleanValue("DescribeNetworkAnalyticsPacketLossResponse.PacketLossInfos[" + i + "].Country.CountryCn"));<NEW_LINE>country.setCountryEn(context.stringValue<MASK><NEW_LINE>packetLossInfo.setCountry(country);<NEW_LINE>Province province = new Province();<NEW_LINE>province.setProvinceCode(context.stringValue("DescribeNetworkAnalyticsPacketLossResponse.PacketLossInfos[" + i + "].Province.ProvinceCode"));<NEW_LINE>province.setProvinceCn(context.booleanValue("DescribeNetworkAnalyticsPacketLossResponse.PacketLossInfos[" + i + "].Province.ProvinceCn"));<NEW_LINE>province.setProvinceEn(context.stringValue("DescribeNetworkAnalyticsPacketLossResponse.PacketLossInfos[" + i + "].Province.ProvinceEn"));<NEW_LINE>packetLossInfo.setProvince(province);<NEW_LINE>Carrier carrier = new Carrier();<NEW_LINE>carrier.setCarrierCode(context.stringValue("DescribeNetworkAnalyticsPacketLossResponse.PacketLossInfos[" + i + "].Carrier.CarrierCode"));<NEW_LINE>carrier.setCarrierCn(context.booleanValue("DescribeNetworkAnalyticsPacketLossResponse.PacketLossInfos[" + i + "].Carrier.CarrierCn"));<NEW_LINE>carrier.setCarrierEn(context.stringValue("DescribeNetworkAnalyticsPacketLossResponse.PacketLossInfos[" + i + "].Carrier.CarrierEn"));<NEW_LINE>packetLossInfo.setCarrier(carrier);<NEW_LINE>packetLossInfos.add(packetLossInfo);<NEW_LINE>}<NEW_LINE>describeNetworkAnalyticsPacketLossResponse.setPacketLossInfos(packetLossInfos);<NEW_LINE>return describeNetworkAnalyticsPacketLossResponse;<NEW_LINE>} | ("DescribeNetworkAnalyticsPacketLossResponse.PacketLossInfos[" + i + "].Country.CountryEn")); |
1,227,854 | public static void main(String[] args) throws ConnectorException, IOException {<NEW_LINE>Config clientConfig = new Config();<NEW_LINE>clientConfig.configurationHeader = CONFIG_HEADER;<NEW_LINE>clientConfig.customConfigurationDefaultsProvider = DEFAULTS;<NEW_LINE>clientConfig.configurationFile = CONFIG_FILE;<NEW_LINE>ClientInitializer.init(args, clientConfig, false);<NEW_LINE>if (clientConfig.helpRequested) {<NEW_LINE>System.exit(0);<NEW_LINE>}<NEW_LINE>if (clientConfig.oscore) {<NEW_LINE>HashMapCtxDB db = new HashMapCtxDB();<NEW_LINE>initOscore(clientConfig, db);<NEW_LINE>OSCoreCoapStackFactory.useAsDefault(db);<NEW_LINE>}<NEW_LINE>ClientInitializer.registerEndpoint(clientConfig, null);<NEW_LINE>if (clientConfig.tcp) {<NEW_LINE>clientConfig.ping = false;<NEW_LINE>} else if (clientConfig.secure && clientConfig.configuration.get(CoapConfig.RESPONSE_MATCHING) == MatcherMode.PRINCIPAL_IDENTITY) {<NEW_LINE>clientConfig.ping = true;<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>EndpointContext context = null;<NEW_LINE>if (clientConfig.ping) {<NEW_LINE>CoapClient clientPing = new CoapClient(clientConfig.uri);<NEW_LINE>System.out.println("===============\nCC31\n---------------");<NEW_LINE>if (!clientPing.ping(2000)) {<NEW_LINE>System.out.println(clientConfig.uri + " does not respond to ping, exiting...");<NEW_LINE>System.exit(-1);<NEW_LINE>} else {<NEW_LINE>System.out.println(clientConfig.uri + " reponds to ping");<NEW_LINE>}<NEW_LINE>context = clientPing.getDestinationContext();<NEW_LINE>if (context != null) {<NEW_LINE>System.out.println(Utils.prettyPrint(context));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>testCC(clientConfig.uri, context);<NEW_LINE>testCB(clientConfig.uri, context);<NEW_LINE>testCO(clientConfig.uri, context);<NEW_LINE><MASK><NEW_LINE>if (clientConfig.oscore) {<NEW_LINE>testOscore(clientConfig.uri, context);<NEW_LINE>}<NEW_LINE>} catch (IOException ex) {<NEW_LINE>System.err.println("IO-Error: " + ex.getMessage());<NEW_LINE>} catch (ConnectorException ex) {<NEW_LINE>System.err.println("Error: " + ex.getMessage());<NEW_LINE>}<NEW_LINE>System.exit(0);<NEW_LINE>} | testCL(clientConfig.uri, context); |
620,376 | public void startUp(FloodlightModuleContext context) {<NEW_LINE>// paag: register the IControllerCompletionListener<NEW_LINE>floodlightProviderService.addCompletionListener(this);<NEW_LINE>floodlightProviderService.addOFMessageListener(OFType.PACKET_IN, this);<NEW_LINE>floodlightProviderService.<MASK><NEW_LINE>floodlightProviderService.addOFMessageListener(OFType.ERROR, this);<NEW_LINE>restApiService.addRestletRoutable(new LearningSwitchWebRoutable());<NEW_LINE>// read our config options<NEW_LINE>Map<String, String> configOptions = context.getConfigParams(this);<NEW_LINE>try {<NEW_LINE>String idleTimeout = configOptions.get("idletimeout");<NEW_LINE>if (idleTimeout != null) {<NEW_LINE>FLOWMOD_DEFAULT_IDLE_TIMEOUT = Short.parseShort(idleTimeout);<NEW_LINE>}<NEW_LINE>} catch (NumberFormatException e) {<NEW_LINE>log.warn("Error parsing flow idle timeout, " + "using default of {} seconds", FLOWMOD_DEFAULT_IDLE_TIMEOUT);<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>String hardTimeout = configOptions.get("hardtimeout");<NEW_LINE>if (hardTimeout != null) {<NEW_LINE>FLOWMOD_DEFAULT_HARD_TIMEOUT = Short.parseShort(hardTimeout);<NEW_LINE>}<NEW_LINE>} catch (NumberFormatException e) {<NEW_LINE>log.warn("Error parsing flow hard timeout, " + "using default of {} seconds", FLOWMOD_DEFAULT_HARD_TIMEOUT);<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>String priority = configOptions.get("priority");<NEW_LINE>if (priority != null) {<NEW_LINE>FLOWMOD_PRIORITY = Short.parseShort(priority);<NEW_LINE>}<NEW_LINE>} catch (NumberFormatException e) {<NEW_LINE>log.warn("Error parsing flow priority, " + "using default of {}", FLOWMOD_PRIORITY);<NEW_LINE>}<NEW_LINE>log.debug("FlowMod idle timeout set to {} seconds", FLOWMOD_DEFAULT_IDLE_TIMEOUT);<NEW_LINE>log.debug("FlowMod hard timeout set to {} seconds", FLOWMOD_DEFAULT_HARD_TIMEOUT);<NEW_LINE>log.debug("FlowMod priority set to {}", FLOWMOD_PRIORITY);<NEW_LINE>debugCounterService.registerModule(this.getName());<NEW_LINE>counterFlowMod = debugCounterService.registerCounter(this.getName(), "flow-mods-written", "Flow mods written to switches by LearningSwitch", MetaData.WARN);<NEW_LINE>counterPacketOut = debugCounterService.registerCounter(this.getName(), "packet-outs-written", "Packet outs written to switches by LearningSwitch", MetaData.WARN);<NEW_LINE>} | addOFMessageListener(OFType.FLOW_REMOVED, this); |
1,792,246 | public static void main(String[] args) {<NEW_LINE>AmazonGuardDuty guardduty = AmazonGuardDutyClientBuilder.defaultClient();<NEW_LINE>// Set detectorId to the detectorId returned by GuardDuty's<NEW_LINE>// ListDetectors() for your current AWS Account/Region<NEW_LINE>final String detectorId = "ceb03b04f96520a8884c959f3e95c25a";<NEW_LINE>FindingCriteria criteria = new FindingCriteria();<NEW_LINE>Condition condition = new Condition();<NEW_LINE>List<String> condValues = new ArrayList<String>();<NEW_LINE>condValues.add("Recon:EC2/PortProbeUnprotectedPort");<NEW_LINE>condValues.add("Recon:EC2/PortScan");<NEW_LINE>condition.withEq(condValues);<NEW_LINE>criteria.addCriterionEntry("type", condition);<NEW_LINE>try {<NEW_LINE>ListFindingsRequest request = new ListFindingsRequest().withDetectorId(detectorId).withFindingCriteria(criteria);<NEW_LINE>ListFindingsResult response = guardduty.listFindings(request);<NEW_LINE>for (String finding : response.getFindingIds()) {<NEW_LINE>System.<MASK><NEW_LINE>}<NEW_LINE>} catch (AmazonServiceException ase) {<NEW_LINE>System.out.println("Caught Exception: " + ase.getMessage());<NEW_LINE>System.out.println("Response Status Code: " + ase.getStatusCode());<NEW_LINE>System.out.println("Error Code: " + ase.getErrorCode());<NEW_LINE>System.out.println("Request ID: " + ase.getRequestId());<NEW_LINE>}<NEW_LINE>} | out.println("FindingId: " + finding); |
338,187 | public static Validated build(String pattern, @Nullable String metadataPattern) {<NEW_LINE>Matcher matcher = TILDE_RANGE_PATTERN.matcher(pattern);<NEW_LINE>if (!matcher.matches()) {<NEW_LINE>return Validated.invalid("tildeRange", pattern, "not a tilde range");<NEW_LINE>}<NEW_LINE>String major = matcher.group(1);<NEW_LINE>String minor = matcher.group(2);<NEW_LINE>String patch = matcher.group(3);<NEW_LINE>String micro = matcher.group(4);<NEW_LINE>String lower;<NEW_LINE>String upper;<NEW_LINE>if (minor == null) {<NEW_LINE>lower = major;<NEW_LINE>upper = Integer.toString(parseInt(major) + 1);<NEW_LINE>} else if (patch == null) {<NEW_LINE>lower = major + "." + minor;<NEW_LINE>upper = major + "." + (parseInt(minor) + 1);<NEW_LINE>} else if (micro == null) {<NEW_LINE>lower = major <MASK><NEW_LINE>upper = major + "." + (parseInt(minor) + 1);<NEW_LINE>} else {<NEW_LINE>lower = major + "." + minor + "." + patch + "." + micro;<NEW_LINE>upper = major + "." + minor + "." + (parseInt(patch) + 1);<NEW_LINE>}<NEW_LINE>return Validated.valid("tildeRange", new TildeRange(lower, upper, metadataPattern));<NEW_LINE>} | + "." + minor + "." + patch; |
700,775 | public AwsElbLoadBalancerConnectionDraining unmarshall(JsonUnmarshallerContext context) throws Exception {<NEW_LINE>AwsElbLoadBalancerConnectionDraining awsElbLoadBalancerConnectionDraining = new AwsElbLoadBalancerConnectionDraining();<NEW_LINE>int originalDepth = context.getCurrentDepth();<NEW_LINE>String currentParentElement = context.getCurrentParentElement();<NEW_LINE>int targetDepth = originalDepth + 1;<NEW_LINE>JsonToken token = context.getCurrentToken();<NEW_LINE>if (token == null)<NEW_LINE>token = context.nextToken();<NEW_LINE>if (token == VALUE_NULL) {<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>while (true) {<NEW_LINE>if (token == null)<NEW_LINE>break;<NEW_LINE>if (token == FIELD_NAME || token == START_OBJECT) {<NEW_LINE>if (context.testExpression("Enabled", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>awsElbLoadBalancerConnectionDraining.setEnabled(context.getUnmarshaller(Boolean.<MASK><NEW_LINE>}<NEW_LINE>if (context.testExpression("Timeout", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>awsElbLoadBalancerConnectionDraining.setTimeout(context.getUnmarshaller(Integer.class).unmarshall(context));<NEW_LINE>}<NEW_LINE>} else if (token == END_ARRAY || token == END_OBJECT) {<NEW_LINE>if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {<NEW_LINE>if (context.getCurrentDepth() <= originalDepth)<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>token = context.nextToken();<NEW_LINE>}<NEW_LINE>return awsElbLoadBalancerConnectionDraining;<NEW_LINE>} | class).unmarshall(context)); |
207,226 | public JSONObject decode42(ByteBuffer buf) {<NEW_LINE>JSONObject m = new JSONObject();<NEW_LINE>while (buf.position() < buf.array().length) {<NEW_LINE>long tl = uint32(buf);<NEW_LINE>int t = (int) (tl >>> 3);<NEW_LINE>switch(t) {<NEW_LINE>case 1:<NEW_LINE>m.put("AAA311", uint32(buf));<NEW_LINE>break;<NEW_LINE>case 2:<NEW_LINE>m.put("AAA303", uint64(buf));<NEW_LINE>break;<NEW_LINE>case 3:<NEW_LINE>m.put("AAA312", uint32(buf));<NEW_LINE>break;<NEW_LINE>case 4:<NEW_LINE>m.put("AAA196", uint32(buf));<NEW_LINE>break;<NEW_LINE>case 5:<NEW_LINE>m.put("AAA197", uint32(buf));<NEW_LINE>break;<NEW_LINE>case 6:<NEW_LINE>m.put<MASK><NEW_LINE>break;<NEW_LINE>default:<NEW_LINE>// r.skipType(t&7)<NEW_LINE>// break;<NEW_LINE>return m;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return m;<NEW_LINE>} | ("AAA198", uint32(buf)); |
1,200,051 | public // wrapper. -- L.A. 4.5<NEW_LINE>DatasetDTO processOAIDCxml(String DcXmlToParse) throws XMLStreamException {<NEW_LINE>// look up DC metadata mapping:<NEW_LINE>ForeignMetadataFormatMapping dublinCoreMapping = findFormatMappingByName(DCTERMS);<NEW_LINE>if (dublinCoreMapping == null) {<NEW_LINE>throw new EJBException("Failed to find metadata mapping for " + DCTERMS);<NEW_LINE>}<NEW_LINE>DatasetDTO datasetDTO = this.initializeDataset();<NEW_LINE>StringReader reader = null;<NEW_LINE>XMLStreamReader xmlr = null;<NEW_LINE>try {<NEW_LINE>reader = new StringReader(DcXmlToParse);<NEW_LINE>XMLInputFactory xmlFactory = javax.xml.stream.XMLInputFactory.newInstance();<NEW_LINE>xmlr = xmlFactory.createXMLStreamReader(reader);<NEW_LINE>// while (xmlr.next() == XMLStreamConstants.COMMENT); // skip pre root comments<NEW_LINE>xmlr.nextTag();<NEW_LINE>xmlr.require(XMLStreamConstants.START_ELEMENT, null, OAI_DC_OPENING_TAG);<NEW_LINE>processXMLElement(xmlr, ":", OAI_DC_OPENING_TAG, dublinCoreMapping, datasetDTO);<NEW_LINE>} catch (XMLStreamException ex) {<NEW_LINE>throw new EJBException("ERROR occurred while parsing XML fragment (" + DcXmlToParse.substring(0, 64) + "...); ", ex);<NEW_LINE>}<NEW_LINE>datasetDTO.getDatasetVersion().<MASK><NEW_LINE>// Our DC import handles the contents of the dc:identifier field<NEW_LINE>// as an "other id". In the context of OAI harvesting, we expect<NEW_LINE>// the identifier to be a global id, so we need to rearrange that:<NEW_LINE>String identifier = getOtherIdFromDTO(datasetDTO.getDatasetVersion());<NEW_LINE>logger.fine("Imported identifier: " + identifier);<NEW_LINE>String globalIdentifier = reassignIdentifierAsGlobalId(identifier, datasetDTO);<NEW_LINE>logger.fine("Detected global identifier: " + globalIdentifier);<NEW_LINE>if (globalIdentifier == null) {<NEW_LINE>throw new EJBException("Failed to find a global identifier in the OAI_DC XML record.");<NEW_LINE>}<NEW_LINE>return datasetDTO;<NEW_LINE>} | setVersionState(DatasetVersion.VersionState.RELEASED); |
1,653,971 | private void createLUsForTUs(final I_M_ShipmentSchedule schedule, final List<I_M_ShipmentSchedule_QtyPicked> qtyPickedRecords) {<NEW_LINE>//<NEW_LINE>// Create HUContext from "schedule" because we want to get the Ctx and TrxName from there<NEW_LINE>final IContextAware contextProvider = InterfaceWrapperHelper.getContextAware(schedule);<NEW_LINE>final IHUContext huContext = handlingUnitsBL.createMutableHUContext(contextProvider);<NEW_LINE>//<NEW_LINE>// Create our LU Loader. This will help us to aggregate TUs on corresponding LUs<NEW_LINE>final <MASK><NEW_LINE>//<NEW_LINE>// Iterate QtyPicked records<NEW_LINE>for (final I_M_ShipmentSchedule_QtyPicked qtyPickedRecord : qtyPickedRecords) {<NEW_LINE>// refresh because it might be that a previous LU creation to update this record too<NEW_LINE>InterfaceWrapperHelper.refresh(qtyPickedRecord);<NEW_LINE>// Skip inactive lines<NEW_LINE>if (!qtyPickedRecord.isActive()) {<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>// Skip lines without TUs<NEW_LINE>if (qtyPickedRecord.getM_TU_HU_ID() <= 0) {<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>// Skip lines with ZERO Qty<NEW_LINE>if (qtyPickedRecord.getQtyPicked().signum() == 0) {<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>// Skip lines which already have LUs created<NEW_LINE>if (qtyPickedRecord.getM_LU_HU_ID() > 0) {<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>final I_M_HU tuHU = qtyPickedRecord.getM_TU_HU();<NEW_LINE>// 4507<NEW_LINE>// make sure the TU from qtyPicked is a real TU<NEW_LINE>if (!handlingUnitsBL.isTransportUnit(tuHU)) {<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>// skip LU creation when there is no LU Packing Instruction Version for this TU, eg.<NEW_LINE>// - Paloxe, as it can be placed directly in a truck, without a Pallet<NEW_LINE>// - any other TUs/LUs which are misconfigured (side effect)<NEW_LINE>{<NEW_LINE>final I_M_HU_PI_Version tuPIVersion = handlingUnitsBL.getEffectivePIVersion(tuHU);<NEW_LINE>final I_M_HU_PI tuPI = handlingUnitsDAO.getPackingInstructionById(HuPackingInstructionsId.ofRepoId(tuPIVersion.getM_HU_PI_ID()));<NEW_LINE>final I_M_HU_PI_Item luPIItem = handlingUnitsDAO.retrieveDefaultParentPIItem(tuPI, X_M_HU_PI_Version.HU_UNITTYPE_LoadLogistiqueUnit, null);<NEW_LINE>if (luPIItem == null) {<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>luLoader.addTU(tuHU);<NEW_LINE>// NOTE: after TU was added to an LU we expect this qtyPickedRecord to be updated and M_LU_HU_ID to be set<NEW_LINE>// Also, if there more then one QtyPickedRecords for tuHU, all those shall be updated<NEW_LINE>// see de.metas.handlingunits.shipmentschedule.api.impl.ShipmentScheduleHUTrxListener.huParentChanged(I_M_HU, I_M_HU_Item)<NEW_LINE>}<NEW_LINE>} | LULoader luLoader = new LULoader(huContext); |
1,267,724 | public void paintEntity(Graphics g) {<NEW_LINE>Graphics2D g2 = (Graphics2D) g;<NEW_LINE>g2.setFont(HandlerElementMap.getHandlerForElement(this).<MASK><NEW_LINE>// enable colors<NEW_LINE>Composite[] composites = colorize(g2);<NEW_LINE>g2.setColor(fgColor);<NEW_LINE>Polygon poly = new Polygon();<NEW_LINE>poly.addPoint(getRectangle().width / 2, 0);<NEW_LINE>poly.addPoint(getRectangle().width, getRectangle().height / 2);<NEW_LINE>poly.addPoint(getRectangle().width / 2, getRectangle().height);<NEW_LINE>poly.addPoint(0, getRectangle().height / 2);<NEW_LINE>g2.setComposite(composites[1]);<NEW_LINE>g2.setColor(bgColor);<NEW_LINE>g2.fillPolygon(poly);<NEW_LINE>g2.setComposite(composites[0]);<NEW_LINE>if (HandlerElementMap.getHandlerForElement(this).getDrawPanel().getSelector().isSelected(this)) {<NEW_LINE>g2.setColor(fgColor);<NEW_LINE>} else {<NEW_LINE>g2.setColor(fgColorBase);<NEW_LINE>}<NEW_LINE>g2.drawPolygon(poly);<NEW_LINE>} | getFontHandler().getFont()); |
725,758 | private static ImmutableList<GeneratedTarget> runQuery(Project project, Label label) {<NEW_LINE>String outputBase = BlazeQueryOutputBaseProvider.<MASK><NEW_LINE>if (outputBase == null) {<NEW_LINE>// since this is run automatically in the background, don't run without a custom output base,<NEW_LINE>// otherwise we'll be monopolizing the primary blaze server<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>String query = String.format("attr('generator_function', '^.+$', %s)", TargetExpression.allFromPackageNonRecursive(label.blazePackage()));<NEW_LINE>// would be nicer to use the Process inputStream directly, rather having two round trips...<NEW_LINE>ByteArrayOutputStream out = new ByteArrayOutputStream(/* size= */<NEW_LINE>4096);<NEW_LINE>int retVal = ExternalTask.builder(WorkspaceRoot.fromProject(project)).args(getBinaryPath(project), outputBase, "query", "--output=proto", query).stdout(out).stderr(LineProcessingOutputStream.of(line -> {<NEW_LINE>// errors are expected, so limit logging to info level<NEW_LINE>logger.info(line);<NEW_LINE>return true;<NEW_LINE>})).build().run();<NEW_LINE>if (retVal != 0 && retVal != 3) {<NEW_LINE>// exit code of 3 indicates non-fatal error (for example, a non-existent directory)<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>return BlazeQueryProtoParser.parseProtoOutput(new ByteArrayInputStream(out.toByteArray()));<NEW_LINE>} catch (IOException e) {<NEW_LINE>logger.warn("Couldn't parse blaze query proto output", e);<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>} | getInstance(project).getOutputBaseFlag(); |
236,012 | final GetNetworkAnalyzerConfigurationResult executeGetNetworkAnalyzerConfiguration(GetNetworkAnalyzerConfigurationRequest getNetworkAnalyzerConfigurationRequest) {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(getNetworkAnalyzerConfigurationRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE>awsRequestMetrics.startEvent(Field.ClientExecuteTime);<NEW_LINE>Request<GetNetworkAnalyzerConfigurationRequest> request = null;<NEW_LINE>Response<GetNetworkAnalyzerConfigurationResult> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new GetNetworkAnalyzerConfigurationRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(getNetworkAnalyzerConfigurationRequest));<NEW_LINE>// Binds the request metrics to the current request.<NEW_LINE>request.setAWSRequestMetrics(awsRequestMetrics);<NEW_LINE>request.addHandlerContext(HandlerContextKey.CLIENT_ENDPOINT, endpoint);<NEW_LINE>request.addHandlerContext(<MASK><NEW_LINE>request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SERVICE_ID, "IoT Wireless");<NEW_LINE>request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "GetNetworkAnalyzerConfiguration");<NEW_LINE>request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);<NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.RequestMarshallTime);<NEW_LINE>}<NEW_LINE>HttpResponseHandler<AmazonWebServiceResponse<GetNetworkAnalyzerConfigurationResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new GetNetworkAnalyzerConfigurationResultJsonUnmarshaller());<NEW_LINE>response = invoke(request, responseHandler, executionContext);<NEW_LINE>return response.getAwsResponse();<NEW_LINE>} finally {<NEW_LINE>endClientExecution(awsRequestMetrics, request, response);<NEW_LINE>}<NEW_LINE>} | HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden()); |
1,439,094 | public static Props loadPropsFromYamlFile(final ProjectLoader projectLoader, final ExecutableFlow executableFlow, final String path) {<NEW_LINE>File tempDir = null;<NEW_LINE>Props props = null;<NEW_LINE>try {<NEW_LINE>tempDir = com.google.common.io.Files.createTempDir();<NEW_LINE>props = FlowLoaderUtils.getPropsFromYamlFile(path == null ? executableFlow.getId() : path, getFlowFile<MASK><NEW_LINE>} catch (final Exception e) {<NEW_LINE>logger.error("Failed to get props from flow file. " + e);<NEW_LINE>} finally {<NEW_LINE>if (tempDir != null && tempDir.exists()) {<NEW_LINE>try {<NEW_LINE>FileUtils.deleteDirectory(tempDir);<NEW_LINE>} catch (final IOException e) {<NEW_LINE>logger.error("Failed to delete temp directory." + e);<NEW_LINE>tempDir.deleteOnExit();<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return props;<NEW_LINE>} | (tempDir, projectLoader, executableFlow)); |
1,738,346 | private boolean sendAsReply(String channel, String text) {<NEW_LINE>boolean restricted = settings.getBoolean("mentionReplyRestricted");<NEW_LINE>boolean doubleAt = text.startsWith("@@");<NEW_LINE>if (doubleAt || (!restricted && text.startsWith("@"))) {<NEW_LINE>String[] split = text.split(" ", 2);<NEW_LINE>// Min username length may be 1 or 2, depending on @@ or @<NEW_LINE>if (split.length == 2 && split[0].length() > 2 && split[1].length() > 0) {<NEW_LINE>String username = split[0].substring(doubleAt ? 2 : 1);<NEW_LINE>String actualMsg = split[1];<NEW_LINE>User user = c.getExistingUser(channel, username);<NEW_LINE>if (user != null) {<NEW_LINE>SelectReplyMessage.settings = settings;<NEW_LINE>SelectReplyMessageResult result = SelectReplyMessage.show(user);<NEW_LINE>if (result.action != SelectReplyMessageResult.Action.SEND_NORMALLY) {<NEW_LINE>// Should not send normally, so return true<NEW_LINE>if (result.action == SelectReplyMessageResult.Action.REPLY) {<NEW_LINE>// If changed to parent msg-id, atMsg will be null<NEW_LINE>sendReply(channel, actualMsg, username, result.atMsgId, result.atMsg);<NEW_LINE>} else {<NEW_LINE><MASK><NEW_LINE>}<NEW_LINE>return true;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return false;<NEW_LINE>} | g.insert(text, false); |
1,681,968 | public void actionPerformed(ActionEvent e) {<NEW_LINE>MenuItem c = (MenuItem) e.getSource();<NEW_LINE>String name = c.getName();<NEW_LINE>if ("ADD_URL".equals(name)) {<NEW_LINE>XDMApp.getInstance().addDownload(null, null);<NEW_LINE>} else if ("RESTORE".equals(name)) {<NEW_LINE>XDMApp.getInstance().showMainWindow();<NEW_LINE>} else if ("EXIT".equals(name)) {<NEW_LINE>XDMApp.getInstance().exit();<NEW_LINE>} else if ("THROTTLE".equals(name)) {<NEW_LINE>int ret = SpeedLimiter.getSpeedLimit();<NEW_LINE>if (ret >= 0) {<NEW_LINE>Config.getInstance().setSpeedLimit(ret);<NEW_LINE>}<NEW_LINE>} else if ("ADD_VID".equals(name)) {<NEW_LINE>MediaDownloaderWnd wnd = new MediaDownloaderWnd();<NEW_LINE>wnd.setVisible(true);<NEW_LINE>} else if ("THROTTLE".equals(name)) {<NEW_LINE><MASK><NEW_LINE>if (ret >= 0) {<NEW_LINE>Config.getInstance().setSpeedLimit(ret);<NEW_LINE>}<NEW_LINE>} else if ("ADD_BAT".equals(name)) {<NEW_LINE>new BatchPatternDialog().setVisible(true);<NEW_LINE>} else if ("ADD_CLIP".equals(name)) {<NEW_LINE>List<String> urlList = BatchDownloadWnd.getUrls();<NEW_LINE>if (urlList.size() > 0) {<NEW_LINE>new BatchDownloadWnd(XDMUtils.toMetadata(urlList)).setVisible(true);<NEW_LINE>} else {<NEW_LINE>JOptionPane.showMessageDialog(null, StringResource.get("LBL_BATCH_EMPTY_CLIPBOARD"));<NEW_LINE>}<NEW_LINE>} else if ("MONITORING".equals(name)) {<NEW_LINE>}<NEW_LINE>} | int ret = SpeedLimiter.getSpeedLimit(); |
754,169 | private HttpServer configHttpServer(URI uri, ResourceConfig rc) {<NEW_LINE>String protocol = uri.getScheme();<NEW_LINE>final HttpServer server;<NEW_LINE>if (protocol != null && protocol.equals("https")) {<NEW_LINE>SSLContextConfigurator sslContext = new SSLContextConfigurator();<NEW_LINE>String keystoreFile = this.conf.get(ServerOptions.SSL_KEYSTORE_FILE);<NEW_LINE>String keystorePass = this.conf.get(ServerOptions.SSL_KEYSTORE_PASSWORD);<NEW_LINE>sslContext.setKeyStoreFile(keystoreFile);<NEW_LINE>sslContext.setKeyStorePass(keystorePass);<NEW_LINE>SSLEngineConfigurator sslConfig = new SSLEngineConfigurator(sslContext);<NEW_LINE>sslConfig.setClientMode(false);<NEW_LINE>sslConfig.setWantClientAuth(true);<NEW_LINE>server = GrizzlyHttpServerFactory.createHttpServer(uri, rc, true, sslConfig);<NEW_LINE>} else {<NEW_LINE>server = GrizzlyHttpServerFactory.createHttpServer(uri, rc, false);<NEW_LINE>}<NEW_LINE>Collection<NetworkListener> listeners = server.getListeners();<NEW_LINE>E.checkState(listeners.<MASK><NEW_LINE>NetworkListener listener = listeners.iterator().next();<NEW_LINE>// Option max_worker_threads<NEW_LINE>int maxWorkerThreads = this.conf.get(ServerOptions.MAX_WORKER_THREADS);<NEW_LINE>listener.getTransport().getWorkerThreadPoolConfig().setCorePoolSize(maxWorkerThreads).setMaxPoolSize(maxWorkerThreads);<NEW_LINE>// Option keep_alive<NEW_LINE>int idleTimeout = this.conf.get(ServerOptions.CONN_IDLE_TIMEOUT);<NEW_LINE>int maxRequests = this.conf.get(ServerOptions.CONN_MAX_REQUESTS);<NEW_LINE>listener.getKeepAlive().setIdleTimeoutInSeconds(idleTimeout);<NEW_LINE>listener.getKeepAlive().setMaxRequestsCount(maxRequests);<NEW_LINE>// Option transaction timeout<NEW_LINE>int transactionTimeout = this.conf.get(ServerOptions.REQUEST_TIMEOUT);<NEW_LINE>listener.setTransactionTimeout(transactionTimeout);<NEW_LINE>return server;<NEW_LINE>} | size() > 0, "Http Server should have some listeners, but now is none"); |
779,971 | public int onStartCommand(Intent intent, int flags, int startId) {<NEW_LINE>int status = intent.getIntExtra(PackageInstaller.EXTRA_STATUS, -999);<NEW_LINE>switch(status) {<NEW_LINE>case PackageInstaller.STATUS_PENDING_USER_ACTION:<NEW_LINE><MASK><NEW_LINE>sendStatusChangeBroadcast(intent.getIntExtra(PackageInstaller.EXTRA_SESSION_ID, -1), STATUS_CONFIRMATION_PENDING, intent.getStringExtra(PackageInstaller.EXTRA_PACKAGE_NAME));<NEW_LINE>Intent confirmationIntent = intent.getParcelableExtra(Intent.EXTRA_INTENT);<NEW_LINE>ConfirmationIntentWrapperActivity.start(this, intent.getIntExtra(PackageInstaller.EXTRA_SESSION_ID, -1), confirmationIntent);<NEW_LINE>break;<NEW_LINE>case PackageInstaller.STATUS_SUCCESS:<NEW_LINE>Log.d(TAG, "Installation succeed");<NEW_LINE>sendStatusChangeBroadcast(intent.getIntExtra(PackageInstaller.EXTRA_SESSION_ID, -1), STATUS_SUCCESS, intent.getStringExtra(PackageInstaller.EXTRA_PACKAGE_NAME));<NEW_LINE>break;<NEW_LINE>default:<NEW_LINE>Log.d(TAG, "Installation failed");<NEW_LINE>sendErrorBroadcast(intent.getIntExtra(PackageInstaller.EXTRA_SESSION_ID, -1), getErrorString(status, intent.getStringExtra(PackageInstaller.EXTRA_OTHER_PACKAGE_NAME)));<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>stopSelf();<NEW_LINE>return START_NOT_STICKY;<NEW_LINE>} | Log.d(TAG, "Requesting user confirmation for installation"); |
142,822 | static void loadCsv(String projectId, String instanceId, String databaseId, String tableName, String filePath, String[] optFlags) throws Exception {<NEW_LINE>SpannerOptions options = SpannerOptions<MASK><NEW_LINE>Spanner spanner = options.getService();<NEW_LINE>// Initialize option flags<NEW_LINE>Options opt = new Options();<NEW_LINE>opt.addOption("h", true, "File Contains Header");<NEW_LINE>opt.addOption("f", true, "Format Type of Input File " + "(EXCEL, POSTGRESQL_CSV, POSTGRESQL_TEXT, DEFAULT)");<NEW_LINE>opt.addOption("n", true, "String Representing Null Value");<NEW_LINE>opt.addOption("d", true, "Character Separating Columns");<NEW_LINE>opt.addOption("e", true, "Character To Escape");<NEW_LINE>CommandLineParser clParser = new DefaultParser();<NEW_LINE>CommandLine cmd = clParser.parse(opt, optFlags);<NEW_LINE>try {<NEW_LINE>// Initialize connection to Cloud Spanner<NEW_LINE>connection = DriverManager.getConnection(String.format("jdbc:cloudspanner:/projects/%s/instances/%s/databases/%s", projectId, instanceId, databaseId));<NEW_LINE>parseTableColumns(tableName);<NEW_LINE>try (Reader in = new FileReader(filePath);<NEW_LINE>CSVParser parser = CSVParser.parse(in, setFormat(cmd))) {<NEW_LINE>// If file has header, verify that header fields are valid<NEW_LINE>if (hasHeader && !isValidHeader(parser)) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>// Write CSV record data to Cloud Spanner<NEW_LINE>writeToSpanner(parser, tableName);<NEW_LINE>} catch (SQLException e) {<NEW_LINE>System.out.println(e.getMessage());<NEW_LINE>}<NEW_LINE>} finally {<NEW_LINE>spanner.close();<NEW_LINE>connection.close();<NEW_LINE>}<NEW_LINE>} | .newBuilder().build(); |
54,813 | public void writeTo(OutputStream out) throws FuseMapFillerException, IOException, PinMapException {<NEW_LINE>for (String in : builder.getInputs()) {<NEW_LINE>int i = pinMap.getInputFor(in);<NEW_LINE>if (i == 13)<NEW_LINE>filler.addVariable(21, new Variable(in));<NEW_LINE>else<NEW_LINE>filler.addVariable((i - 1) * 2, new Variable(in));<NEW_LINE>}<NEW_LINE>for (String o : builder.getOutputs()) {<NEW_LINE>int i = <MASK><NEW_LINE>filler.addVariableReverse(i * 2 + 1, new Variable(o));<NEW_LINE>}<NEW_LINE>for (String o : builder.getOutputs()) {<NEW_LINE>int olmc = 23 - pinMap.getOutputFor(o);<NEW_LINE>int offs = OE_FUSE_NUM_BY_OLMC[olmc];<NEW_LINE>// turn on OE<NEW_LINE>for (int j = 0; j < 44; j++) map.setFuse(offs + j);<NEW_LINE>// set olmc to active high<NEW_LINE>map.setFuse(S0 + olmc * 2);<NEW_LINE>if (builder.getCombinatorial().containsKey(o)) {<NEW_LINE>map.setFuse(S1 + olmc * 2);<NEW_LINE>filler.fillExpression(offs + 44, builder.getCombinatorial().get(o), PRODUCTS_BY_OLMC[olmc]);<NEW_LINE>} else if (builder.getRegistered().containsKey(o)) {<NEW_LINE>filler.fillExpression(offs + 44, builder.getRegistered().get(o), PRODUCTS_BY_OLMC[olmc]);<NEW_LINE>} else<NEW_LINE>throw new FuseMapFillerException("variable " + o + " not found!");<NEW_LINE>}<NEW_LINE>try (JedecWriter w = new JedecWriter(out)) {<NEW_LINE>w.println("Digital GAL22v10 assembler*").write(map);<NEW_LINE>}<NEW_LINE>} | 23 - pinMap.getOutputFor(o); |
5,723 | private void updateColumnItem(TableItem attrItem) {<NEW_LINE>DBDAttributeBinding attr = (DBDAttributeBinding) attrItem.getData();<NEW_LINE>String transformStr = "";<NEW_LINE>DBVEntityAttribute vAttr = vEntity.getVirtualAttribute(attr, false);<NEW_LINE>if (vAttr != null) {<NEW_LINE>DBVTransformSettings transformSettings = vAttr.getTransformSettings();<NEW_LINE>if (transformSettings != null) {<NEW_LINE>if (!CommonUtils.isEmpty(transformSettings.getIncludedTransformers())) {<NEW_LINE>transformStr = String.join(",", transformSettings.getIncludedTransformers());<NEW_LINE>} else if (!CommonUtils.isEmpty(transformSettings.getCustomTransformer())) {<NEW_LINE>DBDAttributeTransformerDescriptor td = DBWorkbench.getPlatform().getValueHandlerRegistry().getTransformer(transformSettings.getCustomTransformer());<NEW_LINE>if (td != null) {<NEW_LINE>transformStr = td.getName();<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>attrItem.setText(1, transformStr);<NEW_LINE>String colorSettings = "";<NEW_LINE>{<NEW_LINE>java.util.List<DBVColorOverride> coList = vEntity.getColorOverrides(attr.getName());<NEW_LINE>if (!coList.isEmpty()) {<NEW_LINE>java.util.List<String> coStrings = new ArrayList<>();<NEW_LINE>for (DBVColorOverride co : coList) {<NEW_LINE>if (co.getAttributeValues() != null) {<NEW_LINE>for (Object value : co.getAttributeValues()) {<NEW_LINE>coStrings.add(CommonUtils.toString(value));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>colorSettings = <MASK><NEW_LINE>}<NEW_LINE>}<NEW_LINE>attrItem.setText(2, colorSettings);<NEW_LINE>} | String.join(",", coStrings); |
1,567,386 | private static long parseLong(final CharSequence cs, final int length) {<NEW_LINE>int i = 0;<NEW_LINE>final char firstCh = cs.charAt(i);<NEW_LINE>final boolean negative = firstCh == '-';<NEW_LINE>if ((negative || firstCh == '+') && ++i == length) {<NEW_LINE>throw illegalInput(cs);<NEW_LINE>}<NEW_LINE>long result = 0;<NEW_LINE>while (i < length) {<NEW_LINE>final int digit = Character.digit(cs.charAt(i++), RADIX_10);<NEW_LINE>if (digit < 0) {<NEW_LINE>throw illegalInput(cs);<NEW_LINE>}<NEW_LINE>if (PARSE_LONG_MIN > result) {<NEW_LINE>throw illegalInput(cs);<NEW_LINE>}<NEW_LINE><MASK><NEW_LINE>if (next > result) {<NEW_LINE>throw illegalInput(cs);<NEW_LINE>}<NEW_LINE>result = next;<NEW_LINE>}<NEW_LINE>if (!negative) {<NEW_LINE>result = -result;<NEW_LINE>if (result < 0) {<NEW_LINE>throw illegalInput(cs);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return result;<NEW_LINE>} | long next = result * RADIX_10 - digit; |
1,810,414 | private void testCodeFirstCompletableFuture(CodeFirstPojoIntf codeFirst) {<NEW_LINE>if (!CodeFirstPojoClientIntf.class.isInstance(codeFirst)) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>Vertx vertx = VertxUtils.getOrCreateVertxByName("transport", null);<NEW_LINE>CountDownLatch latch = new CountDownLatch(1);<NEW_LINE>// vertx.runOnContext in normal thread is not a good practice<NEW_LINE>// here just a test, not care for this.<NEW_LINE>vertx.runOnContext(V -> {<NEW_LINE>InvocationContext context = new InvocationContext();<NEW_LINE><MASK><NEW_LINE>ContextUtils.setInvocationContext(context);<NEW_LINE>((CodeFirstPojoClientIntf) codeFirst).sayHiAsync("someone").thenCompose(result -> {<NEW_LINE>TestMgr.check("someone sayhi, context k: v", result);<NEW_LINE>TestMgr.check(true, context == ContextUtils.getInvocationContext());<NEW_LINE>return ((CodeFirstPojoClientIntf) codeFirst).sayHiAsync("someone 1");<NEW_LINE>}).whenComplete((r, e) -> {<NEW_LINE>TestMgr.check("someone 1 sayhi, context k: v", r);<NEW_LINE>latch.countDown();<NEW_LINE>});<NEW_LINE>ContextUtils.removeInvocationContext();<NEW_LINE>});<NEW_LINE>try {<NEW_LINE>latch.await();<NEW_LINE>} catch (InterruptedException e) {<NEW_LINE>throw new IllegalStateException(e);<NEW_LINE>}<NEW_LINE>} | context.addContext("k", "v"); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.