text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def implement(cls, implementations, for_type=None, for_types=None): """Provide protocol implementation for a type. Register all implementations of multimethod functions in this protocol and add the type into the abstract base class of the protocol. Arguments: implem...
[ "def", "implement", "(", "cls", ",", "implementations", ",", "for_type", "=", "None", ",", "for_types", "=", "None", ")", ":", "for", "type_", "in", "cls", ".", "__get_type_args", "(", "for_type", ",", "for_types", ")", ":", "cls", ".", "_implement_for_typ...
45.875
25.916667
def _get_generator(self, name): """Load the generator plugin and execute its lifecycle. :param dist: distribution """ for ep in pkg_resources.iter_entry_points(self.group, name=None): if ep.name == name: generator = ep.load() return generator
[ "def", "_get_generator", "(", "self", ",", "name", ")", ":", "for", "ep", "in", "pkg_resources", ".", "iter_entry_points", "(", "self", ".", "group", ",", "name", "=", "None", ")", ":", "if", "ep", ".", "name", "==", "name", ":", "generator", "=", "e...
34.555556
12.111111
def is_readonly_path(fn): """Check if a provided path exists and is readonly. Permissions check is `bool(path.stat & stat.S_IREAD)` or `not os.access(path, os.W_OK)` """ fn = fs_encode(fn) if os.path.exists(fn): file_stat = os.stat(fn).st_mode return not bool(file_stat & stat.S_IWR...
[ "def", "is_readonly_path", "(", "fn", ")", ":", "fn", "=", "fs_encode", "(", "fn", ")", "if", "os", ".", "path", ".", "exists", "(", "fn", ")", ":", "file_stat", "=", "os", ".", "stat", "(", "fn", ")", ".", "st_mode", "return", "not", "bool", "("...
32.818182
22.090909
def extract_report_spec( service, label_is_supported=label_descriptor.KnownLabels.is_supported, metric_is_supported=metric_descriptor.KnownMetrics.is_supported): """Obtains the used logs, metrics and labels from a service. label_is_supported and metric_is_supported are filter functions ...
[ "def", "extract_report_spec", "(", "service", ",", "label_is_supported", "=", "label_descriptor", ".", "KnownLabels", ".", "is_supported", ",", "metric_is_supported", "=", "metric_descriptor", ".", "KnownMetrics", ".", "is_supported", ")", ":", "resource_descs", "=", ...
39.276596
20.87234
def __get_item_sh_fields_empty(self, rol, undefined=False): """ Return a SH identity with all fields to empty_field """ # If empty_field is None, the fields do not appear in index patterns empty_field = '' if not undefined else '-- UNDEFINED --' return { rol + "_id": empty_fi...
[ "def", "__get_item_sh_fields_empty", "(", "self", ",", "rol", ",", "undefined", "=", "False", ")", ":", "# If empty_field is None, the fields do not appear in index patterns", "empty_field", "=", "''", "if", "not", "undefined", "else", "'-- UNDEFINED --'", "return", "{", ...
42.933333
10.6
def set_or_clear_breakpoint(self): """Set/Clear breakpoint""" editorstack = self.get_current_editorstack() if editorstack is not None: self.switch_to_plugin() editorstack.set_or_clear_breakpoint()
[ "def", "set_or_clear_breakpoint", "(", "self", ")", ":", "editorstack", "=", "self", ".", "get_current_editorstack", "(", ")", "if", "editorstack", "is", "not", "None", ":", "self", ".", "switch_to_plugin", "(", ")", "editorstack", ".", "set_or_clear_breakpoint", ...
40.666667
5.833333
def assign_params(sess, params, network): """Assign the given parameters to the TensorLayer network. Parameters ---------- sess : Session TensorFlow Session. params : list of array A list of parameters (array) in order. network : :class:`Layer` The network to be assigned...
[ "def", "assign_params", "(", "sess", ",", "params", ",", "network", ")", ":", "ops", "=", "[", "]", "for", "idx", ",", "param", "in", "enumerate", "(", "params", ")", ":", "ops", ".", "append", "(", "network", ".", "all_params", "[", "idx", "]", "....
26.15625
23.9375
def mapping_args(parser): """Add various variable mapping command line options to the parser""" parser.add_argument('--add-prefix', dest='add_prefix', help='Specify a prefix to use when ' 'generating secret key names') parser.add_argume...
[ "def", "mapping_args", "(", "parser", ")", ":", "parser", ".", "add_argument", "(", "'--add-prefix'", ",", "dest", "=", "'add_prefix'", ",", "help", "=", "'Specify a prefix to use when '", "'generating secret key names'", ")", "parser", ".", "add_argument", "(", "'-...
45.12
7.08
def ccmod_class_label_lookup(label): """Get a CCMOD class from a label string.""" clsmod = {'ism': admm_ccmod.ConvCnstrMOD_IterSM, 'cg': admm_ccmod.ConvCnstrMOD_CG, 'cns': admm_ccmod.ConvCnstrMOD_Consensus, 'fista': fista_ccmod.ConvCnstrMOD} if label in clsmod: ...
[ "def", "ccmod_class_label_lookup", "(", "label", ")", ":", "clsmod", "=", "{", "'ism'", ":", "admm_ccmod", ".", "ConvCnstrMOD_IterSM", ",", "'cg'", ":", "admm_ccmod", ".", "ConvCnstrMOD_CG", ",", "'cns'", ":", "admm_ccmod", ".", "ConvCnstrMOD_Consensus", ",", "'...
38.090909
16.272727
def play_beat( self, frequencys, play_time, sample_rate=44100, volume=0.01 ): ''' 引数で指定した条件でビートを鳴らす Args: frequencys: (左の周波数(Hz), 右の周波数(Hz))のtuple play_time: 再生時間(秒) sample_rate: サンプルレート ...
[ "def", "play_beat", "(", "self", ",", "frequencys", ",", "play_time", ",", "sample_rate", "=", "44100", ",", "volume", "=", "0.01", ")", ":", "# 依存するライブラリの基底オブジェクト\r", "audio", "=", "pyaudio", ".", "PyAudio", "(", ")", "# ストリーム\r", "stream", "=", "audio", ...
27.083333
20.75
def page_align_content_length(length): # type: (int) -> int """Compute page boundary alignment :param int length: content length :rtype: int :return: aligned byte boundary """ mod = length % _PAGEBLOB_BOUNDARY if mod != 0: return length + (_PAGEBLOB_BOUNDARY - mod) return len...
[ "def", "page_align_content_length", "(", "length", ")", ":", "# type: (int) -> int", "mod", "=", "length", "%", "_PAGEBLOB_BOUNDARY", "if", "mod", "!=", "0", ":", "return", "length", "+", "(", "_PAGEBLOB_BOUNDARY", "-", "mod", ")", "return", "length" ]
28.454545
10.181818
def virtual_machines_list(resource_group, **kwargs): ''' .. versionadded:: 2019.2.0 List all virtual machines within a resource group. :param resource_group: The resource group name to list virtual machines within. CLI Example: .. code-block:: bash salt-call azurearm_compute...
[ "def", "virtual_machines_list", "(", "resource_group", ",", "*", "*", "kwargs", ")", ":", "result", "=", "{", "}", "compconn", "=", "__utils__", "[", "'azurearm.get_client'", "]", "(", "'compute'", ",", "*", "*", "kwargs", ")", "try", ":", "vms", "=", "_...
27.612903
24.387097
def ibatch(iterable, size): """Yield a series of batches from iterable, each size elements long.""" source = iter(iterable) while True: batch = itertools.islice(source, size) yield itertools.chain([next(batch)], batch)
[ "def", "ibatch", "(", "iterable", ",", "size", ")", ":", "source", "=", "iter", "(", "iterable", ")", "while", "True", ":", "batch", "=", "itertools", ".", "islice", "(", "source", ",", "size", ")", "yield", "itertools", ".", "chain", "(", "[", "next...
40.166667
11.333333
def username(self): """Loking for username in user's input and config file""" if len(self._inp_username.value.strip()) == 0: # if username provided by user if not self.hostname is None: config = parse_sshconfig(self.hostname) if 'user' in config: # if username...
[ "def", "username", "(", "self", ")", ":", "if", "len", "(", "self", ".", "_inp_username", ".", "value", ".", "strip", "(", ")", ")", "==", "0", ":", "# if username provided by user", "if", "not", "self", ".", "hostname", "is", "None", ":", "config", "=...
44.181818
17.181818
def embed_font_to_svg(filepath, outfile, font_files): """ Write ttf and otf font content from `font_files` in the svg file in `filepath` and write the result in `outfile`. Parameters ---------- filepath: str The SVG file whose content must be modified. outfile: str The file...
[ "def", "embed_font_to_svg", "(", "filepath", ",", "outfile", ",", "font_files", ")", ":", "tree", "=", "_embed_font_to_svg", "(", "filepath", ",", "font_files", ")", "tree", ".", "write", "(", "outfile", ",", "encoding", "=", "'utf-8'", ",", "pretty_print", ...
30.055556
19.222222
def gff(args): """ %prog gff seq.gbk Convert Genbank file to GFF and FASTA file. The Genbank file can contain multiple records. """ p = OptionParser(gff.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) gbkfile, = args MultiGenBan...
[ "def", "gff", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "gff", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "1", ":", "sys", ".", "exit", "(", "not", ...
21.066667
16.8
def guest_reset(self, userid): """reset a virtual machine :param str userid: the id of the virtual machine to be reset :returns: None """ action = "reset guest '%s'" % userid with zvmutils.log_and_reraise_sdkbase_error(action): self._vmops.guest_reset(userid)
[ "def", "guest_reset", "(", "self", ",", "userid", ")", ":", "action", "=", "\"reset guest '%s'\"", "%", "userid", "with", "zvmutils", ".", "log_and_reraise_sdkbase_error", "(", "action", ")", ":", "self", ".", "_vmops", ".", "guest_reset", "(", "userid", ")" ]
39
10.375
def resource_info(self): """Get the extended information of this resource. :param resource_name: Unique symbolic name of a resource. :rtype: :class:`pyvisa.highlevel.ResourceInfo` """ return self.visalib.parse_resource_extended(self._resource_manager.session, self.resource_name...
[ "def", "resource_info", "(", "self", ")", ":", "return", "self", ".", "visalib", ".", "parse_resource_extended", "(", "self", ".", "_resource_manager", ".", "session", ",", "self", ".", "resource_name", ")" ]
39.25
24.75
def _parse_json(self, json, exactly_one=True): '''Returns location, (latitude, longitude) from json feed.''' features = json['features'] if features == []: return None def parse_feature(feature): location = feature['place_name'] place = feature['text'...
[ "def", "_parse_json", "(", "self", ",", "json", ",", "exactly_one", "=", "True", ")", ":", "features", "=", "json", "[", "'features'", "]", "if", "features", "==", "[", "]", ":", "return", "None", "def", "parse_feature", "(", "feature", ")", ":", "loca...
40.5625
16.8125
def delete(self, name): """ Deletes a given index. **Note**: This method is only supported in Splunk 5.0 and later. :param name: The name of the index to delete. :type name: ``string`` """ if self.service.splunk_version >= (5,): Collection.delete(self, name)...
[ "def", "delete", "(", "self", ",", "name", ")", ":", "if", "self", ".", "service", ".", "splunk_version", ">=", "(", "5", ",", ")", ":", "Collection", ".", "delete", "(", "self", ",", "name", ")", "else", ":", "raise", "IllegalOperationException", "(",...
37.846154
21.153846
def blum_blum_shub(seed, amount, prime0, prime1): """Creates pseudo-number generator :param seed: seeder :param amount: amount of number to generate :param prime0: one prime number :param prime1: the second prime number :return: pseudo-number generator """ if amount == 0: return...
[ "def", "blum_blum_shub", "(", "seed", ",", "amount", ",", "prime0", ",", "prime1", ")", ":", "if", "amount", "==", "0", ":", "return", "[", "]", "assert", "(", "prime0", "%", "4", "==", "3", "and", "prime1", "%", "4", "==", "3", ")", "# primes must...
25.375
17.166667
def get_event_access_codes(self, id, **data): """ GET /events/:id/access_codes/ Returns a :ref:`paginated <pagination>` response with a key of ``access_codes``, containing a list of :format:`access_codes <access_code>` available on this event. """ return self.get("/event...
[ "def", "get_event_access_codes", "(", "self", ",", "id", ",", "*", "*", "data", ")", ":", "return", "self", ".", "get", "(", "\"/events/{0}/access_codes/\"", ".", "format", "(", "id", ")", ",", "data", "=", "data", ")" ]
51
29.285714
def get_password(self, service, username): """Read the password from the file. """ service = escape_for_ini(service) username = escape_for_ini(username) # load the passwords from the file config = configparser.RawConfigParser() if os.path.exists(self.file_path): ...
[ "def", "get_password", "(", "self", ",", "service", ",", "username", ")", ":", "service", "=", "escape_for_ini", "(", "service", ")", "username", "=", "escape_for_ini", "(", "username", ")", "# load the passwords from the file", "config", "=", "configparser", ".",...
32.833333
14.5
def _set_frr_cspf_group_computation_mode(self, v, load=False): """ Setter method for frr_cspf_group_computation_mode, mapped from YANG variable /mpls_state/rsvp/sessions/psbs/frr_cspf_group_computation_mode (frr-cspf-group-computation-mode) If this variable is read-only (config: false) in the source YAN...
[ "def", "_set_frr_cspf_group_computation_mode", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(",...
107.875
54.375
def interpolations_to_summary(sample_ind, interpolations, first_frame, last_frame, hparams, decode_hp): """Converts interpolated frames into tf summaries. The summaries consists of: 1. Image summary corresponding to the first frame. 2. Image summary corresponding to the last f...
[ "def", "interpolations_to_summary", "(", "sample_ind", ",", "interpolations", ",", "first_frame", ",", "last_frame", ",", "hparams", ",", "decode_hp", ")", ":", "parent_tag", "=", "\"sample_%d\"", "%", "sample_ind", "frame_shape", "=", "hparams", ".", "problem", "...
40.410256
14.641026
def _load_resources(self, abs_path=False): """Copy all of the Datafile entries into the package""" from metapack.doc import MetapackDoc assert type(self.doc) == MetapackDoc for r in self.datafiles: # Special handling for SQL is probably a really bad idea. It should be hand...
[ "def", "_load_resources", "(", "self", ",", "abs_path", "=", "False", ")", ":", "from", "metapack", ".", "doc", "import", "MetapackDoc", "assert", "type", "(", "self", ".", "doc", ")", "==", "MetapackDoc", "for", "r", "in", "self", ".", "datafiles", ":",...
36.714286
22.017857
def _roc_multi(y_true, y_score, ax=None): """ Plot ROC curve for multi classification. Parameters ---------- y_true : array-like, shape = [n_samples, n_classes] Correct target values (ground truth). y_score : array-like, shape = [n_samples, n_classes] Target scores (estimator pr...
[ "def", "_roc_multi", "(", "y_true", ",", "y_score", ",", "ax", "=", "None", ")", ":", "# Compute micro-average ROC curve and ROC area", "fpr", ",", "tpr", ",", "_", "=", "roc_curve", "(", "y_true", ".", "ravel", "(", ")", ",", "y_score", ".", "ravel", "(",...
27.733333
19.8
def get_admin_ids(self): """Method to get the administrator id list.""" admins = self.json_response.get("admin_list", None) admin_ids = [admin_id for admin_id in admins["userid"]] return admin_ids
[ "def", "get_admin_ids", "(", "self", ")", ":", "admins", "=", "self", ".", "json_response", ".", "get", "(", "\"admin_list\"", ",", "None", ")", "admin_ids", "=", "[", "admin_id", "for", "admin_id", "in", "admins", "[", "\"userid\"", "]", "]", "return", ...
45.6
15
def convert_parameter_shape(pb): """Convert the shape of some parameters so they fit NNabla's requirements. We do this as a post conversion because in the future we may be able to delete the whole conversion if NNabla's code gets changed""" if len(pb.network) != 1: raise ValueError( ...
[ "def", "convert_parameter_shape", "(", "pb", ")", ":", "if", "len", "(", "pb", ".", "network", ")", "!=", "1", ":", "raise", "ValueError", "(", "\"NNP with more then a single network is currently not supported\"", ")", "net", "=", "pb", ".", "network", "[", "0",...
54.324324
24.324324
def restorenx(self, name, value, pttl=0): """ Restore serialized dump of a key back into redis :param name: str the name of the redis key :param value: redis RDB-like serialization :param pttl: milliseconds till key expires :return: Future() """ retur...
[ "def", "restorenx", "(", "self", ",", "name", ",", "value", ",", "pttl", "=", "0", ")", ":", "return", "self", ".", "eval", "(", "lua_restorenx", ",", "1", ",", "name", ",", "pttl", ",", "value", ")" ]
35.9
12.7
def tomask(self, pores=None, throats=None): r""" Convert a list of pore or throat indices into a boolean mask of the correct length Parameters ---------- pores or throats : array_like List of pore or throat indices. Only one of these can be specified ...
[ "def", "tomask", "(", "self", ",", "pores", "=", "None", ",", "throats", "=", "None", ")", ":", "if", "(", "pores", "is", "not", "None", ")", "and", "(", "throats", "is", "None", ")", ":", "mask", "=", "self", ".", "_tomask", "(", "element", "=",...
33.190476
23.833333
def find_executable_files(): """ Find max 5 executables that are responsible for this repo. """ files = glob.glob("*") + glob.glob("*/*") + glob.glob('*/*/*') files = filter(lambda f: os.path.isfile(f), files) executable = stat.S_IEXEC | stat.S_IXGRP | stat.S_IXOTH final = [] for filenam...
[ "def", "find_executable_files", "(", ")", ":", "files", "=", "glob", ".", "glob", "(", "\"*\"", ")", "+", "glob", ".", "glob", "(", "\"*/*\"", ")", "+", "glob", ".", "glob", "(", "'*/*/*'", ")", "files", "=", "filter", "(", "lambda", "f", ":", "os"...
33.411765
12.235294
def newton(f, x, verbose=False, tol=1e-6, maxit=5, jactype='serial'): """Solve nonlinear system using safeguarded Newton iterations Parameters ---------- Return ------ """ if verbose: print = lambda txt: old_print(txt) else: print = lambda txt: None it = 0 e...
[ "def", "newton", "(", "f", ",", "x", ",", "verbose", "=", "False", ",", "tol", "=", "1e-6", ",", "maxit", "=", "5", ",", "jactype", "=", "'serial'", ")", ":", "if", "verbose", ":", "print", "=", "lambda", "txt", ":", "old_print", "(", "txt", ")",...
19.774648
24.056338
def call_plugins(self, step): ''' For each plugins, check if a "step" method exist on it, and call it Args: step (str): The method to search and call on each plugin ''' for plugin in self.plugins: try: getattr(plugin, step)() e...
[ "def", "call_plugins", "(", "self", ",", "step", ")", ":", "for", "plugin", "in", "self", ".", "plugins", ":", "try", ":", "getattr", "(", "plugin", ",", "step", ")", "(", ")", "except", "AttributeError", ":", "self", ".", "logger", ".", "debug", "("...
38.285714
24.428571
def getElementByID(self, id): """ returns an element with the specific id and the position of that element within the svg elements array """ pos=0 for element in self._subElements: if element.get_id()==id: return (element,pos) pos+=1
[ "def", "getElementByID", "(", "self", ",", "id", ")", ":", "pos", "=", "0", "for", "element", "in", "self", ".", "_subElements", ":", "if", "element", ".", "get_id", "(", ")", "==", "id", ":", "return", "(", "element", ",", "pos", ")", "pos", "+=",...
37.25
8.625
def finalize_filename(filename, file_format=None): """ Replaces invalid characters in filename string, adds image extension and reduces filename length :param filename: Incomplete filename string :type filename: str :param file_format: Format which will be used for filename extension ...
[ "def", "finalize_filename", "(", "filename", ",", "file_format", "=", "None", ")", ":", "for", "char", "in", "[", "' '", ",", "'/'", ",", "'\\\\'", ",", "'|'", ",", "';'", ",", "':'", ",", "'\\n'", ",", "'\\t'", "]", ":", "filename", "=", "filename",...
39.666667
20.958333
def get_dir_indices(msg, dirs): '''Return path(s) indices of directory list from user input Args ---- msg: str String with message to display before pass selection input dir_list: array-like list of paths to be displayed and selected from Return ------ input_dir_indices...
[ "def", "get_dir_indices", "(", "msg", ",", "dirs", ")", ":", "import", "os", "# Get user input for paths to process", "usage", "=", "(", "'\\nEnter numbers preceeding paths seperated by commas (e.g. '", "'`0,2,3`).\\nTo select all paths type `all`.\\nSingle directories '", "'can also...
33.119048
24.97619
def _auth(self, client_id, key, method, callback): ''' _auth - internal method to ensure the client_id and client_secret passed with the nonce match ''' available = auth_methods.keys() if method not in available: raise Proauth2Error('invalid_request', ...
[ "def", "_auth", "(", "self", ",", "client_id", ",", "key", ",", "method", ",", "callback", ")", ":", "available", "=", "auth_methods", ".", "keys", "(", ")", "if", "method", "not", "in", "available", ":", "raise", "Proauth2Error", "(", "'invalid_request'",...
47.176471
19.294118
def find_nearest_neighbor(query, vectors, ban_set, cossims=None): """ query is a 1d numpy array corresponding to the vector to which you want to find the closest vector vectors is a 2d numpy array corresponding to the vectors you want to consider ban_set is a set of indicies within vectors you want ...
[ "def", "find_nearest_neighbor", "(", "query", ",", "vectors", ",", "ban_set", ",", "cossims", "=", "None", ")", ":", "if", "cossims", "is", "None", ":", "cossims", "=", "np", ".", "matmul", "(", "vectors", ",", "query", ",", "out", "=", "cossims", ")",...
39.809524
22.761905
def get_down_used_bandwith(self): """ Return a percentage of the current used xdsl download bandwith Instant measure, can be very different from one call to another :return: 0 no bandwith is used, 100 all your bandwith is used :rtype: int """ ip_stats_up = self.ge...
[ "def", "get_down_used_bandwith", "(", "self", ")", ":", "ip_stats_up", "=", "self", ".", "get_ip_stats", "(", ")", "[", "'rx'", "]", "percent", "=", "ip_stats_up", "[", "'bandwidth'", "]", "*", "100", "/", "ip_stats_up", "[", "'maxBandwidth'", "]", "return",...
43.2
17.2
def p_null_literal(self, p): """null_literal : NULL""" p[0] = self.asttypes.Null(p[1]) p[0].setpos(p)
[ "def", "p_null_literal", "(", "self", ",", "p", ")", ":", "p", "[", "0", "]", "=", "self", ".", "asttypes", ".", "Null", "(", "p", "[", "1", "]", ")", "p", "[", "0", "]", ".", "setpos", "(", "p", ")" ]
30.5
7.75
def metric_coherence_gensim(measure, topic_word_distrib=None, gensim_model=None, vocab=None, dtm=None, gensim_corpus=None, texts=None, top_n=20, return_coh_model=False, return_mean=False, **kwargs): """ Calculate model coherence using Gensim's `CoherenceMo...
[ "def", "metric_coherence_gensim", "(", "measure", ",", "topic_word_distrib", "=", "None", ",", "gensim_model", "=", "None", ",", "vocab", "=", "None", ",", "dtm", "=", "None", ",", "gensim_corpus", "=", "None", ",", "texts", "=", "None", ",", "top_n", "=",...
45.151515
32.141414
def insert_knot(obj, param, num, **kwargs): """ Inserts knots n-times to a spline geometry. The following code snippet illustrates the usage of this function: .. code-block:: python # Insert knot u=0.5 to a curve 2 times operations.insert_knot(curve, [0.5], [2]) # Insert knot v=0...
[ "def", "insert_knot", "(", "obj", ",", "param", ",", "num", ",", "*", "*", "kwargs", ")", ":", "# Get keyword arguments", "check_num", "=", "kwargs", ".", "get", "(", "'check_num'", ",", "True", ")", "# can be set to False when the caller checks number of insertions...
45.633333
27.625926
def _evaluate_trigger_rule( self, ti, successes, skipped, failed, upstream_failed, done, flag_upstream_failed, session): """ Yields a dependency status that indicate whether the given task instanc...
[ "def", "_evaluate_trigger_rule", "(", "self", ",", "ti", ",", "successes", ",", "skipped", ",", "failed", ",", "upstream_failed", ",", "done", ",", "flag_upstream_failed", ",", "session", ")", ":", "TR", "=", "airflow", ".", "utils", ".", "trigger_rule", "."...
47.746269
18.134328
def attach(self, gui): """Attach the view to the GUI.""" super(CorrelogramView, self).attach(gui) self.actions.add(self.toggle_normalization, shortcut='n') self.actions.separator() self.actions.add(self.set_bin, alias='cb') self.actions.add(self.set_window, alias='cw')
[ "def", "attach", "(", "self", ",", "gui", ")", ":", "super", "(", "CorrelogramView", ",", "self", ")", ".", "attach", "(", "gui", ")", "self", ".", "actions", ".", "add", "(", "self", ".", "toggle_normalization", ",", "shortcut", "=", "'n'", ")", "se...
44.428571
11.714286
def pages_dynamic_tree_menu(context, page, url='/'): """ Render a "dynamic" tree menu, with all nodes expanded which are either ancestors or the current page itself. Override ``pages/dynamic_tree_menu.html`` if you want to change the design. :param page: the current page :param url: not us...
[ "def", "pages_dynamic_tree_menu", "(", "context", ",", "page", ",", "url", "=", "'/'", ")", ":", "lang", "=", "context", ".", "get", "(", "'lang'", ",", "pages_settings", ".", "PAGE_DEFAULT_LANGUAGE", ")", "page", "=", "get_page_from_string_or_id", "(", "page"...
38.038462
17.961538
def register_option(key, defval, doc='', validator=None, cb=None): """Register an option in the package-wide pandas config object Parameters ---------- key - a fully-qualified key, e.g. "x.y.option - z". defval - the default value of the option doc - a string description of the o...
[ "def", "register_option", "(", "key", ",", "defval", ",", "doc", "=", "''", ",", "validator", "=", "None", ",", "cb", "=", "None", ")", ":", "import", "tokenize", "import", "keyword", "key", "=", "key", ".", "lower", "(", ")", "if", "key", "in", "_...
34.292308
22.461538
def LT(self, a, b): """Less-than comparison""" return Operators.ITEBV(256, Operators.ULT(a, b), 1, 0)
[ "def", "LT", "(", "self", ",", "a", ",", "b", ")", ":", "return", "Operators", ".", "ITEBV", "(", "256", ",", "Operators", ".", "ULT", "(", "a", ",", "b", ")", ",", "1", ",", "0", ")" ]
38.333333
14.333333
def severity(self): """ Severity level of the event. One of ``INFO``, ``WATCH``, ``WARNING``, ``DISTRESS``, ``CRITICAL`` or ``SEVERE``. """ if self._proto.HasField('severity'): return yamcs_pb2.Event.EventSeverity.Name(self._proto.severity) return None
[ "def", "severity", "(", "self", ")", ":", "if", "self", ".", "_proto", ".", "HasField", "(", "'severity'", ")", ":", "return", "yamcs_pb2", ".", "Event", ".", "EventSeverity", ".", "Name", "(", "self", ".", "_proto", ".", "severity", ")", "return", "No...
38.125
15.875
def my_pick_non_system_keyspace(self): """ Find a keyspace in the cluster which is not 'system', for the purpose of getting a valid ring view. Can't use 'system' or null. """ d = self.my_describe_keyspaces() def pick_non_system(klist): for k in klist: ...
[ "def", "my_pick_non_system_keyspace", "(", "self", ")", ":", "d", "=", "self", ".", "my_describe_keyspaces", "(", ")", "def", "pick_non_system", "(", "klist", ")", ":", "for", "k", "in", "klist", ":", "if", "k", ".", "name", "not", "in", "SYSTEM_KEYSPACES"...
38.388889
16.166667
def addPlugin(self, plugin, call): """Add plugin to my list of plugins to call, if it has the attribute I'm bound to. """ meth = getattr(plugin, call, None) if meth is not None: if call == 'loadTestsFromModule' and \ len(inspect.getargspec(meth)[0]...
[ "def", "addPlugin", "(", "self", ",", "plugin", ",", "call", ")", ":", "meth", "=", "getattr", "(", "plugin", ",", "call", ",", "None", ")", "if", "meth", "is", "not", "None", ":", "if", "call", "==", "'loadTestsFromModule'", "and", "len", "(", "insp...
42.727273
10.272727
def get_elasticsearch_info(): """Check Elasticsearch connection.""" from elasticsearch import ( Elasticsearch, ConnectionError as ESConnectionError ) if hasattr(settings, 'ELASTICSEARCH_URL'): url = settings.ELASTICSEARCH_URL else: return {"status": NO_CONFIG} sta...
[ "def", "get_elasticsearch_info", "(", ")", ":", "from", "elasticsearch", "import", "(", "Elasticsearch", ",", "ConnectionError", "as", "ESConnectionError", ")", "if", "hasattr", "(", "settings", ",", "'ELASTICSEARCH_URL'", ")", ":", "url", "=", "settings", ".", ...
32.380952
16.714286
def download_bill(self, bill_date, bill_type='ALL', device_info=None): """ 下载对账单 :param bill_date: 下载对账单的日期 :param bill_type: 账单类型,ALL,返回当日所有订单信息,默认值 SUCCESS,返回当日成功支付的订单, REFUND,返回当日退款订单, REVOKED,已撤销的订单 ...
[ "def", "download_bill", "(", "self", ",", "bill_date", ",", "bill_type", "=", "'ALL'", ",", "device_info", "=", "None", ")", ":", "if", "isinstance", "(", "bill_date", ",", "(", "datetime", ",", "date", ")", ")", ":", "bill_date", "=", "bill_date", ".", ...
32.863636
13.954545
def tyn_calus_scaling(target, DABo, To, mu_o, viscosity='pore.viscosity', temperature='pore.temperature'): r""" Uses Tyn_Calus model to adjust a diffusion coeffciient for liquids from reference conditions to conditions of interest Parameters ---------- target : OpenPNM Obj...
[ "def", "tyn_calus_scaling", "(", "target", ",", "DABo", ",", "To", ",", "mu_o", ",", "viscosity", "=", "'pore.viscosity'", ",", "temperature", "=", "'pore.temperature'", ")", ":", "Ti", "=", "target", "[", "temperature", "]", "mu_i", "=", "target", "[", "v...
34.482759
22.37931
def add_request_log_fields( self, log_fields: LogFields, call_details: Union[grpc.HandlerCallDetails, grpc.ClientCallDetails] ): """Add log fields related to a request to the provided log fields :param log_fields: log fields instance to which ...
[ "def", "add_request_log_fields", "(", "self", ",", "log_fields", ":", "LogFields", ",", "call_details", ":", "Union", "[", "grpc", ".", "HandlerCallDetails", ",", "grpc", ".", "ClientCallDetails", "]", ")", ":", "service", ",", "method", "=", "call_details", "...
36.111111
16.111111
def GetFileObject(self, data_stream_name=''): """Retrieves the file-like object. Args: data_stream_name (Optional[str]): data stream name, where an empty string represents the default data stream. Returns: NTFSFileIO: file-like object or None. """ if (not data_stream_name and...
[ "def", "GetFileObject", "(", "self", ",", "data_stream_name", "=", "''", ")", ":", "if", "(", "not", "data_stream_name", "and", "not", "self", ".", "_fsntfs_file_entry", ".", "has_default_data_stream", "(", ")", ")", ":", "return", "None", "# Make sure to make t...
33.227273
19.545455
def graph_attention(q, k, v, bias, dropout_rate=0.0, image_shapes=None, name=None, make_image_summary=True, save_weights_to=None, dropout_br...
[ "def", "graph_attention", "(", "q", ",", "k", ",", "v", ",", "bias", ",", "dropout_rate", "=", "0.0", ",", "image_shapes", "=", "None", ",", "name", "=", "None", ",", "make_image_summary", "=", "True", ",", "save_weights_to", "=", "None", ",", "dropout_b...
43.65625
16.3125
def rosette_summary(fname): """ Make a BTL (bottle) file from a ROS (bottle log) file. More control for the averaging process and at which step we want to perform this averaging eliminating the need to read the data into SBE Software again after pre-processing. NOTE: Do not run LoopEdit on the ...
[ "def", "rosette_summary", "(", "fname", ")", ":", "ros", "=", "from_cnv", "(", "fname", ")", "ros", "[", "\"pressure\"", "]", "=", "ros", ".", "index", ".", "values", ".", "astype", "(", "float", ")", "ros", "[", "\"nbf\"", "]", "=", "ros", "[", "\...
35.5
18.192308
def cut_by_plane(self, plane, inverted=False): ''' Like cut_across_axis, but works with an arbitrary plane. Keeps vertices that lie in front of the plane (i.e. in the direction of the plane normal). inverted: When `True`, invert the logic, to keep the vertices that lie...
[ "def", "cut_by_plane", "(", "self", ",", "plane", ",", "inverted", "=", "False", ")", ":", "vertices_to_keep", "=", "plane", ".", "points_in_front", "(", "self", ".", "v", ",", "inverted", "=", "inverted", ",", "ret_indices", "=", "True", ")", "self", "....
33.823529
26.529412
def compute_hardwired_weights(rho,N_E,N_I,periodic, onlyI=False): ''' %This function returns the synaptic weight matrices %(G_I_EL,G_I_ER,G_EL_I,G_ER_I,G_I_I) and the suppressive envelope %(A_env), based on: % % - the scale of the synaptic profiles (rho) % - the size of the exctitatory and inhibitory pops...
[ "def", "compute_hardwired_weights", "(", "rho", ",", "N_E", ",", "N_I", ",", "periodic", ",", "onlyI", "=", "False", ")", ":", "weight_sizes", "=", "np", ".", "asarray", "(", "[", "[", "N_I", ",", "N_E", "]", ",", "[", "N_I", ",", "N_E", "]", ",", ...
43.149254
32.164179
def optimize(lattice, positions, numbers, displacements, forces, alm_options=None, p2s_map=None, p2p_map=None, log_level=0): """Calculate force constants lattice : array_like Basis vectors. a, b, c a...
[ "def", "optimize", "(", "lattice", ",", "positions", ",", "numbers", ",", "displacements", ",", "forces", ",", "alm_options", "=", "None", ",", "p2s_map", "=", "None", ",", "p2p_map", "=", "None", ",", "log_level", "=", "0", ")", ":", "from", "alm", "i...
34.461538
13.430769
def _string_to_dictsql(self, part): """ Do magic matching of single words or quoted string """ self._logger.debug("parsing string: " + unicode(part[0]) + " of type: " + part.getName()) if part.getName() == 'tag': self._logger.debug("Query part '" + part[0] + "' interpreted a...
[ "def", "_string_to_dictsql", "(", "self", ",", "part", ")", ":", "self", ".", "_logger", ".", "debug", "(", "\"parsing string: \"", "+", "unicode", "(", "part", "[", "0", "]", ")", "+", "\" of type: \"", "+", "part", ".", "getName", "(", ")", ")", "if"...
40.481081
15.827027
def format_frameinfo(fi): """ Takes a frameinfo object (from the inspect module) returns a properly formated string """ s1 = "{0}:{1}".format(fi.filename, fi.lineno) s2 = "function:{0}, code_context:".format(fi.function) if fi.code_context: s3 = fi.code_context[0] else: ...
[ "def", "format_frameinfo", "(", "fi", ")", ":", "s1", "=", "\"{0}:{1}\"", ".", "format", "(", "fi", ".", "filename", ",", "fi", ".", "lineno", ")", "s2", "=", "\"function:{0}, code_context:\"", ".", "format", "(", "fi", ".", "function", ")", "if", "fi...
27.142857
14.714286
def refresh_role(self, role, file_hierarchy): """Checks and refreshes (if needed) all assistants with given role. Args: role: role of assistants to refresh file_hierarchy: hierarchy as returned by devassistant.yaml_assistant_loader.\ YamlAssistantLoad...
[ "def", "refresh_role", "(", "self", ",", "role", ",", "file_hierarchy", ")", ":", "if", "role", "not", "in", "self", ".", "cache", ":", "self", ".", "cache", "[", "role", "]", "=", "{", "}", "was_change", "=", "self", ".", "_refresh_hierarchy_recursive",...
43.4
18.466667
def dont_cache(): """ Set Cache-Control headers for no caching Will generate proxy-revalidate, no-cache, no-store, must-revalidate, max-age=0. """ def decorate_func(func): @wraps(func) def decorate_func_call(*a, **kw): callback = SetCacheControlHeadersForNoCachingCal...
[ "def", "dont_cache", "(", ")", ":", "def", "decorate_func", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "decorate_func_call", "(", "*", "a", ",", "*", "*", "kw", ")", ":", "callback", "=", "SetCacheControlHeadersForNoCachingCallback", "("...
33.235294
15.588235
def tags_in_string(msg): """ Return the set of tags in a message string. Tags includes HTML tags, data placeholders, etc. Skips tags that might change due to translations: HTML entities, <abbr>, and so on. """ def is_linguistic_tag(tag): """Is this tag one that can change with the...
[ "def", "tags_in_string", "(", "msg", ")", ":", "def", "is_linguistic_tag", "(", "tag", ")", ":", "\"\"\"Is this tag one that can change with the language?\"\"\"", "if", "tag", ".", "startswith", "(", "\"&\"", ")", ":", "return", "True", "if", "any", "(", "x", "i...
29.4
18.9
def fmt_dict_vals(dict_vals, shorten=True): """Returns list of key=val pairs formatted for inclusion in an informative text string. """ items = dict_vals.items() if not items: return [fmt_val(None, shorten=shorten)] return ["%s=%s" % (k, fmt_val(v, shorten=shorten)) for k,v in items]
[ "def", "fmt_dict_vals", "(", "dict_vals", ",", "shorten", "=", "True", ")", ":", "items", "=", "dict_vals", ".", "items", "(", ")", "if", "not", "items", ":", "return", "[", "fmt_val", "(", "None", ",", "shorten", "=", "shorten", ")", "]", "return", ...
38.625
10.5
def pretty(timings, label): '''Print timing stats''' results = [(sum(values), len(values), key) for key, values in timings.items()] print(label) print('=' * 65) print('%20s => %13s | %8s | %13s' % ( 'Command', 'Average', '# Calls', 'Total time')) p...
[ "def", "pretty", "(", "timings", ",", "label", ")", ":", "results", "=", "[", "(", "sum", "(", "values", ")", ",", "len", "(", "values", ")", ",", "key", ")", "for", "key", ",", "values", "in", "timings", ".", "items", "(", ")", "]", "print", "...
42.166667
14.666667
def get_constant(self, name, value=None): """Retrieves a :py:class:`.Constant` with name ``self.prefix+name``. If not found, :py:func:`get` will first try to retrieve it from "shared" dict. If still not found, :py:func:`get` will create a new :py:class:`.Constant` with key-word arguments...
[ "def", "get_constant", "(", "self", ",", "name", ",", "value", "=", "None", ")", ":", "name", "=", "self", ".", "prefix", "+", "name", "param", "=", "self", ".", "_get_impl", "(", "name", ")", "if", "param", "is", "None", ":", "if", "value", "is", ...
41.333333
17.820513
def fix_indentation(code, base_indentation=None, correct_indentation="", modifiers=(True, True)): """Replaces base_indentation at beginning of lines with correct_indentation. If base_indentation is None, tries to find it using get_base_indentation. modifiers are passed to re_line_and_in...
[ "def", "fix_indentation", "(", "code", ",", "base_indentation", "=", "None", ",", "correct_indentation", "=", "\"\"", ",", "modifiers", "=", "(", "True", ",", "True", ")", ")", ":", "if", "base_indentation", "is", "None", ":", "base_indentation", "=", "get_b...
50.818182
18.909091
def addColumn(self, header, values=[]): """ Add a new column with the corresponding header and values to the dataframe. Args: header: The name of the new column. values: A list of size :func:`~amplpy.DataFrame.getNumRows` with all the values of the n...
[ "def", "addColumn", "(", "self", ",", "header", ",", "values", "=", "[", "]", ")", ":", "if", "len", "(", "values", ")", "==", "0", ":", "self", ".", "_impl", ".", "addColumn", "(", "header", ")", "else", ":", "assert", "len", "(", "values", ")",...
37.565217
16.782609
def get_reconciler(config, metrics, rrset_channel, changes_channel, **kw): """Get a GDNSReconciler client. A factory function that validates configuration, creates an auth and :class:`GDNSClient` instance, and returns a GDNSReconciler provider. Args: config (dict): Google Cloud Pub/Sub-rel...
[ "def", "get_reconciler", "(", "config", ",", "metrics", ",", "rrset_channel", ",", "changes_channel", ",", "*", "*", "kw", ")", ":", "builder", "=", "reconciler", ".", "GDNSReconcilerBuilder", "(", "config", ",", "metrics", ",", "rrset_channel", ",", "changes_...
41.272727
19.909091
def permitted_actions(self, user, obj=None): """Determine list of permitted actions for an object or object pattern. :param user: The user to test. :type user: ``User`` :param obj: A function mapping from action names to object paths to test. :type ob...
[ "def", "permitted_actions", "(", "self", ",", "user", ",", "obj", "=", "None", ")", ":", "try", ":", "if", "not", "self", ".", "_obj_ok", "(", "obj", ")", ":", "raise", "InvalidPermissionObjectException", "return", "user", ".", "permset_tree", ".", "permit...
34.611111
16
def _deduce_security(kwargs) -> nmcli.SECURITY_TYPES: """ Make sure that the security_type is known, or throw. """ # Security should be one of our valid strings sec_translation = { 'wpa-psk': nmcli.SECURITY_TYPES.WPA_PSK, 'none': nmcli.SECURITY_TYPES.NONE, 'wpa-eap': nmcli.SECURITY_T...
[ "def", "_deduce_security", "(", "kwargs", ")", "->", "nmcli", ".", "SECURITY_TYPES", ":", "# Security should be one of our valid strings", "sec_translation", "=", "{", "'wpa-psk'", ":", "nmcli", ".", "SECURITY_TYPES", ".", "WPA_PSK", ",", "'none'", ":", "nmcli", "."...
42.304348
14.130435
def set_option(self, key, subkey, value): """Sets the value of an option. :param str key: First identifier of the option. :param str subkey: Second identifier of the option. :param value: New value for the option (type varies). :raise: :NotRegisteredError: If ``key`...
[ "def", "set_option", "(", "self", ",", "key", ",", "subkey", ",", "value", ")", ":", "key", ",", "subkey", "=", "_lower_keys", "(", "key", ",", "subkey", ")", "_entry_must_exist", "(", "self", ".", "gc", ",", "key", ",", "subkey", ")", "df", "=", "...
43.933333
18.4
def applyCommand(self): """ Applies the current line of code as an interactive python command. """ # generate the command information cursor = self.textCursor() cursor.movePosition(cursor.EndOfLine) line = projex.text.nativestring(curs...
[ "def", "applyCommand", "(", "self", ")", ":", "# generate the command information\r", "cursor", "=", "self", ".", "textCursor", "(", ")", "cursor", ".", "movePosition", "(", "cursor", ".", "EndOfLine", ")", "line", "=", "projex", ".", "text", ".", "nativestrin...
38.3125
15.9875
def _detect_issue351(): """Detect if github.com/python/typing/issues/351 applies to the installed typing-version. """ class Tuple(typing.Generic[typing.T]): pass res = Tuple[str] == typing.Tuple[str] del Tuple return res
[ "def", "_detect_issue351", "(", ")", ":", "class", "Tuple", "(", "typing", ".", "Generic", "[", "typing", ".", "T", "]", ")", ":", "pass", "res", "=", "Tuple", "[", "str", "]", "==", "typing", ".", "Tuple", "[", "str", "]", "del", "Tuple", "return"...
24.8
14.5
def open_output(self, fname): """Open the output file FNAME. Returns tuple (FD, NEED_CLOSE), where FD is a file (or file-like) object, and NEED_CLOSE is a boolean flag that tells whether FD.close() should be called after finishing writing to the file. FNAME can be one of the thr...
[ "def", "open_output", "(", "self", ",", "fname", ")", ":", "if", "not", "fname", ":", "return", "(", "sys", ".", "stdout", ",", "False", ")", "elif", "isinstance", "(", "fname", ",", "str", ")", ":", "return", "(", "file", "(", "fname", ",", "\"wb\...
44.6
19
def get_available_fields(self, obj): """ Get a list of all available fields for an object. :param obj: The name of the Salesforce object that we are getting a description of. :type obj: str :return: the names of the fields. :rtype: list of str """ self.ge...
[ "def", "get_available_fields", "(", "self", ",", "obj", ")", ":", "self", ".", "get_conn", "(", ")", "obj_description", "=", "self", ".", "describe_object", "(", "obj", ")", "return", "[", "field", "[", "'name'", "]", "for", "field", "in", "obj_description...
31.357143
20.071429
def AddMethod(obj, function, name=None): """ Adds either a bound method to an instance or the function itself (or an unbound method in Python 2) to a class. If name is ommited the name of the specified function is used by default. Example:: a = A() def f(self, x, y): self.z...
[ "def", "AddMethod", "(", "obj", ",", "function", ",", "name", "=", "None", ")", ":", "if", "name", "is", "None", ":", "name", "=", "function", ".", "__name__", "else", ":", "function", "=", "RenameFunction", "(", "function", ",", "name", ")", "# Note t...
30.485714
19.971429
def category(self, value): """ Setter for **self.__category** attribute. :param value: Attribute value. :type value: unicode """ if value is not None: assert type(value) is unicode, "'{0}' attribute: '{1}' type is not 'unicode'!".format( "cat...
[ "def", "category", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", ":", "assert", "type", "(", "value", ")", "is", "unicode", ",", "\"'{0}' attribute: '{1}' type is not 'unicode'!\"", ".", "format", "(", "\"category\"", ",", "value", ...
29.583333
16.75
def _parse_topic_path(topic_path): """Verify that a topic path is in the correct format. .. _resource manager docs: https://cloud.google.com/resource-manager/\ reference/rest/v1beta1/projects#\ Project.FIELDS.project_id .. _topic spec: https://c...
[ "def", "_parse_topic_path", "(", "topic_path", ")", ":", "match", "=", "_TOPIC_REF_RE", ".", "match", "(", "topic_path", ")", "if", "match", "is", "None", ":", "raise", "ValueError", "(", "_BAD_TOPIC", ".", "format", "(", "topic_path", ")", ")", "return", ...
37.828571
24.914286
def fixup_namespace_packages(path_item, parent=None): """Ensure that previously-declared namespace packages include path_item""" _imp.acquire_lock() try: for package in _namespace_packages.get(parent, ()): subpath = _handle_ns(package, path_item) if subpath: f...
[ "def", "fixup_namespace_packages", "(", "path_item", ",", "parent", "=", "None", ")", ":", "_imp", ".", "acquire_lock", "(", ")", "try", ":", "for", "package", "in", "_namespace_packages", ".", "get", "(", "parent", ",", "(", ")", ")", ":", "subpath", "=...
39.3
16.9
def main(): '''Main routine.''' # validate command line arguments argparser = argparse.ArgumentParser() argparser.add_argument('--uri', '-u', required=True, action='store', help='Template URI') argparser.add_argument('--params', '-f', required=True, ...
[ "def", "main", "(", ")", ":", "# validate command line arguments", "argparser", "=", "argparse", ".", "ArgumentParser", "(", ")", "argparser", ".", "add_argument", "(", "'--uri'", ",", "'-u'", ",", "required", "=", "True", ",", "action", "=", "'store'", ",", ...
40.59322
20.508475
def add_issue(self, subject, priority, status, issue_type, severity, **attrs): """ Adds a Issue and returns a :class:`Issue` resource. :param subject: subject of the :class:`Issue` :param priority: priority of the :class:`Issue` :param priority: status of the :...
[ "def", "add_issue", "(", "self", ",", "subject", ",", "priority", ",", "status", ",", "issue_type", ",", "severity", ",", "*", "*", "attrs", ")", ":", "return", "Issues", "(", "self", ".", "requester", ")", ".", "create", "(", "self", ".", "id", ",",...
40
12.5
def retrieve(func): """ Decorator for Zotero read API methods; calls _retrieve_data() and passes the result to the correct processor, based on a lookup """ def wrapped_f(self, *args, **kwargs): """ Returns result of _retrieve_data() func's return value is part of a URI, and...
[ "def", "retrieve", "(", "func", ")", ":", "def", "wrapped_f", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "\"\"\"\n Returns result of _retrieve_data()\n\n func's return value is part of a URI, and it's this\n which is intercepted and p...
37.597701
13.068966
def decrypt_text(self, text, *args, **kwargs): """ Decrypt a string. input: unicode str, output: unicode str """ b = text.encode("utf-8") token = base64.b64decode(b) return self.decrypt(token, *args, **kwargs).decode("utf-8")
[ "def", "decrypt_text", "(", "self", ",", "text", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "b", "=", "text", ".", "encode", "(", "\"utf-8\"", ")", "token", "=", "base64", ".", "b64decode", "(", "b", ")", "return", "self", ".", "decrypt",...
30.444444
12
def _profile(self, frame, event, arg): """The callback function to register by :func:`sys.setprofile`.""" # c = event.startswith('c_') if event.startswith('c_'): return time1 = self.timer() frames = self.frame_stack(frame) if frames: frames.pop() ...
[ "def", "_profile", "(", "self", ",", "frame", ",", "event", ",", "arg", ")", ":", "# c = event.startswith('c_')", "if", "event", ".", "startswith", "(", "'c_'", ")", ":", "return", "time1", "=", "self", ".", "timer", "(", ")", "frames", "=", "self", "....
35.758621
11.551724
def _get_scale(self): """ Subclasses may override this method. """ sx, sxy, syx, sy, ox, oy = self.transformation return sx, sy
[ "def", "_get_scale", "(", "self", ")", ":", "sx", ",", "sxy", ",", "syx", ",", "sy", ",", "ox", ",", "oy", "=", "self", ".", "transformation", "return", "sx", ",", "sy" ]
27
9.333333
def euclideanDistance(instance1, instance2, considerDimensions): """ Calculate Euclidean Distance between two samples Example use: data1 = [2, 2, 2, 'class_a'] data2 = [4, 4, 4, 'class_b'] distance = euclideanDistance(data1, data2, 3) :param instance1: list of attributes :param instance2: list of attri...
[ "def", "euclideanDistance", "(", "instance1", ",", "instance2", ",", "considerDimensions", ")", ":", "distance", "=", "0", "for", "x", "in", "considerDimensions", ":", "distance", "+=", "pow", "(", "(", "instance1", "[", "x", "]", "-", "instance2", "[", "x...
32.941176
13.294118
def to_code(self): """Assemble a Python code object from a Code object.""" co_argcount = len(self.args) - self.varargs - self.varkwargs co_stacksize = self._compute_stacksize() co_flags = self._compute_flags() co_consts = [self.docstring] co_names = [] co_varname...
[ "def", "to_code", "(", "self", ")", ":", "co_argcount", "=", "len", "(", "self", ".", "args", ")", "-", "self", ".", "varargs", "-", "self", ".", "varkwargs", "co_stacksize", "=", "self", ".", "_compute_stacksize", "(", ")", "co_flags", "=", "self", "....
37.731884
14.543478
def update_running_containers_from_spec(compose_config, recreate_containers=True): """Takes in a Compose spec from the Dusty Compose compiler, writes it to the Compose spec folder so Compose can pick it up, then does everything needed to make sure the Docker VM is up and running containers with the upda...
[ "def", "update_running_containers_from_spec", "(", "compose_config", ",", "recreate_containers", "=", "True", ")", ":", "write_composefile", "(", "compose_config", ",", "constants", ".", "COMPOSEFILE_PATH", ")", "compose_up", "(", "constants", ".", "COMPOSEFILE_PATH", "...
69.571429
23.857143
def pem2der(pem_string): """Convert PEM string to DER format""" # Encode all lines between the first '-----\n' and the 2nd-to-last '-----'. pem_string = pem_string.replace(b"\r", b"") first_idx = pem_string.find(b"-----\n") + 6 if pem_string.find(b"-----BEGIN", first_idx) != -1: raise Except...
[ "def", "pem2der", "(", "pem_string", ")", ":", "# Encode all lines between the first '-----\\n' and the 2nd-to-last '-----'.", "pem_string", "=", "pem_string", ".", "replace", "(", "b\"\\r\"", ",", "b\"\"", ")", "first_idx", "=", "pem_string", ".", "find", "(", "b\"----...
49.5
15.666667
def build_post_form_args(self, bucket_name, key, expires_in = 6000, acl = None, success_action_redirect = None, max_content_length = None, http_method = "http", fields=None, conditions=None): """ ...
[ "def", "build_post_form_args", "(", "self", ",", "bucket_name", ",", "key", ",", "expires_in", "=", "6000", ",", "acl", "=", "None", ",", "success_action_redirect", "=", "None", ",", "max_content_length", "=", "None", ",", "http_method", "=", "\"http\"", ",", ...
40.857143
21.653061
def find_callback(args, kw=None): 'Return callback whether passed as a last argument or as a keyword' if args and callable(args[-1]): return args[-1], args[:-1] try: return kw['callback'], args except (KeyError, TypeError): return None, args
[ "def", "find_callback", "(", "args", ",", "kw", "=", "None", ")", ":", "if", "args", "and", "callable", "(", "args", "[", "-", "1", "]", ")", ":", "return", "args", "[", "-", "1", "]", ",", "args", "[", ":", "-", "1", "]", "try", ":", "return...
34.25
13.5
def locate_files(pattern, root_dir=os.curdir): """ Locate all files matching fiven filename pattern in and below supplied root directory. """ for dirpath, dirnames, filenames in os.walk(os.path.abspath(root_dir)): for filename in fnmatch.filter(filenames, pattern): yield os.path....
[ "def", "locate_files", "(", "pattern", ",", "root_dir", "=", "os", ".", "curdir", ")", ":", "for", "dirpath", ",", "dirnames", ",", "filenames", "in", "os", ".", "walk", "(", "os", ".", "path", ".", "abspath", "(", "root_dir", ")", ")", ":", "for", ...
42
13.25
def transform_vector_coorb_to_inertial(vec_coorb, orbPhase, quat_copr): """Given a vector (of size 3) in coorbital frame, orbital phase in coprecessing frame and a minimal rotation frame quat, transforms the vector from the coorbital to the inertial frame. """ # Transform to coprecessing frame ...
[ "def", "transform_vector_coorb_to_inertial", "(", "vec_coorb", ",", "orbPhase", ",", "quat_copr", ")", ":", "# Transform to coprecessing frame", "vec_copr", "=", "rotate_in_plane", "(", "vec_coorb", ",", "-", "orbPhase", ")", "# Transform to inertial frame", "vec", "=", ...
36.928571
18.571429
def get_sum(path, form='sha256'): ''' Return the checksum for the given file. The following checksum algorithms are supported: * md5 * sha1 * sha224 * sha256 **(default)** * sha384 * sha512 path path to the file or directory form desired sum format CLI...
[ "def", "get_sum", "(", "path", ",", "form", "=", "'sha256'", ")", ":", "path", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "if", "not", "os", ".", "path", ".", "isfile", "(", "path", ")", ":", "return", "'File not found'", "return", ...
18.827586
25.517241
def get_data_by_time(path, columns, dates, start_time='00:00', end_time='23:59'): """Extract columns of data from a ProCoDA datalog based on date(s) and time(s) Note: Column 0 is time. The first data column is column 1. :param path: The path to the folder containing the ProCoDA data file(s) :type path...
[ "def", "get_data_by_time", "(", "path", ",", "columns", ",", "dates", ",", "start_time", "=", "'00:00'", ",", "end_time", "=", "'23:59'", ")", ":", "data", "=", "data_from_dates", "(", "path", ",", "dates", ")", "first_time_column", "=", "pd", ".", "to_num...
48.547619
32.238095
def getBestTranslation(basedir, lang=None): """ Find inside basedir the best translation available. lang, if defined, should be a list of prefered languages. It will look for file in the form: - en-US.qm - en_US.qm - en.qm """ if not lang: lang = QtCore.QLocale.system().uiL...
[ "def", "getBestTranslation", "(", "basedir", ",", "lang", "=", "None", ")", ":", "if", "not", "lang", ":", "lang", "=", "QtCore", ".", "QLocale", ".", "system", "(", ")", ".", "uiLanguages", "(", ")", "for", "l", "in", "lang", ":", "l", "=", "l", ...
23
18.411765