code
stringlengths
73
34.1k
label
stringclasses
1 value
private int[] convertBatch(int[] batch) { int[] conv = new int[batch.length]; for (int i=0; i<batch.length; i++) { conv[i] = sample[batch[i]]; } return conv; }
java
public static boolean containsAtLeastOneNonBlank(List<String> list){ for(String str : list){ if(StringUtils.isNotBlank(str)){ return true; } } return false; }
java
public static List<Integer> toIntegerList(List<String> strList, boolean failOnException){ List<Integer> intList = new ArrayList<Integer>(); for(String str : strList){ try{ intList.add(Integer.parseInt(str)); } catch(NumberFormatException nfe){ if(failOnException){ return null; } else{ ...
java
public static void add(double[] array1, double[] array2) { assert (array1.length == array2.length); for (int i=0; i<array1.length; i++) { array1[i] += array2[i]; } }
java
public static boolean containsOnlyNull(Object... values){ for(Object o : values){ if(o!= null){ return false; } } return true; }
java
public static boolean containsOnlyNotNull(Object... values){ for(Object o : values){ if(o== null){ return false; } } return true; }
java
@RequestMapping(value="/soy/compileJs", method=GET) public ResponseEntity<String> compile(@RequestParam(required = false, value="hash", defaultValue = "") final String hash, @RequestParam(required = true, value = "file") final String[] templateFileNames, ...
java
public int[] sampleBatchWithReplacement() { // Sample the indices with replacement. int[] batch = new int[batchSize]; for (int i=0; i<batch.length; i++) { batch[i] = Prng.nextInt(numExamples); } return batch; }
java
public int[] sampleBatchWithoutReplacement() { int[] batch = new int[batchSize]; for (int i=0; i<batch.length; i++) { if (cur == indices.length) { cur = 0; } if (cur == 0) { IntArrays.shuffle(indices); } batch[i]...
java
public void adjustGlassSize() { if (isGlassEnabled()) { ResizeHandler handler = getGlassResizer(); if (handler != null) handler.onResize(null); } }
java
public static Bounds getSymmetricBounds(int dim, double l, double u) { double [] L = new double[dim]; double [] U = new double[dim]; for(int i=0; i<dim; i++) { L[i] = l; U[i] = u; } return new Bounds(L, U); }
java
public static Optional<Tag> parse(final String httpTag) { Tag result = null; boolean weak = false; String internal = httpTag; if (internal.startsWith("W/")) { weak = true; internal = internal.substring(2); } if (internal.startsWith("\""...
java
public String format() { if (getName().equals("*")) { return "*"; } else { StringBuilder sb = new StringBuilder(); if (isWeak()) { sb.append("W/"); } return sb.append('"').append(getName()).append('"').toString(...
java
public static PropertyResourceBundle getBundle(String baseName, Locale locale) throws UnsupportedEncodingException, IOException{ InputStream is = UTF8PropertyResourceBundle.class.getResourceAsStream("/"+baseName + "_"+locale.toString()+PROPERTIES_EXT); if(is != null){ return new PropertyResourceBundle(new InputS...
java
@Override public boolean minimize(DifferentiableBatchFunction function, IntDoubleVector point) { return minimize(function, point, null); }
java
@SuppressWarnings("unchecked") public <T> T convertElement(ConversionContext context, Object source, TypeReference<T> destinationType) throws ConverterException { return (T) elementConverter.convert(context, source, destinationType); }
java
public Conditionals addIfMatch(Tag tag) { Preconditions.checkArgument(!modifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderConstants.IF_MODIFIED_SINCE)); Preconditions.checkArgument(noneMatch.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MATCH, HeaderCons...
java
public Conditionals ifModifiedSince(LocalDateTime time) { Preconditions.checkArgument(match.isEmpty(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MODIFIED_SINCE, HeaderConstants.IF_MATCH)); Preconditions.checkArgument(!unModifiedSince.isPresent(), String.format(ERROR_MESSAGE, HeaderConstants.IF_MOD...
java
public Headers toHeaders() { Headers headers = new Headers(); if (!getMatch().isEmpty()) { headers = headers.add(new Header(HeaderConstants.IF_MATCH, buildTagHeaderValue(getMatch()))); } if (!getNoneMatch().isEmpty()) { headers = headers.add(new Header(HeaderConst...
java
public Collection<QName> getPortComponentQNames() { //TODO:Check if there is just one QName that drives all portcomponents //or each port component can have a distinct QName (namespace/prefix) //Maintain uniqueness of the QName Map<String, QName> map = new HashMap<String, QName>(); for ...
java
public PortComponentMetaData getPortComponentByWsdlPort(String name) { ArrayList<String> pcNames = new ArrayList<String>(); for (PortComponentMetaData pc : portComponents) { String wsdlPortName = pc.getWsdlPort().getLocalPart(); if (wsdlPortName.equals(name)) return pc...
java
public static final void setBounds(UIObject o, Rect bounds) { setPosition(o, bounds); setSize(o, bounds); }
java
public static final void setPosition(UIObject o, Rect pos) { Style style = o.getElement().getStyle(); style.setPropertyPx("left", pos.x); style.setPropertyPx("top", pos.y); }
java
public static final void setSize(UIObject o, Rect size) { o.setPixelSize(size.w, size.h); }
java
public static final boolean isInside(int x, int y, Rect box) { return (box.x < x && x < box.x + box.w && box.y < y && y < box.y + box.h); }
java
public static final boolean isMouseInside(NativeEvent event, Element element) { return isInside(event.getClientX() + Window.getScrollLeft(), event.getClientY() + Window.getScrollTop(), getBounds(element)); }
java
public static final Rect getViewportBounds() { return new Rect(Window.getScrollLeft(), Window.getScrollTop(), Window.getClientWidth(), Window.getClientHeight()); }
java
public static final Date utc2date(Long time) { // don't accept negative values if (time == null || time < 0) return null; // add the timezone offset time += timezoneOffsetMillis(new Date(time)); return new Date(time); }
java
public static final Long date2utc(Date date) { // use null for a null date if (date == null) return null; long time = date.getTime(); // remove the timezone offset time -= timezoneOffsetMillis(date); return time; }
java
public static FullTypeSignature getTypeSignature(String typeSignatureString, boolean useInternalFormFullyQualifiedName) { String key; if (!useInternalFormFullyQualifiedName) { key = typeSignatureString.replace('.', '/') .replace('$', '.'); } else { key = typeSignatureString; } // we always use ...
java
public static FullTypeSignature getTypeSignature(Class<?> clazz, Class<?>[] typeArgs) { ClassTypeSignature rawClassTypeSignature = (ClassTypeSignature) javaTypeToTypeSignature .getTypeSignature(clazz); TypeArgSignature[] typeArgSignatures = new TypeArgSignature[typeArgs.length]; for (int i = 0; i < typeArgs.l...
java
public static OptionalString ofNullable(ResourceKey key, String value) { return new GenericOptionalString(RUNTIME_SOURCE, key, value); }
java
public Archetype parse(String adl) { try { return parse(new StringReader(adl)); } catch (IOException e) { // StringReader should never throw an IOException throw new AssertionError(e); } }
java
@SuppressWarnings({"unchecked", "unused"}) public static <T> T[] object2Array(final Class<T> clazz, final Object obj) { return (T[]) obj; }
java
public void pauseUpload() throws LocalOperationException { if (state == State.UPLOADING) { setState(State.PAUSED); executor.hardStop(); } else { throw new LocalOperationException("Attempt to pause upload while assembly is not uploading"); } }
java
protected AssemblyResponse watchStatus() throws LocalOperationException, RequestException { AssemblyResponse response; do { response = getClient().getAssemblyByUrl(url); try { Thread.sleep(1000); } catch (InterruptedException e) { throw...
java
private long getTotalUploadSize() throws IOException { long size = 0; for (Map.Entry<String, File> entry : files.entrySet()) { size += entry.getValue().length(); } for (Map.Entry<String, InputStream> entry : fileStreams.entrySet()) { size += entry.getValue().avai...
java
public static <T extends InterconnectObject> T fromJson(String data, Class<T> clazz) throws IOException { return InterconnectMapper.mapper.readValue(data, clazz); }
java
public Response save() throws RequestException, LocalOperationException { Map<String, Object> templateData = new HashMap<String, Object>(); templateData.put("name", name); options.put("steps", steps.toMap()); templateData.put("template", options); Request request = new Request(...
java
public boolean matches(String resourcePath) { if (!valid) { return false; } if (resourcePath == null) { return acceptsContextPathEmpty; } if (contextPathRegex != null && !contextPathRegex.matcher(resourcePath).matches()) { return false; } if (contextPathBlacklistRegex != nu...
java
private ClassLoaderInterface getClassLoader() { Map<String, Object> application = ActionContext.getContext().getApplication(); if (application != null) { return (ClassLoaderInterface) application.get(ClassLoaderInterface.CLASS_LOADER_INTERFACE); } return null; }
java
public @Nullable String build() { StringBuilder queryString = new StringBuilder(); for (NameValuePair param : params) { if (queryString.length() > 0) { queryString.append(PARAM_SEPARATOR); } queryString.append(Escape.urlEncode(param.getName())); queryString.append(VALUE_SEPARATO...
java
public AssemblyResponse cancelAssembly(String url) throws RequestException, LocalOperationException { Request request = new Request(this); return new AssemblyResponse(request.delete(url, new HashMap<String, Object>())); }
java
public Response getTemplate(String id) throws RequestException, LocalOperationException { Request request = new Request(this); return new Response(request.get("/templates/" + id)); }
java
public Response updateTemplate(String id, Map<String, Object> options) throws RequestException, LocalOperationException { Request request = new Request(this); return new Response(request.put("/templates/" + id, options)); }
java
public Response deleteTemplate(String id) throws RequestException, LocalOperationException { Request request = new Request(this); return new Response(request.delete("/templates/" + id, new HashMap<String, Object>())); }
java
public ListResponse listTemplates(Map<String, Object> options) throws RequestException, LocalOperationException { Request request = new Request(this); return new ListResponse(request.get("/templates", options)); }
java
public Response getBill(int month, int year) throws RequestException, LocalOperationException { Request request = new Request(this); return new Response(request.get("/bill/" + year + String.format("-%02d", month))); }
java
@SuppressWarnings("unchecked") public static <T> T convert(Object fromValue, Class<T> toType) throws TypeCastException { return convert(fromValue, toType, (String) null); }
java
public SignedJWT verifyToken(String jwtString) throws ParseException { try { SignedJWT jwt = SignedJWT.parse(jwtString); if (jwt.verify(new MACVerifier(this.jwtSharedSecret))) { return jwt; } return null; } catch (JOSEException e) { ...
java
public void bind(T service, Map<String, Object> props) { synchronized (serviceMap) { serviceMap.put(ServiceUtil.getComparableForServiceRanking(props), service); updateSortedServices(); } }
java
public void unbind(T service, Map<String, Object> props) { synchronized (serviceMap) { serviceMap.remove(ServiceUtil.getComparableForServiceRanking(props)); updateSortedServices(); } }
java
private void updateSortedServices() { List<T> copiedList = new ArrayList<T>(serviceMap.values()); sortedServices = Collections.unmodifiableList(copiedList); if (changeListener != null) { changeListener.changed(); } }
java
public static <T> JacksonParser<T> json(Class<T> contentType) { return new JacksonParser<>(null, contentType); }
java
public void addStep(String name, String robot, Map<String, Object> options) { all.put(name, new Step(name, robot, options)); }
java
protected boolean determineFeatureState(final ITemplateContext context, final IProcessableElementTag tag, final AttributeName attributeName, final String attributeValue, boolean defaultState) { final IStandardExpressionParser expressionParser = StandardExpressions.getExpressionParser(context.getConfiguration())...
java
public void init(Configuration configuration) { if (devMode && reload && !listeningToDispatcher) { // this is the only way I found to be able to get added to to // ConfigurationProvider list // listening to events in Dispatcher listeningToDispatcher = true; ...
java
public void addFile(File file) { String name = "file"; files.put(normalizeDuplicateName(name), file); }
java
public void addFile(InputStream inputStream) { String name = "file"; fileStreams.put(normalizeDuplicateName(name), inputStream); }
java
public void removeFile(String name) { if(files.containsKey(name)) { files.remove(name); } if(fileStreams.containsKey(name)) { fileStreams.remove(name); } }
java
public AssemblyResponse save(boolean isResumable) throws RequestException, LocalOperationException { Request request = new Request(getClient()); options.put("steps", steps.toMap()); // only do tus uploads if files will be uploaded if (isResumable && getFilesCount() > 0) { ...
java
protected void processTusFiles(String assemblyUrl) throws IOException, ProtocolException { tusClient.setUploadCreationURL(new URL(getClient().getHostUrl() + "/resumable/files/")); tusClient.enableResuming(tusURLStore); for (Map.Entry<String, File> entry : files.entrySet()) { process...
java
@SuppressWarnings("unchecked") public static <T extends Serializable> T makeClone(T from) { return (T) SerializationUtils.clone(from); }
java
private static int checkResult(int result) { if (exceptionsEnabled && result != cudnnStatus.CUDNN_STATUS_SUCCESS) { throw new CudaException(cudnnStatus.stringFor(result)); } return result; }
java
public static int cudnnSetTensor4dDescriptorEx( cudnnTensorDescriptor tensorDesc, int dataType, /** image data type */ int n, /** number of inputs (batch size) */ int c, /** number of input feature maps */ int h, /** height of input section */ int w, /** width of input s...
java
public static int cudnnOpTensor( cudnnHandle handle, cudnnOpTensorDescriptor opTensorDesc, Pointer alpha1, cudnnTensorDescriptor aDesc, Pointer A, Pointer alpha2, cudnnTensorDescriptor bDesc, Pointer B, Pointer beta, cudnnTensorDes...
java
public static int cudnnGetReductionIndicesSize( cudnnHandle handle, cudnnReduceTensorDescriptor reduceTensorDesc, cudnnTensorDescriptor aDesc, cudnnTensorDescriptor cDesc, long[] sizeInBytes) { return checkResult(cudnnGetReductionIndicesSizeNative(handle, reduceTe...
java
public static int cudnnGetReductionWorkspaceSize( cudnnHandle handle, cudnnReduceTensorDescriptor reduceTensorDesc, cudnnTensorDescriptor aDesc, cudnnTensorDescriptor cDesc, long[] sizeInBytes) { return checkResult(cudnnGetReductionWorkspaceSizeNative(handle, redu...
java
public static int cudnnReduceTensor( cudnnHandle handle, cudnnReduceTensorDescriptor reduceTensorDesc, Pointer indices, long indicesSizeInBytes, Pointer workspace, long workspaceSizeInBytes, Pointer alpha, cudnnTensorDescriptor aDesc, Point...
java
public static int cudnnGetConvolutionNdDescriptor( cudnnConvolutionDescriptor convDesc, int arrayLengthRequested, int[] arrayLength, int[] padA, int[] strideA, int[] dilationA, int[] mode, int[] computeType)/** convolution data type */ { ...
java
public static int cudnnConvolutionForward( cudnnHandle handle, Pointer alpha, cudnnTensorDescriptor xDesc, Pointer x, cudnnFilterDescriptor wDesc, Pointer w, cudnnConvolutionDescriptor convDesc, int algo, Pointer workSpace, long wo...
java
public static int cudnnConvolutionBackwardBias( cudnnHandle handle, Pointer alpha, cudnnTensorDescriptor dyDesc, Pointer dy, Pointer beta, cudnnTensorDescriptor dbDesc, Pointer db) { return checkResult(cudnnConvolutionBackwardBiasNative(handle, a...
java
public static int cudnnSoftmaxForward( cudnnHandle handle, int algo, int mode, Pointer alpha, cudnnTensorDescriptor xDesc, Pointer x, Pointer beta, cudnnTensorDescriptor yDesc, Pointer y) { return checkResult(cudnnSoftmaxForward...
java
public static int cudnnSoftmaxBackward( cudnnHandle handle, int algo, int mode, Pointer alpha, cudnnTensorDescriptor yDesc, Pointer y, cudnnTensorDescriptor dyDesc, Pointer dy, Pointer beta, cudnnTensorDescriptor dxDesc, P...
java
public static int cudnnPoolingForward( cudnnHandle handle, cudnnPoolingDescriptor poolingDesc, Pointer alpha, cudnnTensorDescriptor xDesc, Pointer x, Pointer beta, cudnnTensorDescriptor yDesc, Pointer y) { return checkResult(cudnnPooling...
java
public static int cudnnPoolingBackward( cudnnHandle handle, cudnnPoolingDescriptor poolingDesc, Pointer alpha, cudnnTensorDescriptor yDesc, Pointer y, cudnnTensorDescriptor dyDesc, Pointer dy, cudnnTensorDescriptor xDesc, Pointer x, ...
java
public static int cudnnGetActivationDescriptor( cudnnActivationDescriptor activationDesc, int[] mode, int[] reluNanOpt, double[] coef)/** ceiling for clipped RELU, alpha for ELU */ { return checkResult(cudnnGetActivationDescriptorNative(activationDesc, mode, reluNanOpt, co...
java
public static int cudnnActivationForward( cudnnHandle handle, cudnnActivationDescriptor activationDesc, Pointer alpha, cudnnTensorDescriptor xDesc, Pointer x, Pointer beta, cudnnTensorDescriptor yDesc, Pointer y) { return checkResult(cud...
java
public static int cudnnActivationBackward( cudnnHandle handle, cudnnActivationDescriptor activationDesc, Pointer alpha, cudnnTensorDescriptor yDesc, Pointer y, cudnnTensorDescriptor dyDesc, Pointer dy, cudnnTensorDescriptor xDesc, Pointer x...
java
public static int cudnnLRNCrossChannelForward( cudnnHandle handle, cudnnLRNDescriptor normDesc, int lrnMode, Pointer alpha, cudnnTensorDescriptor xDesc, Pointer x, Pointer beta, cudnnTensorDescriptor yDesc, Pointer y) { return c...
java
public static int cudnnLRNCrossChannelBackward( cudnnHandle handle, cudnnLRNDescriptor normDesc, int lrnMode, Pointer alpha, cudnnTensorDescriptor yDesc, Pointer y, cudnnTensorDescriptor dyDesc, Pointer dy, cudnnTensorDescriptor xDesc, ...
java
public static int cudnnBatchNormalizationBackward( cudnnHandle handle, int mode, Pointer alphaDataDiff, Pointer betaDataDiff, Pointer alphaParamDiff, Pointer betaParamDiff, cudnnTensorDescriptor xDesc, /** same desc for x, dx, dy */ Pointer x, ...
java
public static int cudnnRestoreDropoutDescriptor( cudnnDropoutDescriptor dropoutDesc, cudnnHandle handle, float dropout, Pointer states, long stateSizeInBytes, long seed) { return checkResult(cudnnRestoreDropoutDescriptorNative(dropoutDesc, handle, dropout...
java
public static int cudnnCreatePersistentRNNPlan( cudnnRNNDescriptor rnnDesc, int minibatch, int dataType, cudnnPersistentRNNPlan plan) { return checkResult(cudnnCreatePersistentRNNPlanNative(rnnDesc, minibatch, dataType, plan)); }
java
public static int cudnnGetRNNWorkspaceSize( cudnnHandle handle, cudnnRNNDescriptor rnnDesc, int seqLength, cudnnTensorDescriptor[] xDesc, long[] sizeInBytes) { return checkResult(cudnnGetRNNWorkspaceSizeNative(handle, rnnDesc, seqLength, xDesc, sizeInBytes)); ...
java
public static int cudnnCTCLoss( cudnnHandle handle, cudnnTensorDescriptor probsDesc, /** Tensor descriptor for probabilities, the dimensions are T,N,A (T is the timing steps, N is the mini batch size, A is the alphabet size) */ Pointer probs, /** probabilities after s...
java
public static int cudnnGetCTCLossWorkspaceSize( cudnnHandle handle, cudnnTensorDescriptor probsDesc, /** Tensor descriptor for probabilities, the dimensions are T,N,A (T is the timing steps, N is the mini batch size, A is the alphabet size) */ cud...
java
public static int cudnnGetRNNDataDescriptor( cudnnRNNDataDescriptor RNNDataDesc, int[] dataType, int[] layout, int[] maxSeqLength, int[] batchSize, int[] vectorSize, int arrayLengthRequested, int[] seqLengthArray, Pointer paddingFill) {...
java
public static <T> OptionalValue<T> ofNullable(T value) { return new GenericOptionalValue<T>(RUNTIME_SOURCE, DEFAULT_KEY, value); }
java
public static <T> OptionalValue<T> ofNullable(ResourceKey key, T value) { return new GenericOptionalValue<T>(RUNTIME_SOURCE, key, value); }
java
public static void stopService() { DaemonStarter.currentPhase.set(LifecyclePhase.STOPPING); final CountDownLatch cdl = new CountDownLatch(1); Executors.newSingleThreadExecutor().execute(() -> { DaemonStarter.getLifecycleListener().stopping(); DaemonStarter.daemon.stop(); ...
java
private static void handleSignals() { if (DaemonStarter.isRunMode()) { try { // handle SIGHUP to prevent process to get killed when exiting the tty Signal.handle(new Signal("HUP"), arg0 -> { // Nothing to do here System.out.prin...
java
public static void abortSystem(final Throwable error) { DaemonStarter.currentPhase.set(LifecyclePhase.ABORTING); try { DaemonStarter.getLifecycleListener().aborting(); } catch (Exception e) { DaemonStarter.rlog.error("Custom abort failed", e); } if (error ...
java
@PostConstruct public void initDatabase() { MongoDBInit.LOGGER.info("initializing MongoDB"); String dbName = System.getProperty("mongodb.name"); if (dbName == null) { throw new RuntimeException("Missing database name; Set system property 'mongodb.name'"); } MongoD...
java
public static Map<String, Object> with(Object... params) { Map<String, Object> map = new HashMap<>(); for (int i = 0; i < params.length; i++) { map.put(String.valueOf(i), params[i]); } return map; }
java
public static ResourceResolutionContext context(ResourceResolutionComponent[] components, Map<String, Object> messageParams) { return new ResourceResolutionContext(components, messageParams); }
java
@Inject("struts.json.action.fileProtocols") public void setFileProtocols(String fileProtocols) { if (StringUtils.isNotBlank(fileProtocols)) { this.fileProtocols = TextParseUtil.commaDelimitedStringToSet(fileProtocols); } }
java
protected boolean cannotInstantiate(Class<?> actionClass) { return actionClass.isAnnotation() || actionClass.isInterface() || actionClass.isEnum() || (actionClass.getModifiers() & Modifier.ABSTRACT) != 0 || actionClass.isAnonymousClass(); }
java
protected boolean checkExcludePackages(String classPackageName) { if (excludePackages != null && excludePackages.length > 0) { WildcardHelper wildcardHelper = new WildcardHelper(); // we really don't care about the results, just the boolean Map<String, String> matchMap = new HashMap<String, String>(); f...
java
protected boolean checkActionPackages(String classPackageName) { if (actionPackages != null) { for (String packageName : actionPackages) { String strictPackageName = packageName + "."; if (classPackageName.equals(packageName) || classPackageName.startsWith(strictPackageName)) return true; } } r...
java