text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def search_tags(self, *args, **kwargs): """ Args: query (string): elasticsearch string query order_by (optional[string]): property by which to order results offset (optional[int]): number of results to skip for pagination (default=0) limit ...
[ "def", "search_tags", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_search_metrics_and_metadata", "(", "self", ".", "_TAG_ENDPOINT_SUFFIX", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
41.0625
22.8125
def wrap_line(line, limit=None, chars=80): """Wraps the specified line of text on whitespace to make sure that none of the lines' lengths exceeds 'chars' characters. """ result = [] builder = [] length = 0 if limit is not None: sline = line[0:limit] else: sline = line ...
[ "def", "wrap_line", "(", "line", ",", "limit", "=", "None", ",", "chars", "=", "80", ")", ":", "result", "=", "[", "]", "builder", "=", "[", "]", "length", "=", "0", "if", "limit", "is", "not", "None", ":", "sline", "=", "line", "[", "0", ":", ...
26
15.478261
def get_word_input(data, word_dict, embed, embed_dim): ''' Get word input. ''' batch_size = len(data) max_sequence_length = max(len(d) for d in data) sequence_length = max_sequence_length word_input = np.zeros((max_sequence_length, batch_size, embed_dim), dtype=np....
[ "def", "get_word_input", "(", "data", ",", "word_dict", ",", "embed", ",", "embed_dim", ")", ":", "batch_size", "=", "len", "(", "data", ")", "max_sequence_length", "=", "max", "(", "len", "(", "d", ")", "for", "d", "in", "data", ")", "sequence_length", ...
40.407407
20.037037
def number(self): # type: () -> int """ Return this commits number. This is the same as the total number of commits in history up until this commit. This value can be useful in some CI scenarios as it allows to track progress on any given branch (although there can be t...
[ "def", "number", "(", "self", ")", ":", "# type: () -> int", "cmd", "=", "'git log --oneline {}'", ".", "format", "(", "self", ".", "sha1", ")", "out", "=", "shell", ".", "run", "(", "cmd", ",", "capture", "=", "True", ",", "never_pretend", "=", "True", ...
36.352941
22.352941
def summarize(self, test_arr, vectorizable_token, sentence_list, limit=5): ''' Summarize input document. Args: test_arr: `np.ndarray` of observed data points.. vectorizable_token: is-a `VectorizableToken`. sentence_list: `lis...
[ "def", "summarize", "(", "self", ",", "test_arr", ",", "vectorizable_token", ",", "sentence_list", ",", "limit", "=", "5", ")", ":", "if", "isinstance", "(", "vectorizable_token", ",", "VectorizableToken", ")", "is", "False", ":", "raise", "TypeError", "(", ...
34.439024
20.487805
def is_offsetlike(arr_or_obj): """ Check if obj or all elements of list-like is DateOffset Parameters ---------- arr_or_obj : object Returns ------- boolean Whether the object is a DateOffset or listlike of DatetOffsets Examples -------- >>> is_offsetlike(pd.DateOf...
[ "def", "is_offsetlike", "(", "arr_or_obj", ")", ":", "if", "isinstance", "(", "arr_or_obj", ",", "ABCDateOffset", ")", ":", "return", "True", "elif", "(", "is_list_like", "(", "arr_or_obj", ")", "and", "len", "(", "arr_or_obj", ")", "and", "is_object_dtype", ...
26.033333
23.1
def user_organisations(cls, user_id, state=None, include_deactivated=False): """ Get organisations that the user has joined :param user_id: the user ID :param state: the user's "join" state :param include_deactivated: Include deactivated resources in response :returns: l...
[ "def", "user_organisations", "(", "cls", ",", "user_id", ",", "state", "=", "None", ",", "include_deactivated", "=", "False", ")", ":", "if", "state", "and", "state", "not", "in", "validators", ".", "VALID_STATES", ":", "raise", "exceptions", ".", "Validatio...
42.142857
20.238095
def _parse_coverage(header_str): """Attempts to retrieve the coverage value from the header string. It splits the header by "_" and then screens the list backwards in search of the first float value. This will be interpreted as the coverage value. If it cannot find a float value, it ret...
[ "def", "_parse_coverage", "(", "header_str", ")", ":", "cov", "=", "None", "for", "i", "in", "header_str", ".", "split", "(", "\"_\"", ")", "[", ":", ":", "-", "1", "]", ":", "try", ":", "cov", "=", "float", "(", "i", ")", "break", "except", "Val...
31.225806
22.16129
def add_virtualip(self, lb, vip): """Adds the VirtualIP to the specified load balancer.""" resp, body = self.api.method_post("/loadbalancers/%s/virtualips" % lb.id, body=vip.to_dict()) return resp, body
[ "def", "add_virtualip", "(", "self", ",", "lb", ",", "vip", ")", ":", "resp", ",", "body", "=", "self", ".", "api", ".", "method_post", "(", "\"/loadbalancers/%s/virtualips\"", "%", "lb", ".", "id", ",", "body", "=", "vip", ".", "to_dict", "(", ")", ...
47.6
13.6
def execute(self): """ Entry point to the execution of the program. """ # Ensure that we have commands registered if not self.commands or self._parser is None: raise NotImplementedError( "No commands registered with this program!" ) ...
[ "def", "execute", "(", "self", ")", ":", "# Ensure that we have commands registered", "if", "not", "self", ".", "commands", "or", "self", ".", "_parser", "is", "None", ":", "raise", "NotImplementedError", "(", "\"No commands registered with this program!\"", ")", "# H...
35.709677
23.064516
def get_container_instance_group(access_token, subscription_id, resource_group, container_group_name): '''Get the JSON definition of a container group. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. ...
[ "def", "get_container_instance_group", "(", "access_token", ",", "subscription_id", ",", "resource_group", ",", "container_group_name", ")", ":", "endpoint", "=", "''", ".", "join", "(", "[", "get_rm_endpoint", "(", ")", ",", "'/subscriptions/'", ",", "subscription_...
44.55
21.75
def cosine_similarity(evaluated_model, reference_model): """ Computes cosine similarity of two text documents. Each document has to be represented as TF model of non-empty document. :returns float: 0 <= cos <= 1, where 0 means independence and 1 means exactly the same. """ if no...
[ "def", "cosine_similarity", "(", "evaluated_model", ",", "reference_model", ")", ":", "if", "not", "(", "isinstance", "(", "evaluated_model", ",", "TfModel", ")", "and", "isinstance", "(", "reference_model", ",", "TfModel", ")", ")", ":", "raise", "ValueError", ...
38.52
25.96
def add_task(self, fn, inputs=None, outputs=None): """ Adds a task to the workflow. Returns self to facilitate chaining method calls """ # self.tasks.append({'task': task, 'inputs': inputs, 'outputs': outputs}) self.tasks.append(Task(fn, inputs, outputs)) return ...
[ "def", "add_task", "(", "self", ",", "fn", ",", "inputs", "=", "None", ",", "outputs", "=", "None", ")", ":", "# self.tasks.append({'task': task, 'inputs': inputs, 'outputs': outputs})", "self", ".", "tasks", ".", "append", "(", "Task", "(", "fn", ",", "inputs",...
35.111111
16
def shutdown(self): """ Shut down the entire application. """ logging.info("Shutting down") self.closeAllWindows() self.notifier.hide() self.service.shutdown() self.monitor.stop() self.quit() os.remove(common.LOCK_FILE) # TODO: maybe use a...
[ "def", "shutdown", "(", "self", ")", ":", "logging", ".", "info", "(", "\"Shutting down\"", ")", "self", ".", "closeAllWindows", "(", ")", "self", ".", "notifier", ".", "hide", "(", ")", "self", ".", "service", ".", "shutdown", "(", ")", "self", ".", ...
34
13.666667
def plot(self, hist=False, show=False, **kwargs): """ Plot the distribution of the UncertainFunction. By default, the distribution is shown with a kernel density estimate (kde). Optional -------- hist : bool If true, a density histogram is displayed (...
[ "def", "plot", "(", "self", ",", "hist", "=", "False", ",", "show", "=", "False", ",", "*", "*", "kwargs", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "vals", "=", "self", ".", "_mcpts", "low", "=", "min", "(", "vals", ")", "hig...
30.390244
20.487805
def phmmer(**kwargs): """Search a protein sequence against a HMMER sequence database. Arguments: seq - The sequence to search -- a Fasta string. seqdb -- Sequence database to search against. range -- A string range of results to return (ie. 1,10 for the first ten) output -- The output f...
[ "def", "phmmer", "(", "*", "*", "kwargs", ")", ":", "logging", ".", "debug", "(", "kwargs", ")", "args", "=", "{", "'seq'", ":", "kwargs", ".", "get", "(", "'seq'", ")", ",", "'seqdb'", ":", "kwargs", ".", "get", "(", "'seqdb'", ")", "}", "args2"...
41.2
15.2
def _wrap(text, wrap_max=80, indent=4): """Wrap text at given width using textwrap module. text (unicode): Text to wrap. If it's a Path, it's converted to string. wrap_max (int): Maximum line length (indent is deducted). indent (int): Number of spaces for indentation. RETURNS (unicode): Wrapped tex...
[ "def", "_wrap", "(", "text", ",", "wrap_max", "=", "80", ",", "indent", "=", "4", ")", ":", "indent", "=", "indent", "*", "' '", "wrap_width", "=", "wrap_max", "-", "len", "(", "indent", ")", "if", "isinstance", "(", "text", ",", "Path", ")", ":", ...
42.6
14.8
def write_float_matrices(scp_path, ark_path, matrices): """ Write the given dict matrices (utt-id/float ndarray) to the given scp and ark files. """ scp_entries = [] with open(ark_path, 'wb') as f: for utterance_id in sorted(list(matrices.keys())): matrix = matrices...
[ "def", "write_float_matrices", "(", "scp_path", ",", "ark_path", ",", "matrices", ")", ":", "scp_entries", "=", "[", "]", "with", "open", "(", "ark_path", ",", "'wb'", ")", "as", "f", ":", "for", "utterance_id", "in", "sorted", "(", "list", "(", "matrice...
35.310345
22.068966
def subdevicenames(self) -> Tuple[str, ...]: """A |tuple| containing the (sub)device names. Property |NetCDFVariableFlat.subdevicenames| clarifies which row of |NetCDFVariableAgg.array| contains which time series. For 0-dimensional series like |lland_inputs.Nied|, the plain devi...
[ "def", "subdevicenames", "(", "self", ")", "->", "Tuple", "[", "str", ",", "...", "]", ":", "stats", ":", "List", "[", "str", "]", "=", "collections", ".", "deque", "(", ")", "for", "devicename", ",", "seq", "in", "self", ".", "sequences", ".", "it...
44.875
18.25
def update_params_for_auth(self, headers, querys, auth_settings): """Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. :param querys: Query parameters tuple list to be updated. :param auth_settings: Authentication sett...
[ "def", "update_params_for_auth", "(", "self", ",", "headers", ",", "querys", ",", "auth_settings", ")", ":", "if", "self", ".", "auth_token_holder", ".", "token", "is", "not", "None", ":", "headers", "[", "Configuration", ".", "AUTH_TOKEN_HEADER_NAME", "]", "=...
52.727273
24.363636
def delete(cls, schedule_id, schedule_instance_id, note_attachment_schedule_instance_id, monetary_account_id=None, custom_headers=None): """ :type user_id: int :type monetary_account_id: int :type schedule_id: int :type schedule_instance_id: int ...
[ "def", "delete", "(", "cls", ",", "schedule_id", ",", "schedule_instance_id", ",", "note_attachment_schedule_instance_id", ",", "monetary_account_id", "=", "None", ",", "custom_headers", "=", "None", ")", ":", "if", "custom_headers", "is", "None", ":", "custom_heade...
43.448276
22.344828
def create(self, name, ip_address): """ Creates a new domain Parameters ---------- name: str new domain name ip_address: str IP address for the new domain """ return (self.post(name=name, ip_address=ip_address) .get...
[ "def", "create", "(", "self", ",", "name", ",", "ip_address", ")", ":", "return", "(", "self", ".", "post", "(", "name", "=", "name", ",", "ip_address", "=", "ip_address", ")", ".", "get", "(", "self", ".", "singular", ",", "None", ")", ")" ]
25.384615
13.538462
def scaled_array_2d_with_sub_dimensions_from_sub_array_1d(self, sub_array_1d): """ Map a 1D sub-array the same dimension as the sub-grid to its original masked 2D sub-array and return it as a scaled array. Parameters ----------- sub_array_1d : ndarray The 1D sub-arra...
[ "def", "scaled_array_2d_with_sub_dimensions_from_sub_array_1d", "(", "self", ",", "sub_array_1d", ")", ":", "return", "scaled_array", ".", "ScaledSquarePixelArray", "(", "array", "=", "self", ".", "sub_array_2d_from_sub_array_1d", "(", "sub_array_1d", "=", "sub_array_1d", ...
57.166667
31.416667
def community_user_comments(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/help_center/post_comments#list-comments" api_path = "/api/v2/community/users/{id}/comments.json" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
[ "def", "community_user_comments", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/community/users/{id}/comments.json\"", "api_path", "=", "api_path", ".", "format", "(", "id", "=", "id", ")", "return", "self", ".", "call"...
57.8
17.8
def gradient_local(self, f, index): """ Return the gradient at a specified node. This routine employs a local method, in which values depend only on nearby data points, to compute an estimated gradient at a node. gradient_local() is more efficient than gradient() only if it is ...
[ "def", "gradient_local", "(", "self", ",", "f", ",", "index", ")", ":", "if", "f", ".", "size", "!=", "self", ".", "npoints", ":", "raise", "ValueError", "(", "'f should be the same size as mesh'", ")", "f", "=", "self", ".", "_shuffle_field", "(", "f", ...
33.130435
26.434783
def stats(self): """ Get the stats for the current :class:`Milestone` """ response = self.requester.get( '/{endpoint}/{id}/stats', endpoint=self.endpoint, id=self.id ) return response.json()
[ "def", "stats", "(", "self", ")", ":", "response", "=", "self", ".", "requester", ".", "get", "(", "'/{endpoint}/{id}/stats'", ",", "endpoint", "=", "self", ".", "endpoint", ",", "id", "=", "self", ".", "id", ")", "return", "response", ".", "json", "("...
28.222222
10.222222
def line_evaluate(t, p0, a, b, c): """Evaluate the orthogonal polynomial defined by its recurrence coefficients a, b, and c at the point(s) t. """ vals1 = numpy.zeros_like(t, dtype=int) # The order is important here; see # <https://github.com/sympy/sympy/issues/13637>. vals2 = numpy.ones_lik...
[ "def", "line_evaluate", "(", "t", ",", "p0", ",", "a", ",", "b", ",", "c", ")", ":", "vals1", "=", "numpy", ".", "zeros_like", "(", "t", ",", "dtype", "=", "int", ")", "# The order is important here; see", "# <https://github.com/sympy/sympy/issues/13637>.", "v...
35.692308
9
def cookie_decode(data, key, digestmod=None): """ Verify and decode an encoded string. Return an object or None.""" depr(0, 13, "cookie_decode() will be removed soon.", "Do not use this API directly.") data = tob(data) if cookie_is_encoded(data): sig, msg = data.split(tob('?'), 1...
[ "def", "cookie_decode", "(", "data", ",", "key", ",", "digestmod", "=", "None", ")", ":", "depr", "(", "0", ",", "13", ",", "\"cookie_decode() will be removed soon.\"", ",", "\"Do not use this API directly.\"", ")", "data", "=", "tob", "(", "data", ")", "if", ...
46.166667
12.416667
def _bss_decomp_mtifilt_images(reference_sources, estimated_source, j, flen, Gj=None, G=None): """Decomposition of an estimated source image into four components representing respectively the true source image, spatial (or filtering) distortion, interference and artifacts, der...
[ "def", "_bss_decomp_mtifilt_images", "(", "reference_sources", ",", "estimated_source", ",", "j", ",", "flen", ",", "Gj", "=", "None", ",", "G", "=", "None", ")", ":", "nsampl", "=", "np", ".", "shape", "(", "estimated_source", ")", "[", "0", "]", "nchan...
46.5
18.391304
def acquire(self) -> Connection: '''Register and return a connection. Coroutine. ''' assert not self._closed yield from self._condition.acquire() while True: if self.ready: connection = self.ready.pop() break elif...
[ "def", "acquire", "(", "self", ")", "->", "Connection", ":", "assert", "not", "self", ".", "_closed", "yield", "from", "self", ".", "_condition", ".", "acquire", "(", ")", "while", "True", ":", "if", "self", ".", "ready", ":", "connection", "=", "self"...
25.173913
19.347826
def _run_purecn_dx(out, paired): """Extract signatures and mutational burdens from PureCN rds file. """ out_base, out, all_files = _get_purecn_dx_files(paired, out) if not utils.file_uptodate(out["mutation_burden"], out["rds"]): with file_transaction(paired.tumor_data, out_base) as tx_out_base: ...
[ "def", "_run_purecn_dx", "(", "out", ",", "paired", ")", ":", "out_base", ",", "out", ",", "all_files", "=", "_get_purecn_dx_files", "(", "paired", ",", "out", ")", "if", "not", "utils", ".", "file_uptodate", "(", "out", "[", "\"mutation_burden\"", "]", ",...
59.214286
25.571429
def dtdQElementDesc(self, name, prefix): """Search the DTD for the description of this element """ ret = libxml2mod.xmlGetDtdQElementDesc(self._o, name, prefix) if ret is None:raise treeError('xmlGetDtdQElementDesc() failed') __tmp = xmlElement(_obj=ret) return __tmp
[ "def", "dtdQElementDesc", "(", "self", ",", "name", ",", "prefix", ")", ":", "ret", "=", "libxml2mod", ".", "xmlGetDtdQElementDesc", "(", "self", ".", "_o", ",", "name", ",", "prefix", ")", "if", "ret", "is", "None", ":", "raise", "treeError", "(", "'x...
50.333333
14.166667
def wait_for(self, condition, timeout=None, interval=0.1, errmsg=None): '''Wait for a condition to be True. Wait for condition, a callable, to return True. If timeout is nonzero, raise a TimeoutError(errmsg) if the condition is not True after timeout seconds. Check the condition evera...
[ "def", "wait_for", "(", "self", ",", "condition", ",", "timeout", "=", "None", ",", "interval", "=", "0.1", ",", "errmsg", "=", "None", ")", ":", "t0", "=", "time", ".", "time", "(", ")", "while", "not", "condition", "(", ")", ":", "t1", "=", "ti...
34.75
21
def plotted_data(self): """The data that is shown to the user""" return InteractiveList( [arr for arr, val in zip(self.iter_data, cycle(slist(self.value))) if val is not None])
[ "def", "plotted_data", "(", "self", ")", ":", "return", "InteractiveList", "(", "[", "arr", "for", "arr", ",", "val", "in", "zip", "(", "self", ".", "iter_data", ",", "cycle", "(", "slist", "(", "self", ".", "value", ")", ")", ")", "if", "val", "is...
41.5
11.166667
def add_unqualified_edge(self, u: BaseEntity, v: BaseEntity, relation: str) -> str: """Add a unique edge that has no annotations. :param u: The source node :param v: The target node :param relation: A relationship label from :mod:`pybel.constants` :return: The key for this edge ...
[ "def", "add_unqualified_edge", "(", "self", ",", "u", ":", "BaseEntity", ",", "v", ":", "BaseEntity", ",", "relation", ":", "str", ")", "->", "str", ":", "attr", "=", "{", "RELATION", ":", "relation", "}", "return", "self", ".", "_help_add_edge", "(", ...
42.1
15.5
def greedy_replace(self, seq): ''' Greedily matches strings in ``seq``, and replaces them with their node values. Arguments: - `seq`: an iterable of characters to perform search-and-replace on ''' if not self._suffix_links_set: self._set_suffix_links(...
[ "def", "greedy_replace", "(", "self", ",", "seq", ")", ":", "if", "not", "self", ".", "_suffix_links_set", ":", "self", ".", "_set_suffix_links", "(", ")", "# start at the root", "current", "=", "self", ".", "root", "buffered", "=", "''", "outstr", "=", "'...
34.732143
11.446429
def canonical_url(configs, vip_setting='vip'): ''' Returns the correct HTTP URL to this host given the state of HTTPS configuration and hacluster. :configs : OSTemplateRenderer: A config tempating object to inspect for a complete https context. :vip_setting...
[ "def", "canonical_url", "(", "configs", ",", "vip_setting", "=", "'vip'", ")", ":", "scheme", "=", "'http'", "if", "'https'", "in", "configs", ".", "complete_contexts", "(", ")", ":", "scheme", "=", "'https'", "if", "is_clustered", "(", ")", ":", "addr", ...
35.052632
20.842105
def create(self, price_estimate): """ Take configuration from previous month, it it exists. Set last_update_time equals to the beginning of the month. """ kwargs = {} try: previous_price_estimate = price_estimate.get_previous() except ObjectDoesNotExist: ...
[ "def", "create", "(", "self", ",", "price_estimate", ")", ":", "kwargs", "=", "{", "}", "try", ":", "previous_price_estimate", "=", "price_estimate", ".", "get_previous", "(", ")", "except", "ObjectDoesNotExist", ":", "pass", "else", ":", "configuration", "=",...
48.733333
24.066667
def start(self, io_handler, bundle_id, *bundles_ids): """ Starts the bundles with the given IDs. Stops on first failure. """ for bid in (bundle_id,) + bundles_ids: try: # Got an int => it's a bundle ID bid = int(bid) except ValueErr...
[ "def", "start", "(", "self", ",", "io_handler", ",", "bundle_id", ",", "*", "bundles_ids", ")", ":", "for", "bid", "in", "(", "bundle_id", ",", ")", "+", "bundles_ids", ":", "try", ":", "# Got an int => it's a bundle ID", "bid", "=", "int", "(", "bid", "...
33.125
15.291667
def extrude(self, height, **kwargs): """ Extrude the current 2D path into a 3D mesh. Parameters ---------- height: float, how far to extrude the profile kwargs: passed directly to meshpy.triangle.build: triangle.build(mesh_info, ...
[ "def", "extrude", "(", "self", ",", "height", ",", "*", "*", "kwargs", ")", ":", "from", ".", ".", "primitives", "import", "Extrusion", "result", "=", "[", "Extrusion", "(", "polygon", "=", "i", ",", "height", "=", "height", ",", "*", "*", "kwargs", ...
39.233333
13.166667
def flag_length_outliers(df, columnname): """Return index of records with length-outliers above 3 standard deviations from the median.""" return df[columnname] > (np.median(df[columnname]) + 3 * np.std(df[columnname]))
[ "def", "flag_length_outliers", "(", "df", ",", "columnname", ")", ":", "return", "df", "[", "columnname", "]", ">", "(", "np", ".", "median", "(", "df", "[", "columnname", "]", ")", "+", "3", "*", "np", ".", "std", "(", "df", "[", "columnname", "]"...
74.666667
15
def hook_setup(parent, hook_fpath): """Setup hook""" hook = copy.deepcopy(HOOK) hook["name"] = os.path.splitext(os.path.basename(hook_fpath))[0] hook["name"] = hook["name"].replace("_enter", "").replace("_exit", "") hook["res_root"] = parent["res_root"] hook["fpath_orig"] = hook_fpath hook[...
[ "def", "hook_setup", "(", "parent", ",", "hook_fpath", ")", ":", "hook", "=", "copy", ".", "deepcopy", "(", "HOOK", ")", "hook", "[", "\"name\"", "]", "=", "os", ".", "path", ".", "splitext", "(", "os", ".", "path", ".", "basename", "(", "hook_fpath"...
33.1
20.6
def contains(self, name: str) -> List[str]: """Return a list of all keywords containing the given string. >>> from hydpy.core.devicetools import Keywords >>> keywords = Keywords('first_keyword', 'second_keyword', ... 'keyword_3', 'keyword_4', ... ...
[ "def", "contains", "(", "self", ",", "name", ":", "str", ")", "->", "List", "[", "str", "]", ":", "return", "sorted", "(", "keyword", "for", "keyword", "in", "self", "if", "name", "in", "keyword", ")" ]
47.454545
14.727273
def log_exception(exc_info=None, stream=None): """Log the 'exc_info' tuple in the server log.""" exc_info = exc_info or sys.exc_info() stream = stream or sys.stderr try: from traceback import print_exception print_exception(exc_info[0], exc_info[1], exc_info[2], None, stream) str...
[ "def", "log_exception", "(", "exc_info", "=", "None", ",", "stream", "=", "None", ")", ":", "exc_info", "=", "exc_info", "or", "sys", ".", "exc_info", "(", ")", "stream", "=", "stream", "or", "sys", ".", "stderr", "try", ":", "from", "traceback", "impo...
35.9
15
def _mwi(self): """ Apply moving wave integration (mwi) with a ricker (Mexican hat) wavelet onto the filtered signal, and save the square of the integrated signal. The width of the hat is equal to the qrs width After integration, find all local peaks in the mwi signal. ...
[ "def", "_mwi", "(", "self", ")", ":", "wavelet_filter", "=", "signal", ".", "ricker", "(", "self", ".", "qrs_width", ",", "4", ")", "self", ".", "sig_i", "=", "signal", ".", "filtfilt", "(", "wavelet_filter", ",", "[", "1", "]", ",", "self", ".", "...
41.772727
23.409091
def show_message(device, msg, y_offset=0, fill=None, font=None, scroll_delay=0.03): """ Scrolls a message right-to-left across the devices display. :param device: The device to scroll across. :param msg: The text message to display (must be ASCII only). :type msg: str :param y_...
[ "def", "show_message", "(", "device", ",", "msg", ",", "y_offset", "=", "0", ",", "fill", "=", "None", ",", "font", "=", "None", ",", "scroll_delay", "=", "0.03", ")", ":", "fps", "=", "0", "if", "scroll_delay", "==", "0", "else", "1.0", "/", "scro...
34.363636
19.272727
def generate_confirmation_token(self, user): """ Generates a unique confirmation token for the specified user. :param user: The user to work with """ data = [str(user.id), self.hash_data(user.email)] return self.security.confirm_serializer.dumps(data)
[ "def", "generate_confirmation_token", "(", "self", ",", "user", ")", ":", "data", "=", "[", "str", "(", "user", ".", "id", ")", ",", "self", ".", "hash_data", "(", "user", ".", "email", ")", "]", "return", "self", ".", "security", ".", "confirm_seriali...
36.625
13.875
def _parse_args(): """ Parses the command line arguments. :return: Namespace with arguments. :rtype: Namespace """ parser = argparse.ArgumentParser(description='rain - a new sort of automated builder.') parser.add_argument('action', help='what shall we do?', default='build', nargs='?',...
[ "def", "_parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'rain - a new sort of automated builder.'", ")", "parser", ".", "add_argument", "(", "'action'", ",", "help", "=", "'what shall we do?'", ",", "default",...
40.230769
28.384615
def extern_store_dict(self, context_handle, vals_ptr, vals_len): """Given storage and an array of Handles, return a new Handle to represent the dict. Array of handles alternates keys and values (i.e. key0, value0, key1, value1, ...). It is assumed that an even number of values were passed. """ c =...
[ "def", "extern_store_dict", "(", "self", ",", "context_handle", ",", "vals_ptr", ",", "vals_len", ")", ":", "c", "=", "self", ".", "_ffi", ".", "from_handle", "(", "context_handle", ")", "tup", "=", "tuple", "(", "c", ".", "from_value", "(", "val", "[", ...
41.307692
21.538462
def stack(self, new_column_name=None, drop_na=False, new_column_type=None): """ Convert a "wide" SArray to one or two "tall" columns in an SFrame by stacking all values. The stack works only for columns of dict, list, or array type. If the column is dict type, two new columns a...
[ "def", "stack", "(", "self", ",", "new_column_name", "=", "None", ",", "drop_na", "=", "False", ",", "new_column_type", "=", "None", ")", ":", "from", ".", "sframe", "import", "SFrame", "as", "_SFrame", "return", "_SFrame", "(", "{", "'SArray'", ":", "se...
41.671053
25.25
def _get_thumbnail_src_from_file(dir_path, image_file, force_no_processing=False): """ Get base-64 encoded data as a string for the given image file's thumbnail, for use directly in HTML <img> tags, or a path to the original if image scaling is not supported. @param {String} dir_path - The directory...
[ "def", "_get_thumbnail_src_from_file", "(", "dir_path", ",", "image_file", ",", "force_no_processing", "=", "False", ")", ":", "# If we've specified to force no processing, just return the image filename", "if", "force_no_processing", ":", "if", "image_file", ".", "endswith", ...
53.142857
21.714286
def _get_upsert_sql(queryset, model_objs, unique_fields, update_fields, returning, ignore_duplicate_updates=True, return_untouched=False): """ Generates the postgres specific sql necessary to perform an upsert (ON CONFLICT) INSERT INTO table_name (field1, field2) VALUES (1, 'two') ...
[ "def", "_get_upsert_sql", "(", "queryset", ",", "model_objs", ",", "unique_fields", ",", "update_fields", ",", "returning", ",", "ignore_duplicate_updates", "=", "True", ",", "return_untouched", "=", "False", ")", ":", "model", "=", "queryset", ".", "model", "# ...
39.642202
21.917431
def categorical2transactions(x): # type: (np.ndarray) -> List """ Convert a 2D int array into a transaction list: [ ['x0=1', 'x1=0', ...], ... ] :param x: :return: """ assert len(x.shape) == 2 transactions = [] for entry in x: transact...
[ "def", "categorical2transactions", "(", "x", ")", ":", "# type: (np.ndarray) -> List", "assert", "len", "(", "x", ".", "shape", ")", "==", "2", "transactions", "=", "[", "]", "for", "entry", "in", "x", ":", "transactions", ".", "append", "(", "[", "'x%d=%d...
21.833333
20.277778
def separate_reach_logs(log_str): """Get the list of reach logs from the overall logs.""" log_lines = log_str.splitlines() reach_logs = [] reach_lines = [] adding_reach_lines = False for l in log_lines[:]: if not adding_reach_lines and 'Beginning reach' in l: adding_reach_lin...
[ "def", "separate_reach_logs", "(", "log_str", ")", ":", "log_lines", "=", "log_str", ".", "splitlines", "(", ")", "reach_logs", "=", "[", "]", "reach_lines", "=", "[", "]", "adding_reach_lines", "=", "False", "for", "l", "in", "log_lines", "[", ":", "]", ...
40.157895
12.210526
async def _set_persistent_menu(self): """ Define the persistent menu for all pages """ page = self.settings() if 'menu' in page: await self._send_to_messenger_profile(page, { 'persistent_menu': page['menu'], }) logger.info('S...
[ "async", "def", "_set_persistent_menu", "(", "self", ")", ":", "page", "=", "self", ".", "settings", "(", ")", "if", "'menu'", "in", "page", ":", "await", "self", ".", "_send_to_messenger_profile", "(", "page", ",", "{", "'persistent_menu'", ":", "page", "...
26.615385
17.692308
def write_single_file(args, base_dir, crawler): """Write to a single output file and/or subdirectory.""" if args['urls'] and args['html']: # Create a directory to save PART.html files in domain = utils.get_domain(args['urls'][0]) if not args['quiet']: print('Storing html file...
[ "def", "write_single_file", "(", "args", ",", "base_dir", ",", "crawler", ")", ":", "if", "args", "[", "'urls'", "]", "and", "args", "[", "'html'", "]", ":", "# Create a directory to save PART.html files in", "domain", "=", "utils", ".", "get_domain", "(", "ar...
38.162791
16.44186
def time_to_jump( self ): """ The timestep until the next jump. Args: None Returns: (Float): The timestep until the next jump. """ k_tot = rate_prefactor * np.sum( self.p ) return -( 1.0 / k_tot ) * math.log( random.random() )
[ "def", "time_to_jump", "(", "self", ")", ":", "k_tot", "=", "rate_prefactor", "*", "np", ".", "sum", "(", "self", ".", "p", ")", "return", "-", "(", "1.0", "/", "k_tot", ")", "*", "math", ".", "log", "(", "random", ".", "random", "(", ")", ")" ]
24.833333
17.916667
def main(codelabel, submit): """Command line interface for testing and submitting calculations. This script extends submit.py, adding flexibility in the selected code/computer. Run './cli.py --help' to see options. """ code = Code.get_from_string(codelabel) # set up calculation calc = cod...
[ "def", "main", "(", "codelabel", ",", "submit", ")", ":", "code", "=", "Code", ".", "get_from_string", "(", "codelabel", ")", "# set up calculation", "calc", "=", "code", ".", "new_calc", "(", ")", "calc", ".", "label", "=", "\"compute rips from distance matri...
35.921053
17.473684
def start_watcher(self): """ Start the watcher thread that tries to upload usage statistics. """ if self._watcher and self._watcher.is_alive: self._watcher_enabled = True else: logger.debug('Starting watcher.') self._watcher = threading.Thread(...
[ "def", "start_watcher", "(", "self", ")", ":", "if", "self", ".", "_watcher", "and", "self", ".", "_watcher", ".", "is_alive", ":", "self", ".", "_watcher_enabled", "=", "True", "else", ":", "logger", ".", "debug", "(", "'Starting watcher.'", ")", "self", ...
39.666667
12.833333
def move_grid_to_radial_minimum(func): """ Checks whether any coordinates in the grid are radially near (0.0, 0.0), which can lead to numerical faults in \ the evaluation of a light or mass profiles. If any coordinates are radially within the the radial minimum \ threshold, their (y,x) coordinates are shift...
[ "def", "move_grid_to_radial_minimum", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapper", "(", "profile", ",", "grid", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n\n Parameters\n ----------\n profile : Sp...
41.133333
29.733333
def get_user_orders(self, id, **data): """ GET /users/:id/orders/ Returns a :ref:`paginated <pagination>` response of :format:`orders <order>`, under the key ``orders``, of all orders the user has placed (i.e. where the user was the person buying the tickets). :param int id: The id assig...
[ "def", "get_user_orders", "(", "self", ",", "id", ",", "*", "*", "data", ")", ":", "return", "self", ".", "get", "(", "\"/users/{0}/orders/\"", ".", "format", "(", "id", ")", ",", "data", "=", "data", ")" ]
63.2
37.8
def parse_from_args(synonyms): ''' Parse an array of string from argparser to SynonymSet ''' syns_str = ''.join(synonyms) syns_str = syns_str.replace(' ', '') syn_set = SynonymSet() # to check if we are parsing inside the parenthesis inside_set = False current_syn = '' ...
[ "def", "parse_from_args", "(", "synonyms", ")", ":", "syns_str", "=", "''", ".", "join", "(", "synonyms", ")", "syns_str", "=", "syns_str", ".", "replace", "(", "' '", ",", "''", ")", "syn_set", "=", "SynonymSet", "(", ")", "# to check if we are parsing insi...
21.083333
22.75
def session_rollback(self, session): """Send session_rollback signal in sqlalchemy ``after_rollback``. This marks the failure of session so the session may enter commit phase. """ # this may happen when there's nothing to rollback if not hasattr(session, 'meepo_unique_id...
[ "def", "session_rollback", "(", "self", ",", "session", ")", ":", "# this may happen when there's nothing to rollback", "if", "not", "hasattr", "(", "session", ",", "'meepo_unique_id'", ")", ":", "self", ".", "logger", ".", "debug", "(", "\"skipped - session_rollback\...
39.6
17.733333
def plot(self, columns=None, **errorbar_kwargs): """ Produces a visual representation of the coefficients, including their standard errors and magnitudes. Parameters ---------- columns : list, optional specify a subset of the columns to plot errorbar_kwargs: ...
[ "def", "plot", "(", "self", ",", "columns", "=", "None", ",", "*", "*", "errorbar_kwargs", ")", ":", "from", "matplotlib", "import", "pyplot", "as", "plt", "ax", "=", "errorbar_kwargs", ".", "pop", "(", "\"ax\"", ",", "None", ")", "or", "plt", ".", "...
34.509804
23.568627
def line(*args, **kwargs): """This function creates a line chart. Specifcally it creates an :py:class:`.AxisChart` and then adds a :py:class:`.LineSeries` to it. :param \*data: The data for the line series as either (x,y) values or two\ big tuples/lists of x and y values respectively. :param str na...
[ "def", "line", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "line_series_kwargs", "=", "{", "}", "for", "kwarg", "in", "(", "\"name\"", ",", "\"color\"", ",", "\"linestyle\"", ",", "\"linewidth\"", ")", ":", "if", "kwarg", "in", "kwargs", ":", ...
46.96875
19.375
def unmerged_blobs(self): """ :return: Iterator yielding dict(path : list( tuple( stage, Blob, ...))), being a dictionary associating a path in the index with a list containing sorted stage/blob pairs :note: Blobs that have been removed in one sid...
[ "def", "unmerged_blobs", "(", "self", ")", ":", "is_unmerged_blob", "=", "lambda", "t", ":", "t", "[", "0", "]", "!=", "0", "path_map", "=", "{", "}", "for", "stage", ",", "blob", "in", "self", ".", "iter_blobs", "(", "is_unmerged_blob", ")", ":", "p...
39.85
20.35
def DbPutProperty(self, argin): """ Create / Update free object property(ies) :param argin: Str[0] = Object name Str[1] = Property number Str[2] = Property name Str[3] = Property value number Str[4] = Property value 1 Str[n] = Property value n .... ...
[ "def", "DbPutProperty", "(", "self", ",", "argin", ")", ":", "self", ".", "_log", ".", "debug", "(", "\"In DbPutProperty()\"", ")", "object_name", "=", "argin", "[", "0", "]", "nb_properties", "=", "int", "(", "argin", "[", "1", "]", ")", "self", ".", ...
33.352941
10.647059
def dew_point_from_db_enth(db_temp, enthlpy, b_press=101325): """Dew Point Temperature (C) at Temperature db_temp (C), enthalpy (kJ/kg) and Pressure b_press (Pa). """ rh = rel_humid_from_db_enth(db_temp, enthlpy, b_press) td = dew_point_from_db_rh(db_temp, rh) return td
[ "def", "dew_point_from_db_enth", "(", "db_temp", ",", "enthlpy", ",", "b_press", "=", "101325", ")", ":", "rh", "=", "rel_humid_from_db_enth", "(", "db_temp", ",", "enthlpy", ",", "b_press", ")", "td", "=", "dew_point_from_db_rh", "(", "db_temp", ",", "rh", ...
41.142857
11.142857
def extract_protocol(self): """extract 802.11 protocol from radiotap.channel.flags :return: str protocol name one of below in success [.11a, .11b, .11g, .11n, .11ac] None in fail """ if self.present.mcs: return '.11n' i...
[ "def", "extract_protocol", "(", "self", ")", ":", "if", "self", ".", "present", ".", "mcs", ":", "return", "'.11n'", "if", "self", ".", "present", ".", "vht", ":", "return", "'.11ac'", "if", "self", ".", "present", ".", "channel", "and", "hasattr", "("...
30.041667
12.833333
def _get(self, url, params=None): """ Wrapper method for GET calls. """ self._call(self.GET, url, params, None)
[ "def", "_get", "(", "self", ",", "url", ",", "params", "=", "None", ")", ":", "self", ".", "_call", "(", "self", ".", "GET", ",", "url", ",", "params", ",", "None", ")" ]
41.666667
4.666667
def transfer_project(self, to_namespace, **kwargs): """Transfer a project to the given namespace ID Args: to_namespace (str): ID or path of the namespace to transfer the project to **kwargs: Extra options to send to the server (e.g. sudo) Raises: ...
[ "def", "transfer_project", "(", "self", ",", "to_namespace", ",", "*", "*", "kwargs", ")", ":", "path", "=", "'/projects/%s/transfer'", "%", "(", "self", ".", "id", ",", ")", "self", ".", "manager", ".", "gitlab", ".", "http_put", "(", "path", ",", "po...
42.125
21.75
def find_target_container(portal_type, record): """Locates a target container for the given portal_type and record :param record: The dictionary representation of a content object :type record: dict :returns: folder which contains the object :rtype: object """ portal_type = portal_type or r...
[ "def", "find_target_container", "(", "portal_type", ",", "record", ")", ":", "portal_type", "=", "portal_type", "or", "record", ".", "get", "(", "\"portal_type\"", ")", "container", "=", "get_container_for", "(", "portal_type", ")", "if", "container", ":", "retu...
28.366667
19.4
def _buildTemplates(self): """ OVERRIDING THIS METHOD from Factory """ jsontree_classes = build_D3treeStandard( 0, 99, 1, self.ontospy_graph.toplayer_classes) c_total = len(self.ontospy_graph.all_classes) JSON_DATA_CLASSES = json.dumps({ 'childre...
[ "def", "_buildTemplates", "(", "self", ")", ":", "jsontree_classes", "=", "build_D3treeStandard", "(", "0", ",", "99", ",", "1", ",", "self", ".", "ontospy_graph", ".", "toplayer_classes", ")", "c_total", "=", "len", "(", "self", ".", "ontospy_graph", ".", ...
29.851852
16.888889
def add_accent_char(char, accent): """ Add accent to a single char. Parameter accent is member of class Accent """ if char == "": return "" case = char.isupper() char = char.lower() index = utils.VOWELS.find(char) if (index != -1): index = index - index % 6 + 5 ...
[ "def", "add_accent_char", "(", "char", ",", "accent", ")", ":", "if", "char", "==", "\"\"", ":", "return", "\"\"", "case", "=", "char", ".", "isupper", "(", ")", "char", "=", "char", ".", "lower", "(", ")", "index", "=", "utils", ".", "VOWELS", "."...
27.571429
12.285714
def name_backbone(name, rank=None, kingdom=None, phylum=None, clazz=None, order=None, family=None, genus=None, strict=False, verbose=False, offset=None, limit=100, **kwargs): ''' Lookup names in the GBIF backbone taxonomy. :param name: [str] Full scientific name potentially with authorship (required) :para...
[ "def", "name_backbone", "(", "name", ",", "rank", "=", "None", ",", "kingdom", "=", "None", ",", "phylum", "=", "None", ",", "clazz", "=", "None", ",", "order", "=", "None", ",", "family", "=", "None", ",", "genus", "=", "None", ",", "strict", "=",...
50.786885
30.360656
def _check_authorization(self, properties, stream): """Check authorization id and other properties returned by the authentication mechanism. [receiving entity only] Allow only no authzid or authzid equal to current username@domain FIXME: other rules in s2s :Parameters...
[ "def", "_check_authorization", "(", "self", ",", "properties", ",", "stream", ")", ":", "authzid", "=", "properties", ".", "get", "(", "\"authzid\"", ")", "if", "not", "authzid", ":", "return", "True", "try", ":", "jid", "=", "JID", "(", "authzid", ")", ...
28
18.189189
def bytes_block_cast(block, include_text=True, include_link_tokens=True, include_css=True, include_features=True, **kwargs): """ Converts any string-like items in input Block object to bytes-like values, ...
[ "def", "bytes_block_cast", "(", "block", ",", "include_text", "=", "True", ",", "include_link_tokens", "=", "True", ",", "include_css", "=", "True", ",", "include_features", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "include_text", ":", "block", ...
36.444444
14.611111
def get_subport_statistics(self, id_or_uri, port_name, subport_number): """ Gets the subport statistics on an interconnect. Args: id_or_uri: Can be either the interconnect id or the interconnect uri. port_name (str): A specific port name of an interconnect. ...
[ "def", "get_subport_statistics", "(", "self", ",", "id_or_uri", ",", "port_name", ",", "subport_number", ")", ":", "uri", "=", "self", ".", "_client", ".", "build_uri", "(", "id_or_uri", ")", "+", "\"/statistics/{0}/subport/{1}\"", ".", "format", "(", "port_name...
44.642857
28.071429
def RFC3339(self): """RFC3339. `Link to RFC3339.`__ __ https://www.ietf.org/rfc/rfc3339.txt """ # get timezone offset delta_sec = time.timezone m, s = divmod(delta_sec, 60) h, m = divmod(m, 60) # timestamp format_string = "%Y-%m-%dT%H:%M:...
[ "def", "RFC3339", "(", "self", ")", ":", "# get timezone offset", "delta_sec", "=", "time", ".", "timezone", "m", ",", "s", "=", "divmod", "(", "delta_sec", ",", "60", ")", "h", ",", "m", "=", "divmod", "(", "m", ",", "60", ")", "# timestamp", "forma...
25.642857
16.571429
def getParameter(self, name, index=-1): """ Overrides :meth:`nupic.bindings.regions.PyRegion.PyRegion.getParameter`. """ if name == "trainRecords": return self.trainRecords elif name == "anomalyThreshold": return self.anomalyThreshold elif name == "activeColumnCount": return se...
[ "def", "getParameter", "(", "self", ",", "name", ",", "index", "=", "-", "1", ")", ":", "if", "name", "==", "\"trainRecords\"", ":", "return", "self", ".", "trainRecords", "elif", "name", "==", "\"anomalyThreshold\"", ":", "return", "self", ".", "anomalyTh...
37.8125
10.5625
def xlsx_to_strio(xlsx_wb): """ convert xlwt Workbook instance to a BytesIO instance """ _xlrd_required() fh = BytesIO() xlsx_wb.filename = fh xlsx_wb.close() # prep for reading fh.seek(0) return fh
[ "def", "xlsx_to_strio", "(", "xlsx_wb", ")", ":", "_xlrd_required", "(", ")", "fh", "=", "BytesIO", "(", ")", "xlsx_wb", ".", "filename", "=", "fh", "xlsx_wb", ".", "close", "(", ")", "# prep for reading", "fh", ".", "seek", "(", "0", ")", "return", "f...
21.090909
16.545455
def lacp_timeout(self, **kwargs): """Set lacp timeout. Args: int_type (str): Type of interface. (gigabitethernet, tengigabitethernet, etc) timeout (str): Timeout length. (short, long) name (str): Name of interface. (1/0/5, 1/0/10, etc) c...
[ "def", "lacp_timeout", "(", "self", ",", "*", "*", "kwargs", ")", ":", "int_type", "=", "kwargs", ".", "pop", "(", "'int_type'", ")", ".", "lower", "(", ")", "name", "=", "kwargs", ".", "pop", "(", "'name'", ")", "timeout", "=", "kwargs", ".", "pop...
37.41791
18.268657
def create_report(self, **params): """https://developers.coinbase.com/api/v2#generate-a-new-report""" if 'type' not in params and 'email' not in params: raise ValueError("Missing required parameter: 'type' or 'email'") response = self._post('v2', 'reports', data=params) retur...
[ "def", "create_report", "(", "self", ",", "*", "*", "params", ")", ":", "if", "'type'", "not", "in", "params", "and", "'email'", "not", "in", "params", ":", "raise", "ValueError", "(", "\"Missing required parameter: 'type' or 'email'\"", ")", "response", "=", ...
59.333333
15.666667
def rpc_refactor(self, filename, method, args): """Return a list of changes from the refactoring action. A change is a dictionary describing the change. See elpy.refactor.translate_changes for a description. """ try: from elpy import refactor except: ...
[ "def", "rpc_refactor", "(", "self", ",", "filename", ",", "method", ",", "args", ")", ":", "try", ":", "from", "elpy", "import", "refactor", "except", ":", "raise", "ImportError", "(", "\"Rope not installed, refactorings unavailable\"", ")", "if", "args", "is", ...
35.333333
18.466667
def get_all_roles(resource_root, service_name, cluster_name="default", view=None): """ Get all roles @param resource_root: The root Resource object. @param service_name: Service name @param cluster_name: Cluster name @return: A list of ApiRole objects. """ return call(resource_root.get, _get_roles...
[ "def", "get_all_roles", "(", "resource_root", ",", "service_name", ",", "cluster_name", "=", "\"default\"", ",", "view", "=", "None", ")", ":", "return", "call", "(", "resource_root", ".", "get", ",", "_get_roles_path", "(", "cluster_name", ",", "service_name", ...
36.909091
11.636364
def get_commensurate_points_in_integers(supercell_matrix): """Commensurate q-points in integer representation are returned. A set of integer representation of lattice points is transformed to the equivalent set of lattice points in fractional coordinates with respect to supercell basis vectors by ...
[ "def", "get_commensurate_points_in_integers", "(", "supercell_matrix", ")", ":", "smat", "=", "np", ".", "array", "(", "supercell_matrix", ",", "dtype", "=", "int", ")", "snf", "=", "SNF3x3", "(", "smat", ".", "T", ")", "snf", ".", "run", "(", ")", "D", ...
35.30303
21.212121
def _dT_h_delta(T_in_kK, eta, k, threenk, c_v): """ internal function for calculation of temperature along a Hugoniot :param T_in_kK: temperature in kK scale, see Jamieson for detail :param eta: = 1 - rho0/rho :param k: = [rho0, c0, s, gamma0, q, theta0] :param threenk: see the definition in Ja...
[ "def", "_dT_h_delta", "(", "T_in_kK", ",", "eta", ",", "k", ",", "threenk", ",", "c_v", ")", ":", "rho0", "=", "k", "[", "0", "]", "# g/m^3", "gamma0", "=", "k", "[", "3", "]", "# no unit", "q", "=", "k", "[", "4", "]", "# no unit", "theta0_in_kK...
37.111111
15.388889
def peek(self, size=-1): """ Return bytes from the stream without advancing the position. Args: size (int): Number of bytes to read. -1 to read the full stream. Returns: bytes: bytes read """ if not self._readable: rai...
[ "def", "peek", "(", "self", ",", "size", "=", "-", "1", ")", ":", "if", "not", "self", ".", "_readable", ":", "raise", "UnsupportedOperation", "(", "'read'", ")", "with", "self", ".", "_seek_lock", ":", "self", ".", "_raw", ".", "seek", "(", "self", ...
26.235294
17.647059
def export_mesh(mesh, file_obj, file_type=None, **kwargs): """ Export a Trimesh object to a file- like object, or to a filename Parameters --------- file_obj : str, file-like Where should mesh be exported to file_type : str or None Represents file type (eg: 'stl') Returns -...
[ "def", "export_mesh", "(", "mesh", ",", "file_obj", ",", "file_type", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# if we opened a file object in this function", "# we will want to close it when we're done", "was_opened", "=", "False", "if", "util", ".", "is_stri...
28.72549
18.764706
def last_child(self): """ Get the latest PID as pointed by the Head PID. If the 'pid' is a Head PID, return the latest of its children. If the 'pid' is a Version PID, return the latest of its siblings. Return None for the non-versioned PIDs. """ return self.child...
[ "def", "last_child", "(", "self", ")", ":", "return", "self", ".", "children", ".", "filter", "(", "PIDRelation", ".", "index", ".", "isnot", "(", "None", ")", ")", ".", "ordered", "(", ")", ".", "first", "(", ")" ]
38.3
16.7
def get_backend(self, backend_name): """ returns the given backend instance """ if backend_name == 'twitter': from social_friends_finder.backends.twitter_backend import TwitterFriendsProvider friends_provider = TwitterFriendsProvider() elif backend_name ==...
[ "def", "get_backend", "(", "self", ",", "backend_name", ")", ":", "if", "backend_name", "==", "'twitter'", ":", "from", "social_friends_finder", ".", "backends", ".", "twitter_backend", "import", "TwitterFriendsProvider", "friends_provider", "=", "TwitterFriendsProvider...
46.705882
19.882353
def _walk_req_to_install(self, handler): """Call handler for all pending reqs. :param handler: Handle a single requirement. Should take a requirement to install. Can optionally return an iterable of additional InstallRequirements to cover. """ # The list() here i...
[ "def", "_walk_req_to_install", "(", "self", ",", "handler", ")", ":", "# The list() here is to avoid potential mutate-while-iterating bugs.", "discovered_reqs", "=", "[", "]", "reqs", "=", "itertools", ".", "chain", "(", "list", "(", "self", ".", "unnamed_requirements",...
42.6875
15.8125
def finite_datetimes(self, finite_start, finite_stop): """ Simply returns the points in time that correspond to turn of month. """ start_date = self._align(finite_start) aligned_stop = self._align(finite_stop) dates = [] for m in itertools.count(): t =...
[ "def", "finite_datetimes", "(", "self", ",", "finite_start", ",", "finite_stop", ")", ":", "start_date", "=", "self", ".", "_align", "(", "finite_start", ")", "aligned_stop", "=", "self", ".", "_align", "(", "finite_stop", ")", "dates", "=", "[", "]", "for...
36.461538
10.461538
def set_cpu_property(self, property_p, value): """Sets the virtual CPU boolean value of the specified property. in property_p of type :class:`CPUPropertyType` Property type to query. in value of type bool Property value. raises :class:`OleErrorInvalidarg` ...
[ "def", "set_cpu_property", "(", "self", ",", "property_p", ",", "value", ")", ":", "if", "not", "isinstance", "(", "property_p", ",", "CPUPropertyType", ")", ":", "raise", "TypeError", "(", "\"property_p can only be an instance of type CPUPropertyType\"", ")", "if", ...
36.368421
16.947368
def get_cached_image(self, width, height, zoom, parameters=None, clear=False): """Get ImageSurface object, if possible, cached The method checks whether the image was already rendered. This is done by comparing the passed size and parameters with those of the last image. If they are equal, the ...
[ "def", "get_cached_image", "(", "self", ",", "width", ",", "height", ",", "zoom", ",", "parameters", "=", "None", ",", "clear", "=", "False", ")", ":", "global", "MAX_ALLOWED_AREA", "if", "not", "parameters", ":", "parameters", "=", "{", "}", "if", "self...
54.315789
30.315789
def has_no_dangling_branch(neuron): '''Check if the neuron has dangling neurites''' soma_center = neuron.soma.points[:, COLS.XYZ].mean(axis=0) recentered_soma = neuron.soma.points[:, COLS.XYZ] - soma_center radius = np.linalg.norm(recentered_soma, axis=1) soma_max_radius = radius.max() def is_d...
[ "def", "has_no_dangling_branch", "(", "neuron", ")", ":", "soma_center", "=", "neuron", ".", "soma", ".", "points", "[", ":", ",", "COLS", ".", "XYZ", "]", ".", "mean", "(", "axis", "=", "0", ")", "recentered_soma", "=", "neuron", ".", "soma", ".", "...
41.222222
21.814815
def _process_non_parallel(self, X: Union[pd.DataFrame, np.ndarray], n_refs: int, cluster_array: np.ndarray): """ Process calling of .calculate_gap() method using no parallel backend; simple for loop generator """ for gap_value, n_clusters in [self._calculate_gap(X, n_refs, n_clusters) ...
[ "def", "_process_non_parallel", "(", "self", ",", "X", ":", "Union", "[", "pd", ".", "DataFrame", ",", "np", ".", "ndarray", "]", ",", "n_refs", ":", "int", ",", "cluster_array", ":", "np", ".", "ndarray", ")", ":", "for", "gap_value", ",", "n_clusters...
60.714286
29
def weekday_to_str( weekday: Union[int, str], *, inverse: bool = False ) -> Union[int, str]: """ Given a weekday number (integer in the range 0, 1, ..., 6), return its corresponding weekday name as a lowercase string. Here 0 -> 'monday', 1 -> 'tuesday', and so on. If ``inverse``, then perform th...
[ "def", "weekday_to_str", "(", "weekday", ":", "Union", "[", "int", ",", "str", "]", ",", "*", ",", "inverse", ":", "bool", "=", "False", ")", "->", "Union", "[", "int", ",", "str", "]", ":", "s", "=", "[", "\"monday\"", ",", "\"tuesday\"", ",", "...
23.678571
20.107143
def gen_colors(img): """Generate a colorscheme using Colorz.""" palette = Haishoku.getPalette(img) return [util.rgb_to_hex(col[1]) for col in palette]
[ "def", "gen_colors", "(", "img", ")", ":", "palette", "=", "Haishoku", ".", "getPalette", "(", "img", ")", "return", "[", "util", ".", "rgb_to_hex", "(", "col", "[", "1", "]", ")", "for", "col", "in", "palette", "]" ]
39.75
9.25
def same_notebook_code(nb1, nb2): """ Return true of the code cells of notebook objects `nb1` and `nb2` are the same. """ # Notebooks do not match of the number of cells differ if len(nb1['cells']) != len(nb2['cells']): return False # Iterate over cells in nb1 for n in range(le...
[ "def", "same_notebook_code", "(", "nb1", ",", "nb2", ")", ":", "# Notebooks do not match of the number of cells differ", "if", "len", "(", "nb1", "[", "'cells'", "]", ")", "!=", "len", "(", "nb2", "[", "'cells'", "]", ")", ":", "return", "False", "# Iterate ov...
32.956522
20.782609