text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def add_callback(instance, prop, callback, echo_old=False, priority=0): """ Attach a callback function to a property in an instance Parameters ---------- instance The instance to add the callback to prop : str Name of callback property in `instance` callback : func T...
[ "def", "add_callback", "(", "instance", ",", "prop", ",", "callback", ",", "echo_old", "=", "False", ",", "priority", "=", "0", ")", ":", "p", "=", "getattr", "(", "type", "(", "instance", ")", ",", "prop", ")", "if", "not", "isinstance", "(", "p", ...
29.307692
0.000847
def _process_cross_domain_request(cls, request, response): """Facilitate Cross-Origin Requests (CORs). """ # Step 1 # Check for Origin header. origin = request.get('Origin') if not origin: return # Step 2 # Check if the origin is in the list ...
[ "def", "_process_cross_domain_request", "(", "cls", ",", "request", ",", "response", ")", ":", "# Step 1", "# Check for Origin header.", "origin", "=", "request", ".", "get", "(", "'Origin'", ")", "if", "not", "origin", ":", "return", "# Step 2", "# Check if the o...
33.85
0.000957
def remove_api_gateway(): """Remove the Blockade REST API service.""" logger.debug("[#] Removing API Gateway") client = boto3.client('apigateway', region_name=PRIMARY_REGION) matches = [x for x in client.get_rest_apis().get('items', list()) if x['name'] == API_GATEWAY] if len(matches)...
[ "def", "remove_api_gateway", "(", ")", ":", "logger", ".", "debug", "(", "\"[#] Removing API Gateway\"", ")", "client", "=", "boto3", ".", "client", "(", "'apigateway'", ",", "region_name", "=", "PRIMARY_REGION", ")", "matches", "=", "[", "x", "for", "x", "i...
34.6875
0.001754
def picard_sort(picard, align_bam, sort_order="coordinate", out_file=None, compression_level=None, pipe=False): """Sort a BAM file by coordinates. """ base, ext = os.path.splitext(align_bam) if out_file is None: out_file = "%s-sort%s" % (base, ext) if not file_exists(out_file...
[ "def", "picard_sort", "(", "picard", ",", "align_bam", ",", "sort_order", "=", "\"coordinate\"", ",", "out_file", "=", "None", ",", "compression_level", "=", "None", ",", "pipe", "=", "False", ")", ":", "base", ",", "ext", "=", "os", ".", "path", ".", ...
46.333333
0.001175
def _to_dot_key(cls, section, key=None): """ Return the section and key in dot notation format. """ if key: return (NON_ALPHA_NUM.sub('_', section.lower()), NON_ALPHA_NUM.sub('_', key.lower())) else: return NON_ALPHA_NUM.sub('_', section.lower())
[ "def", "_to_dot_key", "(", "cls", ",", "section", ",", "key", "=", "None", ")", ":", "if", "key", ":", "return", "(", "NON_ALPHA_NUM", ".", "sub", "(", "'_'", ",", "section", ".", "lower", "(", ")", ")", ",", "NON_ALPHA_NUM", ".", "sub", "(", "'_'"...
48.166667
0.010204
def list(self, request, *args, **kwargs): """Modified list view to driving listing from ES""" search_kwargs = {"published": False} query_params = get_query_params(self.request) for field_name in ("status"): if field_name in query_params: search_kwargs[field_...
[ "def", "list", "(", "self", ",", "request", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "search_kwargs", "=", "{", "\"published\"", ":", "False", "}", "query_params", "=", "get_query_params", "(", "self", ".", "request", ")", "for", "field_name"...
37.030303
0.001595
def _process_cmap_cbar_kwargs(func, kwargs, data): """ Parameters ========== func : plotting function kwargs : dict, Dictionary with arguments that need to be parsed data : ndarray, Data values Returns ======= cmap_params cbar_kwargs """ cmap = kwargs.p...
[ "def", "_process_cmap_cbar_kwargs", "(", "func", ",", "kwargs", ",", "data", ")", ":", "cmap", "=", "kwargs", ".", "pop", "(", "'cmap'", ",", "None", ")", "colors", "=", "kwargs", ".", "pop", "(", "'colors'", ",", "None", ")", "cbar_kwargs", "=", "kwar...
32.433962
0.000565
def Right(self, n = 1, dl = 0): """右方向键n次 """ self.Delay(dl) self.keyboard.tap_key(self.keyboard.right_key, n)
[ "def", "Right", "(", "self", ",", "n", "=", "1", ",", "dl", "=", "0", ")", ":", "self", ".", "Delay", "(", "dl", ")", "self", ".", "keyboard", ".", "tap_key", "(", "self", ".", "keyboard", ".", "right_key", ",", "n", ")" ]
27.6
0.042254
def match_best_pdb_chains(pdb1, pdb1_name, pdb2, pdb2_name, cut_off = 60.0, use_seqres_sequences_if_possible = True): '''A wrapper function for match_pdb_chains. This function only takes the best match. The return value is a dict mapping chain_id_in_pdb1 -> None or a tuple (chain_id_in_pdb_2, pe...
[ "def", "match_best_pdb_chains", "(", "pdb1", ",", "pdb1_name", ",", "pdb2", ",", "pdb2_name", ",", "cut_off", "=", "60.0", ",", "use_seqres_sequences_if_possible", "=", "True", ")", ":", "d", "=", "match_pdb_chains", "(", "pdb1", ",", "pdb1_name", ",", "pdb2",...
67.4
0.021962
def addNew(label, version, baseVersion, dataHash="", fixedHash="", replayHash=""): """ Add a new version record to the database to be tracked VERSION RECORD EXAMPLE: "base-version": 55505, "data-hash": "60718A7CA50D0DF42987A30CF87BCB80", "fixed-hash": "0189B2804E2F6BA4C4591222089E6...
[ "def", "addNew", "(", "label", ",", "version", ",", "baseVersion", ",", "dataHash", "=", "\"\"", ",", "fixedHash", "=", "\"\"", ",", "replayHash", "=", "\"\"", ")", ":", "baseVersion", "=", "int", "(", "baseVersion", ")", "version", "=", "int", "(", "v...
59.558824
0.017007
def plot_mag_map(fignum, element, lons, lats, element_type, cmap='coolwarm', lon_0=0, date="", contours=False, proj='PlateCarree'): """ makes a color contour map of geomagnetic field element Parameters ____________ fignum : matplotlib figure number element : field element array from pmag.do_mag...
[ "def", "plot_mag_map", "(", "fignum", ",", "element", ",", "lons", ",", "lats", ",", "element_type", ",", "cmap", "=", "'coolwarm'", ",", "lon_0", "=", "0", ",", "date", "=", "\"\"", ",", "contours", "=", "False", ",", "proj", "=", "'PlateCarree'", ")"...
40.877778
0.001592
def sanitizeStructTime(struct): """ Convert struct_time tuples with possibly invalid values to valid ones by substituting the closest valid value. """ maxValues = (9999, 12, 31, 23, 59, 59) minValues = (1, 1, 1, 0, 0, 0) newstruct = [] for value, maxValue, minValue in zip(struct[:6], max...
[ "def", "sanitizeStructTime", "(", "struct", ")", ":", "maxValues", "=", "(", "9999", ",", "12", ",", "31", ",", "23", ",", "59", ",", "59", ")", "minValues", "=", "(", "1", ",", "1", ",", "1", ",", "0", ",", "0", ",", "0", ")", "newstruct", "...
39.272727
0.002262
def run(self): """ Run the plugin. """ # Only run if the build was successful if self.workflow.build_process_failed: self.log.info("Not promoting failed build to koji") return self.koji_session = get_koji_session(self.workflow, self.koji_fallback)...
[ "def", "run", "(", "self", ")", ":", "# Only run if the build was successful", "if", "self", ".", "workflow", ".", "build_process_failed", ":", "self", ".", "log", ".", "info", "(", "\"Not promoting failed build to koji\"", ")", "return", "self", ".", "koji_session"...
38.302326
0.001184
def make(self, url, browsers=None, destination=None, timeout=DEFAULT_TIMEOUT, retries=DEFAULT_RETRIES, **kwargs): """ Generates screenshots for given settings and saves it to specified destination. """ response = self.generate(url, browsers, **kwargs) return self.download(respons...
[ "def", "make", "(", "self", ",", "url", ",", "browsers", "=", "None", ",", "destination", "=", "None", ",", "timeout", "=", "DEFAULT_TIMEOUT", ",", "retries", "=", "DEFAULT_RETRIES", ",", "*", "*", "kwargs", ")", ":", "response", "=", "self", ".", "gen...
59.666667
0.011019
def get_authors_string(self, own_accts=None, replace_own=None): """ returns a string of comma-separated authors Depending on settings, it will substitute "me" for author name if address is user's own. :param own_accts: list of own accounts to replace :type own_accts: lis...
[ "def", "get_authors_string", "(", "self", ",", "own_accts", "=", "None", ",", "replace_own", "=", "None", ")", ":", "if", "replace_own", "is", "None", ":", "replace_own", "=", "settings", ".", "get", "(", "'thread_authors_replace_me'", ")", "if", "replace_own"...
39.933333
0.00163
def tablelib_unary_features(span): """ Table-/structure-related features for a single span """ if not span.sentence.is_tabular(): return sentence = span.sentence for attrib in settings["featurization"]["table"]["unary_features"]["attrib"]: for ngram in get_cell_ngrams( ...
[ "def", "tablelib_unary_features", "(", "span", ")", ":", "if", "not", "span", ".", "sentence", ".", "is_tabular", "(", ")", ":", "return", "sentence", "=", "span", ".", "sentence", "for", "attrib", "in", "settings", "[", "\"featurization\"", "]", "[", "\"t...
38.74
0.001511
async def query( cls, *, hostnames: typing.Iterable[str] = None, domains: typing.Iterable[str] = None, zones: typing.Iterable[str] = None, macs: typing.Iterable[str] = None, system_ids: typing.Iterable[str] = None, agent_name: str = Non...
[ "async", "def", "query", "(", "cls", ",", "*", ",", "hostnames", ":", "typing", ".", "Iterable", "[", "str", "]", "=", "None", ",", "domains", ":", "typing", ".", "Iterable", "[", "str", "]", "=", "None", ",", "zones", ":", "typing", ".", "Iterable...
36.886792
0.000997
def lookup_rdap(self, inc_raw=False, retry_count=3, depth=0, excluded_entities=None, bootstrap=False, rate_limit_timeout=120, asn_alts=None, extra_org_map=None, inc_nir=True, nir_field_list=None, asn_methods=None, get_asn_description=True):...
[ "def", "lookup_rdap", "(", "self", ",", "inc_raw", "=", "False", ",", "retry_count", "=", "3", ",", "depth", "=", "0", ",", "excluded_entities", "=", "None", ",", "bootstrap", "=", "False", ",", "rate_limit_timeout", "=", "120", ",", "asn_alts", "=", "No...
46.671429
0.000899
def _map_trajectory(self): """ Return filepath as a class attribute""" self.trajectory_map = {} with open(self.filepath, 'r') as trajectory_file: with closing( mmap( trajectory_file.fileno(), 0, access=ACCESS_READ)) ...
[ "def", "_map_trajectory", "(", "self", ")", ":", "self", ".", "trajectory_map", "=", "{", "}", "with", "open", "(", "self", ".", "filepath", ",", "'r'", ")", "as", "trajectory_file", ":", "with", "closing", "(", "mmap", "(", "trajectory_file", ".", "file...
48.888889
0.001114
def request(self, action, data={}, headers={}, method='GET'): """ Append the user authentication details to every incoming request """ data = self.merge(data, {'user': self.username, 'password': self.password, 'api_id': self.apiId}) return Transport.request(self, action, data, he...
[ "def", "request", "(", "self", ",", "action", ",", "data", "=", "{", "}", ",", "headers", "=", "{", "}", ",", "method", "=", "'GET'", ")", ":", "data", "=", "self", ".", "merge", "(", "data", ",", "{", "'user'", ":", "self", ".", "username", ",...
54.833333
0.008982
def set_prefs(prefs): """This function is called before opening the project""" # Specify which files and folders to ignore in the project. # Changes to ignored resources are not added to the history and # VCSs. Also they are not returned in `Project.get_files()`. # Note that ``?`` and ``*`` match ...
[ "def", "set_prefs", "(", "prefs", ")", ":", "# Specify which files and folders to ignore in the project.", "# Changes to ignored resources are not added to the history and", "# VCSs. Also they are not returned in `Project.get_files()`.", "# Note that ``?`` and ``*`` match all characters but slash...
43.047619
0.000216
async def update_description(self, **params): """Set description to unconfirmed status after updating by user. Accepts: - cid - description - transaction id - coinid """ if params.get("message"): params = json.loads(params.get("message", "{}")) if not params: return {"error":400, "reason":"...
[ "async", "def", "update_description", "(", "self", ",", "*", "*", "params", ")", ":", "if", "params", ".", "get", "(", "\"message\"", ")", ":", "params", "=", "json", ".", "loads", "(", "params", ".", "get", "(", "\"message\"", ",", "\"{}\"", ")", ")...
27.44
0.047854
def get_custom_getter(self): """Returns a custom getter that this class's methods must be called All methods of this class must be called under a variable scope that was passed this custom getter. Example: ```python network = ConvNetBuilder(...) with tf.variable_scope("cg", custom_getter=n...
[ "def", "get_custom_getter", "(", "self", ")", ":", "def", "inner_custom_getter", "(", "getter", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "use_tf_layers", ":", "return", "getter", "(", "*", "args", ",", "*", "*", ...
38.65625
0.001577
def hash_algo(self): """ Returns the name of the family of hash algorithms used to generate a DSA key :raises: ValueError - when the key is not a DSA key :return: A unicode string of "sha1" or "sha2" or None if no parameters are present ...
[ "def", "hash_algo", "(", "self", ")", ":", "if", "self", ".", "algorithm", "!=", "'dsa'", ":", "raise", "ValueError", "(", "unwrap", "(", "'''\n Only DSA keys are generated using a hash algorithm, this key is\n %s\n '''", ",", "sel...
27.413793
0.00243
def main(): """Get status from APC NIS and print output on stdout.""" # No need to use "proper" names on such simple code. # pylint: disable=invalid-name p = argparse.ArgumentParser() p.add_argument("--host", default="localhost") p.add_argument("--port", type=int, default=3551) p.add_argumen...
[ "def", "main", "(", ")", ":", "# No need to use \"proper\" names on such simple code.", "# pylint: disable=invalid-name", "p", "=", "argparse", ".", "ArgumentParser", "(", ")", "p", ".", "add_argument", "(", "\"--host\"", ",", "default", "=", "\"localhost\"", ")", "p"...
38.307692
0.001961
def exportdb(outdir): """Export all anchore images to JSON files""" ecode = 0 try: imgdir = os.path.join(outdir, "images") feeddir = os.path.join(outdir, "feeds") storedir = os.path.join(outdir, "storedfiles") for d in [outdir, imgdir, feeddir, storedir]: if not ...
[ "def", "exportdb", "(", "outdir", ")", ":", "ecode", "=", "0", "try", ":", "imgdir", "=", "os", ".", "path", ".", "join", "(", "outdir", ",", "\"images\"", ")", "feeddir", "=", "os", ".", "path", ".", "join", "(", "outdir", ",", "\"feeds\"", ")", ...
42.745455
0.002079
def collect_parameters(uri_query='', body=[], headers=None, exclude_oauth_signature=True, with_realm=False): """**Parameter Sources** Parameters starting with `oauth_` will be unescaped. Body parameters must be supplied as a dict, a list of 2-tuples, or a formencoded query strin...
[ "def", "collect_parameters", "(", "uri_query", "=", "''", ",", "body", "=", "[", "]", ",", "headers", "=", "None", ",", "exclude_oauth_signature", "=", "True", ",", "with_realm", "=", "False", ")", ":", "headers", "=", "headers", "or", "{", "}", "params"...
42.165289
0.000957
def extract_morphological_information(mrph_object, is_feature, is_surface): # type: (pyknp.Morpheme, bool, bool) -> TokenizedResult """This method extracts morphlogical information from token object. """ assert isinstance(mrph_object, pyknp.Morpheme) assert isinstance(is_feature, bool) assert is...
[ "def", "extract_morphological_information", "(", "mrph_object", ",", "is_feature", ",", "is_surface", ")", ":", "# type: (pyknp.Morpheme, bool, bool) -> TokenizedResult", "assert", "isinstance", "(", "mrph_object", ",", "pyknp", ".", "Morpheme", ")", "assert", "isinstance",...
28.806452
0.001083
def sync(self): """Retrieve lights from ElkM1""" for i in range(4): self.elk.send(ps_encode(i)) self.get_descriptions(TextDescriptions.LIGHT.value)
[ "def", "sync", "(", "self", ")", ":", "for", "i", "in", "range", "(", "4", ")", ":", "self", ".", "elk", ".", "send", "(", "ps_encode", "(", "i", ")", ")", "self", ".", "get_descriptions", "(", "TextDescriptions", ".", "LIGHT", ".", "value", ")" ]
35.8
0.010929
def _adapt_response(self, response): """Convert various error responses to standardized ErrorDetails.""" errors, meta = super(ServerError, self)._adapt_response(response) return errors[0], meta
[ "def", "_adapt_response", "(", "self", ",", "response", ")", ":", "errors", ",", "meta", "=", "super", "(", "ServerError", ",", "self", ")", ".", "_adapt_response", "(", "response", ")", "return", "errors", "[", "0", "]", ",", "meta" ]
53.5
0.009217
def nce(reference_intervals, reference_labels, estimated_intervals, estimated_labels, frame_size=0.1, beta=1.0, marginal=False): """Frame-clustering segmentation: normalized conditional entropy Computes cross-entropy of cluster assignment, normalized by the max-entropy. Examples -------- ...
[ "def", "nce", "(", "reference_intervals", ",", "reference_labels", ",", "estimated_intervals", ",", "estimated_labels", ",", "frame_size", "=", "0.1", ",", "beta", "=", "1.0", ",", "marginal", "=", "False", ")", ":", "validate_structure", "(", "reference_intervals...
35.325926
0.000204
def add(self, title, nick=None): '''xxxxx.xxxxx.campaign.add =================================== 创建一个推广计划''' request = TOPRequest('xxxxx.xxxxx.campaign.add') request['title'] = title if nick!=None: request['nick'] = nick self.create(self.execute(request), fields=[...
[ "def", "add", "(", "self", ",", "title", ",", "nick", "=", "None", ")", ":", "request", "=", "TOPRequest", "(", "'xxxxx.xxxxx.campaign.add'", ")", "request", "[", "'title'", "]", "=", "title", "if", "nick", "!=", "None", ":", "request", "[", "'nick'", ...
47.555556
0.025229
def filter(self, dataset): """Mark unusual trips for all the routes in the dataset.""" self.info('Going to filter infrequent routes in the dataset') for route in dataset.routes.values(): self.filter_line(route)
[ "def", "filter", "(", "self", ",", "dataset", ")", ":", "self", ".", "info", "(", "'Going to filter infrequent routes in the dataset'", ")", "for", "route", "in", "dataset", ".", "routes", ".", "values", "(", ")", ":", "self", ".", "filter_line", "(", "route...
44.8
0.008772
def add_record_check(self, actions, table, func): # emitted after query # table: 'table_name' # column: ('table_name', 'column_name') assert isinstance(table, str), '`table` must be table name' for i in actions: assert i not in (A.QUERY, A.CREATE), "meaningless action...
[ "def", "add_record_check", "(", "self", ",", "actions", ",", "table", ",", "func", ")", ":", "# emitted after query", "# table: 'table_name'", "# column: ('table_name', 'column_name')", "assert", "isinstance", "(", "table", ",", "str", ")", ",", "'`table` must be table ...
39.615385
0.01518
def _build_file(self, nmrstar_str): """Build :class:`~nmrstarlib.nmrstarlib.NMRStarFile` object. :param nmrstar_str: NMR-STAR-formatted string. :type nmrstar_str: :py:class:`str` or :py:class:`bytes` :return: instance of :class:`~nmrstarlib.nmrstarlib.NMRStarFile`. :rtype: :clas...
[ "def", "_build_file", "(", "self", ",", "nmrstar_str", ")", ":", "odict", "=", "self", "comment_count", "=", "0", "lexer", "=", "bmrblex", "(", "nmrstar_str", ")", "token", "=", "next", "(", "lexer", ")", "while", "token", "!=", "u\"\"", ":", "try", ":...
36.119048
0.001926
def matches(self, tokenJson): '''Determines whether given token (tokenJson) satisfies all the rules listed in the WordTemplate. If the rules describe tokenJson[ANALYSIS], it is required that at least one item in the list tokenJson[ANALYSIS] satisfies all the rules (but it...
[ "def", "matches", "(", "self", ",", "tokenJson", ")", ":", "if", "self", ".", "otherRules", "!=", "None", ":", "otherMatches", "=", "[", "]", "for", "field", "in", "self", ".", "otherRules", ":", "match", "=", "field", "in", "tokenJson", "and", "(", ...
49.026316
0.013684
def parse_date(value): """Parse one of the following date formats into a datetime object: .. sourcecode:: text Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123 Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036 Sun Nov 6 08:49:37 1994 ; ANSI C's asctime...
[ "def", "parse_date", "(", "value", ")", ":", "if", "value", ":", "t", "=", "parsedate_tz", "(", "value", ".", "strip", "(", ")", ")", "if", "t", "is", "not", "None", ":", "try", ":", "year", "=", "t", "[", "0", "]", "# unfortunately that function doe...
39.9
0.001631
def get_template_info(self, obj): """Returns the info for a Template """ client = self.get_client() client_uid = api.get_uid(client) if client else "" profile = obj.getAnalysisProfile() profile_uid = api.get_uid(profile) if profile else "" profile_title = profile...
[ "def", "get_template_info", "(", "self", ",", "obj", ")", ":", "client", "=", "self", ".", "get_client", "(", ")", "client_uid", "=", "api", ".", "get_uid", "(", "client", ")", "if", "client", "else", "\"\"", "profile", "=", "obj", ".", "getAnalysisProfi...
38.488372
0.001179
def url_assembler(query_string, no_redirect=0, no_html=0, skip_disambig=0): """Assembler of parameters for building request query. Args: query_string: Query to be passed to DuckDuckGo API. no_redirect: Skip HTTP redirects (for !bang commands). Default - False. no_html: Remove HTML from ...
[ "def", "url_assembler", "(", "query_string", ",", "no_redirect", "=", "0", ",", "no_html", "=", "0", ",", "skip_disambig", "=", "0", ")", ":", "params", "=", "[", "(", "'q'", ",", "query_string", ".", "encode", "(", "\"utf-8\"", ")", ")", ",", "(", "...
36.363636
0.001218
def scan_field(self, measure, target, rate, delay=1): """Performs a field scan. Measures until the target field is reached. :param measure: A callable called repeatedly until stability at the target field is reached. :param field: The target field in Tesla. :param r...
[ "def", "scan_field", "(", "self", ",", "measure", ",", "target", ",", "rate", ",", "delay", "=", "1", ")", ":", "if", "not", "hasattr", "(", "measure", ",", "'__call__'", ")", ":", "raise", "TypeError", "(", "'measure parameter not callable.'", ")", "self"...
36.695652
0.002309
def find_checks(argument_name): """ Find all globally visible functions where the first argument name starts with argument_name. """ checks = [] function_type = type(find_checks) for name, function in globals().iteritems(): if type(function) is function_type: args = inspe...
[ "def", "find_checks", "(", "argument_name", ")", ":", "checks", "=", "[", "]", "function_type", "=", "type", "(", "find_checks", ")", "for", "name", ",", "function", "in", "globals", "(", ")", ".", "iteritems", "(", ")", ":", "if", "type", "(", "functi...
35.142857
0.00198
def get_date(context, value): """Tries to return a DateTime.DateTime object """ if not value: return None if isinstance(value, DateTime): return value if isinstance(value, datetime): return dt2DT(value) if not isinstance(value, basestring): return None def tr...
[ "def", "get_date", "(", "context", ",", "value", ")", ":", "if", "not", "value", ":", "return", "None", "if", "isinstance", "(", "value", ",", "DateTime", ")", ":", "return", "value", "if", "isinstance", "(", "value", ",", "datetime", ")", ":", "return...
33.23913
0.000635
def pairs_multi(self, strands, cutoff=0.001, permutation=None, temp=37.0, pseudo=False, material=None, dangles='some', sodium=1.0, magnesium=0.0): '''Compute the pair probabilities for an ordered complex of strands. Runs the \'pairs\' command. :param stra...
[ "def", "pairs_multi", "(", "self", ",", "strands", ",", "cutoff", "=", "0.001", ",", "permutation", "=", "None", ",", "temp", "=", "37.0", ",", "pseudo", "=", "False", ",", "material", "=", "None", ",", "dangles", "=", "'some'", ",", "sodium", "=", "...
49.093333
0.001331
def _concatenate_shape(input_shape, axis=-1): # pylint: disable=invalid-name """Helper to determine the shape of Concatenate output.""" ax = axis % len(input_shape[0]) concat_size = sum(shape[ax] for shape in input_shape) out_shape = input_shape[0][:ax] + (concat_size,) + input_shape[0][ax+1:] return out_sha...
[ "def", "_concatenate_shape", "(", "input_shape", ",", "axis", "=", "-", "1", ")", ":", "# pylint: disable=invalid-name", "ax", "=", "axis", "%", "len", "(", "input_shape", "[", "0", "]", ")", "concat_size", "=", "sum", "(", "shape", "[", "ax", "]", "for"...
52.833333
0.018634
def create(self,obj,cache=False): """ Initializes per-actor data on the given object for this model. If ``cache`` is set to True, the entity will not be redrawn after initialization. Note that this method may set several attributes on the given object, most of them star...
[ "def", "create", "(", "self", ",", "obj", ",", "cache", "=", "False", ")", ":", "obj", ".", "_modeldata", "=", "{", "}", "data", "=", "obj", ".", "_modeldata", "data", "[", "\"_model\"", "]", "=", "self", "data", "[", "\"_modelcache\"", "]", "=", "...
38.545455
0.022539
def drawtree(self): ''' Loop over the object, process path attribute sets, and drawlines based on their current contents. ''' self.win.erase() self.line = 0 for child, depth in self.traverse(): child.curline = self.curline child.picked = se...
[ "def", "drawtree", "(", "self", ")", ":", "self", ".", "win", ".", "erase", "(", ")", "self", ".", "line", "=", "0", "for", "child", ",", "depth", "in", "self", ".", "traverse", "(", ")", ":", "child", ".", "curline", "=", "self", ".", "curline",...
37.37037
0.001932
def post(self, path, data=None, json_data=None, params=None): """Perform POST request""" r = requests.post(url=self.url + path, data=data, json=json_data, params=params, timeout=self.timeout) try: r.raise_for_status() except requests.exceptions.HTTPError: raise Sw...
[ "def", "post", "(", "self", ",", "path", ",", "data", "=", "None", ",", "json_data", "=", "None", ",", "params", "=", "None", ")", ":", "r", "=", "requests", ".", "post", "(", "url", "=", "self", ".", "url", "+", "path", ",", "data", "=", "data...
53.125
0.009259
def check_docstring(self, method): '''All methods should have a docstring.''' mn = method.__name__ if method.__doc__ is None: return ['Missing docstring for method "{}"'.format(mn)]
[ "def", "check_docstring", "(", "self", ",", "method", ")", ":", "mn", "=", "method", ".", "__name__", "if", "method", ".", "__doc__", "is", "None", ":", "return", "[", "'Missing docstring for method \"{}\"'", ".", "format", "(", "mn", ")", "]" ]
42.6
0.009217
def subfolders(self, folder_id, ann_id=None): '''Yields an unodered generator of subfolders in a folder. By default (with ``ann_id=None``), subfolders are shown for all anonymous users. Optionally, ``ann_id`` can be set to a username, which restricts the list to only subfolders owned by...
[ "def", "subfolders", "(", "self", ",", "folder_id", ",", "ann_id", "=", "None", ")", ":", "self", ".", "assert_valid_folder_id", "(", "folder_id", ")", "ann_id", "=", "self", ".", "_annotator", "(", "ann_id", ")", "folder_cid", "=", "self", ".", "wrap_fold...
45.777778
0.002378
def get_permissions(parser, token): """ Retrieves all permissions associated with the given obj and user and assigns the result to a context variable. Syntax:: {% get_permissions obj %} {% for perm in permissions %} {{ perm }} {% endfor %} {% get_permission...
[ "def", "get_permissions", "(", "parser", ",", "token", ")", ":", "return", "PermissionsForObjectNode", ".", "handle_token", "(", "parser", ",", "token", ",", "approved", "=", "True", ",", "name", "=", "'\"permissions\"'", ")" ]
31.166667
0.00173
def diff(self, n=1, axis=-1): """Calculate the n-th order discrete difference along given axis. The first order difference is given by ``out[n] = a[n+1] - a[n]`` along the given axis, higher order differences are calculated by using `diff` recursively. Parameters ------...
[ "def", "diff", "(", "self", ",", "n", "=", "1", ",", "axis", "=", "-", "1", ")", ":", "out", "=", "super", "(", "Array", ",", "self", ")", ".", "diff", "(", "n", "=", "n", ",", "axis", "=", "axis", ")", "try", ":", "out", ".", "x0", "=", ...
32.272727
0.001823
def unwatch(connection, volume_id): """ Remove watching of a volume :type connection: boto.ec2.connection.EC2Connection :param connection: EC2 connection object :type volume_id: str :param volume_id: VolumeID to add to the watchlist :returns: bool - True if the watch was successful """ ...
[ "def", "unwatch", "(", "connection", ",", "volume_id", ")", ":", "try", ":", "volume", "=", "connection", ".", "get_all_volumes", "(", "volume_ids", "=", "[", "volume_id", "]", ")", "[", "0", "]", "volume", ".", "remove_tag", "(", "'AutomatedEBSSnapshots'", ...
30.888889
0.001745
def iri_to_uri(iri, charset='utf-8', errors='strict'): r""" Converts any unicode based IRI to an acceptable ASCII URI. Werkzeug always uses utf-8 URLs internally because this is what browsers and HTTP do as well. In some places where it accepts an URL it also accepts a unicode IRI and converts it in...
[ "def", "iri_to_uri", "(", "iri", ",", "charset", "=", "'utf-8'", ",", "errors", "=", "'strict'", ")", ":", "if", "isinstance", "(", "iri", ",", "tuple", ")", ":", "iri", "=", "url_unparse", "(", "iri", ")", "iri", "=", "url_parse", "(", "to_unicode", ...
37.1
0.000876
def _write(self, body, id): """ Respond to a WRITE command, sending some data over a virtual channel created by VIRTUAL. The answer is simply an acknowledgement, as it is simply meant to note that the write went through without errors. An occurrence of I{Write} on the wire, tog...
[ "def", "_write", "(", "self", ",", "body", ",", "id", ")", ":", "if", "id", "not", "in", "self", ".", "connections", ":", "raise", "error", ".", "ConnectionDone", "(", ")", "connection", "=", "self", ".", "connections", "[", "id", "]", "connection", ...
33.08
0.00235
def menu(self, event_button, event_time, data=None): """Create popup menu """ self.sub_menu() menu = gtk.Menu() menu.append(self.daemon) separator = gtk.SeparatorMenuItem() menu_Check = gtk.ImageMenuItem("Check updates") img_Check = gtk.image_new_from_st...
[ "def", "menu", "(", "self", ",", "event_button", ",", "event_time", ",", "data", "=", "None", ")", ":", "self", ".", "sub_menu", "(", ")", "menu", "=", "gtk", ".", "Menu", "(", ")", "menu", ".", "append", "(", "self", ".", "daemon", ")", "separator...
35.9
0.000904
def _shutdown(self, manual): """ Shuts down the TLS session and then shuts down the underlying socket :param manual: A boolean if the connection was manually shutdown """ if self._session_context is None: return # Ignore error during close in ca...
[ "def", "_shutdown", "(", "self", ",", "manual", ")", ":", "if", "self", ".", "_session_context", "is", "None", ":", "return", "# Ignore error during close in case other end closed already", "result", "=", "Security", ".", "SSLClose", "(", "self", ".", "_session_cont...
28.5
0.002262
def mv_files(src, dst): """ Move all files from one directory to another :param str src: Source directory :param str dst: Destination directory :return none: """ # list the files in the src directory files = os.listdir(src) # loop for each file found for file in files: #...
[ "def", "mv_files", "(", "src", ",", "dst", ")", ":", "# list the files in the src directory", "files", "=", "os", ".", "listdir", "(", "src", ")", "# loop for each file found", "for", "file", "in", "files", ":", "# move the file from the src to the dst", "shutil", "...
28.333333
0.002278
def get_bgp_neighbors(self): """BGP neighbor information. Supports VRFs and IPv4 and IPv6 AFIs { "global": { "router_id": "1.1.1.103", "peers": { "10.99.99.2": { "is_enabled": true, "uptime": -1, ...
[ "def", "get_bgp_neighbors", "(", "self", ")", ":", "bgp_dict", "=", "{", "}", "# get summary output from device", "cmd_bgp_all_sum", "=", "\"show bgp all summary vrf all\"", "bgp_summary_output", "=", "self", ".", "_send_command", "(", "cmd_bgp_all_sum", ")", ".", "stri...
33.891304
0.00187
def sun_earth_distance_correction(utc_time): """Calculate the sun earth distance correction, relative to 1 AU. """ year = 365.256363004 # This is computed from # http://curious.astro.cornell.edu/question.php?number=582 # AU = 149597870700.0 # a = 149598261000.0 # theta = (jdays2000(utc_t...
[ "def", "sun_earth_distance_correction", "(", "utc_time", ")", ":", "year", "=", "365.256363004", "# This is computed from", "# http://curious.astro.cornell.edu/question.php?number=582", "# AU = 149597870700.0", "# a = 149598261000.0", "# theta = (jdays2000(utc_time) - 2) * (2 * np.pi) / ye...
32.294118
0.00177
def _get_pc_covered(self): """Returns a single percentage value for coverage.""" if self.n_statements > 0: pc_cov = (100.0 * (self.n_executed + self.n_executed_branches) / (self.n_statements + self.n_branches)) else: pc_cov = 100.0 return p...
[ "def", "_get_pc_covered", "(", "self", ")", ":", "if", "self", ".", "n_statements", ">", "0", ":", "pc_cov", "=", "(", "100.0", "*", "(", "self", ".", "n_executed", "+", "self", ".", "n_executed_branches", ")", "/", "(", "self", ".", "n_statements", "+...
39.75
0.009231
def load_config(self, path): """ (Re-)load the configuration file """ self.config_path = path self.config.read(self.config_path)
[ "def", "load_config", "(", "self", ",", "path", ")", ":", "self", ".", "config_path", "=", "path", "self", ".", "config", ".", "read", "(", "self", ".", "config_path", ")" ]
27.166667
0.011905
def worker(qin, qout, f): """Worker for muliprocessing. A worker repeatedly picks a dict of arguments in the queue and computes f for this set of arguments, until the input queue is empty. """ while not qin.empty(): i, args = qin.get() qout.put((i, f(**args)))
[ "def", "worker", "(", "qin", ",", "qout", ",", "f", ")", ":", "while", "not", "qin", ".", "empty", "(", ")", ":", "i", ",", "args", "=", "qin", ".", "get", "(", ")", "qout", ".", "put", "(", "(", "i", ",", "f", "(", "*", "*", "args", ")",...
32.666667
0.009934
def fetch_git_package(self, config): """Make a remote git repository available for local use. Args: config (dict): git config dictionary """ # only loading git here when needed to avoid load errors on systems # without git installed from git import Repo ...
[ "def", "fetch_git_package", "(", "self", ",", "config", ")", ":", "# only loading git here when needed to avoid load errors on systems", "# without git installed", "from", "git", "import", "Repo", "ref", "=", "self", ".", "determine_git_ref", "(", "config", ")", "dir_name...
42.974359
0.001167
def derive_title(self): """ Derives our title from our object """ if not self.title: return _("Create %s") % force_text(self.model._meta.verbose_name).title() else: return self.title
[ "def", "derive_title", "(", "self", ")", ":", "if", "not", "self", ".", "title", ":", "return", "_", "(", "\"Create %s\"", ")", "%", "force_text", "(", "self", ".", "model", ".", "_meta", ".", "verbose_name", ")", ".", "title", "(", ")", "else", ":",...
29.875
0.012195
def quick_stewart(input_geojson_points, variable_name, span, beta=2, typefct='exponential',nb_class=None, nb_pts=10000, resolution=None, mask=None, user_defined_breaks=None, variable_name2=None, output="GeoJSON", **kwargs): """ Function act...
[ "def", "quick_stewart", "(", "input_geojson_points", ",", "variable_name", ",", "span", ",", "beta", "=", "2", ",", "typefct", "=", "'exponential'", ",", "nb_class", "=", "None", ",", "nb_pts", "=", "10000", ",", "resolution", "=", "None", ",", "mask", "="...
37.777778
0.001274
def shift_and_pad(array, dist, pad="__null__"): """Shift and pad with item. :params array: list like iterable object :params dist: int :params pad: any value Example:: >>> array = [0, 1, 2] >>> shift_and_pad(array, 0) [0, 1, 2] >>> shift_and_pad(array, 1) ...
[ "def", "shift_and_pad", "(", "array", ",", "dist", ",", "pad", "=", "\"__null__\"", ")", ":", "length", "=", "len", "(", "array", ")", "if", "length", "==", "0", ":", "return", "[", "]", "if", "pad", "==", "\"__null__\"", ":", "if", "dist", ">", "0...
21.807692
0.000844
def log_subtract(loga, logb): r"""Numerically stable method for avoiding overflow errors when calculating :math:`\log (a-b)`, given :math:`\log (a)`, :math:`\log (a)` and that :math:`a > b`. See https://hips.seas.harvard.edu/blog/2013/01/09/computing-log-sum-exp/ for more details. Parameters ...
[ "def", "log_subtract", "(", "loga", ",", "logb", ")", ":", "return", "loga", "+", "np", ".", "log", "(", "1", "-", "np", ".", "exp", "(", "logb", "-", "loga", ")", ")" ]
25.473684
0.001992
def _call_api(self, url, method='GET', params=None, data=None): """ Method used to call the API. It returns the raw JSON returned by the API or raises an exception if something goes wrong. :arg url: the URL to call :kwarg method: the HTTP method to use when calling the specified...
[ "def", "_call_api", "(", "self", ",", "url", ",", "method", "=", "'GET'", ",", "params", "=", "None", ",", "data", "=", "None", ")", ":", "req", "=", "self", ".", "session", ".", "request", "(", "method", "=", "method", ",", "url", "=", "url", ",...
31.75
0.001698
def optimize_providers(providers): ''' Return an optimized list of providers. We want to reduce the duplication of querying the same region. If a provider is using the same credentials for the same region the same data will be returned for each provider, thus causing un-wanted duplicate da...
[ "def", "optimize_providers", "(", "providers", ")", ":", "tmp_providers", "=", "{", "}", "optimized_providers", "=", "{", "}", "for", "name", ",", "data", "in", "six", ".", "iteritems", "(", "providers", ")", ":", "if", "'location'", "not", "in", "data", ...
33.351351
0.000787
def make_pizzly_gtf(gtf_file, out_file, data): """ pizzly needs the GTF to be in gene -> transcript -> exon order for each gene. it also wants the gene biotype set as the source """ if file_exists(out_file): return out_file db = gtf.get_gtf_db(gtf_file) with file_transaction(data, ou...
[ "def", "make_pizzly_gtf", "(", "gtf_file", ",", "out_file", ",", "data", ")", ":", "if", "file_exists", "(", "out_file", ")", ":", "return", "out_file", "db", "=", "gtf", ".", "get_gtf_db", "(", "gtf_file", ")", "with", "file_transaction", "(", "data", ","...
46.458333
0.000879
def pythonize(line, fn='', subdir='gen'): """Convert a line of BMPM code from PHP to Python. Parameters ---------- line : str A line of code fn : str A filename subdir : str The file's subdirectory Returns ------- The code in Python """ glob...
[ "def", "pythonize", "(", "line", ",", "fn", "=", "''", ",", "subdir", "=", "'gen'", ")", ":", "global", "array_seen", ",", "nl", ",", "sd", "if", "'$all'", "in", "line", ":", "return", "''", "if", "'make the sum of all languages be visible in the function'", ...
25.301587
0.000604
def get_impact_report_as_string(analysis_dir): """Retrieve an html string of table report (impact-report-output.html). :param analysis_dir: Directory of where the report located. :type analysis_dir: str :return: HTML string of the report. :rtype: str """ html_report_products = [ 'i...
[ "def", "get_impact_report_as_string", "(", "analysis_dir", ")", ":", "html_report_products", "=", "[", "'impact-report-output.html'", ",", "'multi-exposure-impact-report-output.html'", "]", "output_dir_path", "=", "join", "(", "analysis_dir", ",", "'output'", ")", "for", ...
33.607143
0.001033
def container( state, host, name, present=True, image='ubuntu:16.04', ): ''' Add/remove LXD containers. Note: does not check if an existing container is based on the specified image. + name: name of the container + image: image to base the container on + present: whether the contai...
[ "def", "container", "(", "state", ",", "host", ",", "name", ",", "present", "=", "True", ",", "image", "=", "'ubuntu:16.04'", ",", ")", ":", "container", "=", "get_container_named", "(", "name", ",", "host", ".", "fact", ".", "lxd_containers", ")", "# Co...
29.448276
0.001134
def reverse(self, query, exactly_one=True, timeout=DEFAULT_SENTINEL): """ Return an address by location point. :param query: The coordinates for which you wish to obtain the closest human-readable addresses. :type query: :class:`geopy.point.Point`, list or tuple of ``(latitu...
[ "def", "reverse", "(", "self", ",", "query", ",", "exactly_one", "=", "True", ",", "timeout", "=", "DEFAULT_SENTINEL", ")", ":", "params", "=", "{", "'ak'", ":", "self", ".", "api_key", ",", "'output'", ":", "'json'", ",", "'location'", ":", "self", "....
39.4
0.002123
def create_network(self): """Get an instance of vlan services facade.""" return Network( self.networkapi_url, self.user, self.password, self.user_ldap)
[ "def", "create_network", "(", "self", ")", ":", "return", "Network", "(", "self", ".", "networkapi_url", ",", "self", ".", "user", ",", "self", ".", "password", ",", "self", ".", "user_ldap", ")" ]
29.857143
0.009302
def get_objects_apk(self, filename=None, digest=None): """ Returns APK, DalvikVMFormat and Analysis of a specified APK. You must specify either `filename` or `digest`. It is possible to use both, but in this case only `digest` is used. example:: s = Session() ...
[ "def", "get_objects_apk", "(", "self", ",", "filename", "=", "None", ",", "digest", "=", "None", ")", ":", "if", "not", "filename", "and", "not", "digest", ":", "raise", "ValueError", "(", "\"Must give at least filename or digest!\"", ")", "if", "digest", "is"...
33.216216
0.002372
def new_client_stream(self, sock): """ Returns a new ssl client stream from bind_socket. """ assert sock newsocket, fromaddr = sock.accept() logger.debug("New connection from" " %s:%s", fromaddr[0], fromaddr[1]) # NB: Despite the name, ssl.PROTOCOL_SSLv23 se...
[ "def", "new_client_stream", "(", "self", ",", "sock", ")", ":", "assert", "sock", "newsocket", ",", "fromaddr", "=", "sock", ".", "accept", "(", ")", "logger", ".", "debug", "(", "\"New connection from\"", "\" %s:%s\"", ",", "fromaddr", "[", "0", "]", ",",...
51.916667
0.002364
def _process_ups(ups): # pragma: no cover """This function processes the UpdateInfo instances of the two undo stacks (clustering and cluster metadata) and concatenates them into a single UpdateInfo instance.""" if len(ups) == 0: return elif len(ups) == 1: return ups[0] elif len(...
[ "def", "_process_ups", "(", "ups", ")", ":", "# pragma: no cover", "if", "len", "(", "ups", ")", "==", "0", ":", "return", "elif", "len", "(", "ups", ")", "==", "1", ":", "return", "ups", "[", "0", "]", "elif", "len", "(", "ups", ")", "==", "2", ...
30.5
0.002273
def submit(self, *items): """Return job ids assigned to the submitted items.""" with self.lock: if self.closed: raise BrokenPipe('Job submission has been closed.') id = self.jobcount self._status += ['SUBMITTED'] * len(items) self.jobcount += len(items) for item in items: self.waitqueue.put((...
[ "def", "submit", "(", "self", ",", "*", "items", ")", ":", "with", "self", ".", "lock", ":", "if", "self", ".", "closed", ":", "raise", "BrokenPipe", "(", "'Job submission has been closed.'", ")", "id", "=", "self", ".", "jobcount", "self", ".", "_status...
27.466667
0.037559
def browse_by_idstring(self, search_type, idstring, start=0, max_items=100, full_album_art_uri=False): """Browse (get sub-elements from) a given music library item, specified by a string. Args: search_type (str): The kind of information to retrieve. Can be...
[ "def", "browse_by_idstring", "(", "self", ",", "search_type", ",", "idstring", ",", "start", "=", "0", ",", "max_items", "=", "100", ",", "full_album_art_uri", "=", "False", ")", ":", "search", "=", "self", ".", "SEARCH_TRANSLATION", "[", "search_type", "]",...
46.244444
0.001412
def centroid(im): """ Computes the centroid of an image using the image moments: centroid = {m10/m00, m01/m00} These calls point to Python version of moments function m00 = immoments(im,0,0) m10 = immoments(im, 1,0) m01 = immoments(im,0,1) """ # These calls point to Python version...
[ "def", "centroid", "(", "im", ")", ":", "# These calls point to Python version of moments function", "m00", "=", "cdriz", ".", "arrmoments", "(", "im", ",", "0", ",", "0", ")", "m10", "=", "cdriz", ".", "arrmoments", "(", "im", ",", "1", ",", "0", ")", "...
24.6
0.011742
def random_quat(rand=None): """Return uniform random unit quaternion. rand: array like or None Three independent random variables that are uniformly distributed between 0 and 1. >>> q = random_quat() >>> np.allclose(1.0, vector_norm(q)) True >>> q = random_quat(np.random.random(3...
[ "def", "random_quat", "(", "rand", "=", "None", ")", ":", "if", "rand", "is", "None", ":", "rand", "=", "np", ".", "random", ".", "rand", "(", "3", ")", "else", ":", "assert", "len", "(", "rand", ")", "==", "3", "r1", "=", "np", ".", "sqrt", ...
27.36
0.001412
def _check_quota(self): """ If IP can't make requests, raise BitQuotaExceeded. Called before generating numbers. """ self._request_remaining_quota_if_unset() if self.quota_estimate < self.quota_limit: raise BitQuotaExceeded(self.quota_estimate)
[ "def", "_check_quota", "(", "self", ")", ":", "self", ".", "_request_remaining_quota_if_unset", "(", ")", "if", "self", ".", "quota_estimate", "<", "self", ".", "quota_limit", ":", "raise", "BitQuotaExceeded", "(", "self", ".", "quota_estimate", ")" ]
55.2
0.010714
def save_evaluations(self, evaluations_file = None): """ Saves evaluations at each iteration of the optimization :param evaluations_file: name of the file in which the results are saved. """ iterations = np.array(range(1, self.Y.shape[0] + 1))[:, None] results = np.hsta...
[ "def", "save_evaluations", "(", "self", ",", "evaluations_file", "=", "None", ")", ":", "iterations", "=", "np", ".", "array", "(", "range", "(", "1", ",", "self", ".", "Y", ".", "shape", "[", "0", "]", "+", "1", ")", ")", "[", ":", ",", "None", ...
44
0.011132
def extract(url): """Extract as much information from a (relative) URL as possible. >>> extract('example.com/abc') URL(..., domain='example', tld='com', ..., path='/abc', ...) """ parts = split(url) if parts.scheme: netloc = parts.netloc path = parts.path else: netlo...
[ "def", "extract", "(", "url", ")", ":", "parts", "=", "split", "(", "url", ")", "if", "parts", ".", "scheme", ":", "netloc", "=", "parts", ".", "netloc", "path", "=", "parts", ".", "path", "else", ":", "netloc", "=", "parts", ".", "path", "path", ...
34.15
0.001425
def _check_dir(self): """Makes sure that the working directory for the wrapper modules exists. """ from os import path, mkdir if not path.isdir(self.dirpath): mkdir(self.dirpath) #Copy the ftypes.py module shipped with fortpy to the local directory. ft...
[ "def", "_check_dir", "(", "self", ")", ":", "from", "os", "import", "path", ",", "mkdir", "if", "not", "path", ".", "isdir", "(", "self", ".", "dirpath", ")", ":", "mkdir", "(", "self", ".", "dirpath", ")", "#Copy the ftypes.py module shipped with fortpy to ...
49.173913
0.011275
def eclipse_tt(p0,b,aR,P=1,ecc=0,w=0,npts=100,u1=0.394,u2=0.261,conv=True, cadence=1626./86400,frac=1,sec=False,pars0=None,tol=1e-4,width=3): """ Trapezoidal parameters for simulated orbit. All arguments passed to :func:`eclipse` except the following: :param pars0: (optional) ...
[ "def", "eclipse_tt", "(", "p0", ",", "b", ",", "aR", ",", "P", "=", "1", ",", "ecc", "=", "0", ",", "w", "=", "0", ",", "npts", "=", "100", ",", "u1", "=", "0.394", ",", "u2", "=", "0.261", ",", "conv", "=", "True", ",", "cadence", "=", "...
40.571429
0.042132
def fetch( self, limit=None, offset=0, start_cursor=None, end_cursor=None, client=None, eventual=False, ): """Execute the Query; return an iterator for the matching entities. For example:: >>> from google.cloud import datastore ...
[ "def", "fetch", "(", "self", ",", "limit", "=", "None", ",", "offset", "=", "0", ",", "start_cursor", "=", "None", ",", "end_cursor", "=", "None", ",", "client", "=", "None", ",", "eventual", "=", "False", ",", ")", ":", "if", "client", "is", "None...
31.932203
0.001545
def lowercase_attr_names(tag): """Lower-case all attribute names of the provided BeautifulSoup tag. Note: this mutates the tag's attribute names and does not return a new tag. :param Tag: BeautifulSoup tag """ # Use list comprehension instead of dict comprehension for 2.6 support tag.attrs...
[ "def", "lowercase_attr_names", "(", "tag", ")", ":", "# Use list comprehension instead of dict comprehension for 2.6 support", "tag", ".", "attrs", "=", "dict", "(", "[", "(", "key", ".", "lower", "(", ")", ",", "value", ")", "for", "key", ",", "value", "in", ...
30.769231
0.002427
def insert(exif, image, new_file=None): """ py:function:: piexif.insert(exif_bytes, filename) Insert exif into JPEG. :param bytes exif_bytes: Exif as bytes :param str filename: JPEG """ if exif[0:6] != b"\x45\x78\x69\x66\x00\x00": raise ValueError("Given data is not exif data") ...
[ "def", "insert", "(", "exif", ",", "image", ",", "new_file", "=", "None", ")", ":", "if", "exif", "[", "0", ":", "6", "]", "!=", "b\"\\x45\\x78\\x69\\x66\\x00\\x00\"", ":", "raise", "ValueError", "(", "\"Given data is not exif data\"", ")", "output_file", "=",...
32.5
0.002298
def _local_restart_failed(self, state, fail): ''' Getting here means that all the host agents in the shard are gone. Depending on the restart strategy we finish here, migrate out of the shard or take over (monitoring agent). ''' self.info('Restarting of %r in the same sha...
[ "def", "_local_restart_failed", "(", "self", ",", "state", ",", "fail", ")", ":", "self", ".", "info", "(", "'Restarting of %r in the same shard failed.'", ",", "state", ".", "descriptor", ".", "type_name", ")", "if", "self", ".", "_cmp_strategy", "(", "RestartS...
54.725
0.000898
def load_source(name, pathname): """ This function provides the backward compatibility for 'imp.load_source' in Python 2. :param name: Name used to create or access a module object. :param pathname: Path pointing to the source file. :return: Loaded and initialized module. """ if six.PY2...
[ "def", "load_source", "(", "name", ",", "pathname", ")", ":", "if", "six", ".", "PY2", ":", "import", "imp", "return", "imp", ".", "load_source", "(", "name", ",", "pathname", ")", "else", ":", "loader", "=", "importlib", ".", "machinery", ".", "Source...
32.866667
0.001972
def fit(self, X, y, weights=None): """Fit the generalized additive model. Parameters ---------- X : array-like, shape (n_samples, m_features) Training vectors. y : array-like, shape (n_samples,) Target values, ie integers in classification, re...
[ "def", "fit", "(", "self", ",", "X", ",", "y", ",", "weights", "=", "None", ")", ":", "# validate parameters", "self", ".", "_validate_params", "(", ")", "# validate data", "y", "=", "check_y", "(", "y", ",", "self", ".", "link", ",", "self", ".", "d...
30.107143
0.001149
def replace_gen(network,gen_to_replace): """Replace the generator gen_to_replace with a bus for the energy carrier, a link for the conversion from the energy carrier to electricity and a store to keep track of the depletion of the energy carrier and its CO2 emissions.""" gen = network.generato...
[ "def", "replace_gen", "(", "network", ",", "gen_to_replace", ")", ":", "gen", "=", "network", ".", "generators", ".", "loc", "[", "gen_to_replace", "]", "bus_name", "=", "\"{} {}\"", ".", "format", "(", "gen", "[", "\"bus\"", "]", ",", "gen", "[", "\"car...
39.930233
0.023877
def ActivateCard(self, card): """Activate a card.""" if not hasattr(card, 'connection'): card.connection = card.createConnection() if None != self.parent.apdutracerpanel: card.connection.addObserver(self.parent.apdutracerpanel) card.connection.connect(...
[ "def", "ActivateCard", "(", "self", ",", "card", ")", ":", "if", "not", "hasattr", "(", "card", ",", "'connection'", ")", ":", "card", ".", "connection", "=", "card", ".", "createConnection", "(", ")", "if", "None", "!=", "self", ".", "parent", ".", ...
45
0.008174
def natural_keys(text: str) -> List[Union[int, str]]: """ Sort key function. Returns text split into string/number parts, for natural sorting; as per http://stackoverflow.com/questions/5967500/how-to-correctly-sort-a-string-with-a-number-inside Example (as per the source above): .....
[ "def", "natural_keys", "(", "text", ":", "str", ")", "->", "List", "[", "Union", "[", "int", ",", "str", "]", "]", ":", "# noqa", "return", "[", "atoi", "(", "c", ")", "for", "c", "in", "re", ".", "split", "(", "r'(\\d+)'", ",", "text", ")", "]...
33.4
0.001164
def get_object(self, queryset=None): """ Return the object the view is displaying. Same as rest_framework.generics.GenericAPIView, but: - Failed assertions instead of deprecations """ # Determine the base queryset to use. assert queryset is None, "Passing a query...
[ "def", "get_object", "(", "self", ",", "queryset", "=", "None", ")", ":", "# Determine the base queryset to use.", "assert", "queryset", "is", "None", ",", "\"Passing a queryset is disabled\"", "queryset", "=", "self", ".", "filter_queryset", "(", "self", ".", "get_...
38.590909
0.002299
def download(self, name, ids, datas=None, context=None): """Download a report from the server and return it as a remote file. For instance, to download the "Quotation / Order" report of sale orders identified by the IDs ``[2, 3]``: .. doctest:: :options: +SKIP >...
[ "def", "download", "(", "self", ",", "name", ",", "ids", ",", "datas", "=", "None", ",", "context", "=", "None", ")", ":", "if", "context", "is", "None", ":", "context", "=", "self", ".", "_odoo", ".", "env", ".", "context", "def", "check_report", ...
37.05618
0.000591
def tsp_linearize(data, niter=1000, metric='euclidean', **kwargs): """Sorts a matrix dataset to (approximately) solve the traveling salesperson problem. The matrix can be re-sorted so that sequential rows represent datapoints that are close to each other based on some user-defined distance metric. Uses ...
[ "def", "tsp_linearize", "(", "data", ",", "niter", "=", "1000", ",", "metric", "=", "'euclidean'", ",", "*", "*", "kwargs", ")", ":", "# Compute pairwise distances between all datapoints", "N", "=", "data", ".", "shape", "[", "0", "]", "D", "=", "scipy", "...
35.621622
0.000739
def parse_environment_file_list(names, world_size=(60, 60)): """ Extract information about spatial resources from all environment files in a list. Arguments: names - a list of strings representing the paths to the environment files. world_size - a tuple representing the x and y coordinates of t...
[ "def", "parse_environment_file_list", "(", "names", ",", "world_size", "=", "(", "60", ",", "60", ")", ")", ":", "# Convert single file to list if necessary", "try", ":", "names", "[", "0", "]", "=", "names", "[", "0", "]", "except", ":", "names", "=", "["...
30.538462
0.002442