id
stringlengths
7
14
text
stringlengths
1
37.2k
1767164_19
@RequestMapping(value = "{canonicalClassName:.+}", method = RequestMethod.GET) public ModelConstraint getConstraintsForClassName(@PathVariable String canonicalClassName, @RequestParam(required = false) String locale) { Locale loc = null; try { if (locale != null) { loc = parseLocale(locale); } return this.validationService.getConstraintsForClassName(canonicalClassName, loc); } catch (ClassNotFoundException e) { throw new NotFoundException("Class " + canonicalClassName + " could not be found", e); } }
1767458_8
public List<Trip> getUpcomingTrips() { return getRestTemplate().getForObject("https://api.tripit.com/v1/list/trip/traveler/true/past/false?format=json", TripList.class).getList(); }
1767567_18
public static Map<String, String[]> methodToParamNamesMap( String javaSrcFile, Class<?> clazz) { Map<String, String[]> map = new HashMap<String, String[]>(); try { JavaDocBuilder builder = new JavaDocBuilder(); builder.addSource(new File(javaSrcFile)); JavaClass jc = builder.getClassByName(clazz.getName()); JavaMethod methods[] = jc.getMethods(); for(JavaMethod method: methods) { // Add public and non-static members, only // these methods should be exposed / added to the interface if (method.isPublic() && !method.isStatic()) { String methodName = method.getName(); String[] paramNames = getParameterNames(method); map.put(methodName, paramNames); } } } catch (IOException e) { s_logger.log(Level.WARNING, "Failed to parse source file: " + javaSrcFile, e); } return map; }
1768217_49
public List<Tweet> getUserTimeline() { return getUserTimeline(20, 0, 0); }
1768307_34
@Deprecated public Query createQuery(String query, boolean returnGeneratedKeys) { return new Connection(this, true).createQuery(query, returnGeneratedKeys); }
1768380_12
public void setConnectionValues(Facebook facebook, ConnectionValues values) { User profile = facebook.fetchObject("me", User.class, "id", "name", "link"); values.setProviderUserId(profile.getId()); values.setDisplayName(profile.getName()); values.setProfileUrl(profile.getLink()); values.setImageUrl(facebook.getBaseGraphApiUrl() + profile.getId() + "/picture"); }
1772396_0
public static Date parse(String str) { return parse(str, true); }
1772628_1
public BusinessServiceLevel computeServiceLevel(long responseTime,Date timeStamp){ //assume that the service is at it best shape BusinessServiceLevel sl=BusinessServiceLevel.GOLD; //check if its gold if(goldPeriod.inPeriod(timeStamp)&&responseTime>maxGold){ //it s not so its silver sl=BusinessServiceLevel.SILVER; //check if it s worse than silver if(silverPeriod.inPeriod(timeStamp)&&responseTime>maxSilver){ //it's not even silver level so it s bronze sl=BusinessServiceLevel.BRONZE; //lets checks if there is a violation of the sla if(bronzePeriod.inPeriod(timeStamp)&&responseTime>maxBronze){ //violation of the sla sl=BusinessServiceLevel.VIOLATION; } } } return sl; }
1772795_58
@Override public List<MetricGraphData> getErrorGraph(String serviceName, String operationName, String consumerName, String errorId, String errorCategory, String errorSeverity, MetricCriteria metricCriteria) { return delegate.getErrorGraph(serviceName, operationName, consumerName, errorId, errorCategory, errorSeverity, metricCriteria); }
1772863_14
@Override public GetAuthenticationPolicyResponse getAuthenticationPolicy( GetAuthenticationPolicyRequest request) throws PolicyProviderException { if (request == null || request.getResourceName() == null || request.getResourceType() == null || request.getOperationName() == null || request.getResourceName().equals("") || request.getResourceType().equals("") || request.getOperationName().equals("")) { hrow new org.ebayopensource.turmeric.policyservice.exceptions.PolicyProviderException(Category.POLICY, "AUTHN", "invalid request"); y { olicyProvider.initialize(); catch (org.ebayopensource.turmeric.utils.config.exceptions.PolicyProviderException e) { hrow new PolicyProviderException(Category.POLICY, "AUTHN", "initialization failed", e); tAuthenticationPolicyResponse response = new GetAuthenticationPolicyResponse(); y { uthenticationProviderInfo authInfo = policyProvider.getAuthnPolicyByResource( request.getResourceName(), request.getOperationName(), request.getResourceType()); f (authInfo != null) { mapAuthnPolicy(response, authInfo); esponse.setAck(AckValue.SUCCESS); catch (org.ebayopensource.turmeric.utils.config.exceptions.PolicyProviderException e) { hrow new org.ebayopensource.turmeric.policyservice.exceptions.PolicyProviderException(Category.POLICY, "AUTHN", "unexpected error", e); turn response; }
1772983_15
public Boolean getFinalresult(String val) throws Exception { List<String> expression = simplifyExpression(val, new LinkedList<String>()); int cnt = 0; Boolean lastoutput = null; String lastlogicalOperation = null; for (String a : expression) { if (a != null) { a = a.trim(); if ("true".equalsIgnoreCase(a)) { if (cnt == 0) { lastoutput = true; cnt++; continue; } else { lastoutput = proccesOperation(lastoutput, true, lastlogicalOperation); lastlogicalOperation = null; } } else if ("false".equalsIgnoreCase(a)) { if (cnt == 0) { lastoutput = false; cnt++; continue; } else { lastoutput = proccesOperation(lastoutput, false, lastlogicalOperation); lastlogicalOperation = null; } } else if (("||").equalsIgnoreCase(a)) { if (cnt == 0) { System.out .println("error expression cannot start with ||"); break; } else { if (lastlogicalOperation == null) { lastlogicalOperation = "||"; } else { System.out.println("Invalid exprestion " + expression); } } } else if (("&&").equalsIgnoreCase(a)) { if (cnt == 0) { System.out .println("error expression can not start with &&"); break; } else { if (lastlogicalOperation == null) { lastlogicalOperation = "&&"; } else { System.out.println("Invalid exprestion " + expression); } } } } cnt++; } return lastoutput; }
1782556_1
void onRemoveUpload(int serverIndex) { // We use index of an uploadedFile in 'value' as a key at // the client side and if the uploaded file is removed we cleanup and set // the element at that index to null. As the 'value' may contain null, we // need to remove those entries in processSubmission() if (value != null && serverIndex >= 0 && serverIndex < value.size()) { UploadedFile item = value.get(serverIndex); if (item != null && (item instanceof UploadedFileItem)) { ((UploadedFileItem) item).cleanup(); } value.set(serverIndex, null); } }
1783046_2
@Override public Set<String> discoverMembers() { LOGGER.debug("CELLAR KUBERNETES: query pods with labeled with [{}={}]", kubernetesPodLabelKey, kubernetesPodLabelValue); Set<String> members = new HashSet<String>(); try { PodList podList = kubernetesClient.pods().list(); for (Pod pod : podList.getItems()) { String value = pod.getMetadata().getLabels().get(kubernetesPodLabelKey); if (value != null && !value.isEmpty() && value.equals(kubernetesPodLabelValue)) { members.add(pod.getStatus().getPodIP()); } } } catch (Exception e) { LOGGER.error("CELLAR KUBERNETES: can't get pods", e); } return members; }
1783083_0
public static String formatSize(String size) { if (size != null) { String incomingSize = size.trim(); if (incomingSize.length() > 0) { char lastChar = incomingSize.charAt(incomingSize.length() - 1); if (Character.isDigit(lastChar)) { return incomingSize + "px"; } } } return size; }
1784308_211
public static void setReportWriter(ReportWriter reportWriter) { Assert.notNull("ReportWriter must not be null.", reportWriter); getInstance().reportWriter = reportWriter; }
1784501_0
@Override public boolean equals(Object t) { if (t == null || getClass() != t.getClass()) { return false; } else { ColumnType other = (ColumnType) t; return m_type == other.getType() && Objects.equals(m_typeCode, other.getTypeCode()); } }
1795594_16
public static Validator<String> getBucketNameValidator(final String restrictionValue) { if (restrictionValue != null && "extended".equalsIgnoreCase(restrictionValue)) { return extendedValidator; } else if (restrictionValue != null && "dns-compliant".equalsIgnoreCase(restrictionValue)) { return dnsCompliantValidator; } else { return new Validator<String>() { @Override public boolean check(String value) { LOG.error("the value " + restrictionValue + " is not valid, must be either 'extended' or 'dns-compliant'. No validation " + "will be done on the specified bucket name (may result in errors)."); if (value != null && value.length() > 0) { return true; } return false; } }; } }
1797376_538
public void updateByIndex(int index, Number y) { XYDataItem item = getRawDataItem(index); // figure out if we need to iterate through all the y-values boolean iterate = false; double oldY = item.getYValue(); if (!Double.isNaN(oldY)) { iterate = oldY <= this.minY || oldY >= this.maxY; } item.setY(y); if (iterate) { findBoundsByIteration(); } else if (y != null) { double yy = y.doubleValue(); this.minY = minIgnoreNaN(this.minY, yy); this.maxY = maxIgnoreNaN(this.maxY, yy); } fireSeriesChanged(); }
1810705_22
public String getServerName() { return serverName; }
1810897_0
@RequestMapping(value = "states", method = RequestMethod.GET, produces = "application/json") public @ResponseBody List<State> fetchStatesJson() { logger.info("fetching JSON states"); return getStates(); }
1812602_16
@Override public List<DescribeSObjectResult> filter(List<DescribeSObjectResult> dsrs) { for (DescribeSObjectResult dsr : dsrs) { objectMap.put(dsr.getName(), dsr); } filterObjectAndReferences(objectNames); return filteredResult; }
1814028_2
public static UniversalMockRecorder expectCall() { return StaticConnectionFactory.expectCall(); }
1839196_7
public void setSource(T source) { this.source.set(source); }
1860892_0
protected void fireStartTask() { fireEvent(new Event() { @Override public void fire(final Listener listener) { listener.startTask(); } }); }
1862490_2
public static String resolve(final Properties props, final String expression) { if (expression == null) return null; final StringBuilder builder = new StringBuilder(); final char[] chars = expression.toCharArray(); final int len = chars.length; int state = 0; int start = -1; int nameStart = -1; for (int i = 0; i < len; i++) { char ch = chars[i]; switch (state) { case INITIAL: { switch (ch) { case '$': { state = GOT_DOLLAR; continue; } default: { builder.append(ch); continue; } } // not reachable } case GOT_DOLLAR: { switch (ch) { case '$': { builder.append(ch); state = INITIAL; continue; } case '{': { start = i + 1; nameStart = start; state = GOT_OPEN_BRACE; continue; } default: { // invalid; emit and resume builder.append('$').append(ch); state = INITIAL; continue; } } // not reachable } case GOT_OPEN_BRACE: { switch (ch) { case ':': case '}': case ',': { final String name = expression.substring(nameStart, i).trim(); final String val; if (name.startsWith("env.")) { val = System.getenv(name.substring(4)); } else if (name.startsWith("sys.")) { val = System.getProperty(name.substring(4)); } else { val = props.getProperty(name); } if (val != null) { builder.append(val); state = ch == '}' ? INITIAL : RESOLVED; continue; } else if (ch == ',') { nameStart = i + 1; continue; } else if (ch == ':') { start = i + 1; state = DEFAULT; continue; } else { builder.append(expression.substring(start - 2, i + 1)); state = INITIAL; continue; } } default: { continue; } } // not reachable } case RESOLVED: { if (ch == '}') { state = INITIAL; } continue; } case DEFAULT: { if (ch == '}') { state = INITIAL; builder.append(expression.substring(start, i)); } continue; } default: throw new IllegalStateException(); } } switch (state) { case GOT_DOLLAR: { builder.append('$'); break; } case DEFAULT: case GOT_OPEN_BRACE: { builder.append(expression.substring(start - 2)); break; } } return builder.toString(); }
1862492_0
public void setWriter(final Writer writer) { synchronized (outputLock) { super.setWriter(writer); final OutputStream oldStream = this.outputStream; outputStream = null; safeFlush(oldStream); safeClose(oldStream); } }
1863627_0
@Override public ClusterNode assignClusterNode() { lock.lock(); try { while (!currentlyOwningTask.get()) { taskAcquired.awaitUninterruptibly(); } } catch (Exception e) { logger.error("Exception while waiting for task to be acquired"); return null; } finally { lock.unlock(); } return clusterNodeRef.get(); }
1867246_60
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException { try { SAMLMessageContext context = contextProvider.getLocalEntity(request, response); logger.debug("Attempting SAML2 authentication"); processor.retrieveMessage(context); HttpSessionStorage storage = new HttpSessionStorage(request); SAMLAuthenticationToken token = new SAMLAuthenticationToken(context, storage); return getAuthenticationManager().authenticate(token); } catch (SAMLException e) { throw new SAMLRuntimeException("Incoming SAML message is invalid", e); } catch (MetadataProviderException e) { throw new SAMLRuntimeException("Error determining metadata contracts", e); } catch (MessageDecodingException e) { throw new SAMLRuntimeException("Error decoding incoming SAML message", e); } catch (org.opensaml.xml.security.SecurityException e) { throw new SAMLRuntimeException("Incoming SAML message is invalid", e); } }
1870998_31
public static Period getAge(LocalDate birthDate) { return getAge(birthDate, LocalDate.now()); }
1872106_0
static boolean nameIsValid(String name) { return name.matches("[\\p{L}-]+"); }
1875775_1
public FaceletTaglibType getTaglib() { return taglib; }
1878370_11
public static JavaMethod assertMethodExists(File java, CharSequence methodSignature) throws IOException { JavaDocBuilder builder = new JavaDocBuilder(); JavaSource src = builder.addSource(java); JavaClass jc = getClassName(src, java); Map<String, JavaMethod> sigs = new HashMap<String, JavaMethod>(); for (JavaMethod method : jc.getMethods()) { if (!method.isConstructor()) { sigs.put(getCompleteMethodSignature(method), method); } } if (!sigs.containsKey(methodSignature)) { StringBuilder msg = new StringBuilder(); msg.append("Expected method signature not found: "); msg.append(methodSignature); msg.append("\nMethods present in java source:"); for (String sig : sigs.keySet()) { msg.append("\n ").append(sig); } Assert.fail(msg.toString()); } return sigs.get(methodSignature); }
1886360_35
public static int[] listTotients(int n) { if (n < 0) throw new IllegalArgumentException("Negative array size"); int[] result = new int[n + 1]; for (int i = 0; i <= n; i++) result[i] = i; for (int i = 2; i <= n; i++) { if (result[i] == i) { // i is prime for (int j = i; j <= n; j += i) result[j] -= result[j] / i; } } return result; }
1889681_12
@Nonnull Collection<FilterData> getFilters(@Nonnull ProjectData project) throws RemoteException { return Arrays.asList(connectPortType.mc_filter_get(USERNAME, PASSWORD, project.getId())); }
1894664_13
public SearchResults search(String searchString){ return search(searchString, 1); }
1905463_3
public Object getValue(Object target, Object property) throws GenericElEvaluationException, PropertyNotFoundException { return this.getValue(target, property, getTypeOfCollectionOrBean(target, property)); }
1913648_0
public Map<String,Integer> getMods () { return new HashMap<String,Integer>(_mods); }
1925457_60
public static String getDegreesMinutesSeconds(double decimaldegrees, boolean isLatitude) { String cardinality = (decimaldegrees<0) ? "S":"N"; if(!isLatitude){ cardinality = (decimaldegrees<0) ? "W":"E"; } //Remove negative sign decimaldegrees = Math.abs(decimaldegrees); int deg = (int) Math.floor(decimaldegrees); double minfloat = (decimaldegrees-deg)*60; int min = (int) Math.floor(minfloat); double secfloat = (minfloat-min)*60; double sec = Math.round(secfloat * 10000.0)/10000.0; // After rounding, the seconds might become 60. These two // if-tests are not necessary if no rounding is done. if (sec==60) { min++; sec=0; } if (min==60) { deg++; min=0; } return ("" + deg + "° " + min + "' " + sec + "\" " + cardinality); }
1931685_3
public StompletActivator match(String destination) { Matcher routeMatcher = this.regexp.matcher( destination ); if (routeMatcher.matches()) { Map<String, String> matches = new HashMap<String, String>(); for (int i = 0; i < this.segmentNames.length; ++i) { matches.put( segmentNames[i], routeMatcher.group( i + 1 ) ); } return new StompletActivator( this, destination, matches ); } return null; }
1933490_4
public String getName() { return name; }
1944249_13
public void setText(@Nonnull String text) { Check.isMainThread(); onTextChanged(EditorState.create(text, text.length())); }
1946637_20
public static String path(final CharSequence path) { return decode(path, false); }
1951088_0
public Photoset getInfo(String photosetId) throws FlickrException, IOException, JSONException { List<Parameter> parameters = new ArrayList<Parameter>(); parameters.add(new Parameter("method", METHOD_GET_INFO)); boolean signed = OAuthUtils.hasSigned(); if (signed) { parameters.add(new Parameter( OAuthInterface.PARAM_OAUTH_CONSUMER_KEY, apiKey)); } else { parameters.add(new Parameter("api_key", apiKey)); } parameters.add(new Parameter("photoset_id", photosetId)); if (signed) { OAuthUtils.addOAuthToken(parameters); } Response response = transportAPI .get(transportAPI.getPath(), parameters); if (response.isError()) { throw new FlickrException(response.getErrorCode(), response.getErrorMessage()); } JSONObject photosetElement = response.getData().getJSONObject( "photoset"); return parsePhotoset(photosetElement); }
1952675_29
@Override public boolean isRunning() { return super.isRunning() && stopBarrier.getCount() > 0; }
1953808_0
public Collection<T> getAllAt(WorldPosition position) { Collection<T> objects = positions.get(position); if (objects == null) { return Collections.emptyList(); } else { return Collections.unmodifiableCollection(objects); } }
1956196_2
int getStyle(String style) { int formatType = -1; if("long".equals(style)) { formatType = DateFormat.LONG; } else if("medium".equals(style)) { formatType = DateFormat.MEDIUM; } else if("full".equals(style)) { formatType = DateFormat.FULL; } else if("short".equals(style)) { formatType = DateFormat.SHORT; } return formatType; }
1961837_10
@Override public Piece choosePiece(BitSet interesting, Piece[] pieces) { List<Piece> onlyInterestingPieces = new ArrayList<Piece>(); for (Piece p : pieces) { if (interesting.get(p.getIndex())) onlyInterestingPieces.add(p); } if (onlyInterestingPieces.isEmpty()) return null; return onlyInterestingPieces.get(myRandom.nextInt(onlyInterestingPieces.size())); }
1970932_193
public static String substVars(String val, PropertyContainer pc1) { return substVars(val, pc1, null); }
1971346_2
@Override public void close() throws IOException { try { flush(); } finally { if (isEnabled(Feature.AUTO_CLOSE_TARGET)) { MessagePacker messagePacker = getMessagePacker(); messagePacker.close(); } } }
1971919_26
public void replicateEntries(HLog.Entry[] entries) throws IOException { if (entries.length == 0) { return; } // Very simple optimization where we batch sequences of rows going // to the same table. try { long totalReplicated = 0; // Map of table => list of puts, we only want to flushCommits once per // invocation of this method per table. Map<byte[], List<Put>> puts = new TreeMap<byte[], List<Put>>(Bytes.BYTES_COMPARATOR); for (HLog.Entry entry : entries) { WALEdit edit = entry.getEdit(); List<KeyValue> kvs = edit.getKeyValues(); if (kvs.get(0).isDelete()) { Delete delete = new Delete(kvs.get(0).getRow(), kvs.get(0).getTimestamp(), null); for (KeyValue kv : kvs) { if (kv.isDeleteFamily()) { delete.deleteFamily(kv.getFamily()); } else if (!kv.isEmptyColumn()) { delete.deleteColumn(kv.getFamily(), kv.getQualifier()); } } delete(entry.getKey().getTablename(), delete); } else { byte[] table = entry.getKey().getTablename(); List<Put> tableList = puts.get(table); if (tableList == null) { tableList = new ArrayList<Put>(); puts.put(table, tableList); } // With mini-batching, we need to expect multiple rows per edit byte[] lastKey = kvs.get(0).getRow(); Put put = new Put(kvs.get(0).getRow(), kvs.get(0).getTimestamp()); for (KeyValue kv : kvs) { if (!Bytes.equals(lastKey, kv.getRow())) { tableList.add(put); put = new Put(kv.getRow(), kv.getTimestamp()); } put.add(kv.getFamily(), kv.getQualifier(), kv.getValue()); lastKey = kv.getRow(); } tableList.add(put); } totalReplicated++; } for(byte [] table : puts.keySet()) { put(table, puts.get(table)); } this.metrics.setAgeOfLastAppliedOp( entries[entries.length-1].getKey().getWriteTime()); this.metrics.appliedBatchesRate.inc(1); LOG.info("Total replicated: " + totalReplicated); } catch (IOException ex) { LOG.error("Unable to accept edit because:", ex); throw ex; } }
1980382_73
public static byte typeVal(Object o) { if (o instanceof Long || o instanceof Integer) { return LONG; } else if (o instanceof String) { return STRING; } else if (o instanceof Date) { return DATE; } else if (o instanceof Map || o instanceof List) { return JSON; } else if (o instanceof byte[]) { return BYTE_ARRAY; } else if (o instanceof BufferProxy) { return BUFFER_STREAM; } else if (o instanceof FileProxy) { return FILE_STREAM; } else { return -1; } }
1981819_4
public static List<String> getPostgresCategoryString(String searchString, Map<String, String> mapPrefix, String prefixSplit ) { List<String> finalList = new ArrayList<String>(); if (searchString == null || !(searchString.trim().length() > 0)) { finalList.add( "{}" ); return finalList; } List<String> categories = parse(searchString.trim().toLowerCase()); List<String> catHolder = new ArrayList<String>(); // find if any categories are prefixed, if so, split them out. for( String cat : categories ) { if (cat.matches( SearchToSqlConverter.BAD_SEARCH_REGEX ) ) { throw new IllegalArgumentException( SearchToSqlConverter.BAD_CHAR_MSG ); } if (prefixSplit != null ) { int index = cat.indexOf( prefixSplit ); if ( index != -1 ) { String prefix = cat.substring( 0, index ); String value = cat.substring( index + prefixSplit.length() ); if ( mapPrefix.containsKey( prefix ) ) { addToFinalList( finalList, catHolder ); finalList.add( value ); } else { catHolder.add( cat ); } } else { catHolder.add( cat ); } } else { catHolder.add( cat ); } } addToFinalList( finalList, catHolder ); return finalList; }
1982584_1
public static String toNormalizedSAN(final String pChaine) { assert pChaine != null; final StringBuilder res = new StringBuilder(pChaine); // Le marqueur 'P' pour les pions est possible avec PGN, pas avec SAN... if (res.charAt(0) == 'P') { res.deleteCharAt(0); } // Les promotions sont indiquées avec un '=' sous PGN, pas sous SAN... int p = res.indexOf("="); while (p >= 0) { res.deleteCharAt(p); p = res.indexOf("="); } // Les suffixes d'annotations '?' et '!' ne font pas partie de SAN... while ((res.length() > 0) && ("?!".indexOf(res.charAt(res.length() - 1)) >= 0)) { res.deleteCharAt(res.length() - 1); } // Certains programmes ajoutent des '@' (totalement hors normes)... p = res.indexOf("@"); while (p >= 0) { res.deleteCharAt(p); p = res.indexOf("@"); } return res.toString(); }
1984080_19
public void outFlow(double dt, double simulationTime, long iterationCount) { updateSignalPointsBeforeOutflow(simulationTime); for (final LaneSegment laneSegment : laneSegments) { laneSegment.outFlow(dt, simulationTime, iterationCount); assert laneSegment.assertInvariant(); } overtakingSegment.outFlow(dt, simulationTime, iterationCount); if (sink != null) { sink.timeStep(dt, simulationTime, iterationCount); } }
2003641_100
public OpenAPI filter(OpenAPI openAPI, OpenAPISpecFilter filter, Map<String, List<String>> params, Map<String, String> cookies, Map<String, List<String>> headers) { OpenAPI filteredOpenAPI = filterOpenAPI(filter, openAPI, params, cookies, headers); if (filteredOpenAPI == null) { return filteredOpenAPI; } OpenAPI clone = new OpenAPI(); clone.info(filteredOpenAPI.getInfo()); clone.openapi(filteredOpenAPI.getOpenapi()); clone.setExtensions(filteredOpenAPI.getExtensions()); clone.setExternalDocs(filteredOpenAPI.getExternalDocs()); clone.setSecurity(filteredOpenAPI.getSecurity()); clone.setServers(filteredOpenAPI.getServers()); clone.tags(filteredOpenAPI.getTags() == null ? null : new ArrayList<>(openAPI.getTags())); final Set<String> allowedTags = new HashSet<>(); final Set<String> filteredTags = new HashSet<>(); Paths clonedPaths = new Paths(); if (filteredOpenAPI.getPaths() != null) { for (String resourcePath : filteredOpenAPI.getPaths().keySet()) { PathItem pathItem = filteredOpenAPI.getPaths().get(resourcePath); PathItem filteredPathItem = filterPathItem(filter, pathItem, resourcePath, params, cookies, headers); if (filteredPathItem != null) { PathItem clonedPathItem = new PathItem(); clonedPathItem.set$ref(filteredPathItem.get$ref()); clonedPathItem.setDescription(filteredPathItem.getDescription()); clonedPathItem.setSummary(filteredPathItem.getSummary()); clonedPathItem.setExtensions(filteredPathItem.getExtensions()); clonedPathItem.setParameters(filteredPathItem.getParameters()); clonedPathItem.setServers(filteredPathItem.getServers()); Map<PathItem.HttpMethod, Operation> ops = filteredPathItem.readOperationsMap(); for (Map.Entry<PathItem.HttpMethod, Operation> entry : ops.entrySet()) { PathItem.HttpMethod key = entry.getKey(); Operation op = entry.getValue(); List<String> opTagsBeforeFilter = null; if (op.getTags() != null) { opTagsBeforeFilter = new ArrayList<>(op.getTags()); } else { opTagsBeforeFilter = new ArrayList<>(); } op = filterOperation(filter, op, resourcePath, key.toString(), params, cookies, headers); clonedPathItem.operation(key, op); if (op == null) { filteredTags.addAll(opTagsBeforeFilter); } else { if (op.getTags() != null) { opTagsBeforeFilter.removeAll(op.getTags()); allowedTags.addAll(op.getTags()); } filteredTags.addAll(opTagsBeforeFilter); } } if (!clonedPathItem.readOperations().isEmpty()) { clonedPaths.addPathItem(resourcePath, clonedPathItem); } } } clone.paths(clonedPaths); } filteredTags.removeAll(allowedTags); final List<Tag> tags = clone.getTags(); if (tags != null && !filteredTags.isEmpty()) { for (Iterator<Tag> it = tags.iterator(); it.hasNext(); ) { if (filteredTags.contains(it.next().getName())) { it.remove(); } } if (clone.getTags().isEmpty()) { clone.setTags(null); } } if (filteredOpenAPI.getComponents() != null) { clone.components(new Components()); clone.getComponents().setSchemas(filterComponentsSchema(filter, filteredOpenAPI.getComponents().getSchemas(), params, cookies, headers)); clone.getComponents().setSecuritySchemes(filteredOpenAPI.getComponents().getSecuritySchemes()); clone.getComponents().setCallbacks(filteredOpenAPI.getComponents().getCallbacks()); clone.getComponents().setExamples(filteredOpenAPI.getComponents().getExamples()); clone.getComponents().setExtensions(filteredOpenAPI.getComponents().getExtensions()); clone.getComponents().setHeaders(filteredOpenAPI.getComponents().getHeaders()); clone.getComponents().setLinks(filteredOpenAPI.getComponents().getLinks()); clone.getComponents().setParameters(filteredOpenAPI.getComponents().getParameters()); clone.getComponents().setRequestBodies(filteredOpenAPI.getComponents().getRequestBodies()); clone.getComponents().setResponses(filteredOpenAPI.getComponents().getResponses()); } if (filter.isRemovingUnreferencedDefinitions()) { clone = removeBrokenReferenceDefinitions(clone); } return clone; }
2008119_4
@Get("json") public Representation getEntity() { // extract necessary information from the context CollabinateReader reader = (CollabinateReader)getContext() .getAttributes().get("collabinateReader"); String tenantId = getAttribute("tenantId"); String entityId = getAttribute("entityId"); String result = reader.getEntity(tenantId, entityId).toString(); Representation representation = new StringRepresentation( result, MediaType.APPLICATION_JSON); representation.setTag(new Tag(Hashing.murmur3_128().hashUnencodedChars( result+tenantId+entityId) .toString(), false)); return representation; }
2009311_17
@AroundInvoke public Object markReadOnly(InvocationContext ic) throws Exception { try { return ic.proceed(); } finally { utTransactionHolder.getUserTransaction().setRollbackOnly(); } }
2009635_0
public int unpack(int i) { return ( (this.data[i>>this.indexShift] >> ((i&this.shiftMask)<<this.bitShift)) & this.unitMask ); }
2011647_130
public Quaternion getOrientation(Quaternion quat) { quat.setAll(mOrientation); return quat; }
2023409_11
@Override public void getStatementsGroupByFilledSQL(final LogSearchCriteria searchCriteria, final ResultSetAnalyzer analyzer) { final StringBuilder sql = new StringBuilder( "select * from (select min(id) as ID, statementType, rawSql, filledSql, count(1) as exec_count, " // + "sum(executionDurationNanos+coalesce(rsetUsageDurationNanos,0)) as " + TOTAL_EXEC_PLUS_RSET_USAGE_TIME_COLUMN + ", "// + "max(executionDurationNanos+coalesce(rsetUsageDurationNanos,0)) as " + MAX_EXEC_PLUS_RSET_USAGE_TIME_COLUMN + ", " // + "min(executionDurationNanos+coalesce(rsetUsageDurationNanos,0)) as " + MIN_EXEC_PLUS_RSET_USAGE_TIME_COLUMN + ", " // + "avg(executionDurationNanos+coalesce(rsetUsageDurationNanos,0)) as " + AVG_EXEC_PLUS_RSET_USAGE_TIME_COLUMN + " " // + "from statement_log "); if (searchCriteria.getFilter() != null) { sql.append("where (UPPER(rawSql) like ? or UPPER(filledSql) like ?)"); } sql.append("group by statementType, rawSql, filledSql "); if (searchCriteria.getMinDurationNanos() != null) { sql.append("having sum(executionDurationNanos++coalesce(rsetUsageDurationNanos,0))>=?"); } sql.append(") "); if (searchCriteria.getSqlPassThroughFilter() != null) { addWhereClause(sql, false, searchCriteria.getSqlPassThroughFilter()); } if (searchCriteria.isRemoveTransactionCompletions()) { addWhereClause(sql, false, "statementType<>" + StatementType.TRANSACTION.getId()); } sql.append(" order by " + TOTAL_EXEC_PLUS_RSET_USAGE_TIME_COLUMN + " desc"); try (PreparedStatement statement = connectionRead.prepareStatement(sql.toString())) { applyParametersForWhereClause(searchCriteria, statement); try (ResultSet resultSet = statement.executeQuery()) { analyzer.analyze(resultSet); } } catch (final SQLException e) { throw new RuntimeException(e); } }
2036666_0
public static int findFreePort() throws IOException { ServerSocket server = new ServerSocket(0); int port = server.getLocalPort(); server.close(); return port; }
2037955_0
@Override public Object deserialize(Writable w) throws SerDeException { Text rowText = (Text) w; deserializedDataSize = rowText.getBytes().length; // Try parsing row into JSON object Object jObj = null; try { String txt = rowText.toString().trim(); if(txt.startsWith("{")) { jObj = new JSONObject(txt); } else if (txt.startsWith("[")){ jObj = new JSONArray(txt); } } catch (JSONException e) { // If row is not a JSON object, make the whole row NULL onMalformedJson("Row is not a valid JSON Object - JSONException: " + e.getMessage()); try { jObj = new JSONObject("{}"); } catch (JSONException ex) { onMalformedJson("Error parsing empty row. This should never happen."); } } return jObj; }
2038852_35
@Override public ValidatorResult validate(Host host, Object ctx) { return validator.validate(host, ctx); }
2044534_5
private boolean write(ByteBuffer[] buffers) { try { long written = handler.getChannel().write(buffers); if (getLog().isTraceEnabled()) { getLog().trace(format("%s bytes written", written)); } if (written < 0) { close(); return false; } else if (buffers[buffers.length - 1].hasRemaining()) { long plusWritten = handler.getChannel().write(buffers); if (plusWritten < 0) { close(); return false; } if (getLog().isTraceEnabled()) { getLog().trace(format("%s bytes +written", plusWritten)); } } } catch (ClosedChannelException e) { if (getLog().isTraceEnabled()) { getLog().trace(format("shutting down handler due to other side closing [%s]", this), e); } error(); return false; } catch (IOException ioe) { if (getLog().isWarnEnabled() && !isClose(ioe)) { getLog().warn("shutting down handler", ioe); } error(); return false; } return true; }
2046220_5
public DBDatabase loadDbModel() { DBDatabase db = new InMemoryDatabase(); try { con = openJDBCConnection(config); populateDatabase(db); } catch (SQLException e) { throw new RuntimeException("Unable to read database metadata: " + e.getMessage(), e); } finally { DBUtil.close(con, log); } return db; }
2055952_0
public String toString() { return "X=" + mX + ", Y=" + mY; }
2058044_1
public static Value asResource(java.net.URI uri) { return Values.literal(uri.toString()); }
2061716_1
@Override public Node runMapping(final MetadataRecord metadataRecord) throws MappingException { LOG.trace("Running mapping for record {}", metadataRecord); SimpleBindings bindings = Utils.bindingsFor(recMapping.getFacts(), recMapping.getRecDefTree().getRecDef(), metadataRecord.getRootNode(), recMapping.getRecDefTree().getRecDef().valueOptLookup); try { Node result = (Node) compiledScript.eval(bindings); return Utils.stripEmptyElements(result); } catch (ScriptException e) { throw new RuntimeException(e); } }
2064018_16
public static List<Annotation> readLabelFile(final Reader fileReader) throws IOException { List<Annotation> annotations = new ArrayList<Annotation>(); BufferedReader reader = new BufferedReader(fileReader); String line; while ((line = reader.readLine()) != null) { String[] parts = line.split("\t"); String cidr = parts[0]; String label = parts[1]; String sublabel = parts[2]; Annotation a = new Annotation(new CIDR(cidr), label, sublabel); annotations.add(a); } return annotations; }
2073724_0
@Override public int getColorInt(float intensity) { return (intensity > 0.5) ? 0xffffffff: 0xff000000; }
2080454_21
@Override public boolean equals(final Object other) { if (!(other instanceof SongTo)) return false; SongTo castOther = (SongTo) other; return new EqualsBuilder().appendSuper(super.equals(other)) .append(getType(), castOther.getType()) .append(isPodcast(), castOther.isPodcast()) .append(albumRatingComputed, castOther.albumRatingComputed) .append(albumRating, castOther.albumRating) .append(skipDate, castOther.skipDate) .append(skipCount, castOther.skipCount) .append(compilation, castOther.compilation) .append(trackNumber, castOther.trackNumber) .append(discNumber, castOther.discNumber) .append(totalTime, castOther.totalTime).isEquals(); }
2088736_251
@Override public By buildBy() { if (mobileElement) { return defaultElementByBuilder.buildBy(); } By fieldBy = fieldAnnotations.buildBy(); By classBy = classAnnotations.buildBy(); if (classBy != null && fieldBy instanceof ByIdOrName) { return classBy; } return fieldBy; }
2090979_0
public void setHost(String host) { Assert.notNull(host, "Host may not be null"); this.host = host; }
2101910_9
@Override public Snapshot getSnapshot() { checkBackgroundException(); mutex.lock(); try { return new SnapshotImpl(versions.getCurrent(), versions.getLastSequence()); } finally { mutex.unlock(); } }
2111687_3
public String compile(URL sourceURL) throws UnableToCompleteException { // TODO: this won't work if the .less file is in a jar... LessCompilerContext context = new LessCompilerContext(logger, sourceURL.getFile()); try { Function<LessCompilerContext, String> compiler = LessCompiler.newCompiler(); return compiler.apply(context); } catch (Exception e) { logger.log(TreeLogger.Type.ERROR, "Error compiling LESS: " + e.getMessage(), e); throw new UnableToCompleteException(); } }
2112231_3
public static void readInto(SettingsMap settingsMap, String rawSettings) { String[] settings = rawSettings.split(";"); for (String setting : settings) { String[] settingParts = setting.split("=", 2); String settingName = settingParts[0].toLowerCase().trim(); if (settingName.isEmpty()) { continue; } if (settingParts.length == 1) { // Boolean values RawSettingValue settingValue = RawSettingValue.ofPlainSetting(settingName, "true"); settingsMap.addRawSetting(settingValue); } else if (settingParts.length == 2) { RawSettingValue settingValue = RawSettingValue.ofPlainSetting(settingName, settingParts[1].trim()); settingsMap.addRawSetting(settingValue); } } }
2117797_49
@Override public List<Message2Send> getMessage(MessageProcessUnit inUnit) { if (inUnit instanceof MessageNSettingProcessUnit) { final SubscriptionSchedulingData theSubscriptionSchedulingData = inUnit.get(); final ApplicationSettingData urlSetting = ApplicationSettingData.findByApplicationAndKey(theSubscriptionSchedulingData.getSubscription().getApplication(), WebRadioMessageFactory.URL); if ((urlSetting == null) || !urlSetting.isValid()) { WebRadioMessageFactory.LOGGER.fatal("This webradio does not have any url : " + theSubscriptionSchedulingData.getSubscription().getApplication().getName()); } else { final VObject theObject = theSubscriptionSchedulingData.getSubscription().getObject().getReference(); final SubscriptionSchedulingSettingsData theSetting = ((MessageNSettingProcessUnit) inUnit).getSchedulingSettingsData(); final int listeningTime = Integer.parseInt(SubscriptionSchedulingSettingsData.findBySubscriptionSchedulingAndKey(theSubscriptionSchedulingData, theSetting.getKey() + DailyWithDurationHandler.DURATION_SUFFIXE).getValue()); return WebRadioMessageFactory.getMessage2Send(urlSetting.getValue(), theObject, inUnit.getProcessConditioner(), listeningTime, System.currentTimeMillis()); } } return Collections.emptyList(); }
2118259_0
@Override @Nonnull public List<ContactDetailsDTO> getContactDetails() { initContactsIfRequired(); final ArrayList<ContactDetailsDTO> contactDetails = new ArrayList<ContactDetailsDTO>(); for( final Contact contact : _contactDAO.findAll() ) { contactDetails.add( toLightWeightContactDTO( contact ) ); } return contactDetails; }
2125451_113
public HashObject setObject(RevObject object) { this.object = object; return this; }
2125920_34
public static void inference(List<Rule> rules, Reasoner reasoner, GroundRuleStore groundRuleStore, TermStore termStore, TermGenerator termGenerator, LazyAtomManager lazyAtomManager, int maxRounds) { // Performs rounds of inference until the ground model stops growing. int rounds = 0; int numActivated = 0; do { rounds++; log.debug("Starting round {} of inference.", rounds); // Regenerate optimization terms. termStore.clear(); log.debug("Initializing objective terms for {} ground rules.", groundRuleStore.size()); termStore.ensureVariableCapacity(lazyAtomManager.getCachedRVACount()); @SuppressWarnings("unchecked") int termCount = termGenerator.generateTerms(groundRuleStore, termStore); log.debug("Generated {} objective terms from {} ground rules.", termCount, groundRuleStore.size()); log.info("Beginning inference round {}.", rounds); reasoner.optimize(termStore); log.info("Inference round {} complete.", rounds); numActivated = lazyAtomManager.activateAtoms(rules, groundRuleStore); log.debug("Completed round {} and activated {} atoms.", rounds, numActivated); } while (numActivated > 0 && rounds < maxRounds); }
2129779_2
@RequestMapping(method=RequestMethod.GET,value="edit") public ModelAndView editPerson(@RequestParam(value="id",required=false) Long id) { logger.debug("Received request to edit person id : "+id); ModelAndView mav = new ModelAndView(); mav.setViewName("edit"); Person person = null; if (id == null) { person = new Person(); } else { person = personDao.find(id); } mav.addObject("person", person); return mav; }
2136693_82
public String getName() { return name; }
2139087_23
public Point<C2D> toPoint(Pixel pixel) { double x = extent.lowerLeft().getX() + mapUnitsPerPixelX * (pixel.x - this.pixelRange.getMinX()); double y = extent.upperRight().getY() - mapUnitsPerPixelY * (pixel.y - this.pixelRange.getMinY()); return point(extent.getCoordinateReferenceSystem(), c(x, y)); }
2144321_9
public static String[] getMatchingPaths(final String[] includes, final String[] excludes, final String baseDir) { final DirectoryScanner scanner = new DirectoryScanner(); scanner.setBasedir(baseDir); if (includes != null && includes.length > 0) scanner.setIncludes(includes); if (excludes != null && excludes.length > 0) scanner.setExcludes(excludes); scanner.scan(); return scanner.getIncludedFiles(); }
2153523_457
public void rewrite(HttpRequest request, HttpResponseBuilder original) throws RewritingException { ContentRewriterFeature.Config config = rewriterFeatureFactory.get(request); if (!RewriterUtils.isCss(request, original)) { return; } String css = original.getContent(); StringWriter sw = new StringWriter((css.length() * 110) / 100); rewrite(new StringReader(css), request.getUri(), new UriMaker(proxyUriManager, config), sw, false, DomWalker.makeGadget(request).getContext()); original.setContent(sw.toString()); }
2155500_4
public Customer sample() throws Exception { Integer id = idSampler.sample(); Pair<String, String> name = nameSampler.sample(); Store store = storeSampler.sample(); Location location = locationSampler.sample(store); return new Customer(id, name, store, location); }
2157104_2
public static String formata(String codigo) throws ErroCompilacao { Programa programa = Portugol.compilarParaAnalise(codigo); ASAPrograma asa = programa.getArvoreSintaticaAbstrata(); StringWriter stringWriter = new StringWriter(); try { GeradorCodigoPortugol gerador = new GeradorCodigoPortugol(asa, new PrintWriter(stringWriter)); gerador.visitar(asa); } catch (ExcecaoVisitaASA ex) { LOGGER.log(Level.SEVERE, null, ex); } return stringWriter.toString(); }
2158982_18
@Override public List<Expression<?>> getGroupBy() { return groupBy; }
2168781_12
@Override public void setRetained(boolean retain) { throw new UnsupportedOperationException("DISCONNECT message does not support the RETAIN flag"); }
2173227_2
public void capabilityFactoryAdded(ICapabilityFactory capabilityFactory) { log.info("Adding factory: " + capabilityFactory.getType()); this.capabilityFactories.put(capabilityFactory.getType(), capabilityFactory); }
2173449_175
public static Product createProductSubset(Product sourceProduct, ProductSubsetDef subsetDef, String name, String desc) throws IOException { return createProductSubset(sourceProduct, false, subsetDef, name, desc); }
2177364_0
public LDIFChangeRecord nextRecord() throws IOException, LDIFException { return reader.readChangeRecord(); }
2180960_5
public static void parseDefine(final Define d, final ParsedDefine p) throws MojoExecutionException { parseDefineName(d.getDefineName(), p); parseDefineValueType(d.getValueType(), p); parseDefineValue(d.getValue(), p); }
2185113_0
public static void main(String args[]) { PApplet.main(new String[] { PixelController.class.getName().toString() }); }
2188276_354
public void setSqlStatementSeparator(String sqlStatementSeparator) { this.sqlStatementSeparator = sqlStatementSeparator; }
2192780_20
public static Content content(final String value) { return new Content() { @Override public String content(Context context) { return value; } }; }
2192825_0
public String write(Object object) throws JSONException { return this.write(object, null, null, false); }
2197202_17
public static void clearCache() { fields.clear(); fields = new HashMap<>(); }
2197427_2
public JSONObject postPhoto(String caption, String source, String link, String tags, String date) throws Exception { Map<String, Object> params = new HashMap<String, Object>(); if (caption != null && caption != "") params.put("caption", caption); params.put("source", source); if (link != null && caption != "") params.put("link", link); return post(POST_PHOTO, tags, date, params); }
2209304_0
@Override public void stop(Runnable callback) { stop(); if (null != callback) { callback.run(); } }