text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def register_relax_task(self, *args, **kwargs): """Register a task for structural optimization.""" kwargs["task_class"] = RelaxTask return self.register_task(*args, **kwargs)
[ "def", "register_relax_task", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "\"task_class\"", "]", "=", "RelaxTask", "return", "self", ".", "register_task", "(", "*", "args", ",", "*", "*", "kwargs", ")" ]
48.75
4.25
def remove_file(filename, recursive=False, force=False): """Removes a file or directory.""" import os try: mode = os.stat(filename)[0] if mode & 0x4000 != 0: # directory if recursive: for file in os.listdir(filename): success = remo...
[ "def", "remove_file", "(", "filename", ",", "recursive", "=", "False", ",", "force", "=", "False", ")", ":", "import", "os", "try", ":", "mode", "=", "os", ".", "stat", "(", "filename", ")", "[", "0", "]", "if", "mode", "&", "0x4000", "!=", "0", ...
32.318182
17.590909
def set_nodes(self, nlabels = [], coords = [], nsets = {}, **kwargs): r""" Sets the node data. :arg nlabels: node labels. Items be strictly positive and int typed in 1D array-like with shape :math:`(N_n)`. :type nlabels: 1D uint typed array-like :arg coords: node coordinates....
[ "def", "set_nodes", "(", "self", ",", "nlabels", "=", "[", "]", ",", "coords", "=", "[", "]", ",", "nsets", "=", "{", "}", ",", "*", "*", "kwargs", ")", ":", "# DATA PREPROCESSING", "nlabels", "=", "np", ".", "array", "(", "nlabels", ")", ".", "a...
43.333333
15.555556
def segment_lengths(neurites, neurite_type=NeuriteType.all): '''Lengths of the segments in a collection of neurites''' def _seg_len(sec): '''list of segment lengths of a section''' return np.linalg.norm(np.diff(sec.points[:, COLS.XYZ], axis=0), axis=1) return map_segments(_seg_len, neurites...
[ "def", "segment_lengths", "(", "neurites", ",", "neurite_type", "=", "NeuriteType", ".", "all", ")", ":", "def", "_seg_len", "(", "sec", ")", ":", "'''list of segment lengths of a section'''", "return", "np", ".", "linalg", ".", "norm", "(", "np", ".", "diff",...
47
23.571429
def create_wsgi_factory(mounts_factories): """Create a WSGI application factory. Usage example: .. code-block:: python wsgi_factory = create_wsgi_factory({'/api': create_api}) :param mounts_factories: Dictionary of mount points per application factory. .. versionadded:: 1.0.0 ...
[ "def", "create_wsgi_factory", "(", "mounts_factories", ")", ":", "def", "create_wsgi", "(", "app", ",", "*", "*", "kwargs", ")", ":", "mounts", "=", "{", "mount", ":", "factory", "(", "*", "*", "kwargs", ")", "for", "mount", ",", "factory", "in", "moun...
26
21.142857
def getVulkanInstanceExtensionsRequired(self, pchValue, unBufferSize): """ [Vulkan Only] return 0. Otherwise it returns the length of the number of bytes necessary to hold this string including the trailing null. The string will be a space separated list of-required instance extensions ...
[ "def", "getVulkanInstanceExtensionsRequired", "(", "self", ",", "pchValue", ",", "unBufferSize", ")", ":", "fn", "=", "self", ".", "function_table", ".", "getVulkanInstanceExtensionsRequired", "result", "=", "fn", "(", "pchValue", ",", "unBufferSize", ")", "return",...
48.8
30.2
def members(self): """ A copy of the list of occupants. The local user is always the first item in the list, unless the :meth:`on_enter` has not fired yet. """ if self._this_occupant is not None: items = [self._this_occupant] else: items = [] ...
[ "def", "members", "(", "self", ")", ":", "if", "self", ".", "_this_occupant", "is", "not", "None", ":", "items", "=", "[", "self", ".", "_this_occupant", "]", "else", ":", "items", "=", "[", "]", "items", "+=", "list", "(", "self", ".", "_occupant_in...
31.416667
17.416667
def _precompile_substitution(self, kind, pattern): """Pre-compile the regexp for a substitution pattern. This will speed up the substitutions that happen at the beginning of the reply fetching process. With the default brain, this took the time for _substitute down from 0.08s to 0.02s ...
[ "def", "_precompile_substitution", "(", "self", ",", "kind", ",", "pattern", ")", ":", "if", "pattern", "not", "in", "self", ".", "_regexc", "[", "kind", "]", ":", "qm", "=", "re", ".", "escape", "(", "pattern", ")", "self", ".", "_regexc", "[", "kin...
43.052632
16.842105
def get_cache_stats(): """ Returns a list of dictionaries of all cache servers and their stats, if they provide stats. """ cache_stats = [] for name, _ in six.iteritems(settings.CACHES): cache_backend = caches[name] try: cache_backend_stats = cache_backend._cache.get...
[ "def", "get_cache_stats", "(", ")", ":", "cache_stats", "=", "[", "]", "for", "name", ",", "_", "in", "six", ".", "iteritems", "(", "settings", ".", "CACHES", ")", ":", "cache_backend", "=", "caches", "[", "name", "]", "try", ":", "cache_backend_stats", ...
32
19.304348
def routers_updated(self, context, routers): """Deal with routers modification and creation RPC message.""" LOG.debug('Got routers updated notification :%s', routers) if routers: # This is needed for backward compatibility if isinstance(routers[0], dict): ...
[ "def", "routers_updated", "(", "self", ",", "context", ",", "routers", ")", ":", "LOG", ".", "debug", "(", "'Got routers updated notification :%s'", ",", "routers", ")", "if", "routers", ":", "# This is needed for backward compatibility", "if", "isinstance", "(", "r...
51.875
13.375
def read(self, include_deleted=False): """Return only read items in the current queryset""" if is_soft_delete() and not include_deleted: return self.filter(unread=False, deleted=False) # When SOFT_DELETE=False, developers are supposed NOT to touch 'deleted' field. # In this ...
[ "def", "read", "(", "self", ",", "include_deleted", "=", "False", ")", ":", "if", "is_soft_delete", "(", ")", "and", "not", "include_deleted", ":", "return", "self", ".", "filter", "(", "unread", "=", "False", ",", "deleted", "=", "False", ")", "# When S...
52.625
20.625
def _init_config(): """Setup configuration dictionary from default, command line and configuration file.""" cli_opts, parser = _init_command_line_options() cli_verbose = cli_opts["verbose"] # Set config defaults config = copy.deepcopy(DEFAULT_CONFIG) # Configuration file overrides defaults ...
[ "def", "_init_config", "(", ")", ":", "cli_opts", ",", "parser", "=", "_init_command_line_options", "(", ")", "cli_verbose", "=", "cli_opts", "[", "\"verbose\"", "]", "# Set config defaults", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULT_CONFIG", ")", "#...
35.333333
18.760684
def convert_to_nested_dict(dotted_dict): """Convert a dict with dotted path keys to corresponding nested dict.""" nested_dict = {} for k, v in iterate_flattened(dotted_dict): set_by_dotted_path(nested_dict, k, v) return nested_dict
[ "def", "convert_to_nested_dict", "(", "dotted_dict", ")", ":", "nested_dict", "=", "{", "}", "for", "k", ",", "v", "in", "iterate_flattened", "(", "dotted_dict", ")", ":", "set_by_dotted_path", "(", "nested_dict", ",", "k", ",", "v", ")", "return", "nested_d...
41.666667
8.333333
def __get_inferred_data_res_2(v=None, calc=True): """ Use a list of values to calculate m/m/m/m. Resolution values or otherwise. :param numpy array v: Values :param bool calc: If false, we don't need calculations :return dict: Results of calculation """ # Base: If something goes wrong, or i...
[ "def", "__get_inferred_data_res_2", "(", "v", "=", "None", ",", "calc", "=", "True", ")", ":", "# Base: If something goes wrong, or if there are no values, then use \"NaN\" placeholders.", "d", "=", "{", "\"hasMinValue\"", ":", "\"nan\"", ",", "\"hasMaxValue\"", ":", "\"n...
29.521739
16.826087
def read_json(fp, local_files, dir_files, name_bytes): """ Read json properties from the zip file :param fp: a file pointer :param local_files: the local files structure :param dir_files: the directory headers :param name: the name of the json file to read :return: t...
[ "def", "read_json", "(", "fp", ",", "local_files", ",", "dir_files", ",", "name_bytes", ")", ":", "if", "name_bytes", "in", "dir_files", ":", "json_pos", "=", "local_files", "[", "dir_files", "[", "name_bytes", "]", "[", "1", "]", "]", "[", "1", "]", "...
36.869565
15.652174
def download(self, filename=None): """ Download snapshot to filename :param str filename: fully qualified path including filename .zip :raises EngineCommandFailed: IOError occurred downloading snapshot :return: None """ if not filename: filename = '{}...
[ "def", "download", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "not", "filename", ":", "filename", "=", "'{}{}'", ".", "format", "(", "self", ".", "name", ",", "'.zip'", ")", "try", ":", "self", ".", "make_request", "(", "EngineCommandFa...
32
17
async def sleep(self, sleep_time): """ This method is a proxy method for asyncio.sleep :param sleep_time: Sleep interval in seconds :returns: No return value. """ try: await asyncio.sleep(sleep_time) except RuntimeError: if self.log_outpu...
[ "async", "def", "sleep", "(", "self", ",", "sleep_time", ")", ":", "try", ":", "await", "asyncio", ".", "sleep", "(", "sleep_time", ")", "except", "RuntimeError", ":", "if", "self", ".", "log_output", ":", "logging", ".", "info", "(", "'sleep exception'", ...
28
13
def get_attribute_names(self): """Retrieves the names of all attributes. Returns: list[str]: attribute names. """ attribute_names = [] for attribute_name in iter(self.__dict__.keys()): # Not using startswith to improve performance. if attribute_name[0] == '_': continue ...
[ "def", "get_attribute_names", "(", "self", ")", ":", "attribute_names", "=", "[", "]", "for", "attribute_name", "in", "iter", "(", "self", ".", "__dict__", ".", "keys", "(", ")", ")", ":", "# Not using startswith to improve performance.", "if", "attribute_name", ...
28.923077
13.384615
def get_instance(self, payload): """ Build an instance of WebhookInstance :param dict payload: Payload response from the API :returns: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance :rtype: twilio.rest.chat.v2.service.channel.webhook.WebhookInstance """ ...
[ "def", "get_instance", "(", "self", ",", "payload", ")", ":", "return", "WebhookInstance", "(", "self", ".", "_version", ",", "payload", ",", "service_sid", "=", "self", ".", "_solution", "[", "'service_sid'", "]", ",", "channel_sid", "=", "self", ".", "_s...
33.466667
18.933333
def setup_output_document(input_doc, tmp_input_doc, metadata_info, copy_document_catalog=True): """Create the output `PdfFileWriter` objects and copy over the relevant info.""" # NOTE: Inserting pages from a PdfFileReader into multiple PdfFileWriters # see...
[ "def", "setup_output_document", "(", "input_doc", ",", "tmp_input_doc", ",", "metadata_info", ",", "copy_document_catalog", "=", "True", ")", ":", "# NOTE: Inserting pages from a PdfFileReader into multiple PdfFileWriters", "# seems to cause problems (writer can hang on write), so only...
53.230159
27.285714
def calculate_new_length(gene_split, gene_results, hit): ''' Function for calcualting new length if the gene is split on several contigs ''' # Looping over splitted hits and calculate new length first = 1 for split in gene_split[hit['sbjct_header']]: new_start = int(gene_results[split]['sbjct_st...
[ "def", "calculate_new_length", "(", "gene_split", ",", "gene_results", ",", "hit", ")", ":", "# Looping over splitted hits and calculate new length", "first", "=", "1", "for", "split", "in", "gene_split", "[", "hit", "[", "'sbjct_header'", "]", "]", ":", "new_start"...
31.923077
20.076923
def init_logging(verbose=False, format='%(asctime)s %(message)s'): """ Common utility for setting up logging in PyCBC. Installs a signal handler such that verbosity can be activated at run-time by sending a SIGUSR1 to the process. """ def sig_handler(signum, frame): logger = logging.getLogg...
[ "def", "init_logging", "(", "verbose", "=", "False", ",", "format", "=", "'%(asctime)s %(message)s'", ")", ":", "def", "sig_handler", "(", "signum", ",", "frame", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", ")", "log_level", "=", "logger", "...
34.28
14.44
def get_swagger_view(title=None, url=None, patterns=None, urlconf=None): """ Returns schema view which renders Swagger/OpenAPI. """ class SwaggerSchemaView(APIView): _ignore_model_permissions = True exclude_from_schema = True permission_classes = [AllowAny] renderer_class...
[ "def", "get_swagger_view", "(", "title", "=", "None", ",", "url", "=", "None", ",", "patterns", "=", "None", ",", "urlconf", "=", "None", ")", ":", "class", "SwaggerSchemaView", "(", "APIView", ")", ":", "_ignore_model_permissions", "=", "True", "exclude_fro...
30.064516
14.774194
def route(rule=None, **kwargs): """ This decorator defines custom route for both class and methods in the view. It behaves the same way as Flask's @app.route on class: It takes the following args - rule: the root route of the endpoint - decorators: a list of decorators t...
[ "def", "route", "(", "rule", "=", "None", ",", "*", "*", "kwargs", ")", ":", "_restricted_keys", "=", "[", "\"extends\"", ",", "\"route\"", ",", "\"decorators\"", "]", "def", "decorator", "(", "f", ")", ":", "if", "inspect", ".", "isclass", "(", "f", ...
33.865385
21.134615
def getCursor(self): """ Get a Dictionary Cursor for executing queries """ if self.connection is None: self.Connect() return self.connection.cursor(MySQLdb.cursors.DictCursor)
[ "def", "getCursor", "(", "self", ")", ":", "if", "self", ".", "connection", "is", "None", ":", "self", ".", "Connect", "(", ")", "return", "self", ".", "connection", ".", "cursor", "(", "MySQLdb", ".", "cursors", ".", "DictCursor", ")" ]
23.125
14.625
def update_history(cloud_hero): """ Send each command to the /history endpoint. """ user_command = ' '.join(sys.argv) timestamp = int(time.time()) command = (user_command, timestamp) cloud_hero.send_history([command])
[ "def", "update_history", "(", "cloud_hero", ")", ":", "user_command", "=", "' '", ".", "join", "(", "sys", ".", "argv", ")", "timestamp", "=", "int", "(", "time", ".", "time", "(", ")", ")", "command", "=", "(", "user_command", ",", "timestamp", ")", ...
29.75
3.75
def _checkAttribs(self, strict): """Check initial attributes to make sure they are legal""" if self.min: warning("Minimum value not allowed for boolean-type parameter " + self.name, strict) self.min = None if self.max: if not self.prompt: ...
[ "def", "_checkAttribs", "(", "self", ",", "strict", ")", ":", "if", "self", ".", "min", ":", "warning", "(", "\"Minimum value not allowed for boolean-type parameter \"", "+", "self", ".", "name", ",", "strict", ")", "self", ".", "min", "=", "None", "if", "se...
44.809524
16.904762
def _show_no_gui(): """Popup with information about how to register a new GUI In the event of no GUI being registered or available, this information dialog will appear to guide the user through how to get set up with one. """ messagebox = QtWidgets.QMessageBox() messagebox.setIcon(message...
[ "def", "_show_no_gui", "(", ")", ":", "messagebox", "=", "QtWidgets", ".", "QMessageBox", "(", ")", "messagebox", ".", "setIcon", "(", "messagebox", ".", "Warning", ")", "messagebox", ".", "setWindowIcon", "(", "QtGui", ".", "QIcon", "(", "os", ".", "path"...
30.492754
20.231884
def _build(self, leaves): """Private helper function to create the next aggregation level and put all references in place. """ new, odd = [], None # check if even number of leaves, promote odd leaf to next level, if not if len(leaves) % 2 == 1: odd = leaves.pop(-1) ...
[ "def", "_build", "(", "self", ",", "leaves", ")", ":", "new", ",", "odd", "=", "[", "]", ",", "None", "# check if even number of leaves, promote odd leaf to next level, if not", "if", "len", "(", "leaves", ")", "%", "2", "==", "1", ":", "odd", "=", "leaves",...
46.25
18.1875
def returnListOfConfigurationValues(util): """ Method that recovers the configuration information about each program TODO: Grab the default file from the package data instead of storing it in the main folder. Args: ----- util: Any of the utils that are contained in the framework: domai...
[ "def", "returnListOfConfigurationValues", "(", "util", ")", ":", "VALUES", "=", "{", "}", "# If a api_keys.cfg has not been found, creating it by copying from default", "configPath", "=", "os", ".", "path", ".", "join", "(", "getConfigPath", "(", ")", "[", "\"appPath\""...
40.411111
21.633333
def dump_certificate(certificate, encoding='pem'): """ Serializes a certificate object into a byte string :param certificate: An oscrypto.asymmetric.Certificate or asn1crypto.x509.Certificate object :param encoding: A unicode string of "pem" or "der" :return: A byte string...
[ "def", "dump_certificate", "(", "certificate", ",", "encoding", "=", "'pem'", ")", ":", "if", "encoding", "not", "in", "set", "(", "[", "'pem'", ",", "'der'", "]", ")", ":", "raise", "ValueError", "(", "pretty_message", "(", "'''\n encoding must be ...
28.128205
20.282051
def read(self, entity=None, attrs=None, ignore=None, params=None): """Do not read certain fields. Do not expect the server to return the ``content_view_filter`` attribute. This has no practical impact, as the attribute must be provided when a :class:`nailgun.entities.ContentViewFilterRu...
[ "def", "read", "(", "self", ",", "entity", "=", "None", ",", "attrs", "=", "None", ",", "ignore", "=", "None", ",", "params", "=", "None", ")", ":", "if", "entity", "is", "None", ":", "entity", "=", "type", "(", "self", ")", "(", "self", ".", "...
36.935484
17.677419
def execute_sql(server_context, schema_name, sql, container_path=None, max_rows=None, sort=None, offset=None, container_filter=None, save_in_session=None, parameters=None, required_version=None, ...
[ "def", "execute_sql", "(", "server_context", ",", "schema_name", ",", "sql", ",", "container_path", "=", "None", ",", "max_rows", "=", "None", ",", "sort", "=", "None", ",", "offset", "=", "None", ",", "container_filter", "=", "None", ",", "save_in_session",...
36.912281
20.736842
def _build_search_query(self, from_date): """Build an ElasticSearch search query to retrieve items for read methods. :param from_date: date to start retrieving items from. :return: JSON query in dict format """ sort = [{self._sort_on_field: {"order": "asc"}}] filters =...
[ "def", "_build_search_query", "(", "self", ",", "from_date", ")", ":", "sort", "=", "[", "{", "self", ".", "_sort_on_field", ":", "{", "\"order\"", ":", "\"asc\"", "}", "}", "]", "filters", "=", "[", "]", "if", "self", ".", "_repo", ":", "filters", "...
26.888889
21.740741
def string_to_response(content_type): """ Wrap a view-like function that returns a string and marshalls it into an HttpResponse with the given Content-Type If the view raises an HttpBadRequestException, it will be converted into an HttpResponseBadRequest. """ def outer_wrapper(req_function):...
[ "def", "string_to_response", "(", "content_type", ")", ":", "def", "outer_wrapper", "(", "req_function", ")", ":", "@", "wraps", "(", "req_function", ")", "def", "newreq", "(", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", ...
36.814815
17.407407
def new_instance(type, frum, schema=None): """ Factory! """ if not type2container: _delayed_imports() if isinstance(frum, Container): return frum elif isinstance(frum, _Cube): return frum elif isinstance(frum, _Query): ...
[ "def", "new_instance", "(", "type", ",", "frum", ",", "schema", "=", "None", ")", ":", "if", "not", "type2container", ":", "_delayed_imports", "(", ")", "if", "isinstance", "(", "frum", ",", "Container", ")", ":", "return", "frum", "elif", "isinstance", ...
38.219512
18.073171
def get_network_params(self): """ get network params """ ip = self.__address[0] mask = b'' gate = b'' cmd_response = self.__send_command(const.CMD_OPTIONS_RRQ, b'IPAddress\x00', 1024) if cmd_response.get('status'): ip = (self.__data.split(b'=',...
[ "def", "get_network_params", "(", "self", ")", ":", "ip", "=", "self", ".", "__address", "[", "0", "]", "mask", "=", "b''", "gate", "=", "b''", "cmd_response", "=", "self", ".", "__send_command", "(", "const", ".", "CMD_OPTIONS_RRQ", ",", "b'IPAddress\\x00...
47.882353
21.294118
def scan_upto(self, regex): """ Scan up to, but not including, the given regex. >>> s = Scanner("test string") >>> s.scan('t') 't' >>> s.scan_upto(r' ') 'est' >>> s.pos 4 >>> s.pos_history [0, 1,...
[ "def", "scan_upto", "(", "self", ",", "regex", ")", ":", "pos", "=", "self", ".", "pos", "if", "self", ".", "scan_until", "(", "regex", ")", "is", "not", "None", ":", "self", ".", "pos", "-=", "len", "(", "self", ".", "matched", "(", ")", ")", ...
28.55
13.35
def store_env_override(option_strings, dest, envvar, nargs=None, default=None, type=None, choices=None, description=None, help=None, ...
[ "def", "store_env_override", "(", "option_strings", ",", "dest", ",", "envvar", ",", "nargs", "=", "None", ",", "default", "=", "None", ",", "type", "=", "None", ",", "choices", "=", "None", ",", "description", "=", "None", ",", "help", "=", "None", ",...
31.352941
18.176471
def vert_attr_2_meshes(script, source_mesh=0, target_mesh=1, geometry=False, normal=False, color=True, quality=False, selection=False, quality_distance=False, max_distance=0.5): """Vertex Attribute Transfer (between 2 meshes) ...
[ "def", "vert_attr_2_meshes", "(", "script", ",", "source_mesh", "=", "0", ",", "target_mesh", "=", "1", ",", "geometry", "=", "False", ",", "normal", "=", "False", ",", "color", "=", "True", ",", "quality", "=", "False", ",", "selection", "=", "False", ...
50.461538
28.282051
def forward(self, tokens, mask=None): """ Args: tokens (:class:`torch.FloatTensor` [batch_size, num_tokens, input_dim]): Sequence matrix to encode. mask (:class:`torch.FloatTensor`): Broadcastable matrix to `tokens` used as a mask. Returns: (:c...
[ "def", "forward", "(", "self", ",", "tokens", ",", "mask", "=", "None", ")", ":", "if", "mask", "is", "not", "None", ":", "tokens", "=", "tokens", "*", "mask", ".", "unsqueeze", "(", "-", "1", ")", ".", "float", "(", ")", "# Our input is expected to ...
51.875
29.625
def write(self, b): """ Write the given bytes (binary string) into the WebHDFS file from constructor. """ if self._closed: raise ValueError("I/O operation on closed file") if not isinstance(b, six.binary_type): raise TypeError("input must be a binary str...
[ "def", "write", "(", "self", ",", "b", ")", ":", "if", "self", ".", "_closed", ":", "raise", "ValueError", "(", "\"I/O operation on closed file\"", ")", "if", "not", "isinstance", "(", "b", ",", "six", ".", "binary_type", ")", ":", "raise", "TypeError", ...
33.56
19
def placeFavicon(context): """ Gets Favicon-URL for the Model. Template Syntax: {% placeFavicon %} """ fav = Favicon.objects.filter(isFavicon=True).first() if not fav: return mark_safe('<!-- no favicon -->') html = '' for rel in config: for size in sorted(confi...
[ "def", "placeFavicon", "(", "context", ")", ":", "fav", "=", "Favicon", ".", "objects", ".", "filter", "(", "isFavicon", "=", "True", ")", ".", "first", "(", ")", "if", "not", "fav", ":", "return", "mark_safe", "(", "'<!-- no favicon -->'", ")", "html", ...
30.833333
21.666667
def distances_from_root(self, leaves=True, internal=True, unlabeled=False): '''Generator over the root-to-node distances of this ``Tree``; (node,distance) tuples Args: ``terminal`` (``bool``): ``True`` to include leaves, otherwise ``False`` ``internal`` (``bool``): ``True`` to ...
[ "def", "distances_from_root", "(", "self", ",", "leaves", "=", "True", ",", "internal", "=", "True", ",", "unlabeled", "=", "False", ")", ":", "if", "not", "isinstance", "(", "leaves", ",", "bool", ")", ":", "raise", "TypeError", "(", "\"leaves must be a b...
46
23.62963
def _convert_to_floats(self, data): """ Convert all values in a dict to floats """ for key, value in data.items(): data[key] = float(value) return data
[ "def", "_convert_to_floats", "(", "self", ",", "data", ")", ":", "for", "key", ",", "value", "in", "data", ".", "items", "(", ")", ":", "data", "[", "key", "]", "=", "float", "(", "value", ")", "return", "data" ]
24.625
9.625
def from_dict(cls, D, is_json=False): '''This factory for :class:`Model` takes either a native Python dictionary or a JSON dictionary/object if ``is_json`` is ``True``. The dictionary passed does not need to contain all of the values that the Model declares. ''' instance...
[ "def", "from_dict", "(", "cls", ",", "D", ",", "is_json", "=", "False", ")", ":", "instance", "=", "cls", "(", ")", "instance", ".", "set_data", "(", "D", ",", "is_json", "=", "is_json", ")", "return", "instance" ]
38.9
19.9
def turbulent_Nunner(Re, Pr, fd, fd_smooth): r'''Calculates internal convection Nusselt number for turbulent flows in pipe according to [2]_ as shown in [1]_. .. math:: Nu = \frac{RePr(f/8)}{1 + 1.5Re^{-1/8}Pr^{-1/6}[Pr(f/f_s)-1]} Parameters ---------- Re : float Reynolds numbe...
[ "def", "turbulent_Nunner", "(", "Re", ",", "Pr", ",", "fd", ",", "fd_smooth", ")", ":", "return", "Re", "*", "Pr", "*", "fd", "/", "8.", "/", "(", "1", "+", "1.5", "*", "Re", "**", "-", "0.125", "*", "Pr", "**", "(", "-", "1", "/", "6.", ")...
27.075
25.375
def create_table(self, table_name, attr_descriptions): """ :param str table_name: Table name to create. :param list attr_descriptions: List of table description. :raises simplesqlite.NullDatabaseConnectionError: |raises_check_connection| :raises IOError: |raises_write...
[ "def", "create_table", "(", "self", ",", "table_name", ",", "attr_descriptions", ")", ":", "self", ".", "validate_access_permission", "(", "[", "\"w\"", ",", "\"a\"", "]", ")", "table_name", "=", "table_name", ".", "strip", "(", ")", "if", "self", ".", "ha...
31.833333
19.583333
def key_verify(rsakey, signature, message, digest): """Verify the given signature with the RSA key.""" padding = _asymmetric.padding.PKCS1v15() if isinstance(rsakey, _asymmetric.rsa.RSAPrivateKey): rsakey = rsakey.public_key() try: rsakey.verify(signature, message, padding, digest) ...
[ "def", "key_verify", "(", "rsakey", ",", "signature", ",", "message", ",", "digest", ")", ":", "padding", "=", "_asymmetric", ".", "padding", ".", "PKCS1v15", "(", ")", "if", "isinstance", "(", "rsakey", ",", "_asymmetric", ".", "rsa", ".", "RSAPrivateKey"...
31.833333
17.666667
def ping(): ''' Is the REST server up? ''' r = salt.utils.http.query(DETAILS['url']+'ping', decode_type='json', decode=True) try: return r['dict'].get('ret', False) except Exception: return False
[ "def", "ping", "(", ")", ":", "r", "=", "salt", ".", "utils", ".", "http", ".", "query", "(", "DETAILS", "[", "'url'", "]", "+", "'ping'", ",", "decode_type", "=", "'json'", ",", "decode", "=", "True", ")", "try", ":", "return", "r", "[", "'dict'...
25.222222
25.222222
def y_axis_rotation(theta): """Generates a 3x3 rotation matrix for a rotation of angle theta about the y axis. Parameters ---------- theta : float amount to rotate, in radians Returns ------- :obj:`numpy.ndarray` of float A random...
[ "def", "y_axis_rotation", "(", "theta", ")", ":", "R", "=", "np", ".", "array", "(", "[", "[", "np", ".", "cos", "(", "theta", ")", ",", "0", ",", "np", ".", "sin", "(", "theta", ")", "]", ",", "[", "0", ",", "1", ",", "0", "]", ",", "[",...
27.888889
15.833333
async def do_rollover(self): """ do a rollover; in this case, a date/time stamp is appended to the filename when the rollover happens. However, you want the file to be named for the start of the interval, not the current time. If there is a backup count, then we have to get a l...
[ "async", "def", "do_rollover", "(", "self", ")", ":", "if", "self", ".", "stream", ":", "await", "self", ".", "stream", ".", "close", "(", ")", "self", ".", "stream", "=", "None", "# get the time that this sequence started at and make it a TimeTuple", "current_tim...
43.225806
16.419355
def adjustPeakHeight(self, heightAmount): ''' Adjust peak height The foot of the accent is left unchanged and intermediate values are linearly scaled ''' if heightAmount == 0: return pitchList = [f0V for _, f0V in self.pointList] ...
[ "def", "adjustPeakHeight", "(", "self", ",", "heightAmount", ")", ":", "if", "heightAmount", "==", "0", ":", "return", "pitchList", "=", "[", "f0V", "for", "_", ",", "f0V", "in", "self", ".", "pointList", "]", "minV", "=", "min", "(", "pitchList", ")",...
32.764706
19.705882
def flatten_models(models): " Create 1d-array containing all disctinct models from ``models``. " if isinstance(models, MultiFitterModel): ans = [models] else: tasklist = MultiFitter._compile_models(models) ans = MultiFitter._flatten_models(tasklist) re...
[ "def", "flatten_models", "(", "models", ")", ":", "if", "isinstance", "(", "models", ",", "MultiFitterModel", ")", ":", "ans", "=", "[", "models", "]", "else", ":", "tasklist", "=", "MultiFitter", ".", "_compile_models", "(", "models", ")", "ans", "=", "...
40.125
19.125
def calc_uniform_lim_glorot(inmaps, outmaps, kernel=(1, 1)): r"""Calculates the lower bound and the upper bound of the uniform distribution proposed by Glorot et al. .. math:: b &= \sqrt{\frac{6}{NK + M}}\\ a &= -b Args: inmaps (int): Map size of an input Variable, :math:`N`. ...
[ "def", "calc_uniform_lim_glorot", "(", "inmaps", ",", "outmaps", ",", "kernel", "=", "(", "1", ",", "1", ")", ")", ":", "d", "=", "np", ".", "sqrt", "(", "6.", "/", "(", "np", ".", "prod", "(", "kernel", ")", "*", "inmaps", "+", "outmaps", ")", ...
34.378378
23.756757
def watchlist_movies(self, **kwargs): """ Get the list of movies on an account watchlist. Args: page: (optional) Minimum 1, maximum 1000. sort_by: (optional) 'created_at.asc' | 'created_at.desc' language: (optional) ISO 639-1 code. Returns: ...
[ "def", "watchlist_movies", "(", "self", ",", "*", "*", "kwargs", ")", ":", "path", "=", "self", ".", "_get_id_path", "(", "'watchlist_movies'", ")", "kwargs", ".", "update", "(", "{", "'session_id'", ":", "self", ".", "session_id", "}", ")", "response", ...
33.055556
17.5
def ptmsiReallocationCommand(PTmsiSignature_presence=0): """P-TMSI REALLOCATION COMMAND Section 9.4.7""" a = TpPd(pd=0x3) b = MessageType(mesType=0x10) # 00010000 c = MobileId() d = RoutingAreaIdentification() e = ForceToStandbyAndSpareHalfOctets() packet = a / b / c / d / e if PTmsiSig...
[ "def", "ptmsiReallocationCommand", "(", "PTmsiSignature_presence", "=", "0", ")", ":", "a", "=", "TpPd", "(", "pd", "=", "0x3", ")", "b", "=", "MessageType", "(", "mesType", "=", "0x10", ")", "# 00010000", "c", "=", "MobileId", "(", ")", "d", "=", "Rou...
34.666667
10.083333
def _get_simple_model(self, href=None): """Get a model 'href' the relative href to the model. May not be None. Returns a data structure equivalent to the JSON returned by the API. If the response status is not 2xx, throws an APIException. If the JSON to python data str...
[ "def", "_get_simple_model", "(", "self", ",", "href", "=", "None", ")", ":", "# Argument error checking.", "assert", "href", "is", "not", "None", "raw_result", "=", "self", ".", "get", "(", "href", ")", "if", "raw_result", ".", "status", "<", "200", "or", ...
30.304348
23.695652
def simulate_principal_policy(PolicySourceArn=None, PolicyInputList=None, ActionNames=None, ResourceArns=None, ResourcePolicy=None, ResourceOwner=None, CallerArn=None, ContextEntries=None, ResourceHandlingOption=None, MaxItems=None, Marker=None): """ Simulate how a set of IAM policies attached to an IAM entity ...
[ "def", "simulate_principal_policy", "(", "PolicySourceArn", "=", "None", ",", "PolicyInputList", "=", "None", ",", "ActionNames", "=", "None", ",", "ResourceArns", "=", "None", ",", "ResourcePolicy", "=", "None", ",", "ResourceOwner", "=", "None", ",", "CallerAr...
74.544944
59.55618
def full_dispatch_request(self): """Dispatches the request and on top of that performs request pre and postprocessing as well as HTTP exception catching and error handling. .. versionadded:: 0.7 """ self.try_trigger_before_first_request_functions() try: ...
[ "def", "full_dispatch_request", "(", "self", ")", ":", "self", ".", "try_trigger_before_first_request_functions", "(", ")", "try", ":", "request_started", ".", "send", "(", "self", ")", "rv", "=", "self", ".", "preprocess_request", "(", ")", "if", "rv", "is", ...
36.631579
12.105263
def configure(self, binder): # type: (Binder) -> None """Initializer of the cache - creates the Redis cache module as the default cache infrastructure. The module is bound to `RedisCacheModule` and `CacheModule` keys. The initializer also creates `RedisIdHelper` and bounds it to ...
[ "def", "configure", "(", "self", ",", "binder", ")", ":", "# type: (Binder) -> None", "redis_cache_module", "=", "RedisCacheModule", "(", ")", "binder", ".", "bind", "(", "RedisCacheModule", ",", "to", "=", "redis_cache_module", ",", "scope", "=", "singleton", "...
30.542857
18.542857
def _uncythonized_mb_model(self, beta, mini_batch): """ Creates the structure of the model Parameters ---------- beta : np.array Contains untransformed starting values for latent variables mini_batch : int Size of each mini batch of data Returns...
[ "def", "_uncythonized_mb_model", "(", "self", ",", "beta", ",", "mini_batch", ")", ":", "rand_int", "=", "np", ".", "random", ".", "randint", "(", "low", "=", "0", ",", "high", "=", "self", ".", "data", ".", "shape", "[", "0", "]", "-", "mini_batch",...
37.410256
29.384615
def _solve(self, x0, A, l, u, xmin, xmax): """ Solves using the Interior Point OPTimizer. """ # Indexes of constrained lines. il = [i for i,ln in enumerate(self._ln) if 0.0 < ln.rate_a < 1e10] nl2 = len(il) neqnln = 2 * self._nb # no. of non-linear equality constraints ...
[ "def", "_solve", "(", "self", ",", "x0", ",", "A", ",", "l", ",", "u", ",", "xmin", ",", "xmax", ")", ":", "# Indexes of constrained lines.", "il", "=", "[", "i", "for", "i", ",", "ln", "in", "enumerate", "(", "self", ".", "_ln", ")", "if", "0.0"...
37.395349
20.395349
def rows_to_dicts(self, serialize_cell=None): """Generates a sequence of dictionaries of {header[i] => row[i]} for each row.""" if serialize_cell is None: serialize_cell = self.get_cell_value # keys = [serialize_cell(cell) for cell in self.rows[0]] keys = self.headers(serialize_cell) for row i...
[ "def", "rows_to_dicts", "(", "self", ",", "serialize_cell", "=", "None", ")", ":", "if", "serialize_cell", "is", "None", ":", "serialize_cell", "=", "self", ".", "get_cell_value", "# keys = [serialize_cell(cell) for cell in self.rows[0]]", "keys", "=", "self", ".", ...
49.625
9.5
def upload_attachments(self, attachments, parentid=None, basedir=None): """Upload files to the already created (but never uploaded) attachments""" return Zupload(self, attachments, parentid, basedir=basedir).upload()
[ "def", "upload_attachments", "(", "self", ",", "attachments", ",", "parentid", "=", "None", ",", "basedir", "=", "None", ")", ":", "return", "Zupload", "(", "self", ",", "attachments", ",", "parentid", ",", "basedir", "=", "basedir", ")", ".", "upload", ...
76.666667
22.666667
def check_valid(var, key, expected): r"""Check that a variable's attribute has the expected value. Warn user otherwise.""" att = getattr(var, key, None) if att is None: e = 'Variable does not have a `{}` attribute.'.format(key) warn(e) elif att != expected: e = 'Variable has a n...
[ "def", "check_valid", "(", "var", ",", "key", ",", "expected", ")", ":", "att", "=", "getattr", "(", "var", ",", "key", ",", "None", ")", "if", "att", "is", "None", ":", "e", "=", "'Variable does not have a `{}` attribute.'", ".", "format", "(", "key", ...
39.6
22.1
def registerDirectory(self,name,physicalPath,directoryType,cleanupMode, maxFileAge,description): """ Registers a new server directory. While registering the server directory, you can also specify the directory's cleanup parameters. You can also register a direct...
[ "def", "registerDirectory", "(", "self", ",", "name", ",", "physicalPath", ",", "directoryType", ",", "cleanupMode", ",", "maxFileAge", ",", "description", ")", ":", "url", "=", "self", ".", "_url", "+", "\"/directories/register\"", "params", "=", "{", "\"f\""...
44.314286
19.171429
def _global_dest_mode_is_file(self): # type: (SyncCopy) -> bool """Determine if destination mode is file :param SyncCopy self: this :rtype: bool :return: destination mode is file """ if (self._spec.options.dest_mode == blobxfer.models.azure.Storage...
[ "def", "_global_dest_mode_is_file", "(", "self", ")", ":", "# type: (SyncCopy) -> bool", "if", "(", "self", ".", "_spec", ".", "options", ".", "dest_mode", "==", "blobxfer", ".", "models", ".", "azure", ".", "StorageModes", ".", "File", "or", "(", "self", "....
38.533333
9.666667
def make_statistics_information(info): """Make statistics information table.""" if not info.splits.total_num_examples: # That means that we have yet to calculate the statistics for this. return "None computed" stats = [(info.splits.total_num_examples, "ALL")] for split_name, split_info in info.splits.i...
[ "def", "make_statistics_information", "(", "info", ")", ":", "if", "not", "info", ".", "splits", ".", "total_num_examples", ":", "# That means that we have yet to calculate the statistics for this.", "return", "\"None computed\"", "stats", "=", "[", "(", "info", ".", "s...
40.333333
17
def orthonormal_vectors_old(self): """ Returns a list of three orthogonal vectors, the two first being parallel to the plane and the third one is the normal vector of the plane :return: List of orthogonal vectors :raise: ValueError if all the coefficients are zero or if there is ...
[ "def", "orthonormal_vectors_old", "(", "self", ")", ":", "if", "self", ".", "e1", "is", "None", ":", "imax", "=", "np", ".", "argmax", "(", "np", ".", "abs", "(", "self", ".", "normal_vector", ")", ")", "if", "imax", "==", "0", ":", "self", ".", ...
55.263158
27.052632
def _from_binary_sid(cls, binary_stream): """See base class.""" ''' Revision number - 1 Number of sub authorities - 1 Authority - 6 Array of 32 bits with sub authorities - 4 * number of sub authorities ''' rev_number, sub_auth_len, auth = cls._REPR.unpack(binary_stream[:cls._REPR...
[ "def", "_from_binary_sid", "(", "cls", ",", "binary_stream", ")", ":", "''' Revision number - 1\n Number of sub authorities - 1\n Authority - 6\n Array of 32 bits with sub authorities - 4 * number of sub authorities\n '''", "rev_number", ",", "sub_auth_len", ",", "a...
39.210526
29.578947
def receive_message( sock, operation, request_id, max_message_size=MAX_MESSAGE_SIZE): """Receive a raw BSON message or raise socket.error.""" header = _receive_data_on_socket(sock, 16) length = _UNPACK_INT(header[:4])[0] actual_op = _UNPACK_INT(header[12:])[0] if operation != actual_op: ...
[ "def", "receive_message", "(", "sock", ",", "operation", ",", "request_id", ",", "max_message_size", "=", "MAX_MESSAGE_SIZE", ")", ":", "header", "=", "_receive_data_on_socket", "(", "sock", ",", "16", ")", "length", "=", "_UNPACK_INT", "(", "header", "[", ":"...
46.75
18.541667
def _get_filesystem_path(self, url_path, basedir=settings.MEDIA_ROOT): """Makes a filesystem path from the specified URL path""" if url_path.startswith(settings.MEDIA_URL): url_path = url_path[len(settings.MEDIA_URL):] # strip media root url return os.path.normpath(os.path.join(ba...
[ "def", "_get_filesystem_path", "(", "self", ",", "url_path", ",", "basedir", "=", "settings", ".", "MEDIA_ROOT", ")", ":", "if", "url_path", ".", "startswith", "(", "settings", ".", "MEDIA_URL", ")", ":", "url_path", "=", "url_path", "[", "len", "(", "sett...
49.285714
28.571429
def init_widget(self): """ Initialize the widget with the source. """ d = self.declaration if d.source: self.set_source(d.source) else: super(RawComponent, self).init_widget()
[ "def", "init_widget", "(", "self", ")", ":", "d", "=", "self", ".", "declaration", "if", "d", ".", "source", ":", "self", ".", "set_source", "(", "d", ".", "source", ")", "else", ":", "super", "(", "RawComponent", ",", "self", ")", ".", "init_widget"...
32.142857
13
def get_text(self, node): """ After mark_tokens() has been called, returns the text corresponding to the given node. Returns '' for nodes (like `Load`) that don't correspond to any particular text. """ start, end = self.get_text_range(node) return self._text[start : end]
[ "def", "get_text", "(", "self", ",", "node", ")", ":", "start", ",", "end", "=", "self", ".", "get_text_range", "(", "node", ")", "return", "self", ".", "_text", "[", "start", ":", "end", "]" ]
41.285714
16.714286
def parse_known_args(self, args=None, namespace=None): """this method hijacks the normal argparse Namespace generation, shimming configman into the process. The return value will be a configman DotDict rather than an argparse Namespace.""" # load the config_manager within the scope of th...
[ "def", "parse_known_args", "(", "self", ",", "args", "=", "None", ",", "namespace", "=", "None", ")", ":", "# load the config_manager within the scope of the method that uses it", "# so that we avoid circular references in the outer scope", "from", "configman", ".", "config_man...
44.826087
15.73913
def __graceful_shutdown(self): """ call shutdown routines """ retcode = 1 self.log.info("Trying to shutdown gracefully...") retcode = self.core.plugins_end_test(retcode) retcode = self.core.plugins_post_process(retcode) self.log.info("Done graceful shutdown") retu...
[ "def", "__graceful_shutdown", "(", "self", ")", ":", "retcode", "=", "1", "self", ".", "log", ".", "info", "(", "\"Trying to shutdown gracefully...\"", ")", "retcode", "=", "self", ".", "core", ".", "plugins_end_test", "(", "retcode", ")", "retcode", "=", "s...
40.375
12.875
def from_edges(edges): """ Return DirectedGraph created from edges :param edges: :return: DirectedGraph """ dag = DirectedGraph() for _u, _v in edges: dag.add_edge(_u, _v) return dag
[ "def", "from_edges", "(", "edges", ")", ":", "dag", "=", "DirectedGraph", "(", ")", "for", "_u", ",", "_v", "in", "edges", ":", "dag", ".", "add_edge", "(", "_u", ",", "_v", ")", "return", "dag" ]
27.777778
10.444444
def create_embedded_template_draft(self, client_id, signer_roles, test_mode=False, files=None, file_urls=None, title=None, subject=None, message=None, cc_roles=None, merge_fields=None, use_preexisting_fields=False): ''' Creates an embedded Template draft for further editing. Args: test_mod...
[ "def", "create_embedded_template_draft", "(", "self", ",", "client_id", ",", "signer_roles", ",", "test_mode", "=", "False", ",", "files", "=", "None", ",", "file_urls", "=", "None", ",", "title", "=", "None", ",", "subject", "=", "None", ",", "message", "...
49.538462
43.346154
def auto_slug(self): """This property is used to auto-generate a slug from the name attribute. It can be customized by subclasses. """ slug = self.name if slug is not None: slug = slugify(slug, separator=self.SLUG_SEPARATOR) session = sa.orm.objec...
[ "def", "auto_slug", "(", "self", ")", ":", "slug", "=", "self", ".", "name", "if", "slug", "is", "not", "None", ":", "slug", "=", "slugify", "(", "slug", ",", "separator", "=", "self", ".", "SLUG_SEPARATOR", ")", "session", "=", "sa", ".", "orm", "...
35.285714
17.464286
def persist_trash_info(self, basename, content, logger): """ Create a .trashinfo file in the $trash/info directory. returns the created TrashInfoFile. """ self.ensure_dir(self.info_dir, 0o700) # write trash info index = 0 while True : if inde...
[ "def", "persist_trash_info", "(", "self", ",", "basename", ",", "content", ",", "logger", ")", ":", "self", ".", "ensure_dir", "(", "self", ".", "info_dir", ",", "0o700", ")", "# write trash info", "index", "=", "0", "while", "True", ":", "if", "index", ...
29.529412
18.529412
def styled_status(enabled, bold=True): """ Generate a styled status string @param enabled: Enabled / Disabled boolean @type enabled: bool @param bold: Display status in bold format @type bold: bool @rtype: str """ return click.style('Enabled' if enabled else '...
[ "def", "styled_status", "(", "enabled", ",", "bold", "=", "True", ")", ":", "return", "click", ".", "style", "(", "'Enabled'", "if", "enabled", "else", "'Disabled'", ",", "'green'", "if", "enabled", "else", "'red'", ",", "bold", "=", "bold", ")" ]
36.3
14.1
def get_mean_and_stddevs(self, sites, rup, dists, imt, stddev_types): """ See :meth:`superclass method <.base.GroundShakingIntensityModel.get_mean_and_stddevs>` for spec of input and result values. """ # extract dictionaries of coefficients specific to required # ...
[ "def", "get_mean_and_stddevs", "(", "self", ",", "sites", ",", "rup", ",", "dists", ",", "imt", ",", "stddev_types", ")", ":", "# extract dictionaries of coefficients specific to required", "# intensity measure type and for PGA", "C", "=", "self", ".", "COEFFS", "[", ...
47.73913
17.652174
def _what_default(self, pronunciation): """Provide the default prediction of the what task. This function is used to predict the probability of a given pronunciation being reported for a given token. :param pronunciation: The list or array of confusion probabilities at each index """ ...
[ "def", "_what_default", "(", "self", ",", "pronunciation", ")", ":", "token_default", "=", "self", "[", "'metadata'", "]", "[", "'token_default'", "]", "[", "'what'", "]", "index_count", "=", "2", "*", "len", "(", "pronunciation", ")", "+", "1", "predictio...
36
25.851852
def plot_networkx(self, mode="network", with_edge_labels=False, ax=None, arrows=False, node_size="num_cores", node_label="name_class", layout_type="spring", **kwargs): """ Use networkx to draw the flow with the connections among the nodes and the status of the tasks. ...
[ "def", "plot_networkx", "(", "self", ",", "mode", "=", "\"network\"", ",", "with_edge_labels", "=", "False", ",", "ax", "=", "None", ",", "arrows", "=", "False", ",", "node_size", "=", "\"num_cores\"", ",", "node_label", "=", "\"name_class\"", ",", "layout_t...
43
23.352
def plot_spectra_overlapped(ss, title=None, setup=_default_setup): """ Plots one or more spectra in the same plot. Args: ss: list of Spectrum objects title=None: window title setup: PlotSpectrumSetup object """ plt.figure() draw_spectra_overlapped(ss, title, setup) plt.sh...
[ "def", "plot_spectra_overlapped", "(", "ss", ",", "title", "=", "None", ",", "setup", "=", "_default_setup", ")", ":", "plt", ".", "figure", "(", ")", "draw_spectra_overlapped", "(", "ss", ",", "title", ",", "setup", ")", "plt", ".", "show", "(", ")" ]
24
16.769231
def run(ctx, commandline): """Run command with environment variables present.""" file = ctx.obj['FILE'] dotenv_as_dict = dotenv_values(file) if not commandline: click.echo('No command given.') exit(1) ret = run_command(commandline, dotenv_as_dict) exit(ret)
[ "def", "run", "(", "ctx", ",", "commandline", ")", ":", "file", "=", "ctx", ".", "obj", "[", "'FILE'", "]", "dotenv_as_dict", "=", "dotenv_values", "(", "file", ")", "if", "not", "commandline", ":", "click", ".", "echo", "(", "'No command given.'", ")", ...
32.111111
12
def _vector(x, type='row'): """Convert an object to a row or column vector.""" if isinstance(x, (list, tuple)): x = np.array(x, dtype=np.float32) elif not isinstance(x, np.ndarray): x = np.array([x], dtype=np.float32) assert x.ndim == 1 if type == 'column': x = x[:, None] ...
[ "def", "_vector", "(", "x", ",", "type", "=", "'row'", ")", ":", "if", "isinstance", "(", "x", ",", "(", "list", ",", "tuple", ")", ")", ":", "x", "=", "np", ".", "array", "(", "x", ",", "dtype", "=", "np", ".", "float32", ")", "elif", "not",...
32
10.2
def _get_nx_paths(self, begin, end): """ Get the possible (networkx) simple paths between two nodes or addresses corresponding to nodes. Input: addresses or node instances Return: a list of lists of nodes representing paths. """ if isinstance(begin, int) and isins...
[ "def", "_get_nx_paths", "(", "self", ",", "begin", ",", "end", ")", ":", "if", "isinstance", "(", "begin", ",", "int", ")", "and", "isinstance", "(", "end", ",", "int", ")", ":", "n_begin", "=", "self", ".", "get_any_node", "(", "begin", ")", "n_end"...
38.052632
17.947368
def safe_trigger(self, event, *args): """Safely triggers the specified event by invoking EventHook.safe_trigger under the hood. @param event: event to trigger. Any object can be passed as event, but string is preferable. If qcore.EnumBase instance is ...
[ "def", "safe_trigger", "(", "self", ",", "event", ",", "*", "args", ")", ":", "event_hook", "=", "self", ".", "get_or_create", "(", "event", ")", "event_hook", ".", "safe_trigger", "(", "*", "args", ")", "return", "self" ]
40.642857
17
def load(cls, path): """Load image from file.""" assert os.path.exists(path), "No such file: %r" % path (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) image = Image(None) image._path = path image._format = Image.image_for...
[ "def", "load", "(", "cls", ",", "path", ")", ":", "assert", "os", ".", "path", ".", "exists", "(", "path", ")", ",", "\"No such file: %r\"", "%", "path", "(", "folder", ",", "filename", ")", "=", "os", ".", "path", ".", "split", "(", "path", ")", ...
28.75
20.333333
def info(message, code='INFO'): """Display Information. Method prints the information message, message being given as an input. Arguments: message {string} -- The message to be displayed. """ now = datetime.now().strftime('%Y-%m-%d %H:%M:%S') output = now + ' [' + torn.plugins.col...
[ "def", "info", "(", "message", ",", "code", "=", "'INFO'", ")", ":", "now", "=", "datetime", ".", "now", "(", ")", ".", "strftime", "(", "'%Y-%m-%d %H:%M:%S'", ")", "output", "=", "now", "+", "' ['", "+", "torn", ".", "plugins", ".", "colors", ".", ...
27.666667
20.466667
def _find_file_meta(metadata, bucket_name, saltenv, path): ''' Looks for a file's metadata in the S3 bucket cache file ''' env_meta = metadata[saltenv] if saltenv in metadata else {} bucket_meta = {} for bucket in env_meta: if bucket_name in bucket: bucket_meta = bucket[bucke...
[ "def", "_find_file_meta", "(", "metadata", ",", "bucket_name", ",", "saltenv", ",", "path", ")", ":", "env_meta", "=", "metadata", "[", "saltenv", "]", "if", "saltenv", "in", "metadata", "else", "{", "}", "bucket_meta", "=", "{", "}", "for", "bucket", "i...
36.263158
19.631579
def compile_expression(self, source, undefined_to_none=True): """A handy helper method that returns a callable that accepts keyword arguments that appear as variables in the expression. If called it returns the result of the expression. This is useful if applications want to use the sa...
[ "def", "compile_expression", "(", "self", ",", "source", ",", "undefined_to_none", "=", "True", ")", ":", "parser", "=", "Parser", "(", "self", ",", "source", ",", "state", "=", "'variable'", ")", "exc_info", "=", "None", "try", ":", "expr", "=", "parser...
39.068182
20.795455
def get_value(repo_directory, key, expect_type=None): """Gets the value of the specified key in the config file.""" config = read_config(repo_directory) value = config.get(key) if expect_type and value is not None and not isinstance(value, expect_type): raise ConfigSchemaError('Expected config v...
[ "def", "get_value", "(", "repo_directory", ",", "key", ",", "expect_type", "=", "None", ")", ":", "config", "=", "read_config", "(", "repo_directory", ")", "value", "=", "config", ".", "get", "(", "key", ")", "if", "expect_type", "and", "value", "is", "n...
53.5
19.625
def _FormatUsername(self, event): """Formats the username. Args: event (EventObject): event. Returns: str: formatted username field. """ username = self._output_mediator.GetUsername(event) return self._SanitizeField(username)
[ "def", "_FormatUsername", "(", "self", ",", "event", ")", ":", "username", "=", "self", ".", "_output_mediator", ".", "GetUsername", "(", "event", ")", "return", "self", ".", "_SanitizeField", "(", "username", ")" ]
23.181818
15.454545
def get_structure_with_nodes(self, find_min=True, min_dist=0.5, tol=0.2, threshold_frac=None, threshold_abs=None): """ Get the modified structure with the possible interstitial sites added. The species is set as a DummySpecie X. Args: find_mi...
[ "def", "get_structure_with_nodes", "(", "self", ",", "find_min", "=", "True", ",", "min_dist", "=", "0.5", ",", "tol", "=", "0.2", ",", "threshold_frac", "=", "None", ",", "threshold_abs", "=", "None", ")", ":", "structure", "=", "self", ".", "structure", ...
40.9
26.38
def snmp_server_v3host_source_interface_source_interface_type_loopback_loopback(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") snmp_server = ET.SubElement(config, "snmp-server", xmlns="urn:brocade.com:mgmt:brocade-snmp") v3host = ET.SubElement(snmp_serv...
[ "def", "snmp_server_v3host_source_interface_source_interface_type_loopback_loopback", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "snmp_server", "=", "ET", ".", "SubElement", "(", "config", ",", "\"s...
52.388889
20.333333
def loadalldatas(): """Loads all demo fixtures.""" dependency_order = ['common', 'profiles', 'blog', 'democomments'] for app in dependency_order: project.recursive_load(os.path.join(paths.project_paths.manage_root, app))
[ "def", "loadalldatas", "(", ")", ":", "dependency_order", "=", "[", "'common'", ",", "'profiles'", ",", "'blog'", ",", "'democomments'", "]", "for", "app", "in", "dependency_order", ":", "project", ".", "recursive_load", "(", "os", ".", "path", ".", "join", ...
47.2
20
def validate(self, value, messages=None): """Returns True if the given field value is valid, False otherwise. Validation error messages are appended to an optional messages array. """ valid = True primitive = value def log(msg): if messages is not...
[ "def", "validate", "(", "self", ",", "value", ",", "messages", "=", "None", ")", ":", "valid", "=", "True", "primitive", "=", "value", "def", "log", "(", "msg", ")", ":", "if", "messages", "is", "not", "None", ":", "messages", ".", "append", "(", "...
32.68
20.2