id
stringlengths
7
14
text
stringlengths
1
37.2k
21432552_2
public boolean validate(BidRequest request, BidResponse.Builder response) { return !OpenRtbUtils.removeBids(response, bid -> validate(request, bid)); }
21458450_10
public void removeWindowsEventData(String windowSession, String windowId) { String lookupKey = windowSession + ApplicationLocalStore.OBJECT_DELIMITER + windowId; ApplicationLocalStore.getInstance().deleteAll(lookupKey); }
21462033_32
public void reset(@NonNull final String providerName, @NonNull final Operation operation) { OPFLog.logMethod(providerName, operation); getManagerByOperation(operation).reset(providerName, operation); }
21477166_0
@Override public List<String> tokenize(final String sentence) { return TOKENIZER.tokenize(sentence); }
21499094_4
@Override public StatusCode decodeStatusCode(String field) { if (nextStartElement(field)) { UInteger value = Unsigned.uint(0); if (nextStartElement("Code")) { value = decodeUInt32(null); requireNextEndElement("Code"); } requireNextEndElement(field); ...
21500212_4
public static int getPid() { RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean(); String name = runtime.getName(); // format: "pid@hostname" try { return Integer.parseInt(name.substring(0, name.indexOf('@'))); } catch (Exception e) { return -1; } }
21548299_5
public void transformSensorStringReplacingWithPublicAddressAndPort( final EntityAndAttribute<String> targetToUpdate, final Optional<EntityAndAttribute<Integer>> optionalTargetPort, final Iterable<? extends AttributeSensor<String>> targetsToMatch, final EntityAndAttribute<String> replacem...
21556616_137
public String readLine() { verifyNotClosed(); /* has the underlying stream been exhausted? */ if (pos == end && fillBuf() == -1) return null; for (int charPos = pos; charPos < end; charPos++) { char ch = buf[charPos]; if (ch > '\r') { continue; } if ...
21563363_0
public String[] getAttributes() { return attributes; }
21580302_82
public ComponentFormSet mapUserSubmissionToEntry(SubmissionFormTemplate template, UserSubmission userSubmission) throws MappingException { ComponentFormSet componentFormSet = new ComponentFormSet(); ComponentAll mainComponent = new ComponentAll(); Component component = new Component(); component.setCreateUser(Secu...
21600105_14
List<Snapshot> calculateMissingSnapshots( Collection<Snapshot> sourceSnapshots, Set<SnapshotEntry> availableSnapshots) { List<Snapshot> result = new ArrayList<>(); HashSet<Integer> availableSnapshotNrs = new HashSet<>(); for (SnapshotEntry e : availableSnapshots) { availableSnapshotN...
21621670_3
@Override public boolean validate(AttributedDocumentEvent event) { boolean valid = true; TravelRelocationDocument document = (TravelRelocationDocument) event.getDocument(); // Check to see if from country is selected. If selected from state is required field if (document.getFromCountryCode() != null &...
21631528_12
public String getRegulationEnvironment() { return mRegulationEnvironment; }
21634100_460
protected final void abortIfNeeded() { if (Thread.interrupted()) { try { abort(); // execute subclass specific abortion logic } catch (IOException e) { LogFactory.getLog(getClass()).debug("FYI", e); } throw new AbortedException(); } }
21654705_0
public static List<String> readUNummer(BufferedReader reader) throws IOException { final List<String> uNummern = new ArrayList<>(); String line; while ((line = reader.readLine()) != null) { // use comma as separator String[] record = line.split(CVS_SPLIT_BY); if(record.length > 0 &...
21668967_1
@Override public ElasticsearchQuery<K> where(Predicate... o) { return queryMixin.where(o); }
21691061_0
@Override public PropertiesProcessor getRunnerPropertiesProcessor() { return properties -> { List<InvalidProperty> invalidProperties = new LinkedList<>(); final String serverId = properties.get(Constants.SONAR_SERVER_ID); if (serverId == null) { invalidProperties.add(new Invalid...
21695652_15
public void omitLessFreq() { if (name == null) return; // Illegal int threshold = n_words[0] / LESS_FREQ_RATIO; if (threshold < MINIMUM_FREQ) threshold = MINIMUM_FREQ; Set<String> keys = freq.keySet(); int roman = 0; for(Iterator<String> i = keys.iterator(); i.hasNext(); ){ String...
21741891_3
@Override public TransportClientFactory newTransportClientFactory(Collection<Void> additionalFilters, EurekaJerseyClient providedJerseyClient) { throw new UnsupportedOperationException(); }
21765334_3
public static List<Object[]> parse(CharSequence xml, String... fields) { List<Object[]> list = new ArrayList<>(); StringBuilder sb = new StringBuilder(); if (xml != null && xml.length() != 0) { Map<String, Integer> fieldMap = new HashMap<>(fields.length); for (int i = 0; i < fields.length; i...
21765535_41
public Fight attack(UUID attackerId, UUID defenderId, UUID planetId, Ships attackingShips, Ships defendingShips, long round) { LOGGER.debug("Fight between {} and {}", attackingShips, defendingShips); Ships remainingDefendingShips = fight(attackingShips, defendingShips); Ships remainingAttackingShips = figh...
21770648_34
@Override public List<Message> dequeueOut(String id, int offset) { Validate.notNull(id); Validate.isTrue(offset >= 0); List<byte[]> serializedMessages = outQueue.dequeueOut(id, offset); return serializedMessages.stream() .map(d -> (Message) serializer.deserialize(d)) .collect(to...
21775167_46
public IssuesSearchRequest setRepo(String repo, String userName) { add(new KeyValueStringSearchItem("repo", userName + "/" + repo)); return this; }
21788064_0
public void run() throws IOException { FlatPackageWriterImpl flatPackageWriter = new FlatPackageWriterImpl(0); flatPackageWriter.setDebugOutput(debug); flatPackageWriter.setOutputDirectory(outputDir); Movie movie = new Movie(); for (File input : inputFiles) { System.err.println(input.getAbso...
21797449_58
public static String toRGBCode(final Color color) { return String.format("#%02X%02X%02X", // (int) (color.getRed() * 255), // (int) (color.getGreen() * 255), // (int) (color.getBlue() * 255)); }
21813926_73
@Handler @Override public void onUserLogin(LoginMessage login) { ActivityItem item = ActivityItem.create() .setTitle("User logged in.") .setDescription(String.format("Username: %s", login.getUsername())); getActivityLogger().addActivityItem(item); }
21825681_23
public MapFeature extractMapFeature(Set<String> varIds, RegularGrid targetGrid, Double elevation, DateTime time) throws DataReadingException { GridDomain domain = getDomain(); /* * Find the elevation index, if required */ int zIndex = 0; VerticalAxis zAxis = domain.getVerticalAxis(); ...
21833183_42
@Override public int compare(LayoutElementParcelable file1, LayoutElementParcelable file2) { /*File f1; if(!file1.hasSymlink()) { f1=new File(file1.getDesc()); } else { f1=new File(file1.getSymlink()); } File f2; if(!file2.hasSymlink()) { f2=new File(file2.getDesc()); } else { ...
21858951_204
public static Path toPath(Object candidate) throws IOException, IllegalArgumentException { if (candidate == null) { return null; } if (candidate instanceof Path) { return (Path) candidate; } if (candidate instanceof CharSequence) { URI uri = URI.create(toSafeURI(String.value...
21860658_55
public boolean isAuthorized(final String ip, final String referer) { final String toEvaluate = replaceVariablesInRule(ip, referer); boolean result = false; try { result = (Boolean)SCRIPT_ENGINE.eval(toEvaluate); } catch (ScriptException ex) { LOGGER.log(Level.INFO, "Error trying to evalu...
21871478_109
public static RemoteATCommandPacket createPacket(byte[] payload) { if (payload == null) throw new NullPointerException("Remote AT Command packet payload cannot be null."); // 1 (Frame type) + 1 (frame ID) + 8 (64-bit address) + 2 (16-bit address) + 1 (transmit options byte) + 2 (AT command) if (payload.length < ...
21907146_11
@Override protected Instant extractByIndex(ResultSet r, int index) throws SQLException { final Timestamp timestamp = calendar.isPresent() ? r.getTimestamp(index, cloneCalendar()) : r.getTimestamp(index); return timestamp == null ? null : timestamp.toInstant(); }
21910386_0
public AutoComplete union(AutoComplete other) { if (possibilities.isEmpty()) { return other; } if (other.possibilities.isEmpty()) { return this; } // TODO: Make sure this can't happen. if (!this.prefix.equals(other.prefix)) { throw new IllegalArgumentException("Trying to...
21910720_11
public static User retrieveUser(Directory directoryClient, String userKey) throws IOException { LOG.debug("retrieveUser() - {}", userKey); Directory.Users.Get request = null; try { request = directoryClient.users().get(userKey); } catch (IOException e) { LOG.error("An unknown error occ...
21919832_0
public static String addAtEndIfNotPresent(final String string, final String suffix) { return string == null ? suffix : !string.endsWith(suffix) ? string + suffix : string; }
21921396_10
public static ServiceElement create(final ServiceSignature signature, File configFile) throws IOException, ConfigurationException, ResolverExcep...
21942754_2
@Override public List<ServiceInstance> getInstances(String serviceId) { return getCloudFoundryService().getApplicationInstances(serviceId) .filter(tuple -> tuple.getT1().getUrls().stream().anyMatch(this::isInternalDomain)).map(tuple -> { ApplicationDetail applicationDetail = tuple.getT1(); InstanceDetail in...
21967508_32
public final boolean uploadGlucoseDataSets(List<GlucoseDataSet> glucoseDataSets) { if (glucoseDataSets == null) { return true; } boolean output = true; for (GlucoseDataSet glucoseDataSet : glucoseDataSets) { try { output &= doUpload(glucoseDataSet); } catch (IOExcepti...
21970330_0
@GET @Produces({ "application/json", "application/xml" }) @Path("{id}") public Employee get(@PathParam("id") int id) { if (id < repository.getEmployees().getEmployees().size()) return repository.getEmployees().getEmployees().get(id); else return null; }
21977200_13
String applyReplacements(StringBuilder builder) { boolean prepand = false; if(builder.length() >= 1 && builder.charAt(0) == '\\'){ //our regexpr doesn't work if a special char is at the beginning! builder.insert(0, '_'); prepand = true; } //\c if(builder.indexOf("\\c") != -1){ builder.replace(builder.inde...
21980975_88
@Override public void setBoost(final float b) { nodeQuery.setBoost(b); }
21993347_98
public T withTag(String k, String v) { extraTags.add(new BasicTag(k, v)); return (T) this; }
21996028_0
public String getIssueKey() { return MatcherUtils.singleMatch(desc, "browse/([\\w-]+)"); }
22027221_0
public static int countChars(String string, int character) { int count = 0; int currIndex = 0; while (true) { currIndex = string.indexOf(character, currIndex); if (currIndex == -1) break; ++currIndex; // Start next search from next character ++count; } return count; }
22042780_0
Token next() { if (!hasNextChar()) { return new Token(Type.EOF, currentLineNumber); } char c = getChar(); while (Character.isWhitespace(c)) { if(c == '\n') { currentLineNumber++; } if (!hasNextChar()) { return new Token(Type.EOF, currentLineNumber); } c = getChar(); } if (c == '#') { ...
22045363_246
@Override public int getRasterHeight() { if (height == 0) { try { height = Integer.parseInt(getAttributeValue(AlosAV2Constants.PATH_IMG_NUM_ROWS, AlosAV2Constants.STRING_ZERO)); } catch (NumberFormatException e) { warn(MISSING_ELEMENT_WARNING, AlosAV2Constants.PATH_IMG_NUM_RO...
22080403_1
public static Exhibit create(GenericRecord record) { Schema schema = record.getSchema(); ExhibitDescriptor desc = createDescriptor(schema); List<Object> attrValues = Lists.newArrayListWithExpectedSize(desc.attributes().size()); for (int i = 0; i < desc.attributes().size(); i++) { Object val = record.get(des...
22095939_158
@Override public void configure(Context context) { try { capacity = context.getInteger("capacity", defaultCapacity); } catch(NumberFormatException e) { capacity = defaultCapacity; LOGGER.warn("Invalid capacity specified, initializing channel to " + "default capacity of {}", defaultCapacity); }...
22102786_119
@Override public Result analyze() { checkState(!analyzed); analyzed = true; Result result = analyzeIsFinal(); if (result != Result.OK) return result; return analyzeIsStandard(); }
22104852_1
public void search(IndexSearcher searcher, String fieldName, Query mainQuery, Query filterQuery, Analyzer analyzer, ArrayWindowVisitor visitor, DocIdBuilder docIdBuilder) throws IllegalArgumentException, TargetTokenNotFoundException, IOException { if (mainQuery instanceof Sp...
22130432_10
public static double[] add(double a, double b, double[] result) { double x = a + b; double bv = x - a; double av = x - bv; double br = b - bv; double ar = a - av; if (result != null) { result[0] = ar + br; result[1] = x; return result; } return new double[] { ar + br, x }; }
22248638_1
public static void getClassesWithAnnotation(String packageName, Class<? extends Annotation> annotationClass, ClassVisitor visitor) throws ClassLoadingException { LOGGER.trace("Finding classes with annotation: {}, in package: {...
22254856_57
@Override public Mono<Void> notify(InstanceEvent event) { return Flux.fromIterable(delegates).flatMap((d) -> d.notify(event).onErrorResume((error) -> { log.warn("Unexpected exception while triggering notifications. Notification might not be sent.", error); return Mono.empty(); })).then(); }
22266761_0
public String getMeteringPointName() { return meteringPointName; }
22269384_141
@GET @Path("{datum}") @Produces({MediaType.TEXT_PLAIN, "text/csv", MediaType.APPLICATION_JSON}) public List<IDValue> get(@PathParam("datum") String datum) throws OryxServingException { check(datum != null && !datum.isEmpty(), "Missing input data"); RDFServingModel model = (RDFServingModel) getServingModel(); Inpu...
22289790_6
public static String toString(Throwable error) { if (error == null) return null; StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter); error.printStackTrace(printWriter); return stringWriter.toString(); }
22292873_19
private String getPostContents(String title, String description) { if (StringUtils.isEmpty(title)) { return description; } if (StringUtils.isEmpty(description)) { return title; } return title + "\n\n" + description; }
22318767_3
@NotNull public RequestBuilder<Object> createRequest() { return new RequestBuilder<Object>(transport, mapper); }
22337952_55
@Override public void init() { if (mCache == null) { return; } synchronized (this) { Billing.debug(TAG, "Initializing cache"); mCache.init(); } }
22342877_72
public static byte[] compress(String urlString) throws MalformedURLException { byte[] compressedBytes = null; if (urlString != null) { // Figure the compressed bytes can't be longer than the original string. byte[] byteBuffer = new byte[urlString.length()]; int byteBufferIndex = 0; ...
22344826_5
@Override public void showLoading() { loading = true; notifyShowProgress(); }
22384317_54
@SuppressWarnings({ "unchecked", "rawtypes" }) @RequestMapping( value="${spring.diffsync.path:}/{resource}", method=RequestMethod.PATCH) public Patch patch(@PathVariable("resource") String resource, @RequestBody Patch patch) throws PatchException { PersistenceCallback<?> persistenceCallback = callbackRegistry.find...
22395060_25
;
22412169_0
public static Settings getSettings(ConnectorClusterConfig configuration) { Map<String, String> setting = new HashMap<String, String>(); setting.put(NODE_DATA.getElasticSearchOption(), recoverdOptionValue(configuration.getConnectorOptions(), NODE_DATA)); setting.put(NODE_MASTER.getElasticSearchOption(), rec...
22424494_3
@Override public void afterAgentConfigurationLoaded(@NotNull BuildAgent agent) { try { if ("true".equals(agentConfiguration.getConfigurationParameters().get(OpenstackCloudParameters.AGENT_METADATA_DISABLE))) { LOG.info("Openstack metadata usage disabled (agent configuration not overridden)"); ...
22430910_1
@Override public void configure(final Configurable configurable) { currentState.configure(configurable); }
22441031_2
public String renderPluginDashboard(PluginContext context) { return renderPluginTemplate(context, context.getDashboardPath()); }
22475760_238
public void update() throws SQLException, IOException, AuthorizeException { // Check authorisation canEdit(true); log.info(LogManager.getHeader(ourContext, "update_collection", "collection_id=" + getID())); DatabaseManager.update(ourContext, collectionRow); if (modified) { ...
22527647_2
public List<TailType> getTailTypeFromArgs(String... types) { List<TailType> tailers = new LinkedList<TailType>(); TailType tailType = null; for (String type : types) { if ("".equals(type)) { System.out.println("------------- WARNING -----------------"); System.out.println("--...
22542759_31
public static Builder builder() { return new Builder(); }
22584111_137
public SequenceLookup<ReplaceInstruction> parseConfig() throws IOException { final SequenceLookup<ReplaceInstruction> sequenceLookup = new SequenceLookup<>(ignoreCase); final Set<CharSequence> checkForDuplicateInput = new HashSet<>(); try (final BufferedReader bufferedReader = new BufferedReader(inputStre...
22614011_1
@Override public boolean accepts(@SuppressWarnings("rawtypes") Class type, StatementContext ctx) { return !(type.isPrimitive() || type.isArray() || type.isAnnotation() || BuiltInArgumentFactory.canAccept(type)); }
22661024_1
@Override public String[] keys() throws IOException { /* create the empty array list */ List<String> keys = new ArrayList<String>(); /* build the query */ BasicDBObject sessionKeyQuery = new BasicDBObject(); sessionKeyQuery.put(appContextProperty, this.getName()); /* get the list */ DBCursor mongoSessionKeys...
22686950_5
public static String filter(String input, Map<String, String> variables) { if (variables.isEmpty()) { return input; } if (input == null || input.isEmpty()) { return input; } String current = input; String last = input; while (current.contains("${") && current.contains("}")) { // Replace all...
22693515_14
public OWLAxiom rename(OWLAxiom axiom){ Map<OWLEntity, OWLEntity> renaming = new HashMap<>(); expressionRenamer = new OWLClassExpressionRenamer(df, renaming); boolean multipleClasses = axiom.getClassesInSignature().size() > 1; expressionRenamer.setMultipleClasses(multipleClasses); axiom.accept(this); return renam...
22725357_0
@Override public String fetch(String url) { try{ LOGGER.debug("url:"+url); HtmlPage htmlPage = WEB_CLIENT.getPage(url); String html = htmlPage.getBody().asXml(); LOGGER.debug("html:"+html); return html; }catch (Exception e) { LOGGER.error("获取URL:"+url+"页面出错", e); ...
22734513_237
public void init() { this.serviceRegistrationMap = new ConcurrentHashMap<>(); this.requireConfigMap = new ConcurrentHashMap<>(); this.bundleContext.addBundleListener( this ); for ( Bundle bundle : this.bundleContext.getBundles() ) { this.addBundle( bundle ); } }
22750538_1
public boolean setNodeProperty(Long id, String key, Object value, GraphDatabaseService graphDb) { boolean success = true; // Update the node's property in cache Map<String, Object> node = globalNodeCache.getIfPresent(id); if(node == null) { // The node isn't available in the cache, go to t...
22760763_9
public static RoaringBitmap[] extract(RoaringBitmap bitmap, int[] ukeys) { RoaringArray array = bitmap.highLowContainer; short[] keys = intToShortKeys(ukeys); RoaringBitmap[] extract = new RoaringBitmap[keys.length]; for (int i = 0; i < keys.length; i++) { Container container = array.getContaine...
22789601_112
@CheckReturnValue public <T> JsonAdapter<T> adapter(Type type) { return adapter(type, Util.NO_ANNOTATIONS); }
22790488_229
public String getDetails(Integer id, String... fields) throws Exception { if (fields.length == 0) { return videos.get(id).toString(); } return fieldJsonMapper.toJson(videos.get(id), fields); }
22794824_19
@Override public Map<K, V> next() { final int size = randomValues.randomInteger(sizeRange.lowerBound(), sizeRange.upperBound()); final HashMap<K, V> map = new HashMap<>(); int misses = 0; while (map.size() < size) { final int sizeBeforePut = map.size(); final K key = generatorOfK.next()...
22815625_10
public static double evaluatePolynomial(double x, double[] coefficients) { double value = 0.0; for (int i = 0; i < coefficients.length; i++) value = value * x + coefficients[i]; return value; }
22824768_4
public CFScriptStatement parseScript(String cfscript) throws ParseException, IOException { CommonTokenStream tokens = createTokenStream(cfscript); ScriptBlockContext scriptBlockContext = parseScriptBlockContext(tokens); CFScriptStatement result = scriptVisitor.visit(scriptBlockContext); if (result != null) result...
22829409_13
public <T extends Row<?>> Paginated<T> searchBySQLWithPager(@NonNull final Class<T> klass, final String sql, final List<Object> params, final long entriesPerPage) { return searchBySQLWithPager(klass, sql, params, entriesPerPage, getReadConnection()); }
22835310_14
public Level fromString(String[] string) { Tile[][] field; Level level = new Level(); int indexOfProperties = 0; for (; string[indexOfProperties].charAt(0) != '#'; indexOfProperties++) { switch (indexOfProperties) { case 0: level.setId(Integer.parseInt(string[0])); ...
22880877_4
@Nullable public static String SHA1(String text) { try { final MessageDigest md = MessageDigest.getInstance("SHA-1"); //noinspection CharsetObjectCanBeUsed - NOTE fix not applicable on API16 md.update(text.getBytes("iso-8859-1"), 0, text.length()); final byte[] sha1hash = md.digest()...
22882266_64
@Override public void serviceChanged( ServiceEvent serviceEvent ) { if ( referenceToInstanceMap.containsKey( serviceEvent.getServiceReference() ) ) { Object instance = referenceToInstanceMap.get( serviceEvent.getServiceReference() ); LifecycleEvent type = LifecycleEvent.MODIFY; switch( serviceEvent.getTy...
22910855_18
@Override public String toString() { String endToConcatenate = end != null ? " - " + end : ""; return start + endToConcatenate; }
22917907_1
public String enrichQueryString(String queryString) { nt maxRange = getMaxRange(); eturn enforceRange(enforceRange(queryString , maxRange, fromRangePattern, "from", false), maxRange, toRangePattern, "to"); }
22930887_252
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { process(request, response); }
22944710_75
@Override public boolean remove(final Object o) { if (delegate.remove(o)) { listener.onElementsRemoved(); return true; } return false; }
22944796_124
@Override public byte getType() { return OP_TYPE_DELETE_RESPONSE; }
22944804_331
public static Packet toPacket(byte[] octets) { // for old byte array approach we may have a array longer than packet so trim ByteBuffer down to just // packet length to prevent attribute parsing below from running off the end of the packet and onto unrelated // octets. length is 3rd/4th octets in big endian...
22948530_116
@GET @Path("{type: "+ ALL_TYPES_PATTERN + "}/_search") @Produces(MediaType.APPLICATION_JSON) public final Response search(@PathParam("type") String type, @QueryParam("q") String query) { if (isBlank(query)) { return Response.status(Response.Status.BAD_REQUEST).build(); } switch (type) { case...
22964867_319
@Override public void apply(final DatabaseTemplate databaseTemplate) throws Throwable { final T item = item(); item.setVersion(item.getVersion() - 1); try { databaseTemplate.update(item); } catch (final PersistenceException e) { handlePersistenceException(e); } }
22970701_2
public RawParameters extract(final HttpServletRequest request) { final Map<String, String> contextMap = extractAllVars(request, contextList, PREFIX_VARIABLE_STRING_FUNCTION, true); final Map<TestType, String> identifierMap = extractAllVars(request, identifierList, IDENTIFIER_TEST_TYPE_FUNCTION, false); che...
22974847_14
@Override public List<String> getSuggestions(String prefix) { List<String> suggestions = Lists.newArrayList(); String test = simplify(prefix); for (T entry : enumClass.getEnumConstants()) { String name = simplify(entry.name()); if (name.startsWith(test)) { suggestions.add(entry....
22981257_263
static double diff(double a, double b) { Preconditions.checkArgument(a >= 0 && a < 360); Preconditions.checkArgument(b >= 0 && b < 360); double value; if (a < b) value = a + 360 - b; else value = a - b; if (value > 180) return 360 - value; else return value; ...
23001404_7
@Override public String run() { LOGGER.debug("run: enitty={}, version={}, status={}", entity, version, status); Error.reset(); Error.push(getClass().getSimpleName()); Error.push(entity); Error.push(version); try { MetadataStatus st = MetadataParser.statusFromString(status); Metad...