id
stringlengths
7
14
text
stringlengths
1
37.2k
40115035_16
public Event eventFromContextElement(ContextElement contextElement) throws EventProcessingException, TypeNotFoundException { String eventId = contextElement.getEntityId().getId(); String eventType = contextElement.getEntityId().getType(); Event event = new Event(eventType); // Add metadata values firs...
40167498_37
public static Integer ip2int(String ipAddress) { Inet4Address a; try { a = (Inet4Address) InetAddress.getByName(ipAddress); } catch (UnknownHostException e) { _log.error(ExceptionUtils.errorInfo(e)); return null; } byte[] b = a.getAddress(); return ((b[0] & 0xFF) << 24) |...
40182023_27
public <T extends BaseRequest<T, R>, R extends BaseResponse> R execute(BaseRequest<T, R> request) { return api.send(request); }
40213809_69
@Override public IAnswerData getAnswer() { String answerText = binding.answerText.getText().toString(); return answerText.isEmpty() ? null : new StringData(answerText); }
40234691_1
public static GeoDistanceSortingBuilder builder() { return new GeoDistanceSortingBuilder(); }
40235586_15
@Override public Optional<NetworkInterface> networkInterfaceById(String id) { return hal.getNetworkIFs().stream().filter(n -> n.getName().equalsIgnoreCase(id)).map( mapToNetworkInterface()).findAny(); }
40266095_32
@Override public void process(JCas jcas) throws AnalysisEngineProcessException { getContext().getLogger().log(Level.CONFIG, "Entering " + this.getClass().getSimpleName()); pageRank.initializeFromAnnotationPairIterator( JCasUtil.select(jcas, AnnotationPair.class), weighted ); pa...
40292501_0
@Override public MatlabProxy getProxy() throws MatlabConnectionException { return _delegateFactory.getProxy(); }
40317158_3
public static SplitList<String> parseGOTermList(String target) { SplitList<String> list = parseStringList(COMMA, target); SplitList<String> goList = new SplitList<String>(COMMA); for (String item : list) { item = parseString(item); if (item.startsWith("GO:")) { goList.add(item);...
40321883_9
public List<String> getMainTypesByTumorTypes(Set<TumorType> tumorTypes) { Set<String> mainTypes = new HashSet<>(); // skip the root node, "TISSUE". Just add it's children for (TumorType tumorType : tumorTypes) { if (tumorType.getMainType() != null && tumorType.getParent() != null) { main...
40325889_4
@Override public void encodeChildren(FacesContext context, UIComponent component) throws IOException { // no-op }
40345131_3
public static List<String> sanitizeTopicFilter(String topicFilter) { if (StringUtils.isEmpty(topicFilter)) throw new IllegalArgumentException("Empty topic filer"); if (!topicFilter.contains("+") && !topicFilter.contains("#")) throw new IllegalArgumentException("Topic filter does not contain wildcard"); ...
40396716_0
@Override public List<SearchResult> findDownloadsForMagazine(String issueSearchString) throws Exception { List<SearchResult> results = extract(issueSearchString, 5, 508); return results; }
40404190_2
@Override public void launch(int id) { restartable(id).launch(); }
40405884_15
public Path saveToFile(final Path outputDirectory, final String namePrefix) throws IOException { requireNonNull(outputDirectory); final String prefix = namePrefix.trim(); if (prefix.isEmpty()) { throw new IllegalArgumentException("Name prefix cannot be blank!"); } final String fileName...
40442532_2
@Override public void onPermissionDenied(PermissionDeniedResponse response) { if (!contextProvider.isActivityContextAvailable()) { PermissionsUIViews.showPermissionToast(contextProvider.getApplicationContext(), getPermissionDeniedFeedback()); } if (userPermissionRequestResponseListener != null) { ...
40457462_109
@Override public void initRound() { super.initRound(); lastNonZeroVelocity = 0; previousVelocity = 0; timeSinceDirectionChange = 0; timeSinceVelocityChange = 0; hitLocations.clear(); }
40510168_72
public static boolean poll(BooleanSupplier cond, long periodMs, long timeoutMs) { return poll((n) -> cond.getAsBoolean(), periodMs, timeoutMs, null); }
40527870_200
@Override public boolean passesCriteria(Bundle bundle) { return bundle != null && !isPlatformBundle(bundle) && importsExportsMotechPackage(bundle); }
40536165_6
public PromotionResponse validate(ValidationContext context) throws IOException { Map<String, String> queryParams = createQueryParamsForContext(context); return api.validatePromotion(queryParams).execute().body(); }
40538806_4
public static MeasurementUnit getFromLocale(Locale locale) { String countryCode = locale.getCountry(); ArrayList<String> countriesUsingImperial = new ArrayList<>(Arrays.asList(Locale.US.getCountry())); if (countriesUsingImperial.contains(countryCode)) { return Imperial; } retu...
40541952_2
public static boolean testScript (byte[] script, byte[] template, byte[]... parameters) { Script s = new Script(script); List<ScriptChunk> chunks = s.getChunks(); int parameter = 0; for (int i = 0; i < chunks.size(); i++) { boolean correct = false; ScriptChunk chunk = chunks.get(i); ...
40557971_13
@Subscribe @SuppressWarnings("WeakerAccess") public void productDetailsFragmentDismissed(@SuppressWarnings("UnusedParameters") ProductDetailsFragmentDismissedEvent event) { viewBinder.dismissProductDetailsView(); }
40563017_0
private Yaml yaml() { return this.cachedYaml.get(); }
40563645_11
public static boolean isExpandableGroup(long composedId) { return (composedId != RecyclerView.NO_ID) && ((composedId & BIT_MASK_CHILD_ID) == BIT_MASK_CHILD_ID); }
40605386_2
static Result decode(byte[] packet, int packetLength) throws IOException { Result result = new Result(); decode(packet, packetLength, result); return result; }
40616171_1
public boolean wake() { synchronized (lock) { if (!isWaiting) { return false; } else { woken = true; lock.notify(); return true; } } }
40628209_514
public static Task<Void> unlinkInBackground(ParseUser user) { checkInitialization(); return user.unlinkFromInBackground(AUTH_TYPE); }
40667226_1
public boolean check() { if (name.getText().toString().equals("")) { nameLayout.setError(getString(R.string.empty_username)); return false; } if (pwd.getText().toString().equals("")) { passwordLayout.setError(getString(R.string.empty_pwd)); return false; } return true...
40695309_7
public boolean isLast() { if(isRoot()) return true; return (pathElements.length <= 1); }
40712527_0
public String add(Company companyDto) { Company company = new Company(); company.setName(companyDto.getName()); company.setAddress(companyDto.getAddress()); company.setHeadcount(companyDto.getHeadcount()); company.setStatus(Status.OPEN); Company result = companyRepository.save(company); return result.getId...
40714460_5
public Flux<ServiceMessage> invokeBidirectional(Publisher<ServiceMessage> publisher) { return Flux.from(publisher) .switchOnFirst( (first, messages) -> Mono.deferWithContext(context -> authenticate(first.get(), context)) .flatMapMany(authData -> deferWithContextBidirect...
40733990_31
public static String say(final String[] args) { return sayOrThink(args, false); }
40737618_12
@Override void onNext(ArrayList<Prize> prizes) { Collections.sort(prizes, this); if (isViewAttached()) { getView().showPrizes(prizes); } }
40753051_36
public byte[] transformAsBytes(Source input, Format format) throws TransformerException { return transformAsBytes(input, format, Collections.<String, Object>emptyMap()); }
40762184_0
public static void insertMessage(Throwable onObject, String msg) { try { Field field = Throwable.class.getDeclaredField("detailMessage"); //Method("initCause", new Class[]{Throwable.class}); field.setAccessible(true); if (onObject.getMessage() != null) { field.set(onObject, "\n[\...
40763113_5
public static void throwIfNonEmpty(Collection<Message> messages) throws MergingException { if (!messages.isEmpty()) { throw new MergingException(null, Iterables.toArray(messages, Message.class)); } }
40779062_1
static boolean matchesAsInnerClass(String classFqn, List<String> fqns) { for (String fqn : fqns) { if (classFqn.startsWith(fqn + "$")) { return true; } } return false; }
40780878_15
@Override public void define(Context context) { NewRepository repository = context .createRepository(JSONLanguage.KEY, JSONLanguage.KEY) .setName(CheckList.REPOSITORY_NAME); new AnnotationBasedRulesDefinition(repository, JSONLanguage.KEY).addRuleClasses(false, CheckList.getChecks()); repository.done(); }
40910858_3
public void setPublicKey(String publicKey) throws WPCSEInvalidPublicKey { this.publicKey = WPPublicKey.parseKey(publicKey); }
40961773_3
@NotNull @Override public String create(@NotNull final Context context) { final Document doc = myDocumentManager.createDocument(); final Element patternsElement = doc.createElement(PATTERNS_ELEMENT); String thresholdsStr = myParametersService.tryGetRunnerParameter(Constants.THRESHOLDS_VAR); if(!StringUtil.isEmp...
40970642_3
public static Draw drawNumbers(LocalDate date) { Random random = new Random(date.toEpochDay()); Draw.DrawBuilder builder = Draw.builder().withDate(date); do { Integer number = random.nextInt(MAX_NUMBER_IN_DRAW + 1); if (number < MIN_NUMBER_IN_DRAW) { continue; } i...
40976537_0
public boolean exists(String name) { return cache.containsValue(name); }
40977450_7
public ClubSquad build() { squad.add(goalkeepers.remove(0)); addToSquad(ClubSquad.TOTAL_DEFENDERS, asList(defenders, midfielders, attackers, goalkeepers)); addToSquad(ClubSquad.TOTAL_MIDFIELDERS, asList(midfielders, attackers, defenders, goalkeepers)); addToSquad(ClubSquad.TOTAL_ATTACKERS, asList(attackers, mi...
40998919_6
public static Optional<MediaType> getProblemMediaType(final List<MediaType> mediaTypes) { for (final MediaType mediaType : mediaTypes) { if (mediaType.includes(APPLICATION_JSON) || mediaType.includes(PROBLEM)) { return Optional.of(PROBLEM); } else if (mediaType.includes(X_PROBLEM)) { ...
41012501_0
@SneakyThrows public PDFDoc extractFromInputStream(InputStream is) { return extractResultFromInputStream(is).document; }
41053417_6
public void syncMembers() { log.info("> Sync members"); syncLocalMembers(); syncRemoteMembers(); log.info("< Synced members"); }
41057956_15
@Override public void setTabsFromPagerAdapter(@NonNull PagerAdapter adapter) { super.setTabsFromPagerAdapter( pageTitlesVisible ? adapter : TitleNullifyingPagerAdapter.from(adapter)); if (isLayoutPagerAdapterInstance(adapter)) { setTabIconsFromLayoutPagerAdapter((LayoutViewPager.LayoutPagerAdapter) adapt...
41091157_5
@Override public ModelAndView doGet(ModelMap model) { log.info("Requesting doGet of " + this.getClass()); return buildModelAndView( getModelViewName(), model, new ModelPopulator() { @Override public void populateModel(ModelMap model) { ...
41092630_14
@ExceptionHandler(SmartCosmosException.class) protected ResponseEntity<?> handleSmartCosmosExceptionMethod(SmartCosmosException exception, WebRequest request) { if (exception.getCause() == null) { logException(exception, request); HttpHeaders headers = new HttpHeaders(); HttpStatus status =...
41104075_6
@Override public int run(String[] args) throws Exception { addInputOption(); addOutputOption(); addOption(JOB_NAME_OPTION, "jn", "Optional name to give the Hadoop Job.", false); addOption(ZK_CONNECT_OPTION, "zk", "Connection string for ZooKeeper. Either Solr Server or ZK must be specified.", false); add...
41115262_3
@NonNull @SuppressWarnings("deprecation") public static JobRequest.NetworkType getNetworkType(@NonNull Context context) { ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo; try { networkInfo = connectivityM...
41152339_2
public CharSequence format(Monetary monetary) { return format(monetary, monetary.smallestUnitExponent()); }
41247722_82
static long computeCrcOfCentralDir(RandomAccessFile raf, CentralDirectory dir) throws IOException { CRC32 crc = new CRC32(); long stillToRead = dir.size; raf.seek(dir.offset); int length = (int) Math.min(BUFFER_SIZE, stillToRead); byte[] buffer = new byte[BUFFER_SIZE]; length = raf.read(...
41250653_1
@Override public void bookmarkMovie(Movie movie) { bookmarksStorage.bookmarkMovie(movie); }
41253781_127
public Option<T> orElse(T value) { return isDefined() ? this : of(value); }
41263845_144
@Override public Iterable<KeyValuePair<O>> getKeyValuePairsForKeysPrefixing(final CharSequence document) { return new Iterable<KeyValuePair<O>>() { @Override public Iterator<KeyValuePair<O>> iterator() { return new LazyIterator<KeyValuePair<O>>() { Iterator<KeyValuePair<O...
41263864_17
public static <L extends Lock> boolean tryLockAll(Iterable<L> locks) { Deque<L> stack = new LinkedList<L>(); boolean success = false; try { for (L lock : locks) { success = lock.tryLock(); if (success) { stack.push(lock); } else { ...
41280112_13
public static boolean validateIdCard15(String idCard) { if (idCard.length() != CHINA_ID_MIN_LENGTH) { return false; } if (isNum(idCard)) { String proCode = idCard.substring(0, 2); if (cityCodes.get(proCode) == null) { return false; } String birthCode = idC...
41286649_1
public static String cleanFilename(String fileName, String defaultName) { if (fileName == null || "".equals(fileName)) { fileName = defaultName; } else { fileName = fileName.replaceAll("\\W", ""); fileName = (fileName.length() > 0) ? fileName : defaultName; } return fileName; }
41324285_8
@Override public void execute(final SensorContext context) { final List<InputFile> inputFiles = Lists.newArrayList(this.fileSystem.inputFiles(this.javaFilesPredicate)); final SmellMeasurer measurer = new SmellMeasurer(context); for (final InputFile inputFile : inputFiles) { measurer.measure(inputFil...
41327255_9
public static int[] getWordColors(List<LetterSource> letters, String word) { int[] colors = new int[word.length()]; if (letters == null) { for (int i = 0; i < colors.length; ++i) { colors[i] = COLOR_MISSING; } return colors; } SpelledWord spelledWord = WordUtil.spell(letters, word); return...
41351929_2
public USM getUSM() { MPv3 mp = (MPv3) getMessageProcessingModel(MPv3.ID); if (mp != null) { return (USM)mp.getSecurityModel(SecurityModel.SECURITY_MODEL_USM); } return null; }
41361042_43
public void dump(DumpMode mode, File dbDirectory, File htmlDirectory, @Nullable File imageDirectory) throws IOException { try (WikiDB db = new WikiDB(dbDirectory)) { if (mode == BOTH || mode == WRITE_TEMPLATES_AND_MODULES) { firstPass(db); } if (mode == BOTH || mode == W...
41371438_180
@Override public GeneratedPropertyBuilder addProperty(final String name) { checkArgument(name != null, "Parameter name can't be null"); checkArgument(!containsProperty(name), "This generated type already contains property with the same name."); final GeneratedPropertyBuilder builder = new Generated...
41395725_46
public static String toString(final Collection<?> collection, final String separator) { if (collection == null || collection.isEmpty()) { // just return an empty String if the collection is null or empty return ""; } if (separator == null) { // fall back to the collection's toString(...
41414120_5
public static RowKey getEndRowKeyOfPrefix(RowKey prefixRowKey) { Util.checkRowKey(prefixRowKey); byte[] rowkeyBytes = prefixRowKey.toBytes(); Util.check(rowkeyBytes.length != 0); boolean isAllByteIsFF = true; for (byte b : rowkeyBytes) { if ((b & 0xFF) != 0xFF) { isAllByteIsFF ...
41423327_23
public static int findWhitespace(CharSequence s) { return findWhitespace(s, 0); }
41460477_59
@Override public void run() { try { AtomicInteger dispatchedCount = new AtomicInteger(0); long startMillis = System.currentTimeMillis(); digestsSize.set(digests.size()); // update size before flushing, so we show a higher value Iterator<HistogramKey> index = digests.getRipeDigestsIterator(this.clock)...
41486933_66
public boolean containsKey(final K key) throws DataAccessLayerException { return (key != null && _dao.contains(key)); }
41505622_33
public boolean canShowAdAtPosition(int position, int fetchedAdsCount) { // Is this a valid position for an ad? // Is an ad for this position available? return isAdPosition(position) && isAdAvailable(position, fetchedAdsCount); }
41547678_77
public static String getterName(FormalParameter formalParameter, SymbolResolver resolver) { return Property.getterName(formalParameter.getType(), formalParameter.getName(), resolver); }
41548314_0
public HostDistance distance(Host host) { String dc = dc(host); // If the connection has switched to the backup DC and fulfills // the requirement for a back switch, make it happen. if(!switchBackCanNeverHappen){ triggerBackSwitchIfNecessary(); } if (isLocal(dc)) { return HostDistance.LOCAL; } // Only ...
41627615_0
@Transactional @Override public Movimiento transferir(String codigoOrigen, String codigoDestino, BigDecimal importe) { if (importe.compareTo(MAXIMO_PERMITIDO) > 0) { throw new BusinessException( String.format("Importe {0} supera el máximo {1} permitido.", importe, MAXIMO_PERMITIDO)); ...
41627638_105
public List<String> fizzBuzz(int n) { return IntStream.rangeClosed(1, n).boxed().map(i -> { boolean isFizz = i % 3 == 0; boolean isBuzz = i % 5 == 0; if (isFizz && isBuzz) { return "FizzBuzz"; } else if (isBuzz) { return "Buzz"; } else if (isFizz) { ...
41630081_12
public void renderTodaysExpenses() { view.displayTodaysExpenses(expenses); }
41633076_0
public Set<ClassDefinition> parseClassFiles(Path path) { Set<ClassDefinition> set = new HashSet<>(); try { Map<String, Path> stringPathMap = preloadClassDefs(path, set); for (Map.Entry<String, Path> stringPathEntry : stringPathMap.entrySet()) { String key = stringPathEntry.getKey(); ...
41636618_2
@Nullable @SneakyThrows({ MalformedURLException.class, NoSuchAlgorithmException.class }) @VisibleForTesting Dependency findArtifactInRepository(Artifact artifact, ArtifactRepository repository) throws MojoExecutionException { String artifactPath = getArtifactPath(artifact, artifact.getVersion()); if (a...
41688821_1
MethodSpec handleParamActivity(String group, NavigableAnnotatedClass value) { TypeName activityTypeName = AndroidSpecificClassProvider.getActivityTypeName(); TypeName intentTypeName = AndroidSpecificClassProvider.getIntentTypeName(); String activityQualifiedName = value.getTypeElement().getQualifiedName().t...
41741864_2
public void addOrAppendPath(final String path, final T payload) { if (path == null) { return; } Collection<T> currentPayload = delegate.get(path); if (currentPayload == null) { currentPayload = new LinkedList<>(); delegate.addPath(path, currentPayload); } currentPayload....
41742830_0
public static double getChenScore(Card[] cards) { if (cards.length != 2) { throw new IllegalArgumentException("Invalid number of cards: " + cards.length); } // Analyze hole cards. int rank1 = cards[0].getRank(); int suit1 = cards[0].getSuit(); int rank2 = cards[1].getRank(); int...
41742943_7
private static Data<?> parseData(byte[] data, int offset) throws SecsParseException { if (data.length < 2) { throw new SecsParseException("Invalid data length: " + data.length); } int formatByte = data[offset]; int formatCode = formatByte & 0xfc; int noOfLengthBytes = formatByte & 0x03;...
41754174_4
@Override public void markKeysAsUsed(Transaction tx) { wallet.lock(); wallet.lockKeychain(); try { KeyChainGroup group = wallet.getKeychain(); List<Object> oldCurrentKeys = getCurrentKeys(group); doMarkKeysAsUsed(tx, group); List<Object> currentKeys = getCurrentKeys(group); ...
41767364_8
@Override public SpanContextHandler getSpanContextHandler() { throw new UnsupportedOperationException( "#getSpanContextHandler is not supported because the context " + "is managed by the App Engine runtime"); }
41772834_20
static Comment parse(String owningClass, String commentText) { return isBlank(commentText) ? Comment.createEmpty() : new Comment(parseElements(owningClass, commentText.trim())); }
41812613_1
public String increment(String fullId, int proposedCutoff) { StringBuilder mutable = new StringBuilder(fullId); if (proposedCutoff <= fullId.length()) { // First try normal incrementing for (int i = proposedCutoff - 1; i > 0; i--) { int newValue = mAlphabet.decodeDigit(mutable.charA...
41817706_439
protected Map<String, String> resolveProperties(Map<String, String> originalProperties, Map<String, String> properties, boolean overrideProperties) { if (properties != null) { if (!overrideProperties) { properties.putAll(originalProperties); } original...
41822437_0
@Override public List<Issue> getIssues() { return mIssues; }
41889031_16
public static List<SubscriptionItem> readFrom( final InputStream in, @Nullable final ImportExportEventListener eventListener) throws InvalidSourceException { if (in == null) { throw new InvalidSourceException("input is null"); } final List<SubscriptionItem> channels = new ArrayList<...
41892061_2
public static RecordingTransaction wrap(Transaction tx) { return new RecordingTransaction(tx); }
41930098_3
public boolean tryAcquire() { // current time millis is not monotonic - it can jump back depending on user choice or NTP long now = System.nanoTime() / 1_000_000; // after this the request should be expired long toBeExpired = now - expireTime; synchronized (this) { // having synchronized wi...
41933697_30
@Override public List<MarketConfig> findAll() { LOG.info(() -> "Fetching all Market configs..."); return ConfigurationManager.loadConfig(MarketsType.class, MARKETS_CONFIG_YAML_FILENAME) .getMarkets(); }
41963016_7
public CharSequence subSequence(int start, int end) { if (start < 0 || end < 0 || end > length || start > end) { throw new IndexOutOfBoundsException("Subsequence " + "<" + start + ", " + end + ") not in " + "<0, " + length + ")."); } else { fillBuffer(end - 1); if (end > length) { end = length; } if ...
41963293_1
public int calculateSomething() { return 0; }
41971504_6
public static String linkify(List<Link> links, String text) { //if(!hasLinks(links)) { return text; } int addedChars = 0; //offset for inserting for (Link link : links) { StringBuilder stringBuilder = new StringBuilder(text); int start = link.getStart(); int end = link.getEnd(); String href = ...
41985062_6
@CheckResult @NonNull // public static Observable<Intent> create(@NonNull final Context context, @NonNull final IntentFilter intentFilter) { checkNotNull(context, "context == null"); checkNotNull(intentFilter, "intentFilter == null"); return Observable.create(new Observable.OnSubscribe<Intent>() { @Overri...
41985966_3
@Override public Configuration loadFileConfiguration(String filePath) throws IOException { File configurationFile = new File(filePath); String configurationJson = FileUtils.readFileToString(configurationFile); return loadJsonConfiguration(configurationJson); }
42019073_2
public static double angleDifference(double angle1, double angle2) { return ((((angle1 - angle2) % (Math.PI * 2.0)) + (Math.PI * 3)) % (Math.PI * 2)) - Math.PI; }
42046027_47
public double distanceSquared(final CCVector3 thePoint, final CCVector3 theStore) { final CCVector3 vectorA = new CCVector3(); vectorA.set(thePoint).subtractLocal(_myOrigin); final double t0 = _myDirection.dot(vectorA); if (t0 > 0) { // d = |P - (O + t*D)| vectorA.set(_myDirection).multiplyLocal(t0); vectorA....
42050188_32
public boolean hasStartProd() { return getStartProd().isPresent(); }