code
stringlengths
73
34.1k
label
stringclasses
1 value
public SettingsPack connectionsLimit(int value) { sp.set_int(settings_pack.int_types.connections_limit.swigValue(), value); return this; }
java
public SettingsPack maxPeerlistSize(int value) { sp.set_int(settings_pack.int_types.max_peerlist_size.swigValue(), value); return this; }
java
public SettingsPack inactivityTimeout(int value) { sp.set_int(settings_pack.int_types.inactivity_timeout.swigValue(), value); return this; }
java
public SettingsPack enableDht(boolean value) { sp.set_bool(settings_pack.bool_types.enable_dht.swigValue(), value); return this; }
java
public SettingsPack upnpIgnoreNonRouters(boolean value) { sp.set_bool(settings_pack.bool_types.upnp_ignore_nonrouters.swigValue(), value); return this; }
java
public TorrentBuilder addNode(Pair<String, Integer> value) { if (value != null) { this.nodes.add(value); } return this; }
java
public Result generate() throws IOException { if (path == null) { throw new IOException("path can't be null"); } File absPath = path.getAbsoluteFile(); file_storage fs = new file_storage(); add_files_listener l1 = new add_files_listener() { @Override ...
java
public static byte[] bytes(File file) throws IOException { InputStream in = null; try { in = openInputStream(file); return toByteArray(in, file.length()); } finally { closeQuietly(in); } }
java
public Priority[] filePriorities() { int_vector v = th.get_file_priorities2(); int size = (int) v.size(); Priority[] arr = new Priority[size]; for (int i = 0; i < size; i++) { arr[i] = Priority.fromSwig(v.get(i)); } return arr; }
java
public String name() { torrent_status ts = th.status(torrent_handle.query_name); return ts.getName(); }
java
public static <T, S extends T> Optional<T> of(S value) { if (value == null) { throw new IllegalArgumentException("Optional does not support NULL, use Optional.empty() instead."); } return new Optional<T>(value); }
java
public ErrorResponse parseError(Response response) { if (response.isSuccessful()) { throw new IllegalArgumentException("Response must be unsuccessful."); } Converter<ResponseBody, ErrorResponse> responseBodyObjectConverter = retrofit.responseBodyConverter(ErrorResponse.class, new Annotation[0])...
java
public static void notEmpty(Collection collection, String name) { notNull(collection, name); if (collection.isEmpty()) { throw new IllegalArgumentException(name + " must not be empty"); } }
java
public static void notEmpty(Object[] arr, String name) { notNull(arr, name); if (arr.length == 0) { throw new IllegalArgumentException(name + "must not be empty"); } }
java
public static void notEmpty(Map map, String name) { notNull(map, name); if (map.isEmpty()) { throw new IllegalArgumentException(name + " must not be empty"); } }
java
public static void isBetween(Integer value, int min, int max, String name) { notNull(value, name); if (value < min || value > max) { throw new IllegalArgumentException(name + "(" + value + ") out of range: " + min + " <= " + name + " <= " + max); } }
java
public static void isPositive(Integer value, String name) { notNull(value, name); if (value < 0) { throw new IllegalArgumentException(name + "must be a positive number."); } }
java
public static Map<String, String> arrayToMap(String[] args) { if (args.length % 2 != 0) { throw new IllegalArgumentException("Must pass in an even number of args, one key per value."); } Map<String, String> ret = new HashMap<>(); for (int i = 0; i < args.length; i += 2) { ret.put(args[i], ...
java
private static <T> int binarySearch0(Sortable<T> a, int fromIndex, int toIndex, T key, Comparator<? super T> c) { if (c == null) { throw new NullPointerException(); } int low = fromIndex; int high = toIndex - 1; while (low <= high) { int mid = (low + high...
java
public void addState() { DiffHistoryDataState nextState = new DiffHistoryDataState(stateEngine, typeDiffInstructions); if(currentDataState != null) newHistoricalState(currentDataState, nextState); currentDataState = nextState; }
java
public String generateDiff(String objectType, Object from, Object to) { GenericObject fromGenericObject = from == null ? null : genericObjectFramework.serialize(from, objectType); GenericObject toGenericObject = to == null ? null : genericObjectFramework.serialize(to, objectType); return genera...
java
public String generateDiff(GenericObject from, GenericObject to) { StringBuilder builder = new StringBuilder(); builder.append("<table class=\"nomargin diff\">"); builder.append("<thead>"); builder.append("<tr>"); builder.append("<th/>"); builder.append("<th class=\"text...
java
public DiffReport performDiff(FastBlobStateEngine fromState, FastBlobStateEngine toState) throws DiffReportGenerationException { return performDiff(null, fromState, toState); }
java
public void runCycle(int... valuesForMap) { /// prepare the map Object array recycler for a new cycle. HeapFriendlyMapArrayRecycler.get().swapCycleObjectArrays(); try { makeDataAvailableToApplication(valuesForMap); } finally { // fill all of the Object arrays whi...
java
public void serializePrimitive(S rec, String fieldName, long value) { serializePrimitive(rec, fieldName, Long.valueOf(value)); }
java
public void serializePrimitive(S rec, String fieldName, float value) { serializePrimitive(rec, fieldName, Float.valueOf(value)); }
java
public void serializePrimitive(S rec, String fieldName, double value) { serializePrimitive(rec, fieldName, Double.valueOf(value)); }
java
public <K, V> void serializeSortedMap(S rec, String fieldName, String keyTypeName, String valueTypeName, SortedMap<K, V> obj) { serializeMap(rec, fieldName, keyTypeName, valueTypeName, obj); }
java
private <K, V> List<Map.Entry<K, V>> sortedEntryList(Map<K, V> obj) { List<Map.Entry<K, V>> entryList = new ArrayList<Map.Entry<K, V>>(obj.entrySet()); Collections.sort(entryList, new Comparator<Map.Entry<K, V>>() { @Override @SuppressWarnings({ "unchecked", "rawtypes" }) ...
java
public List<Object> getList(DiffPropertyPath path) { Integer listIndex = fieldValuesLists.get(path); if(listIndex == null) return null; return getList(listIndex.intValue()); }
java
private void reset() { int count = 0; for (int i = 0; i < tableLength; i++) { long t = tableAt(i); count += Long.bitCount(t & ONE_MASK); tableAt(i, (t >>> 1) & RESET_MASK); } size = (size >>> 1) - (count >>> 2); }
java
public long average() { double sum = 0; int count = 0; for (float d = 0 ; d <= 1.0d ; d += 0.02d) { sum += inverseCumProb(d); count += 1; } return (long) (sum / count); }
java
void add(long hashEntryAdr, long expireAt) { // just ignore the fact that expireAt can be less than current time int slotNum = slot(expireAt); slots[slotNum].add(hashEntryAdr, expireAt); }
java
void remove(long hashEntryAdr, long expireAt) { int slot = slot(expireAt); slots[slot].remove(hashEntryAdr); }
java
int removeExpired(TimeoutHandler expireHandler) { // ensure the clock never goes backwards long t = ticker.currentTimeMillis(); int expired = 0; for (int i = 0; i < slotCount; i++) { expired += slots[i].removeExpired(t, expireHandler); } return ex...
java
private void assertValidDateFieldType(Optional<Field> field) { field.ifPresent(it -> { if (SUPPORTED_DATE_TYPES.contains(it.getType().getName())) { return; } Class<?> type = it.getType(); if (Jsr310Converters.supports(type) || ThreeTenBackPortConverters.supports(type)) { return; } ...
java
protected <X> long calculateTotal(Pageable pager, List<X> result) { if (pager.hasPrevious()) { if (CollectionUtils.isEmpty(result)) { return -1; } if (result.size() == pager.getPageSize()) { return -1; } return (pager.getPageNumber() - 1) * pager.getPageSize() + result.size(); } if (result....
java
protected final int bindLimitParameters(RowSelection selection, PreparedStatement statement, int index) throws SQLException { if (!supportsVariableLimit() || !LimitHelper.hasMaxRows(selection)) { return 0; } final int firstRow = convertToFirstRowValue(LimitHelper.getFirstRow(selection)); final int lastRow...
java
public <T> T markCreated(T source) { Assert.notNull(source, "Entity must not be null!"); return touch(source, true); }
java
public <T> T markModified(T source) { Assert.notNull(source, "Entity must not be null!"); return touch(source, false); }
java
protected final boolean isAuditable(Object source) { Assert.notNull(source, "Source must not be null!"); return factory.getBeanWrapperFor(source).isPresent(); }
java
private Optional<Object> touchAuditor(AuditableBeanWrapper<?> wrapper, boolean isNew) { Assert.notNull(wrapper, "AuditableBeanWrapper must not be null!"); return auditorAware.map(it -> { Optional<?> auditor = it.getCurrentAuditor(); Assert.notNull(auditor, () -> String.format("Auditor must not be ...
java
private Optional<TemporalAccessor> touchDate(AuditableBeanWrapper<?> wrapper, boolean isNew) { Assert.notNull(wrapper, "AuditableBeanWrapper must not be null!"); Optional<TemporalAccessor> now = dateTimeProvider.getNow(); Assert.notNull(now, () -> String.format("Now must not be null! Returned by: %s!", ...
java
protected SqlSource buildSqlSourceFromStrings(String[] strings, Class<?> parameterTypeClass) { final StringBuilder sql = new StringBuilder(); for (String fragment : strings) { sql.append(fragment); sql.append(" "); } LanguageDriver languageDriver = getLanguageDriver(); return languageDriver.createSql...
java
public static boolean hasMaxRows(RowSelection selection) { return selection != null && selection.getMaxRows() != null && selection.getMaxRows() > 0; }
java
public static int getFirstRow(RowSelection selection) { return (selection == null || selection.getFirstRow() == null) ? 0 : selection.getFirstRow(); }
java
public static List<Event> parse(String requestBody, String signatureHeader, String webhookEndpointSecret) { if (isValidSignature(requestBody, signatureHeader, webhookEndpointSecret)) { return WebhookParser.parse(requestBody); } else { throw new InvalidSignatureExcepti...
java
public static boolean isValidSignature(String requestBody, String signatureHeader, String webhookEndpointSecret) { String computedSignature = new HmacUtils(HmacAlgorithms.HMAC_SHA_256, webhookEndpointSecret) .hmacHex(requestBody); return MessageDigest....
java
public static GoCardlessApiException toException(ApiErrorResponse error) { switch (error.getType()) { case GOCARDLESS: return new GoCardlessInternalException(error); case INVALID_API_USAGE: return new InvalidApiUsageException(error); case INVAL...
java
public Map<String, String> getLinks() { if (links == null) { return ImmutableMap.of(); } return ImmutableMap.copyOf(links); }
java
private void buildRecorderFromObject( int opcode, String owner, String name, String signature, boolean itf) { super.visitMethodInsn(opcode, owner, name, signature, itf); // -> stack: ... newobj super.visitInsn(Opcodes.DUP); // -> stack: ... newobj newobj super.visitInsn(Opcodes.DUP); // ->...
java
@Override public void visitMaxs(int maxStack, int maxLocals) { if (localScopes != null) { for (VariableScope scope : localScopes) { super.visitLocalVariable( "xxxxx$" + scope.index, scope.desc, null, scope.start, scope.end, scope.index); } } super.visitMaxs(maxStack, maxLoc...
java
private int newLocal(Type type, String typeDesc, Label begin, Label end) { int newVar = lvs.newLocal(type); getLocalScopes().add(new VariableScope(newVar, begin, end, typeDesc)); return newVar; }
java
@Override public void visitMultiANewArrayInsn(String typeName, int dimCount) { // stack: ... dim1 dim2 dim3 ... dimN super.visitMultiANewArrayInsn(typeName, dimCount); // -> stack: ... aref calculateArrayLengthAndDispatch(typeName, dimCount); }
java
public static void instrumentClass(Class<?> c, ConstructorCallback<?> sampler) throws UnmodifiableClassException { // IMPORTANT: Don't forget that other threads may be accessing this // class while this code is running. Specifically, the class may be // executed directly after the retransformClasses ...
java
public static byte[] instrument(byte[] originalBytes, Class<?> classBeingRedefined) { try { ClassReader cr = new ClassReader(originalBytes); ClassWriter cw = new ClassWriter(cr, ClassWriter.COMPUTE_MAXS); VerifyingClassAdapter vcw = new VerifyingClassAdapter(cw, originalBytes, cr.getClassName()); ...
java
@SuppressWarnings("unchecked") public static void invokeSamplers(Object o) { Class<?> currentClass = o.getClass(); while (currentClass != null) { List<ConstructorCallback<?>> samplers = samplerMap.get(currentClass); if (samplers != null) { // Leave in the @SuppressWarnings, because we defi...
java
public byte[] toByteArray() { if (state != State.PASS) { logger.log(Level.WARNING, "Failed to instrument class " + className + " because " + message); return original; } return cw.toByteArray(); }
java
private static long getObjectSize(Object obj, boolean isArray, Instrumentation instr) { if (isArray) { return instr.getObjectSize(obj); } Class<?> clazz = obj.getClass(); Long classSize = classSizesMap.get(clazz); if (classSize == null) { classSize = instr.getObjectSize(obj); clas...
java
public static void recordAllocation(int count, String desc, Object newObj) { if (Objects.equals(recordingAllocation.get(), Boolean.TRUE)) { return; } recordingAllocation.set(Boolean.TRUE); if (count >= 0) { desc = desc.replace('.', '/'); } // Copy value into local variable to prev...
java
@Override public void onNewTraces(List<Trace> traces) { int tracesRemoved = updateTraceBuffer(traces); List<Trace> tracesToNotify = getCurrentTraces(); view.showTraces(tracesToNotify, tracesRemoved); }
java
public void updateFilter(String filter) { if (isInitialized) { LynxConfig lynxConfig = lynx.getConfig(); lynxConfig.setFilter(filter); lynx.setConfig(lynxConfig); clearView(); restartLynx(); } }
java
public void onShareButtonClicked() { List<Trace> tracesToShare = new LinkedList<Trace>(traceBuffer.getTraces()); String plainTraces = generatePlainTracesToShare(tracesToShare); if (!view.shareTraces(plainTraces)) { view.notifyShareTracesFailed(); } }
java
@Override public void run() { super.run(); try { process = Runtime.getRuntime().exec("logcat -v time"); } catch (IOException e) { Log.e(LOGTAG, "IOException executing logcat command.", e); } readLogcat(); }
java
private void generateFiveRandomTracesPerSecond() { logGeneratorThread = new Thread(new Runnable() { @Override public void run() { while (continueReading) { int traceLevel = traceCounter % 6; switch (traceLevel) { case 0: Log.d("Lynx", traceCounter + " - De...
java
@Override protected void onVisibilityChanged(View changedView, int visibility) { super.onVisibilityChanged(changedView, visibility); if (changedView != this) { return; } if (visibility == View.VISIBLE) { resumePresenter(); } else { pausePresenter(); } }
java
public void setLynxConfig(LynxConfig lynxConfig) { validateLynxConfig(lynxConfig); boolean hasChangedLynxConfig = !this.lynxConfig.equals(lynxConfig); if (hasChangedLynxConfig) { this.lynxConfig = (LynxConfig) lynxConfig.clone(); updateFilterText(); updateAdapter(); updateSpinner(); ...
java
@CheckResult @Override public boolean shareTraces(String fullTraces) { try { shareTracesInternal(fullTraces); return true; } catch (RuntimeException exception1) { // Likely cause is a TransactionTooLargeException on API levels 15+. try { /* * Limit trace size to between 100kB ...
java
private void configureCursorColor() { try { Field f = TextView.class.getDeclaredField("mCursorDrawableRes"); f.setAccessible(true); f.set(et_filter, R.drawable.edit_text_cursor_color); } catch (Exception e) { Log.e(LOGTAG, "Error trying to change cursor color text cursor drawable to null...
java
public static Intent getIntent(Context context, LynxConfig lynxConfig) { if (lynxConfig == null) { lynxConfig = new LynxConfig(); } Intent intent = new Intent(context, LynxActivity.class); intent.putExtra(LYNX_CONFIG_EXTRA, lynxConfig); return intent; }
java
public void startReading() { logcat.setListener(new Logcat.Listener() { @Override public void onTraceRead(String logcatTrace) { try { addTraceToTheBuffer(logcatTrace); } catch (IllegalTraceException e) { return; } notifyNewTraces(); } }); boole...
java
public synchronized void restart() { Logcat.Listener previousListener = logcat.getListener(); logcat.stopReading(); logcat.interrupt(); logcat = (Logcat) logcat.clone(); logcat.setListener(previousListener); lastNotificationTime = 0; tracesToNotify.clear(); logcat.start(); }
java
public void init(final LynxConfig lynxConfig) { ShakeDetector shakeDetector = new ShakeDetector(new ShakeDetector.Listener() { @Override public void hearShake() { if (isEnabled) { openLynxActivity(lynxConfig); } } }); SensorManager sensorManager = (SensorManager) contex...
java
public List<String> list(URL url, String path) throws IOException { InputStream is = null; try { List<String> resources = new ArrayList<String>(); // First, try to find the URL of a JAR file containing the requested resource. If a JAR // file is found, then we'll lis...
java
public void doBackgroundOp( final Runnable run, final boolean showWaitCursor ) { final Component[] key = new Component[1]; ExecutorService jobRunner = getJobRunner(); if( jobRunner != null ) { jobRunner.submit( () -> performBackgroundOp( run, key, showWaitCursor ) ); } else { r...
java
public static int getArrayLength( Object obj ) { if( obj == null ) { return 0; } IType type = TypeLoaderAccess.instance().getIntrinsicTypeFromObject( obj ); if( type.isArray() ) { return type.getArrayLength( obj ); } if( obj instanceof CharSequence ) { return ((...
java
private boolean canAccessPrivateMembers( IType ownersClass, IType whosAskin ) { return getOwnersType() == whosAskin || getTopLevelTypeName( whosAskin ).equals( getTopLevelTypeName( ownersClass ) ); }
java
public static <T> T findAncestor( Component start, Class<T> aClass ) { if( start == null ) { return null; } return findAtOrAbove( start.getParent(), aClass ); }
java
public static <T> T findAtOrAbove( Component start, Class<T> aClass ) { Component comp = start; while( comp != null ) { if( aClass.isInstance( comp ) ) { return (T)comp; } else { comp = comp.getParent(); } } return null; }
java
public SimpleXmlNode shallowCopy() { SimpleXmlNode copy = new SimpleXmlNode(_name); copy.setText(_text); copy.getAttributes().putAll(_attributes); return copy; }
java
public SimpleXmlNode deepCopy() { SimpleXmlNode rootCopy = shallowCopy(); for (SimpleXmlNode child : _children) { rootCopy.getChildren().add(child.deepCopy()); } return rootCopy; }
java
private void removeUseless() { Set<Map.Entry<String, PropertyNode>> entries = _children.entrySet(); for (Iterator<Map.Entry<String, PropertyNode>> it = entries.iterator(); it.hasNext(); ) { Map.Entry<String, PropertyNode> entry = it.next(); PropertyNode child = entry.getValue(); child.removeUs...
java
public void setReadMethod( Method getter ) throws IntrospectionException { super.setReadMethod( getter ); if( _propertyClass == null ) { _propertyClass = super.getPropertyType(); } }
java
private void compileJavaInteropBridgeConstructor( DynamicFunctionSymbol dfs ) { DynamicFunctionSymbol copy = new DynamicFunctionSymbol( dfs ); copy.setValue( null ); copy.setInitializer( null ); ConstructorStatement fs = new ConstructorStatement( true ); fs.setDynamicFunctionSymbol( copy ); fs...
java
public Object evaluate() { if( !isCompileTimeConstant() ) { return super.evaluate(); } Object value = getLHS().evaluate(); IType argType = getType(); if( value instanceof IType && argType instanceof IJavaType && JavaTypes.CLASS() == TypeLord.getPureGenericType( argType ) ) { ...
java
public static ProgressFeedback runWithProgress( final String strNotice, final IRunnableWithProgress task ) { return runWithProgress( strNotice, task, false, false ); }
java
public Object parse() { Object val = null; if(T.isValueType()) { val = parseValue(); } else { addError(); } return val; }
java
public Object parseValue() { Object val; switch(T.getType()) { case LCURLY: val = parseObject(); break; case LSQUARE: val = parseArray(); break; case INTEGER: if(useBig) { val = new BigInteger(T.getString()); } else { try { ...
java
private TypeVarToTypeMap mapTypes( TypeVarToTypeMap actualParamByVarName, IType... types ) { for( int i = 0; i < types.length; i++ ) { IType type = types[i]; if( type instanceof ITypeVariableType ) { actualParamByVarName.put( (ITypeVariableType)types[i], types[i] ); } if(...
java
public ProcessRunner withEnvironmentVariable(String name, String value) { _env.put(name, value); return this; }
java
public V put(K key, V value) { return _cacheImpl.put(key, value); }
java
public V get(K key) { V value = _cacheImpl.get(key); _requests.incrementAndGet(); if (value == null) { value = _missHandler.load(key); _cacheImpl.put(key, value); _misses.incrementAndGet(); } else { _hits.incrementAndGet(); } return value; }
java
public synchronized Cache<K, V> logEveryNSeconds(int seconds, final ILogger logger) { if (_loggingTask == null) { ScheduledExecutorService service = Executors.newScheduledThreadPool(1); _loggingTask = service.scheduleAtFixedRate(new Runnable() { public void run() { logger.info(Cache.th...
java
@Override public void setUndoableEditListener( UndoableEditListener uel ) { if( _uel != null ) { getEditor().getDocument().removeUndoableEditListener( _uel ); } _uel = uel; if( _uel != null ) { getEditor().getDocument().addUndoableEditListener( _uel ); } }
java
private IType getCompilingClass() { if( isIncludeAll() ) { return _gsClass; } IType type = GosuClassCompilingStack.getCurrentCompilingType(); if( type != null ) { return type; } ISymbolTable symTableCtx = CompiledGosuClassSymbolTable.getSymTableCtx(); ISymbol thisSymbo...
java
public Object evaluate() { if( !isCompileTimeConstant() ) { return super.evaluate(); } return (Boolean)getLHS().evaluate() || (Boolean)getRHS().evaluate(); }
java
public static int getModifiersFrom( IAttributedFeatureInfo afi ) { int iModifiers = 0; iModifiers = Modifier.setBit( iModifiers, afi.isPublic(), PUBLIC ); iModifiers = Modifier.setBit( iModifiers, afi.isPrivate(), PRIVATE ); iModifiers = Modifier.setBit( iModifiers, afi.isProtected(), PROTECTED ); ...
java
public static boolean isAM(Date date) { return dateToCalendar(date).get(Calendar.AM_PM) == Calendar.AM; }
java
public static boolean isPM(Date date) { return dateToCalendar(date).get(Calendar.AM_PM) == Calendar.PM; }
java
public Color getForeground( int code ) { Style s = _tokenStyles.get( new Integer( code ) ); if( s == null ) { s = getStyle( DEFAULT_STYLE ); } return getForeground( s ); }
java