text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def send_result(job_id, api_key=None): ''' Send results to where requested. If api_key is provided, it is used, otherwiese the key from the job will be used. ''' job_dict = db.get_job(job_id) result_url = job_dict.get('result_url') if not result_url: # A job with an API key (for u...
[ "def", "send_result", "(", "job_id", ",", "api_key", "=", "None", ")", ":", "job_dict", "=", "db", ".", "get_job", "(", "job_id", ")", "result_url", "=", "job_dict", ".", "get", "(", "'result_url'", ")", "if", "not", "result_url", ":", "# A job with an API...
27.5
0.000878
def get_channelstate_by_canonical_identifier( chain_state: ChainState, canonical_identifier: CanonicalIdentifier, ) -> Optional[NettingChannelState]: """ Return the NettingChannelState if it exists, None otherwise. """ token_network = get_token_network_by_identifier( chain_state, ...
[ "def", "get_channelstate_by_canonical_identifier", "(", "chain_state", ":", "ChainState", ",", "canonical_identifier", ":", "CanonicalIdentifier", ",", ")", "->", "Optional", "[", "NettingChannelState", "]", ":", "token_network", "=", "get_token_network_by_identifier", "(",...
34.176471
0.001675
def _add_file(self, path, **params): """ Attempt to add a file to the system monitoring mechanism. """ log = self._getparam('log', self._discard, **params) fd = None try: fd = os.open(path, os.O_RDONLY) except Exception as e: if not self.paths[...
[ "def", "_add_file", "(", "self", ",", "path", ",", "*", "*", "params", ")", ":", "log", "=", "self", ".", "_getparam", "(", "'log'", ",", "self", ".", "_discard", ",", "*", "*", "params", ")", "fd", "=", "None", "try", ":", "fd", "=", "os", "."...
42.432836
0.00825
def _process_methods(self, req, resp, resource): """Adds the Access-Control-Allow-Methods header to the response, using the cors settings to determine which methods are allowed. """ requested_method = self._get_requested_method(req) if not requested_method: return Fal...
[ "def", "_process_methods", "(", "self", ",", "req", ",", "resp", ",", "resource", ")", ":", "requested_method", "=", "self", ".", "_get_requested_method", "(", "req", ")", "if", "not", "requested_method", ":", "return", "False", "if", "self", ".", "_cors_con...
44.384615
0.001696
def keywords(self) -> Set[str]: """A set of all keywords of all handled devices. In addition to attribute access via device names, |Nodes| and |Elements| objects allow for attribute access via keywords, allowing for an efficient search of certain groups of devices. Let us use th...
[ "def", "keywords", "(", "self", ")", "->", "Set", "[", "str", "]", ":", "return", "set", "(", "keyword", "for", "device", "in", "self", "for", "keyword", "in", "device", ".", "keywords", "if", "keyword", "not", "in", "self", ".", "_shadowed_keywords", ...
40.178571
0.000868
def tqdm_hook(t): """ Wraps tqdm instance. Don't forget to close() or __exit__() the tqdm instance once you're done with it (easiest using `with` syntax). Example ------- >>> with tqdm(...) as t: ... reporthook = my_hook(t) ... urllib.urlretrieve(..., reporthook=reporthook) ...
[ "def", "tqdm_hook", "(", "t", ")", ":", "last_b", "=", "[", "0", "]", "def", "update_to", "(", "b", "=", "1", ",", "bsize", "=", "1", ",", "tsize", "=", "None", ")", ":", "\"\"\"\n b : int, optional\n Number of blocks transferred so far [defau...
28.275862
0.001179
def validate_input_format(utterance, intent): """ TODO add handling for bad input""" slots = {slot["name"] for slot in intent["slots"]} split_utt = re.split("{(.*)}", utterance) banned = set("-/\\()^%$#@~`-_=+><;:") # Banned characters for token in split_utt: if (banned & set(token)): ...
[ "def", "validate_input_format", "(", "utterance", ",", "intent", ")", ":", "slots", "=", "{", "slot", "[", "\"name\"", "]", "for", "slot", "in", "intent", "[", "\"slots\"", "]", "}", "split_utt", "=", "re", ".", "split", "(", "\"{(.*)}\"", ",", "utteranc...
38.043478
0.008919
def cmsearch_from_alignment(aln, structure_string, seqs, moltype, cutoff=0.0,\ refine=False,params=None): """Uses cmbuild to build a CM file, then cmsearch to find homologs. - aln: an Alignment object or something that can be used to construct one. All sequences must be the same length. ...
[ "def", "cmsearch_from_alignment", "(", "aln", ",", "structure_string", ",", "seqs", ",", "moltype", ",", "cutoff", "=", "0.0", ",", "refine", "=", "False", ",", "params", "=", "None", ")", ":", "#NOTE: Must degap seqs or Infernal well seg fault!", "seqs", "=", "...
41.035714
0.00935
def median_filter(data, mask, radius, percent=50): '''Masked median filter with octagonal shape data - array of data to be median filtered. mask - mask of significant pixels in data radius - the radius of a circle inscribed into the filtering octagon percent - conceptually, order the significant pi...
[ "def", "median_filter", "(", "data", ",", "mask", ",", "radius", ",", "percent", "=", "50", ")", ":", "if", "mask", "is", "None", ":", "mask", "=", "np", ".", "ones", "(", "data", ".", "shape", ",", "dtype", "=", "bool", ")", "if", "np", ".", "...
35.675
0.002046
def send(self, cmd="", timeout=300, wait_for_string=None, password=False): """Send the command to the device and return the output. Args: cmd (str): Command string for execution. Defaults to empty string. timeout (int): Timeout in seconds. Defaults to 300 sec (5 min) ...
[ "def", "send", "(", "self", ",", "cmd", "=", "\"\"", ",", "timeout", "=", "300", ",", "wait_for_string", "=", "None", ",", "password", "=", "False", ")", ":", "return", "self", ".", "_chain", ".", "send", "(", "cmd", ",", "timeout", ",", "wait_for_st...
44.227273
0.002012
def decode_timeseries_row(self, tsrow, tscols=None, convert_timestamp=False): """ Decodes a TsRow into a list :param tsrow: the protobuf TsRow to decode. :type tsrow: riak.pb.riak_ts_pb2.TsRow :param tscols: the protobuf TsColumn data to help decode...
[ "def", "decode_timeseries_row", "(", "self", ",", "tsrow", ",", "tscols", "=", "None", ",", "convert_timestamp", "=", "False", ")", ":", "row", "=", "[", "]", "for", "i", ",", "cell", "in", "enumerate", "(", "tsrow", ".", "cells", ")", ":", "col", "=...
42.816327
0.001398
def write_id (self): """Write ID for current URL.""" self.writeln(u"<tr>") self.writeln(u'<td>%s</td>' % self.part("id")) self.write(u"<td>%d</td></tr>" % self.stats.number)
[ "def", "write_id", "(", "self", ")", ":", "self", ".", "writeln", "(", "u\"<tr>\"", ")", "self", ".", "writeln", "(", "u'<td>%s</td>'", "%", "self", ".", "part", "(", "\"id\"", ")", ")", "self", ".", "write", "(", "u\"<td>%d</td></tr>\"", "%", "self", ...
40.2
0.014634
def PixelsHDU(model): ''' Construct the HDU containing the pixel-level light curve. ''' # Get mission cards cards = model._mission.HDUCards(model.meta, hdu=2) # Add EVEREST info cards = [] cards.append(('COMMENT', '************************')) cards.append(('COMMENT', '* EVERES...
[ "def", "PixelsHDU", "(", "model", ")", ":", "# Get mission cards", "cards", "=", "model", ".", "_mission", ".", "HDUCards", "(", "model", ".", "meta", ",", "hdu", "=", "2", ")", "# Add EVEREST info", "cards", "=", "[", "]", "cards", ".", "append", "(", ...
34.432432
0.000763
def _create_tcex_dirs(): """Create tcex.d directory and sub directories.""" dirs = ['tcex.d', 'tcex.d/data', 'tcex.d/profiles'] for d in dirs: if not os.path.isdir(d): os.makedirs(d)
[ "def", "_create_tcex_dirs", "(", ")", ":", "dirs", "=", "[", "'tcex.d'", ",", "'tcex.d/data'", ",", "'tcex.d/profiles'", "]", "for", "d", "in", "dirs", ":", "if", "not", "os", ".", "path", ".", "isdir", "(", "d", ")", ":", "os", ".", "makedirs", "(",...
32.714286
0.008511
def handle_resource_not_found(resource): """ Set resource state to ERRED and append/create "not found" error message. """ resource.set_erred() resource.runtime_state = '' message = 'Does not exist at backend.' if message not in resource.error_message: if not resource.error_message: ...
[ "def", "handle_resource_not_found", "(", "resource", ")", ":", "resource", ".", "set_erred", "(", ")", "resource", ".", "runtime_state", "=", "''", "message", "=", "'Does not exist at backend.'", "if", "message", "not", "in", "resource", ".", "error_message", ":",...
37.8
0.001721
def __imap_search(self, ** criteria_dict): """ Searches for query in the given IMAP criteria and returns the message numbers that match as a list of strings. Criteria without values (eg DELETED) should be keyword args with KEY=True, or else not passed. Criteria with values should ...
[ "def", "__imap_search", "(", "self", ",", "*", "*", "criteria_dict", ")", ":", "self", ".", "imap_connect", "(", ")", "criteria", "=", "[", "]", "for", "key", "in", "criteria_dict", ":", "if", "criteria_dict", "[", "key", "]", "is", "True", ":", "crite...
41.571429
0.000959
def wrap_with_monitor(env, video_dir): """Wrap environment with gym.Monitor. Video recording provided by Monitor requires 1) both height and width of observation to be even numbers. 2) rendering of environment Args: env: environment. video_dir: video directory. Returns: wrapped environmen...
[ "def", "wrap_with_monitor", "(", "env", ",", "video_dir", ")", ":", "env", "=", "ExtendToEvenDimentions", "(", "env", ")", "env", "=", "RenderObservations", "(", "env", ")", "# pylint: disable=redefined-variable-type", "env", "=", "gym", ".", "wrappers", ".", "M...
30.2
0.009631
def get_slotname(slot, host=None, admin_username=None, admin_password=None): ''' Get the name of a slot number in the chassis. slot The number of the slot for which to obtain the name. host The chassis host. admin_username The username used to access the chassis. admi...
[ "def", "get_slotname", "(", "slot", ",", "host", "=", "None", ",", "admin_username", "=", "None", ",", "admin_password", "=", "None", ")", ":", "slots", "=", "list_slotnames", "(", "host", "=", "host", ",", "admin_username", "=", "admin_username", ",", "ad...
27.4
0.001175
def handle_onchain_secretreveal( target_state: TargetTransferState, state_change: ContractReceiveSecretReveal, channel_state: NettingChannelState, ) -> TransitionResult[TargetTransferState]: """ Validates and handles a ContractReceiveSecretReveal state change. """ valid_secret = is_valid...
[ "def", "handle_onchain_secretreveal", "(", "target_state", ":", "TargetTransferState", ",", "state_change", ":", "ContractReceiveSecretReveal", ",", "channel_state", ":", "NettingChannelState", ",", ")", "->", "TransitionResult", "[", "TargetTransferState", "]", ":", "val...
37.083333
0.001095
def delta_encode(data, axis=-1, out=None): """Encode Delta.""" if isinstance(data, (bytes, bytearray)): data = numpy.frombuffer(data, dtype='u1') diff = numpy.diff(data, axis=0) return numpy.insert(diff, 0, data[0]).tobytes() dtype = data.dtype if dtype.kind == 'f': data...
[ "def", "delta_encode", "(", "data", ",", "axis", "=", "-", "1", ",", "out", "=", "None", ")", ":", "if", "isinstance", "(", "data", ",", "(", "bytes", ",", "bytearray", ")", ")", ":", "data", "=", "numpy", ".", "frombuffer", "(", "data", ",", "dt...
29.947368
0.001704
def garud_h(h): """Compute the H1, H12, H123 and H2/H1 statistics for detecting signatures of soft sweeps, as defined in Garud et al. (2015). Parameters ---------- h : array_like, int, shape (n_variants, n_haplotypes) Haplotype array. Returns ------- h1 : float H1 stati...
[ "def", "garud_h", "(", "h", ")", ":", "# check inputs", "h", "=", "HaplotypeArray", "(", "h", ",", "copy", "=", "False", ")", "# compute haplotype frequencies", "f", "=", "h", ".", "distinct_frequencies", "(", ")", "# compute H1", "h1", "=", "np", ".", "su...
25.545455
0.000857
def maybe_infer_dtype_type(element): """Try to infer an object's dtype, for use in arithmetic ops Uses `element.dtype` if that's available. Objects implementing the iterator protocol are cast to a NumPy array, and from there the array's type is used. Parameters ---------- element : object ...
[ "def", "maybe_infer_dtype_type", "(", "element", ")", ":", "tipo", "=", "None", "if", "hasattr", "(", "element", ",", "'dtype'", ")", ":", "tipo", "=", "element", ".", "dtype", "elif", "is_list_like", "(", "element", ")", ":", "element", "=", "np", ".", ...
25.741935
0.001208
def get_all_account_certificates(self, account_id, **kwargs): # noqa: E501 """Get all trusted certificates. # noqa: E501 An endpoint for retrieving trusted certificates in an array. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/trusted-certificates -H 'Authori...
[ "def", "get_all_account_certificates", "(", "self", ",", "account_id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", "return", "self"...
69.029412
0.00084
def get_asset_query_session_for_repository(self, repository_id, proxy): """Gets an asset query session for the given repository. arg: repository_id (osid.id.Id): the Id of the repository arg proxy (osid.proxy.Proxy): a proxy return: (osid.repository.AssetQuerySession) - an ...
[ "def", "get_asset_query_session_for_repository", "(", "self", ",", "repository_id", ",", "proxy", ")", ":", "if", "not", "repository_id", ":", "raise", "NullArgument", "(", ")", "if", "not", "self", ".", "supports_asset_query", "(", ")", ":", "raise", "Unimpleme...
42.096774
0.002247
def Create(alias=None,location=None,session=None): """Claims a new network within a given account. https://www.ctl.io/api-docs/v2/#networks-claim-network Returns operation id and link to check status """ if not alias: alias = clc.v2.Account.GetAlias(session=session) if not location: location = clc.v2.A...
[ "def", "Create", "(", "alias", "=", "None", ",", "location", "=", "None", ",", "session", "=", "None", ")", ":", "if", "not", "alias", ":", "alias", "=", "clc", ".", "v2", ".", "Account", ".", "GetAlias", "(", "session", "=", "session", ")", "if", ...
33.866667
0.036398
def allow_events(self, mode, time, onerror = None): """Release some queued events. mode should be one of X.AsyncPointer, X.SyncPointer, X.AsyncKeyboard, X.SyncKeyboard, X.ReplayPointer, X.ReplayKeyboard, X.AsyncBoth, or X.SyncBoth. time should be a timestamp or X.CurrentTime.""" ...
[ "def", "allow_events", "(", "self", ",", "mode", ",", "time", ",", "onerror", "=", "None", ")", ":", "request", ".", "AllowEvents", "(", "display", "=", "self", ".", "display", ",", "onerror", "=", "onerror", ",", "mode", "=", "mode", ",", "time", "=...
53.777778
0.02439
def trifurcate_base(cls, newick): """ Rewrites a newick string so that the base is a trifurcation (usually means an unrooted tree) """ t = cls(newick) t._tree.deroot() return t.newick
[ "def", "trifurcate_base", "(", "cls", ",", "newick", ")", ":", "t", "=", "cls", "(", "newick", ")", "t", ".", "_tree", ".", "deroot", "(", ")", "return", "t", ".", "newick" ]
36.333333
0.008969
def git_list_config(repo_dir): """Return a list of the git configuration.""" command = ['git', 'config', '--list'] raw = execute_git_command(command, repo_dir=repo_dir).splitlines() output = {key: val for key, val in [cfg.split('=', 1) for cfg in raw]} # TODO(sam): maybe turn this into...
[ "def", "git_list_config", "(", "repo_dir", ")", ":", "command", "=", "[", "'git'", ",", "'config'", ",", "'--list'", "]", "raw", "=", "execute_git_command", "(", "command", ",", "repo_dir", "=", "repo_dir", ")", ".", "splitlines", "(", ")", "output", "=", ...
42.7
0.002294
def _convert(ip, notation, inotation, _check, _isnm): """Internally used to convert IPs and netmasks to other notations.""" inotation_orig = inotation notation_orig = notation inotation = _get_notation(inotation) notation = _get_notation(notation) if inotation is None: raise ValueError('...
[ "def", "_convert", "(", "ip", ",", "notation", ",", "inotation", ",", "_check", ",", "_isnm", ")", ":", "inotation_orig", "=", "inotation", "notation_orig", "=", "notation", "inotation", "=", "_get_notation", "(", "inotation", ")", "notation", "=", "_get_notat...
37.785714
0.002303
def get_submit_args(args): """Gets arguments for the `submit_and_verify` method.""" submit_args = dict( testrun_id=args.testrun_id, user=args.user, password=args.password, no_verify=args.no_verify, verify_timeout=args.verify_timeout, log_file=args.job_log, ...
[ "def", "get_submit_args", "(", "args", ")", ":", "submit_args", "=", "dict", "(", "testrun_id", "=", "args", ".", "testrun_id", ",", "user", "=", "args", ".", "user", ",", "password", "=", "args", ".", "password", ",", "no_verify", "=", "args", ".", "n...
36.384615
0.002062
def get_process_uids(self): """Return real, effective and saved user ids.""" real, effective, saved = _psutil_bsd.get_process_uids(self.pid) return nt_uids(real, effective, saved)
[ "def", "get_process_uids", "(", "self", ")", ":", "real", ",", "effective", ",", "saved", "=", "_psutil_bsd", ".", "get_process_uids", "(", "self", ".", "pid", ")", "return", "nt_uids", "(", "real", ",", "effective", ",", "saved", ")" ]
50
0.009852
def get(self, relpath=None, params=None): """ Invoke the GET method on a resource. @param relpath: Optional. A relative path to this resource's path. @param params: Key-value data. @return: A dictionary of the JSON result. """ for retry in xrange(self.retries + 1): if retry: t...
[ "def", "get", "(", "self", ",", "relpath", "=", "None", ",", "params", "=", "None", ")", ":", "for", "retry", "in", "xrange", "(", "self", ".", "retries", "+", "1", ")", ":", "if", "retry", ":", "time", ".", "sleep", "(", "self", ".", "retry_slee...
31.807692
0.011737
def plot_ellipsoid(hessian, center, lattice=None, rescale=1.0, ax=None, coords_are_cartesian=False, arrows=False, **kwargs): """ Plots a 3D ellipsoid rappresenting the Hessian matrix in input. Useful to get a graphical visualization of the effective mass of a band in a single k-point....
[ "def", "plot_ellipsoid", "(", "hessian", ",", "center", ",", "lattice", "=", "None", ",", "rescale", "=", "1.0", ",", "ax", "=", "None", ",", "coords_are_cartesian", "=", "False", ",", "arrows", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", ...
38.958904
0.001029
def importSNPs(name) : """Import a SNP set shipped with pyGeno. Most of the datawraps only contain URLs towards data provided by third parties.""" path = os.path.join(this_dir, "bootstrap_data", "SNPs/" + name) PS.importSNPs(path)
[ "def", "importSNPs", "(", "name", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "this_dir", ",", "\"bootstrap_data\"", ",", "\"SNPs/\"", "+", "name", ")", "PS", ".", "importSNPs", "(", "path", ")" ]
57.5
0.025751
def _parse_objects_from_xml_elts(bucket_name, contents, common_prefixes): """Internal function that extracts objects and common prefixes from list_objects responses. """ objects = [ Object(bucket_name, content.get_child_text('Key'), content.get_localized_time_elem('...
[ "def", "_parse_objects_from_xml_elts", "(", "bucket_name", ",", "contents", ",", "common_prefixes", ")", ":", "objects", "=", "[", "Object", "(", "bucket_name", ",", "content", ".", "get_child_text", "(", "'Key'", ")", ",", "content", ".", "get_localized_time_elem...
32.909091
0.001342
def corr_matrix(df,method = 'pearson'): """ Returns a matrix of correlations between columns of a DataFrame. For categorical columns, it first changes those to a set of dummy variable columns. Booleans are converted to numerical as well. Also ignores any indexes set on the DataFrame Parameters: df -...
[ "def", "corr_matrix", "(", "df", ",", "method", "=", "'pearson'", ")", ":", "# Remove all but categoricals,booleans, and numerics", "df", "=", "df", ".", "reset_index", "(", "drop", "=", "True", ")", "cat_cols", "=", "df", ".", "select_dtypes", "(", "include", ...
50.733333
0.023856
def html_for_cgi_argument(argument, form): """Returns an HTML snippet for a CGI argument. Args: argument: A string representing an CGI argument name in a form. form: A CGI FieldStorage object. Returns: String HTML representing the CGI value and variable. """ value = form[ar...
[ "def", "html_for_cgi_argument", "(", "argument", ",", "form", ")", ":", "value", "=", "form", "[", "argument", "]", ".", "value", "if", "argument", "in", "form", "else", "None", "return", "KEY_VALUE_TEMPLATE", ".", "format", "(", "argument", ",", "value", ...
33.833333
0.002398
def plotEzJz(self,*args,**kwargs): """ NAME: plotEzJz PURPOSE: plot E_z(.)/sqrt(dens(R)) along the orbit INPUT: pot= Potential instance or list of instances in which the orbit was integrated d1= - plot Ez vs d1: e.g., 't', 'z',...
[ "def", "plotEzJz", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "labeldict", "=", "{", "'t'", ":", "r'$t$'", ",", "'R'", ":", "r'$R$'", ",", "'vR'", ":", "r'$v_R$'", ",", "'vT'", ":", "r'$v_T$'", ",", "'z'", ":", "r'$z$'", ",...
45.318182
0.022579
def get_authorizations_for_resource_and_function(self, resource_id, function_id): """Gets a list of ``Authorizations`` associated with a given resource. Authorizations related to the given resource, including those related through an ``Agent,`` are returned. In plenary mode, the returne...
[ "def", "get_authorizations_for_resource_and_function", "(", "self", ",", "resource_id", ",", "function_id", ")", ":", "# Implemented from template for", "# osid.relationship.RelationshipLookupSession.get_relationships_for_peers", "# NOTE: This implementation currently ignores plenary and eff...
53.741935
0.002358
def run(self): """ Perform phantomas run """ self._logger.info("running for <{url}>".format(url=self._url)) args = format_args(self._options) self._logger.debug("command: `{cmd}` / args: {args}". format(cmd=self._cmd, args=args)) # run the process ...
[ "def", "run", "(", "self", ")", ":", "self", ".", "_logger", ".", "info", "(", "\"running for <{url}>\"", ".", "format", "(", "url", "=", "self", ".", "_url", ")", ")", "args", "=", "format_args", "(", "self", ".", "_options", ")", "self", ".", "_log...
32.45283
0.001129
def exit(self): """Close the Kafka export module.""" # To ensure all connections are properly closed self.client.flush() self.client.close() # Call the father method super(Export, self).exit()
[ "def", "exit", "(", "self", ")", ":", "# To ensure all connections are properly closed", "self", ".", "client", ".", "flush", "(", ")", "self", ".", "client", ".", "close", "(", ")", "# Call the father method", "super", "(", "Export", ",", "self", ")", ".", ...
33.428571
0.008333
def build_candidates(current_graph, n_vertices, n_neighbors, max_candidates, rng_state): """Build a heap of candidate neighbors for nearest neighbor descent. For each vertex the candidate neighbors are any current neighbors, and any vertices that have the vertex as one of their nearest neighbors. Param...
[ "def", "build_candidates", "(", "current_graph", ",", "n_vertices", ",", "n_neighbors", ",", "max_candidates", ",", "rng_state", ")", ":", "candidate_neighbors", "=", "make_heap", "(", "n_vertices", ",", "max_candidates", ")", "for", "i", "in", "range", "(", "n_...
34.475
0.00141
def detect_all_faces(image, cascade = None, sampler = None, threshold = 0, overlaps = 1, minimum_overlap = 0.2, relative_prediction_threshold = 0.25): """detect_all_faces(image, [cascade], [sampler], [threshold], [overlaps], [minimum_overlap], [relative_prediction_threshold]) -> bounding_boxes, qualities Detects a...
[ "def", "detect_all_faces", "(", "image", ",", "cascade", "=", "None", ",", "sampler", "=", "None", ",", "threshold", "=", "0", ",", "overlaps", "=", "1", ",", "minimum_overlap", "=", "0.2", ",", "relative_prediction_threshold", "=", "0.25", ")", ":", "if",...
45.063291
0.013194
def _lincomb(self, a, x1, b, x2, out): """Raw linear combination.""" self.tspace._lincomb(a, x1.tensor, b, x2.tensor, out.tensor)
[ "def", "_lincomb", "(", "self", ",", "a", ",", "x1", ",", "b", ",", "x2", ",", "out", ")", ":", "self", ".", "tspace", ".", "_lincomb", "(", "a", ",", "x1", ".", "tensor", ",", "b", ",", "x2", ".", "tensor", ",", "out", ".", "tensor", ")" ]
47.666667
0.013793
def create(self, patchname): """ Adds a new patch with patchname to the queue The new patch will be added as the topmost applied patch. """ patch = Patch(patchname) if self.series.is_patch(patch): raise PatchAlreadyExists(self.series, patchname) patch_dir = ...
[ "def", "create", "(", "self", ",", "patchname", ")", ":", "patch", "=", "Patch", "(", "patchname", ")", "if", "self", ".", "series", ".", "is_patch", "(", "patch", ")", ":", "raise", "PatchAlreadyExists", "(", "self", ".", "series", ",", "patchname", "...
30.411765
0.001874
def list(self, end=values.unset, start=values.unset, limit=None, page_size=None): """ Lists DataSessionInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. :param datetime end: ...
[ "def", "list", "(", "self", ",", "end", "=", "values", ".", "unset", ",", "start", "=", "values", ".", "unset", ",", "limit", "=", "None", ",", "page_size", "=", "None", ")", ":", "return", "list", "(", "self", ".", "stream", "(", "end", "=", "en...
56.75
0.009532
def cmd_remove_label(docid, label_name): """ Arguments: <document_id> <label_name> Remove a label from a document. Note that if the document was the last one to use the label, the label may disappear entirely from Paperwork. Possible JSON replies: -- { "status": "e...
[ "def", "cmd_remove_label", "(", "docid", ",", "label_name", ")", ":", "dsearch", "=", "get_docsearch", "(", ")", "doc", "=", "dsearch", ".", "get", "(", "docid", ")", "if", "doc", "is", "None", ":", "raise", "Exception", "(", "\"Document {} not found. Cannot...
26.186047
0.001712
def _compute_transitions(self, corpus, order=1): """ Computes the transition probabilities of a corpus Args: corpus: the given corpus (a corpus_entry needs to be iterable) order: the maximal Markov chain order """ self.transitions = defaultdict(lambda: defaultdict...
[ "def", "_compute_transitions", "(", "self", ",", "corpus", ",", "order", "=", "1", ")", ":", "self", ".", "transitions", "=", "defaultdict", "(", "lambda", ":", "defaultdict", "(", "int", ")", ")", "for", "corpus_entry", "in", "corpus", ":", "tokens", "=...
40.428571
0.002301
def fromxlsx(filename, sheet=None, range_string=None, row_offset=0, column_offset=0, **kwargs): """ Extract a table from a sheet in an Excel .xlsx file. N.B., the sheet name is case sensitive. The `sheet` argument can be omitted, in which case the first sheet in the workbook is used b...
[ "def", "fromxlsx", "(", "filename", ",", "sheet", "=", "None", ",", "range_string", "=", "None", ",", "row_offset", "=", "0", ",", "column_offset", "=", "0", ",", "*", "*", "kwargs", ")", ":", "return", "XLSXView", "(", "filename", ",", "sheet", "=", ...
32.708333
0.001238
def percentileOnSortedList(N, percent, key=lambda x:x, interpolate='mean'): # 5 ways of resolving fractional # floor, ceil, funky, linear, mean interpolateChoices = ['floor', 'ceil', 'funky', 'linear', 'mean'] if interpolate not in interpolateChoices: print "Bad choice for interpolate:", interpo...
[ "def", "percentileOnSortedList", "(", "N", ",", "percent", ",", "key", "=", "lambda", "x", ":", "x", ",", "interpolate", "=", "'mean'", ")", ":", "# 5 ways of resolving fractional", "# floor, ceil, funky, linear, mean", "interpolateChoices", "=", "[", "'floor'", ","...
30.909091
0.009026
def console_set_char_foreground( con: tcod.console.Console, x: int, y: int, col: Tuple[int, int, int] ) -> None: """Change the foreground color of x,y to col. Args: con (Console): Any Console instance. x (int): Character x position from the left. y (int): Character y position from t...
[ "def", "console_set_char_foreground", "(", "con", ":", "tcod", ".", "console", ".", "Console", ",", "x", ":", "int", ",", "y", ":", "int", ",", "col", ":", "Tuple", "[", "int", ",", "int", ",", "int", "]", ")", "->", "None", ":", "lib", ".", "TCO...
37.058824
0.001548
def _detect_type_load_headers(self, stream, statusline=None, known_format=None): """ If known_format is specified ('warc' or 'arc'), parse only as that format. Otherwise, try parsing record as WARC, then try parsing as ARC. if neither one succeeds, we'r...
[ "def", "_detect_type_load_headers", "(", "self", ",", "stream", ",", "statusline", "=", "None", ",", "known_format", "=", "None", ")", ":", "if", "known_format", "!=", "'arc'", ":", "# try as warc first", "try", ":", "rec_headers", "=", "self", ".", "warc_pars...
39.78125
0.002301
def _uninstall( action='remove', name=None, version=None, pkgs=None, normalize=True, ignore_epoch=False, **kwargs): ''' Common function for package removal ''' if action not in ('remove', 'purge'): return {'name': name, 'changes': {}, '...
[ "def", "_uninstall", "(", "action", "=", "'remove'", ",", "name", "=", "None", ",", "version", "=", "None", ",", "pkgs", "=", "None", ",", "normalize", "=", "True", ",", "ignore_epoch", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "action",...
37.715686
0.001013
def unpack(data): '''unpack from delimited data''' size, position = decoder._DecodeVarint(data, 0) envelope = wire.Envelope() envelope.ParseFromString(data[position:position+size]) return envelope
[ "def", "unpack", "(", "data", ")", ":", "size", ",", "position", "=", "decoder", ".", "_DecodeVarint", "(", "data", ",", "0", ")", "envelope", "=", "wire", ".", "Envelope", "(", ")", "envelope", ".", "ParseFromString", "(", "data", "[", "position", ":"...
35.333333
0.009217
def _process_works(self, maybe_works, no_works, output_dir): """Collect and return the data of how each work in `maybe_works` relates to each other work. :param maybe_works: :type maybe_works: `list` of `str` :param no_works: :type no_works: `list` of `str` :para...
[ "def", "_process_works", "(", "self", ",", "maybe_works", ",", "no_works", ",", "output_dir", ")", ":", "output_data_dir", "=", "os", ".", "path", ".", "join", "(", "output_dir", ",", "'data'", ")", "no_catalogue", "=", "{", "work", ":", "self", ".", "_n...
44.857143
0.001247
def count_neighbours(mask, radius=1): '''Count how many neighbours of a coordinate are set to one. This uses the same principles as anti_alias, compare comments there.''' height, width = mask.shape f = 2.0*radius+1.0 w = -1.0/numpy.sqrt(f) kernel = [w]*radius + [w] + [w]*radius result = ...
[ "def", "count_neighbours", "(", "mask", ",", "radius", "=", "1", ")", ":", "height", ",", "width", "=", "mask", ".", "shape", "f", "=", "2.0", "*", "radius", "+", "1.0", "w", "=", "-", "1.0", "/", "numpy", ".", "sqrt", "(", "f", ")", "kernel", ...
26.3
0.009174
def move(self, dest, src): """Move element from sequence, member from mapping. :param dest: the destination :type dest: Pointer :param src: the source :type src: Pointer :return: resolved document :rtype: Target .. note:: This operation is f...
[ "def", "move", "(", "self", ",", "dest", ",", "src", ")", ":", "doc", "=", "deepcopy", "(", "self", ".", "document", ")", "# delete", "parent", ",", "fragment", "=", "None", ",", "doc", "for", "token", "in", "Pointer", "(", "src", ")", ":", "parent...
30.675676
0.001708
def stop(): """ Stop recording stats. Call this from a benchmark script when the code you want benchmarked has finished. Call this exactly the same number of times you call L{start} and only after calling it. @raise RuntimeError: Raised if the parent process responds with anything other than ...
[ "def", "stop", "(", ")", ":", "os", ".", "write", "(", "BenchmarkProcess", ".", "BACKCHANNEL_OUT", ",", "BenchmarkProcess", ".", "STOP", ")", "response", "=", "util", ".", "untilConcludes", "(", "os", ".", "read", ",", "BenchmarkProcess", ".", "BACKCHANNEL_I...
46.285714
0.001513
def insertVariantAnnotationSet(self, variantAnnotationSet): """ Inserts a the specified variantAnnotationSet into this repository. """ analysisJson = json.dumps( protocol.toJsonDict(variantAnnotationSet.getAnalysis())) try: models.Variantannotationset.crea...
[ "def", "insertVariantAnnotationSet", "(", "self", ",", "variantAnnotationSet", ")", ":", "analysisJson", "=", "json", ".", "dumps", "(", "protocol", ".", "toJsonDict", "(", "variantAnnotationSet", ".", "getAnalysis", "(", ")", ")", ")", "try", ":", "models", "...
50.578947
0.002043
def from_date(cls, date, period=None): """ Create a day long daterange from for the given date. >>> daterange.from_date(date(2000, 1, 1)) daterange([datetime.date(2000, 1, 1),datetime.date(2000, 1, 2))) :param date: A date to convert. :param period: The period t...
[ "def", "from_date", "(", "cls", ",", "date", ",", "period", "=", "None", ")", ":", "if", "period", "is", "None", "or", "period", "==", "\"day\"", ":", "return", "cls", "(", "date", ",", "date", ",", "upper_inc", "=", "True", ")", "elif", "period", ...
41.367347
0.000964
def get_submission(self, submissionid, user_check=True): """ Get a submission from the database """ sub = self._database.submissions.find_one({'_id': ObjectId(submissionid)}) if user_check and not self.user_is_submission_owner(sub): return None return sub
[ "def", "get_submission", "(", "self", ",", "submissionid", ",", "user_check", "=", "True", ")", ":", "sub", "=", "self", ".", "_database", ".", "submissions", ".", "find_one", "(", "{", "'_id'", ":", "ObjectId", "(", "submissionid", ")", "}", ")", "if", ...
49
0.010033
def run_bwa(job, fastqs, sample_type, univ_options, bwa_options): """ Align a pair of fastqs with bwa. :param list fastqs: The input fastqs for alignment :param str sample_type: Description of the sample to inject into the filename :param dict univ_options: Dict of universal options used by almost ...
[ "def", "run_bwa", "(", "job", ",", "fastqs", ",", "sample_type", ",", "univ_options", ",", "bwa_options", ")", ":", "work_dir", "=", "os", ".", "getcwd", "(", ")", "input_files", "=", "{", "'dna_1.fastq'", ":", "fastqs", "[", "0", "]", ",", "'dna_2.fastq...
47.785714
0.002441
def canonic(self, filename): """ Turns `filename' into its canonic representation and returns this string. This allows a user to refer to a given file in one of several equivalent ways. Relative filenames need to be fully resolved, since the current working directory might chang...
[ "def", "canonic", "(", "self", ",", "filename", ")", ":", "if", "filename", "==", "\"<\"", "+", "filename", "[", "1", ":", "-", "1", "]", "+", "\">\"", ":", "return", "filename", "canonic", "=", "self", ".", "filename_cache", ".", "get", "(", "filena...
46.135135
0.001721
def fit_spectrum(self, specFunc, initPars, freePars=None): """ Fit for the free parameters of a spectral function Parameters ---------- specFunc : `~fermipy.spectrum.SpectralFunction` The Spectral Function initPars : `~numpy.ndarray` The initial values o...
[ "def", "fit_spectrum", "(", "self", ",", "specFunc", ",", "initPars", ",", "freePars", "=", "None", ")", ":", "if", "not", "isinstance", "(", "specFunc", ",", "SEDFunctor", ")", ":", "specFunc", "=", "self", ".", "create_functor", "(", "specFunc", ",", "...
33.643836
0.001978
def format_uuid( uuid, max_length=10): """ Format a UUID string :param str uuid: UUID to format :param int max_length: Maximum length of result string (> 3) :return: Formatted UUID :rtype: str :raises ValueError: If *max_length* is not larger than 3 This function format...
[ "def", "format_uuid", "(", "uuid", ",", "max_length", "=", "10", ")", ":", "if", "max_length", "<=", "3", ":", "raise", "ValueError", "(", "\"max length must be larger than 3\"", ")", "if", "len", "(", "uuid", ")", ">", "max_length", ":", "uuid", "=", "\"{...
34.758621
0.000965
def print_text(args, infilenames, outfilename=None): """Print text content of infiles to stdout. Keyword arguments: args -- program arguments (dict) infilenames -- names of user-inputted and/or downloaded files (list) outfilename -- only used for interface purposes (None) """ for infilename...
[ "def", "print_text", "(", "args", ",", "infilenames", ",", "outfilename", "=", "None", ")", ":", "for", "infilename", "in", "infilenames", ":", "parsed_text", "=", "get_parsed_text", "(", "args", ",", "infilename", ")", "if", "parsed_text", ":", "for", "line...
35
0.001988
def get_index(self, filename): """Return index associated with filename""" index = self.fsmodel.index(filename) if index.isValid() and index.model() is self.fsmodel: return self.proxymodel.mapFromSource(index)
[ "def", "get_index", "(", "self", ",", "filename", ")", ":", "index", "=", "self", ".", "fsmodel", ".", "index", "(", "filename", ")", "if", "index", ".", "isValid", "(", ")", "and", "index", ".", "model", "(", ")", "is", "self", ".", "fsmodel", ":"...
49
0.008032
def generate_thumbnail_in_stream( self, width, height, image, smart_cropping=False, custom_headers=None, raw=False, callback=None, **operation_config): """This operation generates a thumbnail image with the user-specified width and height. By default, the service analyzes the image, ...
[ "def", "generate_thumbnail_in_stream", "(", "self", ",", "width", ",", "height", ",", "image", ",", "smart_cropping", "=", "False", ",", "custom_headers", "=", "None", ",", "raw", "=", "False", ",", "callback", "=", "None", ",", "*", "*", "operation_config",...
49.17284
0.001969
def matcher(graph1, graph2, confidence=0.5, output_file="matching_results.csv", class_or_prop="classes", verbose=False): """ takes two graphs and matches its classes based on qname, label etc.. @todo extend to properties and skos etc.. """ printDebug("----------\nNow matching...") f = open(output_file, 'wt') c...
[ "def", "matcher", "(", "graph1", ",", "graph2", ",", "confidence", "=", "0.5", ",", "output_file", "=", "\"matching_results.csv\"", ",", "class_or_prop", "=", "\"classes\"", ",", "verbose", "=", "False", ")", ":", "printDebug", "(", "\"----------\\nNow matching......
25.925926
0.030282
def getNumRegistered(self, includeTemporaryRegs=False, dateTime=None): ''' Method allows the inclusion of temporary registrations, as well as exclusion of temporary registrations that are too new (e.g. for discounts based on the first X registrants, we don't want to include people who st...
[ "def", "getNumRegistered", "(", "self", ",", "includeTemporaryRegs", "=", "False", ",", "dateTime", "=", "None", ")", ":", "count", "=", "self", ".", "eventregistration_set", ".", "filter", "(", "cancelled", "=", "False", ",", "dropIn", "=", "False", ")", ...
54.866667
0.010753
def get_map_title(hazard, exposure, hazard_category): """Helper to get map title. :param hazard: A hazard definition. :type hazard: dict :param exposure: An exposure definition. :type exposure: dict :param hazard_category: A hazard category definition. :type hazard_category: dict :re...
[ "def", "get_map_title", "(", "hazard", ",", "exposure", ",", "hazard_category", ")", ":", "if", "hazard", "==", "hazard_generic", ":", "map_title", "=", "tr", "(", "'{exposure_name} affected'", ")", ".", "format", "(", "exposure_name", "=", "exposure", "[", "'...
33.3
0.000973
def project(original_image, perturbed_images, alphas, shape, constraint): """ Projection onto given l2 / linf balls in a batch. """ alphas_shape = [len(alphas)] + [1] * len(shape) alphas = alphas.reshape(alphas_shape) if constraint == 'l2': projected = (1-alphas) * original_image + alphas * perturbed_images...
[ "def", "project", "(", "original_image", ",", "perturbed_images", ",", "alphas", ",", "shape", ",", "constraint", ")", ":", "alphas_shape", "=", "[", "len", "(", "alphas", ")", "]", "+", "[", "1", "]", "*", "len", "(", "shape", ")", "alphas", "=", "a...
37
0.014199
def extract_header(msg_or_header): """Given a message or header, return the header.""" if not msg_or_header: return {} try: # See if msg_or_header is the entire message. h = msg_or_header['header'] except KeyError: try: # See if msg_or_header is just the heade...
[ "def", "extract_header", "(", "msg_or_header", ")", ":", "if", "not", "msg_or_header", ":", "return", "{", "}", "try", ":", "# See if msg_or_header is the entire message.", "h", "=", "msg_or_header", "[", "'header'", "]", "except", "KeyError", ":", "try", ":", "...
27.555556
0.001949
def convert_instancenorm(net, node, model, builder): """Convert an instance norm layer from mxnet to coreml. Parameters ---------- net: network A mxnet network object. node: layer Node to convert. model: model An model for MXNet builder: NeuralNetworkBuilder ...
[ "def", "convert_instancenorm", "(", "net", ",", "node", ",", "model", ",", "builder", ")", ":", "import", "numpy", "as", "_np", "input_name", ",", "output_name", "=", "_get_input_output_name", "(", "net", ",", "node", ")", "name", "=", "node", "[", "'name'...
30.901961
0.01968
def loads(string): """ Construct a GeoJSON `dict` from WKB (`string`). The resulting GeoJSON `dict` will include the SRID as an integer in the `meta` object. This was an arbitrary decision made by `geomet, the discussion of which took place here: https://github.com/geomet/geomet/issues/28. ...
[ "def", "loads", "(", "string", ")", ":", "# noqa", "string", "=", "iter", "(", "string", ")", "# endianness = string[0:1]", "endianness", "=", "as_bin_str", "(", "take", "(", "1", ",", "string", ")", ")", "if", "endianness", "==", "BIG_ENDIAN", ":", "big_e...
36.506024
0.000321
def crypto_aead_chacha20poly1305_encrypt(message, aad, nonce, key): """ Encrypt the given ``message`` using the "legacy" construction described in draft-agl-tls-chacha20poly1305. :param message: :type message: bytes :param aad: :type aad: bytes :param nonce: :type nonce: bytes :...
[ "def", "crypto_aead_chacha20poly1305_encrypt", "(", "message", ",", "aad", ",", "nonce", ",", "key", ")", ":", "ensure", "(", "isinstance", "(", "message", ",", "bytes", ")", ",", "'Input message type must be bytes'", ",", "raising", "=", "exc", ".", "TypeError"...
33.779412
0.000423
def process_set(line, annotations): """Convert annotations into nanopub_bel annotations format""" matches = re.match('SET\s+(\w+)\s*=\s*"?(.*?)"?\s*$', line) key = None if matches: key = matches.group(1) val = matches.group(2) if key == "STATEMENT_GROUP": annotations["stat...
[ "def", "process_set", "(", "line", ",", "annotations", ")", ":", "matches", "=", "re", ".", "match", "(", "'SET\\s+(\\w+)\\s*=\\s*\"?(.*?)\"?\\s*$'", ",", "line", ")", "key", "=", "None", "if", "matches", ":", "key", "=", "matches", ".", "group", "(", "1",...
29.565217
0.009972
def _json_to_evaluation(data): """ Only keep the data for online evaluations. Two scenarios for multiple instructors: 1) all of the co-instructors may be evaluated online as a group, sharing the eval URL. 2) each co-instructor may be evaluated individually, with separate eval URLs. ...
[ "def", "_json_to_evaluation", "(", "data", ")", ":", "if", "data", "is", "None", ":", "return", "None", "evaluations", "=", "[", "]", "collection_items", "=", "data", ".", "get", "(", "'collection'", ")", ".", "get", "(", "'items'", ")", "for", "item", ...
41.928571
0.000555
def _generate_report(ret, show_tasks): ''' Generate a report of the Salt function :param ret: The Salt return :param show_tasks: Flag to show the name of the changed and failed states :return: The report ''' returns = ret.get('return') sorted_data = sorted( returns.items(), ...
[ "def", "_generate_report", "(", "ret", ",", "show_tasks", ")", ":", "returns", "=", "ret", ".", "get", "(", "'return'", ")", "sorted_data", "=", "sorted", "(", "returns", ".", "items", "(", ")", ",", "key", "=", "lambda", "s", ":", "s", "[", "1", "...
25.90411
0.000509
def fit1d(samples, e, remove_zeros = False, **kw): """Fits a 1D distribution with splines. Input: samples: Array Array of samples from a probability distribution e: Array Edges that define the events in the probability distribution. For example, e[0] < x <= ...
[ "def", "fit1d", "(", "samples", ",", "e", ",", "remove_zeros", "=", "False", ",", "*", "*", "kw", ")", ":", "samples", "=", "samples", "[", "~", "np", ".", "isnan", "(", "samples", ")", "]", "length", "=", "len", "(", "e", ")", "-", "1", "hist"...
35.515152
0.009967
def y(self, y): """Project reversed y""" if y is None: return None return (self.height * (y - self.box.ymin) / self.box.height)
[ "def", "y", "(", "self", ",", "y", ")", ":", "if", "y", "is", "None", ":", "return", "None", "return", "(", "self", ".", "height", "*", "(", "y", "-", "self", ".", "box", ".", "ymin", ")", "/", "self", ".", "box", ".", "height", ")" ]
31.8
0.01227
def tolerate(substitute=None, exceptions=None, switch=DEFAULT_TOLERATE_SWITCH): """ A function decorator which makes a function fail silently To disable fail silently in a decorated function, specify ``fail_silently=False``. To disable fail silenlty in decorated functions globally, spe...
[ "def", "tolerate", "(", "substitute", "=", "None", ",", "exceptions", "=", "None", ",", "switch", "=", "DEFAULT_TOLERATE_SWITCH", ")", ":", "def", "decorator", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "inner", "(", "*", "args", ",", ...
33.636364
0.000309
def imagetransformer_sep_channels_8l_8h_local_and_global_att(): """separate rgb embeddings.""" hparams = imagetransformer_sep_channels_8l_8h() hparams.num_heads = 8 hparams.batch_size = 1 hparams.attention_key_channels = hparams.attention_value_channels = 0 hparams.hidden_size = 256 hparams.filter_size = ...
[ "def", "imagetransformer_sep_channels_8l_8h_local_and_global_att", "(", ")", ":", "hparams", "=", "imagetransformer_sep_channels_8l_8h", "(", ")", "hparams", ".", "num_heads", "=", "8", "hparams", ".", "batch_size", "=", "1", "hparams", ".", "attention_key_channels", "=...
36.333333
0.026846
def list_subdomains(self, limit=None, offset=None): """ Returns a list of all subdomains for this domain. """ return self.manager.list_subdomains(self, limit=limit, offset=offset)
[ "def", "list_subdomains", "(", "self", ",", "limit", "=", "None", ",", "offset", "=", "None", ")", ":", "return", "self", ".", "manager", ".", "list_subdomains", "(", "self", ",", "limit", "=", "limit", ",", "offset", "=", "offset", ")" ]
41.4
0.009479
def callback(self, output, inputs=None, state=None, events=None): 'Form a callback function by wrapping, in the same way as the underlying Dash application would' callback_set = {'output':output, 'inputs':inputs and inputs or dict(), 'state':state and stat...
[ "def", "callback", "(", "self", ",", "output", ",", "inputs", "=", "None", ",", "state", "=", "None", ",", "events", "=", "None", ")", ":", "callback_set", "=", "{", "'output'", ":", "output", ",", "'inputs'", ":", "inputs", "and", "inputs", "or", "d...
64.1
0.015385
def _get_required_fn(fn, root_path): """ Definition of the MD5 file requires, that all paths will be absolute for the package directory, not for the filesystem. This function converts filesystem-absolute paths to package-absolute paths. Args: fn (str): Local/absolute path to the file. ...
[ "def", "_get_required_fn", "(", "fn", ",", "root_path", ")", ":", "if", "not", "fn", ".", "startswith", "(", "root_path", ")", ":", "raise", "ValueError", "(", "\"Both paths have to be absolute or local!\"", ")", "replacer", "=", "\"/\"", "if", "root_path", ".",...
31.583333
0.00128
def execute_get_text(command): # type: (str) ->str """ Execute shell command and return stdout txt :param command: :return: """ try: _ = subprocess.run try: completed = subprocess.run( command, check=True, shell=True, ...
[ "def", "execute_get_text", "(", "command", ")", ":", "# type: (str) ->str", "try", ":", "_", "=", "subprocess", ".", "run", "try", ":", "completed", "=", "subprocess", ".", "run", "(", "command", ",", "check", "=", "True", ",", "shell", "=", "True", ",",...
29.857143
0.002317
def json_worker(self, mask, cache_id=None, cache_method="string", cache_section="www"): """A function annotation that adds a worker request. A worker request is a POST request that is computed asynchronously. That is, the actual task is performed in a different thread a...
[ "def", "json_worker", "(", "self", ",", "mask", ",", "cache_id", "=", "None", ",", "cache_method", "=", "\"string\"", ",", "cache_section", "=", "\"www\"", ")", ":", "use_cache", "=", "cache_id", "is", "not", "None", "def", "wrapper", "(", "fun", ")", ":...
43.334405
0.000218
def synthesizeProperty(propertyName, default = None, contract = None, readOnly = False, privateMemberName = None): """ When applied to a class, this decorator adds a property to it and overrides the constructor in order ...
[ "def", "synthesizeProperty", "(", "propertyName", ",", "default", "=", "None", ",", "contract", "=", "None", ",", "readOnly", "=", "False", ",", "privateMemberName", "=", "None", ")", ":", "return", "SyntheticDecoratorFactory", "(", ")", ".", "syntheticMemberDec...
57.714286
0.01704
def inconsistent(self): r""" Perform some consistency tests on the graph represented by this object Returns ------- consistent : bool or list False if consistent, else a list of inconsistency messages. Notes ----- This check i...
[ "def", "inconsistent", "(", "self", ")", ":", "messages", "=", "[", "]", "for", "node", "in", "list", "(", "self", ".", "__tweights", ".", "keys", "(", ")", ")", ":", "if", "not", "node", "<=", "self", ".", "__nodes", ":", "messages", ".", "append"...
48.448276
0.014655
def ordqz(A, B, sort='lhp', output='real', overwrite_a=False, overwrite_b=False, check_finite=True): """ QZ decomposition for a pair of matrices with reordering. .. versionadded:: 0.17.0 Parameters ---------- A : (N, N) array_like 2d array to decompose B : (N, N) array_li...
[ "def", "ordqz", "(", "A", ",", "B", ",", "sort", "=", "'lhp'", ",", "output", "=", "'real'", ",", "overwrite_a", "=", "False", ",", "overwrite_b", "=", "False", ",", "check_finite", "=", "True", ")", ":", "import", "warnings", "import", "numpy", "as", ...
37.067164
0.000784
def on_each_source(self): """ True if there is an applyToSources for each source. """ return (self.info.applytosources and self.info.applytosources == self.source_ids)
[ "def", "on_each_source", "(", "self", ")", ":", "return", "(", "self", ".", "info", ".", "applytosources", "and", "self", ".", "info", ".", "applytosources", "==", "self", ".", "source_ids", ")" ]
35
0.009302
def _project_on_ellipsoid(c, r, locations): """displace locations to the nearest point on ellipsoid surface""" p0 = locations - c # original locations l2 = 1 / np.sum(p0**2 / r**2, axis=1, keepdims=True) p = p0 * np.sqrt(l2) # initial approximation (projection of points towards center of ellipsoid) ...
[ "def", "_project_on_ellipsoid", "(", "c", ",", "r", ",", "locations", ")", ":", "p0", "=", "locations", "-", "c", "# original locations", "l2", "=", "1", "/", "np", ".", "sum", "(", "p0", "**", "2", "/", "r", "**", "2", ",", "axis", "=", "1", ","...
57
0.010072
def assess_component(model, reaction, side, flux_coefficient_cutoff=0.001, solver=None): """Assesses the ability of the model to provide sufficient precursors, or absorb products, for a reaction operating at, or beyond, the specified cutoff. Parameters ---------- model : co...
[ "def", "assess_component", "(", "model", ",", "reaction", ",", "side", ",", "flux_coefficient_cutoff", "=", "0.001", ",", "solver", "=", "None", ")", ":", "reaction", "=", "model", ".", "reactions", ".", "get_by_any", "(", "reaction", ")", "[", "0", "]", ...
41.324675
0.000307
def encode(self): ''' Encode and store a CONNACK control packet. ''' header = bytearray(1) varHeader = bytearray(2) header[0] = 0x20 varHeader[0] = self.session varHeader[1] = self.resultCode header.extend(encodeLength(len(varHe...
[ "def", "encode", "(", "self", ")", ":", "header", "=", "bytearray", "(", "1", ")", "varHeader", "=", "bytearray", "(", "2", ")", "header", "[", "0", "]", "=", "0x20", "varHeader", "[", "0", "]", "=", "self", ".", "session", "varHeader", "[", "1", ...
30.714286
0.018059
def sentiment(self): """ Returns average sentiment of document. Must have sentiment enabled in XML output. :getter: returns average sentiment of the document :type: float """ if self._sentiment is None: results = self._xml.xpath('/root/document/sentences') ...
[ "def", "sentiment", "(", "self", ")", ":", "if", "self", ".", "_sentiment", "is", "None", ":", "results", "=", "self", ".", "_xml", ".", "xpath", "(", "'/root/document/sentences'", ")", "self", ".", "_sentiment", "=", "float", "(", "results", "[", "0", ...
36.916667
0.008811
def delete_attachment(self, id): """Delete attachment by id. :param id: ID of the attachment to delete :type id: str """ url = self._get_url('attachment/' + str(id)) return self._session.delete(url)
[ "def", "delete_attachment", "(", "self", ",", "id", ")", ":", "url", "=", "self", ".", "_get_url", "(", "'attachment/'", "+", "str", "(", "id", ")", ")", "return", "self", ".", "_session", ".", "delete", "(", "url", ")" ]
30
0.008097
def get_repo_revision(): ''' Returns mercurial revision string somelike `hg identify` does. Format is rev1:short-id1+;rev2:short-id2+ Returns an empty string if anything goes wrong, such as missing .hg files or an unexpected format of internal HG files or no mercurial repository found. '''...
[ "def", "get_repo_revision", "(", ")", ":", "repopath", "=", "_findrepo", "(", ")", "if", "not", "repopath", ":", "return", "''", "# first try to use mercurial itself", "try", ":", "import", "mercurial", ".", "hg", ",", "mercurial", ".", "ui", ",", "mercurial",...
32.133333
0.002014
def zscore(self, mask=NotSpecified, groupby=NotSpecified): """ Construct a Factor that Z-Scores each day's results. The Z-Score of a row is defined as:: (row - row.mean()) / row.stddev() If ``mask`` is supplied, ignore values where ``mask`` returns False when compu...
[ "def", "zscore", "(", "self", ",", "mask", "=", "NotSpecified", ",", "groupby", "=", "NotSpecified", ")", ":", "return", "GroupedRowTransform", "(", "transform", "=", "zscore", ",", "transform_args", "=", "(", ")", ",", "factor", "=", "self", ",", "groupby...
34.491803
0.000924
def reacher(): """Configuration for MuJoCo's reacher task.""" locals().update(default()) # Environment env = 'Reacher-v2' max_length = 1000 steps = 5e6 # 5M discount = 0.985 update_every = 60 return locals()
[ "def", "reacher", "(", ")", ":", "locals", "(", ")", ".", "update", "(", "default", "(", ")", ")", "# Environment", "env", "=", "'Reacher-v2'", "max_length", "=", "1000", "steps", "=", "5e6", "# 5M", "discount", "=", "0.985", "update_every", "=", "60", ...
21.7
0.044248