text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def dodirot_V(di_block, Dbar, Ibar): """ Rotate an array of dec/inc pairs to coordinate system with Dec,Inc as 0,90 Parameters ___________________ di_block : array of [[Dec1,Inc1],[Dec2,Inc2],....] Dbar : declination of desired center Ibar : inclination of desired center Returns __...
[ "def", "dodirot_V", "(", "di_block", ",", "Dbar", ",", "Ibar", ")", ":", "N", "=", "di_block", ".", "shape", "[", "0", "]", "DipDir", ",", "Dip", "=", "np", ".", "ones", "(", "N", ",", "dtype", "=", "np", ".", "float", ")", ".", "transpose", "(...
34.727273
17.636364
def report_target_info(self, scope, target, keys, val): """Add target information to run_info under target_data. Will Recursively construct a nested dict with the keys provided. Primitive values can be overwritten with other primitive values, but a primitive value cannot be overwritten with a dictiona...
[ "def", "report_target_info", "(", "self", ",", "scope", ",", "target", ",", "keys", ",", "val", ")", ":", "new_key_list", "=", "[", "target", ".", "address", ".", "spec", ",", "scope", "]", "new_key_list", "+=", "keys", "self", ".", "_merge_list_of_keys_in...
44
26.884615
def eval_stdin(): 'evaluate expressions read from stdin' cmd = ['plash', 'eval'] p = subprocess.Popen(cmd, stdin=sys.stdin, stdout=sys.stdout) exit = p.wait() if exit: raise subprocess.CalledProcessError(exit, cmd)
[ "def", "eval_stdin", "(", ")", ":", "cmd", "=", "[", "'plash'", ",", "'eval'", "]", "p", "=", "subprocess", ".", "Popen", "(", "cmd", ",", "stdin", "=", "sys", ".", "stdin", ",", "stdout", "=", "sys", ".", "stdout", ")", "exit", "=", "p", ".", ...
33.714286
18
def get_attname_column(self): """ Get the database column name automatically in most cases. """ # See "A guide to Field parameters": django/db/models/fields/__init__.py # * attname: The attribute to use on the model object. This is the same as # "name",...
[ "def", "get_attname_column", "(", "self", ")", ":", "# See \"A guide to Field parameters\": django/db/models/fields/__init__.py", "# * attname: The attribute to use on the model object. This is the same as", "# \"name\", except in the case of ForeignKeys, where \"_id\" is", "# ...
45.84
18.32
def get_current_price(crypto, fiat, services=None, convert_to=None, helper_prices=None, **modes): """ High level function for getting current exchange rate for a cryptocurrency. If the fiat value is not explicitly defined, it will try the wildcard service. if that does not work, it tries converting to a...
[ "def", "get_current_price", "(", "crypto", ",", "fiat", ",", "services", "=", "None", ",", "convert_to", "=", "None", ",", "helper_prices", "=", "None", ",", "*", "*", "modes", ")", ":", "fiat", "=", "fiat", ".", "lower", "(", ")", "args", "=", "{", ...
41.571429
23.178571
def process_result(self, context, result_body, exc, content_type): """ given an result body and an exception object, return the appropriate result object, or raise an exception. """ return process_result(self, context, result_body, exc, content_type)
[ "def", "process_result", "(", "self", ",", "context", ",", "result_body", ",", "exc", ",", "content_type", ")", ":", "return", "process_result", "(", "self", ",", "context", ",", "result_body", ",", "exc", ",", "content_type", ")" ]
41.714286
12.857143
def output_json(data, code, headers=None): '''Use Flask JSON to serialize''' resp = make_response(json.dumps(data), code) resp.headers.extend(headers or {}) return resp
[ "def", "output_json", "(", "data", ",", "code", ",", "headers", "=", "None", ")", ":", "resp", "=", "make_response", "(", "json", ".", "dumps", "(", "data", ")", ",", "code", ")", "resp", ".", "headers", ".", "extend", "(", "headers", "or", "{", "}...
36
8
def set(self, value, mode=None): """Sets metric value. :param int|long value: New value. :param str|unicode mode: Update mode. * None - Unconditional update. * max - Sets metric value if it is greater that the current one. * min - Sets metric value if it is...
[ "def", "set", "(", "self", ",", "value", ",", "mode", "=", "None", ")", ":", "if", "mode", "==", "'max'", ":", "func", "=", "uwsgi", ".", "metric_set_max", "elif", "mode", "==", "'min'", ":", "func", "=", "uwsgi", ".", "metric_set_min", "else", ":", ...
24.333333
20.416667
def raw_datastream(request, pid, dsid, repo=None, headers=None, as_of_date=None): ''' Access raw datastream content from a Fedora object. Returns :class:`~django.http.HttpResponse` for HEAD requests, :class:`~django.http.StreamingHttpResponse` for GET requests. The headers and status code fr...
[ "def", "raw_datastream", "(", "request", ",", "pid", ",", "dsid", ",", "repo", "=", "None", ",", "headers", "=", "None", ",", "as_of_date", "=", "None", ")", ":", "return", "_raw_datastream", "(", "request", ",", "pid", ",", "dsid", ",", "repo", "=", ...
48.652174
25.956522
def get_reversed_statuses(context): """Return a mapping of exit codes to status strings. Args: context (scriptworker.context.Context): the scriptworker context Returns: dict: the mapping of exit codes to status strings. """ _rev = {v: k for k, v in STATUSES.items()} _rev.updat...
[ "def", "get_reversed_statuses", "(", "context", ")", ":", "_rev", "=", "{", "v", ":", "k", "for", "k", ",", "v", "in", "STATUSES", ".", "items", "(", ")", "}", "_rev", ".", "update", "(", "dict", "(", "context", ".", "config", "[", "'reversed_statuse...
28.307692
21.769231
def loggabor(self, x_pos, y_pos, sf_0, B_sf, theta, B_theta, preprocess=True): """ Returns the envelope of a LogGabor Note that the convention for coordinates follows that of matrices: the origin is at the top left of the image, and coordinates are first the rows (vertical axis,...
[ "def", "loggabor", "(", "self", ",", "x_pos", ",", "y_pos", ",", "sf_0", ",", "B_sf", ",", "theta", ",", "B_theta", ",", "preprocess", "=", "True", ")", ":", "env", "=", "np", ".", "multiply", "(", "self", ".", "band", "(", "sf_0", ",", "B_sf", "...
47.55
29.05
def push(self, obj): """Pushes a new item to the stack""" rv = getattr(self._local, "stack", None) if rv is None: self._local.stack = rv = [] rv.append(obj) return rv
[ "def", "push", "(", "self", ",", "obj", ")", ":", "rv", "=", "getattr", "(", "self", ".", "_local", ",", "\"stack\"", ",", "None", ")", "if", "rv", "is", "None", ":", "self", ".", "_local", ".", "stack", "=", "rv", "=", "[", "]", "rv", ".", "...
30.285714
12.571429
def load_related(self, meta, fname, data, fields, encoding): '''Parse data for related objects.''' field = meta.dfields[fname] if field in meta.multifields: fmeta = field.structure_class()._meta if fmeta.name in ('hashtable', 'zset'): return ((native...
[ "def", "load_related", "(", "self", ",", "meta", ",", "fname", ",", "data", ",", "fields", ",", "encoding", ")", ":", "field", "=", "meta", ".", "dfields", "[", "fname", "]", "if", "field", "in", "meta", ".", "multifields", ":", "fmeta", "=", "field"...
46.133333
13.333333
def confd_state_netconf_listen_tcp_port(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring") netconf = ET.SubElement(confd_state, "netconf") listen = E...
[ "def", "confd_state_netconf_listen_tcp_port", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "confd_state", "=", "ET", ".", "SubElement", "(", "config", ",", "\"confd-state\"", ",", "xmlns", "=", ...
42.615385
13.923077
def get_product_set( self, location, product_set_id, project_id=None, retry=None, timeout=None, metadata=None ): """ For the documentation see: :class:`~airflow.contrib.operators.gcp_vision_operator.CloudVisionProductSetGetOperator` """ client = self.get_conn() ...
[ "def", "get_product_set", "(", "self", ",", "location", ",", "product_set_id", ",", "project_id", "=", "None", ",", "retry", "=", "None", ",", "timeout", "=", "None", ",", "metadata", "=", "None", ")", ":", "client", "=", "self", ".", "get_conn", "(", ...
49.785714
23.928571
def register_all(self, callback, user_data=None): """Register a callback for all sensors.""" self._callback = callback self._callback_data = user_data
[ "def", "register_all", "(", "self", ",", "callback", ",", "user_data", "=", "None", ")", ":", "self", ".", "_callback", "=", "callback", "self", ".", "_callback_data", "=", "user_data" ]
42.75
4.25
def parse_request(cls, request_string): """JSONRPC allows for **batch** requests to be communicated as array of dicts. This method parses out each individual element in the batch and returns a list of tuples, each tuple a result of parsing of each item in the batch. :Returns: ...
[ "def", "parse_request", "(", "cls", ",", "request_string", ")", ":", "try", ":", "batch", "=", "cls", ".", "json_loads", "(", "request_string", ")", "except", "ValueError", "as", "err", ":", "raise", "errors", ".", "RPCParseError", "(", "\"No valid JSON. (%s)\...
48.357143
23.928571
def get_elt_projected_plots(self, zero_to_efermi=True, ylim=None, vbm_cbm_marker=False): """ Method returning a plot composed of subplots along different elements Returns: a pylab object with different subfigures for each projection The bl...
[ "def", "get_elt_projected_plots", "(", "self", ",", "zero_to_efermi", "=", "True", ",", "ylim", "=", "None", ",", "vbm_cbm_marker", "=", "False", ")", ":", "band_linewidth", "=", "1.0", "proj", "=", "self", ".", "_get_projections_by_branches", "(", "{", "e", ...
49.244186
20.732558
def _expand_variable_match(positional_vars, named_vars, match): """Expand a matched variable with its value. Args: positional_vars (list): A list of positonal variables. This list will be modified. named_vars (dict): A dictionary of named variables. match (re.Match): A regul...
[ "def", "_expand_variable_match", "(", "positional_vars", ",", "named_vars", ",", "match", ")", ":", "positional", "=", "match", ".", "group", "(", "\"positional\"", ")", "name", "=", "match", ".", "group", "(", "\"name\"", ")", "if", "name", "is", "not", "...
37.297297
23.054054
def rotate_vectors(R, v, axis=-1): """Rotate vectors by given quaternions For simplicity, this function simply converts the input quaternion(s) to a matrix, and rotates the input vector(s) by the usual matrix multiplication. However, it should be noted that if each input quaternion is only used to...
[ "def", "rotate_vectors", "(", "R", ",", "v", ",", "axis", "=", "-", "1", ")", ":", "R", "=", "np", ".", "asarray", "(", "R", ",", "dtype", "=", "np", ".", "quaternion", ")", "v", "=", "np", ".", "asarray", "(", "v", ",", "dtype", "=", "float"...
36.705882
21.705882
def from_py_func(cls, func): """ Create a ``CustomJS`` instance from a Python function. The function is translated to JavaScript using PScript. """ from bokeh.util.deprecation import deprecated deprecated("'from_py_func' is deprecated and will be removed in an eventual 2.0 releas...
[ "def", "from_py_func", "(", "cls", ",", "func", ")", ":", "from", "bokeh", ".", "util", ".", "deprecation", "import", "deprecated", "deprecated", "(", "\"'from_py_func' is deprecated and will be removed in an eventual 2.0 release. \"", "\"Use CustomJS directly instead.\"", ")...
57.409091
22.818182
def _main_cli(self): """Main function of SMAC for CLI interface Returns ------- instance optimizer """ self.logger.info("SMAC call: %s" % (" ".join(sys.argv))) cmd_reader = CMDReader() args, _ = cmd_reader.read_cmd() root_log...
[ "def", "_main_cli", "(", "self", ")", ":", "self", ".", "logger", ".", "info", "(", "\"SMAC call: %s\"", "%", "(", "\" \"", ".", "join", "(", "sys", ".", "argv", ")", ")", ")", "cmd_reader", "=", "CMDReader", "(", ")", "args", ",", "_", "=", "cmd_r...
31.584615
14.430769
def constant(name, value): """Creates a constant that can be referenced from gin config files. After calling this function in Python, the constant can be referenced from within a Gin config file using the macro syntax. For example, in Python: gin.constant('THE_ANSWER', 42) Then, in a Gin config file: ...
[ "def", "constant", "(", "name", ",", "value", ")", ":", "if", "not", "config_parser", ".", "MODULE_RE", ".", "match", "(", "name", ")", ":", "raise", "ValueError", "(", "\"Invalid constant selector '{}'.\"", ".", "format", "(", "name", ")", ")", "if", "_CO...
38.619048
26.142857
def getKw(self, kw): """ Extract doc snippet for element configuration, :param kw: element name :return: instance itself 1 call getKwAsDict() to return config as a dict 2 call getKwAsJson() to return config as json string 3 call getKwAsStri...
[ "def", "getKw", "(", "self", ",", "kw", ")", ":", "ikw", "=", "kw", ".", "lower", "(", ")", "line_continue_flag", "=", "''", "appendflag", "=", "False", "try", ":", "for", "line", "in", "self", ".", "file_lines", ":", "if", "line", ".", "strip", "(...
40.12766
18.489362
def random_density(qubits: Union[int, Qubits]) -> Density: """ Returns: A randomly sampled Density from the Hilbert–Schmidt ensemble of quantum states Ref: "Induced measures in the space of mixed quantum states" Karol Zyczkowski, Hans-Juergen Sommers, J. Phys. A34, 7111-7125 (2001) ...
[ "def", "random_density", "(", "qubits", ":", "Union", "[", "int", ",", "Qubits", "]", ")", "->", "Density", ":", "N", ",", "qubits", "=", "qubits_count_tuple", "(", "qubits", ")", "size", "=", "(", "2", "**", "N", ",", "2", "**", "N", ")", "ginibre...
41.352941
17.823529
def underlying_typedef_type(self): """Return the underlying type of a typedef declaration. Returns a Type for the typedef this cursor is a declaration for. If the current cursor is not a typedef, this raises. """ if not hasattr(self, '_underlying_type'): assert self....
[ "def", "underlying_typedef_type", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'_underlying_type'", ")", ":", "assert", "self", ".", "kind", ".", "is_declaration", "(", ")", "self", ".", "_underlying_type", "=", "conf", ".", "lib", "."...
39.166667
15.166667
def can_ignore_error(self, reqhnd=None): """Tests if the error is worth reporting. """ value = sys.exc_info()[1] try: if isinstance(value, BrokenPipeError) or \ isinstance(value, ConnectionResetError): return True except NameError: ...
[ "def", "can_ignore_error", "(", "self", ",", "reqhnd", "=", "None", ")", ":", "value", "=", "sys", ".", "exc_info", "(", ")", "[", "1", "]", "try", ":", "if", "isinstance", "(", "value", ",", "BrokenPipeError", ")", "or", "isinstance", "(", "value", ...
32.944444
11.055556
def mitochondrial_genes(host, org) -> pd.Index: """Mitochondrial gene symbols for specific organism through BioMart. Parameters ---------- host : {{'www.ensembl.org', ...}} A valid BioMart host URL. org : {{'hsapiens', 'mmusculus', 'drerio'}} Organism to query. Currently available a...
[ "def", "mitochondrial_genes", "(", "host", ",", "org", ")", "->", "pd", ".", "Index", ":", "try", ":", "from", "bioservices", "import", "biomart", "except", "ImportError", ":", "raise", "ImportError", "(", "'You need to install the `bioservices` module.'", ")", "f...
32.795918
17.469388
def serialize(self) -> str: """ Dump current object to a JSON-compatible dictionary. :return: dict representation of current DIDDoc """ return { '@context': DIDDoc.CONTEXT, 'id': canon_ref(self.did, self.did), 'publicKey': [pubkey.to_dict() f...
[ "def", "serialize", "(", "self", ")", "->", "str", ":", "return", "{", "'@context'", ":", "DIDDoc", ".", "CONTEXT", ",", "'id'", ":", "canon_ref", "(", "self", ".", "did", ",", "self", ".", "did", ")", ",", "'publicKey'", ":", "[", "pubkey", ".", "...
37.470588
19.352941
def strftimegen(start_dt, end_dt): """ Return a generator function for datetime format strings. The generator produce a day-by-day sequence starting from the first datetime to the second datetime argument. """ if start_dt > end_dt: raise ValueError("the start datetime is after the end da...
[ "def", "strftimegen", "(", "start_dt", ",", "end_dt", ")", ":", "if", "start_dt", ">", "end_dt", ":", "raise", "ValueError", "(", "\"the start datetime is after the end datetime: (%r,%r)\"", "%", "(", "start_dt", ",", "end_dt", ")", ")", "def", "iterftime", "(", ...
35.73913
19.652174
def create_function(self, vpc_config): """Create lambda function, configures lambda parameters. We need to upload non-zero zip when creating function. Uploading hello_world python lambda function since AWS doesn't care which executable is in ZIP. Args: vpc_config (d...
[ "def", "create_function", "(", "self", ",", "vpc_config", ")", ":", "zip_file", "=", "'lambda-holder.zip'", "with", "zipfile", ".", "ZipFile", "(", "zip_file", ",", "mode", "=", "'w'", ")", "as", "zipped", ":", "zipped", ".", "writestr", "(", "'index.py'", ...
39.377778
18.2
def precip(self, start, end, **kwargs): r""" Returns precipitation observations at a user specified location for a specified time. Users must specify at least one geographic search parameter ('stid', 'state', 'country', 'county', 'radius', 'bbox', 'cwa', 'nwsfirezone', 'gacc', or 'subgacc') to o...
[ "def", "precip", "(", "self", ",", "start", ",", "end", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_check_geo_param", "(", "kwargs", ")", "kwargs", "[", "'start'", "]", "=", "start", "kwargs", "[", "'end'", "]", "=", "end", "kwargs", "[", "'t...
57.053333
32.506667
def _l2rgb(self, mode): """Convert from L (black and white) to RGB. """ self._check_modes(("L", "LA")) self.channels.append(self.channels[0].copy()) self.channels.append(self.channels[0].copy()) if self.fill_value is not None: self.fill_value = self.fill_value...
[ "def", "_l2rgb", "(", "self", ",", "mode", ")", ":", "self", ".", "_check_modes", "(", "(", "\"L\"", ",", "\"LA\"", ")", ")", "self", ".", "channels", ".", "append", "(", "self", ".", "channels", "[", "0", "]", ".", "copy", "(", ")", ")", "self",...
41.333333
10.666667
def _getitem_via_pathlist(external_dict,path_list,**kwargs): ''' y = {'c': {'b': 200}} _getitem_via_pathlist(y,['c','b']) ''' if('s2n' in kwargs): s2n = kwargs['s2n'] else: s2n = 0 if('n2s' in kwargs): n2s = kwargs['n2s'] else: n2s = 0 this = e...
[ "def", "_getitem_via_pathlist", "(", "external_dict", ",", "path_list", ",", "*", "*", "kwargs", ")", ":", "if", "(", "'s2n'", "in", "kwargs", ")", ":", "s2n", "=", "kwargs", "[", "'s2n'", "]", "else", ":", "s2n", "=", "0", "if", "(", "'n2s'", "in", ...
23.333333
18.444444
def continues(method): '''Method decorator signifying that the visitor should not visit the current node's children once this method has been invoked. ''' @functools.wraps(method) def wrapped(self, *args, **kwargs): yield method(self, *args, **kwargs) rais...
[ "def", "continues", "(", "method", ")", ":", "@", "functools", ".", "wraps", "(", "method", ")", "def", "wrapped", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "yield", "method", "(", "self", ",", "*", "args", ",", "*", "*", ...
39.111111
16.888889
def context(name): '''A decorator for theme context processors''' def wrapper(func): g.theme.context_processors[name] = func return func return wrapper
[ "def", "context", "(", "name", ")", ":", "def", "wrapper", "(", "func", ")", ":", "g", ".", "theme", ".", "context_processors", "[", "name", "]", "=", "func", "return", "func", "return", "wrapper" ]
29
16.666667
def execute_script(script_blocks, script_vars, gallery_conf): """Execute and capture output from python script already in block structure Parameters ---------- script_blocks : list (label, content, line_number) List where each element is a tuple with the label ('text' or 'code'), ...
[ "def", "execute_script", "(", "script_blocks", ",", "script_vars", ",", "gallery_conf", ")", ":", "example_globals", "=", "{", "# A lot of examples contains 'print(__doc__)' for example in", "# scikit-learn so that running the example prints some useful", "# information. Because the do...
39.724638
20.942029
def _matching_string(matched, string): """Return the string as byte or unicode depending on the type of matched, assuming string is an ASCII string. """ if string is None: return string if IS_PY2: # pylint: disable=undefined-variable if isinsta...
[ "def", "_matching_string", "(", "matched", ",", "string", ")", ":", "if", "string", "is", "None", ":", "return", "string", "if", "IS_PY2", ":", "# pylint: disable=undefined-variable", "if", "isinstance", "(", "matched", ",", "text_type", ")", ":", "return", "t...
39.428571
14.428571
def list_namespaced_replica_set(self, namespace, **kwargs): """ list or watch objects of kind ReplicaSet This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_namespaced_replica_set(namespac...
[ "def", "list_namespaced_replica_set", "(", "self", ",", "namespace", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async_req'", ")", ":", "return", "self", ".", "list_namesp...
166.928571
137.142857
def clone (self, new_id, new_toolset_properties): """ Returns another generator which differers from $(self) in - id - value to <toolset> feature in properties """ assert isinstance(new_id, basestring) assert is_iterable_typed(new_toolset_properties, basestrin...
[ "def", "clone", "(", "self", ",", "new_id", ",", "new_toolset_properties", ")", ":", "assert", "isinstance", "(", "new_id", ",", "basestring", ")", "assert", "is_iterable_typed", "(", "new_toolset_properties", ",", "basestring", ")", "return", "self", ".", "__cl...
54.571429
18
def WaitUntilComplete(self,poll_freq=2,timeout=None): """Poll until all request objects have completed. If status is 'notStarted' or 'executing' continue polling. If status is 'succeeded' then success Else log as error poll_freq option is in seconds Returns an Int the number of unsuccessful requests. Th...
[ "def", "WaitUntilComplete", "(", "self", ",", "poll_freq", "=", "2", ",", "timeout", "=", "None", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "while", "len", "(", "self", ".", "requests", ")", ":", "cur_requests", "=", "[", "]", "for"...
38.2
29
def query_orders(self, accounts, status='filled'): """查询订单 Arguments: accounts {[type]} -- [description] Keyword Arguments: status {str} -- 'open' 待成交 'filled' 成交 (default: {'filled'}) Returns: [type] -- [description] """ try: ...
[ "def", "query_orders", "(", "self", ",", "accounts", ",", "status", "=", "'filled'", ")", ":", "try", ":", "data", "=", "self", ".", "call", "(", "\"orders\"", ",", "{", "'client'", ":", "accounts", ",", "'status'", ":", "status", "}", ")", "if", "da...
39.302632
19.513158
def utilization(prev, curr, counters): """ calculate the utilization delta_busy = curr.busy - prev.busy delta_idle = curr.idle - prev.idle utilization = delta_busy / (delta_busy + delta_idle) :param prev: previous resource :param curr: current resource :param counters: list of two, busy ti...
[ "def", "utilization", "(", "prev", ",", "curr", ",", "counters", ")", ":", "busy_prop", ",", "idle_prop", "=", "counters", "pb", "=", "getattr", "(", "prev", ",", "busy_prop", ")", "pi", "=", "getattr", "(", "prev", ",", "idle_prop", ")", "cb", "=", ...
25.958333
15.375
def AddBlock(self, block): """ Add the given block to the model and also its input/output variables """ if isinstance(block, Block): self.blocks.append(block) self.max_order = max(self.max_order, block.max_input_order-1) self.max_order = max(self.max_o...
[ "def", "AddBlock", "(", "self", ",", "block", ")", ":", "if", "isinstance", "(", "block", ",", "Block", ")", ":", "self", ".", "blocks", ".", "append", "(", "block", ")", "self", ".", "max_order", "=", "max", "(", "self", ".", "max_order", ",", "bl...
38.214286
14.642857
def get_alternatives(self): """ Get the spelling alternatives for search terms. Returns: A dict in form: {<search term>: {'count': <number of times the searh term occurs in the Storage>, 'words': {<an alternative>: {'count': <number o...
[ "def", "get_alternatives", "(", "self", ")", ":", "return", "dict", "(", "[", "(", "alternatives", ".", "find", "(", "'to'", ")", ".", "text", ",", "{", "'count'", ":", "int", "(", "alternatives", ".", "find", "(", "'count'", ")", ".", "text", ")", ...
61
30.4
def get_author_by_name(self, name: str) -> Optional[Author]: """Get an author by name, if it exists in the database.""" return self.session.query(Author).filter(Author.has_name(name)).one_or_none()
[ "def", "get_author_by_name", "(", "self", ",", "name", ":", "str", ")", "->", "Optional", "[", "Author", "]", ":", "return", "self", ".", "session", ".", "query", "(", "Author", ")", ".", "filter", "(", "Author", ".", "has_name", "(", "name", ")", ")...
70.333333
21.666667
def getsetitem(self, key, klass, args=None, kwdargs=None): """This is similar to setdefault(), except that the new value is created by instantiating _klass_. This prevents you from having to create an object and initialize it and then throw it away if there is already a dictionary item ...
[ "def", "getsetitem", "(", "self", ",", "key", ",", "klass", ",", "args", "=", "None", ",", "kwdargs", "=", "None", ")", ":", "with", "self", ".", "lock", ":", "if", "key", "in", "self", ":", "return", "self", ".", "getitem", "(", "key", ")", "# I...
33.45
16.7
def optionIsSet(self, name): """ Check whether an option with a given name exists and has been set. :param name: the name of the option to check; can be short or long name. :return: true if an option matching the given name exists and it has had it's value set by the user """ name ...
[ "def", "optionIsSet", "(", "self", ",", "name", ")", ":", "name", "=", "name", ".", "strip", "(", ")", "if", "not", "self", ".", "hasOption", "(", "name", ")", ":", "return", "False", "return", "self", ".", "getOption", "(", "name", ")", ".", "isSe...
34.583333
16.916667
def remove_section(self, section): """Remove a file section.""" existed = section in self._sections if existed: del self._sections[section] del self._proxies[section] return existed
[ "def", "remove_section", "(", "self", ",", "section", ")", ":", "existed", "=", "section", "in", "self", ".", "_sections", "if", "existed", ":", "del", "self", ".", "_sections", "[", "section", "]", "del", "self", ".", "_proxies", "[", "section", "]", ...
33
7.285714
def parse_external_id(output, type=EXTERNAL_ID_TYPE_ANY): """ Attempt to parse the output of job submission commands for an external id.__doc__ >>> parse_external_id("12345.pbsmanager") '12345.pbsmanager' >>> parse_external_id('Submitted batch job 185') '185' >>> parse_external_id('Submitte...
[ "def", "parse_external_id", "(", "output", ",", "type", "=", "EXTERNAL_ID_TYPE_ANY", ")", ":", "external_id", "=", "None", "for", "pattern_type", ",", "pattern", "in", "EXTERNAL_ID_PATTERNS", ":", "if", "type", "!=", "EXTERNAL_ID_TYPE_ANY", "and", "type", "!=", ...
31.307692
20.538462
def exec_workflow(self, model, record_id, signal): """Execute the workflow `signal` on the instance having the ID `record_id` of `model`. *Python 2:* :raise: :class:`odoorpc.error.RPCError` :raise: :class:`odoorpc.error.InternalError` (if not logged) :raise: `urllib2.UR...
[ "def", "exec_workflow", "(", "self", ",", "model", ",", "record_id", ",", "signal", ")", ":", "if", "tools", ".", "v", "(", "self", ".", "version", ")", "[", "0", "]", ">=", "11", ":", "raise", "DeprecationWarning", "(", "u\"Workflows have been removed in ...
36.37931
15.758621
def query(): """Query hot movies infomation from douban.""" r = requests_get(QUERY_URL) try: rows = r.json()['subject_collection_items'] except (IndexError, TypeError): rows = [] return MoviesCollection(rows)
[ "def", "query", "(", ")", ":", "r", "=", "requests_get", "(", "QUERY_URL", ")", "try", ":", "rows", "=", "r", ".", "json", "(", ")", "[", "'subject_collection_items'", "]", "except", "(", "IndexError", ",", "TypeError", ")", ":", "rows", "=", "[", "]...
21.545455
21.363636
def add_aliases_formatting(self, aliases): """Adds the formatting information on a command's aliases. The formatting should be added to the :attr:`paginator`. The default implementation is the :attr:`aliases_heading` bolded followed by a comma separated list of aliases. This i...
[ "def", "add_aliases_formatting", "(", "self", ",", "aliases", ")", ":", "self", ".", "paginator", ".", "add_line", "(", "'**%s** %s'", "%", "(", "self", ".", "aliases_heading", ",", "', '", ".", "join", "(", "aliases", ")", ")", ",", "empty", "=", "True"...
36.6875
22.375
def decrypt(key, ciphertext): """Decrypt Vigenere encrypted ``ciphertext`` using ``key``. Example: >>> decrypt("KEY", "RIJVS") HELLO Args: key (iterable): The key to use ciphertext (str): The text to decrypt Returns: Decrypted ciphertext """ index = 0 ...
[ "def", "decrypt", "(", "key", ",", "ciphertext", ")", ":", "index", "=", "0", "decrypted", "=", "\"\"", "for", "char", "in", "ciphertext", ":", "if", "char", "in", "string", ".", "punctuation", "+", "string", ".", "whitespace", "+", "string", ".", "dig...
30.037037
22.925926
def video_top(body_output, targets, model_hparams, vocab_size): """Top transformation for video.""" del targets # unused arg num_channels = model_hparams.problem.num_channels shape = common_layers.shape_list(body_output) reshape_shape = shape[:-1] + [num_channels, vocab_size] res = tf.reshape(body_output, ...
[ "def", "video_top", "(", "body_output", ",", "targets", ",", "model_hparams", ",", "vocab_size", ")", ":", "del", "targets", "# unused arg", "num_channels", "=", "model_hparams", ".", "problem", ".", "num_channels", "shape", "=", "common_layers", ".", "shape_list"...
47.666667
14.75
def format_output(data, headers, format_name, **kwargs): """Format output using *format_name*. This is a wrapper around the :class:`TabularOutputFormatter` class. :param iterable data: An :term:`iterable` (e.g. list) of rows. :param iterable headers: The column headers. :param str format_name: The...
[ "def", "format_output", "(", "data", ",", "headers", ",", "format_name", ",", "*", "*", "kwargs", ")", ":", "formatter", "=", "TabularOutputFormatter", "(", "format_name", "=", "format_name", ")", "return", "formatter", ".", "format_output", "(", "data", ",", ...
38.133333
20.666667
def save(self, overwrite=True): """ Saves PopulationSet and TransitSignal. Shouldn't need to use this if you're using :func:`FPPCalculation.from_ini`. Saves :class`PopulationSet` to ``[folder]/popset.h5]`` and :class:`TransitSignal` to ``[folder]/trsig.pkl``. :...
[ "def", "save", "(", "self", ",", "overwrite", "=", "True", ")", ":", "self", ".", "save_popset", "(", "overwrite", "=", "overwrite", ")", "self", ".", "save_signal", "(", ")" ]
29.1875
16.1875
def _spacingx(node, max_dims, xoffset, xspace): '''Determine the spacing of the current node depending on the number of the leaves of the tree ''' x_spacing = _n_terminations(node) * xspace if x_spacing > max_dims[0]: max_dims[0] = x_spacing return xoffset - x_spacing / 2.
[ "def", "_spacingx", "(", "node", ",", "max_dims", ",", "xoffset", ",", "xspace", ")", ":", "x_spacing", "=", "_n_terminations", "(", "node", ")", "*", "xspace", "if", "x_spacing", ">", "max_dims", "[", "0", "]", ":", "max_dims", "[", "0", "]", "=", "...
30.1
18.9
def set_variable(self, name, type_, size): """ Register variable of name and type_, with a (multidimensional) size. :param name: variable name as it appears in code :param type_: may be any key from Kernel.datatypes_size (typically float or double) :param size: either None for s...
[ "def", "set_variable", "(", "self", ",", "name", ",", "type_", ",", "size", ")", ":", "assert", "type_", "in", "self", ".", "datatypes_size", ",", "'only float and double variables are supported'", "if", "self", ".", "datatype", "is", "None", ":", "self", ".",...
52.266667
26.933333
def create(cls, name, protocol_number, protocol_agent=None, comment=None): """ Create the IP Service :param str name: name of ip-service :param int protocol_number: ip proto number for this service :param str,ProtocolAgent protocol_agent: optional protocol agent for ...
[ "def", "create", "(", "cls", ",", "name", ",", "protocol_number", ",", "protocol_agent", "=", "None", ",", "comment", "=", "None", ")", ":", "json", "=", "{", "'name'", ":", "name", ",", "'protocol_number'", ":", "protocol_number", ",", "'protocol_agent_ref'...
39.315789
17.421053
def write_file(file_path, content): """ Write file at the specified path with content. If file exists, it will be overwritten. """ handler = open(file_path, 'w+') handler.write(content) handler.close()
[ "def", "write_file", "(", "file_path", ",", "content", ")", ":", "handler", "=", "open", "(", "file_path", ",", "'w+'", ")", "handler", ".", "write", "(", "content", ")", "handler", ".", "close", "(", ")" ]
27.75
7.25
def slice_naive(self, key): """ Naively (on index) slice the field data and values. Args: key: Int, slice, or iterable to select data and values Returns: field: Sliced field object """ cls = self.__class__ key = check_key(self, key) ...
[ "def", "slice_naive", "(", "self", ",", "key", ")", ":", "cls", "=", "self", ".", "__class__", "key", "=", "check_key", "(", "self", ",", "key", ")", "enum", "=", "pd", ".", "Series", "(", "range", "(", "len", "(", "self", ")", ")", ")", "enum", ...
29.470588
14.647059
def _iter_coords(nsls): """Iterate through all matching coordinates in a sequence of slices.""" # First convert all slices to ranges ranges = list() for nsl in nsls: if isinstance(nsl, int): ranges.append(range(nsl, nsl+1)) else: ranges.append(range(nsl.start, nsl...
[ "def", "_iter_coords", "(", "nsls", ")", ":", "# First convert all slices to ranges", "ranges", "=", "list", "(", ")", "for", "nsl", "in", "nsls", ":", "if", "isinstance", "(", "nsl", ",", "int", ")", ":", "ranges", ".", "append", "(", "range", "(", "nsl...
36.909091
10.636364
def withdraw(self, amount): """ Withdraws specified neopoints from the user's account, returns result Parameters: amount (int) -- Amount of neopoints to withdraw Returns bool - True if successful, False otherwise Raises ...
[ "def", "withdraw", "(", "self", ",", "amount", ")", ":", "pg", "=", "self", ".", "usr", ".", "getPage", "(", "\"http://www.neopets.com/bank.phtml\"", ")", "try", ":", "results", "=", "pg", ".", "find", "(", "text", "=", "\"Account Type:\"", ")", ".", "pa...
39.028571
24.514286
def main(args): """Remove lines after marker.""" filename = args[0] marker = args[1] for line in fileinput.input(filename, inplace=1): print(line.rstrip()) if line.startswith(marker): break
[ "def", "main", "(", "args", ")", ":", "filename", "=", "args", "[", "0", "]", "marker", "=", "args", "[", "1", "]", "for", "line", "in", "fileinput", ".", "input", "(", "filename", ",", "inplace", "=", "1", ")", ":", "print", "(", "line", ".", ...
28.25
14.5
def set_content(self, content): """Set textual content for the object/node. Verifies the node is allowed to contain content, and throws an exception if not. """ if self.allows_content: self.content = content.strip() else: raise UNTLStructureExcept...
[ "def", "set_content", "(", "self", ",", "content", ")", ":", "if", "self", ".", "allows_content", ":", "self", ".", "content", "=", "content", ".", "strip", "(", ")", "else", ":", "raise", "UNTLStructureException", "(", "'Element \"%s\" does not allow textual co...
33.583333
16.25
def role_get(role_id=None, name=None, profile=None, **connection_args): ''' Return a specific roles (keystone role-get) CLI Examples: .. code-block:: bash salt '*' keystone.role_get c965f79c4f864eaaa9c3b41904e67082 salt '*' keystone.role_get role_id=c965f79c4f864eaaa9c3b41904e67082 ...
[ "def", "role_get", "(", "role_id", "=", "None", ",", "name", "=", "None", ",", "profile", "=", "None", ",", "*", "*", "connection_args", ")", ":", "kstone", "=", "auth", "(", "profile", ",", "*", "*", "connection_args", ")", "ret", "=", "{", "}", "...
28.961538
20.423077
def blast(args): """ %prog blast <deltafile|coordsfile> Covert delta or coordsfile to BLAST tabular output. """ p = OptionParser(blast.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) deltafile, = args blastfile = deltafile.rsplit("....
[ "def", "blast", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "blast", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "1", ":", "sys", ".", "exit", "(", "not...
24.85
14.85
def factory(cfg, src_db, dest_db): """ Instantiate Transformation :param cfg: transformation configuration "class": "na3x.transformation.transformer.Col2XTransformation", <Transformation class> "cfg": { "src.db.load": { "src": "sprint.backlog_links" <Collection(s) to be loaded>...
[ "def", "factory", "(", "cfg", ",", "src_db", ",", "dest_db", ")", ":", "return", "obj_for_name", "(", "cfg", "[", "Transformation", ".", "__CFG_KEY_TRANSFORMATION_CLASS", "]", ")", "(", "cfg", "[", "Transformation", ".", "CFG_KEY_TRANSFORMATION_CFG", "]", ",", ...
39
23.8
def add_job(self, job, merged=False, widened=False): """ Appended a new job to this JobInfo node. :param job: The new job to append. :param bool merged: Whether it is a merged job or not. :param bool widened: Whether it is a widened job or not. """ job_type = '' ...
[ "def", "add_job", "(", "self", ",", "job", ",", "merged", "=", "False", ",", "widened", "=", "False", ")", ":", "job_type", "=", "''", "if", "merged", ":", "job_type", "=", "'merged'", "elif", "widened", ":", "job_type", "=", "'widened'", "self", ".", ...
32.428571
13.285714
def set_process(self, process = None): """ Manually set the parent process. Use with care! @type process: L{Process} @param process: (Optional) Process object. Use C{None} for no process. """ if process is None: self.__process = None else: ...
[ "def", "set_process", "(", "self", ",", "process", "=", "None", ")", ":", "if", "process", "is", "None", ":", "self", ".", "__process", "=", "None", "else", ":", "global", "Process", "# delayed import", "if", "Process", "is", "None", ":", "from", "winapp...
37.5
13.166667
def get(self, requestId): """ Gets details of a device management request. It accepts requestId (string) as parameters In case of failure it throws APIException """ url = MgmtRequests.mgmtSingleRequest % (requestId) r = self._apiClient.get(url) if r.statu...
[ "def", "get", "(", "self", ",", "requestId", ")", ":", "url", "=", "MgmtRequests", ".", "mgmtSingleRequest", "%", "(", "requestId", ")", "r", "=", "self", ".", "_apiClient", ".", "get", "(", "url", ")", "if", "r", ".", "status_code", "==", "200", ":"...
30.615385
12.615385
def delete_password(self, service, username): """Delete the password for the username of the service. """ try: key_name = self._key_for_service(service) hkey = winreg.OpenKey( winreg.HKEY_CURRENT_USER, key_name, 0, winreg.KEY_ALL_ACCESS) ...
[ "def", "delete_password", "(", "self", ",", "service", ",", "username", ")", ":", "try", ":", "key_name", "=", "self", ".", "_key_for_service", "(", "service", ")", "hkey", "=", "winreg", ".", "OpenKey", "(", "winreg", ".", "HKEY_CURRENT_USER", ",", "key_n...
38
7.285714
def composite_multiscale_entropy(time_series, sample_length, scale, tolerance=None): """Calculate the Composite Multiscale Entropy of the given time series. Args: time_series: Time series for analysis sample_length: Number of sequential points of the time series scale: Scale factor ...
[ "def", "composite_multiscale_entropy", "(", "time_series", ",", "sample_length", ",", "scale", ",", "tolerance", "=", "None", ")", ":", "cmse", "=", "np", ".", "zeros", "(", "(", "1", ",", "scale", ")", ")", "for", "i", "in", "range", "(", "scale", ")"...
36.652174
24.391304
def _init_code(self, code: int) -> None: """ Initialize from an int terminal code. """ if -1 < code < 256: self.code = '{:02}'.format(code) self.hexval = term2hex(code) self.rgb = hex2rgb(self.hexval) else: raise ValueError(' '.join(( ...
[ "def", "_init_code", "(", "self", ",", "code", ":", "int", ")", "->", "None", ":", "if", "-", "1", "<", "code", "<", "256", ":", "self", ".", "code", "=", "'{:02}'", ".", "format", "(", "code", ")", "self", ".", "hexval", "=", "term2hex", "(", ...
42.454545
10.545455
def statistics(self): """ Access the statistics :returns: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsList :rtype: twilio.rest.taskrouter.v1.workspace.worker.worker_statistics.WorkerStatisticsList """ if self._statistics is None: ...
[ "def", "statistics", "(", "self", ")", ":", "if", "self", ".", "_statistics", "is", "None", ":", "self", ".", "_statistics", "=", "WorkerStatisticsList", "(", "self", ".", "_version", ",", "workspace_sid", "=", "self", ".", "_solution", "[", "'workspace_sid'...
38.642857
19.928571
def get_extended_metadata_text(self, item_id, metadata_type): """Get extended metadata text for a media item. Args: item_id (str): The item for which metadata is required metadata_type (str): The type of text to return, eg ``'ARTIST_BIO'``, or ``'ALBUM_NOTES'``. Call...
[ "def", "get_extended_metadata_text", "(", "self", ",", "item_id", ",", "metadata_type", ")", ":", "response", "=", "self", ".", "soap_client", ".", "call", "(", "'getExtendedMetadataText'", ",", "[", "(", "'id'", ",", "item_id", ")", ",", "(", "'type'", ",",...
41.714286
21.047619
def spkobj(spk, outCell=None): """ Find the set of ID codes of all objects in a specified SPK file. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkobj_c.html :param spk: Name of SPK file. :type spk: str :param outCell: Optional Spice Int Cell. :type outCell: spiceypy.utils.supp...
[ "def", "spkobj", "(", "spk", ",", "outCell", "=", "None", ")", ":", "spk", "=", "stypes", ".", "stringToCharP", "(", "spk", ")", "if", "not", "outCell", ":", "outCell", "=", "stypes", ".", "SPICEINT_CELL", "(", "1000", ")", "assert", "isinstance", "(",...
32.166667
15.611111
def _upload_in_splits( self, destination_folder_id, source_path, preflight_check, verbose = True, chunked_upload_threads = 5 ): ''' Since Box has a maximum file size limit (15 GB at time of writing), we need to split files larger than this into smaller parts, and chunk upload each part '...
[ "def", "_upload_in_splits", "(", "self", ",", "destination_folder_id", ",", "source_path", ",", "preflight_check", ",", "verbose", "=", "True", ",", "chunked_upload_threads", "=", "5", ")", ":", "file_size", "=", "os", ".", "stat", "(", "source_path", ")", "."...
53.625
29.775
def delete_all(config=None): """ Deletes all hosts from ssh config. """ storm_ = get_storm_instance(config) try: storm_.delete_all_entries() print(get_formatted_message('all entries deleted.', 'success')) except Exception as error: print(get_formatted_message(str(error),...
[ "def", "delete_all", "(", "config", "=", "None", ")", ":", "storm_", "=", "get_storm_instance", "(", "config", ")", "try", ":", "storm_", ".", "delete_all_entries", "(", ")", "print", "(", "get_formatted_message", "(", "'all entries deleted.'", ",", "'success'",...
29.666667
15.666667
def find_path(name, path=None, exact=False): """ Search for a file or directory on your local filesystem by name (file must be in a directory specified in a PATH environment variable) Args: fname (PathLike or str): file name to match. If exact is False this may be a glob pattern ...
[ "def", "find_path", "(", "name", ",", "path", "=", "None", ",", "exact", "=", "False", ")", ":", "path", "=", "os", ".", "environ", ".", "get", "(", "'PATH'", ",", "os", ".", "defpath", ")", "if", "path", "is", "None", "else", "path", "dpaths", "...
39.163265
22.183673
def repeat(sequence): ''' Return a driver function that can advance a repeated of values. .. code-block:: none seq = [0, 1, 2, 3] # repeat(seq) => [0, 1, 2, 3, 0, 1, 2, 3, 0, 1, ...] Args: sequence (seq) : a sequence of values for the driver to bounce ''' N = len(sequenc...
[ "def", "repeat", "(", "sequence", ")", ":", "N", "=", "len", "(", "sequence", ")", "def", "f", "(", "i", ")", ":", "return", "sequence", "[", "i", "%", "N", "]", "return", "partial", "(", "force", ",", "sequence", "=", "_advance", "(", "f", ")", ...
23.352941
27
def print_summary(self, stream=sys.stdout, indent="", recurse_level=2): """Print a summary of the activity done by this `Link`. Parameters ---------- stream : `file` Stream to print to indent : str Indentation at start of line recurse_level : i...
[ "def", "print_summary", "(", "self", ",", "stream", "=", "sys", ".", "stdout", ",", "indent", "=", "\"\"", ",", "recurse_level", "=", "2", ")", ":", "Link", ".", "print_summary", "(", "self", ",", "stream", ",", "indent", ",", "recurse_level", ")", "if...
29.571429
19.285714
def list_platforms(server_url): ''' To list all ASAM platforms present on the Novell Fan-Out Driver CLI Example: .. code-block:: bash salt-run asam.list_platforms prov1.domain.com ''' config = _get_asam_configuration(server_url) if not config: return False url = confi...
[ "def", "list_platforms", "(", "server_url", ")", ":", "config", "=", "_get_asam_configuration", "(", "server_url", ")", "if", "not", "config", ":", "return", "False", "url", "=", "config", "[", "'platform_config_url'", "]", "data", "=", "{", "'manual'", ":", ...
23.282051
23.435897
def _add_listeners ( self ): """ Adds the event listeners for a specified object. """ object = self.value canvas = self.factory.canvas if canvas is not None: for name in canvas.node_children: object.on_trait_change(self._nodes_replaced, name) ...
[ "def", "_add_listeners", "(", "self", ")", ":", "object", "=", "self", ".", "value", "canvas", "=", "self", ".", "factory", ".", "canvas", "if", "canvas", "is", "not", "None", ":", "for", "name", "in", "canvas", ".", "node_children", ":", "object", "."...
43.266667
18
def timedelta2millisecond(td): """Get milliseconds from a timedelta.""" milliseconds = td.days * 24 * 60 * 60 * 1000 milliseconds += td.seconds * 1000 milliseconds += td.microseconds / 1000 return milliseconds
[ "def", "timedelta2millisecond", "(", "td", ")", ":", "milliseconds", "=", "td", ".", "days", "*", "24", "*", "60", "*", "60", "*", "1000", "milliseconds", "+=", "td", ".", "seconds", "*", "1000", "milliseconds", "+=", "td", ".", "microseconds", "/", "1...
37.333333
6.666667
def _pull_status(data, item): ''' Process a status update from a docker pull, updating the data structure. For containers created with older versions of Docker, there is no distinction in the status updates between layers that were already present (and thus not necessary to download), and those whi...
[ "def", "_pull_status", "(", "data", ",", "item", ")", ":", "def", "_already_exists", "(", "id_", ")", ":", "'''\n Layer already exists\n '''", "already_pulled", "=", "data", ".", "setdefault", "(", "'Layers'", ",", "{", "}", ")", ".", "setdefault",...
39.275862
20.896552
def make_auto_deployable(self, stage, swagger=None): """ Sets up the resource such that it will triggers a re-deployment when Swagger changes :param swagger: Dictionary containing the Swagger definition of the API """ if not swagger: return # CloudFormation ...
[ "def", "make_auto_deployable", "(", "self", ",", "stage", ",", "swagger", "=", "None", ")", ":", "if", "not", "swagger", ":", "return", "# CloudFormation does NOT redeploy the API unless it has a new deployment resource", "# that points to latest RestApi resource. Append a hash o...
52.4
31.2
def time_termination(population, num_generations, num_evaluations, args): """Return True if the elapsed time meets or exceeds a duration of time. This function compares the elapsed time with a specified maximum. It returns True if the maximum is met or exceeded. If the `start_time` keyword argumen...
[ "def", "time_termination", "(", "population", ",", "num_generations", ",", "num_evaluations", ",", "args", ")", ":", "start_time", "=", "args", ".", "setdefault", "(", "'start_time'", ",", "None", ")", "max_time", "=", "args", ".", "setdefault", "(", "'max_tim...
46.369565
24.326087
def preprovision_rbridge_id_rbridge_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") preprovision = ET.SubElement(config, "preprovision", xmlns="urn:brocade.com:mgmt:brocade-preprovision") rbridge_id = ET.SubElement(preprovision, "rbridge-id") ...
[ "def", "preprovision_rbridge_id_rbridge_id", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "preprovision", "=", "ET", ".", "SubElement", "(", "config", ",", "\"preprovision\"", ",", "xmlns", "=",...
45.692308
16.692308
def wash_for_js(text): """ DEPRECATED: use htmlutils.escape_javascript_string() instead, and take note that returned value is no longer enclosed into quotes. """ from invenio_utils.html import escape_javascript_string if isinstance(text, six.string_types): return '"%s"' % escape_java...
[ "def", "wash_for_js", "(", "text", ")", ":", "from", "invenio_utils", ".", "html", "import", "escape_javascript_string", "if", "isinstance", "(", "text", ",", "six", ".", "string_types", ")", ":", "return", "'\"%s\"'", "%", "escape_javascript_string", "(", "text...
32.133333
14.8
def set_settings(self, releases=None, default_release=None): """set path to storage""" super(ShardedClusters, self).set_settings(releases, default_release) ReplicaSets().set_settings(releases, default_release)
[ "def", "set_settings", "(", "self", ",", "releases", "=", "None", ",", "default_release", "=", "None", ")", ":", "super", "(", "ShardedClusters", ",", "self", ")", ".", "set_settings", "(", "releases", ",", "default_release", ")", "ReplicaSets", "(", ")", ...
57.5
19.25
def _linux_nqn(): ''' Return NVMe NQN from a Linux host. ''' ret = [] initiator = '/etc/nvme/hostnqn' try: with salt.utils.files.fopen(initiator, 'r') as _nvme: for line in _nvme: line = line.strip() if line.startswith('nqn.'): ...
[ "def", "_linux_nqn", "(", ")", ":", "ret", "=", "[", "]", "initiator", "=", "'/etc/nvme/hostnqn'", "try", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "initiator", ",", "'r'", ")", "as", "_nvme", ":", "for", "line", "in", "_nvm...
26.333333
19.666667
def message(subject, message, access_token, all_members=False, project_member_ids=None, base_url=OH_BASE_URL): """ Send an email to individual users or in bulk. To learn more about Open Humans OAuth2 projects, go to: https://www.openhumans.org/direct-sharing/oauth2-features/ :param subj...
[ "def", "message", "(", "subject", ",", "message", ",", "access_token", ",", "all_members", "=", "False", ",", "project_member_ids", "=", "None", ",", "base_url", "=", "OH_BASE_URL", ")", ":", "url", "=", "urlparse", ".", "urljoin", "(", "base_url", ",", "'...
48.147059
20.852941
def default(self, obj): """This is slightly different than json.JSONEncoder.default(obj) in that it should returned the serialized representation of the passed object, not a serializable representation. """ if isinstance(obj, (datetime.date, datetime.time, datetime.datetime)): ...
[ "def", "default", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "(", "datetime", ".", "date", ",", "datetime", ".", "time", ",", "datetime", ".", "datetime", ")", ")", ":", "return", "'\"%s\"'", "%", "obj", ".", "isoformat",...
49.25
14.333333
def is_valid(self): # type: () -> Union[bool, None] """Determine if the value in the property is valid. If the value of the property is validated as 'valid', than returns a True, otherwise a False. When no validators are configured, returns a None. It checks against all configured valid...
[ "def", "is_valid", "(", "self", ")", ":", "# type: () -> Union[bool, None]", "if", "not", "hasattr", "(", "self", ",", "'_validators'", ")", ":", "return", "None", "else", ":", "self", ".", "validate", "(", "reason", "=", "False", ")", "if", "all", "(", ...
39
20.052632
def _find_zero(cpu, constrs, ptr): """ Helper for finding the closest NULL or, effectively NULL byte from a starting address. :param Cpu cpu: :param ConstraintSet constrs: Constraints for current `State` :param int ptr: Address to start searching for a zero from :return: Offset from `ptr` to fi...
[ "def", "_find_zero", "(", "cpu", ",", "constrs", ",", "ptr", ")", ":", "offset", "=", "0", "while", "True", ":", "byt", "=", "cpu", ".", "read_int", "(", "ptr", "+", "offset", ",", "8", ")", "if", "issymbolic", "(", "byt", ")", ":", "if", "not", ...
26.916667
24.333333
def AgregarUbicacionTambo(self, latitud, longitud, domicilio, cod_localidad, cod_provincia, codigo_postal, nombre_partido_depto, **kwargs): "Agrego los datos del productor a la liq." ubic_tambo = {'latitud': latitud, 'lon...
[ "def", "AgregarUbicacionTambo", "(", "self", ",", "latitud", ",", "longitud", ",", "domicilio", ",", "cod_localidad", ",", "cod_provincia", ",", "codigo_postal", ",", "nombre_partido_depto", ",", "*", "*", "kwargs", ")", ":", "ubic_tambo", "=", "{", "'latitud'",...
52.230769
15.461538
def clear_port_stats(self): """ Clear only port stats (leave stream and packet group stats). Do not use - still working with Ixia to resolve. """ stat = IxeStat(self) stat.ix_set_default() stat.enableValidStats = True stat.ix_set() stat.write()
[ "def", "clear_port_stats", "(", "self", ")", ":", "stat", "=", "IxeStat", "(", "self", ")", "stat", ".", "ix_set_default", "(", ")", "stat", ".", "enableValidStats", "=", "True", "stat", ".", "ix_set", "(", ")", "stat", ".", "write", "(", ")" ]
30
13.5
def to_dict(obj): """ Convert an instance of an object into a dict. """ d = _to_json_type(obj) if isinstance(d, dict): return scrub_dict(d) else: raise ValueError("The value provided must be an object.")
[ "def", "to_dict", "(", "obj", ")", ":", "d", "=", "_to_json_type", "(", "obj", ")", "if", "isinstance", "(", "d", ",", "dict", ")", ":", "return", "scrub_dict", "(", "d", ")", "else", ":", "raise", "ValueError", "(", "\"The value provided must be an object...
29
14.75