text
stringlengths
78
104k
score
float64
0
0.18
async def jsk_in(self, ctx: commands.Context, channel: discord.TextChannel, *, command_string: str): """ Run a command as if it were in a different channel. """ alt_ctx = await copy_context_with(ctx, channel=channel, content=ctx.prefix + command_string) if alt_ctx.command is No...
0.010846
def save_state(self, fname: str): """ Saves the current state of iterator to a file, so that iteration can be continued. Note that the data is not saved, i.e. the iterator must be initialized with the same parameters as in the first call. :param fname: File name to save the info...
0.003175
def list_address_scopes(self, retrieve_all=True, **_params): """Fetches a list of all address scopes for a project.""" return self.list('address_scopes', self.address_scopes_path, retrieve_all, **_params)
0.008163
def iter_feasible_configurations(cur): """Iterate over all of the sets of feasible configurations in the cache. Args: cur (:class:`sqlite3.Cursor`): An sqlite3 cursor. This function is meant to be run within a :obj:`with` statement. Yields: dict[tuple(int): number]: The feasibl...
0.002551
def ncoef_fmap(order): """Expected number of coefficients in a 2D transformation of a given order. Parameters ---------- order : int Order of the 2D polynomial transformation. Returns ------- ncoef : int Expected number of coefficients. """ ncoef = 0 for i in ...
0.002451
def run_via_binary_in_foreground( self, run_command_instance=None, command=None, volumes=None, additional_opts=None, popen_params=None, container_name=None): """ Create a container using this image and run it in foreground; this method is useful to test real user scenario...
0.004081
def list_namespaced_role_binding(self, namespace, **kwargs): """ list or watch objects of kind RoleBinding This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_role_binding(names...
0.002762
def get_as_csv(self, output_file_path: Optional[str] = None) -> str: """ Returns the table object as a CSV string. :param output_file_path: The output file to save the CSV to, or None. :return: CSV representation of the table. """ output = StringIO() if not output_file_p...
0.004695
def _unwrap(x, deserializeFunc, decodeFunc=base64.urlsafe_b64decode, compress=True): """ Unwraps an element @x by decoding and then deserializing """ return deserializeFunc(decodeFunc(x), compress)
0.00939
def slicewise(self, fn, *inputs): """Execute a function in parallel on all slices. Args: fn: a function from tf.Tensors to tf.Tensor or a tuple of tf.Tensors. *inputs: a list of inputs. Each input is either a LaidOutTensor or is convertible to a tf.Tensor. Returns: a LaidOutTenso...
0.005274
def _cc_round(num, dp): """ Convenience function to take a float and round it to dp padding with zeros to return a string :type num: float :param num: Number to round :type dp: int :param dp: Number of decimal places to round to. :returns: str >>> print(_cc_round(0.25364, 2)) ...
0.002439
def open(self): """ Setup serial port and set is as escpos device """ if self.device is not None and self.device.is_open: self.close() self.device = serial.Serial(port=self.devfile, baudrate=self.baudrate, bytesize=self.bytesize, parity=self.parity...
0.006051
def surface(self, canvas, X, Y, Z, color=None, label=None, **kwargs): """ Plot a surface for 3d plotting for the inputs (X, Y, Z). the kwargs are plotting library specific kwargs! """ raise NotImplementedError("Implement all plot functions in AbstractPlottingLibrary in o...
0.011142
def set_color(index, color): """Convert a hex color to a text color sequence.""" if OS == "Darwin" and index < 20: return "\033]P%1x%s\033\\" % (index, color.strip("#")) return "\033]4;%s;%s\033\\" % (index, color)
0.004255
def bin2hexline(data, add_addr=True, width=16): """ Format binary data to a Hex-Editor like format... e.g.: with open("C:\Python27\python.exe", "rb") as f: data = f.read(150) print("\n".join(bin2hexline(data, width=16))) 0000 4d 5a 90 00 03 00 00 00 04 00 00 00 ff ff 00 00 MZ............
0.001622
def is_request_complete_for_rid(request, rid): """Check if a given request has been completed on the given relation @param request: A CephBrokerRq object @param rid: Relation ID """ broker_key = get_broker_rsp_key() for unit in related_units(rid): rdata = relation_get(rid=rid, unit=unit...
0.001432
def edge_by_target(self): """Returns a reference to the dict of target node id to (edge_id, edge)""" if self._edge_by_target is None: self._edge_by_target = reverse_edge_by_source_dict(self._edge_by_source_id, self._nexson_tree['...
0.013405
def stop(self): """ stop daemon """ try: with self.pidfile: self.log.error("failed to stop, missing pid file or not running") except pidfile.PidFileError: # this isn't exposed in pidfile :o with open(self.pidfile.filename) as fobj: ...
0.005618
def get_rendition_fill_size(spec, input_w, input_h, output_scale): """ Determine the scale-crop size given the provided spec """ width = input_w height = input_h scale = spec.get('scale') if scale: width = width / scale height = height / scale i...
0.001839
def ls(obj=None): """List available layers, or infos on a given layer""" if obj is None: import builtins all = builtins.__dict__.copy() all.update(globals()) objlst = sorted(conf.layers, key=lambda x:x.__name__) for o in objlst: print("%-10s : %s" %(...
0.010256
def load_terrohunt(self): """|coro| Loads the player's general stats for terrorist hunt""" stats = yield from self._fetch_statistics("generalpve_dbnoassists", "generalpve_death", "generalpve_revive", "generalpve_matchwon", "generalpve_suicide", ...
0.007179
def from_database(cls, database): """Initialize migrator by db.""" if isinstance(database, PostgresqlDatabase): return PostgresqlMigrator(database) if isinstance(database, SqliteDatabase): return SqliteMigrator(database) if isinstance(database, MySQLDatabase): ...
0.004706
def _visit_functiondef(self, cls, node, parent): """visit an FunctionDef node to become astroid""" self._global_names.append({}) node, doc = self._get_doc(node) newnode = cls(node.name, doc, node.lineno, node.col_offset, parent) if node.decorator_list: decorators = se...
0.001738
def maybe_create_placement_group(name='', max_retries=10): """Creates placement_group group or reuses existing one. Crash if unable to create placement_group group. If name is empty, ignores request.""" if not name: return client = get_ec2_client() while True: try: client.describe_placement_...
0.015625
def imap(requests, stream=False, size=2, exception_handler=None): """Concurrently converts a generator object of Requests to a generator of Responses. :param requests: a generator of Request objects. :param stream: If True, the content will not be downloaded immediately. :param size: Specifies the ...
0.00339
def _delta_filter_command(self, infile, outfile): '''Construct delta-filter command''' command = 'delta-filter' if self.min_id is not None: command += ' -i ' + str(self.min_id) if self.min_length is not None: command += ' -l ' + str(self.min_length) ret...
0.005495
def getBothEdges(self, label=None): """Gets all the edges of the node. If label parameter is provided, it only returns the edges of the given label @params label: Optional parameter to filter the edges @returns A generator function with the incoming edges""" if label: ...
0.003759
def foldr(f, seq, default=_no_default): """Fold a function over a sequence with right associativity. Parameters ---------- f : callable[any, any] The function to reduce the sequence with. The first argument will be the element of the sequence; the second argument will be the acc...
0.000593
def on_message(self, handler, msg): """ In remote debugging mode this simply acts as a forwarding proxy for the two clients. """ if self.remote_debugging: #: Forward to other clients for h in self.handlers: if h != handler: h.wr...
0.005277
def downcase_hook(self, data: cmd2.plugin.PostparsingData) -> cmd2.plugin.PostparsingData: """A hook to make uppercase commands lowercase.""" command = data.statement.command.lower() data.statement = self.statement_parser.parse("{} {}".format( command, '' if data.statemen...
0.007692
def _cache_eta(self): """ Prints the estimated time left.""" self._calc_eta() self._cached_output += ' | ETA: ' + self._get_time(self.eta)
0.012346
def get_value(self, expression): """Return value of expression.""" self._check_valid() return super(Result, self).get_value(expression)
0.012579
def printf(*s) : 'print + sys.stdout.flush()' for e in s[:-1] : print e, print s[-1] sys.stdout.flush()
0.072727
def generate_catalog(xsd_schemas=None, xmlcatalog_dir=None, xmlcatalog_file=None): """Generating an XML catalog for use in resolving schemas Creates the XML Catalog directory if it doesn't already exist. Uses :meth:`download_schema` to save local copies of schemas, adding a comment indicating the date ...
0.000919
def replace(self, parameters=_void, return_annotation=_void): """Creates a customized copy of the Signature. Pass 'parameters' and/or 'return_annotation' arguments to override them in the new copy. """ if parameters is _void: parameters = self.parameters.values() ...
0.004098
def addChild(self, childJob): """ Adds childJob to be run as child of this job. Child jobs will be run \ directly after this job's :func:`toil.job.Job.run` method has completed. :param toil.job.Job childJob: :return: childJob :rtype: toil.job.Job """ self...
0.007317
def create(cls, service=None, endpoint=None, data=None, *args, **kwargs): """ Create an integration within the scope of an service. Make sure that they should reasonably be able to query with an service or endpoint that knows about an service. """ cls.validate(data) ...
0.002484
def sort_image(image, size, vertical=False, path=None, path_kwargs=None, max_interval=0, progressive_amount=0, randomize=False, edge_threshold=0, edge_data=None, image_threshold=None, image_mask=None, key=None, discretize=0, reverse=False, mirror=False, splice...
0.003762
def export_msdt(self, filename): """ Writes MSD data to a csv file that can be easily plotted in other software. Args: filename (str): Filename. Supported formats are csv and dat. If the extension is csv, a csv file is written. Otherwise, a da...
0.002004
def info(ctx): """ Display status of FIDO2 application. """ controller = ctx.obj['controller'] if controller.is_fips: click.echo('FIPS Approved Mode: {}'.format( 'Yes' if controller.is_in_fips_mode else 'No')) else: if controller.has_pin: try: ...
0.001529
def from_b32key(b32_key, state=None): '''Some phone app directly accept a partial b32 encoding, we try to emulate that''' try: lenient_b32decode(b32_key) except TypeError: raise ValueError('invalid base32 value') return GoogleAuthenticator('otpauth://totp/xxx?%s' % urlencode(...
0.008475
def get_tunnel_info_output_tunnel_config_src(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_tunnel_info = ET.Element("get_tunnel_info") config = get_tunnel_info output = ET.SubElement(get_tunnel_info, "output") tunnel = ET.SubElement...
0.003724
def _request_token(self, env): """ Retrieves a new access token from the OAuth2 server. """ params = {} content = env['wsgi.input'].read(int(env['CONTENT_LENGTH'])) post_params = parse_qs(content) # Convert to dict for easier access for param, value in po...
0.001376
def _handle_output(results_queue): """Scan output for exceptions If there is an output from an add task collection call add it to the results. :param results_queue: Queue containing results of attempted add_collection's :type results_queue: collections.deque :return: list of TaskAddResults :rt...
0.006122
def get_all_yep(self): """Cascading style sheet (CSS) extension points. :returns: dict: {yep: [css...], ...} """ yeps = {} for p in self.get_enabled_plugins: for e, v in p["plugin_yep"].items(): yep = yeps.get(e, []) + v yeps[e] = yep ...
0.0059
def subgraph_from_edges(G, edge_list, ref_back=True): """ Creates a networkx graph that is a subgraph of G defined by the list of edges in edge_list. Requires G to be a networkx MultiGraph or MultiDiGraph edge_list is a list of edges in either (u,v) or (u,v,d) form where u and v are nodes compr...
0.001508
def from_pytime(cls, pytime): """ Converts Python time object to sql time object ignoring timezone @param pytime: Python time object @return: sql time object """ secs = pytime.hour * 60 * 60 + pytime.minute * 60 + pytime.second nsec = secs * 10 ** 9 + pyti...
0.005391
def has_child_repositories(self, repository_id): """Tests if a repository has any children. arg: repository_id (osid.id.Id): a repository ``Id`` return: (boolean) - ``true`` if the ``repository_id`` has children, ``false`` otherwise raise: NotFound - ``repository_id`...
0.003359
def add(self, value): """Add value to set.""" added = self.redis.sadd( self.key, value ) if self.redis.scard(self.key) < 2: self.redis.expire(self.key, self.expire) return added
0.007843
def Run(self): """Retrieve all the clients for the AbstractClientStatsCollectors.""" try: self.stats = {} self.BeginProcessing() processed_count = 0 for client_info_batch in _IterateAllClients( recency_window=self.recency_window): for client_info in client_info_batc...
0.014269
def _execute_example_group(self): "Handles the execution of Example Group" for example in self.example: runner = self.__class__(example, self.formatter) runner.is_root_runner = False successes, failures, skipped = runner.run(self.context) self.num_successe...
0.004808
def base62_decode(string): """Decode a Base X encoded string into the number Arguments: - `string`: The encoded string - `alphabet`: The alphabet to use for encoding Stolen from: http://stackoverflow.com/a/1119769/1144479 """ alphabet = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP...
0.001786
def validate_nonce(nonce, secret): ''' Is the nonce one that was generated by this library using the provided secret? ''' nonce_components = nonce.split(':', 2) if not len(nonce_components) == 3: return False timestamp = nonce_components[0] salt = nonce_components[1] nonce_signat...
0.004107
def create_downsampled_data(params): ''' Creates one CSD or LFP file with downsampled data per cell type ''' maxsamples = 1 for data_type in ['LFP','CSD']: if RANK == 0: if not os.path.isdir(os.path.join(params.savefolder, 'populations', 'subsamples')): os.mkdir...
0.010905
def bahttext(number: float) -> str: """ Converts a number to Thai text and adds a suffix of "Baht" currency. Precision will be fixed at two decimal places (0.00) to fits "Satang" unit. Similar to BAHTTEXT function in Excel """ ret = "" if number is None: pass elif number == 0: ...
0.001263
def _fetch_objects(self, key, value): """Fetch Multiple linked objects""" return self.to_cls.query.filter(**{key: value})
0.014599
def hilbert_sort(x): """Hilbert sort: sort vectors according to their Hilbert index. Parameters ---------- x : (N,) or (N, d) float numpy.ndarray N vectors in R^d Returns ------- A : (N,) int numpy.ndarray argsort (e.g. x[A[0], :] is the vector with smallest H index). ...
0.006649
def read_column(self, column, where=None, start=None, stop=None): """return a single column from the table, generally only indexables are interesting """ # validate the version self.validate_version() # infer the data kind if not self.infer_axes(): r...
0.001373
def errorhandle(self, resp): """Parse API error responses and raise appropriate exceptions.""" if self.format == 'json': parsed = xmltodict.parse(resp) errors = parsed[self.RESPONSE_TOKEN][self.ERROR_TOKEN] # Create list of errors if more than one error re...
0.011024
def earning( ticker, by='Geo', typ='Revenue', ccy=None, level=None, **kwargs ) -> pd.DataFrame: """ Earning exposures by Geo or Products Args: ticker: ticker name by: [G(eo), P(roduct)] typ: type of earning, start with `PG_` in Bloomberg FLDS - default `Revenue` ccy:...
0.003671
def _cluster(param, tom, imtls, gsims, grp_ids, pmap): """ Computes the probability map in case of a cluster group """ pmapclu = AccumDict({grp_id: ProbabilityMap(len(imtls.array), len(gsims)) for grp_id in grp_ids}) # Get temporal occurrence model # Number of occurrence...
0.001287
def turbulent_Sieder_Tate(Re, Pr, mu=None, mu_w=None): r'''Calculates internal convection Nusselt number for turbulent flows in pipe according to [1]_ and supposedly [2]_. .. math:: Nu = 0.027Re^{4/5}Pr^{1/3}\left(\frac{\mu}{\mu_s}\right)^{0.14} Parameters ---------- Re : float ...
0.000674
def self_insert(self, e): # (a, b, A, 1, !, ...) u"""Insert yourself. """ if e.char and ord(e.char)!=0: #don't insert null character in buffer, can happen with dead keys. self.insert_text(e.char) self.finalize()
0.027888
def mboxes(self): """Get the mboxes managed by this mailing list. Returns the archives sorted by name. :returns: a list of `.MBoxArchive` objects """ archives = [] if os.path.isfile(self.dirpath): try: archives.append(MBoxArchive(self.dirpat...
0.004635
def Validate(self): """GlobExpression is valid.""" if len(self.RECURSION_REGEX.findall(self._value)) > 1: raise ValueError("Only one ** is permitted per path: %s." % self._value)
0.010417
def score(self, testing_features, testing_labels): """estimates accuracy on testing set""" # print("test features shape:",testing_features.shape) # print("testing labels shape:",testing_labels.shape) yhat = self.predict(testing_features) return self.scoring_function(testing_label...
0.009174
def maps_get_rules_output_rules_op(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") maps_get_rules = ET.Element("maps_get_rules") config = maps_get_rules output = ET.SubElement(maps_get_rules, "output") rules = ET.SubElement(output, "rules...
0.004098
def titleify(self, lang='en', allwords=False, lastword=True): """takes a string and makes a title from it""" if lang in LOWERCASE_WORDS: lc_words = LOWERCASE_WORDS[lang] else: lc_words = [] s = str(self).strip() l = re.split(r"([_\W]+)", s) ...
0.006112
def disable(name, **kwargs): ''' Disable the named service to start at boot CLI Example: .. code-block:: bash salt '*' service.disable <service name> ''' cmd = '/usr/sbin/svcadm disable {0}'.format(name) return not __salt__['cmd.retcode'](cmd, python_shell=False)
0.003311
def desc_for(self, obj: Element, doing_descs: bool) -> str: """ Return a description for object if it is unique (different than its parent) @param obj: object to be described @param doing_descs: If false, always return an empty string @return: text or empty string """ if...
0.005355
def get_element_by_name(self, el_name, el_idx=0): """ Args: el_name : str Name of element to get. el_idx : int Index of element to use as base in the event that there are multiple sibling elements with the same name. Returns: element : The selected element. ...
0.004498
def add(self, *args): """ Add integers args: args (list): target returns: str """ if (len(args) <= 1): return 0 return sum([int(v) for v in args])
0.008696
def random_unicode(length=20): """ Generates a random name; useful for testing. Returns an encoded string of the specified length containing unicode values up to code point 1000. """ def get_char(): return six.unichr(random.randint(32, 1000)) chars = u"".join([get_char() for ii in s...
0.002618
def stop_consuming(self): """Tell RabbitMQ that we would like to stop consuming.""" if self._channel: logger.debug('Sending a Basic.Cancel RPC command to RabbitMQ') self._channel.basic_cancel(self.on_cancelok, self._consumer_tag)
0.007435
def group_subscribe(self, topics): """Add topics to the current group subscription. This is used by the group leader to ensure that it receives metadata updates for all topics that any member of the group is subscribed to. Arguments: topics (list of str): topics to add to t...
0.003929
def CopyFromDateTimeString(self, time_string): """Copies time elements from a date and time string. Args: time_string (str): date and time value formatted as: YYYY-MM-DD hh:mm:ss.######[+-]##:## Where # are numeric digits ranging from 0 to 9 and the seconds fraction can be ...
0.001709
def make_color_wheel(bins=None): """Build a color wheel. Args: bins(list or tuple, optional): Specify the number of bins for each color range, corresponding to six ranges: red -> yellow, yellow -> green, green -> cyan, cyan -> blue, blue -> magenta, magenta -> red. [...
0.000885
def osd_page_handler(config=None, identifier=None, prefix=None, **args): """Flask handler to produce HTML response for OpenSeadragon view of identifier. Arguments: config - Config object for this IIIF handler identifier - identifier of image/generator prefix - path prefix **args...
0.002094
def getPluginDescriptor(self, dir): """ Detects the .uplugin descriptor file for the Unreal plugin in the specified directory """ for plugin in glob.glob(os.path.join(dir, '*.uplugin')): return os.path.realpath(plugin) # No plugin detected raise UnrealManagerException('could not detect an Unreal plugi...
0.037356
def remove_duplicate_metadata_dirs(package_name): """Remove duplicate metadata directories of a package.""" print("Removing duplicate metadata directories of package: %s" % package_name) module = importlib.import_module(package_name) py_mn = "%s.%s" % (sys.version_info[0], sys.version_info[...
0.000765
def bucket_exists(self, bucket_name): """ Check if the bucket exists and if the user has access to it. :param bucket_name: To test the existence and user access. :return: True on success. """ is_valid_bucket_name(bucket_name) try: self._url_open('HEA...
0.005338
def getStuckRelayCheckEnabled(self): """Returns True if enabled, False if disabled""" command = '$GE' settings = self.sendCommand(command) flags = int(settings[2], 16) return not (flags & 0x0010)
0.004651
def hugoniot_t_single(rho, rho0, c0, s, gamma0, q, theta0, n, mass, three_r=3. * constants.R, t_ref=300., c_v=0.): """ internal function to calculate pressure along Hugoniot :param rho: density in g/cm^3 :param rho0: density at 1 bar in g/cm^3 :param c0: velocity at 1 bar in k...
0.00082
def create_sheet(self): ''' create an editable grid showing demag_orient.txt ''' #-------------------------------- # orient.txt supports many other headers # but we will only initialize with # the essential headers for # sample orientation and headers pres...
0.006696
async def valid_token_set(self): """Check for validity of token, and refresh if none or expired.""" is_valid = False if self._auth_client.token: # Account for a token near expiration now = datetime.datetime.utcnow() skew = datetime.timedelta(seconds=60) ...
0.004695
def sort_elements_by_child_values(obj_pyxb, child_name_list): """In-place sort simple or complex elements in a PyXB object by values they contain in child elements. Args: obj_pyxb: PyXB object child_name_list: list of str List of element names that are direct children of the PyXB objec...
0.007229
def GetFilter(cls, filter_name): """Return an initialized filter. Only initialize filters once. Args: filter_name: The name of the filter, as a string. Returns: an initialized instance of the filter. Raises: DefinitionError if the type of filter has not been defined. """ # C...
0.005618
def raster_to_projection_coords(self, pixel_x, pixel_y): """ Use pixel centers when appropriate. See documentation for the GDAL function GetGeoTransform for details. """ h_px_py = np.array([1, pixel_x, pixel_y]) gt = np.array([[1, 0, 0], self.geotransform[0:3], self.geotransform[3:6]]) ...
0.010417
def _call_structure(mname, ename, sname, name, workdir, seed, ntaxa, nsites, kpop, rep): """ make the subprocess call to structure """ ## create call string outname = os.path.join(workdir, "{}-K-{}-rep-{}".format(name, kpop, rep)) cmd = ["structure", "-m", mname, "-e", ename, ...
0.014068
def enable_svc_notifications(self, service): """Enable notifications for a service Format of the line that triggers function call:: ENABLE_SVC_NOTIFICATIONS;<host_name>;<service_description> :param service: service to edit :type service: alignak.objects.service.Service ...
0.003226
def libvlc_vlm_set_loop(p_instance, psz_name, b_loop): '''Set a media's loop status. @param p_instance: the instance. @param psz_name: the media to work on. @param b_loop: the new status. @return: 0 on success, -1 on error. ''' f = _Cfunctions.get('libvlc_vlm_set_loop', None) or \ _C...
0.004032
def save_relationship(self, relationship_form, *args, **kwargs): """Pass through to provider RelationshipAdminSession.update_relationship""" # Implemented from kitosid template for - # osid.resource.ResourceAdminSession.update_resource if relationship_form.is_for_update(): re...
0.006263
def _get_referenced_type_equivalences(graphql_types, type_equivalence_hints): """Filter union types with no edges from the type equivalence hints dict.""" referenced_types = set() for graphql_type in graphql_types.values(): if isinstance(graphql_type, (GraphQLObjectType, GraphQLInterfaceType)): ...
0.00312
def debug(f, *args, **kwargs): """Automatically log progress on function entry and exit. Default logging value: debug. *Logging with values contained in the parameters of the decorated function* Message (args[0]) may be a string to be formatted with parameters passed to the decorated function. Each...
0.001144
def get_auth_from_user(msg_type): """Get the required 'auth' from the user and return as a dict.""" auth = [] for k, v in CONFIG[msg_type]["auth"].items(): auth.append((k, getpass(v + ": "))) return OrderedDict(auth)
0.004167
async def close(self): """Stop serving the :attr:`.Server.sockets`. """ if self._server: self._server.close() self._server = None coro = self._close_connections() if coro: await coro self.logger.debug('%s closed', self) ...
0.005602
def assoc(self, key, value): '''Returns a new ImmutableDict instance with value associated with key. The implicit parameter is not modified.''' copydict = ImmutableDict() copydict.tree = self.tree.assoc(hash(key), (key, value)) copydict._length = self._length + 1 return c...
0.006116
def validate(self, coll, constraint_spec, subject='collection'): """Validation of a collection. This is a generator that yields ConstraintViolationGroups. :param coll: Mongo collection :type coll: pymongo.Collection :param constraint_spec: Constraint specification :type...
0.00224
def view_as_consumer( wrapped_view: typing.Callable[[HttpRequest], HttpResponse], mapped_actions: typing.Optional[ typing.Dict[str, str] ]=None) -> Type[AsyncConsumer]: """ Wrap a django View so that it will be triggered by actions over this json websocket consumer. ...
0.004608
def print_stat(x, message=None): """ A simple print Op that might be easier to use than :meth:`tf.Print`. Use it like: ``x = print_stat(x, message='This is x')``. """ if message is None: message = x.op.name lst = [tf.shape(x), tf.reduce_mean(x)] if x.dtype.is_floating: lst.ap...
0.002252