text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def gff3_to_dataframe(path, attributes=None, region=None, score_fill=-1, phase_fill=-1, attributes_fill='.', tabix='tabix', **kwargs): """Load data from a GFF3 into a pandas DataFrame. Parameters ---------- path : string Path to input file. attributes : list of strings...
[ "def", "gff3_to_dataframe", "(", "path", ",", "attributes", "=", "None", ",", "region", "=", "None", ",", "score_fill", "=", "-", "1", ",", "phase_fill", "=", "-", "1", ",", "attributes_fill", "=", "'.'", ",", "tabix", "=", "'tabix'", ",", "*", "*", ...
34.348837
24.255814
def to_gexf(graph, output_path): """Writes graph to `GEXF <http://gexf.net>`_. Uses the NetworkX method `write_gexf <http://networkx.lanl.gov/reference/generated/networkx.readwrite.gexf.write_gexf.html>`_. Parameters ---------- graph : networkx.Graph The Graph to be exported to GEXF. ...
[ "def", "to_gexf", "(", "graph", ",", "output_path", ")", ":", "warnings", ".", "warn", "(", "\"Removed in 0.8.\"", ",", "DeprecationWarning", ")", "graph", "=", "_strip_list_attributes", "(", "graph", ")", "nx", ".", "write_gexf", "(", "graph", ",", "output_pa...
32.35
20.35
def keypair_add(self, name, pubfile=None, pubkey=None): ''' Add a keypair ''' nt_ks = self.compute_conn if pubfile: with salt.utils.files.fopen(pubfile, 'r') as fp_: pubkey = salt.utils.stringutils.to_unicode(fp_.read()) if not pubkey: ...
[ "def", "keypair_add", "(", "self", ",", "name", ",", "pubfile", "=", "None", ",", "pubkey", "=", "None", ")", ":", "nt_ks", "=", "self", ".", "compute_conn", "if", "pubfile", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "pubfil...
34.230769
19
def validate(cls, mapper_spec): """Validate mapper specification. Args: mapper_spec: an instance of model.MapperSpec Raises: BadReaderParamsError: if the specification is invalid for any reason such as missing the bucket name or providing an invalid bucket name. """ reader_spec...
[ "def", "validate", "(", "cls", ",", "mapper_spec", ")", ":", "reader_spec", "=", "cls", ".", "get_params", "(", "mapper_spec", ",", "allow_old", "=", "False", ")", "# Bucket Name is required", "if", "cls", ".", "BUCKET_NAME_PARAM", "not", "in", "reader_spec", ...
37.909091
13.136364
def setBendLength(self, x): """ set bend length :param x: new bend length to be assigned, [m] :return: None """ if x != self.bend_length: self.bend_length = x self.refresh = True
[ "def", "setBendLength", "(", "self", ",", "x", ")", ":", "if", "x", "!=", "self", ".", "bend_length", ":", "self", ".", "bend_length", "=", "x", "self", ".", "refresh", "=", "True" ]
26.111111
12.111111
def linear_reaction_coefficients(model, reactions=None): """Coefficient for the reactions in a linear objective. Parameters ---------- model : cobra model the model object that defined the objective reactions : list an optional list for the reactions to get the coefficients for. All...
[ "def", "linear_reaction_coefficients", "(", "model", ",", "reactions", "=", "None", ")", ":", "linear_coefficients", "=", "{", "}", "reactions", "=", "model", ".", "reactions", "if", "not", "reactions", "else", "reactions", "try", ":", "objective_expression", "=...
38
20.9375
def _rand_sparse(m, n, density, format='csr'): """Construct base function for sprand, sprandn.""" nnz = max(min(int(m*n*density), m*n), 0) row = np.random.randint(low=0, high=m-1, size=nnz) col = np.random.randint(low=0, high=n-1, size=nnz) data = np.ones(nnz, dtype=float) # duplicate (i,j) en...
[ "def", "_rand_sparse", "(", "m", ",", "n", ",", "density", ",", "format", "=", "'csr'", ")", ":", "nnz", "=", "max", "(", "min", "(", "int", "(", "m", "*", "n", "*", "density", ")", ",", "m", "*", "n", ")", ",", "0", ")", "row", "=", "np", ...
40.6
16
def __set_config_value(self, key, value): """Sets a value for a room config""" self.check_owner() params = {"room": self.room_id, "config": to_json({key: value})} resp = self.conn.make_api_call("setRoomConfig", params) if "error" in resp: raise RuntimeError(f"{resp['...
[ "def", "__set_config_value", "(", "self", ",", "key", ",", "value", ")", ":", "self", ".", "check_owner", "(", ")", "params", "=", "{", "\"room\"", ":", "self", ".", "room_id", ",", "\"config\"", ":", "to_json", "(", "{", "key", ":", "value", "}", ")...
41.555556
20.666667
def append_search_summary(xmldoc, process, shared_object = "standalone", lalwrapper_cvs_tag = "", lal_cvs_tag = "", comment = None, ifos = None, inseg = None, outseg = None, nevents = 0, nnodes = 1): """ Append search summary information associated with the given process to the search summary table in xmldoc. Retur...
[ "def", "append_search_summary", "(", "xmldoc", ",", "process", ",", "shared_object", "=", "\"standalone\"", ",", "lalwrapper_cvs_tag", "=", "\"\"", ",", "lal_cvs_tag", "=", "\"\"", ",", "comment", "=", "None", ",", "ifos", "=", "None", ",", "inseg", "=", "No...
37.28
24.24
def _get_chat(self) -> Dict: """ As Telegram changes where the chat object is located in the response, this method tries to be smart about finding it in the right place. """ if 'callback_query' in self._update: query = self._update['callback_query'] if 'm...
[ "def", "_get_chat", "(", "self", ")", "->", "Dict", ":", "if", "'callback_query'", "in", "self", ".", "_update", ":", "query", "=", "self", ".", "_update", "[", "'callback_query'", "]", "if", "'message'", "in", "query", ":", "return", "query", "[", "'mes...
37.473684
13.368421
def load_dict_from_yaml(path): """ Loads a dictionary from a yaml file :param path: the absolute path of the target yaml file :return: """ f = file(path, 'r') dictionary = yaml.load(f) f.close() return dictionary
[ "def", "load_dict_from_yaml", "(", "path", ")", ":", "f", "=", "file", "(", "path", ",", "'r'", ")", "dictionary", "=", "yaml", ".", "load", "(", "f", ")", "f", ".", "close", "(", ")", "return", "dictionary" ]
23.9
13.1
def tokenize(self): """ Tokenizes the string stored in the parser object into a list of tokens. """ self.token_list = [] ps = self.parse_string.strip() i = 0 last_token = None while i < len(ps) and ps[i].isspace(): i += 1 wh...
[ "def", "tokenize", "(", "self", ")", ":", "self", ".", "token_list", "=", "[", "]", "ps", "=", "self", ".", "parse_string", ".", "strip", "(", ")", "i", "=", "0", "last_token", "=", "None", "while", "i", "<", "len", "(", "ps", ")", "and", "ps", ...
32.735849
19.716981
def end_output (self, **kwargs): """Write edges and end of checking info as gml comment.""" self.write_edges() self.end_graph() if self.has_part("outro"): self.write_outro() self.close_fileoutput()
[ "def", "end_output", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "write_edges", "(", ")", "self", ".", "end_graph", "(", ")", "if", "self", ".", "has_part", "(", "\"outro\"", ")", ":", "self", ".", "write_outro", "(", ")", "self", ...
34.714286
9
def viewport(self): """Rect: The drawing area for rendering on the current target.""" viewport = rect.Rect(0, 0, 0, 0) check_int_err(lib.SDL_RenderGetViewport(self._ptr, viewport._ptr)) return viewport
[ "def", "viewport", "(", "self", ")", ":", "viewport", "=", "rect", ".", "Rect", "(", "0", ",", "0", ",", "0", ",", "0", ")", "check_int_err", "(", "lib", ".", "SDL_RenderGetViewport", "(", "self", ".", "_ptr", ",", "viewport", ".", "_ptr", ")", ")"...
45.8
14.4
def _mapping(self): """Fetch the entire mapping for the specified index. Returns: dict: The full mapping for the index. """ return (self.__search_client.get( "/unstable/index/{}/mapping".format(mdf_toolbox.translate_index(self.index))) ["m...
[ "def", "_mapping", "(", "self", ")", ":", "return", "(", "self", ".", "__search_client", ".", "get", "(", "\"/unstable/index/{}/mapping\"", ".", "format", "(", "mdf_toolbox", ".", "translate_index", "(", "self", ".", "index", ")", ")", ")", "[", "\"mappings\...
35.777778
18.111111
def match_color_index(self, color): """Takes an "R,G,B" string or wx.Color and returns a matching xlwt color. """ from jcvi.utils.webcolors import color_diff if isinstance(color, int): return color if color: if isinstance(color, six.string_types): ...
[ "def", "match_color_index", "(", "self", ",", "color", ")", ":", "from", "jcvi", ".", "utils", ".", "webcolors", "import", "color_diff", "if", "isinstance", "(", "color", ",", "int", ")", ":", "return", "color", "if", "color", ":", "if", "isinstance", "(...
39.166667
12.333333
def bind_super(self, opr): """ 为超级管理员授权所有权限 """ for path in self.routes: route = self.routes.get(path) route['oprs'].append(opr)
[ "def", "bind_super", "(", "self", ",", "opr", ")", ":", "for", "path", "in", "self", ".", "routes", ":", "route", "=", "self", ".", "routes", ".", "get", "(", "path", ")", "route", "[", "'oprs'", "]", ".", "append", "(", "opr", ")" ]
28.5
4.333333
def _get_member_file_data(member_data, id_filename=False): """ Helper function to get file data of member of a project. :param member_data: This field is data related to member in a project. """ file_data = {} for datafile in member_data['data']: if id_filena...
[ "def", "_get_member_file_data", "(", "member_data", ",", "id_filename", "=", "False", ")", ":", "file_data", "=", "{", "}", "for", "datafile", "in", "member_data", "[", "'data'", "]", ":", "if", "id_filename", ":", "basename", "=", "'{}.{}'", ".", "format", ...
40.411765
16.764706
def set_border(self, thickness, color="black"): """ Sets the border thickness and color. :param int thickness: The thickenss of the border. :param str color: The color of the border. """ self._set_tk_config("highlightthickness", thickness) ...
[ "def", "set_border", "(", "self", ",", "thickness", ",", "color", "=", "\"black\"", ")", ":", "self", ".", "_set_tk_config", "(", "\"highlightthickness\"", ",", "thickness", ")", "self", ".", "_set_tk_config", "(", "\"highlightbackground\"", ",", "utils", ".", ...
31.75
14.916667
def _rainbow_lines( self, text, freq=0.1, spread=3.0, offset=0, movefactor=0, rgb_mode=False, **colorargs): """ Create rainbow text, using the same offset for each line. Arguments: text : String to colorize. freq : Frequency/"tightn...
[ "def", "_rainbow_lines", "(", "self", ",", "text", ",", "freq", "=", "0.1", ",", "spread", "=", "3.0", ",", "offset", "=", "0", ",", "movefactor", "=", "0", ",", "rgb_mode", "=", "False", ",", "*", "*", "colorargs", ")", ":", "if", "not", "movefact...
40.72973
14.945946
def destroy_vm(self, vm, logger): """ destroy the given vm :param vm: virutal machine pyvmomi object :param logger: """ self.power_off_before_destroy(logger, vm) logger.info(("Destroying VM {0}".format(vm.name))) task = vm.Destroy_Task() retu...
[ "def", "destroy_vm", "(", "self", ",", "vm", ",", "logger", ")", ":", "self", ".", "power_off_before_destroy", "(", "logger", ",", "vm", ")", "logger", ".", "info", "(", "(", "\"Destroying VM {0}\"", ".", "format", "(", "vm", ".", "name", ")", ")", ")"...
30.230769
19.692308
def FoldByteStream(self, mapped_value, **unused_kwargs): # pylint: disable=redundant-returns-doc """Folds the data type into a byte stream. Args: mapped_value (object): mapped value. Returns: bytes: byte stream. Raises: FoldingError: if the data type definition cannot be folded int...
[ "def", "FoldByteStream", "(", "self", ",", "mapped_value", ",", "*", "*", "unused_kwargs", ")", ":", "# pylint: disable=redundant-returns-doc", "raise", "errors", ".", "FoldingError", "(", "'Unable to fold {0:s} data type into byte stream'", ".", "format", "(", "self", ...
30.875
23.4375
def is_correct(self): """Check if the Daterange is correct : weekdays are valid :return: True if weekdays are valid, False otherwise :rtype: bool """ valid = True valid &= self.swday in range(7) if not valid: logger.error("Error: %s is not a valid day...
[ "def", "is_correct", "(", "self", ")", ":", "valid", "=", "True", "valid", "&=", "self", ".", "swday", "in", "range", "(", "7", ")", "if", "not", "valid", ":", "logger", ".", "error", "(", "\"Error: %s is not a valid day\"", ",", "self", ".", "swday", ...
29.5625
19.6875
def _build_command(self): """ Command to start the Dynamips hypervisor process. (to be passed to subprocess.Popen()) """ command = [self._path] command.extend(["-N1"]) # use instance IDs for filenames command.extend(["-l", "dynamips_i{}_log.txt".format(self._id)...
[ "def", "_build_command", "(", "self", ")", ":", "command", "=", "[", "self", ".", "_path", "]", "command", ".", "extend", "(", "[", "\"-N1\"", "]", ")", "# use instance IDs for filenames", "command", ".", "extend", "(", "[", "\"-l\"", ",", "\"dynamips_i{}_lo...
43.411765
20.352941
def _extract_log_probs(num_states, dist): """Tabulate log probabilities from a batch of distributions.""" states = tf.reshape(tf.range(num_states), tf.concat([[num_states], tf.ones_like(dist.batch_shape_tensor())], axis=0)) re...
[ "def", "_extract_log_probs", "(", "num_states", ",", "dist", ")", ":", "states", "=", "tf", ".", "reshape", "(", "tf", ".", "range", "(", "num_states", ")", ",", "tf", ".", "concat", "(", "[", "[", "num_states", "]", ",", "tf", ".", "ones_like", "(",...
47.5
14.375
def image(self, height=1, module_width=1, add_quiet_zone=True): """Get the barcode as PIL.Image. By default the image is one pixel high and the number of modules pixels wide, with 10 empty modules added to each side to act as the quiet zone. The size can be modified by setting height and module...
[ "def", "image", "(", "self", ",", "height", "=", "1", ",", "module_width", "=", "1", ",", "add_quiet_zone", "=", "True", ")", ":", "if", "Image", "is", "None", ":", "raise", "Code128", ".", "MissingDependencyError", "(", "\"PIL module is required to use image ...
44.548387
28.516129
def main(): '''Calculate the distance of an object in centimeters using a HCSR04 sensor and a Raspberry Pi. This script allows for a quicker reading by decreasing the number of samples and forcing the readings to be taken at quicker intervals.''' trig_pin = 17 echo_pin = 27 # Cre...
[ "def", "main", "(", ")", ":", "trig_pin", "=", "17", "echo_pin", "=", "27", "# Create a distance reading with the hcsr04 sensor module", "value", "=", "sensor", ".", "Measurement", "(", "trig_pin", ",", "echo_pin", ")", "# The default sample_size is 11 and sample_wait is...
42.269231
25.961538
def resource_of_node(resources, node): """ Returns resource of node. """ for resource in resources: model = getattr(resource, 'model', None) if type(node) == model: return resource return BasePageResource
[ "def", "resource_of_node", "(", "resources", ",", "node", ")", ":", "for", "resource", "in", "resources", ":", "model", "=", "getattr", "(", "resource", ",", "'model'", ",", "None", ")", "if", "type", "(", "node", ")", "==", "model", ":", "return", "re...
30.125
6.875
def update_membercard(self, code, card_id, **kwargs): """ 更新会员信息 详情请参见 https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1451025283 注意事项: 1.开发者可以同时传入add_bonus和bonus解决由于同步失败带来的幂等性问题。同时传入add_bonus和bonus时 add_bonus作为积分变动消息中的变量值,而bonus作为卡面上的总积分额度显示。余额变动同理。 ...
[ "def", "update_membercard", "(", "self", ",", "code", ",", "card_id", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "update", "(", "{", "'code'", ":", "code", ",", "'card_id'", ":", "card_id", ",", "}", ")", "return", "self", ".", "_post", "(", ...
29.773585
17.849057
def process(self): """ This method handles the actual processing of Modules and Transforms """ self.modules.sort(key=lambda x: x.priority) for module in self.modules: transforms = module.transform(self.data) transforms.sort(key=lambda x: x.linenum, revers...
[ "def", "process", "(", "self", ")", ":", "self", ".", "modules", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", ".", "priority", ")", "for", "module", "in", "self", ".", "modules", ":", "transforms", "=", "module", ".", "transform", "(", "s...
33.933333
20.066667
def file_change_history(self, branch='master', limit=None, days=None, ignore_globs=None, include_globs=None): """ Returns a DataFrame of all file changes (via the commit history) for the specified branch. This is similar to the commit history DataFrame, but is one row per file edit rather than ...
[ "def", "file_change_history", "(", "self", ",", "branch", "=", "'master'", ",", "limit", "=", "None", ",", "days", "=", "None", ",", "ignore_globs", "=", "None", ",", "include_globs", "=", "None", ")", ":", "# setup the dataset of commits", "if", "limit", "i...
44.654321
24.703704
def create(self, recording_status_callback_event=values.unset, recording_status_callback=values.unset, recording_status_callback_method=values.unset, trim=values.unset, recording_channels=values.unset): """ Create a new RecordingInstance :param unico...
[ "def", "create", "(", "self", ",", "recording_status_callback_event", "=", "values", ".", "unset", ",", "recording_status_callback", "=", "values", ".", "unset", ",", "recording_status_callback_method", "=", "values", ".", "unset", ",", "trim", "=", "values", ".",...
44.916667
27.75
def process_schema(doc, resource, df): """Add schema entiries to a metatab doc from a dataframe""" from rowgenerators import SourceError from requests.exceptions import ConnectionError from metapack.cli.core import extract_path_name, alt_col_name, type_map from tableintuit import TypeIntuiter f...
[ "def", "process_schema", "(", "doc", ",", "resource", ",", "df", ")", ":", "from", "rowgenerators", "import", "SourceError", "from", "requests", ".", "exceptions", "import", "ConnectionError", "from", "metapack", ".", "cli", ".", "core", "import", "extract_path_...
35.962963
26.203704
def find(self, *args, **kwargs): " new query builder on current db" return Query(*args, db=self, schema=self.schema)
[ "def", "find", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "Query", "(", "*", "args", ",", "db", "=", "self", ",", "schema", "=", "self", ".", "schema", ")" ]
40.666667
7.333333
def draw(title, subtitle, author, cover_width=400, cover_height=600): """ Main drawing function, which generates a cover of the given dimension and renders title, author, and graphics. """ # Based on some initial constants and the title+author strings, generate a base # background color and a s...
[ "def", "draw", "(", "title", ",", "subtitle", ",", "author", ",", "cover_width", "=", "400", ",", "cover_height", "=", "600", ")", ":", "# Based on some initial constants and the title+author strings, generate a base", "# background color and a shape color to draw onto the back...
45.235099
24.592715
def OIDC_UNAUTHENTICATED_SESSION_MANAGEMENT_KEY(self): """ OPTIONAL. Supply a fixed string to use as browser-state key for unauthenticated clients. """ # Memoize generated value if not self._unauthenticated_session_management_key: self._unauthenticated_session_manage...
[ "def", "OIDC_UNAUTHENTICATED_SESSION_MANAGEMENT_KEY", "(", "self", ")", ":", "# Memoize generated value", "if", "not", "self", ".", "_unauthenticated_session_management_key", ":", "self", ".", "_unauthenticated_session_management_key", "=", "''", ".", "join", "(", "random",...
48.1
23.3
def _varargs_checks_gen(self, decorated_function, function_spec, arg_specs): """ Generate checks for positional variable argument (varargs) testing :param decorated_function: function decorator :param function_spec: function inspect information :param arg_specs: argument specification (same as arg_specs in :me...
[ "def", "_varargs_checks_gen", "(", "self", ",", "decorated_function", ",", "function_spec", ",", "arg_specs", ")", ":", "inspected_varargs", "=", "function_spec", ".", "varargs", "if", "inspected_varargs", "is", "not", "None", "and", "inspected_varargs", "in", "arg_...
43
26.533333
def _generate_notebooks_by_category(notebook_object, dict_by_tag): """ Internal function that is used for generation of the page "Notebooks by Category". ---------- Parameters ---------- notebook_object : notebook object Object of "notebook" class where the body will be created. di...
[ "def", "_generate_notebooks_by_category", "(", "notebook_object", ",", "dict_by_tag", ")", ":", "# ============================ Insertion of an opening text ====================================", "markdown_cell", "=", "OPEN_IMAGE", "# == Generation of a table that group Notebooks by category...
51.882353
35.397059
def _parse_adf_output(self): """ Parse the standard ADF output file. """ numerical_freq_patt = re.compile( r"\s+\*\s+F\sR\sE\sQ\sU\sE\sN\sC\sI\sE\sS\s+\*") analytic_freq_patt = re.compile( r"\s+\*\s+F\sR\sE\sQ\sU\sE\sN\sC\sY\s+A\sN\sA\sL\sY\sS\sI\sS\s+\*")...
[ "def", "_parse_adf_output", "(", "self", ")", ":", "numerical_freq_patt", "=", "re", ".", "compile", "(", "r\"\\s+\\*\\s+F\\sR\\sE\\sQ\\sU\\sE\\sN\\sC\\sI\\sE\\sS\\s+\\*\"", ")", "analytic_freq_patt", "=", "re", ".", "compile", "(", "r\"\\s+\\*\\s+F\\sR\\sE\\sQ\\sU\\sE\\sN\\s...
42.444444
16.933333
def get_win32_short_path_name(long_name): """ Gets the short path name of a given long path. References: http://stackoverflow.com/a/23598461/200291 http://stackoverflow.com/questions/23598289/get-win-short-fname-python Example: >>> # DISABLE_DOCTEST >>> from utool.util_...
[ "def", "get_win32_short_path_name", "(", "long_name", ")", ":", "import", "ctypes", "from", "ctypes", "import", "wintypes", "_GetShortPathNameW", "=", "ctypes", ".", "windll", ".", "kernel32", ".", "GetShortPathNameW", "_GetShortPathNameW", ".", "argtypes", "=", "["...
36.131579
17.078947
def merge_required_files(dirnames, out_dir): """Merges the required files from each of the directories. :param dirnames: the list of directories to merge data from. :param out_dir: the name of the output directory. :type dirnames: list :type out_dir: str """ # The list of files to merge ...
[ "def", "merge_required_files", "(", "dirnames", ",", "out_dir", ")", ":", "# The list of files to merge", "fn_to_merge", "=", "(", "\"steps_summary.tex\"", ",", "\"excluded_markers.txt\"", ",", "\"excluded_samples.txt\"", ")", "# Merging the files", "for", "fn", "in", "fn...
36.395833
14.333333
def get_encoder(self, content_type): """ Get the encoding function for the provided content type for this bucket. :param content_type: the requested media type :type content_type: str :param content_type: Content type requested """ if content_type in self...
[ "def", "get_encoder", "(", "self", ",", "content_type", ")", ":", "if", "content_type", "in", "self", ".", "_encoders", ":", "return", "self", ".", "_encoders", "[", "content_type", "]", "else", ":", "return", "self", ".", "_client", ".", "get_encoder", "(...
33.769231
13.615385
def fit(self, x0=None, distribution='lognormal', n=None, **kwargs): '''Incomplete method to fit experimental values to a curve. It is very hard to get good initial guesses, which are really required for this. Differential evolution is promissing. This API is likely to change in the futur...
[ "def", "fit", "(", "self", ",", "x0", "=", "None", ",", "distribution", "=", "'lognormal'", ",", "n", "=", "None", ",", "*", "*", "kwargs", ")", ":", "dist", "=", "{", "'lognormal'", ":", "PSDLognormal", ",", "'GGS'", ":", "PSDGatesGaudinSchuhman", ","...
45.2
19.36
def get_queue_obj(session, queue_url, log_url): """Checks that all the data that is needed for submit verification is available.""" skip = False if not queue_url: logger.error("The queue url is not configured, skipping submit verification") skip = True if not session: logger.err...
[ "def", "get_queue_obj", "(", "session", ",", "queue_url", ",", "log_url", ")", ":", "skip", "=", "False", "if", "not", "queue_url", ":", "logger", ".", "error", "(", "\"The queue url is not configured, skipping submit verification\"", ")", "skip", "=", "True", "if...
38.923077
24.384615
def tar_to_bigfile(self, fname, outfile): """Convert tar of multiple FASTAs to one file.""" fnames = [] tmpdir = mkdtemp() # Extract files to temporary directory with tarfile.open(fname) as tar: tar.extractall(path=tmpdir) for root, _, files in os.wal...
[ "def", "tar_to_bigfile", "(", "self", ",", "fname", ",", "outfile", ")", ":", "fnames", "=", "[", "]", "tmpdir", "=", "mkdtemp", "(", ")", "# Extract files to temporary directory", "with", "tarfile", ".", "open", "(", "fname", ")", "as", "tar", ":", "tar",...
33.1
11.95
def execute_command(parser, config, ext_classes): """ Banana banana """ res = 0 cmd = config.get('command') get_private_folder = config.get('get_private_folder', False) if cmd == 'help': parser.print_help() elif cmd == 'run' or get_private_folder: # git.mk backward compat ...
[ "def", "execute_command", "(", "parser", ",", "config", ",", "ext_classes", ")", ":", "res", "=", "0", "cmd", "=", "config", ".", "get", "(", "'command'", ")", "get_private_folder", "=", "config", ".", "get", "(", "'get_private_folder'", ",", "False", ")",...
32.55
14.916667
def describe(self): """Describe the model.""" result = "No description available" if self.description: result = "%s" % self.description else: if self.__doc__: s = [] s += [self.__doc__.strip().replace('\n', ''). ...
[ "def", "describe", "(", "self", ")", ":", "result", "=", "\"No description available\"", "if", "self", ".", "description", ":", "result", "=", "\"%s\"", "%", "self", ".", "description", "else", ":", "if", "self", ".", "__doc__", ":", "s", "=", "[", "]", ...
32.666667
11.916667
def load_internal_cache(cls, pex, pex_info): """Possibly cache out the internal cache.""" internal_cache = os.path.join(pex, pex_info.internal_cache) with TRACER.timed('Searching dependency cache: %s' % internal_cache, V=2): if os.path.isdir(pex): for dist in find_distributions(internal_cache)...
[ "def", "load_internal_cache", "(", "cls", ",", "pex", ",", "pex_info", ")", ":", "internal_cache", "=", "os", ".", "path", ".", "join", "(", "pex", ",", "pex_info", ".", "internal_cache", ")", "with", "TRACER", ".", "timed", "(", "'Searching dependency cache...
45.2
20.6
def on_close(self): ''' Clean up when the connection is closed. ''' log.info('WebSocket connection closed: code=%s, reason=%r', self.close_code, self.close_reason) if self.connection is not None: self.application.client_lost(self.connection)
[ "def", "on_close", "(", "self", ")", ":", "log", ".", "info", "(", "'WebSocket connection closed: code=%s, reason=%r'", ",", "self", ".", "close_code", ",", "self", ".", "close_reason", ")", "if", "self", ".", "connection", "is", "not", "None", ":", "self", ...
40
26
def line(h1: Union[Histogram1D, "HistogramCollection"], ax: Axes, *, errors: bool = False, **kwargs): """Line plot of 1D histogram.""" show_stats = kwargs.pop("show_stats", False) show_values = kwargs.pop("show_values", False) density = kwargs.pop("density", False) cumulative = kwargs.pop("cumulat...
[ "def", "line", "(", "h1", ":", "Union", "[", "Histogram1D", ",", "\"HistogramCollection\"", "]", ",", "ax", ":", "Axes", ",", "*", ",", "errors", ":", "bool", "=", "False", ",", "*", "*", "kwargs", ")", ":", "show_stats", "=", "kwargs", ".", "pop", ...
39.142857
22.071429
def addRecordsFromThread(self, records): """ Adds the given record to the system. :param records | [<orb.Table>, ..] """ label_mapper = self.labelMapper() icon_mapper = self.iconMapper() tree = None if self.showTreeP...
[ "def", "addRecordsFromThread", "(", "self", ",", "records", ")", ":", "label_mapper", "=", "self", ".", "labelMapper", "(", ")", "icon_mapper", "=", "self", ".", "iconMapper", "(", ")", "tree", "=", "None", "if", "self", ".", "showTreePopup", "(", ")", "...
32.545455
12.666667
def add_missing_optional_args_with_value_none(args, optional_args): ''' Adds key-value pairs to the passed dictionary, so that afterwards, the dictionary can be used without needing to check for KeyErrors. If the keys passed as a second argument are not present, they are added with ...
[ "def", "add_missing_optional_args_with_value_none", "(", "args", ",", "optional_args", ")", ":", "for", "name", "in", "optional_args", ":", "if", "not", "name", "in", "args", ".", "keys", "(", ")", ":", "args", "[", "name", "]", "=", "None", "return", "arg...
31.947368
19.315789
def commit_branches(sha1): # type: (str) -> List[str] """ Get the name of the branches that this commit belongs to. """ cmd = 'git branch --contains {}'.format(sha1) return shell.run( cmd, capture=True, never_pretend=True ).stdout.strip().split()
[ "def", "commit_branches", "(", "sha1", ")", ":", "# type: (str) -> List[str]", "cmd", "=", "'git branch --contains {}'", ".", "format", "(", "sha1", ")", "return", "shell", ".", "run", "(", "cmd", ",", "capture", "=", "True", ",", "never_pretend", "=", "True",...
31.333333
13.888889
def buildIcon(icon): """ Builds an icon from the inputed information. :param icon | <variant> """ if icon is None: return QIcon() if type(icon) == buffer: try: icon = QIcon(projexui.generatePixmap(i...
[ "def", "buildIcon", "(", "icon", ")", ":", "if", "icon", "is", "None", ":", "return", "QIcon", "(", ")", "if", "type", "(", "icon", ")", "==", "buffer", ":", "try", ":", "icon", "=", "QIcon", "(", "projexui", ".", "generatePixmap", "(", "icon", ")"...
24.333333
16.142857
def get_community_by_name(self, name, token=None): """ Get a community based on its name. :param name: The name of the target community. :type name: string :param token: (optional) A valid token for the user in question. :type token: None | string :returns: The r...
[ "def", "get_community_by_name", "(", "self", ",", "name", ",", "token", "=", "None", ")", ":", "parameters", "=", "dict", "(", ")", "parameters", "[", "'name'", "]", "=", "name", "if", "token", ":", "parameters", "[", "'token'", "]", "=", "token", "res...
33.352941
13.352941
def backprop(self, input_data, df_output, cache=None): """ Backpropagate through the hidden layer **Parameters:** input_data : ``GPUArray`` Input data to compute activations for. df_output : ``GPUArray`` Gradients with respect to the activations of this layer ...
[ "def", "backprop", "(", "self", ",", "input_data", ",", "df_output", ",", "cache", "=", "None", ")", ":", "# Get cache if it wasn't provided", "if", "cache", "is", "None", ":", "cache", "=", "self", ".", "feed_forward", "(", "input_data", ",", "prediction", ...
31.5
18.65
def _fetch_dimensions(self, dataset): """ Iterate through semesters, counties and municipalities. """ yield Dimension(u"school") yield Dimension(u"year", datatype="year") yield Dimension(u"semester", datatype="academic_term", ...
[ "def", "_fetch_dimensions", "(", "self", ",", "dataset", ")", ":", "yield", "Dimension", "(", "u\"school\"", ")", "yield", "Dimension", "(", "u\"year\"", ",", "datatype", "=", "\"year\"", ")", "yield", "Dimension", "(", "u\"semester\"", ",", "datatype", "=", ...
41
4.666667
def Matches(self, file_entry): """Compares the file entry against the filter collection. Args: file_entry (dfvfs.FileEntry): file entry to compare. Returns: bool: True if the file entry matches one of the filters. If no filters are provided or applicable the result will be True. ...
[ "def", "Matches", "(", "self", ",", "file_entry", ")", ":", "if", "not", "self", ".", "_filters", ":", "return", "True", "results", "=", "[", "]", "for", "file_entry_filter", "in", "self", ".", "_filters", ":", "result", "=", "file_entry_filter", ".", "M...
28.684211
21.210526
def add(self, fig, title, minX, maxX, offsetAdjuster=None, sequenceFetcher=None): """ Find the features for a sequence title. If there aren't too many, add the features to C{fig}. Return information about the features, as described below. @param fig: A matplotlib fig...
[ "def", "add", "(", "self", ",", "fig", ",", "title", ",", "minX", ",", "maxX", ",", "offsetAdjuster", "=", "None", ",", "sequenceFetcher", "=", "None", ")", ":", "offsetAdjuster", "=", "offsetAdjuster", "or", "(", "lambda", "x", ":", "x", ")", "fig", ...
46.266667
21.5
def _download_rtd_zip(rtd_version=None, **kwargs): """ Download and extract HTML ZIP from RTD to installed doc data path. Download is skipped if content already exists. Parameters ---------- rtd_version : str or `None` RTD version to download; e.g., "latest", "stable", or "v2.6.0". ...
[ "def", "_download_rtd_zip", "(", "rtd_version", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# https://github.com/ejeschke/ginga/pull/451#issuecomment-298403134", "if", "not", "toolkit", ".", "family", ".", "startswith", "(", "'qt'", ")", ":", "raise", "ValueErr...
34.016393
21.229508
def account_following(self, id, max_id=None, min_id=None, since_id=None, limit=None): """ Fetch users the given user is following. Returns a list of `user dicts`_. """ id = self.__unpack_id(id) if max_id != None: max_id = self.__unpack_id(max_id) ...
[ "def", "account_following", "(", "self", ",", "id", ",", "max_id", "=", "None", ",", "min_id", "=", "None", ",", "since_id", "=", "None", ",", "limit", "=", "None", ")", ":", "id", "=", "self", ".", "__unpack_id", "(", "id", ")", "if", "max_id", "!...
34.052632
15.947368
def _server_property(self, attr_name): """An attribute of the current server's description. If the client is not connected, this will block until a connection is established or raise ServerSelectionTimeoutError if no server is available. Not threadsafe if used multiple times in...
[ "def", "_server_property", "(", "self", ",", "attr_name", ")", ":", "server", "=", "self", ".", "_topology", ".", "select_server", "(", "writable_server_selector", ")", "return", "getattr", "(", "server", ".", "description", ",", "attr_name", ")" ]
40.933333
21.133333
def information_title_header_element(feature, parent): """Retrieve information title header string from definitions.""" _ = feature, parent # NOQA header = information_title_header['string_format'] return header.capitalize()
[ "def", "information_title_header_element", "(", "feature", ",", "parent", ")", ":", "_", "=", "feature", ",", "parent", "# NOQA", "header", "=", "information_title_header", "[", "'string_format'", "]", "return", "header", ".", "capitalize", "(", ")" ]
47.4
9.4
def make_output_cf_compliant(self, simulation_start_datetime, comid_lat_lon_z_file="", project_name="Normal RAPID project"): """ This function converts the RAPID output to be CF compliant. This wil...
[ "def", "make_output_cf_compliant", "(", "self", ",", "simulation_start_datetime", ",", "comid_lat_lon_z_file", "=", "\"\"", ",", "project_name", "=", "\"Normal RAPID project\"", ")", ":", "with", "RAPIDDataset", "(", "self", ".", "Qout_file", ")", "as", "qout_nc", "...
37.236842
19.105263
def get_network_ipv4(self, id_network): """ Get networkipv4 :param id_network: Identifier of the Network. Integer value and greater than zero. :return: Following dictionary: :: {'network': {'id': < id_networkIpv6 >, 'network_type': < id_tipo_rede >, ...
[ "def", "get_network_ipv4", "(", "self", ",", "id_network", ")", ":", "if", "not", "is_valid_int_param", "(", "id_network", ")", ":", "raise", "InvalidParameterError", "(", "u'O id do rede ip4 foi informado incorretamente.'", ")", "url", "=", "'network/ipv4/id/'", "+", ...
32.9
16.25
def update_module_names(cr, namespec, merge_modules=False): """Deal with changed module names, making all the needed changes on the related tables, like XML-IDs, translations, and so on. :param namespec: list of tuples of (old name, new name) :param merge_modules: Specify if the operation should be a m...
[ "def", "update_module_names", "(", "cr", ",", "namespec", ",", "merge_modules", "=", "False", ")", ":", "for", "(", "old_name", ",", "new_name", ")", "in", "namespec", ":", "if", "merge_modules", ":", "# Delete meta entries, that will avoid the entry removal", "# Th...
47.815385
17.292308
def get_cmd_output(*args, encoding: str = SYS_ENCODING) -> str: """ Returns text output of a command. """ log.debug("get_cmd_output(): args = {!r}", args) p = subprocess.Popen(args, stdout=subprocess.PIPE) stdout, stderr = p.communicate() return stdout.decode(encoding, errors='ignore')
[ "def", "get_cmd_output", "(", "*", "args", ",", "encoding", ":", "str", "=", "SYS_ENCODING", ")", "->", "str", ":", "log", ".", "debug", "(", "\"get_cmd_output(): args = {!r}\"", ",", "args", ")", "p", "=", "subprocess", ".", "Popen", "(", "args", ",", "...
38.375
8.375
def btc_script_deserialize(script): """ Given a script (hex or bin), decode it into its list of opcodes and data. Return a list of strings and ints. Based on code in pybitcointools (https://github.com/vbuterin/pybitcointools) by Vitalik Buterin """ if isinstance(script, str) and re.match('...
[ "def", "btc_script_deserialize", "(", "script", ")", ":", "if", "isinstance", "(", "script", ",", "str", ")", "and", "re", ".", "match", "(", "'^[0-9a-fA-F]*$'", ",", "script", ")", ":", "script", "=", "binascii", ".", "unhexlify", "(", "script", ")", "#...
30.109091
20.763636
def match_names(self, *valist, **kwargs): """performs taxonomic name resolution. See https://github.com/OpenTreeOfLife/opentree/wiki/Open-Tree-of-Life-APIs#match_names with the exception that "ids" in the API call is referred has the name "id_list" in this function. The most commonly use...
[ "def", "match_names", "(", "self", ",", "*", "valist", ",", "*", "*", "kwargs", ")", ":", "if", "len", "(", "valist", ")", "==", "1", ":", "if", "not", "is_str_type", "(", "valist", "[", "0", "]", ")", ":", "return", "self", ".", "taxomachine", "...
66.933333
30.066667
def _remove_wire_nets(block): """ Remove all wire nodes from the block. """ wire_src_dict = _ProducerList() wire_removal_set = set() # set of all wirevectors to be removed # one pass to build the map of value producers and # all of the nets and wires to be removed for net in block.logic: ...
[ "def", "_remove_wire_nets", "(", "block", ")", ":", "wire_src_dict", "=", "_ProducerList", "(", ")", "wire_removal_set", "=", "set", "(", ")", "# set of all wirevectors to be removed", "# one pass to build the map of value producers and", "# all of the nets and wires to be remove...
38.689655
19.827586
def fetch(self, url, encoding=None, force_refetch=False, nocache=False, quiet=True): ''' Fetch a HTML file as binary''' try: if not force_refetch and self.cache is not None and url in self.cache: # try to look for content in cache logging.debug('Retrieving con...
[ "def", "fetch", "(", "self", ",", "url", ",", "encoding", "=", "None", ",", "force_refetch", "=", "False", ",", "nocache", "=", "False", ",", "quiet", "=", "True", ")", ":", "try", ":", "if", "not", "force_refetch", "and", "self", ".", "cache", "is",...
50.083333
20.972222
def get(self, endpoint, params=None): """Send an HTTP GET request to QuadrigaCX. :param endpoint: API endpoint. :type endpoint: str | unicode :param params: URL parameters. :type params: dict :return: Response body from QuadrigaCX. :rtype: dict :raise qua...
[ "def", "get", "(", "self", ",", "endpoint", ",", "params", "=", "None", ")", ":", "response", "=", "self", ".", "_session", ".", "get", "(", "url", "=", "self", ".", "_url", "+", "endpoint", ",", "params", "=", "params", ",", "timeout", "=", "self"...
33.470588
11.294118
def insert(self, point, payload): """! @brief Insert new point with payload to kd-tree. @param[in] point (list): Coordinates of the point of inserted node. @param[in] payload (any-type): Payload of inserted node. It can be identificator of the node or s...
[ "def", "insert", "(", "self", ",", "point", ",", "payload", ")", ":", "if", "self", ".", "__root", "is", "None", ":", "self", ".", "__dimension", "=", "len", "(", "point", ")", "self", ".", "__root", "=", "node", "(", "point", ",", "payload", ",", ...
42.772727
20.022727
def clean(self, value): """Cleans and returns the given value, or raises a ParameterNotValidError exception""" if isinstance(value, (list, tuple)): return [super(FeatureCollectionParameter, self).clean(x) for x in value] raise ParameterNotValidError
[ "def", "clean", "(", "self", ",", "value", ")", ":", "if", "isinstance", "(", "value", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "[", "super", "(", "FeatureCollectionParameter", ",", "self", ")", ".", "clean", "(", "x", ")", "for", "...
40.142857
21.285714
def register_elastic_task(self, *args, **kwargs): """Register an elastic task.""" kwargs["task_class"] = ElasticTask return self.register_task(*args, **kwargs)
[ "def", "register_elastic_task", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "\"task_class\"", "]", "=", "ElasticTask", "return", "self", ".", "register_task", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
45
5.25
def list_nodes_min(call=None): ''' Return a list of the VMs that are on the provider. Only a list of VM names and their state is returned. This is the minimum amount of information needed to check for existing VMs. .. versionadded:: 2015.8.0 CLI Example: .. code-block:: bash salt...
[ "def", "list_nodes_min", "(", "call", "=", "None", ")", ":", "if", "call", "==", "'action'", ":", "raise", "SaltCloudSystemExit", "(", "'The list_nodes_min function must be called with -f or --function.'", ")", "ret", "=", "{", "}", "nodes", "=", "_query", "(", "'...
25.969697
25.787879
def cache(self): """Call a user defined query and cache the results""" if not self._bucket_width or self._untrusted_time is None: raise ValueError('QueryCompute must be initialized with a bucket_width ' 'and an untrusted_time in order to write to the cache.') now = datetime.dat...
[ "def", "cache", "(", "self", ")", ":", "if", "not", "self", ".", "_bucket_width", "or", "self", ".", "_untrusted_time", "is", "None", ":", "raise", "ValueError", "(", "'QueryCompute must be initialized with a bucket_width '", "'and an untrusted_time in order to write to t...
44.416667
22.833333
def supports_export(self, exported_configs, service_intents, export_props): """ Method called by rsa.export_service to ask if this ExportDistributionProvider supports export for given exported_configs (list), service_intents (list), and export_props (dict). If a ExportCo...
[ "def", "supports_export", "(", "self", ",", "exported_configs", ",", "service_intents", ",", "export_props", ")", ":", "return", "self", ".", "_get_or_create_container", "(", "exported_configs", ",", "service_intents", ",", "export_props", ")" ]
42.8125
21.8125
def backup(file_name, jail=None, chroot=None, root=None): ''' Export installed packages into yaml+mtree file CLI Example: .. code-block:: bash salt '*' pkg.backup /tmp/pkg jail Backup packages from the specified jail. Note that this will run the command within the jail, a...
[ "def", "backup", "(", "file_name", ",", "jail", "=", "None", ",", "chroot", "=", "None", ",", "root", "=", "None", ")", ":", "ret", "=", "__salt__", "[", "'cmd.run'", "]", "(", "_pkg", "(", "jail", ",", "chroot", ",", "root", ")", "+", "[", "'bac...
28.8
27.777778
def compare_and_update_config(config, update_config, changes, namespace=''): ''' Recursively compare two configs, writing any needed changes to the update_config and capturing changes in the changes dict. ''' if isinstance(config, dict): if not update_config: if config: ...
[ "def", "compare_and_update_config", "(", "config", ",", "update_config", ",", "changes", ",", "namespace", "=", "''", ")", ":", "if", "isinstance", "(", "config", ",", "dict", ")", ":", "if", "not", "update_config", ":", "if", "config", ":", "# the updated c...
37.888889
15.282828
def deleter(self, func): """Register a delete function for the DynamicProperty This function may only take one argument, self. """ if not callable(func): raise TypeError('deleter must be callable function') if hasattr(func, '__code__') and func.__code__.co_argcount !...
[ "def", "deleter", "(", "self", ",", "func", ")", ":", "if", "not", "callable", "(", "func", ")", ":", "raise", "TypeError", "(", "'deleter must be callable function'", ")", "if", "hasattr", "(", "func", ",", "'__code__'", ")", "and", "func", ".", "__code__...
42.769231
18.769231
def do_ams_put(endpoint, path, body, access_token, rformat="json", ds_min_version="3.0;NetFx"): '''Do a AMS HTTP PUT request and return JSON. Args: endpoint (str): Azure Media Services Initial Endpoint. path (str): Azure Media Services Endpoint Path. body (str): Azure Media Services Con...
[ "def", "do_ams_put", "(", "endpoint", ",", "path", ",", "body", ",", "access_token", ",", "rformat", "=", "\"json\"", ",", "ds_min_version", "=", "\"3.0;NetFx\"", ")", ":", "min_ds", "=", "dsversion_min", "content_acceptformat", "=", "json_acceptformat", "if", "...
47.15625
19.28125
def args(self): """Parse args if they have not already been parsed and return the Namespace for args. .. Note:: Accessing args should only be done directly in the App. Returns: (namespace): ArgParser parsed arguments. """ if not self._parsed: # only resolve once ...
[ "def", "args", "(", "self", ")", ":", "if", "not", "self", ".", "_parsed", ":", "# only resolve once", "self", ".", "_default_args", ",", "unknown", "=", "self", ".", "parser", ".", "parse_known_args", "(", ")", "# when running locally retrieve any args from the r...
35.16
23.08
def message_worker(device): """Loop through messages and pass them on to right device""" _LOGGER.debug("Starting Worker Thread.") msg_q = device.messages while True: if not msg_q.empty(): message = msg_q.get() data = {} try: data = json.load...
[ "def", "message_worker", "(", "device", ")", ":", "_LOGGER", ".", "debug", "(", "\"Starting Worker Thread.\"", ")", "msg_q", "=", "device", ".", "messages", "while", "True", ":", "if", "not", "msg_q", ".", "empty", "(", ")", ":", "message", "=", "msg_q", ...
30.4
19.36
def add_service_certificate(self, service_name, data, certificate_format, password=None): ''' Adds a certificate to a hosted service. service_name: Name of the hosted service. data: The base-64 encoded form of the pfx/cer file. ...
[ "def", "add_service_certificate", "(", "self", ",", "service_name", ",", "data", ",", "certificate_format", ",", "password", "=", "None", ")", ":", "_validate_not_none", "(", "'service_name'", ",", "service_name", ")", "_validate_not_none", "(", "'data'", ",", "da...
39.04
18.32
def process_post_tags(self, bulk_mode, api_post, post_tags): """ Create or update Tags related to a post. :param bulk_mode: If True, minimize db operations by bulk creating post objects :param api_post: the API data for the post :param post_tags: a mapping of Tags keyed by post ...
[ "def", "process_post_tags", "(", "self", ",", "bulk_mode", ",", "api_post", ",", "post_tags", ")", ":", "post_tags", "[", "api_post", "[", "\"ID\"", "]", "]", "=", "[", "]", "for", "api_tag", "in", "six", ".", "itervalues", "(", "api_post", "[", "\"tags\...
40.928571
16.785714
async def communicate(self, data_id=None, run_sync=False, save_settings=True): """Scan database for resolving Data objects and process them. This is submitted as a task to the manager's channel workers. :param data_id: Optional id of Data object which (+ its children) should be pro...
[ "async", "def", "communicate", "(", "self", ",", "data_id", "=", "None", ",", "run_sync", "=", "False", ",", "save_settings", "=", "True", ")", ":", "executor", "=", "getattr", "(", "settings", ",", "'FLOW_EXECUTOR'", ",", "{", "}", ")", ".", "get", "(...
44.948276
21.810345
def _generate_shape(word: str) -> str: """ Recreate shape from a token input by user Args: word: str Returns: str """ def counting_stars(w) -> List[int]: count = [1] for i in range(1, len(w)): if w[i - 1] == w[i]: ...
[ "def", "_generate_shape", "(", "word", ":", "str", ")", "->", "str", ":", "def", "counting_stars", "(", "w", ")", "->", "List", "[", "int", "]", ":", "count", "=", "[", "1", "]", "for", "i", "in", "range", "(", "1", ",", "len", "(", "w", ")", ...
22.103448
16.724138
def fit(self, y, exogenous=None): """Fit the transformer Computes the periods of all the Fourier terms. The values of ``y`` are not actually used; only the periodicity is used when computing Fourier terms. Parameters ---------- y : array-like or None, shape=(n_s...
[ "def", "fit", "(", "self", ",", "y", ",", "exogenous", "=", "None", ")", ":", "# Since we don't fit any params here, we can just check the params", "_", ",", "_", "=", "self", ".", "_check_y_exog", "(", "y", ",", "exogenous", ",", "null_allowed", "=", "True", ...
36.04878
25.536585
def log_commit( self, block_id, vtxindex, op, opcode, op_data ): """ Log a committed operation """ debug_op = self.sanitize_op( op_data ) if 'history' in debug_op: del debug_op['history'] log.debug("COMMIT %s (%s) at (%s, %s) data: %s", opcode, op, block_id...
[ "def", "log_commit", "(", "self", ",", "block_id", ",", "vtxindex", ",", "op", ",", "opcode", ",", "op_data", ")", ":", "debug_op", "=", "self", ".", "sanitize_op", "(", "op_data", ")", "if", "'history'", "in", "debug_op", ":", "del", "debug_op", "[", ...
33.153846
22.846154
def node_has_namespaces(node: BaseEntity, namespaces: Set[str]) -> bool: """Pass for nodes that have one of the given namespaces.""" ns = node.get(NAMESPACE) return ns is not None and ns in namespaces
[ "def", "node_has_namespaces", "(", "node", ":", "BaseEntity", ",", "namespaces", ":", "Set", "[", "str", "]", ")", "->", "bool", ":", "ns", "=", "node", ".", "get", "(", "NAMESPACE", ")", "return", "ns", "is", "not", "None", "and", "ns", "in", "names...
52.25
12.5
def _collapse_variants_by_function(graph: BELGraph, func: str) -> None: """Collapse all of the given functions' variants' edges to their parents, in-place.""" for parent_node, variant_node, data in graph.edges(data=True): if data[RELATION] == HAS_VARIANT and parent_node.function == func: col...
[ "def", "_collapse_variants_by_function", "(", "graph", ":", "BELGraph", ",", "func", ":", "str", ")", "->", "None", ":", "for", "parent_node", ",", "variant_node", ",", "data", "in", "graph", ".", "edges", "(", "data", "=", "True", ")", ":", "if", "data"...
75.6
25.6
def rotation_matrix(angle, direction, point=None): """ Returns matrix to rotate about axis defined by point and direction. Examples: >>> angle = (random.random() - 0.5) * (2*math.pi) >>> direc = numpy.random.random(3) - 0.5 >>> point = numpy.random.random(3) - 0.5 >>> R0 = ...
[ "def", "rotation_matrix", "(", "angle", ",", "direction", ",", "point", "=", "None", ")", ":", "sina", "=", "math", ".", "sin", "(", "angle", ")", "cosa", "=", "math", ".", "cos", "(", "angle", ")", "direction", "=", "unit_vector", "(", "direction", ...
33.489796
18.959184
def refresh(self, force: bool = False) -> bool: """ Loads the cauldron.json definition file for the project and populates the project with the loaded data. Any existing data will be overwritten, if the new definition file differs from the previous one. If the project has already...
[ "def", "refresh", "(", "self", ",", "force", ":", "bool", "=", "False", ")", "->", "bool", ":", "lm", "=", "self", ".", "last_modified", "is_newer", "=", "lm", "is", "not", "None", "and", "lm", ">=", "os", ".", "path", ".", "getmtime", "(", "self",...
35.764706
23.607843
def _add_parser_arguments_git(self, subparsers): """Create a sub-parsers for git subcommands. """ subparsers.add_parser( "git-clone", help="Clone all defined data repositories if they dont exist.") subparsers.add_parser( "git-push", help="...
[ "def", "_add_parser_arguments_git", "(", "self", ",", "subparsers", ")", ":", "subparsers", ".", "add_parser", "(", "\"git-clone\"", ",", "help", "=", "\"Clone all defined data repositories if they dont exist.\"", ")", "subparsers", ".", "add_parser", "(", "\"git-push\"",...
31.107143
21
def _get_date_facet_counts(self, timespan, date_field, start_date=None, end_date=None): ''' Returns Range Facet counts based on ''' if 'DAY' not in timespan: raise ValueError("At this time, only DAY date range increment is supported. Aborting..... ") #Need to ...
[ "def", "_get_date_facet_counts", "(", "self", ",", "timespan", ",", "date_field", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ")", ":", "if", "'DAY'", "not", "in", "timespan", ":", "raise", "ValueError", "(", "\"At this time, only DAY date rang...
47.882353
27.823529
def merge(*args): """Implements the 'merge' operator for merging lists.""" ret = [] for arg in args: if isinstance(arg, list) or isinstance(arg, tuple): ret += list(arg) else: ret.append(arg) return ret
[ "def", "merge", "(", "*", "args", ")", ":", "ret", "=", "[", "]", "for", "arg", "in", "args", ":", "if", "isinstance", "(", "arg", ",", "list", ")", "or", "isinstance", "(", "arg", ",", "tuple", ")", ":", "ret", "+=", "list", "(", "arg", ")", ...
27.777778
18.666667
def whitespace_around_operator(logical_line): """ Avoid extraneous whitespace in the following situations: - More than one space around an assignment (or other) operator to align it with another. """ line = logical_line for operator in operators: found = line.find(' ' + operator)...
[ "def", "whitespace_around_operator", "(", "logical_line", ")", ":", "line", "=", "logical_line", "for", "operator", "in", "operators", ":", "found", "=", "line", ".", "find", "(", "' '", "+", "operator", ")", "if", "found", ">", "-", "1", ":", "return", ...
35.952381
13.47619
def _backsearch(self): """ Inspect previous peaks from the last detected qrs peak (if any), using a lower threshold """ if self.last_qrs_peak_num is not None: for peak_num in range(self.last_qrs_peak_num + 1, self.peak_num + 1): if self._is_qrs(peak_n...
[ "def", "_backsearch", "(", "self", ")", ":", "if", "self", ".", "last_qrs_peak_num", "is", "not", "None", ":", "for", "peak_num", "in", "range", "(", "self", ".", "last_qrs_peak_num", "+", "1", ",", "self", ".", "peak_num", "+", "1", ")", ":", "if", ...
41.4
20.6
def getServiceEndpoints(self, yadis_url, service_element): """Returns an iterator of endpoint objects produced by the filter functions.""" endpoints = [] # Do an expansion of the service element by xrd:Type and xrd:URI for type_uris, uri, _ in expandService(service_element): ...
[ "def", "getServiceEndpoints", "(", "self", ",", "yadis_url", ",", "service_element", ")", ":", "endpoints", "=", "[", "]", "# Do an expansion of the service element by xrd:Type and xrd:URI", "for", "type_uris", ",", "uri", ",", "_", "in", "expandService", "(", "servic...
36.722222
19.277778