text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def generate_signature(payload, secret): '''use an endpoint specific payload and client secret to generate a signature for the request''' payload = _encode(payload) secret = _encode(secret) return hmac.new(secret, digestmod=hashlib.sha256, msg=payload).hexdigest()
[ "def", "generate_signature", "(", "payload", ",", "secret", ")", ":", "payload", "=", "_encode", "(", "payload", ")", "secret", "=", "_encode", "(", "secret", ")", "return", "hmac", ".", "new", "(", "secret", ",", "digestmod", "=", "hashlib", ".", "sha25...
42.571429
10.571429
def generate(cls): """ Generates a random :class:`~PrivateKey` object :rtype: :class:`~PrivateKey` """ return cls(libnacl.randombytes(PrivateKey.SIZE), encoder=encoding.RawEncoder)
[ "def", "generate", "(", "cls", ")", ":", "return", "cls", "(", "libnacl", ".", "randombytes", "(", "PrivateKey", ".", "SIZE", ")", ",", "encoder", "=", "encoding", ".", "RawEncoder", ")" ]
30.714286
17.857143
def set_defaults(self, address): """ Set defaults If a message has different than low priority or NO_RTR set, then this method needs override in subclass :return: None """ if address is not None: self.set_address(address) self.set_...
[ "def", "set_defaults", "(", "self", ",", "address", ")", ":", "if", "address", "is", "not", "None", ":", "self", ".", "set_address", "(", "address", ")", "self", ".", "set_low_priority", "(", ")", "self", ".", "set_no_rtr", "(", ")" ]
26.846154
15
def _check_valid_data(self, data): """Checks that the incoming data is a 3 x #elements ndarray of normal vectors. Parameters ---------- data : :obj:`numpy.ndarray` The data to verify. Raises ------ ValueError If the data is not of...
[ "def", "_check_valid_data", "(", "self", ",", "data", ")", ":", "if", "data", ".", "dtype", ".", "type", "!=", "np", ".", "float32", "and", "data", ".", "dtype", ".", "type", "!=", "np", ".", "float64", ":", "raise", "ValueError", "(", "'Must initializ...
45.217391
27.652174
def do_request(self, method, url, callback_url = None, get = None, post = None, files = None, stream = False, is_json = True): if files == {}: files = None self._multipart = files is not None header = self.get_oauth_header(method, url, callback_url, get, post) if get: full_url = url + "?" + urllib.urlenco...
[ "def", "do_request", "(", "self", ",", "method", ",", "url", ",", "callback_url", "=", "None", ",", "get", "=", "None", ",", "post", "=", "None", ",", "files", "=", "None", ",", "stream", "=", "False", ",", "is_json", "=", "True", ")", ":", "if", ...
36.06
24.66
def make_mujoco_env(env_id, seed, reward_scale=1.0): """ Create a wrapped, monitored gym.Env for MuJoCo. """ rank = MPI.COMM_WORLD.Get_rank() myseed = seed + 1000 * rank if seed is not None else None set_global_seeds(myseed) env = gym.make(env_id) logger_path = None if logger.get_dir() ...
[ "def", "make_mujoco_env", "(", "env_id", ",", "seed", ",", "reward_scale", "=", "1.0", ")", ":", "rank", "=", "MPI", ".", "COMM_WORLD", ".", "Get_rank", "(", ")", "myseed", "=", "seed", "+", "1000", "*", "rank", "if", "seed", "is", "not", "None", "el...
39.6
16.133333
def apply_strain(self, strain): """ Apply a strain to the lattice. Args: strain (float or list): Amount of strain to apply. Can be a float, or a sequence of 3 numbers. E.g., 0.01 means all lattice vectors are increased by 1%. This is equivalent to cal...
[ "def", "apply_strain", "(", "self", ",", "strain", ")", ":", "s", "=", "(", "1", "+", "np", ".", "array", "(", "strain", ")", ")", "*", "np", ".", "eye", "(", "3", ")", "self", ".", "lattice", "=", "Lattice", "(", "np", ".", "dot", "(", "self...
41.923077
19.923077
def _build_filename_from_browserstack_json(j): """ Build a useful filename for an image from the screenshot json metadata """ filename = '' device = j['device'] if j['device'] else 'Desktop' if j['state'] == 'done' and j['image_url']: detail = [device, j['os'], j['os_version'], ...
[ "def", "_build_filename_from_browserstack_json", "(", "j", ")", ":", "filename", "=", "''", "device", "=", "j", "[", "'device'", "]", "if", "j", "[", "'device'", "]", "else", "'Desktop'", "if", "j", "[", "'state'", "]", "==", "'done'", "and", "j", "[", ...
47.454545
17.272727
def make_replacement_visitor(find_expression, replace_expression): """Return a visitor function that replaces every instance of one expression with another one.""" def visitor_fn(expression): """Return the replacement if this expression matches the expression we're looking for.""" if expression ...
[ "def", "make_replacement_visitor", "(", "find_expression", ",", "replace_expression", ")", ":", "def", "visitor_fn", "(", "expression", ")", ":", "\"\"\"Return the replacement if this expression matches the expression we're looking for.\"\"\"", "if", "expression", "==", "find_exp...
43.5
13.6
def store_records_for_package(self, entry_point, records): """ Store the records in a way that permit lookup by package """ # If provided records already exist in the module mapping list, # it likely means that a package declared multiple keys for the # same package name...
[ "def", "store_records_for_package", "(", "self", ",", "entry_point", ",", "records", ")", ":", "# If provided records already exist in the module mapping list,", "# it likely means that a package declared multiple keys for the", "# same package namespace; while normally this does not happen,...
48.166667
20.5
def _find_edge_intersections(self): """ Return a dictionary containing, for each edge in self.edges, a list of the positions at which the edge should be split. """ edges = self.pts[self.edges] cuts = {} # { edge: [(intercept, point), ...], ... } for i in range(ed...
[ "def", "_find_edge_intersections", "(", "self", ")", ":", "edges", "=", "self", ".", "pts", "[", "self", ".", "edges", "]", "cuts", "=", "{", "}", "# { edge: [(intercept, point), ...], ... }", "for", "i", "in", "range", "(", "edges", ".", "shape", "[", "0"...
41.021277
13.489362
def decline_weak_feminine_noun(ns: str, gs: str, np: str): """ Gives the full declension of weak feminine nouns. >>> decline_weak_feminine_noun("saga", "sögu", "sögur") saga sögu sögu sögu sögur sögur sögum sagna >>> decline_weak_feminine_noun("kona", "konu", "konur") ...
[ "def", "decline_weak_feminine_noun", "(", "ns", ":", "str", ",", "gs", ":", "str", ",", "np", ":", "str", ")", ":", "if", "ns", "[", "-", "1", "]", "==", "\"i\"", "and", "gs", "[", "-", "1", "]", "==", "\"i\"", "and", "not", "np", ":", "print",...
16.040984
27.762295
def get_line_numbers(self, buffer): """ Return a (start_line, end_line) pair. """ # Get absolute cursor positions from the text object. from_, to = self.operator_range(buffer.document) from_ += buffer.cursor_position to += buffer.cursor_position # Take th...
[ "def", "get_line_numbers", "(", "self", ",", "buffer", ")", ":", "# Get absolute cursor positions from the text object.", "from_", ",", "to", "=", "self", ".", "operator_range", "(", "buffer", ".", "document", ")", "from_", "+=", "buffer", ".", "cursor_position", ...
34.857143
14.428571
def blog_recent_posts(limit=5, tag=None, username=None, category=None): """ Put a list of recently published blog posts into the template context. A tag title or slug, category title or slug or author's username can also be specified to filter the recent posts returned. Usage:: {% blog_rec...
[ "def", "blog_recent_posts", "(", "limit", "=", "5", ",", "tag", "=", "None", ",", "username", "=", "None", ",", "category", "=", "None", ")", ":", "blog_posts", "=", "BlogPost", ".", "objects", ".", "published", "(", ")", ".", "select_related", "(", "\...
39
20.714286
def exitClient(self): """Teardown button handler.""" self.sendRtspRequest(self.TEARDOWN) #self.handler() os.remove(CACHE_FILE_NAME + str(self.sessionId) + CACHE_FILE_EXT) # Delete the cache image from video rate = float(self.counter/self.frameNbr) print('-'*60 + "\nRTP Packet Loss Rate :" + str(...
[ "def", "exitClient", "(", "self", ")", ":", "self", ".", "sendRtspRequest", "(", "self", ".", "TEARDOWN", ")", "#self.handler()", "os", ".", "remove", "(", "CACHE_FILE_NAME", "+", "str", "(", "self", ".", "sessionId", ")", "+", "CACHE_FILE_EXT", ")", "# De...
43.75
21
def get_suggested_filename(metadata): """Generate a filename for a song based on metadata. Parameters: metadata (dict): A metadata dict. Returns: A filename. """ if metadata.get('title') and metadata.get('track_number'): suggested_filename = '{track_number:0>2} {title}'.format(**metadata) elif metadata.g...
[ "def", "get_suggested_filename", "(", "metadata", ")", ":", "if", "metadata", ".", "get", "(", "'title'", ")", "and", "metadata", ".", "get", "(", "'track_number'", ")", ":", "suggested_filename", "=", "'{track_number:0>2} {title}'", ".", "format", "(", "*", "...
32.3
23.65
def post(self, body=None, params=None): """ `<https://www.elastic.co/guide/en/x-pack/current/license-management.html>`_ :arg body: licenses to be installed :arg acknowledge: whether the user has acknowledged acknowledge messages (default: false) """ return se...
[ "def", "post", "(", "self", ",", "body", "=", "None", ",", "params", "=", "None", ")", ":", "return", "self", ".", "transport", ".", "perform_request", "(", "\"PUT\"", ",", "\"/_license\"", ",", "params", "=", "params", ",", "body", "=", "body", ")" ]
36.909091
17.454545
def parse_config_file(path: str, final: bool = True) -> None: """Parses global options from a config file. See `OptionParser.parse_config_file`. """ return options.parse_config_file(path, final=final)
[ "def", "parse_config_file", "(", "path", ":", "str", ",", "final", ":", "bool", "=", "True", ")", "->", "None", ":", "return", "options", ".", "parse_config_file", "(", "path", ",", "final", "=", "final", ")" ]
35.333333
12.833333
def mkdir(dirname, overwrite=False): """ Wraps around os.mkdir(), but checks for existence first. """ if op.isdir(dirname): if overwrite: shutil.rmtree(dirname) os.mkdir(dirname) logging.debug("Overwrite folder `{0}`.".format(dirname)) else: ...
[ "def", "mkdir", "(", "dirname", ",", "overwrite", "=", "False", ")", ":", "if", "op", ".", "isdir", "(", "dirname", ")", ":", "if", "overwrite", ":", "shutil", ".", "rmtree", "(", "dirname", ")", "os", ".", "mkdir", "(", "dirname", ")", "logging", ...
27.842105
17.631579
def get_annotation(self, key, result_format='list'): """ Is a convenience method for accessing annotations on models that have them """ value = self.get('_annotations_by_key', {}).get(key) if not value: return value if result_format == 'one': retu...
[ "def", "get_annotation", "(", "self", ",", "key", ",", "result_format", "=", "'list'", ")", ":", "value", "=", "self", ".", "get", "(", "'_annotations_by_key'", ",", "{", "}", ")", ".", "get", "(", "key", ")", "if", "not", "value", ":", "return", "va...
28.5
19
def encoding(self) -> _Encoding: """The encoding string to be used, extracted from the HTML and :class:`HTMLResponse <HTMLResponse>` headers. """ if self._encoding: return self._encoding # Scan meta tags for charset. if self._html: self._encoding ...
[ "def", "encoding", "(", "self", ")", "->", "_Encoding", ":", "if", "self", ".", "_encoding", ":", "return", "self", ".", "_encoding", "# Scan meta tags for charset.", "if", "self", ".", "_html", ":", "self", ".", "_encoding", "=", "html_to_unicode", "(", "se...
38.222222
19.944444
def atoms(self): """List of :class:`Atoms <pubchempy.Atom>` in this Compound.""" return sorted(self._atoms.values(), key=lambda x: x.aid)
[ "def", "atoms", "(", "self", ")", ":", "return", "sorted", "(", "self", ".", "_atoms", ".", "values", "(", ")", ",", "key", "=", "lambda", "x", ":", "x", ".", "aid", ")" ]
50.333333
16
def phase_step(z,Ns,p_step,Nstep): """ Create a one sample per symbol signal containing a phase rotation step Nsymb into the waveform. :param z: complex baseband signal after matched filter :param Ns: number of sample per symbol :param p_step: size in radians of the phase step :param Nstep:...
[ "def", "phase_step", "(", "z", ",", "Ns", ",", "p_step", ",", "Nstep", ")", ":", "nn", "=", "np", ".", "arange", "(", "0", ",", "len", "(", "z", "[", ":", ":", "Ns", "]", ")", ")", "theta", "=", "np", ".", "zeros", "(", "len", "(", "nn", ...
34
14.421053
def expand(self, url): """Expand implementation for Bit.ly Args: url: the URL you want to shorten Returns: A string containing the expanded URL Raises: ExpandingErrorException: If the API Returns an error as response """ expand_url = ...
[ "def", "expand", "(", "self", ",", "url", ")", ":", "expand_url", "=", "f'{self.api_url}v3/expand'", "params", "=", "{", "'shortUrl'", ":", "url", ",", "'access_token'", ":", "self", ".", "api_key", ",", "'format'", ":", "'txt'", ",", "}", "response", "=",...
30.095238
16.857143
def process(self, obj, parent=None, parent_key=None, depth=0): """Recursively process the data for sideloading. Converts the nested representation into a sideloaded representation. """ if isinstance(obj, list): for key, o in enumerate(obj): # traverse into li...
[ "def", "process", "(", "self", ",", "obj", ",", "parent", "=", "None", ",", "parent_key", "=", "None", ",", "depth", "=", "0", ")", ":", "if", "isinstance", "(", "obj", ",", "list", ")", ":", "for", "key", ",", "o", "in", "enumerate", "(", "obj",...
40.051282
17.192308
def connect_qtconsole(connection_file=None, argv=None, profile=None): """Connect a qtconsole to the current kernel. This is useful for connecting a second qtconsole to a kernel, or to a local notebook. Parameters ---------- connection_file : str [optional] The connection file t...
[ "def", "connect_qtconsole", "(", "connection_file", "=", "None", ",", "argv", "=", "None", ",", "profile", "=", "None", ")", ":", "argv", "=", "[", "]", "if", "argv", "is", "None", "else", "argv", "if", "connection_file", "is", "None", ":", "# get connec...
35.4
24.4
def create_parsing_plan(self, desired_type: Type[T], filesystem_object: PersistedObject, logger: Logger, _main_call: bool = True): """ Implements the abstract parent method by using the recursive parsing plan impl. Subclasses wishing to produce their own parsing plans...
[ "def", "create_parsing_plan", "(", "self", ",", "desired_type", ":", "Type", "[", "T", "]", ",", "filesystem_object", ":", "PersistedObject", ",", "logger", ":", "Logger", ",", "_main_call", ":", "bool", "=", "True", ")", ":", "in_root_call", "=", "False", ...
48.461538
30.564103
def _cassist_any(self,dc,dt,dt2,name,nodiag=False,memlimit=-1): """Calculates probability of gene i regulating gene j with continuous data assisted method, with the recommended combination of multiple tests. dc: numpy.ndarray(nt,ns,dtype=ftype(='f4' by default)) Continuous anchor data. Entry dc[i,j] is anchor i's ...
[ "def", "_cassist_any", "(", "self", ",", "dc", ",", "dt", ",", "dt2", ",", "name", ",", "nodiag", "=", "False", ",", "memlimit", "=", "-", "1", ")", ":", "if", "self", ".", "lib", "is", "None", ":", "raise", "ValueError", "(", "\"Not initialized.\"",...
51.836364
24.709091
def merge_xml(first_doc, second_doc): """Merges two XML documents. Args: first_doc (str): First XML document. `second_doc` is merged into this document. second_doc (str): Second XML document. It is merged into the first. Returns: XML Document: The merged document. ...
[ "def", "merge_xml", "(", "first_doc", ",", "second_doc", ")", ":", "# Adapted from:", "# http://stackoverflow.com/questions/27258013/merge-two-xml-files-python", "# Maps each elements tag to the element from the first document", "if", "isinstance", "(", "first_doc", ",", "lxml", "....
38.019608
18.784314
def round(self, value_array): """ Rounds a bandit variable by selecting the closest point in the domain Closest here is defined by euclidian distance Assumes an 1d array of the same length as the single variable value """ distances = np.linalg.norm(np.array(self.domain) -...
[ "def", "round", "(", "self", ",", "value_array", ")", ":", "distances", "=", "np", ".", "linalg", ".", "norm", "(", "np", ".", "array", "(", "self", ".", "domain", ")", "-", "value_array", ",", "axis", "=", "1", ")", "idx", "=", "np", ".", "argmi...
44.666667
16.444444
def list_incomplete_uploads(self, bucket_name, prefix='', recursive=False): """ List all in-complete uploads for a given bucket. Examples: incomplete_uploads = minio.list_incomplete_uploads('foo') for current_upload in incomplete_uploads: ...
[ "def", "list_incomplete_uploads", "(", "self", ",", "bucket_name", ",", "prefix", "=", "''", ",", "recursive", "=", "False", ")", ":", "is_valid_bucket_name", "(", "bucket_name", ")", "return", "self", ".", "_list_incomplete_uploads", "(", "bucket_name", ",", "p...
40.111111
21.622222
def convert_to_timezone_naive(time_to_freeze): """ Converts a potentially timezone-aware datetime to be a naive UTC datetime """ if time_to_freeze.tzinfo: time_to_freeze -= time_to_freeze.utcoffset() time_to_freeze = time_to_freeze.replace(tzinfo=None) return time_to_freeze
[ "def", "convert_to_timezone_naive", "(", "time_to_freeze", ")", ":", "if", "time_to_freeze", ".", "tzinfo", ":", "time_to_freeze", "-=", "time_to_freeze", ".", "utcoffset", "(", ")", "time_to_freeze", "=", "time_to_freeze", ".", "replace", "(", "tzinfo", "=", "Non...
37.875
12.625
def io_loop(self): """Access the :class:`tornado.ioloop.IOLoop` instance for the current message. .. versionadded:: 3.18.4 :rtype: :class:`tornado.ioloop.IOLoop` or :data:`None` """ if self._message and self._message.connection: return self._connections[sel...
[ "def", "io_loop", "(", "self", ")", ":", "if", "self", ".", "_message", "and", "self", ".", "_message", ".", "connection", ":", "return", "self", ".", "_connections", "[", "self", ".", "_message", ".", "connection", "]", ".", "io_loop" ]
30.909091
21.090909
def get_correlation(self, t1, t2): """ Computes the correlation coefficient for the specified periods. :param float t1: First period of interest. :param float t2: Second period of interest. :return float rho: The predicted correlation coeffi...
[ "def", "get_correlation", "(", "self", ",", "t1", ",", "t2", ")", ":", "t_min", "=", "min", "(", "t1", ",", "t2", ")", "t_max", "=", "max", "(", "t1", ",", "t2", ")", "c1", "=", "1.0", "c1", "-=", "np", ".", "cos", "(", "np", ".", "pi", "/"...
23.409091
23.090909
def _covar_mstep_spherical(*args): """Performing the covariance M step for spherical cases""" cv = _covar_mstep_diag(*args) return np.tile(cv.mean(axis=1)[:, np.newaxis], (1, cv.shape[1]))
[ "def", "_covar_mstep_spherical", "(", "*", "args", ")", ":", "cv", "=", "_covar_mstep_diag", "(", "*", "args", ")", "return", "np", ".", "tile", "(", "cv", ".", "mean", "(", "axis", "=", "1", ")", "[", ":", ",", "np", ".", "newaxis", "]", ",", "(...
49.25
10.25
def _github_count(self, url): """ Get counts for requests that return 'total_count' in the json response. """ url = self.url_api + url + "&per_page=1" # if we have authentication details use them as we get better # rate-limiting. if self.username and self.auth_tok...
[ "def", "_github_count", "(", "self", ",", "url", ")", ":", "url", "=", "self", ".", "url_api", "+", "url", "+", "\"&per_page=1\"", "# if we have authentication details use them as we get better", "# rate-limiting.", "if", "self", ".", "username", "and", "self", ".",...
37.227273
13.590909
def metric_create(self, project, metric_name, filter_, description=None): """API call: create a metric resource. See https://cloud.google.com/logging/docs/reference/v2/rest/v2/projects.metrics/create :type project: str :param project: ID of the project in which to create the m...
[ "def", "metric_create", "(", "self", ",", "project", ",", "metric_name", ",", "filter_", ",", "description", "=", "None", ")", ":", "target", "=", "\"/projects/%s/metrics\"", "%", "(", "project", ",", ")", "data", "=", "{", "\"name\"", ":", "metric_name", ...
38.409091
24.590909
def cyl_to_rect_vec(vr,vt,vz,phi): """ NAME: cyl_to_rect_vec PURPOSE: transform vectors from cylindrical to rectangular coordinate vectors INPUT: vr - radial velocity vt - tangential velocity vz - vertical velocity phi - azimuth OUTPUT: vx,v...
[ "def", "cyl_to_rect_vec", "(", "vr", ",", "vt", ",", "vz", ",", "phi", ")", ":", "vx", "=", "vr", "*", "sc", ".", "cos", "(", "phi", ")", "-", "vt", "*", "sc", ".", "sin", "(", "phi", ")", "vy", "=", "vr", "*", "sc", ".", "sin", "(", "phi...
14.25
25.875
def fermat_potential(self, x_image, y_image, x_source, y_source, kwargs_lens, k=None): """ fermat potential (negative sign means earlier arrival time) :param x_image: image position :param y_image: image position :param x_source: source position :param y_source: source p...
[ "def", "fermat_potential", "(", "self", ",", "x_image", ",", "y_image", ",", "x_source", ",", "y_source", ",", "kwargs_lens", ",", "k", "=", "None", ")", ":", "potential", "=", "self", ".", "potential", "(", "x_image", ",", "y_image", ",", "kwargs_lens", ...
49.466667
25.2
def paw_header(filename, ppdesc): """ Parse the PAW abinit header. Examples: Paw atomic data for element Ni - Generated by AtomPAW (N. Holzwarth) + AtomPAW2Abinit v3.0.5 28.000 18.000 20061204 : zatom,zion,pspdat 7 7 2 0 350 0. : pspcod,...
[ "def", "paw_header", "(", "filename", ",", "ppdesc", ")", ":", "supported_formats", "=", "[", "\"paw3\"", ",", "\"paw4\"", ",", "\"paw5\"", "]", "if", "ppdesc", ".", "format", "not", "in", "supported_formats", ":", "raise", "NotImplementedError", "(", "\"forma...
53.493671
30.531646
def fillup_layer(names): # pylint: disable=arguments-differ """ Creates a layer with InputWire elements. Args: names (list): List of names for the wires. Returns: list: The new layer """ longest = max([len(name) for name in names]) inputs...
[ "def", "fillup_layer", "(", "names", ")", ":", "# pylint: disable=arguments-differ", "longest", "=", "max", "(", "[", "len", "(", "name", ")", "for", "name", "in", "names", "]", ")", "inputs_wires", "=", "[", "]", "for", "name", "in", "names", ":", "inpu...
31.214286
15.642857
def find_candidate_metadata_files(names): """Filter files that may be METADATA files.""" tuples = [ x.split('/') for x in map(try_decode, names) if 'METADATA' in x ] return [x[1] for x in sorted([(len(x), x) for x in tuples])]
[ "def", "find_candidate_metadata_files", "(", "names", ")", ":", "tuples", "=", "[", "x", ".", "split", "(", "'/'", ")", "for", "x", "in", "map", "(", "try_decode", ",", "names", ")", "if", "'METADATA'", "in", "x", "]", "return", "[", "x", "[", "1", ...
39.428571
15.428571
def set_attributes(self, attrs): """ Create new style and output. :param attrs: `Attrs` instance. """ if self.true_color() and not self.ansi_colors_only(): self.write_raw(self._escape_code_cache_true_color[attrs]) else: self.write_raw(self._escape...
[ "def", "set_attributes", "(", "self", ",", "attrs", ")", ":", "if", "self", ".", "true_color", "(", ")", "and", "not", "self", ".", "ansi_colors_only", "(", ")", ":", "self", ".", "write_raw", "(", "self", ".", "_escape_code_cache_true_color", "[", "attrs"...
33
14.8
def set_arc(self, arc): """ Set the ACK retry count for radio communication """ _send_vendor_setup(self.handle, SET_RADIO_ARC, arc, 0, ()) self.arc = arc
[ "def", "set_arc", "(", "self", ",", "arc", ")", ":", "_send_vendor_setup", "(", "self", ".", "handle", ",", "SET_RADIO_ARC", ",", "arc", ",", "0", ",", "(", ")", ")", "self", ".", "arc", "=", "arc" ]
43.5
15.25
def assign_user_policies(user, *policies_roles): """Assign a sequence of policies to a user (or the anonymous user is ``user`` is ``None``). (Also installed as ``assign_policies`` method on ``User`` model. """ clear_user_policies(user) pset = PermissionSet.objects.by_policies_and_roles(policie...
[ "def", "assign_user_policies", "(", "user", ",", "*", "policies_roles", ")", ":", "clear_user_policies", "(", "user", ")", "pset", "=", "PermissionSet", ".", "objects", ".", "by_policies_and_roles", "(", "policies_roles", ")", "pset", ".", "refresh", "(", ")", ...
32.4
16.2
def lookup_basis_by_role(primary_basis, role, data_dir=None): '''Lookup the name of an auxiliary basis set given a primary basis set and role Parameters ---------- primary_basis : str The primary (orbital) basis set that we want the auxiliary basis set for. This is not case sensitive. ...
[ "def", "lookup_basis_by_role", "(", "primary_basis", ",", "role", ",", "data_dir", "=", "None", ")", ":", "data_dir", "=", "fix_data_dir", "(", "data_dir", ")", "role", "=", "role", ".", "lower", "(", ")", "if", "not", "role", "in", "get_roles", "(", ")"...
28.333333
26.688889
def gnuplot_3d_matrix(z_matrix, filename, title='', x_label='', y_label=''): ''' Function to produce a general 3D plot from a 2D matrix. Args: z_matrix (list): 2D matrix. filename (str): Filename of the output image. title (str): Title of the plot. Default is '' (no title). ...
[ "def", "gnuplot_3d_matrix", "(", "z_matrix", ",", "filename", ",", "title", "=", "''", ",", "x_label", "=", "''", ",", "y_label", "=", "''", ")", ":", "_", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "ext", "!="...
24.285714
20.47619
def _collect_values(handlers, names, user, client, values): """ Get the values from the handlers of the requested claims. """ results = {} def visitor(claim_name, func): data = {'user': user, 'client': client} data.update(values.get(claim_name) or {}) claim_value = func(data) ...
[ "def", "_collect_values", "(", "handlers", ",", "names", ",", "user", ",", "client", ",", "values", ")", ":", "results", "=", "{", "}", "def", "visitor", "(", "claim_name", ",", "func", ")", ":", "data", "=", "{", "'user'", ":", "user", ",", "'client...
34.647059
19.411765
def _get_json(location): """Reads JSON data from file or URL.""" location = os.path.expanduser(location) try: if os.path.isfile(location): with io.open(location, encoding="utf-8") as json_data: return json.load(json_data, object_pairs_hook=OrderedDict).get("tests") ...
[ "def", "_get_json", "(", "location", ")", ":", "location", "=", "os", ".", "path", ".", "expanduser", "(", "location", ")", "try", ":", "if", "os", ".", "path", ".", "isfile", "(", "location", ")", ":", "with", "io", ".", "open", "(", "location", "...
47.75
21.3125
def _must_decode(value): """Copied from pkginfo 1.4.1, _compat module.""" if type(value) is bytes: try: return value.decode('utf-8') except UnicodeDecodeError: return value.decode('latin1') return value
[ "def", "_must_decode", "(", "value", ")", ":", "if", "type", "(", "value", ")", "is", "bytes", ":", "try", ":", "return", "value", ".", "decode", "(", "'utf-8'", ")", "except", "UnicodeDecodeError", ":", "return", "value", ".", "decode", "(", "'latin1'",...
30.875
10.875
def acl_show(self, msg, args): """Show current allow and deny blocks for the given acl.""" name = args[0] if len(args) > 0 else None if name is None: return "%s: The following ACLs are defined: %s" % (msg.user, ', '.join(self._acl.keys())) if name not in self._acl: ...
[ "def", "acl_show", "(", "self", ",", "msg", ",", "args", ")", ":", "name", "=", "args", "[", "0", "]", "if", "len", "(", "args", ")", ">", "0", "else", "None", "if", "name", "is", "None", ":", "return", "\"%s: The following ACLs are defined: %s\"", "%"...
42.571429
23.071429
def set_model(self, model): """ Set a model instance for the model being queried. :param model: The model instance :type model: orator.orm.Model :return: The current Builder instance :rtype: Builder """ self._model = model self._query.from_(mode...
[ "def", "set_model", "(", "self", ",", "model", ")", ":", "self", ".", "_model", "=", "model", "self", ".", "_query", ".", "from_", "(", "model", ".", "get_table", "(", ")", ")", "return", "self" ]
22.733333
16.866667
def _format_vector(self, vecs, form='broadcast'): """ Format a 3d vector field in certain ways, see `coords` for a description of each formatting method. """ if form == 'meshed': return np.meshgrid(*vecs, indexing='ij') elif form == 'vector': vecs ...
[ "def", "_format_vector", "(", "self", ",", "vecs", ",", "form", "=", "'broadcast'", ")", ":", "if", "form", "==", "'meshed'", ":", "return", "np", ".", "meshgrid", "(", "*", "vecs", ",", "indexing", "=", "'ij'", ")", "elif", "form", "==", "'vector'", ...
40.357143
16.5
def get_potential_energy(self, a): """Calculate potential energy.""" e = 0.0 for c in self.calcs: e += c.get_potential_energy(a) return e
[ "def", "get_potential_energy", "(", "self", ",", "a", ")", ":", "e", "=", "0.0", "for", "c", "in", "self", ".", "calcs", ":", "e", "+=", "c", ".", "get_potential_energy", "(", "a", ")", "return", "e" ]
29.333333
11.5
def ls_files(client, names, authors, include, exclude, format): """List files in dataset.""" records = _filter( client, names=names, authors=authors, include=include, exclude=exclude ) DATASET_FILES_FORMATS[format](client, records)
[ "def", "ls_files", "(", "client", ",", "names", ",", "authors", ",", "include", ",", "exclude", ",", "format", ")", ":", "records", "=", "_filter", "(", "client", ",", "names", "=", "names", ",", "authors", "=", "authors", ",", "include", "=", "include...
35.714286
23.428571
def getComponentByType(self, tagSet, default=noValue, instantiate=True, innerFlag=False): """Returns |ASN.1| type component by ASN.1 tag. Parameters ---------- tagSet : :py:class:`~pyasn1.type.tag.TagSet` Object representing ASN.1 tags to identify ...
[ "def", "getComponentByType", "(", "self", ",", "tagSet", ",", "default", "=", "noValue", ",", "instantiate", "=", "True", ",", "innerFlag", "=", "False", ")", ":", "componentValue", "=", "self", ".", "getComponentByPosition", "(", "self", ".", "componentType",...
37.083333
20.194444
def check_impl(self): """ returns a tuple of (is_change,description) which are then stored in self.changed and self.description The default implementation will get the data from the left and right sides by calling self.fn_data, then compare them via self.fn_differ. If th...
[ "def", "check_impl", "(", "self", ")", ":", "if", "self", ".", "fn_differ", "(", "self", ".", "get_ldata", "(", ")", ",", "self", ".", "get_rdata", "(", ")", ")", ":", "left", "=", "self", ".", "pretty_ldata_desc", "(", ")", "right", "=", "self", "...
34.090909
21.090909
def ListDir(self, path="temp"): """ Returns a list of files in the specified path (directory), or an empty list if the directory doesn't exist. """ full_path = _os.path.join(self.path_home, path) # only if the path exists! if _os.path.exists(full_path) and _os.pa...
[ "def", "ListDir", "(", "self", ",", "path", "=", "\"temp\"", ")", ":", "full_path", "=", "_os", ".", "path", ".", "join", "(", "self", ".", "path_home", ",", "path", ")", "# only if the path exists!", "if", "_os", ".", "path", ".", "exists", "(", "full...
33.916667
15.583333
def _configure_logger(cls, simple_name, log_dest, detail_level, log_filename, connection, propagate): # pylint: disable=line-too-long """ Configure the pywbem loggers and optionally activate WBEM connections for logging and setting a log detail level. P...
[ "def", "_configure_logger", "(", "cls", ",", "simple_name", ",", "log_dest", ",", "detail_level", ",", "log_filename", ",", "connection", ",", "propagate", ")", ":", "# pylint: disable=line-too-long", "# noqa: E501", "# pylint: enable=line-too-long", "if", "simple_name", ...
43.764706
26.372549
def get_post(id, check_author=True): """Get a post and its author by id. Checks that the id exists and optionally that the current user is the author. :param id: id of post to get :param check_author: require the current user to be the author :return: the post with author information :rais...
[ "def", "get_post", "(", "id", ",", "check_author", "=", "True", ")", ":", "post", "=", "Post", ".", "query", ".", "get_or_404", "(", "id", ",", "f\"Post id {id} doesn't exist.\"", ")", "if", "check_author", "and", "post", ".", "author", "!=", "g", ".", "...
31.388889
20.388889
def error(msg): """Emit an error message to stderr.""" _flush() sys.stderr.write("\033[1;37;41mERROR: {}\033[0m\n".format(msg)) sys.stderr.flush()
[ "def", "error", "(", "msg", ")", ":", "_flush", "(", ")", "sys", ".", "stderr", ".", "write", "(", "\"\\033[1;37;41mERROR: {}\\033[0m\\n\"", ".", "format", "(", "msg", ")", ")", "sys", ".", "stderr", ".", "flush", "(", ")" ]
31.6
19.6
def error(request, message, extra_tags='', fail_silently=False, async=False): """Adds a message with the ``ERROR`` level.""" if ASYNC and async: messages.debug(_get_user(request), message) else: add_message(request, constants.ERROR, message, extra_tags=extra_tags, fail_si...
[ "def", "error", "(", "request", ",", "message", ",", "extra_tags", "=", "''", ",", "fail_silently", "=", "False", ",", "async", "=", "False", ")", ":", "if", "ASYNC", "and", "async", ":", "messages", ".", "debug", "(", "_get_user", "(", "request", ")",...
47.857143
20.142857
def short_stack(): """Return a string summarizing the call stack.""" stack = inspect.stack()[:0:-1] return "\n".join(["%30s : %s @%d" % (t[3],t[1],t[2]) for t in stack])
[ "def", "short_stack", "(", ")", ":", "stack", "=", "inspect", ".", "stack", "(", ")", "[", ":", "0", ":", "-", "1", "]", "return", "\"\\n\"", ".", "join", "(", "[", "\"%30s : %s @%d\"", "%", "(", "t", "[", "3", "]", ",", "t", "[", "1", "]", "...
44.5
15.25
def set_factory(self, thing: type, value, overwrite=False): """ Set the factory for something. """ if thing in self.factories and not overwrite: raise DiayException('factory for %r already exists' % thing) self.factories[thing] = value
[ "def", "set_factory", "(", "self", ",", "thing", ":", "type", ",", "value", ",", "overwrite", "=", "False", ")", ":", "if", "thing", "in", "self", ".", "factories", "and", "not", "overwrite", ":", "raise", "DiayException", "(", "'factory for %r already exist...
40.142857
9.857143
def _initStormLibs(self): ''' Registration for built-in Storm Libraries ''' self.addStormLib(('str',), s_stormtypes.LibStr) self.addStormLib(('time',), s_stormtypes.LibTime)
[ "def", "_initStormLibs", "(", "self", ")", ":", "self", ".", "addStormLib", "(", "(", "'str'", ",", ")", ",", "s_stormtypes", ".", "LibStr", ")", "self", ".", "addStormLib", "(", "(", "'time'", ",", ")", ",", "s_stormtypes", ".", "LibTime", ")" ]
34.666667
19
def resample_to_delta_t(timeseries, delta_t, method='butterworth'): """Resmple the time_series to delta_t Resamples the TimeSeries instance time_series to the given time step, delta_t. Only powers of two and real valued time series are supported at this time. Additional restrictions may apply to partic...
[ "def", "resample_to_delta_t", "(", "timeseries", ",", "delta_t", ",", "method", "=", "'butterworth'", ")", ":", "if", "not", "isinstance", "(", "timeseries", ",", "TimeSeries", ")", ":", "raise", "TypeError", "(", "\"Can only resample time series\"", ")", "if", ...
31.652174
23.913043
def reuse_variables(method): """Wraps an arbitrary method so it does variable sharing. This decorator creates variables the first time it calls `method`, and reuses them for subsequent calls. The object that calls `method` provides a `tf.VariableScope`, either as a `variable_scope` attribute or as the return ...
[ "def", "reuse_variables", "(", "method", ")", ":", "initialized_variable_scopes_eager", "=", "set", "(", ")", "initialized_variable_scopes_graph", "=", "weakref", ".", "WeakKeyDictionary", "(", ")", "# Ensure that the argument passed in is really a method by checking that the", ...
36.242009
23.004566
def add_element(self, element, override=False): """Add an element to the parser. :param element: the element class. :param override: whether to replace the default element based on. .. note:: If one needs to call it inside ``__init__()``, please call it after ``super().__i...
[ "def", "add_element", "(", "self", ",", "element", ",", "override", "=", "False", ")", ":", "if", "issubclass", "(", "element", ",", "inline", ".", "InlineElement", ")", ":", "dest", "=", "self", ".", "inline_elements", "elif", "issubclass", "(", "element"...
36.814815
15.37037
def get_site_type_dummy_variables(self, sites): """ Binary rock/soil classification dummy variable based on sites.vs30. "``S`` is 1 for a rock site and 0 otherwise" (p. 1201). """ is_rock = np.array(sites.vs30 > self.NEHRP_BC_BOUNDARY) return is_rock
[ "def", "get_site_type_dummy_variables", "(", "self", ",", "sites", ")", ":", "is_rock", "=", "np", ".", "array", "(", "sites", ".", "vs30", ">", "self", ".", "NEHRP_BC_BOUNDARY", ")", "return", "is_rock" ]
36.5
18.25
def json_to_string(self, source): """ Serialize JSON structure into string. *Args:*\n _source_ - JSON structure *Returns:*\n JSON string *Raises:*\n JsonValidatorError *Example:*\n | *Settings* | *Value* | | Library | JsonVal...
[ "def", "json_to_string", "(", "self", ",", "source", ")", ":", "try", ":", "load_input_json", "=", "json", ".", "dumps", "(", "source", ")", "except", "ValueError", "as", "e", ":", "raise", "JsonValidatorError", "(", "\"Could serialize '%s' to JSON: %s\"", "%", ...
35.655172
21.793103
def get_first(self): """Return snmp value for the first OID.""" try: # Nested try..except because of Python 2.4 self.lock.acquire() try: return self.get(self.data_idx[0]) except (IndexError, ValueError): return "NONE" finally: self.lock.release()
[ "def", "get_first", "(", "self", ")", ":", "try", ":", "# Nested try..except because of Python 2.4", "self", ".", "lock", ".", "acquire", "(", ")", "try", ":", "return", "self", ".", "get", "(", "self", ".", "data_idx", "[", "0", "]", ")", "except", "(",...
26.3
15.9
def iterate_from_vcf(infile, sample): '''iterate over a vcf-formatted file. *infile* can be any iterator over a lines. The function yields named tuples of the type :class:`pysam.Pileup.PileupSubstitution` or :class:`pysam.Pileup.PileupIndel`. Positions without a snp will be skipped. This...
[ "def", "iterate_from_vcf", "(", "infile", ",", "sample", ")", ":", "vcf", "=", "pysam", ".", "VCF", "(", ")", "vcf", ".", "connect", "(", "infile", ")", "if", "sample", "not", "in", "vcf", ".", "getsamples", "(", ")", ":", "raise", "KeyError", "(", ...
25.666667
18.851852
def _api_key_patch_add(conn, apiKey, pvlist): ''' the add patch operation for a list of (path, value) tuples on an ApiKey resource list path ''' response = conn.update_api_key(apiKey=apiKey, patchOperations=_api_key_patchops('add', pvlist)) return response
[ "def", "_api_key_patch_add", "(", "conn", ",", "apiKey", ",", "pvlist", ")", ":", "response", "=", "conn", ".", "update_api_key", "(", "apiKey", "=", "apiKey", ",", "patchOperations", "=", "_api_key_patchops", "(", "'add'", ",", "pvlist", ")", ")", "return",...
43.571429
28.428571
def mme_match(case_obj, match_type, mme_base_url, mme_token, nodes=None, mme_accepts=None): """Initiate a MatchMaker match against either other Scout patients or external nodes Args: case_obj(dict): a scout case object already submitted to MME match_type(str): 'internal' or 'external' m...
[ "def", "mme_match", "(", "case_obj", ",", "match_type", ",", "mme_base_url", ",", "mme_token", ",", "nodes", "=", "None", ",", "mme_accepts", "=", "None", ")", ":", "query_patients", "=", "[", "]", "server_responses", "=", "[", "]", "url", "=", "None", "...
46.490566
20.509434
def append_index_id(id, ids): """ add index to id to make it unique wrt ids """ index = 1 mod = '%s_%s' % (id, index) while mod in ids: index += 1 mod = '%s_%s' % (id, index) ids.append(mod) return mod, ids
[ "def", "append_index_id", "(", "id", ",", "ids", ")", ":", "index", "=", "1", "mod", "=", "'%s_%s'", "%", "(", "id", ",", "index", ")", "while", "mod", "in", "ids", ":", "index", "+=", "1", "mod", "=", "'%s_%s'", "%", "(", "id", ",", "index", "...
22.181818
12.727273
def applyAndAllocate(self,allocatedPrices,tieredTuples,payAtDoor=False): ''' This method takes an initial allocation of prices across events, and an identical length list of allocation tuples. It applies the rule specified by this discount, allocates the discount across the listed ...
[ "def", "applyAndAllocate", "(", "self", ",", "allocatedPrices", ",", "tieredTuples", ",", "payAtDoor", "=", "False", ")", ":", "initial_net_price", "=", "sum", "(", "[", "x", "for", "x", "in", "allocatedPrices", "]", ")", "if", "self", ".", "discountType", ...
55.339286
32.339286
def _build_validation_payload(self, request): """ Extract relevant information from request to build a ClientValidationJWT :param PreparedRequest request: request we will extract information from. :return: ValidationPayload """ parsed = urlparse(request.url) path ...
[ "def", "_build_validation_payload", "(", "self", ",", "request", ")", ":", "parsed", "=", "urlparse", "(", "request", ".", "url", ")", "path", "=", "parsed", ".", "path", "query_string", "=", "parsed", ".", "query", "or", "''", "return", "ValidationPayload",...
35.5
13.277778
def merge_arena(self, mujoco_arena): """Adds arena model to the MJCF model.""" self.arena = mujoco_arena self.table_top_offset = mujoco_arena.table_top_abs self.table_size = mujoco_arena.table_full_size self.merge(mujoco_arena)
[ "def", "merge_arena", "(", "self", ",", "mujoco_arena", ")", ":", "self", ".", "arena", "=", "mujoco_arena", "self", ".", "table_top_offset", "=", "mujoco_arena", ".", "table_top_abs", "self", ".", "table_size", "=", "mujoco_arena", ".", "table_full_size", "self...
43.666667
8.5
def reverse(self, start=None, end=None): """Reverse bits in-place. start -- Position of first bit to reverse. Defaults to 0. end -- One past the position of the last bit to reverse. Defaults to self.len. Using on an empty bitstring will have no effect. Raises Va...
[ "def", "reverse", "(", "self", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "start", ",", "end", "=", "self", ".", "_validate_slice", "(", "start", ",", "end", ")", "if", "start", "==", "0", "and", "end", "==", "self", ".", "len"...
31.421053
18.263158
def run_fib_with_stats(r): """ Run Fibonacci generator r times. """ for i in range(r): res = fib(PythonInt(FIB)) if RESULT != res: raise ValueError("Expected %d, Got %d" % (RESULT, res))
[ "def", "run_fib_with_stats", "(", "r", ")", ":", "for", "i", "in", "range", "(", "r", ")", ":", "res", "=", "fib", "(", "PythonInt", "(", "FIB", ")", ")", "if", "RESULT", "!=", "res", ":", "raise", "ValueError", "(", "\"Expected %d, Got %d\"", "%", "...
36.166667
13.5
def _clone(self): """ Return a clone of the current search request. Performs a shallow copy of all the underlying objects. Used internally by most state modifying APIs. """ s = super(Search, self)._clone() s._response_class = self._response_class s._sort ...
[ "def", "_clone", "(", "self", ")", ":", "s", "=", "super", "(", "Search", ",", "self", ")", ".", "_clone", "(", ")", "s", ".", "_response_class", "=", "self", ".", "_response_class", "s", ".", "_sort", "=", "self", ".", "_sort", "[", ":", "]", "s...
38.652174
15.347826
def CheckNextIncludeOrder(self, header_type): """Returns a non-empty error message if the next header is out of order. This function also updates the internal state to be ready to check the next include. Args: header_type: One of the _XXX_HEADER constants defined above. Returns: The e...
[ "def", "CheckNextIncludeOrder", "(", "self", ",", "header_type", ")", ":", "error_message", "=", "(", "'Found %s after %s'", "%", "(", "self", ".", "_TYPE_NAMES", "[", "header_type", "]", ",", "self", ".", "_SECTION_NAMES", "[", "self", ".", "_section", "]", ...
31.711538
16.423077
def link_empty_favicon_fallback(self): """Links the empty favicon as default favicon.""" self.favicon_fallback = os.path.join( os.path.dirname(__file__), 'favicon.ico')
[ "def", "link_empty_favicon_fallback", "(", "self", ")", ":", "self", ".", "favicon_fallback", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'favicon.ico'", ")" ]
48.25
5
def is_partial(self, filename): """Check if a file is a partial. Partial files are not rendered, but they are used in rendering templates. A file is considered a partial if it or any of its parent directories are prefixed with an ``'_'``. :param filename: the name of t...
[ "def", "is_partial", "(", "self", ",", "filename", ")", ":", "return", "any", "(", "(", "x", ".", "startswith", "(", "\"_\"", ")", "for", "x", "in", "filename", ".", "split", "(", "os", ".", "path", ".", "sep", ")", ")", ")" ]
34.5
22.583333
def upload_from_file( self, file_obj, rewind=False, size=None, content_type=None, num_retries=None, client=None, predefined_acl=None, ): """Upload the contents of this blob from a file-like object. The content type of the upload will b...
[ "def", "upload_from_file", "(", "self", ",", "file_obj", ",", "rewind", "=", "False", ",", "size", "=", "None", ",", "content_type", "=", "None", ",", "num_retries", "=", "None", ",", "client", "=", "None", ",", "predefined_acl", "=", "None", ",", ")", ...
36.855556
24.777778
def _get_drive_resource(self, drive_name): """Gets the DiskDrive resource if exists. :param drive_name: can be either "PhysicalDrives" or "LogicalDrives". :returns the list of drives. :raises: IloCommandNotSupportedError if the given drive resource doesn't exist...
[ "def", "_get_drive_resource", "(", "self", ",", "drive_name", ")", ":", "disk_details_list", "=", "[", "]", "array_uri_links", "=", "self", ".", "_create_list_of_array_controllers", "(", ")", "for", "array_link", "in", "array_uri_links", ":", "_", ",", "_", ",",...
45.153846
15.153846
def equal(mol, query, largest_only=True, ignore_hydrogen=True): """ if mol is exactly same structure as the query, return True Args: mol: Compound query: Compound """ m = molutil.clone(mol) q = molutil.clone(query) if largest_only: m = molutil.largest_graph(m) q = mol...
[ "def", "equal", "(", "mol", ",", "query", ",", "largest_only", "=", "True", ",", "ignore_hydrogen", "=", "True", ")", ":", "m", "=", "molutil", ".", "clone", "(", "mol", ")", "q", "=", "molutil", ".", "clone", "(", "query", ")", "if", "largest_only",...
32.5
12.555556
def stmt_lambdef_handle(self, original, loc, tokens): """Process multi-line lambdef statements.""" if len(tokens) == 2: params, stmts = tokens elif len(tokens) == 3: params, stmts, last = tokens if "tests" in tokens: stmts = stmts.asList() + ["...
[ "def", "stmt_lambdef_handle", "(", "self", ",", "original", ",", "loc", ",", "tokens", ")", ":", "if", "len", "(", "tokens", ")", "==", "2", ":", "params", ",", "stmts", "=", "tokens", "elif", "len", "(", "tokens", ")", "==", "3", ":", "params", ",...
39.68
16.56
def QA_util_random_with_topic(topic='Acc', lens=8): """ 生成account随机值 Acc+4数字id+4位大小写随机 """ _list = [chr(i) for i in range(65, 91)] + [chr(i) for i in range(97, 123) ...
[ "def", "QA_util_random_with_topic", "(", "topic", "=", "'Acc'", ",", "lens", "=", "8", ")", ":", "_list", "=", "[", "chr", "(", "i", ")", "for", "i", "in", "range", "(", "65", ",", "91", ")", "]", "+", "[", "chr", "(", "i", ")", "for", "i", "...
30.857143
19.714286
def barcode(self, data, format, characters='off', height=48, width='small', parentheses='on', ratio='3:1', equalize='off', rss_symbol='rss14std', horiz_char_rss=2): '''Print a standard barcode in the specified format Args: data: the barcode data format: the barcode type ...
[ "def", "barcode", "(", "self", ",", "data", ",", "format", ",", "characters", "=", "'off'", ",", "height", "=", "48", ",", "width", "=", "'small'", ",", "parentheses", "=", "'on'", ",", "ratio", "=", "'3:1'", ",", "equalize", "=", "'off'", ",", "rss_...
48.403226
25.274194
def cpu_count(): """ Returns the default number of slave processes to be spawned. The default value is the number of physical cpu cores seen by python. :code:`OMP_NUM_THREADS` environment variable overrides it. On PBS/torque systems if OMP_NUM_THREADS is empty, we try to use the va...
[ "def", "cpu_count", "(", ")", ":", "num", "=", "os", ".", "getenv", "(", "\"OMP_NUM_THREADS\"", ")", "if", "num", "is", "None", ":", "num", "=", "os", ".", "getenv", "(", "\"PBS_NUM_PPN\"", ")", "try", ":", "return", "int", "(", "num", ")", "except",...
31.727273
22.954545
def update_campaign_destroy(self, campaign_id, **kwargs): # noqa: E501 """Delete a campaign # noqa: E501 Delete an update campaign. # noqa: E501 This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass asynchronous=True >>> th...
[ "def", "update_campaign_destroy", "(", "self", ",", "campaign_id", ",", "*", "*", "kwargs", ")", ":", "# noqa: E501", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'asynchronous'", ")", ":", "return", "self", ...
46.190476
22.714286
def prevSolarReturn(date, lon): """ Returns the previous date when sun is at longitude 'lon'. """ jd = eph.prevSolarReturn(date.jd, lon) return Datetime.fromJD(jd, date.utcoffset)
[ "def", "prevSolarReturn", "(", "date", ",", "lon", ")", ":", "jd", "=", "eph", ".", "prevSolarReturn", "(", "date", ".", "jd", ",", "lon", ")", "return", "Datetime", ".", "fromJD", "(", "jd", ",", "date", ".", "utcoffset", ")" ]
47
4.25
def offset(self, offset): """Fetch results after `offset` value""" clone = self._clone() if isinstance(offset, int): clone._offset = offset return clone
[ "def", "offset", "(", "self", ",", "offset", ")", ":", "clone", "=", "self", ".", "_clone", "(", ")", "if", "isinstance", "(", "offset", ",", "int", ")", ":", "clone", ".", "_offset", "=", "offset", "return", "clone" ]
23.875
17.125
def bloquear_sat(self): """Sobrepõe :meth:`~satcfe.base.FuncoesSAT.bloquear_sat`. :return: Uma resposta SAT padrão. :rtype: satcfe.resposta.padrao.RespostaSAT """ resp = self._http_post('bloquearsat') conteudo = resp.json() return RespostaSAT.bloquear_sat(conteud...
[ "def", "bloquear_sat", "(", "self", ")", ":", "resp", "=", "self", ".", "_http_post", "(", "'bloquearsat'", ")", "conteudo", "=", "resp", ".", "json", "(", ")", "return", "RespostaSAT", ".", "bloquear_sat", "(", "conteudo", ".", "get", "(", "'retorno'", ...
36.555556
11.888889
def get_item_ids_metadata(self): """get the metadata for item""" metadata = dict(self._item_ids_metadata) metadata.update({'existing_id_values': self.my_osid_object_form._my_map['itemIds']}) return Metadata(**metadata)
[ "def", "get_item_ids_metadata", "(", "self", ")", ":", "metadata", "=", "dict", "(", "self", ".", "_item_ids_metadata", ")", "metadata", ".", "update", "(", "{", "'existing_id_values'", ":", "self", ".", "my_osid_object_form", ".", "_my_map", "[", "'itemIds'", ...
49.2
14.6
def _wrap(obj, wrapper=None, methods_to_add=(), name=None, skip=(), wrap_return_values=False, wrap_filenames=(), filename=None, wrapped_name_func=None, wrapped=None): """ Wrap module, class, function or another variable recursively :param Any obj: Object to wrap recursively :param Optional[Ca...
[ "def", "_wrap", "(", "obj", ",", "wrapper", "=", "None", ",", "methods_to_add", "=", "(", ")", ",", "name", "=", "None", ",", "skip", "=", "(", ")", ",", "wrap_return_values", "=", "False", ",", "wrap_filenames", "=", "(", ")", ",", "filename", "=", ...
41.533512
18.884718
def run(self, channels=None, samplerate=None, blocksize=None): """Setup/reset all processors in cascade""" source = self.processors[0] items = self.processors[1:] # Check if any processor in items need to force the samplerate force_samplerate = set([item.force_samplerate for it...
[ "def", "run", "(", "self", ",", "channels", "=", "None", ",", "samplerate", "=", "None", ",", "blocksize", "=", "None", ")", ":", "source", "=", "self", ".", "processors", "[", "0", "]", "items", "=", "self", ".", "processors", "[", "1", ":", "]", ...
32.918919
18.418919
def request(input, representation, resolvers=None, get3d=False, tautomers=False, **kwargs): """Make a request to CIR and return the XML response. :param string input: Chemical identifier to resolve :param string representation: Desired output representation :param list(string) resolvers: (Optional) Ord...
[ "def", "request", "(", "input", ",", "representation", ",", "resolvers", "=", "None", ",", "get3d", "=", "False", ",", "tautomers", "=", "False", ",", "*", "*", "kwargs", ")", ":", "url", "=", "construct_api_url", "(", "input", ",", "representation", ","...
50.941176
21.176471
def refactor(source, fixer_names, ignore=None, filename=''): """Return refactored code using lib2to3. Skip if ignore string is produced in the refactored code. """ check_lib2to3() from lib2to3 import pgen2 try: new_text = refactor_with_2to3(source, ...
[ "def", "refactor", "(", "source", ",", "fixer_names", ",", "ignore", "=", "None", ",", "filename", "=", "''", ")", ":", "check_lib2to3", "(", ")", "from", "lib2to3", "import", "pgen2", "try", ":", "new_text", "=", "refactor_with_2to3", "(", "source", ",", ...
28.130435
19.217391