text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def _start_handler_thread(self): """Called once to start the event handler thread.""" # Create handler thread t = Thread(target=self._start_loop) t.daemon = True # Start handler thread t.start() self.thread_started = True
[ "def", "_start_handler_thread", "(", "self", ")", ":", "# Create handler thread", "t", "=", "Thread", "(", "target", "=", "self", ".", "_start_loop", ")", "t", ".", "daemon", "=", "True", "# Start handler thread", "t", ".", "start", "(", ")", "self", ".", ...
30
12.888889
def usages_list(location, **kwargs): ''' .. versionadded:: 2019.2.0 List subscription network usage for a location. :param location: The Azure location to query for network usage. CLI Example: .. code-block:: bash salt-call azurearm_network.usages_list westus ''' netconn = ...
[ "def", "usages_list", "(", "location", ",", "*", "*", "kwargs", ")", ":", "netconn", "=", "__utils__", "[", "'azurearm.get_client'", "]", "(", "'network'", ",", "*", "*", "kwargs", ")", "try", ":", "result", "=", "__utils__", "[", "'azurearm.paged_object_to_...
26.695652
27.565217
def _Stat(self, path, ext_attrs=False): """Returns stat information of a specific path. Args: path: A unicode string containing the path. ext_attrs: Whether the call should also collect extended attributes. Returns: a StatResponse proto Raises: IOError when call to os.stat() f...
[ "def", "_Stat", "(", "self", ",", "path", ",", "ext_attrs", "=", "False", ")", ":", "# Note that the encoding of local path is system specific", "local_path", "=", "client_utils", ".", "CanonicalPathToLocalPath", "(", "path", ")", "result", "=", "client_utils", ".", ...
30.2
22.36
def get_or_create_collection(self, name): '''get a collection if it exists. If it doesn't exist, create it first. Parameters ========== name: the collection name, usually parsed from get_image_names()['name'] ''' from sregistry.database.models import Collection collection = self.get_collec...
[ "def", "get_or_create_collection", "(", "self", ",", "name", ")", ":", "from", "sregistry", ".", "database", ".", "models", "import", "Collection", "collection", "=", "self", ".", "get_collection", "(", "name", ")", "# If it doesn't exist, create it", "if", "colle...
28.388889
21.388889
def predict(self, obs, pstates, next_pstate=None): """ Predict the next observation """ assert len(obs) == len(pstates) pstates_idx = np.array([self.e[ei] for ei in pstates]) next_pstate_idx = self.e[next_pstate] if len(obs) == 0: # No history, use th...
[ "def", "predict", "(", "self", ",", "obs", ",", "pstates", ",", "next_pstate", "=", "None", ")", ":", "assert", "len", "(", "obs", ")", "==", "len", "(", "pstates", ")", "pstates_idx", "=", "np", ".", "array", "(", "[", "self", ".", "e", "[", "ei...
38.595238
22.309524
def is_ancestor(self, child_key_name, ancestor_key_name): """Returns True if ancestor lies in the ancestry tree of child.""" # all keys are descendents of None if ancestor_key_name is None: return True one_up_parent = self.dct[child_key_name]['parent'] if child_key_...
[ "def", "is_ancestor", "(", "self", ",", "child_key_name", ",", "ancestor_key_name", ")", ":", "# all keys are descendents of None", "if", "ancestor_key_name", "is", "None", ":", "return", "True", "one_up_parent", "=", "self", ".", "dct", "[", "child_key_name", "]", ...
37.25
17.375
def hash_count(self, line, pound=None): """ Count hashes (or other run of chars) at start of line >>> x = Mark2Slide() >>> x.hash_count('### hello') 3 >>> x = Mark2Slide() >>> x.hash_count(' hello', ' ') 1 """ if pound is None: pound...
[ "def", "hash_count", "(", "self", ",", "line", ",", "pound", "=", "None", ")", ":", "if", "pound", "is", "None", ":", "pound", "=", "'#'", "count", "=", "0", "for", "c", "in", "line", ":", "if", "c", "!=", "pound", ":", "break", "count", "+=", ...
20.590909
19.227273
def _parse_pool_transaction_file( ledger, nodeReg, cliNodeReg, nodeKeys, activeValidators, ledger_size=None): """ helper function for parseLedgerForHaAndKeys """ for _, txn in ledger.getAllTxn(to=ledger_size): if get_type(txn) == NODE: ...
[ "def", "_parse_pool_transaction_file", "(", "ledger", ",", "nodeReg", ",", "cliNodeReg", ",", "nodeKeys", ",", "activeValidators", ",", "ledger_size", "=", "None", ")", ":", "for", "_", ",", "txn", "in", "ledger", ".", "getAllTxn", "(", "to", "=", "ledger_si...
44.829268
18
def get_binary_property(value, is_bytes=False): """Get `BINARY` property.""" obj = unidata.ascii_binary if is_bytes else unidata.unicode_binary if value.startswith('^'): negated = value[1:] value = '^' + unidata.unicode_alias['binary'].get(negated, negated) else: value = unidat...
[ "def", "get_binary_property", "(", "value", ",", "is_bytes", "=", "False", ")", ":", "obj", "=", "unidata", ".", "ascii_binary", "if", "is_bytes", "else", "unidata", ".", "unicode_binary", "if", "value", ".", "startswith", "(", "'^'", ")", ":", "negated", ...
31.25
24.25
def get_all_job_list(agent): """ Get all job list by each project name then return three job list on the base of different status(pending,running,finished). """ project_list = agent.get_project_list() if project_list['status'] == 'error': raise ScrapydTimeoutException project_list = ...
[ "def", "get_all_job_list", "(", "agent", ")", ":", "project_list", "=", "agent", ".", "get_project_list", "(", ")", "if", "project_list", "[", "'status'", "]", "==", "'error'", ":", "raise", "ScrapydTimeoutException", "project_list", "=", "project_list", "[", "'...
55.833333
22.642857
def get_progress(self): """ Give a rough estimate of the progress done. """ pos = self.reader.reader.tell() return min((pos - self.region_start) / float(self.region_end - self.region_start), 1.0)
[ "def", "get_progress", "(", "self", ")", ":", "pos", "=", "self", ".", "reader", ".", "reader", ".", "tell", "(", ")", "return", "min", "(", "(", "pos", "-", "self", ".", "region_start", ")", "/", "float", "(", "self", ".", "region_end", "-", "self...
33.25
9.25
def get_token(username, length=20, timeout=20): """ Obtain an access token that can be passed to a websocket client. """ redis = get_redis_client() token = get_random_string(length) token_key = 'token:{}'.format(token) redis.set(token_key, username) redis.expire(token_key, timeout) r...
[ "def", "get_token", "(", "username", ",", "length", "=", "20", ",", "timeout", "=", "20", ")", ":", "redis", "=", "get_redis_client", "(", ")", "token", "=", "get_random_string", "(", "length", ")", "token_key", "=", "'token:{}'", ".", "format", "(", "to...
32.2
8.2
def label_count(self): """ Return for each label the number of occurrences within the list. Returns: dict: A dictionary containing for every label-value (key) the number of occurrences (value). Example: >>> ll = LabelList(labels=[ >>> ...
[ "def", "label_count", "(", "self", ")", ":", "occurrences", "=", "collections", ".", "defaultdict", "(", "int", ")", "for", "label", "in", "self", ":", "occurrences", "[", "label", ".", "value", "]", "+=", "1", "return", "occurrences" ]
27.884615
16.269231
def src_to_html(fpath): """ Returns content of the given 'fpath' with HTML annotations for syntax highlighting """ if not os.path.exists(fpath): return "COULD-NOT-FIND-TESTCASE-SRC-AT-FPATH:%r" % fpath # NOTE: Do SYNTAX highlight? return open(fpath, "r").read()
[ "def", "src_to_html", "(", "fpath", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "fpath", ")", ":", "return", "\"COULD-NOT-FIND-TESTCASE-SRC-AT-FPATH:%r\"", "%", "fpath", "# NOTE: Do SYNTAX highlight?", "return", "open", "(", "fpath", ",", "\"r\...
24.083333
19.916667
def mangle(text): """ Takes a script and mangles it TokenError is thrown when encountering bad syntax """ text_bytes = text.encode('utf-8') # Wrap the input script as a byte stream buff = BytesIO(text_bytes) # Byte stream for the mangled script mangled = BytesIO() last_tok = ...
[ "def", "mangle", "(", "text", ")", ":", "text_bytes", "=", "text", ".", "encode", "(", "'utf-8'", ")", "# Wrap the input script as a byte stream", "buff", "=", "BytesIO", "(", "text_bytes", ")", "# Byte stream for the mangled script", "mangled", "=", "BytesIO", "(",...
34.95
17.175
def update(self, path, verbose=False): """ if the path isn't being watched, start watching it if it is, stop watching it """ if path in self._by_path: self.remove(path) else: self.add(path, verbose)
[ "def", "update", "(", "self", ",", "path", ",", "verbose", "=", "False", ")", ":", "if", "path", "in", "self", ".", "_by_path", ":", "self", ".", "remove", "(", "path", ")", "else", ":", "self", ".", "add", "(", "path", ",", "verbose", ")" ]
32.375
6.75
def create_decoder_config(args: argparse.Namespace, encoder_num_hidden: int, max_seq_len_source: int, max_seq_len_target: int, num_embed_target: int) -> decoder.DecoderConfig: """ Create the config for the decoder. :param args: Arguments as returned by ar...
[ "def", "create_decoder_config", "(", "args", ":", "argparse", ".", "Namespace", ",", "encoder_num_hidden", ":", "int", ",", "max_seq_len_source", ":", "int", ",", "max_seq_len_target", ":", "int", ",", "num_embed_target", ":", "int", ")", "->", "decoder", ".", ...
62.555556
31.981481
def get_current(self): """Get current forecast.""" now = dt.now().timestamp() url = build_url(self.api_key, self.spot_id, self.fields, self.unit, now, now) return get_msw(url)
[ "def", "get_current", "(", "self", ")", ":", "now", "=", "dt", ".", "now", "(", ")", ".", "timestamp", "(", ")", "url", "=", "build_url", "(", "self", ".", "api_key", ",", "self", ".", "spot_id", ",", "self", ".", "fields", ",", "self", ".", "uni...
37.666667
10.833333
def a_message_callback(ctx): """Message the captured pattern.""" message = ctx.ctrl.after.strip().splitlines()[-1] ctx.device.chain.connection.emit_message(message, log_level=logging.INFO) return True
[ "def", "a_message_callback", "(", "ctx", ")", ":", "message", "=", "ctx", ".", "ctrl", ".", "after", ".", "strip", "(", ")", ".", "splitlines", "(", ")", "[", "-", "1", "]", "ctx", ".", "device", ".", "chain", ".", "connection", ".", "emit_message", ...
42.4
17.4
def _defaults(cls): """Helper to get the default minimum needs. .. note:: Key names will be translated. """ minimum_needs = { "resources": [ { "Default": "2.8", "Minimum allowed": "0", "Maximum allow...
[ "def", "_defaults", "(", "cls", ")", ":", "minimum_needs", "=", "{", "\"resources\"", ":", "[", "{", "\"Default\"", ":", "\"2.8\"", ",", "\"Minimum allowed\"", ":", "\"0\"", ",", "\"Maximum allowed\"", ":", "\"100\"", ",", "\"Frequency\"", ":", "\"weekly\"", "...
41.024096
12.204819
def backfill_fields(self, fields, forms): """ Properly backfill fields to explicitly request specific keys. The issue is that >6.X servers *only* return requested fields so to improve backwards compatiblity for PyCap clients, add specific fields when required. Parameters...
[ "def", "backfill_fields", "(", "self", ",", "fields", ",", "forms", ")", ":", "if", "forms", "and", "not", "fields", ":", "new_fields", "=", "[", "self", ".", "def_field", "]", "elif", "fields", "and", "self", ".", "def_field", "not", "in", "fields", "...
30.724138
16.241379
def _ParseEventData(self, variable_length_section): """Parses the event data form a variable-length data section. Args: variable_length_section (job_variable_length_data_section): a Windows Scheduled Task job variable-length data section. Returns: WinJobEventData: event data of the j...
[ "def", "_ParseEventData", "(", "self", ",", "variable_length_section", ")", ":", "event_data", "=", "WinJobEventData", "(", ")", "event_data", ".", "application", "=", "(", "variable_length_section", ".", "application_name", ".", "rstrip", "(", "'\\x00'", ")", ")"...
38.380952
20.571429
def step_worker(step, pipe, max_entities): """ All messages follow the form: <message>, <data> Valid messages -------------- run, <input_data> finalise, None next, None stop, None """ state = None while True: message, input = pipe.recv() if message == 'run': ...
[ "def", "step_worker", "(", "step", ",", "pipe", ",", "max_entities", ")", ":", "state", "=", "None", "while", "True", ":", "message", ",", "input", "=", "pipe", ".", "recv", "(", ")", "if", "message", "==", "'run'", ":", "state", "=", "step", ".", ...
33.1
17.7
def run_sketch(self): """ Initialises the underlying PApplet and creates a frame ( using ``create_frame`` if required ) to display it in. """ Sketch.instance = self self.init() frame = self.create_frame() if frame: frame.add(self) ...
[ "def", "run_sketch", "(", "self", ")", ":", "Sketch", ".", "instance", "=", "self", "self", ".", "init", "(", ")", "frame", "=", "self", ".", "create_frame", "(", ")", "if", "frame", ":", "frame", ".", "add", "(", "self", ")", "frame", ".", "pack",...
26.923077
16.307692
def rectangle(self, x, y, width, height): """Adds a closed sub-path rectangle of the given size to the current path at position ``(x, y)`` in user-space coordinates. This method is logically equivalent to:: context.move_to(x, y) context.rel_line_to(width, 0) ...
[ "def", "rectangle", "(", "self", ",", "x", ",", "y", ",", "width", ",", "height", ")", ":", "cairo", ".", "cairo_rectangle", "(", "self", ".", "_pointer", ",", "x", ",", "y", ",", "width", ",", "height", ")", "self", ".", "_check_status", "(", ")" ...
34.68
15.72
def subtract(self, other, numPartitions=None): """ Return each value in C{self} that is not contained in C{other}. >>> x = sc.parallelize([("a", 1), ("b", 4), ("b", 5), ("a", 3)]) >>> y = sc.parallelize([("a", 3), ("c", None)]) >>> sorted(x.subtract(y).collect()) [('a', ...
[ "def", "subtract", "(", "self", ",", "other", ",", "numPartitions", "=", "None", ")", ":", "# note: here 'True' is just a placeholder", "rdd", "=", "other", ".", "map", "(", "lambda", "x", ":", "(", "x", ",", "True", ")", ")", "return", "self", ".", "map...
43.75
15.583333
def missingDataValue(self): """ Returns the value to indicate missing data. """ value = getMissingDataValue(self._array) fieldNames = self._array.dtype.names # If the missing value attibute is a list with the same length as the number of fields, # return the missing val...
[ "def", "missingDataValue", "(", "self", ")", ":", "value", "=", "getMissingDataValue", "(", "self", ".", "_array", ")", "fieldNames", "=", "self", ".", "_array", ".", "dtype", ".", "names", "# If the missing value attibute is a list with the same length as the number of...
41.692308
19.230769
def download_segmentation_image(self, mapobject_type_name, plate_name, well_name, well_pos_y, well_pos_x, tpoint=0, zplane=0, align = False): '''Downloads a segmentation image. Parameters ---------- plate_id: int ID of the parent experiment mapobject_type...
[ "def", "download_segmentation_image", "(", "self", ",", "mapobject_type_name", ",", "plate_name", ",", "well_name", ",", "well_pos_y", ",", "well_pos_x", ",", "tpoint", "=", "0", ",", "zplane", "=", "0", ",", "align", "=", "False", ")", ":", "response", "=",...
35.675
19.475
def main(args=None): """Main function.""" parser = get_parser() args = parser.parse_args(args=args) Logger.set_level(args.level) colorama_args = {'autoreset': True} if args.no_color: colorama_args['strip'] = True colorama.init(**colorama_args) config = None if args.no_confi...
[ "def", "main", "(", "args", "=", "None", ")", ":", "parser", "=", "get_parser", "(", ")", "args", "=", "parser", ".", "parse_args", "(", "args", "=", "args", ")", "Logger", ".", "set_level", "(", "args", ".", "level", ")", "colorama_args", "=", "{", ...
34.611111
17.574074
def get(self, path, content=True, type=None, format=None): """ Special case handling for listing root dir. """ path = normalize_api_path(path) if path: return self.__get(path, content=content, type=type, format=format) if not content: return base_d...
[ "def", "get", "(", "self", ",", "path", ",", "content", "=", "True", ",", "type", "=", "None", ",", "format", "=", "None", ")", ":", "path", "=", "normalize_api_path", "(", "path", ")", "if", "path", ":", "return", "self", ".", "__get", "(", "path"...
31.392857
13.964286
def parse_accept_header(value, cls=None): """Parses an HTTP Accept-* header. This does not implement a complete valid algorithm but one that supports at least value and quality extraction. Returns a new :class:`Accept` object (basically a list of ``(value, quality)`` tuples sorted by the quality w...
[ "def", "parse_accept_header", "(", "value", ",", "cls", "=", "None", ")", ":", "if", "cls", "is", "None", ":", "cls", "=", "Accept", "if", "not", "value", ":", "return", "cls", "(", "None", ")", "result", "=", "[", "]", "for", "match", "in", "_acce...
33.645161
20.903226
def _get_site_type_dummy_variables(self, sites): """ Get site type dummy variables, three different site classes, based on the shear wave velocity intervals in the uppermost 30 m, Vs30, according to the NEHRP: class A-B: Vs30 > 760 m/s class C: Vs30 = 360 − 760 m/s ...
[ "def", "_get_site_type_dummy_variables", "(", "self", ",", "sites", ")", ":", "S", "=", "np", ".", "zeros", "(", "len", "(", "sites", ".", "vs30", ")", ")", "SS", "=", "np", ".", "zeros", "(", "len", "(", "sites", ".", "vs30", ")", ")", "# Class C;...
32.142857
15.666667
def train( self, env_fn, hparams, simulated, save_continuously, epoch, sampling_temp=1.0, num_env_steps=None, env_step_multiplier=1, eval_env_fn=None, report_fn=None ): """Train.""" raise NotImplementedError()
[ "def", "train", "(", "self", ",", "env_fn", ",", "hparams", ",", "simulated", ",", "save_continuously", ",", "epoch", ",", "sampling_temp", "=", "1.0", ",", "num_env_steps", "=", "None", ",", "env_step_multiplier", "=", "1", ",", "eval_env_fn", "=", "None", ...
18.066667
20.333333
def _calculate_offset(date, local_tz): """ input : date : date type local_tz : if true, use system timezone, otherwise return 0 return the date of UTC offset. If date does not have any timezone info, we use local timezone, otherwise return 0 """ if local_tz: #handle year bef...
[ "def", "_calculate_offset", "(", "date", ",", "local_tz", ")", ":", "if", "local_tz", ":", "#handle year before 1970 most sytem there is no timezone information before 1970.", "if", "date", ".", "year", "<", "1970", ":", "# Use 1972 because 1970 doesn't have a leap day", "t",...
32.32
20.32
def MergeOrAddUser(self, kb_user): """Merge a user into existing users or add new if it doesn't exist. Args: kb_user: A User rdfvalue. Returns: A list of strings with the set attribute names, e.g. ["users.sid"] """ user = self.GetUser( sid=kb_user.sid, uid=kb_user.uid, usernam...
[ "def", "MergeOrAddUser", "(", "self", ",", "kb_user", ")", ":", "user", "=", "self", ".", "GetUser", "(", "sid", "=", "kb_user", ".", "sid", ",", "uid", "=", "kb_user", ".", "uid", ",", "username", "=", "kb_user", ".", "username", ")", "new_attrs", "...
30.916667
19.666667
def get_referenced_object(self): """ :rtype: core.BunqModel :raise: BunqException """ if self._BunqMeTab is not None: return self._BunqMeTab if self._BunqMeTabResultResponse is not None: return self._BunqMeTabResultResponse if self._Bunq...
[ "def", "get_referenced_object", "(", "self", ")", ":", "if", "self", ".", "_BunqMeTab", "is", "not", "None", ":", "return", "self", ".", "_BunqMeTab", "if", "self", ".", "_BunqMeTabResultResponse", "is", "not", "None", ":", "return", "self", ".", "_BunqMeTab...
29.527473
17.681319
def get_value(self, context): """Run python eval on the input string.""" if self.value: return expressions.eval_string(self.value, context) else: # Empty input raises cryptic EOF syntax err, this more human # friendly raise ValueError('!py string e...
[ "def", "get_value", "(", "self", ",", "context", ")", ":", "if", "self", ".", "value", ":", "return", "expressions", ".", "eval_string", "(", "self", ".", "value", ",", "context", ")", "else", ":", "# Empty input raises cryptic EOF syntax err, this more human", ...
45.666667
21
def get_all_widget_classes(): """returns collected Leonardo Widgets if not declared in settings is used __subclasses__ which not supports widget subclassing """ from leonardo.module.web.models import Widget _widgets = getattr(settings, 'WIDGETS', Widget.__subclasses__())...
[ "def", "get_all_widget_classes", "(", ")", ":", "from", "leonardo", ".", "module", ".", "web", ".", "models", "import", "Widget", "_widgets", "=", "getattr", "(", "settings", ",", "'WIDGETS'", ",", "Widget", ".", "__subclasses__", "(", ")", ")", "widgets", ...
32.764706
12.294118
def colorize(text, color=None, **kwargs): """ Colorize the text kwargs arguments: style=, bg= """ style = None bg = None # ================ # # Keyword checking # # ================ # if 'style' in kwargs: if kwargs['style'] not in STYLE: raise WrongStyle(...
[ "def", "colorize", "(", "text", ",", "color", "=", "None", ",", "*", "*", "kwargs", ")", ":", "style", "=", "None", "bg", "=", "None", "# ================ #", "# Keyword checking #", "# ================ #", "if", "'style'", "in", "kwargs", ":", "if", "kwargs...
32.225
19.525
def consume(self, char): """ Consume a single character and advance the state as necessary. """ if self.state == "stream": self._stream(char) elif self.state == "escape": self._escape_sequence(char) elif self.state == "escape-lb": self...
[ "def", "consume", "(", "self", ",", "char", ")", ":", "if", "self", ".", "state", "==", "\"stream\"", ":", "self", ".", "_stream", "(", "char", ")", "elif", "self", ".", "state", "==", "\"escape\"", ":", "self", ".", "_escape_sequence", "(", "char", ...
32.058824
8.176471
def get_resources(self, type: Type[T_Resource]) -> Set[T_Resource]: """ Retrieve all the resources of the given type in this context and its parents. Any matching resource factories are also triggered if necessary. :param type: type of the resources to get :return: a set of all...
[ "def", "get_resources", "(", "self", ",", "type", ":", "Type", "[", "T_Resource", "]", ")", "->", "Set", "[", "T_Resource", "]", ":", "assert", "check_argument_types", "(", ")", "# Collect all the matching resources from this context", "resources", "=", "{", "cont...
47.939394
26.969697
def magnitude(self): """Return the magnitude when treating the point as a vector.""" return math.sqrt( self.x * self.x + self.y * self.y )
[ "def", "magnitude", "(", "self", ")", ":", "return", "math", ".", "sqrt", "(", "self", ".", "x", "*", "self", ".", "x", "+", "self", ".", "y", "*", "self", ".", "y", ")" ]
50.666667
13.666667
def MySend1(request_path, payload=None, content_type="application/octet-stream", timeout=None, force_auth=True, **kwargs): """Sends an RPC and returns the response. Args: request_path: The path to send the request to, eg /api/appversion/create. payload: The body of the request, or None to send an emp...
[ "def", "MySend1", "(", "request_path", ",", "payload", "=", "None", ",", "content_type", "=", "\"application/octet-stream\"", ",", "timeout", "=", "None", ",", "force_auth", "=", "True", ",", "*", "*", "kwargs", ")", ":", "# TODO: Don't require authentication. Le...
29.044776
18.746269
def resume(oid, restart_point="continue_next", **kwargs): """Continue workflow for given WorkflowObject id (oid). Depending on `start_point` it may start from previous, current or next task. Special custom keyword arguments can be given to the workflow engine in order to pass certain variables to ...
[ "def", "resume", "(", "oid", ",", "restart_point", "=", "\"continue_next\"", ",", "*", "*", "kwargs", ")", ":", "from", ".", "worker_engine", "import", "continue_worker", "return", "text_type", "(", "continue_worker", "(", "oid", ",", "restart_point", ",", "*"...
39.956522
23.347826
def args_ok(self, options, args): """Check for conflicts and problems in the options. Returns True if everything is ok, or False if not. """ for i in ['erase', 'execute']: for j in ['annotate', 'html', 'report', 'combine']: if (i in options.actions) and (j i...
[ "def", "args_ok", "(", "self", ",", "options", ",", "args", ")", ":", "for", "i", "in", "[", "'erase'", ",", "'execute'", "]", ":", "for", "j", "in", "[", "'annotate'", ",", "'html'", ",", "'report'", ",", "'combine'", "]", ":", "if", "(", "i", "...
35.028571
17.2
def read(self, n): """Read n bytes. Returns exactly n bytes of data unless the underlying raw IO stream reaches EOF. """ pos = self._read_pos self._read_pos = min(len(self.raw), pos + n) return self.raw[pos:self._read_pos]
[ "def", "read", "(", "self", ",", "n", ")", ":", "pos", "=", "self", ".", "_read_pos", "self", ".", "_read_pos", "=", "min", "(", "len", "(", "self", ".", "raw", ")", ",", "pos", "+", "n", ")", "return", "self", ".", "raw", "[", "pos", ":", "s...
33.875
11.25
def index_exists(index, hosts=None, profile=None): ''' Return a boolean indicating whether given index exists index Index name CLI example:: salt myminion elasticsearch.index_exists testindex ''' es = _get_instance(hosts, profile) try: return es.indices.exists(ind...
[ "def", "index_exists", "(", "index", ",", "hosts", "=", "None", ",", "profile", "=", "None", ")", ":", "es", "=", "_get_instance", "(", "hosts", ",", "profile", ")", "try", ":", "return", "es", ".", "indices", ".", "exists", "(", "index", "=", "index...
30.263158
27.736842
def details( self, query, accept_language=None, content_type=None, user_agent=None, client_id=None, client_ip=None, location=None, crop_bottom=None, crop_left=None, crop_right=None, crop_top=None, crop_type=None, country_code=None, id=None, image_url=None, insights_token=None, modules=None, market=None, saf...
[ "def", "details", "(", "self", ",", "query", ",", "accept_language", "=", "None", ",", "content_type", "=", "None", ",", "user_agent", "=", "None", ",", "client_id", "=", "None", ",", "client_ip", "=", "None", ",", "location", "=", "None", ",", "crop_bot...
68.172932
33.79198
def disable_servicegroup_svc_notifications(self, servicegroup): """Disable service notifications for a servicegroup Format of the line that triggers function call:: DISABLE_SERVICEGROUP_SVC_NOTIFICATIONS;<servicegroup_name> :param servicegroup: servicegroup to disable :type ser...
[ "def", "disable_servicegroup_svc_notifications", "(", "self", ",", "servicegroup", ")", ":", "for", "service_id", "in", "servicegroup", ".", "get_services", "(", ")", ":", "self", ".", "disable_svc_notifications", "(", "self", ".", "daemon", ".", "services", "[", ...
43.916667
21.25
def stderr(self): """ Converts stderr string to a list. """ if self._streaming: stderr = [] while not self.__stderr.empty(): try: line = self.__stderr.get_nowait() stderr.append(line) except: ...
[ "def", "stderr", "(", "self", ")", ":", "if", "self", ".", "_streaming", ":", "stderr", "=", "[", "]", "while", "not", "self", ".", "__stderr", ".", "empty", "(", ")", ":", "try", ":", "line", "=", "self", ".", "__stderr", ".", "get_nowait", "(", ...
26.733333
11.8
def backup_db(self): """ " Generate a xxxxx.backup.json. """ with self.db_mutex: if os.path.exists(self.json_db_path): try: shutil.copy2(self.json_db_path, self.backup_json_db_path) except (IOError, OSError): ...
[ "def", "backup_db", "(", "self", ")", ":", "with", "self", ".", "db_mutex", ":", "if", "os", ".", "path", ".", "exists", "(", "self", ".", "json_db_path", ")", ":", "try", ":", "shutil", ".", "copy2", "(", "self", ".", "json_db_path", ",", "self", ...
35.3
11.9
def returns(self): """Gets a string showing the return type and modifiers for the function in a nice display format.""" kind = "({}) ".format(self.kind) if self.kind is not None else "" mods = ", ".join(self.modifiers) + " " dtype = self.dtype if self.dtype is not None else...
[ "def", "returns", "(", "self", ")", ":", "kind", "=", "\"({}) \"", ".", "format", "(", "self", ".", "kind", ")", "if", "self", ".", "kind", "is", "not", "None", "else", "\"\"", "mods", "=", "\", \"", ".", "join", "(", "self", ".", "modifiers", ")",...
52.428571
13.714286
def name(self): """ Get the module name :return: Module name :rtype: str | unicode """ res = type(self).__name__ if self._id: res += ".{}".format(self._id) return res
[ "def", "name", "(", "self", ")", ":", "res", "=", "type", "(", "self", ")", ".", "__name__", "if", "self", ".", "_id", ":", "res", "+=", "\".{}\"", ".", "format", "(", "self", ".", "_id", ")", "return", "res" ]
21.181818
13.727273
def to_iterable(value, allow_none=True): """ Tries to convert the given value to an iterable, if necessary. If the given value is a list, a list is returned; if it is a string, a list containing one string is returned, ... :param value: Any object :param allow_none: If True, the method returns ...
[ "def", "to_iterable", "(", "value", ",", "allow_none", "=", "True", ")", ":", "if", "value", "is", "None", ":", "# None given", "if", "allow_none", ":", "return", "None", "return", "[", "]", "elif", "isinstance", "(", "value", ",", "(", "list", ",", "t...
30.416667
20
def checkout(config, rev): """Upgrade/revert to a different revision. <rev> must be "head", integer or revision id. To pass negative number you need to write "--" before it""" with open(config, 'r'): main.checkout(yaml.load(open(config)), rev)
[ "def", "checkout", "(", "config", ",", "rev", ")", ":", "with", "open", "(", "config", ",", "'r'", ")", ":", "main", ".", "checkout", "(", "yaml", ".", "load", "(", "open", "(", "config", ")", ")", ",", "rev", ")" ]
38
14.285714
def update_user(bridge_user): """ Update only the user attributes provided. Return a list of BridgeUsers objects with custom fields. """ if bridge_user.bridge_id: url = author_id_url(bridge_user.bridge_id) else: url = author_uid_url(bridge_user.netid) resp = patch_resource(ur...
[ "def", "update_user", "(", "bridge_user", ")", ":", "if", "bridge_user", ".", "bridge_id", ":", "url", "=", "author_id_url", "(", "bridge_user", ".", "bridge_id", ")", "else", ":", "url", "=", "author_uid_url", "(", "bridge_user", ".", "netid", ")", "resp", ...
38.692308
11.923077
def plot_iv_curve(a, hold_v, i, *plt_args, **plt_kwargs): """A single IV curve""" grid = plt_kwargs.pop('grid',True) same_fig = plt_kwargs.pop('same_fig',False) if not len(plt_args): plt_args = ('ko-',) if 'label' not in plt_kwargs: plt_kwargs['label'] = 'Current' if not sa...
[ "def", "plot_iv_curve", "(", "a", ",", "hold_v", ",", "i", ",", "*", "plt_args", ",", "*", "*", "plt_kwargs", ")", ":", "grid", "=", "plt_kwargs", ".", "pop", "(", "'grid'", ",", "True", ")", "same_fig", "=", "plt_kwargs", ".", "pop", "(", "'same_fig...
37.214286
12.428571
def captcha_refresh(request): """ Return json with new captcha for ajax refresh request """ if not request.is_ajax(): raise Http404 new_key = CaptchaStore.pick() to_json_response = { 'key': new_key, 'image_url': captcha_image_url(new_key), 'audio_url': captcha_audio_url...
[ "def", "captcha_refresh", "(", "request", ")", ":", "if", "not", "request", ".", "is_ajax", "(", ")", ":", "raise", "Http404", "new_key", "=", "CaptchaStore", ".", "pick", "(", ")", "to_json_response", "=", "{", "'key'", ":", "new_key", ",", "'image_url'",...
37.666667
21.5
def update_ref(profile, ref, sha): """Point a ref to a new SHA. Args: profile A profile generated from ``simplygithub.authentication.profile``. Such profiles tell this module (i) the ``repo`` to connect to, and (ii) the ``token`` to connect with. ref ...
[ "def", "update_ref", "(", "profile", ",", "ref", ",", "sha", ")", ":", "resource", "=", "\"/refs/\"", "+", "ref", "payload", "=", "{", "\"sha\"", ":", "sha", "}", "data", "=", "api", ".", "patch_request", "(", "profile", ",", "resource", ",", "payload"...
26.041667
23.666667
def format_completion_message(self, defFile, completionsList): ''' Format the completions suggestions in the following format: @@COMPLETIONS(modFile(token,description),(token,description),(token,description))END@@ ''' compMsg = [] compMsg.append('%s' % defFile) fo...
[ "def", "format_completion_message", "(", "self", ",", "defFile", ",", "completionsList", ")", ":", "compMsg", "=", "[", "]", "compMsg", ".", "append", "(", "'%s'", "%", "defFile", ")", "for", "tup", "in", "completionsList", ":", "compMsg", ".", "append", "...
37.653846
24.807692
def strptime(date): """Returns datetime object from the given date, which is in a specific format: YYYY-MM-ddTHH:mm:ss""" d = { 'year': date[0:4], 'month': date[5:7], 'day': date[8:10], 'hour': date[11:13], 'minute': date[14:16], 'second': date[17:], } d ...
[ "def", "strptime", "(", "date", ")", ":", "d", "=", "{", "'year'", ":", "date", "[", "0", ":", "4", "]", ",", "'month'", ":", "date", "[", "5", ":", "7", "]", ",", "'day'", ":", "date", "[", "8", ":", "10", "]", ",", "'hour'", ":", "date", ...
26.714286
18.928571
def _setup_chans(self): """Setup channel borders """ if self.header[b'foff'] < 0: f0 = self.f_end else: f0 = self.f_begin i_start, i_stop = 0, self.n_channels_in_file if self.f_start: i_start = np.round((self.f_start - f0) / self.head...
[ "def", "_setup_chans", "(", "self", ")", ":", "if", "self", ".", "header", "[", "b'foff'", "]", "<", "0", ":", "f0", "=", "self", ".", "f_end", "else", ":", "f0", "=", "self", ".", "f_begin", "i_start", ",", "i_stop", "=", "0", ",", "self", ".", ...
30.875
17.916667
def sqlupdate(table, rowupdate, where): """Generates SQL update table set ... Returns (sql, parameters) >>> sqlupdate('mytable', {'field1': 3, 'field2': 'hello'}, {'id': 5}) ('update mytable set field1=%s, field2=%s where id=%s', [3, 'hello', 5]) """ validate_name(table) fields = sorted(row...
[ "def", "sqlupdate", "(", "table", ",", "rowupdate", ",", "where", ")", ":", "validate_name", "(", "table", ")", "fields", "=", "sorted", "(", "rowupdate", ".", "keys", "(", ")", ")", "validate_names", "(", "fields", ")", "values", "=", "[", "rowupdate", ...
38.222222
12.555556
def pad_shape_right_with_ones(x, ndims): """Maybe add `ndims` ones to `x.shape` on the right. If `ndims` is zero, this is a no-op; otherwise, we will create and return a new `Tensor` whose shape is that of `x` with `ndims` ones concatenated on the right side. If the shape of `x` is known statically, the shape ...
[ "def", "pad_shape_right_with_ones", "(", "x", ",", "ndims", ")", ":", "if", "not", "(", "isinstance", "(", "ndims", ",", "int", ")", "and", "ndims", ">=", "0", ")", ":", "raise", "ValueError", "(", "'`ndims` must be a Python `integer` greater than zero. Got: {}'",...
38.3125
22.21875
def buscar_por_equipamento(self, nome_equipamento, ip_equipamento): """Obtém um ambiente a partir do ip e nome de um equipamento. :param nome_equipamento: Nome do equipamento. :param ip_equipamento: IP do equipamento no formato XXX.XXX.XXX.XXX. :return: Dicionário com a seguinte estrut...
[ "def", "buscar_por_equipamento", "(", "self", ",", "nome_equipamento", ",", "ip_equipamento", ")", ":", "if", "nome_equipamento", "==", "''", "or", "nome_equipamento", "is", "None", ":", "raise", "InvalidParameterError", "(", "u'O nome do equipamento não foi informado.')"...
40.813953
21.418605
def having(self, column, operator=None, value=None, boolean="and"): """ Add a "having" clause to the query :param column: The column :type column: str :param operator: The having clause operator :type operator: str :param value: The having clause value ...
[ "def", "having", "(", "self", ",", "column", ",", "operator", "=", "None", ",", "value", "=", "None", ",", "boolean", "=", "\"and\"", ")", ":", "type", "=", "\"basic\"", "self", ".", "havings", ".", "append", "(", "{", "\"type\"", ":", "type", ",", ...
24.257143
18.257143
def child_allocation(self): """ The sum of all child asset classes' allocations """ sum = Decimal(0) if self.classes: for child in self.classes: sum += child.child_allocation else: # This is not a branch but a leaf. Return own allocation. ...
[ "def", "child_allocation", "(", "self", ")", ":", "sum", "=", "Decimal", "(", "0", ")", "if", "self", ".", "classes", ":", "for", "child", "in", "self", ".", "classes", ":", "sum", "+=", "child", ".", "child_allocation", "else", ":", "# This is not a bra...
32.181818
16.090909
def _get_and_count_containers(self, custom_cgroups=False, healthchecks=False): """List all the containers from the API, filter and count them.""" # Querying the size of containers is slow, we don't do it at each run must_query_size = self.collect_container_size and self._latest_size_query == 0 ...
[ "def", "_get_and_count_containers", "(", "self", ",", "custom_cgroups", "=", "False", ",", "healthchecks", "=", "False", ")", ":", "# Querying the size of containers is slow, we don't do it at each run", "must_query_size", "=", "self", ".", "collect_container_size", "and", ...
46.308824
28.779412
def get_int(self): """Read the next token and interpret it as an integer. @raises dns.exception.SyntaxError: @rtype: int """ token = self.get().unescape() if not token.is_identifier(): raise dns.exception.SyntaxError('expecting an identifier') if not...
[ "def", "get_int", "(", "self", ")", ":", "token", "=", "self", ".", "get", "(", ")", ".", "unescape", "(", ")", "if", "not", "token", ".", "is_identifier", "(", ")", ":", "raise", "dns", ".", "exception", ".", "SyntaxError", "(", "'expecting an identif...
33.153846
15.384615
def read(cls, f): """Read WETRecord from file. Records end with 2 blank lines.""" header = WETHeader.read(f) if header is None: # EOF return None content = f.read(header.length) # Consume empty separators f.readline() f.readline() return cls(header.url, content)
[ "def", "read", "(", "cls", ",", "f", ")", ":", "header", "=", "WETHeader", ".", "read", "(", "f", ")", "if", "header", "is", "None", ":", "# EOF", "return", "None", "content", "=", "f", ".", "read", "(", "header", ".", "length", ")", "# Consume emp...
22.769231
19.307692
def shorten_url(url, cols, shorten): """Shorten long URLs to fit on one line. """ cols = ((cols - 6) * .85) # 6 cols for urlref and don't use while line if shorten is False or len(url) < cols: return url split = int(cols * .5) return url[:split] + "..." + url[-split:]
[ "def", "shorten_url", "(", "url", ",", "cols", ",", "shorten", ")", ":", "cols", "=", "(", "(", "cols", "-", "6", ")", "*", ".85", ")", "# 6 cols for urlref and don't use while line", "if", "shorten", "is", "False", "or", "len", "(", "url", ")", "<", "...
32.666667
13.666667
def handle_walk(self, listener: TreeListener, tree: Union[ast.Node, dict, list]) -> None: """ Handles tree walking, has to account for dictionaries and lists :param listener: listener that reacts to walked events :param tree: the tree to walk :return: None """ if ...
[ "def", "handle_walk", "(", "self", ",", "listener", ":", "TreeListener", ",", "tree", ":", "Union", "[", "ast", ".", "Node", ",", "dict", ",", "list", "]", ")", "->", "None", ":", "if", "isinstance", "(", "tree", ",", "ast", ".", "Node", ")", ":", ...
38.294118
12.882353
def log_every_x_times(logger, counter, x, msg, *args, **kwargs): ''' Works like logdebug, but only prints first and and every xth message. ''' if counter==1 or counter % x == 0: #msg = msg + (' (counter %i)' % counter) logdebug(logger, msg, *args, **kwargs)
[ "def", "log_every_x_times", "(", "logger", ",", "counter", ",", "x", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "counter", "==", "1", "or", "counter", "%", "x", "==", "0", ":", "#msg = msg + (' (counter %i)' % counter)", "logd...
35.75
16.25
def uncompress(pub): ''' Input must be hex string, and a valid compressed public key. Check if it's a valid key first, using the validatepubkey() function below, and then verify that the str len is 66. ''' yp = int(pub[:2],16) - 2 x = int(pub[2:],16) a = (pow_mod(x,3,P) + 7) % P y =...
[ "def", "uncompress", "(", "pub", ")", ":", "yp", "=", "int", "(", "pub", "[", ":", "2", "]", ",", "16", ")", "-", "2", "x", "=", "int", "(", "pub", "[", "2", ":", "]", ",", "16", ")", "a", "=", "(", "pow_mod", "(", "x", ",", "3", ",", ...
27.125
21.125
def get_output_data_port_m(self, data_port_id): """Returns the output data port model for the given data port id :param data_port_id: The data port id to search for :return: The model of the data port with the given id """ for data_port_m in self.output_data_ports: i...
[ "def", "get_output_data_port_m", "(", "self", ",", "data_port_id", ")", ":", "for", "data_port_m", "in", "self", ".", "output_data_ports", ":", "if", "data_port_m", ".", "data_port", ".", "data_port_id", "==", "data_port_id", ":", "return", "data_port_m", "return"...
41.9
15
def diff_text1(self, diffs): """Compute and return the source text (all equalities and deletions). Args: diffs: Array of diff tuples. Returns: Source text. """ text = [] for (op, data) in diffs: if op != self.DIFF_INSERT: text.append(data) return "".join(text)
[ "def", "diff_text1", "(", "self", ",", "diffs", ")", ":", "text", "=", "[", "]", "for", "(", "op", ",", "data", ")", "in", "diffs", ":", "if", "op", "!=", "self", ".", "DIFF_INSERT", ":", "text", ".", "append", "(", "data", ")", "return", "\"\"",...
21.642857
18.357143
def exists_by_source(self): """Does this GTFS contain this file? (file specified by the class)""" exists_list = [] for source in self.gtfs_sources: if isinstance(source, dict): # source can now be either a dict or a zipfile if self.fname in source: ...
[ "def", "exists_by_source", "(", "self", ")", ":", "exists_list", "=", "[", "]", "for", "source", "in", "self", ".", "gtfs_sources", ":", "if", "isinstance", "(", "source", ",", "dict", ")", ":", "# source can now be either a dict or a zipfile", "if", "self", "...
44.1
11.866667
def filtered(self): """Determines whether or not resource is filtered. Resources may be filtered if the tags do not match or the user has specified explict paths to include or exclude via command line options""" if not is_tagged(self.tags, self.opt.tags): LOG.info("Sk...
[ "def", "filtered", "(", "self", ")", ":", "if", "not", "is_tagged", "(", "self", ".", "tags", ",", "self", ".", "opt", ".", "tags", ")", ":", "LOG", ".", "info", "(", "\"Skipping %s as it does not have requested tags\"", ",", "self", ".", "path", ")", "r...
38.5625
18.5625
def kpl_status(self, address, group): """Get the status of a KPL button.""" addr = Address(address) device = self.plm.devices[addr.id] device.states[group].async_refresh_state()
[ "def", "kpl_status", "(", "self", ",", "address", ",", "group", ")", ":", "addr", "=", "Address", "(", "address", ")", "device", "=", "self", ".", "plm", ".", "devices", "[", "addr", ".", "id", "]", "device", ".", "states", "[", "group", "]", ".", ...
41
4.8
def get_node(self, role: str, default=None) -> BioCNode: """ Get the first node with role Args: role: role default: node returned instead of raising StopIteration Returns: the first node with role """ return next((node for node in sel...
[ "def", "get_node", "(", "self", ",", "role", ":", "str", ",", "default", "=", "None", ")", "->", "BioCNode", ":", "return", "next", "(", "(", "node", "for", "node", "in", "self", ".", "nodes", "if", "node", ".", "role", "==", "role", ")", ",", "d...
29
20
def read_binary_array(self, key, b64decode=True, decode=False): """Read method of CRUD operation for binary array data. Args: key (string): The variable to read from the DB. b64decode (bool): If true the data will be base64 decoded. decode (bool): If true the data wi...
[ "def", "read_binary_array", "(", "self", ",", "key", ",", "b64decode", "=", "True", ",", "decode", "=", "False", ")", ":", "data", "=", "None", "if", "key", "is", "not", "None", ":", "data", "=", "self", ".", "db", ".", "read", "(", "key", ".", "...
42.571429
18.114286
def read_annotations(**kws): """Read annotations from either a GAF file or NCBI's gene2go file.""" if 'gaf' not in kws and 'gene2go' not in kws: return gene2gos = None if 'gaf' in kws: gene2gos = read_gaf(kws['gaf'], prt=sys.stdout) if not gene2gos: raise RuntimeError...
[ "def", "read_annotations", "(", "*", "*", "kws", ")", ":", "if", "'gaf'", "not", "in", "kws", "and", "'gene2go'", "not", "in", "kws", ":", "return", "gene2gos", "=", "None", "if", "'gaf'", "in", "kws", ":", "gene2gos", "=", "read_gaf", "(", "kws", "[...
45
21.1875
def str2type(value): """ Take a string and convert it to a value of proper type. .. testsetup:: from proso.coversion import str2type .. doctest:: >>> print(str2type("[1, 2, 3]") [1, 2, 3] """ if not isinstance(value, str): return value ...
[ "def", "str2type", "(", "value", ")", ":", "if", "not", "isinstance", "(", "value", ",", "str", ")", ":", "return", "value", "try", ":", "return", "json", ".", "loads", "(", "value", ")", "except", "JSONDecodeError", ":", "return", "value" ]
19.4
20.3
def dynamize_attribute_updates(self, pending_updates): """ Convert a set of pending item updates into the structure required by Layer1. """ d = {} for attr_name in pending_updates: action, value = pending_updates[attr_name] if value is None: ...
[ "def", "dynamize_attribute_updates", "(", "self", ",", "pending_updates", ")", ":", "d", "=", "{", "}", "for", "attr_name", "in", "pending_updates", ":", "action", ",", "value", "=", "pending_updates", "[", "attr_name", "]", "if", "value", "is", "None", ":",...
37
13.8
def _setup_gc2_framework(self): """ This method establishes the GC2 framework for a multi-segment (and indeed multi-typology) case based on the description in Spudich & Chiou (2015) - see section on Generalized Coordinate System for Multiple Rupture Traces """ # G...
[ "def", "_setup_gc2_framework", "(", "self", ")", ":", "# Generate cartesian edge set", "edge_sets", "=", "self", ".", "_get_cartesian_edge_set", "(", ")", "self", ".", "gc2_config", "=", "{", "}", "# Determine furthest two points apart", "endpoint_set", "=", "numpy", ...
46.186441
15.779661
def normalize_result(result, default, threshold=0.2): """Interpret a chardet result.""" if result is None: return default if result.get('confidence') is None: return default if result.get('confidence') < threshold: return default return normalize_encoding(result.get('encoding...
[ "def", "normalize_result", "(", "result", ",", "default", ",", "threshold", "=", "0.2", ")", ":", "if", "result", "is", "None", ":", "return", "default", "if", "result", ".", "get", "(", "'confidence'", ")", "is", "None", ":", "return", "default", "if", ...
36.1
10.8
def sign(ctx, file, account): """ Sign a message with an account """ if not file: print_message("Prompting for message. Terminate with CTRL-D", "info") file = click.get_text_stream("stdin") m = Message(file.read(), bitshares_instance=ctx.bitshares) print_message(m.sign(account), "inf...
[ "def", "sign", "(", "ctx", ",", "file", ",", "account", ")", ":", "if", "not", "file", ":", "print_message", "(", "\"Prompting for message. Terminate with CTRL-D\"", ",", "\"info\"", ")", "file", "=", "click", ".", "get_text_stream", "(", "\"stdin\"", ")", "m"...
39.5
12.625
def stop(self): '''Set everything back to normal and collect our data''' for key, value in self._configs.items(): self._client.config_set(key, value) logs = self._client.execute_command('slowlog', 'get', 100000) current = { 'name': None, 'accumulated': defaultdict...
[ "def", "stop", "(", "self", ")", ":", "for", "key", ",", "value", "in", "self", ".", "_configs", ".", "items", "(", ")", ":", "self", ".", "_client", ".", "config_set", "(", "key", ",", "value", ")", "logs", "=", "self", ".", "_client", ".", "exe...
46.212121
18.454545
def is_running(conn, args): """ Run a command to check the status of a mon, return a boolean. We heavily depend on the format of the output, if that ever changes we need to modify this. Check daemon status for 3 times output of the status should be similar to:: mon.mira094: running {"v...
[ "def", "is_running", "(", "conn", ",", "args", ")", ":", "stdout", ",", "stderr", ",", "_", "=", "remoto", ".", "process", ".", "check", "(", "conn", ",", "args", ")", "result_string", "=", "b' '", ".", "join", "(", "stdout", ")", "for", "run_check",...
28
18.24
def parse_buckets(self, bucket, params): """ Parse a single S3 bucket TODO: - CORS - Lifecycle - Notification ? - Get bucket's policy :param bucket: :param params: :return: """ bucket['name'] = bucket.pop('Name') a...
[ "def", "parse_buckets", "(", "self", ",", "bucket", ",", "params", ")", ":", "bucket", "[", "'name'", "]", "=", "bucket", ".", "pop", "(", "'Name'", ")", "api_client", "=", "params", "[", "'api_clients'", "]", "[", "get_s3_list_region", "(", "list", "(",...
44.666667
23.190476
def FromBinary(cls, record_data, record_count=1): """Create an UpdateRecord subclass from binary record data. This should be called with a binary record blob (NOT including the record type header) and it will decode it into a SetDeviceTagRecord. Args: record_data (bytearray...
[ "def", "FromBinary", "(", "cls", ",", "record_data", ",", "record_count", "=", "1", ")", ":", "_cmd", ",", "_address", ",", "_resp_length", ",", "payload", "=", "cls", ".", "_parse_rpc_info", "(", "record_data", ")", "try", ":", "os_info", ",", "app_info",...
45.02439
27.609756
def stop(self): """Stop the logging for this entry""" if (self.cf.link is not None): if (self.id is None): logger.warning('Stopping block, but no block registered') else: logger.debug('Sending stop logging for block id=%d', self.id) ...
[ "def", "stop", "(", "self", ")", ":", "if", "(", "self", ".", "cf", ".", "link", "is", "not", "None", ")", ":", "if", "(", "self", ".", "id", "is", "None", ")", ":", "logger", ".", "warning", "(", "'Stopping block, but no block registered'", ")", "el...
44.5
15.416667
def time_left(self): """ `int`: The amount of time left until the subscription expires (seconds) If the subscription is unsubscribed (or not yet subscribed), `time_left` is 0. """ if self._timestamp is None: return 0 else: time_left = self...
[ "def", "time_left", "(", "self", ")", ":", "if", "self", ".", "_timestamp", "is", "None", ":", "return", "0", "else", ":", "time_left", "=", "self", ".", "timeout", "-", "(", "time", ".", "time", "(", ")", "-", "self", ".", "_timestamp", ")", "retu...
33.666667
19.666667
def blob_exists(self, table, digest): """ Returns true if the blob with the given digest exists under the given table. """ response = self._request('HEAD', _blob_path(table, digest)) if response.status == 200: return True elif response.status == 404: ...
[ "def", "blob_exists", "(", "self", ",", "table", ",", "digest", ")", ":", "response", "=", "self", ".", "_request", "(", "'HEAD'", ",", "_blob_path", "(", "table", ",", "digest", ")", ")", "if", "response", ".", "status", "==", "200", ":", "return", ...
33.545455
9.909091
def cli(): """ Allow the module to be called from the cli. """ import argparse parser = argparse.ArgumentParser(description='Send data to graphite') # Core of the application is to accept a metric and a value. parser.add_argument('metric', metavar='metric', type=str, help='...
[ "def", "cli", "(", ")", ":", "import", "argparse", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Send data to graphite'", ")", "# Core of the application is to accept a metric and a value.", "parser", ".", "add_argument", "(", "'metric'", ...
33.111111
21.277778
def from_view(cls, view, *methods, name=None): """Create a handler class from function or coroutine.""" docs = getattr(view, '__doc__', None) view = to_coroutine(view) methods = methods or ['GET'] if METH_ANY in methods: methods = METH_ALL def proxy(self, *a...
[ "def", "from_view", "(", "cls", ",", "view", ",", "*", "methods", ",", "name", "=", "None", ")", ":", "docs", "=", "getattr", "(", "view", ",", "'__doc__'", ",", "None", ")", "view", "=", "to_coroutine", "(", "view", ")", "methods", "=", "methods", ...
31.277778
14.722222
def render_template(self): """Render and save API doc in openapi.yml.""" self._parse_paths() context = dict(napp=self._napp.__dict__, paths=self._paths) self._save(context)
[ "def", "render_template", "(", "self", ")", ":", "self", ".", "_parse_paths", "(", ")", "context", "=", "dict", "(", "napp", "=", "self", ".", "_napp", ".", "__dict__", ",", "paths", "=", "self", ".", "_paths", ")", "self", ".", "_save", "(", "contex...
40
13.4
def create_member(self, member_json): ''' Create a Member object from JSON object Returns: Member: The member from the given `member_json`. ''' return trolly.member.Member( trello_client=self, member_id=member_json['id'], name=memb...
[ "def", "create_member", "(", "self", ",", "member_json", ")", ":", "return", "trolly", ".", "member", ".", "Member", "(", "trello_client", "=", "self", ",", "member_id", "=", "member_json", "[", "'id'", "]", ",", "name", "=", "member_json", "[", "'fullName...
28.307692
16
def port_profile_qos_profile_qos_cos_traffic_class(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile") name_key = ET.SubElement(port_profile, "name") ...
[ "def", "port_profile_qos_profile_qos_cos_traffic_class", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "port_profile", "=", "ET", ".", "SubElement", "(", "config", ",", "\"port-profile\"", ",", "xm...
48.714286
18.928571
def check_spec(self, pos_args, kwargs=None): """Check if there are any missing or duplicate arguments. Args: pos_args (list): A list of arguments that will be passed as positional arguments. kwargs (dict): A dictionary of the keyword arguments that will be passed...
[ "def", "check_spec", "(", "self", ",", "pos_args", ",", "kwargs", "=", "None", ")", ":", "if", "kwargs", "is", "None", ":", "kwargs", "=", "{", "}", "if", "self", ".", "varargs", "is", "not", "None", "or", "self", ".", "kwargs", "is", "not", "None"...
38.912281
26.45614