text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def find_met_in_model(model, mnx_id, compartment_id=None): """ Return specific metabolites by looking up IDs in METANETX_SHORTLIST. Parameters ---------- model : cobra.Model The metabolic model under investigation. mnx_id : string Memote internal MetaNetX metabolite identifier u...
[ "def", "find_met_in_model", "(", "model", ",", "mnx_id", ",", "compartment_id", "=", "None", ")", ":", "def", "compare_annotation", "(", "annotation", ")", ":", "\"\"\"\n Return annotation IDs that match to METANETX_SHORTLIST references.\n\n Compares the set of META...
44.50495
0.000218
def write_terminal_win(matrix, version, border=None): # pragma: no cover """\ Function to write a QR Code to a MS Windows terminal. :param matrix: The matrix to serialize. :param int version: The (Micro) QR code version :param int border: Integer indicating the size of the quiet zone. ...
[ "def", "write_terminal_win", "(", "matrix", ",", "version", ",", "border", "=", "None", ")", ":", "# pragma: no cover", "import", "sys", "import", "struct", "import", "ctypes", "write", "=", "sys", ".", "stdout", ".", "write", "std_out", "=", "ctypes", ".", ...
38.05
0.001281
def present(dbname, name, owner=None, user=None, db_user=None, db_password=None, db_host=None, db_port=None): ''' Ensure that the named schema is present in the database. dbname The database's name will work on name The name of the schema to manage ...
[ "def", "present", "(", "dbname", ",", "name", ",", "owner", "=", "None", ",", "user", "=", "None", ",", "db_user", "=", "None", ",", "db_password", "=", "None", ",", "db_host", "=", "None", ",", "db_port", "=", "None", ")", ":", "ret", "=", "{", ...
28.539474
0.000446
def plot_i0(self, colorbar=True, cb_orientation='vertical', cb_label=None, ax=None, show=True, fname=None, **kwargs): """ Plot the first invariant I0 (the trace) of the tensor I0 = vxx + vyy + vzz which should be identically zero. Usage ----- ...
[ "def", "plot_i0", "(", "self", ",", "colorbar", "=", "True", ",", "cb_orientation", "=", "'vertical'", ",", "cb_label", "=", "None", ",", "ax", "=", "None", ",", "show", "=", "True", ",", "fname", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if...
38.25
0.001274
def get_trans(self, out_vec=None): """Return the translation portion of the matrix as a vector. If out_vec is provided, store in out_vec instead of creating a new Vec3. """ if out_vec: return out_vec.set(*self.data[3][:3]) return Vec3(*self.data[3][:3])
[ "def", "get_trans", "(", "self", ",", "out_vec", "=", "None", ")", ":", "if", "out_vec", ":", "return", "out_vec", ".", "set", "(", "*", "self", ".", "data", "[", "3", "]", "[", ":", "3", "]", ")", "return", "Vec3", "(", "*", "self", ".", "data...
29.9
0.00974
def p_not_expression(tok): """not_expression : OP_NOT ex_expression | ex_expression""" if len(tok) == 3: tok[0] = UnaryOperationRule(tok[1], tok[2]) else: tok[0] = tok[1]
[ "def", "p_not_expression", "(", "tok", ")", ":", "if", "len", "(", "tok", ")", "==", "3", ":", "tok", "[", "0", "]", "=", "UnaryOperationRule", "(", "tok", "[", "1", "]", ",", "tok", "[", "2", "]", ")", "else", ":", "tok", "[", "0", "]", "=",...
34
0.008197
def Modify(self, client_limit=None, client_rate=None, duration=None): """Modifies a number of hunt arguments.""" args = hunt_pb2.ApiModifyHuntArgs(hunt_id=self.hunt_id) if client_limit is not None: args.client_limit = client_limit if client_rate is not None: args.client_rate = client_rate ...
[ "def", "Modify", "(", "self", ",", "client_limit", "=", "None", ",", "client_rate", "=", "None", ",", "duration", "=", "None", ")", ":", "args", "=", "hunt_pb2", ".", "ApiModifyHuntArgs", "(", "hunt_id", "=", "self", ".", "hunt_id", ")", "if", "client_li...
31.6
0.008197
def get_params(self): """ returns a list """ value = self._get_lookup(self.operator, self.value) self.params.append(self.value) return self.params
[ "def", "get_params", "(", "self", ")", ":", "value", "=", "self", ".", "_get_lookup", "(", "self", ".", "operator", ",", "self", ".", "value", ")", "self", ".", "params", ".", "append", "(", "self", ".", "value", ")", "return", "self", ".", "params" ...
26.857143
0.010309
def Stop(self): """Signals the worker threads to shut down and waits until it exits.""" self._shutdown = True self._new_updates.set() # Wake up the transmission thread. if self._main_thread is not None: self._main_thread.join() self._main_thread = None if self._transmission_thread is ...
[ "def", "Stop", "(", "self", ")", ":", "self", ".", "_shutdown", "=", "True", "self", ".", "_new_updates", ".", "set", "(", ")", "# Wake up the transmission thread.", "if", "self", ".", "_main_thread", "is", "not", "None", ":", "self", ".", "_main_thread", ...
33
0.012285
def load_all_distributions(self): """Replace the :attr:`distributions` attribute with all scipy distributions""" distributions = [] for this in dir(scipy.stats): if "fit" in eval("dir(scipy.stats." + this +")"): distributions.append(this) self.distributions = ...
[ "def", "load_all_distributions", "(", "self", ")", ":", "distributions", "=", "[", "]", "for", "this", "in", "dir", "(", "scipy", ".", "stats", ")", ":", "if", "\"fit\"", "in", "eval", "(", "\"dir(scipy.stats.\"", "+", "this", "+", "\")\"", ")", ":", "...
47.142857
0.011905
def van_image_enc_2d(x, first_depth, reuse=False, hparams=None): """The image encoder for the VAN. Similar architecture as Ruben's paper (http://proceedings.mlr.press/v70/villegas17a/villegas17a.pdf). Args: x: The image to encode. first_depth: The depth of the first layer. Depth is increased in subseq...
[ "def", "van_image_enc_2d", "(", "x", ",", "first_depth", ",", "reuse", "=", "False", ",", "hparams", "=", "None", ")", ":", "with", "tf", ".", "variable_scope", "(", "'van_image_enc'", ",", "reuse", "=", "reuse", ")", ":", "enc_history", "=", "[", "x", ...
27.138889
0.001481
def lparsm(inlist, delims, nmax, lenout=None): """ Parse a list of items separated by multiple delimiters. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/lparsm_c.html :param inlist: list of items delimited by delims. :type inlist: list of strings :param delims: Single characters whic...
[ "def", "lparsm", "(", "inlist", ",", "delims", ",", "nmax", ",", "lenout", "=", "None", ")", ":", "if", "lenout", "is", "None", ":", "lenout", "=", "ctypes", ".", "c_int", "(", "len", "(", "inlist", ")", "+", "1", ")", "else", ":", "lenout", "=",...
36.607143
0.000951
def show(ctx, project_id, backend): """ Shows the details of the given project id. """ try: project = ctx.obj['projects_db'].get(project_id, backend) except IOError: raise Exception("Error: the projects database file doesn't exist. " "Please run `taxi update` ...
[ "def", "show", "(", "ctx", ",", "project_id", ",", "backend", ")", ":", "try", ":", "project", "=", "ctx", ".", "obj", "[", "'projects_db'", "]", ".", "get", "(", "project_id", ",", "backend", ")", "except", "IOError", ":", "raise", "Exception", "(", ...
31.6875
0.001916
def fetch(self, vault_client, backends): """Updates local resource with context on whether this backend is actually mounted and available""" if not is_mounted(self.backend, self.path, backends) or \ self.tune_prefix is None: return backend_details = get_backend(se...
[ "def", "fetch", "(", "self", ",", "vault_client", ",", "backends", ")", ":", "if", "not", "is_mounted", "(", "self", ".", "backend", ",", "self", ".", "path", ",", "backends", ")", "or", "self", ".", "tune_prefix", "is", "None", ":", "return", "backend...
35.378378
0.001487
def feat(self,subset): """Obtain the feature class value of the specific subset. If a feature occurs multiple times, the values will be returned in a list. Example:: sense = word.annotation(folia.Sense) synset = sense.feat('synset') Returns: str or...
[ "def", "feat", "(", "self", ",", "subset", ")", ":", "r", "=", "None", "for", "f", "in", "self", ":", "if", "isinstance", "(", "f", ",", "Feature", ")", "and", "f", ".", "subset", "==", "subset", ":", "if", "r", ":", "#support for multiclass features...
28.148148
0.008906
def options(self, my_psy): '''Returns all potential loop fusion options for the psy object provided''' # compute options dynamically here as they may depend on previous # changes to the psy tree my_options = [] invokes = my_psy.invokes.invoke_list #print "there ar...
[ "def", "options", "(", "self", ",", "my_psy", ")", ":", "# compute options dynamically here as they may depend on previous", "# changes to the psy tree", "my_options", "=", "[", "]", "invokes", "=", "my_psy", ".", "invokes", ".", "invoke_list", "#print \"there are {0} invok...
43.518519
0.002498
def get_probs_for_labels(labels, prediction_results): """ Given ML Workbench prediction results, get probs of each label for each instance. The prediction results are like: [ {'predicted': 'daisy', 'probability': 0.8, 'predicted_2': 'rose', 'probability_2': 0.1}, {'predicted': 'sunflower', 'probability':...
[ "def", "get_probs_for_labels", "(", "labels", ",", "prediction_results", ")", ":", "probs", "=", "[", "]", "if", "'probability'", "in", "prediction_results", ":", "# 'probability' exists so top-n is set to none zero, and results are like", "# \"predicted, predicted_2,...,probabil...
36.160714
0.011058
def dendrite_filter(n): '''Select only dendrites''' return n.type == NeuriteType.basal_dendrite or n.type == NeuriteType.apical_dendrite
[ "def", "dendrite_filter", "(", "n", ")", ":", "return", "n", ".", "type", "==", "NeuriteType", ".", "basal_dendrite", "or", "n", ".", "type", "==", "NeuriteType", ".", "apical_dendrite" ]
47.333333
0.013889
def partial_transform(self, sequence, mode='clip'): """Transform a sequence to internal indexing Recall that `sequence` can be arbitrary labels, whereas ``transmat_`` and ``countsmat_`` are indexed with integers between 0 and ``n_states - 1``. This methods maps a set of sequences from t...
[ "def", "partial_transform", "(", "self", ",", "sequence", ",", "mode", "=", "'clip'", ")", ":", "if", "mode", "not", "in", "[", "'clip'", ",", "'fill'", "]", ":", "raise", "ValueError", "(", "'mode must be one of [\"clip\", \"fill\"]: %s'", "%", "mode", ")", ...
39.79661
0.000831
async def commit( request: web.Request, session: UpdateSession) -> web.Response: """ Serves /update/:session/commit """ if session.stage != Stages.DONE: return web.json_response( data={'error': 'not-ready', 'message': f'System is not ready to commit the update ' ...
[ "async", "def", "commit", "(", "request", ":", "web", ".", "Request", ",", "session", ":", "UpdateSession", ")", "->", "web", ".", "Response", ":", "if", "session", ".", "stage", "!=", "Stages", ".", "DONE", ":", "return", "web", ".", "json_response", ...
37.6875
0.001618
def upload(self, synchronous=True, **kwargs): """Upload a subscription manifest. Here is an example of how to use this method:: with open('my_manifest.zip') as manifest: sub.upload({'organization_id': org.id}, manifest) :param synchronous: What should happen if the...
[ "def", "upload", "(", "self", ",", "synchronous", "=", "True", ",", "*", "*", "kwargs", ")", ":", "kwargs", "=", "kwargs", ".", "copy", "(", ")", "# shadow the passed-in kwargs", "kwargs", ".", "update", "(", "self", ".", "_server_config", ".", "get_client...
39.870968
0.00158
def from_json(json_data): """ Returns a pyalveo.OAuth2 given a json string built from the oauth.to_json() method. """ #If we have a string, then decode it, otherwise assume it's already decoded if isinstance(json_data, str): data = json.loads(json_data) el...
[ "def", "from_json", "(", "json_data", ")", ":", "#If we have a string, then decode it, otherwise assume it's already decoded", "if", "isinstance", "(", "json_data", ",", "str", ")", ":", "data", "=", "json", ".", "loads", "(", "json_data", ")", "else", ":", "data", ...
41.545455
0.017131
def get(): """Check the health of this service""" uptime = time.time() - START_TIME response = dict(uptime=f'{uptime:.2f}s', links=dict(root='{}'.format(get_root_url()))) # TODO(BM) check if we can connect to the config database ... # try: # DB.get_sub_array_ids() # ...
[ "def", "get", "(", ")", ":", "uptime", "=", "time", ".", "time", "(", ")", "-", "START_TIME", "response", "=", "dict", "(", "uptime", "=", "f'{uptime:.2f}s'", ",", "links", "=", "dict", "(", "root", "=", "'{}'", ".", "format", "(", "get_root_url", "(...
35.076923
0.002137
def p_information_duration_speed(self, p): 'information : duration AT speed' logger.debug('information = duration %s at speed %s', p[1], p[3]) p[0] = p[3].for_duration(p[1])
[ "def", "p_information_duration_speed", "(", "self", ",", "p", ")", ":", "logger", ".", "debug", "(", "'information = duration %s at speed %s'", ",", "p", "[", "1", "]", ",", "p", "[", "3", "]", ")", "p", "[", "0", "]", "=", "p", "[", "3", "]", ".", ...
48.5
0.010152
def assign_reads_to_otus(original_fasta, filtered_fasta, output_filepath=None, log_name="assign_reads_to_otus.log", perc_id_blast=0.97, global_alignment=True, HALT_EXEC=F...
[ "def", "assign_reads_to_otus", "(", "original_fasta", ",", "filtered_fasta", ",", "output_filepath", "=", "None", ",", "log_name", "=", "\"assign_reads_to_otus.log\"", ",", "perc_id_blast", "=", "0.97", ",", "global_alignment", "=", "True", ",", "HALT_EXEC", "=", "F...
38.833333
0.000523
def cliques(self, reordered = True): """ Returns a list of cliques """ if reordered: return [list(self.snrowidx[self.sncolptr[k]:self.sncolptr[k+1]]) for k in range(self.Nsn)] else: return [list(self.__p[self.snrowidx[self.sncolptr[k]:self.sncolptr[k+1]]])...
[ "def", "cliques", "(", "self", ",", "reordered", "=", "True", ")", ":", "if", "reordered", ":", "return", "[", "list", "(", "self", ".", "snrowidx", "[", "self", ".", "sncolptr", "[", "k", "]", ":", "self", ".", "sncolptr", "[", "k", "+", "1", "]...
42.375
0.017341
def prepare_prop_defs(prop_defs, prop_name, cls_names): """ Examines and adds any missing defs to the prop_defs dictionary for use with the RdfPropertyMeta.__prepare__ method Args: ----- prop_defs: the defintions from the rdf vocabulary defintion prop_name: the property name ...
[ "def", "prepare_prop_defs", "(", "prop_defs", ",", "prop_name", ",", "cls_names", ")", ":", "def", "get_def", "(", "prop_defs", ",", "def_fields", ",", "default_val", "=", "None", ")", ":", "\"\"\" returns the cross corelated fields for delealing with mutiple\n ...
37.505747
0.000896
def stop(self): """停止引擎""" # 将引擎设为停止 self.__active = False # 停止计时器 self.__timerActive = False self.__timer.join() # 等待事件处理线程退出 self.__thread.join()
[ "def", "stop", "(", "self", ")", ":", "# 将引擎设为停止", "self", ".", "__active", "=", "False", "# 停止计时器", "self", ".", "__timerActive", "=", "False", "self", ".", "__timer", ".", "join", "(", ")", "# 等待事件处理线程退出", "self", ".", "__thread", ".", "join", "(", "...
19.909091
0.017467
def safe_import_module(path, default=None): """ Try to import the specified module from the given Python path @path is a string containing a Python path to the wanted module, @default is an object to return if import fails, it can be None, a callable or whatever you need. Return a object ...
[ "def", "safe_import_module", "(", "path", ",", "default", "=", "None", ")", ":", "if", "path", "is", "None", ":", "return", "default", "dot", "=", "path", ".", "rindex", "(", "'.'", ")", "module_name", "=", "path", "[", ":", "dot", "]", "class_name", ...
31.727273
0.011127
def _update_content(self, other_filth): """this updates the bounds, text and placeholder for the merged filth """ if self.end < other_filth.beg or other_filth.end < self.beg: raise exceptions.FilthMergeError( "a_filth goes from [%s, %s) and b_filth goes from [...
[ "def", "_update_content", "(", "self", ",", "other_filth", ")", ":", "if", "self", ".", "end", "<", "other_filth", ".", "beg", "or", "other_filth", ".", "end", "<", "self", ".", "beg", ":", "raise", "exceptions", ".", "FilthMergeError", "(", "\"a_filth goe...
38.466667
0.001691
def reverse_action(self, url_name, *args, **kwargs): """ Extended DRF with fallback to requested namespace if request.version is missing """ if self.request and not self.request.version: return reverse(self.get_url_name(url_name), *args, **kwargs) return super().reve...
[ "def", "reverse_action", "(", "self", ",", "url_name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "request", "and", "not", "self", ".", "request", ".", "version", ":", "return", "reverse", "(", "self", ".", "get_url_name", ...
43.75
0.008403
def SetExtractionConfiguration(self, configuration): """Sets the extraction configuration settings. Args: configuration (ExtractionConfiguration): extraction configuration. """ self._hasher_file_size_limit = configuration.hasher_file_size_limit self._SetHashers(configuration.hasher_names_stri...
[ "def", "SetExtractionConfiguration", "(", "self", ",", "configuration", ")", ":", "self", ".", "_hasher_file_size_limit", "=", "configuration", ".", "hasher_file_size_limit", "self", ".", "_SetHashers", "(", "configuration", ".", "hasher_names_string", ")", "self", "....
46.272727
0.001927
def spread_stats(stats, spreader=False): """Iterates all descendant statistics under the given root statistics. When ``spreader=True``, each iteration yields a descendant statistics and `spread()` function together. You should call `spread()` if you want to spread the yielded statistics also. """...
[ "def", "spread_stats", "(", "stats", ",", "spreader", "=", "False", ")", ":", "spread", "=", "spread_t", "(", ")", "if", "spreader", "else", "True", "descendants", "=", "deque", "(", "stats", ")", "while", "descendants", ":", "_stats", "=", "descendants", ...
32.578947
0.00157
def convert_clip(node, **kwargs): """Map MXNet's Clip operator attributes to onnx's Clip operator and return the created node. """ name, input_nodes, attrs = get_inputs(node, kwargs) a_min = np.float(attrs.get('a_min', -np.inf)) a_max = np.float(attrs.get('a_max', np.inf)) clip_node = onnx...
[ "def", "convert_clip", "(", "node", ",", "*", "*", "kwargs", ")", ":", "name", ",", "input_nodes", ",", "attrs", "=", "get_inputs", "(", "node", ",", "kwargs", ")", "a_min", "=", "np", ".", "float", "(", "attrs", ".", "get", "(", "'a_min'", ",", "-...
25.5
0.002101
def setPluginSetting(name, value, namespace = None): ''' Sets the value of a plugin setting. :param name: the name of the setting. It is not the full path, but just the last name of it :param value: the value to set for the plugin setting :param namespace: The namespace. If not passed or None, the ...
[ "def", "setPluginSetting", "(", "name", ",", "value", ",", "namespace", "=", "None", ")", ":", "namespace", "=", "namespace", "or", "_callerName", "(", ")", ".", "split", "(", "\".\"", ")", "[", "0", "]", "settings", ".", "setValue", "(", "namespace", ...
52.307692
0.010116
def select_army(action, action_space, select_add): """Select the entire army.""" del action_space action.action_ui.select_army.selection_add = select_add
[ "def", "select_army", "(", "action", ",", "action_space", ",", "select_add", ")", ":", "del", "action_space", "action", ".", "action_ui", ".", "select_army", ".", "selection_add", "=", "select_add" ]
39
0.025157
def create(cls, skydir, ltc, event_class, event_types, energies, cth_bins=None, ndtheta=500, use_edisp=False, fn=None, nbin=64): """Create a PSFModel object. This class can be used to evaluate the exposure-weighted PSF for a source with a given observing profile and energy distri...
[ "def", "create", "(", "cls", ",", "skydir", ",", "ltc", ",", "event_class", ",", "event_types", ",", "energies", ",", "cth_bins", "=", "None", ",", "ndtheta", "=", "500", ",", "use_edisp", "=", "False", ",", "fn", "=", "None", ",", "nbin", "=", "64",...
36.894737
0.001853
def parse_interface_type_extension(lexer: Lexer) -> InterfaceTypeExtensionNode: """InterfaceTypeExtension""" start = lexer.token expect_keyword(lexer, "extend") expect_keyword(lexer, "interface") name = parse_name(lexer) directives = parse_directives(lexer, True) fields = parse_fields_defini...
[ "def", "parse_interface_type_extension", "(", "lexer", ":", "Lexer", ")", "->", "InterfaceTypeExtensionNode", ":", "start", "=", "lexer", ".", "token", "expect_keyword", "(", "lexer", ",", "\"extend\"", ")", "expect_keyword", "(", "lexer", ",", "\"interface\"", ")...
39.230769
0.001916
def simxPackFloats(floatList): ''' Please have a look at the function description/documentation in the V-REP user manual ''' if sys.version_info[0] == 3: s=bytes() for i in range(len(floatList)): s=s+struct.pack('<f',floatList[i]) s=bytearray(s) else: s='...
[ "def", "simxPackFloats", "(", "floatList", ")", ":", "if", "sys", ".", "version_info", "[", "0", "]", "==", "3", ":", "s", "=", "bytes", "(", ")", "for", "i", "in", "range", "(", "len", "(", "floatList", ")", ")", ":", "s", "=", "s", "+", "stru...
27.066667
0.021429
def interpolate_masked_data(data, mask, error=None, background=None): """ Interpolate over masked pixels in data and optional error or background images. The value of masked pixels are replaced by the mean value of the connected neighboring non-masked pixels. This function is intended for sing...
[ "def", "interpolate_masked_data", "(", "data", ",", "mask", ",", "error", "=", "None", ",", "background", "=", "None", ")", ":", "if", "data", ".", "shape", "!=", "mask", ".", "shape", ":", "raise", "ValueError", "(", "'data and mask must have the same shape'"...
36.646341
0.000324
def __squid_to_guid(self, squid): ''' Squished GUID (SQUID) to GUID. A SQUID is a Squished/Compressed version of a GUID to use up less space in the registry. Args: squid (str): Squished GUID. Returns: str: the GUID if a valid SQUID provided. ...
[ "def", "__squid_to_guid", "(", "self", ",", "squid", ")", ":", "if", "not", "squid", ":", "return", "''", "squid_match", "=", "self", ".", "__squid_pattern", ".", "match", "(", "squid", ")", "guid", "=", "''", "if", "squid_match", "is", "not", "None", ...
31.333333
0.002294
def img2img_transformer_dilated(): """Try dilated.""" hparams = img2img_transformer_base() hparams.add_hparam("num_memory_blocks", 1) hparams.num_heads = 8 hparams.attention_key_channels = hparams.attention_value_channels = 0 hparams.hidden_size = 512 hparams.filter_size = 2048 hparams.num_decoder_layer...
[ "def", "img2img_transformer_dilated", "(", ")", ":", "hparams", "=", "img2img_transformer_base", "(", ")", "hparams", ".", "add_hparam", "(", "\"num_memory_blocks\"", ",", "1", ")", "hparams", ".", "num_heads", "=", "8", "hparams", ".", "attention_key_channels", "...
34.625
0.02812
def axis_labels(xtitle, ytitle, xsuffix="continuous", ysuffix="continuous", xkwargs={}, ykwargs={}): """ Helper function to create reasonable axis labels @param xtitle String for the title of the X axis. Automatically escaped @...
[ "def", "axis_labels", "(", "xtitle", ",", "ytitle", ",", "xsuffix", "=", "\"continuous\"", ",", "ysuffix", "=", "\"continuous\"", ",", "xkwargs", "=", "{", "}", ",", "ykwargs", "=", "{", "}", ")", ":", "exec", "\"xfunc = scale_x_%s\"", "%", "xsuffix", "exe...
33.285714
0.01251
def autoencoder_ordered_text_small(): """Ordered discrete autoencoder model for text, small version.""" hparams = autoencoder_ordered_text() hparams.bottleneck_bits = 32 hparams.num_hidden_layers = 3 hparams.hidden_size = 64 hparams.max_hidden_size = 512 hparams.bottleneck_noise = 0.0 hparams.autoregres...
[ "def", "autoencoder_ordered_text_small", "(", ")", ":", "hparams", "=", "autoencoder_ordered_text", "(", ")", "hparams", ".", "bottleneck_bits", "=", "32", "hparams", ".", "num_hidden_layers", "=", "3", "hparams", ".", "hidden_size", "=", "64", "hparams", ".", "...
34
0.028646
def classify_import(module_name, application_directories=('.',)): """Classifies an import by its package. Returns a value in ImportType.__all__ :param text module_name: The dotted notation of a module :param tuple application_directories: tuple of paths which are considered application roots. ...
[ "def", "classify_import", "(", "module_name", ",", "application_directories", "=", "(", "'.'", ",", ")", ")", ":", "# Only really care about the first part of the path", "base", ",", "_", ",", "_", "=", "module_name", ".", "partition", "(", "'.'", ")", "found", ...
35.111111
0.00077
def execute(scope, command): """ Executes the given command locally. :type command: string :param command: A shell command. """ process = Popen(command[0], shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT, ...
[ "def", "execute", "(", "scope", ",", "command", ")", ":", "process", "=", "Popen", "(", "command", "[", "0", "]", ",", "shell", "=", "True", ",", "stdin", "=", "PIPE", ",", "stdout", "=", "PIPE", ",", "stderr", "=", "STDOUT", ",", "close_fds", "=",...
26.933333
0.002392
def index_fields(self, index=Index(), **options): """ Indexes all fields in the `Structure` starting with the given *index* and returns the :class:`Index` after the last :class:`Field` in the `Structure`. :param Index index: start :class:`Index` for the first :class:`Field` ...
[ "def", "index_fields", "(", "self", ",", "index", "=", "Index", "(", ")", ",", "*", "*", "options", ")", ":", "for", "name", ",", "item", "in", "self", ".", "items", "(", ")", ":", "# Container", "if", "is_container", "(", "item", ")", ":", "index"...
42.28
0.00185
def degree_dist(graph, limits=(0,0), bin_num=10, mode='out'): ''' Computes the degree distribution for a graph. Returns a list of tuples where the first element of the tuple is the center of the bin representing a range of degrees and the second element of the tuple are the number of nodes with the...
[ "def", "degree_dist", "(", "graph", ",", "limits", "=", "(", "0", ",", "0", ")", ",", "bin_num", "=", "10", ",", "mode", "=", "'out'", ")", ":", "deg", "=", "[", "]", "if", "mode", "==", "'inc'", ":", "get_deg", "=", "graph", ".", "inc_degree", ...
23.5
0.008759
def filter_select_columns_intensity(df, prefix, columns): """ Filter dataframe to include specified columns, retaining any Intensity columns. """ # Note: I use %s.+ (not %s.*) so it forces a match with the prefix string, ONLY if it is followed by something. return df.filter(regex='^(%s.+|%s)$' % (pr...
[ "def", "filter_select_columns_intensity", "(", "df", ",", "prefix", ",", "columns", ")", ":", "# Note: I use %s.+ (not %s.*) so it forces a match with the prefix string, ONLY if it is followed by something.", "return", "df", ".", "filter", "(", "regex", "=", "'^(%s.+|%s)$'", "%...
56.833333
0.011561
def setEditor(self, name): """Sets the editor class for this Stimulus""" editor = get_stimulus_editor(name) self.editor = editor self._stim.setStimType(name)
[ "def", "setEditor", "(", "self", ",", "name", ")", ":", "editor", "=", "get_stimulus_editor", "(", "name", ")", "self", ".", "editor", "=", "editor", "self", ".", "_stim", ".", "setStimType", "(", "name", ")" ]
37
0.010582
def htmresearchCorePrereleaseInstalled(): """ Make an attempt to determine if a pre-release version of htmresearch-core is installed already. @return: boolean """ try: coreDistribution = pkg_resources.get_distribution("htmresearch-core") if pkg_resources.parse_version(coreDistribution.version).is_p...
[ "def", "htmresearchCorePrereleaseInstalled", "(", ")", ":", "try", ":", "coreDistribution", "=", "pkg_resources", ".", "get_distribution", "(", "\"htmresearch-core\"", ")", "if", "pkg_resources", ".", "parse_version", "(", "coreDistribution", ".", "version", ")", ".",...
33.882353
0.016892
def _validate_stone_cfg(self): """ Returns: Struct: A schema for route attributes. """ def mk_route_schema(): s = Struct('Route', ApiNamespace('stone_cfg'), None) s.set_attributes(None, [], None) return s try: stone_cf...
[ "def", "_validate_stone_cfg", "(", "self", ")", ":", "def", "mk_route_schema", "(", ")", ":", "s", "=", "Struct", "(", "'Route'", ",", "ApiNamespace", "(", "'stone_cfg'", ")", ",", "None", ")", "s", ".", "set_attributes", "(", "None", ",", "[", "]", ",...
32.105263
0.001591
def execute_async(query, auth=None, client=event_loop): """Execute a query asynchronously, returning its result Parameters ---------- query: Query[T] The query to resolve auth: ~typing.Tuple[str, str] \ or ~typing.Callable[[Request], Request] or None This may be: * ...
[ "def", "execute_async", "(", "query", ",", "auth", "=", "None", ",", "client", "=", "event_loop", ")", ":", "exc_fn", "=", "getattr", "(", "type", "(", "query", ")", ",", "'__execute_async__'", ",", "Query", ".", "__execute_async__", ")", "return", "exc_fn...
30.03125
0.001008
def load_lib(filename): """ Loads a Python file containing functions, and returns the content of the __lib__ variable. The __lib__ variable must contain a dictionary mapping function names to callables. Returns a dictionary mapping the namespaced function names to callables. The namespace is th...
[ "def", "load_lib", "(", "filename", ")", ":", "# Open the file.", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "raise", "IOError", "(", "'No such file: %s'", "%", "filename", ")", "name", "=", "os", ".", "path", ".", "splitex...
35.032258
0.001792
def cal_k_vinet_from_v(v, v0, k0, k0p): """ calculate bulk modulus in GPa :param v: unit-cell volume in A^3 :param v0: unit-cell volume in A^3 at 1 bar :param k0: bulk modulus at reference conditions :param k0p: pressure derivative of bulk modulus at reference conditions :return: bulk modul...
[ "def", "cal_k_vinet_from_v", "(", "v", ",", "v0", ",", "k0", ",", "k0p", ")", ":", "x", "=", "v", "/", "v0", "y", "=", "np", ".", "power", "(", "x", ",", "1.", "/", "3.", ")", "eta", "=", "1.5", "*", "(", "k0p", "-", "1.", ")", "k", "=", ...
32.75
0.001855
def jacobi(a, b): '''Calculates the value of the Jacobi symbol (a/b) where both a and b are positive integers, and b is odd :returns: -1, 0 or 1 ''' assert a > 0 assert b > 0 if a == 0: return 0 result = 1 while a > 1: if a & 1: if ((a-1)*(b-1) >> 2) & ...
[ "def", "jacobi", "(", "a", ",", "b", ")", ":", "assert", "a", ">", "0", "assert", "b", ">", "0", "if", "a", "==", "0", ":", "return", "0", "result", "=", "1", "while", "a", ">", "1", ":", "if", "a", "&", "1", ":", "if", "(", "(", "a", "...
20.68
0.001848
def indexOfClosest( arr, val ): '''Return the index in arr of the closest float value to val.''' i_closest = None for i,v in enumerate(arr): d = math.fabs( v - val ) if i_closest == None or d < d_closest: i_closest = i d_closest = d return i_closest
[ "def", "indexOfClosest", "(", "arr", ",", "val", ")", ":", "i_closest", "=", "None", "for", "i", ",", "v", "in", "enumerate", "(", "arr", ")", ":", "d", "=", "math", ".", "fabs", "(", "v", "-", "val", ")", "if", "i_closest", "==", "None", "or", ...
33
0.022951
def get_file(self): """SCP copy the file from the remote device to local system.""" source_file = "{}".format(self.source_file) self.scp_conn.scp_get_file(source_file, self.dest_file) self.scp_conn.close()
[ "def", "get_file", "(", "self", ")", ":", "source_file", "=", "\"{}\"", ".", "format", "(", "self", ".", "source_file", ")", "self", ".", "scp_conn", ".", "scp_get_file", "(", "source_file", ",", "self", ".", "dest_file", ")", "self", ".", "scp_conn", "....
46.6
0.008439
def discover_modules(directory): """ Attempts to list all of the modules and submodules found within a given directory tree. This function searches the top-level of the directory tree for potential python modules and returns a list of candidate names. **Note:** This function returns a list of strin...
[ "def", "discover_modules", "(", "directory", ")", ":", "found", "=", "list", "(", ")", "if", "os", ".", "path", ".", "isdir", "(", "directory", ")", ":", "for", "entry", "in", "os", ".", "listdir", "(", "directory", ")", ":", "next_dir", "=", "os", ...
35.318182
0.001253
def policy_and_value_net(rng_key, batch_observations_shape, num_actions, bottom_layers=None): """A policy and value net function.""" # Layers. cur_layers = [] if bottom_layers is not None: cur_layers.extend(bottom_layers) # Now, ...
[ "def", "policy_and_value_net", "(", "rng_key", ",", "batch_observations_shape", ",", "num_actions", ",", "bottom_layers", "=", "None", ")", ":", "# Layers.", "cur_layers", "=", "[", "]", "if", "bottom_layers", "is", "not", "None", ":", "cur_layers", ".", "extend...
37.1
0.015769
def create_config_files(directory): """ Initialize directory ready for vpn walker :param directory: the path where you want this to happen :return: """ # Some constant strings config_zip_url = "http://www.ipvanish.com/software/configs/configs.zip" if not os.path.exists(directory): ...
[ "def", "create_config_files", "(", "directory", ")", ":", "# Some constant strings", "config_zip_url", "=", "\"http://www.ipvanish.com/software/configs/configs.zip\"", "if", "not", "os", ".", "path", ".", "exists", "(", "directory", ")", ":", "os", ".", "makedirs", "(...
33.819672
0.000942
def _dump_arg_defaults(kwargs): """Inject default arguments for dump functions.""" if current_app: kwargs.setdefault('cls', current_app.json_encoder) if not current_app.config['JSON_AS_ASCII']: kwargs.setdefault('ensure_ascii', False) kwargs.setdefault('sort_keys', current_ap...
[ "def", "_dump_arg_defaults", "(", "kwargs", ")", ":", "if", "current_app", ":", "kwargs", ".", "setdefault", "(", "'cls'", ",", "current_app", ".", "json_encoder", ")", "if", "not", "current_app", ".", "config", "[", "'JSON_AS_ASCII'", "]", ":", "kwargs", "....
43.9
0.002232
def find_all(self, header, list_type=None): """Find all direct children with header and optional list type.""" found = [] for chunk in self: if chunk.header == header and (not list_type or (header in list_headers and chunk.type == list_type)): found.ap...
[ "def", "find_all", "(", "self", ",", "header", ",", "list_type", "=", "None", ")", ":", "found", "=", "[", "]", "for", "chunk", "in", "self", ":", "if", "chunk", ".", "header", "==", "header", "and", "(", "not", "list_type", "or", "(", "header", "i...
43.125
0.011364
def create(instances_schedule): ''' Creates load plan timestamps generator >>> from util import take >>> take(7, LoadPlanBuilder().ramp(5, 4000).create()) [0, 1000, 2000, 3000, 4000, 0, 0] >>> take(7, create(['ramp(5, 4s)'])) [0, 1000, 2000, 3000, 4000, 0, 0] >>> take(12, create(['ra...
[ "def", "create", "(", "instances_schedule", ")", ":", "lpb", "=", "LoadPlanBuilder", "(", ")", ".", "add_all_steps", "(", "instances_schedule", ")", "lp", "=", "lpb", ".", "create", "(", ")", "info", ".", "status", ".", "publish", "(", "'duration'", ",", ...
32.865385
0.001136
def profile(schemaname='sensordata', profiletype='pjs'): """Profiles object model handling with a very simple benchmarking test""" db_log("Profiling ", schemaname) schema = schemastore[schemaname]['schema'] db_log("Schema: ", schema, lvl=debug) testclass = None if profiletype == 'warmongo':...
[ "def", "profile", "(", "schemaname", "=", "'sensordata'", ",", "profiletype", "=", "'pjs'", ")", ":", "db_log", "(", "\"Profiling \"", ",", "schemaname", ")", "schema", "=", "schemastore", "[", "schemaname", "]", "[", "'schema'", "]", "db_log", "(", "\"Schem...
28.684211
0.000887
def _expand(self, normalization, csphase, **kwargs): """Expand the grid into real spherical harmonics.""" if normalization.lower() == '4pi': norm = 1 elif normalization.lower() == 'schmidt': norm = 2 elif normalization.lower() == 'unnorm': norm = 3 ...
[ "def", "_expand", "(", "self", ",", "normalization", ",", "csphase", ",", "*", "*", "kwargs", ")", ":", "if", "normalization", ".", "lower", "(", ")", "==", "'4pi'", ":", "norm", "=", "1", "elif", "normalization", ".", "lower", "(", ")", "==", "'schm...
40.791667
0.001996
def _can_process_pre_prepare(self, pre_prepare: PrePrepare, sender: str) -> Optional[int]: """ Decide whether this replica is eligible to process a PRE-PREPARE. :param pre_prepare: a PRE-PREPARE msg to process :param sender: the name of the node that sent the PRE-PREPARE msg """...
[ "def", "_can_process_pre_prepare", "(", "self", ",", "pre_prepare", ":", "PrePrepare", ",", "sender", ":", "str", ")", "->", "Optional", "[", "int", "]", ":", "# TODO: Check whether it is rejecting PRE-PREPARE from previous view", "# PRE-PREPARE should not be sent from non pr...
41.414634
0.002301
def _initialize(self): """Read the SharQ configuration and set appropriate variables. Open a redis connection pool and load all the Lua scripts. """ self._key_prefix = self._config.get('redis', 'key_prefix') self._job_expire_interval = int( self._config.get('s...
[ "def", "_initialize", "(", "self", ")", ":", "self", ".", "_key_prefix", "=", "self", ".", "_config", ".", "get", "(", "'redis'", ",", "'key_prefix'", ")", "self", ".", "_job_expire_interval", "=", "int", "(", "self", ".", "_config", ".", "get", "(", "...
37.137931
0.00181
def write_grid_tpl(self,name,tpl_file,zn_array): """ write a template file a for grid-based multiplier parameters Parameters ---------- name : str the base parameter name tpl_file : str the template file to write zn_array : numpy.ndarray ...
[ "def", "write_grid_tpl", "(", "self", ",", "name", ",", "tpl_file", ",", "zn_array", ")", ":", "parnme", ",", "x", ",", "y", "=", "[", "]", ",", "[", "]", ",", "[", "]", "with", "open", "(", "os", ".", "path", ".", "join", "(", "self", ".", "...
38
0.01796
def get_subhash(hash): """Get a second hash based on napiprojekt's hash. :param str hash: napiprojekt's hash. :return: the subhash. :rtype: str """ idx = [0xe, 0x3, 0x6, 0x8, 0x2] mul = [2, 2, 5, 4, 3] add = [0, 0xd, 0x10, 0xb, 0x5] b = [] for i in range(len(idx)): a =...
[ "def", "get_subhash", "(", "hash", ")", ":", "idx", "=", "[", "0xe", ",", "0x3", ",", "0x6", ",", "0x8", ",", "0x2", "]", "mul", "=", "[", "2", ",", "2", ",", "5", ",", "4", ",", "3", "]", "add", "=", "[", "0", ",", "0xd", ",", "0x10", ...
21.545455
0.00202
def get_compositions_by_search(self, composition_query, composition_search): """Pass through to provider CompositionSearchSession.get_compositions_by_search""" # Implemented from azosid template for - # osid.resource.ResourceSearchSession.get_resources_by_search_template if not self._can...
[ "def", "get_compositions_by_search", "(", "self", ",", "composition_query", ",", "composition_search", ")", ":", "# Implemented from azosid template for -", "# osid.resource.ResourceSearchSession.get_resources_by_search_template", "if", "not", "self", ".", "_can", "(", "'search'"...
66.571429
0.008475
def _get_ngram_counter(ids, n): """Get a Counter with the ngrams of the given ID list. Args: ids: np.array or a list corresponding to a single sentence n: n-gram size Returns: collections.Counter with ID tuples as keys and 1s as values. """ # Remove zero IDs used to pad the sequence. ids = [to...
[ "def", "_get_ngram_counter", "(", "ids", ",", "n", ")", ":", "# Remove zero IDs used to pad the sequence.", "ids", "=", "[", "token_id", "for", "token_id", "in", "ids", "if", "token_id", "!=", "0", "]", "ngram_list", "=", "[", "tuple", "(", "ids", "[", "i", ...
29.888889
0.016216
def record(ekey, entry, diff=False): """Records the specified entry to the key-value store under the specified entity key. Args: ekey (str): fqdn/uuid of the method/object to store the entry for. entry (dict): attributes and values gleaned from the execution. diff (bool): when True,...
[ "def", "record", "(", "ekey", ",", "entry", ",", "diff", "=", "False", ")", ":", "taskdb", "=", "active_db", "(", ")", "taskdb", ".", "record", "(", "ekey", ",", "entry", ",", "diff", ")", "# The task database save method makes sure that we only save as often as...
41.4375
0.001475
def get( self, name=None, group=None, index=None, raster=None, samples_only=False, data=None, raw=False, ignore_invalidation_bits=False, source=None, record_offset=0, record_count=None, copy_master=True, ): ...
[ "def", "get", "(", "self", ",", "name", "=", "None", ",", "group", "=", "None", ",", "index", "=", "None", ",", "raster", "=", "None", ",", "samples_only", "=", "False", ",", "data", "=", "None", ",", "raw", "=", "False", ",", "ignore_invalidation_bi...
34.744444
0.001119
def calculate_last_common_level(k, b1, b2): """ Calculate the highest level after which the paths from the root to these buckets diverge. """ l1 = calculate_bucket_level(k, b1) l2 = calculate_bucket_level(k, b2) while l1 > l2: b1 = (b1-1)//k l1 -= 1 while l2 > l1: ...
[ "def", "calculate_last_common_level", "(", "k", ",", "b1", ",", "b2", ")", ":", "l1", "=", "calculate_bucket_level", "(", "k", ",", "b1", ")", "l2", "=", "calculate_bucket_level", "(", "k", ",", "b2", ")", "while", "l1", ">", "l2", ":", "b1", "=", "(...
23.888889
0.002237
def login_open_sheet(email, password, spreadsheet): """Connect to Google Docs spreadsheet and return the first worksheet.""" try: gc = gspread.login(email, password) worksheet = gc.open(spreadsheet).sheet1 return worksheet except: print 'Unable to login and get spreadsheet. Check email, password, spreadshee...
[ "def", "login_open_sheet", "(", "email", ",", "password", ",", "spreadsheet", ")", ":", "try", ":", "gc", "=", "gspread", ".", "login", "(", "email", ",", "password", ")", "worksheet", "=", "gc", ".", "open", "(", "spreadsheet", ")", ".", "sheet1", "re...
37.111111
0.032164
def _load_timestamps(self): """Load timestamps from file.""" timestamp_file = os.path.join( self.data_path, 'oxts', 'timestamps.txt') # Read and parse the timestamps self.timestamps = [] with open(timestamp_file, 'r') as f: for line in f.readlines(): ...
[ "def", "_load_timestamps", "(", "self", ")", ":", "timestamp_file", "=", "os", ".", "path", ".", "join", "(", "self", ".", "data_path", ",", "'oxts'", ",", "'timestamps.txt'", ")", "# Read and parse the timestamps", "self", ".", "timestamps", "=", "[", "]", ...
44.555556
0.002442
def folderitem(self, obj, item, index): """Service triggered each time an item is iterated in folderitems. The use of this service prevents the extra-loops in child objects. :obj: the instance of the class to be foldered :item: dict containing the properties of the object to be used by ...
[ "def", "folderitem", "(", "self", ",", "obj", ",", "item", ",", "index", ")", ":", "fullname", "=", "obj", ".", "getFullname", "(", ")", "if", "fullname", ":", "item", "[", "\"Fullname\"", "]", "=", "fullname", "item", "[", "\"replace\"", "]", "[", "...
36.790698
0.001232
def a2b_base58(s): """Convert base58 to binary using BASE58_ALPHABET.""" v, prefix = to_long(BASE58_BASE, lambda c: BASE58_LOOKUP[c], s.encode("utf8")) return from_long(v, prefix, 256, lambda x: x)
[ "def", "a2b_base58", "(", "s", ")", ":", "v", ",", "prefix", "=", "to_long", "(", "BASE58_BASE", ",", "lambda", "c", ":", "BASE58_LOOKUP", "[", "c", "]", ",", "s", ".", "encode", "(", "\"utf8\"", ")", ")", "return", "from_long", "(", "v", ",", "pre...
51.5
0.009569
def is_valid_pid_for_create(did): """Assert that ``did`` can be used as a PID for creating a new object with MNStorage.create() or MNStorage.update().""" if not d1_gmn.app.did.is_valid_pid_for_create(did): raise d1_common.types.exceptions.IdentifierNotUnique( 0, 'Identifier i...
[ "def", "is_valid_pid_for_create", "(", "did", ")", ":", "if", "not", "d1_gmn", ".", "app", ".", "did", ".", "is_valid_pid_for_create", "(", "did", ")", ":", "raise", "d1_common", ".", "types", ".", "exceptions", ".", "IdentifierNotUnique", "(", "0", ",", "...
42.272727
0.002105
def _check_random_state(random_state): """Checks and processes user input for seeding random numbers. Parameters ---------- random_state : int, RandomState instance or None If int, a RandomState instance is created with this integer seed. If RandomState instance, random_state is returne...
[ "def", "_check_random_state", "(", "random_state", ")", ":", "if", "random_state", "is", "None", "or", "isinstance", "(", "random_state", ",", "int", ")", ":", "return", "sci", ".", "random", ".", "RandomState", "(", "random_state", ")", "elif", "isinstance", ...
32.8
0.001185
def set_var(var, set_='""'): '''set var outside notebook''' if isinstance(set_, str): to_set = json.dumps(set_) elif isinstance(set_, dict) or isinstance(set_, list): try: to_set = json.dumps(set_) except ValueError: raise Exception('var not jsonable') els...
[ "def", "set_var", "(", "var", ",", "set_", "=", "'\"\"'", ")", ":", "if", "isinstance", "(", "set_", ",", "str", ")", ":", "to_set", "=", "json", ".", "dumps", "(", "set_", ")", "elif", "isinstance", "(", "set_", ",", "dict", ")", "or", "isinstance...
32
0.002336
def _improve_attribute_docs(obj, name, lines): """Improve the documentation of various attributes. This improves the navigation between related objects. :param obj: the instance of the object to document. :param name: full dotted path to the object. :param lines: expected documentation lines. "...
[ "def", "_improve_attribute_docs", "(", "obj", ",", "name", ",", "lines", ")", ":", "if", "obj", "is", "None", ":", "# Happens with form attributes.", "return", "if", "isinstance", "(", "obj", ",", "DeferredAttribute", ")", ":", "# This only points to a field name, n...
45.756757
0.002313
def items(self, *args, **kwargs): """ Returns a queryset of Actions to use based on the stream method and object. """ return self.get_stream()(self.get_object(*args, **kwargs))
[ "def", "items", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "get_stream", "(", ")", "(", "self", ".", "get_object", "(", "*", "args", ",", "*", "*", "kwargs", ")", ")" ]
40.8
0.014423
def _determine_checkout_url(self, platform, action): """This returns the Adyen API endpoint based on the provided platform, service and action. Args: platform (str): Adyen platform, ie 'live' or 'test'. action (str): the API action to perform. """ api_ver...
[ "def", "_determine_checkout_url", "(", "self", ",", "platform", ",", "action", ")", ":", "api_version", "=", "settings", ".", "API_CHECKOUT_VERSION", "if", "platform", "==", "\"test\"", ":", "base_uri", "=", "settings", ".", "ENDPOINT_CHECKOUT_TEST", "elif", "self...
45.740741
0.001586
def find_valid_combinations(self, tiles_34, first_index, second_index, hand_not_completed=False): """ Find and return all valid set combinations in given suit :param tiles_34: :param first_index: :param second_index: :param hand_not_completed: in that mode we can return j...
[ "def", "find_valid_combinations", "(", "self", ",", "tiles_34", ",", "first_index", ",", "second_index", ",", "hand_not_completed", "=", "False", ")", ":", "indices", "=", "[", "]", "for", "x", "in", "range", "(", "first_index", ",", "second_index", "+", "1"...
38.020408
0.002093
def grep(rootdir, searched): "grep -l <searched>" to_inspect = [] for root, dirs, files in os.walk(rootdir): for _file in files: if _file.endswith('.rst'): to_inspect.append(join(root, _file)) to_check = ((_file, open(_file, 'r').read()) for _file in to_inspect) ...
[ "def", "grep", "(", "rootdir", ",", "searched", ")", ":", "to_inspect", "=", "[", "]", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "rootdir", ")", ":", "for", "_file", "in", "files", ":", "if", "_file", ".", "endswith", ...
36.75
0.002212
def stream_sync(self, report, timeout=120.0): """Send a report and wait for it to finish. This awaitable coroutine wraps VirtualIOTileDevice.stream() and turns the callback into an awaitable object. The appropriate usage of this method is by calling it inside the event loop as: ...
[ "def", "stream_sync", "(", "self", ",", "report", ",", "timeout", "=", "120.0", ")", ":", "done", "=", "AwaitableResponse", "(", ")", "self", ".", "stream", "(", "report", ",", "callback", "=", "done", ".", "set_result", ")", "return", "done", ".", "wa...
37.357143
0.001864
def keyed_hash(digest, passphrase): """Calculate a HMAC/keyed hash. :param digest: Digest used to create hash. :type digest: str :param passphrase: Passphrase used to generate the hash. :type passphrase: str :returns: HMAC/keyed hash. :rtype: str """ encodedPassphrase = passphrase.e...
[ "def", "keyed_hash", "(", "digest", ",", "passphrase", ")", ":", "encodedPassphrase", "=", "passphrase", ".", "encode", "(", ")", "encodedDigest", "=", "digest", ".", "encode", "(", ")", "return", "hmac", ".", "new", "(", "encodedPassphrase", ",", "encodedDi...
30.714286
0.002257
def classes_in_namespaces_converter_with_compression( reference_namespace={}, template_for_namespace="class-%(name)s", list_splitter_fn=_default_list_splitter, class_extractor=_default_class_extractor, extra_extractor=_default_extra_extractor): """ parameters: tem...
[ "def", "classes_in_namespaces_converter_with_compression", "(", "reference_namespace", "=", "{", "}", ",", "template_for_namespace", "=", "\"class-%(name)s\"", ",", "list_splitter_fn", "=", "_default_list_splitter", ",", "class_extractor", "=", "_default_class_extractor", ",", ...
47.757282
0.000199
def add_key(service, key): """ Add a key to a keyring. Creates the keyring if it doesn't already exist. Logs and returns if the key is already in the keyring. """ keyring = _keyring_path(service) if os.path.exists(keyring): with open(keyring, 'r') as ring: if key in rin...
[ "def", "add_key", "(", "service", ",", "key", ")", ":", "keyring", "=", "_keyring_path", "(", "service", ")", "if", "os", ".", "path", ".", "exists", "(", "keyring", ")", ":", "with", "open", "(", "keyring", ",", "'r'", ")", "as", "ring", ":", "if"...
35.047619
0.001323
def diff_sevice_by_text(service_name, service, environment, cf_client, repo_root): """ Render the local template and compare it to the template that was last applied in the target environment. """ global ret_code logger.info('Investigating textual diff for `%s`:`%s` in environment `%s`', ...
[ "def", "diff_sevice_by_text", "(", "service_name", ",", "service", ",", "environment", ",", "cf_client", ",", "repo_root", ")", ":", "global", "ret_code", "logger", ".", "info", "(", "'Investigating textual diff for `%s`:`%s` in environment `%s`'", ",", "service", "[", ...
37.53125
0.002435
def _extract_domain_from_file(cls): """ Extract all non commented lines from the file we are testing. :return: The elements to test. :rtype: list """ # We initiate the variable which will save what we are going to return. result = [] if PyFunceble.path....
[ "def", "_extract_domain_from_file", "(", "cls", ")", ":", "# We initiate the variable which will save what we are going to return.", "result", "=", "[", "]", "if", "PyFunceble", ".", "path", ".", "isfile", "(", "PyFunceble", ".", "INTERN", "[", "\"file_to_test\"", "]", ...
35.468085
0.001751
def get_my_credits(self, access_token=None, user_id=None): """ Get the credits by user to use in the QX Platform """ if access_token: self.req.credential.set_token(access_token) if user_id: self.req.credential.set_user_id(user_id) if not self.check...
[ "def", "get_my_credits", "(", "self", ",", "access_token", "=", "None", ",", "user_id", "=", "None", ")", ":", "if", "access_token", ":", "self", ".", "req", ".", "credential", ".", "set_token", "(", "access_token", ")", "if", "user_id", ":", "self", "."...
43.25
0.002262
def external_program_check( to_check=frozenset([PSQL_BIN, LZOP_BIN, PV_BIN])): """ Validates the existence and basic working-ness of other programs Implemented because it is easy to get confusing error output when one does not install a dependency because of the fork-worker model that is both n...
[ "def", "external_program_check", "(", "to_check", "=", "frozenset", "(", "[", "PSQL_BIN", ",", "LZOP_BIN", ",", "PV_BIN", "]", ")", ")", ":", "could_not_run", "=", "[", "]", "error_msgs", "=", "[", "]", "def", "psql_err_handler", "(", "popen", ")", ":", ...
36.786885
0.000868
def cancel(): """HTTP endpoint for canceling tasks If an active task is cancelled, an inactive task with the same code and the smallest interval will be activated if it exists. """ task_id = request.form['id'] task = Task.query.get(task_id) if not task: return json.dumps({ 'status': 'success',...
[ "def", "cancel", "(", ")", ":", "task_id", "=", "request", ".", "form", "[", "'id'", "]", "task", "=", "Task", ".", "query", ".", "get", "(", "task_id", ")", "if", "not", "task", ":", "return", "json", ".", "dumps", "(", "{", "'status'", ":", "'s...
22.428571
0.013431
def unflat_map(func, unflat_items, vectorized=False, **kwargs): r""" Uses an ibeis lookup function with a non-flat rowid list. In essence this is equivilent to [list(map(func, _items)) for _items in unflat_items]. The utility of this function is that it only calls method once. This is more efficient...
[ "def", "unflat_map", "(", "func", ",", "unflat_items", ",", "vectorized", "=", "False", ",", "*", "*", "kwargs", ")", ":", "import", "utool", "as", "ut", "# First flatten the list, and remember the original dimensions", "flat_items", ",", "reverse_list", "=", "ut", ...
38.08
0.001024
def fix_raw_path(path): """Prettify name of path :param path: path to fix :return: Good name for path """ double_path_separator = PATH_SEPARATOR + PATH_SEPARATOR while path.find( double_path_separator) >= 0: # there are double separators path = path.replace(double_path_sepa...
[ "def", "fix_raw_path", "(", "path", ")", ":", "double_path_separator", "=", "PATH_SEPARATOR", "+", "PATH_SEPARATOR", "while", "path", ".", "find", "(", "double_path_separator", ")", ">=", "0", ":", "# there are double separators", "path", "=", "path", ".", "replac...
30.125
0.002012
def _update_aes(self): ''' Check to see if a fresh AES key is available and update the components of the worker ''' if salt.master.SMaster.secrets['aes']['secret'].value != self.crypticle.key_string: self.crypticle = salt.crypt.Crypticle(self.opts, salt.master.SMaster...
[ "def", "_update_aes", "(", "self", ")", ":", "if", "salt", ".", "master", ".", "SMaster", ".", "secrets", "[", "'aes'", "]", "[", "'secret'", "]", ".", "value", "!=", "self", ".", "crypticle", ".", "key_string", ":", "self", ".", "crypticle", "=", "s...
43.222222
0.010076
def sdiffstore(self, destkey, key, *keys): """Subtract multiple sets and store the resulting set in a key.""" return self.execute(b'SDIFFSTORE', destkey, key, *keys)
[ "def", "sdiffstore", "(", "self", ",", "destkey", ",", "key", ",", "*", "keys", ")", ":", "return", "self", ".", "execute", "(", "b'SDIFFSTORE'", ",", "destkey", ",", "key", ",", "*", "keys", ")" ]
59.666667
0.01105