code
stringlengths
73
34.1k
label
stringclasses
1 value
private static void mkdir(@NonNull final File directory, final boolean createParents) throws IOException { Condition.INSTANCE.ensureNotNull(directory, "The directory may not be null"); boolean result = createParents ? directory.mkdirs() : directory.mkdir(); if (!result && !directory...
java
public static void deleteRecursively(@NonNull final File file) throws IOException { Condition.INSTANCE.ensureNotNull(file, "The file or directory may not be null"); if (file.isDirectory()) { for (File child : file.listFiles()) { deleteRecursively(child); } ...
java
public static void createNewFile(@NonNull final File file, final boolean overwrite) throws IOException { Condition.INSTANCE.ensureNotNull(file, "The file may not be null"); boolean result = file.createNewFile(); if (!result) { if (overwrite) { try { ...
java
public void maybeDoOffset(){ long seen = tuplesSeen; if (offsetCommitInterval > 0 && seen % offsetCommitInterval == 0 && offsetStorage != null && fp.supportsOffsetManagement()){ doOffsetInternal(); } }
java
private static TypedArray obtainStyledAttributes(@NonNull final Context context, @StyleRes final int themeResourceId, @AttrRes final int resourceId) { Condition.INSTANCE.ensureNotNull(context, "The context ...
java
public static boolean getBoolean(@NonNull final Context context, @StyleRes final int themeResourceId, @AttrRes final int resourceId) { TypedArray typedArray = null; try { typedArray = obtainStyledAttributes(context, t...
java
public static boolean getBoolean(@NonNull final Context context, @AttrRes final int resourceId, final boolean defaultValue) { return getBoolean(context, -1, resourceId, defaultValue); }
java
public static int getInt(@NonNull final Context context, @AttrRes final int resourceId, final int defaultValue) { return getInt(context, -1, resourceId, defaultValue); }
java
public static float getFloat(@NonNull final Context context, @AttrRes final int resourceId, final float defaultValue) { return getFloat(context, -1, resourceId, defaultValue); }
java
public static int getResId(@NonNull final Context context, @AttrRes final int resourceId, final int defaultValue) { return getResId(context, -1, resourceId, defaultValue); }
java
void setRequest(HttpUriRequest request) { requestLock.lock(); try { if (this.request != null) { throw new SparqlException("Command is already executing a request."); } this.request = request; } finally { requestLock.unlock(); } }
java
private Result execute(ResultType cmdType) throws SparqlException { String mimeType = contentType; // Validate the user-supplied MIME type. if (mimeType != null && !ResultFactory.supports(mimeType, cmdType)) { logger.warn("Requested MIME content type '{}' does not support expected response type: ...
java
private void logRequest(ResultType cmdType, String mimeType) { StringBuilder sb = new StringBuilder("Executing SPARQL protocol request "); sb.append("to endpoint <").append(((ProtocolDataSource)getConnection().getDataSource()).getUrl()).append("> "); if (mimeType != null) { sb.append("for content type...
java
public void initialize(){ thread = new Thread(collectorProcessor); thread.start(); for (DriverNode dn : this.children){ dn.initialize(); } }
java
public void addChild(DriverNode dn){ collectorProcessor.getChildren().add(dn.operator); children.add(dn); }
java
public static String getNamespace(JsonNode node) { JsonNode nodeNs = obj(node).get(ID_NAMESPACE); return (nodeNs != null) ? nodeNs.asText() : null; }
java
public static void setVersion(JsonNode node, Long version) { obj(node).put(ID_VERSION, version); }
java
public static Date getTimestamp(JsonNode node) { String text = obj(node).get(ID_TIMESTAMP).asText(); return isNotBlank(text) ? from(instantUtc(text)).toDate() : null; }
java
public final void update(final float position) { if (reset) { reset = false; distance = 0; thresholdReachedPosition = -1; dragStartTime = -1; dragStartPosition = position; reachedThreshold = false; minDragDistance = 0; ...
java
public final void setMaxDragDistance(final float maxDragDistance) { if (maxDragDistance != 0) { Condition.INSTANCE.ensureGreater(maxDragDistance, threshold, "The maximum drag distance must be greater than " + threshold); } this.maxDragDistance = maxDragDistance; ...
java
public final void setMinDragDistance(final float minDragDistance) { if (minDragDistance != 0) { Condition.INSTANCE.ensureSmaller(minDragDistance, -threshold, "The minimum drag distance must be smaller than " + -threshold); } this.minDragDistance = minDragDistance...
java
public final float getDragSpeed() { if (hasThresholdBeenReached()) { long interval = System.currentTimeMillis() - dragStartTime; return Math.abs(getDragDistance()) / (float) interval; } else { return -1; } }
java
private OnSeekBarChangeListener createSeekBarListener() { return new OnSeekBarChangeListener() { @Override public void onProgressChanged(final SeekBar seekBar, final int progress, final boolean fromUser) { adaptElevation(progress...
java
private void adaptElevation(final int elevation, final boolean parallelLight) { elevationTextView.setText(String.format(getString(R.string.elevation), elevation)); elevationLeft.setShadowElevation(elevation); elevationLeft.emulateParallelLight(parallelLight); elevationTopLeft.setShadowEl...
java
public Segment getSegment(SEGMENT_TYPE segmentType){ if(segmentType == null){ return null; } if(segmentType == SEGMENT_TYPE.LINEAR){ return new LinearSegment(); } else if(segmentType == SEGMENT_TYPE.SPATIAL){ return new SpatialSegment(); } else if(segmentType == SEGMENT_TYPE.TEMPORAL){ r...
java
public String write(T obj) throws JsonProcessingException { Date ts = includeTimestamp ? Date.from(now()) : null; MetaWrapper wrapper = new MetaWrapper(getHighestSourceVersion(), getNamespace(), obj, ts); return mapper.writeValueAsString(wrapper); }
java
private void obtainInsetForeground(@NonNull final TypedArray typedArray) { int color = typedArray.getColor(R.styleable.ScrimInsetsLayout_insetDrawable, -1); if (color == -1) { Drawable drawable = typedArray.getDrawable(R.styleable.ScrimInsetsLayout_insetDrawable); if (drawable ...
java
public void parse (final int nYear, final HolidayMap aHolidayMap, final Holidays aConfig) { for (final RelativeToEasterSunday aDay : aConfig.getRelativeToEasterSunday ()) { if (!isValid (aDay, nYear)) continue; final ChronoLocalDate aEasterSunday = getEasterSunday (nYear, aDay.getChronolog...
java
protected final void addChrstianHoliday (final ChronoLocalDate aDate, final String sPropertiesKey, final IHolidayType aHolidayType, final HolidayMap holidays) { final LocalDate converte...
java
public static ChronoLocalDate getEasterSunday (final int nYear) { return nYear <= CPDT.LAST_JULIAN_YEAR ? getJulianEasterSunday (nYear) : getGregorianEasterSunday (nYear); }
java
public static JulianDate getJulianEasterSunday (final int nYear) { final int a = nYear % 4; final int b = nYear % 7; final int c = nYear % 19; final int d = (19 * c + 15) % 30; final int e = (2 * a + 4 * b - d + 34) % 7; final int x = d + e + 114; final int nMonth = x / 31; final int n...
java
public static LocalDate getGregorianEasterSunday (final int nYear) { final int a = nYear % 19; final int b = nYear / 100; final int c = nYear % 100; final int d = b / 4; final int e = b % 4; final int f = (b + 8) / 25; final int g = (b - f + 1) / 3; final int h = (19 * a + b - d - g + ...
java
private static Bitmap createEdgeShadow(@NonNull final Context context, final int elevation, @NonNull final Orientation orientation, final boolean parallelLight) { if (elevation == 0) { return null; } else {...
java
private static Bitmap createCornerShadow(@NonNull final Context context, final int elevation, @NonNull final Orientation orientation, final boolean parallelLight) { if (elevation == 0) { return null; } ...
java
private static RectF getCornerBounds(@NonNull final Orientation orientation, final int size) { switch (orientation) { case TOP_LEFT: return new RectF(0, 0, 2 * size, 2 * size); case TOP_RIGHT: return new RectF(-size, 0, size, 2 * size); case BO...
java
private static float getHorizontalShadowWidth(@NonNull final Context context, final int elevation, @NonNull final Orientation orientation, final boolean parallelLight) { ...
java
private static float getShadowWidth(@NonNull final Context context, final int elevation, @NonNull final Orientation orientation, final boolean parallelLight) { float referenceElevationWidth = (float) elevation / (flo...
java
private static int getHorizontalShadowColor(final int elevation, @NonNull final Orientation orientation, final boolean parallelLight) { switch (orientation) { case TOP_LEFT: case TOP_RIGHT: ...
java
private static int getVerticalShadowColor(final int elevation, @NonNull final Orientation orientation, final boolean parallelLight) { switch (orientation) { case TOP_LEFT: case BOTTOM_LEFT: ...
java
private static int getShadowColor(final int elevation, @NonNull final Orientation orientation, final boolean parallelLight) { int alpha; if (parallelLight) { alpha = getShadowAlpha(elevation, MIN_BOTTOM_ALPHA, MAX_BOTTOM_ALPHA); } else { ...
java
private static int getShadowAlpha(final int elevation, final int minTransparency, final int maxTransparency) { float ratio = (float) elevation / (float) MAX_ELEVATION; int range = maxTransparency - minTransparency; return Math.round(minTransparency + ratio *...
java
private static Shader createLinearGradient(@NonNull final Orientation orientation, final int bitmapWidth, final int bitmapHeight, final float shadowWidth, @ColorInt final int shad...
java
private static Shader createRadialGradient(@NonNull final Orientation orientation, final int bitmapSize, final float radius) { PointF center = new PointF(); switch (orientation) { case TOP_LEFT: center.x = bitmapSize; ...
java
private static float getCornerAngle(@NonNull final Orientation orientation) { switch (orientation) { case TOP_LEFT: return QUARTER_ARC_DEGRESS * 2; case TOP_RIGHT: return QUARTER_ARC_DEGRESS * 3; case BOTTOM_LEFT: return QUARTER...
java
public static Bitmap createElevationShadow(@NonNull final Context context, final int elevation, @NonNull final Orientation orientation) { return createElevationShadow(context, elevation, orientation, false); }
java
public static Bitmap createElevationShadow(@NonNull final Context context, final int elevation, @NonNull final Orientation orientation, final boolean parallelLight) { Condition.INSTANCE.ensureNotNull(context, "The cont...
java
private void mergeTemplate(String templateFilename, File folder, String javaFilename, boolean overwrite) { final File javaFile = new File(folder, javaFilename); // create destination folder? File destinationFolder = javaFile.getParentFile(); if (false == destinationFo...
java
private static void processResource(String resourceName, AbstractProcessor processor) { InputStream lastNameStream = NameDbUsa.class.getClassLoader().getResourceAsStream(resourceName); BufferedReader lastNameReader = new BufferedReader(new InputStreamReader(lastNameStream)); try { in...
java
private int binarySearch(@NonNull final List<ItemType> list, @NonNull final ItemType item, @NonNull final Comparator<ItemType> comparator) { int index = Collections.binarySearch(list, item, comparator); if (index < 0) { index = ~index; } return ...
java
public final void setComparator(@Nullable final Comparator<ItemType> comparator) { this.comparator = comparator; if (comparator != null) { if (items.size() > 0) { List<ItemType> newItems = new ArrayList<>(); List<View> views = new ArrayList<>(); ...
java
public <T> T httpRequest(HttpMethod method, Class<T> cls, Map<String, Object> params, Object data, String... segments) { HttpHeaders requestHeaders = new HttpHeaders(); requestHeaders.setAccept(Collections .singletonList(MediaType.APPLICATION_JSON)); if (accessToken !...
java
public ApiResponse apiRequest(HttpMethod method, Map<String, Object> params, Object data, String... segments) { ApiResponse response = null; try { response = httpRequest(method, ApiResponse.class, params, data, segments); log.info("Client.apiReques...
java
public ApiResponse authorizeAppUser(String email, String password) { validateNonEmptyParam(email, "email"); validateNonEmptyParam(password,"password"); assertValidApplicationId(); loggedInUser = null; accessToken = null; currentOrganization = null; Map<String, Obj...
java
public ApiResponse changePassword(String username, String oldPassword, String newPassword) { Map<String, Object> data = new HashMap<String, Object>(); data.put("newpassword", newPassword); data.put("oldpassword", oldPassword); return apiRequest(HttpMethod.POST, null, data, ...
java
public ApiResponse authorizeAppClient(String clientId, String clientSecret) { validateNonEmptyParam(clientId, "client identifier"); validateNonEmptyParam(clientSecret, "client secret"); assertValidApplicationId(); loggedInUser = null; accessToken = null; currentOrganizati...
java
public ApiResponse createEntity(Entity entity) { assertValidApplicationId(); if (isEmpty(entity.getType())) { throw new IllegalArgumentException("Missing entity type"); } ApiResponse response = apiRequest(HttpMethod.POST, null, entity, organizationId, applicat...
java
public ApiResponse createEntity(Map<String, Object> properties) { assertValidApplicationId(); if (isEmpty(properties.get("type"))) { throw new IllegalArgumentException("Missing entity type"); } ApiResponse response = apiRequest(HttpMethod.POST, null, properties, ...
java
public Map<String, Group> getGroupsForUser(String userId) { ApiResponse response = apiRequest(HttpMethod.GET, null, null, organizationId, applicationId, "users", userId, "groups"); Map<String, Group> groupMap = new HashMap<String, Group>(); if (response != null) { Lis...
java
public Query queryActivityFeedForUser(String userId) { Query q = queryEntitiesRequest(HttpMethod.GET, null, null, organizationId, applicationId, "users", userId, "feed"); return q; }
java
public ApiResponse postUserActivity(String userId, Activity activity) { return apiRequest(HttpMethod.POST, null, activity, organizationId, applicationId, "users", userId, "activities"); }
java
public ApiResponse postUserActivity(String verb, String title, String content, String category, User user, Entity object, String objectType, String objectName, String objectContent) { Activity activity = Activity.newActivity(verb, title, content, category, user, object, o...
java
public ApiResponse postGroupActivity(String groupId, Activity activity) { return apiRequest(HttpMethod.POST, null, activity, organizationId, applicationId, "groups", groupId, "activities"); }
java
public ApiResponse postGroupActivity(String groupId, String verb, String title, String content, String category, User user, Entity object, String objectType, String objectName, String objectContent) { Activity activity = Activity.newActivity(verb, title, content, category...
java
public Query queryActivity() { Query q = queryEntitiesRequest(HttpMethod.GET, null, null, organizationId, applicationId, "activities"); return q; }
java
public Query queryEntitiesRequest(HttpMethod method, Map<String, Object> params, Object data, String... segments) { ApiResponse response = apiRequest(method, params, data, segments); return new EntityQuery(response, method, params, data, segments); }
java
public Query queryUsersForGroup(String groupId) { Query q = queryEntitiesRequest(HttpMethod.GET, null, null, organizationId, applicationId, "groups", groupId, "users"); return q; }
java
public ApiResponse addUserToGroup(String userId, String groupId) { return apiRequest(HttpMethod.POST, null, null, organizationId, applicationId, "groups", groupId, "users", userId); }
java
public ApiResponse createGroup(String groupPath, String groupTitle, String groupName){ Map<String, Object> data = new HashMap<String, Object>(); data.put("type", "group"); data.put("path", groupPath); if (groupTitle != null) { data.put("title", groupTitle); }...
java
public ApiResponse connectEntities(String connectingEntityType, String connectingEntityId, String connectionType, String connectedEntityId) { return apiRequest(HttpMethod.POST, null, null, organizationId, applicationId, connectingEntityType, connectingEntityId, connectio...
java
public ApiResponse disconnectEntities(String connectingEntityType, String connectingEntityId, String connectionType, String connectedEntityId) { return apiRequest(HttpMethod.DELETE, null, null, organizationId, applicationId, connectingEntityType, connectingEntityId, conn...
java
public Query queryEntityConnections(String connectingEntityType, String connectingEntityId, String connectionType, String ql) { Map<String, Object> params = new HashMap<String, Object>(); params.put("ql", ql); Query q = queryEntitiesRequest(HttpMethod.GET, params, null, ...
java
public Query queryEntityConnectionsWithinLocation( String connectingEntityType, String connectingEntityId, String connectionType, float distance, float lattitude, float longitude, String ql) { Map<String, Object> params = new HashMap<String, Object>(); params.put("ql"...
java
public static Object toData(Literal lit) { if (lit == null) throw new IllegalArgumentException("Can't convert null literal"); if (lit instanceof TypedLiteral) return toData((TypedLiteral)lit); // Untyped literals are xsd:string // Note this isn't strictly correct; language tags will be lost here. re...
java
public static Object toData(TypedLiteral lit) { if (lit == null) throw new IllegalArgumentException("Can't convert null literal"); Conversion<?> c = uriConversions.get(lit.getDataType()); if (c == null) throw new IllegalArgumentException("Don't know how to convert literal of type " + lit.getDataType()); ...
java
public static TypedLiteral toLiteral(Object value) { if (value == null) throw new IllegalArgumentException("Can't convert null value"); Conversion<?> c = classConversions.get(value.getClass()); if (c != null) return c.literal(value); // The object has an unrecognized type that doesn't translate directly...
java
protected Map<String,RDFNode> readNext() throws SparqlException { try { // read <result> or </results> int eventType = reader.nextTag(); // if a closing element, then it should be </results> if (eventType == END_ELEMENT) { // already read the final result, so clean up and return noth...
java
private static void append(StringBuilder sb, int val, int width) { String s = Integer.toString(val); for (int i = s.length(); i < width; i++) sb.append('0'); sb.append(s); }
java
private static long elapsedDays(int year) { int y = year - 1; return DAYS_IN_YEAR * (long)y + div(y, 400) - div(y, 100) + div(y, 4); }
java
private static int daysInMonth(int year, int month) { assert month >= FIRST_MONTH && month <= LAST_MONTH; int d = DAYS_IN_MONTH[month - 1]; if (month == FEBRUARY && isLeapYear(year)) d++; return d; }
java
private static int parseMillis(Input s) { if (s.index < s.len && s.getChar() == '.') { int startIndex = ++s.index; int ms = parseInt(s); int len = s.index - startIndex; for (; len < 3; len++) ms *= 10; for (; len > 3; len--) ms /= 10; // truncate because it's easier than rounding. ...
java
private static Integer parseTzOffsetMs(Input s, boolean strict) { if (s.index < s.len) { char c = s.getChar(); s.index++; int sign; if (c == 'Z') { return 0; } else if (c == '+') { sign = 1; } else if (c == '-') { sign = -1; } else { throw ne...
java
private static int parseField(String field, Input s, Character delim, int minLen, int maxLen, boolean strict) { int startIndex = s.index; int result = parseInt(s); if (startIndex == s.index) throw new DateFormatException("missing value for field '" + field + "'", s.str, startIndex); if (strict) { ...
java
private static int parseInt(Input s) { if (s.index >= s.len) throw new DateFormatException("unexpected end of input", s.str, s.index); int result = 0; while (s.index < s.len) { char c = s.getChar(); if (c >= '0' && c <= '9') { if (result >= Integer.MAX_VALUE / 10) throw new ArithmeticExc...
java
public static void showAppInfo(@NonNull final Context context, @NonNull final String packageName) { Condition.INSTANCE.ensureNotNull(context, "The context may not be null"); Condition.INSTANCE.ensureNotNull(packageName, "The package name may not be null"); Cond...
java
public ApiResponse<Void> postPermissionsWithHttpInfo(String objectType, PostPermissionsData body) throws ApiException { com.squareup.okhttp.Call call = postPermissionsValidateBeforeCall(objectType, body, null, null); return apiClient.execute(call); }
java
Optional<PlayerKilled> move(Player player) { Move move = player.getMoves().poll(); if (move != null) { Tile from = tiles[move.getFrom()]; boolean armyBigEnough = from.getArmySize() > 1; boolean tileAndPlayerMatching = from.isOwnedBy(player.getPlayerIndex()); ...
java
public List<String> getPlayerNames() { return lastGameState.getPlayers().stream().map(Player::getUsername).collect(Collectors.toList()); }
java
public static Field getField(Class<?> clazz, String fieldName) throws NoSuchFieldException { if (clazz == Object.class) { return null; } try { Field field = clazz.getDeclaredField(fieldName); return field; } catch (NoSuchFieldException e) { return getField(clazz.getSupercla...
java
public com.squareup.okhttp.Call connectCall(final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException { Object localVarPostBody = null; // create path and map variables String localVarPath = "/not...
java
protected void invokeDelegate( ActionFilter delegate, ActionRequest request, ActionResponse response, FilterChain filterChain) throws PortletException, IOException { delegate.doFilter(request, response, filterChain); }
java
protected void invokeDelegate( EventFilter delegate, EventRequest request, EventResponse response, FilterChain filterChain) throws PortletException, IOException { delegate.doFilter(request, response, filterChain); }
java
protected void invokeDelegate( RenderFilter delegate, RenderRequest request, RenderResponse response, FilterChain filterChain) throws PortletException, IOException { delegate.doFilter(request, response, filterChain); }
java
protected void invokeDelegate( ResourceFilter delegate, ResourceRequest request, ResourceResponse response, FilterChain filterChain) throws PortletException, IOException { delegate.doFilter(request, response, filterChain); }
java
public PreAuthenticatedGrantedAuthoritiesPortletAuthenticationDetails buildDetails(PortletRequest context) { Collection<? extends GrantedAuthority> userGas = buildGrantedAuthorities(context); PreAuthenticatedGrantedAuthoritiesPortletAuthenticationDetails result = new PreAuthenticatedGr...
java
private boolean _runDML(DataManupulationStatement q, boolean isDDL){ boolean readOnly = ConnectionManager.instance().isPoolReadOnly(getPool()); Transaction txn = Database.getInstance().getCurrentTransaction(); if (!readOnly) { q.executeUpdate(); if (Database.getJdbcTypeHe...
java
private List<PortletFilter> getFilters(PortletRequest request) { for (PortletSecurityFilterChain chain : filterChains) { if (chain.matches(request)) { return chain.getFilters(); } } return null; }
java
@Deprecated public void setFilterChainMap(Map<RequestMatcher, List<PortletFilter>> filterChainMap) { filterChains = new ArrayList<PortletSecurityFilterChain>(filterChainMap.size()); for (Map.Entry<RequestMatcher,List<PortletFilter>> entry : filterChainMap.entrySet()) { filterChains.add(...
java
@Deprecated public Map<RequestMatcher, List<PortletFilter>> getFilterChainMap() { LinkedHashMap<RequestMatcher, List<PortletFilter>> map = new LinkedHashMap<RequestMatcher, List<PortletFilter>>(); for (PortletSecurityFilterChain chain : filterChains) { map.put(((DefaultPortletSecurityF...
java
private void displaySearchLine(String line, String searchWord) throws IOException { int start = line.indexOf(searchWord); connection.write(line.substring(0,start)); connection.write(ANSI.INVERT_BACKGROUND); connection.write(searchWord); connection.write(ANSI.RESET); conne...
java
public static PortletApplicationContext getPortletApplicationContext(PortletContext pc, String attrName) { Assert.notNull(pc, "PortletContext must not be null"); Object attr = pc.getAttribute(attrName); if (attr == null) { return null; } if (attr instanceof RuntimeExc...
java