language
stringclasses
2 values
func_code_string
stringlengths
63
466k
python
def top_k(x, reduced_dim, new_dim, dtype=tf.int32, name=None): """Like tf.top_k. This operation returns two tensors with the same shape. The output shape is identical to the shape of x, except that reduced_dim is replaced by new_dim. Args: x: a Tensor reduced_dim: a Dimension in x.shape.dims. n...
java
public synchronized boolean remove(final K key) { if (readOnly) { return false; } if (!validState) { throw new InvalidStateException(); } if (key == null) { return false; } try { if (log.isDebugEnabled()) { log.debug("trying remove key=" + key); } submitRedoRemove(key); if (remove...
java
public static CommerceNotificationAttachment fetchByUuid_First( String uuid, OrderByComparator<CommerceNotificationAttachment> orderByComparator) { return getPersistence().fetchByUuid_First(uuid, orderByComparator); }
java
public static void read() throws IOException, InterruptedException { for(short channel = 0; channel < ADC_CHANNEL_COUNT; channel++){ int conversion_value = getConversionValue(channel); console.print(String.format(" | %04d", conversion_value)); // print 4 digits with leading zeros ...
python
def setup(app): ''' Required Sphinx extension setup function. ''' app.connect('html-page-context', html_page_context) app.connect('build-finished', build_finished) app.sitemap_links = set()
java
public static UResourceBundle getBundleInstance(ULocale locale) { if (locale==null) { locale = ULocale.getDefault(); } return getBundleInstance(ICUData.ICU_BASE_NAME, locale.getBaseName(), ICUResourceBundle.ICU_DATA_CLASS_LOADER, false); }
java
public static nstrace get(nitro_service service) throws Exception{ nstrace obj = new nstrace(); nstrace[] response = (nstrace[])obj.get_resources(service); return response[0]; }
java
public java.util.List<ConnectionNotification> getConnectionNotificationSet() { if (connectionNotificationSet == null) { connectionNotificationSet = new com.amazonaws.internal.SdkInternalList<ConnectionNotification>(); } return connectionNotificationSet; }
java
public void forEach(BiConsumer<? super PropertyKey, ? super String> action) { for (Map.Entry<PropertyKey, String> entry : entrySet()) { action.accept(entry.getKey(), entry.getValue()); } }
java
public static <T> Vector<T> toVector( T... objects ) { return new Vector<T>( Arrays.asList( objects ) ); }
python
def Up(self, n = 1, dl = 0): """上方向键n次 """ self.Delay(dl) self.keyboard.tap_key(self.keyboard.up_key, n)
java
public void send(String destination, Object body) { AsyncMessage message = this.defaultMessageCreator.createMessage(); message.setDestination(destination); message.setBody(body); getMessageBroker().routeMessageToService(message, null); }
java
private Set<URL> filterAndBuildUserClasspath(Container container) { if (logger.isDebugEnabled()) { logger.debug("Building additional classpath for the container: " + container); } Set<URL> additionalClassPathUrls = new HashSet<URL>(); Set<Path> userClassPath = ...
python
def timed_rotating_file_handler(name, logname, filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False): """ A Bark logging handler logging output to a named file. At intervals specified by the 'when', the file wil...
python
def present( name, engine=None, cache_node_type=None, num_cache_nodes=None, preferred_availability_zone=None, port=None, cache_parameter_group_name=None, cache_security_group_names=None, replication_group_id=None, auto_minor_version_upgrade...
python
def _getOpenID1SessionType(self, assoc_response): """Given an association response message, extract the OpenID 1.X session type. This function mostly takes care of the 'no-encryption' default behavior in OpenID 1. If the association type is plain-text, this function will ...
java
public Observable<ServerDnsAliasInner> beginCreateOrUpdateAsync(String resourceGroupName, String serverName, String dnsAliasName) { return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, serverName, dnsAliasName).map(new Func1<ServiceResponse<ServerDnsAliasInner>, ServerDnsAliasInner>() { ...
python
def set_time(self, key_name, new_time): """Sets the time of key.""" self.unbake() kf = self.dct[key_name] kf['time'] = new_time self.bake()
java
public <T extends RegressionEvaluation> T evaluateRegression(DataSetIterator iterator, List<String> columnNames) { return (T)doEvaluation(iterator, new org.deeplearning4j.eval.RegressionEvaluation(columnNames))[0]; }
java
private Expr parseBitwiseAndExpression(EnclosingScope scope, boolean terminated) { int start = index; Expr lhs = parseConditionExpression(scope, terminated); if (tryAndMatch(terminated, Ampersand) != null) { Expr rhs = parseExpression(scope, terminated); return annotateSourceLocation(new Expr.BitwiseAnd(Ty...
java
public void setRevokedStart(Date revokedStart) throws InvalidArgumentException { if (revokedStart == null) { throw new InvalidArgumentException("Date can't be null"); } queryParms.put("revoked_start", Util.dateToString(revokedStart)); }
java
public com.google.api.ads.adwords.axis.v201809.cm.VanityPharmaText getVanityPharmaText() { return vanityPharmaText; }
python
def mle_parameter_estimate(self): """ get the maximum likelihood parameter estimate. Returns ------- post_expt : pandas.Series the maximum likelihood parameter estimates """ res = self.pst.res assert res is not None # build the prior...
python
def leaf_nodes(self): """ Return an interable of nodes with no edges pointing at them. This is helpful to find all nodes without dependencies. """ # Now contains all nodes that contain dependencies. deps = {item for sublist in self.edges.values() for item in sublist} ...
java
public ProgressStyle setIndeterminate(boolean value){ if(mProgressStyle == HORIZONTAL) { mProgress.setIndeterminate(value); mProgressText.setVisibility(value ? View.GONE : View.VISIBLE); mProgressMax.setVisibility(value ? View.GONE : View.VISIBLE); } return th...
python
def _get_alm_disp_fc3(disp_dataset): """Create displacements of atoms for ALM input Note ---- Dipslacements of all atoms in supercells for all displacement configurations in phono3py are returned, i.e., most of displacements are zero. Only the configurations with 'included' == True are incl...
java
public void add(ManagedObject managedObject, boolean requiresCurrentCheckpoint) throws ObjectManagerException { final String methodName = "add"; if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled()) trace.entry(this, ...
python
def cli(ctx, stage, port): """Web interface(experimental).""" if not ctx.bubble: ctx.say_yellow('There is no bubble present, will not listen') raise click.Abort() gbc = ctx.gbc WEB = None if stage in STAGES: STAGE = ctx.cfg.CFG[stage] if 'SERVER' in STAGE: ...
java
public int color(Context ctx, @AttrRes int colorStyle, @ColorRes int colorDefaultRes) { //get the color from the holder else from the theme int color = color(ctx); if (color == 0) { return UIUtils.getThemeColorFromAttrOrRes(ctx, colorStyle, colorDefaultRes); } else { ...
python
def _unzip(self, src, dst, scene, force_unzip=False): """ Unzip tar files """ self.output("Unzipping %s - It might take some time" % scene, normal=True, arrow=True) try: # check if file is already unzipped, skip if isdir(dst) and not force_unzip: self.out...
java
protected void initiateCommsHandshakingImpl(final boolean serverMode, final ConversationUsageType usageType) throws SIConnectionLostException, SIConnectionDroppedException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "initiateCommsHandshakingImpl", ...
java
static UUID getNextHash(UUID hash) { if (hash == null) { // No hash given. By definition, the first hash is the "next" one". hash = MIN_HASH; } else if (hash.compareTo(MAX_HASH) >= 0) { // Given hash already equals or exceeds the max value. There is no successor. ...
java
private void obtainDialogWindowBackground(@NonNull final TypedArray typedArray) { int resourceId = typedArray.getResourceId(R.styleable.DialogPreference_dialogWindowBackground, -1); if (resourceId != -1) { setDialogWindowBackground(resourceId); } }
python
def list_message_files (package, suffix=".mo"): """Return list of all found message files and their installation paths.""" for fname in glob.glob("po/*" + suffix): # basename (without extension) is a locale name localename = os.path.splitext(os.path.basename(fname))[0] domainname = "%s.m...
python
def remove_existing_container(engine_obj, service_name, remove_volumes=False): """ Remove a container for an existing service. Handy for removing an existing conductor. """ conductor_container_id = engine_obj.get_container_id_for_service(service_name) if engine_obj.service_is_running(service_name): ...
java
public static String[] segmentTags(String qualifiedSegmentName) { Preconditions.checkNotNull(qualifiedSegmentName); String[] tags = {TAG_SCOPE, null, TAG_STREAM, null, TAG_SEGMENT, null, TAG_EPOCH, null}; if (qualifiedSegmentName.contains(TABLE_SEGMENT_DELIMITER)) { String[] tokens =...
python
def _dfs_preorder(node, visited): """Iterate through nodes in DFS pre-order.""" if node not in visited: visited.add(node) yield node if node.lo is not None: yield from _dfs_preorder(node.lo, visited) if node.hi is not None: yield from _dfs_preorder(node.hi, visited)
java
public static Catalog read(final DataInput pDataInput) throws IOException { CatalogHeader header = CatalogHeader.read(pDataInput); CatalogItem[] items = new CatalogItem[header.getThumbnailCount()]; for (int i = 0; i < header.getThumbnailCount(); i++) { CatalogItem item = CatalogItem...
java
private static String[] appendToStringArray(String[] array, String element) { if (array != null) { String[] newArray = new String[array.length + 1]; System.arraycopy(array, 0, newArray, 0, array.length); newArray[array.length] = element; return newArray; }...
python
def evaluate(self, evaluation_context: EvaluationContext) -> Any: """ Evaluates the expression with the context provided. If the execution results in failure, an ExpressionEvaluationException encapsulating the underlying exception is raised. :param evaluation_context: Global and...
java
public EventSource createEventSource(boolean createAsyncEventSource, String cacheName) throws DynamicCacheServiceNotStarted { if (objectCacheUnit == null) { throw new DynamicCacheServiceNotStarted("Object cache service has not been started."); } return objectCacheUnit.createEventSource(createAsync...
java
@Traced public String call() { // tag::client-registration[] Client client = ClientTracingRegistrar.configure(ClientBuilder.newBuilder()).build(); // end::client-registration[] try { String response = client.target("http://localhost:8080") .path("/simp...
java
public static void divRow(Matrix A, int i, double c) { divRow(A, i, 0, A.cols(), c); }
java
public void deleteDevicePipe(String deviceName, String pipeName) throws DevFailed { databaseDAO.deleteDevicePipe(this, deviceName, pipeName); }
java
private Point intersection(int x1, int y1, int x2, int y2, int x3, int y3, int x4, int y4) { double dem = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); // Solve the intersect point double xi = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)) / dem; double yi = ((x1 * y2 - y1 * x2) *...
python
def make_and_start_process(self, index, num_items, progress_queue): """ Create and start a process to upload num_items chunks from our file starting at index. :param index: int offset into file(must be multiplied by upload_bytes_per_chunk to get actual location) :param num_items: int num...
java
@Override protected void preparePaintComponent(final Request request) { super.preparePaintComponent(request); List<AjaxTarget> targets = getTargets(); if (targets != null && !targets.isEmpty()) { WComponent triggerComponent = trigger == null ? this : trigger; // The trigger maybe in a different context ...
java
protected void doPut(String path) throws ClientException { this.readLock.lock(); try { ClientResponse response = this.getResourceWrapper() .rewritten(path, HttpMethod.PUT) .put(ClientResponse.class); errorIfStatusNotEqualTo(response, Client...
python
def dumpb(obj, container_count=False, sort_keys=False, no_float32=True, default=None): """Returns the given object as UBJSON in a bytes instance. See dump() for available arguments.""" with BytesIO() as fp: dump(obj, fp, container_count=container_count, sort_keys=sort_keys, no_float32=no_float32,...
java
public FileNode locatePathEntry(Class<?> c) { return locateEntry(c, Reflect.resourceName(c), true); }
python
def task_done(self): """Indicate that a formerly enqueued task is complete. Used by queue consumers. For each get() used to fetch a task, a subsequent call to task_done() tells the queue that the processing on the task is complete. If a join() is currently blocking, it will res...
python
def update_extent(self, extent): """Update extent value in GUI based from an extent. :param extent: A list in the form [xmin, ymin, xmax, ymax] where all coordinates provided are in Geographic / EPSG:4326. :type extent: list """ self.x_minimum.setValue(extent[0]) ...
java
public void setInboundPermissions(java.util.Collection<IpPermission> inboundPermissions) { if (inboundPermissions == null) { this.inboundPermissions = null; return; } this.inboundPermissions = new java.util.ArrayList<IpPermission>(inboundPermissions); }
java
public DomainModelResults analyzeImageByDomain(String model, String url, AnalyzeImageByDomainOptionalParameter analyzeImageByDomainOptionalParameter) { return analyzeImageByDomainWithServiceResponseAsync(model, url, analyzeImageByDomainOptionalParameter).toBlocking().single().body(); }
java
@Override protected Operand createEqualsExpression(final EqualsFilter filter, final boolean not) { if (filter == null) { return null; } final String name = filter.getAttribute().getName(); final String value = AttributeUtil.getAsStringValue(filter.getAttribute()); ...
java
private void normalizeFilePaths(Reportable report) { for (TestSuiteReport testSuiteReport : ((Report) report).getTestSuiteReports()) { for (PropertyEntry entry : testSuiteReport.getPropertyEntries()) { validatePath(entry); } for (TestClassReport testClassR...
java
public static void unpack(InputStream is, File outputDir) { unpack(is, outputDir, IdentityNameMapper.INSTANCE, null); }
python
def complete_hosts(self, text, line, begidx, endidx): "Tab-complete 'creds' commands." commands = ["add", "remove", "dc"] mline = line.partition(' ')[2] offs = len(mline) - len(text) return [s[offs:] for s in commands if s.startswith(mline)]
java
@Override public void installTheme(Theme theme) { this.removeCssLinks(); if (this.currentTheme != null) { for (CssLink link : this.currentTheme.getLinks()) { link.getLink().removeFromParent(); } } this.currentTheme = theme; this.resetTheme(); }
java
public void encrypt(File src, File dest) throws GeneralSecurityException, IOException { InputStream is = null; OutputStream os = null; try { is = new FileInputStream(src); os = encryptor.wrapOutputStream(new FileOutputStream(dest)); copy(is, os); } finally { if(is != null) { is.close(); } ...
java
public static List<Word> seg(String text, SegmentationAlgorithm segmentationAlgorithm){ List<Word> words = SegmentationFactory.getSegmentation(segmentationAlgorithm).seg(text); //停用词过滤 StopWord.filterStopWords(words); return words; }
python
def _delete_org(self, org_name): """Send organization delete request to DCNM. :param org_name: name of organization to be deleted """ url = self._del_org_url % (org_name) return self._send_request('DELETE', url, '', 'organization')
python
def triggers(self, triggers): """Sets the triggers of this Notificant. A list of occurrences on which this webhook will be fired. Valid values are ALERT_OPENED, ALERT_UPDATED, ALERT_RESOLVED, ALERT_MAINTENANCE, ALERT_SNOOZED # noqa: E501 :param triggers: The triggers of this Notificant. # n...
python
def _fullsize_link_tag(self, kwargs, title): """ Render a <a href> that points to the fullsize rendition specified """ return utils.make_tag('a', { 'href': self.get_fullsize(kwargs), 'data-lightbox': kwargs['gallery_id'], 'title': title })
java
public void processResponse(Object result) { if (result instanceof JSObject) { MaxZoomResult mzr = new MaxZoomResult((JSObject) result); callback.maxZoomReceived(mzr); } }
python
def key_list(items=None): ''' convert list to dictionary using the key as the identifier :param items: array to iterate over :return: dictionary ''' if items is None: items = [] ret = {} if items and isinstance(items, list): for item in items: if 'name' in it...
java
void compileToJar(ByteSink jarTarget, Optional<ByteSink> srcJarTarget) throws IOException { resetErrorReporter(); disallowExternalCalls(); ServerCompilationPrimitives primitives = compileForServerRendering(); BytecodeCompiler.compileToJar( primitives.registry, primitives.soyTree, errorReporter, ...
java
public static Object withOutputStream(Path self, @ClosureParams(value = SimpleType.class, options = "java.io.OutputStream") Closure closure) throws IOException { return IOGroovyMethods.withStream(newOutputStream(self), closure); }
python
def schema_dialog(schema, data=None, device_name=None, max_width=None, max_fps=None, **kwargs): ''' Parameters ---------- schema : dict jsonschema definition. Each property *must* have a default value. device_name : False or None or str or list_like, optional GStre...
java
public static void addPlural(String match, String rule, boolean insensitive){ plurals.add(0, new Replacer(match, rule, insensitive)); }
java
public final void mMULT_ASSIGN() throws RecognitionException { try { int _type = MULT_ASSIGN; int _channel = DEFAULT_TOKEN_CHANNEL; // src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:164:5: ( '*=' ) // src/main/resources/org/drools/compiler/lang/DRL5Lexer.g:164:7: '*=' { match("*="); if (sta...
java
private void deleteObject(final WebContext ctx, final Bucket bucket, final String id) { StoredObject object = bucket.getObject(id); object.delete(); ctx.respondWith().status(HttpResponseStatus.OK); signalObjectSuccess(ctx); }
python
def check_nodes_count(baremetal_client, stack, parameters, defaults): """Check if there are enough available nodes for creating/scaling stack""" count = 0 if stack: for param in defaults: try: current = int(stack.parameters[param]) except KeyError: ...
python
def add_elasticache_node(self, node, cluster, region): ''' Adds an ElastiCache node to the inventory and index, as long as it is addressable ''' # Only want available nodes unless all_elasticache_nodes is True if not self.all_elasticache_nodes and node['CacheNodeStatus'] != 'available':...
java
public static <V,T,R> Function1<V, R> compose(final Function1<? super T, ? extends R> after, final Function1<? super V, ? extends T> before) { if (after == null) throw new NullPointerException("after"); if (before == null) throw new NullPointerException("before"); return new Function1<V,R>() { @Override ...
java
void setDisplayNone(boolean displayNone) { if (displayNone) { getElement().getStyle().setDisplay(Display.NONE); } else { getElement().getStyle().clearDisplay(); } }
python
def tile_2d(input, k_x, k_y, name, reorder_required=True): """ A tiling layer like introduced in overfeat and huval papers. :param input: Your input tensor. :param k_x: The tiling factor in x direction. :param k_y: The tiling factor in y direction. :param name: The name of the layer. :param ...
java
public void swapRows(int r1, int r2) { int n = columns(); ItemSupplier s = supplier; ItemConsumer c = consumer; for (int j = 0; j < n; j++) { double v = s.get(r1, j); c.set(r1, j, s.get(r2, j)); c.set(r2, j, v); } }
java
@Fix(io.sarl.lang.validation.IssueCodes.DISCOURAGED_BOOLEAN_EXPRESSION) public void fixDiscouragedBooleanExpression(final Issue issue, IssueResolutionAcceptor acceptor) { BehaviorUnitGuardRemoveModification.accept(this, issue, acceptor); }
java
public DescribeSecurityGroupReferencesResult withSecurityGroupReferenceSet(SecurityGroupReference... securityGroupReferenceSet) { if (this.securityGroupReferenceSet == null) { setSecurityGroupReferenceSet(new com.amazonaws.internal.SdkInternalList<SecurityGroupReference>(securityGroupReferenceSet.le...
python
def ReadAtOffset(self, offset, size=None): """Reads a byte string from the gzip member at the specified offset. The function will read a byte string of the specified size or all of the remaining data if no size was specified. Args: offset (int): offset within the uncompressed data in this member...
java
public final TableSpec getTableSpec(TableSpecName name) { GetTableSpecRequest request = GetTableSpecRequest.newBuilder().setName(name == null ? null : name.toString()).build(); return getTableSpec(request); }
java
private void visitImplicitReturnExpression(NodeTraversal t, Node exprNode) { Node enclosingFunction = t.getEnclosingFunction(); JSType jsType = getJSType(enclosingFunction); if (jsType.isFunctionType()) { FunctionType functionType = jsType.toMaybeFunctionType(); JSType expectedReturnType = func...
python
def destroy(self): """ This method removes this share and all of its associated files. There is no way to recover a share or its contents once this method has been called. Input: * None Output: * ``True`` Example:: client.get_share(...
java
public static SocksProxyTransport connectViaSocks4Proxy(String remoteHost, int remotePort, String proxyHost, int proxyPort, String userId) throws IOException, UnknownHostException { SocksProxyTransport proxySocket = new SocksProxyTransport(remoteHost, remotePort, proxyHost, proxyPort, SOCKS4); proxySocket...
python
def get_responses(self, assessment_taken_id): """Gets the submitted responses. arg: assessment_taken_id (osid.id.Id): ``Id`` of the ``AssessmentTaken`` return: (osid.assessment.ResponseList) - the submitted answers raise: NotFound - ``assessment_taken_id`` is not fou...
java
public Variant merge(Variant current, Variant load) { return merge(current, Collections.singleton(load)); }
python
def loads(content, dict_=dict): """Parse a toml string An additional argument `dict_` is used to specify the output type """ if not isinstance(content, basestring): raise ValueError('The first parameter needs to be a string object, ', '%r is passed' % type(content)) ...
python
def onelineaddress(self, address, **kwargs): '''Geocode an an address passed as one string. e.g. "4600 Silver Hill Rd, Suitland, MD 20746" ''' fields = { 'address': address, } return self._fetch('onelineaddress', fields, **kwargs)
java
@Override public S transactional(boolean b) { attributes.attribute(TRANSACTIONAL).set(b); return self(); }
java
public MapSchema.MessageFactory getEnumMapFactory() { MapSchema.MessageFactory enumMapFactory = this.enumMapFactory; if (enumMapFactory == null) { synchronized (this) { if ((enumMapFactory = this.enumMapFactory) == null) thi...
java
public ServerConfig setContextPath(String contextPath) { if (!contextPath.endsWith(StringUtils.CONTEXT_SEP)) { contextPath += StringUtils.CONTEXT_SEP; } this.contextPath = contextPath; return this; }
python
def __copyfile2(source, destination): """Copy data and all stat info ("cp -p source destination"). The destination may be a directory. Args: source (str): Source file (file to copy). destination (str): Destination file or directory (where to copy). Returns: bool: True if the o...
python
def all(self, customer_id, data={}, **kwargs): """" Get all tokens for given customer Id Args: customer_id : Customer Id for which tokens have to be fetched Returns: Token dicts for given cutomer Id """ url = "{}/{}/tokens".format(self.base_url, ...
java
public void printIt(Record recLayout, PrintWriter out, int iIndents, String strEnd) { // Print out the current record String strName = recLayout.getField(Layout.NAME).toString(); String strType = recLayout.getField(Layout.TYPE).toString(); String strValue = recLayout.getField(Layout....
java
public static <T> T createProxy(T target, Class<? extends Aspect> aspectClass){ return createProxy(target, ReflectUtil.newInstance(aspectClass)); }
python
def _compute_term_1(self, C, mag): """ Compute term 1 a1 + a2.*M + a3.*M.^2 + a4.*M.^3 + a5.*M.^4 + a6.*M.^5 + a7.*M.^6 """ return ( C['a1'] + C['a2'] * mag + C['a3'] * np.power(mag, 2) + C['a4'] * np.power(mag, 3) + C['a5'] * np.power(mag, 4) ...
java
public boolean isInState(JComponent c) { Component parent = c; while (parent.getParent() != null) { if (parent instanceof JFrame) { break; } parent = parent.getParent(); } if (parent instanceof JFrame) { return ((JFrame)...
python
def poll_for_response(self): """ Polls the device for user input If there is a keymapping for the device, the key map is applied to the key reported from the device. If a response is waiting to be processed, the response is appended to the internal response_queue ...
java
static public String fromLevel(int level, int length) { StringBuffer sb = new StringBuffer(length > 7 ? length : 7); switch (level) { case LogService.LOG_INFO: sb.append("info"); break; case LogService.LOG_DEBUG: sb.append("debug"); break; ...