text
stringlengths
78
104k
score
float64
0
0.18
def construct(key_data, algorithm=None): """ Construct a Key object for the given algorithm with the given key_data. """ # Allow for pulling the algorithm off of the passed in jwk. if not algorithm and isinstance(key_data, dict): algorithm = key_data.get('alg', None) if not algorit...
0.001739
def get_changes(self, name, *args): """Return a list of changes for the named refactoring action. Changes are dictionaries describing a single action to be taken for the refactoring to be successful. A change has an action and possibly a type. In the description below, the acti...
0.001337
def delete_certificate(ctx, slot, management_key, pin): """ Delete a certificate. Delete a certificate from a slot on the YubiKey. """ controller = ctx.obj['controller'] _ensure_authenticated(ctx, controller, pin, management_key) controller.delete_certificate(slot)
0.003401
def default_listener(col_attr, default): """Establish a default-setting listener.""" @event.listens_for(col_attr, "init_scalar", retval=True, propagate=True) def init_scalar(target, value, dict_): if default.is_callable: # the callable of ColumnDefault always accepts a context argument...
0.001642
def expand_role(self, role): """Expand an IAM role name into an ARN. If the role is already in the form of an ARN, then the role is simply returned. Otherwise we retrieve the full ARN and return it. Args: role (str): An AWS IAM role (either name or full ARN). Retur...
0.005792
def inspect(self): """Inspect device requests and sensors, update model Returns ------- Tornado future that resolves with: model_changes : Nested AttrDict or None Contains sets of added/removed request/sensor names Example structure: {'req...
0.001085
def validate(self, processes=1, fast=False, completeness_only=False, callback=None): """Checks the structure and contents are valid. If you supply the parameter fast=True the Payload-Oxum (if present) will be used to check that the payload files are present and accounted for, instead of...
0.008427
def plot(self, axis, ith_plot, total_plots, limits): """ Plot the histogram as a whole over all groups. Do not plot as individual groups like other plot types. """ print(self.plot_type_str.upper() + " plot") print("%5s %9s %s" % ("id", " #points", "group")) for...
0.000696
def list_files(root, suffix, prefix=False): """List all files ending with a suffix at a given root Args: root (str): Path to directory whose folders need to be listed suffix (str or tuple): Suffix of the files to match, e.g. '.png' or ('.jpg', '.png'). It uses the Python "str.endswi...
0.005025
def log_player_trades_with_port(self, player, to_port, port, to_player): """ :param player: catan.game.Player :param to_port: list of tuples, [(int, game.board.Terrain), (int, game.board.Terrain)] :param port: catan.board.Port :param to_player: list of tuples, [(int, game.board.T...
0.004107
def np_lst_sq_xval(vecMdl, aryFuncChnk, aryIdxTrn, aryIdxTst): """Least squares fitting in numpy with cross-validation. """ varNumXval = aryIdxTrn.shape[-1] varNumVoxChnk = aryFuncChnk.shape[-1] # pre-allocate ary to collect cross-validation # error for every xval fold aryResXval = np.emp...
0.000679
def get_assessment_taken_ids_by_banks(self, bank_ids): """Gets the list of ``AssessmentTaken Ids`` corresponding to a list of ``Banks``. arg: bank_ids (osid.id.IdList): list of bank ``Ids`` return: (osid.id.IdList) - list of bank ``Ids`` raise: NullArgument - ``bank_ids`` is ``null`...
0.00365
def get_column(columns, column_tys, index): """ Get column corresponding to passed-in index from ptr returned by groupBySum. Args: columns (List<WeldObject>): List of columns as WeldObjects column_tys (List<str>): List of each column data ty index (int): index of selected column...
0.002075
def MAVOL_serial(self,days,rev=0): """ see make_serial() 成較量移動平均 list 化,資料格式請見 def make_serial() """ return self.make_serial(self.stock_vol,days,rev=0)
0.02924
def complete(self): """ Complete current task :return: :rtype: requests.models.Response """ return self._post_request( data='', endpoint=self.ENDPOINT + '/' + str(self.id) + '/complete' )
0.007491
def reshape_fortran(tensor, shape): """The missing Fortran reshape for mx.NDArray Parameters ---------- tensor : NDArray source tensor shape : NDArray desired shape Returns ------- output : NDArray reordered result """ return tensor.T.reshape(tuple(rever...
0.002994
def fnr(y, z): """False negative rate `fn / (fn + tp)` """ tp, tn, fp, fn = contingency_table(y, z) return fn / (fn + tp)
0.007299
def find_free_prefix(self, auth, vrf, args): """ Finds free prefixes in the sources given in `args`. * `auth` [BaseAuth] AAA options. * `vrf` [vrf] Full VRF-dict specifying in which VRF the prefix should be unique. * `args` [fi...
0.002927
def _idle(self): """ since imaplib doesn't support IMAP4r1 IDLE, we'll do it by hand """ socket = None try: # build a new command tag (Xnnn) as bytes: self.command_tag = (self.command_tag + 1) % 1000 command_tag = b"X" + bytes(str(self.command...
0.003129
def write(self, group_id, handle): '''Write this parameter group, with parameters, to a file handle. Parameters ---------- group_id : int The numerical ID of the group. handle : file handle An open, writable, binary file handle. ''' name =...
0.002886
def AddArguments(cls, argument_group): """Adds command line arguments the helper supports to an argument group. This function takes an argument parser or an argument group object and adds to it all the command line arguments this helper supports. Args: argument_group (argparse._ArgumentGroup|arg...
0.000836
def execute_withdrawal(self, withdrawal_params, private_key): """ This function is to sign the message generated from the create withdrawal function and submit it to the blockchain for transfer from the smart contract to the owners address. Execution of this function is as follows:: ...
0.004915
def update_xml_element(self): """ Updates the xml element contents to matches the instance contents. :returns: Updated XML element. :rtype: lxml.etree._Element """ if not hasattr(self, 'xml_element'): self.xml_element = etree.Element(self.name, nsmap=NSMAP) ...
0.003745
def get_2q_nodes(self): """Deprecated. Use twoQ_gates().""" warnings.warn('The method get_2q_nodes() is being replaced by twoQ_gates()', 'Returning a list of data_dicts is also deprecated, twoQ_gates() ' 'returns a list of DAGNodes.', Dep...
0.007273
def _process_params(self, params): """ Converts Unicode/lists/booleans inside HTTP parameters """ processed_params = {} for key, value in params.items(): processed_params[key] = self._process_param_value(value) return processed_params
0.007168
def get_outcome_probs(self): """ Parses a wavefunction (array of complex amplitudes) and returns a dictionary of outcomes and associated probabilities. :return: A dict with outcomes as keys and probabilities as values. :rtype: dict """ outcome_dict = {} q...
0.005464
def _on_read_only_error(self, command, future): """Invoked when a Redis node returns an error indicating it's in read-only mode. It will use the ``INFO REPLICATION`` command to attempt to find the master server and failover to that, reissuing the command to that server. :param c...
0.000891
def as_manager(cls, obj): """ Convert obj into TaskManager instance. Accepts string, filepath, dictionary, `TaskManager` object. If obj is None, the manager is initialized from the user config file. """ if isinstance(obj, cls): return obj if obj is None: return cls.from_u...
0.008571
def main(): """Main entry point for script.""" parser = argparse.ArgumentParser( description='Auto-generate a RESTful API service ' 'from an existing database.' ) parser.add_argument( 'URI', help='Database URI in the format ' 'postgresql+psycopg2://user:p...
0.001974
def unmarshal(self, v): """ Convert a date in "2012-12-13" format to a :class:`datetime.date` object. """ if not isinstance(v, date): # 2012-12-13 v = datetime.strptime(v, "%Y-%m-%d").date() return v
0.011407
def clean_locks(root=None): ''' Remove unused locks that do not currently (with regard to repositories used) lock any package. root Operate on a different root directory. CLI Example: .. code-block:: bash salt '*' pkg.clean_locks ''' LCK = "removed" out = {LCK: 0}...
0.004237
def libvlc_video_get_chapter_description(p_mi, i_title): '''Get the description of available chapters for specific title. @param p_mi: the media player. @param i_title: selected title. @return: list containing description of available chapter for title i_title. ''' f = _Cfunctions.get('libvlc_vi...
0.007286
def _on_decisions_event(self, event=None, **kwargs): """Called when an Event is received on the decisions channel. Saves the value in group_decisions. If num_subperiods is None, immediately broadcasts the event back out on the group_decisions channel. """ if not self.ran_ready_fu...
0.004635
def get_parameters(self): """ Parse DockerRunBuilder options and create object with properties for docker-py run command :return: DockerContainerParameters """ import argparse parser = argparse.ArgumentParser(add_help=False) # without parameter parser.add...
0.005762
def path(self, which=None): """Extend ``nailgun.entity_mixins.Entity.path``. The format of the returned path depends on the value of ``which``: build_pxe_default /provisioning_templates/build_pxe_default clone /provisioning_templates/clone revision ...
0.002725
def process_flagged_blocks(self, content: str) -> str: '''Replace flagged blocks either with their contents or nothing, depending on the value of ``FOLIANT_FLAGS`` environment variable and ``flags`` config value. :param content: Markdown content :returns: Markdown content without flagg...
0.004942
def get_branding(self): """Gets a branding, such as an image or logo, expressed using the ``Asset`` interface. return: (osid.repository.AssetList) - a list of assets raise: OperationFailed - unable to complete request *compliance: mandatory -- This method must be implemented.* ...
0.00519
def get_build_controller(self, controller_id): """GetBuildController. Gets a controller :param int controller_id: :rtype: :class:`<BuildController> <azure.devops.v5_0.build.models.BuildController>` """ route_values = {} if controller_id is not None: ro...
0.007123
def postinit(self, expr=None, globals=None, locals=None): """Do some setup after initialisation. :param expr: The expression to be executed. :type expr: NodeNG or None :param globals:The globals dictionary to execute with. :type globals: NodeNG or None :param locals: T...
0.004073
def rename_categories(self, new_categories, inplace=False): """ Rename categories. Parameters ---------- new_categories : list-like, dict-like or callable * list-like: all items must be unique and the number of items in the new categories must match the ...
0.000605
def modification_time(self): """dfdatetime.DateTimeValues: modification time or None if not available.""" timestamp = getattr(self._tar_info, 'mtime', None) if timestamp is None: return None return dfdatetime_posix_time.PosixTime(timestamp=timestamp)
0.011029
def create_packages_archive(packages, filename): """ Create a tar archive which will contain the files for the packages listed in packages. """ import tarfile tar = tarfile.open(filename, "w") def add(src, dst): logger.debug('adding to tar: %s -> %s', src, dst) tar.add(src, dst)...
0.002401
def get_band_gap(self): """ Returns band gap data. Returns: A dict {"energy","direct","transition"}: "energy": band gap energy "direct": A boolean telling if the gap is direct or not "transition": kpoint labels of the transition (e.g., "\\Gamma-X"...
0.001671
def __start_datanode(self, job): """ Launches the Hadoop datanode. :param job: The underlying job. """ self.hdfsContainerID = dockerCheckOutput(job=job, defer=STOP, workDir=os.getcw...
0.009079
def content_preview(self, request): """ Admin view to preview Entry.content in HTML, useful when using markups to write entries. """ data = request.POST.get('data', '') entry = self.model(content=data) return TemplateResponse( request, 'admin/zinnia/en...
0.005222
def got(self, *args, **kwargs): """Does `.request` match the given :ref:`message spec <message spec>`? >>> s = MockupDB(auto_ismaster=True) >>> port = s.run() >>> s.got(timeout=0) # No request enqueued. False >>> from pymongo import MongoClient >>> client = Mong...
0.001759
def _tokenize(sentence): '''Tokenizer and Stemmer''' _tokens = nltk.word_tokenize(sentence) tokens = [stemmer.stem(tk) for tk in _tokens] return tokens
0.005952
def addAllowedType(self, assoc_type, session_type=None): """Add an association type and session type to the allowed types list. The assocation/session pairs are tried in the order that they are added.""" if self.allowed_types is None: self.allowed_types = [] if sessi...
0.002475
def find(self, _id, instance = None): """ Find Args: _id (str): instance id or binding Id Keyword Arguments: instance (AtlasServiceInstance.Instance): Existing instance Returns: AtlasServiceInstance.Instance or AtlasS...
0.015873
def create_host_template(resource_root, name, cluster_name): """ Create a host template. @param resource_root: The root Resource object. @param name: Host template name @param cluster_name: Cluster name @return: An ApiHostTemplate object for the created host template. @since: API v3 """ apitemplate = ...
0.011858
def convert_nsarg( nsarg: str, api_url: str = None, namespace_targets: Mapping[str, List[str]] = None, canonicalize: bool = False, decanonicalize: bool = False, ) -> str: """[De]Canonicalize NSArg Args: nsarg (str): bel statement string or partial string (e.g. subject or object) ...
0.002174
def parse(self): """ Try to extract domain (full, naked, sub-domain), IP and port. """ if self.target.endswith("/"): self.target = self.target[:-1] if self._is_proto(self.target): try: self.protocol, self.target = self.target.split("://") ...
0.004781
def get_cache_key(request, meta, orgaMode, currentOrga): """Return the cache key to use""" # Caching cacheKey = None if 'cache_time' in meta: if meta['cache_time'] > 0: # by default, no cache by user useUser = False # If a logged user in needed, cache the ...
0.004234
def _extract_from_included(self, data): """Extract included data matching the items in ``data``. For each item in ``data``, extract the full data from the included data. """ return (item for item in self.included_data if item['type'] == data['type'] and ...
0.005525
def fixedvar(self): """Returns the name of a member in this type that is non-custom so that it would terminate the auto-class variable context chain. """ possible = [m for m in self.members.values() if not m.is_custom] #If any of the possible variables is not allocatable or point...
0.007669
def upload_pdf(self, pdf): """ 上传电子发票中的消费凭证 PDF 详情请参考 https://mp.weixin.qq.com/wiki?id=mp1497082828_r1cI2 :param pdf: 要上传的 PDF 文件,一个 File-object :return: 64位整数,在将发票卡券插入用户卡包时使用用于关联pdf和发票卡券。有效期为3天。 """ return self._post( 'platform/setpdf', ...
0.004515
def push_blob(self, filename=None, progress=None, data=None, digest=None, check_exists=True): # pylint: disable=too-many-arguments """ Upload a file to the registry and return its (SHA-256) hash. The registry is con...
0.004167
def write_listing_to_textfile(textfile, tracklisting): """Write tracklisting to a text file.""" with codecs.open(textfile, 'wb', 'utf-8') as text: text.write(tracklisting)
0.005348
def get_authed_registries(): """Reads the local Docker client config for the current user and returns all registries to which the user may be logged in. This is intended to be run client-side, not by the daemon.""" result = set() if not os.path.exists(constants.DOCKER_CONFIG_PATH): return re...
0.001808
def QA_fetch_future_min_adv( code, start, end=None, frequence='1min', if_drop_index=True, collections=DATABASE.future_min): ''' '获取股票分钟线' :param code: :param start: :param end: :param frequence: :param if_drop_index: :param collections: :return...
0.003452
def cancelPendingResultsFor( self, params ): """Cancel any results pending for experiments at the given point in the parameter space. :param params: the experimental parameters""" # grab the result job ids jobs = self.pendingResultsFor(params) if len(jo...
0.015238
def modify_ssh_template(auth, url, ssh_template, template_name= None, template_id = None): """ Function takes input of a dictionry containing the required key/value pair for the modification of a ssh template. :param auth: :param url: :param ssh_template: Human readable label which is the name ...
0.008449
def getChild(self, name, ns=None, default=None): """ Get a child by (optional) name and/or (optional) namespace. @param name: The name of a child element (may contain prefix). @type name: basestring @param ns: An optional namespace used to match the child. @type ns: (I{p...
0.002506
def set_buffer_limits(self, high=None, low=None): """Set the low and high watermarks for the read buffer.""" if high is None: high = self.default_buffer_size if low is None: low = high // 2 self._buffer_high = high self._buffer_low = low
0.006645
def AddInformationalOptions(self, argument_group): """Adds the informational options to the argument group. Args: argument_group (argparse._ArgumentGroup): argparse argument group. """ argument_group.add_argument( '-d', '--debug', dest='debug', action='store_true', default=False, ...
0.001988
def dataframe(self, predicate=None, filtered_columns=None, columns=None, df_class=None): """Return the partition as a Pandas dataframe :param predicate: If defined, a callable that is called for each row, and if it returns true, the row is included in the output. :param filtered_column...
0.003808
def get_abbreviation_of(self, name): """Get abbreviation of a language.""" for language in self.user_data.languages: if language['language_string'] == name: return language['language'] return None
0.008065
def get_route(self, name): '''Get a child :class:`Router` by its :attr:`name`. This method search child routes recursively. ''' for route in self.routes: if route.name == name: return route for child in self.routes: route = child.get_route...
0.005305
def window_cover(self, window_shape, pad=True): """ Iterate over a grid of windows of a specified shape covering an image. The image is divided into a grid of tiles of size window_shape. Each iteration returns the next window. Args: window_shape (tuple): The desired shape ...
0.002992
def iterate_with_selected_objects(analysis_objects: Mapping[Any, Any], **selections: Mapping[str, Any]) -> Iterator[Tuple[Any, Any]]: """ Iterate over an analysis dictionary with selected attributes. Args: analysis_objects: Analysis objects dictionary. selections: Keyword arguments used to sele...
0.005875
def defer(target, args=None, kwargs=None, callback=None): """Perform operation in thread with callback Instances are cached until finished, at which point they are garbage collected. If we didn't do this, Python would step in and garbage collect the thread before having had time to finish, resultin...
0.001389
def split(self, split_on): """ Splits the AST if its operation is `split_on` (i.e., return all the arguments). Otherwise, return a list with just the AST. """ if self.op in split_on: return list(self.args) else: return [ self ]
0.025455
def get_data_info(self): """ imports er tables and places data into Data_info data structure outlined bellow: Data_info - {er_samples: {er_samples.txt info} er_sites: {er_sites.txt info} er_locations: {er_locations.txt info} ...
0.002209
def set_version(new_version_number=None, old_version_number=''): """ Set package version as listed in `__version__` in `__init__.py`. """ if new_version_number is None: return ValueError import fileinput import sys file = join('timezonefinder', '__init__.py') for line in filei...
0.002041
def find_end(self, text, start_token, end_token, ignore_end_token=None): '''find the of a token. Returns the offset in the string immediately after the matching end_token''' if not text.startswith(start_token): raise MAVParseError("invalid token start") offset = len(start_tok...
0.004163
def parse_date(dateString): '''Parses a variety of date formats into a 9-tuple in GMT''' if not dateString: return None for handler in _date_handlers: try: date9tuple = handler(dateString) except (KeyError, OverflowError, ValueError): continue if not d...
0.002237
def from_whypo(cls, xml, encoding='utf-8'): """Constructor from xml element *WHYPO* :param xml.etree.ElementTree xml: the xml *WHYPO* element :param string encoding: encoding of the xml """ word = unicode(xml.get('WORD'), encoding) confidence = float(xml.get('CM')) ...
0.005682
def _read_response(self, response): """ JSON Documentation: https://www.jfrog.com/confluence/display/RTF/Security+Configuration+JSON """ self.name = response['name'] self.includesPattern = response['includesPattern'] self.excludesPattern = response['excludesPattern'] ...
0.00468
def process_log_record(self, log_record): """Add customer record keys and rename threadName key.""" log_record["version"] = __version__ log_record["program"] = PROGRAM_NAME log_record["service_name"] = log_record.pop('threadName', None) # return jsonlogger.JsonFormatter.process_l...
0.005348
def list(self, name, iterator=False, **kwargs): """ Returns a list of the files under the specified path name must be in the form of `s3://bucket/prefix` Parameters ---------- keys: optional if True then this will return the actual boto keys for files ...
0.003444
def age(self): """ :returns: The age of the user associated with this profile. """ if self.is_logged_in_user: # Retrieve the logged-in user's profile age return int(self._user_age_xpb.get_text_(self.profile_tree).strip()) else: # Retrieve a no...
0.007194
def exit_ok(self, message, exit_code=None): """Log a message and exit :param exit_code: if not None, exit with the provided value as exit code :type exit_code: int :param message: message for the exit reason :type message: str :return: None """ logger.inf...
0.005291
def score_(self): """ The concordance score (also known as the c-index) of the fit. The c-index is a generalization of the ROC AUC to survival data, including censorships. For this purpose, the ``score_`` is a measure of the predictive accuracy of the fitted model onto the trai...
0.004667
def _get_cursor(self): ''' Yield a SQLCipher cursor ''' _options = self._get_options() conn = sqlcipher.connect(_options.get('database'), timeout=float(_options.get('timeout'))) conn.execute('pragma key="{0}"'.format(_options.get('pass')))...
0.003683
def rings_full_data(self): """ Returns a generator for iterating over each ring Yields ------ For each ring, tuple composed by ring ID, list of edges, list of nodes Notes ----- Circuit breakers must be closed to find rings, this is done automatically. ...
0.008215
def get_statements_by_hash(hash_list, ev_limit=100, best_first=True, tries=2): """Get fully formed statements from a list of hashes. Parameters ---------- hash_list : list[int or str] A list of statement hashes. ev_limit : int or None Limit the amount of evidence returned per Statem...
0.000566
def __as_list(value: List[JsonObjTypes]) -> List[JsonTypes]: """ Return a json array as a list :param value: array :return: array with JsonObj instances removed """ return [e._as_dict if isinstance(e, JsonObj) else e for e in value]
0.007326
def json(value, schema = None, allow_empty = False, json_serializer = None, **kwargs): """Validate that ``value`` conforms to the supplied JSON Schema. .. note:: ``schema`` supports JSON Schema Drafts 3 - 7. Unless the JSON Schema indicates the meta-schema using...
0.00529
def get_sitk_image_from_ndarray(data3d): """ Prepare SimpleItk Image object and rescale data to unsigned types. Simple ITK with version higher than 1.0.0 can not write signed int16. This function check the SimpleITK version and use work around with Rescale Intercept and Rescale Slope :param data3d:...
0.002292
def _raw_read(self): """ Reads data from the socket and writes it to the memory bio used by libssl to decrypt the data. Returns the unencrypted data for the purpose of debugging handshakes. :return: A byte string of ciphertext from the socket. Used for de...
0.003096
def _get_default_value_to_cache(self, xblock): """ Perform special logic to provide a field's default value for caching. """ try: # pylint: disable=protected-access return self.from_json(xblock._field_data.default(xblock, self.name)) except KeyError: ...
0.008048
def generate_molecule_object_dict(source, format, values): """Generate a dictionary that represents a Squonk MoleculeObject when written as JSON :param source: Molecules in molfile or smiles format :param format: The format of the molecule. Either 'mol' or 'smiles' :param values: Optional dict of v...
0.002008
def absent( name, region, user=None, opts=False): ''' Remove the named SQS queue if it exists. name Name of the SQS queue. region Region to remove the queue from user Name of the user performing the SQS operations opts Include a...
0.000904
def log_file_list_handler(self, **kwargs): # noqa: E501 """log_file_list_handler # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.log_file_list_handler(async_req=True) >>> re...
0.0025
def get(self): '''taobao.time.get 获取前台展示的店铺类目 获取淘宝系统当前时间''' request = TOPRequest('taobao.time.get') self.create(self.execute(request)) return self.time
0.015
def strip_filter(value): ''' Strips HTML tags from strings according to SANITIZER_ALLOWED_TAGS, SANITIZER_ALLOWED_ATTRIBUTES and SANITIZER_ALLOWED_STYLES variables in settings. Example usage: {% load sanitizer %} {{ post.content|strip_html }} ''' if isinstance(value, basestring): ...
0.003876
def _import_class(self, class_path): """Try and import the specified namespaced class. :param str class_path: The full path to the class (foo.bar.Baz) :rtype: class """ LOGGER.debug('Importing %s', class_path) try: return utils.import_namespaced_class(class_...
0.004348
def publisher(self_url=None, hub_url=None): """This decorator makes it easier to implement a websub publisher. You use it on an endpoint, and Link headers will automatically be added. To also include these links in your template html/atom/rss (and you should!) you can use the following to get the raw li...
0.00056
def bytes_to_number(b, endian='big'): """ Convert a string to an integer. :param b: String or bytearray to convert. :param endian: Byte order to convert into ('big' or 'little' endian-ness, default 'big') Assumes bytes are 8 bits. This is a special-case version of str...
0.001241
def get_available_mfds(): ''' Returns an ordered dictionary with the available GSIM classes keyed by class name ''' mfds = {} for fname in os.listdir(os.path.dirname(__file__)): if fname.endswith('.py'): modname, _ext = os.path.splitext(fname) mod = importlib.impo...
0.001647