id
stringlengths
7
14
text
stringlengths
1
37.2k
12006992_3
public static TrezorMessage.TxInput newTxInput(Transaction tx, int index) { Preconditions.checkNotNull(tx, "Transaction must be present"); Preconditions.checkElementIndex(index, tx.getInputs().size(), "TransactionInput not present at index " + index); // Input index is valid TransactionInput txInput = tx.getI...
12046384_0
public Tuple enrichEvent(Tuple event) { if ("PRODUCT".equals(event.getString("type"))) { List<String> names = new ArrayList<>(event.getFieldNames()); List<Object> values = new ArrayList(event.getValues()); names.add("category"); values.add(getCategory(event.getString("product"))); return TupleBuilder.tuple()...
12057541_2
@Override public final boolean incrementToken() throws IOException { clearAttributes(); logger.debug("incrementToken"); int length = 0; int start = -1; // this variable is always initialized int end = -1; char[] buffer = termAtt.buffer(); while (true) { if (bufferIndex >= dataLen) { offset += dataLen...
12058287_0
public static final <T extends KeyLabel> String contructJson(List<T> list) { StringWriter writer = new StringWriter(); JsonGenerator g; try { g = JsonUtil.jsonFactory.createJsonGenerator(writer); g.writeStartArray(); if (null != list && !list.isEmpty()) { for (T model : list) { g.writeStartObject(); ...
12067623_0
@Override public int calculate(int a, int b) { return a * b; }
12085714_9
@Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof ActionFlowStepConfig)) { return false; } final ActionFlowStepConfig stepConfig = (ActionFlowStepConfig) o; if (index != stepConfig.index) { return false; } if ((nextAc...
12117077_49
public static Style parse(Object css) throws IOException { Reader reader = Convert.toReader(css).get("Unable to handle input: " + css); return new CartoParser().parse(reader); }
12134164_54
@SafeVarargs public static <T> Expression[] literals(T... objects) { Preconditions.checkNotNull(objects); Expression[] result = new Expression[objects.length]; for (int i = 0; i < objects.length; i++) { result[i] = literal(objects[i]); } return result; }
12151814_1
@SuppressWarnings("unchecked") public static <E extends Enum<? extends Style.HasCssName>> E fromStyleName(final String styleName, final Class<E> enumClass, final E defaul...
12246820_18
@Override public long putFile(File sourceFile, ContentReference targetContentReference) throws ContentIOException { ContentReferenceHandler delegate = getDelegate(targetContentReference); return delegate.putFile(sourceFile, targetContentReference); }
12250309_0
public void startServer() throws LDAPException { logger.info("Starting LDAP Server Configuration."); File installFile = new File(dataPath); installDir = installFile.getAbsolutePath(); boolean isFreshInstall; if (installFile.exists()) { isFreshInstall = false; logger.debug("Configurat...
12255838_2
public GuiceVerticleFactory setInjector(Injector injector) { this.injector = injector; return this; }
12299144_16
@Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { LOGGER.debug("Loading user by username: {}", username); User user = repository.findByEmail(username); LOGGER.debug("Found user: {}", user); if (user == null) { throw new UsernameNotFoundExceptio...
12299794_3
public static String combine(final String... parts) { final StringBuilder sb = new StringBuilder(); for (final String part : parts) { if (isHttpUrl(part) || isHttpsUrl(part)) { sb.setLength(0); } else if (!part.startsWith("/")) { sb.append("/"); } final S...
12304596_1
@Override @SuppressWarnings("unchecked") public void invoke(Context context, Result result) { Object object = result.getRenderable(); ResponseStreams responseStreams = context.finalizeHeaders(result); Map map; // if the object is null we simply render an empty map... if (object == null) { ...
12319410_2
public static XContentBuilder marshall(PoliciesBean bean) throws StorageException { try (XContentBuilder builder = XContentFactory.jsonBuilder()) { preMarshall(bean); builder .startObject() .field("organizationId", bean.getOrganizationId()) .field("entityI...
12343833_0
@SuppressWarnings("unchecked") public static <T> T transform(Class<T> type, String value) throws IllegalArgumentException { if (!VALUE_TRANSFORMER.containsKey(type)) { throw new IllegalArgumentException("unsupported parameter type: " + type); } // since VALUE_TRANSFORMER contains the transformer for...
12356701_0
private String getProperty(String key) { return store.get(key); }
12414592_26
@Transactional(Transactional.TxType.NOT_SUPPORTED) public void notSupported() { System.out.println(getClass().getName() + "Transactional.TxType.NOT_SUPPORTED"); }
12473833_38
public static int myBinarySearch(int[] indices, int key, int begin, int end) { if (indices.length == 0 || begin == end) { return -1; } end--; int mid = begin; while (begin <= end) { mid = (end + begin) >> 1; if (indices[mid] < key) { begin = mid + 1; ...
12485907_12
public static String normalizeSubject(String subject) { String s = subject; if (s != null) { s = s.replaceAll("\\[.*?\\][^$]","") // remove any brackets at the beginning except the one having end of line after the "]" .replaceAll("^\\s*(-*\\s*[a-zA-Z]{2,3}:\\s*)*","") // remove all Re: ...
12488647_6
public static String implode(String separator, List<String> elements){ StringBuffer s = new StringBuffer(); for(int i = 0; i < elements.size(); i++){ if(i > 0){ s.append(" "); } s.append(elements.get(i)); } return s.toString(); }
12497963_1
@Override public boolean shouldBreak(IHierarchicalNodeLayout layout) { if(layout.getDelegate()==null) // TODO : do not point on delegate but on MultiStepLayout.getCounter return false; if(layout.getDelegate().getCounter()>maxSteps) return true; else return false; }
12506813_0
public BM25FQuery( Collection<Query> perFieldQueries, Map<String, Float> fieldWeights, Map<String, Float> normFactors) { super(perFieldQueries, 0.0f); this.fieldWeights = fieldWeights; this.normFactors = normFactors; }
12508001_17
@Override public RenderedFileInfo render(final AbstractAllParams<W> all) throws VCatException { // Build a Job instance for the parameters. final String jobId = HashHelper.sha256Hex(all.getCombined()); Object lock; // Synchronized to jobs, as all code changing it or any of the other Collections storing Jobs. syn...
12520014_8
public static Boolean toBoolean(Integer intValue) { if (intValue == null) { return null; } if (FALSE.equals(intValue)) { return Boolean.FALSE; } return Boolean.TRUE; }
12544638_6
public static ClassPath buildDefaultClassPath (Application app) { LinkedHashSet<File> classPathEntries = new LinkedHashSet<File>(); for (Resource resource : app.getActiveCodeResources()) { classPathEntries.add(resource.getFinalTarget()); } addClassPathDirectories(app, classPathEntries); retu...
12554530_5
protected boolean sample() { if (curr.increment() >= freq) { curr.set(0); target.set(rand.nextInt(freq)); } return curr.get() == target.get(); }
12555873_41
public boolean hasInsituFilter() { return parameters.getInsitu() != null; }
12561697_1
private void reloadCacheEntry(CacheEntry cacheEntry) throws ExecutionException, InterruptedException { LoaderCallable<T> loaderCallable = new LoaderCallable<T>(this, cacheProvider, cacheLoader, cacheEntry); executorService.submit(loaderCallable); }
12578911_0
public static boolean checkNameing(String str) { char[] commonArray = new char[str.length()]; int len = 0; if (str == null || (len = str.length()) == 0) { return false; } str.getChars(0, len, commonArray, 0); int index = 0; char word = commonArray[index++]; //首字母判断 不为数字 , . if (word >= 46 && word <= 57) ...
12587918_4
public static byte[] undo(byte[] target, byte[] diff) { MemoryDiff md = Serials.deserialize(DefaultSerialization.newInstance(), MemoryDiff.class, diff); return Diffs.apply(new UndoOpQueue(md.queue()), target); }
12590126_3
@Loggable(Loggable.DEBUG) public int foo() { return 1; }
12591138_1
public String notNull(@NotNull final String value) { return value; }
12593159_0
public Author getAuthorByURL(String link, Author a) throws IOException, SamlibParseException, SamlibInterruptException { a.setUrl(link); String str = getURL(mSamLibConfig.getAuthorIndexDate(a), new StringReader()); parseAuthorIndexDateData(a, str); return a; }
12652086_0
public static Time fromMillis(long timeInMillis) { int secs = (int) (timeInMillis / 1000); int nsecs = (int) (timeInMillis % 1000) * 1000000; return new Time(secs, nsecs); }
12652338_12
public long getPriceWithVAT(LineItem lineItem) { CalcLineItem calcLineItem = new CalcLineItem(lineItem); return getCalc().getPriceWithVat(calcLineItem).getCents(); }
12686435_0
public FutureTask<ProxyServer> run() { FutureTask<ProxyServer> future = new FutureTask<>(new Callable<ProxyServer>() { @Override public ProxyServer call() throws Exception { // Configure the server. bootstrap = new ServerBootstrap(new NioServerSocketChannelFactory(Executors....
12768312_22
@Override public boolean hasNext() { return it != null; }
12796207_5
@NonNull public static Builder emptyBuilder() { return new Builder(Collections.emptyList()); }
12796568_15
public String getKey() { return key; }
12812578_34
public static boolean hasDependency(final PluginContext context, final EssentialsDependency dependency) { final TargetPom targetPom = dependency.getDependencyTargetPom(); if (targetPom == TargetPom.INVALID) { return false; } final Model model = ProjectUtils.getPomModel(context, targetPom); f...
12847265_23
@ExceptionMetered(name = "illegalArgumentExceptionMeteredStaticMethod", cause = IllegalArgumentException.class) public static void illegalArgumentExceptionMeteredStaticMethod(Runnable runnable) { runnable.run(); }
12853082_2
public void close() throws IOException { for (StreamingTrack streamingTrack : source) { writeChunkContainer(createChunkContainer(streamingTrack)); streamingTrack.close(); } write(sink, createMoov()); }
12854207_1
public void initDBTools(String schemaDir) { DBToolsFiles.copyXsdFileToSchemaDir(schemaDir); DBToolsFiles.copySampleSchemaFileToSchemaDir(schemaDir); }
12903179_22
public void unregister(Command command) { registeredCommands.remove(command); }
12918104_20
public static String clone(String URL) throws Exception { File tempDirectory = new File(Configuration.getTemporaryDirectory() + "/" + Calendar.getInstance().getTime().getTime() + ""); Main.printLine("[Info] Cloning from \"" +URL+ "\""); ProcessBuilder builder = new ProcessBuilder("git","clone", URL, tempDirectory....
12939200_53
public void debug(String msg) { logger.debug(msg); }
12953256_122
public static int unionSize(LongSortedSet a, LongSortedSet b) { return a.size() + b.size() - intersectSize(a, b); }
12959153_0
@Override @NonNull public List<Range> findTokenRanges(CharSequence charSequence, int start, int end) { ArrayList<Range>result = new ArrayList<>(); if (start == end) { //Can't have a 0 length token return result; } int tokenStart = Integer.MAX_VALUE; for (int cursor = start; cursor...
12960439_18
public ImmutableList<TransferSegment> createStateList(Layout layout, long trimMark) { return layout.getSegments() .stream() // Keep all the segments after the trim mark, except the open one. .filter(segment -> segment.getEnd() != NON_ADDRESS && segment.getEnd() > trimMark) ...
12962336_18
public static TransactionResult fromJSON(JSONObject json) { boolean binary; String metaKey = json.has("meta") ? "meta" : "metaData"; String txKey = json.has("transaction") ? "transaction" : json.has("tx") ? "tx" : json.has("tx_blob") ? "tx_blob" : null; if (txKey...
12963511_14
@Override public String encode( String jti, String issuer, String subject, Date currentTime, String method, String path, String contentHashAlgorithm, String contentHash ) throws JWTError { JwtClaims jwtClaims = new JwtClaims(); jwtClaims.setJwtId(jti); jwtClaims.setIssuer(issuer); jwtClaims.setS...
12974177_0
@NotNull public static String dumpLocks() { return LOCK_INVENTORY.dumpLocks(); }
12983151_0
public static FS20Command convertHABCommandToFS20Command(Command command) { if (command instanceof UpDownType) { return convertUpDownType((UpDownType) command); } else if (command instanceof OnOffType) { return convertOnOffType((OnOffType) command); } else if (command instanceof PercentType)...
13028147_119
public void assertOk() { if (hasErrors()) { throw new MrrtReportTemplateValidationException(this); } }
13062062_215
@Override public void restoreStateFrom(Map<String, String> data) { field.setText(Optional.ofNullable(data.get("pages")).orElse(EMPTY)); }
13068300_23
public static <T> List<T> notNulls(List<T> l, String paramName) { notNull(l, paramName); for (T t : l) { if (t == null) { throw new IllegalArgumentException(paramName + " cannot have NULL elements"); } } return l; }
13073335_8
public String formatCondition( Operator op, String objectName, String value, boolean parameterized ) { if ( parameterized ) { value = "[param:" + value.replaceAll( "[\\{\\}]", "" ) + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } else if ( op == Operator.IN ) { Matcher m = IN_EVAL_PAT.matche...
13075106_43
public static void radixSort(int[] input, int n, int[] scratch, int[] countScratch) { if (countScratch.length != 65536) throw new IllegalArgumentException("countScratch.length must be = 65536"); if (input.length < n) throw new IllegalArgumentException("input.length must be >= n"); if (scratch.length < n) th...
13075200_44
protected String[] convertToStringArray(final Payload payload, final String payloadMapKey) throws IllegalArgumentException { // historically, null values are allowed in the result, reasons unknown return extractNonNullValueFromMapPayload(payload, payloadMapKey, o -> convertToList(o)).stream() .map(S...
13077546_22
@Override public int size() { return numElements; }
13095397_0
public void execute( final String[] sql, final ExecutorCallback callback ) throws DataAccessException { Exception exceptionDuringExecute = null; DatabaseMeta dbMeta = connectionModel.getDatabaseMeta( ); String url = null; try { url = dbMeta.getURL( ); } catch ( KettleDatabaseException e ) { throw ne...
13105692_5
public List<Throwable> getErrors() { final List<Throwable> retval = new ArrayList<Throwable>(); for (final TestInfo testInfo : contractTestMap.listTestInfo()) { retval.addAll( testInfo.getErrors() ); } return retval; }
13107807_6
public static String getUrlString( String realHostname, String port ) { String urlString = "http://" + realHostname + ":" + port + GetStatusServlet.CONTEXT_PATH + "?xml=Y"; urlString = Const.replace( urlString, " ", "%20" ); return urlString; }
13126412_15
public int getHunkSize() { return hunkSize; }
13127985_31
@Override public String getExtension() { return delegate.getExtension(); }
13133836_7
String[] getSchemas( Database database, DatabaseMeta databaseMeta ) throws KettleDatabaseException { // This is a hack for PMD-907. A NPE can be thrown on getSchema JDBC's implementations. String[] schemas = null; Exception ex = null; try { schemas = database.getSchemas(); } catch ( Exception e ) { //...
13137355_28
public static Map<String, String> parse(String s) { final Map<String, String> result = new HashMap<>(); if (s == null) return result; // Process each line separated by a newline. for (String line : s.split("\n")) { // Parse the line looking for the first equals to get the map key. ...
13139604_0
public static void setValueString(DataType d, String value) throws DataException { if (value != null && value.length() > 255) { try { setValue(d, value.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { logger.error(e.getMessage()); logger.error(FactoryException.TRACE_EXCEPTION,e); } d...
13160719_0
public Table<String, NewRelicMetric, Boolean> loadTable(@Nonnull InputStream inputStream) throws IOException { Map<String, Map<NewRelicMetric, Boolean>> m = objectReader.forType(new TypeReference<Map<String, Map<NewRelicMetric, Boolean>>>() {}) .readValue(inputStream); return tab...
13191344_54
public static boolean matchesModifierLevel(AccessModifier modifierLevelOfElement, AccessModifier modifierLevel) { return (modifierLevelOfElement.getLevel() >= modifierLevel.getLevel()); }
13217403_10
@Override public void intercept(HttpRequest request) throws IOException { try { binding.sign(request, request); } catch (RequestSigningException e) { throw new RuntimeException(e); } }
13236207_0
public static InStream create(String name, ByteBuffer input, CompressionCodec codec, int bufferSize) throws IOException { if (codec == null) { return new UncompressedStream(name, input); } else { return new CompressedS...
13240419_2
public static boolean intersects(GenericSegment seg1, GenericSegment seg2) { //System.out.println("seg1: " + seg1 + "\nseg2: " + seg2); //System.out.println("H: " + horizIntersect(seg1, seg2) + " V: " + vertIntersect(seg1, seg2)); return horizIntersect(seg1, seg2) && vertIntersect(seg1, seg2); }
13272929_2
public ReadOnlyStyledDocumentBuilder<PS, SEG, S> addParagraphs(List<List<SEG>> listOfSegLists, StyleSpans<S> entireDocumentStyleSpans) { return addParagraphList(listOfSegLists, entireDocumentStyleSpans, ignore -> null, Function.identity()); }
13292939_10
@Override public List<Value> getValues(String field) { try { XPathExpression expr = xpath_map.get(field); if (expr == null) { return null; } NodeList lst = (NodeList)expr.evaluate(doc, XPathConstants.NODESET); ArrayList<Value> ret = new ArrayList<Value>(); ...
13317929_25
@Override public Parser<String> getParser(NonEmpty annotation, Class<?> fieldType) { return new Parser<String>() { @Override public String parse(String text, Locale locale) throws ParseException { if (!StringUtils.hasText(text)) { return null; ...
13325401_358
public static ValueMap toValueMap(final Map<String, ?> map) { final Map<String, Object> objectMap = new LinkedHashMap<String, Object>(map.size()); for (final Map.Entry<String, ?> entry : map.entrySet()) { objectMap.put(entry.getKey(), entry.getValue()); } return new ValueMapDecorator(objectMap...
13343738_8
public List<JUGMember> findByExperience(int experience) { return entityManager.createNamedQuery( "JUGMember-findByExperience") .setParameter( 1, experience ) .getResultList(); }
13348306_1
public static Properties bind(URI fsURI, Configuration conf) throws SwiftConfigurationException { String host = fsURI.getHost(); if (host == null || host.isEmpty()) { //expect shortnames -> conf names throw invalidName(host); } String container = extractContainerName(host); String service = e...
13349691_13
public TestPerformances getPerformancesFor(final String msg) { return map.get(msg); }
13363575_17
@Transactional @Override public User updateWithoutPassword(String username, User updatedUser) { Assert.notNull(updatedUser, "user must not be null"); Assert.notNull(updatedUser.getPassword(), "(old) password must not be null"); preUpdate(username, updatedUser); return doUpdate(username, updatedUser); }
13363729_38
public List<String> queryXml(String url, String username, String password, String... xpathQueries) throws IOException { byte[] xmlContent = doGet(url, username, password); List<String> results = new ArrayList<>(); try { InputSource is = new InputSource(new ByteArrayInputStream(xmlContent)); ...
13379760_81
public static String formatAlertMessage(TransactionSeenEvent event) { // Decode the "transaction seen" event final Coin amount = event.getAmount(); final Coin modulusAmount; if (amount.compareTo(Coin.ZERO) >= 0) { modulusAmount = amount; } else { modulusAmount = amount.negate(); } // Create a su...
13383431_28
public UndoableEdit delete(PetriNetComponent component) throws PetriNetComponentException { return deleteComponent(component); }
13414290_2
public Schema getSchema(int version) { return new Schema(version); }
13424587_55
public static RoundedMoney ofMinor(CurrencyUnit currency, long amountMinor) { return ofMinor(currency, amountMinor, currency.getDefaultFractionDigits()); }
13471496_3
@Override public String toString() { StringBuilder builder = new StringBuilder(); boolean firstTime = true; for (String key : mParams.keySet()) { builder.append(firstTime ? "?" : "&"); if (firstTime) firstTime = false; String value = mParams.get(key); builder.append(key).app...
13486560_0
public String guessMimeType(String path) { int lastDot = path.lastIndexOf('.'); if (lastDot == -1) { return null; } String extension = path.substring(lastDot + 1); extension = extension.toLowerCase(); String mimeType = extensionToMimeType.get(extension); return mimeType; }
13486910_2
public void removeAllSpringConfig() { mSpringConfigMap.clear(); }
13490595_330
@Override public void validate(Sentence sentence) { invalidOkurigana.stream().forEach(value -> { int startPosition = sentence.getContent().indexOf(value); if (startPosition != -1) { addLocalizedErrorWithPosition(sentence, startPosition, ...
13498449_0
double score(double balance, double numTrans, double creditLine) { ScriptEngine engine = ENGINE.get(); if(engine == null) { engine = initEngine(); ENGINE.set(engine); } double score; Bindings bindings = engine.getBindings(ENGINE_SCOPE); bindings.put("balance", balance); bindings.put("numTrans", nu...
13512175_99
@Override public EntityUpdateBatch<Id, M, V> updateBatch(Id id) { return updateBatch(singleton(id)); }
13521187_28
public <T> void registerType(Class<T> clazz, TypeSerializer<T> serializer) { typeSerializers.put(clazz, serializer); }
13535208_210
public String toObject(String value) { if (StringUtil.isEmpty(value)) { return null; } return ArgumentUtil.decode(value); }
13570618_2
@Override public synchronized void cleanup() { logInfoWithQueueName("purging completed tasks"); // clear all tasks from the finished queue final List<Future<Void>> completedTasks = Lists.newArrayListWithExpectedSize(this.completedTasksQueue.size()); this.completedTasksQueue.drainTo(completedTasks)...
13580866_73
public char[] readNumber( ) { try { ensureBuffer(); char [] results = CharScanner.readNumber( readBuf, index, length); index += results.length; if (index >= length && more) { ensureBuffer(); if (length!=0) { char results2[] = readNumber(); ...
13590591_6
public void modifyUserProfile(String pid, IUserProfileModification modifier) throws GetFailedException, PutFailedException, AbortModifyException { PutQueueEntry entry = new PutQueueEntry(pid); modifyQueue.add(entry); synchronized (queueWaiter) { queueWaiter.notify(); } UserProfile profile; try { profile =...
13601636_0
public Map<String, Object> deserialize(String data) throws IOException { try { Map<String, Object> map = new LinkedHashMap<String, Object>(); JsonParser jp = jsonFactory.createJsonParser(data); jp.nextToken(); // Object jp.nextToken(); // key map.put(KEY, new DataByteArray(jp.getCurrentName().getBytes())); ...