code
stringlengths
73
34.1k
label
stringclasses
1 value
private int readInt() throws IOException { latestRead = (int)SerializationUtils.readIntegerType(input, WriterImpl.INT_BYTE_SIZE, true, input.useVInts()); return latestRead; }
java
public static boolean needsSymbolData(ObjectCreationExpr n) { final SymbolType st = symbolDataType(n); return st == null || !st.isLoadedAnonymousClass(); }
java
public void setFieldNames(List<String> fieldNames) { this.fieldNames = fieldNames; if (fields.length != fieldNames.size()) { Object[] oldFields = fields; fields = new Object[fieldNames.size()]; System.arraycopy(oldFields, 0, fields, 0, Math.min(oldFields.length, fieldNames.size())); ...
java
public boolean isSkipLine(String line) { return skipLinePattern != null && line != null && skipLinePattern.matcher(line).matches(); }
java
public boolean isFirstHeaderLine(String line) { return firstLineDetectionPattern != null && line != null && firstLineDetectionPattern.matcher(line).matches(); }
java
public boolean isLastHeaderLine(String line) { return lastLineDetectionPattern != null && line != null && lastLineDetectionPattern.matcher(line).matches(); }
java
public void validate() { check("firstLine", this.firstLine); check("beforeEachLine", this.beforeEachLine); check("endLine", this.endLine); check("firstLineDetectionPattern", this.firstLineDetectionPattern); check("lastLineDetectionPattern", this.lastLineDetectionPattern); ...
java
protected DestroyableManager configureManager(final DestroyableManager manager) { bind(DestroyableManager.class).toInstance(manager); // if logic will not call destroy at least it will be called before jvm shutdown Runtime.getRuntime().addShutdownHook(new Thread(manager)); return manager...
java
public static void skip32(byte[] key, int[] buf, boolean encrypt) { int k; /* round number */ int i; /* round counter */ int kstep; int wl, wr; /* sort out direction */ if (encrypt) { kstep = 1; k = 0; } else { kstep = -1; k = 23; } /* pack into words */ wl = (buf[0] << 8) + buf[1]; ...
java
public static int encrypt(int value, byte[] key) { int[] buf = new int[4]; buf[0] = ((value >> 24) & 0xff); buf[1] = ((value >> 16) & 0xff); buf[2] = ((value >> 8) & 0xff); buf[3] = ((value >> 0) & 0xff); skip32(key, buf, true); int out = ((buf[0]) << 24) | ((buf[1]) << 16) | ((buf[2]) << 8) | (buf[...
java
public static int decrypt(int value, byte[] key) { int[] buf = new int[4]; buf[0] = ((value >> 24) & 0xff); buf[1] = ((value >> 16) & 0xff); buf[2] = ((value >> 8) & 0xff); buf[3] = ((value >> 0) & 0xff); skip32(key, buf, false); int out = ((buf[0]) << 24) | ((buf[1]) << 16) | ((buf[2]) << 8) | (bu...
java
public static Object toBasicType(String value, String type) throws SQLException { // Early return from first "if" condition that evaluates to true if (value == null) { return null; } if (type == null || type.equals(String.class.getName())) { return value; ...
java
public static void throwSQLException(Exception cause, String theType, String value) throws SQLException { throw new SQLException("Invalid " + theType + " value: " + value, cause); }
java
protected final void bindPropertiesWithOverrides(final String propertyFile) { checkNotNull(propertyFile, "classpath resource property file must not be null"); Properties properties = new Properties(); // load classpath resource properties InputStream inputStream = getClass().getResourc...
java
protected static final boolean looksLikeAnnotationName(final String name) { return name.startsWith("org.nmdp") && Character.isUpperCase(name.charAt(name.lastIndexOf(".") + 1)); }
java
@SuppressWarnings("unchecked") protected static final <A extends Annotation> Class<A> annotation(final String annotationClassName) { try { return (Class<A>) Class.forName(annotationClassName); } catch (ClassNotFoundException e) { throw new ProvisionException(format("c...
java
@SuppressWarnings("unchecked") public static Optional<AlexaIntentHandler> createHandler(final AlexaInput input) { try { final Class factoryImpl = Class.forName(FACTORY_PACKAGE + "." + FACTORY_CLASS_NAME); final Method method = factoryImpl.getMethod(FACTORY_METHOD_NAME, AlexaInput.cla...
java
public void setLogFileDir(String logDirName) { File logDir = new File(logDirName); if (!logDir.isAbsolute()) { logDir = new File(serverBaseDir, logDirName); } this.logFileDir = logDirName; if (started) { configuration.setLogFileDir(logDir.getAbsolutePath(...
java
public void start() throws Exception { started = true; setLogFileDir(logFileDir); LOGGER.debug("Initiating transaction manager recovery"); recovered = new HashMap<>(); logger.open(null); ReplayListener replayListener = new GeronimoReplayListener(xidFactory, recovered); ...
java
public Object prepare(Xid xid, List<? extends TransactionBranchInfo> branches) throws LogException { int branchCount = branches.size(); byte[][] data = new byte[3 + 2 * branchCount][]; data[0] = intToBytes(xid.getFormatId()); data[1] = xid.getGlobalTransactionId(); data[2] = xid....
java
public void commit(Xid xid, Object logMark) throws LogException { //the data is theoretically unnecessary but is included to help with debugging // and because HOWL currently requires it. byte[][] data = new byte[4][]; data[0] = new byte[]{COMMIT}; data[1] = intToBytes(xid.getFor...
java
protected final Allele loadAllele(final String glstring, final String accession) throws IOException { final String id = glstringResolver.resolveAllele(glstring); Allele allele = idResolver.findAllele(id); if (allele == null) { Matcher m = ALLELE_PATTERN.matcher(glstring); ...
java
protected Elements getFirst(Elements elems) { @SuppressWarnings("unchecked") IterableElements<Elements> iterableElems = elems.as(IterableElements.class); return Iterables.getFirst(iterableElems, null); }
java
protected boolean triggerReverse(Type type, Throwable e) { return trigger(Lists.reverse(getAllListeners()), type, e); }
java
public DataSource createDataSource(Properties props) throws SQLException { if (props == null) { props = new Properties(); } DataSource dataSource = newDataSource(); setBeanProperties(dataSource, props); return dataSource; }
java
public ConnectionPoolDataSource createConnectionPoolDataSource(Properties props) throws SQLException { if (props == null) props = new Properties(); ConnectionPoolDataSource dataSource = newConnectionPoolDataSource(); setBeanProperties(dataSource, props); return dataSource; }
java
public XADataSource createXADataSource(Properties props) throws SQLException { if (props == null) props = new Properties(); XADataSource dataSource = newXADataSource(); setBeanProperties(dataSource, props); return dataSource; }
java
public Driver createDriver(Properties props) throws SQLException { Driver driver = newJdbcDriver(); setBeanProperties(driver, props); return driver; }
java
static void setBeanProperties(Object object, Properties props) throws SQLException { if (props != null) { Enumeration<?> enumeration = props.keys(); while (enumeration.hasMoreElements()) { String name = (String) enumeration.nextElement(); setP...
java
public String nextToken(String separators) { separator = 0; if (peek != null) { String tmp = peek; peek = null; return tmp; } if (index == string.length()) { return null; } StringBuilder sb = new StringBuilder(); ...
java
private EntityManager getEM() throws IllegalStateException { if (!open) { throw new IllegalStateException("The JPA bridge has closed"); } try { // Do we already have one on this thread? EntityManager em = perThreadEntityManager.get(); if (em != ...
java
@Override public OutputSpeech getOutputSpeech() { if (outputSpeech != null) { return outputSpeech; } final String utterance; try { utterance = yamlReader.getRandomUtterance(output).orElseThrow(IOException::new); LOG.debug("Random utterance read o...
java
@Override public Reprompt getReprompt() { if (reprompt != null || !output.shouldReprompt()) { return reprompt; } final String repromptSpeech = yamlReader.getRandomReprompt(output).orElse(null); if (repromptSpeech != null) { final String utteranceSsml = resol...
java
private Transaction getActiveTransaction() throws SystemException { Transaction tx = manager.getTransaction(); if (tx != null && tx.getStatus() != Status.STATUS_NO_TRANSACTION) { return tx; } else { return null; } }
java
public void onEntry(Propagation propagation, int timeout, String interceptionId) throws SystemException, NotSupportedException, RollbackException { Transaction transaction = getActiveTransaction(); switch (propagation) { case REQUIRES: // Are we already in a tran...
java
public void onExit(Propagation propagation, String interceptionId, TransactionCallback callback) throws HeuristicRollbackException, HeuristicMixedException, SystemException, InvalidTransactionException { Transaction current = getActiveTransaction(); if (callback == nul...
java
public void onError(Exception e, Propagation propagation, Class<? extends Exception>[] noRollbackFor, Class<? extends Exception>[] rollbackFor, String interceptionId, TransactionCallback callback) throws SystemException, HeuristicRollbackException, HeuristicMixedException, InvalidTransactionExce...
java
public static <T extends AlexaSpeechlet> T createSpeechletFromRequest(final byte[] serializedSpeechletRequest, final Class<T> speechletClass, final UtteranceReader utteranceReader) throws IOException { final ObjectMapper mapper = new ObjectMapper(); final JsonNode parser = mapper.readTree(serializedSpe...
java
public String build() { if (locus == null && tree.isEmpty()) { throw new IllegalStateException("must call locus(String) or allele(String) at least once"); } if (tree.isEmpty()) { return locus; } String glstring = tree.toString(); char last = glstri...
java
public Path download(Appcast appcast, Path targetDir) throws IOException, Exception { Path downloaded = null; Enclosure enclosure = appcast.getLatestEnclosure(); if (enclosure != null) { String url = enclosure.getUrl(); if (url != null && !url.isEmpty()) { ...
java
private Stream<Object> flatten(final Object o) { if (o instanceof Map<?, ?>) { return ((Map<?, ?>) o).values().stream().flatMap(this::flatten); } return Stream.of(o); }
java
protected List<File> findEntityClassFiles() throws MojoExecutionException { try { return FileUtils.getFiles(classes, includes, excludes); } catch (IOException e) { throw new MojoExecutionException("Error while scanning for '" + includes + "' in " + "'" + class...
java
protected Options getOptions() throws MojoExecutionException { File persistence = ensurePersistenceXml(); Options opts = new Options(); if (toolProperties != null) { opts.putAll(toolProperties); } opts.put(OPTION_PROPERTIES_FILE, persistence.getAbsolutePath()); ...
java
private void enhance(List<File> files) throws MojoExecutionException { Options opts = getOptions(); // list of input files String[] args = getFilePaths(files); boolean ok; final ClassLoader original = Thread.currentThread().getContextClassLoader(); try { if...
java
protected void handleAlert(Alert alert) { if (LOGGEER.isDebugEnabled()) { LOGGEER.debug("Accepting alert box with message: {}", alert.getText()); } alert.accept(); }
java
public static Path update(Path applicationFile, Path updateDir, boolean removeUpdateFiles) throws IOException { Path newApplicationJar = null; // Extract the application name from the application file String applicationName = applicationFile.getFileName().toString(); // Strip the extensi...
java
protected WebElement getFirstElement(Elements elems) { DocumentWebElement documentWebElement = Iterables.getFirst(elems.as(InternalWebElements.class).wrappedNativeElements(), null); return documentWebElement == null ? null : documentWebElement.getWrappedWebElement(); }
java
@Override public <R> FluentTransaction<R>.Intermediate transaction(Callable<R> callable) { return FluentTransaction.transaction(getTransactionManager()).with(callable); }
java
@Override public T findOne(final I id) { return inTransaction(new Callable<T>() { @Override public T call() throws Exception { return entityManager.find(entity, id); } }); }
java
@Override public Iterable<T> findAll() { return inTransaction(new Callable<Iterable<T>>() { @Override public Iterable<T> call() throws Exception { CriteriaQuery<T> cq = entityManager.getCriteriaBuilder().createQuery(entity); Root<T> pet = cq.from(entit...
java
@Override public T findOne(EntityFilter<T> filter) { for (T object : findAll()) { if (filter.accept(object)) { return object; } } return null; }
java
@Override public Iterable<T> findAll(Iterable<I> ids) { List<T> results = new ArrayList<>(); for (I id : ids) { T t = findOne(id); if (t != null) { results.add(t); } } return results; }
java
@Override public Iterable<T> findAll(EntityFilter<T> filter) { List<T> results = new ArrayList<>(); for (T object : findAll()) { if (filter.accept(object)) { results.add(object); } } return results; }
java
@Override public T delete(final T t) { return inTransaction( new Callable<T>() { @Override public T call() throws Exception { T attached = getAttached(t); if (attached != null) { ...
java
@SuppressWarnings("unchecked") private T getAttached(T object) { if (entityManager.contains(object)) { return object; } else { return findOne((I) entityManager.getEntityManagerFactory() .getPersistenceUnitUtil().getIdentifier(object)); } }
java
@Override public Iterable<T> delete(final Iterable<T> entities) { return inTransaction(new Callable<Iterable<T>>() { @Override public Iterable<T> call() throws Exception { for (T object : entities) { T attached = getAttached(object); ...
java
@Override public Iterable<T> save(final Iterable<T> entities) { return inTransaction(new Callable<Iterable<T>>() { @Override public Iterable<T> call() throws Exception { for (T object : entities) { entityManager.persist(object); } ...
java
private ComponentInstance createUnitInstance(Persistence.PersistenceUnit unit) throws MissingHandlerException, UnacceptableConfiguration, ConfigurationException { LOGGER.info("Creating persistence unit instance for unit {}", unit.getName()); Dictionary<String, Object> configuration = new Has...
java
public boolean hasSlot(final String slotName) { return intentRequest != null && intentRequest.getIntent().getSlots().containsKey(slotName); }
java
public boolean hasSlotIsEqual(final String slotName, final String value) { final String slotValue = getSlotValue(slotName); return (slotValue != null && slotValue.equals(value)) || slotValue == value; }
java
public boolean hasSlotIsDoubleMetaphoneEqual(final String slotName, final String value) { final String slotValue = getSlotValue(slotName); return hasSlotNotBlank(slotName) && value != null && new DoubleMetaphone().isDoubleMetaphoneEqual(slotValue, value); }
java
public boolean hasSlotIsCologneEqual(final String slotName, final String value) { final String slotValue = getSlotValue(slotName); return hasSlotNotBlank(slotName) && value != null && new ColognePhonetic().isEncodeEqual(slotValue, value); }
java
public boolean hasSlotIsPhoneticallyEqual(final String slotName, final String value) { return getLocale().equals("de-DE") ? hasSlotIsCologneEqual(slotName, value) : hasSlotIsDoubleMetaphoneEqual(slotName, value); }
java
public boolean hasSlotNotBlank(final String slotName) { return hasSlot(slotName) && StringUtils.isNotBlank(intentRequest.getIntent().getSlot(slotName).getValue()); }
java
public boolean hasSlotIsNumber(final String slotName) { return hasSlot(slotName) && NumberUtils.isNumber(intentRequest.getIntent().getSlot(slotName).getValue()); }
java
public String getSlotValue(final String slotName) { return hasSlot(slotName) ? intentRequest.getIntent().getSlot(slotName).getValue() : null; }
java
public Class<? extends AlexaSpeechlet> getSpeechlet() { final AlexaApplication app = this.getClass().getAnnotation(AlexaApplication.class); return app != null ? app.speechlet() : AlexaSpeechlet.class; }
java
@Override public void handleRequest(final InputStream input, final OutputStream output, final Context context) throws IOException { byte[] serializedSpeechletRequest = IOUtils.toByteArray(input); final AlexaSpeechlet speechlet = AlexaSpeechletFactory.createSpeechletFromRequest(serializedSpeechletReq...
java
private SpeechletRequestHandler getRequestStreamHandler() { final Set<String> supportedApplicationIds = getSupportedApplicationIds(); // at least one supported application-id need to be provided Validate.notEmpty(supportedApplicationIds, "Must provide supported application-id either with overrid...
java
public static GlClient create() { Injector injector = Guice.createInjector(getLocalModules()); return injector.getInstance(GlClient.class); }
java
public static GlClient createStrict(final Class<? extends Nomenclature> nomenclatureClass) throws IOException { checkNotNull(nomenclatureClass); Injector injector = Guice.createInjector(getLocalStrictModules(nomenclatureClass)); Nomenclature nomenclature = injector.getInstance(Nomenclature.class...
java
public static List<AbstractModule> getLocalStrictModules(final Class<? extends Nomenclature> nomenclatureClass) { checkNotNull(nomenclatureClass); return ImmutableList.of(new LocalStrictModule(), new CacheModule(), new IdModule(), new AbstractModule() { @Override protecte...
java
@Override public Collection<Crud<?, ?>> getCrudServices() { List<Crud<?, ?>> list = new ArrayList<>(); list.addAll(cruds); return list; }
java
public void dispose() { for (ServiceRegistration registration : registrations) { registration.unregister(); } registrations.clear(); for (AbstractJTACrud crud : cruds) { crud.dispose(); } }
java
public GlResourceBuilder reset() { alleles.clear(); alleleLists.clear(); haplotypes.clear(); genotypes.clear(); genotypeLists.clear(); locus = null; allele = null; alleleList = null; haplotype = null; genotype = null; genotypeList =...
java
@Validate public void start() { try { Map<String, Object> map = new HashMap<>(); for (Persistence.PersistenceUnit.Properties.Property p : persistenceUnitXml.getProperties().getProperty()) { map.put(p.getName(), p.getValue()); } ...
java
@Override public ClassLoader getNewTempClassLoader() { return new ClassLoader(getClassLoader()) { //NOSONAR /** * Searches for the .class file and define it using the current class loader. * @param className the class name * @return the class object ...
java
public Xid createXid() { byte[] globalId = baseId.clone(); long id; synchronized (this) { id = count++; } insertLong(id, globalId, 0); return new XidImpl(globalId); }
java
public Xid createBranch(Xid globalId, int branch) { byte[] branchId = baseId.clone(); branchId[0] = (byte) branch; branchId[1] = (byte) (branch >>> 8); branchId[2] = (byte) (branch >>> 16); branchId[3] = (byte) (branch >>> 24); insertLong(start, branchId, 4); retu...
java
public boolean matchesGlobalId(byte[] globalTransactionId) { if (globalTransactionId.length != Xid.MAXGTRIDSIZE) { return false; } for (int i = 8; i < globalTransactionId.length; i++) { if (globalTransactionId[i] != baseId[i]) { return false; }...
java
public boolean matchesBranchId(byte[] branchQualifier) { if (branchQualifier.length != Xid.MAXBQUALSIZE) { return false; } long id = extractLong(branchQualifier, 4); if (id >= start) { // newly created branch, not recoverable return false; } ...
java
public static boolean isPackageInstalled(Context context, String packageName) { try { context.getPackageManager().getApplicationInfo(packageName, 0); return true; } catch (Exception e) { return false; } }
java
public static String getBaseActivityClassName(Context context) { ComponentName activity = getBaseActivity(context); if (activity == null) { return null; } return activity.getClassName(); }
java
public static String getTopActivityPackageName(Context context) { ComponentName activity = getTopActivity(context); if (activity == null) { return null; } return activity.getPackageName(); }
java
public static String getTopActivityClassName(Context context) { ComponentName activity = getTopActivity(context); if (activity == null) { return null; } return activity.getClassName(); }
java
public static boolean isTopApplication(Context context) { ComponentName activity = getTopActivity(context); if (activity == null) { return false; } return activity.getPackageName().equals(context.getApplicationInfo().packageName); }
java
public static boolean isContextForeground(Context context) { ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE); List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses(); int pid = getPid(); for (RunningAppProcessInfo appProcess : a...
java
public DeviceType getDeviceType(Context activityContext) { // Verifies if the Generalized Size of the device is XLARGE to be // considered a Tablet boolean xlarge = ((activityContext.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == SCREENLAYOUT_SIZE_XLARGE); // If XLarg...
java
public static int getCurrentVolume(Context context) { AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE); return mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC); }
java
public static int getMaximumVolume(Context context) { return ((AudioManager) context.getSystemService(Context.AUDIO_SERVICE)).getStreamMaxVolume(AudioManager.STREAM_MUSIC); }
java
private void registerConnectivityReceiver() { IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); context.registerReceiver(connectivityReceiver, intentFilter); }
java
public boolean isWifiFake(String ipAddress, int port) { SocketChannel socketChannel = null; try { socketChannel = SocketChannel.open(); socketChannel.connect(new InetSocketAddress(ipAddress, port)); } catch (IOException e) { Log.d(TAG, "Current Wifi is stupid!!! by IOException"); return true; } catc...
java
@Override public final Object instantiateItem(final ViewGroup container, final int position) { if (Constants.DEBUG) { Log.i("InfiniteViewPager", String.format("instantiating position %s", position)); } final PageModel<T> model = createPageModel(position); mPageModels[posi...
java
private void printPageModels(final String tag) { for (int i = 0; i < PAGE_COUNT; i++) { printPageModel(tag, mPageModels[i], i); } }
java
public final Position predict(double distanceKm, double courseDegrees) { assertWithMsg(alt == 0.0, "Predictions only valid for Earth's surface"); double dr = distanceKm / EARTH_RADIUS_KM; double latR = toRadians(lat); double lonR = toRadians(lon); double courseR = toRadians(cours...
java
public final double getBearingDegrees(Position position) { double lat1 = toRadians(lat); double lat2 = toRadians(position.lat); double lon1 = toRadians(lon); double lon2 = toRadians(position.lon); double dLon = lon2 - lon1; double sinDLon = sin(dLon); double cosLa...
java
public static double getBearingDifferenceDegrees(double bearing1, double bearing2) { if (bearing1 < 0) bearing1 += 360; if (bearing2 > 180) bearing2 -= 360; double result = bearing1 - bearing2; if (result > 180) result -= 360; return result; ...
java
public final Position getPositionAlongPath(Position position, double proportion) { if (proportion >= 0 && proportion <= 1) { // Get bearing degrees for course double courseDegrees = this.getBearingDegrees(position); // Get distance from position arg and this objects locati...
java
public static double longitudeDiff(double a, double b) { a = to180(a); b = to180(b); return Math.abs(to180(a - b)); }
java
public static double to180(double d) { if (d < 0) return -to180(abs(d)); else { if (d > 180) { long n = round(floor((d + 180) / 360.0)); return d - n * 360; } else return d; } }
java