text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def create_kernel_spec(self, is_cython=False, is_pylab=False, is_sympy=False): """Create a kernel spec for our own kernels""" # Before creating our kernel spec, we always need to # set this value in spyder.ini CONF.set('main', 'spyder_pythonpath', ...
[ "def", "create_kernel_spec", "(", "self", ",", "is_cython", "=", "False", ",", "is_pylab", "=", "False", ",", "is_sympy", "=", "False", ")", ":", "# Before creating our kernel spec, we always need to\r", "# set this value in spyder.ini\r", "CONF", ".", "set", "(", "'m...
51.3
10
def pairwise_cos_distance(A, B): """Pairwise cosine distance between two matrices. :param A: a matrix. :param B: a matrix. :returns: A tensor for the pairwise cosine between A and B. """ normalized_A = tf.nn.l2_normalize(A, dim=1) normalized_B = tf.nn.l2_normalize(B, dim=1) prod = tf.ma...
[ "def", "pairwise_cos_distance", "(", "A", ",", "B", ")", ":", "normalized_A", "=", "tf", ".", "nn", ".", "l2_normalize", "(", "A", ",", "dim", "=", "1", ")", "normalized_B", "=", "tf", ".", "nn", ".", "l2_normalize", "(", "B", ",", "dim", "=", "1",...
34.363636
14.909091
def editprojecthook(self, project_id, hook_id, url, push=False, issues=False, merge_requests=False, tag_push=False): """ edit an existing hook from a project :param id_: project id :param hook_id: hook id :param url: the new url :return: True if success """ ...
[ "def", "editprojecthook", "(", "self", ",", "project_id", ",", "hook_id", ",", "url", ",", "push", "=", "False", ",", "issues", "=", "False", ",", "merge_requests", "=", "False", ",", "tag_push", "=", "False", ")", ":", "data", "=", "{", "\"id\"", ":",...
34.518519
20.296296
def get_language(self, language_id): """ Retrieves information about the language of the given id. :param language_id: The TheTVDB Id of the language. :return: a python dictionary with either the result of the search or an error from TheTVDB. """ raw_response = requests...
[ "def", "get_language", "(", "self", ",", "language_id", ")", ":", "raw_response", "=", "requests_util", ".", "run_request", "(", "'get'", ",", "self", ".", "API_BASE_URL", "+", "'/languages/%d'", "%", "language_id", ",", "headers", "=", "self", ".", "__get_hea...
43.833333
29.333333
def selectlanguage(self, event): """Store client's selection of a new translation""" self.log('Language selection event:', event.client, pretty=True) if event.data not in all_languages(): self.log('Unavailable language selected:', event.data, lvl=warn) language = None ...
[ "def", "selectlanguage", "(", "self", ",", "event", ")", ":", "self", ".", "log", "(", "'Language selection event:'", ",", "event", ".", "client", ",", "pretty", "=", "True", ")", "if", "event", ".", "data", "not", "in", "all_languages", "(", ")", ":", ...
30.736842
19.421053
def _handle_template(self, token): """Handle a case where a template is at the head of the tokens.""" params = [] default = 1 self._push() while self._tokens: token = self._tokens.pop() if isinstance(token, tokens.TemplateParamSeparator): i...
[ "def", "_handle_template", "(", "self", ",", "token", ")", ":", "params", "=", "[", "]", "default", "=", "1", "self", ".", "_push", "(", ")", "while", "self", ".", "_tokens", ":", "token", "=", "self", ".", "_tokens", ".", "pop", "(", ")", "if", ...
39.619048
11.809524
def types(self): """ Tuple containing types transformed by this transformer. """ out = [] if self._transform_bytes: out.append(bytes) if self._transform_str: out.append(str) return tuple(out)
[ "def", "types", "(", "self", ")", ":", "out", "=", "[", "]", "if", "self", ".", "_transform_bytes", ":", "out", ".", "append", "(", "bytes", ")", "if", "self", ".", "_transform_str", ":", "out", ".", "append", "(", "str", ")", "return", "tuple", "(...
26.2
12.6
def write_mnefiff(data, filename): """Export data to MNE using FIFF format. Parameters ---------- data : instance of ChanTime data with only one trial filename : path to file file to export to (include '.mat') Notes ----- It cannot store data larger than 2 GB. The d...
[ "def", "write_mnefiff", "(", "data", ",", "filename", ")", ":", "from", "mne", "import", "create_info", ",", "set_log_level", "from", "mne", ".", "io", "import", "RawArray", "set_log_level", "(", "WARNING", ")", "TRIAL", "=", "0", "info", "=", "create_info",...
28.121212
19.181818
def colored(msg, color=None, background=None, style=None, force=False): """ Return the colored version of a string *msg*. For *color*, *background* and *style* options, see https://misc.flogisoft.com/bash/tip_colors_and_formatting. Unless *force* is *True*, the *msg* string is returned unchanged in case...
[ "def", "colored", "(", "msg", ",", "color", "=", "None", ",", "background", "=", "None", ",", "style", "=", "None", ",", "force", "=", "False", ")", ":", "try", ":", "if", "not", "force", "and", "not", "os", ".", "isatty", "(", "sys", ".", "stdou...
40.2
27.2
def main(): """ The "main" entry that controls the flow of the script based on the provided arguments. """ setup_logging(logging.INFO) # Parse arguments parser = argparse.ArgumentParser( description="A utility to interact with AWS using Cloudera Manager.") parser.add_argument('-H', '--hostname', ac...
[ "def", "main", "(", ")", ":", "setup_logging", "(", "logging", ".", "INFO", ")", "# Parse arguments", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "\"A utility to interact with AWS using Cloudera Manager.\"", ")", "parser", ".", "add_argu...
45.608108
20.851351
def save(self): """ Creates this index in the collection if it hasn't been already created """ api = Client.instance().api index_details = { 'type': self.index_type_obj.type_name } extra_index_attributes = self.index_type_obj.get_extra_attribute...
[ "def", "save", "(", "self", ")", ":", "api", "=", "Client", ".", "instance", "(", ")", ".", "api", "index_details", "=", "{", "'type'", ":", "self", ".", "index_type_obj", ".", "type_name", "}", "extra_index_attributes", "=", "self", ".", "index_type_obj",...
31.2
25.44
def _label_setter(self, new_label, current_label, attr_label, default=np.NaN, use_names_default=False): """Generalized setter of default meta attributes Parameters ---------- new_label : str New label to use in the Meta object current_label : str ...
[ "def", "_label_setter", "(", "self", ",", "new_label", ",", "current_label", ",", "attr_label", ",", "default", "=", "np", ".", "NaN", ",", "use_names_default", "=", "False", ")", ":", "if", "new_label", "not", "in", "self", ".", "attrs", "(", ")", ":", ...
41.586207
19.189655
def path(self, root_dir): """Manually establishes the build root for the current workspace.""" path = os.path.realpath(root_dir) if not os.path.exists(path): raise ValueError('Build root does not exist: {}'.format(root_dir)) self._root_dir = path
[ "def", "path", "(", "self", ",", "root_dir", ")", ":", "path", "=", "os", ".", "path", ".", "realpath", "(", "root_dir", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "ValueError", "(", "'Build root does not exist:...
43.833333
12.166667
async def client_event_handler(self, client_id, event_tuple, user_data): """Method called to actually send an event to a client. Users of this class should override this method to actually forward device events to their clients. It is called with the client_id passed to (or returned fr...
[ "async", "def", "client_event_handler", "(", "self", ",", "client_id", ",", "event_tuple", ",", "user_data", ")", ":", "conn_string", ",", "event_name", ",", "_event", "=", "event_tuple", "self", ".", "_logger", ".", "debug", "(", "\"Ignoring event %s from device ...
39.233333
26.1
def sync(self, command, arguments, tags=None, id=None): """ Same as self.raw except it do a response.get() waiting for the command execution to finish and reads the result :param command: Command name to execute supported by the node (ex: core.system, info.cpu, etc...) ch...
[ "def", "sync", "(", "self", ",", "command", ",", "arguments", ",", "tags", "=", "None", ",", "id", "=", "None", ")", ":", "response", "=", "self", ".", "raw", "(", "command", ",", "arguments", ",", "tags", "=", "tags", ",", "id", "=", "id", ")", ...
44.5
26.833333
def search_dimensions(self, *args, **kwargs): """ Args: query (string): elasticsearch string query order_by (optional[string]): property by which to order results offset (optional[int]): number of results to skip for pagination (default=0) ...
[ "def", "search_dimensions", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_search_metrics_and_metadata", "(", "self", ".", "_DIMENSION_ENDPOINT_SUFFIX", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
42.6
20.333333
def graph(self): """ Returns MultiDiGraph from kihs. Nodes are helices and edges are kihs. """ g = networkx.MultiDiGraph() edge_list = [(x.knob_helix, x.hole_helix, x.id, {'kih': x}) for x in self.get_monomers()] g.add_edges_from(edge_list) return g
[ "def", "graph", "(", "self", ")", ":", "g", "=", "networkx", ".", "MultiDiGraph", "(", ")", "edge_list", "=", "[", "(", "x", ".", "knob_helix", ",", "x", ".", "hole_helix", ",", "x", ".", "id", ",", "{", "'kih'", ":", "x", "}", ")", "for", "x",...
47.333333
19.166667
def dnd_endDnd(self, **kwargs) -> SlackResponse: """Ends the current user's Do Not Disturb session immediately.""" self._validate_xoxp_token() return self.api_call("dnd.endDnd", json=kwargs)
[ "def", "dnd_endDnd", "(", "self", ",", "*", "*", "kwargs", ")", "->", "SlackResponse", ":", "self", ".", "_validate_xoxp_token", "(", ")", "return", "self", ".", "api_call", "(", "\"dnd.endDnd\"", ",", "json", "=", "kwargs", ")" ]
52.75
7
def _delete(self, pos, idx): """Delete the item at the given (pos, idx). Combines lists that are less than half the load level. Updates the index when the sublist length is more than half the load level. This requires decrementing the nodes in a traversal from the leaf node to ...
[ "def", "_delete", "(", "self", ",", "pos", ",", "idx", ")", ":", "_maxes", ",", "_lists", ",", "_index", "=", "self", ".", "_maxes", ",", "self", ".", "_lists", ",", "self", ".", "_index", "lists_pos", "=", "_lists", "[", "pos", "]", "del", "lists_...
24.54717
21.377358
def get_agent_pools(self, pool_name=None, properties=None, pool_type=None, action_filter=None): """GetAgentPools. [Preview API] Get a list of agent pools. :param str pool_name: Filter by name :param [str] properties: Filter by agent pool properties (comma-separated) :param str po...
[ "def", "get_agent_pools", "(", "self", ",", "pool_name", "=", "None", ",", "properties", "=", "None", ",", "pool_type", "=", "None", ",", "action_filter", "=", "None", ")", ":", "query_parameters", "=", "{", "}", "if", "pool_name", "is", "not", "None", "...
59.291667
24.708333
def from_payload(self, payload): """Init frame from binary data.""" self.session_id = payload[0]*256 + payload[1] self.status = CommandSendConfirmationStatus(payload[2])
[ "def", "from_payload", "(", "self", ",", "payload", ")", ":", "self", ".", "session_id", "=", "payload", "[", "0", "]", "*", "256", "+", "payload", "[", "1", "]", "self", ".", "status", "=", "CommandSendConfirmationStatus", "(", "payload", "[", "2", "]...
47.5
11
def on_failure(self, exc, task_id, args, kwargs, einfo): """ If the task fails, persist a record of the task. """ if not FailedTask.objects.filter(task_id=task_id, datetime_resolved=None).exists(): FailedTask.objects.create( task_name=_truncate_to_field(Failed...
[ "def", "on_failure", "(", "self", ",", "exc", ",", "task_id", ",", "args", ",", "kwargs", ",", "einfo", ")", ":", "if", "not", "FailedTask", ".", "objects", ".", "filter", "(", "task_id", "=", "task_id", ",", "datetime_resolved", "=", "None", ")", ".",...
49.461538
22.076923
def tan_rand(q, seed=9): """Find a random vector in the tangent space of the n sphere This function will find a random orthogonal vector to q. Parameters ---------- q (n+1,) array which is in the n-sphere Returns ------- qd (n+1,) array which is orthogonal to n-sphere ...
[ "def", "tan_rand", "(", "q", ",", "seed", "=", "9", ")", ":", "# probably need a check in case we get a parallel vector", "rs", "=", "np", ".", "random", ".", "RandomState", "(", "seed", ")", "rvec", "=", "rs", ".", "rand", "(", "q", ".", "shape", "[", "...
22.655172
22.068966
def step(self, y, u, t, h): """ This is called by solve, but can be called by the user who wants to run through an integration with a control force. y - state at t u - control inputs at t t - time h - step size """ k1 = h * self.func(t, y, u) k2 = h * self.func(t + .5*h, y + .5*h*k1, u) k3 = h * ...
[ "def", "step", "(", "self", ",", "y", ",", "u", ",", "t", ",", "h", ")", ":", "k1", "=", "h", "*", "self", ".", "func", "(", "t", ",", "y", ",", "u", ")", "k2", "=", "h", "*", "self", ".", "func", "(", "t", "+", ".5", "*", "h", ",", ...
28.333333
14.066667
def delete_files(): """ Delete one or more files from the server """ session_token = request.headers['session_token'] repository = request.headers['repository'] #=== current_user = have_authenticated_user(request.environ['REMOTE_ADDR'], repository, session_token) if current_user is False: r...
[ "def", "delete_files", "(", ")", ":", "session_token", "=", "request", ".", "headers", "[", "'session_token'", "]", "repository", "=", "request", ".", "headers", "[", "'repository'", "]", "#===", "current_user", "=", "have_authenticated_user", "(", "request", "....
36.866667
25.466667
def lon180to360(lon): """Convert longitude from (-180, 180) to (0, 360) """ if np.any(lon > 180.0) or np.any(lon < -180.0): print("Warning: lon outside expected range") lon = lon360to180(lon) #lon[lon < 0.0] += 360.0 lon = (lon + 360.0) % 360.0 return lon
[ "def", "lon180to360", "(", "lon", ")", ":", "if", "np", ".", "any", "(", "lon", ">", "180.0", ")", "or", "np", ".", "any", "(", "lon", "<", "-", "180.0", ")", ":", "print", "(", "\"Warning: lon outside expected range\"", ")", "lon", "=", "lon360to180",...
31.888889
11
def check(self, instance): """ Process both the istio_mesh instance and process_mixer instance associated with this instance """ # Get the config for the istio_mesh instance istio_mesh_endpoint = instance.get('istio_mesh_endpoint') istio_mesh_config = self.config_map[ist...
[ "def", "check", "(", "self", ",", "instance", ")", ":", "# Get the config for the istio_mesh instance", "istio_mesh_endpoint", "=", "instance", ".", "get", "(", "'istio_mesh_endpoint'", ")", "istio_mesh_config", "=", "self", ".", "config_map", "[", "istio_mesh_endpoint"...
36.555556
21.555556
def route(self, method, pattern): """Decorator to add route for a request with any HTTP method. Arguments: method (str): HTTP method name, e.g. GET, POST, etc. pattern (str): Routing pattern the path must match. Returns: function: Decorator function to add route. ...
[ "def", "route", "(", "self", ",", "method", ",", "pattern", ")", ":", "def", "decorator", "(", "callback", ")", ":", "self", ".", "_router", ".", "add", "(", "method", ",", "pattern", ",", "callback", ")", "return", "callback", "return", "decorator" ]
32.857143
17.142857
def create_closure_model(cls): """Creates a <Model>Closure model in the same module as the model.""" meta_vals = { 'unique_together': (("parent", "child"),) } if getattr(cls._meta, 'db_table', None): meta_vals['db_table'] = '%sclosure' % getattr(cls._meta, 'db_table') model = type('...
[ "def", "create_closure_model", "(", "cls", ")", ":", "meta_vals", "=", "{", "'unique_together'", ":", "(", "(", "\"parent\"", ",", "\"child\"", ")", ",", ")", "}", "if", "getattr", "(", "cls", ".", "_meta", ",", "'db_table'", ",", "None", ")", ":", "me...
36.173913
14.478261
def inv_diagonal(S): """ Computes the inverse of a diagonal NxN np.array S. In general this will be much faster than calling np.linalg.inv(). However, does NOT check if the off diagonal elements are non-zero. So long as S is truly diagonal, the output is identical to np.linalg.inv(). Parameter...
[ "def", "inv_diagonal", "(", "S", ")", ":", "S", "=", "np", ".", "asarray", "(", "S", ")", "if", "S", ".", "ndim", "!=", "2", "or", "S", ".", "shape", "[", "0", "]", "!=", "S", ".", "shape", "[", "1", "]", ":", "raise", "ValueError", "(", "'...
25.512821
24.74359
def center(self): ''' Point whose coordinates are (midX,midY,origin.z), Point. ''' return Point(self.midX, self.midY, self.origin.z)
[ "def", "center", "(", "self", ")", ":", "return", "Point", "(", "self", ".", "midX", ",", "self", ".", "midY", ",", "self", ".", "origin", ".", "z", ")" ]
32
24.4
def AgregarTributo(self, codigo_tributo, descripcion, base_imponible, alicuota, importe): "Agrega la información referente a las retenciones de la liquidación" trib = dict(codigoTributo=codigo_tributo, descripcion=descripcion, baseImponible=base_imponible, alicuota=alicuota, importe=importe) sel...
[ "def", "AgregarTributo", "(", "self", ",", "codigo_tributo", ",", "descripcion", ",", "base_imponible", ",", "alicuota", ",", "importe", ")", ":", "trib", "=", "dict", "(", "codigoTributo", "=", "codigo_tributo", ",", "descripcion", "=", "descripcion", ",", "b...
74.2
42.6
def generate_seviri_file(seviri, platform_name): """Generate the pyspectral internal common format relative response function file for one SEVIRI """ import h5py filename = os.path.join(seviri.output_dir, "rsr_seviri_{0}.h5".format(platform_name)) sat_name = platfor...
[ "def", "generate_seviri_file", "(", "seviri", ",", "platform_name", ")", ":", "import", "h5py", "filename", "=", "os", ".", "path", ".", "join", "(", "seviri", ".", "output_dir", ",", "\"rsr_seviri_{0}.h5\"", ".", "format", "(", "platform_name", ")", ")", "s...
38.263158
17.631579
async def deserialize(data: dict): """ :param data: Data provided by the serialize method Example: msg_id = '1' phone_number = '8019119191' connection = await Connection.create(source_id) await connection.connect(phone_number) disclosed_proof = await Discl...
[ "async", "def", "deserialize", "(", "data", ":", "dict", ")", ":", "disclosed_proof", "=", "await", "DisclosedProof", ".", "_deserialize", "(", "\"vcx_disclosed_proof_deserialize\"", ",", "json", ".", "dumps", "(", "data", ")", ",", "data", ".", "get", "(", ...
47.588235
19.588235
def replace_tax_class_by_id(cls, tax_class_id, tax_class, **kwargs): """Replace TaxClass Replace all attributes of TaxClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.replace_tax_class_by...
[ "def", "replace_tax_class_by_id", "(", "cls", ",", "tax_class_id", ",", "tax_class", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".",...
45.727273
23.090909
def add(self, name, nestable, **kw): """ Adds a level to the nesting and creates a checkpoint that can be reverted to later for aggregation by calling :meth:`SConsWrap.pop`. :param name: Identifier for the nest level :param nestable: A nestable object - see :meth:`Ne...
[ "def", "add", "(", "self", ",", "name", ",", "nestable", ",", "*", "*", "kw", ")", ":", "self", ".", "checkpoints", "[", "name", "]", "=", "self", ".", "nest", "self", ".", "nest", "=", "copy", ".", "copy", "(", "self", ".", "nest", ")", "retur...
42.428571
12.857143
def with_connection(func): """Decorate a function to open a new datafind connection if required This method will inspect the ``connection`` keyword, and if `None` (or missing), will use the ``host`` and ``port`` keywords to open a new connection and pass it as ``connection=<new>`` to ``func``. """ ...
[ "def", "with_connection", "(", "func", ")", ":", "@", "wraps", "(", "func", ")", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "kwargs", ".", "get", "(", "'connection'", ")", "is", "None", ":", "kwargs", "[", "'connec...
42.611111
18.888889
def _place_tables_section(skeleton_section, sheet, keys_section): """ Place data into skeleton for either a paleo or chron section. :param dict skeleton_section: Empty or current progress of skeleton w/ data :param dict sheet: Sheet metadata :param list keys_section: Paleo or Chron specific keys ...
[ "def", "_place_tables_section", "(", "skeleton_section", ",", "sheet", ",", "keys_section", ")", ":", "logger_excel", ".", "info", "(", "\"enter place_tables_section\"", ")", "try", ":", "logger_excel", ".", "info", "(", "\"excel: place_tables_section: placing table: {}\"...
46.58
17.9
def class_args(cls): """ Decorates a class to handle the arguments parser. """ # get the Singleton ap_ = ArgParseInator(skip_init=True) # collect special vars (really need?) utils.collect_appendvars(ap_, cls) # set class reference cls.__cls__ = cls cmds = {} # get eventual cl...
[ "def", "class_args", "(", "cls", ")", ":", "# get the Singleton", "ap_", "=", "ArgParseInator", "(", "skip_init", "=", "True", ")", "# collect special vars (really need?)", "utils", ".", "collect_appendvars", "(", "ap_", ",", "cls", ")", "# set class reference", "cl...
37.594595
12.027027
def handle_route_spec_request(): """ Process request for route spec. Either a new one is posted or the current one is to be retrieved. """ try: if bottle.request.method == 'GET': # Just return what we currenty have cached as the route spec data = CURRENT_STATE.route...
[ "def", "handle_route_spec_request", "(", ")", ":", "try", ":", "if", "bottle", ".", "request", ".", "method", "==", "'GET'", ":", "# Just return what we currenty have cached as the route spec", "data", "=", "CURRENT_STATE", ".", "route_spec", "if", "not", "data", ":...
32.325
15.725
def cpustats(): ''' Return the CPU stats for this minion .. versionchanged:: 2016.11.4 Added support for AIX .. versionchanged:: 2018.3.0 Added support for OpenBSD CLI Example: .. code-block:: bash salt '*' status.cpustats ''' def linux_cpustats(): ''...
[ "def", "cpustats", "(", ")", ":", "def", "linux_cpustats", "(", ")", ":", "'''\n linux specific implementation of cpustats\n '''", "ret", "=", "{", "}", "try", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "'/proc/stat'", ",",...
32.739726
19.506849
def register(self, event, callable, priority=10): """Register interest in an event. event: name of the event (str) callable: the callable to be used as a callback function Returns an EventReceiver object. To unregister interest, simply delete the object.""" ...
[ "def", "register", "(", "self", ",", "event", ",", "callable", ",", "priority", "=", "10", ")", ":", "logger", ".", "debug", "(", "'registered: '", "+", "event", "+", "': '", "+", "repr", "(", "callable", ")", "+", "' ['", "+", "repr", "(", "self", ...
60.625
21.5
def console_getfd(self, ttynum=-1): """ Attach to console of running container. """ if not self.running: return False return _lxc.Container.console_getfd(self, ttynum)
[ "def", "console_getfd", "(", "self", ",", "ttynum", "=", "-", "1", ")", ":", "if", "not", "self", ".", "running", ":", "return", "False", "return", "_lxc", ".", "Container", ".", "console_getfd", "(", "self", ",", "ttynum", ")" ]
24.111111
15.666667
def _parseExceptionDirectory(self, rva, size, magic = consts.PE32): """ Parses the C{IMAGE_EXCEPTION_DIRECTORY} directory. @type rva: int @param rva: The RVA where the C{IMAGE_EXCEPTION_DIRECTORY} starts. @type size: int @param size: The size of the C{I...
[ "def", "_parseExceptionDirectory", "(", "self", ",", "rva", ",", "size", ",", "magic", "=", "consts", ".", "PE32", ")", ":", "return", "self", ".", "getDataAtRva", "(", "rva", ",", "size", ")" ]
36.352941
23.176471
def create_tag(self, tag_name=None, **properties): """Creates a tag and adds it to the tag table of the TextBuffer. :param str tag_name: Name of the new tag, or None :param **properties: Keyword list of properties and their values :returns: A new tag....
[ "def", "create_tag", "(", "self", ",", "tag_name", "=", "None", ",", "*", "*", "properties", ")", ":", "tag", "=", "Gtk", ".", "TextTag", "(", "name", "=", "tag_name", ",", "*", "*", "properties", ")", "self", ".", "_get_or_create_tag_table", "(", ")",...
35.538462
21.269231
def starts_within(self, start=None, end=None): """ :return: normal occurrences that start within the given start and end datetimes, inclusive, and drop-in occurrences that """ qs = self if start: dt_start=coerce_dt_awareness(start) qs = qs.filt...
[ "def", "starts_within", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "qs", "=", "self", "if", "start", ":", "dt_start", "=", "coerce_dt_awareness", "(", "start", ")", "qs", "=", "qs", ".", "filter", "(", "Q", "(", "is_...
33.26087
21.347826
def generate_search_space(code_dir): """Generate search space from Python source code. Return a serializable search space object. code_dir: directory path of source files (str) """ search_space = {} if code_dir.endswith(slash): code_dir = code_dir[:-1] for subdir, _, files in o...
[ "def", "generate_search_space", "(", "code_dir", ")", ":", "search_space", "=", "{", "}", "if", "code_dir", ".", "endswith", "(", "slash", ")", ":", "code_dir", "=", "code_dir", "[", ":", "-", "1", "]", "for", "subdir", ",", "_", ",", "files", "in", ...
33.884615
15.730769
def FileHacks(self): """Hacks to make the filesystem look normal.""" if sys.platform == "win32": import win32api # pylint: disable=g-import-not-at-top # Make the filesystem look like the topmost level are the drive letters. if self.path == "/": self.files = win32api.GetLogicalDriveSt...
[ "def", "FileHacks", "(", "self", ")", ":", "if", "sys", ".", "platform", "==", "\"win32\"", ":", "import", "win32api", "# pylint: disable=g-import-not-at-top", "# Make the filesystem look like the topmost level are the drive letters.", "if", "self", ".", "path", "==", "\"...
49.4
24
def _serve_individual_image(self, request): """Serves an individual image.""" run = request.args.get('run') tag = request.args.get('tag') index = int(request.args.get('index')) sample = int(request.args.get('sample', 0)) data = self._get_individual_image(run, tag, index, sample) image_type =...
[ "def", "_serve_individual_image", "(", "self", ",", "request", ")", ":", "run", "=", "request", ".", "args", ".", "get", "(", "'run'", ")", "tag", "=", "request", ".", "args", ".", "get", "(", "'tag'", ")", "index", "=", "int", "(", "request", ".", ...
47.3
10.4
def get_graph(graph=None, *, _limit=(), _print=()): """ Extracts a list of cafes with on euro in Paris, renames the name, address and zipcode fields, reorders the fields and formats to json and csv files. """ graph = graph or bonobo.Graph() producer = ( graph.get_cursor() >> OD...
[ "def", "get_graph", "(", "graph", "=", "None", ",", "*", ",", "_limit", "=", "(", ")", ",", "_print", "=", "(", ")", ")", ":", "graph", "=", "graph", "or", "bonobo", ".", "Graph", "(", ")", "producer", "=", "(", "graph", ".", "get_cursor", "(", ...
36.741935
27.774194
def _log_vector_matrix(vs, ms): """Multiply tensor of vectors by matrices assuming values stored are logs.""" return tf.reduce_logsumexp(input_tensor=vs[..., tf.newaxis] + ms, axis=-2)
[ "def", "_log_vector_matrix", "(", "vs", ",", "ms", ")", ":", "return", "tf", ".", "reduce_logsumexp", "(", "input_tensor", "=", "vs", "[", "...", ",", "tf", ".", "newaxis", "]", "+", "ms", ",", "axis", "=", "-", "2", ")" ]
46.5
21.25
def resources(ctx, gpu): """Get build job resources. Uses [Caching](/references/polyaxon-cli/#caching) Examples: \b ```bash $ polyaxon build -b 2 resources ``` For GPU resources \b ```bash $ polyaxon build -b 2 resources --gpu ``` """ user, project_name, _bui...
[ "def", "resources", "(", "ctx", ",", "gpu", ")", ":", "user", ",", "project_name", ",", "_build", "=", "get_build_or_local", "(", "ctx", ".", "obj", ".", "get", "(", "'project'", ")", ",", "ctx", ".", "obj", ".", "get", "(", "'build'", ")", ")", "t...
31.533333
27.066667
def find_replace(obj, find, replace): """ Searches an object and performs a find and replace. Args: obj (object): The object to iterate and find/replace. find (str): The string to search for. replace (str): The string to replace with. Returns: object: The object with replace...
[ "def", "find_replace", "(", "obj", ",", "find", ",", "replace", ")", ":", "try", ":", "if", "isinstance", "(", "obj", ",", "dict", ")", ":", "return", "{", "find_replace", "(", "key", ",", "find", ",", "replace", ")", ":", "find_replace", "(", "value...
35.805556
17.138889
def conformPadding(cls, chars): """ Ensure alternate input padding formats are conformed to formats defined in PAD_MAP If chars is already a format defined in PAD_MAP, then it is returned unmodified. Example:: '#' -> '#' '@@@@' -> '@@@@' ...
[ "def", "conformPadding", "(", "cls", ",", "chars", ")", ":", "pad", "=", "chars", "if", "pad", "and", "pad", "[", "0", "]", "not", "in", "PAD_MAP", ":", "pad", "=", "cls", ".", "getPaddingChars", "(", "cls", ".", "getPaddingNum", "(", "pad", ")", "...
25.961538
19.115385
def connect(self): """ Creates the connection with the redis server. Return ``True`` if the connection works, else returns ``False``. It does not take any arguments. :return: ``Boolean`` value .. note:: After creating the ``Queue`` object the user should cal...
[ "def", "connect", "(", "self", ")", ":", "config", "=", "self", ".", "config", "self", ".", "rdb", "=", "redis", ".", "Redis", "(", "config", "[", "'host'", "]", ",", "config", "[", "'port'", "]", ",", "config", "[", "'db'", "]", ",", "config", "...
26.645161
20.258065
def _set_exit_timeout(self, timeout, reason): """Set a timeout for the remainder of the session, along with an exception to raise. which is implemented by NailgunProtocol. This method may be called by a signal handler to set a timeout for the remainder of the session. If the session completes before th...
[ "def", "_set_exit_timeout", "(", "self", ",", "timeout", ",", "reason", ")", ":", "self", ".", "_exit_timeout_start_time", "=", "time", ".", "time", "(", ")", "self", ".", "_exit_timeout", "=", "timeout", "self", ".", "_exit_reason", "=", "reason" ]
49.8
22.4
def _set_interface_type(self, v, load=False): """ Setter method for interface_type, mapped from YANG variable /brocade_interface_ext_rpc/get_interface_detail/input/interface_type (enumeration) If this variable is read-only (config: false) in the source YANG file, then _set_interface_type is considered a...
[ "def", "_set_interface_type", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", ...
115.4
57.04
def _heuristic_bin_width(obs): """Optimal histogram bin width based on the Freedman-Diaconis rule""" IQR = sp.percentile(obs, 75) - sp.percentile(obs, 25) N = len(obs) return 2*IQR*N**(-1/3)
[ "def", "_heuristic_bin_width", "(", "obs", ")", ":", "IQR", "=", "sp", ".", "percentile", "(", "obs", ",", "75", ")", "-", "sp", ".", "percentile", "(", "obs", ",", "25", ")", "N", "=", "len", "(", "obs", ")", "return", "2", "*", "IQR", "*", "N...
40.4
13
def _index(*args, **kwargs): """Implementation of list searching. :param of: Element to search for :param where: Predicate to search for :param in_: List to search in :param start: Start index for the lookup :param step: Counter step (i.e. in/decrement) for each iteration :return: Pair of ...
[ "def", "_index", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "start", "=", "kwargs", ".", "pop", "(", "'start'", ",", "0", ")", "step", "=", "kwargs", ".", "pop", "(", "'step'", ",", "1", ")", "if", "len", "(", "args", ")", "==", "2"...
31.934783
17.391304
def to_xml(self): """ Serialize all properties as XML """ ret = '<exif>' for k in self.__dict__: ret += '<%s>%s</%s>' % (k, self.__dict__[k], k) ret += '</exif>' return ret
[ "def", "to_xml", "(", "self", ")", ":", "ret", "=", "'<exif>'", "for", "k", "in", "self", ".", "__dict__", ":", "ret", "+=", "'<%s>%s</%s>'", "%", "(", "k", ",", "self", ".", "__dict__", "[", "k", "]", ",", "k", ")", "ret", "+=", "'</exif>'", "re...
25.777778
12
def send(self, target, topic, content): """ Fires a message """ event = threading.Event() results = [] def got_message(sender, content): results.append(content) event.set() self.post(target, topic, content, got_message) event.wait...
[ "def", "send", "(", "self", ",", "target", ",", "topic", ",", "content", ")", ":", "event", "=", "threading", ".", "Event", "(", ")", "results", "=", "[", "]", "def", "got_message", "(", "sender", ",", "content", ")", ":", "results", ".", "append", ...
22.133333
16
def delete_all_volumes(self): """Remove all the volumes. Only the manager nodes can delete a volume """ # Raise an exception if we are not a manager if not self._manager: raise RuntimeError('Volumes can only be deleted ' 'on swarm manag...
[ "def", "delete_all_volumes", "(", "self", ")", ":", "# Raise an exception if we are not a manager", "if", "not", "self", ".", "_manager", ":", "raise", "RuntimeError", "(", "'Volumes can only be deleted '", "'on swarm manager nodes'", ")", "volume_list", "=", "self", ".",...
35.785714
14
def kwargs_helper(kwargs): """This function preprocesses the kwargs dictionary to sanitize it.""" args = [] for param, value in kwargs.items(): param = kw_subst.get(param, param) args.append((param, value)) return args
[ "def", "kwargs_helper", "(", "kwargs", ")", ":", "args", "=", "[", "]", "for", "param", ",", "value", "in", "kwargs", ".", "items", "(", ")", ":", "param", "=", "kw_subst", ".", "get", "(", "param", ",", "param", ")", "args", ".", "append", "(", ...
30.5
14.25
def processors(self, processor_name=None): """Return a list of Processor objects. :param project_id: ObjectId of Genesis project :type project_id: string :rtype: list of Processor objects """ if processor_name: return self.api.processor.get(name=processor_na...
[ "def", "processors", "(", "self", ",", "processor_name", "=", "None", ")", ":", "if", "processor_name", ":", "return", "self", ".", "api", ".", "processor", ".", "get", "(", "name", "=", "processor_name", ")", "[", "'objects'", "]", "else", ":", "return"...
32.666667
16.083333
def sync_agg_metric(self, unique_identifier, metric, start_date, end_date): """ Uses the count for each day in the date range to recalculate the counters for the associated weeks and months for the ``metric`` for ``unique_identifier``. Useful for updating the counters for week and month after us...
[ "def", "sync_agg_metric", "(", "self", ",", "unique_identifier", ",", "metric", ",", "start_date", ",", "end_date", ")", ":", "self", ".", "sync_week_metric", "(", "unique_identifier", ",", "metric", ",", "start_date", ",", "end_date", ")", "self", ".", "sync_...
64.733333
39.266667
def categorical__int(self, column_name, output_column_prefix): """ Interprets an integer column as a categorical variable. """ return [_ColumnFunctionTransformation( features = [column_name], output_column_prefix = output_column_prefix, transform_func...
[ "def", "categorical__int", "(", "self", ",", "column_name", ",", "output_column_prefix", ")", ":", "return", "[", "_ColumnFunctionTransformation", "(", "features", "=", "[", "column_name", "]", ",", "output_column_prefix", "=", "output_column_prefix", ",", "transform_...
40
14.4
def stop(self): '''Stop the rpc server.''' if self.uiautomator_process and self.uiautomator_process.poll() is None: res = None try: res = urllib2.urlopen(self.stop_uri) self.uiautomator_process.wait() except: self.uiauto...
[ "def", "stop", "(", "self", ")", ":", "if", "self", ".", "uiautomator_process", "and", "self", ".", "uiautomator_process", ".", "poll", "(", ")", "is", "None", ":", "res", "=", "None", "try", ":", "res", "=", "urllib2", ".", "urlopen", "(", "self", "...
39.545455
20.454545
def compute_center( feed: "Feed", num_busiest_stops: Optional[int] = None ) -> Tuple: """ Return the centroid (WGS84 longitude-latitude pair) of the convex hull of the stops of the given Feed. If ``num_busiest_stops`` (integer) is given, then compute the ``num_busiest_stops`` busiest stops in th...
[ "def", "compute_center", "(", "feed", ":", "\"Feed\"", ",", "num_busiest_stops", ":", "Optional", "[", "int", "]", "=", "None", ")", "->", "Tuple", ":", "s", "=", "feed", ".", "stops", ".", "copy", "(", ")", "if", "num_busiest_stops", "is", "None", ":"...
35.545455
13.909091
def query(*args, **kwargs): ''' Query the node for specific information. Parameters: * **scope**: Specify scope of the query. * **System**: Return system data. * **Software**: Return software information. * **Services**: Return known services. * **Identity**: Return use...
[ "def", "query", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "query", "=", "_", "(", "\"query\"", ")", "try", ":", "return", "query", ".", "Query", "(", "kwargs", ".", "get", "(", "'scope'", ")", ",", "cachedir", "=", "__opts__", "[", "'c...
30.793651
25.904762
def maybe_convert_to_index_date_type(index, date): """Convert a datetime-like object to the index's date type. Datetime indexing in xarray can be done using either a pandas DatetimeIndex or a CFTimeIndex. Both support partial-datetime string indexing regardless of the calendar type of the underlying d...
[ "def", "maybe_convert_to_index_date_type", "(", "index", ",", "date", ")", ":", "if", "isinstance", "(", "date", ",", "str", ")", ":", "return", "date", "if", "isinstance", "(", "index", ",", "pd", ".", "DatetimeIndex", ")", ":", "if", "isinstance", "(", ...
36.148936
21.510638
def get_keywords(lexer): """Get the keywords for a given lexer. """ if not hasattr(lexer, 'tokens'): return [] if 'keywords' in lexer.tokens: try: return lexer.tokens['keywords'][0][0].words except: pass keywords = [] for vals in lexer.tokens.value...
[ "def", "get_keywords", "(", "lexer", ")", ":", "if", "not", "hasattr", "(", "lexer", ",", "'tokens'", ")", ":", "return", "[", "]", "if", "'keywords'", "in", "lexer", ".", "tokens", ":", "try", ":", "return", "lexer", ".", "tokens", "[", "'keywords'", ...
33.464286
14.071429
def set_code_exprs(self, codes): """Convenience: sets all the code expressions at once.""" self.code_objs = dict() self._codes = [] for code in codes: self.append_code_expr(code)
[ "def", "set_code_exprs", "(", "self", ",", "codes", ")", ":", "self", ".", "code_objs", "=", "dict", "(", ")", "self", ".", "_codes", "=", "[", "]", "for", "code", "in", "codes", ":", "self", ".", "append_code_expr", "(", "code", ")" ]
36.166667
8
def data_mod(self, *args, **kwargs): """ Register a function to modify data of member Instruments. The function is not partially applied to modify member data. When the Constellation receives a function call to register a function for data modification, it passes the call to ea...
[ "def", "data_mod", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "for", "instrument", "in", "self", ".", "instruments", ":", "instrument", ".", "custom", ".", "add", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
35.265306
23.877551
def run(self): '''Run until there are no events to be processed.''' # We left-append rather than emit (right-append) because some message # may have been already queued for execution before the director runs. global_event_queue.appendleft((INITIATE, self, (), {})) while global_ev...
[ "def", "run", "(", "self", ")", ":", "# We left-append rather than emit (right-append) because some message", "# may have been already queued for execution before the director runs.", "global_event_queue", ".", "appendleft", "(", "(", "INITIATE", ",", "self", ",", "(", ")", ","...
55
24.428571
def generate_from_yaml(pseudo_ast, language): ''' generate output code in `language` converts yaml input to a Node-based pseudo internal tree and passes it to `generate ''' return pseudo.generate(pseudo.loader.as_tree(pseudo_ast), language)
[ "def", "generate_from_yaml", "(", "pseudo_ast", ",", "language", ")", ":", "return", "pseudo", ".", "generate", "(", "pseudo", ".", "loader", ".", "as_tree", "(", "pseudo_ast", ")", ",", "language", ")" ]
28.666667
24.666667
def logical_chassis_fwdl_sanity_input_host(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") logical_chassis_fwdl_sanity = ET.Element("logical_chassis_fwdl_sanity") config = logical_chassis_fwdl_sanity input = ET.SubElement(logical_chassis_fwdl_san...
[ "def", "logical_chassis_fwdl_sanity_input_host", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "logical_chassis_fwdl_sanity", "=", "ET", ".", "Element", "(", "\"logical_chassis_fwdl_sanity\"", ")", "co...
41.333333
13.583333
def _fetch_dataframe(self): """Return a pandas dataframe with all the training jobs, along with their hyperparameters, results, and metadata. This also includes a column to indicate if a training job was the best seen so far. """ def reshape(training_summary): # Helpe...
[ "def", "_fetch_dataframe", "(", "self", ")", ":", "def", "reshape", "(", "training_summary", ")", ":", "# Helper method to reshape a single training job summary into a dataframe record", "out", "=", "{", "}", "for", "k", ",", "v", "in", "training_summary", "[", "'Tune...
52.566667
23.833333
def ConsultarCTGExcel(self, numero_carta_de_porte=None, numero_ctg=None, patente=None, cuit_solicitante=None, cuit_destino=None, fecha_emision_desde=None, fecha_emision_hasta=None, archivo="planilla.xls"): "Operación que realiza consulta de CTGs, g...
[ "def", "ConsultarCTGExcel", "(", "self", ",", "numero_carta_de_porte", "=", "None", ",", "numero_ctg", "=", "None", ",", "patente", "=", "None", ",", "cuit_solicitante", "=", "None", ",", "cuit_destino", "=", "None", ",", "fecha_emision_desde", "=", "None", ",...
50.875
17.958333
def _send_to_address(self, address, data, timeout=10): """send data to *address* and *port* without verification of response. """ # Socket to talk to server socket = get_context().socket(REQ) try: socket.setsockopt(LINGER, timeout * 1000) if address.find("...
[ "def", "_send_to_address", "(", "self", ",", "address", ",", "data", ",", "timeout", "=", "10", ")", ":", "# Socket to talk to server", "socket", "=", "get_context", "(", ")", ".", "socket", "(", "REQ", ")", "try", ":", "socket", ".", "setsockopt", "(", ...
38.444444
14.5
def login(self, **params): """ **login** Use the current credentials to get a valid Gett access token. Input: * A dict of parameters to use for the login attempt (optional) Output: * ``True`` Example:: if client.user.login(): ...
[ "def", "login", "(", "self", ",", "*", "*", "params", ")", ":", "if", "not", "params", ":", "params", "=", "{", "\"apikey\"", ":", "self", ".", "apikey", ",", "\"email\"", ":", "self", ".", "email", ",", "\"password\"", ":", "self", ".", "password", ...
33
25.972973
def accounts(self): """Ask the bank for the known :py:class:`ofxclient.Account` list. :rtype: list of :py:class:`ofxclient.Account` objects """ from ofxclient.account import Account client = self.client() query = client.account_list_query() resp = client.post(que...
[ "def", "accounts", "(", "self", ")", ":", "from", "ofxclient", ".", "account", "import", "Account", "client", "=", "self", ".", "client", "(", ")", "query", "=", "client", ".", "account_list_query", "(", ")", "resp", "=", "client", ".", "post", "(", "q...
33.833333
16.5
def get(self, k): """Returns key contents, and modify time""" if self._changed(): self._read() if k in self.store: return tuple(self.store[k]) else: return None
[ "def", "get", "(", "self", ",", "k", ")", ":", "if", "self", ".", "_changed", "(", ")", ":", "self", ".", "_read", "(", ")", "if", "k", "in", "self", ".", "store", ":", "return", "tuple", "(", "self", ".", "store", "[", "k", "]", ")", "else",...
24.555556
16.666667
def load_cufflinks(self, filter_ok=True): """ Load a Cufflinks gene expression data for a cohort Parameters ---------- filter_ok : bool, optional If true, filter Cufflinks data to row with FPKM_status == "OK" Returns ------- cufflinks_data : ...
[ "def", "load_cufflinks", "(", "self", ",", "filter_ok", "=", "True", ")", ":", "return", "pd", ".", "concat", "(", "[", "self", ".", "_load_single_patient_cufflinks", "(", "patient", ",", "filter_ok", ")", "for", "patient", "in", "self", "]", ",", "copy", ...
33.3
22.9
def polygons_full(self): """ A list of shapely.geometry.Polygon objects with interiors created by checking which closed polygons enclose which other polygons. Returns --------- full : (len(self.root),) shapely.geometry.Polygon Polygons containing interiors ...
[ "def", "polygons_full", "(", "self", ")", ":", "# pre- allocate the list to avoid indexing problems", "full", "=", "[", "None", "]", "*", "len", "(", "self", ".", "root", ")", "# store the graph to avoid cache thrashing", "enclosure", "=", "self", ".", "enclosure_dire...
39.628571
14.657143
def _get_site(self, url, headers, cookies, timeout, driver_args, driver_kwargs): """ Try and return page content in the requested format using selenium """ try: # **TODO**: Find what exception this will throw and catch it and call # self.driver.execute_script("w...
[ "def", "_get_site", "(", "self", ",", "url", ",", "headers", ",", "cookies", ",", "timeout", ",", "driver_args", ",", "driver_kwargs", ")", ":", "try", ":", "# **TODO**: Find what exception this will throw and catch it and call", "# self.driver.execute_script(\"window.sto...
41.025641
21.282051
def remove_post_process(self, name): """remove a post-process Parameters ---------- name : str name of the post-process to remove. """ self._pprocesses = [post_process for post_process in self._pprocesses ...
[ "def", "remove_post_process", "(", "self", ",", "name", ")", ":", "self", ".", "_pprocesses", "=", "[", "post_process", "for", "post_process", "in", "self", ".", "_pprocesses", "if", "post_process", ".", "name", "!=", "name", "]" ]
31
14.363636
def _global_step(hparams): """Adjust global step if a multi-step optimizer is used.""" step = tf.to_float(tf.train.get_or_create_global_step()) multiplier = hparams.optimizer_multistep_accumulate_steps if not multiplier: return step tf.logging.info("Dividing global step by %d for multi-step optimizer." ...
[ "def", "_global_step", "(", "hparams", ")", ":", "step", "=", "tf", ".", "to_float", "(", "tf", ".", "train", ".", "get_or_create_global_step", "(", ")", ")", "multiplier", "=", "hparams", ".", "optimizer_multistep_accumulate_steps", "if", "not", "multiplier", ...
38.1
17.8
def parse_header(data, verbose=False, *args, **kwargs): """Parse the data using the grammar specified in this module :param str data: delimited data to be parsed for metadata :return list parsed_data: structured metadata """ # the parser if verbose: print >> sys.stderr, "Creating p...
[ "def", "parse_header", "(", "data", ",", "verbose", "=", "False", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# the parser", "if", "verbose", ":", "print", ">>", "sys", ".", "stderr", ",", "\"Creating parser object...\"", "parser", "=", "Parser",...
33.666667
22.296296
def _active_mounts(ret): ''' List active mounts on Linux systems ''' _list = _list_mounts() filename = '/proc/self/mounts' if not os.access(filename, os.R_OK): msg = 'File not readable {0}' raise CommandExecutionError(msg.format(filename)) with salt.utils.files.fopen(filenam...
[ "def", "_active_mounts", "(", "ret", ")", ":", "_list", "=", "_list_mounts", "(", ")", "filename", "=", "'/proc/self/mounts'", "if", "not", "os", ".", "access", "(", "filename", ",", "os", ".", "R_OK", ")", ":", "msg", "=", "'File not readable {0}'", "rais...
37.666667
18.333333
def list(self, request): """Search the doctypes for this model.""" query = get_query_params(request).get("search", "") results = [] base = self.model.get_base_class() doctypes = indexable_registry.families[base] for doctype, klass in doctypes.items(): name = k...
[ "def", "list", "(", "self", ",", "request", ")", ":", "query", "=", "get_query_params", "(", "request", ")", ".", "get", "(", "\"search\"", ",", "\"\"", ")", "results", "=", "[", "]", "base", "=", "self", ".", "model", ".", "get_base_class", "(", ")"...
40.466667
10.133333
def data(self, root): '''Convert etree.Element into a dictionary''' value = self.dict() children = [node for node in root if isinstance(node.tag, basestring)] for attr, attrval in root.attrib.items(): attr = attr if self.attr_prefix is None else self.attr_prefix + attr ...
[ "def", "data", "(", "self", ",", "root", ")", ":", "value", "=", "self", ".", "dict", "(", ")", "children", "=", "[", "node", "for", "node", "in", "root", "if", "isinstance", "(", "node", ".", "tag", ",", "basestring", ")", "]", "for", "attr", ",...
48.28
18.6
async def get_random(self) -> Word: """Gets a random word. Returns: A random :class:`Word`\. Raises: UrbanConnectionError: If the response status isn't ``200``. """ resp = await self._get(random=True) return Word(resp['list'][0])
[ "async", "def", "get_random", "(", "self", ")", "->", "Word", ":", "resp", "=", "await", "self", ".", "_get", "(", "random", "=", "True", ")", "return", "Word", "(", "resp", "[", "'list'", "]", "[", "0", "]", ")" ]
28.090909
14.545455
def cherry_pick(self, branch, **kwargs): """Cherry-pick a commit into a branch. Args: branch (str): Name of target branch **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct ...
[ "def", "cherry_pick", "(", "self", ",", "branch", ",", "*", "*", "kwargs", ")", ":", "path", "=", "'%s/%s/cherry_pick'", "%", "(", "self", ".", "manager", ".", "path", ",", "self", ".", "get_id", "(", ")", ")", "post_data", "=", "{", "'branch'", ":",...
40.785714
21.571429
def show_plot(t_array, th_array): """ Display theta vs t plot. """ th_mean = gv.mean(th_array) th_sdev = gv.sdev(th_array) thp = th_mean + th_sdev thm = th_mean - th_sdev plt.fill_between(t_array, thp, thm, color='0.8') plt.plot(t_array, th_mean, linewidth=0.5) plt.xlabel('$t$') plt....
[ "def", "show_plot", "(", "t_array", ",", "th_array", ")", ":", "th_mean", "=", "gv", ".", "mean", "(", "th_array", ")", "th_sdev", "=", "gv", ".", "sdev", "(", "th_array", ")", "thp", "=", "th_mean", "+", "th_sdev", "thm", "=", "th_mean", "-", "th_sd...
33.25
11.25
def set_iter_mesh(self, mesh, shift=None, is_time_reversal=True, is_mesh_symmetry=True, is_eigenvectors=False, is_gamma_center=False): """Create an IterMesh instancer Attr...
[ "def", "set_iter_mesh", "(", "self", ",", "mesh", ",", "shift", "=", "None", ",", "is_time_reversal", "=", "True", ",", "is_mesh_symmetry", "=", "True", ",", "is_eigenvectors", "=", "False", ",", "is_gamma_center", "=", "False", ")", ":", "warnings", ".", ...
33.653846
15.346154
def get_wiki(self, section): """ Returns a section of the wiki. Only for Album/Track. section can be "content", "summary" or "published" (for published date) """ doc = self._request(self.ws_prefix + ".getInfo", True) if len(doc.getElementsByTagName("...
[ "def", "get_wiki", "(", "self", ",", "section", ")", ":", "doc", "=", "self", ".", "_request", "(", "self", ".", "ws_prefix", "+", "\".getInfo\"", ",", "True", ")", "if", "len", "(", "doc", ".", "getElementsByTagName", "(", "\"wiki\"", ")", ")", "==", ...
26.8125
16.5625
def ask_float(msg="Enter a float", dft=None, vld=None, hlp=None): """Prompts the user for a float.""" vld = vld or [float] return ask(msg, dft=dft, vld=vld, fmt=partial(cast, typ=float), hlp=hlp)
[ "def", "ask_float", "(", "msg", "=", "\"Enter a float\"", ",", "dft", "=", "None", ",", "vld", "=", "None", ",", "hlp", "=", "None", ")", ":", "vld", "=", "vld", "or", "[", "float", "]", "return", "ask", "(", "msg", ",", "dft", "=", "dft", ",", ...
51
19.25
def update_case_task(self, task): """ :Updates TheHive Task :param case: The task to update. The task's `id` determines which Task to update. :return: """ req = self.url + "/api/case/task/{}".format(task.id) # Choose which attributes to send update_keys =...
[ "def", "update_case_task", "(", "self", ",", "task", ")", ":", "req", "=", "self", ".", "url", "+", "\"/api/case/task/{}\"", ".", "format", "(", "task", ".", "id", ")", "# Choose which attributes to send", "update_keys", "=", "[", "'title'", ",", "'description...
40.7
27.4
def begin(self): """Initialize communication with the PN532. Must be called before any other calls are made against the PN532. """ # Assert CS pin low for a second for PN532 to be ready. self._gpio.set_low(self._cs) time.sleep(1.0) # Call GetFirmwareVersion to sy...
[ "def", "begin", "(", "self", ")", ":", "# Assert CS pin low for a second for PN532 to be ready.", "self", ".", "_gpio", ".", "set_low", "(", "self", ".", "_cs", ")", "time", ".", "sleep", "(", "1.0", ")", "# Call GetFirmwareVersion to sync up with the PN532. This might...
45.818182
14.636364
def ParseArguments(self): """Parses the command line arguments. Returns: bool: True if the arguments were successfully parsed. """ loggers.ConfigureLogging() argument_parser = argparse.ArgumentParser( description=self.DESCRIPTION, epilog=self.EPILOG, add_help=False, formatter...
[ "def", "ParseArguments", "(", "self", ")", ":", "loggers", ".", "ConfigureLogging", "(", ")", "argument_parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "self", ".", "DESCRIPTION", ",", "epilog", "=", "self", ".", "EPILOG", ",", "add...
38.392857
24.178571