text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def post_parse_action(self, entry): """separate hosts and ports after entry is parsed""" if 'source_host' in entry.keys(): host = self.ip_port_regex.findall(entry['source_host']) if host: hlist = host[0].split('.') entry['source_host'] = '.'.join(h...
[ "def", "post_parse_action", "(", "self", ",", "entry", ")", ":", "if", "'source_host'", "in", "entry", ".", "keys", "(", ")", ":", "host", "=", "self", ".", "ip_port_regex", ".", "findall", "(", "entry", "[", "'source_host'", "]", ")", "if", "host", ":...
41.1875
13.1875
def process_file(source_file): """ Extract text from a file (pdf, txt, eml, csv, json) :param source_file path to file to read :return text from file """ if source_file.endswith(('.pdf', '.PDF')): txt = extract_pdf(source_file) elif source_file.endswith(('.txt', '.eml', '.csv', '.jso...
[ "def", "process_file", "(", "source_file", ")", ":", "if", "source_file", ".", "endswith", "(", "(", "'.pdf'", ",", "'.PDF'", ")", ")", ":", "txt", "=", "extract_pdf", "(", "source_file", ")", "elif", "source_file", ".", "endswith", "(", "(", "'.txt'", "...
33.666667
14.066667
def srotate(self): """Single rotation. Assumes that balance is +-2.""" # self save save # save 3 -> 1 self -> 1 self.rot() # 1 2 2 3 # # self save save # 3 save -> self 1 -> self.rot()...
[ "def", "srotate", "(", "self", ")", ":", "# self save save", "# save 3 -> 1 self -> 1 self.rot()", "# 1 2 2 3", "#", "# self save save", "# 3 save -> self 1 -> self.rot() 1", "# 2 1 3 2", "#assert(...
41.71875
19.5
def _exec_query(self): """ Executes solr query if it hasn't already executed. Returns: Self. """ if not self._solr_locked: if not self.compiled_query: self._compile_query() try: solr_params = self._process_param...
[ "def", "_exec_query", "(", "self", ")", ":", "if", "not", "self", ".", "_solr_locked", ":", "if", "not", "self", ".", "compiled_query", ":", "self", ".", "_compile_query", "(", ")", "try", ":", "solr_params", "=", "self", ".", "_process_params", "(", ")"...
39.444444
17.37037
def permutations(x): '''Given a listlike, x, return all permutations of x Returns the permutations of x in the lexical order of their indices: e.g. >>> x = [ 1, 2, 3, 4 ] >>> for p in permutations(x): >>> print p [ 1, 2, 3, 4 ] [ 1, 2, 4, 3 ] [ 1, 3, 2, 4 ] [ 1, 3, 4, 2 ] ...
[ "def", "permutations", "(", "x", ")", ":", "#", "# The algorithm is attributed to Narayana Pandit from his", "# Ganita Kaumundi (1356). The following is from", "#", "# http://en.wikipedia.org/wiki/Permutation#Systematic_generation_of_all_permutations", "#", "# 1. Find the largest index k suc...
31.28
20.36
def statistical_axes(fit, **kw): """ Hyperbolic error using a statistical process (either sampling or noise errors) Integrates covariance with error level and degrees of freedom for plotting confidence intervals. Degrees of freedom is set to 2, which is the relevant number of independe...
[ "def", "statistical_axes", "(", "fit", ",", "*", "*", "kw", ")", ":", "method", "=", "kw", ".", "pop", "(", "'method'", ",", "'noise'", ")", "confidence_level", "=", "kw", ".", "pop", "(", "'confidence_level'", ",", "0.95", ")", "dof", "=", "kw", "."...
33.051282
15.358974
def p_gate_op_1(self, program): """ gate_op : CX id ',' id ';' """ program[0] = node.Cnot([program[2], program[4]]) self.verify_declared_bit(program[2]) self.verify_declared_bit(program[4]) self.verify_distinct([program[2], program[4]])
[ "def", "p_gate_op_1", "(", "self", ",", "program", ")", ":", "program", "[", "0", "]", "=", "node", ".", "Cnot", "(", "[", "program", "[", "2", "]", ",", "program", "[", "4", "]", "]", ")", "self", ".", "verify_declared_bit", "(", "program", "[", ...
35.625
6.625
async def servo_config(self, pin, min_pulse=544, max_pulse=2400): """ Configure a pin as a servo pin. Set pulse min, max in ms. Use this method (not set_pin_mode) to configure a pin for servo operation. :param pin: Servo Pin. :param min_pulse: Min pulse width in ms. ...
[ "async", "def", "servo_config", "(", "self", ",", "pin", ",", "min_pulse", "=", "544", ",", "max_pulse", "=", "2400", ")", ":", "command", "=", "[", "pin", ",", "min_pulse", "&", "0x7f", ",", "(", "min_pulse", ">>", "7", ")", "&", "0x7f", ",", "max...
33.166667
22.944444
def condition_from_text(text) -> Condition: """ Return a Condition instance with PEG grammar from text :param text: PEG parsable string :return: """ try: condition = pypeg2.parse(text, output.Condition) except SyntaxError: # Invalid condit...
[ "def", "condition_from_text", "(", "text", ")", "->", "Condition", ":", "try", ":", "condition", "=", "pypeg2", ".", "parse", "(", "text", ",", "output", ".", "Condition", ")", "except", "SyntaxError", ":", "# Invalid conditions are possible, see https://github.com/...
38.571429
20.142857
def merge_all_models_into_first_model(biop_structure): """Merge all existing models into a Structure's first_model attribute. This directly modifies the Biopython Structure object. Chains IDs will start from A and increment for each new chain (model that is converted). Args: biop_structure (St...
[ "def", "merge_all_models_into_first_model", "(", "biop_structure", ")", ":", "from", "string", "import", "ascii_uppercase", "idx", "=", "1", "first_model", "=", "biop_structure", "[", "0", "]", "for", "m", "in", "biop_structure", ".", "get_models", "(", ")", ":"...
32.818182
20.045455
def resolve_url(self, resource_name): """Return a URL to a local copy of a resource, suitable for get_generator() For Package URLS, resolution involves generating a URL to a data file from the package URL and the value of a resource. The resource value, the url, can be one of: - An abs...
[ "def", "resolve_url", "(", "self", ",", "resource_name", ")", ":", "u", "=", "parse_app_url", "(", "resource_name", ")", "if", "u", ".", "scheme", "!=", "'file'", ":", "t", "=", "u", "elif", "self", ".", "target_format", "==", "'csv'", "and", "self", "...
41.942308
30.057692
def get_exception_information(self, index): """ @type index: int @param index: Index into the exception information block. @rtype: int @return: Exception information DWORD. """ if index < 0 or index > win32.EXCEPTION_MAXIMUM_PARAMETERS: raise IndexE...
[ "def", "get_exception_information", "(", "self", ",", "index", ")", ":", "if", "index", "<", "0", "or", "index", ">", "win32", ".", "EXCEPTION_MAXIMUM_PARAMETERS", ":", "raise", "IndexError", "(", "\"Array index out of range: %s\"", "%", "repr", "(", "index", ")...
35.066667
17.866667
def safe_unicode(string): """If Python 2, replace non-ascii characters and return encoded string.""" if not PY3: uni = string.replace(u'\u2019', "'") return uni.encode('utf-8') return string
[ "def", "safe_unicode", "(", "string", ")", ":", "if", "not", "PY3", ":", "uni", "=", "string", ".", "replace", "(", "u'\\u2019'", ",", "\"'\"", ")", "return", "uni", ".", "encode", "(", "'utf-8'", ")", "return", "string" ]
31.571429
15
def delete(self, path=None, headers=None): """ HTTP DELETE - path: string additionnal path to the uri - headers: dict, optionnal headers that will be added to HTTP request. - params: Optionnal parameterss added to the request """ return self.request("DELETE",...
[ "def", "delete", "(", "self", ",", "path", "=", "None", ",", "headers", "=", "None", ")", ":", "return", "self", ".", "request", "(", "\"DELETE\"", ",", "path", "=", "path", ",", "headers", "=", "headers", ")" ]
42.625
9.125
def get_mean_and_stddevs(self, sctx, rctx, dctx, imt, stddev_types): """ Call the get mean and stddevs of the GMPE for the respective IMT """ return self.kwargs[str(imt)].get_mean_and_stddevs( sctx, rctx, dctx, imt, stddev_types)
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sctx", ",", "rctx", ",", "dctx", ",", "imt", ",", "stddev_types", ")", ":", "return", "self", ".", "kwargs", "[", "str", "(", "imt", ")", "]", ".", "get_mean_and_stddevs", "(", "sctx", ",", "rctx", ",",...
44.666667
14.333333
def get_followers(self, auth_secret): """Get the follower list of a logged-in user. Parameters ---------- auth_secret: str The authentication secret of the logged-in user. Returns ------- bool True if the follower list is successfully obt...
[ "def", "get_followers", "(", "self", ",", "auth_secret", ")", ":", "result", "=", "{", "pytwis_constants", ".", "ERROR_KEY", ":", "None", "}", "# Check if the user is logged in.", "loggedin", ",", "userid", "=", "self", ".", "_is_loggedin", "(", "auth_secret", "...
35.54902
24.45098
def lowest(self, rtol=1.e-5, atol=1.e-8): """Return a sample set containing the lowest-energy samples. A sample is included if its energy is within tolerance of the lowest energy in the sample set. The following equation is used to determine if two values are equivalent: absolu...
[ "def", "lowest", "(", "self", ",", "rtol", "=", "1.e-5", ",", "atol", "=", "1.e-8", ")", ":", "if", "len", "(", "self", ")", "==", "0", ":", "# empty so all are lowest", "return", "self", ".", "copy", "(", ")", "record", "=", "self", ".", "record", ...
36.526316
21.245614
def put(self, transfer_id, amount, created_timestamp, receipt): """ :param transfer_id: int of the account_id to deposit the money to :param amount: float of the amount to transfer :param created_timestamp: str of the validated receipt that money has been received ...
[ "def", "put", "(", "self", ",", "transfer_id", ",", "amount", ",", "created_timestamp", ",", "receipt", ")", ":", "return", "self", ".", "connection", ".", "put", "(", "'account/transfer/claim'", ",", "data", "=", "dict", "(", "transfer_id", "=", "transfer_i...
58.076923
22.538462
def call_path(self, basepath): """return that path to be able to call this script from the passed in basename example -- basepath = /foo/bar self.path = /foo/bar/che/baz.py self.call_path(basepath) # che/baz.py basepath -- string -- the directory yo...
[ "def", "call_path", "(", "self", ",", "basepath", ")", ":", "rel_filepath", "=", "self", ".", "path", "if", "basepath", ":", "rel_filepath", "=", "os", ".", "path", ".", "relpath", "(", "self", ".", "path", ",", "basepath", ")", "basename", "=", "self"...
34.045455
20.409091
def _get_dependencies(sql): """ Return the list of variables referenced in this SQL. """ dependencies = [] for (_, placeholder, dollar, _) in SqlStatement._get_tokens(sql): if placeholder: variable = placeholder[1:] if variable not in dependencies: dependencies.append(variabl...
[ "def", "_get_dependencies", "(", "sql", ")", ":", "dependencies", "=", "[", "]", "for", "(", "_", ",", "placeholder", ",", "dollar", ",", "_", ")", "in", "SqlStatement", ".", "_get_tokens", "(", "sql", ")", ":", "if", "placeholder", ":", "variable", "=...
40.181818
15.636364
def sum_to_n(n, size, limit=None): #from http://stackoverflow.com/questions/2065553/python-get-all-numbers-that-add-up-to-a-number """Produce all lists of `size` positive integers in decreasing order that add up to `n`.""" if size == 1: yield [n] return if limit is None: limit = ...
[ "def", "sum_to_n", "(", "n", ",", "size", ",", "limit", "=", "None", ")", ":", "#from http://stackoverflow.com/questions/2065553/python-get-all-numbers-that-add-up-to-a-number", "if", "size", "==", "1", ":", "yield", "[", "n", "]", "return", "if", "limit", "is", "...
38.153846
18.461538
def clean_slug(self): """slug title if is not provided """ slug = self.cleaned_data.get('slug', None) if slug is None or len(slug) == 0 and 'title' in self.cleaned_data: slug = slugify(self.cleaned_data['title']) return slug
[ "def", "clean_slug", "(", "self", ")", ":", "slug", "=", "self", ".", "cleaned_data", ".", "get", "(", "'slug'", ",", "None", ")", "if", "slug", "is", "None", "or", "len", "(", "slug", ")", "==", "0", "and", "'title'", "in", "self", ".", "cleaned_d...
38.571429
14.142857
def generate(self): """Generate a new string and return it.""" key = self._propose_new_key() while self.key_exists(key): _logger.warning('Previous candidate was used.' ' Regenerating another...') key = self._propose_new_key() return key
[ "def", "generate", "(", "self", ")", ":", "key", "=", "self", ".", "_propose_new_key", "(", ")", "while", "self", ".", "key_exists", "(", "key", ")", ":", "_logger", ".", "warning", "(", "'Previous candidate was used.'", "' Regenerating another...'", ")", "key...
39.125
10.625
def tz_file(name): """ Open a timezone file from the zoneinfo subdir for reading. :param name: The name of the timezone. :type name: str :rtype: file """ try: filepath = tz_path(name) return open(filepath, 'rb') except TimezoneNotFound: # http://bugs.launchpad....
[ "def", "tz_file", "(", "name", ")", ":", "try", ":", "filepath", "=", "tz_path", "(", "name", ")", "return", "open", "(", "filepath", ",", "'rb'", ")", "except", "TimezoneNotFound", ":", "# http://bugs.launchpad.net/bugs/383171 - we avoid using this", "# unless abso...
27.068966
19.206897
def get_base_modules(): " Get list of installed modules. " return sorted(filter( lambda x: op.isdir(op.join(MOD_DIR, x)), listdir(MOD_DIR)))
[ "def", "get_base_modules", "(", ")", ":", "return", "sorted", "(", "filter", "(", "lambda", "x", ":", "op", ".", "isdir", "(", "op", ".", "join", "(", "MOD_DIR", ",", "x", ")", ")", ",", "listdir", "(", "MOD_DIR", ")", ")", ")" ]
30
16
def _exec(self, cmd, url, json_data=None): """ execute a command at the device using the RESTful API :param str cmd: one of the REST commands, e.g. GET or POST :param str url: URL of the REST API the command should be applied to :param dict json_data: json data that should be at...
[ "def", "_exec", "(", "self", ",", "cmd", ",", "url", ",", "json_data", "=", "None", ")", ":", "assert", "(", "cmd", "in", "(", "\"GET\"", ",", "\"POST\"", ",", "\"PUT\"", ",", "\"DELETE\"", ")", ")", "assert", "(", "self", ".", "dev", "is", "not", ...
30.148936
19.638298
def points(self, points): """ set points without copying """ if not isinstance(points, np.ndarray): raise TypeError('Points must be a numpy array') vtk_points = vtki.vtk_points(points, False) self.SetPoints(vtk_points) self.GetPoints().Modified() self.Modified...
[ "def", "points", "(", "self", ",", "points", ")", ":", "if", "not", "isinstance", "(", "points", ",", "np", ".", "ndarray", ")", ":", "raise", "TypeError", "(", "'Points must be a numpy array'", ")", "vtk_points", "=", "vtki", ".", "vtk_points", "(", "poin...
39.375
9.875
def reduce_logsumexp(x, reduced_dim, extra_logit=None, name=None): """Numerically stable version of log(reduce_sum(exp(x))). Unlike other reductions, the output has the same shape as the input. Note: with a minor change, we could allow multiple reduced dimensions. Args: x: a Tensor reduced_dim: a dime...
[ "def", "reduce_logsumexp", "(", "x", ",", "reduced_dim", ",", "extra_logit", "=", "None", ",", "name", "=", "None", ")", ":", "reduced_dim", "=", "convert_to_dimension", "(", "reduced_dim", ")", "with", "tf", ".", "variable_scope", "(", "name", ",", "default...
39.142857
17.714286
def zone_position(self): """ Returns the card's position (1-indexed) in its zone, or 0 if not available. """ if self.zone == Zone.HAND: return self.controller.hand.index(self) + 1 return 0
[ "def", "zone_position", "(", "self", ")", ":", "if", "self", ".", "zone", "==", "Zone", ".", "HAND", ":", "return", "self", ".", "controller", ".", "hand", ".", "index", "(", "self", ")", "+", "1", "return", "0" ]
27.857143
14.428571
def play_sync(self): """ Play the video and block whilst the video is playing """ self.play() logger.info("Playing synchronously") try: time.sleep(0.05) logger.debug("Wait for playing to start") while self.is_playing(): ...
[ "def", "play_sync", "(", "self", ")", ":", "self", ".", "play", "(", ")", "logger", ".", "info", "(", "\"Playing synchronously\"", ")", "try", ":", "time", ".", "sleep", "(", "0.05", ")", "logger", ".", "debug", "(", "\"Wait for playing to start\"", ")", ...
31.466667
14.8
def _attach(self, purrlog, watchdirs=None): """Attaches Purr to a purrlog directory, and loads content. Returns False if nothing new has been loaded (because directory is the same), or True otherwise.""" purrlog = os.path.abspath(purrlog) dprint(1, "attaching to purrlog", purrlog...
[ "def", "_attach", "(", "self", ",", "purrlog", ",", "watchdirs", "=", "None", ")", ":", "purrlog", "=", "os", ".", "path", ".", "abspath", "(", "purrlog", ")", "dprint", "(", "1", ",", "\"attaching to purrlog\"", ",", "purrlog", ")", "self", ".", "logd...
46.883721
18.139535
def mean_otu_pct_abundance(ra, otuIDs): """ Calculate the mean OTU abundance percentage. :type ra: Dict :param ra: 'ra' refers to a dictionary keyed on SampleIDs, and the values are dictionaries keyed on OTUID's and their values represent the relative abundance of that OTU...
[ "def", "mean_otu_pct_abundance", "(", "ra", ",", "otuIDs", ")", ":", "sids", "=", "ra", ".", "keys", "(", ")", "otumeans", "=", "defaultdict", "(", "int", ")", "for", "oid", "in", "otuIDs", ":", "otumeans", "[", "oid", "]", "=", "sum", "(", "[", "r...
35.875
24.041667
def attach_usage_plan_to_apis(plan_id, apis, region=None, key=None, keyid=None, profile=None): ''' Attaches given usage plan to each of the apis provided in a list of apiId and stage values .. versionadded:: 2017.7.0 apis a list of dictionaries, where each dictionary contains the following: ...
[ "def", "attach_usage_plan_to_apis", "(", "plan_id", ",", "apis", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "return", "_update_usage_plan_apis", "(", "plan_id", ",", "apis", ",", ...
34.26087
39.652174
def tokenize(self, s): """Splits a string into tokens.""" s = tf.compat.as_text(s) if self.reserved_tokens: # First split out the reserved tokens substrs = self._reserved_tokens_re.split(s) else: substrs = [s] toks = [] for substr in substrs: if substr in self.reserved_...
[ "def", "tokenize", "(", "self", ",", "s", ")", ":", "s", "=", "tf", ".", "compat", ".", "as_text", "(", "s", ")", "if", "self", ".", "reserved_tokens", ":", "# First split out the reserved tokens", "substrs", "=", "self", ".", "_reserved_tokens_re", ".", "...
24.15
18.15
def pack(self, value=None): """Pack the value as a binary representation. Returns: bytes: The binary representation. Raises: ValueError: If value can't be represented with bytes """ if value is None: value = self._value if hasattr(v...
[ "def", "pack", "(", "self", ",", "value", "=", "None", ")", ":", "if", "value", "is", "None", ":", "value", "=", "self", ".", "_value", "if", "hasattr", "(", "value", ",", "'pack'", ")", "and", "callable", "(", "value", ".", "pack", ")", ":", "re...
27.571429
19.857143
def write_svg(matrix, version, out, scale=1, border=None, color='#000', background=None, xmldecl=True, svgns=True, title=None, desc=None, svgid=None, svgclass='segno', lineclass='qrline', omitsize=False, unit=None, encoding='utf-8', svgversion=None, nl=True): """\ Seria...
[ "def", "write_svg", "(", "matrix", ",", "version", ",", "out", ",", "scale", "=", "1", ",", "border", "=", "None", ",", "color", "=", "'#000'", ",", "background", "=", "None", ",", "xmldecl", "=", "True", ",", "svgns", "=", "True", ",", "title", "=...
49.86087
20.756522
def maps_get_default_rules_output_rules_action(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") maps_get_default_rules = ET.Element("maps_get_default_rules") config = maps_get_default_rules output = ET.SubElement(maps_get_default_rules, "output") ...
[ "def", "maps_get_default_rules_output_rules_action", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "maps_get_default_rules", "=", "ET", ".", "Element", "(", "\"maps_get_default_rules\"", ")", "config",...
41.230769
12.384615
def image_from_simplestreams(server, alias, remote_addr=None, cert=None, key=None, verify_cert=True, aliases=None, pu...
[ "def", "image_from_simplestreams", "(", "server", ",", "alias", ",", "remote_addr", "=", "None", ",", "cert", "=", "None", ",", "key", "=", "None", ",", "verify_cert", "=", "True", ",", "aliases", "=", "None", ",", "public", "=", "False", ",", "auto_upda...
27.950617
22
def write(self, filename, header=None): """ Writes the AST as a configuration file. `filename` Filename to save configuration file to. `header` Header string to use for the file. Returns boolean. """ origfile = self._file...
[ "def", "write", "(", "self", ",", "filename", ",", "header", "=", "None", ")", ":", "origfile", "=", "self", ".", "_filename", "try", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "_file", ":", "self", ".", "writestream", "(", "_file",...
25.727273
17.181818
def _summary(self, name, tensor): """Create a scalar or histogram summary matching the rank of the tensor. Args: name: Name for the summary. tensor: Tensor to summarize. Returns: Summary tensor. """ if tensor.shape.ndims == 0: return tf.summary.scalar(name, tensor) else...
[ "def", "_summary", "(", "self", ",", "name", ",", "tensor", ")", ":", "if", "tensor", ".", "shape", ".", "ndims", "==", "0", ":", "return", "tf", ".", "summary", ".", "scalar", "(", "name", ",", "tensor", ")", "else", ":", "return", "tf", ".", "s...
25.428571
16.357143
def dateAt( self, point ): """ Returns the date at the given point. :param point | <QPoint> """ for date, data in self._dateGrid.items(): if ( data[1].contains(point) ): return QDate.fromJulianDay(date) return QDate()
[ "def", "dateAt", "(", "self", ",", "point", ")", ":", "for", "date", ",", "data", "in", "self", ".", "_dateGrid", ".", "items", "(", ")", ":", "if", "(", "data", "[", "1", "]", ".", "contains", "(", "point", ")", ")", ":", "return", "QDate", "....
30.7
9.3
def start_centroid_distance(item_a, item_b, max_value): """ Distance between the centroids of the first step in each object. Args: item_a: STObject from the first set in TrackMatcher item_b: STObject from the second set in TrackMatcher max_value: Maximum distance value used as scali...
[ "def", "start_centroid_distance", "(", "item_a", ",", "item_b", ",", "max_value", ")", ":", "start_a", "=", "item_a", ".", "center_of_mass", "(", "item_a", ".", "times", "[", "0", "]", ")", "start_b", "=", "item_b", ".", "center_of_mass", "(", "item_b", "....
41.5625
23.1875
def libvlc_video_set_scale(p_mi, f_factor): '''Set the video scaling factor. That is the ratio of the number of pixels on screen to the number of pixels in the original decoded video in each dimension. Zero is a special value; it will adjust the video to the output window/drawable (in windowed mode) or ...
[ "def", "libvlc_video_set_scale", "(", "p_mi", ",", "f_factor", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_video_set_scale'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_video_set_scale'", ",", "(", "(", "1", ",", ")", ",", "(", "1...
52.538462
20.384615
def do_batch(args): """Runs the batch list, batch show or batch status command, printing output to the console Args: args: The parsed arguments sent to the command at runtime """ if args.subcommand == 'list': do_batch_list(args) if args.subcommand == 'show': do_...
[ "def", "do_batch", "(", "args", ")", ":", "if", "args", ".", "subcommand", "==", "'list'", ":", "do_batch_list", "(", "args", ")", "if", "args", ".", "subcommand", "==", "'show'", ":", "do_batch_show", "(", "args", ")", "if", "args", ".", "subcommand", ...
25.166667
18.388889
def libvlc_audio_equalizer_get_band_frequency(u_index): '''Get a particular equalizer band frequency. This value can be used, for example, to create a label for an equalizer band control in a user interface. @param u_index: index of the band, counting from zero. @return: equalizer band frequency (Hz...
[ "def", "libvlc_audio_equalizer_get_band_frequency", "(", "u_index", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_audio_equalizer_get_band_frequency'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_audio_equalizer_get_band_frequency'", ",", "(", "(", ...
51.666667
23.666667
def _update_sys_path(self, package_path=None): """Updates and adds current directory to sys path""" self.package_path = package_path if not self.package_path in sys.path: sys.path.append(self.package_path)
[ "def", "_update_sys_path", "(", "self", ",", "package_path", "=", "None", ")", ":", "self", ".", "package_path", "=", "package_path", "if", "not", "self", ".", "package_path", "in", "sys", ".", "path", ":", "sys", ".", "path", ".", "append", "(", "self",...
47.4
3.4
def filter_images_urls(image_urls, image_filter, common_image_filter=None): ''' 图片链接过滤器,根据传入的过滤器规则,对图片链接列表进行过滤并返回结果列表 :param list(str) image_urls: 图片链接字串列表 :param list(str) image_filter: 过滤器字串列表 :param list(str) common_image_filter: 可选,通用的基础过滤器, 会在定制过滤器前对传入图片应用 ...
[ "def", "filter_images_urls", "(", "image_urls", ",", "image_filter", ",", "common_image_filter", "=", "None", ")", ":", "common_image_filter", "=", "common_image_filter", "or", "[", "]", "# 对图片过滤器进行完整性验证", "image_filter", "=", "json", ".", "loads", "(", "image_filte...
35.512821
14.282051
def derivative(self, x): """Derivative of the broadcast operator. Parameters ---------- x : `domain` element The point to take the derivative in Returns ------- adjoint : linear `BroadcastOperator` The derivative Examples ...
[ "def", "derivative", "(", "self", ",", "x", ")", ":", "return", "BroadcastOperator", "(", "*", "[", "op", ".", "derivative", "(", "x", ")", "for", "op", "in", "self", ".", "operators", "]", ")" ]
26.25
19.825
def Dir(self, name, create=True): """ Looks up or creates a directory node named 'name' relative to this directory. """ return self.fs.Dir(name, self, create)
[ "def", "Dir", "(", "self", ",", "name", ",", "create", "=", "True", ")", ":", "return", "self", ".", "fs", ".", "Dir", "(", "name", ",", "self", ",", "create", ")" ]
32.166667
9.833333
def create_class(self, data, options=None, path=None, **kwargs): """ Return instance of class based on Roslyn type property Data keys handled here: type Set the object class items Recurse into :py:meth:`create_class` to create child obje...
[ "def", "create_class", "(", "self", ",", "data", ",", "options", "=", "None", ",", "path", "=", "None", ",", "*", "*", "kwargs", ")", ":", "obj_map", "=", "dict", "(", "(", "cls", ".", "type", ",", "cls", ")", "for", "cls", "in", "ALL_CLASSES", "...
28.085714
20.657143
def reset(): """Resets Logger to its initial state""" Logger.journal = [] Logger.fatal_warnings = False Logger._ignored_codes = set() Logger._ignored_domains = set() Logger._verbosity = 2 Logger._last_checkpoint = 0
[ "def", "reset", "(", ")", ":", "Logger", ".", "journal", "=", "[", "]", "Logger", ".", "fatal_warnings", "=", "False", "Logger", ".", "_ignored_codes", "=", "set", "(", ")", "Logger", ".", "_ignored_domains", "=", "set", "(", ")", "Logger", ".", "_verb...
33
8
def egg_info_writer(cmd, basename, filename): # type: (setuptools.command.egg_info.egg_info, str, str) -> None """Read rcli configuration and write it out to the egg info. Args: cmd: An egg info command instance to use for writing. basename: The basename of the file to write. filena...
[ "def", "egg_info_writer", "(", "cmd", ",", "basename", ",", "filename", ")", ":", "# type: (setuptools.command.egg_info.egg_info, str, str) -> None", "setupcfg", "=", "next", "(", "(", "f", "for", "f", "in", "setuptools", ".", "findall", "(", ")", "if", "os", "....
39.37931
17.896552
def time_str (time_t, slug = False): '''Converts floating point number a'la time.time() using DEFAULT_TIMEFORMAT ''' return datetime.fromtimestamp (int (time_t)).strftime ( DEFAULT_SLUGFORMAT if slug else DEFAULT_TIMEFORMAT)
[ "def", "time_str", "(", "time_t", ",", "slug", "=", "False", ")", ":", "return", "datetime", ".", "fromtimestamp", "(", "int", "(", "time_t", ")", ")", ".", "strftime", "(", "DEFAULT_SLUGFORMAT", "if", "slug", "else", "DEFAULT_TIMEFORMAT", ")" ]
38.5
16.166667
def matching_files(self): """ Find files. Returns: list: the list of matching files. """ matching = [] matcher = self.file_path_regex pieces = self.file_path_regex.pattern.split(sep) partial_matchers = list(map(re.compile, ( sep.jo...
[ "def", "matching_files", "(", "self", ")", ":", "matching", "=", "[", "]", "matcher", "=", "self", ".", "file_path_regex", "pieces", "=", "self", ".", "file_path_regex", ".", "pattern", ".", "split", "(", "sep", ")", "partial_matchers", "=", "list", "(", ...
33.88
18.04
def define_example_values(self, http_method, route, values, update=False): """Define example values for a given request. By default, example values are determined from the example properties in the schema. But if you want to change the example used in the documentation for a specific ro...
[ "def", "define_example_values", "(", "self", ",", "http_method", ",", "route", ",", "values", ",", "update", "=", "False", ")", ":", "self", ".", "defined_example_values", "[", "(", "http_method", ".", "lower", "(", ")", ",", "route", ")", "]", "=", "{",...
48.722222
24.611111
def get_file(self, project, build_id, artifact_name, file_id, file_name, **kwargs): """GetFile. Gets a file from the build. :param str project: Project ID or project name :param int build_id: The ID of the build. :param str artifact_name: The name of the artifact. :param ...
[ "def", "get_file", "(", "self", ",", "project", ",", "build_id", ",", "artifact_name", ",", "file_id", ",", "file_name", ",", "*", "*", "kwargs", ")", ":", "route_values", "=", "{", "}", "if", "project", "is", "not", "None", ":", "route_values", "[", "...
51.181818
20.757576
def add_record(self, length): # type: (int) -> None ''' Add some more length to this CE record. Used when a new record is going to get recorded into the CE (rather than the DR). Parameters: length - The length to add to this CE record. Returns: Nothing...
[ "def", "add_record", "(", "self", ",", "length", ")", ":", "# type: (int) -> None", "if", "not", "self", ".", "_initialized", ":", "raise", "pycdlibexception", ".", "PyCdlibInternalError", "(", "'CE record not yet initialized!'", ")", "self", ".", "len_cont_area", "...
32.066667
23.933333
def affine_zoom_matrix(zoom_range=(0.8, 1.1)): """Create an affine transform matrix for zooming/scaling an image's height and width. OpenCV format, x is width. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). zoom_range : float or tuple of...
[ "def", "affine_zoom_matrix", "(", "zoom_range", "=", "(", "0.8", ",", "1.1", ")", ")", ":", "if", "isinstance", "(", "zoom_range", ",", "(", "float", ",", "int", ")", ")", ":", "scale", "=", "zoom_range", "elif", "isinstance", "(", "zoom_range", ",", "...
31.806452
19.677419
def to_binary_string(self): """Pack the feedback to binary form and return it as string.""" timestamp = datetime_to_timestamp(self.when) token = binascii.unhexlify(self.token) return struct.pack(self.FORMAT_PREFIX + '{0}s'.format(len(token)), timestamp, len(tok...
[ "def", "to_binary_string", "(", "self", ")", ":", "timestamp", "=", "datetime_to_timestamp", "(", "self", ".", "when", ")", "token", "=", "binascii", ".", "unhexlify", "(", "self", ".", "token", ")", "return", "struct", ".", "pack", "(", "self", ".", "FO...
54.333333
13.5
def smooth(x,window_len,window='bartlett'): """smooth the data using a sliding window with requested size. This method is based on the convolution of a scaled window with the signal. The signal is prepared by padding the beginning and the end of the signal with average of the first (last) ten values of...
[ "def", "smooth", "(", "x", ",", "window_len", ",", "window", "=", "'bartlett'", ")", ":", "if", "x", ".", "ndim", "!=", "1", ":", "raise", "ValueError", "(", "\"smooth only accepts 1 dimension arrays.\"", ")", "if", "x", ".", "size", "<", "window_len", ":"...
37.8
26.38
def cmd_tool(args=None): """ Command line tool for plotting and viewing info on filterbank files """ from argparse import ArgumentParser parser = ArgumentParser(description="Command line utility for reading and plotting filterbank files.") parser.add_argument('-p', action='store', default='ank', des...
[ "def", "cmd_tool", "(", "args", "=", "None", ")", ":", "from", "argparse", "import", "ArgumentParser", "parser", "=", "ArgumentParser", "(", "description", "=", "\"Command line utility for reading and plotting filterbank files.\"", ")", "parser", ".", "add_argument", "(...
48.315315
25.567568
def setup(use_latex=False, overwrite=False): """Set up matplotlib imports and settings. Parameters ---------- use_latex: bool, optional Determine if Latex output should be used. Latex will only be enable if a 'latex' binary is found in the system. overwrite: bool, optional O...
[ "def", "setup", "(", "use_latex", "=", "False", ",", "overwrite", "=", "False", ")", ":", "# just make sure we can access matplotlib as mpl", "import", "matplotlib", "as", "mpl", "# general settings", "if", "overwrite", ":", "mpl", ".", "rcParams", "[", "\"lines.lin...
30.326087
17.043478
def parse(uri, user=None, port=22): """ parses ssh connection uri-like sentences. ex: - root@google.com -> (root, google.com, 22) - noreply@facebook.com:22 -> (noreply, facebook.com, 22) - facebook.com:3306 -> ($USER, facebook.com, 3306) - twitter.com -> ($USER, twitter.com, ...
[ "def", "parse", "(", "uri", ",", "user", "=", "None", ",", "port", "=", "22", ")", ":", "uri", "=", "uri", ".", "strip", "(", ")", "if", "not", "user", ":", "user", "=", "getpass", ".", "getuser", "(", ")", "# get user", "if", "'@'", "in", "uri...
20.365854
21.878049
def mstmap(args): """ %prog mstmap LMD50.snps.genotype.txt Convert LMDs to MSTMAP input. """ from jcvi.assembly.geneticmap import MSTMatrix p = OptionParser(mstmap.__doc__) p.add_option("--population_type", default="RIL6", help="Type of population, possible values are DH a...
[ "def", "mstmap", "(", "args", ")", ":", "from", "jcvi", ".", "assembly", ".", "geneticmap", "import", "MSTMatrix", "p", "=", "OptionParser", "(", "mstmap", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--population_type\"", ",", "default", "=", "\"R...
31.529412
17.411765
def __compute_evolution( df, id_cols, value_col, date_col=None, freq=1, compare_to=None, method='abs', format='column', offseted_suffix='_offseted', evolution_col_name='evolution_computed', how='left', fillna=None, raise_duplicate_error=True ): """ Compute an ...
[ "def", "__compute_evolution", "(", "df", ",", "id_cols", ",", "value_col", ",", "date_col", "=", "None", ",", "freq", "=", "1", ",", "compare_to", "=", "None", ",", "method", "=", "'abs'", ",", "format", "=", "'column'", ",", "offseted_suffix", "=", "'_o...
34.7375
19.3625
def execute(self): """Resolves the specified confs for the configured targets and returns an iterator over tuples of (conf, jar path). """ if JvmResolveSubsystem.global_instance().get_options().resolver != 'ivy': return compile_classpath = self.context.products.get_data('compile_classpath', ...
[ "def", "execute", "(", "self", ")", ":", "if", "JvmResolveSubsystem", ".", "global_instance", "(", ")", ".", "get_options", "(", ")", ".", "resolver", "!=", "'ivy'", ":", "return", "compile_classpath", "=", "self", ".", "context", ".", "products", ".", "ge...
43.333333
23.933333
def conv(self,field_name,conv_func): """When a record is returned by a SELECT, ask conversion of specified field value with the specified function""" if field_name not in self.fields: raise NameError,"Unknown field %s" %field_name self.conv_func[field_name] = conv_func
[ "def", "conv", "(", "self", ",", "field_name", ",", "conv_func", ")", ":", "if", "field_name", "not", "in", "self", ".", "fields", ":", "raise", "NameError", ",", "\"Unknown field %s\"", "%", "field_name", "self", ".", "conv_func", "[", "field_name", "]", ...
52.166667
5
def set_auxiliary_basis_set(self, folder, auxiliary_folder, auxiliary_basis_set_type="aug_cc_pvtz"): """ copy in the desired folder the needed auxiliary basis set "X2.ion" where X is a specie. :param auxiliary_folder: folder where the auxiliary basis sets are stor...
[ "def", "set_auxiliary_basis_set", "(", "self", ",", "folder", ",", "auxiliary_folder", ",", "auxiliary_basis_set_type", "=", "\"aug_cc_pvtz\"", ")", ":", "list_files", "=", "os", ".", "listdir", "(", "auxiliary_folder", ")", "for", "specie", "in", "self", ".", "...
53.777778
26.777778
def copy(self): """ Returns a copy of JunctionTree. Returns ------- JunctionTree : copy of JunctionTree Examples -------- >>> import numpy as np >>> from pgmpy.factors.discrete import DiscreteFactor >>> from pgmpy.models import JunctionTr...
[ "def", "copy", "(", "self", ")", ":", "copy", "=", "JunctionTree", "(", "self", ".", "edges", "(", ")", ")", "copy", ".", "add_nodes_from", "(", "self", ".", "nodes", "(", ")", ")", "if", "self", ".", "factors", ":", "factors_copy", "=", "[", "fact...
37.4
19.285714
def define_function(self, function, name=None): """Define the Python function within the CLIPS environment. If a name is given, it will be the function name within CLIPS. Otherwise, the name of the Python function will be used. The Python function will be accessible within CLIPS via it...
[ "def", "define_function", "(", "self", ",", "function", ",", "name", "=", "None", ")", ":", "name", "=", "name", "if", "name", "is", "not", "None", "else", "function", ".", "__name__", "ENVIRONMENT_DATA", "[", "self", ".", "_env", "]", ".", "user_functio...
37.666667
24.466667
def _get_core_keywords(skw_matches, ckw_matches, spires=False): """Return the output for the field codes. :var skw_matches: dict of {keyword: [info,...]} :var ckw_matches: dict of {keyword: [info,...]} :keyword spires: bool, to get the spires output :return: list of formatted core keywords """ ...
[ "def", "_get_core_keywords", "(", "skw_matches", ",", "ckw_matches", ",", "spires", "=", "False", ")", ":", "output", "=", "{", "}", "category", "=", "{", "}", "def", "_get_value_kw", "(", "kw", ")", ":", "\"\"\"Help to sort the Core keywords.\"\"\"", "i", "="...
31.973684
16.631579
def read(self, size): """ Read from the current offset a total number of `size` bytes and increment the offset by `size` :param int size: length of bytes to read :rtype: bytearray """ if isinstance(size, SV): size = size.value buff = self.__b...
[ "def", "read", "(", "self", ",", "size", ")", ":", "if", "isinstance", "(", "size", ",", "SV", ")", ":", "size", "=", "size", ".", "value", "buff", "=", "self", ".", "__buff", "[", "self", ".", "__idx", ":", "self", ".", "__idx", "+", "size", "...
25.8
17.4
def unbind_opr(self, opr, path=None): """ 接触操作员与权限关联 """ if path: self.routes[path]['oprs'].remove(opr) else: for path in self.routes: route = self.routes.get(path) if route and opr in route['oprs']: route['oprs'...
[ "def", "unbind_opr", "(", "self", ",", "opr", ",", "path", "=", "None", ")", ":", "if", "path", ":", "self", ".", "routes", "[", "path", "]", "[", "'oprs'", "]", ".", "remove", "(", "opr", ")", "else", ":", "for", "path", "in", "self", ".", "ro...
32.4
8.7
def create(self, alert_config, occurrence_frequency_count=None, occurrence_frequency_unit=None, alert_frequency_count=None, alert_frequency_unit=None): """ Create a new alert :param alert_config: A list of AlertConfig cl...
[ "def", "create", "(", "self", ",", "alert_config", ",", "occurrence_frequency_count", "=", "None", ",", "occurrence_frequency_unit", "=", "None", ",", "alert_frequency_count", "=", "None", ",", "alert_frequency_unit", "=", "None", ")", ":", "data", "=", "{", "'r...
40.711864
20.745763
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None): """Sends PreparedRequest object. Returns Response object. :param request: The :class:`PreparedRequest <PreparedRequest>` being sent. :param stream: (optional) Whether to stream the request co...
[ "def", "send", "(", "self", ",", "request", ",", "stream", "=", "False", ",", "timeout", "=", "None", ",", "verify", "=", "True", ",", "cert", "=", "None", ",", "proxies", "=", "None", ")", ":", "raise", "NotImplementedError" ]
57.117647
24.294118
def random_deletion(self,fastq,rate): """Perform the permutation on the sequence :param fastq: FASTQ sequence to permute :type fastq: format.fastq.FASTQ :param rate: how frequently to permute :type rate: float :return: Permutted FASTQ :rtype: format.fastq.FASTQ """ sequence = fastq....
[ "def", "random_deletion", "(", "self", ",", "fastq", ",", "rate", ")", ":", "sequence", "=", "fastq", ".", "sequence", "quality", "=", "fastq", ".", "qual", "seq", "=", "''", "qual", "=", "None", "if", "quality", ":", "qual", "=", "''", "for", "i", ...
30.461538
15.410256
def find_optconf(self, pconfs): """Find the optimal Parallel configuration.""" # Save pconfs for future reference. self.set_pconfs(pconfs) # Select the partition on which we'll be running and set MPI/OMP cores. optconf = self.manager.select_qadapter(pconfs) return optcon...
[ "def", "find_optconf", "(", "self", ",", "pconfs", ")", ":", "# Save pconfs for future reference.", "self", ".", "set_pconfs", "(", "pconfs", ")", "# Select the partition on which we'll be running and set MPI/OMP cores.", "optconf", "=", "self", ".", "manager", ".", "sele...
39.25
16.5
def qloguniform(low, high, q, random_state): ''' low: an float that represent an lower bound high: an float that represent an upper bound q: sample step random_state: an object of numpy.random.RandomState ''' return np.round(loguniform(low, high, random_state) / q) * q
[ "def", "qloguniform", "(", "low", ",", "high", ",", "q", ",", "random_state", ")", ":", "return", "np", ".", "round", "(", "loguniform", "(", "low", ",", "high", ",", "random_state", ")", "/", "q", ")", "*", "q" ]
36.25
18.25
def _onError(self, message): """Memorizies a parser error message""" self.isOK = False if message.strip() != "": self.errors.append(message)
[ "def", "_onError", "(", "self", ",", "message", ")", ":", "self", ".", "isOK", "=", "False", "if", "message", ".", "strip", "(", ")", "!=", "\"\"", ":", "self", ".", "errors", ".", "append", "(", "message", ")" ]
34.4
7
def zip_(zip_file, sources, template=None, cwd=None, runas=None, zip64=False): ''' Uses the ``zipfile`` Python module to create zip files .. versionchanged:: 2015.5.0 This function was rewritten to use Python's native zip file support. The old functionality has been preserved in the new fun...
[ "def", "zip_", "(", "zip_file", ",", "sources", ",", "template", "=", "None", ",", "cwd", "=", "None", ",", "runas", "=", "None", ",", "zip64", "=", "False", ")", ":", "if", "runas", ":", "euid", "=", "os", ".", "geteuid", "(", ")", "egid", "=", ...
39.614865
23.222973
def subnet_group_exists(name, tags=None, region=None, key=None, keyid=None, profile=None): ''' Check to see if an RDS subnet group exists. CLI example:: salt myminion boto_rds.subnet_group_exists my-param-group \ region=us-east-1 ''' try: con...
[ "def", "subnet_group_exists", "(", "name", ",", "tags", "=", "None", ",", "region", "=", "None", ",", "key", "=", "None", ",", "keyid", "=", "None", ",", "profile", "=", "None", ")", ":", "try", ":", "conn", "=", "_get_conn", "(", "region", "=", "r...
33.272727
22.181818
def sum(x, axis=None, keepdims=False): """Reduction along axes with sum operation. Args: x (Variable): An input variable. axis (None, int or tuple of ints): Axis or axes along which the sum is calculated. Passing the default value `None` will reduce all dimensions. keepdims ...
[ "def", "sum", "(", "x", ",", "axis", "=", "None", ",", "keepdims", "=", "False", ")", ":", "from", ".", "function_bases", "import", "sum", "as", "sum_base", "if", "axis", "is", "None", ":", "axis", "=", "range", "(", "x", ".", "ndim", ")", "elif", ...
35.444444
19
def restore(self, filename): """Restore object from mat-file. TODO: determine format specification """ matfile = loadmat(filename) if matfile['dim'] == 1: matfile['solution'] = matfile['solution'][0, :] self.elapsed_time = matfile['elapsed_time'][0, 0] self....
[ "def", "restore", "(", "self", ",", "filename", ")", ":", "matfile", "=", "loadmat", "(", "filename", ")", "if", "matfile", "[", "'dim'", "]", "==", "1", ":", "matfile", "[", "'solution'", "]", "=", "matfile", "[", "'solution'", "]", "[", "0", ",", ...
30
17.166667
def main(argv=None): """The entry point of the application.""" if argv is None: argv = sys.argv[1:] usage = '\n\n\n'.join(__doc__.split('\n\n\n')[1:]) version = 'Gitpress ' + __version__ # Parse options args = docopt(usage, argv=argv, version=version) # Execute command try: ...
[ "def", "main", "(", "argv", "=", "None", ")", ":", "if", "argv", "is", "None", ":", "argv", "=", "sys", ".", "argv", "[", "1", ":", "]", "usage", "=", "'\\n\\n\\n'", ".", "join", "(", "__doc__", ".", "split", "(", "'\\n\\n\\n'", ")", "[", "1", ...
29.066667
17.8
def datatype(self, value): """ Args: value (string): 'uint8', 'uint16', 'uint64' Raises: ValueError """ self._datatype = self.validate_datatype(value) self._cutout_ready = True
[ "def", "datatype", "(", "self", ",", "value", ")", ":", "self", ".", "_datatype", "=", "self", ".", "validate_datatype", "(", "value", ")", "self", ".", "_cutout_ready", "=", "True" ]
26.666667
13.333333
def load(pipette_model: str, pipette_id: str = None) -> pipette_config: """ Load pipette config data This function loads from a combination of - the pipetteModelSpecs.json file in the wheel (should never be edited) - the pipetteNameSpecs.json file in the wheel(should never be edited) - any co...
[ "def", "load", "(", "pipette_model", ":", "str", ",", "pipette_id", ":", "str", "=", "None", ")", "->", "pipette_config", ":", "# Load the model config and update with the name config", "cfg", "=", "copy", ".", "deepcopy", "(", "configs", "[", "pipette_model", "]"...
45.709677
22.075269
def chain_future(a: "Future[_T]", b: "Future[_T]") -> None: """Chain two futures together so that when one completes, so does the other. The result (success or failure) of ``a`` will be copied to ``b``, unless ``b`` has already been completed or cancelled by the time ``a`` finishes. .. versionchanged:...
[ "def", "chain_future", "(", "a", ":", "\"Future[_T]\"", ",", "b", ":", "\"Future[_T]\"", ")", "->", "None", ":", "def", "copy", "(", "future", ":", "\"Future[_T]\"", ")", "->", "None", ":", "assert", "future", "is", "a", "if", "b", ".", "done", "(", ...
32.258065
19.967742
def memoize(func=None, maxlen=None): """Cache a function's return value each time it is called. This function serves as a function decorator to provide a caching of evaluated fitness values. If called later with the same arguments, the cached value is returned instead of being re-evaluated. ...
[ "def", "memoize", "(", "func", "=", "None", ",", "maxlen", "=", "None", ")", ":", "if", "func", "is", "not", "None", ":", "cache", "=", "BoundedOrderedDict", "(", "maxlen", "=", "maxlen", ")", "@", "functools", ".", "wraps", "(", "func", ")", "def", ...
42.44
20.58
def get_filename(file): """ Safe method to retrieve only the name of the file. :param file: Path of the file to retrieve the name from. :return: None if the file is non-existant, otherwise the filename (extension included) :rtype: None, str """ if not os.path.exists(file): return Non...
[ "def", "get_filename", "(", "file", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "file", ")", ":", "return", "None", "return", "\"%s%s\"", "%", "os", ".", "path", ".", "splitext", "(", "file", ")" ]
35.5
15.1
def merge_entity(self, table_name, entity, if_match='*', timeout=None): ''' Updates an existing entity by merging the entity's properties. Throws if the entity does not exist. This operation does not replace the existing entity as the update_entity operation does. A pr...
[ "def", "merge_entity", "(", "self", ",", "table_name", ",", "entity", ",", "if_match", "=", "'*'", ",", "timeout", "=", "None", ")", ":", "_validate_not_none", "(", "'table_name'", ",", "table_name", ")", "request", "=", "_merge_entity", "(", "entity", ",", ...
48.5
27.15
def child_added(self, child): """ Handle the child added event from the declaration. This handler will unparent the child toolkit widget. Subclasses which need more control should reimplement this method. """ super(AndroidViewGroup, self).child_added(child) widget = se...
[ "def", "child_added", "(", "self", ",", "child", ")", ":", "super", "(", "AndroidViewGroup", ",", "self", ")", ".", "child_added", "(", "child", ")", "widget", "=", "self", ".", "widget", "#: TODO: Should index be cached?", "for", "i", ",", "child_widget", "...
38.611111
17.111111
def set_verify_depth(self, depth): """ Set the maximum depth for the certificate chain verification that shall be allowed for this Context object. :param depth: An integer specifying the verify depth :return: None """ if not isinstance(depth, integer_types): ...
[ "def", "set_verify_depth", "(", "self", ",", "depth", ")", ":", "if", "not", "isinstance", "(", "depth", ",", "integer_types", ")", ":", "raise", "TypeError", "(", "\"depth must be an integer\"", ")", "_lib", ".", "SSL_CTX_set_verify_depth", "(", "self", ".", ...
35.083333
17.416667
def from_config(cls, cp, section, outputs, skip_opts=None, additional_opts=None): """Initializes a transform from the given section. Parameters ---------- cp : pycbc.workflow.WorkflowConfigParser A parsed configuration file that contains the transform opt...
[ "def", "from_config", "(", "cls", ",", "cp", ",", "section", ",", "outputs", ",", "skip_opts", "=", "None", ",", "additional_opts", "=", "None", ")", ":", "tag", "=", "outputs", "if", "skip_opts", "is", "None", ":", "skip_opts", "=", "[", "]", "if", ...
38.818182
16.727273
def resolve_path(self, address): ''' Resolve the given address in this tree branch ''' match = self.find_one(address) if not match: return [self] # Go further up the tree if possible if isinstance(match, ContainerNode): return match.resolv...
[ "def", "resolve_path", "(", "self", ",", "address", ")", ":", "match", "=", "self", ".", "find_one", "(", "address", ")", "if", "not", "match", ":", "return", "[", "self", "]", "# Go further up the tree if possible", "if", "isinstance", "(", "match", ",", ...
28.214286
16.928571
def Print(self, output_writer): """Prints a human readable version of the filter. Args: output_writer (CLIOutputWriter): output writer. """ if self._filters: output_writer.Write('Filters:\n') for file_entry_filter in self._filters: file_entry_filter.Print(output_writer)
[ "def", "Print", "(", "self", ",", "output_writer", ")", ":", "if", "self", ".", "_filters", ":", "output_writer", ".", "Write", "(", "'Filters:\\n'", ")", "for", "file_entry_filter", "in", "self", ".", "_filters", ":", "file_entry_filter", ".", "Print", "(",...
30.4
12.4
def list(self): """Returns a list of the users gists as GistInfo objects Returns: a list of GistInfo objects """ # Define the basic request. The per_page parameter is set to 100, which # is the maximum github allows. If the user has more than one page of # g...
[ "def", "list", "(", "self", ")", ":", "# Define the basic request. The per_page parameter is set to 100, which", "# is the maximum github allows. If the user has more than one page of", "# gists, this request object will be modified to retrieve each", "# successive page of gists.", "request", ...
33.432432
19.5
def _interpolate(self, kind='linear'): """Apply scipy.interpolate.interp1d along resampling dimension.""" # drop any existing non-dimension coordinates along the resampling # dimension dummy = self._obj.copy() for k, v in self._obj.coords.items(): if k != self._dim an...
[ "def", "_interpolate", "(", "self", ",", "kind", "=", "'linear'", ")", ":", "# drop any existing non-dimension coordinates along the resampling", "# dimension", "dummy", "=", "self", ".", "_obj", ".", "copy", "(", ")", "for", "k", ",", "v", "in", "self", ".", ...
50.181818
13.272727
def register_integration(package_folder): """Register a honeycomb integration. :param package_folder: Path to folder with integration to load :returns: Validated integration object :rtype: :func:`honeycomb.utils.defs.Integration` """ logger.debug("registering integration %s", package_folder) ...
[ "def", "register_integration", "(", "package_folder", ")", ":", "logger", ".", "debug", "(", "\"registering integration %s\"", ",", "package_folder", ")", "package_folder", "=", "os", ".", "path", ".", "realpath", "(", "package_folder", ")", "if", "not", "os", "...
39.428571
19.107143
def set_amount_cb(self, widget, val): """This method is called when 'Zoom Amount' control is adjusted. """ self.zoom_amount = val zoomlevel = self.fitsimage_focus.get_zoom() self._zoomset(self.fitsimage_focus, zoomlevel)
[ "def", "set_amount_cb", "(", "self", ",", "widget", ",", "val", ")", ":", "self", ".", "zoom_amount", "=", "val", "zoomlevel", "=", "self", ".", "fitsimage_focus", ".", "get_zoom", "(", ")", "self", ".", "_zoomset", "(", "self", ".", "fitsimage_focus", "...
42.5
6.333333
def get_users_in_organization(self, organization_id, start=0, limit=50): """ Get all the users of a specified organization :param organization_id: str :param start: OPTIONAL: int :param limit: OPTIONAL: int :return: Users list in organization """ url = 'r...
[ "def", "get_users_in_organization", "(", "self", ",", "organization_id", ",", "start", "=", "0", ",", "limit", "=", "50", ")", ":", "url", "=", "'rest/servicedeskapi/organization/{}/user'", ".", "format", "(", "organization_id", ")", "params", "=", "{", "}", "...
35.882353
15.529412