text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def end(self): """ This method must be called after the operation returns. Note that this method is not to be invoked by the user; it is invoked by the implementation of the :class:`~zhmcclient.Session` class. If the statistics keeper holding this time statistics is enabled, thi...
[ "def", "end", "(", "self", ")", ":", "if", "self", ".", "keeper", ".", "enabled", ":", "if", "self", ".", "_begin_time", "is", "None", ":", "raise", "RuntimeError", "(", "\"end() called without preceding begin()\"", ")", "dt", "=", "time", ".", "time", "("...
39.5
22.125
def get(self, name_or_uri): """ Get the role by its URI or Name. Args: name_or_uri: Can be either the Name or the URI. Returns: dict: Role """ name_or_uri = quote(name_or_uri) return self._client.get(name_or_uri)
[ "def", "get", "(", "self", ",", "name_or_uri", ")", ":", "name_or_uri", "=", "quote", "(", "name_or_uri", ")", "return", "self", ".", "_client", ".", "get", "(", "name_or_uri", ")" ]
22.923077
14.769231
def binary_float_to_decimal_float(number: Union[float, str]) -> float: """ Convert binary floating point to decimal floating point. :param number: Binary floating point. :return: Decimal floating point representation of binary floating point. """ if isinstance(number, str): if number[0]...
[ "def", "binary_float_to_decimal_float", "(", "number", ":", "Union", "[", "float", ",", "str", "]", ")", "->", "float", ":", "if", "isinstance", "(", "number", ",", "str", ")", ":", "if", "number", "[", "0", "]", "==", "'-'", ":", "n_sign", "=", "-",...
27.727273
18.363636
def run_calibration(self, interval, applycal): """Runs the calibration operation with the current settings :param interval: The repetition interval between stimuli presentations (seconds) :type interval: float :param applycal: Whether to apply a previous saved calibration to thi...
[ "def", "run_calibration", "(", "self", ",", "interval", ",", "applycal", ")", ":", "if", "self", ".", "selected_calibration_index", "==", "2", ":", "self", ".", "tone_calibrator", ".", "apply_calibration", "(", "applycal", ")", "self", ".", "tone_calibrator", ...
48.5
17.722222
def convert_reset_type(value): """! @brief Convert a reset_type session option value to the Target.ResetType enum. @param value The value of the reset_type session option. @exception ValueError Raised if an unknown reset_type value is passed. """ value = value.lower() if value not in RESET_TYPE_...
[ "def", "convert_reset_type", "(", "value", ")", ":", "value", "=", "value", ".", "lower", "(", ")", "if", "value", "not", "in", "RESET_TYPE_MAP", ":", "raise", "ValueError", "(", "\"unexpected value for reset_type option ('%s')\"", "%", "value", ")", "return", "...
47.888889
14.777778
def mutate_add_connection(self, config): """ Attempt to add a new connection, the only restriction being that the output node cannot be one of the network input pins. """ possible_outputs = list(iterkeys(self.nodes)) out_node = choice(possible_outputs) possible_i...
[ "def", "mutate_add_connection", "(", "self", ",", "config", ")", ":", "possible_outputs", "=", "list", "(", "iterkeys", "(", "self", ".", "nodes", ")", ")", "out_node", "=", "choice", "(", "possible_outputs", ")", "possible_inputs", "=", "possible_outputs", "+...
39.4375
21.4375
def ngfileupload_partfactory(part_number=None, content_length=None, uploaded_file=None): """Part factory for ng-file-upload. :param part_number: The part number. (Default: ``None``) :param content_length: The content length. (Default: ``None``) :param uploaded_file: The upl...
[ "def", "ngfileupload_partfactory", "(", "part_number", "=", "None", ",", "content_length", "=", "None", ",", "uploaded_file", "=", "None", ")", ":", "return", "content_length", ",", "part_number", ",", "uploaded_file", ".", "stream", ",", "uploaded_file", ".", "...
47
20.666667
def hook(name=None, *args, **kwargs): """Decorator to register the function as a hook """ def decorator(f): if not hasattr(f, "hooks"): f.hooks = [] f.hooks.append((name or f.__name__, args, kwargs)) return f return decorator
[ "def", "hook", "(", "name", "=", "None", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "def", "decorator", "(", "f", ")", ":", "if", "not", "hasattr", "(", "f", ",", "\"hooks\"", ")", ":", "f", ".", "hooks", "=", "[", "]", "f", ".", ...
29.888889
11.666667
def calculate_concat_output_shapes(operator): ''' Allowed input/output patterns are 1. [N_1, C, H, W], ..., [N_n, C, H, W] ---> [N_1 + ... + N_n, C, H, W] 2. [N, C_1, H, W], ..., [N, C_n, H, W] ---> [N, C_1 + ... + C_n, H, W] ''' check_input_and_output_numbers(operator, input_count_range...
[ "def", "calculate_concat_output_shapes", "(", "operator", ")", ":", "check_input_and_output_numbers", "(", "operator", ",", "input_count_range", "=", "[", "1", ",", "None", "]", ",", "output_count_range", "=", "[", "1", ",", "1", "]", ")", "output_shape", "=", ...
53.52381
30.666667
def add_format(self, format_id, number, entry_type, description): """ Add a format line to the header. Arguments: format_id (str): The id of the format line number (str): Integer or any of [A,R,G,.] entry_type (str): Any of [Integer,Float,Flag,Character,Strin...
[ "def", "add_format", "(", "self", ",", "format_id", ",", "number", ",", "entry_type", ",", "description", ")", ":", "format_line", "=", "'##FORMAT=<ID={0},Number={1},Type={2},Description=\"{3}\">'", ".", "format", "(", "format_id", ",", "number", ",", "entry_type", ...
39.117647
21.235294
def load(self, name, skip='', skip_original='', default_template=None, layout=None): """Loads a template.""" filename = self.resolve_path(name, skip=skip, skip_original=skip_original, default_template=default_template) if not filename: rais...
[ "def", "load", "(", "self", ",", "name", ",", "skip", "=", "''", ",", "skip_original", "=", "''", ",", "default_template", "=", "None", ",", "layout", "=", "None", ")", ":", "filename", "=", "self", ".", "resolve_path", "(", "name", ",", "skip", "=",...
38.054054
18.648649
def _countWhereGreaterEqualInRows(sparseMatrix, rows, threshold): """ Like countWhereGreaterOrEqual, but for an arbitrary selection of rows, and without any column filtering. """ return sum(sparseMatrix.countWhereGreaterOrEqual(row, row+1, 0, sparseMatrix.nCo...
[ "def", "_countWhereGreaterEqualInRows", "(", "sparseMatrix", ",", "rows", ",", "threshold", ")", ":", "return", "sum", "(", "sparseMatrix", ".", "countWhereGreaterOrEqual", "(", "row", ",", "row", "+", "1", ",", "0", ",", "sparseMatrix", ".", "nCols", "(", "...
45.444444
17.666667
def _write(self, s): """Write a string out to the SSL socket fully.""" try: write = self.sock.write except AttributeError: # Works around a bug in python socket library raise IOError('Socket closed') else: while s: n = write...
[ "def", "_write", "(", "self", ",", "s", ")", ":", "try", ":", "write", "=", "self", ".", "sock", ".", "write", "except", "AttributeError", ":", "# Works around a bug in python socket library", "raise", "IOError", "(", "'Socket closed'", ")", "else", ":", "whil...
31.846154
13.923077
def _make_skel_func(code, cell_count, base_globals=None): """ Creates a skeleton function object that contains just the provided code and the correct number of cells in func_closure. All other func attributes (e.g. func_globals) are empty. """ if base_globals is None: base_globals =...
[ "def", "_make_skel_func", "(", "code", ",", "cell_count", ",", "base_globals", "=", "None", ")", ":", "if", "base_globals", "is", "None", ":", "base_globals", "=", "{", "}", "base_globals", "[", "'__builtins__'", "]", "=", "__builtins__", "closure", "=", "("...
37.133333
18.933333
def _set_topology_group(self, v, load=False): """ Setter method for topology_group, mapped from YANG variable /topology_group (list) If this variable is read-only (config: false) in the source YANG file, then _set_topology_group is considered as a private method. Backends looking to populate this va...
[ "def", "_set_topology_group", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v", ",", ...
159.227273
76.818182
def delete_directory(self, dirname): """Delete a directory (and contents) from the bucket. Parameters ---------- dirname : `str` Name of the directory, relative to ``bucket_root/``. Raises ------ RuntimeError Raised when there are no obje...
[ "def", "delete_directory", "(", "self", ",", "dirname", ")", ":", "key", "=", "os", ".", "path", ".", "join", "(", "self", ".", "_bucket_root", ",", "dirname", ")", "if", "not", "key", ".", "endswith", "(", "'/'", ")", ":", "key", "+=", "'/'", "key...
36.064516
17.806452
def get_setters_property_name(node): """Get the name of the property that the given node is a setter for. :param node: The node to get the property name for. :type node: str :rtype: str or None :returns: The name of the property that the node is a setter for, or None if one could not be fo...
[ "def", "get_setters_property_name", "(", "node", ")", ":", "decorators", "=", "node", ".", "decorators", ".", "nodes", "if", "node", ".", "decorators", "else", "[", "]", "for", "decorator", "in", "decorators", ":", "if", "(", "isinstance", "(", "decorator", ...
34.157895
16.842105
def insert_multiple(self, documents): """ Insert multiple documents into the table. :param documents: a list of documents to insert :returns: a list containing the inserted documents' IDs """ doc_ids = [] data = self._read() for doc in documents: ...
[ "def", "insert_multiple", "(", "self", ",", "documents", ")", ":", "doc_ids", "=", "[", "]", "data", "=", "self", ".", "_read", "(", ")", "for", "doc", "in", "documents", ":", "doc_id", "=", "self", ".", "_get_doc_id", "(", "doc", ")", "doc_ids", "."...
23.05
18.95
def _reset(self): """ Rebuilds structure for AST and resets internal data. """ self._filename = None self._block_map = {} self._ast = [] self._ast.append(None) # header self._ast.append([]) # options list self._ast.append([])
[ "def", "_reset", "(", "self", ")", ":", "self", ".", "_filename", "=", "None", "self", ".", "_block_map", "=", "{", "}", "self", ".", "_ast", "=", "[", "]", "self", ".", "_ast", ".", "append", "(", "None", ")", "# header", "self", ".", "_ast", "....
28.9
12.2
def from_base64_data(cls, **kwargs): '''Load a :class:`StdModel` from possibly base64encoded data. This method is used to load models from data obtained from the :meth:`tojson` method.''' o = cls() meta = cls._meta pkname = meta.pkname() for name, value in iteritems(kwargs): ...
[ "def", "from_base64_data", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "o", "=", "cls", "(", ")", "meta", "=", "cls", ".", "_meta", "pkname", "=", "meta", ".", "pkname", "(", ")", "for", "name", ",", "value", "in", "iteritems", "(", "kwargs", ...
32.888889
15.888889
def remove_declaration(self, decl): """ Removes declaration from members list. :param decl: declaration to be removed :type decl: :class:`declaration_t` """ del self.declarations[self.declarations.index(decl)] decl.cache.reset()
[ "def", "remove_declaration", "(", "self", ",", "decl", ")", ":", "del", "self", ".", "declarations", "[", "self", ".", "declarations", ".", "index", "(", "decl", ")", "]", "decl", ".", "cache", ".", "reset", "(", ")" ]
25.181818
15.727273
def _set_show_mpls_dynamic_bypass(self, v, load=False): """ Setter method for show_mpls_dynamic_bypass, mapped from YANG variable /brocade_mpls_rpc/show_mpls_dynamic_bypass (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_show_mpls_dynamic_bypass is considered as a ...
[ "def", "_set_show_mpls_dynamic_bypass", "(", "self", ",", "v", ",", "load", "=", "False", ")", ":", "if", "hasattr", "(", "v", ",", "\"_utype\"", ")", ":", "v", "=", "v", ".", "_utype", "(", "v", ")", "try", ":", "t", "=", "YANGDynClass", "(", "v",...
80.227273
38
def start(self, exceptions): """Start the Heartbeat Checker. :param list exceptions: :return: """ if not self._interval: return False self._running.set() with self._lock: self._threshold = 0 self._reads_since_check = 0 ...
[ "def", "start", "(", "self", ",", "exceptions", ")", ":", "if", "not", "self", ".", "_interval", ":", "return", "False", "self", ".", "_running", ".", "set", "(", ")", "with", "self", ".", "_lock", ":", "self", ".", "_threshold", "=", "0", "self", ...
29
10.25
def size_in_days(self): """Return the size of the period in days. >>> period('month', '2012-2-29', 4).size_in_days 28 >>> period('year', '2012', 1).size_in_days 366 """ unit, instant, length = self if unit == DAY: return length if uni...
[ "def", "size_in_days", "(", "self", ")", ":", "unit", ",", "instant", ",", "length", "=", "self", "if", "unit", "==", "DAY", ":", "return", "length", "if", "unit", "in", "[", "MONTH", ",", "YEAR", "]", ":", "last_day", "=", "self", ".", "start", "....
31.588235
20.882353
def crop_on_centerpoint(self, image, width, height, ppoi=(0.5, 0.5)): """ Return a PIL Image instance cropped from `image`. Image has an aspect ratio provided by dividing `width` / `height`), sized down to `width`x`height`. Any 'excess pixels' are trimmed away in respect to the ...
[ "def", "crop_on_centerpoint", "(", "self", ",", "image", ",", "width", ",", "height", ",", "ppoi", "=", "(", "0.5", ",", "0.5", ")", ")", ":", "ppoi_x_axis", "=", "int", "(", "image", ".", "size", "[", "0", "]", "*", "ppoi", "[", "0", "]", ")", ...
43.924731
19.795699
def simulate_measurement(self, index: int) -> bool: """Simulates a single qubit measurement in the computational basis. Args: index: Which qubit is measured. Returns: True iff the measurement result corresponds to the |1> state. """ args = self._shard_nu...
[ "def", "simulate_measurement", "(", "self", ",", "index", ":", "int", ")", "->", "bool", ":", "args", "=", "self", ".", "_shard_num_args", "(", "{", "'index'", ":", "index", "}", ")", "prob_one", "=", "np", ".", "sum", "(", "self", ".", "_pool", ".",...
32.85
18.05
def _process_qtls_genomic_location( self, raw, txid, build_id, build_label, common_name, limit=None): """ This method Triples created: :param limit: :return: """ if self.test_mode: graph = self.testgraph else: graph = ...
[ "def", "_process_qtls_genomic_location", "(", "self", ",", "raw", ",", "txid", ",", "build_id", ",", "build_label", ",", "common_name", ",", "limit", "=", "None", ")", ":", "if", "self", ".", "test_mode", ":", "graph", "=", "self", ".", "testgraph", "else"...
44.402985
20.761194
def get_start_and_end_time(self, ref=None): """Specific function to get start time and end time for CalendarDaterange :param ref: time in seconds :type ref: int :return: tuple with start and end time :rtype: tuple (int, int) """ return (get_start_of_day(self.syea...
[ "def", "get_start_and_end_time", "(", "self", ",", "ref", "=", "None", ")", ":", "return", "(", "get_start_of_day", "(", "self", ".", "syear", ",", "int", "(", "self", ".", "smon", ")", ",", "self", ".", "smday", ")", ",", "get_end_of_day", "(", "self"...
41.4
14.4
def services(self, *args, **kwargs): """Retrieve services belonging to this scope. See :class:`pykechain.Client.services` for available parameters. .. versionadded:: 1.13 """ return self._client.services(*args, scope=self.id, **kwargs)
[ "def", "services", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_client", ".", "services", "(", "*", "args", ",", "scope", "=", "self", ".", "id", ",", "*", "*", "kwargs", ")" ]
33.75
19.25
def _prevent_core_dump(cls): """Prevent the process from generating a core dump.""" try: # Try to get the current limit resource.getrlimit(resource.RLIMIT_CORE) except ValueError: # System doesn't support the RLIMIT_CORE resource limit return ...
[ "def", "_prevent_core_dump", "(", "cls", ")", ":", "try", ":", "# Try to get the current limit", "resource", ".", "getrlimit", "(", "resource", ".", "RLIMIT_CORE", ")", "except", "ValueError", ":", "# System doesn't support the RLIMIT_CORE resource limit", "return", "else...
40.818182
17.545455
def get_genus_type(self): """Gets the genus type of this object. return: (osid.type.Type) - the genus type of this object compliance: mandatory - This method must be implemented. """ if self._my_genus_type_map is None: url_path = '/handcar/services/learning/types/' ...
[ "def", "get_genus_type", "(", "self", ")", ":", "if", "self", ".", "_my_genus_type_map", "is", "None", ":", "url_path", "=", "'/handcar/services/learning/types/'", "+", "self", ".", "_my_map", "[", "'genusTypeId'", "]", "# url_str = self._base_url + '/types/'...
45.538462
21.923077
def get_activity_objective_bank_session(self, proxy): """Gets the session for retrieving activity to objective bank mappings. arg: proxy (osid.proxy.Proxy): a proxy return: (osid.learning.ActivityObjectiveBankSession) - an ``ActivityObjectiveBankSession`` raise: Null...
[ "def", "get_activity_objective_bank_session", "(", "self", ",", "proxy", ")", ":", "if", "not", "self", ".", "supports_activity_objective_bank", "(", ")", ":", "raise", "errors", ".", "Unimplemented", "(", ")", "# pylint: disable=no-member", "return", "sessions", "....
47.777778
18
def get_languages_from_item(ct_item, item): """ Get the languages configured for the current item :param ct_item: :param item: :return: """ try: item_lan = TransItemLanguage.objects.filter(content_type__pk=ct_item.id, object_id=item.id).get() ...
[ "def", "get_languages_from_item", "(", "ct_item", ",", "item", ")", ":", "try", ":", "item_lan", "=", "TransItemLanguage", ".", "objects", ".", "filter", "(", "content_type__pk", "=", "ct_item", ".", "id", ",", "object_id", "=", "item", ".", "id", ")", "."...
36.076923
19
def train(self, epochs=2000, training_iterations=5): ''' Parameters ---------- epochs : int Number of epochs to train for. Default is 2000. training_iterations : int Number of times to repeat training process. Default is training_iterations. Returns ------- A trained word2vec model. ''' se...
[ "def", "train", "(", "self", ",", "epochs", "=", "2000", ",", "training_iterations", "=", "5", ")", ":", "self", ".", "_scan_and_build_vocab", "(", ")", "for", "_", "in", "range", "(", "training_iterations", ")", ":", "self", ".", "model", ".", "train", ...
27.6
23.5
def mask(self, image): """ self.mask setter Parameters ---------- image: str or img-like object. See NeuroImage constructor docstring. """ if image is None: self._mask = None try: mask = load_mask(image) except Excepti...
[ "def", "mask", "(", "self", ",", "image", ")", ":", "if", "image", "is", "None", ":", "self", ".", "_mask", "=", "None", "try", ":", "mask", "=", "load_mask", "(", "image", ")", "except", "Exception", "as", "exc", ":", "raise", "Exception", "(", "'...
26
17.705882
def get_angle_addr(value): """ angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / obs-angle-addr obs-angle-addr = [CFWS] "<" obs-route addr-spec ">" [CFWS] """ angle_addr = AngleAddr() if value[0] in CFWS_LEADER: token, value = get_cfws(value) angle_addr.append(token) if not val...
[ "def", "get_angle_addr", "(", "value", ")", ":", "angle_addr", "=", "AngleAddr", "(", ")", "if", "value", "[", "0", "]", "in", "CFWS_LEADER", ":", "token", ",", "value", "=", "get_cfws", "(", "value", ")", "angle_addr", ".", "append", "(", "token", ")"...
39.222222
14.022222
def init_model(self, clear_registry: bool = True) -> None: """Load the control file of the actual |Element| object, initialise its |Model| object, build the required connections via (an eventually overridden version of) method |Model.connect| of class |Model|, and update its derived par...
[ "def", "init_model", "(", "self", ",", "clear_registry", ":", "bool", "=", "True", ")", "->", "None", ":", "try", ":", "with", "hydpy", ".", "pub", ".", "options", ".", "warnsimulationstep", "(", "False", ")", ":", "info", "=", "hydpy", ".", "pub", "...
49.133333
20.2
def main(): """ NAME scalc.py DESCRIPTION calculates Sb from VGP Long,VGP Lat,Directional kappa,Site latitude data SYNTAX scalc -h [command line options] [< standard input] INPUT takes space delimited files with PLong, PLat,[kappa, N_site, slat] OPTIONS -h p...
[ "def", "main", "(", ")", ":", "kappa", ",", "cutoff", "=", "0", ",", "180", "rev", ",", "anti", ",", "boot", "=", "0", ",", "0", ",", "0", "spin", ",", "n", ",", "v", ",", "mm97", "=", "0", ",", "0", ",", "0", ",", "0", "if", "'-h'", "i...
36.136364
18.166667
def _create_dns_list(self, dns): """ :param dns: :return: """ if not dns: return None dns_list = [] if isinstance(dns, six.string_types): if is_valid_ip(dns): dns_list.append(dns) else: raise Va...
[ "def", "_create_dns_list", "(", "self", ",", "dns", ")", ":", "if", "not", "dns", ":", "return", "None", "dns_list", "=", "[", "]", "if", "isinstance", "(", "dns", ",", "six", ".", "string_types", ")", ":", "if", "is_valid_ip", "(", "dns", ")", ":", ...
30.884615
22.653846
def plot_cumulative_density(self, **kwargs): """ Plots a pretty figure of {0}.{1} Matplotlib plot arguments can be passed in inside the kwargs, plus Parameters ----------- show_censors: bool place markers at censorship events. Default: False censor_s...
[ "def", "plot_cumulative_density", "(", "self", ",", "*", "*", "kwargs", ")", ":", "return", "_plot_estimate", "(", "self", ",", "estimate", "=", "self", ".", "cumulative_density_", ",", "confidence_intervals", "=", "self", ".", "confidence_interval_cumulative_densit...
37.833333
26.333333
def _maybe_from_pandas(data, feature_names, feature_types): """ Extract internal data from pd.DataFrame """ try: import pandas as pd except ImportError: return data, feature_names, feature_types if not isinstance(data, pd.DataFrame): return data, feature_names, feature_types ...
[ "def", "_maybe_from_pandas", "(", "data", ",", "feature_names", ",", "feature_types", ")", ":", "try", ":", "import", "pandas", "as", "pd", "except", "ImportError", ":", "return", "data", ",", "feature_names", ",", "feature_types", "if", "not", "isinstance", "...
37.809524
18.428571
def is_temple_project(): """Raises `InvalidTempleProjectError` if repository is not a temple project""" if not os.path.exists(temple.constants.TEMPLE_CONFIG_FILE): msg = 'No {} file found in repository.'.format(temple.constants.TEMPLE_CONFIG_FILE) raise temple.exceptions.InvalidTempleProjectErro...
[ "def", "is_temple_project", "(", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "temple", ".", "constants", ".", "TEMPLE_CONFIG_FILE", ")", ":", "msg", "=", "'No {} file found in repository.'", ".", "format", "(", "temple", ".", "constants", "...
64.4
22.4
def density_2d(self, x, y, rho0, Ra, Rs, center_x=0, center_y=0): """ projected density :param x: :param y: :param rho0: :param Ra: :param Rs: :param center_x: :param center_y: :return: """ Ra, Rs = self._sort_ra_rs(Ra, Rs) ...
[ "def", "density_2d", "(", "self", ",", "x", ",", "y", ",", "rho0", ",", "Ra", ",", "Rs", ",", "center_x", "=", "0", ",", "center_y", "=", "0", ")", ":", "Ra", ",", "Rs", "=", "self", ".", "_sort_ra_rs", "(", "Ra", ",", "Rs", ")", "x_", "=", ...
29.789474
17.789474
def is_url_allowed(url): """ Return ``True`` if ``url`` is not in ``blacklist``. :rtype: bool """ blacklist = [ r'\.ttf', r'\.woff', r'fonts\.googleapis\.com', r'\.png', r'\.jpe?g', r'\.gif', r'\.svg' ] for ft in blacklist: if re.search(ft, url): return Fal...
[ "def", "is_url_allowed", "(", "url", ")", ":", "blacklist", "=", "[", "r'\\.ttf'", ",", "r'\\.woff'", ",", "r'fonts\\.googleapis\\.com'", ",", "r'\\.png'", ",", "r'\\.jpe?g'", ",", "r'\\.gif'", ",", "r'\\.svg'", "]", "for", "ft", "in", "blacklist", ":", "if", ...
20.25
24.75
def execute_sql_statements( ctask, query_id, rendered_query, return_results=True, store_results=False, user_name=None, session=None, start_time=None, ): """Executes the sql query returns the results.""" if store_results and start_time: # only asynchronous queries stats_logger.timing( ...
[ "def", "execute_sql_statements", "(", "ctask", ",", "query_id", ",", "rendered_query", ",", "return_results", "=", "True", ",", "store_results", "=", "False", ",", "user_name", "=", "None", ",", "session", "=", "None", ",", "start_time", "=", "None", ",", ")...
37.978261
16.228261
def load_config_file(appdirs=DEFAULT_APPDIRS, file_name=DEFAULT_CONFIG_FILENAME, fallback_config_instance=None): """ Retrieve config information from file at default location. If no config file is found a new one will be created either with ``fallback_config_instance`` as content or if none is ...
[ "def", "load_config_file", "(", "appdirs", "=", "DEFAULT_APPDIRS", ",", "file_name", "=", "DEFAULT_CONFIG_FILENAME", ",", "fallback_config_instance", "=", "None", ")", ":", "if", "not", "fallback_config_instance", ":", "fallback_config_instance", "=", "backend_config_to_c...
42.53125
26.40625
def purge_deleted( self, vault_name, location, custom_headers=None, raw=False, polling=True, **operation_config): """Permanently deletes the specified vault. aka Purges the deleted Azure key vault. :param vault_name: The name of the soft-deleted vault. :type vault_name: str ...
[ "def", "purge_deleted", "(", "self", ",", "vault_name", ",", "location", ",", "custom_headers", "=", "None", ",", "raw", "=", "False", ",", "polling", "=", "True", ",", "*", "*", "operation_config", ")", ":", "raw_result", "=", "self", ".", "_purge_deleted...
47.875
21.95
def get_assets_by_repositories(self, repository_ids): """Gets the list of ``Assets`` corresponding to a list of ``Repository`` objects. arg: repository_ids (osid.id.IdList): list of repository ``Ids`` return: (osid.repository.AssetList) - list of assets raise: NullAr...
[ "def", "get_assets_by_repositories", "(", "self", ",", "repository_ids", ")", ":", "# Implemented from template for", "# osid.resource.ResourceBinSession.get_resources_by_bins", "asset_list", "=", "[", "]", "for", "repository_id", "in", "repository_ids", ":", "asset_list", "+...
44.894737
16.894737
def _keys2sls(self, keys, key2sl): """Convert an input key to a list of slices.""" sls = list() if isinstance(keys, tuple): for key in keys: sls.append(key2sl(key)) else: sls.append(key2sl(keys)) if len(sls) > self.ndim: fstr = ...
[ "def", "_keys2sls", "(", "self", ",", "keys", ",", "key2sl", ")", ":", "sls", "=", "list", "(", ")", "if", "isinstance", "(", "keys", ",", "tuple", ")", ":", "for", "key", "in", "keys", ":", "sls", ".", "append", "(", "key2sl", "(", "key", ")", ...
36.166667
12.416667
def rest(url, req="GET", data=None): """Main function to be called from this module. send a request using method 'req' and to the url. the _rest() function will add the base_url to this, so 'url' should be something like '/ips'. """ load_variables() return _rest(base_url + url, req, data)
[ "def", "rest", "(", "url", ",", "req", "=", "\"GET\"", ",", "data", "=", "None", ")", ":", "load_variables", "(", ")", "return", "_rest", "(", "base_url", "+", "url", ",", "req", ",", "data", ")" ]
34.111111
19.666667
def persist_block(self, block: 'BaseBlock' ) -> Tuple[Tuple[Hash32, ...], Tuple[Hash32, ...]]: """ Persist the given block's header and uncles. Assumes all block transactions have been persisted already. """ with self.db.atomic_batch()...
[ "def", "persist_block", "(", "self", ",", "block", ":", "'BaseBlock'", ")", "->", "Tuple", "[", "Tuple", "[", "Hash32", ",", "...", "]", ",", "Tuple", "[", "Hash32", ",", "...", "]", "]", ":", "with", "self", ".", "db", ".", "atomic_batch", "(", ")...
36.8
14
def formula_to_dictionary(formula='', thickness=np.NaN, density=np.NaN, database='ENDF_VII'): """create dictionary based on formula given Parameters: =========== formula: string ex: 'AgCo2' ex: 'Ag' thickness: float (in mm) default is np.NaN density: float (in g/cm3) default i...
[ "def", "formula_to_dictionary", "(", "formula", "=", "''", ",", "thickness", "=", "np", ".", "NaN", ",", "density", "=", "np", ".", "NaN", ",", "database", "=", "'ENDF_VII'", ")", ":", "if", "'.'", "in", "formula", ":", "raise", "ValueError", "(", "\"f...
38.2
21.366667
def hash64(key, seed): """ Wrapper around mmh3.hash64 to get us single 64-bit value. This also does the extra work of ensuring that we always treat the returned values as big-endian unsigned long, like smhasher used to do. """ hash_val = mmh3.hash64(key, seed)[0] return struct.unpack('>...
[ "def", "hash64", "(", "key", ",", "seed", ")", ":", "hash_val", "=", "mmh3", ".", "hash64", "(", "key", ",", "seed", ")", "[", "0", "]", "return", "struct", ".", "unpack", "(", "'>Q'", ",", "struct", ".", "pack", "(", "'q'", ",", "hash_val", ")",...
34.5
19.3
def _initial_placement(movable_vertices, vertices_resources, machine, random): """For internal use. Produces a random, sequential initial placement, updating the resource availabilities of every core in the supplied machine. Parameters ---------- movable_vertices : {vertex, ...} A set of th...
[ "def", "_initial_placement", "(", "movable_vertices", ",", "vertices_resources", ",", "machine", ",", "random", ")", ":", "# Initially fill chips in the system in a random order", "locations", "=", "list", "(", "machine", ")", "random", ".", "shuffle", "(", "locations",...
35.620253
20.455696
def vectorize_dialogue_ohe(self, dia): """ Take in a dialogue (a sequence of tokenized utterances) and transform it into a sequence of sequences of one-hot vectors """ # we squeeze it because it's coming out with an extra empty # dimension at the front of the shape: (1 x ...
[ "def", "vectorize_dialogue_ohe", "(", "self", ",", "dia", ")", ":", "# we squeeze it because it's coming out with an extra empty", "# dimension at the front of the shape: (1 x dia x utt x word)", "return", "np", ".", "array", "(", "[", "[", "self", ".", "vectorize_utterance_ohe...
52.25
20
def _replace_fields(self, json_dict): """ Delete this object's attributes, and replace with those in json_dict. """ for key in self._json_dict.keys(): if not key.startswith("_"): delattr(self, key) self._json_dict = json_dict self._set_...
[ "def", "_replace_fields", "(", "self", ",", "json_dict", ")", ":", "for", "key", "in", "self", ".", "_json_dict", ".", "keys", "(", ")", ":", "if", "not", "key", ".", "startswith", "(", "\"_\"", ")", ":", "delattr", "(", "self", ",", "key", ")", "s...
32.8
5.2
def generate_doc(self, dir_name, vasprun_files): """ Process aflow style runs, where each run is actually a combination of two vasp runs. """ try: fullpath = os.path.abspath(dir_name) # Defensively copy the additional fields first. This is a MUST. ...
[ "def", "generate_doc", "(", "self", ",", "dir_name", ",", "vasprun_files", ")", ":", "try", ":", "fullpath", "=", "os", ".", "path", ".", "abspath", "(", "dir_name", ")", "# Defensively copy the additional fields first. This is a MUST.", "# Otherwise, parallel updates ...
49.706667
20.56
def centroid_sources(data, xpos, ypos, box_size=11, footprint=None, error=None, mask=None, centroid_func=centroid_com): """ Calculate the centroid of sources at the defined positions. A cutout image centered on each input position will be used to calculate the centroid position. T...
[ "def", "centroid_sources", "(", "data", ",", "xpos", ",", "ypos", ",", "box_size", "=", "11", ",", "footprint", "=", "None", ",", "error", "=", "None", ",", "mask", "=", "None", ",", "centroid_func", "=", "centroid_com", ")", ":", "xpos", "=", "np", ...
39.290323
21.741935
def ephemeral(*, port: int = 6060, timeout_connection: int = 30, verbose: bool = False ) -> Iterator[Client]: """ Launches an ephemeral server instance that will be immediately close when no longer in context. Parameters: port: the port th...
[ "def", "ephemeral", "(", "*", ",", "port", ":", "int", "=", "6060", ",", "timeout_connection", ":", "int", "=", "30", ",", "verbose", ":", "bool", "=", "False", ")", "->", "Iterator", "[", "Client", "]", ":", "url", "=", "\"http://127.0.0.1:{}\"", ".",...
36.034483
15.068966
def compact(self, revision, physical=False): """ Compact the event history in etcd up to a given revision. All superseded keys with a revision less than the compaction revision will be removed. :param revision: revision for the compaction operation :param physical: if s...
[ "def", "compact", "(", "self", ",", "revision", ",", "physical", "=", "False", ")", ":", "compact_request", "=", "etcdrpc", ".", "CompactionRequest", "(", "revision", "=", "revision", ",", "physical", "=", "physical", ")", "self", ".", "kvstub", ".", "Comp...
41.761905
20.904762
def write(self, address, data, x, y, p=0): """Write a bytestring to an address in memory. It is strongly encouraged to only read and write to blocks of memory allocated using :py:meth:`.sdram_alloc`. Additionally, :py:meth:`.sdram_alloc_as_filelike` can be used to safely wrap re...
[ "def", "write", "(", "self", ",", "address", ",", "data", ",", "x", ",", "y", ",", "p", "=", "0", ")", ":", "# Call the SCPConnection to perform the write on our behalf", "connection", "=", "self", ".", "_get_connection", "(", "x", ",", "y", ")", "return", ...
47.913043
21.695652
def available_digests(family=None, name=None): """ Return names of available generators :param family: name of hash-generator family to select :param name: name of hash-generator to select :return: set of int """ generators = WHash.available_generators(family=family, name=name) return set([WHash.generat...
[ "def", "available_digests", "(", "family", "=", "None", ",", "name", "=", "None", ")", ":", "generators", "=", "WHash", ".", "available_generators", "(", "family", "=", "family", ",", "name", "=", "name", ")", "return", "set", "(", "[", "WHash", ".", "...
36.2
19.3
def rebase_event(self, event): """ Rebase the coordinates of the passed event to frame-relative coordinates. :param event: The event to be rebased. :returns: A new event object appropriately re-based. """ new_event = copy(event) if isinstance(new_event, MouseEven...
[ "def", "rebase_event", "(", "self", ",", "event", ")", ":", "new_event", "=", "copy", "(", "event", ")", "if", "isinstance", "(", "new_event", ",", "MouseEvent", ")", ":", "origin", "=", "self", ".", "_canvas", ".", "origin", "new_event", ".", "x", "-=...
37.5
12.928571
def soft_target_update(self): """ Soft update model parameters: .. math:: \\theta_target = \\tau \\times \\theta_local + (1 - \\tau) \\times \\theta_target , with \\tau \\ll 1 See https://arxiv.org/pdf/1509.02971.pdf """ for target_param, local_param in zip(self.target.parameters()...
[ "def", "soft_target_update", "(", "self", ")", ":", "for", "target_param", ",", "local_param", "in", "zip", "(", "self", ".", "target", ".", "parameters", "(", ")", ",", "self", ".", "local", ".", "parameters", "(", ")", ")", ":", "target_param", ".", ...
36.166667
25.333333
def clear(self, context=None): """ Delete all data from the graph. """ context = URIRef(context).n3() if context is not None else '?g' query = """ DELETE { GRAPH %s { ?s ?p ?o } } WHERE { GRAPH %s { ?s ?p ?o } } """ % (context, context) self.parent.graph.update(query)
[ "def", "clear", "(", "self", ",", "context", "=", "None", ")", ":", "context", "=", "URIRef", "(", "context", ")", ".", "n3", "(", ")", "if", "context", "is", "not", "None", "else", "'?g'", "query", "=", "\"\"\"\n DELETE { GRAPH %s { ?s ?p ?o } } ...
44.857143
11.142857
def get_traffic_items(self): """ :return: dictionary {name: object} of all traffic items. """ traffic = self.get_child_static('traffic') return {o.obj_name(): o for o in traffic.get_objects_or_children_by_type('trafficItem')}
[ "def", "get_traffic_items", "(", "self", ")", ":", "traffic", "=", "self", ".", "get_child_static", "(", "'traffic'", ")", "return", "{", "o", ".", "obj_name", "(", ")", ":", "o", "for", "o", "in", "traffic", ".", "get_objects_or_children_by_type", "(", "'...
37.142857
20.285714
def processRequest(self, request: Request, frm: str): """ Handle a REQUEST from the client. If the request has already been executed, the node re-sends the reply to the client. Otherwise, the node acknowledges the client request, adds it to its list of client requests, and sends ...
[ "def", "processRequest", "(", "self", ",", "request", ":", "Request", ",", "frm", ":", "str", ")", ":", "logger", ".", "debug", "(", "\"{} received client request: {} from {}\"", ".", "format", "(", "self", ".", "name", ",", "request", ",", "frm", ")", ")"...
42.046154
21.523077
def get_broadcast_shape(*tensors): """Get broadcast shape as a Python list of integers (preferred) or `Tensor`. Args: *tensors: One or more `Tensor` objects (already converted!). Returns: broadcast shape: Python list (if shapes determined statically), otherwise an `int32` `Tensor`. """ # Try...
[ "def", "get_broadcast_shape", "(", "*", "tensors", ")", ":", "# Try static.", "s_shape", "=", "tensors", "[", "0", "]", ".", "shape", "for", "t", "in", "tensors", "[", "1", ":", "]", ":", "s_shape", "=", "tf", ".", "broadcast_static_shape", "(", "s_shape...
31.227273
19.818182
def getMouse(self): """ Waits for a mouse click. """ # FIXME: this isn't working during an executing cell self.mouse_x.value = -1 self.mouse_y.value = -1 while self.mouse_x.value == -1 and self.mouse_y.value == -1: time.sleep(.1) return (self.m...
[ "def", "getMouse", "(", "self", ")", ":", "# FIXME: this isn't working during an executing cell", "self", ".", "mouse_x", ".", "value", "=", "-", "1", "self", ".", "mouse_y", ".", "value", "=", "-", "1", "while", "self", ".", "mouse_x", ".", "value", "==", ...
34.4
12.4
def refreshFromTarget(self, level=0): """ Refreshes the configuration tree from the target it monitors (if present). Recursively call _refreshNodeFromTarget for itself and all children. Subclasses should typically override _refreshNodeFromTarget instead of this function. Duri...
[ "def", "refreshFromTarget", "(", "self", ",", "level", "=", "0", ")", ":", "if", "self", ".", "getRefreshBlocked", "(", ")", ":", "logger", ".", "debug", "(", "\"_refreshNodeFromTarget blocked\"", ")", "return", "if", "False", "and", "level", "==", "0", ":...
46.25
20.5625
def _convert_xml_to_service_properties(response): ''' <?xml version="1.0" encoding="utf-8"?> <StorageServiceProperties> <Logging> <Version>version-number</Version> <Delete>true|false</Delete> <Read>true|false</Read> <Write>true|false</Write> ...
[ "def", "_convert_xml_to_service_properties", "(", "response", ")", ":", "if", "response", "is", "None", "or", "response", ".", "body", "is", "None", ":", "return", "None", "service_properties_element", "=", "ETree", ".", "fromstring", "(", "response", ".", "body...
42.552239
22.910448
def convert(ast): """Convert BEL1 AST Function to BEL2 AST Function""" if ast and ast.type == "Function": # Activity function conversion if ( ast.name != "molecularActivity" and ast.name in spec["namespaces"]["Activity"]["list"] ): print("name", ast.n...
[ "def", "convert", "(", "ast", ")", ":", "if", "ast", "and", "ast", ".", "type", "==", "\"Function\"", ":", "# Activity function conversion", "if", "(", "ast", ".", "name", "!=", "\"molecularActivity\"", "and", "ast", ".", "name", "in", "spec", "[", "\"name...
32.609756
20.02439
def ssh_config(self, name=''): """ Get the SSH parameters for connecting to a vagrant VM. """ r = self.local_renderer with self.settings(hide('running')): output = r.local('vagrant ssh-config %s' % name, capture=True) config = {} for line in output.sp...
[ "def", "ssh_config", "(", "self", ",", "name", "=", "''", ")", ":", "r", "=", "self", ".", "local_renderer", "with", "self", ".", "settings", "(", "hide", "(", "'running'", ")", ")", ":", "output", "=", "r", ".", "local", "(", "'vagrant ssh-config %s'"...
33
14.076923
def init(self, acct: Account, payer_acct: Account, gas_limit: int, gas_price: int) -> str: """ This interface is used to call the TotalSupply method in ope4 that initialize smart contract parameter. :param acct: an Account class that used to sign the transaction. :param payer_ac...
[ "def", "init", "(", "self", ",", "acct", ":", "Account", ",", "payer_acct", ":", "Account", ",", "gas_limit", ":", "int", ",", "gas_price", ":", "int", ")", "->", "str", ":", "func", "=", "InvokeFunction", "(", "'init'", ")", "tx_hash", "=", "self", ...
55.933333
27.933333
def _update_index(self, axis, key, value): """Update the current axis index based on a given key or value This is an internal method designed to set the origin or step for an index, whilst updating existing Index arrays as appropriate Examples -------- >>> self._update_...
[ "def", "_update_index", "(", "self", ",", "axis", ",", "key", ",", "value", ")", ":", "# delete current value if given None", "if", "value", "is", "None", ":", "return", "delattr", "(", "self", ",", "key", ")", "_key", "=", "\"_{}\"", ".", "format", "(", ...
31.111111
16.866667
def download_file(filename, session): """ Downloads a file """ print('Downloading file %s' % filename) infilesource = os.path.join('sftp://' + ADDRESS + WORKING_DIR, filename) infiletarget = os.path.join(os.getcwd(), filename) incoming = saga.filesystem.File(infileso...
[ "def", "download_file", "(", "filename", ",", "session", ")", ":", "print", "(", "'Downloading file %s'", "%", "filename", ")", "infilesource", "=", "os", ".", "path", ".", "join", "(", "'sftp://'", "+", "ADDRESS", "+", "WORKING_DIR", ",", "filename", ")", ...
51
15
def batch_filter(self, Zs,update_first=False, saver=False): """ Batch processes a sequences of measurements. Parameters ---------- Zs : list-like list of measurements at each time step `self.dt` Missing measurements must be represented by 'None'. update_...
[ "def", "batch_filter", "(", "self", ",", "Zs", ",", "update_first", "=", "False", ",", "saver", "=", "False", ")", ":", "n", "=", "np", ".", "size", "(", "Zs", ",", "0", ")", "# mean estimates from H-Infinity Filter", "means", "=", "zeros", "(", "(", "...
31.964912
19.350877
def expand(expression): """ Expand a reference expression to individual spans. Also works on space-separated ID lists, although a sequence of space characters will be considered a delimiter. >>> expand('a1') 'a1' >>> expand('a1[3:5]') 'a1[3:5]' >>> expand('a1[3:5+6:7]') 'a1[3:5]...
[ "def", "expand", "(", "expression", ")", ":", "tokens", "=", "[", "]", "for", "(", "pre", ",", "_id", ",", "_range", ")", "in", "robust_ref_re", ".", "findall", "(", "expression", ")", ":", "if", "not", "_range", ":", "tokens", ".", "append", "(", ...
27.777778
19.407407
def _read_stdout(self): """ Reads the child process' stdout and process it. """ output = self._decode(self._process.readAllStandardOutput().data()) if self._formatter: self._formatter.append_message(output, output_format=OutputFormat.NormalMessageFormat) else:...
[ "def", "_read_stdout", "(", "self", ")", ":", "output", "=", "self", ".", "_decode", "(", "self", ".", "_process", ".", "readAllStandardOutput", "(", ")", ".", "data", "(", ")", ")", "if", "self", ".", "_formatter", ":", "self", ".", "_formatter", ".",...
39.222222
18.333333
def _group_changes(cur, wanted, remove=False): ''' Determine if the groups need to be changed ''' old = set(cur) new = set(wanted) if (remove and old != new) or (not remove and not new.issubset(old)): return True return False
[ "def", "_group_changes", "(", "cur", ",", "wanted", ",", "remove", "=", "False", ")", ":", "old", "=", "set", "(", "cur", ")", "new", "=", "set", "(", "wanted", ")", "if", "(", "remove", "and", "old", "!=", "new", ")", "or", "(", "not", "remove",...
28.111111
21.888889
async def write_non_secret(self, storec: StorageRecord, replace_meta: bool = False) -> StorageRecord: """ Add or update non-secret storage record to the wallet; return resulting wallet non-secret record. :param storec: non-secret storage record :param replace_meta: whether to replace an...
[ "async", "def", "write_non_secret", "(", "self", ",", "storec", ":", "StorageRecord", ",", "replace_meta", ":", "bool", "=", "False", ")", "->", "StorageRecord", ":", "LOGGER", ".", "debug", "(", "'Wallet.write_non_secret >>> storec: %s, replace_meta: %s'", ",", "st...
42.943662
24.352113
def get_cpu_info(): ''' Returns the CPU info by using the best sources of information for your OS. Returns the result in a dict ''' import json output = get_cpu_info_json() # Convert JSON to Python with non unicode strings output = json.loads(output, object_hook = _utf_to_str) return output
[ "def", "get_cpu_info", "(", ")", ":", "import", "json", "output", "=", "get_cpu_info_json", "(", ")", "# Convert JSON to Python with non unicode strings", "output", "=", "json", ".", "loads", "(", "output", ",", "object_hook", "=", "_utf_to_str", ")", "return", "o...
20.785714
27.785714
def build_from_file(self, dockerfile, tag, **kwargs): """ Builds a docker image from the given :class:`~dockermap.build.dockerfile.DockerFile`. Use this as a shortcut to :meth:`build_from_context`, if no extra data is added to the context. :param dockerfile: An instance of :class:`~dock...
[ "def", "build_from_file", "(", "self", ",", "dockerfile", ",", "tag", ",", "*", "*", "kwargs", ")", ":", "with", "DockerContext", "(", "dockerfile", ",", "finalize", "=", "True", ")", "as", "ctx", ":", "return", "self", ".", "build_from_context", "(", "c...
50.466667
23
def edit(self): """ Edit the SSH Key """ input_params = { "name": self.name, "public_key": self.public_key, } data = self.get_data( "account/keys/%s" % self.id, type=PUT, params=input_params ) ...
[ "def", "edit", "(", "self", ")", ":", "input_params", "=", "{", "\"name\"", ":", "self", ".", "name", ",", "\"public_key\"", ":", "self", ".", "public_key", ",", "}", "data", "=", "self", ".", "get_data", "(", "\"account/keys/%s\"", "%", "self", ".", "...
21.117647
16.058824
def set_sim_data(inj, field, data): """Sets data of a SimInspiral instance.""" try: sim_field = sim_inspiral_map[field] except KeyError: sim_field = field # for tc, map to geocentric times if sim_field == 'tc': inj.geocent_end_time = int(data) inj.geocent_end_time_ns ...
[ "def", "set_sim_data", "(", "inj", ",", "field", ",", "data", ")", ":", "try", ":", "sim_field", "=", "sim_inspiral_map", "[", "field", "]", "except", "KeyError", ":", "sim_field", "=", "field", "# for tc, map to geocentric times", "if", "sim_field", "==", "'t...
31.5
11.666667
def get_cfn_parameters(self): """Return a dictionary of variables with `type` :class:`CFNType`. Returns: dict: variables that need to be submitted as CloudFormation Parameters. """ variables = self.get_variables() output = {} for key, value i...
[ "def", "get_cfn_parameters", "(", "self", ")", ":", "variables", "=", "self", ".", "get_variables", "(", ")", "output", "=", "{", "}", "for", "key", ",", "value", "in", "variables", ".", "items", "(", ")", ":", "if", "hasattr", "(", "value", ",", "\"...
32.785714
16.5
def write_manifest(self): """ Write the manifest content to the zip file. It must be a predictable order. """ config = configparser.ConfigParser() config.add_section('Manifest') for f in sorted(self.manifest.keys()): config.set('Manifest', f.replace(...
[ "def", "write_manifest", "(", "self", ")", ":", "config", "=", "configparser", ".", "ConfigParser", "(", ")", "config", ".", "add_section", "(", "'Manifest'", ")", "for", "f", "in", "sorted", "(", "self", ".", "manifest", ".", "keys", "(", ")", ")", ":...
31.058824
17.294118
def cancel_hardware(self, hardware_id, reason='unneeded', comment='', immediate=False): """Cancels the specified dedicated server. Example:: # Cancels hardware id 1234 result = mgr.cancel_hardware(hardware_id=1234) :param int hardware_id: The ID of the hardware to be c...
[ "def", "cancel_hardware", "(", "self", ",", "hardware_id", ",", "reason", "=", "'unneeded'", ",", "comment", "=", "''", ",", "immediate", "=", "False", ")", ":", "# Get cancel reason", "reasons", "=", "self", ".", "get_cancellation_reasons", "(", ")", "cancel_...
54.153846
33.134615
def parse_parameters(self, parameters): """Parses and sets parameters in the model.""" self.parameters = [] for param_name, param_value in parameters.items(): p = Parameter(param_name, param_value) if p: self.parameters.append(p)
[ "def", "parse_parameters", "(", "self", ",", "parameters", ")", ":", "self", ".", "parameters", "=", "[", "]", "for", "param_name", ",", "param_value", "in", "parameters", ".", "items", "(", ")", ":", "p", "=", "Parameter", "(", "param_name", ",", "param...
35.875
13.125
def transform(self, a, b, c, d, e, f): """ Adjust the current transformation state of the current graphics state matrix. Not recommended for the faint of heart. """ a0, b0, c0, d0, e0, f0 = self._currentMatrix self._currentMatrix = (a0 * a + c0 * b, b0 * a + d0 * b, ...
[ "def", "transform", "(", "self", ",", "a", ",", "b", ",", "c", ",", "d", ",", "e", ",", "f", ")", ":", "a0", ",", "b0", ",", "c0", ",", "d0", ",", "e0", ",", "f0", "=", "self", ".", "_currentMatrix", "self", ".", "_currentMatrix", "=", "(", ...
59.1
18.3
def search(self, id_perm): """Search Administrative Permission from by the identifier. :param id_perm: Identifier of the Administrative Permission. Integer value and greater than zero. :return: Following dictionary: :: {'perm': {'ugrupo': < ugrupo_id >, 'permi...
[ "def", "search", "(", "self", ",", "id_perm", ")", ":", "if", "not", "is_valid_int_param", "(", "id_perm", ")", ":", "raise", "InvalidParameterError", "(", "u'The identifier of Administrative Permission is invalid or was not informed.'", ")", "url", "=", "'aperms/get/'", ...
37.607143
26.75
def smove(self, source, destination, member): """Move member from the set at source to the set at destination. This operation is atomic. In every given moment the element will appear to be a member of source or destination for other clients. If the source set does not exist or does not ...
[ "def", "smove", "(", "self", ",", "source", ",", "destination", ",", "member", ")", ":", "return", "self", ".", "_execute", "(", "[", "b'SMOVE'", ",", "source", ",", "destination", ",", "member", "]", ",", "1", ")" ]
42
23.034483
def _ready(self): """ Marks the task as ready for execution. """ if self._has_state(self.COMPLETED) or self._has_state(self.CANCELLED): return self._set_state(self.READY) self.task_spec._on_ready(self)
[ "def", "_ready", "(", "self", ")", ":", "if", "self", ".", "_has_state", "(", "self", ".", "COMPLETED", ")", "or", "self", ".", "_has_state", "(", "self", ".", "CANCELLED", ")", ":", "return", "self", ".", "_set_state", "(", "self", ".", "READY", ")"...
31.75
12
def add_where_clause(self, clause): """ adds a where clause to this statement :param clause: the clause to add :type clause: WhereClause """ if not isinstance(clause, WhereClause): raise StatementException("only instances of WhereClause can be added to stateme...
[ "def", "add_where_clause", "(", "self", ",", "clause", ")", ":", "if", "not", "isinstance", "(", "clause", ",", "WhereClause", ")", ":", "raise", "StatementException", "(", "\"only instances of WhereClause can be added to statements\"", ")", "clause", ".", "set_contex...
42.454545
9.909091
def geometry_within_radius(geometry, center, radius): """ To valid whether point or linestring or polygon is inside a radius around a center Keyword arguments: geometry -- point/linstring/polygon geojson object center -- point geojson object radius -- radius if(geometry inside radiu...
[ "def", "geometry_within_radius", "(", "geometry", ",", "center", ",", "radius", ")", ":", "if", "geometry", "[", "'type'", "]", "==", "'Point'", ":", "return", "point_distance", "(", "geometry", ",", "center", ")", "<=", "radius", "elif", "geometry", "[", ...
38.304348
20.652174
def get_default_repo(self): """ Go through all the repositories defined in the config file and search for a truthy value for the ``default`` key. If there isn't any return None. """ for repo in self.get_repos(): if self.get_safe(repo, 'default') and self.getbo...
[ "def", "get_default_repo", "(", "self", ")", ":", "for", "repo", "in", "self", ".", "get_repos", "(", ")", ":", "if", "self", ".", "get_safe", "(", "repo", ",", "'default'", ")", "and", "self", ".", "getboolean", "(", "repo", ",", "'default'", ")", "...
38.3
19.3
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: IpAccessControlListContext for this IpAccessControlListInstance :rtype: twilio.rest.api.v2010.acc...
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "IpAccessControlListContext", "(", "self", ".", "_version", ",", "account_sid", "=", "self", ".", "_solution", "[", "'account_sid'", "]"...
42.8
22.533333
def get_batched_changesets(self, changesets_request_data): """GetBatchedChangesets. Returns changesets for a given list of changeset Ids. :param :class:`<TfvcChangesetsRequestData> <azure.devops.v5_0.tfvc.models.TfvcChangesetsRequestData>` changesets_request_data: List of changeset IDs. ...
[ "def", "get_batched_changesets", "(", "self", ",", "changesets_request_data", ")", ":", "content", "=", "self", ".", "_serialize", ".", "body", "(", "changesets_request_data", ",", "'TfvcChangesetsRequestData'", ")", "response", "=", "self", ".", "_send", "(", "ht...
62.833333
26.916667
def distance_to_semi_arc(alon, alat, aazimuth, plons, plats): """ In this method we use a reference system centerd on (alon, alat) and with the y-axis corresponding to aazimuth direction to calculate the minimum distance from a semiarc with generates in (alon, alat). Parameters are the same as for ...
[ "def", "distance_to_semi_arc", "(", "alon", ",", "alat", ",", "aazimuth", ",", "plons", ",", "plats", ")", ":", "if", "type", "(", "plons", ")", "is", "float", ":", "plons", "=", "numpy", ".", "array", "(", "[", "plons", "]", ")", "plats", "=", "nu...
43.754717
24.018868
def get_field_info(model): """ Given a model class, returns a `FieldInfo` instance, which is a `namedtuple`, containing metadata about the various field types on the model including information about their relationships. """ # Deal with the primary key. if issubclass(model, mongoengine.Embed...
[ "def", "get_field_info", "(", "model", ")", ":", "# Deal with the primary key.", "if", "issubclass", "(", "model", ",", "mongoengine", ".", "EmbeddedDocument", ")", ":", "pk", "=", "None", "else", ":", "pk", "=", "model", ".", "_fields", "[", "model", ".", ...
32.34
16.98