text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def set_section_order(self, section_name_list): """Set the order of the sections, which are by default unorderd. Any unlisted sections that exist will be placed at the end of the document in no particular order. """ self.section_headings = section_name_list[:] for sectio...
[ "def", "set_section_order", "(", "self", ",", "section_name_list", ")", ":", "self", ".", "section_headings", "=", "section_name_list", "[", ":", "]", "for", "section_name", "in", "self", ".", "sections", ".", "keys", "(", ")", ":", "if", "section_name", "no...
42.636364
14.363636
def updatePlaceWeights(self): """ We use a simplified version of Hebbian learning to learn place weights. Cells above the boost target are wired to the currently-active places, cells below it have their connection strength to them reduced. """ self.weightsPI += np.outer(self.activationsI - self....
[ "def", "updatePlaceWeights", "(", "self", ")", ":", "self", ".", "weightsPI", "+=", "np", ".", "outer", "(", "self", ".", "activationsI", "-", "self", ".", "boostTarget", ",", "self", ".", "activationsP", ")", "*", "self", ".", "dt", "*", "self", ".", ...
52.210526
21.052632
def zforce(self,R,z,phi=0.,t=0.): """ NAME: zforce PURPOSE: evaluate the vertical force F_z (R,z,t) INPUT: R - Cylindrical Galactocentric radius (can be Quantity) z - vertical height (can be Quantity) phi - azimuth (optional;...
[ "def", "zforce", "(", "self", ",", "R", ",", "z", ",", "phi", "=", "0.", ",", "t", "=", "0.", ")", ":", "return", "self", ".", "_zforce_nodecorator", "(", "R", ",", "z", ",", "phi", "=", "phi", ",", "t", "=", "t", ")" ]
17.866667
25.8
def sync_local_to_remote(force="no"): """ Sync your local postgres database with remote Example: fabrik prod sync_local_to_remote:force=yes """ _check_requirements() if force != "yes": message = "This will replace the remote database '%s' with your "\ "local '%s', ...
[ "def", "sync_local_to_remote", "(", "force", "=", "\"no\"", ")", ":", "_check_requirements", "(", ")", "if", "force", "!=", "\"yes\"", ":", "message", "=", "\"This will replace the remote database '%s' with your \"", "\"local '%s', are you sure [y/n]\"", "%", "(", "env", ...
27.921569
22.470588
def decompose_position(self, offset): """ Returns a ``line, column`` tuple for a character offset into the source, orraises :exc:`IndexError` if ``lineno`` is out of range. """ line_begins = self._extract_line_begins() lineno = bisect.bisect_right(line_begins, offset) - 1...
[ "def", "decompose_position", "(", "self", ",", "offset", ")", ":", "line_begins", "=", "self", ".", "_extract_line_begins", "(", ")", "lineno", "=", "bisect", ".", "bisect_right", "(", "line_begins", ",", "offset", ")", "-", "1", "if", "offset", ">=", "0",...
43.818182
16.727273
def matchFileOnDirPath(curpath, pathdir): """Find match for a file by slicing away its directory elements from the front and replacing them with pathdir. Assume that the end of curpath is right and but that the beginning may contain some garbage (or it may be short) Overlaps are allowed...
[ "def", "matchFileOnDirPath", "(", "curpath", ",", "pathdir", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "curpath", ")", ":", "return", "curpath", "filedirs", "=", "curpath", ".", "split", "(", "'/'", ")", "[", "1", ":", "]", "filename", "...
36.205128
14.153846
def get_all_formulae(chebi_ids): '''Returns all formulae''' all_formulae = [get_formulae(chebi_id) for chebi_id in chebi_ids] return [x for sublist in all_formulae for x in sublist]
[ "def", "get_all_formulae", "(", "chebi_ids", ")", ":", "all_formulae", "=", "[", "get_formulae", "(", "chebi_id", ")", "for", "chebi_id", "in", "chebi_ids", "]", "return", "[", "x", "for", "sublist", "in", "all_formulae", "for", "x", "in", "sublist", "]" ]
47.5
16.5
def extract_text(input_file, pageno=1): """Use the txtwrite device to get text layout information out For details on options of -dTextFormat see https://www.ghostscript.com/doc/current/VectorDevices.htm#TXT Format is like <page> <line> <span bbox="left top right bottom" font="..." size=".....
[ "def", "extract_text", "(", "input_file", ",", "pageno", "=", "1", ")", ":", "if", "pageno", "is", "not", "None", ":", "pages", "=", "[", "'-dFirstPage=%i'", "%", "pageno", ",", "'-dLastPage=%i'", "%", "pageno", "]", "else", ":", "pages", "=", "[", "]"...
25.767442
21.813953
def create_env_by_folder(folder): """ Create :mod:`jinja2` environment with :meth:`jinja2.FileSystemLoader` :param folder: folder path. :return: jinja2 environment object. """ global _default_filters global _default_tests env = jinja2.Environment(loader=jinja2.FileSystemLoader(folder)) ...
[ "def", "create_env_by_folder", "(", "folder", ")", ":", "global", "_default_filters", "global", "_default_tests", "env", "=", "jinja2", ".", "Environment", "(", "loader", "=", "jinja2", ".", "FileSystemLoader", "(", "folder", ")", ")", "for", "k", ",", "f", ...
25.666667
18.333333
def _split_mod_var_names(resource_name): """ Return (module_name, class_name) pair from given string. """ try: dot_index = resource_name.rindex('.') except ValueError: # no dot found return '', resource_name return resource_name[:dot_index], resource_name[dot_index + 1:]
[ "def", "_split_mod_var_names", "(", "resource_name", ")", ":", "try", ":", "dot_index", "=", "resource_name", ".", "rindex", "(", "'.'", ")", "except", "ValueError", ":", "# no dot found", "return", "''", ",", "resource_name", "return", "resource_name", "[", ":"...
38
13.5
async def load_device_aldb(self, addr, clear=True): """Read the device ALDB.""" dev_addr = Address(addr) device = None if dev_addr == self.plm.address: device = self.plm else: device = self.plm.devices[dev_addr.id] if device: if clear: ...
[ "async", "def", "load_device_aldb", "(", "self", ",", "addr", ",", "clear", "=", "True", ")", ":", "dev_addr", "=", "Address", "(", "addr", ")", "device", "=", "None", "if", "dev_addr", "==", "self", ".", "plm", ".", "address", ":", "device", "=", "s...
38.5
13.55
def delete_variant_by_id(cls, variant_id, **kwargs): """Delete Variant Delete an instance of Variant by its ID. This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.delete_variant_by_id(variant_id,...
[ "def", "delete_variant_by_id", "(", "cls", ",", "variant_id", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_delete_variant_by_id_w...
40.952381
19.619048
def _add(self, sprite, index = None): """add one sprite at a time. used by add_child. split them up so that it would be possible specify the index externally""" if sprite == self: raise Exception("trying to add sprite to itself") if sprite.parent: sprite.x, sprit...
[ "def", "_add", "(", "self", ",", "sprite", ",", "index", "=", "None", ")", ":", "if", "sprite", "==", "self", ":", "raise", "Exception", "(", "\"trying to add sprite to itself\"", ")", "if", "sprite", ".", "parent", ":", "sprite", ".", "x", ",", "sprite"...
37.933333
15.866667
def pdf(self, mag_1, mag_2, mag_err_1, mag_err_2, distance_modulus=None, delta_mag=0.03, steps=10000): """ Compute isochrone probability for each catalog object. ADW: This is a memory intensive function, so try as much as possible to keep array types at `float32` or smalle...
[ "def", "pdf", "(", "self", ",", "mag_1", ",", "mag_2", ",", "mag_err_1", ",", "mag_err_2", ",", "distance_modulus", "=", "None", ",", "delta_mag", "=", "0.03", ",", "steps", "=", "10000", ")", ":", "nsigma", "=", "5.0", "#pad = 1. # mag", "if", "distance...
44.59434
24.575472
def makeductbranch(idf, bname): """make a branch with a duct use standard inlet outlet names""" # make the duct component first pname = "%s_duct" % (bname,) aduct = makeductcomponent(idf, pname) # now make the branch with the duct in it abranch = idf.newidfobject("BRANCH", Name=bname) ab...
[ "def", "makeductbranch", "(", "idf", ",", "bname", ")", ":", "# make the duct component first", "pname", "=", "\"%s_duct\"", "%", "(", "bname", ",", ")", "aduct", "=", "makeductcomponent", "(", "idf", ",", "pname", ")", "# now make the branch with the duct in it", ...
41.857143
9.428571
def compute_from_ll(self,ll): """ m.compute_from_ll(ll) -- Build motif from an inputed log-likelihood matrix (This function reverse-calculates the probability matrix and background frequencies that were used to construct the log-likelihood matrix) """ self.ll = ll ...
[ "def", "compute_from_ll", "(", "self", ",", "ll", ")", ":", "self", ".", "ll", "=", "ll", "self", ".", "width", "=", "len", "(", "ll", ")", "self", ".", "_compute_bg_from_ll", "(", ")", "self", ".", "_compute_logP_from_ll", "(", ")", "self", ".", "_c...
34.933333
16.533333
def x_runtime(f, *args, **kwargs): """X-Runtime Flask Response Decorator.""" _t0 = now() r = f(*args, **kwargs) _t1 = now() r.headers['X-Runtime'] = '{0}s'.format(Decimal(str(_t1 - _t0))) return r
[ "def", "x_runtime", "(", "f", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "_t0", "=", "now", "(", ")", "r", "=", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "_t1", "=", "now", "(", ")", "r", ".", "headers", "[", "'X-Runtim...
23.777778
22.777778
def encode(self, value): """encode(value) -> bytearray Encodes the given value to a bytearray according to this ComplexType definition. """ if type(value) is not datetime.datetime: raise TypeError('encode() argument must be a Python datetime') coarse = Time3...
[ "def", "encode", "(", "self", ",", "value", ")", ":", "if", "type", "(", "value", ")", "is", "not", "datetime", ".", "datetime", ":", "raise", "TypeError", "(", "'encode() argument must be a Python datetime'", ")", "coarse", "=", "Time32Type", "(", ")", ".",...
32.384615
19
def extension_allowed(self, ext): """ This determines whether a specific extension is allowed. It is called by `file_allowed`, so if you override that but still want to check extensions, call back into this. :param ext: The extension to check, without the dot. """ ...
[ "def", "extension_allowed", "(", "self", ",", "ext", ")", ":", "return", "(", "(", "ext", "in", "self", ".", "config", ".", "allow", ")", "or", "(", "ext", "in", "self", ".", "extensions", "and", "ext", "not", "in", "self", ".", "config", ".", "den...
42.4
17.6
def ratio_value_number_to_time_series_length(x): """ Returns a factor which is 1 if all values in the time series occur only once, and below one if this is not the case. In principle, it just returns # unique values / # values :param x: the time series to calculate the feature of :type...
[ "def", "ratio_value_number_to_time_series_length", "(", "x", ")", ":", "if", "not", "isinstance", "(", "x", ",", "(", "np", ".", "ndarray", ",", "pd", ".", "Series", ")", ")", ":", "x", "=", "np", ".", "asarray", "(", "x", ")", "if", "x", ".", "siz...
28.842105
15.894737
def sitemap_uri(self, basename): """Get full URI (filepath) for sitemap based on basename.""" if (re.match(r"\w+:", basename)): # looks like URI return(basename) elif (re.match(r"/", basename)): # looks like full path return(basename) else:...
[ "def", "sitemap_uri", "(", "self", ",", "basename", ")", ":", "if", "(", "re", ".", "match", "(", "r\"\\w+:\"", ",", "basename", ")", ")", ":", "# looks like URI", "return", "(", "basename", ")", "elif", "(", "re", ".", "match", "(", "r\"/\"", ",", "...
39
10.454545
def Network_setCacheDisabled(self, cacheDisabled): """ Function path: Network.setCacheDisabled Domain: Network Method name: setCacheDisabled Parameters: Required arguments: 'cacheDisabled' (type: boolean) -> Cache disabled state. No return value. Description: Toggles ignoring cache for...
[ "def", "Network_setCacheDisabled", "(", "self", ",", "cacheDisabled", ")", ":", "assert", "isinstance", "(", "cacheDisabled", ",", "(", "bool", ",", ")", ")", ",", "\"Argument 'cacheDisabled' must be of type '['bool']'. Received type: '%s'\"", "%", "type", "(", "cacheDi...
34.263158
20.578947
def reftrack_task_data(rt, role): """Return the data for the task that is loaded by the reftrack :param rt: the :class:`jukeboxcore.reftrack.Reftrack` holds the data :type rt: :class:`jukeboxcore.reftrack.Reftrack` :param role: item data role :type role: QtCore.Qt.ItemDataRole :returns: data fo...
[ "def", "reftrack_task_data", "(", "rt", ",", "role", ")", ":", "tfi", "=", "rt", ".", "get_taskfileinfo", "(", ")", "if", "not", "tfi", ":", "return", "return", "filesysitemdata", ".", "taskfileinfo_task_data", "(", "tfi", ",", "role", ")" ]
33.066667
15
def generate_nodes_clasification(bpmn_diagram): """ Diagram elements classification. Implementation based on article "A Simple Algorithm for Automatic Layout of BPMN Processes". Assigns a classification to the diagram element according to specific element parameters. - Element - ...
[ "def", "generate_nodes_clasification", "(", "bpmn_diagram", ")", ":", "nodes_classification", "=", "{", "}", "classification_element", "=", "\"Element\"", "classification_start_event", "=", "\"Start Event\"", "classification_end_event", "=", "\"End Event\"", "task_list", "=",...
56.539474
33.039474
def default_errorhandler(self, f): """Decorator that registers handler of default (Werkzeug) HTTP errors. Note that it might override already defined error handlers. """ for http_code in default_exceptions: self.error_handler_spec[None][http_code] = f return f
[ "def", "default_errorhandler", "(", "self", ",", "f", ")", ":", "for", "http_code", "in", "default_exceptions", ":", "self", ".", "error_handler_spec", "[", "None", "]", "[", "http_code", "]", "=", "f", "return", "f" ]
34
17.444444
def clean_up(group, identifier, date): """Delete all of a groups local mbox, index, and state files. :type group: str :param group: group name :type identifier: str :param identifier: the identifier for the given group. :rtype: bool :returns: True """ #log.error('exception raised...
[ "def", "clean_up", "(", "group", ",", "identifier", ",", "date", ")", ":", "#log.error('exception raised, cleaning up files.')", "glob_pat", "=", "'{g}.{d}.mbox*'", ".", "format", "(", "g", "=", "group", ",", "d", "=", "date", ")", "for", "f", "in", "glob", ...
26.137931
18.551724
def subprocess_run(*popenargs, input=None, timeout=None, check=False, **kwargs): """Run command with arguments and return a CompletedProcess instance. The returned instance will have attributes args, returncode, stdout and stderr. By default, stdout and stderr are not captured, and those attributes wil...
[ "def", "subprocess_run", "(", "*", "popenargs", ",", "input", "=", "None", ",", "timeout", "=", "None", ",", "check", "=", "False", ",", "*", "*", "kwargs", ")", ":", "#pylint: disable=redefined-builtin", "if", "input", "is", "not", "None", ":", "if", "'...
43.653061
24.755102
def overwhitened_data(self, delta_f): """ Return overwhitened data Parameters ---------- delta_f: float The sample step to generate overwhitened frequency domain data for Returns ------- htilde: FrequencySeries Overwhited strain data ...
[ "def", "overwhitened_data", "(", "self", ",", "delta_f", ")", ":", "# we haven't already computed htilde for this delta_f", "if", "delta_f", "not", "in", "self", ".", "segments", ":", "buffer_length", "=", "int", "(", "1.0", "/", "delta_f", ")", "e", "=", "len",...
44.295082
23.688525
def set_structure(self, lattice, species, coords, coords_are_cartesian): """ Sets up the pymatgen structure for which the coordination geometries have to be identified starting from the lattice, the species and the coordinates :param lattice: The lattice of the structure :param s...
[ "def", "set_structure", "(", "self", ",", "lattice", ",", "species", ",", "coords", ",", "coords_are_cartesian", ")", ":", "self", ".", "setup_structure", "(", "Structure", "(", "lattice", ",", "species", ",", "coords", ",", "coords_are_cartesian", ")", ")" ]
55.545455
22.818182
def _should_field_exist( self, field_name, omit_fields, sparse_fields, next_level_omits ): """ Next level omits take form of: { 'this_level_field': [field_to_omit_at_next_level] } We don't want to prematurely omit a field, eg "omit=hous...
[ "def", "_should_field_exist", "(", "self", ",", "field_name", ",", "omit_fields", ",", "sparse_fields", ",", "next_level_omits", ")", ":", "if", "field_name", "in", "omit_fields", "and", "field_name", "not", "in", "next_level_omits", ":", "return", "False", "if", ...
35.111111
24.666667
def run_tpm(system, steps, blackbox): """Iterate the TPM for the given number of timesteps. Returns: np.ndarray: tpm * (noise_tpm^(t-1)) """ # Generate noised TPM # Noise the connections from every output element to elements in other # boxes. node_tpms = [] for node in system.no...
[ "def", "run_tpm", "(", "system", ",", "steps", ",", "blackbox", ")", ":", "# Generate noised TPM", "# Noise the connections from every output element to elements in other", "# boxes.", "node_tpms", "=", "[", "]", "for", "node", "in", "system", ".", "nodes", ":", "node...
32.785714
20.714286
def upload_part_copy(Bucket=None, CopySource=None, CopySourceIfMatch=None, CopySourceIfModifiedSince=None, CopySourceIfNoneMatch=None, CopySourceIfUnmodifiedSince=None, CopySourceRange=None, Key=None, PartNumber=None, UploadId=None, SSECustomerAlgorithm=None, SSECustomerKey=None, SSECustomerKeyMD5=None, CopySourceSSECu...
[ "def", "upload_part_copy", "(", "Bucket", "=", "None", ",", "CopySource", "=", "None", ",", "CopySourceIfMatch", "=", "None", ",", "CopySourceIfModifiedSince", "=", "None", ",", "CopySourceIfNoneMatch", "=", "None", ",", "CopySourceIfUnmodifiedSince", "=", "None", ...
64.247706
54.06422
def print_help(self, prog_name, subcommand): """ Print the help message for this command, derived from ``self.usage()``. """ parser = self.create_parser(prog_name, subcommand) parser.print_help()
[ "def", "print_help", "(", "self", ",", "prog_name", ",", "subcommand", ")", ":", "parser", "=", "self", ".", "create_parser", "(", "prog_name", ",", "subcommand", ")", "parser", ".", "print_help", "(", ")" ]
31
13.5
def create_plan(existing_users=None, proposed_users=None, purge_undefined=None, protected_users=None, allow_non_unique_id=None, manage_home=True, manage_keys=True): """Determine what changes are required. args: existing_users (Users): List of discovered users proposed_users (Use...
[ "def", "create_plan", "(", "existing_users", "=", "None", ",", "proposed_users", "=", "None", ",", "purge_undefined", "=", "None", ",", "protected_users", "=", "None", ",", "allow_non_unique_id", "=", "None", ",", "manage_home", "=", "True", ",", "manage_keys", ...
54.172414
30.724138
def __single_arity_fn_to_py_ast( ctx: GeneratorContext, node: Fn, method: FnMethod, def_name: Optional[str] = None, meta_node: Optional[MetaNode] = None, ) -> GeneratedPyAST: """Return a Python AST node for a function with a single arity.""" assert node.op == NodeOp.FN assert method.op =...
[ "def", "__single_arity_fn_to_py_ast", "(", "ctx", ":", "GeneratorContext", ",", "node", ":", "Fn", ",", "method", ":", "FnMethod", ",", "def_name", ":", "Optional", "[", "str", "]", "=", "None", ",", "meta_node", ":", "Optional", "[", "MetaNode", "]", "=",...
39
15.169492
def fingerprint_helper(egg, permute=False, n_perms=1000, match='exact', distance='euclidean', features=None): """ Computes clustering along a set of feature dimensions Parameters ---------- egg : quail.Egg Data to analyze dist_funcs : dict Dictionary of d...
[ "def", "fingerprint_helper", "(", "egg", ",", "permute", "=", "False", ",", "n_perms", "=", "1000", ",", "match", "=", "'exact'", ",", "distance", "=", "'euclidean'", ",", "features", "=", "None", ")", ":", "if", "features", "is", "None", ":", "features"...
28.068966
23.448276
def enqueue_job(self, job): """ Move a scheduled job to a queue. In addition, it also does puts the job back into the scheduler if needed. """ self.log.debug('Pushing {0} to {1}'.format(job.id, job.origin)) interval = job.meta.get('interval', None) repeat = job.m...
[ "def", "enqueue_job", "(", "self", ",", "job", ")", ":", "self", ".", "log", ".", "debug", "(", "'Pushing {0} to {1}'", ".", "format", "(", "job", ".", "id", ",", "job", ".", "origin", ")", ")", "interval", "=", "job", ".", "meta", ".", "get", "(",...
40.575758
19.30303
def edit(self): """ Edit file with default os application. """ if platform.system().lower() == 'windows': os.startfile(str(self.config_file)) else: if platform.system().lower() == 'darwin': call = 'open' else: ...
[ "def", "edit", "(", "self", ")", ":", "if", "platform", ".", "system", "(", ")", ".", "lower", "(", ")", "==", "'windows'", ":", "os", ".", "startfile", "(", "str", "(", "self", ".", "config_file", ")", ")", "else", ":", "if", "platform", ".", "s...
32.416667
11.75
def remove_choice(self, choice_id, inline_region): """remove a choice, given the id""" if inline_region in self.my_osid_object_form._my_map['choices']: updated_choices = [] for choice in self.my_osid_object_form._my_map['choices'][inline_region]: if choice['id'] !...
[ "def", "remove_choice", "(", "self", ",", "choice_id", ",", "inline_region", ")", ":", "if", "inline_region", "in", "self", ".", "my_osid_object_form", ".", "_my_map", "[", "'choices'", "]", ":", "updated_choices", "=", "[", "]", "for", "choice", "in", "self...
58.125
19.75
def retryNextHost(self, connector=None): """ Have this connector connect again, to the next host in the configured list of hosts. """ if not self.continueTrying: msg = "TxMongo: Abandoning {0} on explicit request.".format(connector) log.msg(msg...
[ "def", "retryNextHost", "(", "self", ",", "connector", "=", "None", ")", ":", "if", "not", "self", ".", "continueTrying", ":", "msg", "=", "\"TxMongo: Abandoning {0} on explicit request.\"", ".", "format", "(", "connector", ")", "log", ".", "msg", "(", "msg", ...
29.172414
19.310345
def is_job_ref(thing, reftype=dict): ''' :param thing: something that might be a job-based object reference hash :param reftype: type that a job-based object reference would be (default is dict) ''' return isinstance(thing, reftype) and \ ((len(thing) == 2 and \ isinstance(thin...
[ "def", "is_job_ref", "(", "thing", ",", "reftype", "=", "dict", ")", ":", "return", "isinstance", "(", "thing", ",", "reftype", ")", "and", "(", "(", "len", "(", "thing", ")", "==", "2", "and", "isinstance", "(", "thing", ".", "get", "(", "'field'", ...
51.923077
24.846154
def applyStyle(self, styleName, networkId, verbose=None): """ Applies the Visual Style specified by the `styleName` parameter to the network specified by the `networkId` parameter. :param styleName: Name of the Visual Style :param networkId: SUID of the Network :param verbose: p...
[ "def", "applyStyle", "(", "self", ",", "styleName", ",", "networkId", ",", "verbose", "=", "None", ")", ":", "response", "=", "api", "(", "url", "=", "self", ".", "___url", "+", "'apply/styles/'", "+", "str", "(", "styleName", ")", "+", "'/'", "+", "...
41.615385
28.076923
def show_backends(socket=DEFAULT_SOCKET_URL): ''' Show HaProxy Backends socket haproxy stats socket, default ``/var/run/haproxy.sock`` CLI Example: .. code-block:: bash salt '*' haproxy.show_backends ''' ha_conn = _get_conn(socket) ha_cmd = haproxy.cmds.showBackends()...
[ "def", "show_backends", "(", "socket", "=", "DEFAULT_SOCKET_URL", ")", ":", "ha_conn", "=", "_get_conn", "(", "socket", ")", "ha_cmd", "=", "haproxy", ".", "cmds", ".", "showBackends", "(", ")", "return", "ha_conn", ".", "sendCmd", "(", "ha_cmd", ")" ]
21.25
22.25
def communicate(self, job_ids = None): """Communicates with the SGE grid (using qstat) to see if jobs are still running.""" self.lock() # iterate over all jobs jobs = self.get_jobs(job_ids) for job in jobs: job.refresh() if job.status in ('queued', 'executing', 'waiting') and job.queue_n...
[ "def", "communicate", "(", "self", ",", "job_ids", "=", "None", ")", ":", "self", ".", "lock", "(", ")", "# iterate over all jobs", "jobs", "=", "self", ".", "get_jobs", "(", "job_ids", ")", "for", "job", "in", "jobs", ":", "job", ".", "refresh", "(", ...
39.809524
19.52381
def get_context_for_help_msgs(self, context_dict): """ We override this method from HelpMsgMixIn to replace wrapped_func with its name """ context_dict = copy(context_dict) context_dict['wrapped_func'] = get_callable_name(context_dict['wrapped_func']) return context_dict
[ "def", "get_context_for_help_msgs", "(", "self", ",", "context_dict", ")", ":", "context_dict", "=", "copy", "(", "context_dict", ")", "context_dict", "[", "'wrapped_func'", "]", "=", "get_callable_name", "(", "context_dict", "[", "'wrapped_func'", "]", ")", "retu...
59.8
14
def _realGetAllThemes(self): """ Collect themes from all available offerings. """ l = [] for offering in getOfferings(): l.extend(offering.themes) l.sort(key=lambda o: o.priority) l.reverse() return l
[ "def", "_realGetAllThemes", "(", "self", ")", ":", "l", "=", "[", "]", "for", "offering", "in", "getOfferings", "(", ")", ":", "l", ".", "extend", "(", "offering", ".", "themes", ")", "l", ".", "sort", "(", "key", "=", "lambda", "o", ":", "o", "....
26.7
9.9
def run_model(t_output_every, output_dir=None, m=None, force_resume=True, **iterate_args): """Convenience function to combine making a Runner object, and running it for some time. Parameters ---------- m: Model Model to run. iterate_args: Arguments to pass to :meth...
[ "def", "run_model", "(", "t_output_every", ",", "output_dir", "=", "None", ",", "m", "=", "None", ",", "force_resume", "=", "True", ",", "*", "*", "iterate_args", ")", ":", "r", "=", "runner", ".", "Runner", "(", "output_dir", ",", "m", ",", "force_res...
26.826087
22.347826
def start_workflow(name, config, *, queue=DefaultJobQueueName.Workflow, clear_data_store=True, store_args=None): """ Start a single workflow by sending it to the workflow queue. Args: name (str): The name of the workflow that should be started. Refers to the name of the w...
[ "def", "start_workflow", "(", "name", ",", "config", ",", "*", ",", "queue", "=", "DefaultJobQueueName", ".", "Workflow", ",", "clear_data_store", "=", "True", ",", "store_args", "=", "None", ")", ":", "try", ":", "wf", "=", "Workflow", ".", "from_name", ...
49.088235
22.647059
def get_update_io_tiles(self, params, values): """ Get the tiles corresponding to a particular section of image needed to be updated. Inputs are the parameters and values. Returned is the padded tile, inner tile, and slicer to go between, but accounting for wrap with the edge of ...
[ "def", "get_update_io_tiles", "(", "self", ",", "params", ",", "values", ")", ":", "# get the affected area of the model image", "otile", "=", "self", ".", "get_update_tile", "(", "params", ",", "values", ")", "if", "otile", "is", "None", ":", "return", "[", "...
45.83871
23
def get_template_names(self): """ Returns the name of the template to use to render this request. Smartmin provides default templates as fallbacks, so appends it's own templates names to the end of whatever list is built by the generic views. Subclasses can override this by set...
[ "def", "get_template_names", "(", "self", ")", ":", "templates", "=", "[", "]", "if", "getattr", "(", "self", ",", "'template_name'", ",", "None", ")", ":", "templates", ".", "append", "(", "self", ".", "template_name", ")", "if", "getattr", "(", "self",...
36.473684
23.947368
def toggle_reciprocal(self): """Flip my ``reciprocal_portal`` boolean, and draw (or stop drawing) an extra arrow on the appropriate button to indicate the fact. """ self.screen.boardview.reciprocal_portal = not self.screen.boardview.reciprocal_portal if self.screen.board...
[ "def", "toggle_reciprocal", "(", "self", ")", ":", "self", ".", "screen", ".", "boardview", ".", "reciprocal_portal", "=", "not", "self", ".", "screen", ".", "boardview", ".", "reciprocal_portal", "if", "self", ".", "screen", ".", "boardview", ".", "reciproc...
41.263158
15.315789
def longitude(self): '''Longitude in signed degrees (python float)''' sd = dm_to_sd(self.lon) if self.lon_dir == 'E': return +sd elif self.lon_dir == 'W': return -sd else: return 0.
[ "def", "longitude", "(", "self", ")", ":", "sd", "=", "dm_to_sd", "(", "self", ".", "lon", ")", "if", "self", ".", "lon_dir", "==", "'E'", ":", "return", "+", "sd", "elif", "self", ".", "lon_dir", "==", "'W'", ":", "return", "-", "sd", "else", ":...
28.555556
15.222222
def request(self, path, method=None, data={}): """sends a request and gets a response from the Plivo REST API path: the URL (relative to the endpoint URL, after the /v1 method: the HTTP method to use, defaults to POST data: for POST or PUT, a dict of data to send returns Plivo ...
[ "def", "request", "(", "self", ",", "path", ",", "method", "=", "None", ",", "data", "=", "{", "}", ")", ":", "if", "not", "path", ":", "raise", "ValueError", "(", "'Invalid path parameter'", ")", "if", "method", "and", "method", "not", "in", "[", "'...
38.173913
19.869565
def fromtext(self, text, encoding='utf-8', mimetype='text/plain'): """ set blob content from given text in StorageBlobModel instance. Parameters are: - text (required): path to a local file - encoding (optional): text encoding (default is utf-8) - mimetype (optional): set a mim...
[ "def", "fromtext", "(", "self", ",", "text", ",", "encoding", "=", "'utf-8'", ",", "mimetype", "=", "'text/plain'", ")", ":", "if", "isinstance", "(", "text", ",", "str", ")", ":", "text", "=", "text", ".", "encode", "(", "encoding", ",", "'ignore'", ...
46.470588
28.176471
def create(annot=None, config=None, networkId=None, nodeId=None, state=None, ui=None): """ :type annot: dict :type config: NetworkMemberConfig :type networkId: str :type nodeId: str :type state: int :type ui: dict :rtype: NetworkMember """ ...
[ "def", "create", "(", "annot", "=", "None", ",", "config", "=", "None", ",", "networkId", "=", "None", ",", "nodeId", "=", "None", ",", "state", "=", "None", ",", "ui", "=", "None", ")", ":", "return", "NetworkMember", "(", "annot", "=", "annot", "...
25.789474
16.105263
def assertUnique(self, container, msg=None): '''Fail if elements in ``container`` are not unique. Parameters ---------- container : iterable msg : str If not provided, the :mod:`marbles.mixins` or :mod:`unittest` standard message will be used. Ra...
[ "def", "assertUnique", "(", "self", ",", "container", ",", "msg", "=", "None", ")", ":", "if", "not", "isinstance", "(", "container", ",", "collections", ".", "Iterable", ")", ":", "raise", "TypeError", "(", "'First argument is not iterable'", ")", "standardMs...
37.892857
22.392857
def memoryit_block(group_by='lineno', limit=10, label='code block'): """ 追踪代码块内存消耗情况 :param group_by: 统计分组,有 'filename', 'lineno', 'traceback' 可选 :param limit: 限制输出行数 :param label: 代码块标签 """ tracemalloc.start() _start = tracemalloc.take_snapshot() try: yield finally: ...
[ "def", "memoryit_block", "(", "group_by", "=", "'lineno'", ",", "limit", "=", "10", ",", "label", "=", "'code block'", ")", ":", "tracemalloc", ".", "start", "(", ")", "_start", "=", "tracemalloc", ".", "take_snapshot", "(", ")", "try", ":", "yield", "fi...
26.875
16.875
def _populate_rv(self, dataset, **kwargs): """ Populate columns necessary for an RV dataset This should not be called directly, but rather via :meth:`Body.populate_observable` or :meth:`System.populate_observables` """ logger.debug("{}._populate_rv(dataset={})".format(se...
[ "def", "_populate_rv", "(", "self", ",", "dataset", ",", "*", "*", "kwargs", ")", ":", "logger", ".", "debug", "(", "\"{}._populate_rv(dataset={})\"", ".", "format", "(", "self", ".", "component", ",", "dataset", ")", ")", "# We need to fill all the flux-related...
36.806452
25.064516
def update(self): """ Update the screens contents in every loop. """ # this is not really neccesary because the surface is black after initializing self.corners.fill(BLACK) self.corners.draw_dot((0, 0), self.colors[0]) self.corners.draw_dot((self.screen.width - 1,...
[ "def", "update", "(", "self", ")", ":", "# this is not really neccesary because the surface is black after initializing", "self", ".", "corners", ".", "fill", "(", "BLACK", ")", "self", ".", "corners", ".", "draw_dot", "(", "(", "0", ",", "0", ")", ",", "self", ...
48.441176
23.088235
def _listWrapOn(F, availWidth, canv, mergeSpace=1, obj=None, dims=None): '''return max width, required height for a list of flowables F''' doct = getattr(canv, '_doctemplate', None) cframe = getattr(doct, 'frame', None) if cframe: from reportlab.platypus.doctemplate import _addGeneratedContent, ...
[ "def", "_listWrapOn", "(", "F", ",", "availWidth", ",", "canv", ",", "mergeSpace", "=", "1", ",", "obj", "=", "None", ",", "dims", "=", "None", ")", ":", "doct", "=", "getattr", "(", "canv", ",", "'_doctemplate'", ",", "None", ")", "cframe", "=", "...
32.051724
17.741379
def read_cclib(value, name=None): """ Create an `Atoms` object from data attributes parsed by cclib. `cclib <https://cclib.github.io/>`_ is an open source library, written in Python, for parsing and interpreting the results (logfiles) of computational chemistry packages. Parameters -------...
[ "def", "read_cclib", "(", "value", ",", "name", "=", "None", ")", ":", "if", "isinstance", "(", "value", ",", "_logfileparser", ".", "Logfile", ")", ":", "# TODO: test this case.", "jobfilename", "=", "value", ".", "filename", "ccdata", "=", "value", ".", ...
30.051724
20.982759
def autodiscover(): ''' Auto-discover INSTALLED_APPS autofixtures.py and tests.py modules and fail silently when not present. This forces an import on them to register any autofixture bits they may want. ''' from .compat import importlib # Bail out if autodiscover didn't finish loading from...
[ "def", "autodiscover", "(", ")", ":", "from", ".", "compat", "import", "importlib", "# Bail out if autodiscover didn't finish loading from a previous call so", "# that we avoid running autodiscover again when the URLconf is loaded by", "# the exception handler to resolve the handler500 view....
35.305882
24.082353
def _validate_items(self, path, obj, _): """ validate option combination of Property object """ errs = [] if obj.type == 'void': errs.append('void is only allowed in Operation object.') return path, obj.__class__.__name__, errs
[ "def", "_validate_items", "(", "self", ",", "path", ",", "obj", ",", "_", ")", ":", "errs", "=", "[", "]", "if", "obj", ".", "type", "==", "'void'", ":", "errs", ".", "append", "(", "'void is only allowed in Operation object.'", ")", "return", "path", ",...
33.25
18.75
def get_random_id(length): """Generate a random, alpha-numerical id.""" alphabet = string.ascii_uppercase + string.ascii_lowercase + string.digits return ''.join(random.choice(alphabet) for _ in range(length))
[ "def", "get_random_id", "(", "length", ")", ":", "alphabet", "=", "string", ".", "ascii_uppercase", "+", "string", ".", "ascii_lowercase", "+", "string", ".", "digits", "return", "''", ".", "join", "(", "random", ".", "choice", "(", "alphabet", ")", "for",...
54.5
19.5
def submit_all(self): """ :returns: an IterResult object """ for args in self.task_args: self.submit(*args) return self.get_results()
[ "def", "submit_all", "(", "self", ")", ":", "for", "args", "in", "self", ".", "task_args", ":", "self", ".", "submit", "(", "*", "args", ")", "return", "self", ".", "get_results", "(", ")" ]
25.571429
6.142857
def _guess_available_methods(self): """ Guess the method implemented by the subclass""" available_methods = [] for m in ["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"]: self_method = getattr(type(self), "API_{}".format(m)) super_method = getattr(APIPage, "API...
[ "def", "_guess_available_methods", "(", "self", ")", ":", "available_methods", "=", "[", "]", "for", "m", "in", "[", "\"GET\"", ",", "\"POST\"", ",", "\"PUT\"", ",", "\"DELETE\"", ",", "\"PATCH\"", ",", "\"HEAD\"", ",", "\"OPTIONS\"", "]", ":", "self_method"...
49.777778
12.777778
def wrapped(f): """ Decorator to append routed docstrings """ import inspect def extract(func): append = "" args = inspect.getargspec(func) for i, a in enumerate(args.args): if i < (len(args) - len(args.defaults)): append += str(a) + ", " ...
[ "def", "wrapped", "(", "f", ")", ":", "import", "inspect", "def", "extract", "(", "func", ")", ":", "append", "=", "\"\"", "args", "=", "inspect", ".", "getargspec", "(", "func", ")", "for", "i", ",", "a", "in", "enumerate", "(", "args", ".", "args...
32.37037
16.888889
def _create_diff_action(diff, diff_key, key, value): ''' DRY to build diff parts (added, removed, updated). ''' if diff_key not in diff.keys(): diff[diff_key] = {} diff[diff_key][key] = value
[ "def", "_create_diff_action", "(", "diff", ",", "diff_key", ",", "key", ",", "value", ")", ":", "if", "diff_key", "not", "in", "diff", ".", "keys", "(", ")", ":", "diff", "[", "diff_key", "]", "=", "{", "}", "diff", "[", "diff_key", "]", "[", "key"...
23.666667
22.111111
def registIssue(self, CorpNum, taxinvoice, writeSpecification=False, forceIssue=False, dealInvoiceMgtKey=None, memo=None, emailSubject=None, UserID=None): """ 즉시 발행 args CorpNum : 팝빌회원 사업자번호 taxinvoice : 세금계산서 객체 writeSpecification ...
[ "def", "registIssue", "(", "self", ",", "CorpNum", ",", "taxinvoice", ",", "writeSpecification", "=", "False", ",", "forceIssue", "=", "False", ",", "dealInvoiceMgtKey", "=", "None", ",", "memo", "=", "None", ",", "emailSubject", "=", "None", ",", "UserID", ...
34.142857
18.485714
def read(self, n): """ Read *n* bytes from the subprocess' output channel. Args: n(int): The number of bytes to read. Returns: bytes: *n* bytes of output. Raises: EOFError: If the process exited. """ d = b'' while n:...
[ "def", "read", "(", "self", ",", "n", ")", ":", "d", "=", "b''", "while", "n", ":", "try", ":", "block", "=", "self", ".", "_process", ".", "stdout", ".", "read", "(", "n", ")", "except", "ValueError", ":", "block", "=", "None", "if", "not", "b...
23.230769
18.384615
def get(self, sid): """ Constructs a TerminatingSipDomainContext :param sid: The unique string that identifies the resource :returns: twilio.rest.trunking.v1.trunk.terminating_sip_domain.TerminatingSipDomainContext :rtype: twilio.rest.trunking.v1.trunk.terminating_sip_domain.Te...
[ "def", "get", "(", "self", ",", "sid", ")", ":", "return", "TerminatingSipDomainContext", "(", "self", ".", "_version", ",", "trunk_sid", "=", "self", ".", "_solution", "[", "'trunk_sid'", "]", ",", "sid", "=", "sid", ",", ")" ]
45.6
31.6
def ctmc(data, numstates, transintv=1.0, toltime=1e-8, debug=False): """ Continous Time Markov Chain Parameters ---------- data : list of lists A python list of N examples (e.g. rating histories of N companies, the event data of N basketball games, etc.). The i-th example consis...
[ "def", "ctmc", "(", "data", ",", "numstates", ",", "transintv", "=", "1.0", ",", "toltime", "=", "1e-8", ",", "debug", "=", "False", ")", ":", "# raise an exception if the data format is wrong", "if", "debug", ":", "datacheck", "(", "data", ",", "numstates", ...
27.897959
24.102041
def run(self, packets): """Run automatically. Positional arguments: * packets -- list<dict>, list of packet dicts to be reassembled """ for packet in packets: frag_check(packet, protocol=self.protocol) info = Info(packet) self.reassembly(...
[ "def", "run", "(", "self", ",", "packets", ")", ":", "for", "packet", "in", "packets", ":", "frag_check", "(", "packet", ",", "protocol", "=", "self", ".", "protocol", ")", "info", "=", "Info", "(", "packet", ")", "self", ".", "reassembly", "(", "inf...
28.5
16.333333
def governor(self): """ Accesses the governor node :getter: Returns the Governor node :type: corenlp_xml.dependencies.DependencyNode """ if self._governor is None: governors = self._element.xpath('governor') if len(governors) > 0: ...
[ "def", "governor", "(", "self", ")", ":", "if", "self", ".", "_governor", "is", "None", ":", "governors", "=", "self", ".", "_element", ".", "xpath", "(", "'governor'", ")", "if", "len", "(", "governors", ")", ">", "0", ":", "self", ".", "_governor",...
30.923077
15.384615
def bandpass_filter(data, low, high, fs, order=5): """ Does a bandpass filter over the given data. :param data: The data (numpy array) to be filtered. :param low: The low cutoff in Hz. :param high: The high cutoff in Hz. :param fs: The sample rate (in Hz) of the data. :param order: The orde...
[ "def", "bandpass_filter", "(", "data", ",", "low", ",", "high", ",", "fs", ",", "order", "=", "5", ")", ":", "nyq", "=", "0.5", "*", "fs", "low", "=", "low", "/", "nyq", "high", "=", "high", "/", "nyq", "b", ",", "a", "=", "signal", ".", "but...
34.529412
14.882353
def RegisterValue(self, value): """Puts a given value into an appropriate bin.""" if self.bins: for b in self.bins: if b.range_max_value > value: b.num += 1 return self.bins[-1].num += 1
[ "def", "RegisterValue", "(", "self", ",", "value", ")", ":", "if", "self", ".", "bins", ":", "for", "b", "in", "self", ".", "bins", ":", "if", "b", ".", "range_max_value", ">", "value", ":", "b", ".", "num", "+=", "1", "return", "self", ".", "bin...
25.222222
16.222222
def rpc_get_blockstack_ops_at(self, block_id, offset, count, **con_info): """ Get the name operations that occured in the given block. Does not include account operations. Returns {'nameops': [...]} on success. Returns {'error': ...} on error """ if not check_blo...
[ "def", "rpc_get_blockstack_ops_at", "(", "self", ",", "block_id", ",", "offset", ",", "count", ",", "*", "*", "con_info", ")", ":", "if", "not", "check_block", "(", "block_id", ")", ":", "return", "{", "'error'", ":", "'Invalid block height'", ",", "'http_st...
39.266667
23.466667
def pose_from_oxts_packet(packet, scale): """Helper method to compute a SE(3) pose matrix from an OXTS packet. """ er = 6378137. # earth radius (approx.) in meters # Use a Mercator projection to get the translation vector tx = scale * packet.lon * np.pi * er / 180. ty = scale * er * \ ...
[ "def", "pose_from_oxts_packet", "(", "packet", ",", "scale", ")", ":", "er", "=", "6378137.", "# earth radius (approx.) in meters", "# Use a Mercator projection to get the translation vector", "tx", "=", "scale", "*", "packet", ".", "lon", "*", "np", ".", "pi", "*", ...
32.65
17.6
def events(self, since=None, until=None, filters=None, decode=None): """ Get real-time events from the server. Similar to the ``docker events`` command. Args: since (UTC datetime or int): Get events from this point until (UTC datetime or int): Get events until th...
[ "def", "events", "(", "self", ",", "since", "=", "None", ",", "until", "=", "None", ",", "filters", "=", "None", ",", "decode", "=", "None", ")", ":", "if", "isinstance", "(", "since", ",", "datetime", ")", ":", "since", "=", "utils", ".", "datetim...
30.672414
21.5
def decrypt(self, encrypted): """ decrypts the encrypted message using Fernet :param encrypted: the encrypted message :returns: the decrypted, serialized identifier collection """ fernet = Fernet(self.decryption_cipher_key) return fernet.decrypt(encrypted)
[ "def", "decrypt", "(", "self", ",", "encrypted", ")", ":", "fernet", "=", "Fernet", "(", "self", ".", "decryption_cipher_key", ")", "return", "fernet", ".", "decrypt", "(", "encrypted", ")" ]
33.888889
11.666667
def bandstats(filenames=None, num_sample_points=3, temperature=None, degeneracy_tol=1e-4, parabolic=True): """Calculate the effective masses of the bands of a semiconductor. Args: filenames (:obj:`str` or :obj:`list`, optional): Path to vasprun.xml or vasprun.xml.gz file. If n...
[ "def", "bandstats", "(", "filenames", "=", "None", ",", "num_sample_points", "=", "3", ",", "temperature", "=", "None", ",", "degeneracy_tol", "=", "1e-4", ",", "parabolic", "=", "True", ")", ":", "if", "not", "filenames", ":", "filenames", "=", "find_vasp...
40.032258
23.233871
def modLocationPort(self, location): """ Ensures that the location port is a the given port value Used in `handleHeader` """ components = urlparse.urlparse(location) reverse_proxy_port = self.father.getHost().port reverse_proxy_host = self.father.getHost().host ...
[ "def", "modLocationPort", "(", "self", ",", "location", ")", ":", "components", "=", "urlparse", ".", "urlparse", "(", "location", ")", "reverse_proxy_port", "=", "self", ".", "father", ".", "getHost", "(", ")", ".", "port", "reverse_proxy_host", "=", "self"...
41.285714
11.857143
def run_dot(self, args, name, parts=0, urls={}, graph_options={}, node_options={}, edge_options={}): """ Run graphviz 'dot' over this graph, returning whatever 'dot' writes to stdout. *args* will be passed along as commandline arguments. *name* is the name of th...
[ "def", "run_dot", "(", "self", ",", "args", ",", "name", ",", "parts", "=", "0", ",", "urls", "=", "{", "}", ",", "graph_options", "=", "{", "}", ",", "node_options", "=", "{", "}", ",", "edge_options", "=", "{", "}", ")", ":", "try", ":", "dot...
39.294118
22.294118
def proxy_alias(alias_name, node_type): """Get a Proxy from the given name to the given node type.""" proxy = type( alias_name, (lazy_object_proxy.Proxy,), { "__class__": object.__dict__["__class__"], "__instancecheck__": _instancecheck, }, ) retur...
[ "def", "proxy_alias", "(", "alias_name", ",", "node_type", ")", ":", "proxy", "=", "type", "(", "alias_name", ",", "(", "lazy_object_proxy", ".", "Proxy", ",", ")", ",", "{", "\"__class__\"", ":", "object", ".", "__dict__", "[", "\"__class__\"", "]", ",", ...
30.545455
15.727273
def from_nid(cls, lib, nid): """ Instantiate a new :py:class:`_EllipticCurve` associated with the given OpenSSL NID. :param lib: The OpenSSL library binding object. :param nid: The OpenSSL NID the resulting curve object will represent. This must be a curve NID (and ...
[ "def", "from_nid", "(", "cls", ",", "lib", ",", "nid", ")", ":", "return", "cls", "(", "lib", ",", "nid", ",", "_ffi", ".", "string", "(", "lib", ".", "OBJ_nid2sn", "(", "nid", ")", ")", ".", "decode", "(", "\"ascii\"", ")", ")" ]
37.8
23.533333
def hide_routemap_holder_route_map_content_set_metric_delta_rms(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") hide_routemap_holder = ET.SubElement(config, "hide-routemap-holder", xmlns="urn:brocade.com:mgmt:brocade-ip-policy") route_map = ET.SubElement...
[ "def", "hide_routemap_holder_route_map_content_set_metric_delta_rms", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "hide_routemap_holder", "=", "ET", ".", "SubElement", "(", "config", ",", "\"hide-rou...
49.8
16.95
def resample(self, section_length): """ Resample this line into sections. The first point in the resampled line corresponds to the first point in the original line. Starting from the first point in the original line, a line segment is defined as the line connecting the ...
[ "def", "resample", "(", "self", ",", "section_length", ")", ":", "if", "len", "(", "self", ".", "points", ")", "<", "2", ":", "return", "Line", "(", "self", ".", "points", ")", "resampled_points", "=", "[", "]", "# 1. Resample the first section. 2. Loop over...
37.322581
21.967742
def _set_account_info(self): """ Connect to the AWS IAM API via boto3 and run the GetUser operation on the current user. Use this to set ``self.aws_account_id`` and ``self.aws_region``. """ if 'AWS_DEFAULT_REGION' in os.environ: logger.debug('Connecting to IAM...
[ "def", "_set_account_info", "(", "self", ")", ":", "if", "'AWS_DEFAULT_REGION'", "in", "os", ".", "environ", ":", "logger", ".", "debug", "(", "'Connecting to IAM with region_name=%s'", ",", "os", ".", "environ", "[", "'AWS_DEFAULT_REGION'", "]", ")", "kwargs", ...
47.083333
17.333333
def animate_2Dscatter(x, y, NumAnimatedPoints=50, NTrailPoints=20, xlabel="", ylabel="", xlims=None, ylims=None, filename="testAnim.mp4", bitrate=1e5, dpi=5e2, fps=30, figsize = [6, 6]): """ Animates x and y - where x and y are 1d arrays of x and y positions and it plots x[i:i+NTrailPoints] a...
[ "def", "animate_2Dscatter", "(", "x", ",", "y", ",", "NumAnimatedPoints", "=", "50", ",", "NTrailPoints", "=", "20", ",", "xlabel", "=", "\"\"", ",", "ylabel", "=", "\"\"", ",", "xlims", "=", "None", ",", "ylims", "=", "None", ",", "filename", "=", "...
33.042553
20.957447
def import_spydercustomize(): """Import our customizations into the kernel.""" here = osp.dirname(__file__) parent = osp.dirname(here) customize_dir = osp.join(parent, 'customize') # Remove current directory from sys.path to prevent kernel # crashes when people name Python files or modules with...
[ "def", "import_spydercustomize", "(", ")", ":", "here", "=", "osp", ".", "dirname", "(", "__file__", ")", "parent", "=", "osp", ".", "dirname", "(", "here", ")", "customize_dir", "=", "osp", ".", "join", "(", "parent", ",", "'customize'", ")", "# Remove ...
30.045455
16.227273
def _pack_date(self, date): """This method is used to encode dates""" # Just copied from original KeePassX source y, mon, d, h, min_, s = date.timetuple()[:6] dw1 = 0x0000FFFF & ((y>>6) & 0x0000003F) dw2 = 0x0000FFFF & ((y & 0x0000003F)<<2 | ((mon>>2) & 0x00000003)) ...
[ "def", "_pack_date", "(", "self", ",", "date", ")", ":", "# Just copied from original KeePassX source", "y", ",", "mon", ",", "d", ",", "h", ",", "min_", ",", "s", "=", "date", ".", "timetuple", "(", ")", "[", ":", "6", "]", "dw1", "=", "0x0000FFFF", ...
45.142857
22.357143
def unique_slug_required(form, slug): """Enforce a unique slug accross all pages and websistes.""" if hasattr(form, 'instance') and form.instance.id: if Content.objects.exclude(page=form.instance).filter( body=slug, type="slug").count(): raise forms.ValidationError(error_dict['a...
[ "def", "unique_slug_required", "(", "form", ",", "slug", ")", ":", "if", "hasattr", "(", "form", ",", "'instance'", ")", "and", "form", ".", "instance", ".", "id", ":", "if", "Content", ".", "objects", ".", "exclude", "(", "page", "=", "form", ".", "...
48.2
19.4
def getState(self): """Get the particle state as a dict. This is enough information to instantiate this particle on another worker.""" varStates = dict() for varName, var in self.permuteVars.iteritems(): varStates[varName] = var.getState() return dict(id=self.particleId, genId...
[ "def", "getState", "(", "self", ")", ":", "varStates", "=", "dict", "(", ")", "for", "varName", ",", "var", "in", "self", ".", "permuteVars", ".", "iteritems", "(", ")", ":", "varStates", "[", "varName", "]", "=", "var", ".", "getState", "(", ")", ...
36.272727
10
def start_session(self): """ Start Session """ response = self.request("hello") bits = response.split(" ") self.server_info.update({ "server_version": bits[2], "protocol_version": bits[4], "screen_width": int(bits[7]), "screen_height": int...
[ "def", "start_session", "(", "self", ")", ":", "response", "=", "self", ".", "request", "(", "\"hello\"", ")", "bits", "=", "response", ".", "split", "(", "\" \"", ")", "self", ".", "server_info", ".", "update", "(", "{", "\"server_version\"", ":", "bits...
31
8.642857
def get_system_category(auth, url): """Takes string no input to issue RESTUL call to HP IMC\n :param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class :param url: base url of IMC RS interface #usually auth.url from pyhpeimc.auth.authclass :return: list of dictionaries...
[ "def", "get_system_category", "(", "auth", ",", "url", ")", ":", "get_system_category_url", "=", "'/imcrs/plat/res/category?start=0&size=10000&orderBy=id&desc=false&total=false'", "f_url", "=", "url", "+", "get_system_category_url", "# creates the URL using the payload variable as th...
34.972222
27.027778
def target(self): """ Find the target name for this build. :returns: deferred that when fired returns the build task's target name. If we could not determine the build task, or the task's target, return None. """ task = yield self.task() ...
[ "def", "target", "(", "self", ")", ":", "task", "=", "yield", "self", ".", "task", "(", ")", "if", "not", "task", ":", "yield", "defer", ".", "succeed", "(", "None", ")", "defer", ".", "returnValue", "(", "None", ")", "defer", ".", "returnValue", "...
33.538462
13.846154
def symbols(names, **args): """ Transform strings into instances of :class:`Symbol` class. :func:`symbols` function returns a sequence of symbols with names taken from ``names`` argument, which can be a comma or whitespace delimited string, or a sequence of strings:: >>> from symengine impor...
[ "def", "symbols", "(", "names", ",", "*", "*", "args", ")", ":", "result", "=", "[", "]", "if", "isinstance", "(", "names", ",", "string_types", ")", ":", "marker", "=", "0", "literals", "=", "[", "'\\,'", ",", "'\\:'", ",", "'\\ '", "]", "for", ...
36.729412
16.388235
def _recursively_replace_dict_for_pretty_dict(x): """Recursively replace `dict`s with `_PrettyDict`.""" # We use "PrettyDict" because collections.OrderedDict repr/str has the word # "OrderedDict" in it. We only want to print "OrderedDict" if in fact the # input really is an OrderedDict. if isinstance(x, dict)...
[ "def", "_recursively_replace_dict_for_pretty_dict", "(", "x", ")", ":", "# We use \"PrettyDict\" because collections.OrderedDict repr/str has the word", "# \"OrderedDict\" in it. We only want to print \"OrderedDict\" if in fact the", "# input really is an OrderedDict.", "if", "isinstance", "("...
47.35
14.1
def work(self, burst=False, logging_level=logging.INFO): """ Spawning a greenlet to be able to kill it when it's blocked dequeueing job :param burst: if it's burst worker don't need to spawn a greenlet """ # If the is a burst worker it's not needed to spawn greenlet if bu...
[ "def", "work", "(", "self", ",", "burst", "=", "False", ",", "logging_level", "=", "logging", ".", "INFO", ")", ":", "# If the is a burst worker it's not needed to spawn greenlet", "if", "burst", ":", "return", "self", ".", "_work", "(", "burst", ",", "logging_l...
42.916667
19.583333
def _process_using_meta_feature_generator(self, X, meta_feature_generator): """Process using secondary learner meta-feature generator Since secondary learner meta-feature generator can be anything e.g. predict, predict_proba, this internal method gives the ability to use any string. Just make s...
[ "def", "_process_using_meta_feature_generator", "(", "self", ",", "X", ",", "meta_feature_generator", ")", ":", "all_learner_meta_features", "=", "[", "]", "for", "idx", ",", "base_learner", "in", "enumerate", "(", "self", ".", "base_learners", ")", ":", "single_l...
44
32.888889