id
stringlengths
7
14
text
stringlengths
1
37.2k
116402868_2
@Nonnull @Override public List<Endpoint> generateEndpoints() { return endpoints; }
116500263_0
public static Set<WeatherForecastPerDay> calculateWeatherForDays(WeatherForecastDbHelper.WeatherForecastRecord weatherForecastRecord) { Set<WeatherForecastPerDay> result = new HashSet<>(); Calendar forecastCalendar = Calendar.getInstance(); int initialYearForTheList = forecastCalendar.get(Calendar.YEAR); ...
116522300_55
@Override public void executeMigration(Datastore datastore) { PriceList priceList = datastore.createQuery(PriceList.class).field("lotteryIdentifier").equal(German6aus49Lottery.IDENTIFIER).get(); if (priceList == null) { priceList = new PriceList(); } priceList.setLotteryIdentifier(German6aus49Lo...
116565956_0
@Override public List<SubjectDto> questionsToSubjectsDto(List<Question> questions) { Assert.notNull(questions, "Cannot map a null list of questions to a list of subject dtos"); Multimap<Subject, Question> multimap = Multimaps.index(questions, Question::getSubject); return multimap.keySet().stream().map(subject ...
116678593_1
public static CombinedVariablesSource forSources(List<String> sourceNames, InstallHookLogger logger, InstallContext context) { List<VariablesSource> sources = new ArrayList<VariablesSource>(); for (String string : sourceNames) { if(string.equals(OsEnvVarsSource.NAME)) { sources.add(new OsEnv...
116714930_15
protected long getLastCommittedOffset() { OffsetAndMetadata lastCommittedOffset; try { lastCommittedOffset = consumer.committed(topicPartition); } catch (KafkaException e) { throw new IllegalStateException("Unable to retrieve committed offset for topic partition [" + topicPartition + "]", e)...
116798721_0
private DateUtils() { }
116999027_941
public boolean add(String queryId, String userId, QueryLogic<?> logic, Connector cxn) { Triple value = new Triple(userId, logic, cxn); long updateTime = System.currentTimeMillis(); return cache.putIfAbsent(new Pair<>(queryId, updateTime), value) == null; }
117019016_55
public void process(HttpRecordingDocument result) throws IOException { try { final Transformer transformer = m_transformerFactory .newTransformer(new StreamSource(m_styleSheetInputStream)); // One might expect this to be the default, but it's not. transformer.setErrorListener(m_transformerFactor...
117054584_7
@Override public String getPath(String key) { return getNodePath(key, null); }
117060928_69
@Override public void onMessage(String text) { try { JSONObject message = new JSONObject(text); int version = message.optInt("version"); String method = message.optString("method"); Object id = message.opt("id"); Object params = message.opt("params"); if (version != PROTOCOL_VERSION) { ...
117076526_0
public void add(@Valid User newUser) { em.persist(newUser); }
117088815_195
@Transactional @Nonnull @Override public T updateNotificationState(@Nonnull final Long notificationId, @Nonnull final NotificationState notificationState) { assertNotificationIdNotNull(notificationId); Assert.notNull(notificationState, "Notification state should not be null"); LOGGER.debug("Updating notific...
117093610_4
public static String formatBalanceFullPrecision(final long amount) { return XLM_PRECISION_FORMATTER.format(stroopToXLM(amount)); }
117128136_21
@Override public SimpleNode moveTo(String nodeQuery, String... keys) { SimpleNode javaSourceNode=new JavaSourceNode(this,nodeQuery,keys); optionalStartNode(javaSourceNode); return javaSourceNode; }
117143344_15
public static boolean isInteger(String s) { try { Integer.parseInt(s); } catch (NumberFormatException e) { return false; } return true; }
117200555_0
@GetMapping public List<Holding> getHoldings(Principal principal) { User user = client.getUser(principal.getName()); String holdingsFromOkta = (String) user.getProfile().get(HOLDINGS_ATTRIBUTE_NAME); List<Holding> holdings = new LinkedList<>(); if (holdingsFromOkta != null) { try { ...
117255089_189
public static float getFloat(Object value) { return getFloat(value, Float.NaN); }
117256380_1
public static List<Integer> positive(List<Integer> vals) { return vals.stream().filter(val -> val > 0).collect(Collectors.toList()); }
117353090_4
static Position calculateCentre(Disk m, Disk n, double angle) { angle = correctAngle(angle); if (angle == 0 || angle == 360) { return new Position(m.getPosition().x, m.getPosition().y + n.getRadius() + m.getRadius(), n.getPosition().z); } else if (0 < angle && angle < 90) { double c = n.getR...
117357780_257
@Override public long upload(String sid, Long docId, Long folderId, boolean release, String filename, String language, DataHandler content) throws Exception { validateSession(sid); if (docId != null) { checkout(sid, docId); checkin(sid, docId, "", filename, release, content); return docId; } else { WSDocu...
117452304_11
@Override public Position clone() { return new Position(x, y, angle); }
117474465_9
@Override public void getRepo(@NonNull String owner, @NonNull String repo) { checkViewAttached(); getMvpView().showMessageView(false); getMvpView().showProgress(true); getDataManager().getRepo(owner, repo) .observeOn(schedulerProvider.ui()) .subscribeOn(schedulerProvider.io()) ...
117550735_65
void activate(@NonNull KeyPair account) throws OperationFailedException { verifyParams(account); AccountResponse accountResponse; try { accountResponse = getAccountDetails(account); if (kinAsset.hasKinTrust(accountResponse)) { return; } SubmitTransactionResponse r...
117598163_0
@Override public void clear() { this.values().parallelStream().forEach(closable -> { releaseResources(closable); }); super.clear(); }
117664267_205
@Nonnull public static Builder builder() { return new AutoValue_CreationScheme.Builder(); }
117711019_4
@Override public boolean isEmpty() { final Image image = getImage(); if (StringUtils.isBlank(name)) { // Name is missing, but required return true; } else if (occupations == null || occupations.isEmpty()) { // At least one occupation is required return true; } else i...
117755974_0
public List<Integer> optimizeConstraints() { List<Integer> result = new ArrayList<>(); optimizeConstraints(result); return result; }
117915559_10
@Override public List<PermissionEntity> findPermissions() { return userDAO.findPermissions(); }
117965972_5
@Override public boolean isSupported() { String versionJson = version(); if (StringUtils.isBlank(versionJson)) { throw new RuntimeException("Cannot get the version!"); } String version = JSON.parseObject(versionJson).getString("version"); if (StringUtils.isBlank(version)) { return fa...
117978265_8
@Override public void onApplicationEvent(ApplicationEnvironmentPreparedEvent event) { /** * Gets Logger After LoggingSystem configuration ready * @see LoggingApplicationListener */ final Logger logger = LoggerFactory.getLogger(getClass()); ConfigurableEnvironment environment = event.getEnvi...
118104847_0
public static boolean hasPermissions(@NonNull Context context, @Size(min = 1) @NonNull String... perms) { // Always return true for SDK < M, let the system deal with the permissions if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) { Log.w(TAG, "hasPermissions: API ...
118151375_4
@Override public AppraisalStatus validatePlatformCredentialAttributes( final PlatformCredential platformCredential, final DeviceInfoReport deviceInfoReport, final EndorsementCredential endorsementCredential) { final String baseErrorMessage = "Can't validate platform credential attributes wit...
118198720_1
String traitsToDataFormat(final boolean onlyFromProperty) { boolean isArray = false; boolean isBig = false; boolean isSmall = false; boolean isInteger = false; boolean probablyJson = false; Enum<CdmDataFormat> baseType = CdmDataFormat.Unknown; final CdmTraitCollection traits = this.getTraits(); if (tr...
118261543_81
public WishlistDataDto build(CSVRecord csvRecord) throws ImportException { try { return new WishlistDataDto( formatLong(getId(csvRecord)), formatInteger(csvRecord.get("movie_id")), csvRecord.get("title"), csvRecord.get("poster_path"), ...
118323013_0
@Command(MSG_SEARCH_FOR_CITY_RESULT) void onSearchForCityResult(Optional<City> foundCity) { foundCity.map(this::addNewFavoriteCityAndSaveToPreferences) .defaultIfEmpty(false) .whenNot(Boolean::booleanValue) .then(searchForCityFailure::onNext) .invoke(() -> searchCityI...
118375319_0
@Override protected IcyHttpDataSource createDataSourceInternal(@NonNull HttpDataSource.RequestProperties defaultRequestProperties) { return new IcyHttpDataSource.Builder(callFactory) .setUserAgent(userAgent) .setContentTypePredicate(contentTypePredicate) .setCacheControl(cacheCon...
118421344_71
@SuppressWarnings("deprecation") /* package */ static void setConnectionParametersForRequest(HttpURLConnection connection, Request<?> request) throws IOException, AuthFailureError { switch (request.getMethod()) { case Method.DEPRECATED_GET_OR_POST: // This is the deprecated way that need...
118477931_0
public boolean cmp(Value o) { if (o == null) { return false; } if (rlp != null && o.rlp != null) { return Arrays.equals(rlp, o.rlp); } else { return Arrays.equals(this.encode(), o.encode()); } // return DeepEquals.deepEquals(this, o); }
118478361_3
@Override public void execute() throws MojoExecutionException { checkMandatoryField(inputFileDirectory, "inputFileDirectory"); checkMandatoryField(outputFileDirectory, "outputFileDirectory"); this.getLog().info(String.format("Transforming '%s' to '%s' ...", this.inputFileDirectory, this.outputFileDirectory...
118497841_326
public Credential retrieve() throws IOException, CredentialHelperUnhandledServerUrlException, CredentialHelperNotFoundException { boolean isWindows = systemProperties.getProperty("os.name").toLowerCase(Locale.ENGLISH).contains("windows"); String lowerCaseHelper = credentialHelper.toString().toLowe...
118602757_0
void applyStyle(@NonNull TextView textView) { for (Map.Entry<TextStyle, Object> entry : values.entrySet()) { switch (entry.getKey()) { case SIZE: { final float size = (float) entry.getValue(); applyTextSize(textView, size); } break; ...
118737633_1
public static void stop() { Socket socket = null; SocketAddress addr = null; OutputStream out = null; try { addr = new InetSocketAddress("127.0.0.1", MY_APP_PORT ); socket = new Socket(); socket.setSoTimeout( 3*1000 ); socket.connect( addr ); out = socket.g...
118738606_4
public void putAll(XCLLongLongMap map) { if (put == null) put = this::put; map.forEach(put); }
118768968_4
@Override public Record single() throws NoSuchRecordException { if (!iterator.hasNext()) { throw new NoSuchRecordException("Cannot retrieve a single record, because this result is empty."); } Record next = next(); if (iterator.hasNext()) { throw new NoSuchRecordException("Expected a re...
118781792_9
boolean isAngleAcceptable() { MultiFingerDistancesObject distancesObject = pointersDistanceMap.get(new PointerDistancePair(pointerIdList.get(0), pointerIdList.get(1))); // Takes values from 0 to 180 double angle = Math.toDegrees(Math.abs(Math.atan2( distancesObject.getCurrFingersDiffY(), distancesObject....
118782609_5
public static void main(String[] args) throws Exception { Comparator<LogEvent> sort = LogParser.sortByStart; boolean statistics = false; boolean printInlining = false; boolean cleanup = false; boolean trapHistory = false; boolean printTimeStamps = false; boolean compare = false; boolean ...
118787197_1
public long _calculateTimestamp(long offset) { return this.startTimestamp + offset; }
118799500_3
public static boolean isResourceMap(String namespace) { boolean is = false; if(namespace != null && !namespace.trim().equals("")) { getNamespaces(); if(resourceMapNamespaces != null && resourceMapNamespaces.contains(namespace)) { is = true; } } return is; }
118824988_0
public List<PlayedWord> getPlayedWords() { return playedWords; }
118866992_1
public static String getConn(String url) throws Exception { HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); conn.setRequestMethod(GET); conn.setConnectTimeout(CONNECT_TIMEOUT); conn.setReadTimeout(READ_TIMEOUT); conn.setDoInput(true); conn.setDoOutput(true); conn...
118885653_1
@GetMapping("/users") public List<User> getUsers() { return usersService.getUsers(); }
118963036_1
;
118998719_2
@Override public void customize(ConfigurableEmbeddedServletContainer container) { MimeMappings mappings = new MimeMappings(MimeMappings.DEFAULT); // IE issue, see https://github.com/jhipster/generator-jhipster/pull/711 mappings.add("html", MediaType.TEXT_HTML_VALUE + ";charset=utf-8"); // CloudFoundry i...
119147365_6
public void add(TYPE type, int value) { if (type == MINUTE) value *= 60; if (type == HOUR) value *= 3600; value += toSeconds(); switch (type) { case SECOND: second = (value % 3600) % 60; case MINUTE: minute = (value % 3600) / 60; case HOUR: ho...
119281902_3
public Geometry read(String string) { try { JSONObject json = new JSONObject(string); String type = json.getString(TYPE); switch (type) { case "Feature": return createFeature(json); case "FeatureCollection": Geometry[] features = createFeatures(json.getJSONArray(FEATURES)); return factory.cr...
119369247_14
public static <T> LiteObserverFactory<T> with(T item) { return new LiteObserverFactory<>(item); }
119475284_25
public static byte[] Hmac(byte[] data, String algorithm, byte[] key) { SecretKey secretKey = new SecretKeySpec(key, algorithm); Mac mac = null; try { mac = Mac.getInstance(algorithm); mac.init(secretKey); return mac.doFinal(data); } catch (NoSuchAlgorithmException|InvalidKeyExcep...
119531923_16
public static String convertMillisToMinSecFormat(long millis) { long ms = millis % 1000; long s = (millis / 1000) % 60; long m = ((millis / 1000) / 60) % 60; if (s > 0 && m <= 0) { return String.format("%d sec %d ms", s, ms); } else if (s > 0 || m > 0) { return String.format("%d min ...
119633513_2
@Override public int getItemCount() { if (cursor == null) { return 0; } else { return cursor.getCount(); } }
119644903_0
public static SSLContext pinSha256SSLContext(final Stream<String> sha256Pins) { return sslContext(pinSha256TrustManager(sha256Pins)); }
119702819_35
@Override public boolean validate() { log.info("Validating DeadLetterConfig..."); if (deadLetterExchange != null && deadLetterExchange.validate()) { log.info("DeadLetterConfig configuration validated successfully for deadLetterExchange '{}'", deadLetterExchange); return true; } log.error("Invalid DeadLe...
119727871_28
public static Options parsePattern(String pattern) { char opt = ' '; boolean required = false; Class<?> type = null; Options options = new Options(); for (int i = 0; i < pattern.length(); i++) { char ch = pattern.charAt(i); // a value code comes after an option and specifies ...
119737924_5
public void setEmail(String mail) throws InvalidEmailException { this.email = mail; }
119759931_4
public String path(final TokenMatcher.State state) { return match(state, "path"); }
119819447_306
@Deprecated public void visitMethodInsn( final int opcode, final String owner, final String name, final String descriptor) { int opcodeAndSource = opcode | (api < Opcodes.ASM5 ? Opcodes.SOURCE_DEPRECATED : 0); visitMethodInsn(opcodeAndSource, owner, name, descriptor, opcode == Opcodes.INVOKEINTERFACE); }
119873830_2
public String awesome(String who) { return "Awesome! " + checkNotNull(who); }
119921993_7
public static String convertFieldsToColumns(EntityMeta entityMeta, String sql) { String key = entityMeta.getTableName() + sql; // 从缓存中直接获取,避免每次都处理提升效率 if (convertSqlMap.contains(key)) { return convertSqlMap.get(key); } String[] fields = entityMeta.getFieldsArray(); StringBuilder sqlBuff = new StringBuilder(); ...
119975005_5
@Override public Worker editWorker(String login, Worker editedWorker) throws BaseException { Worker worker = workerRepository.findWorkerByLogin(login); if (worker == null) { throw new WorkerDontExistsException("Edited worker dont exists"); } return workerRepository.updateWorker(new Worker(login,...
120003293_2
public static Builder always() { return new Builder(t -> true); }
120074273_7
public List<Integer> retrieveOutputIndexesFromScript(byte []scriptBytes) throws ParseException { List<Integer> indexes = new ArrayList<>(); if (!isValidColuScript(scriptBytes)) { return indexes; } int offset = OPCODE_OFFSET; //we don't have issue byte in transfer and burn transactions ...
120152712_6
public XMLDsigVerificationResult VerifyXMLDSig(InputStream fileStream) { XMLDsigVerificationResult result = new XMLDsigVerificationResult(); try { //Signature will also be validated in this call, if it fails an exception is thrown //No point to validate the certificate is this signature is i...
120272671_0
@Nullable public OrderList getAllCachedOrderHistory() { return cachedOrderList; }
120274146_0
public boolean isValidPassword(String password) { Pattern p = Pattern.compile("^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=\\S+$).{8,}$"); Matcher m = p.matcher(password); if (m.find()) return true; return false; }
120363922_2
@Nullable public <T> T getInstanceWithoutAncestors(String name, Class<T> type) { try { return BeanFactoryUtils.beanOfType(getContext(name), type); } catch (BeansException ex) { return null; } }
120417004_1
@Override public void parse(String data, ParseCallback<String[][]> parseResult) { // clear cached instances on each time parse is called rows = null; titleRow = null; totalColumns = 0; Row[] lines; try { lines = getRows(data); } catch (ColumnsLengthException e) { parseResu...
120471283_161
public List<Role> findAll() { List<Role> result = new ArrayList<>(); try (Connection connect = CON.getConnect(); Statement st = connect.createStatement(); ResultSet rstSet = st.executeQuery(QUERIES.getProperty("findAllRoles"))) { while (rstSet.next()) { Role role = new Role...
120487379_34
public List<Builder> build(Domain domain, DomainTypeResolver domainTypeResolver) { final List<Type> domainTypes = domain.getTypes(); List<TypeHandlerResult> result = new ArrayList<>(); if (CollectionUtils.isNotEmpty(domainTypes)) { for (Type type : domainTypes) { result.add(buildType(type, domain, doma...
120578437_0
@PostMapping(value = "/list") @Log(name = "图书管理", value = "查询图书") @ApiOperation(value = "查看图书列表", notes = "可以通过查询条件查询图书列表,包括分页信息") @ApiPageable public ApiResult<Page<BookDto>> list(Pageable pageable, @RequestBody @Valid @ApiParam("查询参数") SearchBookParam searchParam, @ModelAttribute("user") User user) { System.out.prin...
120606464_2
@Asynchronous public Future<Boolean> timeout(boolean shouldTimeout) { Boolean timedOut = false; if (shouldTimeout) { try { // Simulate a long running query Thread.sleep(AWAIT); } catch (InterruptedException ex) { timedOut = true; } } ...
120684055_76
public PoRevision getRevision() { return this.revision; }
120756407_1
public static CompositeBuffer newBuffer() { return BuffersBuffer.create(); }
120761297_9
@Override public User apply(UserRaw userRaw) { return User.builder() .login(notNullOrEmpty(userRaw.login())) .id(userRaw.id()) .avatarUrl(notNullOrEmpty(userRaw.avatarUrl())) .url(notNullOrEmpty(userRaw.url())) .htmlUrl(notNullOrEmpty(userRaw.htmlUrl())) ...
120778005_2
@Nullable @Override public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) type; if (p...
120780458_0
public Collection<Book> getFirstAvailableBooks(final String keyword) { return new GetFirstAvailableBooks(emf, keyword).transact(); }
120905144_6
protected static List<ProcSmaps> parseSmaps(String output) { String[] lines = output.split("\n"); List<ProcSmaps> res = new ArrayList<>(); ProcSmaps.Builder builder = null; for (String line : lines) { line = line.trim(); Matcher address = ADDRESS_PATTERN.matcher(line); if (addr...
120961330_12
public static Set<String> getResourceReferences(Collection<? extends Message> resources) { final ImmutableSet.Builder<String> refs = ImmutableSet.builder(); for (Message r : resources) { if (r instanceof ClusterLoadAssignment || r instanceof RouteConfiguration) { // Endpoints have no dependencies. ...
120970441_39
public static Schema beamSchemaToBigQueryClientSchema( org.apache.beam.sdk.schemas.Schema tableSchema) { ArrayList<Field> bqFields = new ArrayList<>(tableSchema.getFieldCount()); for (org.apache.beam.sdk.schemas.Schema.Field f : tableSchema.getFields()) { bqFields.add(beamFieldToBigQueryClientField(f)); ...
121075789_4
public String greet(String name) { return Util.join("Hello ", name); }
121110666_1
public static List<Date> getMonthDates(int year, int month) { long curTime = System.currentTimeMillis(); LocalDate localDate = new LocalDate(year, month, 1); List<Date> dates = new ArrayList<>(); while (localDate.getMonthOfYear() <= month && localDate.getYear() == year) { dates.addAll(getWeekD...
121151622_4
protected boolean isChild(INode node) { INode parent = node.getParent(); while (parent != null) { if (parent == this) { return true; } parent = parent.getParent(); } return false; }
121153885_0
public static int getExpectedLength(@NotNull McuMgrScheme scheme, @NotNull byte[] bytes) throws IOException { if (scheme.isCoap()) { throw new UnsupportedOperationException("Method not implemented for CoAP"); } else { if (bytes.length < McuMgrHeader.HEADER_LENGTH) { throw new...
121218280_1
public static double computeRms(float[] signal) { double sum = 0; for (double aSignal : signal) { sum += aSignal * aSignal; } return Math.sqrt(sum / signal.length); }
121236494_125
;
121247108_26
public static List<Integer> sort(List<Integer> sourceDatas) { switch (sourceDatas.size()) { case 0: // Base Case return new ArrayList<>(); case 1: // Base Case return sourceDatas; default: int pivot = sourceDatas.get(0); // pivot, 枢轴 List<Inte...
121312281_8
@Override public void onStartup(ServletContext servletContext) throws ServletException { if (env.getActiveProfiles().length != 0) { log.info("Web application configuration, using profiles: {}", (Object[]) env.getActiveProfiles()); } EnumSet<DispatcherType> disps = EnumSet.of(DispatcherType.REQUEST, ...
121320887_3
public CursorPoint getCursorPointScaledBy(double scaleFactor) { return (new CursorPoint((int) (this.x * scaleFactor), (int) (this.y * scaleFactor), (int) (delay * scaleFactor))); }
121349361_3
@Override public APIGatewayProxyResponseEvent handleRequest(APIGatewayProxyRequestEvent request, Context context) { String who = "World"; if ( request.getPathParameters() != null ) { String name = request.getPathParameters().get("name"); if ( name != null && !"".equals(name.trim()) ) { who = name; ...
121391917_16
@Override public CompletionStage<Envelope> preProcess(Envelope envelope) { try { var rawValue = envelope.getRawValue(); final JsonNode event; final String eventType; if (rawValue instanceof CloudEvent) { var cloudEvent = (CloudEvent<?, ?>) rawValue; var medi...
121405227_0
@Override protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception { while (in.readableBytes() >= length){ ByteBuf byt = in.readBytes(length) ; out.add(byt) ; } }