text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def parse_request_body_response(self, body, scope=None, **kwargs): """Parse the JSON response body. If the access token request is valid and authorized, the authorization server issues an access token as described in `Section 5.1`_. A refresh token SHOULD NOT be included. If the reque...
[ "def", "parse_request_body_response", "(", "self", ",", "body", ",", "scope", "=", "None", ",", "*", "*", "kwargs", ")", ":", "self", ".", "token", "=", "parse_token_response", "(", "body", ",", "scope", "=", "scope", ")", "self", ".", "populate_token_attr...
45.897959
0.001741
def pylog(self, *args, **kwargs): """Display all available logging information.""" printerr(self.name, args, kwargs, traceback.format_exc())
[ "def", "pylog", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "printerr", "(", "self", ".", "name", ",", "args", ",", "kwargs", ",", "traceback", ".", "format_exc", "(", ")", ")" ]
51.333333
0.012821
def python_op(fn, inputs=None, outputs=None): """ User-exposed api method for constructing a python_node Args: fn: python function that computes some np.ndarrays given np.ndarrays as inputs. it can have arbitrary side effects. inputs: array of tf.Tensors (optional). These are where fn derives its values from out...
[ "def", "python_op", "(", "fn", ",", "inputs", "=", "None", ",", "outputs", "=", "None", ")", ":", "# construct a PythonOp and return its TensorNode outputs, if it has one", "global", "COUNT", "# check outputs", "if", "not", "isinstance", "(", "outputs", ",", "list", ...
33.928571
0.0348
def output_cert(gandi, cert, output_keys, justify=13): """Helper to output a certificate information.""" output = list(output_keys) display_altnames = False if 'altnames' in output: display_altnames = True output.remove('altnames') display_output = False if 'cert' in output: ...
[ "def", "output_cert", "(", "gandi", ",", "cert", ",", "output_keys", ",", "justify", "=", "13", ")", ":", "output", "=", "list", "(", "output_keys", ")", "display_altnames", "=", "False", "if", "'altnames'", "in", "output", ":", "display_altnames", "=", "T...
28.666667
0.001406
def _launch_instance(self): """Launch an instance of the given image.""" metadata = {'key': 'ssh-keys', 'value': self.ssh_public_key} self.running_instance_id = ipa_utils.generate_instance_name( 'gce-ipa-test' ) self.logger.debug('ID of instance: %s' % self.running_in...
[ "def", "_launch_instance", "(", "self", ")", ":", "metadata", "=", "{", "'key'", ":", "'ssh-keys'", ",", "'value'", ":", "self", ".", "ssh_public_key", "}", "self", ".", "running_instance_id", "=", "ipa_utils", ".", "generate_instance_name", "(", "'gce-ipa-test'...
32.136364
0.001373
def bs_plot_data(self): """ Get the data nicely formatted for a plot Returns: A dict of the following format: ticks: A dict with the 'distances' at which there is a qpoint (the x axis) and the labels (None if no label) frequencies: A list (one el...
[ "def", "bs_plot_data", "(", "self", ")", ":", "distance", "=", "[", "]", "frequency", "=", "[", "]", "ticks", "=", "self", ".", "get_ticks", "(", ")", "for", "b", "in", "self", ".", "_bs", ".", "branches", ":", "frequency", ".", "append", "(", "[",...
35.484848
0.002494
def get_position(self): """Returns tuple of 4 numbers: (x, y)s of top-left and bottom-right corners""" rect = _Rect() GetWindowRect(self._hwnd, ctypes.pointer(rect)) return rect.left, rect.top, rect.right, rect.bottom
[ "def", "get_position", "(", "self", ")", ":", "rect", "=", "_Rect", "(", ")", "GetWindowRect", "(", "self", ".", "_hwnd", ",", "ctypes", ".", "pointer", "(", "rect", ")", ")", "return", "rect", ".", "left", ",", "rect", ".", "top", ",", "rect", "."...
49
0.012048
def _set_grouper(self, obj, sort=False): """ given an object and the specifications, setup the internal grouper for this particular specification Parameters ---------- obj : the subject object sort : bool, default False whether the resulting grouper s...
[ "def", "_set_grouper", "(", "self", ",", "obj", ",", "sort", "=", "False", ")", ":", "if", "self", ".", "key", "is", "not", "None", "and", "self", ".", "level", "is", "not", "None", ":", "raise", "ValueError", "(", "\"The Grouper cannot specify both a key ...
35.6
0.000911
def p_simple_list1(p): '''simple_list1 : simple_list1 AND_AND newline_list simple_list1 | simple_list1 OR_OR newline_list simple_list1 | simple_list1 AMPERSAND simple_list1 | simple_list1 SEMICOLON simple_list1 | pipeline_command''' ...
[ "def", "p_simple_list1", "(", "p", ")", ":", "if", "len", "(", "p", ")", "==", "2", ":", "p", "[", "0", "]", "=", "[", "p", "[", "1", "]", "]", "else", ":", "p", "[", "0", "]", "=", "p", "[", "1", "]", "p", "[", "0", "]", ".", "append...
40.5
0.002012
def authorize_handler(self, f): """Authorization handler decorator. This decorator will sort the parameters and headers out, and pre validate everything:: @app.route('/oauth/authorize', methods=['GET', 'POST']) @oauth.authorize_handler def authorize(*args, *...
[ "def", "authorize_handler", "(", "self", ",", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# raise if server not implemented", "server", "=", "self", ".", "server", "uri", ",", "h...
44.423077
0.001976
def get_curvature(nodes, s, tangent_vec, curvature): """Image for :func:`get_curvature` docstring.""" if NO_IMAGES: return curve = bezier.Curve.from_nodes(nodes) # Find the center of the circle along the direction # perpendicular to the tangent vector (90 degree left turn). radius_dir =...
[ "def", "get_curvature", "(", "nodes", ",", "s", ",", "tangent_vec", ",", "curvature", ")", ":", "if", "NO_IMAGES", ":", "return", "curve", "=", "bezier", ".", "Curve", ".", "from_nodes", "(", "nodes", ")", "# Find the center of the circle along the direction", "...
36.961538
0.001014
def timezone(self, tz): """ Set timezone on the audit records. Timezone can be in formats: 'US/Eastern', 'PST', 'Europe/Helsinki' See SMC Log Viewer settings for more examples. :param str tz: timezone, i.e. CST """ self.data['resolving'].update( ...
[ "def", "timezone", "(", "self", ",", "tz", ")", ":", "self", ".", "data", "[", "'resolving'", "]", ".", "update", "(", "timezone", "=", "tz", ",", "time_show_zone", "=", "True", ")" ]
30.5
0.01061
def add(self, datapoint): """ Adds the datapoint to the tensor if room is available. """ if not self.is_full: self.set_datapoint(self.cur_index, datapoint) self.cur_index += 1
[ "def", "add", "(", "self", ",", "datapoint", ")", ":", "if", "not", "self", ".", "is_full", ":", "self", ".", "set_datapoint", "(", "self", ".", "cur_index", ",", "datapoint", ")", "self", ".", "cur_index", "+=", "1" ]
42.2
0.009302
def search_with_retry(self, sleeptime=3.0, retrycount=3, **params): """Perform a search given a dictionary of ``search(...)`` parameters. It accounts for server timeouts as necessary and will retry some number of times. :param sleeptime: number of seconds to sleep between retries ...
[ "def", "search_with_retry", "(", "self", ",", "sleeptime", "=", "3.0", ",", "retrycount", "=", "3", ",", "*", "*", "params", ")", ":", "results", "=", "[", "]", "count", "=", "0", "while", "count", "<", "retrycount", ":", "try", ":", "results", "=", ...
37.36
0.002088
def area_at_zoom(self, zoom=None): """ Return process bounding box for zoom level. Parameters ---------- zoom : int or None if None, the union of all zoom level areas is returned Returns ------- process area : shapely geometry """ ...
[ "def", "area_at_zoom", "(", "self", ",", "zoom", "=", "None", ")", ":", "if", "zoom", "is", "None", ":", "if", "not", "self", ".", "_cache_full_process_area", ":", "logger", ".", "debug", "(", "\"calculate process area ...\"", ")", "self", ".", "_cache_full_...
34.36
0.002265
def dump_viewset(viewset_class, root_folder, folder_fn=lambda i: ".", sample_size=None): """ Dump the contents of a rest-api queryset to a folder structure. :param viewset_class: A rest-api viewset to iterate through :param root_folder: The root folder to write results to. :param folder_fn: A funct...
[ "def", "dump_viewset", "(", "viewset_class", ",", "root_folder", ",", "folder_fn", "=", "lambda", "i", ":", "\".\"", ",", "sample_size", "=", "None", ")", ":", "if", "os", ".", "path", ".", "exists", "(", "root_folder", ")", ":", "shutil", ".", "rmtree",...
36.235294
0.002372
def communicator(func): '''Warning, this is a picklable decorator !''' def _call(queue, args, kwargs): '''called with [queue, args, kwargs] as first optional arg''' kwargs['queue'] = queue ret = None try: ret = func(*args, **kwargs) queue.put('END') ...
[ "def", "communicator", "(", "func", ")", ":", "def", "_call", "(", "queue", ",", "args", ",", "kwargs", ")", ":", "'''called with [queue, args, kwargs] as first optional arg'''", "kwargs", "[", "'queue'", "]", "=", "queue", "ret", "=", "None", "try", ":", "ret...
35.961538
0.001042
def allowed(self): ''' Check to see if the pop request is allowed @return: True means the maximum was not been reached for the current time window, thus allowing what ever operation follows ''' # Expire old keys (hits) expires = time.time() - self.window ...
[ "def", "allowed", "(", "self", ")", ":", "# Expire old keys (hits)", "expires", "=", "time", ".", "time", "(", ")", "-", "self", ".", "window", "self", ".", "redis_conn", ".", "zremrangebyscore", "(", "self", ".", "window_key", ",", "'-inf'", ",", "expires...
38.608696
0.001098
def buildURL(self, action, **query): """Build a URL relative to the server base_url, with the given query parameters added.""" base = urlparse.urljoin(self.server.base_url, action) return appendArgs(base, query)
[ "def", "buildURL", "(", "self", ",", "action", ",", "*", "*", "query", ")", ":", "base", "=", "urlparse", ".", "urljoin", "(", "self", ".", "server", ".", "base_url", ",", "action", ")", "return", "appendArgs", "(", "base", ",", "query", ")" ]
47.8
0.00823
def user(self, user_id): """Fetch user info.""" resource = self.RUSER_INFO params = { self.PUSER: user_id } response = self._fetch(resource, params) return response
[ "def", "user", "(", "self", ",", "user_id", ")", ":", "resource", "=", "self", ".", "RUSER_INFO", "params", "=", "{", "self", ".", "PUSER", ":", "user_id", "}", "response", "=", "self", ".", "_fetch", "(", "resource", ",", "params", ")", "return", "r...
18.083333
0.008772
def file_list(self, tgt_env): ''' Get file list for the target environment using pygit2 ''' def _traverse(tree, blobs, prefix): ''' Traverse through a pygit2 Tree object recursively, accumulating all the file paths and symlink info in the "blobs" dict ...
[ "def", "file_list", "(", "self", ",", "tgt_env", ")", ":", "def", "_traverse", "(", "tree", ",", "blobs", ",", "prefix", ")", ":", "'''\n Traverse through a pygit2 Tree object recursively, accumulating all\n the file paths and symlink info in the \"blobs\" d...
42.839286
0.002037
def initialize_fields(self, content): """ Initializes the :class:`Field` elements in the `Array` with the *values* in the *content* list. If the *content* list is shorter than the `Array` then the *content* list is used as a rotating fill pattern for the :class:`Field` elements ...
[ "def", "initialize_fields", "(", "self", ",", "content", ")", ":", "if", "isinstance", "(", "content", ",", "(", "list", ",", "tuple", ")", ")", ":", "capacity", "=", "len", "(", "content", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(",...
41.657895
0.001235
def create_conf_loader(*args, **kwargs): # pragma: no cover """Create a default configuration loader. .. deprecated:: 1.0.0b1 Use :func:`create_config_loader` instead. This function will be removed in version 1.0.1. """ import warnings warnings.warn( '"create_conf_loader" has...
[ "def", "create_conf_loader", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# pragma: no cover", "import", "warnings", "warnings", ".", "warn", "(", "'\"create_conf_loader\" has been renamed to \"create_config_loader\".'", ",", "DeprecationWarning", ")", "return", ...
33.230769
0.002252
def idPlayerResults(cfg, rawResult): """interpret standard rawResult for all players with known IDs""" result = {} knownPlayers = [] dictResult = {plyrRes.player_id : plyrRes.result for plyrRes in rawResult} for p in cfg.players: if p.playerID and p.playerID in dictResult: # identified playe...
[ "def", "idPlayerResults", "(", "cfg", ",", "rawResult", ")", ":", "result", "=", "{", "}", "knownPlayers", "=", "[", "]", "dictResult", "=", "{", "plyrRes", ".", "player_id", ":", "plyrRes", ".", "result", "for", "plyrRes", "in", "rawResult", "}", "for",...
48.058824
0.008403
def _format_numeric_sequence(self, _sequence, separator="."): """ Length of the highest index in chars = justification size """ if not _sequence: return colorize(_sequence, "purple") _sequence = _sequence if _sequence is not None else self.obj minus = (2 if self._depth > 0 el...
[ "def", "_format_numeric_sequence", "(", "self", ",", "_sequence", ",", "separator", "=", "\".\"", ")", ":", "if", "not", "_sequence", ":", "return", "colorize", "(", "_sequence", ",", "\"purple\"", ")", "_sequence", "=", "_sequence", "if", "_sequence", "is", ...
46.263158
0.00223
def unescape_single_character(match): """ Unescape a single escape sequence found from a MySQL string literal, according to the rules defined at: https://dev.mysql.com/doc/refman/5.6/en/string-literals.html#character-escape-sequences :param match: Regular expression match object. :return: Unes...
[ "def", "unescape_single_character", "(", "match", ")", ":", "value", "=", "match", ".", "group", "(", "0", ")", "assert", "value", ".", "startswith", "(", "\"\\\\\"", ")", "return", "MYSQL_STRING_ESCAPE_SEQUENCE_MAPPING", ".", "get", "(", "value", ")", "or", ...
35.928571
0.001938
def matches_rule(message, rule, destinations = None) : "does Message message match against the specified rule." if not isinstance(message, Message) : raise TypeError("message must be a Message") #end if rule = unformat_rule(rule) eavesdrop = rule.get("eavesdrop", "false") == "true" def ...
[ "def", "matches_rule", "(", "message", ",", "rule", ",", "destinations", "=", "None", ")", ":", "if", "not", "isinstance", "(", "message", ",", "Message", ")", ":", "raise", "TypeError", "(", "\"message must be a Message\"", ")", "#end if", "rule", "=", "unf...
32.251497
0.01549
def clone(self, name=None): """Create full copy of the current table, including table contents and index definitions. """ ret = self.copy_template().insert_many(self.obs)(name) return ret
[ "def", "clone", "(", "self", ",", "name", "=", "None", ")", ":", "ret", "=", "self", ".", "copy_template", "(", ")", ".", "insert_many", "(", "self", ".", "obs", ")", "(", "name", ")", "return", "ret" ]
37.5
0.008696
def sgraph(N_clusters_max, file_name): """Runs METIS or hMETIS and returns the labels found by those (hyper-)graph partitioning algorithms. Parameters ---------- N_clusters_max : int file_name : string Returns ------- labels : array of shape (n_samples,) ...
[ "def", "sgraph", "(", "N_clusters_max", ",", "file_name", ")", ":", "if", "file_name", "==", "'DO_NOT_PROCESS'", ":", "return", "[", "]", "print", "(", "'\\n#'", ")", "k", "=", "str", "(", "N_clusters_max", ")", "out_name", "=", "file_name", "+", "'.part.'...
37.246154
0.011268
def get_pinned_version(ireq): """Get the pinned version of an InstallRequirement. An InstallRequirement is considered pinned if: - Is not editable - It has exactly one specifier - That specifier is "==" - The version does not contain a wildcard Examples: django==1.8 # pinned ...
[ "def", "get_pinned_version", "(", "ireq", ")", ":", "try", ":", "specifier", "=", "ireq", ".", "specifier", "except", "AttributeError", ":", "raise", "TypeError", "(", "\"Expected InstallRequirement, not {}\"", ".", "format", "(", "type", "(", "ireq", ")", ".", ...
31.075
0.00078
def split_authority(authority): """ Basic authority parser that splits authority into component parts >>> split_authority("user:password@host:port") ('user', 'password', 'host', 'port') """ if '@' in authority: userinfo, hostport = authority.split('@', 1) else: use...
[ "def", "split_authority", "(", "authority", ")", ":", "if", "'@'", "in", "authority", ":", "userinfo", ",", "hostport", "=", "authority", ".", "split", "(", "'@'", ",", "1", ")", "else", ":", "userinfo", ",", "hostport", "=", "None", ",", "authority", ...
28.869565
0.001458
def set_focus(self, focus_stage=None, samples=None, subset=None): """ Set the 'focus' attribute of the data file. The 'focus' attribute of the object points towards data from a particular stage of analysis. It is used to identify the 'working stage' of the data. Processing funct...
[ "def", "set_focus", "(", "self", ",", "focus_stage", "=", "None", ",", "samples", "=", "None", ",", "subset", "=", "None", ")", ":", "if", "samples", "is", "not", "None", ":", "subset", "=", "self", ".", "make_subset", "(", "samples", ")", "if", "sub...
32.979167
0.002454
def coefficient_between_units(unit_a, unit_b): """A helper to get the coefficient between two units. :param unit_a: The first unit. :type unit_a: safe.definitions.units :param unit_b: The second unit. :type unit_b: safe.definitions.units :return: The coefficient between these two units. :...
[ "def", "coefficient_between_units", "(", "unit_a", ",", "unit_b", ")", ":", "for", "mapping", "in", "unit_mapping", ":", "if", "unit_a", "==", "mapping", "[", "0", "]", "and", "unit_b", "==", "mapping", "[", "1", "]", ":", "return", "mapping", "[", "2", ...
29.052632
0.001754
def is_buffer(self, address, size): """ Determines if the given memory area is a valid code or data buffer. @note: Returns always C{False} for kernel mode addresses. @see: L{mquery} @type address: int @param address: Memory address. @type size: int @...
[ "def", "is_buffer", "(", "self", ",", "address", ",", "size", ")", ":", "if", "size", "<=", "0", ":", "raise", "ValueError", "(", "\"The size argument must be greater than zero\"", ")", "while", "size", ">", "0", ":", "try", ":", "mbi", "=", "self", ".", ...
31.971429
0.001735
def dft_optsize(im, shape=None): """Resize image for optimal DFT and computes it Parameters ---------- im: 2d array The image shape: 2 numbers, optional The shape of the output image (None will optimize the shape) Returns ------- dft: 2d array The dft in CCS rep...
[ "def", "dft_optsize", "(", "im", ",", "shape", "=", "None", ")", ":", "im", "=", "np", ".", "asarray", "(", "im", ")", "# save shape", "initshape", "=", "im", ".", "shape", "# get optimal size", "if", "shape", "is", "None", ":", "ys", "=", "cv2", "."...
28.176471
0.001009
def on_created(self, event): """On created method""" for delegate in self.delegates: if hasattr(delegate, "on_created"): delegate.on_created(event)
[ "def", "on_created", "(", "self", ",", "event", ")", ":", "for", "delegate", "in", "self", ".", "delegates", ":", "if", "hasattr", "(", "delegate", ",", "\"on_created\"", ")", ":", "delegate", ".", "on_created", "(", "event", ")" ]
37.4
0.010471
def _arithmetic_operation(self, other, operation): """ Applies an operation between the values of a trajectories and a scalar or between the respective values of two trajectories. In the latter case, trajectories should have equal descriptions and time points """ if isins...
[ "def", "_arithmetic_operation", "(", "self", ",", "other", ",", "operation", ")", ":", "if", "isinstance", "(", "other", ",", "TrajectoryWithSensitivityData", ")", ":", "if", "self", ".", "description", "!=", "other", ".", "description", ":", "raise", "Excepti...
57.791667
0.008511
def get_row(self, row_index): """Returns the row at row_index.""" if self._raw_rows is None: self._raw_rows = list(self.raw_sheet.rows()) return self._raw_rows[row_index]
[ "def", "get_row", "(", "self", ",", "row_index", ")", ":", "if", "self", ".", "_raw_rows", "is", "None", ":", "self", ".", "_raw_rows", "=", "list", "(", "self", ".", "raw_sheet", ".", "rows", "(", ")", ")", "return", "self", ".", "_raw_rows", "[", ...
36.8
0.010638
def rprof_h5(rproffile, colnames): """Extract radial profiles data If :data:`colnames` is too long, it will be truncated. If it is too short, additional column names will be deduced from the content of the file. Args: rproffile (:class:`pathlib.Path`): path of the rprof.dat file. colna...
[ "def", "rprof_h5", "(", "rproffile", ",", "colnames", ")", ":", "if", "not", "rproffile", ".", "is_file", "(", ")", ":", "return", "None", ",", "None", "isteps", "=", "[", "]", "with", "h5py", ".", "File", "(", "rproffile", ")", "as", "h5f", ":", "...
38.522727
0.000575
def parse_fields_http(self, response, extra_org_map=None): """ The function for parsing ASN fields from a http response. Args: response (:obj:`str`): The response from the ASN http server. extra_org_map (:obj:`dict`): Dictionary mapping org handles to RIR...
[ "def", "parse_fields_http", "(", "self", ",", "response", ",", "extra_org_map", "=", "None", ")", ":", "# Set the org_map. Map the orgRef handle to an RIR.", "org_map", "=", "self", ".", "org_map", ".", "copy", "(", ")", "try", ":", "org_map", ".", "update", "("...
30.777778
0.000636
def stretch(self, factor, window=20): '''Change the audio duration (but not its pitch). **Unless factor is close to 1, use the tempo effect instead.** This effect is broadly equivalent to the tempo effect with search set to zero, so in general, its results are comparatively poor; it is ...
[ "def", "stretch", "(", "self", ",", "factor", ",", "window", "=", "20", ")", ":", "if", "not", "is_number", "(", "factor", ")", "or", "factor", "<=", "0", ":", "raise", "ValueError", "(", "\"factor must be a positive number\"", ")", "if", "factor", "<", ...
33.571429
0.001181
def pick_kwargs(kwargs: dict, required_args: list, prefix: str = None): """ Given a dict of kwargs and a list of required_args, return a dict containing only the args in required_args. If prefix is specified, also search for args that begin with '{prefix}__'. Removes prefix in returned dict. R...
[ "def", "pick_kwargs", "(", "kwargs", ":", "dict", ",", "required_args", ":", "list", ",", "prefix", ":", "str", "=", "None", ")", ":", "picked", "=", "{", "k", ":", "v", "for", "k", ",", "v", "in", "kwargs", ".", "items", "(", ")", "if", "k", "...
34.714286
0.000667
def handle_keypress(self): """When hitting tab, it handles if single or double tab""" if self.numpress == 2: self.sig_double_tab_pressed.emit(True) self.numpress = 0
[ "def", "handle_keypress", "(", "self", ")", ":", "if", "self", ".", "numpress", "==", "2", ":", "self", ".", "sig_double_tab_pressed", ".", "emit", "(", "True", ")", "self", ".", "numpress", "=", "0" ]
40.2
0.009756
def _load_signal_data(self, address=None, stream=None, group=None, index=None): """ this method is used to get the channel signal data, usually for VLSD channels Parameters ---------- address : int address of refrerenced block stream : handle file...
[ "def", "_load_signal_data", "(", "self", ",", "address", "=", "None", ",", "stream", "=", "None", ",", "group", "=", "None", ",", "index", "=", "None", ")", ":", "if", "address", "==", "0", ":", "data", "=", "b\"\"", "elif", "address", "is", "not", ...
39.633663
0.00195
def re_raise(self): """ Raise this exception with the original traceback """ if self.exc_info is not None: six.reraise(type(self), self, self.exc_info[2]) else: raise self
[ "def", "re_raise", "(", "self", ")", ":", "if", "self", ".", "exc_info", "is", "not", "None", ":", "six", ".", "reraise", "(", "type", "(", "self", ")", ",", "self", ",", "self", ".", "exc_info", "[", "2", "]", ")", "else", ":", "raise", "self" ]
35.666667
0.009132
def _sendStatCmd(self, cmd): """Send stat command to Memcached Server and return response lines. @param cmd: Command string. @return: Array of strings. """ try: self._conn.write("%s\r\n" % cmd) regex = re.compile('^(END|ERROR)\r\n', r...
[ "def", "_sendStatCmd", "(", "self", ",", "cmd", ")", ":", "try", ":", "self", ".", "_conn", ".", "write", "(", "\"%s\\r\\n\"", "%", "cmd", ")", "regex", "=", "re", ".", "compile", "(", "'^(END|ERROR)\\r\\n'", ",", "re", ".", "MULTILINE", ")", "(", "i...
42.047619
0.012182
def parFactory(fields, strict=0): """parameter factory function fields is a list of the comma-separated fields (as in the .par file). Each entry is a string or None (indicating that field was omitted.) Set the strict parameter to a non-zero value to do stricter parsing (to find errors in the inpu...
[ "def", "parFactory", "(", "fields", ",", "strict", "=", "0", ")", ":", "if", "len", "(", "fields", ")", "<", "3", "or", "None", "in", "fields", "[", "0", ":", "3", "]", ":", "raise", "SyntaxError", "(", "\"At least 3 fields must be given\"", ")", "type...
32.945946
0.008765
def getProperty(self, key, defaultValue=None): """ Fetch the value associated with the key ``key`` in the `Properties` object. If the key is not present, `defaults` is checked, and then *its* `defaults`, etc., until either a value for ``key`` is found or the next `defaults` is `...
[ "def", "getProperty", "(", "self", ",", "key", ",", "defaultValue", "=", "None", ")", ":", "try", ":", "return", "self", "[", "key", "]", "except", "KeyError", ":", "if", "self", ".", "defaults", "is", "not", "None", ":", "return", "self", ".", "defa...
40.863636
0.002174
def diskwarp_multi(src_ds_list, res='first', extent='intersection', t_srs='first', r='cubic', verbose=True, outdir=None, dst_ndv=None): """Helper function for diskwarp of multiple input GDAL Datasets """ return warp_multi(src_ds_list, res, extent, t_srs, r, verbose=verbose, warptype=diskwarp, outdir=outdir,...
[ "def", "diskwarp_multi", "(", "src_ds_list", ",", "res", "=", "'first'", ",", "extent", "=", "'intersection'", ",", "t_srs", "=", "'first'", ",", "r", "=", "'cubic'", ",", "verbose", "=", "True", ",", "outdir", "=", "None", ",", "dst_ndv", "=", "None", ...
83.5
0.008902
def make_abstract_dist(req): # type: (InstallRequirement) -> DistAbstraction """Factory to make an abstract dist object. Preconditions: Either an editable req with a source_dir, or satisfied_by or a wheel link, or a non-editable req with a source_dir. :return: A concrete DistAbstraction. """ ...
[ "def", "make_abstract_dist", "(", "req", ")", ":", "# type: (InstallRequirement) -> DistAbstraction", "if", "req", ".", "editable", ":", "return", "IsSDist", "(", "req", ")", "elif", "req", ".", "link", "and", "req", ".", "link", ".", "is_wheel", ":", "return"...
30.666667
0.00211
def get_group_members(self, group_name='confluence-users', start=0, limit=1000): """ Get a paginated collection of users in the given group :param group_name :param start: OPTIONAL: The start point of the collection to return. Default: None (0). :param limit: OPTIONAL: The limit ...
[ "def", "get_group_members", "(", "self", ",", "group_name", "=", "'confluence-users'", ",", "start", "=", "0", ",", "limit", "=", "1000", ")", ":", "url", "=", "'rest/api/group/{group_name}/member?limit={limit}&start={start}'", ".", "format", "(", "group_name", "=",...
62.923077
0.009639
def add(args): """ cdstarcat add SPEC Add metadata about objects (specified by SPEC) in CDSTAR to the catalog. SPEC: Either a CDSTAR object ID or a query. """ spec = args.args[0] with _catalog(args) as cat: n = len(cat) if OBJID_PATTERN.match(spec): cat.add_objid...
[ "def", "add", "(", "args", ")", ":", "spec", "=", "args", ".", "args", "[", "0", "]", "with", "_catalog", "(", "args", ")", "as", "cat", ":", "n", "=", "len", "(", "cat", ")", "if", "OBJID_PATTERN", ".", "match", "(", "spec", ")", ":", "cat", ...
31.352941
0.001821
def _parsePageToken(pageToken, numValues): """ Parses the specified pageToken and returns a list of the specified number of values. Page tokens are assumed to consist of a fixed number of integers seperated by colons. If the page token does not conform to this specification, raise a InvalidPageToken...
[ "def", "_parsePageToken", "(", "pageToken", ",", "numValues", ")", ":", "tokens", "=", "pageToken", ".", "split", "(", "\":\"", ")", "if", "len", "(", "tokens", ")", "!=", "numValues", ":", "msg", "=", "\"Invalid number of values in page token\"", "raise", "ex...
38.055556
0.001425
def get_jid(jid): ''' Return the information returned when the specified job id was executed ''' serv = _get_serv(ret=None) sql = "select id, full_ret from returns where jid = '{0}'".format(jid) data = serv.query(sql) ret = {} if data: points = data[0]['points'] for poi...
[ "def", "get_jid", "(", "jid", ")", ":", "serv", "=", "_get_serv", "(", "ret", "=", "None", ")", "sql", "=", "\"select id, full_ret from returns where jid = '{0}'\"", ".", "format", "(", "jid", ")", "data", "=", "serv", ".", "query", "(", "sql", ")", "ret",...
24.625
0.002445
def coeffArraySizeCheck(self): """ Make sure that q0 and coefficient array are the right size compared to each other (for finite difference if loading a pre-build coefficient array). Otherwise, exit. """ if prod(self.coeff_matrix.shape) != long(prod(np.array(self.qs.shape,dtype=int64)+2)**2): ...
[ "def", "coeffArraySizeCheck", "(", "self", ")", ":", "if", "prod", "(", "self", ".", "coeff_matrix", ".", "shape", ")", "!=", "long", "(", "prod", "(", "np", ".", "array", "(", "self", ".", "qs", ".", "shape", ",", "dtype", "=", "int64", ")", "+", ...
41.9
0.016355
def create(name, profile="splunk", **kwargs): ''' Create a splunk search CLI Example: splunk_search.create 'my search name' search='error msg' ''' client = _get_splunk(profile) search = client.saved_searches.create(name, **kwargs) # use the REST API to set owner and permissions ...
[ "def", "create", "(", "name", ",", "profile", "=", "\"splunk\"", ",", "*", "*", "kwargs", ")", ":", "client", "=", "_get_splunk", "(", "profile", ")", "search", "=", "client", ".", "saved_searches", ".", "create", "(", "name", ",", "*", "*", "kwargs", ...
34.259259
0.001052
def import_setting(file_path, qsettings=None): """Import InaSAFE's setting from a file. :param file_path: The file to read the imported setting. :type file_path: basestring :param qsettings: A custom QSettings to use. If it's not defined, it will use the default one. :type qsettings: qgis....
[ "def", "import_setting", "(", "file_path", ",", "qsettings", "=", "None", ")", ":", "with", "open", "(", "file_path", ",", "'r'", ")", "as", "f", ":", "inasafe_settings", "=", "json", ".", "load", "(", "f", ")", "if", "not", "qsettings", ":", "qsetting...
27.892857
0.001238
def wait(animation='elipses', text='', speed=0.2): """ Decorator for adding wait animation to long running functions. Args: animation (str, tuple): String reference to animation or tuple with custom animation. speed (float): Number of seconds each cycle of animation. Ex...
[ "def", "wait", "(", "animation", "=", "'elipses'", ",", "text", "=", "''", ",", "speed", "=", "0.2", ")", ":", "def", "decorator", "(", "func", ")", ":", "func", ".", "animation", "=", "animation", "func", ".", "speed", "=", "speed", "func", ".", "...
30.769231
0.000808
def time_recommendation(move_num, seconds_per_move=5, time_limit=15 * 60, decay_factor=0.98): """Given the current move number and the 'desired' seconds per move, return how much time should actually be used. This is intended specifically for CGOS time controls, which has an absolute...
[ "def", "time_recommendation", "(", "move_num", ",", "seconds_per_move", "=", "5", ",", "time_limit", "=", "15", "*", "60", ",", "decay_factor", "=", "0.98", ")", ":", "# Divide by two since you only play half the moves in a game.", "player_move_num", "=", "move_num", ...
46.666667
0.000778
def arp_ip(opcode, src_mac, src_ip, dst_mac, dst_ip): """A convenient wrapper for IPv4 ARP for Ethernet. This is an equivalent of the following code. arp(ARP_HW_TYPE_ETHERNET, ether.ETH_TYPE_IP, \ 6, 4, opcode, src_mac, src_ip, dst_mac, dst_ip) """ return arp(ARP_HW_TYPE_ETHERNE...
[ "def", "arp_ip", "(", "opcode", ",", "src_mac", ",", "src_ip", ",", "dst_mac", ",", "dst_ip", ")", ":", "return", "arp", "(", "ARP_HW_TYPE_ETHERNET", ",", "ether", ".", "ETH_TYPE_IP", ",", "6", ",", "# ether mac address length", "4", ",", "# ipv4 address lengt...
39.583333
0.002058
def _googleauth(key_file=None, scopes=[], user_agent=None): """ Google http_auth helper. If key_file is not specified, default credentials will be used. If scopes is specified (and key_file), will be used instead of DEFAULT_SCOPES :param key_file: path to key file to use. Default is None :typ...
[ "def", "_googleauth", "(", "key_file", "=", "None", ",", "scopes", "=", "[", "]", ",", "user_agent", "=", "None", ")", ":", "if", "key_file", ":", "if", "not", "scopes", ":", "scopes", "=", "DEFAULT_SCOPES", "creds", "=", "ServiceAccountCredentials", ".", ...
32.4375
0.001871
def color(self, s, color=None, bold=False): """ :param str s: :param str|None color: sth in self.ColorIdxTable :param bool bold: :return: s optionally wrapped with ansi escape codes :rtype: str """ if not self.enable: return s code_seq ...
[ "def", "color", "(", "self", ",", "s", ",", "color", "=", "None", ",", "bold", "=", "False", ")", ":", "if", "not", "self", ".", "enable", ":", "return", "s", "code_seq", "=", "[", "]", "if", "color", ":", "code_seq", "+=", "[", "30", "+", "sel...
31.384615
0.002378
def get_all_boards(*args, **kwargs): """Returns every board on 4chan. Returns: dict of :class:`basc_py4chan.Board`: All boards. """ # Use https based on how the Board class instances are to be instantiated https = kwargs.get('https', args[1] if len(args) > 1 else False) # Dummy URL gen...
[ "def", "get_all_boards", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Use https based on how the Board class instances are to be instantiated", "https", "=", "kwargs", ".", "get", "(", "'https'", ",", "args", "[", "1", "]", "if", "len", "(", "args", ...
38.142857
0.001828
def _get_page_title(self, page): """ Open the rst file `page` and extract its title. """ fname = os.path.join(SOURCE_PATH, '{}.rst'.format(page)) option_parser = docutils.frontend.OptionParser( components=(docutils.parsers.rst.Parser,)) doc = docutils.utils.ne...
[ "def", "_get_page_title", "(", "self", ",", "page", ")", ":", "fname", "=", "os", ".", "path", ".", "join", "(", "SOURCE_PATH", ",", "'{}.rst'", ".", "format", "(", "page", ")", ")", "option_parser", "=", "docutils", ".", "frontend", ".", "OptionParser",...
37.08
0.002103
def save_anim(self, fig, animate, init, bitrate=10000, fps=30): """Not functional -- TODO""" from matplotlib import animation anim = animation.FuncAnimation(fig, animate, init_func=init, frames=360, interval=20) FFMpegWriter = animation.writers['ffmpeg'] writer = FFMpegWriter(bit...
[ "def", "save_anim", "(", "self", ",", "fig", ",", "animate", ",", "init", ",", "bitrate", "=", "10000", ",", "fps", "=", "30", ")", ":", "from", "matplotlib", "import", "animation", "anim", "=", "animation", ".", "FuncAnimation", "(", "fig", ",", "anim...
53.222222
0.008214
def vrf_add(self, route_dist, import_rts, export_rts, site_of_origins=None, route_family=RF_VPN_V4, multi_exit_disc=None): """ This method adds a new vrf used for VPN. ``route_dist`` specifies a route distinguisher value. ``import_rts`` specifies a list of route targets to be i...
[ "def", "vrf_add", "(", "self", ",", "route_dist", ",", "import_rts", ",", "export_rts", ",", "site_of_origins", "=", "None", ",", "route_family", "=", "RF_VPN_V4", ",", "multi_exit_disc", "=", "None", ")", ":", "if", "route_family", "not", "in", "SUPPORTED_VRF...
36.179487
0.00207
def get_storage(request): """ Gets a Credentials storage object provided by the Django OAuth2 Helper object. Args: request: Reference to the current request object. Returns: An :class:`oauth2.client.Storage` object. """ storage_model = oauth2_settings.storage_model user_prop...
[ "def", "get_storage", "(", "request", ")", ":", "storage_model", "=", "oauth2_settings", ".", "storage_model", "user_property", "=", "oauth2_settings", ".", "storage_model_user_property", "credentials_property", "=", "oauth2_settings", ".", "storage_model_credentials_property...
38.038462
0.000986
def read_mol2_from_list(self, mol2_lines, mol2_code, columns=None): r"""Reads Mol2 file from a list into DataFrames Attributes ---------- mol2_lines : list A list of lines containing the mol2 file contents. For example, ['@<TRIPOS>MOLECULE\n', 'ZINC3...
[ "def", "read_mol2_from_list", "(", "self", ",", "mol2_lines", ",", "mol2_code", ",", "columns", "=", "None", ")", ":", "self", ".", "_load_mol2", "(", "mol2_lines", ",", "mol2_code", ",", "columns", ")", "return", "self" ]
36.95
0.001318
def kill(self): '''Kills Entity''' if self._world: self._world.remove_entity(self, True) self._world = None self._tag = None self._uuid = None self._components = None
[ "def", "kill", "(", "self", ")", ":", "if", "self", ".", "_world", ":", "self", ".", "_world", ".", "remove_entity", "(", "self", ",", "True", ")", "self", ".", "_world", "=", "None", "self", ".", "_tag", "=", "None", "self", ".", "_uuid", "=", "...
27.875
0.008696
def load_feedback(): """ Open existing feedback file """ result = {} if os.path.exists(_feedback_file): f = open(_feedback_file, 'r') cont = f.read() f.close() else: cont = '{}' try: result = json.loads(cont) if cont else {} except ValueError as e: ...
[ "def", "load_feedback", "(", ")", ":", "result", "=", "{", "}", "if", "os", ".", "path", ".", "exists", "(", "_feedback_file", ")", ":", "f", "=", "open", "(", "_feedback_file", ",", "'r'", ")", "cont", "=", "f", ".", "read", "(", ")", "f", ".", ...
27
0.009547
def _validate_usecols_names(usecols, names): """ Validates that all usecols are present in a given list of names. If not, raise a ValueError that shows what usecols are missing. Parameters ---------- usecols : iterable of usecols The columns to validate are present in names. nam...
[ "def", "_validate_usecols_names", "(", "usecols", ",", "names", ")", ":", "missing", "=", "[", "c", "for", "c", "in", "usecols", "if", "c", "not", "in", "names", "]", "if", "len", "(", "missing", ")", ">", "0", ":", "raise", "ValueError", "(", "\"Use...
27.8
0.001159
def aa_counts(aln, weights=None, gap_chars='-.'): """Calculate the amino acid frequencies in a set of SeqRecords. Weights for each sequence in the alignment can be given as a list/tuple, usually calculated with the sequence_weights function. For convenience, you can also pass "weights=True" and the wei...
[ "def", "aa_counts", "(", "aln", ",", "weights", "=", "None", ",", "gap_chars", "=", "'-.'", ")", ":", "if", "weights", "is", "None", ":", "counts", "=", "Counter", "(", ")", "for", "rec", "in", "aln", ":", "seq_counts", "=", "Counter", "(", "str", ...
34.677419
0.00181
def clean_data(data): """ Shift to lower case, replace unknowns with UNK, and listify """ new_data = [] VALID = 'abcdefghijklmnopqrstuvwxyz123456789"\'?!.,:; ' for sample in data: new_sample = [] for char in sample[1].lower(): # Just grab the string, not the label if char in...
[ "def", "clean_data", "(", "data", ")", ":", "new_data", "=", "[", "]", "VALID", "=", "'abcdefghijklmnopqrstuvwxyz123456789\"\\'?!.,:; '", "for", "sample", "in", "data", ":", "new_sample", "=", "[", "]", "for", "char", "in", "sample", "[", "1", "]", ".", "l...
33.571429
0.00207
def post_stats(cls, stats_url, stats, timeout=2, auth_provider=None): """POST stats to the given url. :return: True if upload was successful, False otherwise. """ def error(msg): # Report aleady closed, so just print error. print('WARNING: Failed to upload stats to {}. due to {}'.format(sta...
[ "def", "post_stats", "(", "cls", ",", "stats_url", ",", "stats", ",", "timeout", "=", "2", ",", "auth_provider", "=", "None", ")", ":", "def", "error", "(", "msg", ")", ":", "# Report aleady closed, so just print error.", "print", "(", "'WARNING: Failed to uploa...
52.302326
0.010476
def export_msdt(self, filename): """ Writes MSD data to a csv file that can be easily plotted in other software. Args: filename (str): Filename. Supported formats are csv and dat. If the extension is csv, a csv file is written. Otherwise, a da...
[ "def", "export_msdt", "(", "self", ",", "filename", ")", ":", "fmt", "=", "\"csv\"", "if", "filename", ".", "lower", "(", ")", ".", "endswith", "(", "\".csv\"", ")", "else", "\"dat\"", "delimiter", "=", "\", \"", "if", "fmt", "==", "\"csv\"", "else", "...
42.434783
0.002004
def write_astrom_data(self, astrom_data): """ Writes a full AstromData structure at once. """ self.write_headers(astrom_data.observations, astrom_data.sys_header) self._write_source_data(astrom_data.sources)
[ "def", "write_astrom_data", "(", "self", ",", "astrom_data", ")", ":", "self", ".", "write_headers", "(", "astrom_data", ".", "observations", ",", "astrom_data", ".", "sys_header", ")", "self", ".", "_write_source_data", "(", "astrom_data", ".", "sources", ")" ]
40.333333
0.008097
def _Region4(P, x): """Basic equation for region 4 Parameters ---------- P : float Pressure, [MPa] x : float Vapor quality, [-] Returns ------- prop : dict Dict with calculated properties. The available properties are: * T: Saturated temperature, [K...
[ "def", "_Region4", "(", "P", ",", "x", ")", ":", "T", "=", "_TSat_P", "(", "P", ")", "if", "T", ">", "623.15", ":", "rhol", "=", "1.", "/", "_Backward3_sat_v_P", "(", "P", ",", "T", ",", "0", ")", "P1", "=", "_Region3", "(", "rhol", ",", "T",...
26.108696
0.000803
def parse_options(): """ Parses command-line option """ try: opts, args = getopt.getopt(sys.argv[1:], 'ac:e:hilms:t:vx', ['adapt', 'comp=', 'enum=', 'exhaust', 'help', 'incr', 'blo', 'minimize', 'solver=', 'trim=', 'verbose']) except getopt.GetoptErro...
[ "def", "parse_options", "(", ")", ":", "try", ":", "opts", ",", "args", "=", "getopt", ".", "getopt", "(", "sys", ".", "argv", "[", "1", ":", "]", ",", "'ac:e:hilms:t:vx'", ",", "[", "'adapt'", ",", "'comp='", ",", "'enum='", ",", "'exhaust'", ",", ...
27.517241
0.001815
def correct(text: str, matches: [Match]) -> str: """Automatically apply suggestions to the text.""" ltext = list(text) matches = [match for match in matches if match.replacements] errors = [ltext[match.offset:match.offset + match.errorlength] for match in matches] correct_offset = 0 ...
[ "def", "correct", "(", "text", ":", "str", ",", "matches", ":", "[", "Match", "]", ")", "->", "str", ":", "ltext", "=", "list", "(", "text", ")", "matches", "=", "[", "match", "for", "match", "in", "matches", "if", "match", ".", "replacements", "]"...
43.8125
0.001397
def hdf_injtype_from_approximant(approximant): """Gets the HDFInjectionSet class to use with the given approximant. Parameters ---------- approximant : str Name of the approximant. Returns ------- HDFInjectionSet : The type of HDFInjectionSet to use. """ retcls = No...
[ "def", "hdf_injtype_from_approximant", "(", "approximant", ")", ":", "retcls", "=", "None", "for", "cls", "in", "hdfinjtypes", ".", "values", "(", ")", ":", "if", "approximant", "in", "cls", ".", "supported_approximants", "(", ")", ":", "retcls", "=", "cls",...
28.318182
0.001553
def _stop_cpulimit(self): """ Stops the cpulimit process. """ if self._cpulimit_process and self._cpulimit_process.returncode is None: self._cpulimit_process.kill() try: self._process.wait(3) except subprocess.TimeoutExpired: ...
[ "def", "_stop_cpulimit", "(", "self", ")", ":", "if", "self", ".", "_cpulimit_process", "and", "self", ".", "_cpulimit_process", ".", "returncode", "is", "None", ":", "self", ".", "_cpulimit_process", ".", "kill", "(", ")", "try", ":", "self", ".", "_proce...
36.272727
0.00978
def deepnn(x): """deepnn builds the graph for a deep net for classifying digits. Args: x: an input tensor with the dimensions (N_examples, 784), where 784 is the number of pixels in a standard MNIST image. Returns: A tuple (y, keep_prob). y is a tensor of shape (N_examples, 10)...
[ "def", "deepnn", "(", "x", ")", ":", "# Reshape to use within a convolutional neural net.", "# Last dimension is for \"features\" - there is only one here, since images", "# are grayscale -- it would be 3 for an RGB image, 4 for RGBA, etc.", "with", "tf", ".", "name_scope", "(", "\"resha...
39.032787
0.00041
async def sonar_read(self, command): """ This method retrieves the last sonar data value that was cached. This is a polling method. After sonar config, sonar_data_reply messages will be sent automatically. :param command: {"method": "sonar_read", "params": [TRIGGER_PIN]} :returns...
[ "async", "def", "sonar_read", "(", "self", ",", "command", ")", ":", "pin", "=", "int", "(", "command", "[", "0", "]", ")", "val", "=", "await", "self", ".", "core", ".", "sonar_data_retrieve", "(", "pin", ")", "reply", "=", "json", ".", "dumps", "...
49.75
0.008224
def locate_spheres(image, feature_rad, dofilter=False, order=(3 ,3, 3), trim_edge=True, **kwargs): """ Get an initial featuring of sphere positions in an image. Parameters ----------- image : :class:`peri.util.Image` object Image object which defines the image file as we...
[ "def", "locate_spheres", "(", "image", ",", "feature_rad", ",", "dofilter", "=", "False", ",", "order", "=", "(", "3", ",", "3", ",", "3", ")", ",", "trim_edge", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# We just want a smoothed field model of the ...
41.693548
0.002268
def process(self): """! @brief Perform graph coloring using DSATUR algorithm. @see get_colors() """ color_counter = 1; degrees = list(); saturation_degrees = [0] * len(self.__data_pointer); self.__coloring = [0] ...
[ "def", "process", "(", "self", ")", ":", "color_counter", "=", "1", "degrees", "=", "list", "(", ")", "saturation_degrees", "=", "[", "0", "]", "*", "len", "(", "self", ".", "__data_pointer", ")", "self", ".", "__coloring", "=", "[", "0", "]", "*", ...
43.961039
0.017914
def set_verbosity(verbosity): """Banana banana """ Logger._verbosity = min(max(0, WARNING - verbosity), 2) debug("Verbosity set to %d" % (WARNING - Logger._verbosity), 'logging')
[ "def", "set_verbosity", "(", "verbosity", ")", ":", "Logger", ".", "_verbosity", "=", "min", "(", "max", "(", "0", ",", "WARNING", "-", "verbosity", ")", ",", "2", ")", "debug", "(", "\"Verbosity set to %d\"", "%", "(", "WARNING", "-", "Logger", ".", "...
41.2
0.009524
def on_batch_begin(self, train, **kwargs:Any)->None: "Record learning rate and momentum at beginning of batch." if train: self.lrs.append(self.opt.lr) self.moms.append(self.opt.mom)
[ "def", "on_batch_begin", "(", "self", ",", "train", ",", "*", "*", "kwargs", ":", "Any", ")", "->", "None", ":", "if", "train", ":", "self", ".", "lrs", ".", "append", "(", "self", ".", "opt", ".", "lr", ")", "self", ".", "moms", ".", "append", ...
43.4
0.0181
def merge (d, o): """Recursively merges keys from o into d and returns d.""" for k in o.keys(): if type(o[k]) is dict and k in d: merge(d[k], o[k]) else: d[k] = o[k] return d
[ "def", "merge", "(", "d", ",", "o", ")", ":", "for", "k", "in", "o", ".", "keys", "(", ")", ":", "if", "type", "(", "o", "[", "k", "]", ")", "is", "dict", "and", "k", "in", "d", ":", "merge", "(", "d", "[", "k", "]", ",", "o", "[", "k...
27.375
0.00885
def cholesky_concat(chol, cols, name=None): """Concatenates `chol @ chol.T` with additional rows and columns. This operation is conceptually identical to: ```python def cholesky_concat_slow(chol, cols): # cols shaped (n + m) x m = z x m mat = tf.matmul(chol, chol, adjoint_b=True) # batch of n x n # C...
[ "def", "cholesky_concat", "(", "chol", ",", "cols", ",", "name", "=", "None", ")", ":", "with", "tf", ".", "compat", ".", "v2", ".", "name_scope", "(", "name", "or", "'cholesky_extend'", ")", ":", "dtype", "=", "dtype_util", ".", "common_dtype", "(", "...
45.625
0.001916
def evaluate_cut(uncut_subsystem, cut, unpartitioned_ces): """Compute the system irreducibility for a given cut. Args: uncut_subsystem (Subsystem): The subsystem without the cut applied. cut (Cut): The cut to evaluate. unpartitioned_ces (CauseEffectStructure): The cause-effect structure...
[ "def", "evaluate_cut", "(", "uncut_subsystem", ",", "cut", ",", "unpartitioned_ces", ")", ":", "log", ".", "debug", "(", "'Evaluating %s...'", ",", "cut", ")", "cut_subsystem", "=", "uncut_subsystem", ".", "apply_cut", "(", "cut", ")", "if", "config", ".", "...
33.210526
0.00077
def get_attached_bytes_map(meta_graph): """Returns the dict of ModuleAttachments stored in `meta_graph`. Args: meta_graph: A MetaGraphDef, as built by SavedModelHandler.add_graph_copy() from some graph. Returns: A dict, containing the `(key, bytes)` items passed to `attach_bytes()` when the gr...
[ "def", "get_attached_bytes_map", "(", "meta_graph", ")", ":", "result", "=", "{", "}", "if", "ATTACHMENT_COLLECTION_SAVED", "not", "in", "meta_graph", ".", "collection_def", ":", "return", "result", "collection_def", "=", "meta_graph", ".", "collection_def", "[", ...
36.888889
0.008806
def validity_index(X, labels, metric='euclidean', d=None, per_cluster_scores=False, **kwd_args): """ Compute the density based cluster validity index for the clustering specified by `labels` and for each cluster in `labels`. Parameters ---------- X : array (n_samples, n_featu...
[ "def", "validity_index", "(", "X", ",", "labels", ",", "metric", "=", "'euclidean'", ",", "d", "=", "None", ",", "per_cluster_scores", "=", "False", ",", "*", "*", "kwd_args", ")", ":", "core_distances", "=", "{", "}", "density_sparseness", "=", "{", "}"...
34.349593
0.00023
def get_exported_interfaces(svc_ref, overriding_props=None): # type: (ServiceReference, Optional[Dict[str, Any]]) -> Optional[List[str]] """ Looks for the interfaces exported by a service :param svc_ref: Service reference :param overriding_props: Properties overriding service ones :return: The ...
[ "def", "get_exported_interfaces", "(", "svc_ref", ",", "overriding_props", "=", "None", ")", ":", "# type: (ServiceReference, Optional[Dict[str, Any]]) -> Optional[List[str]]", "# first check overriding_props for service.exported.interfaces", "exported_intfs", "=", "get_prop_value", "(...
34.434783
0.001229
def output(self, name: str, value: Any): """ Export a stack output with a given name and value. """ self.outputs[name] = value
[ "def", "output", "(", "self", ",", "name", ":", "str", ",", "value", ":", "Any", ")", ":", "self", ".", "outputs", "[", "name", "]", "=", "value" ]
30.8
0.012658
def addDesktopResource(self, pluginSubPath: bytes, resource: BasicResource) -> None: """ Add Site Resource Add a cusotom implementation of a served http resource. :param pluginSubPath: The resource path where you want to serve this resource. :param resource: The resource to serve. ...
[ "def", "addDesktopResource", "(", "self", ",", "pluginSubPath", ":", "bytes", ",", "resource", ":", "BasicResource", ")", "->", "None", ":", "pluginSubPath", "=", "pluginSubPath", ".", "strip", "(", "b'/'", ")", "self", ".", "__rootDesktopResource", ".", "putC...
38.166667
0.008529
def mpl_weight2qt(weight): """Convert a weight from matplotlib definition to a Qt weight Parameters ---------- weight: int or string Either an integer between 1 and 1000 or a string out of :attr:`weights_mpl2qt` Returns ------- int One type of the PyQt5.QtGui.QFont....
[ "def", "mpl_weight2qt", "(", "weight", ")", ":", "try", ":", "weight", "=", "weights_mpl2qt", "[", "weight", "]", "except", "KeyError", ":", "try", ":", "weight", "=", "float", "(", "weight", ")", "/", "10", "except", "(", "ValueError", ",", "TypeError",...
28.37037
0.001263
def GetSubkeys(self): """Retrieves all subkeys within the key. Yields: WinRegistryKey: Windows Registry subkey. """ for pyregf_key in self._pyregf_key.sub_keys: key_path = key_paths.JoinKeyPath([self._key_path, pyregf_key.name]) yield REGFWinRegistryKey(pyregf_key, key_path=key_path)
[ "def", "GetSubkeys", "(", "self", ")", ":", "for", "pyregf_key", "in", "self", ".", "_pyregf_key", ".", "sub_keys", ":", "key_path", "=", "key_paths", ".", "JoinKeyPath", "(", "[", "self", ".", "_key_path", ",", "pyregf_key", ".", "name", "]", ")", "yiel...
34.555556
0.009404
def delete(self): """Remove this object.""" self._client.remove_object(self._instance, self._bucket, self.name)
[ "def", "delete", "(", "self", ")", ":", "self", ".", "_client", ".", "remove_object", "(", "self", ".", "_instance", ",", "self", ".", "_bucket", ",", "self", ".", "name", ")" ]
41.666667
0.015748
def runge_kutta4(y, x, dx, f): """computes 4th order Runge-Kutta for dy/dx. Parameters ---------- y : scalar Initial/current value for y x : scalar Initial/current value for x dx : scalar difference in x (e.g. the time step) f : ufunc(y,x) Callable function ...
[ "def", "runge_kutta4", "(", "y", ",", "x", ",", "dx", ",", "f", ")", ":", "k1", "=", "dx", "*", "f", "(", "y", ",", "x", ")", "k2", "=", "dx", "*", "f", "(", "y", "+", "0.5", "*", "k1", ",", "x", "+", "0.5", "*", "dx", ")", "k3", "=",...
23.291667
0.001718
def complement(self, frame_bound=None): r"""Return the filter that makes the frame tight. The complementary filter is designed such that the union of a filter bank and its complementary filter forms a tight frame. Parameters ---------- frame_bound : float or None ...
[ "def", "complement", "(", "self", ",", "frame_bound", "=", "None", ")", ":", "def", "kernel", "(", "x", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "y", "=", "self", ".", "evaluate", "(", "x", ")", "np", ".", "power", "(", "y", ",", ...
31.79661
0.001034