id
stringlengths
7
14
text
stringlengths
1
37.2k
20076963_0
public BasicScript(String text) { super(); buffer.append(text); setupImports(); }
20127629_1
public void setName(String name) { this.name = name; }
20132937_2
public String getName() { return name; }
20147131_4
@Override public <T> T unwrap(Class<T> clazz) { return AtmosphereResource.class.isAssignableFrom(clazz) ? clazz.cast(resource) : null; }
20171642_88
public static Builder newBuilder() { return new Builder(); }
20175098_0
@Override public Bitmap transform(Bitmap source) { if (Build.VERSION.SDK_INT < 17) { return source; } RenderScript rs = RenderScript.create(mContext); Allocation input = Allocation.createFromBitmap(rs, source, Allocation.MipmapControl.MIPMAP_NONE, Allocation.USAGE_SCRIPT); Allocation ou...
20186069_20
@Override public byte[] countersign(final byte[] sign, final String algorithm, final CounterSignTarget targetType, final Object[] targets, final PrivateKey key, final Certificate[] certChain, final Properties xParams) throws AOException { // Si no se ha definido nodos objeto de la contrafirma se definen l...
20213217_6
public static HashMap<String, String> getCertificateInfos(File file) { Certificate[] certs; HashMap<String, String> hashMap = new HashMap<>(); try { certs = getCertificates(file); for (Certificate cert : certs) { hashMap.put(getCertMd5(cert), getCertSubject(cert)); } ...
20214352_40
public BuildState setAllEnabled(){ for (BuildStateEnum state : states.keySet()){ switch (state){ case BUILD_BROKEN: disable(state); break; case BUILD_FIXED: disable(state); break; default: enable(state); break; } } return this; }
20216746_5
public static boolean isStaxResult(Result result) { return (result instanceof StaxResult || (jaxp14Available && Jaxp14StaxHandler.isStaxResult(result))); }
20227177_0
@Override public void onDataPushed(Collection<E> dataCollection) { persistenceStrategy.add(dataCollection); }
20236504_1
public String text2number(String snumber) { // UK "and" hundreds/thousands/tens/units separator "five hundred and six" // UK/US "-" is tens and units separator // UK magnitudes are singular. Plural (milions) is informal/indefinite (e.g., there were millions of people) // eleven hundred == 1100 (correc...
20248084_1
public void execute() { validate(); // find all files for (Path path : paths) { for (String includedFile : path.list()) { String filename = includedFile.replace('\\', '/'); filename = filename.substring(filename.lastIndexOf("/") + 1); if (file.equals(filename) && ...
20249391_68
public static Method[] getMethods(Class<?> clazz, String... methodNames) { return WhiteboxImpl.getMethods(clazz, methodNames); }
20256052_0
private void injectVariables(Map<String, String> variables, Statement statement) { if (statement instanceof VariablesAware) { ((VariablesAware) statement).setVariables(variables); } }
20281385_0
public static String getProperty(String str) { String value = ""; String defaultValue = ""; if( !StringUtils.isNullOrEmpty(str) && str.startsWith("${") && str.endsWith("}") ) { String variable = str.trim().substring(2, str.length()-1); if( variable.contains(":") ) { defaultValue...
20303761_199
public boolean prepare(final RegionServerServices services) { if (!region_a.getTableDesc().getTableName() .equals(region_b.getTableDesc().getTableName())) { LOG.info("Can't merge regions " + region_a + "," + region_b + " because they do not belong to the same table"); return false; } if (reg...
20320123_137
public static Tracer trace(String desc, Parameter... parameters) { TraceCollector collector = _tracer.get(); if (collector == null) { return DO_NOTHING; } TracerImpl tracer = new TracerImpl(desc, parameters, collector.getNextId(), collector.getScope()); collector.add(tracer); return tracer; }
20321029_18
public ZonedDateTime nextTimeAfter(ZonedDateTime afterTime) { // will search for the next time within the next 4 years. If there is no // time matching, an InvalidArgumentException will be thrown (it is very // likely that the cron expression is invalid, like the February 30th). return nextTimeAfter(aft...
20332528_2
public void execute(String path) { execute(path, (String) null, (Type) null, (Callback) null); }
20336406_9
public void addListener(AchievementListener listener) { listeners.add(listener); }
20337377_1
public String getMessage() { return "Hello World!"; }
20354740_11
public static Builder builder() { return new Builder(); }
20356428_5
@Override public <R> R enterContentOperationMode(ContentOperationMode<R> operationMode) { AbstractContentOperationModeHandler<?> handler; if (operationMode == ContentOperationMode.PASS_TROUGH) { handler = new PassThroughContentHandler(); } else if (operationMode == ContentOperationMode.SIMPLE) { ...
20357183_1
public BindingConfiguration addBinding(BindingConfiguration configuration){ JabbotConfiguration jabbotConfiguration; try { jabbotConfiguration = mapper.readValue(resource,JabbotConfiguration.class); } catch (IOException e) { logger.warn("unable to read source config, creating a new one"); jabbotConfiguration =...
20374886_5
public boolean matches(CharSequence rawPassword, String encodedPassword) { if (encodedPassword == null || encodedPassword.length() == 0) { logger.warning("Empty encoded password"); return false; } if (!BCRYPT_PATTERN.matcher(encodedPassword).matches()) { logger.warning("Encoded password does not look like BCr...
20426356_0
@POST @Consumes("application/json") @Produces("application/json") public Bid addBid(Bid bid) { return bidService.addBid(bid); }
20432793_28
@Override public AWSRunInstancesOptions asType(String type) { launchSpecificationBuilder.instanceType(type); return AWSRunInstancesOptions.class.cast(super.asType(type)); }
20433857_36
public AddressMappingSet xtreemfs_address_mappings_get(InetSocketAddress server, final Auth authHeader, final UserCredentials userCreds, final String uuid) throws IOException, InterruptedException { return xtreemfs_address_mappings_get(server, authHeader, userCreds, uuid, maxRetries); }
20439978_2
;
20444986_95
public ParseBaseNode parse(String query) { // parse string to AST by antlr parser CommonTree queryTree = parseAST(query); // parse AST to query node list try { ParseBaseNode rootNode = parseQuery(queryTree, query); rootNode.validate(parseContext); // post validation actions that ...
20456181_2
@Override public ServerStats choose(List<ServerStats> availableServerStats) { int index = random.nextInt(availableServerStats.size()); return availableServerStats.get(index); }
20473418_5
@Override public DataValue getDataValue() { return new DataValue(columnRule.getType(), String.valueOf((counter.getAndIncrement() % (maxValue - minValue + 1)) + minValue)); }
20499820_5
@NonNull @WorkerThread public CallResult<Depth> depth(@NonNull String pair) { final String serverPair = PairUtils.localToServer(pair); final String url = hostUrl + "/api/3/depth/" + serverPair; JsonObject response = guestApi.call(url); CallResult<Depth> result = new CallResult<>(); if (response == n...
20501508_0
public void updateIntModel(AjaxBehaviorEvent event) { intModel.setValue(intModel.getValue() + UPDATE_INT_VALUE); eduContext.update("int-model-changed"); }
20517345_6
@Override public void init(FilterConfig config) throws ServletException { String headerName = config.getInitParameter(CORRELATION_ID_HEADER_NAME_PARAM); if (headerName == null) { LOG.debug("Parameter {} not configured via filter config.", CORRELATION_ID_HEADER_NAME_PARAM); } else { this.correlationIdHttp...
20522047_10
@Override public <T> void updateOrCreateDTOList(List<T> toUpdate, KeySet keySet, JsonWriter<T> jsonWriter, List<Long> oids) { int i = 0; for (T type : toUpdate) { final String key = keySet.createKey(String.valueOf(oids.get(i))); localStorage.setItem(key, jsonWriter.toJson(type)); i++; } localStorage.setItem(k...
20530482_7
public static boolean match(Writable value, String regex) { if (value == null) { return false; } String valueStr = value.toString(); if (valueStr == null || valueStr.length() == 0) { return false; } // TODO: Remove Pattern.compile Pattern p = Pattern.compile(regex); Matcher m = p.matcher(valueStr); retur...
20530820_70
public static Object parseValue(final DataType type, final String value) { if (value == null) { return null; } switch (type.getName()) { case TEXT: case VARCHAR: case ASCII: return value; case INET: return type.parse("'" + value + "'"); case INT: case VARINT: case BIGINT: case FLOAT: ...
20572012_144
@Override public ExpressionResult evaluate(EvaluationContext evaluationContext, List<FunctionArgument> arguments) { List<I> convertedArguments = new ArrayList<I>(); Status status = this.validateArguments(arguments, convertedArguments); /* * If the function arguments are not correct, just return an error statu...
20576090_0
static String colorToHTML(int argb) { return String.format("#%06X", argb & 0xffffff); }
20577351_0
public double getAlpha() { return alpha; }
20582138_2
@Override protected List<Runner> getChildren() { return fRunners; }
20614852_6
public static String getRGB(float n) { return String.format(Locale.ENGLISH, "%.0f", n).replaceAll("\\.0*$", ""); }
20645540_8
@Override public Schema outputSchema(Schema inputSch) { try { if (returnType == DataType.UNKNOWN) { return Schema.generateNestedSchema(DataType.BAG, DataType.NULL); } else { Schema outputTupleSchema = new Schema(new Schema.FieldSchema(returnName, returnType)); ret...
20647901_31
@Override public TimestampsRegion buildTimestampsRegion(String regionName, Properties properties) throws CacheException { return new TimestampMemcachedRegion(regionName, new OverridableReadOnlyPropertiesImpl(properties, cacheProviderConfigProperties), settings, memcachedAdapter, hibernateCacheTimestampe...
20660910_3
private Image findFirmwareImage(String hardware, String model, String build, Transform transform) throws JSONException, IllegalFirmwareFile { JSONObject models= root.getJSONObject(hardware); JSONObject builds = models.getJSONObject(model); JSONObject versions = builds.getJSONObject(build); return trans...
20673421_39
public static Transaction get(final Context context, final String number) throws NetLicensingException { CheckUtils.paramNotEmpty(number, "number"); return NetLicensingService.getInstance().get(context, Constants.Transaction.ENDPOINT_PATH + "/" + number, null, Transaction.class); }
20687990_0
public static void main(String[] args) throws Exception { new Main(args).run(); }
20701495_29
public PublicKey decodePublicKey(final String keyLine) throws GeneralSecurityException { // look for the Base64 encoded part of the line to decode // both ssh-rsa and ssh-dss begin with "AAAA" due to the length bytes bytes = Base64.getDecoder().decode(keyLine.getBytes(StandardCharsets.UTF_8)); if (byte...
20707395_11
public final double getDistanceToPathKm(List<Position> positions) { if (positions.size() == 0) throw new RuntimeException("positions must not be empty"); else if (positions.size() == 1) return this.getDistanceToKm(positions.get(0)); else { Double distance = null; for (int i =...
20710724_3
}
20717348_1
public static String modifyWorkFlowExtensions(String xmlContent) throws APIMigrationException { Writer stringWriter = new StringWriter(); Document doc = ResourceUtil.buildDocument(xmlContent, APIConstants.WORKFLOW_EXECUTOR_LOCATION); if (doc != null) { Element rootElement = doc.getDocumentElement(...
20746753_2
public void setOutputFolder(String outputFolder) { this.outputFolder = outputFolder; }
20811348_6
public Map<String, JGitEnvironmentProperties> getSshKeysByHostname() { return extractNestedProperties(this.sshUriProperties); }
20812119_27
public Hashtable<String, String> loadConfiguration(InputStream stream) { this.configurationInputSourceName = "stream"; return this.loadConfigurationSettings(stream); }
20819185_0
public static FlowDef buildFlowDef(Properties properties){ // create the Cascading "source" (input) tap to read the commonCrawl WAT file(s) Tap source=null; //check if we're running locally or on HDFS Boolean isDistributed =((properties.containsKey("platform")) && properties.getProperty("platform").toSt...
20844705_0
public void run() { new StatsView(store); new TermsView(store); new InputView(dispatcher, numberOfActions).dispatch(); }
20855247_10
public static <T> T readObject(final String jsonAsString, final TypeReference<T> typeReference) { return executing(() -> objectMapper.readValue(jsonAsString, typeReference)); }
20874043_4
@Override public void activate(RuleBlock ruleBlock) { if (FuzzyLite.isDebugging()) { FuzzyLite.logger().log(Level.FINE, "Activation: {0} {1}", new String[]{getClass().getName(), parameters()}); } TNorm conjunction = ruleBlock.getConjunction(); SNorm disjunction = ruleBlock.getDis...
20882897_131
@Override public Double apply(double[] x) { ArgChecker.notEmpty(x, "x"); int n = x.length; double mult = x[0]; for (int i = 1; i < n; i++) { mult *= x[i]; } return Math.pow(mult, 1. / n); }
20893538_4
@Override public Void call() throws Exception { setState(ExecutionState.RUNNING); try { callable.call(); incrementProgress(); } catch (Exception e) { setState(ExecutionState.FAILED); throw e; } setState(ExecutionState.COMPLETED); return null; }
20898148_15
public static boolean equals( Object head1, Object head2){ if (head1 != null){ return head1.equals(head2); } else { return head2 == null; // both null is treated as equal } }
20974631_1
public static String getUrlFromArgs(String[] args) { if (args == null || args.length < 1) { throw new IllegalArgumentException("Collector URL is required"); } return args[0]; }
20989862_0
public static <T> CompletableFuture<T> afterTimeout(T value, long millis) { CompletableFuture<T> future = new CompletableFuture<>(); timer.newTimeout(t -> future.complete(value), millis, TimeUnit.MILLISECONDS); return future; }
20990716_0
public Sentence parse(String originalLiteral) { / StrTokenizer tokenizer = new StrTokenizer(originalLiteral); List<String> tokens = tokenizer.tokenize(originalLiteral); log.debug("Tokens: {}", tokens); Sentence sentence = RelexidFactory.eINSTANCE.createSentence(); for (int i = 0; i < tokens.size(); i++) { Un...
20991787_0
boolean isThreadNameMatch(String name) { if (name == null) return false; if (threadPattern == null) { return false; } if (historyThreadName.add(name)) { int now = ManagementFactory.getThreadMXBean().getThreadCount(); int old; for (; ; ) { old = statMaxThread.get(); if (now > old) { if (stat...
21003796_53
public ScriptUpdates calculateScriptUpdates() { // Iterate over the already executed scripts to find out whether the contents of some scripts has been modified // since the last update. We also map the executed scripts with their script counterparts, to be able to verify // afterwards if scripts have been r...
21019546_0
public File getDataDir() { return dataDir; }
21019797_28
boolean onStartJob(JobParameters params) { SchedulerConstraint constraint; try { constraint = fromBundle(params.getExtras()); } catch (Exception e) { JqLog.e(e, "bad bundle from framework job scheduler start callback."); return false; } JqLog.d("[FW Scheduler] start job %s %d...
21052744_4
@Override public List<SessionInformation> getAllSessions(Object principal, boolean includeExpiredSessions) { Collection<S> sessions = this.sessionRepository.findByPrincipalName(name(principal)).values(); List<SessionInformation> infos = new ArrayList<>(); for (S session : sessions) { if (includeExpiredSessions ...
21089070_4
public static String extractNavigatorURL(String navigatorUrl) { Pattern compile = Pattern.compile("((?:ht|f)tps?\\:\\/\\/[^:]*:[0-9]*)"); Matcher matcher = compile.matcher(navigatorUrl); if (matcher.find()) { return matcher.group(0); } else { return navigatorUrl; } }
21099161_9
public String normalize(String original, String extracted) { Validate.notBlank(original); Validate.notNull(extracted); URI originalUri = null; URI extractedUri = null; try { originalUri = new URI(original); extractedUri = new URI(extracted); } catch (URISyntaxException ex) { ...
21112886_7
public List<Token> lex(final InputStream stream) { try (final BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream))) { List<Token> tokens = tokenize(bufferedReader); tokens.add(Token.END_OF_INPUT); return tokens; } catch (Exception e) { throw new Ru...
21138894_2
@Nullable @Override public GitRepository getRepoForRoot(@NotNull VirtualFile root) { Preconditions.checkArgument(root.isDirectory(), "%s is not a dir", root); return rootsVFileCache.get(root); }
21148694_16
public int compare(Cell o1, Cell o2) { return Long.valueOf(o1.getTimestamp()).compareTo(o2.getTimestamp()); }
21153865_10
protected static Output getQuestions(String query) { // ?:What is blue? // ?:"What is blue?" // ?:What is blue Matcher matcher = PATTERN.matcher(query); List<String> questions = new ArrayList<>(); while (matcher.find()) { String group = matcher.group(); query = query.replaceFirst(Pattern.quote(grou...
21180741_325
@Transactional(propagation = Propagation.NEVER) @Override public Bundle transaction(RequestDetails theRequestDetails, Bundle theRequest) { return myTransactionProcessor.transaction(theRequestDetails, theRequest); }
21182169_0
public static Map<String, List<String>> getUrlParameters(String url) { try { final Map<String, List<String>> query_pairs = new LinkedHashMap<String, List<String>>(); final String[] pairs = getQuery(url).split("&"); for (String pair : pairs) { final int idx = pair.indexOf("="); ...
21190869_0
@Override public Try<TableName> resolveTableNameByHint(T hint) { Validate.notNull(hint); TableName tableName = tableNameResolver.apply(hint); if (tableNames != null && !containsInTableNames(tableName)) { return Try.ofFailure(new IllegalArgumentException(String.format("hint(%s) is not found.", hint))...
21193524_24
public static String toLinux(String s) { return s.replace("\r\n", "\n"); }
21217047_173
@Override public void rotate(ParentReference<MutableBinaryTreeNode<E>> reference, MutableBinaryTreeNode<E> currentRoot) { final MutableBinaryTreeNodeImpl<E> root = (MutableBinaryTreeNodeImpl<E>)currentRoot; final MutableBinaryTreeNodeImpl<E> pivot = (MutableBinaryTreeNodeImpl<E>)root.getLeft(); if (pivot =...
21235372_2
public static int fibo(int n) { if (n < 0) { throw new IllegalArgumentException("n must be positive"); } if (n <= 1) { return n; } return fibo(n - 1) + fibo(n - 2); }
21242302_0
@Override public String getTemplateStringWithoutColumnNames() { return templateStringWithoutColumnNames; }
21248236_23
@Override public boolean isAddressValid(String address) { if (address.startsWith("L") || address.startsWith("3") || address.startsWith("M")) { try { Base58.decodeToBigInteger(address); Base58.decodeChecked(address); return true; } catch (AddressFormatException e) ...
21252787_66
public static void checkValidPath(final String path) { if (path == null) { throw new IllegalArgumentException("null path"); } if (path.isEmpty()) { throw new IllegalArgumentException("empty path"); } if (path.charAt(path.length() - 1) == PATH_SEPARATOR) { throw new IllegalArg...
21257044_10
public static ServerInstanceContext initialize() { try { return new ServerInstanceContext(); } catch (Exception e) { LOGGER.warn("Caught exception initializing AWS Instance Context.",e); return null; } }
21266289_82
public int getMonthlyValue(Commodity commodity, Date startingDate, Date endDate, DataElementType dataElementType) { SQLiteOpenHelper openHelper = LmisSqliteOpenHelper.getInstance(context); int commodityActionValueQuantity = 0; try { Dao<CommodityActionValue, String> commodityActionValueDao = DbUtil....
21285858_2
public Map<String, List<TaskInfo>> getTasksToLaunch(Topologies topologies, Map<String, Collection<WorkerSlot>> slots, Map<String, AggregatedOffers> aggregatedOffersPerNode) { Map<String, List<TaskInfo>> tasksToLaun...
21330228_66
@Override public int run(@Nonnull ProcessStream process) throws CmdLineException { IO io = new IO(new BufferedInputStream(process.in()), process.out(), process.err()); // Do not use .inputrc as jline does not interpret it correctly: https://github.com/jline/jline2/issues/51 System.setProperty("jline.input...
21352848_115
public static int closestIdentifierPosition(List<Integer> positions, int wordIdx) { if (positions.isEmpty()) { return -1; } Iterator<Integer> it = positions.iterator(); int bestPos = it.next(); int bestDist = Math.abs(wordIdx - bestPos); while (it.hasNext()) { int pos = it.next(); int dist = Ma...
21357013_15
public static ProtoNode buildDOM(byte[] data) throws ProtoReaderException { ProtoStreamNode node = new ProtoStreamNode(-1, data); return node; }
21357853_0
public static String iso8601UTCFromDate(Date date) { if (date == null) { return ""; } TimeZone tz = TimeZone.getTimeZone("UTC"); DateFormat formatter = ISO8601_FORMAT.get(); formatter.setTimeZone(tz); String iso8601date = formatter.format(date); // Use "+00:00" notation rather than...
21363553_1
public static JMHRunBuilderAssert assertJMH() { return new RunBuilderAssert(); }
21366948_53
@Override public String generateId( IHasProperties propertiesNode ) { Set<String> propertyKeys = getLogicalIdPropertyKeys(); if ( propertiesNode.getPropertyKeys().size() == 0 ) { return null; } String logicalId = null; if ( propertyKeys != null && propertyKeys.size() > 0 ) { StringBuilder sb = new...
21367254_93
@Override public double getDerivative(double net) { return this.slope; }
21375484_32
public void updateCategory(Category category) { categoryMapper.updateCategory(category); }
21388581_1
public static Map<Integer, String> getSqlColumnEntityHints(String sql) { Map<Integer, String> columnEntityHints = new HashMap<Integer, String>(); String columns = sql.substring(sql.toLowerCase().indexOf("select") + 6, getFromIndex(sql)); int commentIdx = 0; Set<String> used = new HashSet<>(); while ...
21394954_5
public OperationStepHandler getReadBootErrorsHandler() { return this.listBootErrorsHandler; }
21404821_24
public boolean parse(InputStream is, String regex, Function<List<String>, Boolean> sink) throws IOException { return parse(is, Pattern.compile(regex), sink); }