text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def monochrome(clr): """ Returns colors in the same hue with varying brightness/saturation. """ def _wrap(x, min, threshold, plus): if x - min < threshold: return x + plus else: return x - min colors = colorlist(clr) c = clr.copy() c.brightness = _wr...
[ "def", "monochrome", "(", "clr", ")", ":", "def", "_wrap", "(", "x", ",", "min", ",", "threshold", ",", "plus", ")", ":", "if", "x", "-", "min", "<", "threshold", ":", "return", "x", "+", "plus", "else", ":", "return", "x", "-", "min", "colors", ...
25.258065
0.00123
def _strip_leading_dirname(self, path): '''Strip leading directory name from the given path''' return os.path.sep.join(path.split(os.path.sep)[1:])
[ "def", "_strip_leading_dirname", "(", "self", ",", "path", ")", ":", "return", "os", ".", "path", ".", "sep", ".", "join", "(", "path", ".", "split", "(", "os", ".", "path", ".", "sep", ")", "[", "1", ":", "]", ")" ]
53.666667
0.01227
def job_step_store_output_complete(self, job_request_payload, output_project_info): """ Send message that the store output job step is complete using payload data. Raises ValueError if used for non-StoreJobOutputPayload message type. :param job_request_payload: StoreJobOutputPayload payl...
[ "def", "job_step_store_output_complete", "(", "self", ",", "job_request_payload", ",", "output_project_info", ")", ":", "if", "job_request_payload", ".", "success_command", "!=", "JobCommands", ".", "STORE_JOB_OUTPUT_COMPLETE", ":", "raise", "ValueError", "(", "\"Programm...
71
0.010114
def get_opt_tag(self, section, option, tag): """ Convenience function accessing get_opt_tags() for a single tag: see documentation for that function. NB calling get_opt_tags() directly is preferred for simplicity. Parameters ----------- self : ConfigParser object...
[ "def", "get_opt_tag", "(", "self", ",", "section", ",", "option", ",", "tag", ")", ":", "return", "self", ".", "get_opt_tags", "(", "section", ",", "option", ",", "[", "tag", "]", ")" ]
35.166667
0.002307
def del_row(self, row_index): """Delete a row to the table Arguments: row_index - The index of the row you want to delete. Indexing starts at 0.""" if row_index > len(self._rows)-1: raise Exception("Cant delete row at index %d, table only has %d rows!" % (row_index, len(...
[ "def", "del_row", "(", "self", ",", "row_index", ")", ":", "if", "row_index", ">", "len", "(", "self", ".", "_rows", ")", "-", "1", ":", "raise", "Exception", "(", "\"Cant delete row at index %d, table only has %d rows!\"", "%", "(", "row_index", ",", "len", ...
32.454545
0.010899
def _get_sorted_conditions_list(self, raw_set): """ This returns a list of dictionaries with the conditions got in the raw_set. :raw_set: is the dict representing a set of rules and conditions. """ keys_list = raw_set.keys() # cond_dicts_l is the final list which ...
[ "def", "_get_sorted_conditions_list", "(", "self", ",", "raw_set", ")", ":", "keys_list", "=", "raw_set", ".", "keys", "(", ")", "# cond_dicts_l is the final list which will contain the the", "# dictionaries with the conditions.", "# The dictionaries will be sorted by the index obt...
43.3
0.001129
def copy_within(ol,target, start=None, end=None): ''' from elist.elist import * ol = [1, 2, 3, 4, 5] id(ol) rslt = copyWithin(ol,0,3,4) rslt id(rslt) #### ol = [1, 2, 3, 4, 5] id(ol) rslt = copyWithin(ol,0,3) rslt id(rsl...
[ "def", "copy_within", "(", "ol", ",", "target", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "length", "=", "ol", ".", "__len__", "(", ")", "if", "(", "start", "==", "None", ")", ":", "start", "=", "0", "else", ":", "pass", "if...
22.1875
0.011691
def pipeline( ctx, input_fn, db_save, db_delete, output_fn, rules, species, namespace_targets, version, api, config_fn, ): """BEL Pipeline - BEL Nanopubs into BEL Edges This will process BEL Nanopubs into BEL Edges by validating, orthologizing (if requested), can...
[ "def", "pipeline", "(", "ctx", ",", "input_fn", ",", "db_save", ",", "db_delete", ",", "output_fn", ",", "rules", ",", "species", ",", "namespace_targets", ",", "version", ",", "api", ",", "config_fn", ",", ")", ":", "if", "config_fn", ":", "config", "="...
31.408
0.001975
def get_all_components(user, topic_id): """Get all components of a topic.""" args = schemas.args(flask.request.args.to_dict()) query = v1_utils.QueryBuilder(_TABLE, args, _C_COLUMNS) query.add_extra_condition(sql.and_( _TABLE.c.topic_id == topic_id, _TABLE.c.state != 'archived')) ...
[ "def", "get_all_components", "(", "user", ",", "topic_id", ")", ":", "args", "=", "schemas", ".", "args", "(", "flask", ".", "request", ".", "args", ".", "to_dict", "(", ")", ")", "query", "=", "v1_utils", ".", "QueryBuilder", "(", "_TABLE", ",", "args...
34.090909
0.001297
def verification_delete(self, verification_id): """ Remove verification. Uses DELETE to /verifications/<verification_id> interface. :Args: * *verification_id*: (str) Verification ID """ response = self._delete(url.verifications_id.format(id=verification_id)) ...
[ "def", "verification_delete", "(", "self", ",", "verification_id", ")", ":", "response", "=", "self", ".", "_delete", "(", "url", ".", "verifications_id", ".", "format", "(", "id", "=", "verification_id", ")", ")", "self", ".", "_check_response", "(", "respo...
38.666667
0.011236
def set_memory_limits(self, rss_soft=None, rss_hard=None): """Sets worker memory limits for cheapening. :param int rss_soft: Don't spawn new workers if total resident memory usage of all workers is higher than this limit in bytes. .. warning:: This option expects me...
[ "def", "set_memory_limits", "(", "self", ",", "rss_soft", "=", "None", ",", "rss_hard", "=", "None", ")", ":", "self", ".", "_set", "(", "'cheaper-rss-limit-soft'", ",", "rss_soft", ")", "self", ".", "_set", "(", "'cheaper-rss-limit-hard'", ",", "rss_hard", ...
40.470588
0.008523
def get_item_abspath(self, identifier): """Return absolute path at which item content can be accessed. :param identifier: item identifier :returns: absolute path from which the item content can be accessed """ dataset_cache_abspath = os.path.join( self._cache_abspat...
[ "def", "get_item_abspath", "(", "self", ",", "identifier", ")", ":", "dataset_cache_abspath", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_cache_abspath", ",", "self", ".", "uuid", ")", "mkdir_parents", "(", "dataset_cache_abspath", ")", "manifest"...
32.242424
0.001825
def _convert_batch_to_json(batch_requests): ''' Create json to send for an array of batch requests. batch_requests: an array of requests ''' batch_boundary = b'batch_' + _new_boundary() changeset_boundary = b'changeset_' + _new_boundary() body = [b'--' + batch_boundary + b'\n', ...
[ "def", "_convert_batch_to_json", "(", "batch_requests", ")", ":", "batch_boundary", "=", "b'batch_'", "+", "_new_boundary", "(", ")", "changeset_boundary", "=", "b'changeset_'", "+", "_new_boundary", "(", ")", "body", "=", "[", "b'--'", "+", "batch_boundary", "+",...
35.382979
0.00117
def catchable_exceptions(exceptions): """Returns True if exceptions can be caught in the except clause. The exception can be caught if it is an Exception type or a tuple of exception types. """ if isinstance(exceptions, type) and issubclass(exceptions, BaseException): return True if (...
[ "def", "catchable_exceptions", "(", "exceptions", ")", ":", "if", "isinstance", "(", "exceptions", ",", "type", ")", "and", "issubclass", "(", "exceptions", ",", "BaseException", ")", ":", "return", "True", "if", "(", "isinstance", "(", "exceptions", ",", "t...
26.5
0.002024
async def query(self, url, *, post_data=None, headers=None, verify=True, cache=None, pre_cache_callback=None): """ Send a GET/POST request or get data from cache, retry if it fails, and return a tuple of store in cache callback, response content. """ async def store_in_cache_callback(): pass if cache ...
[ "async", "def", "query", "(", "self", ",", "url", ",", "*", ",", "post_data", "=", "None", ",", "headers", "=", "None", ",", "verify", "=", "True", ",", "cache", "=", "None", ",", "pre_cache_callback", "=", "None", ")", ":", "async", "def", "store_in...
45.61039
0.010033
def columns(self): """Index of the column names present in the DataFrame in order. Returns ------- Index """ return Index(np.array(self._gather_column_names(), dtype=np.bytes_), np.dtype(np.bytes_))
[ "def", "columns", "(", "self", ")", ":", "return", "Index", "(", "np", ".", "array", "(", "self", ".", "_gather_column_names", "(", ")", ",", "dtype", "=", "np", ".", "bytes_", ")", ",", "np", ".", "dtype", "(", "np", ".", "bytes_", ")", ")" ]
26.666667
0.012097
def separation(self, ra, dec): """Compute the separation between self and (ra,dec)""" if self.coord is None: return None return self.coord.separation(SkyCoord(ra, dec, unit=('degree', 'degree')))
[ "def", "separation", "(", "self", ",", "ra", ",", "dec", ")", ":", "if", "self", ".", "coord", "is", "None", ":", "return", "None", "return", "self", ".", "coord", ".", "separation", "(", "SkyCoord", "(", "ra", ",", "dec", ",", "unit", "=", "(", ...
45.4
0.012987
def create_metadata(self, **params): """ Adds metadata to a media element, such as image descriptions for visually impaired. Docs: https://developer.twitter.com/en/docs/media/upload-media/api-reference/post-media-metadata-create """ params = json.dumps(params) return se...
[ "def", "create_metadata", "(", "self", ",", "*", "*", "params", ")", ":", "params", "=", "json", ".", "dumps", "(", "params", ")", "return", "self", ".", "post", "(", "\"https://upload.twitter.com/1.1/media/metadata/create.json\"", ",", "params", "=", "params", ...
43.888889
0.009926
def file_sign( blockchain_id, hostname, input_path, passphrase=None, config_path=CONFIG_PATH, wallet_keys=None ): """ Sign a file with the current blockchain ID's host's public key. @config_path should be for the *client*, not blockstack-file Return {'status': True, 'sender_key_id': ..., 'sig': ...} on ...
[ "def", "file_sign", "(", "blockchain_id", ",", "hostname", ",", "input_path", ",", "passphrase", "=", "None", ",", "config_path", "=", "CONFIG_PATH", ",", "wallet_keys", "=", "None", ")", ":", "config_dir", "=", "os", ".", "path", ".", "dirname", "(", "con...
46.095238
0.012146
def set_options(self, force_read=False, force_fulltext=False): """Set the options for this run.""" self.options['force_read'] = force_read self.options['force_fulltext'] = force_fulltext return
[ "def", "set_options", "(", "self", ",", "force_read", "=", "False", ",", "force_fulltext", "=", "False", ")", ":", "self", ".", "options", "[", "'force_read'", "]", "=", "force_read", "self", ".", "options", "[", "'force_fulltext'", "]", "=", "force_fulltext...
44.2
0.008889
def tree(path, load_path=None): ''' Returns recursively the complete tree of a node CLI Example: .. code-block:: bash salt '*' augeas.tree /files/etc/ path The base of the recursive listing .. versionadded:: 2016.3.0 load_path A colon-spearated list of directori...
[ "def", "tree", "(", "path", ",", "load_path", "=", "None", ")", ":", "load_path", "=", "_check_load_paths", "(", "load_path", ")", "aug", "=", "_Augeas", "(", "loadpath", "=", "load_path", ")", "path", "=", "path", ".", "rstrip", "(", "'/'", ")", "+", ...
23.777778
0.001497
def _menuitem(self, label, icon, onclick, checked=None): """ Create a generic menu item. :param str label: text :param Gtk.Image icon: icon (may be ``None``) :param onclick: onclick handler, either a callable or Gtk.Menu :returns: the menu item object :rtype: Gtk...
[ "def", "_menuitem", "(", "self", ",", "label", ",", "icon", ",", "onclick", ",", "checked", "=", "None", ")", ":", "if", "checked", "is", "not", "None", ":", "item", "=", "Gtk", ".", "CheckMenuItem", "(", ")", "item", ".", "set_active", "(", "checked...
34.464286
0.002016
def indexOf(self, action): """ Returns the index of the inputed action. :param action | <QAction> || None :return <int> """ for i, act in enumerate(self.actionGroup().actions()): if action in (act, act.objectName(), act.text...
[ "def", "indexOf", "(", "self", ",", "action", ")", ":", "for", "i", ",", "act", "in", "enumerate", "(", "self", ".", "actionGroup", "(", ")", ".", "actions", "(", ")", ")", ":", "if", "action", "in", "(", "act", ",", "act", ".", "objectName", "("...
29.833333
0.01084
def truncate_impulse(impulse, ntaps, window='hanning'): """Smoothly truncate a time domain impulse response Parameters ---------- impulse : `numpy.ndarray` the impulse response to start from ntaps : `int` number of taps in the final filter window : `str`, `numpy.ndarray`, opti...
[ "def", "truncate_impulse", "(", "impulse", ",", "ntaps", ",", "window", "=", "'hanning'", ")", ":", "out", "=", "impulse", ".", "copy", "(", ")", "trunc_start", "=", "int", "(", "ntaps", "/", "2", ")", "trunc_stop", "=", "out", ".", "size", "-", "tru...
30.285714
0.001143
def max_global_iteration(self): """Return global iterator with last iteration number""" return self.indices_to_global_iterator({ symbol_pos_int(var_name): end-1 for var_name, start, end, incr in self._loop_stack })
[ "def", "max_global_iteration", "(", "self", ")", ":", "return", "self", ".", "indices_to_global_iterator", "(", "{", "symbol_pos_int", "(", "var_name", ")", ":", "end", "-", "1", "for", "var_name", ",", "start", ",", "end", ",", "incr", "in", "self", ".", ...
49.2
0.012
def extractSeparators(self, hl7dict, msg): """ Read from the MSH (Message Header) the separators used to separate the pieces of data Ex: In the message MSH|^~\&|OF|Chemistry|ORT||200309060825||ORU^R01^ORU_R01|msgOF105|T|2.5|123||||USA||EN The values separator are ^~\&| ...
[ "def", "extractSeparators", "(", "self", ",", "hl7dict", ",", "msg", ")", ":", "assert", "msg", "[", ":", "self", ".", "segment_len", "]", "==", "self", ".", "header_segment", ",", "\"Message MUST start with the %s segment : Here %s\"", "%", "(", "self", ".", ...
42.928571
0.011401
def sampleLocationFromFeature(self, feature): """ Samples a location from the provided specific feature. In the case of a sphere, there is only one feature. """ if feature == "surface": coordinates = [random.gauss(0, 1.) for _ in xrange(self.dimension)] norm = sqrt(sum([coord ** 2 for c...
[ "def", "sampleLocationFromFeature", "(", "self", ",", "feature", ")", ":", "if", "feature", "==", "\"surface\"", ":", "coordinates", "=", "[", "random", ".", "gauss", "(", "0", ",", "1.", ")", "for", "_", "in", "xrange", "(", "self", ".", "dimension", ...
38.857143
0.010772
def get_instance(self, payload): """ Build an instance of OutgoingCallerIdInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.outgoing_caller_id.OutgoingCallerIdInstance :rtype: twilio.rest.api.v2010.account.outgoing_caller_id.Out...
[ "def", "get_instance", "(", "self", ",", "payload", ")", ":", "return", "OutgoingCallerIdInstance", "(", "self", ".", "_version", ",", "payload", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", ")" ]
45.3
0.010823
def _get_file(handle): '''Returns the filename of the file to read If handle is a stream, a temp file is written on disk first and its filename is returned''' if not isinstance(handle, IOBase): return handle fd, temp_file = tempfile.mkstemp(str(uuid.uuid4()), prefix='neurom-') os.close...
[ "def", "_get_file", "(", "handle", ")", ":", "if", "not", "isinstance", "(", "handle", ",", "IOBase", ")", ":", "return", "handle", "fd", ",", "temp_file", "=", "tempfile", ".", "mkstemp", "(", "str", "(", "uuid", ".", "uuid4", "(", ")", ")", ",", ...
30.785714
0.002252
def CI_calc(mean, SE, CV=1.96): """ Calculate confidence interval. :param mean: mean of data :type mean : float :param SE: standard error of data :type SE : float :param CV: critical value :type CV:float :return: confidence interval as tuple """ try: CI_down = mean -...
[ "def", "CI_calc", "(", "mean", ",", "SE", ",", "CV", "=", "1.96", ")", ":", "try", ":", "CI_down", "=", "mean", "-", "CV", "*", "SE", "CI_up", "=", "mean", "+", "CV", "*", "SE", "return", "(", "CI_down", ",", "CI_up", ")", "except", "Exception", ...
23.777778
0.002247
def vector_generate(start_pt, end_pt, normalize=False): """ Generates a vector from 2 input points. :param start_pt: start point of the vector :type start_pt: list, tuple :param end_pt: end point of the vector :type end_pt: list, tuple :param normalize: if True, the generated vector is normaliz...
[ "def", "vector_generate", "(", "start_pt", ",", "end_pt", ",", "normalize", "=", "False", ")", ":", "try", ":", "if", "start_pt", "is", "None", "or", "len", "(", "start_pt", ")", "==", "0", "or", "end_pt", "is", "None", "or", "len", "(", "end_pt", ")...
32.214286
0.002153
def alpha(returns, factor_returns, risk_free=0.0, period=DAILY, annualization=None, out=None, _beta=None): """Calculates annualized alpha. Parameters ---------- returns : pd.Series Daily returns of the strategy, noncumulative. ...
[ "def", "alpha", "(", "returns", ",", "factor_returns", ",", "risk_free", "=", "0.0", ",", "period", "=", "DAILY", ",", "annualization", "=", "None", ",", "out", "=", "None", ",", "_beta", "=", "None", ")", ":", "if", "not", "(", "isinstance", "(", "r...
32.4
0.000499
def compute_transformed(context): """Compute transformed key for opening database""" key_composite = compute_key_composite( password=context._._.password, keyfile=context._._.keyfile ) kdf_parameters = context._.header.value.dynamic_header.kdf_parameters.data.dict if context._._.tr...
[ "def", "compute_transformed", "(", "context", ")", ":", "key_composite", "=", "compute_key_composite", "(", "password", "=", "context", ".", "_", ".", "_", ".", "password", ",", "keyfile", "=", "context", ".", "_", ".", "_", ".", "keyfile", ")", "kdf_param...
36.34375
0.001675
def lockfile(path): ''' A file lock with-block helper. Args: path (str): A path to a lock file. Examples: Get the lock on a file and dostuff while having the lock:: path = '/hehe/haha.lock' with lockfile(path): dostuff() Notes: Thi...
[ "def", "lockfile", "(", "path", ")", ":", "with", "genfile", "(", "path", ")", "as", "fd", ":", "fcntl", ".", "lockf", "(", "fd", ",", "fcntl", ".", "LOCK_EX", ")", "yield", "None" ]
24.703704
0.001443
def _default(self, obj: object): """ Return a serializable version of obj. Overrides JsonObj _default method :param obj: Object to be serialized :return: Serialized version of obj """ return None if obj is JSGNull else obj.val if type(obj) is AnyType else \ JSGObject....
[ "def", "_default", "(", "self", ",", "obj", ":", "object", ")", ":", "return", "None", "if", "obj", "is", "JSGNull", "else", "obj", ".", "val", "if", "type", "(", "obj", ")", "is", "AnyType", "else", "JSGObject", ".", "_strip_nones", "(", "obj", ".",...
57.625
0.010684
def update_screen(self): """Refresh the screen. You don't need to override this except to update only small portins of the screen.""" self.clock.tick(self.FPS) pygame.display.update()
[ "def", "update_screen", "(", "self", ")", ":", "self", ".", "clock", ".", "tick", "(", "self", ".", "FPS", ")", "pygame", ".", "display", ".", "update", "(", ")" ]
51
0.014493
def _create_matrix_chart(self, data, works, output_dir): """Generates and writes to a file in `output_dir` the data used to display a matrix chart. :param data: data to derive the matrix data from :type data: `pandas.DataFrame` :param works: works to display :type works:...
[ "def", "_create_matrix_chart", "(", "self", ",", "data", ",", "works", ",", "output_dir", ")", ":", "nodes", "=", "[", "{", "'work'", ":", "work", ",", "'group'", ":", "1", "}", "for", "work", "in", "works", "]", "weights", "=", "data", ".", "stack",...
43.64
0.001794
def get_audits(): """Get Apache hardening config audits. :returns: dictionary of audits """ if subprocess.call(['which', 'apache2'], stdout=subprocess.PIPE) != 0: log("Apache server does not appear to be installed on this node - " "skipping apache hardening", level=INFO) re...
[ "def", "get_audits", "(", ")", ":", "if", "subprocess", ".", "call", "(", "[", "'which'", ",", "'apache2'", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "!=", "0", ":", "log", "(", "\"Apache server does not appear to be installed on this node - \"", ...
37.541667
0.000541
def _intersection(seg1_start, seg1_end, seg2_start, seg2_end): """ Get the intersection point between two segments. The calculation is in Catestian coordinate system. :param seg1_start: A numpy array, representing one end point of a segment(e.g. segment1) segment. :param seg...
[ "def", "_intersection", "(", "seg1_start", ",", "seg1_end", ",", "seg2_start", ",", "seg2_end", ")", ":", "pa", "=", "np", ".", "array", "(", "[", "seg1_start", ",", "seg2_start", "]", ")", "pb", "=", "np", ".", "array", "(", "[", "seg1_end", ",", "s...
36.689189
0.000359
def indent_list(inlist, level): """Join a list of strings, one per line with 'level' spaces before each one""" indent = ' '*level joinstr = '\n' + indent retval = joinstr.join(inlist) return indent + retval
[ "def", "indent_list", "(", "inlist", ",", "level", ")", ":", "indent", "=", "' '", "*", "level", "joinstr", "=", "'\\n'", "+", "indent", "retval", "=", "joinstr", ".", "join", "(", "inlist", ")", "return", "indent", "+", "retval" ]
27.625
0.008772
def copy_model_instance(obj): """ Copy Django model instance as a dictionary excluding automatically created fields like an auto-generated sequence as a primary key or an auto-created many-to-one reverse relation. :param obj: Django model object :return: copy of model instance as dictionary ...
[ "def", "copy_model_instance", "(", "obj", ")", ":", "meta", "=", "getattr", "(", "obj", ",", "'_meta'", ")", "# make pycharm happy", "# dictionary of model values excluding auto created and related fields", "return", "{", "f", ".", "name", ":", "getattr", "(", "obj", ...
41.214286
0.001695
def write_model(self, file, model, pretty=False): """Write a given model to file. Args: file: File-like object open for writing. model: Instance of :class:`NativeModel` to write. pretty: Whether to format the XML output for readability. """ ET.registe...
[ "def", "write_model", "(", "self", ",", "file", ",", "model", ",", "pretty", "=", "False", ")", ":", "ET", ".", "register_namespace", "(", "'mathml'", ",", "MATHML_NS", ")", "ET", ".", "register_namespace", "(", "'xhtml'", ",", "XHTML_NS", ")", "ET", "."...
43.555102
0.000183
def _start_instance(self): """Start the instance.""" instance = self._get_instance() instance.start() self._wait_on_instance('running', self.timeout)
[ "def", "_start_instance", "(", "self", ")", ":", "instance", "=", "self", ".", "_get_instance", "(", ")", "instance", ".", "start", "(", ")", "self", ".", "_wait_on_instance", "(", "'running'", ",", "self", ".", "timeout", ")" ]
35.4
0.01105
def save(self, file_tag='2016', add_header='N'): """ save table to folder in appropriate files NOTE - ONLY APPEND AT THIS STAGE - THEN USE DATABASE """ fname = self.get_filename(file_tag) with open(fname, 'a') as f: if add_header == 'Y': f.writ...
[ "def", "save", "(", "self", ",", "file_tag", "=", "'2016'", ",", "add_header", "=", "'N'", ")", ":", "fname", "=", "self", ".", "get_filename", "(", "file_tag", ")", "with", "open", "(", "fname", ",", "'a'", ")", "as", "f", ":", "if", "add_header", ...
35.333333
0.011494
def update_media_assetfile(access_token, parent_asset_id, asset_id, content_length, name): '''Update Media Service Asset File. Args: access_token (str): A valid Azure authentication token. parent_asset_id (str): A Media Service Asset Parent Asset ID. asset_id (str): A Media Service Asse...
[ "def", "update_media_assetfile", "(", "access_token", ",", "parent_asset_id", ",", "asset_id", ",", "content_length", ",", "name", ")", ":", "path", "=", "'/Files'", "full_path", "=", "''", ".", "join", "(", "[", "path", ",", "\"('\"", ",", "asset_id", ",", ...
38.4
0.010163
def route(origin, destination, city_origin='Dresden', city_destination='Dresden', time=None, deparr='dep', eduroam=False, recommendations=False, *, raw=False): """ VVO Online EFA TripRequest (GET http://efa.vvo-online.de:8080/dvb/XML_TRIP_REQUEST2) :param origin: Origin of route :param de...
[ "def", "route", "(", "origin", ",", "destination", ",", "city_origin", "=", "'Dresden'", ",", "city_destination", "=", "'Dresden'", ",", "time", "=", "None", ",", "deparr", "=", "'dep'", ",", "eduroam", "=", "False", ",", "recommendations", "=", "False", "...
36.057471
0.001862
def parse_python_version(output): """Parse a Python version output returned by `python --version`. Return a dict with three keys: major, minor, and micro. Each value is a string containing a version part. Note: The micro part would be `'0'` if it's missing from the input string. """ version_li...
[ "def", "parse_python_version", "(", "output", ")", ":", "version_line", "=", "output", ".", "split", "(", "\"\\n\"", ",", "1", ")", "[", "0", "]", "version_pattern", "=", "re", ".", "compile", "(", "r\"\"\"\n ^ # Beginning of line.\n ...
36.483871
0.000861
def get_cmsg(emsg): """Get protobuf for a given EMsg :param emsg: EMsg :type emsg: :class:`steam.enums.emsg.EMsg`, :class:`int` :return: protobuf message """ if not isinstance(emsg, EMsg): emsg = EMsg(emsg) if emsg in cmsg_lookup_predefined: return cmsg_lookup_predefined[em...
[ "def", "get_cmsg", "(", "emsg", ")", ":", "if", "not", "isinstance", "(", "emsg", ",", "EMsg", ")", ":", "emsg", "=", "EMsg", "(", "emsg", ")", "if", "emsg", "in", "cmsg_lookup_predefined", ":", "return", "cmsg_lookup_predefined", "[", "emsg", "]", "else...
29
0.001757
def get_results(self, client): """ Returns a result. """ data = self._request('GET', '/results/{}'.format(client)) return data.json()
[ "def", "get_results", "(", "self", ",", "client", ")", ":", "data", "=", "self", ".", "_request", "(", "'GET'", ",", "'/results/{}'", ".", "format", "(", "client", ")", ")", "return", "data", ".", "json", "(", ")" ]
28
0.011561
def delete_vector(self, hash_name, bucket_keys, data): """ Deletes vector and JSON-serializable data in buckets with specified keys. """ lsh_keys = [self._format_mongo_key(hash_name, key) for key in bucket_keys] self.mongo_object.remove({'lsh': {'$in': lsh_key...
[ "def", "delete_vector", "(", "self", ",", "hash_name", ",", "bucket_keys", ",", "data", ")", ":", "lsh_keys", "=", "[", "self", ".", "_format_mongo_key", "(", "hash_name", ",", "key", ")", "for", "key", "in", "bucket_keys", "]", "self", ".", "mongo_object"...
45.625
0.008065
def load_blind(self, item): """Load blind from JSON.""" blind = Blind.from_config(self.pyvlx, item) self.add(blind)
[ "def", "load_blind", "(", "self", ",", "item", ")", ":", "blind", "=", "Blind", ".", "from_config", "(", "self", ".", "pyvlx", ",", "item", ")", "self", ".", "add", "(", "blind", ")" ]
34
0.014388
def bootstrap(nside, rand, nbar, *data): """ This function will bootstrap data based on the sky coverage of rand. It is different from bootstrap in the traditional sense, but for correlation functions it gives the correct answer with less computation. nbar : number density of rand, used to ...
[ "def", "bootstrap", "(", "nside", ",", "rand", ",", "nbar", ",", "*", "data", ")", ":", "def", "split", "(", "data", ",", "indices", ",", "axis", ")", ":", "\"\"\" This function splits array. It fixes the bug\n in numpy that zero length array are improperly h...
30.955056
0.002462
def zrange(self, key, start=0, stop=-1, with_scores=False): """Returns the specified range of elements in the sorted set stored at key. The elements are considered to be ordered from the lowest to the highest score. Lexicographical order is used for elements with equal score. Se...
[ "def", "zrange", "(", "self", ",", "key", ",", "start", "=", "0", ",", "stop", "=", "-", "1", ",", "with_scores", "=", "False", ")", ":", "command", "=", "[", "b'ZRANGE'", ",", "key", ",", "start", ",", "stop", "]", "if", "with_scores", ":", "com...
46.705882
0.000822
def fullLoad(self): """Parse all the directories in the PE file.""" self._parseDirectories(self.ntHeaders.optionalHeader.dataDirectory, self.PE_TYPE)
[ "def", "fullLoad", "(", "self", ")", ":", "self", ".", "_parseDirectories", "(", "self", ".", "ntHeaders", ".", "optionalHeader", ".", "dataDirectory", ",", "self", ".", "PE_TYPE", ")" ]
54.333333
0.018182
def download(directory, filename): """Download (and unzip) a file from the MNIST dataset if not already done.""" filepath = os.path.join(directory, filename) if tf.gfile.Exists(filepath): return filepath if not tf.gfile.Exists(directory): tf.gfile.MakeDirs(directory) url = 'http://yann.lecun.com/exdb/...
[ "def", "download", "(", "directory", ",", "filename", ")", ":", "filepath", "=", "os", ".", "path", ".", "join", "(", "directory", ",", "filename", ")", "if", "tf", ".", "gfile", ".", "Exists", "(", "filepath", ")", ":", "return", "filepath", "if", "...
42.0625
0.018895
def map_trips( feed: "Feed", trip_ids: List[str], color_palette: List[str] = cs.COLORS_SET2, *, include_stops: bool = True, ): """ Return a Folium map showing the given trips and (optionally) their stops. Parameters ---------- feed : Feed trip_ids : list IDs of t...
[ "def", "map_trips", "(", "feed", ":", "\"Feed\"", ",", "trip_ids", ":", "List", "[", "str", "]", ",", "color_palette", ":", "List", "[", "str", "]", "=", "cs", ".", "COLORS_SET2", ",", "*", ",", "include_stops", ":", "bool", "=", "True", ",", ")", ...
27.982143
0.000308
def migrate(ctx,): """Migrate an old loqusdb instance to 1.0 """ adapter = ctx.obj['adapter'] start_time = datetime.now() nr_updated = migrate_database(adapter) LOG.info("All variants updated, time to complete migration: {}".format( datetime.now() - start_time)) LOG.in...
[ "def", "migrate", "(", "ctx", ",", ")", ":", "adapter", "=", "ctx", ".", "obj", "[", "'adapter'", "]", "start_time", "=", "datetime", ".", "now", "(", ")", "nr_updated", "=", "migrate_database", "(", "adapter", ")", "LOG", ".", "info", "(", "\"All vari...
30.083333
0.010753
def get_config_file(): # type: () -> AnyStr """Get model configuration file name from argv""" parser = argparse.ArgumentParser(description="Read configuration file.") parser.add_argument('-ini', help="Full path of configuration file") args = parser.parse_args() ini_file = args.ini if not Fil...
[ "def", "get_config_file", "(", ")", ":", "# type: () -> AnyStr", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"Read configuration file.\"", ")", "parser", ".", "add_argument", "(", "'-ini'", ",", "help", "=", "\"Full path of configurati...
40.636364
0.002188
def to_graphviz(booster, fmap='', num_trees=0, rankdir='UT', yes_color='#0000FF', no_color='#FF0000', condition_node_params=None, leaf_node_params=None, **kwargs): """Convert specified tree to graphviz instance. IPython can automatically plot the returned graphiz instance. Otherw...
[ "def", "to_graphviz", "(", "booster", ",", "fmap", "=", "''", ",", "num_trees", "=", "0", ",", "rankdir", "=", "'UT'", ",", "yes_color", "=", "'#0000FF'", ",", "no_color", "=", "'#FF0000'", ",", "condition_node_params", "=", "None", ",", "leaf_node_params", ...
32.155844
0.000784
def example(n): """ Data generator for the one machine scheduling problem. """ J,p,r,d,w = multidict({ 1:[1,4,0,3], 2:[4,0,0,1], 3:[2,2,0,2], 4:[3,4,0,3], 5:[1,1,0,1], 6:[4,5,0,2], }) return J,p,r,d,w
[ "def", "example", "(", "n", ")", ":", "J", ",", "p", ",", "r", ",", "d", ",", "w", "=", "multidict", "(", "{", "1", ":", "[", "1", ",", "4", ",", "0", ",", "3", "]", ",", "2", ":", "[", "4", ",", "0", ",", "0", ",", "1", "]", ",", ...
20.307692
0.119565
def update_hosts(self, host_names): """Primarily for puppet-unity use. Update the hosts for the lun if needed. :param host_names: specify the new hosts which access the LUN. """ if self.host_access: curr_hosts = [access.host.name for access in self.host_access] ...
[ "def", "update_hosts", "(", "self", ",", "host_names", ")", ":", "if", "self", ".", "host_access", ":", "curr_hosts", "=", "[", "access", ".", "host", ".", "name", "for", "access", "in", "self", ".", "host_access", "]", "else", ":", "curr_hosts", "=", ...
32.962963
0.002183
def is_comparable_type(var, type_): """ Check to see if `var` is an instance of known compatible types for `type_` Args: var (?): type_ (?): Returns: bool: CommandLine: python -m utool.util_type is_comparable_type --show Example: >>> # DISABLE_DOCTEST ...
[ "def", "is_comparable_type", "(", "var", ",", "type_", ")", ":", "other_types", "=", "COMPARABLE_TYPES", ".", "get", "(", "type_", ",", "type_", ")", "return", "isinstance", "(", "var", ",", "other_types", ")" ]
28.8
0.00112
def _draw_uniform(self,num_reals=1): """ Draw parameter realizations from a (log10) uniform distribution described by the parameter bounds. Respect Log10 transformation Parameters ---------- num_reals : int number of realizations to generate """ if ...
[ "def", "_draw_uniform", "(", "self", ",", "num_reals", "=", "1", ")", ":", "if", "not", "self", ".", "istransformed", ":", "self", ".", "_transform", "(", ")", "self", ".", "loc", "[", ":", ",", ":", "]", "=", "np", ".", "NaN", "self", ".", "drop...
37.48
0.008325
def extract_columns(data, *cols): """Extract columns specified in the argument list. >>> chart_data.extract_columns([[10,20], [30,40], [50,60]], 0) [[10],[30],[50]] """ out = [] try: # for python 2.2: # return [ [r[c] for c in cols] for r in data] for r in data: col = []...
[ "def", "extract_columns", "(", "data", ",", "*", "cols", ")", ":", "out", "=", "[", "]", "try", ":", "# for python 2.2:", "# return [ [r[c] for c in cols] for r in data]", "for", "r", "in", "data", ":", "col", "=", "[", "]", "for", "c", "in", "cols", ":", ...
27
0.001988
def delete_webhook(self, webhook): """ Deletes the specified webhook from this policy. """ return self.manager.delete_webhook(self.scaling_group, self, webhook)
[ "def", "delete_webhook", "(", "self", ",", "webhook", ")", ":", "return", "self", ".", "manager", ".", "delete_webhook", "(", "self", ".", "scaling_group", ",", "self", ",", "webhook", ")" ]
37.6
0.010417
def _copy_database_data_serverside(self, source, destination, tables): """Select rows from a source database and insert them into a destination db in one query""" for table in tqdm(tables, total=len(tables), desc='Copying table data (optimized)'): self.execute('INSERT INTO {0}.{1} SELECT * F...
[ "def", "_copy_database_data_serverside", "(", "self", ",", "source", ",", "destination", ",", "tables", ")", ":", "for", "table", "in", "tqdm", "(", "tables", ",", "total", "=", "len", "(", "tables", ")", ",", "desc", "=", "'Copying table data (optimized)'", ...
92.75
0.013369
def from_jd(jd): '''Return Gregorian date in a (Y, M, D) tuple''' wjd = floor(jd - 0.5) + 0.5 depoch = wjd - EPOCH quadricent = floor(depoch / INTERCALATION_CYCLE_DAYS) dqc = depoch % INTERCALATION_CYCLE_DAYS cent = floor(dqc / LEAP_SUPPRESSION_DAYS) dcent = dqc % LEAP_SUPPRESSION_DAYS ...
[ "def", "from_jd", "(", "jd", ")", ":", "wjd", "=", "floor", "(", "jd", "-", "0.5", ")", "+", "0.5", "depoch", "=", "wjd", "-", "EPOCH", "quadricent", "=", "floor", "(", "depoch", "/", "INTERCALATION_CYCLE_DAYS", ")", "dqc", "=", "depoch", "%", "INTER...
23.692308
0.00104
def param_search(estimator, param_dict, n_iter=None, seed=None): """ Generator for cloned copies of `estimator` set with parameters as specified by `param_dict`. `param_dict` can contain either lists of parameter values (grid search) or a scipy distribution function to be sampled from. If distributi...
[ "def", "param_search", "(", "estimator", ",", "param_dict", ",", "n_iter", "=", "None", ",", "seed", "=", "None", ")", ":", "if", "n_iter", "is", "None", ":", "param_iter", "=", "ParameterGrid", "(", "param_dict", ")", "else", ":", "param_iter", "=", "Pa...
30.705882
0.000929
def execute_replay() -> None: """ Execute all commands. For every command that is found in replay/toDo, execute each of them and move the file to the replay/archive directory. """ files = glob.glob('./replay/toDo/*') sorted_files = sorted(files, key=os.path.getctime) if not sorted_file...
[ "def", "execute_replay", "(", ")", "->", "None", ":", "files", "=", "glob", ".", "glob", "(", "'./replay/toDo/*'", ")", "sorted_files", "=", "sorted", "(", "files", ",", "key", "=", "os", ".", "path", ".", "getctime", ")", "if", "not", "sorted_files", ...
41.666667
0.000978
def monthly(self): """ Access the monthly :returns: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyList :rtype: twilio.rest.api.v2010.account.usage.record.monthly.MonthlyList """ if self._monthly is None: self._monthly = MonthlyList(self._version, ...
[ "def", "monthly", "(", "self", ")", ":", "if", "self", ".", "_monthly", "is", "None", ":", "self", ".", "_monthly", "=", "MonthlyList", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]", ",", ")"...
38.4
0.010178
def accepts_valid_urls(func): """Return a wrapper that runs given method only for valid URLs. :param func: a method to be wrapped :returns: a wrapper that adds argument validation """ @functools.wraps(func) def wrapper(obj, urls, *args, **kwargs): """Run the function and return a value ...
[ "def", "accepts_valid_urls", "(", "func", ")", ":", "@", "functools", ".", "wraps", "(", "func", ")", "def", "wrapper", "(", "obj", ",", "urls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"Run the function and return a value for valid URLs.\n\n...
39.363636
0.001127
def as_date(dat): """Return the RFC3339 UTC string representation of the given date and time. Args: dat (:py:class:`datetime.date`): the object/type to be serialized. Raises: TypeError: when ``o`` is not an instance of ``datetime.date``. Returns: (str) JSON seriali...
[ "def", "as_date", "(", "dat", ")", ":", "LOGGER", ".", "debug", "(", "'as_date(%s)'", ",", "dat", ")", "return", "strict_rfc3339", ".", "timestamp_to_rfc3339_utcoffset", "(", "calendar", ".", "timegm", "(", "dat", ".", "timetuple", "(", ")", ")", ")" ]
28.352941
0.002008
def process_sels(self): """ A redefined version of :func:`RC2.process_sels`. The only modification affects the clauses whose weight after splitting becomes less than the weight of the current optimization level. Such clauses are deactivated and to be r...
[ "def", "process_sels", "(", "self", ")", ":", "# new relaxation variables", "self", ".", "rels", "=", "[", "]", "# selectors that should be deactivated (but not removed completely)", "to_deactivate", "=", "set", "(", "[", "]", ")", "for", "l", "in", "self", ".", "...
38.902439
0.001835
def element_focused(self, id_): """ Assert the element is focused. """ try: elem = world.browser.find_element_by_id(id_) except NoSuchElementException: raise AssertionError("Element with ID '{}' not found.".format(id_)) focused = world.browser.switch_to.active_element # El...
[ "def", "element_focused", "(", "self", ",", "id_", ")", ":", "try", ":", "elem", "=", "world", ".", "browser", ".", "find_element_by_id", "(", "id_", ")", "except", "NoSuchElementException", ":", "raise", "AssertionError", "(", "\"Element with ID '{}' not found.\"...
30.533333
0.002119
def to_file(self, slug, folderpath=None, header=None, footer=None): """ Writes the html report to a file from the report stack """ if folderpath is None: if self.report_path is None: self.err( "Please set the report_path parameter or pass a...
[ "def", "to_file", "(", "self", ",", "slug", ",", "folderpath", "=", "None", ",", "header", "=", "None", ",", "footer", "=", "None", ")", ":", "if", "folderpath", "is", "None", ":", "if", "self", ".", "report_path", "is", "None", ":", "self", ".", "...
39.151515
0.002266
def get_available_extension(name, user=None, host=None, port=None, maintenance_db=None, password=None, runas=None): ''' Get info about an availa...
[ "def", "get_available_extension", "(", "name", ",", "user", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ",", "maintenance_db", "=", "None", ",", "password", "=", "None", ",", "runas", "=", "None", ")", ":", "return", "available_exten...
32.086957
0.001316
def nscan_minmax_frontiers(y0_frontier_lower, y0_frontier_upper, resize=False): """Compute valid scan range for provided y0_frontier values. Parameters ---------- y0_frontier_lower : float Ordinate of the lower frontier. y0_frontier_upper : float Ordinate o...
[ "def", "nscan_minmax_frontiers", "(", "y0_frontier_lower", ",", "y0_frontier_upper", ",", "resize", "=", "False", ")", ":", "fraction_pixel", "=", "y0_frontier_lower", "-", "int", "(", "y0_frontier_lower", ")", "if", "fraction_pixel", ">", "0.0", ":", "nscan_min", ...
31.704545
0.000695
def brozzler_ensure_tables(argv=None): ''' Creates rethinkdb tables if they don't already exist. Brozzler (brozzler-worker, brozzler-new-job, etc) normally creates the tables it needs on demand at startup, but if multiple instances are starting up at the same time, you can end up with duplicate brok...
[ "def", "brozzler_ensure_tables", "(", "argv", "=", "None", ")", ":", "argv", "=", "argv", "or", "sys", ".", "argv", "arg_parser", "=", "argparse", ".", "ArgumentParser", "(", "prog", "=", "os", ".", "path", ".", "basename", "(", "argv", "[", "0", "]", ...
35.96
0.001083
def create_run(cls, *args, **kwargs): """ :return: a delegator function that calls the ``cls`` constructor whose arguments being a seed tuple followed by supplied ``*args`` and ``**kwargs``, then returns the object's ``run`` method. By default, a thread wrapping that ``run`` method ...
[ "def", "create_run", "(", "cls", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "f", "(", "seed_tuple", ")", ":", "j", "=", "cls", "(", "seed_tuple", ",", "*", "args", ",", "*", "*", "kwargs", ")", "return", "j", ".", "run", "retur...
36.083333
0.009009
def set_rcParams_scanpy(fontsize=14, color_map=None): """Set matplotlib.rcParams to Scanpy defaults. Call this through `settings.set_figure_params`. """ # figure rcParams['figure.figsize'] = (4, 4) rcParams['figure.subplot.left'] = 0.18 rcParams['figure.subplot.right'] = 0.96 rcParams[...
[ "def", "set_rcParams_scanpy", "(", "fontsize", "=", "14", ",", "color_map", "=", "None", ")", ":", "# figure", "rcParams", "[", "'figure.figsize'", "]", "=", "(", "4", ",", "4", ")", "rcParams", "[", "'figure.subplot.left'", "]", "=", "0.18", "rcParams", "...
28.087719
0.001207
def getDatabases(self): """Returns list of databases. @return: List of databases. """ cur = self._conn.cursor() cur.execute("""SHOW DATABASES;""") rows = cur.fetchall() if rows: return [row[0] for row in rows] else: ...
[ "def", "getDatabases", "(", "self", ")", ":", "cur", "=", "self", ".", "_conn", ".", "cursor", "(", ")", "cur", ".", "execute", "(", "\"\"\"SHOW DATABASES;\"\"\"", ")", "rows", "=", "cur", ".", "fetchall", "(", ")", "if", "rows", ":", "return", "[", ...
24.538462
0.012085
def read_files(path, verbose=True): """Read multiple ``CTfile`` formatted files. :param str path: Path to ``CTfile``. :return: Subclass of :class:`~ctfile.ctfile.CTfile`. :rtype: :class:`~ctfile.ctfile.CTfile` """ for filehandle in filehandles(path, verbose=verbose): yield CTfile.l...
[ "def", "read_files", "(", "path", ",", "verbose", "=", "True", ")", ":", "for", "filehandle", "in", "filehandles", "(", "path", ",", "verbose", "=", "verbose", ")", ":", "yield", "CTfile", ".", "load", "(", "filehandle", ")" ]
36.333333
0.008955
def p2pkh_input_and_witness(outpoint, sig, pubkey, sequence=0xFFFFFFFE): ''' OutPoint, hex_string, hex_string, int -> (TxIn, InputWitness) Create a signed legacy TxIn from a p2pkh prevout Create an empty InputWitness for it Useful for transactions spending some witness and some legacy prevouts '...
[ "def", "p2pkh_input_and_witness", "(", "outpoint", ",", "sig", ",", "pubkey", ",", "sequence", "=", "0xFFFFFFFE", ")", ":", "stack_script", "=", "'{sig} {pk}'", ".", "format", "(", "sig", "=", "sig", ",", "pk", "=", "pubkey", ")", "return", "tb", ".", "m...
42.923077
0.001754
def require_instance(obj, types=None, name=None, type_name=None, truncate_at=80): """ Raise an exception if obj is not an instance of one of the specified types. Similarly to isinstance, 'types' may be either a single type or a tuple of types. If name or type_name is provided, it is used in the ex...
[ "def", "require_instance", "(", "obj", ",", "types", "=", "None", ",", "name", "=", "None", ",", "type_name", "=", "None", ",", "truncate_at", "=", "80", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "types", ")", ":", "obj_string", "=", "str...
42.666667
0.00191
def create_dataclass_loader(cls, registry, field_getters): """create a loader for a dataclass type""" fields = cls.__dataclass_fields__ item_loaders = map(registry, map(attrgetter('type'), fields.values())) getters = map(field_getters.__getitem__, fields) loaders = list(starmap(compose, zip(item_loa...
[ "def", "create_dataclass_loader", "(", "cls", ",", "registry", ",", "field_getters", ")", ":", "fields", "=", "cls", ".", "__dataclass_fields__", "item_loaders", "=", "map", "(", "registry", ",", "map", "(", "attrgetter", "(", "'type'", ")", ",", "fields", "...
37.818182
0.002347
def write(self, filename, append=True): """Write the parameters to a file as a human-readable series of dicts. :type filename: str :param filename: File to write to :type append: bool :param append: Append to already existing file or over-write. """ header = ' '....
[ "def", "write", "(", "self", ",", "filename", ",", "append", "=", "True", ")", ":", "header", "=", "' '", ".", "join", "(", "[", "'# User:'", ",", "getpass", ".", "getuser", "(", ")", ",", "'\\n# Creation date:'", ",", "str", "(", "UTCDateTime", "(", ...
35.043478
0.002415
def find_inouts_st(voxel_grid, datapts, **kwargs): """ Single-threaded ins and outs finding (default) :param voxel_grid: voxel grid :param datapts: data points :return: in-outs """ tol = kwargs.get('tol', 10e-8) filled = [0 for _ in range(len(voxel_grid))] for idx, bb in enumerate(voxel...
[ "def", "find_inouts_st", "(", "voxel_grid", ",", "datapts", ",", "*", "*", "kwargs", ")", ":", "tol", "=", "kwargs", ".", "get", "(", "'tol'", ",", "10e-8", ")", "filled", "=", "[", "0", "for", "_", "in", "range", "(", "len", "(", "voxel_grid", ")"...
32
0.002169
def fit_with_hmc(model, observed_time_series, num_results=100, num_warmup_steps=50, num_leapfrog_steps=15, initial_state=None, initial_step_size=None, chain_batch_shape=(), num_variati...
[ "def", "fit_with_hmc", "(", "model", ",", "observed_time_series", ",", "num_results", "=", "100", ",", "num_warmup_steps", "=", "50", ",", "num_leapfrog_steps", "=", "15", ",", "initial_state", "=", "None", ",", "initial_step_size", "=", "None", ",", "chain_batc...
45.284585
0.001537
def setportprio(self, port, prio): """ Set port priority value. """ _runshell([brctlexe, 'setportprio', self.name, port, str(prio)], "Could not set priority in port %s in %s." % (port, self.name))
[ "def", "setportprio", "(", "self", ",", "port", ",", "prio", ")", ":", "_runshell", "(", "[", "brctlexe", ",", "'setportprio'", ",", "self", ".", "name", ",", "port", ",", "str", "(", "prio", ")", "]", ",", "\"Could not set priority in port %s in %s.\"", "...
55.25
0.013393
def _find_dr_record_by_name(vd, path, encoding): # type: (headervd.PrimaryOrSupplementaryVD, bytes, str) -> dr.DirectoryRecord ''' An internal function to find an directory record on the ISO given an ISO or Joliet path. If the entry is found, it returns the directory record object corresponding to ...
[ "def", "_find_dr_record_by_name", "(", "vd", ",", "path", ",", "encoding", ")", ":", "# type: (headervd.PrimaryOrSupplementaryVD, bytes, str) -> dr.DirectoryRecord", "if", "not", "utils", ".", "starts_with_slash", "(", "path", ")", ":", "raise", "pycdlibexception", ".", ...
33.202703
0.001581
def rightjoin(left, right, key=None, lkey=None, rkey=None, missing=None, presorted=False, buffersize=None, tempdir=None, cache=True, lprefix=None, rprefix=None): """ Perform a right outer join on the given tables. E.g.:: >>> import petl as etl >>> table1 = [['id', 'c...
[ "def", "rightjoin", "(", "left", ",", "right", ",", "key", "=", "None", ",", "lkey", "=", "None", ",", "rkey", "=", "None", ",", "missing", "=", "None", ",", "presorted", "=", "False", ",", "buffersize", "=", "None", ",", "tempdir", "=", "None", ",...
40.911111
0.000531
def send_mail(subject, body_text, addr_from, recipient_list, fail_silently=False, auth_user=None, auth_password=None, attachments=None, body_html=None, html_message=None, connection=None, headers=None): """ Sends a multipart email containing text and html versions ...
[ "def", "send_mail", "(", "subject", ",", "body_text", ",", "addr_from", ",", "recipient_list", ",", "fail_silently", "=", "False", ",", "auth_user", "=", "None", ",", "auth_password", "=", "None", ",", "attachments", "=", "None", ",", "body_html", "=", "None...
45.408602
0.000232
def delete(self, name, kind=None): """Removes an input from the collection. :param `kind`: The kind of input: - "ad": Active Directory - "monitor": Files and directories - "registry": Windows Registry - "script": Scripts - "splunktcp": TC...
[ "def", "delete", "(", "self", ",", "name", ",", "kind", "=", "None", ")", ":", "if", "kind", "is", "None", ":", "self", ".", "service", ".", "delete", "(", "self", "[", "name", "]", ".", "path", ")", "else", ":", "self", ".", "service", ".", "d...
23.916667
0.002232
def receiveVolumeInfo(self, paths): """ Return Context Manager for a file-like (stream) object to store volume info. """ path = self.selectReceivePath(paths) path = path + Store.theInfoExtension if Store.skipDryRun(logger, self.dryrun)("receive info to %s", path): return Non...
[ "def", "receiveVolumeInfo", "(", "self", ",", "paths", ")", ":", "path", "=", "self", ".", "selectReceivePath", "(", "paths", ")", "path", "=", "path", "+", "Store", ".", "theInfoExtension", "if", "Store", ".", "skipDryRun", "(", "logger", ",", "self", "...
38.333333
0.008499
def pubkey(self): """If the :py:obj:`PGPKey` object is a private key, this method returns a corresponding public key object with all the trimmings. Otherwise, returns ``None`` """ if not self.is_public: if self._sibling is None or isinstance(self._sibling, weakref.ref): ...
[ "def", "pubkey", "(", "self", ")", ":", "if", "not", "self", ".", "is_public", ":", "if", "self", ".", "_sibling", "is", "None", "or", "isinstance", "(", "self", ".", "_sibling", ",", "weakref", ".", "ref", ")", ":", "# create a new key shell", "pub", ...
38.46875
0.002377
def parallaxMaxError(G, vmini, extension=0.0): """ Calculate the maximum parallax error from G and (V-I). This correspond to the sky regions with the largest astrometric errors. At the bright end the parallax error is at least 14 muas due to the gating scheme. Parameters ---------- G - Value(s) of ...
[ "def", "parallaxMaxError", "(", "G", ",", "vmini", ",", "extension", "=", "0.0", ")", ":", "errors", "=", "_astrometricErrorFactors", "[", "\"parallax\"", "]", ".", "max", "(", ")", "*", "parallaxErrorSkyAvg", "(", "G", ",", "vmini", ",", "extension", "=",...
29.038462
0.015385
def get_capabilities(image=None): ''' List all capabilities on the system Args: image (Optional[str]): The path to the root directory of an offline Windows image. If `None` is passed, the running operating system is targeted. Default is None. Raises: NotImplemen...
[ "def", "get_capabilities", "(", "image", "=", "None", ")", ":", "if", "salt", ".", "utils", ".", "versions", ".", "version_cmp", "(", "__grains__", "[", "'osversion'", "]", ",", "'10'", ")", "==", "-", "1", ":", "raise", "NotImplementedError", "(", "'`in...
29.921053
0.001704
def broadcast(self, from_client, message, valid_till=None, push_data=None): """ 发送广播消息,只能以系统会话名义发送。全部用户都会收到此消息,不论是否在此会话中。 :param from_client: 发送者 id :param message: 消息内容 :param valid_till: 指定广播消息过期时间 :param puhs_data: 推送消息内容,参考:https://url.leanapp.cn/pushData """...
[ "def", "broadcast", "(", "self", ",", "from_client", ",", "message", ",", "valid_till", "=", "None", ",", "push_data", "=", "None", ")", ":", "if", "isinstance", "(", "message", ",", "dict", ")", ":", "message", "=", "json", ".", "dumps", "(", "message...
35.347826
0.002395
def replace_suffix (name, new_suffix): """ Replaces the suffix of name by new_suffix. If no suffix exists, the new one is added. """ assert isinstance(name, basestring) assert isinstance(new_suffix, basestring) split = os.path.splitext (name) return split [0] + new_suffix
[ "def", "replace_suffix", "(", "name", ",", "new_suffix", ")", ":", "assert", "isinstance", "(", "name", ",", "basestring", ")", "assert", "isinstance", "(", "new_suffix", ",", "basestring", ")", "split", "=", "os", ".", "path", ".", "splitext", "(", "name"...
37.125
0.013158
def peek_lock_subscription_message(self, topic_name, subscription_name, timeout='60'): ''' This operation is used to atomically retrieve and lock a message for processing. The message is guaranteed not to be delivered to other receivers during the l...
[ "def", "peek_lock_subscription_message", "(", "self", ",", "topic_name", ",", "subscription_name", ",", "timeout", "=", "'60'", ")", ":", "_validate_not_none", "(", "'topic_name'", ",", "topic_name", ")", "_validate_not_none", "(", "'subscription_name'", ",", "subscri...
50.72973
0.002091