idx int32 46 1.86M | input stringlengths 321 6.6k | target stringlengths 9 1.24k |
|---|---|---|
695,070 | private void removeRemainingSlashes() {<NEW_LINE>ArrayList<String> tmp = new ArrayList<String>();<NEW_LINE>boolean foundEOLSlash = false;<NEW_LINE>for (Iterator<String> iter = _queries.iterator(); iter.hasNext(); ) {<NEW_LINE>String next = iter.next();<NEW_LINE>if (slashPattern.matcher(next).matches()) {<NEW_LINE>foundEOLSlash = true;<NEW_LINE>String[] parts = next.split(SLASH_SPLIT_PATTERN);<NEW_LINE>for (int i = 0; i < parts.length; i++) {<NEW_LINE>String part = parts[i];<NEW_LINE>if (slashPattern.matcher(part).matches()) {<NEW_LINE>int lastIndex = part.lastIndexOf("/");<NEW_LINE>tmp.add(part.substring(0, lastIndex));<NEW_LINE>} else {<NEW_LINE>if (part.endsWith("/")) {<NEW_LINE>part = part.substring(0, part.lastIndexOf("/"));<NEW_LINE>}<NEW_LINE>tmp.add(part);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} else if (next.endsWith("/")) {<NEW_LINE>foundEOLSlash = true;<NEW_LINE>int lastIndex = next.lastIndexOf("/");<NEW_LINE>tmp.add(next<MASK><NEW_LINE>} else {<NEW_LINE>tmp.add(next);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (foundEOLSlash == true) {<NEW_LINE>_queries = tmp;<NEW_LINE>}<NEW_LINE>} | .substring(0, lastIndex)); |
1,155,177 | public DecisionTaskCompletedEventAttributes unmarshall(JsonUnmarshallerContext context) throws Exception {<NEW_LINE>DecisionTaskCompletedEventAttributes decisionTaskCompletedEventAttributes = new DecisionTaskCompletedEventAttributes();<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("executionContext", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>decisionTaskCompletedEventAttributes.setExecutionContext(context.getUnmarshaller(String.<MASK><NEW_LINE>}<NEW_LINE>if (context.testExpression("scheduledEventId", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>decisionTaskCompletedEventAttributes.setScheduledEventId(context.getUnmarshaller(Long.class).unmarshall(context));<NEW_LINE>}<NEW_LINE>if (context.testExpression("startedEventId", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>decisionTaskCompletedEventAttributes.setStartedEventId(context.getUnmarshaller(Long.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 decisionTaskCompletedEventAttributes;<NEW_LINE>} | class).unmarshall(context)); |
1,267,183 | public static Vector combineServerRowSplits(List<ServerRow> rowSplits, int matrixId, int rowIndex) {<NEW_LINE>MatrixMeta matrixMeta = PSAgentContext.get().getMatrixMetaManager().getMatrixMeta(matrixId);<NEW_LINE>RowType rowType = matrixMeta.getRowType();<NEW_LINE>switch(rowType) {<NEW_LINE>case T_DOUBLE_DENSE:<NEW_LINE>case T_DOUBLE_SPARSE:<NEW_LINE>return <MASK><NEW_LINE>case T_FLOAT_DENSE:<NEW_LINE>case T_FLOAT_SPARSE:<NEW_LINE>return combineServerIntFloatRowSplits(rowSplits, matrixMeta, rowIndex);<NEW_LINE>case T_INT_DENSE:<NEW_LINE>case T_INT_SPARSE:<NEW_LINE>return combineServerIntIntRowSplits(rowSplits, matrixMeta, rowIndex);<NEW_LINE>case T_LONG_DENSE:<NEW_LINE>case T_LONG_SPARSE:<NEW_LINE>return combineServerIntLongRowSplits(rowSplits, matrixMeta, rowIndex);<NEW_LINE>case T_DOUBLE_SPARSE_LONGKEY:<NEW_LINE>return combineServerLongDoubleRowSplits(rowSplits, matrixMeta, rowIndex);<NEW_LINE>case T_FLOAT_SPARSE_LONGKEY:<NEW_LINE>return combineServerLongFloatRowSplits(rowSplits, matrixMeta, rowIndex);<NEW_LINE>case T_INT_SPARSE_LONGKEY:<NEW_LINE>return combineServerLongIntRowSplits(rowSplits, matrixMeta, rowIndex);<NEW_LINE>case T_LONG_SPARSE_LONGKEY:<NEW_LINE>return combineServerLongLongRowSplits(rowSplits, matrixMeta, rowIndex);<NEW_LINE>default:<NEW_LINE>throw new UnsupportedOperationException("Unsupport operation: merge " + rowType + " vector splits");<NEW_LINE>}<NEW_LINE>} | combineServerIntDoubleRowSplits(rowSplits, matrixMeta, rowIndex); |
427,567 | private static BiPredicate<AccessGroupDefinition, Entity> createBiPredicate(String className, String methodName, String argClassName) {<NEW_LINE>Class<?> clazz = ReflectionHelper.getClass(className);<NEW_LINE>Class<?> argumentClazz = ReflectionHelper.getClass(argClassName);<NEW_LINE>Method method = Arrays.stream(clazz.getMethods()).filter(m -> Objects.equals(m.getName(), methodName)).filter(m -> m.getParameterCount() == 1 && Objects.equals(m.getParameterTypes()[0], argumentClazz)).findFirst().orElseThrow(() -> new RuntimeException(String.format(<MASK><NEW_LINE>try {<NEW_LINE>MethodHandles.Lookup caller = MethodHandles.lookup();<NEW_LINE>CallSite site = LambdaMetafactory.metafactory(caller, "test", MethodType.methodType(BiPredicate.class), MethodType.methodType(boolean.class, Object.class, Object.class), caller.findVirtual(clazz, method.getName(), MethodType.methodType(method.getReturnType(), argumentClazz)), MethodType.methodType(boolean.class, clazz, argumentClazz));<NEW_LINE>// noinspection unchecked<NEW_LINE>return (BiPredicate<AccessGroupDefinition, Entity>) site.getTarget().invoke();<NEW_LINE>} catch (Throwable e) {<NEW_LINE>throw new IllegalStateException(String.format("Can't create in-memory constraint predicate for method %s#%s", className, methodName), e);<NEW_LINE>}<NEW_LINE>} | "Unable to find corresponding in-memory predicate method %s#%s", className, methodName))); |
1,305,548 | public Object createBean(Object srcObj, Class<?> srcObjClass, String beanId, BeanContainer beanContainer) {<NEW_LINE>log.debug("createBean(Object, Class, String) - start [{}]", beanId);<NEW_LINE>int indexOf = beanId.indexOf(INNER_CLASS_DELIMITER);<NEW_LINE>while (indexOf > 0) {<NEW_LINE>beanId = beanId.substring(0, indexOf) + beanId.substring(indexOf + 1);<NEW_LINE>log.debug("createBean(Object, Class, String) - HAS BEEN CHANGED TO [{}]", beanId);<NEW_LINE>indexOf = beanId.indexOf(INNER_CLASS_DELIMITER);<NEW_LINE>}<NEW_LINE>Object result;<NEW_LINE>Class<?> objectFactory = MappingUtils.loadClass(beanId.substring(0, beanId.lastIndexOf(<MASK><NEW_LINE>Object factory = ReflectionUtils.newInstance(objectFactory);<NEW_LINE>Method method = null;<NEW_LINE>try {<NEW_LINE>method = ReflectionUtils.getMethod(objectFactory, "create" + beanId.substring(beanId.lastIndexOf(".") + 1), new Class[] {});<NEW_LINE>} catch (NoSuchMethodException e) {<NEW_LINE>MappingUtils.throwMappingException(e);<NEW_LINE>}<NEW_LINE>Object returnObject = ReflectionUtils.invoke(method, factory, new Object[] {});<NEW_LINE>log.debug("createBean(Object, Class, String) - end [{}]", returnObject.getClass().getName());<NEW_LINE>result = returnObject;<NEW_LINE>return result;<NEW_LINE>} | ".")) + ".ObjectFactory", beanContainer); |
835,843 | public PendingModifiedServiceUpdate unmarshall(JsonUnmarshallerContext context) throws Exception {<NEW_LINE>PendingModifiedServiceUpdate pendingModifiedServiceUpdate = new PendingModifiedServiceUpdate();<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("ServiceUpdateName", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>pendingModifiedServiceUpdate.setServiceUpdateName(context.getUnmarshaller(String.class).unmarshall(context));<NEW_LINE>}<NEW_LINE>if (context.testExpression("Status", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>pendingModifiedServiceUpdate.setStatus(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 pendingModifiedServiceUpdate;<NEW_LINE>} | String currentParentElement = context.getCurrentParentElement(); |
732,272 | public String execute(CommandContext commandContext, String[] args) {<NEW_LINE>String config = frameworkModel.getApplicationModels().stream().map(applicationModel -> applicationModel.getApplicationConfigManager().getApplication()).map(o -> o.orElse(null)).filter(Objects::nonNull).map(ApplicationConfig::getStartupProbe).filter(Objects::nonNull).collect<MASK><NEW_LINE>URL url = URL.valueOf("application://").addParameter(CommonConstants.QOS_STARTUP_PROBE_EXTENSION, config);<NEW_LINE>List<StartupProbe> startupProbes = frameworkModel.getExtensionLoader(StartupProbe.class).getActivateExtension(url, CommonConstants.QOS_STARTUP_PROBE_EXTENSION);<NEW_LINE>if (!startupProbes.isEmpty()) {<NEW_LINE>for (StartupProbe startupProbe : startupProbes) {<NEW_LINE>if (!startupProbe.check()) {<NEW_LINE>// 503 Service Unavailable<NEW_LINE>commandContext.setHttpCode(503);<NEW_LINE>return "false";<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// 200 OK<NEW_LINE>commandContext.setHttpCode(200);<NEW_LINE>return "true";<NEW_LINE>} | (Collectors.joining(",")); |
1,165,014 | public void deleteMessage(final Message message, final String userId) {<NEW_LINE>if (getActivity() == null) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>this.getActivity().runOnUiThread(new Runnable() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void run() {<NEW_LINE>Message recentMessage;<NEW_LINE>if (message.getGroupId() != null) {<NEW_LINE>recentMessage = latestMessageForEachContact.get(ConversationUIService.<MASK><NEW_LINE>} else {<NEW_LINE>recentMessage = latestMessageForEachContact.get(message.getContactIds());<NEW_LINE>}<NEW_LINE>if (recentMessage != null && message.getCreatedAtTime() <= recentMessage.getCreatedAtTime()) {<NEW_LINE>if (message.getGroupId() != null) {<NEW_LINE>latestMessageForEachContact.put(ConversationUIService.GROUP + message.getGroupId(), message);<NEW_LINE>} else {<NEW_LINE>latestMessageForEachContact.put(message.getContactIds(), message);<NEW_LINE>}<NEW_LINE>messageList.set(messageList.indexOf(recentMessage), message);<NEW_LINE>recyclerAdapter.notifyDataSetChanged();<NEW_LINE>if (messageList.isEmpty()) {<NEW_LINE>emptyTextView.setVisibility(View.VISIBLE);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>});<NEW_LINE>} | GROUP + message.getGroupId()); |
1,194,317 | public static int[] hashCarterWegman(byte[] value, int m, int k) {<NEW_LINE>int[<MASK><NEW_LINE>BigInteger prime32 = BigInteger.valueOf(4294967279l);<NEW_LINE>BigInteger prime64 = BigInteger.valueOf(53200200938189l);<NEW_LINE>BigInteger prime128 = new BigInteger("21213943449988109084994671");<NEW_LINE>Random r = new Random(seed32);<NEW_LINE>// BigInteger.valueOf(hashBytes(value)<NEW_LINE>BigInteger v = new BigInteger(value.length > 0 ? value : new byte[1]);<NEW_LINE>for (int i = 0; i < k; i++) {<NEW_LINE>BigInteger a = BigInteger.valueOf(r.nextLong());<NEW_LINE>BigInteger b = BigInteger.valueOf(r.nextLong());<NEW_LINE>positions[i] = a.multiply(v).add(b).mod(prime64).mod(BigInteger.valueOf(m)).intValue();<NEW_LINE>}<NEW_LINE>return positions;<NEW_LINE>} | ] positions = new int[k]; |
1,659,417 | public Builder mergeFrom(cn.wildfirechat.proto.WFCMessage.Group other) {<NEW_LINE>if (other == cn.wildfirechat.proto.WFCMessage.Group.getDefaultInstance())<NEW_LINE>return this;<NEW_LINE>if (other.hasGroupInfo()) {<NEW_LINE>mergeGroupInfo(other.getGroupInfo());<NEW_LINE>}<NEW_LINE>if (membersBuilder_ == null) {<NEW_LINE>if (!other.members_.isEmpty()) {<NEW_LINE>if (members_.isEmpty()) {<NEW_LINE>members_ = other.members_;<NEW_LINE>bitField0_ = (bitField0_ & ~0x00000002);<NEW_LINE>} else {<NEW_LINE>ensureMembersIsMutable();<NEW_LINE>members_.addAll(other.members_);<NEW_LINE>}<NEW_LINE>onChanged();<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>if (!other.members_.isEmpty()) {<NEW_LINE>if (membersBuilder_.isEmpty()) {<NEW_LINE>membersBuilder_.dispose();<NEW_LINE>membersBuilder_ = null;<NEW_LINE>members_ = other.members_;<NEW_LINE><MASK><NEW_LINE>membersBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getMembersFieldBuilder() : null;<NEW_LINE>} else {<NEW_LINE>membersBuilder_.addAllMessages(other.members_);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>this.mergeUnknownFields(other.getUnknownFields());<NEW_LINE>return this;<NEW_LINE>} | bitField0_ = (bitField0_ & ~0x00000002); |
1,846,086 | private void run() {<NEW_LINE>if (badOptions || helpRequested || blobFile == null || outDir == null) {<NEW_LINE>System.out.printf("Usage: java %s [options]%n", getClass().getName());<NEW_LINE>System.out.printf(" options:%n");<NEW_LINE>System.out.printf(" --blob=<blob file>%n");<NEW_LINE>System.out.printf(" --debug%n");<NEW_LINE><MASK><NEW_LINE>System.out.printf(" --out=<output directory>%n");<NEW_LINE>} else {<NEW_LINE>try {<NEW_LINE>StructureReader reader = readBlob(blobFile);<NEW_LINE>checkAndFilterFields(reader);<NEW_LINE>writeTo(reader, outDir);<NEW_LINE>} catch (IOException e) {<NEW_LINE>System.out.printf("Can't read blob: %s%n", e.getLocalizedMessage());<NEW_LINE>System.exit(1);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | System.out.printf(" --help%n"); |
1,707,804 | public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {<NEW_LINE>View view = inflater.inflate(<MASK><NEW_LINE>mActionButton = (Button) view.findViewById(R.id.action);<NEW_LINE>mActionButton.setOnClickListener(v -> {<NEW_LINE>if (mService != null) {<NEW_LINE>mService.disconnect();<NEW_LINE>}<NEW_LINE>});<NEW_LINE>enableActionButton(null);<NEW_LINE>mErrorView = view.findViewById(R.id.vpn_error);<NEW_LINE>mErrorText = view.findViewById(R.id.vpn_error_text);<NEW_LINE>mErrorRetry = view.findViewById(R.id.retry);<NEW_LINE>mShowLog = view.findViewById(R.id.show_log);<NEW_LINE>mProgress = (ProgressBar) view.findViewById(R.id.progress);<NEW_LINE>mStateView = (TextView) view.findViewById(R.id.vpn_state);<NEW_LINE>mColorStateBase = mStateView.getCurrentTextColor();<NEW_LINE>mProfileView = (TextView) view.findViewById(R.id.vpn_profile_label);<NEW_LINE>mProfileNameView = (TextView) view.findViewById(R.id.vpn_profile_name);<NEW_LINE>mErrorRetry.setOnClickListener(v -> {<NEW_LINE>if (mService != null) {<NEW_LINE>mService.reconnect();<NEW_LINE>}<NEW_LINE>});<NEW_LINE>mShowLog.setOnClickListener(v -> {<NEW_LINE>Intent intent = new Intent(getActivity(), LogActivity.class);<NEW_LINE>startActivity(intent);<NEW_LINE>});<NEW_LINE>return view;<NEW_LINE>} | R.layout.vpn_state_fragment, null); |
577,057 | public GetResult merge(List<PartitionGetResult> partResults) {<NEW_LINE>Int2ObjectArrayMap<PartitionGetResult> partIdToResultMap = new Int2ObjectArrayMap<>(partResults.size());<NEW_LINE>for (PartitionGetResult result : partResults) {<NEW_LINE>partIdToResultMap.put(((PartGetNodeFeatsResult) result).getPartId(), result);<NEW_LINE>}<NEW_LINE>GetNodeFeatsParam param = (GetNodeFeatsParam) getParam();<NEW_LINE>long[<MASK><NEW_LINE>List<PartitionGetParam> partParams = param.getPartParams();<NEW_LINE>Long2ObjectOpenHashMap<IntFloatVector> results = new Long2ObjectOpenHashMap<>(nodeIds.length);<NEW_LINE>int size = partResults.size();<NEW_LINE>for (int i = 0; i < size; i++) {<NEW_LINE>PartGetNodeFeatsParam partParam = (PartGetNodeFeatsParam) partParams.get(i);<NEW_LINE>PartGetNodeFeatsResult partResult = (PartGetNodeFeatsResult) partIdToResultMap.get(partParam.getPartKey().getPartitionId());<NEW_LINE>int start = partParam.getStartIndex();<NEW_LINE>int end = partParam.getEndIndex();<NEW_LINE>IntFloatVector[] feats = partResult.getFeats();<NEW_LINE>for (int j = start; j < end; j++) {<NEW_LINE>if (feats[j - start] != null) {<NEW_LINE>results.put(nodeIds[j], feats[j - start]);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return new GetNodeFeatsResult(results);<NEW_LINE>} | ] nodeIds = param.getNodeIds(); |
1,423,105 | private PricingConditionsBreak changePricingConditionsBreak0(@NonNull final PricingConditionsBreakChangeRequest request) {<NEW_LINE>final PricingConditionsId pricingConditionsId = request.getPricingConditionsId();<NEW_LINE>//<NEW_LINE>// Load/Create discount schema record<NEW_LINE>final I_M_DiscountSchemaBreak schemaBreak;<NEW_LINE>final PricingConditionsBreakId pricingConditionsBreakId = request.getPricingConditionsBreakId();<NEW_LINE>if (pricingConditionsBreakId != null) {<NEW_LINE>schemaBreak = load(pricingConditionsBreakId.getDiscountSchemaBreakId(), I_M_DiscountSchemaBreak.class);<NEW_LINE>if (!pricingConditionsBreakId.matchingDiscountSchemaId(schemaBreak.getM_DiscountSchema_ID())) {<NEW_LINE>throw new AdempiereException("" + request + " and " + schemaBreak + " does not have the same discount schema");<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>if (pricingConditionsId == null) {<NEW_LINE>throw new AdempiereException("Cannot create new break because no pricingConditionsId found: " + request);<NEW_LINE>}<NEW_LINE>final int discountSchemaId = pricingConditionsId.getRepoId();<NEW_LINE>schemaBreak = newInstance(I_M_DiscountSchemaBreak.class);<NEW_LINE>schemaBreak.setM_DiscountSchema_ID(discountSchemaId);<NEW_LINE>schemaBreak.setSeqNo(retrieveNextSeqNo(discountSchemaId));<NEW_LINE>schemaBreak.setBreakValue(BigDecimal.ZERO);<NEW_LINE>}<NEW_LINE>//<NEW_LINE>// Update<NEW_LINE>updateSchemaBreakRecordFromRecordFromMatchCriteria(schemaBreak, request.getMatchCriteria());<NEW_LINE>updateSchemaBreakRecordFromSourceScheamaBreakRecord(schemaBreak, request.getUpdateFromPricingConditionsBreakId());<NEW_LINE>updateSchemaBreakRecordFromPrice(schemaBreak, request.getPrice());<NEW_LINE>if (request.getDiscount() != null) {<NEW_LINE>schemaBreak.setBreakDiscount(request.getDiscount().toBigDecimal());<NEW_LINE>}<NEW_LINE>if (request.getPaymentTermId() != null) {<NEW_LINE>final int paymentTermRepoId = PaymentTermId.toRepoId(request.getPaymentTermId().orElse(null));<NEW_LINE>schemaBreak.setC_PaymentTerm_ID(paymentTermRepoId);<NEW_LINE>}<NEW_LINE>if (request.getPaymentDiscount() != null) {<NEW_LINE>final BigDecimal paymentDiscountValue = request.getPaymentDiscount().map(Percent<MASK><NEW_LINE>schemaBreak.setPaymentDiscount(paymentDiscountValue);<NEW_LINE>}<NEW_LINE>//<NEW_LINE>// Save & validate<NEW_LINE>InterfaceWrapperHelper.save(schemaBreak);<NEW_LINE>if (!schemaBreak.isValid()) {<NEW_LINE>throw new AdempiereException(schemaBreak.getNotValidReason());<NEW_LINE>}<NEW_LINE>return toPricingConditionsBreak(schemaBreak);<NEW_LINE>} | ::toBigDecimal).orElse(null); |
844,683 | // [END_EXCLUDE]<NEW_LINE>public void onCreate(Bundle savedState) {<NEW_LINE>super.onCreate(savedState);<NEW_LINE>// Set the layout. It only contains a SupportMapFragment and a DismissOverlay.<NEW_LINE>setContentView(R.layout.activity_main);<NEW_LINE>// Enable ambient support, so the map remains visible in simplified, low-color display<NEW_LINE>// when the user is no longer actively using the app but the app is still visible on the<NEW_LINE>// watch face.<NEW_LINE>// [START maps_wear_os_ambient_mode_support]<NEW_LINE>AmbientModeSupport.AmbientController controller = AmbientModeSupport.attach(this);<NEW_LINE>// [END maps_wear_os_ambient_mode_support]<NEW_LINE>Log.d(MainActivity.class.getSimpleName(), <MASK><NEW_LINE>// Retrieve the containers for the root of the layout and the map. Margins will need to be<NEW_LINE>// set on them to account for the system window insets.<NEW_LINE>final SwipeDismissFrameLayout mapFrameLayout = (SwipeDismissFrameLayout) findViewById(R.id.map_container);<NEW_LINE>mapFrameLayout.addCallback(new SwipeDismissFrameLayout.Callback() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void onDismissed(SwipeDismissFrameLayout layout) {<NEW_LINE>onBackPressed();<NEW_LINE>}<NEW_LINE>});<NEW_LINE>// Obtain the MapFragment and set the async listener to be notified when the map is ready.<NEW_LINE>mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);<NEW_LINE>mapFragment.getMapAsync(this);<NEW_LINE>} | "Is ambient enabled: " + controller.isAmbient()); |
1,474,794 | public void saveAttachment() throws Exception {<NEW_LINE>IWebDav handler = getFileHandler();<NEW_LINE>MADAttachmentReference attachmentReference = getAttachmentReference();<NEW_LINE>if (attachmentReference == null || attachmentReference.getAD_AttachmentReference_ID() <= 0) {<NEW_LINE>attachmentReference = new MADAttachmentReference(context, 0, transactionName);<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>attachmentReference.setFileHandler_ID(fileHandlerId);<NEW_LINE>attachmentReference.setFileName(getFileName());<NEW_LINE>// Reference<NEW_LINE>if (attachmentId > 0) {<NEW_LINE>attachmentReference.setAD_Attachment_ID(attachmentId);<NEW_LINE>}<NEW_LINE>if (imageId > 0) {<NEW_LINE>attachmentReference.setAD_Image_ID(imageId);<NEW_LINE>}<NEW_LINE>if (archiveId > 0) {<NEW_LINE>attachmentReference.setAD_Archive_ID(archiveId);<NEW_LINE>}<NEW_LINE>// Note<NEW_LINE>if (!Util.isEmpty(note)) {<NEW_LINE>attachmentReference.setTextMsg(note);<NEW_LINE>}<NEW_LINE>// Description<NEW_LINE>if (!Util.isEmpty(description)) {<NEW_LINE>attachmentReference.setDescription(description);<NEW_LINE>}<NEW_LINE>// Save reference<NEW_LINE>attachmentReference.saveEx();<NEW_LINE>// Remove from cache<NEW_LINE>MADAttachmentReference.resetAttachmentCacheFromId(fileHandlerId, attachmentId);<NEW_LINE>if (data == null) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>// Set file size<NEW_LINE>attachmentReference.setFileSize(new BigDecimal(data.length));<NEW_LINE>// Save<NEW_LINE>attachmentReference.saveEx();<NEW_LINE>// Save<NEW_LINE>String validForlder = getValidFolder(attachmentReference);<NEW_LINE>if (!Util.isEmpty(baseFolder)) {<NEW_LINE>// Validate if exist<NEW_LINE>if (!handler.exists(baseFolder)) {<NEW_LINE>handler.createDirectory(baseFolder);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (!Util.isEmpty(validForlder)) {<NEW_LINE>// Validate if exist<NEW_LINE>if (!handler.exists(validForlder)) {<NEW_LINE>handler.createDirectory(validForlder);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>handler.putResource<MASK><NEW_LINE>} catch (Exception e) {<NEW_LINE>if (attachmentReference.getAD_AttachmentReference_ID() > 0) {<NEW_LINE>attachmentReference.deleteEx(true);<NEW_LINE>}<NEW_LINE>throw new AdempiereException(e);<NEW_LINE>}<NEW_LINE>} | (getCompleteFileName(attachmentReference), data); |
1,447,316 | private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {<NEW_LINE>StreamEvent previousStreamEvent;<NEW_LINE>beforeWindowData = (Object[]) stream.readObject();<NEW_LINE>onAfterWindowData = (Object[]) stream.readObject();<NEW_LINE>outputData = (Object[]) stream.readObject();<NEW_LINE>type = (Type) stream.readObject();<NEW_LINE>timestamp = stream.readLong();<NEW_LINE>previousStreamEvent = this;<NEW_LINE>boolean isNextAvailable = stream.readBoolean();<NEW_LINE>while (isNextAvailable) {<NEW_LINE>StreamEvent nextEvent = new StreamEvent(0, 0, 0);<NEW_LINE>nextEvent.beforeWindowData = (Object[]) stream.readObject();<NEW_LINE>nextEvent.onAfterWindowData = (Object[]) stream.readObject();<NEW_LINE>nextEvent.outputData = (Object[]) stream.readObject();<NEW_LINE>nextEvent.type = (Type) stream.readObject();<NEW_LINE>nextEvent<MASK><NEW_LINE>previousStreamEvent.next = nextEvent;<NEW_LINE>previousStreamEvent = nextEvent;<NEW_LINE>isNextAvailable = stream.readBoolean();<NEW_LINE>}<NEW_LINE>} | .timestamp = stream.readLong(); |
1,403,890 | final CreateDiskSnapshotResult executeCreateDiskSnapshot(CreateDiskSnapshotRequest createDiskSnapshotRequest) {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(createDiskSnapshotRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE>awsRequestMetrics.startEvent(Field.ClientExecuteTime);<NEW_LINE>Request<CreateDiskSnapshotRequest> request = null;<NEW_LINE>Response<CreateDiskSnapshotResult> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new CreateDiskSnapshotRequestProtocolMarshaller(protocolFactory).marshall<MASK><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(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Lightsail");<NEW_LINE>request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "CreateDiskSnapshot");<NEW_LINE>request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);<NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.RequestMarshallTime);<NEW_LINE>}<NEW_LINE>HttpResponseHandler<AmazonWebServiceResponse<CreateDiskSnapshotResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new CreateDiskSnapshotResultJsonUnmarshaller());<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>} | (super.beforeMarshalling(createDiskSnapshotRequest)); |
1,518,832 | private <T> void assertSuccess(ManagedExecutorService executor, Future<T> future, Object task, TaskListener listener, T... validResults) throws Exception {<NEW_LINE>assertTrue(listener.latch[SUBMITTED].await(TIMEOUT_NS, TimeUnit.NANOSECONDS));<NEW_LINE>assertEquals(future, listener.future[SUBMITTED]);<NEW_LINE>assertEquals(executor, listener.executor[SUBMITTED]);<NEW_LINE>assertEquals(task, listener.task[SUBMITTED]);<NEW_LINE>assertFalse(listener.isCancelled[SUBMITTED]);<NEW_LINE>assertFalse(listener.isDone[SUBMITTED]);<NEW_LINE>if (listener.failure[SUBMITTED] != null)<NEW_LINE>throw new Exception("Unexpected failure, see cause", listener.failure[SUBMITTED]);<NEW_LINE>assertTrue(listener.latch[STARTING].await(TIMEOUT_NS, TimeUnit.NANOSECONDS));<NEW_LINE>assertEquals(future, listener.future[STARTING]);<NEW_LINE>assertEquals(executor, listener.executor[STARTING]);<NEW_LINE>assertEquals(task, listener.task[STARTING]);<NEW_LINE>assertFalse(listener.isCancelled[STARTING]);<NEW_LINE>assertFalse(listener.isDone[STARTING]);<NEW_LINE>if (listener.failure[STARTING] != null)<NEW_LINE>throw new Exception("Unexpected failure, see cause", listener.failure[STARTING]);<NEW_LINE>assertTrue(listener.latch[DONE].await(TIMEOUT_NS, TimeUnit.NANOSECONDS));<NEW_LINE>assertEquals(future, listener.future[DONE]);<NEW_LINE>assertEquals(executor, listener.executor[DONE]);<NEW_LINE>assertEquals(task, listener.task[DONE]);<NEW_LINE>assertNull(listener.exception[DONE]);<NEW_LINE>assertFalse(listener.isCancelled[DONE]);<NEW_LINE>assertTrue(listener.isDone[DONE]);<NEW_LINE>if (listener.failure[DONE] != null)<NEW_LINE>throw new Exception("Unexpected failure, see cause"<MASK><NEW_LINE>assertEquals(listener.result[DONE], future.get(1, TimeUnit.NANOSECONDS));<NEW_LINE>boolean hasValidResult = false;<NEW_LINE>for (T valid : validResults) hasValidResult |= valid == null && listener.result[DONE] == null || valid.equals(listener.result[DONE]);<NEW_LINE>assertTrue("unexpected: " + listener.result[DONE], hasValidResult);<NEW_LINE>assertFalse(listener.invoked[ABORTED]);<NEW_LINE>} | , listener.failure[DONE]); |
641,645 | private static boolean sameValueAs(LiteralLabel lit1, LiteralLabel lit2) {<NEW_LINE>// return lit1.sameValueAs(lit2) ;<NEW_LINE>if (lit1 == null)<NEW_LINE>throw new NullPointerException();<NEW_LINE>if (lit2 == null)<NEW_LINE>throw new NullPointerException();<NEW_LINE>// Strings.<NEW_LINE>if (isStringValue(lit1) && isStringValue(lit2)) {<NEW_LINE>// Complete compatibility mode.<NEW_LINE>if (JenaParameters.enablePlainLiteralSameAsString)<NEW_LINE>return lit1.getLexicalForm().equals(lit2.getLexicalForm());<NEW_LINE>else<NEW_LINE>return lit1.getLexicalForm().equals(lit2.getLexicalForm()) && Objects.equals(lit1.getDatatype(), lit2.getDatatype());<NEW_LINE>}<NEW_LINE>if (isStringValue(lit1))<NEW_LINE>return false;<NEW_LINE>if (isStringValue(lit2))<NEW_LINE>return false;<NEW_LINE>// Language tag strings<NEW_LINE>if (isLangString(lit1) && isLangString(lit2)) {<NEW_LINE><MASK><NEW_LINE>String lex2 = lit2.getLexicalForm();<NEW_LINE>return lex1.equals(lex2) && lit1.language().equalsIgnoreCase(lit2.language());<NEW_LINE>}<NEW_LINE>if (isLangString(lit1))<NEW_LINE>return false;<NEW_LINE>if (isLangString(lit2))<NEW_LINE>return false;<NEW_LINE>// Both not strings, not lang strings.<NEW_LINE>// Datatype set.<NEW_LINE>if (lit1.isWellFormedRaw() && lit2.isWellFormedRaw())<NEW_LINE>// Both well-formed.<NEW_LINE>return lit1.getDatatype().isEqual(lit1, lit2);<NEW_LINE>if (!lit1.isWellFormedRaw() && !lit2.isWellFormedRaw())<NEW_LINE>return lit1.equals(lit2);<NEW_LINE>// One is well formed, the other is not.<NEW_LINE>return false;<NEW_LINE>} | String lex1 = lit1.getLexicalForm(); |
37,111 | public void checkForDeprecations(String id, NamedXContentRegistry namedXContentRegistry, Consumer<DeprecationIssue> onDeprecation) {<NEW_LINE>LoggingDeprecationAccumulationHandler deprecationLogger = new LoggingDeprecationAccumulationHandler();<NEW_LINE>try {<NEW_LINE>queryFromXContent(source, namedXContentRegistry, deprecationLogger);<NEW_LINE>} catch (IOException e) {<NEW_LINE>onDeprecation.accept(new DeprecationIssue(Level.CRITICAL, "Transform [" + id + "]: " + TransformMessages.LOG_TRANSFORM_CONFIGURATION_BAD_QUERY, TransformDeprecations.QUERY_BREAKING_CHANGES_URL, e.getMessage(), false, null));<NEW_LINE>}<NEW_LINE>deprecationLogger.getDeprecations().forEach(deprecationMessage -> {<NEW_LINE>onDeprecation.accept(new DeprecationIssue(Level.CRITICAL, "Transform [" + id + "] uses deprecated query options", TransformDeprecations.QUERY_BREAKING_CHANGES_URL<MASK><NEW_LINE>});<NEW_LINE>} | , deprecationMessage, false, null)); |
1,267,376 | private void handleResultForAsyncAvailabilityCheck_Error(final PurchaseRowsList rows, final Throwable throwable) {<NEW_LINE>if (throwable instanceof AvailabilityException) {<NEW_LINE>final AvailabilityException availabilityException = AvailabilityException.cast(throwable);<NEW_LINE>final List<DocumentId> changedRowIds = new ArrayList<>();<NEW_LINE>for (final AvailabilityException.ErrorItem errorItem : availabilityException.getErrorItems()) {<NEW_LINE>final TrackingId trackingId = errorItem.getTrackingId();<NEW_LINE>final PurchaseRow lineRow = rows.getPurchaseRowByTrackingId(trackingId);<NEW_LINE>if (lineRow == null) {<NEW_LINE>logger.<MASK><NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>final PurchaseRow availabilityResultRow = purchaseRowFactory.availabilityDetailErrorBuilder().lineRow(lineRow).throwable(errorItem.getError()).build();<NEW_LINE>lineRow.setAvailabilityInfoRow(availabilityResultRow);<NEW_LINE>changedRowIds.add(rows.getTopLevelDocumentIdByTrackingId(trackingId, lineRow.getId()));<NEW_LINE>}<NEW_LINE>notifyViewOfChanges(changedRowIds);<NEW_LINE>} else {<NEW_LINE>// TODO: display an error-message in the webui<NEW_LINE>logger.warn("Got unknown exception while doing availability check. Ignored.", throwable);<NEW_LINE>}<NEW_LINE>} | warn("No line row found for {}. Skip updating the row with availability errors: {}", trackingId, errorItem); |
1,837,573 | private static FilterSpecPlanForge planFilterParametersInternal(List<ExprNode> validatedNodes, FilterSpecCompilerArgs args) throws ExprValidationException {<NEW_LINE>if (validatedNodes.isEmpty()) {<NEW_LINE>return FilterSpecPlanForge.EMPTY;<NEW_LINE>}<NEW_LINE>if (args.compileTimeServices.getConfiguration().getCompiler().getExecution().getFilterIndexPlanning() == ConfigurationCompilerExecution.FilterIndexPlanning.NONE) {<NEW_LINE>decomposeCheckAggregation(validatedNodes);<NEW_LINE>return buildNoPlan(validatedNodes, args);<NEW_LINE>}<NEW_LINE>boolean performConditionPlanning = hasLevelOrHint(FilterSpecCompilerIndexPlannerHint.CONDITIONS, args.statementRawInfo, args.compileTimeServices);<NEW_LINE>FilterSpecParaForgeMap filterParamExprMap = new FilterSpecParaForgeMap();<NEW_LINE>// Make filter parameter for each expression node, if it can be optimized.<NEW_LINE>// Optionally receive a top-level control condition that negates<NEW_LINE>ExprNode topLevelNegation = decomposePopulateConsolidate(filterParamExprMap, performConditionPlanning, validatedNodes, args);<NEW_LINE>// Use all filter parameter and unassigned expressions<NEW_LINE>int countUnassigned = filterParamExprMap.countUnassignedExpressions();<NEW_LINE>// we are done if there are no remaining nodes<NEW_LINE>if (countUnassigned == 0) {<NEW_LINE>return makePlanFromTriplets(filterParamExprMap.getTriplets(), topLevelNegation, args);<NEW_LINE>}<NEW_LINE>// determine max-width<NEW_LINE>int filterServiceMaxFilterWidth = args.compileTimeServices.getConfiguration().getCompiler()<MASK><NEW_LINE>Hint hint = HintEnum.MAX_FILTER_WIDTH.getHint(args.statementRawInfo.getAnnotations());<NEW_LINE>if (hint != null) {<NEW_LINE>String hintValue = HintEnum.MAX_FILTER_WIDTH.getHintAssignedValue(hint);<NEW_LINE>filterServiceMaxFilterWidth = Integer.parseInt(hintValue);<NEW_LINE>}<NEW_LINE>FilterSpecPlanForge plan = null;<NEW_LINE>if (filterServiceMaxFilterWidth > 0) {<NEW_LINE>if (performConditionPlanning) {<NEW_LINE>plan = planRemainingNodesWithConditions(filterParamExprMap, args, filterServiceMaxFilterWidth, topLevelNegation);<NEW_LINE>} else {<NEW_LINE>plan = planRemainingNodesBasic(filterParamExprMap, args, filterServiceMaxFilterWidth);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (plan != null) {<NEW_LINE>return plan;<NEW_LINE>}<NEW_LINE>// handle no-plan<NEW_LINE>List<FilterSpecPlanPathTripletForge> triplets = new ArrayList<>(filterParamExprMap.getTriplets());<NEW_LINE>List<ExprNode> unassignedExpressions = filterParamExprMap.getUnassignedExpressions();<NEW_LINE>FilterSpecPlanPathTripletForge triplet = makeRemainingNode(unassignedExpressions, args);<NEW_LINE>triplets.add(triplet);<NEW_LINE>return makePlanFromTriplets(triplets, topLevelNegation, args);<NEW_LINE>} | .getExecution().getFilterServiceMaxFilterWidth(); |
1,709,850 | public void start() throws Exception {<NEW_LINE>EventBus eventBus = getVertx().eventBus();<NEW_LINE>// Register codec for custom message<NEW_LINE>eventBus.registerDefaultCodec(CustomMessage.class, new CustomMessageCodec());<NEW_LINE>// Custom message<NEW_LINE>CustomMessage clusterWideMessage = new CustomMessage(200, "a00000001", "Message sent from publisher!");<NEW_LINE>CustomMessage localMessage = new CustomMessage(200, "a0000001", "Local message!");<NEW_LINE>// Send a message to [cluster receiver] every second<NEW_LINE>getVertx().setPeriodic(1000, _id -> {<NEW_LINE>eventBus.request("cluster-message-receiver", clusterWideMessage, reply -> {<NEW_LINE>if (reply.succeeded()) {<NEW_LINE>CustomMessage replyMessage = (CustomMessage) reply.result().body();<NEW_LINE>System.out.println("Received reply: " + replyMessage.getSummary());<NEW_LINE>} else {<NEW_LINE>System.out.println("No reply from cluster receiver");<NEW_LINE>}<NEW_LINE>});<NEW_LINE>});<NEW_LINE>// Deploy local receiver<NEW_LINE>getVertx().deployVerticle(LocalReceiver.class.getName(), deployResult -> {<NEW_LINE>// Deploy succeed<NEW_LINE>if (deployResult.succeeded()) {<NEW_LINE>// Send a message to [local receiver] every 2 second<NEW_LINE>getVertx().setPeriodic(2000, _id -> {<NEW_LINE>eventBus.request("local-message-receiver", localMessage, reply -> {<NEW_LINE>if (reply.succeeded()) {<NEW_LINE>CustomMessage replyMessage = (CustomMessage) reply.result().body();<NEW_LINE>System.out.println("Received local reply: " + replyMessage.getSummary());<NEW_LINE>} else {<NEW_LINE>System.out.println("No reply from local receiver");<NEW_LINE>}<NEW_LINE>});<NEW_LINE>});<NEW_LINE>// Deploy failed<NEW_LINE>} else {<NEW_LINE>deployResult<MASK><NEW_LINE>}<NEW_LINE>});<NEW_LINE>} | .cause().printStackTrace(); |
298,893 | public boolean rejectPresenter(MvpPresenter<?> presenter, String delegateTag) {<NEW_LINE>Set<MvpPresenter> <MASK><NEW_LINE>if (presenters != null) {<NEW_LINE>presenters.remove(presenter);<NEW_LINE>}<NEW_LINE>if (presenters == null || presenters.isEmpty()) {<NEW_LINE>mTags.remove(delegateTag);<NEW_LINE>}<NEW_LINE>Set<String> delegateTags = mConnections.get(presenter);<NEW_LINE>if (delegateTags == null) {<NEW_LINE>mConnections.remove(presenter);<NEW_LINE>return true;<NEW_LINE>}<NEW_LINE>Iterator<String> tagsIterator = delegateTags.iterator();<NEW_LINE>while (tagsIterator.hasNext()) {<NEW_LINE>String tag = tagsIterator.next();<NEW_LINE>if (tag.startsWith(delegateTag)) {<NEW_LINE>tagsIterator.remove();<NEW_LINE>}<NEW_LINE>}<NEW_LINE>boolean noTags = delegateTags.isEmpty();<NEW_LINE>if (noTags) {<NEW_LINE>mConnections.remove(presenter);<NEW_LINE>}<NEW_LINE>return noTags;<NEW_LINE>} | presenters = mTags.get(delegateTag); |
354,351 | private Mono<Response<Void>> deleteWithResponseAsync(String resourceGroupName, String namespaceName, String alias, Context context) {<NEW_LINE>if (this.client.getEndpoint() == null) {<NEW_LINE>return Mono.error(new IllegalArgumentException("Parameter this.client.getEndpoint() 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 (namespaceName == null) {<NEW_LINE>return Mono.error(new IllegalArgumentException("Parameter namespaceName is required and cannot be null."));<NEW_LINE>}<NEW_LINE>if (alias == null) {<NEW_LINE>return Mono.error(new IllegalArgumentException("Parameter alias is required and cannot be null."));<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>final String apiVersion = "2017-04-01";<NEW_LINE>final String accept = "application/json";<NEW_LINE>context = <MASK><NEW_LINE>return service.delete(this.client.getEndpoint(), resourceGroupName, namespaceName, alias, apiVersion, this.client.getSubscriptionId(), accept, context);<NEW_LINE>} | this.client.mergeContext(context); |
519,096 | final ListMonitoringSchedulesResult executeListMonitoringSchedules(ListMonitoringSchedulesRequest listMonitoringSchedulesRequest) {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(listMonitoringSchedulesRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE>awsRequestMetrics.startEvent(Field.ClientExecuteTime);<NEW_LINE>Request<ListMonitoringSchedulesRequest> request = null;<NEW_LINE>Response<ListMonitoringSchedulesResult> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new ListMonitoringSchedulesRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(listMonitoringSchedulesRequest));<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(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SERVICE_ID, "SageMaker");<NEW_LINE>request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "ListMonitoringSchedules");<NEW_LINE>request.addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig);<NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.RequestMarshallTime);<NEW_LINE>}<NEW_LINE>HttpResponseHandler<AmazonWebServiceResponse<ListMonitoringSchedulesResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new ListMonitoringSchedulesResultJsonUnmarshaller());<NEW_LINE>response = <MASK><NEW_LINE>return response.getAwsResponse();<NEW_LINE>} finally {<NEW_LINE>endClientExecution(awsRequestMetrics, request, response);<NEW_LINE>}<NEW_LINE>} | invoke(request, responseHandler, executionContext); |
1,825,265 | // check if all these names are not existing, remove invalid events from the list<NEW_LINE>public void validateChildrenToCreate(@Nonnull List<? extends VFileCreateEvent> childrenToCreate) {<NEW_LINE>if (childrenToCreate.size() <= 1) {<NEW_LINE>for (int i = childrenToCreate.size() - 1; i >= 0; i--) {<NEW_LINE>VFileCreateEvent event = childrenToCreate.get(i);<NEW_LINE>if (!event.isValid()) {<NEW_LINE>childrenToCreate.remove(i);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>boolean caseSensitive = getFileSystem().isCaseSensitive();<NEW_LINE>CharSequenceHashingStrategy strategy = caseSensitive ? CharSequenceHashingStrategy.CASE_SENSITIVE : CharSequenceHashingStrategy.CASE_INSENSITIVE;<NEW_LINE>Set<CharSequence> existingNames = Sets.newHashSet(myData.myChildrenIds.length, strategy);<NEW_LINE>for (int id : myData.myChildrenIds) {<NEW_LINE>existingNames.add(mySegment.vfsData.getNameByFileId(id));<NEW_LINE>}<NEW_LINE>int id = getId();<NEW_LINE>synchronized (myData) {<NEW_LINE>FSRecords.NameId[] persistentIds = FSRecords.listAll(id);<NEW_LINE>for (FSRecords.NameId nameId : persistentIds) {<NEW_LINE>existingNames.add(nameId.name);<NEW_LINE>}<NEW_LINE>validateAgainst(childrenToCreate, existingNames);<NEW_LINE>if (!childrenToCreate.isEmpty() && !allChildrenLoaded()) {<NEW_LINE>// findChild asks delegate FS when failed to locate child, and so should we<NEW_LINE><MASK><NEW_LINE>String[] names = getFileSystem().list(this);<NEW_LINE>existingNames.addAll(Arrays.asList(names));<NEW_LINE>if (beforeSize != existingNames.size()) {<NEW_LINE>validateAgainst(childrenToCreate, existingNames);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | int beforeSize = existingNames.size(); |
149,023 | private CompletableFuture<List<SetMonitoringModeResult>> executeAsync(UInteger operationLimit) {<NEW_LINE>List<Map.Entry<OpcUaMonitoredItem, MonitoringMode>> entries = new ArrayList<>(monitoringModesByItem.entrySet());<NEW_LINE>CompletableFuture<List<SetMonitoringModeResult>> resultsFuture = GroupMapCollate.groupMapCollate(entries, Map.Entry::getValue, monitoringMode -> itemsAndModes -> {<NEW_LINE>List<CompletableFuture<List<SetMonitoringModeResult>>> partitionFutures = Lists.partition(itemsAndModes, operationLimit.intValue()).stream().map(this::setMonitoringModeAsync).collect(Collectors.toList());<NEW_LINE>return FutureUtils.flatSequence(partitionFutures);<NEW_LINE>});<NEW_LINE>return resultsFuture.thenCompose(results -> {<NEW_LINE>List<OpcUaMonitoredItem> items = new ArrayList<>(monitoringModesByItem.keySet());<NEW_LINE>assert items.size<MASK><NEW_LINE>for (int i = 0; i < items.size(); i++) {<NEW_LINE>OpcUaMonitoredItem item = items.get(i);<NEW_LINE>SetMonitoringModeResult result = results.get(i);<NEW_LINE>List<CompletableFuture<SetMonitoringModeResult>> futures;<NEW_LINE>synchronized (futuresByItem) {<NEW_LINE>futures = new ArrayList<>(futuresByItem.get(item));<NEW_LINE>}<NEW_LINE>futures.forEach(f -> f.complete(result));<NEW_LINE>}<NEW_LINE>return FutureUtils.sequence(resultFutures);<NEW_LINE>});<NEW_LINE>} | () == results.size(); |
22,561 | public void reduce(Text key, Iterator<Text> values, OutputCollector<Text, Text> output, Reporter reporter) throws IOException {<NEW_LINE>String field = key.toString();<NEW_LINE>reporter.setStatus("starting " + field + " ::host = " + hostName);<NEW_LINE>// concatenate strings<NEW_LINE>if (field.startsWith("s:") || field.startsWith("g:")) {<NEW_LINE>String sSum = "";<NEW_LINE>while (values.hasNext()) sSum += values.next().toString() + ";";<NEW_LINE>output.collect(key, new Text(sSum));<NEW_LINE>reporter.setStatus("finished " + field + " ::host = " + hostName);<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>// sum long values<NEW_LINE>if (field.startsWith("f:")) {<NEW_LINE>float fSum = 0;<NEW_LINE>while (values.hasNext()) fSum += Float.parseFloat(values.next().toString());<NEW_LINE>output.collect(key, new Text(String.valueOf(fSum)));<NEW_LINE>reporter.setStatus("finished " + field + " ::host = " + hostName);<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>// sum long values<NEW_LINE>if (field.startsWith("l:")) {<NEW_LINE>long lSum = 0;<NEW_LINE>while (values.hasNext()) {<NEW_LINE>lSum += Long.parseLong(values.<MASK><NEW_LINE>}<NEW_LINE>output.collect(key, new Text(String.valueOf(lSum)));<NEW_LINE>}<NEW_LINE>reporter.setStatus("finished " + field + " ::host = " + hostName);<NEW_LINE>} | next().toString()); |
1,056,200 | public void populateEntity(List<String> attrList) throws WIMException {<NEW_LINE>boolean uniqueIdPropSet = false;<NEW_LINE>setIdentifierProperties();<NEW_LINE>// Loop through the attributes to try to set each.<NEW_LINE>for (int i = 0; i < attrList.size(); i++) {<NEW_LINE>String attrName = attrList.get(i);<NEW_LINE>try {<NEW_LINE>if (attrName.equals(displayNameProp)) {<NEW_LINE>getDisplayName(true);<NEW_LINE>} else if (attrName.equals(rdnProp)) {<NEW_LINE>entity.set(rdnProp, entity.getIdentifier<MASK><NEW_LINE>} else if (attrName.equals(SchemaConstants.PROP_PRINCIPAL_NAME) || attrName.equals(SchemaConstantsInternal.PROP_DISPLAY_BRIDGE_PRINCIPAL_NAME)) {<NEW_LINE>if ((attrMap.containsKey(LOCAL_DOMAIN_REGISTRY_PROP) && (attrMap.get(LOCAL_DOMAIN_REGISTRY_PROP).toString().equalsIgnoreCase("local") || attrMap.get(LOCAL_DOMAIN_REGISTRY_PROP).toString().equalsIgnoreCase("domain"))) || attrMap.containsKey(SECURITY_NAME_RDN_PROP)) {<NEW_LINE>entity.set(SchemaConstants.PROP_PRINCIPAL_NAME, urBridge.getUserSecurityName(getUniqueId(true)));<NEW_LINE>} else {<NEW_LINE>entity.set(SchemaConstants.PROP_PRINCIPAL_NAME, entity.getIdentifier().get(securityNameProp));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} catch (Exception e) {<NEW_LINE>throw new WIMApplicationException(e);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (entity.getIdentifier().isSet(uniqueIdProp)) {<NEW_LINE>entity.getIdentifier().set(SchemaConstants.PROP_EXTERNAL_ID, entity.getIdentifier().get(uniqueIdProp));<NEW_LINE>}<NEW_LINE>if (!uniqueIdPropSet) {<NEW_LINE>entity.getIdentifier().unset(uniqueIdProp);<NEW_LINE>}<NEW_LINE>} | ().get(securityNameProp)); |
832,714 | public Object methodsAnnotatedWithHystrixCommand(final ProceedingJoinPoint joinPoint) throws Throwable {<NEW_LINE>Method method = getMethodFromTarget(joinPoint);<NEW_LINE>Validate.notNull(method, "failed to get method from joinPoint: %s", joinPoint);<NEW_LINE>if (method.isAnnotationPresent(HystrixCommand.class) && method.isAnnotationPresent(HystrixCollapser.class)) {<NEW_LINE>throw new IllegalStateException("method cannot be annotated with HystrixCommand and HystrixCollapser " + "annotations at the same time");<NEW_LINE>}<NEW_LINE>MetaHolderFactory metaHolderFactory = META_HOLDER_FACTORY_MAP.get<MASK><NEW_LINE>MetaHolder metaHolder = metaHolderFactory.create(joinPoint);<NEW_LINE>HystrixInvokable invokable = HystrixCommandFactory.getInstance().create(metaHolder);<NEW_LINE>ExecutionType executionType = metaHolder.isCollapserAnnotationPresent() ? metaHolder.getCollapserExecutionType() : metaHolder.getExecutionType();<NEW_LINE>Object result;<NEW_LINE>try {<NEW_LINE>if (!metaHolder.isObservable()) {<NEW_LINE>result = CommandExecutor.execute(invokable, executionType, metaHolder);<NEW_LINE>} else {<NEW_LINE>result = executeObservable(invokable, executionType, metaHolder);<NEW_LINE>}<NEW_LINE>} catch (HystrixBadRequestException e) {<NEW_LINE>throw e.getCause() != null ? e.getCause() : e;<NEW_LINE>} catch (HystrixRuntimeException e) {<NEW_LINE>throw hystrixRuntimeExceptionToThrowable(metaHolder, e);<NEW_LINE>}<NEW_LINE>return result;<NEW_LINE>} | (HystrixPointcutType.of(method)); |
206,725 | boolean ForEachFile(String root_path, ForEachFileCallback f) {<NEW_LINE>CHECK(zip_handle_ != null);<NEW_LINE>String root_path_full = root_path;<NEW_LINE>// if (root_path_full.back() != '/') {<NEW_LINE>if (!root_path_full.endsWith("/")) {<NEW_LINE>root_path_full += '/';<NEW_LINE>}<NEW_LINE>String prefix = root_path_full;<NEW_LINE>Enumeration<? extends ZipEntry> entries = zip_handle_.zipFile.entries();<NEW_LINE>// if (StartIteration(zip_handle_.get(), &cookie, &prefix, null) != 0) {<NEW_LINE>// return false;<NEW_LINE>// }<NEW_LINE>if (!entries.hasMoreElements()) {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>// String name;<NEW_LINE>// ZipEntry entry;<NEW_LINE>// We need to hold back directories because many paths will contain them and we want to only<NEW_LINE>// surface one.<NEW_LINE>final Set<String> dirs = new HashSet<>();<NEW_LINE>// int32_t result;<NEW_LINE>// while ((result = Next(cookie, &entry, &name)) == 0) {<NEW_LINE>while (entries.hasMoreElements()) {<NEW_LINE><MASK><NEW_LINE>if (!zipEntry.getName().startsWith(prefix)) {<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>// StringPiece full_file_path(reinterpret_cast<const char*>(name.name), name.name_length);<NEW_LINE>String full_file_path = zipEntry.getName();<NEW_LINE>// StringPiece leaf_file_path = full_file_path.substr(root_path_full.size());<NEW_LINE>String leaf_file_path = full_file_path.substring(root_path_full.length());<NEW_LINE>if (!leaf_file_path.isEmpty()) {<NEW_LINE>// auto iter = stdfind(leaf_file_path.begin(), leaf_file_path.end(), '/');<NEW_LINE>// if (iter != leaf_file_path.end()) {<NEW_LINE>// stdstring dir =<NEW_LINE>// leaf_file_path.substr(0, stddistance(leaf_file_path.begin(), iter)).to_string();<NEW_LINE>// dirs.insert(stdmove(dir));<NEW_LINE>if (zipEntry.isDirectory()) {<NEW_LINE>dirs.add(leaf_file_path.substring(0, leaf_file_path.indexOf("/")));<NEW_LINE>} else {<NEW_LINE>f.callback(leaf_file_path, kFileTypeRegular);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// EndIteration(cookie);<NEW_LINE>// Now present the unique directories.<NEW_LINE>for (final String dir : dirs) {<NEW_LINE>f.callback(dir, kFileTypeDirectory);<NEW_LINE>}<NEW_LINE>// -1 is end of iteration, anything else is an error.<NEW_LINE>// return result == -1;<NEW_LINE>return true;<NEW_LINE>} | ZipEntry zipEntry = entries.nextElement(); |
1,323,707 | public void onClick(View v) {<NEW_LINE>new ColorsDialog((FragmentActivity) controller.getActivity(), (Boolean) t1Img.getTag(), (Integer) t3Text.getTag(), (Integer) t2BG.getTag(), true, true, new ColorsDialogResult() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void onChooseColor(int colorText, int colorBg) {<NEW_LINE>t1Img.setTextColor(colorText);<NEW_LINE>t1Img.setBackgroundColor(colorBg);<NEW_LINE>t2BG.setText(TxtUtils.underline(MagicHelper.colorToString(colorBg)));<NEW_LINE>t3Text.setText(TxtUtils.underline(MagicHelper.colorToString(colorText)));<NEW_LINE>t2BG.setTag(colorBg);<NEW_LINE>t3Text.setTag(colorText);<NEW_LINE>String line = name + "," + MagicHelper.colorToString(colorBg) + "," + MagicHelper.colorToString(colorText<MASK><NEW_LINE>child.setTag(line);<NEW_LINE>}<NEW_LINE>});<NEW_LINE>} | ) + "," + split[3]; |
948,047 | public Repo<Manager> call(long tid, Manager manager) throws Exception {<NEW_LINE>String fmtTid = FateTxId.formatTid(tid);<NEW_LINE>log.debug(" {} sourceDir {}", fmtTid, sourceDir);<NEW_LINE>Utils.getReadLock(manager, tableId, tid).lock();<NEW_LINE>// check that the error directory exists and is empty<NEW_LINE>VolumeManager fs = manager.getVolumeManager();<NEW_LINE>Path errorPath = new Path(errorDir);<NEW_LINE>FileStatus errorStatus = null;<NEW_LINE>try {<NEW_LINE>errorStatus = fs.getFileStatus(errorPath);<NEW_LINE>} catch (FileNotFoundException ex) {<NEW_LINE>// ignored<NEW_LINE>}<NEW_LINE>if (errorStatus == null)<NEW_LINE>throw new AcceptableThriftTableOperationException(tableId.canonical(), null, TableOperation.BULK_IMPORT, TableOperationExceptionType.BULK_BAD_ERROR_DIRECTORY, errorDir + " does not exist");<NEW_LINE>if (!errorStatus.isDirectory())<NEW_LINE>throw new AcceptableThriftTableOperationException(tableId.canonical(), null, TableOperation.BULK_IMPORT, <MASK><NEW_LINE>if (fs.listStatus(errorPath).length != 0)<NEW_LINE>throw new AcceptableThriftTableOperationException(tableId.canonical(), null, TableOperation.BULK_IMPORT, TableOperationExceptionType.BULK_BAD_ERROR_DIRECTORY, errorDir + " is not empty");<NEW_LINE>ZooArbitrator.start(manager.getContext(), Constants.BULK_ARBITRATOR_TYPE, tid);<NEW_LINE>manager.updateBulkImportStatus(sourceDir, BulkImportState.MOVING);<NEW_LINE>// move the files into the directory<NEW_LINE>try {<NEW_LINE>String bulkDir = prepareBulkImport(manager.getContext(), fs, sourceDir, tableId, tid);<NEW_LINE>log.debug(" {} bulkDir {}", tid, bulkDir);<NEW_LINE>return new LoadFiles(tableId, sourceDir, bulkDir, errorDir, setTime);<NEW_LINE>} catch (IOException ex) {<NEW_LINE>log.error("error preparing the bulk import directory", ex);<NEW_LINE>throw new AcceptableThriftTableOperationException(tableId.canonical(), null, TableOperation.BULK_IMPORT, TableOperationExceptionType.BULK_BAD_INPUT_DIRECTORY, sourceDir + ": " + ex);<NEW_LINE>}<NEW_LINE>} | TableOperationExceptionType.BULK_BAD_ERROR_DIRECTORY, errorDir + " is not a directory"); |
956,186 | public JobExecution updateJobExecutionAndInstanceOnEnd(long jobExecutionId, BatchStatus finalBatchStatus, String finalExitStatus, Date endTime) throws NoSuchJobExecutionException {<NEW_LINE>JobExecutionEntity exec = getJobExecution(jobExecutionId);<NEW_LINE>try {<NEW_LINE>verifyStatusTransitionIsValid(exec, finalBatchStatus);<NEW_LINE>} catch (BatchIllegalJobStatusTransitionException e) {<NEW_LINE>throw new PersistenceException(e);<NEW_LINE>}<NEW_LINE>exec.setBatchStatus(finalBatchStatus);<NEW_LINE>exec.<MASK><NEW_LINE>exec.setExitStatus(finalExitStatus);<NEW_LINE>exec.getJobInstance().setExitStatus(finalExitStatus);<NEW_LINE>exec.getJobInstance().setLastUpdatedTime(endTime);<NEW_LINE>// set the state to be the same value as the batchstatus<NEW_LINE>// Note: we only want to do this is if the batchStatus is one of the "done" statuses.<NEW_LINE>if (isFinalBatchStatus(finalBatchStatus)) {<NEW_LINE>InstanceState newInstanceState = InstanceState.valueOf(finalBatchStatus.toString());<NEW_LINE>exec.getJobInstance().setInstanceState(newInstanceState);<NEW_LINE>}<NEW_LINE>exec.setLastUpdatedTime(endTime);<NEW_LINE>exec.setEndTime(endTime);<NEW_LINE>return exec;<NEW_LINE>} | getJobInstance().setBatchStatus(finalBatchStatus); |
1,826,362 | public void marshall(QualificationType qualificationType, ProtocolMarshaller protocolMarshaller) {<NEW_LINE>if (qualificationType == null) {<NEW_LINE>throw new SdkClientException("Invalid argument passed to marshall(...)");<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>protocolMarshaller.marshall(qualificationType.getQualificationTypeId(), QUALIFICATIONTYPEID_BINDING);<NEW_LINE>protocolMarshaller.marshall(qualificationType.getCreationTime(), CREATIONTIME_BINDING);<NEW_LINE>protocolMarshaller.marshall(<MASK><NEW_LINE>protocolMarshaller.marshall(qualificationType.getDescription(), DESCRIPTION_BINDING);<NEW_LINE>protocolMarshaller.marshall(qualificationType.getKeywords(), KEYWORDS_BINDING);<NEW_LINE>protocolMarshaller.marshall(qualificationType.getQualificationTypeStatus(), QUALIFICATIONTYPESTATUS_BINDING);<NEW_LINE>protocolMarshaller.marshall(qualificationType.getTest(), TEST_BINDING);<NEW_LINE>protocolMarshaller.marshall(qualificationType.getTestDurationInSeconds(), TESTDURATIONINSECONDS_BINDING);<NEW_LINE>protocolMarshaller.marshall(qualificationType.getAnswerKey(), ANSWERKEY_BINDING);<NEW_LINE>protocolMarshaller.marshall(qualificationType.getRetryDelayInSeconds(), RETRYDELAYINSECONDS_BINDING);<NEW_LINE>protocolMarshaller.marshall(qualificationType.getIsRequestable(), ISREQUESTABLE_BINDING);<NEW_LINE>protocolMarshaller.marshall(qualificationType.getAutoGranted(), AUTOGRANTED_BINDING);<NEW_LINE>protocolMarshaller.marshall(qualificationType.getAutoGrantedValue(), AUTOGRANTEDVALUE_BINDING);<NEW_LINE>} catch (Exception e) {<NEW_LINE>throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);<NEW_LINE>}<NEW_LINE>} | qualificationType.getName(), NAME_BINDING); |
240,349 | public static boolean verifSignData(final byte[] signedData) throws CMSException, IOException, OperatorCreationException, CertificateException {<NEW_LINE>ByteArrayInputStream bIn = new ByteArrayInputStream(signedData);<NEW_LINE>ASN1InputStream aIn = new ASN1InputStream(bIn);<NEW_LINE>CMSSignedData s = new CMSSignedData(ContentInfo.getInstance(aIn.readObject()));<NEW_LINE>aIn.close();<NEW_LINE>bIn.close();<NEW_LINE>Store certs = s.getCertificates();<NEW_LINE>SignerInformationStore signers = s.getSignerInfos();<NEW_LINE>Collection<SignerInformation> c = signers.getSigners();<NEW_LINE>SignerInformation signer = c.iterator().next();<NEW_LINE>Collection<X509CertificateHolder> certCollection = certs.getMatches(signer.getSID());<NEW_LINE>Iterator<X509CertificateHolder<MASK><NEW_LINE>X509CertificateHolder certHolder = certIt.next();<NEW_LINE>boolean verifResult = signer.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certHolder));<NEW_LINE>if (!verifResult) {<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>return true;<NEW_LINE>} | > certIt = certCollection.iterator(); |
1,749,058 | public void cleanup() {<NEW_LINE>for (ThirdpartyBookmarkCollection t : collections) {<NEW_LINE>t.filter(bookmarks);<NEW_LINE>if (t.isEmpty()) {<NEW_LINE>preferences.setProperty(t.getConfiguration(), true);<NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>final NSAlert alert = // default<NEW_LINE>NSAlert.// default<NEW_LINE>alert(// default<NEW_LINE>MessageFormat.format(LocaleFactory.localizedString("Import {0} Bookmarks", "Configuration"), t.getName()), // default<NEW_LINE>MessageFormat.format(LocaleFactory.localizedString("{0} bookmarks found. Do you want to add these to your bookmarks?", "Configuration"), t.size()), // other<NEW_LINE>LocaleFactory.localizedString("Import", "Configuration"), null, LocaleFactory.localizedString("Cancel", "Configuration"));<NEW_LINE>alert.setShowsSuppressionButton(true);<NEW_LINE>alert.suppressionButton().setTitle(LocaleFactory.localizedString("Don't ask again", "Configuration"));<NEW_LINE><MASK><NEW_LINE>// alternate<NEW_LINE>int choice = new AlertSheetReturnCodeMapper().getOption(alert.runModal());<NEW_LINE>if (alert.suppressionButton().state() == NSCell.NSOnState) {<NEW_LINE>// Never show again.<NEW_LINE>preferences.setProperty(t.getConfiguration(), true);<NEW_LINE>}<NEW_LINE>if (choice == SheetCallback.DEFAULT_OPTION) {<NEW_LINE>bookmarks.addAll(t);<NEW_LINE>// Flag as imported<NEW_LINE>preferences.setProperty(t.getConfiguration(), true);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | alert.setAlertStyle(NSAlert.NSInformationalAlertStyle); |
219,477 | protected String runSingleTask(String[] args) throws Exception {<NEW_LINE>// prepare the benchmark.<NEW_LINE>prepare();<NEW_LINE>if (!mBaseParameters.mProfileAgent.isEmpty()) {<NEW_LINE>mBaseParameters.mJavaOpts.add("-javaagent:" + mBaseParameters.mProfileAgent + "=" + BaseParameters.AGENT_OUTPUT_PATH);<NEW_LINE>}<NEW_LINE>AlluxioConfiguration conf = new InstancedConfiguration(ConfigurationUtils.defaults());<NEW_LINE>String className = this.getClass().getCanonicalName();<NEW_LINE>if (mBaseParameters.mCluster) {<NEW_LINE>// run on job service<NEW_LINE>long jobId = JobGrpcClientUtils.run(generateJobConfig(args), 0, conf);<NEW_LINE>JobInfo jobInfo = JobGrpcClientUtils.getJobStatus(jobId, conf, true);<NEW_LINE>return jobInfo.getResult().toString();<NEW_LINE>}<NEW_LINE>// run locally<NEW_LINE>if (mBaseParameters.mInProcess) {<NEW_LINE>// run in process<NEW_LINE>T result = runLocal();<NEW_LINE>if (mBaseParameters.mDistributed) {<NEW_LINE>return result.toJson();<NEW_LINE>}<NEW_LINE>// aggregate the results<NEW_LINE>final String s = result.aggregator().aggregate(Collections.singletonList(result)).toJson();<NEW_LINE>return s;<NEW_LINE>} else {<NEW_LINE>// Spawn a new process<NEW_LINE>List<String> command = new ArrayList<>();<NEW_LINE>command.add(conf.get<MASK><NEW_LINE>command.add("runClass");<NEW_LINE>command.add(className);<NEW_LINE>command.addAll(Arrays.asList(args));<NEW_LINE>command.add(BaseParameters.IN_PROCESS_FLAG);<NEW_LINE>command.addAll(mBaseParameters.mJavaOpts.stream().map(String::trim).collect(Collectors.toList()));<NEW_LINE>LOG.info("running command: " + String.join(" ", command));<NEW_LINE>return ShellUtils.execCommand(command.toArray(new String[0]));<NEW_LINE>}<NEW_LINE>} | (PropertyKey.HOME) + "/bin/alluxio"); |
914,979 | protected PathConfig resolvePathConfig(PathConfig originalConfig, String path) {<NEW_LINE>if (originalConfig.hasPattern()) {<NEW_LINE>ProtectedResource resource = authzClient.protection().resource();<NEW_LINE>// search by an exact match<NEW_LINE>List<ResourceRepresentation> search = resource.findByUri(path);<NEW_LINE>// if exact match not found, try to obtain from current path the parent path.<NEW_LINE>// if path is /resource/1/test and pattern from pathConfig is /resource/{id}/*, parent path is /resource/1<NEW_LINE>// this logic allows to match sub resources of a resource instance (/resource/1) to the parent resource,<NEW_LINE>// so any permission granted to parent also applies to sub resources<NEW_LINE>if (search.isEmpty()) {<NEW_LINE>search = resource.findByUri(buildUriFromTemplate(originalConfig.getPath(), path, true));<NEW_LINE>}<NEW_LINE>if (!search.isEmpty()) {<NEW_LINE>ResourceRepresentation targetResource = search.get(0);<NEW_LINE>PathConfig config = PathConfig.createPathConfigs(targetResource).iterator().next();<NEW_LINE>config.setScopes(originalConfig.getScopes());<NEW_LINE>config.<MASK><NEW_LINE>config.setParentConfig(originalConfig);<NEW_LINE>config.setEnforcementMode(originalConfig.getEnforcementMode());<NEW_LINE>config.setClaimInformationPointConfig(originalConfig.getClaimInformationPointConfig());<NEW_LINE>return config;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return null;<NEW_LINE>} | setMethods(originalConfig.getMethods()); |
1,603,652 | public PutContainerRecipePolicyResult unmarshall(JsonUnmarshallerContext context) throws Exception {<NEW_LINE>PutContainerRecipePolicyResult putContainerRecipePolicyResult = new PutContainerRecipePolicyResult();<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 putContainerRecipePolicyResult;<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("requestId", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>putContainerRecipePolicyResult.setRequestId(context.getUnmarshaller(String.<MASK><NEW_LINE>}<NEW_LINE>if (context.testExpression("containerRecipeArn", targetDepth)) {<NEW_LINE>context.nextToken();<NEW_LINE>putContainerRecipePolicyResult.setContainerRecipeArn(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 putContainerRecipePolicyResult;<NEW_LINE>} | class).unmarshall(context)); |
1,793,820 | public void calculate(final IPricingContext pricingCtx, final IPricingResult result) {<NEW_LINE>if (!applies(pricingCtx, result)) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>final I_M_PriceList_Version priceListVersion = pricingCtx.getM_PriceList_Version();<NEW_LINE>if (priceListVersion == null) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>final I_M_ProductPrice productPrice = ProductPrices.newQuery(priceListVersion).setProductId(pricingCtx.getProductId()).noAttributePricing().onlyValidPrices(true).onlyScalePrices().firstMatching();<NEW_LINE>if (productPrice == null) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>if (Objects.equals(productPrice.getUseScalePrice(), X_M_ProductPrice.USESCALEPRICE_DonTUseScalePrice)) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>final BigDecimal qty = pricingCtx.getQty();<NEW_LINE>final I_M_ProductScalePrice scalePrice = // createNew<NEW_LINE>Services.get(IProductPA.class).// createNew<NEW_LINE>retrieveOrCreateScalePrices(// createNew<NEW_LINE>productPrice.getM_ProductPrice_ID(), // createNew<NEW_LINE>qty, false, ITrx.TRXNAME_None);<NEW_LINE>if (scalePrice == null) {<NEW_LINE>if (Objects.equals(productPrice.getUseScalePrice(), X_M_ProductPrice.USESCALEPRICE_UseScalePriceFallbackToProductPrice)) {<NEW_LINE>return;<NEW_LINE>} else {<NEW_LINE>throw new AdempiereException(MSG_NO_SCALE_PRICE, qty);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>calculateWithScalePrice(pricingCtx, result, scalePrice);<NEW_LINE>result.setTaxCategoryId(TaxCategoryId.ofRepoId<MASK><NEW_LINE>} | (productPrice.getC_TaxCategory_ID())); |
1,292,059 | private List<Object> transformInput(List iLeft, Object iRight, OLuceneFullTextIndex index, MemoryIndex memoryIndex) {<NEW_LINE>Integer collectionIndex = getCollectionIndex(iLeft);<NEW_LINE>if (collectionIndex == -1) {<NEW_LINE>// collection not found;<NEW_LINE>return iLeft;<NEW_LINE>}<NEW_LINE>if (collectionIndex > 1) {<NEW_LINE>throw new UnsupportedOperationException("Index of collection cannot be > 1");<NEW_LINE>}<NEW_LINE>// otherwise the input is [val,[]] or [[],val]<NEW_LINE>Collection collection = (Collection) iLeft.get(collectionIndex);<NEW_LINE>if (iLeft.size() == 1) {<NEW_LINE>return new ArrayList<Object>(collection);<NEW_LINE>}<NEW_LINE>List<Object> transformed = new ArrayList<Object>(collection.size());<NEW_LINE>for (Object o : collection) {<NEW_LINE>List<Object> objects <MASK><NEW_LINE>// [[],val]<NEW_LINE>if (collectionIndex == 0) {<NEW_LINE>objects.add(o);<NEW_LINE>objects.add(iLeft.get(1));<NEW_LINE>// [val,[]]<NEW_LINE>} else {<NEW_LINE>objects.add(iLeft.get(0));<NEW_LINE>objects.add(o);<NEW_LINE>}<NEW_LINE>transformed.add(objects);<NEW_LINE>}<NEW_LINE>return transformed;<NEW_LINE>} | = new ArrayList<Object>(); |
580,894 | public Registration deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {<NEW_LINE>JsonNode node = p.readValueAsTree();<NEW_LINE>Registration.Builder builder = Registration.builder();<NEW_LINE>if (node.has("name")) {<NEW_LINE>builder.name(node.get("name").asText());<NEW_LINE>}<NEW_LINE>if (node.has("url")) {<NEW_LINE>String url = node.get("url").asText();<NEW_LINE>builder.healthUrl(url.replaceFirst("/+$", "") <MASK><NEW_LINE>} else {<NEW_LINE>if (node.has("healthUrl")) {<NEW_LINE>builder.healthUrl(node.get("healthUrl").asText());<NEW_LINE>}<NEW_LINE>if (node.has("managementUrl")) {<NEW_LINE>builder.managementUrl(node.get("managementUrl").asText());<NEW_LINE>}<NEW_LINE>if (node.has("serviceUrl")) {<NEW_LINE>builder.serviceUrl(node.get("serviceUrl").asText());<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (node.has("metadata")) {<NEW_LINE>Iterator<Map.Entry<String, JsonNode>> it = node.get("metadata").fields();<NEW_LINE>while (it.hasNext()) {<NEW_LINE>Map.Entry<String, JsonNode> entry = it.next();<NEW_LINE>builder.metadata(entry.getKey(), entry.getValue().asText());<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return builder.build();<NEW_LINE>} | + "/health").managementUrl(url); |
111,232 | /*<NEW_LINE>@Override<NEW_LINE>public JsonSerializer<?> createContextual(SerializerProvider ctxt, BeanProperty property) throws JsonMappingException {<NEW_LINE>TypeSerializer typeSer = _valueTypeSerializer;<NEW_LINE>if (typeSer != null) {<NEW_LINE>typeSer = typeSer.forProperty(property);<NEW_LINE>}<NEW_LINE>JsonSerializer<?> ser = _valueSerializer;<NEW_LINE>if (ser == null) {<NEW_LINE>// Can only assign serializer statically if the declared type is final:<NEW_LINE>// if not, we don't really know the actual type until we get the instance.<NEW_LINE>// 10-Mar-2010, tatu: Except if static typing is to be used<NEW_LINE>if (ctxt.isEnabled(MapperFeature.USE_STATIC_TYPING) || _valueType.isFinal()) {<NEW_LINE>// 05-Sep-2013, tatu: I _think_ this can be considered a primary property...<NEW_LINE>ser = ctxt.findPrimaryPropertySerializer(_valueType, property);<NEW_LINE>boolean forceTypeInformation = isNaturalTypeWithStdHandling(<MASK><NEW_LINE>return withResolved(property, typeSer, ser, forceTypeInformation);<NEW_LINE>}<NEW_LINE>// [databind#2822]: better hold on to "property", regardless<NEW_LINE>if (property != _property) {<NEW_LINE>return withResolved(property, typeSer, ser, _forceTypeInformation);<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>// 05-Sep-2013, tatu: I _think_ this can be considered a primary property...<NEW_LINE>ser = ctxt.handlePrimaryContextualization(ser, property);<NEW_LINE>return withResolved(property, typeSer, ser, _forceTypeInformation);<NEW_LINE>}<NEW_LINE>return this;<NEW_LINE>} | _valueType.getRawClass(), ser); |
709,893 | public void onReceive(Context context, Intent intent) {<NEW_LINE><MASK><NEW_LINE>if (action == null)<NEW_LINE>return;<NEW_LINE>if (action.equals(LOCAL_ACTION_LOG)) {<NEW_LINE>Message msg = mStatusUpdateHandler.obtainMessage(STATUS_UPDATE);<NEW_LINE>msg.obj = intent.getStringExtra(LOCAL_EXTRA_LOG);<NEW_LINE>msg.getData().putString("status", intent.getStringExtra(EXTRA_STATUS));<NEW_LINE>mStatusUpdateHandler.sendMessage(msg);<NEW_LINE>} else if (action.equals(LOCAL_ACTION_BANDWIDTH)) {<NEW_LINE>long upload = intent.getLongExtra("up", 0);<NEW_LINE>long download = intent.getLongExtra("down", 0);<NEW_LINE>long written = intent.getLongExtra("written", 0);<NEW_LINE>long read = intent.getLongExtra("read", 0);<NEW_LINE>Message msg = mStatusUpdateHandler.obtainMessage(MESSAGE_TRAFFIC_COUNT);<NEW_LINE>msg.getData().putLong("download", download);<NEW_LINE>msg.getData().putLong("upload", upload);<NEW_LINE>msg.getData().putLong("readTotal", read);<NEW_LINE>msg.getData().putLong("writeTotal", written);<NEW_LINE>msg.getData().putString("status", intent.getStringExtra(EXTRA_STATUS));<NEW_LINE>mStatusUpdateHandler.sendMessage(msg);<NEW_LINE>} else if (action.equals(ACTION_STATUS)) {<NEW_LINE>lastStatusIntent = intent;<NEW_LINE>Message msg = mStatusUpdateHandler.obtainMessage(STATUS_UPDATE);<NEW_LINE>msg.getData().putString("status", intent.getStringExtra(EXTRA_STATUS));<NEW_LINE>mStatusUpdateHandler.sendMessage(msg);<NEW_LINE>} else if (action.equals(LOCAL_ACTION_PORTS)) {<NEW_LINE>Message msg = mStatusUpdateHandler.obtainMessage(MESSAGE_PORTS);<NEW_LINE>msg.getData().putInt("socks", intent.getIntExtra(OrbotService.EXTRA_SOCKS_PROXY_PORT, -1));<NEW_LINE>msg.getData().putInt("http", intent.getIntExtra(OrbotService.EXTRA_HTTP_PROXY_PORT, -1));<NEW_LINE>mStatusUpdateHandler.sendMessage(msg);<NEW_LINE>}<NEW_LINE>} | String action = intent.getAction(); |
706,366 | public void main() {<NEW_LINE>RVec4 srcColor = new RVec4("srcColor");<NEW_LINE>srcColor.assign(texture2D(uTexture, vTextureCoord));<NEW_LINE>switch(mMode) {<NEW_LINE>case LIGHTNESS:<NEW_LINE>RFloat least = new RFloat("least");<NEW_LINE>least.assign(min(srcColor.g(), min(srcColor.r(), srcColor.b())));<NEW_LINE>RFloat most = new RFloat("most");<NEW_LINE>most.assign(max(srcColor.g(), max(srcColor.r(), srcColor.b())));<NEW_LINE>RFloat lightness = new RFloat("lightness");<NEW_LINE>lightness.assign("(least + most) / 2.0");<NEW_LINE>GL_FRAG_COLOR.assign(uOpacity.multiply(castVec4("lightness, lightness, lightness, srcColor.a")));<NEW_LINE>break;<NEW_LINE>case LUMA:<NEW_LINE>RFloat luma = new RFloat("luma");<NEW_LINE>luma.assign(0);<NEW_LINE>luma.assignAdd(srcColor.r().multiply(0.2126f));<NEW_LINE>luma.assignAdd(srcColor.g().multiply(0.7152f));<NEW_LINE>luma.assignAdd(srcColor.b().multiply(0.0722f));<NEW_LINE>GL_FRAG_COLOR.assign(uOpacity.multiply(castVec4("luma, luma, luma, srcColor.a")));<NEW_LINE>break;<NEW_LINE>case VALUE:<NEW_LINE>RFloat value = new RFloat("value");<NEW_LINE>value.assign(max(srcColor.g(), max(srcColor.r(), srcColor.b())));<NEW_LINE>GL_FRAG_COLOR.assign(uOpacity.multiply(castVec4("value, value, value, srcColor.a")));<NEW_LINE>break;<NEW_LINE>default:<NEW_LINE>RFloat average = new RFloat("average");<NEW_LINE>average.assign("(srcColor.r + srcColor.g + srcColor.b) / 3.0");<NEW_LINE>GL_FRAG_COLOR.assign(uOpacity.<MASK><NEW_LINE>break;<NEW_LINE>}<NEW_LINE>} | multiply(castVec4("average, average, average, srcColor.a"))); |
1,379,484 | public Object fallback(MethodInvocationContext<Object, Object> context, Throwable exception) {<NEW_LINE>if (exception instanceof NoAvailableServiceException) {<NEW_LINE>NoAvailableServiceException ex = (NoAvailableServiceException) exception;<NEW_LINE>if (logger.isErrorEnabled()) {<NEW_LINE>logger.debug(ex.getMessage(), ex);<NEW_LINE>logger.error("Type [{}] attempting to resolve fallback for unavailable service [{}]", context.getTarget().getClass().getName(), ex.getServiceID());<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>if (logger.isErrorEnabled()) {<NEW_LINE>logger.error("Type [{}] executed with error: {}", context.getTarget().getClass().getName(), exception.getMessage(), exception);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>Optional<? extends MethodExecutionHandle<?, Object>> fallback = findFallbackMethod(context);<NEW_LINE>if (fallback.isPresent()) {<NEW_LINE>MethodExecutionHandle<?, Object> fallbackMethod = fallback.get();<NEW_LINE>if (logger.isDebugEnabled()) {<NEW_LINE>logger.debug("Type [{}] resolved fallback: {}", context.getTarget().getClass().getName(), fallbackMethod);<NEW_LINE>}<NEW_LINE>return fallbackMethod.<MASK><NEW_LINE>} else {<NEW_LINE>if (exception instanceof RuntimeException) {<NEW_LINE>throw (RuntimeException) exception;<NEW_LINE>} else {<NEW_LINE>throw new CompletionException(exception);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | invoke(context.getParameterValues()); |
1,469,602 | public Tile findClosestOre(float xp, float yp, Item item) {<NEW_LINE>if (ores[item.id] != null) {<NEW_LINE>float minDst = 0f;<NEW_LINE>Tile closest = null;<NEW_LINE>for (int qx = 0; qx < quadWidth; qx++) {<NEW_LINE>for (int qy = 0; qy < quadHeight; qy++) {<NEW_LINE>var arr = ores[item.id][qx][qy];<NEW_LINE>if (arr != null && arr.size > 0) {<NEW_LINE>Tile tile = world.<MASK><NEW_LINE>float dst = Mathf.dst2(xp, yp, tile.worldx(), tile.worldy());<NEW_LINE>if (closest == null || dst < minDst) {<NEW_LINE>closest = tile;<NEW_LINE>minDst = dst;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return closest;<NEW_LINE>}<NEW_LINE>return null;<NEW_LINE>} | tile(arr.first()); |
843,977 | private List<InsertVO> takeInsertVO(Class<?> triggeredVO) {<NEW_LINE>List<String> voNames = insertVOTriggerClassNames.get(triggeredVO);<NEW_LINE>TypedQuery<InsertVO> query = null;<NEW_LINE>if (voNames.size() == 1) {<NEW_LINE>String sql = "select i from InsertVO i where i.voName = :voName";<NEW_LINE>query = dbf.getEntityManager().createQuery(sql, InsertVO.class);<NEW_LINE>query.setParameter("voName", triggeredVO.getSimpleName());<NEW_LINE>} else {<NEW_LINE>String sql = "select i from InsertVO i where i.voName in (:voName)";<NEW_LINE>query = dbf.getEntityManager().createQuery(sql, InsertVO.class);<NEW_LINE>query.setParameter("voName", voNames);<NEW_LINE>}<NEW_LINE>query.setLockMode(LockModeType.PESSIMISTIC_WRITE);<NEW_LINE>List<InsertVO> ret = query.getResultList();<NEW_LINE>if (!ret.isEmpty()) {<NEW_LINE>List<Long> ids = CollectionUtils.transformToList(ret, new Function<Long, InsertVO>() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public Long call(InsertVO arg) {<NEW_LINE>return arg.getId();<NEW_LINE>}<NEW_LINE>});<NEW_LINE>String usql = "delete from InsertVO i where i.id in :id";<NEW_LINE>Query uquery = dbf.<MASK><NEW_LINE>uquery.setParameter("id", ids);<NEW_LINE>uquery.executeUpdate();<NEW_LINE>}<NEW_LINE>return ret;<NEW_LINE>} | getEntityManager().createQuery(usql); |
1,473,444 | private static ITranslatableString extractDescription(final Field field) {<NEW_LINE>final ViewColumn viewColumnAnn = <MASK><NEW_LINE>final String captionKey = !Check.isEmpty(viewColumnAnn.captionKey()) ? viewColumnAnn.captionKey() : extractFieldName(field);<NEW_LINE>final TranslationSource captionTranslationSource = viewColumnAnn.captionTranslationSource();<NEW_LINE>if (captionTranslationSource == TranslationSource.DEFAULT) {<NEW_LINE>final IMsgBL msgBL = Services.get(IMsgBL.class);<NEW_LINE>return msgBL.translatable(captionKey + "/Description");<NEW_LINE>} else if (captionTranslationSource == TranslationSource.ATTRIBUTE_NAME) {<NEW_LINE>final IAttributeDAO attributesRepo = Services.get(IAttributeDAO.class);<NEW_LINE>return attributesRepo.getAttributeDescriptionByValue(captionKey).orElseGet(() -> TranslatableStrings.anyLanguage(captionKey));<NEW_LINE>} else {<NEW_LINE>logger.warn("Unknown TranslationSource={} for {}. Returning the captionKey={}", captionTranslationSource, field, captionKey);<NEW_LINE>return TranslatableStrings.anyLanguage(captionKey);<NEW_LINE>}<NEW_LINE>} | field.getAnnotation(ViewColumn.class); |
557,622 | public Dialog onCreateDialog(Bundle savedInstanceState) {<NEW_LINE>mTargetFile = getArguments().getParcelable(ARG_TARGET_FILE);<NEW_LINE>// Inflate the layout for the dialog<NEW_LINE>LayoutInflater inflater = getActivity().getLayoutInflater();<NEW_LINE>View v = inflater.inflate(R.layout.edit_box_dialog, null);<NEW_LINE>// Allow or disallow touches with other visible windows<NEW_LINE>v.setFilterTouchesWhenObscured(PreferenceUtils.shouldDisallowTouchesWithOtherVisibleWindows(getContext()));<NEW_LINE>// Setup layout<NEW_LINE>String currentName = mTargetFile.getFileName();<NEW_LINE>EditText inputText = v.<MASK><NEW_LINE>inputText.setText(currentName);<NEW_LINE>int selectionStart = 0;<NEW_LINE>int extensionStart = mTargetFile.isFolder() ? -1 : currentName.lastIndexOf(".");<NEW_LINE>int selectionEnd = (extensionStart >= 0) ? extensionStart : currentName.length();<NEW_LINE>if (selectionStart >= 0 && selectionEnd >= 0) {<NEW_LINE>inputText.setSelection(Math.min(selectionStart, selectionEnd), Math.max(selectionStart, selectionEnd));<NEW_LINE>}<NEW_LINE>inputText.requestFocus();<NEW_LINE>// Build the dialog<NEW_LINE>AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());<NEW_LINE>builder.setView(v).setPositiveButton(android.R.string.ok, this).setNegativeButton(android.R.string.cancel, this).setTitle(R.string.rename_dialog_title);<NEW_LINE>Dialog d = builder.create();<NEW_LINE>d.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_VISIBLE);<NEW_LINE>return d;<NEW_LINE>} | findViewById(R.id.user_input); |
1,606,982 | private boolean compareNumber(Number valueObj, String value1, String value2) {<NEW_LINE>BigDecimal valueObjB = null;<NEW_LINE>BigDecimal value1B = null;<NEW_LINE>BigDecimal value2B = null;<NEW_LINE>try {<NEW_LINE>if (valueObj instanceof BigDecimal)<NEW_LINE>valueObjB = (BigDecimal) valueObj;<NEW_LINE>else if (valueObj instanceof Integer)<NEW_LINE>valueObjB = new BigDecimal(((Integer) valueObj).intValue());<NEW_LINE>else<NEW_LINE>valueObjB = new BigDecimal(String.valueOf(valueObj));<NEW_LINE>} catch (Exception e) {<NEW_LINE>log.fine("compareNumber - valueObj=" + valueObj + " - " + e.toString());<NEW_LINE>return compareString(valueObj, value1, value2);<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>value1B = new BigDecimal(value1);<NEW_LINE>} catch (Exception e) {<NEW_LINE>log.fine("compareNumber - value1=" + value1 + " - " + e.toString());<NEW_LINE>return compareString(valueObj, value1, value2);<NEW_LINE>}<NEW_LINE>String op = getOperation();<NEW_LINE>if (OPERATION_Eq.equals(op))<NEW_LINE>return valueObjB.compareTo(value1B) == 0;<NEW_LINE>else if (OPERATION_Gt.equals(op))<NEW_LINE>return valueObjB.compareTo(value1B) > 0;<NEW_LINE>else if (OPERATION_GtEq.equals(op))<NEW_LINE>return valueObjB.compareTo(value1B) >= 0;<NEW_LINE>else if (OPERATION_Le.equals(op))<NEW_LINE>return valueObjB.compareTo(value1B) < 0;<NEW_LINE>else if (OPERATION_LeEq.equals(op))<NEW_LINE>return <MASK><NEW_LINE>else if (OPERATION_Like.equals(op))<NEW_LINE>return valueObjB.compareTo(value1B) == 0;<NEW_LINE>else if (OPERATION_NotEq.equals(op))<NEW_LINE>return valueObjB.compareTo(value1B) != 0;<NEW_LINE>else //<NEW_LINE>if (OPERATION_Sql.equals(op))<NEW_LINE>throw new IllegalArgumentException("SQL not Implemented");<NEW_LINE>else //<NEW_LINE>if (OPERATION_X.equals(op)) {<NEW_LINE>if (valueObjB.compareTo(value1B) < 0)<NEW_LINE>return false;<NEW_LINE>// To<NEW_LINE>try {<NEW_LINE>value2B = new BigDecimal(String.valueOf(value2));<NEW_LINE>return valueObjB.compareTo(value2B) <= 0;<NEW_LINE>} catch (Exception e) {<NEW_LINE>log.fine("compareNumber - value2=" + value2 + " - " + e.toString());<NEW_LINE>return false;<NEW_LINE>}<NEW_LINE>}<NEW_LINE>//<NEW_LINE>throw new IllegalArgumentException("Unknown Operation=" + op);<NEW_LINE>} | valueObjB.compareTo(value1B) <= 0; |
465,280 | private static void addMainValueHashToTextLoader(Step step, TextLoader textLoader) {<NEW_LINE>StepEnum.Type stepType = StepEnum.Type.of(step.getStepType());<NEW_LINE>String textTypeName = stepType.getAssociatedMainTextTypeName();<NEW_LINE>TextTypeEnum textTypeEnum = TextTypeEnum.of(textTypeName);<NEW_LINE>switch(stepType) {<NEW_LINE>case METHOD:<NEW_LINE>case METHOD2:<NEW_LINE>textLoader.addTextHash(textTypeEnum, ((MethodStep) step).getHash());<NEW_LINE>break;<NEW_LINE>case SQL:<NEW_LINE>case SQL2:<NEW_LINE>case SQL3:<NEW_LINE>textLoader.addTextHash(textTypeEnum, ((SqlStep) step).getHash());<NEW_LINE>break;<NEW_LINE>case APICALL:<NEW_LINE>case APICALL2:<NEW_LINE>textLoader.addTextHash(textTypeEnum, ((ApiCallStep) step).getHash());<NEW_LINE>break;<NEW_LINE>case THREAD_SUBMIT:<NEW_LINE>textLoader.addTextHash(textTypeEnum, ((ThreadSubmitStep) step).getHash());<NEW_LINE>break;<NEW_LINE>case HASHED_MESSAGE:<NEW_LINE>textLoader.addTextHash(textTypeEnum, ((HashedMessageStep) step).getHash());<NEW_LINE>break;<NEW_LINE>case PARAMETERIZED_MESSAGE:<NEW_LINE>textLoader.addTextHash(textTypeEnum, ((ParameterizedMessageStep<MASK><NEW_LINE>break;<NEW_LINE>case DISPATCH:<NEW_LINE>textLoader.addTextHash(textTypeEnum, ((DispatchStep) step).getHash());<NEW_LINE>break;<NEW_LINE>case THREAD_CALL_POSSIBLE:<NEW_LINE>textLoader.addTextHash(textTypeEnum, ((ThreadCallPossibleStep) step).getHash());<NEW_LINE>break;<NEW_LINE>case SPAN:<NEW_LINE>case SPANCALL:<NEW_LINE>textLoader.addTextHash(textTypeEnum, ((SCommonSpanStep) step).getHash());<NEW_LINE>break;<NEW_LINE>case DUMP:<NEW_LINE>break;<NEW_LINE>case MESSAGE:<NEW_LINE>case SOCKET:<NEW_LINE>default:<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>} | ) step).getHash()); |
152,332 | public void notifyBlacklistedConnection(ConnectionDescriptor conn) {<NEW_LINE>int uid = conn.uid;<NEW_LINE>AppDescriptor app = appsResolver.<MASK><NEW_LINE>assert app != null;<NEW_LINE>FilterDescriptor filter = new FilterDescriptor();<NEW_LINE>filter.onlyBlacklisted = true;<NEW_LINE>Intent intent = new Intent(this, ConnectionsActivity.class).putExtra(ConnectionsFragment.FILTER_EXTRA, filter).putExtra(ConnectionsFragment.QUERY_EXTRA, app.getPackageName());<NEW_LINE>PendingIntent pi = PendingIntent.getActivity(this, 0, intent, Utils.getIntentFlags(PendingIntent.FLAG_UPDATE_CURRENT));<NEW_LINE>String rule_label;<NEW_LINE>if (conn.isBlacklistedHost())<NEW_LINE>rule_label = MatchList.getRuleLabel(this, MatchList.RuleType.HOST, conn.info);<NEW_LINE>else<NEW_LINE>rule_label = MatchList.getRuleLabel(this, MatchList.RuleType.IP, conn.dst_ip);<NEW_LINE>mBlacklistedBuilder.setContentIntent(pi).setWhen(System.currentTimeMillis()).setContentTitle(String.format(getResources().getString(R.string.malicious_connection_app), app.getName())).setContentText(rule_label);<NEW_LINE>Notification notification = mBlacklistedBuilder.build();<NEW_LINE>// Use the UID as the notification ID to group alerts from the same app<NEW_LINE>mHandler.post(() -> NotificationManagerCompat.from(this).notify(uid, notification));<NEW_LINE>} | get(conn.uid, 0); |
1,157,884 | public void run() {<NEW_LINE>log.info("Running {}", getName());<NEW_LINE>XClusterConfig xClusterConfig = refreshXClusterConfig();<NEW_LINE>Universe targetUniverse = Universe.getOrBadRequest(xClusterConfig.targetUniverseUUID);<NEW_LINE>String targetUniverseMasterAddresses = targetUniverse.getMasterAddresses();<NEW_LINE>String targetUniverseCertificate = targetUniverse.getCertificateNodetoNode();<NEW_LINE>YBClient client = ybService.getClient(targetUniverseMasterAddresses, targetUniverseCertificate);<NEW_LINE>try {<NEW_LINE>XClusterConfigStatusType desiredStatus = XClusterConfigStatusType.valueOf(taskParams().editFormData.status);<NEW_LINE>if (desiredStatus == XClusterConfigStatusType.Running) {<NEW_LINE>log.info("Resuming XClusterConfig({})", xClusterConfig.uuid);<NEW_LINE>} else {<NEW_LINE>log.info("Pausing XClusterConfig({})", xClusterConfig.uuid);<NEW_LINE>}<NEW_LINE>SetUniverseReplicationEnabledResponse resp = client.setUniverseReplicationEnabled(xClusterConfig.getReplicationGroupName(), desiredStatus == XClusterConfigStatusType.Running);<NEW_LINE>if (resp.hasError()) {<NEW_LINE>throw new RuntimeException(String.format("Failed to set XClusterConfig(%s) status: %s", xClusterConfig.uuid, resp.errorMessage()));<NEW_LINE>}<NEW_LINE>xClusterConfig.status = desiredStatus;<NEW_LINE>xClusterConfig.update();<NEW_LINE>if (HighAvailabilityConfig.get().isPresent()) {<NEW_LINE>getUniverse(true).incrementVersion();<NEW_LINE>}<NEW_LINE>} catch (Exception e) {<NEW_LINE>log.error("{} hit error : {}", getName(), e.getMessage());<NEW_LINE>throw new RuntimeException(e);<NEW_LINE>} finally {<NEW_LINE><MASK><NEW_LINE>}<NEW_LINE>log.info("Completed {}", getName());<NEW_LINE>} | ybService.closeClient(client, targetUniverseMasterAddresses); |
1,119,594 | protected Page newPage(final HttpServletRequest req, final HttpServletResponse resp, final Session session, final String template) {<NEW_LINE>final Page page = new Page(req, resp, getApplication().getVelocityEngine(), template);<NEW_LINE>page.add("version", jarVersion);<NEW_LINE>page.add("azkaban_name", this.name);<NEW_LINE>page.add("azkaban_label", this.label);<NEW_LINE>page.add("azkaban_color", this.color);<NEW_LINE>page.add("azkaban_depth", this.depth);<NEW_LINE>page.add("note_type", NoteServlet.type);<NEW_LINE>page.add("note_message", NoteServlet.message);<NEW_LINE>page.add("note_url", NoteServlet.url);<NEW_LINE>page.add("timezone", TimeZone.getDefault().getID());<NEW_LINE>page.add("currentTime", (new DateTime()).getMillis());<NEW_LINE>page.add("size", getDisplayExecutionPageSize());<NEW_LINE>page.add("System", System.class);<NEW_LINE>page.<MASK><NEW_LINE>page.add("WebUtils", WebUtils.class);<NEW_LINE>if (session != null && session.getUser() != null) {<NEW_LINE>page.add("user_id", session.getUser().getUserId());<NEW_LINE>}<NEW_LINE>final String errorMsg = getErrorMessageFromCookie(req);<NEW_LINE>page.add("error_message", errorMsg == null || errorMsg.isEmpty() ? "null" : errorMsg);<NEW_LINE>setErrorMessageInCookie(resp, null);<NEW_LINE>final String warnMsg = getWarnMessageFromCookie(req);<NEW_LINE>page.add("warn_message", warnMsg == null || warnMsg.isEmpty() ? "null" : warnMsg);<NEW_LINE>setWarnMessageInCookie(resp, null);<NEW_LINE>final String successMsg = getSuccessMessageFromCookie(req);<NEW_LINE>page.add("success_message", successMsg == null || successMsg.isEmpty() ? "null" : successMsg);<NEW_LINE>setSuccessMessageInCookie(resp, null);<NEW_LINE>// @TODO, allow more than one type of viewer. For time sake, I only install<NEW_LINE>// the first one<NEW_LINE>if (this.viewerPlugins != null && !this.viewerPlugins.isEmpty()) {<NEW_LINE>page.add("viewers", this.viewerPlugins);<NEW_LINE>}<NEW_LINE>if (this.triggerPlugins != null && !this.triggerPlugins.isEmpty()) {<NEW_LINE>page.add("triggerPlugins", this.triggerPlugins);<NEW_LINE>}<NEW_LINE>return page;<NEW_LINE>} | add("TimeUtils", TimeUtils.class); |
716,000 | public static void updateALiveEvent(com.azure.resourcemanager.mediaservices.MediaServicesManager manager) {<NEW_LINE>LiveEvent resource = manager.liveEvents().getWithResponse("mediaresources", "slitestmedia10", "myLiveEvent1", <MASK><NEW_LINE>resource.update().withTags(mapOf("tag1", "value1", "tag2", "value2", "tag3", "value3")).withDescription("test event updated").withInput(new LiveEventInput().withStreamingProtocol(LiveEventInputProtocol.FRAGMENTED_MP4).withAccessControl(new LiveEventInputAccessControl().withIp(new IpAccessControl().withAllow(Arrays.asList(new IpRange().withName("AllowOne").withAddress("192.1.1.0"))))).withKeyFrameIntervalDuration("PT6S")).withPreview(new LiveEventPreview().withAccessControl(new LiveEventPreviewAccessControl().withIp(new IpAccessControl().withAllow(Arrays.asList(new IpRange().withName("AllowOne").withAddress("192.1.1.0")))))).apply();<NEW_LINE>} | Context.NONE).getValue(); |
918,881 | protected void drawFilter() {<NEW_LINE>final Status status = renderingStatus;<NEW_LINE>switch(status) {<NEW_LINE>case DONE1:<NEW_LINE>surfaceTexture.setDefaultBufferSize(getPreviewWidth(), getPreviewHeight());<NEW_LINE>surfaceTexture.updateTexImage();<NEW_LINE>renderingStatus = Status.RENDER2;<NEW_LINE>break;<NEW_LINE>case DONE2:<NEW_LINE>surfaceTexture2.setDefaultBufferSize(getPreviewWidth(), getPreviewHeight());<NEW_LINE>surfaceTexture2.updateTexImage();<NEW_LINE>renderingStatus = Status.RENDER1;<NEW_LINE>break;<NEW_LINE>case RENDER1:<NEW_LINE>surfaceTexture2.setDefaultBufferSize(getPreviewWidth(), getPreviewHeight());<NEW_LINE>surfaceTexture2.updateTexImage();<NEW_LINE>break;<NEW_LINE>case RENDER2:<NEW_LINE>default:<NEW_LINE>surfaceTexture.setDefaultBufferSize(getPreviewWidth(), getPreviewHeight());<NEW_LINE>surfaceTexture.updateTexImage();<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>GLES20.glUseProgram(program);<NEW_LINE>squareVertex.position(SQUARE_VERTEX_DATA_POS_OFFSET);<NEW_LINE>GLES20.glVertexAttribPointer(aPositionHandle, 3, GLES20.GL_FLOAT, false, SQUARE_VERTEX_DATA_STRIDE_BYTES, squareVertex);<NEW_LINE>GLES20.glEnableVertexAttribArray(aPositionHandle);<NEW_LINE>squareVertex.position(SQUARE_VERTEX_DATA_UV_OFFSET);<NEW_LINE>GLES20.glVertexAttribPointer(aTextureHandle, 2, GLES20.GL_FLOAT, false, SQUARE_VERTEX_DATA_STRIDE_BYTES, squareVertex);<NEW_LINE>GLES20.glEnableVertexAttribArray(aTextureHandle);<NEW_LINE>GLES20.glUniformMatrix4fv(uMVPMatrixHandle, 1, false, MVPMatrix, 0);<NEW_LINE>GLES20.glUniformMatrix4fv(uSTMatrixHandle, 1, false, STMatrix, 0);<NEW_LINE>GLES20.glUniform1i(uSamplerHandle, 4);<NEW_LINE>GLES20.glActiveTexture(GLES20.GL_TEXTURE4);<NEW_LINE>GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, previousTexId);<NEW_LINE>// android view<NEW_LINE>GLES20.glUniform1i(uSamplerViewHandle, 5);<NEW_LINE><MASK><NEW_LINE>switch(status) {<NEW_LINE>case DONE2:<NEW_LINE>case RENDER1:<NEW_LINE>GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, viewId[1]);<NEW_LINE>break;<NEW_LINE>case RENDER2:<NEW_LINE>case DONE1:<NEW_LINE>default:<NEW_LINE>GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, viewId[0]);<NEW_LINE>break;<NEW_LINE>}<NEW_LINE>} | GLES20.glActiveTexture(GLES20.GL_TEXTURE5); |
484,659 | public void operationComplete(int rc, Set<LedgerFragment> fragments) {<NEW_LINE>if (rc == BKException.Code.OK) {<NEW_LINE>Set<BookieId> bookies = Sets.newHashSet();<NEW_LINE>for (LedgerFragment f : fragments) {<NEW_LINE>bookies.addAll(f.getAddresses());<NEW_LINE>}<NEW_LINE>if (bookies.isEmpty()) {<NEW_LINE>// no missing fragments<NEW_LINE>callback.processResult(<MASK><NEW_LINE>return;<NEW_LINE>}<NEW_LINE>publishSuspectedLedgersAsync(bookies.stream().map(BookieId::toString).collect(Collectors.toList()), Sets.newHashSet(lh.getId())).whenComplete((result, cause) -> {<NEW_LINE>if (null != cause) {<NEW_LINE>LOG.error("Auditor exception publishing suspected ledger {} with lost bookies {}", lh.getId(), bookies, cause);<NEW_LINE>callback.processResult(Code.ReplicationException, null, null);<NEW_LINE>} else {<NEW_LINE>callback.processResult(Code.OK, null, null);<NEW_LINE>}<NEW_LINE>});<NEW_LINE>} else {<NEW_LINE>callback.processResult(rc, null, null);<NEW_LINE>}<NEW_LINE>lh.closeAsync().whenComplete((result, cause) -> {<NEW_LINE>if (null != cause) {<NEW_LINE>LOG.warn("Error closing ledger {} : {}", lh.getId(), cause.getMessage());<NEW_LINE>}<NEW_LINE>});<NEW_LINE>} | Code.OK, null, null); |
1,660,789 | final DescribeMovingAddressesResult executeDescribeMovingAddresses(DescribeMovingAddressesRequest describeMovingAddressesRequest) {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(describeMovingAddressesRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE>awsRequestMetrics.startEvent(Field.ClientExecuteTime);<NEW_LINE>Request<DescribeMovingAddressesRequest> request = null;<NEW_LINE>Response<DescribeMovingAddressesResult> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new DescribeMovingAddressesRequestMarshaller().marshall(super.beforeMarshalling(describeMovingAddressesRequest));<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(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SERVICE_ID, "EC2");<NEW_LINE>request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "DescribeMovingAddresses");<NEW_LINE>request.<MASK><NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.RequestMarshallTime);<NEW_LINE>}<NEW_LINE>StaxResponseHandler<DescribeMovingAddressesResult> responseHandler = new StaxResponseHandler<DescribeMovingAddressesResult>(new DescribeMovingAddressesResultStaxUnmarshaller());<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>} | addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig); |
224,921 | private void tunnelSucceeded(EndPoint endPoint) {<NEW_LINE>try {<NEW_LINE>HttpDestination destination = (HttpDestination) <MASK><NEW_LINE>ClientConnectionFactory connectionFactory = this.connectionFactory;<NEW_LINE>if (destination.isSecure()) {<NEW_LINE>// Don't want to do DNS resolution here.<NEW_LINE>InetSocketAddress address = InetSocketAddress.createUnresolved(destination.getHost(), destination.getPort());<NEW_LINE>context.put(ClientConnector.REMOTE_SOCKET_ADDRESS_CONTEXT_KEY, address);<NEW_LINE>connectionFactory = destination.newSslClientConnectionFactory(null, connectionFactory);<NEW_LINE>}<NEW_LINE>var oldConnection = endPoint.getConnection();<NEW_LINE>var newConnection = connectionFactory.newConnection(endPoint, context);<NEW_LINE>endPoint.upgrade(newConnection);<NEW_LINE>if (LOG.isDebugEnabled())<NEW_LINE>LOG.debug("HTTP tunnel established: {} over {}", oldConnection, newConnection);<NEW_LINE>} catch (Throwable x) {<NEW_LINE>tunnelFailed(endPoint, x);<NEW_LINE>}<NEW_LINE>} | context.get(HttpClientTransport.HTTP_DESTINATION_CONTEXT_KEY); |
1,508,563 | private List<FastqWriter> makeTagWriters(final SAMReadGroupRecord readGroup, final FastqWriterFactory factory) {<NEW_LINE>String baseFilename = null;<NEW_LINE>if (readGroup != null) {<NEW_LINE>if (RG_TAG.equalsIgnoreCase("PU")) {<NEW_LINE>baseFilename = readGroup.getPlatformUnit() + "_";<NEW_LINE>} else if (RG_TAG.equalsIgnoreCase("ID")) {<NEW_LINE>baseFilename = readGroup.getReadGroupId() + "_";<NEW_LINE>}<NEW_LINE>if (baseFilename == null) {<NEW_LINE>throw new PicardException("The selected RG_TAG: " + RG_TAG + " is not present in the bam header.");<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>baseFilename = "";<NEW_LINE>}<NEW_LINE>List<File> tagFiles = new ArrayList<>();<NEW_LINE>for (String tagSplit : SEQUENCE_TAG_GROUP) {<NEW_LINE>String fileName = baseFilename + tagSplit.replace(",", "_");<NEW_LINE><MASK><NEW_LINE>fileName += COMPRESS_OUTPUTS_PER_TAG_GROUP ? ".fastq.gz" : ".fastq";<NEW_LINE>final File result = (OUTPUT_DIR != null) ? new File(OUTPUT_DIR, fileName) : new File(FASTQ.getParent(), fileName);<NEW_LINE>IOUtil.assertFileIsWritable(result);<NEW_LINE>tagFiles.add(result);<NEW_LINE>}<NEW_LINE>return tagFiles.stream().map(factory::newWriter).collect(Collectors.toList());<NEW_LINE>} | fileName = IOUtil.makeFileNameSafe(fileName); |
1,380,383 | public static void processParent(Class claz, Set configProperties) {<NEW_LINE>if (claz == null) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>// process the methods<NEW_LINE>Method[] methods = claz.getDeclaredMethods();<NEW_LINE>for (Method m : methods) {<NEW_LINE>ConfigProperty property = m.getAnnotation(ConfigProperty.class);<NEW_LINE>if (property != null) {<NEW_LINE>String result = validateMethod(m, property);<NEW_LINE>if (!result.equals(SUCCESS)) {<NEW_LINE>throw new IllegalStateException(result);<NEW_LINE>}<NEW_LINE>String defaultValue = property.defaultValue();<NEW_LINE>Class type = getType(property, m<MASK><NEW_LINE>processConfigProperty(configProperties, m.getName().substring(3), property, defaultValue, type);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// process the fields<NEW_LINE>Field[] fields = claz.getDeclaredFields();<NEW_LINE>for (Field f : fields) {<NEW_LINE>ConfigProperty property = f.getAnnotation(ConfigProperty.class);<NEW_LINE>if (property != null) {<NEW_LINE>String status = validateField(f, property);<NEW_LINE>if (!status.equals(SUCCESS)) {<NEW_LINE>throw new IllegalStateException(status);<NEW_LINE>}<NEW_LINE>String defaultValue = property.defaultValue();<NEW_LINE>if (defaultValue == null || defaultValue.equals("")) {<NEW_LINE>defaultValue = deriveDefaultValueOfField(f);<NEW_LINE>}<NEW_LINE>processConfigProperty(configProperties, f.getName(), property, defaultValue, f.getType());<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// process its super-class<NEW_LINE>if (claz.getSuperclass() != null) {<NEW_LINE>processParent(claz.getSuperclass(), configProperties);<NEW_LINE>}<NEW_LINE>} | .getParameterTypes()[0]); |
283,087 | public void init(Map<String, String> writerOptions) throws IOException {<NEW_LINE>this.location = writerOptions.get("location");<NEW_LINE>this.prefix = writerOptions.get("prefix");<NEW_LINE>this.fs = FileSystem.get(fsConf);<NEW_LINE>String <MASK><NEW_LINE>this.extension = extension == null ? "" : "." + extension;<NEW_LINE>this.fileNumberIndex = 0;<NEW_LINE>CsvWriterSettings writerSettings = new CsvWriterSettings();<NEW_LINE>writerSettings.setMaxColumns(TextFormatPlugin.MAXIMUM_NUMBER_COLUMNS);<NEW_LINE>writerSettings.setMaxCharsPerColumn(TextFormatPlugin.MAX_CHARS_PER_COLUMN);<NEW_LINE>writerSettings.setHeaderWritingEnabled(Boolean.parseBoolean(writerOptions.get("addHeader")));<NEW_LINE>writerSettings.setQuoteAllFields(Boolean.parseBoolean(writerOptions.get("forceQuotes")));<NEW_LINE>CsvFormat format = writerSettings.getFormat();<NEW_LINE>format.setLineSeparator(writerOptions.get("lineSeparator"));<NEW_LINE>format.setDelimiter(writerOptions.get("fieldDelimiter"));<NEW_LINE>format.setQuote(writerOptions.get("quote").charAt(0));<NEW_LINE>format.setQuoteEscape(writerOptions.get("escape").charAt(0));<NEW_LINE>// do not escape "escape" char<NEW_LINE>format.setCharToEscapeQuoteEscaping(TextFormatPlugin.NULL_CHAR);<NEW_LINE>this.writerSettings = writerSettings;<NEW_LINE>logger.trace("Text writer settings: {}", this.writerSettings);<NEW_LINE>} | extension = writerOptions.get("extension"); |
858,152 | protected void calculateRecall(Document doc) {<NEW_LINE>int rDen = 0;<NEW_LINE>int rNum = 0;<NEW_LINE>Map<Integer, Mention> predictedMentions = doc.allPredictedMentions;<NEW_LINE>for (CorefCluster g : doc.goldCorefClusters.values()) {<NEW_LINE>if (g.corefMentions.size() == 0) {<NEW_LINE>SieveCoreferenceSystem.logger.warning(<MASK><NEW_LINE>continue;<NEW_LINE>}<NEW_LINE>rDen += g.corefMentions.size() - 1;<NEW_LINE>rNum += g.corefMentions.size();<NEW_LINE>Set<CorefCluster> partitions = Generics.newHashSet();<NEW_LINE>for (Mention goldMention : g.corefMentions) {<NEW_LINE>if (!predictedMentions.containsKey(goldMention.mentionID)) {<NEW_LINE>// twinless goldmention<NEW_LINE>rNum--;<NEW_LINE>} else {<NEW_LINE>partitions.add(doc.corefClusters.get(predictedMentions.get(goldMention.mentionID).corefClusterID));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>rNum -= partitions.size();<NEW_LINE>}<NEW_LINE>if (rDen != doc.allGoldMentions.size() - doc.goldCorefClusters.values().size()) {<NEW_LINE>log.info("rDen is " + rDen);<NEW_LINE>log.info("doc.allGoldMentions.size() is " + doc.allGoldMentions.size());<NEW_LINE>log.info("doc.goldCorefClusters.values().size() is " + doc.goldCorefClusters.values().size());<NEW_LINE>}<NEW_LINE>assert (rDen == (doc.allGoldMentions.size() - doc.goldCorefClusters.values().size()));<NEW_LINE>recallNumSum += rNum;<NEW_LINE>recallDenSum += rDen;<NEW_LINE>} | "NO MENTIONS for cluster " + g.getClusterID()); |
1,628,859 | public void beforeMountItem(final ExtensionState<IncrementalMountExtensionState> extensionState, final RenderTreeNode renderTreeNode, final int index) {<NEW_LINE>final <MASK><NEW_LINE>if (IncrementalMountExtensionConfigs.isDebugLoggingEnabled) {<NEW_LINE>Log.d(DEBUG_TAG, "beforeMountItem [id=" + renderTreeNode.getRenderUnit().getId() + "]");<NEW_LINE>}<NEW_LINE>if (isTracing) {<NEW_LINE>RenderCoreSystrace.beginSection("IncrementalMountExtension.beforeMountItem");<NEW_LINE>}<NEW_LINE>final long id = renderTreeNode.getRenderUnit().getId();<NEW_LINE>final IncrementalMountExtensionState state = extensionState.getState();<NEW_LINE>if (state.mInput == null) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>final IncrementalMountOutput output = state.mInput.getIncrementalMountOutputForId(id);<NEW_LINE>if (output == null) {<NEW_LINE>throw new IllegalArgumentException("Output with id=" + id + " not found.");<NEW_LINE>}<NEW_LINE>maybeAcquireReference(extensionState, state.mPreviousLocalVisibleRect, output, false);<NEW_LINE>if (isTracing) {<NEW_LINE>RenderCoreSystrace.endSection();<NEW_LINE>}<NEW_LINE>} | boolean isTracing = RenderCoreSystrace.isEnabled(); |
820,388 | private void presentBackground(boolean collapseAbove, boolean collapseBelow, boolean hasWallpaper) {<NEW_LINE>int marginDefault = getContext().getResources().getDimensionPixelOffset(R.dimen.conversation_update_vertical_margin);<NEW_LINE>int marginCollapsed = 0;<NEW_LINE>int paddingDefault = getContext().getResources().getDimensionPixelOffset(R.dimen.conversation_update_vertical_padding);<NEW_LINE>int paddingCollapsed = getContext().getResources().getDimensionPixelOffset(R.dimen.conversation_update_vertical_padding_collapsed);<NEW_LINE>if (collapseAbove && collapseBelow) {<NEW_LINE>ViewUtil.setTopMargin(background, marginCollapsed);<NEW_LINE>ViewUtil.setBottomMargin(background, marginCollapsed);<NEW_LINE>ViewUtil.setPaddingTop(background, paddingCollapsed);<NEW_LINE>ViewUtil.setPaddingBottom(background, paddingCollapsed);<NEW_LINE>ViewUtil.updateLayoutParams(background, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);<NEW_LINE>if (hasWallpaper) {<NEW_LINE>background.setBackgroundResource(R.drawable.conversation_update_wallpaper_background_middle);<NEW_LINE>} else {<NEW_LINE>background.setBackground(null);<NEW_LINE>}<NEW_LINE>} else if (collapseAbove) {<NEW_LINE>ViewUtil.setTopMargin(background, marginCollapsed);<NEW_LINE>ViewUtil.setBottomMargin(background, marginDefault);<NEW_LINE>ViewUtil.setPaddingTop(background, paddingDefault);<NEW_LINE>ViewUtil.setPaddingBottom(background, paddingDefault);<NEW_LINE>ViewUtil.updateLayoutParams(background, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);<NEW_LINE>if (hasWallpaper) {<NEW_LINE>background.<MASK><NEW_LINE>} else {<NEW_LINE>background.setBackground(null);<NEW_LINE>}<NEW_LINE>} else if (collapseBelow) {<NEW_LINE>ViewUtil.setTopMargin(background, marginDefault);<NEW_LINE>ViewUtil.setBottomMargin(background, marginCollapsed);<NEW_LINE>ViewUtil.setPaddingTop(background, paddingDefault);<NEW_LINE>ViewUtil.setPaddingBottom(background, paddingCollapsed);<NEW_LINE>ViewUtil.updateLayoutParams(background, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);<NEW_LINE>if (hasWallpaper) {<NEW_LINE>background.setBackgroundResource(R.drawable.conversation_update_wallpaper_background_top);<NEW_LINE>} else {<NEW_LINE>background.setBackground(null);<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>ViewUtil.setTopMargin(background, marginDefault);<NEW_LINE>ViewUtil.setBottomMargin(background, marginDefault);<NEW_LINE>ViewUtil.setPaddingTop(background, paddingDefault);<NEW_LINE>ViewUtil.setPaddingBottom(background, paddingDefault);<NEW_LINE>ViewUtil.updateLayoutParams(background, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);<NEW_LINE>if (hasWallpaper) {<NEW_LINE>background.setBackgroundResource(R.drawable.conversation_update_wallpaper_background_singular);<NEW_LINE>} else {<NEW_LINE>background.setBackground(null);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | setBackgroundResource(R.drawable.conversation_update_wallpaper_background_bottom); |
1,206,627 | public static void convert(InterleavedS32 input, InterleavedS64 output) {<NEW_LINE>if (input.isSubimage() || output.isSubimage()) {<NEW_LINE>final int N = input<MASK><NEW_LINE>// CONCURRENT_BELOW BoofConcurrency.loopFor(0, input.height, y -> {<NEW_LINE>for (int y = 0; y < input.height; y++) {<NEW_LINE>int indexSrc = input.getIndex(0, y);<NEW_LINE>int indexDst = output.getIndex(0, y);<NEW_LINE>for (int x = 0; x < N; x++) {<NEW_LINE>output.data[indexDst++] = (input.data[indexSrc++]);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// CONCURRENT_ABOVE });<NEW_LINE>} else {<NEW_LINE>final int N = input.width * input.height * input.getNumBands();<NEW_LINE>// CONCURRENT_BELOW BoofConcurrency.loopBlocks(0,N,(i0,i1)->{<NEW_LINE>int i0 = 0, i1 = N;<NEW_LINE>for (int i = i0; i < i1; i++) {<NEW_LINE>output.data[i] = (input.data[i]);<NEW_LINE>}<NEW_LINE>// CONCURRENT_INLINE });<NEW_LINE>}<NEW_LINE>} | .width * input.getNumBands(); |
692,859 | public Response toResponse(Throwable ex) {<NEW_LINE>LOG.<MASK><NEW_LINE>if (ex instanceof ProcessingException || ex instanceof IllegalArgumentException) {<NEW_LINE>final Response response = BadRequestException.of().getResponse();<NEW_LINE>return Response.fromResponse(response).type(MediaType.APPLICATION_JSON_TYPE).entity(new ErrorMessage(response.getStatus(), ex.getLocalizedMessage())).build();<NEW_LINE>} else if (ex instanceof UnableToExecuteStatementException) {<NEW_LINE>// TODO remove this<NEW_LINE>if (ex.getCause() instanceof SQLIntegrityConstraintViolationException) {<NEW_LINE>return Response.status(CONFLICT).type(MediaType.APPLICATION_JSON_TYPE).entity(new ErrorMessage(CONFLICT.getStatusCode(), CatalogExceptionMessage.ENTITY_ALREADY_EXISTS)).build();<NEW_LINE>}<NEW_LINE>} else if (ex instanceof EntityNotFoundException) {<NEW_LINE>return Response.status(NOT_FOUND).type(MediaType.APPLICATION_JSON_TYPE).entity(new ErrorMessage(NOT_FOUND.getStatusCode(), ex.getMessage())).build();<NEW_LINE>} else if (ex instanceof AirflowPipelineDeploymentException) {<NEW_LINE>return Response.status(BAD_REQUEST).type(MediaType.APPLICATION_JSON_TYPE).entity(new ErrorMessage(BAD_REQUEST.getStatusCode(), ex.getMessage())).build();<NEW_LINE>} else if (ex instanceof AuthenticationException) {<NEW_LINE>return Response.status(UNAUTHORIZED).type(MediaType.APPLICATION_JSON_TYPE).entity(new ErrorMessage(UNAUTHORIZED.getStatusCode(), ex.getMessage())).build();<NEW_LINE>} else if (ex instanceof AuthorizationException) {<NEW_LINE>return Response.status(FORBIDDEN).type(MediaType.APPLICATION_JSON_TYPE).entity(new ErrorMessage(FORBIDDEN.getStatusCode(), ex.getMessage())).build();<NEW_LINE>} else if (ex instanceof WebServiceException) {<NEW_LINE>final Response response = ((WebServiceException) ex).getResponse();<NEW_LINE>Family family = response.getStatusInfo().getFamily();<NEW_LINE>if (family.equals(Response.Status.Family.REDIRECTION)) {<NEW_LINE>return response;<NEW_LINE>}<NEW_LINE>if (family.equals(Family.SERVER_ERROR)) {<NEW_LINE>throwException(ex);<NEW_LINE>}<NEW_LINE>return Response.fromResponse(response).type(MediaType.APPLICATION_JSON_TYPE).entity(new ErrorMessage(response.getStatus(), ex.getLocalizedMessage())).build();<NEW_LINE>}<NEW_LINE>LOG.info("exception ", ex);<NEW_LINE>logUnhandledException(ex);<NEW_LINE>return new UnhandledServerException(ex.getMessage()).getResponse();<NEW_LINE>} | debug(ex.getMessage()); |
1,516,761 | public void initialize(GenericApplicationContext context) {<NEW_LINE>MongoDataConfiguration dataConfiguration = new MongoDataConfiguration();<NEW_LINE>context.registerBean(MongoCustomConversions.class, dataConfiguration::mongoCustomConversions);<NEW_LINE>context.registerBean(MongoMappingContext.class, () -> {<NEW_LINE>try {<NEW_LINE>return dataConfiguration.mongoMappingContext(context, properties, context.getBean(MongoCustomConversions.class));<NEW_LINE>} catch (ClassNotFoundException e) {<NEW_LINE>e.printStackTrace();<NEW_LINE>}<NEW_LINE>return null;<NEW_LINE>});<NEW_LINE>context.registerBean(<MASK><NEW_LINE>MongoDatabaseFactoryDependentConfiguration conf = new MongoDatabaseFactoryDependentConfiguration(properties);<NEW_LINE>context.registerBean(SimpleMongoClientDatabaseFactory.class, () -> new SimpleMongoClientDatabaseFactory(context.getBean(MongoClient.class), properties.getMongoClientDatabase()));<NEW_LINE>context.registerBean(MongoConverter.class, () -> conf.mappingMongoConverter(context.getBean(MongoDatabaseFactory.class), context.getBean(MongoMappingContext.class), context.getBean(MongoCustomConversions.class)));<NEW_LINE>context.registerBean(MongoTemplate.class, () -> conf.mongoTemplate(context.getBean(MongoDatabaseFactory.class), context.getBean(MongoConverter.class)));<NEW_LINE>} | MongoCustomConversions.class, dataConfiguration::mongoCustomConversions); |
10,836 | public void apply(Project project) {<NEW_LINE>super.apply(project);<NEW_LINE>atlasConfigurationHelper.createLibCompenents();<NEW_LINE>project.afterEvaluate(project1 -> {<NEW_LINE>if (PluginTypeUtils.isAppProject(project) && atlasExtension.isAtlasEnabled()) {<NEW_LINE>Map<String, String> multiDex = new HashMap<>();<NEW_LINE>multiDex.put("group", "com.android.support");<NEW_LINE>multiDex.put("module", "multidex");<NEW_LINE>project1.getConfigurations().all(configuration -> configuration.exclude(multiDex));<NEW_LINE>}<NEW_LINE>Plugin plugin = project.getPlugins().findPlugin("kotlin-android");<NEW_LINE>if (plugin != null) {<NEW_LINE>project.getDependencies(<MASK><NEW_LINE>}<NEW_LINE>atlasConfigurationHelper.registAtlasStreams();<NEW_LINE>atlasConfigurationHelper.configDependencies(atlasExtension.getTBuildConfig().getAwbConfigFile());<NEW_LINE>// 3. update extension<NEW_LINE>atlasConfigurationHelper.updateExtensionAfterEvaluate();<NEW_LINE>// 4. Set up the android builder<NEW_LINE>try {<NEW_LINE>atlasConfigurationHelper.createBuilderAfterEvaluate();<NEW_LINE>} catch (Exception e) {<NEW_LINE>throw new GradleException("update builder failed", e);<NEW_LINE>}<NEW_LINE>// 5. Configuration tasks<NEW_LINE>atlasConfigurationHelper.configTasksAfterEvaluate();<NEW_LINE>project1.getTasks().create("atlasList", AtlasListTask.class);<NEW_LINE>});<NEW_LINE>} | ).add("compile", "org.jetbrains.kotlin:kotlin-stdlib:1.2.41"); |
653,273 | private void init() {<NEW_LINE>addListener(nativeBuffer -> {<NEW_LINE>Iterator<ComplexSamples> iterator = nativeBuffer.iterator();<NEW_LINE>while (iterator.hasNext()) {<NEW_LINE>getDecoder().receive(iterator.next());<NEW_LINE>}<NEW_LINE>});<NEW_LINE>getDecoder().setFilteredBufferListener(mFilteredBufferBroadcaster);<NEW_LINE>getDecoder().setComplexSymbolListener(getSymbolConstellationChart());<NEW_LINE>getDecoder().setPLLPhaseErrorListener(getPLLPhaseErrorLineChart());<NEW_LINE>getDecoder().setPLLFrequencyListener(getPLLFrequencyLineChart());<NEW_LINE>getDecoder(<MASK><NEW_LINE>getDecoder().setSamplesPerSymbolListener(getSamplesPerSymbolLineChart());<NEW_LINE>mFilteredBufferBroadcaster.addListener(getDifferentialDemodulatedSamplesChartBox());<NEW_LINE>HBox.setHgrow(getTopChartBox(), Priority.ALWAYS);<NEW_LINE>HBox.setHgrow(getBottomChartBox(), Priority.ALWAYS);<NEW_LINE>getChildren().addAll(getTopChartBox(), getBottomChartBox());<NEW_LINE>mDecoder.setMessageListener(new Listener<IMessage>() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void receive(IMessage message) {<NEW_LINE>mLog.debug(message.toString());<NEW_LINE>}<NEW_LINE>});<NEW_LINE>} | ).setSymbolDecisionDataListener(getEyeDiagramChart()); |
1,556,633 | final GetDistributionsResult executeGetDistributions(GetDistributionsRequest getDistributionsRequest) {<NEW_LINE>ExecutionContext executionContext = createExecutionContext(getDistributionsRequest);<NEW_LINE>AWSRequestMetrics awsRequestMetrics = executionContext.getAwsRequestMetrics();<NEW_LINE>awsRequestMetrics.startEvent(Field.ClientExecuteTime);<NEW_LINE>Request<GetDistributionsRequest> request = null;<NEW_LINE>Response<GetDistributionsResult> response = null;<NEW_LINE>try {<NEW_LINE>awsRequestMetrics.startEvent(Field.RequestMarshallTime);<NEW_LINE>try {<NEW_LINE>request = new GetDistributionsRequestProtocolMarshaller(protocolFactory).marshall(super.beforeMarshalling(getDistributionsRequest));<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(HandlerContextKey.ENDPOINT_OVERRIDDEN, isEndpointOverridden());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SIGNING_REGION, getSigningRegion());<NEW_LINE>request.addHandlerContext(HandlerContextKey.SERVICE_ID, "Lightsail");<NEW_LINE>request.addHandlerContext(HandlerContextKey.OPERATION_NAME, "GetDistributions");<NEW_LINE>request.<MASK><NEW_LINE>} finally {<NEW_LINE>awsRequestMetrics.endEvent(Field.RequestMarshallTime);<NEW_LINE>}<NEW_LINE>HttpResponseHandler<AmazonWebServiceResponse<GetDistributionsResult>> responseHandler = protocolFactory.createResponseHandler(new JsonOperationMetadata().withPayloadJson(true).withHasStreamingSuccessResponse(false), new GetDistributionsResultJsonUnmarshaller());<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>} | addHandlerContext(HandlerContextKey.ADVANCED_CONFIG, advancedConfig); |
36,883 | private static // accrual schedule<NEW_LINE>PeriodicSchedule parseAccrualSchedule(CsvRow row, String leg) {<NEW_LINE>PeriodicSchedule.Builder builder = PeriodicSchedule.builder();<NEW_LINE>// basics<NEW_LINE>builder.startDate(LoaderUtils.parseDate(getValueWithFallback(row, leg, START_DATE_FIELD)));<NEW_LINE>builder.endDate(LoaderUtils.parseDate(getValueWithFallback(row, leg, END_DATE_FIELD)));<NEW_LINE>builder.frequency(Frequency.parse(getValue(row, leg, FREQUENCY_FIELD)));<NEW_LINE>// adjustments<NEW_LINE>BusinessDayAdjustment dateAdj = parseBusinessDayAdjustment(row, leg, DATE_ADJ_CNV_FIELD, DATE_ADJ_CAL_FIELD).orElse(BusinessDayAdjustment.NONE);<NEW_LINE>Optional<BusinessDayAdjustment> startDateAdj = parseBusinessDayAdjustment(row, leg, START_DATE_CNV_FIELD, START_DATE_CAL_FIELD);<NEW_LINE>Optional<BusinessDayAdjustment> endDateAdj = parseBusinessDayAdjustment(row, leg, END_DATE_CNV_FIELD, END_DATE_CAL_FIELD);<NEW_LINE>builder.businessDayAdjustment(dateAdj);<NEW_LINE>if (startDateAdj.isPresent() && !startDateAdj.get().equals(dateAdj)) {<NEW_LINE>builder.startDateBusinessDayAdjustment(startDateAdj.get());<NEW_LINE>}<NEW_LINE>if (endDateAdj.isPresent() && !endDateAdj.get().equals(dateAdj)) {<NEW_LINE>builder.<MASK><NEW_LINE>}<NEW_LINE>// optionals<NEW_LINE>builder.stubConvention(findValueWithFallback(row, leg, STUB_CONVENTION_FIELD).map(s -> StubConvention.of(s)).orElse(StubConvention.SMART_INITIAL));<NEW_LINE>findValue(row, leg, ROLL_CONVENTION_FIELD).map(s -> LoaderUtils.parseRollConvention(s)).ifPresent(v -> builder.rollConvention(v));<NEW_LINE>findValue(row, leg, FIRST_REGULAR_START_DATE_FIELD).map(s -> LoaderUtils.parseDate(s)).ifPresent(v -> builder.firstRegularStartDate(v));<NEW_LINE>findValue(row, leg, LAST_REGULAR_END_DATE_FIELD).map(s -> LoaderUtils.parseDate(s)).ifPresent(v -> builder.lastRegularEndDate(v));<NEW_LINE>parseAdjustableDate(row, leg, OVERRIDE_START_DATE_FIELD, OVERRIDE_START_DATE_CNV_FIELD, OVERRIDE_START_DATE_CAL_FIELD).ifPresent(d -> builder.overrideStartDate(d));<NEW_LINE>return builder.build();<NEW_LINE>} | endDateBusinessDayAdjustment(endDateAdj.get()); |
738,463 | public List<io.ballerina.tools.diagnostics.Diagnostic> diagnostics(Path filePath) {<NEW_LINE>this.checkCancelled();<NEW_LINE>if (this.diagnostics != null) {<NEW_LINE>return this.diagnostics;<NEW_LINE>}<NEW_LINE>PackageCompilation compilation;<NEW_LINE>if (this.getCancelChecker().isPresent()) {<NEW_LINE>compilation = workspace().waitAndGetPackageCompilation(filePath, this.getCancelChecker().get()).orElseThrow();<NEW_LINE>} else {<NEW_LINE>compilation = workspace().waitAndGetPackageCompilation(filePath).orElseThrow();<NEW_LINE>}<NEW_LINE>Project project = this.workspace().project(this.filePath()).orElseThrow();<NEW_LINE>Path projectRoot = (project.kind() == ProjectKind.SINGLE_FILE_PROJECT) ? project.sourceRoot().getParent() : project.sourceRoot();<NEW_LINE>this.diagnostics = compilation.diagnosticResult().diagnostics().stream().filter(diag -> projectRoot.resolve(diag.location().lineRange().filePath()).equals(filePath)).<MASK><NEW_LINE>return this.diagnostics;<NEW_LINE>} | collect(Collectors.toList()); |
1,696,699 | /*<NEW_LINE>* upload a file or directory in ftp default directory<NEW_LINE>*<NEW_LINE>* @param uploadFile file<NEW_LINE>* @throws BrokerException BrokerException<NEW_LINE>*/<NEW_LINE>public void upLoadFile(File uploadFile) throws BrokerException {<NEW_LINE>if (!this.ftpClient.isConnected() || !this.ftpClient.isAvailable()) {<NEW_LINE>log.error("ftp client not connected to a server");<NEW_LINE>throw new BrokerException(ErrorCode.FTP_CLIENT_NOT_CONNECT_TO_SERVER);<NEW_LINE>}<NEW_LINE>if (!uploadFile.exists()) {<NEW_LINE>log.error("upload file not exist");<NEW_LINE><MASK><NEW_LINE>}<NEW_LINE>try {<NEW_LINE>this.ftpClient.setDataTimeout(300 * 1000);<NEW_LINE>this.ftpClient.enterLocalPassiveMode();<NEW_LINE>this.ftpClient.setFileType(FTP.BINARY_FILE_TYPE);<NEW_LINE>if (uploadFile.isDirectory()) {<NEW_LINE>log.error("it's not a file");<NEW_LINE>throw new BrokerException(ErrorCode.FTP_NOT_FILE);<NEW_LINE>}<NEW_LINE>FileInputStream inputStream = new FileInputStream(uploadFile);<NEW_LINE>this.ftpClient.storeFile(uploadFile.getName(), inputStream);<NEW_LINE>inputStream.close();<NEW_LINE>log.info("file upload success, file name: {}", uploadFile.getName());<NEW_LINE>} catch (IOException e) {<NEW_LINE>throw new BrokerException(e.getMessage());<NEW_LINE>}<NEW_LINE>} | throw new BrokerException(ErrorCode.FTP_NOT_EXIST_PATH); |
1,340,867 | public void marshall(ListNotebookInstancesRequest listNotebookInstancesRequest, ProtocolMarshaller protocolMarshaller) {<NEW_LINE>if (listNotebookInstancesRequest == null) {<NEW_LINE>throw new SdkClientException("Invalid argument passed to marshall(...)");<NEW_LINE>}<NEW_LINE>try {<NEW_LINE>protocolMarshaller.marshall(listNotebookInstancesRequest.getNextToken(), NEXTTOKEN_BINDING);<NEW_LINE>protocolMarshaller.marshall(<MASK><NEW_LINE>protocolMarshaller.marshall(listNotebookInstancesRequest.getSortBy(), SORTBY_BINDING);<NEW_LINE>protocolMarshaller.marshall(listNotebookInstancesRequest.getSortOrder(), SORTORDER_BINDING);<NEW_LINE>protocolMarshaller.marshall(listNotebookInstancesRequest.getNameContains(), NAMECONTAINS_BINDING);<NEW_LINE>protocolMarshaller.marshall(listNotebookInstancesRequest.getCreationTimeBefore(), CREATIONTIMEBEFORE_BINDING);<NEW_LINE>protocolMarshaller.marshall(listNotebookInstancesRequest.getCreationTimeAfter(), CREATIONTIMEAFTER_BINDING);<NEW_LINE>protocolMarshaller.marshall(listNotebookInstancesRequest.getLastModifiedTimeBefore(), LASTMODIFIEDTIMEBEFORE_BINDING);<NEW_LINE>protocolMarshaller.marshall(listNotebookInstancesRequest.getLastModifiedTimeAfter(), LASTMODIFIEDTIMEAFTER_BINDING);<NEW_LINE>protocolMarshaller.marshall(listNotebookInstancesRequest.getStatusEquals(), STATUSEQUALS_BINDING);<NEW_LINE>protocolMarshaller.marshall(listNotebookInstancesRequest.getNotebookInstanceLifecycleConfigNameContains(), NOTEBOOKINSTANCELIFECYCLECONFIGNAMECONTAINS_BINDING);<NEW_LINE>protocolMarshaller.marshall(listNotebookInstancesRequest.getDefaultCodeRepositoryContains(), DEFAULTCODEREPOSITORYCONTAINS_BINDING);<NEW_LINE>protocolMarshaller.marshall(listNotebookInstancesRequest.getAdditionalCodeRepositoryEquals(), ADDITIONALCODEREPOSITORYEQUALS_BINDING);<NEW_LINE>} catch (Exception e) {<NEW_LINE>throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);<NEW_LINE>}<NEW_LINE>} | listNotebookInstancesRequest.getMaxResults(), MAXRESULTS_BINDING); |
1,536,076 | PECoffSymbolStruct addSymbolEntry(String name, byte type, byte storageclass, byte secHdrIndex, long offset) {<NEW_LINE>// Get the current symbol index and append symbol name to string table.<NEW_LINE>int index;<NEW_LINE>PECoffSymbolStruct sym;<NEW_LINE>if (name.isEmpty()) {<NEW_LINE>index = strTabNrOfBytes;<NEW_LINE>strTabContent.append('\0');<NEW_LINE>strTabNrOfBytes += 1;<NEW_LINE>sym = new PECoffSymbolStruct(index, type, storageclass, secHdrIndex, offset);<NEW_LINE>symbols.add(sym);<NEW_LINE>} else {<NEW_LINE>int nameSize = name.getBytes(StandardCharsets.UTF_8).length;<NEW_LINE>// We can't trust strTabContent.length() since that is<NEW_LINE>// chars (UTF16), keep track of bytes on our own.<NEW_LINE>index = strTabNrOfBytes;<NEW_LINE>// strTabContent.append('_').append(name).append('\0');<NEW_LINE>strTabContent.append<MASK><NEW_LINE>strTabNrOfBytes += (nameSize + 1);<NEW_LINE>sym = new PECoffSymbolStruct(index, type, storageclass, secHdrIndex, offset);<NEW_LINE>symbols.add(sym);<NEW_LINE>// Only add exports for external class symbols that are defined<NEW_LINE>if (storageclass == IMAGE_SYMBOL.IMAGE_SYM_CLASS_EXTERNAL && secHdrIndex != -1) {<NEW_LINE>addDirective(name, type);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>symbolCount++;<NEW_LINE>return (sym);<NEW_LINE>} | (name).append('\0'); |
192,079 | protected List<Class<? extends C>> parseValue(Object obj) throws ParameterException {<NEW_LINE>if (obj == null) {<NEW_LINE>throw new UnspecifiedParameterException(this);<NEW_LINE>}<NEW_LINE>if (List.class.isInstance(obj)) {<NEW_LINE>List<?> l = (List<?>) obj;<NEW_LINE>ArrayList<C> inst = new ArrayList<>(l.size());<NEW_LINE>ArrayList<Class<? extends C>> classes = new ArrayList<>(l.size());<NEW_LINE>for (Object o : l) {<NEW_LINE>// does the given objects class fit?<NEW_LINE>if (restrictionClass.isInstance(o)) {<NEW_LINE>inst.add((C) o);<NEW_LINE>classes.add((Class<? extends C>) o.getClass());<NEW_LINE>} else if (o instanceof Class) {<NEW_LINE>if (restrictionClass.isAssignableFrom((Class<?>) o)) {<NEW_LINE>inst.add(null);<NEW_LINE>classes.add((Class<MASK><NEW_LINE>} else {<NEW_LINE>throw new WrongParameterValueException(this, ((Class<?>) o).getName(), "Given class not a subclass / implementation of " + restrictionClass.getName());<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>throw new WrongParameterValueException(this, o.getClass().getName(), "Given instance not an implementation of " + restrictionClass.getName());<NEW_LINE>}<NEW_LINE>}<NEW_LINE>this.instances = inst;<NEW_LINE>return super.parseValue(classes);<NEW_LINE>}<NEW_LINE>// Did we get a single instance?<NEW_LINE>try {<NEW_LINE>C inst = restrictionClass.cast(obj);<NEW_LINE>this.instances = Arrays.asList(inst);<NEW_LINE>return super.parseValue(inst.getClass());<NEW_LINE>} catch (ClassCastException e) {<NEW_LINE>// Continue<NEW_LINE>}<NEW_LINE>return super.parseValue(obj);<NEW_LINE>} | <? extends C>) o); |
1,449,015 | public boolean retainAll(Collection<?> collection) {<NEW_LINE>int retainedSize = collection.size();<NEW_LINE>UnifiedMap<K, V> retainedCopy = (UnifiedMap<K, V>) UnifiedMap.this.newEmpty(retainedSize);<NEW_LINE>for (Object obj : collection) {<NEW_LINE>if (obj instanceof Entry) {<NEW_LINE>Entry<?, ?> otherEntry = (Entry<?, ?>) obj;<NEW_LINE>Entry<K, V> thisEntry = this.getEntry(otherEntry);<NEW_LINE>if (thisEntry != null) {<NEW_LINE>retainedCopy.put(thisEntry.getKey(<MASK><NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (retainedCopy.size() < this.size()) {<NEW_LINE>UnifiedMap.this.maxSize = retainedCopy.maxSize;<NEW_LINE>UnifiedMap.this.occupied = retainedCopy.occupied;<NEW_LINE>UnifiedMap.this.table = retainedCopy.table;<NEW_LINE>return true;<NEW_LINE>}<NEW_LINE>return false;<NEW_LINE>} | ), thisEntry.getValue()); |
65,745 | public List<String> listByTopUnitYearAndMonth(String topUnitName, String sYear, String sMonth) throws Exception {<NEW_LINE>if (topUnitName == null || topUnitName.isEmpty()) {<NEW_LINE>logger.error(new TopUnitNamesEmptyException());<NEW_LINE>return null;<NEW_LINE>}<NEW_LINE>EntityManager em = this.entityManagerContainer().get(StatisticTopUnitForMonth.class);<NEW_LINE>CriteriaBuilder cb = em.getCriteriaBuilder();<NEW_LINE>CriteriaQuery<String> cq = cb.createQuery(String.class);<NEW_LINE>Root<StatisticTopUnitForMonth> root = cq.from(StatisticTopUnitForMonth.class);<NEW_LINE>Predicate p = cb.equal(root.get(StatisticTopUnitForMonth_.topUnitName), topUnitName);<NEW_LINE>if (sYear == null || sYear.isEmpty()) {<NEW_LINE>logger.error(new StatisticYearEmptyException());<NEW_LINE>} else {<NEW_LINE>p = cb.and(p, cb.equal(root.get(StatisticTopUnitForMonth_.statisticYear), sYear));<NEW_LINE>}<NEW_LINE>if (sMonth == null || sMonth.isEmpty()) {<NEW_LINE>logger.error(new StatisticMonthEmptyException());<NEW_LINE>} else {<NEW_LINE>p = cb.and(p, cb.equal(root.get(<MASK><NEW_LINE>}<NEW_LINE>cq.select(root.get(StatisticTopUnitForMonth_.id));<NEW_LINE>return em.createQuery(cq.where(p)).setMaxResults(60).getResultList();<NEW_LINE>} | StatisticTopUnitForMonth_.statisticMonth), sMonth)); |
594,439 | public void linkReferenceNo(final PO po, final IReferenceNoGeneratorInstance instance) {<NEW_LINE>final IReferenceNoDAO dao = Services.get(IReferenceNoDAO.class);<NEW_LINE>final IContextAware contextAware = getContextAware(po);<NEW_LINE>final String referenceNoStr = instance.generateReferenceNo(po);<NEW_LINE>if (IReferenceNoGenerator.REFERENCENO_None == referenceNoStr) {<NEW_LINE>logger.debug("Instance {} did not generate any referenceNo for '{}'. Skip.", new Object[] { instance, po });<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>final I_C_ReferenceNo referenceNo = dao.getCreateReferenceNo(instance.<MASK><NEW_LINE>dao.getCreateReferenceNoDoc(referenceNo, TableRecordReference.of(po));<NEW_LINE>// 04153 : mark the reference numbers with 'referenceNoStr' created by the system with isManual = N<NEW_LINE>if (referenceNo != null) {<NEW_LINE>referenceNo.setIsManual(false);<NEW_LINE>// make sure the flag is saved<NEW_LINE>InterfaceWrapperHelper.save(referenceNo);<NEW_LINE>}<NEW_LINE>if (logger.isDebugEnabled()) {<NEW_LINE>logger.debug("Created reference " + referenceNoStr + " for " + po);<NEW_LINE>}<NEW_LINE>} | getType(), referenceNoStr, contextAware); |
1,368,810 | private void fixNewMethods(String signature) {<NEW_LINE>Set<ExecutablePair> existingMethods = this.existingMethods.get(signature);<NEW_LINE>Set<ExecutablePair> newMethods = this.newMethods.get(signature);<NEW_LINE>Iterable<ExecutablePair> allMethods = Iterables.concat(existingMethods, newMethods);<NEW_LINE>ExecutablePair first = allMethods.iterator().next();<NEW_LINE>String mainSelector = nameTable.getMethodSelector(first.element());<NEW_LINE>ExecutablePair impl = resolveImplementation(allMethods);<NEW_LINE>// Find the set of selectors for this method that don't yet have shims in a superclass.<NEW_LINE>Set<String> existingSelectors = new HashSet<>();<NEW_LINE>Map<String, ExecutablePair> newSelectors = new LinkedHashMap<>();<NEW_LINE>for (ExecutablePair method : existingMethods) {<NEW_LINE>existingSelectors.add(nameTable.getMethodSelector(method.element()));<NEW_LINE>}<NEW_LINE>existingSelectors.add(mainSelector);<NEW_LINE>for (ExecutablePair method : newMethods) {<NEW_LINE>String sel = nameTable.getMethodSelector(method.element());<NEW_LINE>if (!existingSelectors.contains(sel) && !newSelectors.containsKey(sel)) {<NEW_LINE>newSelectors.put(sel, method);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (newMethods.contains(impl)) {<NEW_LINE>if (ElementUtil.isDefault(impl.element())) {<NEW_LINE>addDefaultMethodShim(mainSelector, impl);<NEW_LINE>} else {<NEW_LINE>// Must be an abstract class.<NEW_LINE>unit.setHasIncompleteProtocol();<NEW_LINE>}<NEW_LINE>}<NEW_LINE>for (Map.Entry<String, ExecutablePair> entry : newSelectors.entrySet()) {<NEW_LINE>addRenamingMethodShim(entry.getKey(), <MASK><NEW_LINE>}<NEW_LINE>} | entry.getValue(), impl); |
1,231,355 | public Events queryEvents(List<EventQueryCondition> conditionList) throws Exception {<NEW_LINE>// This method maybe have poor efficiency. It queries all data which meets a condition without select function.<NEW_LINE>// https://github.com/apache/iotdb/discussions/3888<NEW_LINE>StringBuilder query = new StringBuilder();<NEW_LINE>query.append("select * from ");<NEW_LINE>IoTDBUtils.addModelPath(client.getStorageGroup(), query, Event.INDEX_NAME);<NEW_LINE>IoTDBUtils.<MASK><NEW_LINE>StringBuilder where = whereSQL(conditionList);<NEW_LINE>if (where.length() > 0) {<NEW_LINE>query.append(" where ").append(where);<NEW_LINE>}<NEW_LINE>query.append(IoTDBClient.ALIGN_BY_DEVICE);<NEW_LINE>List<? super StorageData> storageDataList = client.filterQuery(Event.INDEX_NAME, query.toString(), storageBuilder);<NEW_LINE>final Events events = new Events();<NEW_LINE>EventQueryCondition condition = conditionList.get(0);<NEW_LINE>int limitCount = 0;<NEW_LINE>PaginationUtils.Page page = PaginationUtils.INSTANCE.exchange(condition.getPaging());<NEW_LINE>for (int i = page.getFrom(); i < storageDataList.size(); i++) {<NEW_LINE>if (limitCount < page.getLimit()) {<NEW_LINE>limitCount++;<NEW_LINE>Event event = (Event) storageDataList.get(i);<NEW_LINE>events.getEvents().add(parseEvent(event));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>events.setTotal(storageDataList.size());<NEW_LINE>// resort by self, because of the select query result order by time.<NEW_LINE>final Order order = Objects.isNull(condition.getOrder()) ? Order.DES : condition.getOrder();<NEW_LINE>if (Order.DES.equals(order)) {<NEW_LINE>events.getEvents().sort((org.apache.skywalking.oap.server.core.query.type.event.Event e1, org.apache.skywalking.oap.server.core.query.type.event.Event e2) -> Long.compare(e2.getStartTime(), e1.getStartTime()));<NEW_LINE>} else {<NEW_LINE>events.getEvents().sort(Comparator.comparingLong(org.apache.skywalking.oap.server.core.query.type.event.Event::getStartTime));<NEW_LINE>}<NEW_LINE>return events;<NEW_LINE>} | addQueryAsterisk(Event.INDEX_NAME, query); |
640,278 | public PagedFlux<VirtualMachineImage> listAsync() {<NEW_LINE>final VirtualMachineImagesInSkuImpl self = this;<NEW_LINE>PagedFlux<VirtualMachineImageResourceInner> virtualMachineImageResourcePagedFlux = PagedConverter.convertListToPagedFlux(innerCollection.listWithResponseAsync(sku.region().toString(), sku.publisher().name(), sku.offer().name(), sku.name(), null, null, null));<NEW_LINE>return PagedConverter.flatMapPage(virtualMachineImageResourcePagedFlux, resourceInner -> innerCollection.getAsync(self.sku.region().toString(), self.sku.publisher().name(), self.sku.offer().name(), self.sku.name(), resourceInner.name()).map(imageInner -> (VirtualMachineImage) new VirtualMachineImageImpl(self.sku.region(), self.sku.publisher().name(), self.sku.offer().name(), self.sku.name(), resourceInner.<MASK><NEW_LINE>} | name(), imageInner))); |
1,058,596 | public void addHistogramGraph() {<NEW_LINE>if (histogramPanel != null)<NEW_LINE>throw new IllegalArgumentException("Already called");<NEW_LINE>histogramPanel = new ImageHistogramPanel(maxGrayLevels + 1, maxGrayLevels);<NEW_LINE>histogramHolder.add(BorderLayout.CENTER, histogramPanel);<NEW_LINE>histogramHolder.setPreferredSize(<MASK><NEW_LINE>histogramHolder.setMaximumSize(new Dimension(100000, 60));<NEW_LINE>histogramHolder.validate();<NEW_LINE>MouseAdapter mouse = new MouseAdapter() {<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void mousePressed(MouseEvent e) {<NEW_LINE>if (type != ThresholdType.FIXED) {<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>int where = 255 * e.getX() / (histogramPanel.getWidth() - 1);<NEW_LINE>spinnerThreshold.setValue(where);<NEW_LINE>}<NEW_LINE><NEW_LINE>@Override<NEW_LINE>public void mouseDragged(MouseEvent e) {<NEW_LINE>mousePressed(e);<NEW_LINE>}<NEW_LINE>};<NEW_LINE>histogramPanel.addMouseListener(mouse);<NEW_LINE>histogramPanel.addMouseMotionListener(mouse);<NEW_LINE>} | new Dimension(0, 60)); |
1,727,329 | public Request<UpdateThingGroupRequest> marshall(UpdateThingGroupRequest updateThingGroupRequest) {<NEW_LINE>if (updateThingGroupRequest == null) {<NEW_LINE>throw new AmazonClientException("Invalid argument passed to marshall(UpdateThingGroupRequest)");<NEW_LINE>}<NEW_LINE>Request<UpdateThingGroupRequest> request = new DefaultRequest<UpdateThingGroupRequest>(updateThingGroupRequest, "AWSIot");<NEW_LINE>request.setHttpMethod(HttpMethodName.PATCH);<NEW_LINE>String uriResourcePath = "/thing-groups/{thingGroupName}";<NEW_LINE>uriResourcePath = uriResourcePath.replace("{thingGroupName}", (updateThingGroupRequest.getThingGroupName() == null) ? "" : StringUtils.fromString(updateThingGroupRequest.getThingGroupName()));<NEW_LINE>request.setResourcePath(uriResourcePath);<NEW_LINE>try {<NEW_LINE>StringWriter stringWriter = new StringWriter();<NEW_LINE>AwsJsonWriter jsonWriter = JsonUtils.getJsonWriter(stringWriter);<NEW_LINE>jsonWriter.beginObject();<NEW_LINE>if (updateThingGroupRequest.getThingGroupProperties() != null) {<NEW_LINE><MASK><NEW_LINE>jsonWriter.name("thingGroupProperties");<NEW_LINE>ThingGroupPropertiesJsonMarshaller.getInstance().marshall(thingGroupProperties, jsonWriter);<NEW_LINE>}<NEW_LINE>if (updateThingGroupRequest.getExpectedVersion() != null) {<NEW_LINE>Long expectedVersion = updateThingGroupRequest.getExpectedVersion();<NEW_LINE>jsonWriter.name("expectedVersion");<NEW_LINE>jsonWriter.value(expectedVersion);<NEW_LINE>}<NEW_LINE>jsonWriter.endObject();<NEW_LINE>jsonWriter.close();<NEW_LINE>String snippet = stringWriter.toString();<NEW_LINE>byte[] content = snippet.getBytes(UTF8);<NEW_LINE>request.setContent(new StringInputStream(snippet));<NEW_LINE>request.addHeader("Content-Length", Integer.toString(content.length));<NEW_LINE>} catch (Throwable t) {<NEW_LINE>throw new AmazonClientException("Unable to marshall request to JSON: " + t.getMessage(), t);<NEW_LINE>}<NEW_LINE>if (!request.getHeaders().containsKey("Content-Type")) {<NEW_LINE>request.addHeader("Content-Type", "application/x-amz-json-1.0");<NEW_LINE>}<NEW_LINE>return request;<NEW_LINE>} | ThingGroupProperties thingGroupProperties = updateThingGroupRequest.getThingGroupProperties(); |
1,212,662 | private List<DataCheckEntity> computeAlertForRule(String domain, String type, String name, String monitor, List<Config> configs) {<NEW_LINE>List<DataCheckEntity> results = new ArrayList<DataCheckEntity>();<NEW_LINE>Pair<Integer, List<Condition>> conditionPair = m_ruleConfigManager.convertConditions(configs);<NEW_LINE>int minute = calAlreadyMinute();<NEW_LINE>Map<String, String> pars = new HashMap<String, String>();<NEW_LINE>pars.put("type", type);<NEW_LINE>pars.put("name", name);<NEW_LINE>if (conditionPair != null) {<NEW_LINE>int maxMinute = conditionPair.getKey();<NEW_LINE>List<Condition> conditions = conditionPair.getValue();<NEW_LINE>if (StringUtils.isEmpty(name)) {<NEW_LINE>name = Constants.ALL;<NEW_LINE>}<NEW_LINE>if (minute >= maxMinute - 1) {<NEW_LINE>int start = minute + 1 - maxMinute;<NEW_LINE>int end = minute;<NEW_LINE>pars.put(MIN, String.valueOf(start));<NEW_LINE>pars.put(MAX, String.valueOf(end));<NEW_LINE>EventReport report = fetchEventReport(domain, ModelPeriod.CURRENT, pars);<NEW_LINE>if (report != null) {<NEW_LINE>double[] data = buildArrayData(start, end, type, name, monitor, report);<NEW_LINE>results.addAll(m_dataChecker.checkData(data, conditions));<NEW_LINE>}<NEW_LINE>} else if (minute < 0) {<NEW_LINE>int start = 60 + minute + 1 - (maxMinute);<NEW_LINE>int end = 60 + minute;<NEW_LINE>pars.put(MIN, String.valueOf(start));<NEW_LINE>pars.put(MAX, String.valueOf(end));<NEW_LINE>EventReport report = fetchEventReport(domain, ModelPeriod.LAST, pars);<NEW_LINE>if (report != null) {<NEW_LINE>double[] data = buildArrayData(start, end, type, name, monitor, report);<NEW_LINE>results.addAll(m_dataChecker.checkData(data, conditions));<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>int currentStart = 0, currentEnd = minute;<NEW_LINE>int lastStart = 60 + 1 - (maxMinute - minute);<NEW_LINE>int lastEnd = 59;<NEW_LINE>pars.put(MIN, String.valueOf(currentStart));<NEW_LINE>pars.put(MAX, String.valueOf(currentEnd));<NEW_LINE>EventReport currentReport = fetchEventReport(<MASK><NEW_LINE>pars.put(MIN, String.valueOf(lastStart));<NEW_LINE>pars.put(MAX, String.valueOf(lastEnd));<NEW_LINE>EventReport lastReport = fetchEventReport(domain, ModelPeriod.LAST, pars);<NEW_LINE>if (currentReport != null && lastReport != null) {<NEW_LINE>double[] currentValue = buildArrayData(currentStart, currentEnd, type, name, monitor, currentReport);<NEW_LINE>double[] lastValue = buildArrayData(lastStart, lastEnd, type, name, monitor, lastReport);<NEW_LINE>double[] data = mergerArray(lastValue, currentValue);<NEW_LINE>results.addAll(m_dataChecker.checkData(data, conditions));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>return results;<NEW_LINE>} | domain, ModelPeriod.CURRENT, pars); |
1,274,871 | public SBase convertProtocolBuffersMessageToSObject(Message message, SBase newInstance, SClass sClass) throws ConvertException {<NEW_LINE>try {<NEW_LINE>Descriptor descriptor = message.getDescriptorForType();<NEW_LINE>if (newInstance == null) {<NEW_LINE>newInstance = sClass.newInstance();<NEW_LINE>}<NEW_LINE>Message subTypeMessage = null;<NEW_LINE>for (FieldDescriptor fieldDescriptor : descriptor.getFields()) {<NEW_LINE>if (fieldDescriptor.getName().equals("__actual_type")) {<NEW_LINE>sClass = sClass.getServicesMap().getSType((String) message.getField(fieldDescriptor));<NEW_LINE>newInstance = sClass.newInstance();<NEW_LINE>} else if (fieldDescriptor.getName().startsWith("__")) {<NEW_LINE>if (fieldDescriptor.getName().substring(2).equals(sClass.getSimpleName())) {<NEW_LINE>subTypeMessage = (Message) message.getField(fieldDescriptor);<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>Object val = message.getField(fieldDescriptor);<NEW_LINE>SField field = newInstance.getSClass().getField(fieldDescriptor.getName());<NEW_LINE>if (field == null) {<NEW_LINE>throw new ConvertException("No field on " + sClass.getName() + " with name " + fieldDescriptor.getName());<NEW_LINE>}<NEW_LINE>if (fieldDescriptor.isRepeated()) {<NEW_LINE>List list = new ArrayList();<NEW_LINE>if (val instanceof List) {<NEW_LINE>List oldList = (List) val;<NEW_LINE>for (Object x : oldList) {<NEW_LINE>list.add(convertFieldValue(field, x));<NEW_LINE>}<NEW_LINE>} else if (val instanceof DynamicMessage) {<NEW_LINE>int <MASK><NEW_LINE>for (int index = 0; index < size; index++) {<NEW_LINE>Object repeatedField = message.getRepeatedField(fieldDescriptor, index);<NEW_LINE>list.add(convertFieldValue(field, repeatedField));<NEW_LINE>}<NEW_LINE>} else {<NEW_LINE>throw new ConvertException("Field " + sClass.getName() + "." + fieldDescriptor.getName() + " should have list value");<NEW_LINE>}<NEW_LINE>newInstance.sSet(field, list);<NEW_LINE>} else {<NEW_LINE>SField sField = sClass.getField(fieldDescriptor.getName());<NEW_LINE>newInstance.sSet(sField, convertFieldValue(sField, val));<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (subTypeMessage != null) {<NEW_LINE>convertProtocolBuffersMessageToSObject(subTypeMessage, newInstance, sClass);<NEW_LINE>}<NEW_LINE>return newInstance;<NEW_LINE>} catch (IllegalArgumentException e) {<NEW_LINE>LOGGER.error("", e);<NEW_LINE>}<NEW_LINE>return null;<NEW_LINE>} | size = message.getRepeatedFieldCount(fieldDescriptor); |
606,682 | public static Point calculatePositionForPopupKeyboard(Keyboard.Key key, View keyboardView, AnyKeyboardViewBase popupKeyboardView, PreviewPopupTheme theme, int[] windowOffset) {<NEW_LINE>Point point = new Point(key.x + windowOffset[0], key.y + windowOffset[1]);<NEW_LINE>point.offset(0, theme.getVerticalOffset());<NEW_LINE>// moving the keyboard to the left, so the first key will be above the initial X<NEW_LINE>point.offset(-popupKeyboardView.getPaddingLeft(), 0);<NEW_LINE>// moving the keyboard down, so the bottom padding will not push the keys too high<NEW_LINE>point.offset(0, popupKeyboardView.getPaddingBottom());<NEW_LINE>// moving the keyboard its height up<NEW_LINE>point.offset(0, -popupKeyboardView.getMeasuredHeight());<NEW_LINE>boolean shouldMirrorKeys = false;<NEW_LINE>// now we need to see the the popup is positioned correctly:<NEW_LINE>// 1) if the right edge is off the screen, then we'll try to put the right edge over the<NEW_LINE>// popup key<NEW_LINE>if (point.x + popupKeyboardView.getMeasuredWidth() > keyboardView.getMeasuredWidth()) {<NEW_LINE>int mirroredX = key.x + windowOffset[<MASK><NEW_LINE>// adding the width of the key - now the right most popup key is above the finger<NEW_LINE>mirroredX += key.width;<NEW_LINE>mirroredX += popupKeyboardView.getPaddingRight();<NEW_LINE>shouldMirrorKeys = true;<NEW_LINE>point = new Point(mirroredX, point.y);<NEW_LINE>}<NEW_LINE>// 2) if it took too much to adjust the X, then forget about it.<NEW_LINE>if (point.x < 0) {<NEW_LINE>point.offset(-point.x, 0);<NEW_LINE>shouldMirrorKeys = false;<NEW_LINE>}<NEW_LINE>if (shouldMirrorKeys)<NEW_LINE>((AnyPopupKeyboard) popupKeyboardView.getKeyboard()).mirrorKeys();<NEW_LINE>return point;<NEW_LINE>} | 0] - popupKeyboardView.getMeasuredWidth(); |
1,794,990 | public static QueryParams fromQueryObject(Map<String, Object> map) {<NEW_LINE>QueryParams params = new QueryParams();<NEW_LINE>params.limit = (<MASK><NEW_LINE>if (map.containsKey(INDEX_START_VALUE)) {<NEW_LINE>Object indexStartValue = map.get(INDEX_START_VALUE);<NEW_LINE>params.indexStartValue = normalizeValue(NodeFromJSON(indexStartValue));<NEW_LINE>String indexStartName = (String) map.get(INDEX_START_NAME);<NEW_LINE>if (indexStartName != null) {<NEW_LINE>params.indexStartName = ChildKey.fromString(indexStartName);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>if (map.containsKey(INDEX_END_VALUE)) {<NEW_LINE>Object indexEndValue = map.get(INDEX_END_VALUE);<NEW_LINE>params.indexEndValue = normalizeValue(NodeFromJSON(indexEndValue));<NEW_LINE>String indexEndName = (String) map.get(INDEX_END_NAME);<NEW_LINE>if (indexEndName != null) {<NEW_LINE>params.indexEndName = ChildKey.fromString(indexEndName);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>String viewFrom = (String) map.get(VIEW_FROM);<NEW_LINE>if (viewFrom != null) {<NEW_LINE>params.viewFrom = viewFrom.equals("l") ? ViewFrom.LEFT : ViewFrom.RIGHT;<NEW_LINE>}<NEW_LINE>String indexStr = (String) map.get(INDEX);<NEW_LINE>if (indexStr != null) {<NEW_LINE>params.index = Index.fromQueryDefinition(indexStr);<NEW_LINE>}<NEW_LINE>return params;<NEW_LINE>} | Integer) map.get(LIMIT); |
1,512,545 | public void widgetSelected(SelectionEvent e) {<NEW_LINE>String newAddr = newAddressTxt.getText();<NEW_LINE>newAddr.replaceAll("\\s+", "");<NEW_LINE>if (StringUtil.isNotEmpty(newAddr)) {<NEW_LINE>if (isInvalidFormat(newAddr)) {<NEW_LINE>newAddressTxt.setFocus();<NEW_LINE>newAddressTxt.selectAll();<NEW_LINE>Point loc = newAddressTxt.toDisplay(newAddressTxt.getLocation());<NEW_LINE>formatTip.setLocation(loc.x, loc.y - <MASK><NEW_LINE>formatTip.setVisible(true);<NEW_LINE>return;<NEW_LINE>} else if (addr.contains(newAddr)) {<NEW_LINE>newAddressTxt.setFocus();<NEW_LINE>newAddressTxt.selectAll();<NEW_LINE>Point loc = newAddressTxt.toDisplay(newAddressTxt.getLocation());<NEW_LINE>existTip.setLocation(loc.x, loc.y - newAddressTxt.getSize().y);<NEW_LINE>existTip.setVisible(true);<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>callback.addServerAddress(newAddr);<NEW_LINE>dialog.close();<NEW_LINE>}<NEW_LINE>} | newAddressTxt.getSize().y); |
1,454,412 | public void process(String child, byte[] data) {<NEW_LINE>String work = new String(data);<NEW_LINE>String[] parts = work.split("\\|");<NEW_LINE>String src = parts[0];<NEW_LINE>String dest = parts[1];<NEW_LINE>String sortId = new <MASK><NEW_LINE>log.debug("Sorting {} to {} using sortId {}", src, dest, sortId);<NEW_LINE>synchronized (currentWork) {<NEW_LINE>if (currentWork.containsKey(sortId))<NEW_LINE>return;<NEW_LINE>currentWork.put(sortId, this);<NEW_LINE>}<NEW_LINE>synchronized (this) {<NEW_LINE>sortStart = System.currentTimeMillis();<NEW_LINE>}<NEW_LINE>VolumeManager fs = context.getVolumeManager();<NEW_LINE>String formerThreadName = Thread.currentThread().getName();<NEW_LINE>try {<NEW_LINE>sort(fs, sortId, new Path(src), dest);<NEW_LINE>} catch (Exception t) {<NEW_LINE>try {<NEW_LINE>// parent dir may not exist<NEW_LINE>fs.mkdirs(new Path(dest));<NEW_LINE>fs.create(SortedLogState.getFailedMarkerPath(dest)).close();<NEW_LINE>} catch (IOException e) {<NEW_LINE>log.error("Error creating failed flag file " + sortId, e);<NEW_LINE>}<NEW_LINE>log.error("Caught exception", t);<NEW_LINE>} finally {<NEW_LINE>Thread.currentThread().setName(formerThreadName);<NEW_LINE>try {<NEW_LINE>close();<NEW_LINE>} catch (Exception e) {<NEW_LINE>log.error("Error during cleanup sort/copy " + sortId, e);<NEW_LINE>}<NEW_LINE>synchronized (this) {<NEW_LINE>sortStop = System.currentTimeMillis();<NEW_LINE>}<NEW_LINE>currentWork.remove(sortId);<NEW_LINE>}<NEW_LINE>} | Path(src).getName(); |
1,362,244 | private static void extractGenericsConnections(final Map<GenericsTypeName, GenericsType> connections, final GenericsType[] usage, final GenericsType[] declaration) {<NEW_LINE>// if declaration does not provide generics, there is no connection to make<NEW_LINE>if (usage == null || declaration == null || declaration.length == 0)<NEW_LINE>return;<NEW_LINE>if (usage.length != declaration.length)<NEW_LINE>return;<NEW_LINE>// both have generics<NEW_LINE>for (int i = 0, n = usage.length; i < n; i += 1) {<NEW_LINE>GenericsType ui = usage[i];<NEW_LINE>GenericsType di = declaration[i];<NEW_LINE>if (di.isPlaceholder()) {<NEW_LINE>connections.put(new GenericsTypeName(di.getName()), ui);<NEW_LINE>} else if (di.isWildcard()) {<NEW_LINE>ClassNode lowerBound = di.getLowerBound(), upperBounds[] = di.getUpperBounds();<NEW_LINE>if (ui.isWildcard()) {<NEW_LINE>extractGenericsConnections(connections, ui.getLowerBound(), lowerBound);<NEW_LINE>extractGenericsConnections(connections, ui.getUpperBounds(), upperBounds);<NEW_LINE>} else if (!isUnboundedWildcard(di)) {<NEW_LINE>ClassNode boundType = lowerBound != null ? lowerBound : upperBounds[0];<NEW_LINE>if (boundType.isGenericsPlaceHolder()) {<NEW_LINE>ui = new GenericsType(ui.getType());<NEW_LINE>ui.setPlaceHolder(false);<NEW_LINE>ui.setWildcard(true);<NEW_LINE>connections.put(new GenericsTypeName(boundType.getUnresolvedName()), ui);<NEW_LINE>} else {<NEW_LINE>// di like "? super Iterable<T>" and ui like "Collection<Type>"<NEW_LINE>extractGenericsConnections(connections, ui.getType(), boundType);<NEW_LINE>}<NEW_LINE>}<NEW_LINE>// GRECLIPSE end<NEW_LINE>} else {<NEW_LINE>extractGenericsConnections(connections, ui.getType(<MASK><NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | ), di.getType()); |
1,728,926 | public void onEnable() {<NEW_LINE>PlanBungeeComponent component = DaggerPlanBungeeComponent.builder().plan(this).abstractionLayer(abstractionLayer).build();<NEW_LINE>try {<NEW_LINE>system = component.system();<NEW_LINE>locale = system<MASK><NEW_LINE>system.enable();<NEW_LINE>new BStatsBungee(this, system.getDatabaseSystem().getDatabase()).registerMetrics();<NEW_LINE>logger.info(locale.getString(PluginLang.ENABLED));<NEW_LINE>} catch (AbstractMethodError e) {<NEW_LINE>logger.error("Plugin ran into AbstractMethodError - Server restart is required. Likely cause is updating the jar without a restart.");<NEW_LINE>} catch (EnableException e) {<NEW_LINE>logger.error("----------------------------------------");<NEW_LINE>logger.error("Error: " + e.getMessage());<NEW_LINE>logger.error("----------------------------------------");<NEW_LINE>logger.error("Plugin Failed to Initialize Correctly. If this issue is caused by config settings you can use /planbungee reload");<NEW_LINE>onDisable();<NEW_LINE>} catch (Exception e) {<NEW_LINE>String version = abstractionLayer.getPluginInformation().getVersion();<NEW_LINE>Logger.getGlobal().log(Level.SEVERE, e, () -> this.getClass().getSimpleName() + "-v" + version);<NEW_LINE>logger.error("Plugin Failed to Initialize Correctly. If this issue is caused by config settings you can use /planbungee reload");<NEW_LINE>logger.error("This error should be reported at https://github.com/plan-player-analytics/Plan/issues");<NEW_LINE>onDisable();<NEW_LINE>}<NEW_LINE>registerCommand(component.planCommand().build());<NEW_LINE>if (system != null) {<NEW_LINE>system.getProcessing().submitNonCritical(() -> system.getListenerSystem().callEnableEvent(this));<NEW_LINE>}<NEW_LINE>} | .getLocaleSystem().getLocale(); |
1,790,273 | private void pullUp(NbCodeLanguageClient client, String uri, QuickPickItem source, QuickPickItem target, List<QuickPickItem> members) {<NEW_LINE>try {<NEW_LINE>FileObject file = Utils.fromUri(uri);<NEW_LINE>ClasspathInfo <MASK><NEW_LINE>JavaSource js = JavaSource.forFileObject(file);<NEW_LINE>if (js == null) {<NEW_LINE>throw new IOException("Cannot get JavaSource for: " + uri);<NEW_LINE>}<NEW_LINE>ElementHandle sourceHandle = gson.fromJson(gson.toJson(source.getUserData()), ElementData.class).toHandle();<NEW_LINE>ElementHandle targetHandle = gson.fromJson(gson.toJson(target.getUserData()), ElementData.class).toHandle();<NEW_LINE>List<MemberInfo<ElementHandle<Element>>> memberHandles = new ArrayList<>();<NEW_LINE>js.runUserActionTask(ci -> {<NEW_LINE>ci.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);<NEW_LINE>boolean isAbstract = targetHandle.resolve(ci).getModifiers().contains(Modifier.ABSTRACT);<NEW_LINE>for (QuickPickItem member : members) {<NEW_LINE>Element el = gson.fromJson(gson.toJson(member.getUserData()), ElementData.class).resolve(ci);<NEW_LINE>MemberInfo<ElementHandle<Element>> memberInfo = MemberInfo.create(el, ci);<NEW_LINE>memberInfo.setMakeAbstract(isAbstract && el.getKind() == ElementKind.METHOD);<NEW_LINE>memberHandles.add(memberInfo);<NEW_LINE>}<NEW_LINE>}, true);<NEW_LINE>org.netbeans.modules.refactoring.java.api.PullUpRefactoring refactoring = new org.netbeans.modules.refactoring.java.api.PullUpRefactoring(TreePathHandle.from(sourceHandle, info));<NEW_LINE>refactoring.setTargetType(targetHandle);<NEW_LINE>refactoring.setMembers(memberHandles.toArray(new MemberInfo[memberHandles.size()]));<NEW_LINE>refactoring.getContext().add(JavaRefactoringUtils.getClasspathInfoFor(file));<NEW_LINE>client.applyEdit(new ApplyWorkspaceEditParams(perform(refactoring, "PullUp")));<NEW_LINE>} catch (Exception ex) {<NEW_LINE>client.showMessage(new MessageParams(MessageType.Error, ex.getLocalizedMessage()));<NEW_LINE>}<NEW_LINE>} | info = ClasspathInfo.create(file); |
974,359 | public void testSFLocal() {<NEW_LINE>SFLocalHome fhome1;<NEW_LINE>try {<NEW_LINE>fhome1 = (SFLocalHome) FATHelper.lookupJavaBinding(jndiSFLHome);<NEW_LINE>if (fhome1 == null) {<NEW_LINE>results <MASK><NEW_LINE>return;<NEW_LINE>}<NEW_LINE>} catch (Exception e) {<NEW_LINE>results = results + " FAIL: Exception thrown when looking up " + jndiSFLHome + ": " + e.toString() + ". ";<NEW_LINE>svLogger.info("Lookup Exception:");<NEW_LINE>e.printStackTrace();<NEW_LINE>return;<NEW_LINE>}<NEW_LINE>SFLocal ejb1 = null;<NEW_LINE>try {<NEW_LINE>ejb1 = fhome1.create();<NEW_LINE>if (ejb1 == null) {<NEW_LINE>results = results + " FAIL: Couldn't create SFL from the Home interface. ";<NEW_LINE>} else {<NEW_LINE>results = results + " SFL created from the Home interface successfully. ";<NEW_LINE>String tmpStr = "tmpStr";<NEW_LINE>String testStr = ejb1.method1(tmpStr);<NEW_LINE>if (testStr.equals(tmpStr))<NEW_LINE>results = results + " SFL.method1 functions correctly. ";<NEW_LINE>else<NEW_LINE>results = results + " FAIL: SFL.method1 returns a wrong value: " + testStr + ". ";<NEW_LINE>}<NEW_LINE>} catch (Throwable t) {<NEW_LINE>results = results + " FAIL: Caught unexpected: " + t.toString() + ". ";<NEW_LINE>svLogger.info("Unexpected Exception:");<NEW_LINE>t.printStackTrace();<NEW_LINE>} finally {<NEW_LINE>if (ejb1 != null) {<NEW_LINE>try {<NEW_LINE>ejb1.remove();<NEW_LINE>svLogger.info("Cleanup completed, EJB removed");<NEW_LINE>} catch (Throwable t) {<NEW_LINE>svLogger.info("Warning: Unable to remove EJB.");<NEW_LINE>}<NEW_LINE>}<NEW_LINE>}<NEW_LINE>} | = results + " FAIL: Unable to lookup bean home for " + jndiSFLHome + ". "; |
306,280 | public SSHKeyPairResponse createSSHKeyPairResponse(SSHKeyPair sshkeyPair, boolean privatekey) {<NEW_LINE>SSHKeyPairResponse response = new SSHKeyPairResponse(sshkeyPair.getUuid(), sshkeyPair.getName(), sshkeyPair.getFingerprint());<NEW_LINE>if (privatekey) {<NEW_LINE>response = new CreateSSHKeyPairResponse(sshkeyPair.getUuid(), sshkeyPair.getName(), sshkeyPair.getFingerprint(), sshkeyPair.getPrivateKey());<NEW_LINE>}<NEW_LINE>Account account = ApiDBUtils.<MASK><NEW_LINE>response.setAccountName(account.getAccountName());<NEW_LINE>Domain domain = ApiDBUtils.findDomainById(sshkeyPair.getDomainId());<NEW_LINE>response.setDomainId(domain.getUuid());<NEW_LINE>response.setDomainName(domain.getName());<NEW_LINE>response.setHasAnnotation(annotationDao.hasAnnotations(sshkeyPair.getUuid(), AnnotationService.EntityType.SSH_KEYPAIR.name(), _accountMgr.isRootAdmin(CallContext.current().getCallingAccount().getId())));<NEW_LINE>return response;<NEW_LINE>} | findAccountById(sshkeyPair.getAccountId()); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.