language
stringclasses
2 values
func_code_string
stringlengths
63
466k
java
public static AddressInfo of(String region, String name) { return of(RegionAddressId.of(region, name)); }
python
def get_calling_module_object_and_name(): """Returns the module that's calling into this module. We generally use this function to get the name of the module calling a DEFINE_foo... function. Returns: The module object that called into this one. Raises: AssertionError: Raised when no calling module...
python
def decode_data_with_length(reader) -> bytes: """ Read data from a reader. Data is prefixed with 2 bytes length :param reader: Stream reader :return: bytes read from stream (without length) """ length_bytes = yield from read_or_raise(reader, 2) bytes_length = unpack("!H", length_bytes) d...
java
@Indexable(type = IndexableType.DELETE) @Override public CommerceWishList deleteCommerceWishList(long commerceWishListId) throws PortalException { return commerceWishListPersistence.remove(commerceWishListId); }
python
def selectrangeopenleft(table, field, minv, maxv, complement=False): """Select rows where the given field is greater than or equal to `minv` and less than `maxv`.""" minv = Comparable(minv) maxv = Comparable(maxv) return select(table, field, lambda v: minv <= v < maxv, complement=...
python
def create(self, graph): """ Create a new scoped component. """ scoped_config = self.get_scoped_config(graph) scoped_graph = ScopedGraph(graph, scoped_config) return self.func(scoped_graph)
java
public SegmentedSuggestion wordSegmentation(String input, int maxEditDistance, int maxSegmentationWordLength) { if (input.isEmpty()) { return new SegmentedSuggestion(); } int arraySize = Math.min(maxSegmentationWordLength, input.length()); SegmentedSuggestion[] compositions = new SegmentedSuggesti...
java
public void incrementDependencySufficientStatistics(SufficientStatistics gradient, SufficientStatistics parameters, List<String> posTags, Collection<DependencyStructure> dependencies, double count) { int[] puncCounts = CcgParser.computeDistanceCounts(posTags, puncTagSet); int[] verbCounts = CcgPars...
python
def _get_default_radius(site): """ An internal method to get a "default" covalent/element radius Args: site: (Site) Returns: Covalent radius of element on site, or Atomic radius if unavailable """ try: return CovalentRadius.radius[sit...
python
def replace_acquaintance_with_swap_network( circuit: circuits.Circuit, qubit_order: Sequence[ops.Qid], acquaintance_size: Optional[int] = 0, swap_gate: ops.Gate = ops.SWAP ) -> bool: """ Replace every moment containing acquaintance gates (after rectification) with a g...
python
def show(self): """ Simulates switching the display mode ON; this is achieved by restoring the contrast to the level prior to the last time hide() was called. """ if self._prev_contrast is not None: self.contrast(self._prev_contrast) self._prev_contrast = ...
python
def get_hosts(sld, tld): ''' Retrieves DNS host record settings for the requested domain. returns a dictionary of information about the requested domain sld SLD of the domain name tld TLD of the domain name CLI Example: .. code-block:: bash salt 'my-minion' name...
java
public static DateType parseV3(String theV3String) { DateType retVal = new DateType(); retVal.setValueAsV3String(theV3String); return retVal; }
java
public static SanitizedContent fromSafeScriptProto(SafeScriptProto script) { return SanitizedContent.create( SafeScripts.fromProto(script).getSafeScriptString(), ContentKind.JS); }
python
def create_public_room(self, name, **kwargs): """ Create room with given name :param name: Room name :param kwargs: members: The users to add to the channel when it is created. Optional; Ex.: ["rocket.cat"], Default: [] read_only: Set if the channel is read on...
java
public void complete(Session session) { try { session.complete(); sessionCache.put(session.getId(), session); } catch (Exception e) { log.warn("Session failed to complete", e); } }
python
def main(): 'Main function. Handles delegation to other functions.' logging.basicConfig() type_choices = {'any': constants.PACKAGE_ANY, 'extension': constants.PACKAGE_EXTENSION, 'theme': constants.PACKAGE_THEME, 'dictionary': constants.PACKAGE_DI...
java
@BetaApi public final Operation insertRegionCommitment(String region, Commitment commitmentResource) { InsertRegionCommitmentHttpRequest request = InsertRegionCommitmentHttpRequest.newBuilder() .setRegion(region) .setCommitmentResource(commitmentResource) .build(); ...
python
def _verify_shape_bounds(shape, bounds): """Verify that shape corresponds to bounds apect ratio.""" if not isinstance(shape, (tuple, list)) or len(shape) != 2: raise TypeError( "shape must be a tuple or list with two elements: %s" % str(shape) ) if not isinstance(bounds, (tuple, ...
java
private void obtainWindowBackground(@StyleRes final int themeResourceId) { TypedArray typedArray = getContext().getTheme().obtainStyledAttributes(themeResourceId, new int[]{R.attr.materialDialogWindowBackground}); int resourceId = typedArray.getResourceId(0, 0); if (resourceId !...
python
def main(vocab_path: str, elmo_config_path: str, elmo_weights_path: str, output_dir: str, batch_size: int, device: int, use_custom_oov_token: bool = False): """ Creates ELMo word representations from a vocabulary file. These word representations are _ind...
java
public void marshall(IpRouteInfo ipRouteInfo, ProtocolMarshaller protocolMarshaller) { if (ipRouteInfo == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(ipRouteInfo.getDirectoryId(), DIRECTORYID_BIND...
java
public Principal getCallerPrincipal(boolean useRealm, String realm, boolean web, boolean isJaspiEnabled) { Subject subject = subjectManager.getCallerSubject(); if (subject == null) { return null; } SubjectHelper subjectHelper = new SubjectHelper(); if (subjectHelper....
python
def run(self, postfunc=lambda: None): """Run the jobs. postfunc() will be invoked after the jobs has run. It will be invoked even if the jobs are interrupted by a keyboard interrupt (well, in fact by a signal such as either SIGINT, SIGTERM or SIGHUP). The execution of postfunc()...
python
def fetch_build_eggs(self, requires): """Resolve pre-setup requirements""" resolved_dists = pkg_resources.working_set.resolve( pkg_resources.parse_requirements(requires), installer=self.fetch_build_egg, replace_conflicting=True, ) for dist in resolved_...
java
public DeletePresetResponse deletePreset(DeletePresetRequest request) { checkNotNull(request, "The parameter request should NOT be null."); checkStringNotEmpty(request.getName(), "The parameter name should NOT be null or empty string."); InternalRequest internalRequest = createRequest(HttpMethod...
python
def get_peer(self, name, peer_type="REPLICATION"): """ Retrieve a replication peer by name. @param name: The name of the peer. @param peer_type: Added in v11. The type of the peer. Defaults to 'REPLICATION'. @return: The peer. @since: API v3 """ params = self._get_peer_type_param(peer_t...
python
def _run_default_moderator(comment, content_object, request): """ Run the default moderator """ # The default moderator will likely not check things like "auto close". # It can still provide akismet and bad word checking. if not default_moderator.allow(comment, content_object, request): ...
java
private void initializeExtension(InstalledExtension installedExtension, String namespaceToLoad, Map<String, Set<InstalledExtension>> initializedExtensions) throws ExtensionException { if (installedExtension.getNamespaces() != null) { if (namespaceToLoad == null) { for (St...
python
def remove_nio(self, nio): """ Removes the specified NIO as member of this bridge. :param nio: NIO instance to remove """ if self._hypervisor: yield from self._hypervisor.send('nio_bridge remove_nio "{name}" {nio}'.format(name=self._name, nio=nio)) self._nios...
python
def calculate_hmac(cls, params): """ Calculate the HMAC of the given parameters in line with Shopify's rules for OAuth authentication. See http://docs.shopify.com/api/authentication/oauth#verification. """ encoded_params = cls.__encoded_params_for_signature(params) # Gene...
java
private boolean isGZip(byte[] bytes) { if(bytes == null || bytes.length == 0) { return false; } // refer http://www.gzip.org/zlib/rfc-gzip.html#file-format for magic numbers if(bytes[0] == 31 && (bytes[1] == 0x8b || bytes[1] == -117)) { return true; } ...
java
private CloseableDataStore asCloseableDataStore(final DataStore dataStore, final Optional<Runnable> onClose) { return (CloseableDataStore) Proxy.newProxyInstance( DataStore.class.getClassLoader(), new Class[] { CloseableDataStore.class }, new AbstractInvocationHandler() { ...
python
def _indent_decor(lbl): """ does the actual work of indent_func """ def closure_indent(func): if util_arg.TRACE: @ignores_exc_tb(outer_wrapper=False) #@wraps(func) def wrp_indent(*args, **kwargs): with util_print.Indenter(lbl): ...
python
def deploy_war(war, context, force='no', url='http://localhost:8080/manager', saltenv='base', timeout=180, temp_war_location=None, version=True): ''' Deploy a WAR file war absolute path to WAR f...
python
def key_string_to_lens_path(key_string): """ Converts a key string like 'foo.bar.0.wopper' to ['foo', 'bar', 0, 'wopper'] :param {String} keyString The dot-separated key string :return {[String]} The lens array containing string or integers """ return map( if_else( isinstance(int)...
java
public void runPostCrawlingPlugins(CrawlSession session, ExitStatus exitReason) { LOGGER.debug("Running PostCrawlingPlugins..."); counters.get(PostCrawlingPlugin.class).inc(); for (Plugin plugin : plugins.get(PostCrawlingPlugin.class)) { if (plugin instanceof PostCrawlingPlugin) { try { LOGGER.debug("...
python
def load_training_vector(response_shapes, explanatory_rasters, response_field, metric='mean'): """ Parameters ---------- response_shapes : Source of vector features for raster_stats; can be OGR file path or iterable of geojson-like features response_field : Field name containin...
python
def service_info(self, short_name): """Get static information about a service. Args: short_name (string): The short name of the service to query Returns: dict: A dictionary with the long_name and preregistered info on this service. """ i...
python
def add_intercept_term(self, x): """ Adds a column of ones to estimate the intercept term for separation boundary """ nr_x,nr_f = x.shape intercept = np.ones([nr_x,1]) x = np.hstack((intercept,x)) return x
python
def __stop(self): # pragma: no cover """Stops the background engine.""" if not self.dispatcher_thread: return logger.info('Stopping dispatcher') self.running = False # graceful shutdown self.dispatcher_thread.join() self.dispatcher_thread = None
java
public void addInjectionTarget(Member member) throws InjectionException { final boolean isTraceOn = TraceComponent.isAnyTracingEnabled(); if (isTraceOn && tc.isEntryEnabled()) Tr.entry(tc, "addInjectionTarget: " + member); // ---------------------------------...
java
@Override public CallSequence get(int index) { if (indics == null) { size(); } Pair<Integer, Integer> v = indics.get(index); int r = v.getFirst(); if (r == 0) { CallSequence seq = getVars(); CallStatement skip = new CallStatement() { public Object execute() { return Utils.VOID...
python
def add_icon_widget(self, ref, x=1, y=1, name="heart"): """ Add Icon Widget """ if ref not in self.widgets: widget = IconWidget(screen=self, ref=ref, x=x, y=y, name=name) self.widgets[ref] = widget return self.widgets[ref]
python
def scores(factors): """ Computes the score of temperaments and elements. """ temperaments = { const.CHOLERIC: 0, const.MELANCHOLIC: 0, const.SANGUINE: 0, const.PHLEGMATIC: 0 } qualities = { const.HOT: 0, const.COLD: 0, ...
python
def pprint_tree_differences(self, missing_pys, missing_docs): """Pprint the missing files of each given set. :param set missing_pys: The set of missing Python files. :param set missing_docs: The set of missing documentation files. :rtype: None """ if missing_pys: ...
python
def get_calculated_aes(aesthetics): """ Return a list of the aesthetics that are calculated """ calculated_aesthetics = [] for name, value in aesthetics.items(): if is_calculated_aes(value): calculated_aesthetics.append(name) return calculated_aesthetics
python
def complexity_entropy_multiscale(signal, max_scale_factor=20, m=2, r="default"): """ Computes the Multiscale Entropy. Uses sample entropy with 'chebychev' distance. Parameters ---------- signal : list or array List or array of values. max_scale_factor: int Max scale factor (*ta...
java
public BoardingPassBuilder addBoardingPass(String passengerName, String pnrNumber, String logoImageUrl, String aboveBarCodeImageUrl) { return new BoardingPassBuilder(this, passengerName, pnrNumber, logoImageUrl, aboveBarCodeImageUrl); }
python
def data_filler_simple_registration(self, number_of_rows, conn): '''creates and fills the table with simple regis. information ''' cursor = conn.cursor() cursor.execute(''' CREATE TABLE simple_registration(id TEXT PRIMARY KEY, email TEXT , password TEXT) ''') ...
python
def populateFromFile(self, dataUrl, indexFile=None): """ Populates the instance variables of this ReadGroupSet from the specified dataUrl and indexFile. If indexFile is not specified guess usual form. """ self._dataUrl = dataUrl self._indexFile = indexFile ...
python
def register(self, key_or_tag, f_val): """Register a custom transit tag and decoder/parser function for use during reads. """ self.reader.decoder.register(key_or_tag, f_val)
java
public java.util.List<VpcEndpointConnection> getVpcEndpointConnections() { if (vpcEndpointConnections == null) { vpcEndpointConnections = new com.amazonaws.internal.SdkInternalList<VpcEndpointConnection>(); } return vpcEndpointConnections; }
java
public List<String> selectJars(String targetPath) { List<String> jarPaths = new ArrayList<String>(); if (targetPath == null) { return jarPaths; } File targetDir = new File(targetPath); if (!UtilImpl_FileUtils.exists(targetDir)) { return jarPaths; ...
python
def clicked(self, px, py): '''see if the image has been clicked on''' if self.hidden: return None if (abs(px - self.posx) > self.width/2 or abs(py - self.posy) > self.height/2): return None return math.sqrt((px-self.posx)**2 + (py-self.posy)**2)
java
public boolean renameFile(@NotNull final Transaction txn, @NotNull final File origin, @NotNull final String newPath) { final ArrayByteIterable key = StringBinding.stringToEntry(newPath); final ByteIterable value = pathnames.get(txn, key); if (value != null) { return false; } ...
python
def split_field_path(path): """Split a field path into valid elements (without dots). Args: path (str): field path to be lexed. Returns: List(str): tokens Raises: ValueError: if the path does not match the elements-interspersed- with-dots pattern. """ ...
python
def _hash_html_blocks(self, text, raw=False): """Hashify HTML blocks We only want to do this for block-level HTML tags, such as headers, lists, and tables. That's because we still want to wrap <p>s around "paragraphs" that are wrapped in non-block-level tags, such as anchors, ph...
java
public CloseableResource<FileSystemMasterClient> acquireMasterClientResource() { return new CloseableResource<FileSystemMasterClient>(mFileSystemMasterClientPool.acquire()) { @Override public void close() { mFileSystemMasterClientPool.release(get()); } }; }
python
def get_all_handleable_roots(self): """ Get list of all handleable devices, return only those that represent root nodes within the filtered device tree. """ nodes = self.get_device_tree() return [node.device for node in sorted(nodes.values(), key=DevNode._...
python
def triplify(binding): """ Recursively generate RDF statement triples from the data and schema supplied to the application. """ triples = [] if binding.data is None: return None, triples if binding.is_object: return triplify_object(binding) elif binding.is_array: for ite...
java
@Override public void connectToResourceManager(@Nonnull ResourceManagerGateway resourceManagerGateway) { this.resourceManagerGateway = checkNotNull(resourceManagerGateway); // work on all slots waiting for this connection for (PendingRequest pendingRequest : waitingForResourceManager.values()) { requestSlotF...
java
public GroovyExpression generateArithmeticExpression(GroovyExpression left, String operator, GroovyExpression right) throws AtlasException { ArithmeticOperator op = ArithmeticOperator.lookup(operator); return new ArithmeticExpression(left, op, right); }
python
def save_params( self, f=None, f_params=None, f_optimizer=None, f_history=None): """Saves the module's parameters, history, and optimizer, not the whole object. To save the whole object, use pickle. ``f_params`` and ``f_optimizer`` uses PyTorchs' :func:`~torch.save`...
java
@Override public SendTaskFailureResult sendTaskFailure(SendTaskFailureRequest request) { request = beforeClientExecution(request); return executeSendTaskFailure(request); }
java
@NonNull /*package*/ <T extends View> Parcelable saveInstanceState(@NonNull T target, @Nullable Parcelable state) { Injector.View<T> injector = safeGet(target, Injector.View.DEFAULT); return injector.save(target, state); }
java
public static String getIsolationLevelString(int level) { switch (level) { case Connection.TRANSACTION_NONE: return "NONE (" + level + ')'; case Connection.TRANSACTION_READ_UNCOMMITTED: return "READ UNCOMMITTED (" + level + ')'; case Connec...
python
def make_encoder(self,formula_dict,inter_list,param_dict): """ make the encoder function """ X_dict = {} Xcol_dict = {} encoder_dict = {} # first, replace param_dict[key] = values, with param_dict[key] = dmatrix for key in formula_dict: encodin...
java
public static int cudaMemcpyArrayToArray(cudaArray dst, long wOffsetDst, long hOffsetDst, cudaArray src, long wOffsetSrc, long hOffsetSrc, long count, int cudaMemcpyKind_kind) { return checkResult(cudaMemcpyArrayToArrayNative(dst, wOffsetDst, hOffsetDst, src, wOffsetSrc, hOffsetSrc, count, cudaMemcpyKind_...
java
public static DateTimeField getInstance(DateTimeField field) { if (field == null) { return null; } if (field instanceof LenientDateTimeField) { field = ((LenientDateTimeField)field).getWrappedField(); } if (!field.isLenient()) { return field; ...
java
public static <T extends Enum<?>> T enumFromString(final String value, final T[] values) { if (value == null) { return null; } for (T v : values) { if (v.toString().equalsIgnoreCase(value)) { return v; } } return null; }
java
private List<TimeStep<State, Observation, Path>> createTimeSteps( List<Observation> filteredGPXEntries, List<Collection<QueryResult>> queriesPerEntry, QueryGraph queryGraph) { final int n = filteredGPXEntries.size(); if (queriesPerEntry.size() != n) { throw new Illega...
python
def preflight(self, program, start, stop, resolution=None, max_delay=None): """Preflight the given SignalFlow program and stream the output back.""" params = self._get_params(start=start, stop=stop, resolution=resolution, ...
python
def Parse(self, conditions, host_data): """Runs methods that evaluate whether collected host_data has an issue. Args: conditions: A list of conditions to determine which Methods to trigger. host_data: A map of artifacts and rdf data. Returns: A CheckResult populated with Anomalies if an ...
java
public OvhSecondaryDNS serviceName_secondaryDnsDomains_domain_GET(String serviceName, String domain) throws IOException { String qPath = "/vps/{serviceName}/secondaryDnsDomains/{domain}"; StringBuilder sb = path(qPath, serviceName, domain); String resp = exec(qPath, "GET", sb.toString(), null); return convertTo...
java
@CheckReturnValue @BackpressureSupport(BackpressureKind.FULL) @SchedulerSupport(SchedulerSupport.NONE) public final <U, V> Flowable<V> flatMapIterable(final Function<? super T, ? extends Iterable<? extends U>> mapper, final BiFunction<? super T, ? super U, ? extends V> resultSelector) { ...
python
def iter_sources(self): """Iterates over all source names and IDs.""" for src_id in xrange(self.get_source_count()): yield src_id, self.get_source_name(src_id)
python
def _search_in_bases(type_): """Implementation detail.""" found = False for base_type in type_.declaration.bases: try: found = internal_type_traits.get_by_name( base_type.related_class, "element_type") except runtime_errors.declaration_not_found_t: pas...
python
def read_file(path): """ Read file to string. Arguments: path (str): Source. """ with open(must_exist(path)) as infile: r = infile.read() return r
java
private Pair<List<CloseableIterator<Entry<KeyType>>>, List<Future>> buildCombineTree( List<? extends CloseableIterator<Entry<KeyType>>> childIterators, Supplier<ByteBuffer> bufferSupplier, AggregatorFactory[] combiningFactories, int combineDegree, List<String> dictionary ) { final ...
java
@Override public <OUTPUT extends GVRHybridObject, INTER> void registerCallback( GVRContext gvrContext, Class<OUTPUT> outClass, CancelableCallback<OUTPUT> callback, GVRAndroidResource request, int priority) { requests.registerCallback(gvrContext, outClass, callback, reques...
python
def getLoader(user, repo, sha=None, prov=None): """Build a fileLoader (LocalLoader or GithubLoader) for the given repository.""" if user is None and repo is None: loader = LocalLoader() else: loader = GithubLoader(user, repo, sha, prov) return loader
python
def determine_name(func): """ Given a function, returns the name of the function. Ex:: from random import choice determine_name(choice) # Returns 'choice' :param func: The callable :type func: function :returns: Name string """ if hasattr(func, '__name__'): re...
python
def build_tree_file_pathname(filename, directory_depth=8, pathname_separator_character=os.sep): """ Return a file pathname which pathname is built of the specified number of sub-directories, and where each directory is named after the nth letter of the filename corresponding to the directory depth. ...
python
def new_program(self, _id, series, title, subtitle, description, mpaaRating, starRating, runTime, year, showType, colorCode, originalAirDate, syndicatedEpisodeNumber, advisories): """Callback run for each new program entry""" raise NotImplementedError()
java
public static MappedByteBuffer map(File file) { N.checkArgNotNull(file); return map(file, MapMode.READ_ONLY); }
java
public void setEscapeHtml(String value) { if (value != null) { m_escapeHtml = Boolean.valueOf(value.trim()).booleanValue(); } }
python
def _meet(intervals_hier, labels_hier, frame_size): '''Compute the (sparse) least-common-ancestor (LCA) matrix for a hierarchical segmentation. For any pair of frames ``(s, t)``, the LCA is the deepest level in the hierarchy such that ``(s, t)`` are contained within a single segment at that level. ...
java
protected boolean isSuppressed() { if (_suppressed == null) { // we haven't called this method before, so determine the suppressed // value and cache it for later calls to this method. if (isFacet()) { // facets are always rendered by ...
java
public static Duration fromMillis(long millis) { long seconds = millis / MILLIS_PER_SECOND; int nanos = (int) (millis % MILLIS_PER_SECOND * NANOS_PER_MILLI); return Duration.create(seconds, nanos); }
java
public void setName(String name) { put(PdfName.NAME, new PdfString(name, PdfObject.TEXT_UNICODE)); }
python
def add_epoch(self, epoch_name, start_frame, end_frame): '''This function adds an epoch to your recording extractor that tracks a certain time period in your recording. It is stored in an internal dictionary of start and end frame tuples. Parameters ---------- epoch_name...
python
def gen_sponsor_schedule(user, sponsor=None, num_blocks=6, surrounding_blocks=None, given_date=None): r"""Return a list of :class:`EighthScheduledActivity`\s in which the given user is sponsoring. Returns: Dictionary with: activities no_attendance_today num_acts ...
java
public static boolean isUuid(final String uuid) { return uuid != null && (uuid.length() == 36 || uuid.length() == 32) && UUID_PATTERN.matcher(uuid).matches(); }
java
private void addTypesToFunctions( Node objLit, String thisType, PolymerClassDefinition.DefinitionType defType) { checkState(objLit.isObjectLit()); for (Node keyNode : objLit.children()) { Node value = keyNode.getLastChild(); if (value != null && value.isFunction()) { JSDocInfoBuilder f...
python
def do_edit(self, args): """Edit a command with $EDITOR.""" if 'EDITOR' not in os.environ: print('*** $EDITOR not set') else: path = os.path.join(utils.CONFIG_DIR, 'sql') cmd = os.environ['EDITOR'] try: os.system(cmd + ' ' + path) ...
python
def p_changepassword(self): ''' Changing password. ''' post_data = self.get_post_data() usercheck = MUser.check_user(self.userinfo.uid, post_data['rawpass']) if usercheck == 1: MUser.update_pass(self.userinfo.uid, post_data['user_pass']) output =...
java
public static Expression fields(String operator, Val<Expression>[] args, QueryExprMeta parent) { if (args.length < 1) { throw new QuerySyntaxException(Messages.get("dsl.arguments.error2", operator, 0)); } if (parent == null) { throw new QuerySyntaxException(Messages.get("...
java
public void setBrokerInstances(java.util.Collection<BrokerInstance> brokerInstances) { if (brokerInstances == null) { this.brokerInstances = null; return; } this.brokerInstances = new java.util.ArrayList<BrokerInstance>(brokerInstances); }
java
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public static ViewTreeObserver.OnGlobalLayoutListener attach(final Activity activity, IPanelHeightTarget target, /* Nullable */ ...