id
stringlengths
7
14
text
stringlengths
1
37.2k
91324844_0
@PrePersist public void slugify(){ this.slug = new Slugify().slugify(this.title); }
91367377_1
public BufferedImage exportCurrentGraph(mxGraph graph, double scale, UIAbstractBlock selectedBlock, BlockState<? extends LatticeElement> state) { BufferedImage graphImage; int stateImageWidth = (int) (STATE_AREA_WIDTH * scale); BufferedImage stateImage = null; if (selectedBlock != null && state != null...
91427887_1
Span spanFromPayload(Tracer tracer, @Nullable Map<String, ByteBuffer> payload) { ByteBuffer b3 = payload != null ? payload.get("b3") : null; if (b3 == null) return tracer.nextSpan(); TraceContextOrSamplingFlags extracted = B3SingleFormat.parseB3SingleFormat(UTF_8.decode(b3)); if (extracted == null) return trace...
91470090_46
@Override public BlockResultDTO eth_getUncleByBlockHashAndIndex(String blockHash, String uncleIdx) { BlockResultDTO s = null; try { Block block = blockchain.getBlockByHash(stringHexToByteArray(blockHash)); if (block == null) { return null; } s = getUncleResultDTO(u...
91478358_21
public static Topic split(String path) { if (path == null) { return null; } path = path.replaceAll("(^/+|/$)+", ""); if (path.isEmpty()) { return null; } return new Topic(Arrays.asList(path.split("\\/+"))); }
91496363_8
public void getWebClient(Function<Record, Boolean> filter, Handler<AsyncResult<WebClient>> handler) { HttpEndpoint.getWebClient(serviceDiscovery, filter, handler); }
91546562_0
@PluginBuilderFactory @SuppressWarnings("WeakerAccess") public static Builder newBuilder() { return new Builder(); }
91547699_1
public static void start(Context context, BmiValue bmiValue) { Intent intent = new Intent(context, SaveBmiService.class); intent.putExtra(PARAM_KEY_BMI_VALUE, bmiValue); context.startService(intent); }
91552889_11
public static String evaljs(String script) { try { return JS.eval("JSON.stringify(" + script + ")").toString(); } catch (ScriptException ex) { LOG.log(Level.SEVERE, ex.getMessage(), ex); } return "undefined"; }
91571398_0
public RedisThrottlerJmxBean getJmxBean() { return throttler.getJmxBean(); }
91581792_11
public void putMonitor(String content) { long time = System.currentTimeMillis(); contentList.add(content); timeList.add(time); }
91583905_213
public boolean tablesMatch(Table table1, Table table2) { noDifferences = true; checkTable(table1, table2); return noDifferences; }
91584792_0
@Override }
91595685_5
static Note extractMostFrequentNote(List<PitchDifference> samples) { Map<Note, Integer> noteFrequencies = new HashMap<>(); for (PitchDifference pitchDifference : samples) { Note closest = pitchDifference.closest; if (noteFrequencies.containsKey(closest)) { Integer count = noteFreque...
91663814_3
@Override public void onEdtUserNameChanged(String userName) { if (!TextUtil.isEmpty(userName)) { mView.showClearUserNameButton(); } else { mView.hideClearUserNameButton(); } }
91674936_332
static void setServletParameters(ServletContext servletContext) { UploadConfig uploadConfig = new UploadConfig(); MultipartConfigElement multipartConfig = uploadConfig.toMultipartConfigElement(); if (multipartConfig == null) { return; } File dir = createUploadDir(servletContext, multipartConfig.getLocati...
91683656_295
public static void setProperty(Object bean, String field, Object value) { INSTANCE.checkParameters(bean, field); try { INSTANCE.setPropertyValue(bean, field, value); } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { throw handleReflectionException(bean.getClass(), field, e...
91712296_15
public double calculateBonus(Employee user) { return 0.1 * user.getSalary(); }
91725602_1
public static boolean flushIfNeeded(String url) { // Flush if request to whitelisted url if (isUrlWhiteListed(url)) { flush(); return true; } return false; }
91763900_3
@RequestMapping(path = "/post/{name}", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE) @ResponseBody public User post(@PathVariable String name, Model model){ logger.info("name : {}",name); return new User(20,name,"男"); }
91826174_48
@Override protected Query getComponentQuery(final RRestoreBlobData data) throws IOException { RRestoreFacet facet = getRestoreFacet(data); RestoreBlobData blobData = data.getBlobData(); Map<String, String> attributes; try (InputStream inputStream = blobData.getBlob().getInputStream()) { attributes = facet.e...
91855710_3
@PreAuthorize("@blogSecurityService.hasPostPermission(#postDTO, #userAccount, T(com.github.nkonev.blog.security.permissions.PostPermissions).EDIT)") @PutMapping(Constants.Urls.API + Constants.Urls.POST) public PostDTOWithAuthorization updatePost( @AuthenticationPrincipal UserAccountDetailsDTO userAccount, // nu...
91952715_2
public static File doChooseFile(String extension, String directory, String type) { if (MainWindow.getInstance().getActiveProject() != null) { File projectPath = new File(System.getProperty("project.path") + File.separator + directory); if (projectPath.exists()) { JFileChooser fileChoose...
91956337_0
String encrypt(String randomStr, String text) throws AesException { ByteGroup byteCollector = new ByteGroup(); byte[] randomStrBytes = randomStr.getBytes(CHARSET); byte[] textBytes = text.getBytes(CHARSET); byte[] networkBytesOrder = getNetworkBytesOrder(textBytes.length); byte[] appidBytes = appId.getBytes(CHARSE...
91984043_2
public void dataProvided(List<ITEM> items) { if (items == null) { dataProvided(items, 0); } else { dataProvided(items, getFrom() + items.size()); } }
91984923_2
public void loadForecastWeatherDataForTomorrow() { Location lastKnownLocation = locationService.lastLocation(); if (lastKnownLocation != null) { double longitude = lastKnownLocation.getLongitude(); double latitude = lastKnownLocation.getLatitude(); dispatchRequestStarted(); w...
92027307_1
public void check(){ check(false); }
92033442_103
public static Byte asByte(String expression, Node node) throws XPathExpressionException { String byteString = evaluateAsString(expression, node); return (isEmptyString(byteString)) ? null : Byte.valueOf(byteString); }
92062193_3
@Override public double getRate(long time) { double valueInPeriod = normalizeValue(time); double result = rateFunction(valueInPeriod); LOGGER.trace("rateFunction returned: {} for value: {}", result, valueInPeriod); return result < 0 ? 0d : result; }
92073011_44
public OrderExecutionReport execInst(List<ExecInstEnum> execInst) { this.execInst = execInst; return this; }
92116596_22
public void deserialize(JSONObject jsonObject) { if (jsonObject != null) { code = jsonObject.optString("code", code); tickerText = jsonObject.optString("tickerText", tickerText); title = jsonObject.optString("title", title); body = jsonObject.optString("body", body); playSoun...
92120027_58
public static String getSmallestAndLargest(String str, int k) { if (str == null || str.length() < k || k <= 0) { return "\n"; } String smallest = str.substring(0, k); String largest = smallest; // Loop to check for (int i = 1; i < str.length() - k + 1; i++) { String sub = str.s...
92150440_1
SortedSet<HookMetadata> parse() throws IOException, ClassNotFoundException { return parse(className -> true); // Parse all classes found in the JAR files. }
92184534_26
@Override public boolean isPassed(int timestamp) { return items.getFirst().isPassed(timestamp); }
92225522_5
void append(@NonNull MobileEventJson event) { long now = Time.now(); if (event.userId == null) { event.userId = userIdProvider.getUserId(); } if (this.config.acceptSameEventAfter > 0 && state.lastEvent != null && now < state.lastEvent.time + this.config.acceptSameEventA...
92269851_15
public boolean greaterThan(SentinelVersion version) { if (version == null) { return true; } return getFullVersion() > version.getFullVersion(); }
92283185_0
@Benchmark public BufferedImage RGB_to_3ByteBGR() { DataBuffer buffer = new DataBufferByte(RGB_SRC, RGB_SRC.length); SampleModel sampleModel = new ComponentSampleModel(DataBuffer.TYPE_BYTE, WIDTH, HEIGHT, 3, WIDTH * 3, new int[]{0, 1, 2}); BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImag...
92312271_14
public static SenseHatColor fromRGB(int red, int green, int blue) { short r = (short) ((red >> 3) & 0b11111); short g = (short) ((green >> 2) & 0b111111); short b = (short) ((blue >> 3) & 0b11111); return new SenseHatColor(r, g, b); }
92362395_119
public static Properties loadProperties(String fileName) { return loadProperties(fileName, false, false); }
92375988_132
@Override public void clean() { if (destroyed || cancelled) { return; } destroyed = true; // Do not perform the destructor if the native handle is not valid. if (!nativeHandle.isValid()) { return; } long handle = nativeHandle.get(); // Close the native handle. nativeHandle.close(); // P...
92377986_4
protected boolean isLoginValid() { boolean valid = true; if (mLoginValidator != null && !mLoginValidator.isValid(mLogin.get())) { mLoginError.set(mViewAccess.getLoginErrorMessage()); valid = false; } else { mLoginError.set(null); } return valid; }
92469890_21
public static Date getNowDate() { return new Date(); }
92486066_10
@Override public void processEvents(final List<Event> eventList, final Set<String> dashboardIds) { final List<String> ids = eventList.stream() .map(Event::getCollectionId) .map(String.class::cast) .collect(Collectors.toList()); if (ids.contains(null)) { connectionHandler.sendEve...
92500825_0
@Override public List<Map<String, String>> getPageEntries(PaginationCriteria paginationCriteria) throws TableDataException { List<T> data = getData(paginationCriteria); log.debug("Table data retrieved..."); List<Map<String, String>> records = new ArrayList<>(data.size()); try { data.forEach(i -...
92515991_163
@Override public void accept(FailedMessage failedMessage) { actions.forEach(action -> action.accept(failedMessage)); }
92536940_1
@SuppressWarnings("unchecked") public T getItem(int index) { int target = head - index; if (target < 0) target = queue.length + target; return (T) queue[target]; }
92611668_3
@Override public boolean canStartNewInstance(@NotNull CloudImage cloudImage) { KubeCloudImage kubeCloudImage = (KubeCloudImage) cloudImage; String kubeCloudImageId = kubeCloudImage.getId(); if(!myImageIdToImageMap.containsKey(kubeCloudImageId)){ LOG.debug("Can't start instance of unknown cloud image...
92615561_5
public BoltKeyValue next() { try(KeyValue.ByValue keyValue = BoltNative.BoltDBCursor_Next(objectId)) { return keyValue.hasKeyValue() ? new BoltKeyValue(keyValue.getKey(), keyValue.getValue()) : null; } }
92620072_1
public String delete(String id) throws ApiException { ApiResponse<String> resp = deleteWithHttpInfo(id); return resp.getData(); }
92632486_1
public int estimateTableCardinality(double selectivityFactor) { // some code goes here return (int) Math.ceil(totalTuples() * selectivityFactor); }
92746837_311
public MetadataReportBuilder address(String address) { this.address = address; return getThis(); }
92755785_4
public boolean isValid(CharSequence email) { return email != null && EMAIL_ADDRESS.matcher(email).matches(); }
92768732_18
public ConditionScript parse(final String script) throws ConditionParsingException { return parse(script, true); }
92915376_2
@RequestMapping(value = "/listspam/{id}") public List<CommentDTO> getSpamComments(@PathVariable(value = "id") String pageId) throws IOException { LOGGER.info("get spam comments for pageId {}", pageId); counterService.increment("commentstore.list_spamcomments"); List<CommentModel> r = service.listSpamComments(pageId)...
92919239_1
public static void removeLogPrint(AbstractLogPrinter logPrinter) { if (logPrinter == null) throw new NullPointerException("logPrinter is null"); logAdapter.remove(logPrinter); }
92944959_7
public static final Singleton4 getInstance() { if (INSTANCE == null) { INSTANCE = Singleton4Holder.obj ; } return INSTANCE ; }
92951080_4
public boolean shouldExecuteOnProject(Project project) { return _1C.KEY.equalsIgnoreCase(project.getLanguageKey()) && StringUtils.isNotBlank(_1c.getSettings().getString(_1CPlugin.LCOV_REPORT_PATH)); }
92956570_25
public ArchiveCompression getCompression() { return compression; }
92974732_0
protected static void parseInts(String str, int[] ints) { int len = str.length(); int intIndex = 0; int currentInt = -1; ints[0] = -1; ints[1] = -1; ints[2] = -1; for (int i = 0; i < len; i++) { char c = str.charAt(i); if (c >= '0' && c <= '9') { if (currentInt =...
92980167_129
@Override public void addMutation(Mutation mutation) throws MutationsRejectedException { for (ColumnUpdate update : mutation.getUpdates()) { MutableEntry entry = new MutableEntry(mutation.getRow(), update); if (update.isDeleted()) { if (!supportsDelete) { throw new IllegalArgumentException("can...
92982984_62
public static TypeFetcher fromTypes() { return new TypeFetcher() { // this is technically invalid, as different apis might call. Won't happen, but could. // make better Iterable<TypeDeclaration> foundInApi; @Override public TypeDeclaration fetchType(Api api, final String n...
93055348_0
@NonNull public static ArrayList<ContentValues> deserializeToContentValues(@NonNull String serialized, PageInfo pageInfo, int bookId) { Matcher matcher = HIGHLIGHT_PATTERN.matcher(ser...
93131587_43
public String generateMainClass(final Collection<TableModel> tables, final boolean enableVisualizationSupport) { Objects.requireNonNull(tables); //get package from the table models final String targetPackage = ((TableModel) tables.toArray()[0]).getPackageName(); final ST template = this.stGroup.getInst...
93167847_2
@Override protected void initView() { mainActivity = (MainActivity) getActivity(); //Fragment里 嵌套Fragment的Manager要用getChildFragmentManager() mPresent = new HotPresenterImp(this, getChildFragmentManager()); mHotTl.setTabMode(TabLayout.MODE_FIXED); mPresent.initPage(mHotVp); }
93181581_6
public static StatementKind getStatementKind(String sql) { String prefix = sql.trim(); prefix = prefix.length() < 10 ? prefix : prefix.substring(0, 10); prefix = prefix.toLowerCase(); if (prefix.startsWith("select")) { return SELECT; } else if (prefix.startsWith("insert")) { ...
93201544_1
public <T extends LogEvent> Logger<T> getLogger(Supplier<?> supplier, Function<? super LoggerKey, ? extends Logger> builder) { final String name = getLoggerName(); return getLogger(name, supplier, builder); }
93268041_15
public void assertCurrentStageExists(final String secretId) { final GetSecretValueRequest getSecretValueRequest = new GetSecretValueRequest(); getSecretValueRequest.setSecretId(secretId); getSecretValueRequest.setVersionStage(CURRENT.getAwsName()); getDelegate().getSecretValue(getSecretValueRequest); }
93307435_0
public static HeapImage captureHeap() throws IOException { String path = "target/heapunit/" + System.currentTimeMillis() + ".hprof"; return new SimpleHeapImage(HeapDumpProcuder.makeHeapDump(path, TimeUnit.SECONDS.toMillis(60))); }
93314642_136
public static BigInteger translate( final BigInteger sourceAmount, final int sourceScale, final int destinationScale ) { Objects.requireNonNull(sourceAmount, "sourceAmount must not be null"); Preconditions.checkArgument(sourceAmount.compareTo(BigInteger.ZERO) >= 0, "sourceAmount must be positive"); Precondition...
93364077_10
@VisibleForTesting static AttractionCollection buildNightLifeCollection() { ArrayList<Attraction> attractions = new ArrayList<>(); attractions.add(new Attraction( R.drawable.social, R.string.social_title, R.string.creative_cocktails, ...
93389699_3
@Override public void validate(T t) throws CompositeValidationException { List<ValidationException> exceptions = new ArrayList<>(); for (Validator<? super T> validator : validators) { try { validator.validate(t); } catch (ValidationException e) { exceptions.add(e); } } if (!exceptions.is...
93475299_4
@Override public void onCompletion(RecordMetadata metadata, Exception exception) { if (exception != null) { for (SpanDecorator decorator : spanDecorators) { decorator.onError(exception, span); } } try (Scope ignored = tracer.scopeManager().activate(span)) { if (callback != null) { callbac...
93584385_175
public void updateActionOrderState(DelegateExecution exec, CmsActionOrderSimple aos, String newState) { aos.setActionState(OpsActionState.valueOf(newState)); try { if (newState.equalsIgnoreCase(COMPLETE)) { CmsActionOrder ao = cmsUtil.custSimple2ActionOrder(aos); opsProcedurePro...
93609439_0
public static Map<String, Object> getKeys() throws NoSuchAlgorithmException { Map<String, Object> map = new HashMap<>(); KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("RSA"); keyPairGen.initialize(1024); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey publicKey = (RSAPublic...
93627493_4
public static String processMessage(String message, BungeeChatContext context) { final StringBuilder builder = new StringBuilder(); final List<BungeeChatPlaceHolder> placeholders = getApplicableStream(context).collect(Collectors.toList()); processMessageInternal(message, context, builder, placeholders); ...
93642073_6
public boolean isInRegistry(String url) { if (getMockedEndpointsMethod == null) { return false; } Set<String> mockedEndpoints = getMockedEndpoints(); for (String endpoint : mockedEndpoints) { if (endpointMatches(endpoint, url)) { return true; } } return fal...
93647440_7
String resolveVersion(String groupId, String artifactId, String versionSpec) throws InvalidArtifactCoordinateException { List<String> versions; try { versions = requestVersionList(groupId, artifactId, versionSpec); } catch (VersionRangeResolutionException e) { String errorMessage = messageFor...
93682788_19
@Override public void onLoadFinished(Loader<List<Person>> loader, List<Person> data) { // This callback may be called twice, once for the cache and once for loading // the data from the server API, so we check before decrementing, otherwise // it throws "Counter has been corrupted!" exception. if (!Esp...
93754068_10
protected void checkAndInstallConfiguration(String configName) throws IOException { this.checkAndInstallConfiguration(configName, false); }
93782049_221
public static Object parse(final VType value, String text, final FormatOption format) { try { switch (format) { case STRING: return text; case HEX: { // Remove trailing text (units or part of units) text = text.trim(); final int sep =...
93861612_50
private String formatDocString(final String docString) { if (docString == null || docString.isEmpty()) { return ""; } return "\"\"\"" + LINE_SEPARATOR + docString + LINE_SEPARATOR + "\"\"\"" + LINE_SEPARATOR; }
93868467_35
public String index(String key, long index) { return getJedis().lindex(key, index); }
93951167_2
public static LaunchData getLaunchType(String launchUri) { if (launchUri == null) { launchUri = ""; } LaunchData data; if (launchUri.contains(ADD_ISSUER_PATH)) { data = handleAddIssuerUri(launchUri); if (data != null) { return data; } } else if (launchUr...
93973957_0
public void createPacketsFile() { File packetsFile = new File(this.sharedDir, "Packets.txt"); if (packetsFile.exists()) { try { packetsFile.createNewFile(); } catch (IOException e) { log.error("Cannot create", e); } } try (PrintWriter writer = new PrintWriter(new FileOutputStream(packetsFile))) { for ...
94000641_0
@Override public Flowable<List<Question>> loadQuestions(boolean forceRemote) { if (forceRemote) { return refreshData(); } else { if (caches.size() > 0) { // if cache is available, return it immediately return Flowable.just(caches); } else { // else return data from local storage ...
94090559_61
public long getCacheSize() { return mCacheManager.getCacheSize(); }
94165107_13
public <P extends BasePageObject<P>> P newInstance(Class<P> expectedPage, Object... params) { try { // Account for PageObjects that only have a BrowserBasedTest constructor. if (params.length > 0) { Class<?>[] constructorArguments = new Class<?>[2]; constructorArguments[0] =...
94222613_4
@Override public Object value(SpanData spanData) { Object ret = spanData.getBaggageItem(name()); return ret == null ? defaultValue : ret; }
94269521_1
@Override public void onAltKeyClick(CharSequence altKeyText) { final String altKeyString = altKeyText.toString(); final int[] altDigits = mTextModel.altDigits(altKeyString); if (count() <= 2) { insertDigits(altDigits); } if (!is24HourFormat()) { mAmPmState = altKeyString.equalsIgnore...
94284531_10
public String getString(@StringRes int id) throws NotFoundException { return getText(id).toString(); }
94393859_0
public void hello(String name) throws FileNotFoundException { System.out.println(demoService.sayHello(name)); }
94457960_67
@Override public void onMessage(ResponseBody response) { if (response.contentType() != WebSocket.TEXT) { FLog.w( TAG, "Websocket received message with payload of unexpected type " + response.contentType()); return; } try { JSONObject message = new JSONObject(response.string()); int v...
94459145_2
public static Codebook parseCodebookPdf(SupportedCodebook codebookSource) { try (InputStream codebookPdfStream = codebookSource.getCodebookPdfInputStream();) { List<String> codebookTextLines = extractTextLinesFromPdf(codebookPdfStream); Codebook codebook = new Codebook(codebookSource); /* * It's a bit ineff...
94524678_483
public boolean isDisplaySearchRssLinks() { return getLocalBoolean("rss.displaySearchRssLinks", true); }
94570463_0
public static <STATE> Observable<STATE> states(Store<STATE> store) { if (store == null) { throw new IllegalArgumentException("Store is null"); } return Observable.create(new StoreOnSubscribe<>(store), BackpressureMode.ERROR); }
94627909_0
public Call<State> state() { return service.state(); }
94631072_0
@Override public void onAttach(Context context) { super.onAttach(context); FragmentActivity activity = getActivity(); LocationViewModel locationViewModel = getViewModelProvider(activity).get(LocationViewModel.class); LiveData<CommonLocation> liveData = locationViewModel.getLocation(context); liveDat...
94646544_22
public void setTitle(String prefix) { setProperty(TITLE, prefix); }
94742091_0
public static long ip2long( String ip ) { String[] p = ip.split("\\."); if ( p.length != 4 ) return 0; int p1 = ((Integer.valueOf(p[0]) << 24) & 0xFF000000); int p2 = ((Integer.valueOf(p[1]) << 16) & 0x00FF0000); int p3 = ((Integer.valueOf(p[2]) << 8) & 0x0000FF00); int p4 = ((Integer.valu...
94749724_21
@Override public void saveNote(String noteNote, List<Tag> noteTags) { if (isNewNote()) { createNote(noteNote, noteTags); } else { updateNote(noteNote, noteTags); } }