text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def get_experiment_info(self): """Get a dictionary with information about this experiment. Contains: * *name*: the name * *sources*: a list of sources (filename, md5) * *dependencies*: a list of package dependencies (name, version) :return: experiment information ...
[ "def", "get_experiment_info", "(", "self", ")", ":", "dependencies", "=", "set", "(", ")", "sources", "=", "set", "(", ")", "for", "ing", ",", "_", "in", "self", ".", "traverse_ingredients", "(", ")", ":", "dependencies", "|=", "ing", ".", "dependencies"...
31.8
17.857143
def get_templates(load_all=True, **kwargs): """ Get all templates. Args: load_all Boolean: Returns just the template entry or the full template structure (template types and type attrs) Returns: List of Template objects """ if load_all is False: templa...
[ "def", "get_templates", "(", "load_all", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "load_all", "is", "False", ":", "templates", "=", "db", ".", "DBSession", ".", "query", "(", "Template", ")", ".", "all", "(", ")", "else", ":", "templates...
34.642857
24.357143
def get_hex_chain(self, index): """Assemble and return the chain leading from a given node to the merkle root of this tree with hash values in hex form """ return [(codecs.encode(i[0], 'hex_codec'), i[1]) for i in self.get_chain(index)]
[ "def", "get_hex_chain", "(", "self", ",", "index", ")", ":", "return", "[", "(", "codecs", ".", "encode", "(", "i", "[", "0", "]", ",", "'hex_codec'", ")", ",", "i", "[", "1", "]", ")", "for", "i", "in", "self", ".", "get_chain", "(", "index", ...
52.8
12.2
def bank_bins_from_cli(opts): """ Parses the CLI options related to binning templates in the bank. Parameters ---------- opts : object Result of parsing the CLI with OptionParser. Results ------- bins_idx : dict A dict with bin names as key and an array of their indices as ...
[ "def", "bank_bins_from_cli", "(", "opts", ")", ":", "bank", "=", "{", "}", "fp", "=", "h5py", ".", "File", "(", "opts", ".", "bank_file", ")", "for", "key", "in", "fp", ".", "keys", "(", ")", ":", "bank", "[", "key", "]", "=", "fp", "[", "key",...
29.538462
21.730769
def __create_object_body(kind, obj_class, spec_creator, name, namespace, metadata, spec, source, template, ...
[ "def", "__create_object_body", "(", "kind", ",", "obj_class", ",", "spec_creator", ",", "name", ",", "namespace", ",", "metadata", ",", "spec", ",", "source", ",", "template", ",", "saltenv", ")", ":", "if", "source", ":", "src_obj", "=", "__read_and_render_...
32.645161
13.225806
def teletex_search_function(name): """ Search function for teletex codec that is passed to codecs.register() """ if name != 'teletex': return None return codecs.CodecInfo( name='teletex', encode=TeletexCodec().encode, decode=TeletexCodec().decode, incrementa...
[ "def", "teletex_search_function", "(", "name", ")", ":", "if", "name", "!=", "'teletex'", ":", "return", "None", "return", "codecs", ".", "CodecInfo", "(", "name", "=", "'teletex'", ",", "encode", "=", "TeletexCodec", "(", ")", ".", "encode", ",", "decode"...
28.411765
14.882353
def advpng(ext_args): """Run the external program advpng on the file.""" args = _ADVPNG_ARGS + [ext_args.new_filename] extern.run_ext(args) return _PNG_FORMAT
[ "def", "advpng", "(", "ext_args", ")", ":", "args", "=", "_ADVPNG_ARGS", "+", "[", "ext_args", ".", "new_filename", "]", "extern", ".", "run_ext", "(", "args", ")", "return", "_PNG_FORMAT" ]
34
12.4
def createBlendedFolders(): """Creates the standard folders for a Blended website""" # Create the templates folder create_folder(os.path.join(cwd, "templates")) # Create the templates/assets folder create_folder(os.path.join(cwd, "templates", "assets")) # Create the templates/assets/css folder...
[ "def", "createBlendedFolders", "(", ")", ":", "# Create the templates folder", "create_folder", "(", "os", ".", "path", ".", "join", "(", "cwd", ",", "\"templates\"", ")", ")", "# Create the templates/assets folder", "create_folder", "(", "os", ".", "path", ".", "...
35.473684
18.526316
def run_sink_check(self, model, solver, threshold, implicit_sinks=True): """Run sink production check method.""" prob = solver.create_problem() # Create flux variables v = prob.namespace() for reaction_id in model.reactions: lower, upper = model.limits[reaction_id] ...
[ "def", "run_sink_check", "(", "self", ",", "model", ",", "solver", ",", "threshold", ",", "implicit_sinks", "=", "True", ")", ":", "prob", "=", "solver", ".", "create_problem", "(", ")", "# Create flux variables", "v", "=", "prob", ".", "namespace", "(", "...
40.173913
17.717391
def _check_experiment(self, name): """Check the signal type of the experiment Returns ------- True, if the signal type is supported, False otherwise Raises ------ Warning if the signal type is not supported """ with h5py.File(name=self.path, mode...
[ "def", "_check_experiment", "(", "self", ",", "name", ")", ":", "with", "h5py", ".", "File", "(", "name", "=", "self", ".", "path", ",", "mode", "=", "\"r\"", ")", "as", "h5", ":", "sigpath", "=", "\"/Experiments/{}/metadata/Signal\"", ".", "format", "("...
40.2
20.25
def get_linenumbers(functions, module, searchstr='def {}(image):\n'): """Returns a dictionary which maps function names to line numbers. Args: functions: a list of function names module: the module to look the functions up searchstr: the string to search for Returns: A di...
[ "def", "get_linenumbers", "(", "functions", ",", "module", ",", "searchstr", "=", "'def {}(image):\\n'", ")", ":", "lines", "=", "inspect", ".", "getsourcelines", "(", "module", ")", "[", "0", "]", "line_numbers", "=", "{", "}", "for", "function", "in", "f...
37.65
16.7
def _validate_cert_path(name): ''' Ensure that the certificate path, as determind from user input, is valid. ''' cmd = r"Test-Path -Path '{0}'".format(name) if not ast.literal_eval(_cmd_run(cmd=cmd)): raise SaltInvocationError(r"Invalid path specified: {0}".format(name))
[ "def", "_validate_cert_path", "(", "name", ")", ":", "cmd", "=", "r\"Test-Path -Path '{0}'\"", ".", "format", "(", "name", ")", "if", "not", "ast", ".", "literal_eval", "(", "_cmd_run", "(", "cmd", "=", "cmd", ")", ")", ":", "raise", "SaltInvocationError", ...
36.625
25.625
def norm_name(build_module: str, target_name: str): """Return a normalized canonical target name for the `target_name` observed in build module `build_module`. A normalized canonical target name is of the form "<build module>:<name>", where <build module> is the relative normalized path from the pro...
[ "def", "norm_name", "(", "build_module", ":", "str", ",", "target_name", ":", "str", ")", ":", "if", "':'", "not", "in", "target_name", ":", "raise", "ValueError", "(", "\"Must provide fully-qualified target name (with `:') to avoid \"", "\"possible ambiguity - `{}' not v...
44.111111
20.833333
def listen(self, timeout=10): """ Listen for incoming messages. Timeout is used to check if the server must be switched off. :param timeout: Socket Timeout in seconds """ self._socket.settimeout(float(timeout)) while not self.stopped.isSet(): try: ...
[ "def", "listen", "(", "self", ",", "timeout", "=", "10", ")", ":", "self", ".", "_socket", ".", "settimeout", "(", "float", "(", "timeout", ")", ")", "while", "not", "self", ".", "stopped", ".", "isSet", "(", ")", ":", "try", ":", "data", ",", "c...
38.363636
16.181818
def apply_mtd(self, mtd, *args, cont=False, tag=None, **kwargs): """Call the method `mtd` on both sides of the equation That is, the left-hand-side and right-hand-side are replaced by:: lhs=lhs.<mtd>(*args, **kwargs) rhs=rhs.<mtd>(*args, **kwargs) The `cont` and `tag` ...
[ "def", "apply_mtd", "(", "self", ",", "mtd", ",", "*", "args", ",", "cont", "=", "False", ",", "tag", "=", "None", ",", "*", "*", "kwargs", ")", ":", "new_lhs", "=", "getattr", "(", "self", ".", "lhs", ",", "mtd", ")", "(", "*", "args", ",", ...
38.6875
18.25
def read_header(filename): ''' returns a dictionary of values in the header of the given file ''' header = {} in_header = False data = nl.universal_read(filename) lines = [x.strip() for x in data.split('\n')] for line in lines: if line=="*** Header Start ***": in_header=True ...
[ "def", "read_header", "(", "filename", ")", ":", "header", "=", "{", "}", "in_header", "=", "False", "data", "=", "nl", ".", "universal_read", "(", "filename", ")", "lines", "=", "[", "x", ".", "strip", "(", ")", "for", "x", "in", "data", ".", "spl...
32.933333
12.933333
def get_object_metadata( name, extra_args=None, region=None, key=None, keyid=None, profile=None, ): ''' Get metadata about an S3 object. Returns None if the object does not exist. You can pass AWS SSE-C related args and/or RequestPayer in extra_args. CLI Example: .. co...
[ "def", "get_object_metadata", "(", "name", ",", "extra_args", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ",", ")", ":", "bucket", ",", "_", ",", "s3_key", "=", "name", "...
25.837209
21.139535
def numeric_part(s): """Returns the leading numeric part of a string. >>> numeric_part("20-alpha") 20 >>> numeric_part("foo") >>> numeric_part("16b") 16 """ m = re_numeric_part.match(s) if m: return int(m.group(1)) return None
[ "def", "numeric_part", "(", "s", ")", ":", "m", "=", "re_numeric_part", ".", "match", "(", "s", ")", "if", "m", ":", "return", "int", "(", "m", ".", "group", "(", "1", ")", ")", "return", "None" ]
18.785714
19.714286
def get_global(self): """Gets the current global evaluation result. Returns ------- names : list of str Name of the metrics. values : list of float Value of the evaluations. """ if self._has_global_stats: if self.global_num_inst ...
[ "def", "get_global", "(", "self", ")", ":", "if", "self", ".", "_has_global_stats", ":", "if", "self", ".", "global_num_inst", "==", "0", ":", "return", "(", "self", ".", "name", ",", "float", "(", "'nan'", ")", ")", "else", ":", "return", "(", "self...
29.529412
15.411765
def irregular_contour(x, y, z, func=plt.contourf, func_kwargs=dict(), grid_size=(100,100), padding_fraction=0.05, interp_method='nearest'): '''Handles interpolating irregular data to a grid, and plots it using the given func [default: contourf] See http://wiki.scipy.org...
[ "def", "irregular_contour", "(", "x", ",", "y", ",", "z", ",", "func", "=", "plt", ".", "contourf", ",", "func_kwargs", "=", "dict", "(", ")", ",", "grid_size", "=", "(", "100", ",", "100", ")", ",", "padding_fraction", "=", "0.05", ",", "interp_meth...
53.833333
19.944444
def render_check_and_set_platforms(self): """ If the check_and_set_platforms plugin is present, configure it """ phase = 'prebuild_plugins' plugin = 'check_and_set_platforms' if not self.pt.has_plugin_conf(phase, plugin): return if self.user_params.ko...
[ "def", "render_check_and_set_platforms", "(", "self", ")", ":", "phase", "=", "'prebuild_plugins'", "plugin", "=", "'check_and_set_platforms'", "if", "not", "self", ".", "pt", ".", "has_plugin_conf", "(", "phase", ",", "plugin", ")", ":", "return", "if", "self",...
38.416667
14.583333
def get_builtin_type(self, model): """Return built-in type representation of Collection. :param DomainModel model: :rtype list: """ return [item.get_data() if isinstance(item, self.related_model_cls) else item for item in self.get_value(model)]
[ "def", "get_builtin_type", "(", "self", ",", "model", ")", ":", "return", "[", "item", ".", "get_data", "(", ")", "if", "isinstance", "(", "item", ",", "self", ".", "related_model_cls", ")", "else", "item", "for", "item", "in", "self", ".", "get_value", ...
36.75
16
def nb_to_html(nb_path): """convert notebook to html""" exporter = html.HTMLExporter(template_file='full') output, resources = exporter.from_filename(nb_path) header = output.split('<head>', 1)[1].split('</head>',1)[0] body = output.split('<body>', 1)[1].split('</body>',1)[0] # http://imgur.com...
[ "def", "nb_to_html", "(", "nb_path", ")", ":", "exporter", "=", "html", ".", "HTMLExporter", "(", "template_file", "=", "'full'", ")", "output", ",", "resources", "=", "exporter", ".", "from_filename", "(", "nb_path", ")", "header", "=", "output", ".", "sp...
33.193548
21
def extract_lzma(archive, compression, cmd, verbosity, interactive, outdir): """Extract an LZMA archive.""" cmdlist = [util.shell_quote(cmd), '--format=lzma'] if verbosity > 1: cmdlist.append('-v') outfile = util.get_single_outfile(outdir, archive) cmdlist.extend(['-c', '-d', '--', util.shel...
[ "def", "extract_lzma", "(", "archive", ",", "compression", ",", "cmd", ",", "verbosity", ",", "interactive", ",", "outdir", ")", ":", "cmdlist", "=", "[", "util", ".", "shell_quote", "(", "cmd", ")", ",", "'--format=lzma'", "]", "if", "verbosity", ">", "...
45.333333
14.666667
def ParseMultiple(self, stats, file_objects, knowledge_base): """Parse the found release files.""" _ = knowledge_base # Collate files into path: contents dictionary. found_files = self._Combine(stats, file_objects) # Determine collected files and apply weighting. weights = [w for w in self.WEI...
[ "def", "ParseMultiple", "(", "self", ",", "stats", ",", "file_objects", ",", "knowledge_base", ")", ":", "_", "=", "knowledge_base", "# Collate files into path: contents dictionary.", "found_files", "=", "self", ".", "_Combine", "(", "stats", ",", "file_objects", ")...
35.041667
19.541667
def generate_cxx(module_name, code, specs=None, optimizations=None, module_dir=None): '''python + pythran spec -> c++ code returns a PythonModule object and an error checker the error checker can be used to print more detailed info on the origin of a compile error (e.g. due to bad typi...
[ "def", "generate_cxx", "(", "module_name", ",", "code", ",", "specs", "=", "None", ",", "optimizations", "=", "None", ",", "module_dir", "=", "None", ")", ":", "pm", ",", "ir", ",", "renamings", ",", "docstrings", "=", "front_middle_end", "(", "module_name...
40.922581
19.812903
def srbt(bt_address, pkts, inter=0.1, *args, **kargs): """send and receive using a bluetooth socket""" if "port" in kargs: s = conf.BTsocket(bt_address=bt_address, port=kargs.pop("port")) else: s = conf.BTsocket(bt_address=bt_address) a, b = sndrcv(s, pkts, inter=inter, *args, **kargs) ...
[ "def", "srbt", "(", "bt_address", ",", "pkts", ",", "inter", "=", "0.1", ",", "*", "args", ",", "*", "*", "kargs", ")", ":", "if", "\"port\"", "in", "kargs", ":", "s", "=", "conf", ".", "BTsocket", "(", "bt_address", "=", "bt_address", ",", "port",...
37.777778
18.777778
def parse_args(): """Parses command line arguments.""" parser = argparse.ArgumentParser( description='Tool to run attacks and defenses.') parser.add_argument('--attacks_dir', required=True, help='Location of all attacks.') parser.add_argument('--targeted_attacks_dir', required=True, ...
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Tool to run attacks and defenses.'", ")", "parser", ".", "add_argument", "(", "'--attacks_dir'", ",", "required", "=", "True", ",", "help", "=", "'Lo...
55.310345
18.413793
def html_table_from_dict(data, ordering): """ >>> ordering = ['administrators', 'key', 'leader', 'project'] >>> data = [ \ {'key': 'DEMO', 'project': 'Demo project', 'leader': 'lead@example.com', \ 'administrators': ['admin@example.com', 'root@example.com']},] >>> html_table_from_dic...
[ "def", "html_table_from_dict", "(", "data", ",", "ordering", ")", ":", "html", "=", "'<table><tbody>'", "html", "+=", "html_table_header_row", "(", "ordering", ")", "for", "row", "in", "data", ":", "html", "+=", "html_row_with_ordered_headers", "(", "row", ",", ...
31.508475
19
def login(self): """ 登陆系统,返回一个requests的session对象 :return: session with login cookies :rtype: requests.sessions.Session """ if not hasattr(self, 'session'): self.last_connect = time.time() s = requests.session() s.get('http://bkjws.sdu....
[ "def", "login", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'session'", ")", ":", "self", ".", "last_connect", "=", "time", ".", "time", "(", ")", "s", "=", "requests", ".", "session", "(", ")", "s", ".", "get", "(", "'http:...
30.333333
12.083333
def work(self, i): """ Internal function that performs the pair-counting """ n1, n2 = self.p[i] # initialize the total arrays for this process sum1 = numpy.zeros_like(self.sum1g) sum2 = 1. if not self.pts_only: sum2 = numpy.zeros_like(self.sum2g) ...
[ "def", "work", "(", "self", ",", "i", ")", ":", "n1", ",", "n2", "=", "self", ".", "p", "[", "i", "]", "# initialize the total arrays for this process", "sum1", "=", "numpy", ".", "zeros_like", "(", "self", ".", "sum1g", ")", "sum2", "=", "1.", "if", ...
33.525
18.375
def make_client(self, token): """Creates a client with specific access token pair. :param token: a tuple of access token pair ``(token, token_secret)`` or a dictionary of access token response. :returns: a :class:`requests_oauthlib.oauth1_session.OAuth1Session` ...
[ "def", "make_client", "(", "self", ",", "token", ")", ":", "if", "isinstance", "(", "token", ",", "dict", ")", ":", "access_token", "=", "token", "[", "'oauth_token'", "]", "access_token_secret", "=", "token", "[", "'oauth_token_secret'", "]", "else", ":", ...
42.8125
15.75
def fullStats(a, b): """Performs several stats on a against b, typically a is the predictions array, and b the observations array Returns: A dataFrame of stat name, stat description, result """ stats = [ ['bias', 'Bias', bias(a, b)], ['stderr', 'Standard Deviation Error', s...
[ "def", "fullStats", "(", "a", ",", "b", ")", ":", "stats", "=", "[", "[", "'bias'", ",", "'Bias'", ",", "bias", "(", "a", ",", "b", ")", "]", ",", "[", "'stderr'", ",", "'Standard Deviation Error'", ",", "stderr", "(", "a", ",", "b", ")", "]", ...
42.192308
19.076923
def _set_get_nameserver_detail(self, v, load=False): """ Setter method for get_nameserver_detail, mapped from YANG variable /brocade_nameserver_rpc/get_nameserver_detail (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_get_nameserver_detail is considered as a privat...
[ "def", "_set_get_nameserver_detail", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ...
78.16
38.04
def delete(self, uid): ''' Delete the history of certain ID. ''' if self.check_post_role()['DELETE']: pass else: return False histinfo = MWikiHist.get_by_uid(uid) if histinfo: pass else: return False ...
[ "def", "delete", "(", "self", ",", "uid", ")", ":", "if", "self", ".", "check_post_role", "(", ")", "[", "'DELETE'", "]", ":", "pass", "else", ":", "return", "False", "histinfo", "=", "MWikiHist", ".", "get_by_uid", "(", "uid", ")", "if", "histinfo", ...
24.722222
20.388889
def schedule_snapshot(self, format): """ Tell the canvas to perform a snapshot when it's finished rendering :param format: :return: """ bot = self.bot canvas = self.bot.canvas script = bot._namespace['__file__'] if script: filename = os...
[ "def", "schedule_snapshot", "(", "self", ",", "format", ")", ":", "bot", "=", "self", ".", "bot", "canvas", "=", "self", ".", "bot", ".", "canvas", "script", "=", "bot", ".", "_namespace", "[", "'__file__'", "]", "if", "script", ":", "filename", "=", ...
31.625
15.375
def getPanelStatus(self, panelName, verbose=None): """ Returns the status of the CytoPanel specified by the `panelName` parameter. :param panelName: Name of the CytoPanel :param verbose: print more :returns: 200: successful operation """ response=api(url=self._...
[ "def", "getPanelStatus", "(", "self", ",", "panelName", ",", "verbose", "=", "None", ")", ":", "response", "=", "api", "(", "url", "=", "self", ".", "___url", "+", "'ui/panels/'", "+", "str", "(", "panelName", ")", "+", "''", ",", "method", "=", "\"G...
35.083333
23.75
def create(self, resource_class, content_type): """ Creates a representer for the given combination of resource and content type. This will also find representer factories that were registered for a base class of the given resource. """ rpr_fac = self.__find_representer_f...
[ "def", "create", "(", "self", ",", "resource_class", ",", "content_type", ")", ":", "rpr_fac", "=", "self", ".", "__find_representer_factory", "(", "resource_class", ",", "content_type", ")", "if", "rpr_fac", "is", "None", ":", "# Register a representer with default...
50.533333
17.866667
def authorized_connect_apps(self): """ Access the authorized_connect_apps :returns: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppList :rtype: twilio.rest.api.v2010.account.authorized_connect_app.AuthorizedConnectAppList """ if self._authorized...
[ "def", "authorized_connect_apps", "(", "self", ")", ":", "if", "self", ".", "_authorized_connect_apps", "is", "None", ":", "self", ".", "_authorized_connect_apps", "=", "AuthorizedConnectAppList", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".",...
41.615385
18.846154
def pushover(message, token, user, title="JCVI: Job Monitor", \ priority=0, timestamp=None): """ pushover.net python API <https://pushover.net/faq#library-python> """ assert -1 <= priority <= 2, \ "Priority should be an int() between -1 and 2" if timestamp == None: ...
[ "def", "pushover", "(", "message", ",", "token", ",", "user", ",", "title", "=", "\"JCVI: Job Monitor\"", ",", "priority", "=", "0", ",", "timestamp", "=", "None", ")", ":", "assert", "-", "1", "<=", "priority", "<=", "2", ",", "\"Priority should be an int...
28.566667
15.633333
def file_type_stats(config): ''' returns a kba.pipeline "transform" function that generates file type stats from the stream_items that it sees. Currently, these stats are just the first five non-whitespace characters. ''' ## make a closure around config def _file_type_stats(stream_item, con...
[ "def", "file_type_stats", "(", "config", ")", ":", "## make a closure around config", "def", "_file_type_stats", "(", "stream_item", ",", "context", ")", ":", "if", "stream_item", ".", "body", "and", "stream_item", ".", "body", ".", "raw", ":", "#print repr(stream...
48.23913
21.456522
def value2rgba(x:float, cmap:Callable=cm.RdYlGn, alpha_mult:float=1.0)->Tuple: "Convert a value `x` from 0 to 1 (inclusive) to an RGBA tuple according to `cmap` times transparency `alpha_mult`." c = cmap(x) rgb = (np.array(c[:-1]) * 255).astype(int) a = c[-1] * alpha_mult return tuple(rgb.tolist() +...
[ "def", "value2rgba", "(", "x", ":", "float", ",", "cmap", ":", "Callable", "=", "cm", ".", "RdYlGn", ",", "alpha_mult", ":", "float", "=", "1.0", ")", "->", "Tuple", ":", "c", "=", "cmap", "(", "x", ")", "rgb", "=", "(", "np", ".", "array", "("...
53.333333
27.666667
def send(self): """ self.data format: {metric_name: [(t1, val1), (t2, val2)]} """ buf_sz = 500 to_send = {} for mn in self.data.iterkeys(): while len(self.data[mn]) > 0: l = len(to_send) if l < buf_sz: to_send.setdefault(mn...
[ "def", "send", "(", "self", ")", ":", "buf_sz", "=", "500", "to_send", "=", "{", "}", "for", "mn", "in", "self", ".", "data", ".", "iterkeys", "(", ")", ":", "while", "len", "(", "self", ".", "data", "[", "mn", "]", ")", ">", "0", ":", "l", ...
38.558824
17.941176
def acceptText(self): """ Emits the editing finished signals for this widget. """ if not self.signalsBlocked(): self.textEntered.emit(self.toPlainText()) self.htmlEntered.emit(self.toHtml()) self.returnPressed.emit()
[ "def", "acceptText", "(", "self", ")", ":", "if", "not", "self", ".", "signalsBlocked", "(", ")", ":", "self", ".", "textEntered", ".", "emit", "(", "self", ".", "toPlainText", "(", ")", ")", "self", ".", "htmlEntered", ".", "emit", "(", "self", ".",...
35.5
8.25
def writeBaseToProto(self, proto): """Save the state maintained by the Model base class :param proto: capnp ModelProto message builder """ inferenceType = self.getInferenceType() # lower-case first letter to be compatible with capnproto enum naming inferenceType = inferenceType[:1].lower() + in...
[ "def", "writeBaseToProto", "(", "self", ",", "proto", ")", ":", "inferenceType", "=", "self", ".", "getInferenceType", "(", ")", "# lower-case first letter to be compatible with capnproto enum naming", "inferenceType", "=", "inferenceType", "[", ":", "1", "]", ".", "l...
38.266667
16.333333
def solve_tsp(V,c): """solve_tsp -- solve the traveling salesman problem - start with assignment model - check flow from a source to every other node; - if no flow, a sub-cycle has been found --> add cut - otherwise, the solution is optimal Parameters: - V: set/list of ...
[ "def", "solve_tsp", "(", "V", ",", "c", ")", ":", "def", "addcut", "(", "X", ")", ":", "for", "sink", "in", "V", "[", "1", ":", "]", ":", "mflow", "=", "maxflow", "(", "V", ",", "X", ",", "V", "[", "0", "]", ",", "sink", ")", "mflow", "."...
33.4
21.706667
def _raw_request(self, method_name, region, url, query_params): """ Sends a request through the BaseApi instance provided, injecting the provided endpoint_name into the method call, so the caller doesn't have to. :param string method_name: The name of the calling method :param ...
[ "def", "_raw_request", "(", "self", ",", "method_name", ",", "region", ",", "url", ",", "query_params", ")", ":", "return", "self", ".", "_base_api", ".", "raw_request", "(", "self", ".", "_endpoint_name", ",", "method_name", ",", "region", ",", "url", ","...
51.615385
27
def _base_query(self, session): """Base query for a target. Args: session: database session to query in """ return session.query(ORMTargetMarker) \ .filter(ORMTargetMarker.name == self.name) \ .filter(ORMTargetMarker.params == self.params)
[ "def", "_base_query", "(", "self", ",", "session", ")", ":", "return", "session", ".", "query", "(", "ORMTargetMarker", ")", ".", "filter", "(", "ORMTargetMarker", ".", "name", "==", "self", ".", "name", ")", ".", "filter", "(", "ORMTargetMarker", ".", "...
33.333333
14
def from_params(cls, params): """Returns Params streams given a dictionary of parameters Args: params (dict): Dictionary of parameters Returns: List of Params streams """ key_fn = lambda x: id(x[1].owner) streams = [] for _, group in grou...
[ "def", "from_params", "(", "cls", ",", "params", ")", ":", "key_fn", "=", "lambda", "x", ":", "id", "(", "x", "[", "1", "]", ".", "owner", ")", "streams", "=", "[", "]", "for", "_", ",", "group", "in", "groupby", "(", "sorted", "(", "params", "...
34.75
16
def IsNameBased(link): """Finds whether the link is name based or not :param str link: :return: True if link is name-based; otherwise, False. :rtype: boolean """ if not link: return False # trimming the leading "/" if link.startswith('/') and len(link) > 1: lin...
[ "def", "IsNameBased", "(", "link", ")", ":", "if", "not", "link", ":", "return", "False", "# trimming the leading \"/\"", "if", "link", ".", "startswith", "(", "'/'", ")", "and", "len", "(", "link", ")", ">", "1", ":", "link", "=", "link", "[", "1", ...
25.371429
21.8
def add_adsorbate(self, molecule, ads_coord, repeat=None, reorient=True): """ Adds an adsorbate at a particular coordinate. Adsorbate represented by a Molecule object, and is positioned relative to the input adsorbate coordinate. Args: molecule (Molecule): molecule ...
[ "def", "add_adsorbate", "(", "self", ",", "molecule", ",", "ads_coord", ",", "repeat", "=", "None", ",", "reorient", "=", "True", ")", ":", "if", "reorient", ":", "# Reorient the molecule along slab m_index", "sop", "=", "get_rot", "(", "self", ".", "slab", ...
49.064516
20.612903
def _align_intervals(int_hier, lab_hier, t_min=0.0, t_max=None): '''Align a hierarchical annotation to span a fixed start and end time. Parameters ---------- int_hier : list of list of intervals lab_hier : list of list of str Hierarchical segment annotations, encoded as a list of li...
[ "def", "_align_intervals", "(", "int_hier", ",", "lab_hier", ",", "t_min", "=", "0.0", ",", "t_max", "=", "None", ")", ":", "return", "[", "list", "(", "_", ")", "for", "_", "in", "zip", "(", "*", "[", "util", ".", "adjust_intervals", "(", "np", "....
38.75
22.464286
def compute_index_key(self, to_instance): ''' Compute the index key that can be used to identify an instance on the link. ''' kwargs = dict() for attr in self.key_map.values(): if _is_null(to_instance, attr): return None ...
[ "def", "compute_index_key", "(", "self", ",", "to_instance", ")", ":", "kwargs", "=", "dict", "(", ")", "for", "attr", "in", "self", ".", "key_map", ".", "values", "(", ")", ":", "if", "_is_null", "(", "to_instance", ",", "attr", ")", ":", "return", ...
32.625
17.5
def add_item_languages(self, item, languages): """ Update the TransItemLanguage model with the selected languages :param item: :param languages: :return: """ # get the langs we have to add to the TransModelLanguage qs = TransLanguage.objects.filter(code__...
[ "def", "add_item_languages", "(", "self", ",", "item", ",", "languages", ")", ":", "# get the langs we have to add to the TransModelLanguage", "qs", "=", "TransLanguage", ".", "objects", ".", "filter", "(", "code__in", "=", "languages", ")", "new_langs", "=", "[", ...
36.529412
20.647059
def stop(self, **kwargs): """Stop the environment. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabStopError: If the operation failed """ path = '%s/%s/...
[ "def", "stop", "(", "self", ",", "*", "*", "kwargs", ")", ":", "path", "=", "'%s/%s/stop'", "%", "(", "self", ".", "manager", ".", "path", ",", "self", ".", "get_id", "(", ")", ")", "self", ".", "manager", ".", "gitlab", ".", "http_post", "(", "p...
33.75
21.333333
def console_width(kwargs): """"Determine console_width.""" if sys.platform.startswith('win'): console_width = _find_windows_console_width() else: console_width = _find_unix_console_width() _width = kwargs.get('width', None) if _width: console_width = _width else: ...
[ "def", "console_width", "(", "kwargs", ")", ":", "if", "sys", ".", "platform", ".", "startswith", "(", "'win'", ")", ":", "console_width", "=", "_find_windows_console_width", "(", ")", "else", ":", "console_width", "=", "_find_unix_console_width", "(", ")", "_...
24.0625
18.5
def find_medium_metabolites(model): """Return the list of metabolites ingested/excreted by the model.""" return [met.id for rxn in model.medium for met in model.reactions.get_by_id(rxn).metabolites]
[ "def", "find_medium_metabolites", "(", "model", ")", ":", "return", "[", "met", ".", "id", "for", "rxn", "in", "model", ".", "medium", "for", "met", "in", "model", ".", "reactions", ".", "get_by_id", "(", "rxn", ")", ".", "metabolites", "]" ]
53.75
8.25
def zone_create_or_update(name, resource_group, **kwargs): ''' .. versionadded:: Fluorine Creates or updates a DNS zone. Does not modify DNS records within the zone. :param name: The name of the DNS zone to create (without a terminating dot). :param resource_group: The name of the resource group....
[ "def", "zone_create_or_update", "(", "name", ",", "resource_group", ",", "*", "*", "kwargs", ")", ":", "# DNS zones are global objects", "kwargs", "[", "'location'", "]", "=", "'global'", "dnsconn", "=", "__utils__", "[", "'azurearm.get_client'", "]", "(", "'dns'"...
35.372549
28.470588
def _fetch(self): ''' Fetch the repo. If the local copy was updated, return True. If the local copy was already up-to-date, return False. ''' origin = self.repo.remotes[0] refs_pre = self.repo.listall_references() fetch_kwargs = {} # pygit2 radically chang...
[ "def", "_fetch", "(", "self", ")", ":", "origin", "=", "self", ".", "repo", ".", "remotes", "[", "0", "]", "refs_pre", "=", "self", ".", "repo", ".", "listall_references", "(", ")", "fetch_kwargs", "=", "{", "}", "# pygit2 radically changed fetchiing in 0.23...
42.03125
19.25
def find_invalid_venues(all_items): """Find venues assigned slots that aren't on the allowed list of days.""" venues = {} for item in all_items: valid = False item_days = list(item.venue.days.all()) for slot in item.slots.all(): for day in item_days: ...
[ "def", "find_invalid_venues", "(", "all_items", ")", ":", "venues", "=", "{", "}", "for", "item", "in", "all_items", ":", "valid", "=", "False", "item_days", "=", "list", "(", "item", ".", "venue", ".", "days", ".", "all", "(", ")", ")", "for", "slot...
33.0625
9.125
def tcpdump(pktlist, dump=False, getfd=False, args=None, prog=None, getproc=False, quiet=False, use_tempfile=None, read_stdin_opts=None, linktype=None, wait=True): """Run tcpdump or tshark on a list of packets. When using ``tcpdump`` on OSX (``prog == conf.prog.tcpdump``), this uses a ...
[ "def", "tcpdump", "(", "pktlist", ",", "dump", "=", "False", ",", "getfd", "=", "False", ",", "args", "=", "None", ",", "prog", "=", "None", ",", "getproc", "=", "False", ",", "quiet", "=", "False", ",", "use_tempfile", "=", "None", ",", "read_stdin_...
39.410405
21.416185
def notify_of_external_update(self, value): """ Notify observers of a new value. value -- new value """ if value is not None and value != self.last_value: self.last_value = value self.emit('update', value)
[ "def", "notify_of_external_update", "(", "self", ",", "value", ")", ":", "if", "value", "is", "not", "None", "and", "value", "!=", "self", ".", "last_value", ":", "self", ".", "last_value", "=", "value", "self", ".", "emit", "(", "'update'", ",", "value"...
29.111111
9.111111
def deploy_db(rollback=False): """ Deploy a sqlite database from development """ if not rollback: if env.DEFAULT_DATABASE_ENGINE=='django.db.backends.sqlite3': db_dir = '/'.join([deployment_root(),'database']) db_name = ''.join([env.project_name,'_','site_1','.db']) ...
[ "def", "deploy_db", "(", "rollback", "=", "False", ")", ":", "if", "not", "rollback", ":", "if", "env", ".", "DEFAULT_DATABASE_ENGINE", "==", "'django.db.backends.sqlite3'", ":", "db_dir", "=", "'/'", ".", "join", "(", "[", "deployment_root", "(", ")", ",", ...
47.468085
26.914894
def output_to_json(sources): """Print statistics to the terminal in Json format""" results = OrderedDict() for source in sources: if source.get_is_available(): source.update() source_name = source.get_source_name() results[source_name] = source.get_sensors_summary...
[ "def", "output_to_json", "(", "sources", ")", ":", "results", "=", "OrderedDict", "(", ")", "for", "source", "in", "sources", ":", "if", "source", ".", "get_is_available", "(", ")", ":", "source", ".", "update", "(", ")", "source_name", "=", "source", "....
36.9
11.4
def create_part(self, parent, model, name=None, **kwargs): """Create a new part instance from a given model under a given parent. In order to prevent the backend from updating the frontend you may add `suppress_kevents=True` as additional keyword=value argument to this method. This will improve...
[ "def", "create_part", "(", "self", ",", "parent", ",", "model", ",", "name", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "parent", ".", "category", "!=", "Category", ".", "INSTANCE", ":", "raise", "IllegalArgumentError", "(", "\"The parent should...
44.885714
24.914286
def simDeath(self): ''' Determines which agents in the current population "die" or should be replaced. Takes no inputs, returns a Boolean array of size self.AgentCount, which has True for agents who die and False for those that survive. Returns all False by default, must be overwritten ...
[ "def", "simDeath", "(", "self", ")", ":", "print", "(", "'AgentType subclass must define method simDeath!'", ")", "who_dies", "=", "np", ".", "ones", "(", "self", ".", "AgentCount", ",", "dtype", "=", "bool", ")", "return", "who_dies" ]
37.684211
30.421053
def calculate(self, T, method): r'''Method to calculate heat capacity of a solid at temperature `T` with a given method. This method has no exception handling; see `T_dependent_property` for that. Parameters ---------- T : float Temperature at which ...
[ "def", "calculate", "(", "self", ",", "T", ",", "method", ")", ":", "if", "method", "==", "PERRY151", ":", "Cp", "=", "(", "self", ".", "PERRY151_const", "+", "self", ".", "PERRY151_lin", "*", "T", "+", "self", ".", "PERRY151_quadinv", "/", "T", "**"...
32.8
20.333333
def should_be_excluded(name, exclude_patterns): """Check if a name should be excluded. Returns True if name matches at least one of the exclude patterns in the exclude_patterns list. """ for pattern in exclude_patterns: if fnmatch.fnmatch(name, pattern): return True return ...
[ "def", "should_be_excluded", "(", "name", ",", "exclude_patterns", ")", ":", "for", "pattern", "in", "exclude_patterns", ":", "if", "fnmatch", ".", "fnmatch", "(", "name", ",", "pattern", ")", ":", "return", "True", "return", "False" ]
28.636364
16
def cli(env, identifier): """Cancel global IP.""" mgr = SoftLayer.NetworkManager(env.client) global_ip_id = helpers.resolve_id(mgr.resolve_global_ip_ids, identifier, name='global ip') if not (env.skip_confirmations or formatting.no_going_back(global_ip_id)): ...
[ "def", "cli", "(", "env", ",", "identifier", ")", ":", "mgr", "=", "SoftLayer", ".", "NetworkManager", "(", "env", ".", "client", ")", "global_ip_id", "=", "helpers", ".", "resolve_id", "(", "mgr", ".", "resolve_global_ip_ids", ",", "identifier", ",", "nam...
35.363636
21.454545
def verify(self): """ Verify the completeness of the data. Raises: ValueError: When this chat is invalid. """ if any(not i for i in (self.chat_uid, self.module_id)): raise ValueError("Chat data is incomplete.") if not isinstance(self.chat_type, Ch...
[ "def", "verify", "(", "self", ")", ":", "if", "any", "(", "not", "i", "for", "i", "in", "(", "self", ".", "chat_uid", ",", "self", ".", "module_id", ")", ")", ":", "raise", "ValueError", "(", "\"Chat data is incomplete.\"", ")", "if", "not", "isinstanc...
47.764706
21.529412
def cancel_capture(self): """ cancel capturing finger :return: bool """ command = const.CMD_CANCELCAPTURE cmd_response = self.__send_command(command) return bool(cmd_response.get('status'))
[ "def", "cancel_capture", "(", "self", ")", ":", "command", "=", "const", ".", "CMD_CANCELCAPTURE", "cmd_response", "=", "self", ".", "__send_command", "(", "command", ")", "return", "bool", "(", "cmd_response", ".", "get", "(", "'status'", ")", ")" ]
26.444444
11.333333
def _get_file_from_s3(creds, metadata, saltenv, bucket, path, cached_file_path): ''' Checks the local cache for the file, if it's old or missing go grab the file from S3 and update the cache ''' # check the local cache... if os.path.isfile(cached_file_path): file_m...
[ "def", "_get_file_from_s3", "(", "creds", ",", "metadata", ",", "saltenv", ",", "bucket", ",", "path", ",", "cached_file_path", ")", ":", "# check the local cache...", "if", "os", ".", "path", ".", "isfile", "(", "cached_file_path", ")", ":", "file_meta", "=",...
33.371429
17.485714
def find_venv_DST(): """Find where this package should be installed to in this virtualenv. For example: ``/path-to-venv/lib/python2.7/site-packages/package-name`` """ dir_path = os.path.dirname(SRC) if SYS_NAME == "Windows": DST = os.path.join(dir_path, "Lib", "site-packages", PKG_NAME) ...
[ "def", "find_venv_DST", "(", ")", ":", "dir_path", "=", "os", ".", "path", ".", "dirname", "(", "SRC", ")", "if", "SYS_NAME", "==", "\"Windows\"", ":", "DST", "=", "os", ".", "path", ".", "join", "(", "dir_path", ",", "\"Lib\"", ",", "\"site-packages\"...
35.928571
21.928571
def handle_error(index_name, keep=False): ''' Handle errors while indexing. In case of error, properly log it, remove the index and exit. If `keep` is `True`, index is not deleted. ''' # Handle keyboard interrupt signal.signal(signal.SIGINT, signal.default_int_handler) signal.signal(sign...
[ "def", "handle_error", "(", "index_name", ",", "keep", "=", "False", ")", ":", "# Handle keyboard interrupt", "signal", ".", "signal", "(", "signal", ".", "SIGINT", ",", "signal", ".", "default_int_handler", ")", "signal", ".", "signal", "(", "signal", ".", ...
32.625
17.625
def traverse(data, key, delim=defaults.DEFAULT_DELIM): ''' Traverse a dict or list using a slash delimiter target string. The target 'foo/bar/0' will return data['foo']['bar'][0] if this value exists, otherwise will return empty dict. Return None when not found. This can be used to verify if a c...
[ "def", "traverse", "(", "data", ",", "key", ",", "delim", "=", "defaults", ".", "DEFAULT_DELIM", ")", ":", "for", "each", "in", "key", ".", "split", "(", "delim", ")", ":", "if", "isinstance", "(", "data", ",", "list", ")", ":", "if", "isinstance", ...
36.314286
14.542857
def is_lambda(fun): """ Check whether the given function is a lambda function. .. testsetup:: from proso.func import is_lambda .. testcode:: def not_lambda_fun(): return 1 lambda_fun = lambda: 1 print( is_lambda(not_lambda_fun), i...
[ "def", "is_lambda", "(", "fun", ")", ":", "return", "isinstance", "(", "fun", ",", "type", "(", "LAMBDA", ")", ")", "and", "fun", ".", "__name__", "==", "LAMBDA", ".", "__name__" ]
19.1
24.833333
def _tempfilepager(generator, cmd, color): """Page through text by invoking a program on a temporary file.""" import tempfile filename = tempfile.mktemp() # TODO: This never terminates if the passed generator never terminates. text = "".join(generator) if not color: text = strip_ansi(tex...
[ "def", "_tempfilepager", "(", "generator", ",", "cmd", ",", "color", ")", ":", "import", "tempfile", "filename", "=", "tempfile", ".", "mktemp", "(", ")", "# TODO: This never terminates if the passed generator never terminates.", "text", "=", "\"\"", ".", "join", "(...
35.666667
13.266667
def create_valid_aggregation(layer): """Create a local copy of the aggregation layer and try to make it valid. We need to make the layer valid if we can. We got some issues with DKI Jakarta dataset : Districts and Subdistricts layers. See issue : https://github.com/inasafe/inasafe/issues/3713 :par...
[ "def", "create_valid_aggregation", "(", "layer", ")", ":", "cleaned", "=", "create_memory_layer", "(", "'aggregation'", ",", "layer", ".", "geometryType", "(", ")", ",", "layer", ".", "crs", "(", ")", ",", "layer", ".", "fields", "(", ")", ")", "# We trans...
31.285714
19.785714
def orfs(self, frame=0, revcomp=False): '''Returns a list of ORFs that the sequence has, starting on the given frame. Each returned ORF is an interval.Interval object. If revomp=True, then finds the ORFs of the reverse complement of the sequence.''' assert frame in [0,1,...
[ "def", "orfs", "(", "self", ",", "frame", "=", "0", ",", "revcomp", "=", "False", ")", ":", "assert", "frame", "in", "[", "0", ",", "1", ",", "2", "]", "if", "revcomp", ":", "self", ".", "revcomp", "(", ")", "aa_seq", "=", "self", ".", "transla...
35.2
20.56
def build_image_from_git(self, url, image, git_path=None, git_commit=None, copy_dockerfile_to=None, stream=False, use_cache=False): """ build image from provided url and tag it this operation is asynchronous and you should consume return...
[ "def", "build_image_from_git", "(", "self", ",", "url", ",", "image", ",", "git_path", "=", "None", ",", "git_commit", "=", "None", ",", "copy_dockerfile_to", "=", "None", ",", "stream", "=", "False", ",", "use_cache", "=", "False", ")", ":", "logger", "...
46.75
21.75
def reload(self, *fields, **kwargs): """Reloads all attributes from the database. :param fields: (optional) args list of fields to reload :param max_depth: (optional) depth of dereferencing to follow .. versionadded:: 0.1.2 .. versionchanged:: 0.6 Now chainable .. versio...
[ "def", "reload", "(", "self", ",", "*", "fields", ",", "*", "*", "kwargs", ")", ":", "max_depth", "=", "1", "if", "fields", "and", "isinstance", "(", "fields", "[", "0", "]", ",", "int", ")", ":", "max_depth", "=", "fields", "[", "0", "]", "field...
39.891304
18.608696
def create_cluster(self, name, version=None, fullVersion=None): """ Create a new cluster. @param name: Cluster name. @param version: Cluster major CDH version, e.g. 'CDH5'. Ignored if fullVersion is specified. @param fullVersion: Complete CDH version, e.g. '5.1.2'. Overrides major versi...
[ "def", "create_cluster", "(", "self", ",", "name", ",", "version", "=", "None", ",", "fullVersion", "=", "None", ")", ":", "return", "clusters", ".", "create_cluster", "(", "self", ",", "name", ",", "version", ",", "fullVersion", ")" ]
36.75
17.083333
def assertSameType(a, b): """ Raises an exception if @b is not an instance of type(@a) """ if not isinstance(b, type(a)): raise NotImplementedError("This operation is only supported for " \ "elements of the same type. Instead found {} and {}". format(type(a), type(b))...
[ "def", "assertSameType", "(", "a", ",", "b", ")", ":", "if", "not", "isinstance", "(", "b", ",", "type", "(", "a", ")", ")", ":", "raise", "NotImplementedError", "(", "\"This operation is only supported for \"", "\"elements of the same type. Instead found {} and {}\""...
39.25
12.75
def save_portfolio(self, datetime, portfolio): ''' Store in Rethinkdb a zipline.Portfolio object ''' log.debug('Saving portfolio in database') pf = dbutils.portfolio_to_dict(portfolio) pf.pop('positions') data = [{ "name": self.name, "time"...
[ "def", "save_portfolio", "(", "self", ",", "datetime", ",", "portfolio", ")", ":", "log", ".", "debug", "(", "'Saving portfolio in database'", ")", "pf", "=", "dbutils", ".", "portfolio_to_dict", "(", "portfolio", ")", "pf", ".", "pop", "(", "'positions'", "...
35.5
14.875
def formfield(self, **kwargs): """Gets the form field associated with this field.""" defaults = { 'form_class': LocalizedIntegerFieldForm } defaults.update(kwargs) return super().formfield(**defaults)
[ "def", "formfield", "(", "self", ",", "*", "*", "kwargs", ")", ":", "defaults", "=", "{", "'form_class'", ":", "LocalizedIntegerFieldForm", "}", "defaults", ".", "update", "(", "kwargs", ")", "return", "super", "(", ")", ".", "formfield", "(", "*", "*", ...
30.75
15.625
def get_func(self, path): """ :return: (func, methods) """ for url_match, func_pair in self._urls_regex_map.items(): m = url_match.match(path) if m is not None: return func_pair.func, func_pair.methods, m.groupdict() return None, None, None
[ "def", "get_func", "(", "self", ",", "path", ")", ":", "for", "url_match", ",", "func_pair", "in", "self", ".", "_urls_regex_map", ".", "items", "(", ")", ":", "m", "=", "url_match", ".", "match", "(", "path", ")", "if", "m", "is", "not", "None", "...
34.666667
11.333333
def set_option(self, name, val, action=Empty, opts=Empty): """Determine which options were specified outside of the defaults""" if action is Empty and opts is Empty: self.specified.append(name) super(SpecRegister, self).set_option(name, val) else: super(SpecRe...
[ "def", "set_option", "(", "self", ",", "name", ",", "val", ",", "action", "=", "Empty", ",", "opts", "=", "Empty", ")", ":", "if", "action", "is", "Empty", "and", "opts", "is", "Empty", ":", "self", ".", "specified", ".", "append", "(", "name", ")"...
51.857143
14.714286
def get_params_from_page(path, file_name, method_count): """ This function accesses the rendered content. We must do this because how the params are not defined in the docs, but rather the rendered HTML """ # open the rendered file. file_name = file_name.replace(".rst", "") file_...
[ "def", "get_params_from_page", "(", "path", ",", "file_name", ",", "method_count", ")", ":", "# open the rendered file.", "file_name", "=", "file_name", ".", "replace", "(", "\".rst\"", ",", "\"\"", ")", "file_path", "=", "\"{0}/../_build/html/endpoints/{1}/index.html\"...
36.833333
14.266667
def subsample(self, key, order='random', auto_resize=False, ID=None): """ Allows arbitrary slicing (subsampling) of the data. .. note:: When using order='random', the sampling is random for each of the measurements in the collection. Parameters --------...
[ "def", "subsample", "(", "self", ",", "key", ",", "order", "=", "'random'", ",", "auto_resize", "=", "False", ",", "ID", "=", "None", ")", ":", "def", "func", "(", "well", ")", ":", "return", "well", ".", "subsample", "(", "key", "=", "key", ",", ...
28.347826
23.913043
def flush(self, multithread=True, **kwargs): ''' Flushes the internal write buffer. ''' if self._write_buf.tell() > 0: data = self._write_buf.getvalue() self._write_buf = BytesIO() if multithread: self._async_upload_part_request(data, ...
[ "def", "flush", "(", "self", ",", "multithread", "=", "True", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "_write_buf", ".", "tell", "(", ")", ">", "0", ":", "data", "=", "self", ".", "_write_buf", ".", "getvalue", "(", ")", "self", "."...
35.869565
19.347826
def palette_image(self): """ PIL weird interface for making a paletted image: create an image which already has the palette, and use that in Image.quantize. This function returns this palette image. """ if self.pimage is None: palette = [] for i in range(s...
[ "def", "palette_image", "(", "self", ")", ":", "if", "self", ".", "pimage", "is", "None", ":", "palette", "=", "[", "]", "for", "i", "in", "range", "(", "self", ".", "NETSIZE", ")", ":", "palette", ".", "extend", "(", "self", ".", "colormap", "[", ...
40.2
15.2
def create_xml(self, useNamespace=False): """Create an ElementTree representation of the object.""" UNTL_NAMESPACE = 'http://digital2.library.unt.edu/untl/' UNTL = '{%s}' % UNTL_NAMESPACE NSMAP = {'untl': UNTL_NAMESPACE} if useNamespace: root = Element(UNTL + self.t...
[ "def", "create_xml", "(", "self", ",", "useNamespace", "=", "False", ")", ":", "UNTL_NAMESPACE", "=", "'http://digital2.library.unt.edu/untl/'", "UNTL", "=", "'{%s}'", "%", "UNTL_NAMESPACE", "NSMAP", "=", "{", "'untl'", ":", "UNTL_NAMESPACE", "}", "if", "useNamesp...
35.045455
14.818182
def _body_builder(self, kwargs): """ Helper method to construct the appropriate SOAP-body to call a FritzBox-Service. """ p = { 'action_name': self.name, 'service_type': self.service_type, 'arguments': '', } if kwargs: ...
[ "def", "_body_builder", "(", "self", ",", "kwargs", ")", ":", "p", "=", "{", "'action_name'", ":", "self", ".", "name", ",", "'service_type'", ":", "self", ".", "service_type", ",", "'arguments'", ":", "''", ",", "}", "if", "kwargs", ":", "arguments", ...
31.055556
13.944444
def find_network_by_name(self, si, path, name): """ Finds network in the vCenter or returns "None" :param si: pyvmomi 'ServiceInstance' :param path: the path to find the object ('dc' or 'dc/folder' or 'dc/folder/folder/etc...') :param name: the datastore name...
[ "def", "find_network_by_name", "(", "self", ",", "si", ",", "path", ",", "name", ")", ":", "return", "self", ".", "find_obj_by_path", "(", "si", ",", "path", ",", "name", ",", "self", ".", "Network", ")" ]
44.555556
19.888889
def topological_sort(self): """ Returns a topological ordering of the DAG. Returns: list: A list of topologically sorted nodes in the graph. Raises: ValueError: Raised if the graph is not acyclic. """ graph = self.graph in_degree = {} fo...
[ "def", "topological_sort", "(", "self", ")", ":", "graph", "=", "self", ".", "graph", "in_degree", "=", "{", "}", "for", "u", "in", "graph", ":", "in_degree", "[", "u", "]", "=", "0", "for", "u", "in", "graph", ":", "for", "v", "in", "graph", "["...
25.540541
17.405405
def read_blacklist (self): """ Read a previously stored blacklist from file fd. """ with codecs.open(self.filename, 'r', self.output_encoding, self.codec_errors) as fd: for line in fd: line = line.rstrip() if line.start...
[ "def", "read_blacklist", "(", "self", ")", ":", "with", "codecs", ".", "open", "(", "self", ".", "filename", ",", "'r'", ",", "self", ".", "output_encoding", ",", "self", ".", "codec_errors", ")", "as", "fd", ":", "for", "line", "in", "fd", ":", "lin...
38.25
10.25
def resolve_polytomy(self, default_dist=0.0, default_support=0.0, recursive=True): """ Resolve all polytomies under current node by creating an arbitrary dicotomic structure among the affected nodes. This function randomly modifies current tree topology and shou...
[ "def", "resolve_polytomy", "(", "self", ",", "default_dist", "=", "0.0", ",", "default_support", "=", "0.0", ",", "recursive", "=", "True", ")", ":", "def", "_resolve", "(", "node", ")", ":", "if", "len", "(", "node", ".", "children", ")", ">", "2", ...
37.85
17.45
def is_empty(self): """ Check whether this interval is empty. :rtype: bool """ if self.bounds[1] < self.bounds[0]: return True if self.bounds[1] == self.bounds[0]: return not (self.included[0] and self.included[1])
[ "def", "is_empty", "(", "self", ")", ":", "if", "self", ".", "bounds", "[", "1", "]", "<", "self", ".", "bounds", "[", "0", "]", ":", "return", "True", "if", "self", ".", "bounds", "[", "1", "]", "==", "self", ".", "bounds", "[", "0", "]", ":...
27.8
13.2
def main(): """ Commandline interface to rerank nbest lists. """ log.setup_main_logger(console=True, file_logging=False) log.log_sockeye_version(logger) params = argparse.ArgumentParser(description="Rerank nbest lists of translations." " Rerankin...
[ "def", "main", "(", ")", ":", "log", ".", "setup_main_logger", "(", "console", "=", "True", ",", "file_logging", "=", "False", ")", "log", ".", "log_sockeye_version", "(", "logger", ")", "params", "=", "argparse", ".", "ArgumentParser", "(", "description", ...
34.625
25
def delete_cgroup(self, name): """ Delete a cgroup by name and detach it from this node. Raises OSError if the cgroup is not empty. """ name = name.encode() fp = os.path.join(self.full_path, name) if os.path.exists(fp): os.rmdir(fp) node = Node...
[ "def", "delete_cgroup", "(", "self", ",", "name", ")", ":", "name", "=", "name", ".", "encode", "(", ")", "fp", "=", "os", ".", "path", ".", "join", "(", "self", ".", "full_path", ",", "name", ")", "if", "os", ".", "path", ".", "exists", "(", "...
30.285714
11