text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def get_window_size(self): """Generic method to get window size using a javascript workaround for Android web tests :returns: dict with window width and height """ if not self._window_size: if self.driver_wrapper.is_android_web_test() and self.driver_wrapper.driver.current_c...
[ "def", "get_window_size", "(", "self", ")", ":", "if", "not", "self", ".", "_window_size", ":", "if", "self", ".", "driver_wrapper", ".", "is_android_web_test", "(", ")", "and", "self", ".", "driver_wrapper", ".", "driver", ".", "current_context", "!=", "'NA...
57.846154
0.010471
def make_command(self, ctx, name, info): """ make click sub-command from command info gotten from xbahn engineer """ @self.command() @click.option("--debug/--no-debug", default=False, help="Show debug information") @doc(info.get("description")) def func(...
[ "def", "make_command", "(", "self", ",", "ctx", ",", "name", ",", "info", ")", ":", "@", "self", ".", "command", "(", ")", "@", "click", ".", "option", "(", "\"--debug/--no-debug\"", ",", "default", "=", "False", ",", "help", "=", "\"Show debug informati...
32.964286
0.008421
async def start(request): """ Begins the session manager for factory calibration, if a session is not already in progress, or if the "force" key is specified in the request. To force, use the following body: { "force": true } :return: The current session ID token or an error message ...
[ "async", "def", "start", "(", "request", ")", ":", "global", "session", "try", ":", "body", "=", "await", "request", ".", "json", "(", ")", "except", "json", ".", "decoder", ".", "JSONDecodeError", ":", "# Body will be null for requests without parameters (normal ...
31.973684
0.000799
def _build_matches(matches, uuids, no_filtered, fastmode=False): """Build a list with matching subsets""" result = [] for m in matches: mk = m[0].uuid if not fastmode else m[0] subset = [uuids[mk]] for id_ in m[1:]: uk = id_.uuid if not fastmode else id_ u ...
[ "def", "_build_matches", "(", "matches", ",", "uuids", ",", "no_filtered", ",", "fastmode", "=", "False", ")", ":", "result", "=", "[", "]", "for", "m", "in", "matches", ":", "mk", "=", "m", "[", "0", "]", ".", "uuid", "if", "not", "fastmode", "els...
22
0.001613
def shred(args): """ %prog shred fastafile Similar to the method of `shredContig` in runCA script. The contigs are shredded into pseudo-reads with certain length and depth. """ p = OptionParser(shred.__doc__) p.set_depth(depth=2) p.add_option("--readlen", default=1000, type="int", ...
[ "def", "shred", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "shred", ".", "__doc__", ")", "p", ".", "set_depth", "(", "depth", "=", "2", ")", "p", ".", "add_option", "(", "\"--readlen\"", ",", "default", "=", "1000", ",", "type", "=", "\"...
33.62766
0.002459
def generate_np(self, x_val, **kwargs): """ Generate adversarial examples and return them as a NumPy array. :param x_val: A NumPy array with the original inputs. :param **kwargs: optional parameters used by child classes. :return: A NumPy array holding the adversarial examples. """ tfe = tf...
[ "def", "generate_np", "(", "self", ",", "x_val", ",", "*", "*", "kwargs", ")", ":", "tfe", "=", "tf", ".", "contrib", ".", "eager", "x", "=", "tfe", ".", "Variable", "(", "x_val", ")", "adv_x", "=", "self", ".", "generate", "(", "x", ",", "*", ...
34.583333
0.002347
def updateQueue(self): """Process inbound communication buffer. Updates the local queue with elements from the broker.""" for future in self.socket.recvFuture(): if future._ended(): # If the answer is coming back, update its entry try: ...
[ "def", "updateQueue", "(", "self", ")", ":", "for", "future", "in", "self", ".", "socket", ".", "recvFuture", "(", ")", ":", "if", "future", ".", "_ended", "(", ")", ":", "# If the answer is coming back, update its entry", "try", ":", "thisFuture", "=", "sco...
50.423077
0.001497
def from_filename(cls, filename): """Return a :class:`Link` wrapping the local filename.""" result = cls._FROM_FILENAME_CACHE.get(filename) if result is None: result = cls(cls._normalize(filename)) cls._FROM_FILENAME_CACHE.store(filename, result) return result
[ "def", "from_filename", "(", "cls", ",", "filename", ")", ":", "result", "=", "cls", ".", "_FROM_FILENAME_CACHE", ".", "get", "(", "filename", ")", "if", "result", "is", "None", ":", "result", "=", "cls", "(", "cls", ".", "_normalize", "(", "filename", ...
40.285714
0.010417
def gaussian_noise(in_features, out_features, device): """ Normal gaussian N(0, 1) noise """ return torch.randn((in_features, out_features), device=device), torch.randn(out_features, device=device)
[ "def", "gaussian_noise", "(", "in_features", ",", "out_features", ",", "device", ")", ":", "return", "torch", ".", "randn", "(", "(", "in_features", ",", "out_features", ")", ",", "device", "=", "device", ")", ",", "torch", ".", "randn", "(", "out_features...
67.666667
0.009756
def get_attributes(name, region=None, key=None, keyid=None, profile=None): ''' Return attributes currently set on an SQS queue. CLI Example: .. code-block:: bash salt myminion boto_sqs.get_attributes myqueue ''' conn = _get_conn(region=region, key=key, keyid=keyid, profile=profile) ...
[ "def", "get_attributes", "(", "name", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "conn", "=", "_get_conn", "(", "region", "=", "region", ",", "key", "=", "key", ",", "keyid...
33.166667
0.001629
def compactness(target, throat_perimeter='throat.perimeter', throat_area='throat.area'): r""" Mortensen et al. have shown that the Hagen-Poiseuille hydraluic resistance is linearly dependent on the compactness. Defined as perimeter^2/area. The dependence is not universal as shapes with s...
[ "def", "compactness", "(", "target", ",", "throat_perimeter", "=", "'throat.perimeter'", ",", "throat_area", "=", "'throat.area'", ")", ":", "# Only apply to throats with an area", "ts", "=", "target", ".", "throats", "(", ")", "[", "target", "[", "throat_area", "...
42.725
0.000572
def write_versions(dirs, items): """Write data versioning for genomes present in the configuration. """ genomes = {} for d in items: genomes[d["genome_build"]] = d.get("reference", {}).get("versions") out_file = _get_out_file(dirs) found_versions = False if genomes and out_file: ...
[ "def", "write_versions", "(", "dirs", ",", "items", ")", ":", "genomes", "=", "{", "}", "for", "d", "in", "items", ":", "genomes", "[", "d", "[", "\"genome_build\"", "]", "]", "=", "d", ".", "get", "(", "\"reference\"", ",", "{", "}", ")", ".", "...
46.185185
0.001571
def get(self, position=0): """ Return a color interpolated from the Palette. In the case where continuous=False, serpentine=False, scale=1, autoscale=False, and offset=0, this is exactly the same as plain old [] indexing, but with a wrap-around. The constructor paramete...
[ "def", "get", "(", "self", ",", "position", "=", "0", ")", ":", "n", "=", "len", "(", "self", ")", "if", "n", "==", "1", ":", "return", "self", "[", "0", "]", "pos", "=", "position", "if", "self", ".", "length", "and", "self", ".", "autoscale",...
26.370968
0.001179
def delta_e_cmc(lab_color_vector, lab_color_matrix, pl=2, pc=1): """ Calculates the Delta E (CIE1994) of two colors. CMC values Acceptability: pl=2, pc=1 Perceptability: pl=1, pc=1 """ L, a, b = lab_color_vector C_1 = numpy.sqrt(numpy.sum(numpy.power(lab_color_vector[1:], 2))) ...
[ "def", "delta_e_cmc", "(", "lab_color_vector", ",", "lab_color_matrix", ",", "pl", "=", "2", ",", "pc", "=", "1", ")", ":", "L", ",", "a", ",", "b", "=", "lab_color_vector", "C_1", "=", "numpy", ".", "sqrt", "(", "numpy", ".", "sum", "(", "numpy", ...
28.56
0.002031
def launch(thing,title=False): """analyze a thing, create a nice HTML document, and launch it.""" html=htmlFromThing(thing,title=title) if not html: print("no HTML was generated.") return fname="%s/%s.html"%(tempfile.gettempdir(),str(time.time())) with open(fname,'w') as f: ...
[ "def", "launch", "(", "thing", ",", "title", "=", "False", ")", ":", "html", "=", "htmlFromThing", "(", "thing", ",", "title", "=", "title", ")", "if", "not", "html", ":", "print", "(", "\"no HTML was generated.\"", ")", "return", "fname", "=", "\"%s/%s....
35.9
0.021739
def execute(self): """Run selected module generator.""" if self._cli_arguments['cfn']: generate_sample_cfn_module(self.env_root) elif self._cli_arguments['sls']: generate_sample_sls_module(self.env_root) elif self._cli_arguments['sls-tsc']: generate_sa...
[ "def", "execute", "(", "self", ")", ":", "if", "self", ".", "_cli_arguments", "[", "'cfn'", "]", ":", "generate_sample_cfn_module", "(", "self", ".", "env_root", ")", "elif", "self", ".", "_cli_arguments", "[", "'sls'", "]", ":", "generate_sample_sls_module", ...
46.777778
0.002328
def get_creation_date( self, bucket: str, key: str, ) -> datetime.datetime: """ Retrieves the creation date for a given key in a given bucket. :param bucket: the bucket the object resides in. :param key: the key of the object for which the creation...
[ "def", "get_creation_date", "(", "self", ",", "bucket", ":", "str", ",", "key", ":", "str", ",", ")", "->", "datetime", ".", "datetime", ":", "blob_obj", "=", "self", ".", "_get_blob_obj", "(", "bucket", ",", "key", ")", "return", "blob_obj", ".", "tim...
36
0.008333
def serialize_obj(obj): '''Custom serialization functionality for working with advanced data types. - numpy arrays are converted to lists - lists are recursively serialized element-wise ''' if isinstance(obj, np.integer): return int(obj) elif isinstance(obj, np.floating): ret...
[ "def", "serialize_obj", "(", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "np", ".", "integer", ")", ":", "return", "int", "(", "obj", ")", "elif", "isinstance", "(", "obj", ",", "np", ".", "floating", ")", ":", "return", "float", "(", "ob...
24.666667
0.001626
def on_delete(self, btn): "Flag this image as delete or keep." btn.button_style = "" if btn.flagged_for_delete else "danger" btn.flagged_for_delete = not btn.flagged_for_delete
[ "def", "on_delete", "(", "self", ",", "btn", ")", ":", "btn", ".", "button_style", "=", "\"\"", "if", "btn", ".", "flagged_for_delete", "else", "\"danger\"", "btn", ".", "flagged_for_delete", "=", "not", "btn", ".", "flagged_for_delete" ]
49.25
0.01
def run(dataset): """Run brain locally""" config = _get_config() if dataset: _print("getting dataset from brains...") cprint("done", 'green') # check dataset cache for dataset # if not exists # r = requests.get('https://api.github.com/events', stream=True) #...
[ "def", "run", "(", "dataset", ")", ":", "config", "=", "_get_config", "(", ")", "if", "dataset", ":", "_print", "(", "\"getting dataset from brains...\"", ")", "cprint", "(", "\"done\"", ",", "'green'", ")", "# check dataset cache for dataset", "# if not exists", ...
31.352941
0.001821
def update_tool_tip(self): """ Updates the node tooltip. :return: Method success. :rtype: bool """ self.roles[Qt.ToolTipRole] = self.__tool_tip_text.format(self.component.name, self.component.author, ...
[ "def", "update_tool_tip", "(", "self", ")", ":", "self", ".", "roles", "[", "Qt", ".", "ToolTipRole", "]", "=", "self", ".", "__tool_tip_text", ".", "format", "(", "self", ".", "component", ".", "name", ",", "self", ".", "component", ".", "author", ","...
46.133333
0.011331
def generate(self): """Generate a signed request from this instance.""" payload = { 'algorithm': 'HMAC-SHA256' } if self.data: payload['app_data'] = self.data if self.page: payload['page'] = {} if self.page.id: pa...
[ "def", "generate", "(", "self", ")", ":", "payload", "=", "{", "'algorithm'", ":", "'HMAC-SHA256'", "}", "if", "self", ".", "data", ":", "payload", "[", "'app_data'", "]", "=", "self", ".", "data", "if", "self", ".", "page", ":", "payload", "[", "'pa...
30.545455
0.001922
def pipe_yql(context=None, _INPUT=None, conf=None, **kwargs): """A source that issues YQL queries. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : pipeforever pipe or an iterable of items or fields conf : yqlquery -- YQL query # todo: handle envURL Yields ...
[ "def", "pipe_yql", "(", "context", "=", "None", ",", "_INPUT", "=", "None", ",", "conf", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# todo: get from a config/env file", "url", "=", "\"http://query.yahooapis.com/v1/public/yql\"", "conf", "=", "DotDict", "("...
28.770833
0.0007
def createEncoder(): """Create the encoder instance for our test and return it.""" consumption_encoder = ScalarEncoder(21, 0.0, 100.0, n=50, name="consumption", clipInput=True) time_encoder = DateEncoder(timeOfDay=(21, 9.5), name="timestamp_timeOfDay") encoder = MultiEncoder() encoder.addEncoder("consu...
[ "def", "createEncoder", "(", ")", ":", "consumption_encoder", "=", "ScalarEncoder", "(", "21", ",", "0.0", ",", "100.0", ",", "n", "=", "50", ",", "name", "=", "\"consumption\"", ",", "clipInput", "=", "True", ")", "time_encoder", "=", "DateEncoder", "(", ...
36.818182
0.021687
def translate(otp, to=MODHEX): """Return set() of possible modhex interpretations of a Yubikey otp. If otp uses all 16 characters in its alphabet, there will be only one possible interpretation of that Yubikey otp (except for two Armenian keyboard layouts). otp: Yubikey output. to: 16-characte...
[ "def", "translate", "(", "otp", ",", "to", "=", "MODHEX", ")", ":", "if", "PY3", ":", "if", "isinstance", "(", "otp", ",", "bytes", ")", ":", "raise", "ValueError", "(", "\"otp must be unicode\"", ")", "if", "isinstance", "(", "to", ",", "bytes", ")", ...
34.233333
0.000947
def large_clusters_mask(volume, min_cluster_size): """ Return as mask for `volume` that includes only areas where the connected components have a size bigger than `min_cluster_size` in number of voxels. Parameters ----------- volume: numpy.array 3D boolean array. min_cluster_size: ...
[ "def", "large_clusters_mask", "(", "volume", ",", "min_cluster_size", ")", ":", "labels", ",", "num_labels", "=", "scn", ".", "label", "(", "volume", ")", "labels_to_keep", "=", "set", "(", "[", "i", "for", "i", "in", "range", "(", "num_labels", ")", "if...
29.344828
0.002275
def get(self, *args, **kwargs): """ An interface for get requests that handles errors more gracefully to prevent data loss """ try: req_func = self.session.get if self.session else requests.get req = req_func(*args, **kwargs) req.ra...
[ "def", "get", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "req_func", "=", "self", ".", "session", ".", "get", "if", "self", ".", "session", "else", "requests", ".", "get", "req", "=", "req_func", "(", "*", "args...
37.117647
0.001544
def save_dynamic_class(self, obj): """ Save a class that can't be stored as module global. This method is used to serialize classes that are defined inside functions, or that otherwise can't be serialized as attribute lookups from global modules. """ clsdict = di...
[ "def", "save_dynamic_class", "(", "self", ",", "obj", ")", ":", "clsdict", "=", "dict", "(", "obj", ".", "__dict__", ")", "# copy dict proxy to a dict", "clsdict", ".", "pop", "(", "'__weakref__'", ",", "None", ")", "# For ABCMeta in python3.7+, remove _abc_impl as ...
43.802632
0.001175
def mknod(self, req, parent, name, mode, rdev): """Create file node Valid replies: reply_entry reply_err """ self.reply_err(req, errno.EROFS)
[ "def", "mknod", "(", "self", ",", "req", ",", "parent", ",", "name", ",", "mode", ",", "rdev", ")", ":", "self", ".", "reply_err", "(", "req", ",", "errno", ".", "EROFS", ")" ]
23.875
0.010101
def remove_file(profile, branch, file_path, commit_message=None): """Remove a file from a branch. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to...
[ "def", "remove_file", "(", "profile", ",", "branch", ",", "file_path", ",", "commit_message", "=", "None", ")", ":", "branch_sha", "=", "get_branch_sha", "(", "profile", ",", "branch", ")", "tree", "=", "get_files_in_branch", "(", "profile", ",", "branch_sha",...
33.444444
0.000807
def fmt(y, t_min=0.5, n_fmt=None, kind='cubic', beta=0.5, over_sample=1, axis=-1): """The fast Mellin transform (FMT) [1]_ of a uniformly sampled signal y. When the Mellin parameter (beta) is 1/2, it is also known as the scale transform [2]_. The scale transform can be useful for audio analysis because its...
[ "def", "fmt", "(", "y", ",", "t_min", "=", "0.5", ",", "n_fmt", "=", "None", ",", "kind", "=", "'cubic'", ",", "beta", "=", "0.5", ",", "over_sample", "=", "1", ",", "axis", "=", "-", "1", ")", ":", "n", "=", "y", ".", "shape", "[", "axis", ...
36.5
0.001584
def delete_object(container_name, object_name, profile, **libcloud_kwargs): ''' Delete an object in the cloud :param container_name: Container name :type container_name: ``str`` :param object_name: Object name :type object_name: ``str`` :param profile: The profile key :type profile...
[ "def", "delete_object", "(", "container_name", ",", "object_name", ",", "profile", ",", "*", "*", "libcloud_kwargs", ")", ":", "conn", "=", "_get_driver", "(", "profile", "=", "profile", ")", "libcloud_kwargs", "=", "salt", ".", "utils", ".", "args", ".", ...
29.566667
0.002183
def show(self, title=''): """ Display Bloch sphere and corresponding data sets. """ self.render(title=title) if self.fig: plt.show(self.fig)
[ "def", "show", "(", "self", ",", "title", "=", "''", ")", ":", "self", ".", "render", "(", "title", "=", "title", ")", "if", "self", ".", "fig", ":", "plt", ".", "show", "(", "self", ".", "fig", ")" ]
26.571429
0.010417
def Pop(self): """Remove the tag from the front of the list and return it.""" if self.tagList: tag = self.tagList[0] del self.tagList[0] else: tag = None return tag
[ "def", "Pop", "(", "self", ")", ":", "if", "self", ".", "tagList", ":", "tag", "=", "self", ".", "tagList", "[", "0", "]", "del", "self", ".", "tagList", "[", "0", "]", "else", ":", "tag", "=", "None", "return", "tag" ]
25
0.008584
def get_docker(interfaces=None, cidrs=None, with_container_id=False): ''' .. versionchanged:: 2017.7.8,2018.3.3 When :conf_minion:`docker.update_mine` is set to ``False`` for a given minion, no mine data will be populated for that minion, and thus none will be returned for it. .. ver...
[ "def", "get_docker", "(", "interfaces", "=", "None", ",", "cidrs", "=", "None", ",", "with_container_id", "=", "False", ")", ":", "# Enforce that interface and cidr are lists", "if", "interfaces", ":", "interface_", "=", "[", "]", "interface_", ".", "extend", "(...
41.584906
0.001551
def docker_inspect(image): '''Inspects a docker image Returns: Parsed JSON data ''' args = ['docker', 'inspect', '--type', 'image', image] p = Popen(args, stdout = subprocess.PIPE, stderr = subprocess.PIPE) stdout, stderr = p.communicate() stdout = stdout.decode('utf-8') stderr = stder...
[ "def", "docker_inspect", "(", "image", ")", ":", "args", "=", "[", "'docker'", ",", "'inspect'", ",", "'--type'", ",", "'image'", ",", "image", "]", "p", "=", "Popen", "(", "args", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "s...
30.722222
0.008772
def Jkpw(dW, h, n=5): """matrix J approximating repeated Stratonovich integrals for each of N time intervals, based on the method of Kloeden, Platen and Wright (1992). Args: dW (array of shape (N, m)): giving m independent Weiner increments for each time step N. (You can make this array using...
[ "def", "Jkpw", "(", "dW", ",", "h", ",", "n", "=", "5", ")", ":", "m", "=", "dW", ".", "shape", "[", "1", "]", "A", ",", "I", "=", "Ikpw", "(", "dW", ",", "h", ",", "n", ")", "J", "=", "I", "+", "0.5", "*", "h", "*", "np", ".", "eye...
39.7
0.00246
def cleanup(self): ''' Stop backgroud thread and cleanup resources ''' self._processing_stop = True self._wakeup_processing_thread() self._processing_stopped_event.wait(3)
[ "def", "cleanup", "(", "self", ")", ":", "self", ".", "_processing_stop", "=", "True", "self", ".", "_wakeup_processing_thread", "(", ")", "self", ".", "_processing_stopped_event", ".", "wait", "(", "3", ")" ]
39.8
0.009852
def AVEDEV(Series, N): """ 平均绝对偏差 mean absolute deviation 修正: 2018-05-25 之前用mad的计算模式依然返回的是单值 """ return Series.rolling(N).apply(lambda x: (np.abs(x - x.mean())).mean(), raw=True)
[ "def", "AVEDEV", "(", "Series", ",", "N", ")", ":", "return", "Series", ".", "rolling", "(", "N", ")", ".", "apply", "(", "lambda", "x", ":", "(", "np", ".", "abs", "(", "x", "-", "x", ".", "mean", "(", ")", ")", ")", ".", "mean", "(", ")",...
24.625
0.014706
def eigenvectors_rev(T, right=True, mu=None): r"""Compute eigenvectors of reversible transition matrix. Parameters ---------- T : (d, d) ndarray Transition matrix (stochastic matrix) right : bool, optional If right=True compute right eigenvectors, left eigenvectors otherwise...
[ "def", "eigenvectors_rev", "(", "T", ",", "right", "=", "True", ",", "mu", "=", "None", ")", ":", "if", "mu", "is", "None", ":", "mu", "=", "stationary_distribution", "(", "T", ")", "\"\"\" symmetrize T \"\"\"", "smu", "=", "np", ".", "sqrt", "(", "mu"...
27.212121
0.002151
def plot(self): """ Return a matplotlib figure of the dose-response dataset. Examples -------- >>> fig = dataset.plot() >>> fig.show() .. image:: ../tests/resources/test_cdataset_plot.png :align: center :alt: Example generated BMD plot ...
[ "def", "plot", "(", "self", ")", ":", "fig", "=", "plotting", ".", "create_empty_figure", "(", ")", "ax", "=", "fig", ".", "gca", "(", ")", "xlabel", "=", "self", ".", "kwargs", ".", "get", "(", "\"xlabel\"", ",", "\"Dose\"", ")", "ylabel", "=", "s...
28.685714
0.001927
def _copy_finfo_directory(finfo, out_dir): """Copy a directory into the final output directory. """ out_dir = _get_dir_upload_path(finfo, out_dir) if not shared.up_to_date(out_dir, finfo): logger.info("Storing directory in local filesystem: %s" % out_dir) if os.path.exists(out_dir): ...
[ "def", "_copy_finfo_directory", "(", "finfo", ",", "out_dir", ")", ":", "out_dir", "=", "_get_dir_upload_path", "(", "finfo", ",", "out_dir", ")", "if", "not", "shared", ".", "up_to_date", "(", "out_dir", ",", "finfo", ")", ":", "logger", ".", "info", "(",...
42.571429
0.001642
def _parse_record_line(record_line): """ Extract fields from a record line string into a dictionary """ # Dictionary for record fields record_fields = {} # Read string fields from record line (record_fields['record_name'], record_fields['n_seg'], record_fields['n_sig'], record_fields[...
[ "def", "_parse_record_line", "(", "record_line", ")", ":", "# Dictionary for record fields", "record_fields", "=", "{", "}", "# Read string fields from record line", "(", "record_fields", "[", "'record_name'", "]", ",", "record_fields", "[", "'n_seg'", "]", ",", "record...
43.911111
0.00099
def openpgp(ctx): """ Manage OpenPGP Application. Examples: \b Set the retries for PIN, Reset Code and Admin PIN to 10: $ ykman openpgp set-retries 10 10 10 \b Require touch to use the authentication key: $ ykman openpgp touch aut on """ try: ctx.obj['contr...
[ "def", "openpgp", "(", "ctx", ")", ":", "try", ":", "ctx", ".", "obj", "[", "'controller'", "]", "=", "OpgpController", "(", "ctx", ".", "obj", "[", "'dev'", "]", ".", "driver", ")", "except", "APDUError", "as", "e", ":", "if", "e", ".", "sw", "=...
28.909091
0.001522
def rc2_cbc_pkcs5_encrypt(key, data, iv): """ Encrypts plaintext using RC2 with a 64 bit key :param key: The encryption key - a byte string 8 bytes long :param data: The plaintext - a byte string :param iv: The 8-byte initialization vector to use - a byte string - set as N...
[ "def", "rc2_cbc_pkcs5_encrypt", "(", "key", ",", "data", ",", "iv", ")", ":", "if", "len", "(", "key", ")", "<", "5", "or", "len", "(", "key", ")", ">", "16", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n key must be 5 to 16 byt...
27.380952
0.001679
def to_clipboard(obj, excel=True, sep=None, **kwargs): # pragma: no cover """ Attempt to write text representation of object to the system clipboard The clipboard can be then pasted into Excel for example. Parameters ---------- obj : the object to write to the clipboard excel : boolean, de...
[ "def", "to_clipboard", "(", "obj", ",", "excel", "=", "True", ",", "sep", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# pragma: no cover", "encoding", "=", "kwargs", ".", "pop", "(", "'encoding'", ",", "'utf-8'", ")", "# testing if an invalid encoding i...
33.086207
0.000506
def generate(tagGroups, terms): """ create Tag Groups and Child Tags using data from terms dict """ rv = [] for pid in tagGroups: # In testing we may not have complete set if pid not in terms.keys(): continue groupData = terms[pid] groupName = "[%s] %s" ...
[ "def", "generate", "(", "tagGroups", ",", "terms", ")", ":", "rv", "=", "[", "]", "for", "pid", "in", "tagGroups", ":", "# In testing we may not have complete set", "if", "pid", "not", "in", "terms", ".", "keys", "(", ")", ":", "continue", "groupData", "="...
29.038462
0.001282
def _getManagedObjectsInstances(self, varBinds, **context): """Iterate over Managed Objects fulfilling SNMP query. Returns ------- :py:class:`list` - List of Managed Objects Instances to respond with or `None` to indicate that not all objects have been gathered s...
[ "def", "_getManagedObjectsInstances", "(", "self", ",", "varBinds", ",", "*", "*", "context", ")", ":", "rspVarBinds", "=", "context", "[", "'rspVarBinds'", "]", "varBindsMap", "=", "context", "[", "'varBindsMap'", "]", "rtrVarBinds", "=", "[", "]", "for", "...
34.72973
0.001514
def html_for_modules_method(method_name, *args, **kwargs): """Returns an HTML snippet for a Modules API method. Args: method_name: A string containing a Modules API method. args: Positional arguments to be passed to the method. kwargs: Keyword arguments to be passed to the method. ...
[ "def", "html_for_modules_method", "(", "method_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "method", "=", "getattr", "(", "modules", ",", "method_name", ")", "value", "=", "method", "(", "*", "args", ",", "*", "*", "kwargs", ")", "retur...
37.571429
0.001855
def _shutdown(self): """Terminate the sub-process.""" if self._proc: ret = _shutdown_proc(self._proc, 3) logging.info("Shutdown with return code: %s", ret) self._proc = None
[ "def", "_shutdown", "(", "self", ")", ":", "if", "self", ".", "_proc", ":", "ret", "=", "_shutdown_proc", "(", "self", ".", "_proc", ",", "3", ")", "logging", ".", "info", "(", "\"Shutdown with return code: %s\"", ",", "ret", ")", "self", ".", "_proc", ...
32.333333
0.020101
def kogge_stone(a, b, cin=0): """ Creates a Kogge-Stone adder given two inputs :param WireVector a, b: The two WireVectors to add up (bitwidths don't need to match) :param cin: An optimal carry in WireVector or value :return: a Wirevector representing the output of the adder The Kogge-Stone ad...
[ "def", "kogge_stone", "(", "a", ",", "b", ",", "cin", "=", "0", ")", ":", "a", ",", "b", "=", "libutils", ".", "match_bitwidth", "(", "a", ",", "b", ")", "prop_orig", "=", "a", "^", "b", "prop_bits", "=", "[", "i", "for", "i", "in", "prop_orig"...
38.78125
0.002358
def Query(args): """Calls osquery with given query and returns its output. Args: args: A query to call osquery with. Returns: A "parsed JSON" representation of the osquery output. Raises: QueryError: If the query is incorrect. TimeoutError: If a call to the osquery executable times out. E...
[ "def", "Query", "(", "args", ")", ":", "query", "=", "args", ".", "query", ".", "encode", "(", "\"utf-8\"", ")", "timeout", "=", "args", ".", "timeout_millis", "/", "1000", "# `subprocess.run` uses seconds.", "# TODO: pytype is not aware of the backport.", "# pytype...
39.227273
0.010741
def freeSearch(self, searchString): """Execute a free text search for all columns in the dataframe. Parameters ---------- searchString (str): Any string which may be contained in a column. Returns ------- list: A list containing all indexes with filtered...
[ "def", "freeSearch", "(", "self", ",", "searchString", ")", ":", "if", "not", "self", ".", "_dataFrame", ".", "empty", ":", "# set question to the indexes of data and set everything to false.", "question", "=", "self", ".", "_dataFrame", ".", "index", "==", "-", "...
38.551724
0.001745
def _check_last_arg_pattern(self, current_arg_pattern, last_arg_pattern): """Given a "current" arg pattern (that was used to match the last actual argument of an expression), and another ("last") argument pattern, raise a ValueError, unless the "last" argument pattern is a "zero or more"...
[ "def", "_check_last_arg_pattern", "(", "self", ",", "current_arg_pattern", ",", "last_arg_pattern", ")", ":", "try", ":", "if", "last_arg_pattern", ".", "mode", "==", "self", ".", "single", ":", "raise", "ValueError", "(", "\"insufficient number of arguments\"", ")"...
54.666667
0.001712
def enable_static_ip_config(self, ip_address, network_mask): """sets and enables the static IP V4 configuration for the given interface. in ip_address of type str IP address. in network_mask of type str network mask. """ if not isinstance(ip_address, ba...
[ "def", "enable_static_ip_config", "(", "self", ",", "ip_address", ",", "network_mask", ")", ":", "if", "not", "isinstance", "(", "ip_address", ",", "basestring", ")", ":", "raise", "TypeError", "(", "\"ip_address can only be an instance of type basestring\"", ")", "if...
39.8125
0.009202
def sendIq(self, entity): """ :type entity: IqProtocolEntity """ if entity.getType() == IqProtocolEntity.TYPE_SET and entity.getXmlns() == "w:m": #media upload! self._sendIq(entity, self.onRequestUploadSuccess, self.onRequestUploadError)
[ "def", "sendIq", "(", "self", ",", "entity", ")", ":", "if", "entity", ".", "getType", "(", ")", "==", "IqProtocolEntity", ".", "TYPE_SET", "and", "entity", ".", "getXmlns", "(", ")", "==", "\"w:m\"", ":", "#media upload!", "self", ".", "_sendIq", "(", ...
41
0.017065
def create_snapshot(self, name, *args, **kwargs): """ Thin method that just uses the provider """ return self.provider.create_snapshot(name, *args, **kwargs)
[ "def", "create_snapshot", "(", "self", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "provider", ".", "create_snapshot", "(", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
37
0.010582
def _bss_decomp_mtifilt(reference_sources, estimated_source, j, flen): """Decomposition of an estimated source image into four components representing respectively the true source image, spatial (or filtering) distortion, interference and artifacts, derived from the true source images using multichannel...
[ "def", "_bss_decomp_mtifilt", "(", "reference_sources", ",", "estimated_source", ",", "j", ",", "flen", ")", ":", "nsampl", "=", "estimated_source", ".", "size", "# decomposition", "# true source image", "s_true", "=", "np", ".", "hstack", "(", "(", "reference_sou...
45.35
0.00108
def object_len(node, context=None): """Infer length of given node object :param Union[nodes.ClassDef, nodes.Instance] node: :param node: Node to infer length of :raises AstroidTypeError: If an invalid node is returned from __len__ method or no __len__ method exists :raises InferenceError: ...
[ "def", "object_len", "(", "node", ",", "context", "=", "None", ")", ":", "from", "astroid", ".", "objects", "import", "FrozenSet", "inferred_node", "=", "safe_infer", "(", "node", ",", "context", "=", "context", ")", "if", "inferred_node", "is", "None", "o...
39.071429
0.001189
def index_modules(root) -> Dict: """ Counts the number of modules in the Fortran file including the program file. Each module is written out into a separate Python file. """ module_index_dict = { node["name"]: (node.get("tag"), index) for index, node in enumerate(root) if node.get(...
[ "def", "index_modules", "(", "root", ")", "->", "Dict", ":", "module_index_dict", "=", "{", "node", "[", "\"name\"", "]", ":", "(", "node", ".", "get", "(", "\"tag\"", ")", ",", "index", ")", "for", "index", ",", "node", "in", "enumerate", "(", "root...
35.545455
0.002494
def set_tempo_event(self, bpm): """Calculate the microseconds per quarter note.""" ms_per_min = 60000000 mpqn = a2b_hex('%06x' % (ms_per_min / bpm)) return self.delta_time + META_EVENT + SET_TEMPO + '\x03' + mpqn
[ "def", "set_tempo_event", "(", "self", ",", "bpm", ")", ":", "ms_per_min", "=", "60000000", "mpqn", "=", "a2b_hex", "(", "'%06x'", "%", "(", "ms_per_min", "/", "bpm", ")", ")", "return", "self", ".", "delta_time", "+", "META_EVENT", "+", "SET_TEMPO", "+"...
48
0.008197
def serial_udb_extra_f13_encode(self, sue_week_no, sue_lat_origin, sue_lon_origin, sue_alt_origin): ''' Backwards compatible version of SERIAL_UDB_EXTRA F13: format sue_week_no : Serial UDB Extra GPS Week Number (int16_t) sue_lat_origin ...
[ "def", "serial_udb_extra_f13_encode", "(", "self", ",", "sue_week_no", ",", "sue_lat_origin", ",", "sue_lon_origin", ",", "sue_alt_origin", ")", ":", "return", "MAVLink_serial_udb_extra_f13_message", "(", "sue_week_no", ",", "sue_lat_origin", ",", "sue_lon_origin", ",", ...
63.909091
0.01122
def _vard(ins): """ Defines a memory space with a default set of bytes/words in hexadecimal (starting with a number) or literals (starting with #). Numeric values with more than 2 digits represents a WORD (2 bytes) value. E.g. '01' => 0, '001' => 1, 0 bytes Literal values starts with # (1 byte) or #...
[ "def", "_vard", "(", "ins", ")", ":", "output", "=", "[", "]", "output", ".", "append", "(", "'%s:'", "%", "ins", ".", "quad", "[", "1", "]", ")", "q", "=", "eval", "(", "ins", ".", "quad", "[", "2", "]", ")", "for", "x", "in", "q", ":", ...
34.103448
0.000983
def _set_link(self, linkname, cls, **kwargs): """Transfer options kwargs to a `Link` object, optionally building the `Link if needed. Parameters ---------- linkname : str Unique name of this particular link cls : type Type of `Link` being create...
[ "def", "_set_link", "(", "self", ",", "linkname", ",", "cls", ",", "*", "*", "kwargs", ")", ":", "val_copy", "=", "purge_dict", "(", "kwargs", ".", "copy", "(", ")", ")", "sub_link_prefix", "=", "val_copy", ".", "pop", "(", "'link_prefix'", ",", "''", ...
38.242424
0.002318
def str2dt(time: datetime) -> np.ndarray: """ Converts times in string or list of strings to datetime(s) Parameters ---------- time : str or datetime.datetime or numpy.datetime64 Results ------- t : datetime.datetime """ if isinstance(time, datetime): return time ...
[ "def", "str2dt", "(", "time", ":", "datetime", ")", "->", "np", ".", "ndarray", ":", "if", "isinstance", "(", "time", ",", "datetime", ")", ":", "return", "time", "elif", "isinstance", "(", "time", ",", "str", ")", ":", "return", "parse", "(", "time"...
25.8
0.001067
def _init_map(self): """stub""" QuestionTextFormRecord._init_map(self) QuestionFilesFormRecord._init_map(self) super(QuestionTextAndFilesMixin, self)._init_map()
[ "def", "_init_map", "(", "self", ")", ":", "QuestionTextFormRecord", ".", "_init_map", "(", "self", ")", "QuestionFilesFormRecord", ".", "_init_map", "(", "self", ")", "super", "(", "QuestionTextAndFilesMixin", ",", "self", ")", ".", "_init_map", "(", ")" ]
37.8
0.010363
def write_tsv(headerfields, features, outfn): """Writes header and generator of lines to tab separated file. headerfields - list of field names in header in correct order features - generates 1 list per line that belong to header outfn - filename to output to. Overwritten if exists """ with ope...
[ "def", "write_tsv", "(", "headerfields", ",", "features", ",", "outfn", ")", ":", "with", "open", "(", "outfn", ",", "'w'", ")", "as", "fp", ":", "write_tsv_line_from_list", "(", "headerfields", ",", "fp", ")", "for", "line", "in", "features", ":", "writ...
44.583333
0.001832
def update(self, render, force = False): """ Update view @param render: IRender @param force: force update """ if not force: return; drawArea = QtGui.QImage(self._width, self._height, render.getImageFormat()) drawArea.fill(self._backgroundColor...
[ "def", "update", "(", "self", ",", "render", ",", "force", "=", "False", ")", ":", "if", "not", "force", ":", "return", "drawArea", "=", "QtGui", ".", "QImage", "(", "self", ".", "_width", ",", "self", ".", "_height", ",", "render", ".", "getImageFor...
35.933333
0.012658
def godot_options(self, info): """ Handles display of the options menu. """ if info.initialized: self.edit_traits( parent = info.ui.control, kind = "livemodal", view = "options_view" )
[ "def", "godot_options", "(", "self", ",", "info", ")", ":", "if", "info", ".", "initialized", ":", "self", ".", "edit_traits", "(", "parent", "=", "info", ".", "ui", ".", "control", ",", "kind", "=", "\"livemodal\"", ",", "view", "=", "\"options_view\"",...
38.714286
0.043321
def _qrd_solve_full(a, b, ddiag, dtype=np.float): """Solve the equation A^T x = B, D x = 0. Parameters: a - an n-by-m array, m >= n b - an m-vector ddiag - an n-vector giving the diagonal of D. (The rest of D is 0.) Returns: x - n-vector solving the equation. s - the n-by-n supplementary matrix s. p...
[ "def", "_qrd_solve_full", "(", "a", ",", "b", ",", "ddiag", ",", "dtype", "=", "np", ".", "float", ")", ":", "a", "=", "np", ".", "asarray", "(", "a", ",", "dtype", ")", "b", "=", "np", ".", "asarray", "(", "b", ",", "dtype", ")", "ddiag", "=...
29.452381
0.001565
def delete(self, queue='', if_unused=False, if_empty=False): """Delete a Queue. :param str queue: Queue name :param bool if_unused: Delete only if unused :param bool if_empty: Delete only if empty :raises AMQPInvalidArgument: Invalid Parameters :raises AMQPChannelError:...
[ "def", "delete", "(", "self", ",", "queue", "=", "''", ",", "if_unused", "=", "False", ",", "if_empty", "=", "False", ")", ":", "if", "not", "compatibility", ".", "is_string", "(", "queue", ")", ":", "raise", "AMQPInvalidArgument", "(", "'queue should be a...
43.083333
0.001892
def visualize(self, show_ports=False): """Visualize the Compound using nglview. Allows for visualization of a Compound within a Jupyter Notebook. Parameters ---------- show_ports : bool, optional, default=False Visualize Ports in addition to Particles """ ...
[ "def", "visualize", "(", "self", ",", "show_ports", "=", "False", ")", ":", "nglview", "=", "import_", "(", "'nglview'", ")", "from", "mdtraj", ".", "geometry", ".", "sasa", "import", "_ATOMIC_RADII", "if", "run_from_ipython", "(", ")", ":", "remove_digits",...
43.604167
0.002336
def generate_scope_string(date, region): """ Generate scope string. :param date: Date is input from :meth:`datetime.datetime` :param region: Region should be set to bucket region. """ formatted_date = date.strftime("%Y%m%d") scope = '/'.join([formatted_date, region, ...
[ "def", "generate_scope_string", "(", "date", ",", "region", ")", ":", "formatted_date", "=", "date", ".", "strftime", "(", "\"%Y%m%d\"", ")", "scope", "=", "'/'", ".", "join", "(", "[", "formatted_date", ",", "region", ",", "'s3'", ",", "'aws4_request'", "...
29.923077
0.002494
def _get_translated_field_names(model_instance): """ Get the instance translatable fields :return: """ hvad_internal_fields = ['id', 'language_code', 'master', 'master_id', 'master_id'] translated_field_names = set(model_instance._translated_field_names) - set(hvad_inter...
[ "def", "_get_translated_field_names", "(", "model_instance", ")", ":", "hvad_internal_fields", "=", "[", "'id'", ",", "'language_code'", ",", "'master'", ",", "'master_id'", ",", "'master_id'", "]", "translated_field_names", "=", "set", "(", "model_instance", ".", "...
40.111111
0.01084
def make_code_from_py(filename): """Get source from `filename` and make a code object of it.""" # Open the source file. try: source_file = open_source(filename) except IOError: raise NoSource("No file to run: %r" % filename) try: source = source_file.read() finally: ...
[ "def", "make_code_from_py", "(", "filename", ")", ":", "# Open the source file.", "try", ":", "source_file", "=", "open_source", "(", "filename", ")", "except", "IOError", ":", "raise", "NoSource", "(", "\"No file to run: %r\"", "%", "filename", ")", "try", ":", ...
29.45
0.001645
def print_ldamodel_doc_topics(doc_topic_distrib, doc_labels, n_top=3, val_labels=DEFAULT_TOPIC_NAME_FMT): """Print `n_top` values from a LDA model's document-topic distributions.""" print_ldamodel_distribution(doc_topic_distrib, row_labels=doc_labels, val_labels=val_labels, top_n...
[ "def", "print_ldamodel_doc_topics", "(", "doc_topic_distrib", ",", "doc_labels", ",", "n_top", "=", "3", ",", "val_labels", "=", "DEFAULT_TOPIC_NAME_FMT", ")", ":", "print_ldamodel_distribution", "(", "doc_topic_distrib", ",", "row_labels", "=", "doc_labels", ",", "va...
81
0.009174
def update_to_v24(self): """Convert older tags into an ID3v2.4 tag. This updates old ID3v2 frames to ID3v2.4 ones (e.g. TYER to TDRC). If you intend to save tags, you must call this function at some point; it is called by default when loading the tag. """ self.__update_...
[ "def", "update_to_v24", "(", "self", ")", ":", "self", ".", "__update_common", "(", ")", "# TDAT, TYER, and TIME have been turned into TDRC.", "try", ":", "date", "=", "text_type", "(", "self", ".", "get", "(", "\"TYER\"", ",", "\"\"", ")", ")", "if", "date", ...
36.696429
0.000948
def substitute_synonym(self, nt): """ Replace the record_term and parent_term with a synonym :param nt: :return: """ if nt.join_lc in self.synonyms: nt.parent_term, nt.record_term = Term.split_term_lower(self.synonyms[nt.join_lc]);
[ "def", "substitute_synonym", "(", "self", ",", "nt", ")", ":", "if", "nt", ".", "join_lc", "in", "self", ".", "synonyms", ":", "nt", ".", "parent_term", ",", "nt", ".", "record_term", "=", "Term", ".", "split_term_lower", "(", "self", ".", "synonyms", ...
31.555556
0.013699
def instantiate(self, scope, args, interp): """Create a ParamList instance for actual interpretation :args: TODO :returns: A ParamList object """ param_instances = [] BYREF = "byref" # TODO are default values for function parameters allowed in 010? for...
[ "def", "instantiate", "(", "self", ",", "scope", ",", "args", ",", "interp", ")", ":", "param_instances", "=", "[", "]", "BYREF", "=", "\"byref\"", "# TODO are default values for function parameters allowed in 010?", "for", "param_name", ",", "param_cls", "in", "sel...
35
0.001853
def create_cylinder(rows, cols, radius=[1.0, 1.0], length=1.0, offset=False): """Create a cylinder Parameters ---------- rows : int Number of rows. cols : int Number of columns. radius : tuple of float Cylinder radii. length : float Length of the cylinder. ...
[ "def", "create_cylinder", "(", "rows", ",", "cols", ",", "radius", "=", "[", "1.0", ",", "1.0", "]", ",", "length", "=", "1.0", ",", "offset", "=", "False", ")", ":", "verts", "=", "np", ".", "empty", "(", "(", "rows", "+", "1", ",", "cols", ",...
36.365385
0.000515
def methodcall(obj, method_name, *args, **kwargs): """Call a method of `obj`, either locally or remotely as appropriate. obj may be an ordinary object, or a Remote object (or Ref or object Id) If there are multiple remote arguments, they must be on the same engine. kwargs: prefer_local (bool,...
[ "def", "methodcall", "(", "obj", ",", "method_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "this_engine", "=", "distob", ".", "engine", ".", "eid", "args", "=", "[", "obj", "]", "+", "list", "(", "args", ")", "prefer_local", "=", "kw...
44.26
0.001326
def index(context, update): """Create indexes for the database""" LOG.info("Running scout index") adapter = context.obj['adapter'] if update: adapter.update_indexes() else: adapter.load_indexes()
[ "def", "index", "(", "context", ",", "update", ")", ":", "LOG", ".", "info", "(", "\"Running scout index\"", ")", "adapter", "=", "context", ".", "obj", "[", "'adapter'", "]", "if", "update", ":", "adapter", ".", "update_indexes", "(", ")", "else", ":", ...
25.333333
0.008475
def get_region (self, rs,cs, re,ce): '''This returns a list of lines representing the region. ''' rs = constrain (rs, 1, self.rows) re = constrain (re, 1, self.rows) cs = constrain (cs, 1, self.cols) ce = constrain (ce, 1, self.cols) if rs > re: rs, r...
[ "def", "get_region", "(", "self", ",", "rs", ",", "cs", ",", "re", ",", "ce", ")", ":", "rs", "=", "constrain", "(", "rs", ",", "1", ",", "self", ".", "rows", ")", "re", "=", "constrain", "(", "re", ",", "1", ",", "self", ".", "rows", ")", ...
29.7
0.022838
def to_match(self): """Return a unicode object with the MATCH representation of this GlobalContextField.""" self.validate() mark_name, field_name = self.location.get_location_name() validate_safe_string(mark_name) validate_safe_string(field_name) return u'%s.%s' % (mark...
[ "def", "to_match", "(", "self", ")", ":", "self", ".", "validate", "(", ")", "mark_name", ",", "field_name", "=", "self", ".", "location", ".", "get_location_name", "(", ")", "validate_safe_string", "(", "mark_name", ")", "validate_safe_string", "(", "field_na...
36.666667
0.008876
def send_vdp_msg(self, mode, mgrid, typeid, typeid_ver, vsiid_frmt, vsiid, filter_frmt, gid, mac, vlan, oui_id, oui_data, sw_resp): """Constructs and Sends the VDP Message. Please refer http://www.ieee802.org/1/pages/802.1bg.html VDP Section for more de...
[ "def", "send_vdp_msg", "(", "self", ",", "mode", ",", "mgrid", ",", "typeid", ",", "typeid_ver", ",", "vsiid_frmt", ",", "vsiid", ",", "filter_frmt", ",", "gid", ",", "mac", ",", "vlan", ",", "oui_id", ",", "oui_data", ",", "sw_resp", ")", ":", "if", ...
49.949153
0.001331
def read_unicode_csv_fileobj(fileobj, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL, lineterminator='\n', encoding='utf-8', skiprows=0): """fileobj can be a StringIO in Py3, but should be a BytesIO in Py2.""" # Python 3 version if sys.versi...
[ "def", "read_unicode_csv_fileobj", "(", "fileobj", ",", "delimiter", "=", "','", ",", "quotechar", "=", "'\"'", ",", "quoting", "=", "csv", ".", "QUOTE_MINIMAL", ",", "lineterminator", "=", "'\\n'", ",", "encoding", "=", "'utf-8'", ",", "skiprows", "=", "0",...
49.37931
0.002055
def attach(self, app, engineio_path='engine.io'): """Attach the Engine.IO server to an application.""" engineio_path = engineio_path.strip('/') self._async['create_route'](app, self, '/{}/'.format(engineio_path))
[ "def", "attach", "(", "self", ",", "app", ",", "engineio_path", "=", "'engine.io'", ")", ":", "engineio_path", "=", "engineio_path", ".", "strip", "(", "'/'", ")", "self", ".", "_async", "[", "'create_route'", "]", "(", "app", ",", "self", ",", "'/{}/'",...
58.25
0.008475
def clone(repo, log, depth=1): """Given a list of repositories, make sure they're all cloned. Should be called from the subclassed `Catalog` objects, passed a list of specific repository names. Arguments --------- all_repos : list of str *Absolute* path specification of each target rep...
[ "def", "clone", "(", "repo", ",", "log", ",", "depth", "=", "1", ")", ":", "kwargs", "=", "{", "}", "if", "depth", ">", "0", ":", "kwargs", "[", "'depth'", "]", "=", "depth", "try", ":", "repo_name", "=", "os", ".", "path", ".", "split", "(", ...
29.962963
0.002395
def assign_to_topic_partition(self, topic_partition=None): """Assign a list of TopicPartitions to this consumer. - ``partitions`` (list of `TopicPartition`): Assignment for this instance. """ if isinstance(topic_partition, TopicPartition): topic_partition = [topic_p...
[ "def", "assign_to_topic_partition", "(", "self", ",", "topic_partition", "=", "None", ")", ":", "if", "isinstance", "(", "topic_partition", ",", "TopicPartition", ")", ":", "topic_partition", "=", "[", "topic_partition", "]", "if", "not", "self", ".", "_is_assig...
42.1
0.009302
def _construct_predict(self, beta, h): """ Creates h-step ahead forecasts for the Gaussian process Parameters ---------- beta : np.array Contains untransformed starting values for the latent variables h: int How many steps ahead to fo...
[ "def", "_construct_predict", "(", "self", ",", "beta", ",", "h", ")", ":", "# Refactor this entire code in future", "parm", "=", "np", ".", "array", "(", "[", "self", ".", "latent_variables", ".", "z_list", "[", "k", "]", ".", "prior", ".", "transform", "(...
36.693878
0.009751
def delete_vector(self, hash_name, bucket_keys, data): """ Deletes vector and JSON-serializable data in buckets with specified keys. """ for key in bucket_keys: bucket = self.get_bucket(hash_name, key) bucket[:] = [(v, id_data) for v, id_data ...
[ "def", "delete_vector", "(", "self", ",", "hash_name", ",", "bucket_keys", ",", "data", ")", ":", "for", "key", "in", "bucket_keys", ":", "bucket", "=", "self", ".", "get_bucket", "(", "hash_name", ",", "key", ")", "bucket", "[", ":", "]", "=", "[", ...
43.25
0.008499
def read(self, n=-1): """ Reads C{n} bytes from the stream. """ if n < -1: raise IOError('Cannot read backwards') bytes = self._buffer.read(n) return bytes
[ "def", "read", "(", "self", ",", "n", "=", "-", "1", ")", ":", "if", "n", "<", "-", "1", ":", "raise", "IOError", "(", "'Cannot read backwards'", ")", "bytes", "=", "self", ".", "_buffer", ".", "read", "(", "n", ")", "return", "bytes" ]
20.8
0.009217
def genCaCert(self, name, signas=None, outp=None, save=True): ''' Generates a CA keypair. Args: name (str): The name of the CA keypair. signas (str): The CA keypair to sign the new CA with. outp (synapse.lib.output.Output): The output buffer. Example...
[ "def", "genCaCert", "(", "self", ",", "name", ",", "signas", "=", "None", ",", "outp", "=", "None", ",", "save", "=", "True", ")", ":", "pkey", ",", "cert", "=", "self", ".", "_genBasePkeyCert", "(", "name", ")", "ext0", "=", "crypto", ".", "X509Ex...
32.081081
0.002453
def weber(I,x,y,w): """weber: model for solving the single source weber problem using soco. Parameters: - I: set of customers - x[i]: x position of customer i - y[i]: y position of customer i - w[i]: weight of customer i Returns a model, ready to be solved. """ model...
[ "def", "weber", "(", "I", ",", "x", ",", "y", ",", "w", ")", ":", "model", "=", "Model", "(", "\"weber\"", ")", "X", ",", "Y", ",", "z", ",", "xaux", ",", "yaux", "=", "{", "}", ",", "{", "}", ",", "{", "}", ",", "{", "}", ",", "{", "...
36.241379
0.022243
def delete_all_hosting_devices_by_template(self, context, template, force_delete=False): """Deletes all hosting devices based on <template>.""" plugging_drv = self.get_hosting_device_plugging_driver( context, template['id']) hosting_devi...
[ "def", "delete_all_hosting_devices_by_template", "(", "self", ",", "context", ",", "template", ",", "force_delete", "=", "False", ")", ":", "plugging_drv", "=", "self", ".", "get_hosting_device_plugging_driver", "(", "context", ",", "template", "[", "'id'", "]", "...
54.1
0.001816
def observeElements(self, what, call=None): """ Registers an observer function to a specific state field or list of state fields. The function to call should have 2 parameters: - previousValue, -actualValue :param what: name of the state field or ...
[ "def", "observeElements", "(", "self", ",", "what", ",", "call", "=", "None", ")", ":", "def", "_observe", "(", "call", ")", ":", "self", ".", "__observers", ".", "add", "(", "what", ",", "call", ")", "return", "call", "toEvaluate", "=", "[", "]", ...
32.896552
0.001018
def update_homed_flags(self, flags=None): ''' Returns Smoothieware's current homing-status, which is a dictionary of boolean values for each axis (XYZABC). If an axis is False, then it still needs to be homed, and it's coordinate cannot be trusted. Smoothieware sets it's internal...
[ "def", "update_homed_flags", "(", "self", ",", "flags", "=", "None", ")", ":", "if", "flags", "and", "isinstance", "(", "flags", ",", "dict", ")", ":", "self", ".", "homed_flags", ".", "update", "(", "flags", ")", "elif", "self", ".", "simulating", ":"...
37.05
0.001315
def show_replace(self): """Show replace widgets""" self.show(hide_replace=False) for widget in self.replace_widgets: widget.show()
[ "def", "show_replace", "(", "self", ")", ":", "self", ".", "show", "(", "hide_replace", "=", "False", ")", "for", "widget", "in", "self", ".", "replace_widgets", ":", "widget", ".", "show", "(", ")" ]
33.2
0.011765
def class_register(cls): """Class decorator that allows to map LSP method names to class methods.""" cls.handler_registry = {} cls.sender_registry = {} for method_name in dir(cls): method = getattr(cls, method_name) if hasattr(method, '_handle'): cls.handler_registry.update({...
[ "def", "class_register", "(", "cls", ")", ":", "cls", ".", "handler_registry", "=", "{", "}", "cls", ".", "sender_registry", "=", "{", "}", "for", "method_name", "in", "dir", "(", "cls", ")", ":", "method", "=", "getattr", "(", "cls", ",", "method_name...
41.909091
0.002123
def _write_adminfile(kwargs): ''' Create a temporary adminfile based on the keyword arguments passed to pkg.install. ''' # Set the adminfile default variables email = kwargs.get('email', '') instance = kwargs.get('instance', 'quit') partial = kwargs.get('partial', 'nocheck') runlevel...
[ "def", "_write_adminfile", "(", "kwargs", ")", ":", "# Set the adminfile default variables", "email", "=", "kwargs", ".", "get", "(", "'email'", ",", "''", ")", "instance", "=", "kwargs", ".", "get", "(", "'instance'", ",", "'quit'", ")", "partial", "=", "kw...
40.815789
0.00063