code
stringlengths
73
34.1k
label
stringclasses
1 value
@Override public RackResponse call(RackEnvironment environment) { RubyHash environmentHash = convertToRubyHash(environment.entrySet()); RubyArray response = callRackApplication(environmentHash); return convertToJavaRackResponse(response); }
java
protected AttributeCertificate getACFromResponse(VOMSACRequest request, VOMSResponse response) { byte[] acBytes = response.getAC(); if (acBytes == null) return null; ASN1InputStream asn1InputStream = new ASN1InputStream(acBytes); AttributeCertificate attributeCertificate = null; try {...
java
protected void handleErrorsInResponse(VOMSACRequest request, VOMSServerInfo si, VOMSResponse response) { if (response.hasErrors()) requestListener.notifyErrorsInVOMSReponse(request, si, response.errorMessages()); }
java
protected void handleWarningsInResponse(VOMSACRequest request, VOMSServerInfo si, VOMSResponse response) { if (response.hasWarnings()) requestListener.notifyWarningsInVOMSResponse(request, si, response.warningMessages()); }
java
protected void drawCheckerBoard(Graphics2D g2d) { g2d.setColor(getBackground()); g2d.fillRect(0, 0, getWidth(), getHeight()); g2d.setColor(getForeground()); final int checkSize = this.checkerSize; final int halfCheckSize = checkSize/2; final Stroke checker = this.checkerStroke; final Stroke backup = g2...
java
@POST @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Override public String getMessageToClient(@FormParam(Constants.Message.MFC) String json) { HttpSession httpSession = getHttpSession(); setContext(httpSession); MessageFromClient message = MessageFromClient.createFrom...
java
@JsCacheRemove(cls = OcelotServices.class, methodName = "getLocale", keys = {}, userScope = true) public void setLocale(@JsonUnmarshaller(LocaleMarshaller.class) Locale locale) { logger.debug("Receive setLocale call from client. {}", locale); ocelotContext.setLocale(locale); }
java
@JsCacheResult(year = 1) @JsonMarshaller(LocaleMarshaller.class) public Locale getLocale() { logger.debug("Receive getLocale call from client."); return ocelotContext.getLocale(); }
java
public Collection<String> getOutDatedCache(Map<String, Long> states) { return updatedCacheManager.getOutDatedCache(states); }
java
@JsTopic @WsDataService public Integer subscribe(@JsTopicName(prefix = Constants.Topic.SUBSCRIBERS) String topic, Session session) throws IllegalAccessException { return topicManager.registerTopicSession(topic, session); }
java
@JsTopic @WsDataService public Integer unsubscribe(@JsTopicName(prefix = Constants.Topic.SUBSCRIBERS) String topic, Session session) { return topicManager.unregisterTopicSession(topic, session); }
java
public JsTopicMessageController getJsTopicMessageController(String topic) { logger.debug("Looking for messageController for topic '{}'", topic); JsTopicMessageController messageController = messageControllerCache.loadFromCache(topic); if(null == messageController) { // not in cache messageController = getJsTop...
java
JsTopicMessageController getJsTopicMessageControllerFromJsTopicControl(String topic) { logger.debug("Looking for messageController for topic '{}' from JsTopicControl annotation", topic); Instance<JsTopicMessageController<?>> select = topicMessageController.select(new JsTopicCtrlAnnotationLiteral(topic)); if(!sele...
java
int sendMessageToTopicForSessions(Collection<Session> sessions, MessageToClient mtc, Object payload) { int sended = 0; JsTopicMessageController msgControl = messageControllerManager.getJsTopicMessageController(mtc.getId()); Collection<Session> sessionsClosed = new ArrayList<>(); for (Session session : sessi...
java
int checkAndSendMtcToSession(Session session, JsTopicMessageController msgControl, MessageToClient mtc, Object payload) throws SessionException { if (session != null) { if (session.isOpen()) { try { if (null != msgControl) { checkMessageTopic(userContextFactory.getUserContext(session.getId()), ...
java
void checkMessageTopic(UserContext ctx, String topic, Object payload, JsTopicMessageController msgControl) throws NotRecipientException { if (null != msgControl) { msgControl.checkRight(ctx, topic, payload); } }
java
public User getMe(AccessToken accessToken, String... attributes) { return getUserService().getMe(accessToken, attributes); }
java
public AccessToken refreshAccessToken(AccessToken accessToken, Scope... scopes) { return getAuthService().refreshAccessToken(accessToken, scopes); }
java
@Deprecated public User updateUser(String id, UpdateUser updateUser, AccessToken accessToken) { return getUserService().updateUser(id, updateUser, accessToken); }
java
@Deprecated public Group updateGroup(String id, UpdateGroup updateGroup, AccessToken accessToken) { return getGroupService().updateGroup(id, updateGroup, accessToken); }
java
public Client getClient(String clientId, AccessToken accessToken) { return getAuthService().getClient(clientId, accessToken); }
java
public Client createClient(Client client, AccessToken accessToken) { return getAuthService().createClient(client, accessToken); }
java
public Client updateClient(String clientId, Client client, AccessToken accessToken) { return getAuthService().updateClient(clientId, client, accessToken); }
java
public void print(final PrintStream out, final ICodingAnnotationStudy study) { if (study.getRaterCount() > 2) throw new IllegalArgumentException("Contingency tables are only applicable for two rater studies."); //TODO: measure length of cats. maybe cut them. Map<Object, Integer> categories = new Linked...
java
public static void checkSyntax(String fqan) { if (fqan.length() > 255) throw new VOMSError("fqan.length() > 255"); if (!fqanPattern.matcher(fqan).matches()) throw new VOMSError("Syntax error in fqan: " + fqan); }
java
public static void checkRole(String roleName) { if (roleName.length() > 255) throw new VOMSError("roleName.length()>255"); if (!rolePattern.matcher(roleName).matches()) throw new VOMSError("Syntax error in role name: " + roleName); }
java
public static String getRoleName(String containerName) { if (!isRole(containerName) && !isQualifiedRole(containerName)) throw new VOMSError("No role specified in \"" + containerName + "\" voms syntax."); Matcher m = fqanPattern.matcher(containerName); if (m.matches()) { String roleGr...
java
public static String getGroupName(String containerName) { checkSyntax(containerName); // If it's a container and it's not a role or a qualified role, then // it's a group! if (!isRole(containerName) && !isQualifiedRole(containerName)) return containerName; Matcher m = fqanPattern.matcher(c...
java
@Override public void send(byte[] b, int off, int len) { handler.send(b, off, len); }
java
protected Artifact createArtifact(final ArtifactItem item) throws MojoExecutionException { assert item != null; if (item.getVersion() == null) { fillMissingArtifactVersion(item); if (item.getVersion() == null) { throw new MojoExecutionException("Unable to find a...
java
private void fillMissingArtifactVersion(final ArtifactItem item) { log.trace("Attempting to find missing version in {}:{}", item.getGroupId() , item.getArtifactId()); List list = project.getDependencies(); for (int i = 0; i < list.size(); ++i) { Dependency dependency = (Dependency)...
java
@Override public void onRecv(byte[] b, int off, int len) { connection.onRecv(b, off, len); }
java
public List<Integer> searchBigBytes(byte[] srcBytes, byte[] searchBytes) { int numOfThreadsOptimized = (srcBytes.length / analyzeByteArrayUnitSize); if (numOfThreadsOptimized == 0) { numOfThreadsOptimized = 1; } return searchBigBytes(srcBytes, searchBytes, numOfThreadsOptimized); }
java
public String getFromEnvOrSystemProperty(String propName) { String val = System.getenv(propName); if (val == null) val = System.getProperty(propName); return val; }
java
public void print(final PrintStream out, final ICodingAnnotationStudy study) { //TODO: measure length of cats. maybe cut them. Map<Object, Integer> categories = new LinkedHashMap<Object, Integer>(); for (Object cat : study.getCategories()) categories.put(cat, categories.size()); final String DIVIDER...
java
String getPackagePath(TypeElement te) { return te.getQualifiedName().toString().replaceAll("." + te.getSimpleName(), ""); }
java
String getFilename(TypeElement te, String fwk) { return getFilename(te.getSimpleName().toString(), fwk); }
java
void writeCoreInClassesOutput() { String resPath = ProcessorConstants.SEPARATORCHAR + "js"; fws.copyResourceToClassesOutput(resPath, "core.ng.min.js"); fws.copyResourceToClassesOutput(resPath, "core.ng.js"); fws.copyResourceToClassesOutput(resPath, "core.min.js"); fws.copyResourceToClassesOutput(resPath,...
java
protected boolean fileExistsAndIsReadable(String filename) { File f = new File(filename); return f.exists() && f.isFile() && f.canRead(); }
java
WSController getWSController() { if (null == controller) { controller = CDI.current().select(WSController.class).get(); // controller = getCdiBeanResolver().getBean(WSController.class); } return controller; }
java
@Override public double calculateExpectedAgreement() { Map<Object, int[]> annotationsPerCategory = CodingAnnotationStudy.countAnnotationsPerCategory(study); BigDecimal result = BigDecimal.ZERO; for (Object category : study.getCategories()) { int[] annotations = annotationsPerCategory.get(category)...
java
@Override public double calculateCategoryAgreement(final Object category) { // N = # subjects = #items -> index i // n = # ratings/subject = #raters // k = # categories -> index j // n_ij = # raters that annotated item i as category j // // k_j = (P_j - p_j) / (1 - p_j) // P_j = (sum( n_ij^2 ) - ...
java
public IJsonMarshaller getIJsonMarshallerInstance(Class<? extends IJsonMarshaller> cls) throws JsonMarshallerException { if(logger.isDebugEnabled()) { logger.debug("Try to get {} by CDI.select Unsatisfied: {}", cls.getName(), CDI.current().select(cls).isUnsatisfied()); } if(CDI.current().select(cls).isUnsa...
java
public static double getSignificance(double[] sample1, double[] sample2) throws IllegalArgumentException, MathException { double alpha = TestUtils.pairedTTest(sample1, sample2); boolean significance = TestUtils.pairedTTest(sample1, sample2, .30); System.err.println("sig: " + significance); ...
java
public static double getSignificance(double correlation1, double correlation2, int n1, int n2) throws MathException { // transform to Fisher Z-values double zv1 = FisherZTransformation.transform(correlation1); double zv2 = FisherZTransformation.transform(correlation2); // diffe...
java
private AntBuilder getAnt() { if (this.ant == null) { AntBuilder ant = new AntBuilder(); BuildLogger logger = (BuildLogger) ant.getAntProject().getBuildListeners().get(0); logger.setEmacsMode(true); this.ant = ant; } return this.ant; }
java
public Method getMethodFromDataService(final Class dsClass, final MessageFromClient message, List<Object> arguments) throws NoSuchMethodException { logger.debug("Try to find method {} on class {}", message.getOperation(), dsClass); List<String> parameters = message.getParameters(); int nbparam = parameters.siz...
java
public Method getNonProxiedMethod(Class cls, String methodName, Class<?>... parameterTypes) throws NoSuchMethodException { return cls.getMethod(methodName, parameterTypes); }
java
int getNumberOfNullEnderParameter(List<String> parameters) { int nbnull = 0; for (int i = parameters.size() - 1; i >= 0; i--) { String parameter = parameters.get(i); if (parameter.equals("null")) { nbnull++; } else { break; } } return nbnull; }
java
void checkMethod(Method method, List<Object> arguments, List<String> parameters, int nbparam) throws IllegalArgumentException, JsonUnmarshallingException, JsonMarshallerException { Type[] paramTypes = method.getGenericParameterTypes(); Annotation[][] parametersAnnotations = method.getParameterAnnotations(); in...
java
public void setARGB(int a, int r, int g, int b){ setValue(Pixel.argb(a, r, g, b)); }
java
public void setRGB(int r, int g, int b){ setValue(Pixel.rgb(r, g, b)); }
java
public void setRGB_preserveAlpha(int r, int g, int b){ setValue((getValue() & 0xff000000 ) | Pixel.argb(0, r, g, b)); }
java
public static BufferedImage get(Image img, int imgType){ Function<Integer, ImageObserver> obs = flags->{ return (image, infoflags, x, y, width, height)->(infoflags & flags)!=flags; }; BufferedImage bimg = new BufferedImage( img.getWidth(obs.apply(ImageObserver.WIDTH)), img.getHeight(obs.apply(ImageObs...
java
@Override public int registerTopicSession(String topic, Session session) throws IllegalAccessException { if (isInconsistenceContext(topic, session)) { return 0; } Collection<Session> sessions; if (map.containsKey(topic)) { sessions = map.get(topic); } else { sessions = Collections.synchroni...
java
@Override public int unregisterTopicSession(String topic, Session session) { if (isInconsistenceContext(topic, session)) { return 0; } logger.debug("'{}' unsubscribe to '{}'", session.getId(), topic); if (Constants.Topic.ALL.equals(topic)) { for (Map.Entry<String, Collection<Session>> entry : map....
java
int removeSessionToSessions(Session session, Collection<Session> sessions) { if (sessions != null) { if (sessions.remove(session)) { return 1; } } return 0; }
java
boolean unregisterTopicSessions(String topic, Collection<Session> sessions) { boolean unregister = false; if (sessions != null && !sessions.isEmpty()) { Collection<Session> all = map.get(topic); if(all != null) { unregister = all.removeAll(sessions); if (all.isEmpty()) { map.remove(topic);...
java
@Override public Collection<String> removeSessionsToTopic(Collection<Session> sessions) { if (sessions != null && !sessions.isEmpty()) { Collection<String> topicUpdated = new ArrayList<>(); for (String topic : map.keySet()) { if(unregisterTopicSessions(topic, sessions)) { topicUpdated.add(topic)...
java
@Override public Collection<String> removeSessionToTopics(Session session) { if (session != null) { return removeSessionsToTopic(Arrays.asList(session)); // for (String topic : map.keySet()) { // sendSubscriptionEvent(Constants.Topic.SUBSCRIBERS + Constants.Topic.COLON + topic, unregisterTopicSession(to...
java
void sendSubscriptionEvent(String topic, int nb) { Collection<Session> sessions = getSessionsForTopic(topic); if (!sessions.isEmpty()) { MessageToClient messageToClient = new MessageToClient(); messageToClient.setId(topic); messageToClient.setType(MessageType.MESSAGE); messageToClient.setResponse(...
java
@Override public Collection<Session> getSessionsForTopic(String topic) { Collection<Session> result; if (map.containsKey(topic)) { return Collections.unmodifiableCollection(map.get(topic)); } else { result = Collections.EMPTY_LIST; } return result; }
java
@Override public int getNumberSubscribers(String topic) { if (map.containsKey(topic)) { return map.get(topic).size(); } return 0; }
java
public SSLSocketFactory getSSLSockectFactory() { SSLContext context = null; try { context = SSLContext.getInstance("TLS"); } catch (NoSuchAlgorithmException e) { throw new VOMSError(e.getMessage(), e); } KeyManager[] keyManagers = new KeyManager[] { credential.getKeyManager() }; ...
java
public static void scaleArray(final double[] array, final double factor){ for(int i = 0; i < array.length; i++){ array[i] *= factor; } }
java
@Override public double calculateObservedDisagreement() { ensureDistanceFunction(); double result = 0.0; double maxDistance = 1.0; for (ICodingAnnotationItem item : study.getItems()) { Map<Object, Integer> annotationsPerCategory = CodingAnnotationStudy.countTotalAnnotationsPerCategory(item); for (...
java
String getJsInstancename(String classname) { char chars[] = classname.toCharArray(); chars[0] = Character.toLowerCase(chars[0]); return new String(chars); //return Introspector.decapitalize(classname); }
java
String getJsClassname(TypeElement typeElement) { DataService dsAnno = typeElement.getAnnotation(DataService.class); String name = dsAnno.name(); if (name.isEmpty()) { name = typeElement.getSimpleName().toString(); } return name; }
java
void browseAndWriteMethods(List<ExecutableElement> methodElements, String classname, Writer writer) throws IOException { Collection<String> methodProceeds = new ArrayList<>(); boolean first = true; for (ExecutableElement methodElement : methodElements) { if (isConsiderateMethod(methodProceeds, methodElemen...
java
protected List<ExecutableElement> getOrderedMethods(TypeElement typeElement, Comparator<ExecutableElement> comparator) { List<ExecutableElement> methods = ElementFilter.methodsIn(typeElement.getEnclosedElements()); Collections.sort(methods, comparator); return methods; }
java
List<String> getArgumentsType(ExecutableElement methodElement) { ExecutableType methodType = (ExecutableType) methodElement.asType(); List<String> res = new ArrayList<>(); for (TypeMirror argumentType : methodType.getParameterTypes()) { res.add(argumentType.toString()); } return res; }
java
List<String> getArguments(ExecutableElement methodElement) { List<String> res = new ArrayList<>(); for (VariableElement variableElement : methodElement.getParameters()) { res.add(variableElement.toString()); } return res; }
java
public CodingAnnotationStudy stripCategories(final Object keepCategory, final Object nullCategory) { CodingAnnotationStudy result = new CodingAnnotationStudy(getRaterCount()); for (ICodingAnnotationItem item : getItems()) { CodingAnnotationItem newItem = new CodingAnnotationItem(raters.size()); for (I...
java
public double computePhase(int idx){ double r = real[idx]; double i = imag[idx]; return atan2(r, i); }
java
private Map findLoaders() { Map loaders = getContainer().getComponentDescriptorMap(ProviderLoader.class.getName()); if (loaders == null) { throw new Error("No provider loaders found"); } Set keys = loaders.keySet(); Map found = null; ProviderLoader defaultLoa...
java
public static byte[] getBytes(String text) { byte[] bytes = new byte[] {}; try { bytes = text.getBytes("utf-8"); } catch (UnsupportedEncodingException e) { } return bytes; }
java
public static byte[] loadBytesFromFile(File file) { byte[] bytes = null; try { bytes = Files.readAllBytes(Paths.get(file.getAbsolutePath())); } catch (IOException e) { e.printStackTrace(); } return bytes; }
java
public static void saveBytesToFile(byte[] data, File file) { if (data == null) { return; } FileOutputStream fos = null; BufferedOutputStream bos = null; try { fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); bos.write(data); bos.flush(); } catch (FileNotFoundE...
java
public static BufferedImage loadImage(String fileName){ File f = new File(fileName); if(f.exists()){ return loadImage(f); } throw new ImageLoaderException(new FileNotFoundException(fileName)); }
java
public static BufferedImage loadImage(File file){ try { BufferedImage bimg = ImageIO.read(file); if(bimg == null){ throw new ImageLoaderException("Could not load Image! ImageIO.read() returned null."); } return bimg; } catch (IOException e) { throw new ImageLoaderException(e); } }
java
MessageToClient _createMessageToClient(MessageFromClient message, T session) { MessageToClient messageToClient = new MessageToClient(); messageToClient.setId(message.getId()); try { Class cls = Class.forName(message.getDataService()); Object dataService = this.getDataService(session, cls); logger.d...
java
void injectSession(Class<?>[] parameterTypes, List<Object> arguments, T session) { if (parameterTypes != null) { int i = 0; for (Class<?> parameterType : parameterTypes) { if (parameterType.isInstance(session)) { arguments.set(i, session); break; } i++; } } }
java
private void loadCertificateFromFile(File file) { certificateFileSanityChecks(file); try { X509Certificate aaCert = CertificateUtils.loadCertificate( new FileInputStream(file), Encoding.PEM); // Get certificate subject hash, using the CANL implementation for CA // files Strin...
java
private void certificateFileSanityChecks(File certFile) { if (!certFile.exists()) throw new VOMSError("Local VOMS trusted certificate does not exist:" + certFile.getAbsolutePath()); if (!certFile.canRead()) throw new VOMSError("Local VOMS trusted certificate is not readable:" + cer...
java
private void directorySanityChecks(File directory) { if (!directory.exists()) throw new VOMSError("Local trust directory does not exists:" + directory.getAbsolutePath()); if (!directory.isDirectory()) throw new VOMSError("Local trust directory is not a directory:" + directory.getAb...
java
private boolean doesItemMatchAppropriateCondition(Object item) { Matcher<?> matcher; if (item instanceof View) { matcher = loaded(); } else if (item instanceof Element) { matcher = displayed(); } else { matcher = present(); } return m...
java
String getClassnameFromProxy(Object dataservice) { String ds = dataservice.toString(); return getClassnameFromProxyname(ds); }
java
String getClassnameFromProxyname(String proxyname) { Pattern pattern = Pattern.compile("[@$]"); Matcher matcher = pattern.matcher(proxyname); matcher.find(); matcher.start(); return proxyname.substring(0, matcher.start()); }
java
public static X509CertChainValidatorExt buildCertificateValidator() { return buildCertificateValidator( DefaultVOMSValidator.DEFAULT_TRUST_ANCHORS_DIR, null, null, 0L, DEFAULT_NS_CHECKS, DEFAULT_CRL_CHECKS, DEFAULT_OCSP_CHECKS); }
java
public int getIndexOfMaxValue(int channel){ double[] values = getData()[channel]; int index = 0; double val = values[index]; for(int i = 1; i < numValues(); i++){ if(values[i] > val){ index = i; val = values[index]; } } return index; }
java
public int getIndexOfMinValue(int channel){ double[] values = getData()[channel]; int index = 0; double val = values[index]; for(int i = 1; i < numValues(); i++){ if(values[i] < val){ index = i; val = values[index]; } } return index; }
java
public void setValue(final int channel, final int x, final int y, final double value){ this.data[channel][y*this.width + x] = value; }
java
boolean isMonitored(HttpSession session) { boolean monitor = false; if (null != session && session.getAttribute(Constants.Options.OPTIONS) != null) { monitor = ((Options) session.getAttribute(Constants.Options.OPTIONS)).isMonitor(); } return monitor; }
java
public void saveToCache(String topic, Class<? extends JsTopicMessageController> cls) { if(null != topic && null != cls) { messageControllers.put(topic, cls); } }
java
public JsTopicMessageController loadFromCache(String topic) { if(null == topic) { return null; } if(messageControllers.containsKey(topic)) { Instance<? extends JsTopicMessageController> instances = getInstances(messageControllers.get(topic)); if(!instances.isUnsatisfied()) { return instances.get(); ...
java
public static IUnitizingAnnotationUnit findNextUnit( final Iterator<IUnitizingAnnotationUnit> units, int raterIdx) { return findNextUnit(units, raterIdx, null); }
java
public static IUnitizingAnnotationUnit findNextUnit( final Iterator<IUnitizingAnnotationUnit> units, final Object category) { return findNextUnit(units, -1, category); }
java
public static IUnitizingAnnotationUnit findNextUnit( final Iterator<IUnitizingAnnotationUnit> units, int raterIdx, final Object category) { while (units.hasNext()) { IUnitizingAnnotationUnit result = units.next(); if (category != null && !category.equals(result.getCategory())) { cont...
java
public static Object deserialize(String json, String containerType, Class cls, NestedContent nestedContent) throws ApiException { try{ if(("List".equals(containerType) || "Array".equals(containerType)) && nestedContent != null){ if(NestedContent.CONTEXT.equals(nestedContent)){ ...
java
public void checkAccessTopic(UserContext ctx, String topic) throws IllegalAccessException { boolean tacPresent0 = checkAccessTopicGlobalAC(ctx, topic); boolean tacPresent1 = checkAccessTopicFromJsTopicControl(ctx, topic); boolean tacPresent2 = checkAccessTopicFromJsTopicControls(ctx, topic); if (logger.isDebugE...
java