text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def dtype(self): """ Returns the numpy.dtype used to store the point records in a numpy array .. note:: The dtype corresponds to the dtype with sub_fields *packed* into their composed fields """ dtype = self._access_dict(dims.ALL_POINT_FORMATS_DTYPE, self.id) ...
[ "def", "dtype", "(", "self", ")", ":", "dtype", "=", "self", ".", "_access_dict", "(", "dims", ".", "ALL_POINT_FORMATS_DTYPE", ",", "self", ".", "id", ")", "dtype", "=", "self", ".", "_dtype_add_extra_dims", "(", "dtype", ")", "return", "dtype" ]
31.5
0.010283
def consolidate(self, volume, source, dest, *args, **kwargs): """ Consolidate will move a volume of liquid from a list of sources to a single target location. See :any:`Transfer` for details and a full list of optional arguments. Returns ------- This instance of...
[ "def", "consolidate", "(", "self", ",", "volume", ",", "source", ",", "dest", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'mode'", "]", "=", "'consolidate'", "kwargs", "[", "'mix_before'", "]", "=", "(", "0", ",", "0", ")",...
34.888889
0.002066
def _get_samples_shared_with(self, other, index=None): """Find samples shared with another dataset. Args: other (:py:class:`pymds.Projection` or :py:class:`pandas.DataFrame` or `array-like`): The other dataset. If `other` is an instance of...
[ "def", "_get_samples_shared_with", "(", "self", ",", "other", ",", "index", "=", "None", ")", ":", "if", "isinstance", "(", "other", ",", "(", "pd", ".", "DataFrame", ",", "Projection", ")", ")", ":", "df_other", "=", "other", ".", "coords", "if", "isi...
38.435484
0.000818
def poster(self): """ Returns the considered user. """ user_model = get_user_model() return get_object_or_404(user_model, pk=self.kwargs[self.user_pk_url_kwarg])
[ "def", "poster", "(", "self", ")", ":", "user_model", "=", "get_user_model", "(", ")", "return", "get_object_or_404", "(", "user_model", ",", "pk", "=", "self", ".", "kwargs", "[", "self", ".", "user_pk_url_kwarg", "]", ")" ]
45.5
0.016216
def _ping_check(self, ping=1, reconnect=True): """Check whether the connection is still alive using ping(). If the the underlying connection is not active and the ping parameter is set accordingly, the connection will be recreated unless the connection is currently inside a transaction....
[ "def", "_ping_check", "(", "self", ",", "ping", "=", "1", ",", "reconnect", "=", "True", ")", ":", "if", "ping", "&", "self", ".", "_ping", ":", "try", ":", "# if possible, ping the connection", "alive", "=", "self", ".", "_con", ".", "ping", "(", ")",...
37
0.001646
def to_dict(self, *, include_keys=None, exclude_keys=None, use_default_excludes=True): """Converts the class to a dictionary. :include_keys: if not None, only the attrs given will be included. :exclude_keys: if not None, all attrs except those listed will be included, with respect to use_default_exclud...
[ "def", "to_dict", "(", "self", ",", "*", ",", "include_keys", "=", "None", ",", "exclude_keys", "=", "None", ",", "use_default_excludes", "=", "True", ")", ":", "data", "=", "self", ".", "__dict__", "if", "include_keys", ":", "return", "pick", "(", "data...
42.095238
0.009956
def add_igrf(inst, glat_label='glat', glong_label='glong', alt_label='alt'): """ Uses International Geomagnetic Reference Field (IGRF) model to obtain geomagnetic field values. Uses pyglow module to run IGRF. Configured to use actual solar parameters to run ...
[ "def", "add_igrf", "(", "inst", ",", "glat_label", "=", "'glat'", ",", "glong_label", "=", "'glong'", ",", "alt_label", "=", "'alt'", ")", ":", "import", "pyglow", "from", "pyglow", ".", "pyglow", "import", "Point", "import", "pysatMagVect", "igrf_params", "...
42.060976
0.014164
def parse_args(): """ Parse the args, returns if the type of update: Major, minor, fix """ parser = argparse.ArgumentParser() parser.add_argument('-M', action='store_true') parser.add_argument('-m', action='store_true') parser.add_argument('-f', action='store_true') args = parser.parse_a...
[ "def", "parse_args", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "'-M'", ",", "action", "=", "'store_true'", ")", "parser", ".", "add_argument", "(", "'-m'", ",", "action", "=", "'store_tru...
36.692308
0.002045
def __create_weights(self, stimulus): """! @brief Create weights between neurons in line with stimulus. @param[in] stimulus (list): External stimulus for the chaotic neural network. """ self.__average_distance = average_neighbor_distance(stimulu...
[ "def", "__create_weights", "(", "self", ",", "stimulus", ")", ":", "self", ".", "__average_distance", "=", "average_neighbor_distance", "(", "stimulus", ",", "self", ".", "__amount_neighbors", ")", "self", ".", "__weights", "=", "[", "[", "0.0", "for", "_", ...
43.166667
0.021411
def compute_advantages(rollout, last_r, gamma=0.9, lambda_=1.0, use_gae=True): """Given a rollout, compute its value targets and the advantage. Args: rollout (SampleBatch): SampleBatch of a single trajectory last_r (float): Value estimation for last observation gamma (float): Discount f...
[ "def", "compute_advantages", "(", "rollout", ",", "last_r", ",", "gamma", "=", "0.9", ",", "lambda_", "=", "1.0", ",", "use_gae", "=", "True", ")", ":", "traj", "=", "{", "}", "trajsize", "=", "len", "(", "rollout", "[", "SampleBatch", ".", "ACTIONS", ...
39.8125
0.000511
def get_single_fixer(fixname): '''return a single fixer found in the lib2to3 library''' fixer_dirname = fixer_dir.__path__[0] for name in sorted(os.listdir(fixer_dirname)): if (name.startswith("fix_") and name.endswith(".py") and fixname == name[4:-3]): return "lib2to3.fixes...
[ "def", "get_single_fixer", "(", "fixname", ")", ":", "fixer_dirname", "=", "fixer_dir", ".", "__path__", "[", "0", "]", "for", "name", "in", "sorted", "(", "os", ".", "listdir", "(", "fixer_dirname", ")", ")", ":", "if", "(", "name", ".", "startswith", ...
46.857143
0.008982
def add_spec(self, *specs): """Add specs to the topology :type specs: HeronComponentSpec :param specs: specs to add to the topology """ for spec in specs: if not isinstance(spec, HeronComponentSpec): raise TypeError("Argument to add_spec needs to be HeronComponentSpec, given: %s" ...
[ "def", "add_spec", "(", "self", ",", "*", "specs", ")", ":", "for", "spec", "in", "specs", ":", "if", "not", "isinstance", "(", "spec", ",", "HeronComponentSpec", ")", ":", "raise", "TypeError", "(", "\"Argument to add_spec needs to be HeronComponentSpec, given: %...
38.333333
0.011315
def child(self, local_name=None, name=None, ns_uri=None, node_type=None, filter_fn=None): """ :return: the first child node matching the given constraints, or \ *None* if there are no matching child nodes. Delegates to :meth:`NodeList.filter`. """ re...
[ "def", "child", "(", "self", ",", "local_name", "=", "None", ",", "name", "=", "None", ",", "ns_uri", "=", "None", ",", "node_type", "=", "None", ",", "filter_fn", "=", "None", ")", ":", "return", "self", ".", "children", "(", "name", "=", "name", ...
44.9
0.008734
def post_optimization_step(self, batch_info, device, model, rollout): """ Steps to take after optimization has been done""" if batch_info.aggregate_batch_number % self.target_update_frequency == 0: self.target_model.load_state_dict(model.state_dict()) self.target_model.eval()
[ "def", "post_optimization_step", "(", "self", ",", "batch_info", ",", "device", ",", "model", ",", "rollout", ")", ":", "if", "batch_info", ".", "aggregate_batch_number", "%", "self", ".", "target_update_frequency", "==", "0", ":", "self", ".", "target_model", ...
62.4
0.009494
def fetch_git_sha(path, head=None): """ >>> fetch_git_sha(os.path.dirname(__file__)) """ if not head: head_path = os.path.join(path, '.git', 'HEAD') if not os.path.exists(head_path): raise InvalidGitRepository( 'Cannot identify HEAD for git repository at %s' %...
[ "def", "fetch_git_sha", "(", "path", ",", "head", "=", "None", ")", ":", "if", "not", "head", ":", "head_path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "'.git'", ",", "'HEAD'", ")", "if", "not", "os", ".", "path", ".", "exists", "(...
37.166667
0.001092
def set_expire(name, date): ''' Sets the date on which the account expires. The user will not be able to login after this date. Date format is mm/dd/yyyy :param str name: The name of the user account :param datetime date: The date the account will expire. Format must be mm/dd/yyyy. :r...
[ "def", "set_expire", "(", "name", ",", "date", ")", ":", "_set_account_policy", "(", "name", ",", "'usingHardExpirationDate=1 hardExpireDateGMT={0}'", ".", "format", "(", "date", ")", ")", "return", "get_expire", "(", "name", ")", "==", "date" ]
27.24
0.001418
def delete(filename, delete_v1=True, delete_v2=True): """Remove tags from a file. Keyword arguments: * delete_v1 -- delete any ID3v1 tag * delete_v2 -- delete any ID3v2 tag """ f = open(filename, 'rb+') if delete_v1: try: f.seek(-128, 2) except IOError: ...
[ "def", "delete", "(", "filename", ",", "delete_v1", "=", "True", ",", "delete_v2", "=", "True", ")", ":", "f", "=", "open", "(", "filename", ",", "'rb+'", ")", "if", "delete_v1", ":", "try", ":", "f", ".", "seek", "(", "-", "128", ",", "2", ")", ...
26.151515
0.001117
def bfgs(x0, rho, f_df, maxiter=50, method='BFGS'): """ Proximal operator for minimizing an arbitrary function using BFGS Uses the BFGS algorithm to find the proximal update for an arbitrary function, `f`, whose gradient is known. Parameters ---------- x0 : array_like The starting or i...
[ "def", "bfgs", "(", "x0", ",", "rho", ",", "f_df", ",", "maxiter", "=", "50", ",", "method", "=", "'BFGS'", ")", ":", "# keep track of the original shape", "orig_shape", "=", "x0", ".", "shape", "# specify the objective function and gradient for the proximal operator"...
28.215686
0.002015
def __get_average_inter_cluster_distance(self, entry): """! @brief Calculates average inter cluster distance between current and specified clusters. @param[in] entry (cfentry): Clustering feature to which distance should be obtained. @return (double) Average inter...
[ "def", "__get_average_inter_cluster_distance", "(", "self", ",", "entry", ")", ":", "linear_part_distance", "=", "sum", "(", "list_math_multiplication", "(", "self", ".", "linear_sum", ",", "entry", ".", "linear_sum", ")", ")", "return", "(", "(", "entry", ".", ...
49.923077
0.022693
def _reset_state(self): """! @brief Clear all state variables. """ self._builders = {} self._total_data_size = 0 self._progress_offset = 0 self._current_progress_fraction = 0
[ "def", "_reset_state", "(", "self", ")", ":", "self", ".", "_builders", "=", "{", "}", "self", ".", "_total_data_size", "=", "0", "self", ".", "_progress_offset", "=", "0", "self", ".", "_current_progress_fraction", "=", "0" ]
34.833333
0.009346
def setecho(self, state): '''This sets the terminal echo mode on or off. Note that anything the child sent before the echo will be lost, so you should be sure that your input buffer is empty before you call setecho(). For example, the following will work as expected:: p = pe...
[ "def", "setecho", "(", "self", ",", "state", ")", ":", "_setecho", "(", "self", ".", "fd", ",", "state", ")", "self", ".", "echo", "=", "state" ]
41.028571
0.001361
def summarize_address_range(first, last): """Summarize a network range given the first and last IP addresses. Example: >>> list(summarize_address_range(IPv4Address('192.0.2.0'), ... IPv4Address('192.0.2.130'))) ... #doctest: +N...
[ "def", "summarize_address_range", "(", "first", ",", "last", ")", ":", "if", "(", "not", "(", "isinstance", "(", "first", ",", "_BaseAddress", ")", "and", "isinstance", "(", "last", ",", "_BaseAddress", ")", ")", ")", ":", "raise", "TypeError", "(", "'fi...
36.407407
0.000495
def data_find_all(data, path, dyn_cls=False): """Find and return all element-as-tuples in tuple ``data`` using simplified XPath ``path``. """ path_parts = path.split("/") try: sub_elms = tuple( el for el in data if isinstance(el, (tuple, list)) and el[0] =...
[ "def", "data_find_all", "(", "data", ",", "path", ",", "dyn_cls", "=", "False", ")", ":", "path_parts", "=", "path", ".", "split", "(", "\"/\"", ")", "try", ":", "sub_elms", "=", "tuple", "(", "el", "for", "el", "in", "data", "if", "isinstance", "(",...
29.68
0.001305
def generate(env): """Add Builders and construction variables for Ghostscript to an Environment.""" global GhostscriptAction # The following try-except block enables us to use the Tool # in standalone mode (without the accompanying pdf.py), # whenever we need an explicit call of gs via the Gs() ...
[ "def", "generate", "(", "env", ")", ":", "global", "GhostscriptAction", "# The following try-except block enables us to use the Tool", "# in standalone mode (without the accompanying pdf.py),", "# whenever we need an explicit call of gs via the Gs()", "# Builder ...", "try", ":", "if", ...
35.961538
0.009375
def build_default_endpoint_prefixes(records_rest_endpoints): """Build the default_endpoint_prefixes map.""" pid_types = set() guessed = set() endpoint_prefixes = {} for key, endpoint in records_rest_endpoints.items(): pid_type = endpoint['pid_type'] pid_types.add(pid_type) i...
[ "def", "build_default_endpoint_prefixes", "(", "records_rest_endpoints", ")", ":", "pid_types", "=", "set", "(", ")", "guessed", "=", "set", "(", ")", "endpoint_prefixes", "=", "{", "}", "for", "key", ",", "endpoint", "in", "records_rest_endpoints", ".", "items"...
34.7
0.000935
def cigar_to_seq(a, gap='*'): """ Accepts a pysam row. cigar alignment is presented as a list of tuples (operation,length). For example, the tuple [ (0,3), (1,5), (0,2) ] refers to an alignment with 3 matches, 5 insertions and another 2 matches. Op BAM Description M 0 alignment match (can ...
[ "def", "cigar_to_seq", "(", "a", ",", "gap", "=", "'*'", ")", ":", "seq", ",", "cigar", "=", "a", ".", "seq", ",", "a", ".", "cigar", "start", "=", "0", "subseqs", "=", "[", "]", "npadded", "=", "0", "if", "cigar", "is", "None", ":", "return", ...
29.897959
0.000661
def rfc2426(self): """Get the RFC2426 representation of `self`. :return: the UTF-8 encoded RFC2426 representation. :returntype: `str`""" ret="begin:VCARD\r\n" ret+="version:3.0\r\n" for _unused, value in self.content.items(): if value is None: ...
[ "def", "rfc2426", "(", "self", ")", ":", "ret", "=", "\"begin:VCARD\\r\\n\"", "ret", "+=", "\"version:3.0\\r\\n\"", "for", "_unused", ",", "value", "in", "self", ".", "content", ".", "items", "(", ")", ":", "if", "value", "is", "None", ":", "continue", "...
31.058824
0.012868
def is_analysis_instrument_valid(self, analysis_brain): """Return if the analysis has a valid instrument. If the analysis passed in is from ReferenceAnalysis type or does not have an instrument assigned, returns True :param analysis_brain: Brain that represents an analysis :ret...
[ "def", "is_analysis_instrument_valid", "(", "self", ",", "analysis_brain", ")", ":", "if", "analysis_brain", ".", "meta_type", "==", "'ReferenceAnalysis'", ":", "# If this is a ReferenceAnalysis, there is no need to check the", "# validity of the instrument, because this is a QC anal...
52.5625
0.002336
def default(self, obj): """If input object is an ndarray it will be converted into a dict holding dtype, shape and the data, base64 encoded and blosc compressed. """ if isinstance(obj, np.ndarray): if obj.flags['C_CONTIGUOUS']: obj_data = obj.data ...
[ "def", "default", "(", "self", ",", "obj", ")", ":", "if", "isinstance", "(", "obj", ",", "np", ".", "ndarray", ")", ":", "if", "obj", ".", "flags", "[", "'C_CONTIGUOUS'", "]", ":", "obj_data", "=", "obj", ".", "data", "else", ":", "cont_obj", "=",...
46.142857
0.002022
def _pages_to_generate(self): '''Return list of slugs that correspond to pages to generate.''' # right now it gets all the files. In theory, It should only # get what's changed... but the program is not doing that yet. all_pages = self.get_page_names() # keep only those whose st...
[ "def", "_pages_to_generate", "(", "self", ")", ":", "# right now it gets all the files. In theory, It should only", "# get what's changed... but the program is not doing that yet.", "all_pages", "=", "self", ".", "get_page_names", "(", ")", "# keep only those whose status is published"...
44.058824
0.010458
def _extract_delta(expr, idx): """Extract a "simple" Kronecker delta containing `idx` from `expr`. Assuming `expr` can be written as the product of a Kronecker Delta and a `new_expr`, return a tuple of the sympy.KroneckerDelta instance and `new_expr`. Otherwise, return a tuple of None and the original ...
[ "def", "_extract_delta", "(", "expr", ",", "idx", ")", ":", "from", "qnet", ".", "algebra", ".", "core", ".", "abstract_quantum_algebra", "import", "QuantumExpression", "from", "qnet", ".", "algebra", ".", "core", ".", "scalar_algebra", "import", "ScalarValue", ...
45.458333
0.000898
def _approx_equal(x, y, eps): """Test if elements ``x`` and ``y`` are approximately equal. ``eps`` is a given absolute tolerance. """ if x.space != y.space: return False if x is y: return True try: return x.dist(y) <= eps except NotImplementedError: try: ...
[ "def", "_approx_equal", "(", "x", ",", "y", ",", "eps", ")", ":", "if", "x", ".", "space", "!=", "y", ".", "space", ":", "return", "False", "if", "x", "is", "y", ":", "return", "True", "try", ":", "return", "x", ".", "dist", "(", "y", ")", "<...
21.5
0.002475
def radiated_intensity(rho, i, j, epsilonp, rm, omega_level, xi, N, D, unfolding): r"""Return the radiated intensity in a given direction. >>> from fast import State, Integer, split_hyperfine_to_magnetic >>> g = State("Rb", 87, 5, 1, 3/Integer(2), 0) >>> e = State("Rb", 87, 4, 2,...
[ "def", "radiated_intensity", "(", "rho", ",", "i", ",", "j", ",", "epsilonp", ",", "rm", ",", "omega_level", ",", "xi", ",", "N", ",", "D", ",", "unfolding", ")", ":", "def", "inij", "(", "i", ",", "j", ",", "ilist", ",", "jlist", ")", ":", "if...
29.813953
0.000378
def _ensure_counter(self): """Ensure counter exists in Consul.""" if self._counter_path not in self._client.kv: self._client.kv[self._counter_path] = ''.zfill(self._COUNTER_FILL)
[ "def", "_ensure_counter", "(", "self", ")", ":", "if", "self", ".", "_counter_path", "not", "in", "self", ".", "_client", ".", "kv", ":", "self", ".", "_client", ".", "kv", "[", "self", ".", "_counter_path", "]", "=", "''", ".", "zfill", "(", "self",...
50.75
0.009709
def rover_turn_circle(SERVO_OUTPUT_RAW): '''return turning circle (diameter) in meters for steering_angle in degrees ''' # this matches Toms slash max_wheel_turn = 35 wheelbase = 0.335 wheeltrack = 0.296 steering_angle = max_wheel_turn * (SERVO_OUTPUT_RAW.servo1_raw - 1500) / 400....
[ "def", "rover_turn_circle", "(", "SERVO_OUTPUT_RAW", ")", ":", "# this matches Toms slash", "max_wheel_turn", "=", "35", "wheelbase", "=", "0.335", "wheeltrack", "=", "0.296", "steering_angle", "=", "max_wheel_turn", "*", "(", "SERVO_OUTPUT_RAW", ".", "servo1_raw", "-...
33.083333
0.009804
def abu_chartMulti(self, cyclist, mass_range=None, ilabel=True, imlabel=True, imlabel_fontsize=8, imagic=False, boxstable=True, lbound=20, plotaxis=[0,0,0,0], color_map='jet', pdf=False, title=None, path=None): ''' Method that plots ab...
[ "def", "abu_chartMulti", "(", "self", ",", "cyclist", ",", "mass_range", "=", "None", ",", "ilabel", "=", "True", ",", "imlabel", "=", "True", ",", "imlabel_fontsize", "=", "8", ",", "imagic", "=", "False", ",", "boxstable", "=", "True", ",", "lbound", ...
43.9
0.008912
def generate(env): """Add Builders and construction variables for aCC & cc to an Environment.""" cc.generate(env) env['CXX'] = 'aCC' env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS +Z')
[ "def", "generate", "(", "env", ")", ":", "cc", ".", "generate", "(", "env", ")", "env", "[", "'CXX'", "]", "=", "'aCC'", "env", "[", "'SHCCFLAGS'", "]", "=", "SCons", ".", "Util", ".", "CLVar", "(", "'$CCFLAGS +Z'", ")" ]
33.833333
0.019231
def grab_hotkey(self, item): """ Grab a hotkey. If the hotkey has no filter regex, it is global and is grabbed recursively from the root window If it has a filter regex, iterate over all children of the root and grab from matching windows """ if item.get_applicable_regex...
[ "def", "grab_hotkey", "(", "self", ",", "item", ")", ":", "if", "item", ".", "get_applicable_regex", "(", ")", "is", "None", ":", "self", ".", "__enqueue", "(", "self", ".", "__grabHotkey", ",", "item", ".", "hotKey", ",", "item", ".", "modifiers", ","...
48.230769
0.00939
def get_channels(self): """Get all tv channels.""" self.request(EP_GET_TV_CHANNELS) return {} if self.last_response is None else self.last_response.get('payload').get('channelList')
[ "def", "get_channels", "(", "self", ")", ":", "self", ".", "request", "(", "EP_GET_TV_CHANNELS", ")", "return", "{", "}", "if", "self", ".", "last_response", "is", "None", "else", "self", ".", "last_response", ".", "get", "(", "'payload'", ")", ".", "get...
50.5
0.014634
def duplicate_node(self, node, x, y, z): """ Duplicate a node :param node: Node instance :param x: X position :param y: Y position :param z: Z position :returns: New node """ if node.status != "stopped" and not node.is_always_running(): ...
[ "def", "duplicate_node", "(", "self", ",", "node", ",", "x", ",", "y", ",", "z", ")", ":", "if", "node", ".", "status", "!=", "\"stopped\"", "and", "not", "node", ".", "is_always_running", "(", ")", ":", "raise", "aiohttp", ".", "web", ".", "HTTPConf...
35.145833
0.002307
def _add_labels(self, axes, dtype): """Given a 2x2 array of axes, add x and y labels Parameters ---------- axes: numpy.ndarray, 2x2 A numpy array containing the four principal axes of an SIP plot dtype: string Can be either 'rho' or 'r', indicating the ty...
[ "def", "_add_labels", "(", "self", ",", "axes", ",", "dtype", ")", ":", "for", "ax", "in", "axes", "[", "1", ",", ":", "]", ".", "flat", ":", "ax", ".", "set_xlabel", "(", "'frequency [Hz]'", ")", "if", "dtype", "==", "'rho'", ":", "axes", "[", "...
36.096774
0.001741
def project_hours_for_contract(contract, project, billable=None): """Total billable hours worked on project for contract. If billable is passed as 'billable' or 'nonbillable', limits to the corresponding hours. (Must pass a variable name first, of course.) """ hours = contract.entries.filter(projec...
[ "def", "project_hours_for_contract", "(", "contract", ",", "project", ",", "billable", "=", "None", ")", ":", "hours", "=", "contract", ".", "entries", ".", "filter", "(", "project", "=", "project", ")", "if", "billable", "is", "not", "None", ":", "if", ...
48
0.001277
def biopax_process_pc_pathsfromto(): """Process PathwayCommons paths from-to genes, return INDRA Statements.""" if request.method == 'OPTIONS': return {} response = request.body.read().decode('utf-8') body = json.loads(response) source = body.get('source') target = body.get('target') ...
[ "def", "biopax_process_pc_pathsfromto", "(", ")", ":", "if", "request", ".", "method", "==", "'OPTIONS'", ":", "return", "{", "}", "response", "=", "request", ".", "body", ".", "read", "(", ")", ".", "decode", "(", "'utf-8'", ")", "body", "=", "json", ...
39.4
0.002481
def get_login(self, use_session=True): """ Get an active login session @param use_session: Use a saved session file if available @type use_session: bool """ # Should we try and return an existing login session? if use_session and self._login.check(): ...
[ "def", "get_login", "(", "self", ",", "use_session", "=", "True", ")", ":", "# Should we try and return an existing login session?", "if", "use_session", "and", "self", ".", "_login", ".", "check", "(", ")", ":", "self", ".", "cookiejar", "=", "self", ".", "_l...
36.090909
0.002454
async def _transmit(self): """ Transmit outbound data. """ # send FORWARD TSN if self._forward_tsn_chunk is not None: await self._send_chunk(self._forward_tsn_chunk) self._forward_tsn_chunk = None # ensure T3 is running if not self...
[ "async", "def", "_transmit", "(", "self", ")", ":", "# send FORWARD TSN", "if", "self", ".", "_forward_tsn_chunk", "is", "not", "None", ":", "await", "self", ".", "_send_chunk", "(", "self", ".", "_forward_tsn_chunk", ")", "self", ".", "_forward_tsn_chunk", "=...
33.75
0.001107
def take_notification(self, block=True, timeout=None): '''take_notification High-level api: Receive notification messages. Parameters ---------- block : `bool` True if this is a blocking call. timeout : `int` Timeout value in seconds. ...
[ "def", "take_notification", "(", "self", ",", "block", "=", "True", ",", "timeout", "=", "None", ")", ":", "reply", "=", "super", "(", ")", ".", "take_notification", "(", "block", "=", "block", ",", "timeout", "=", "timeout", ")", "if", "isinstance", "...
26.305556
0.002037
def list(self, start_date=values.unset, end_date=values.unset, identity=values.unset, tag=values.unset, limit=None, page_size=None): """ Lists BindingInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory b...
[ "def", "list", "(", "self", ",", "start_date", "=", "values", ".", "unset", ",", "end_date", "=", "values", ".", "unset", ",", "identity", "=", "values", ".", "unset", ",", "tag", "=", "values", ".", "unset", ",", "limit", "=", "None", ",", "page_siz...
53.655172
0.008207
def infer_import_from(self, context=None, asname=True): """infer a ImportFrom node: return the imported module/object""" name = context.lookupname if name is None: raise exceptions.InferenceError(node=self, context=context) if asname: name = self.real_name(name) try: module ...
[ "def", "infer_import_from", "(", "self", ",", "context", "=", "None", ",", "asname", "=", "True", ")", ":", "name", "=", "context", ".", "lookupname", "if", "name", "is", "None", ":", "raise", "exceptions", ".", "InferenceError", "(", "node", "=", "self"...
39.136364
0.001134
def list_files(dirname='.', digest=True): """Yield (digest, fname) tuples for all interesting files in `dirname`. """ skipdirs = ['__pycache__', '.git', '.svn', 'htmlcov', 'dist', 'build', '.idea', 'tasks', 'static', 'media', 'data', 'migrations', '.doctrees', '_static...
[ "def", "list_files", "(", "dirname", "=", "'.'", ",", "digest", "=", "True", ")", ":", "skipdirs", "=", "[", "'__pycache__'", ",", "'.git'", ",", "'.svn'", ",", "'htmlcov'", ",", "'dist'", ",", "'build'", ",", "'.idea'", ",", "'tasks'", ",", "'static'", ...
34.527273
0.001024
def _proxy(self): """ Generate an instance context for the instance, the context is capable of performing various actions. All instance actions are proxied to the context :returns: AssistantContext for this AssistantInstance :rtype: twilio.rest.autopilot.v1.assistant.AssistantC...
[ "def", "_proxy", "(", "self", ")", ":", "if", "self", ".", "_context", "is", "None", ":", "self", ".", "_context", "=", "AssistantContext", "(", "self", ".", "_version", ",", "sid", "=", "self", ".", "_solution", "[", "'sid'", "]", ",", ")", "return"...
43.636364
0.010204
def inspect_network(self, net_id, verbose=None, scope=None): """ Get detailed information about a network. Args: net_id (str): ID of network verbose (bool): Show the service details across the cluster in swarm mode. scope (str): Filter the net...
[ "def", "inspect_network", "(", "self", ",", "net_id", ",", "verbose", "=", "None", ",", "scope", "=", "None", ")", ":", "params", "=", "{", "}", "if", "verbose", "is", "not", "None", ":", "if", "version_lt", "(", "self", ".", "_version", ",", "'1.28'...
38.333333
0.002121
def cursor(self, user=None, configuration=None, convert_types=True, dictify=False, fetch_error=True): """Get a cursor from the HiveServer2 (HS2) connection. Parameters ---------- user : str, optional configuration : dict of str keys and values, optional ...
[ "def", "cursor", "(", "self", ",", "user", "=", "None", ",", "configuration", "=", "None", ",", "convert_types", "=", "True", ",", "dictify", "=", "False", ",", "fetch_error", "=", "True", ")", ":", "# PEP 249", "log", ".", "debug", "(", "'Getting a curs...
44.459016
0.001443
def ask_question(self, field_name, pattern=NAME_PATTERN, is_required=False, password=False): """Ask a question and get the input values. This method will validade the input values. Args: field_name(string): Field name used to ask for input value. pat...
[ "def", "ask_question", "(", "self", ",", "field_name", ",", "pattern", "=", "NAME_PATTERN", ",", "is_required", "=", "False", ",", "password", "=", "False", ")", ":", "input_value", "=", "\"\"", "question", "=", "(", "\"Insert the field using the pattern below:\""...
38.944444
0.002088
def CheckForCopyright(filename, lines, error): """Logs an error if no Copyright message appears at the top of the file.""" # We'll say it should occur by line 10. Don't forget there's a # dummy line at the front. for line in range(1, min(len(lines), 11)): if re.search(r'Copyright', lines[line], re.I): brea...
[ "def", "CheckForCopyright", "(", "filename", ",", "lines", ",", "error", ")", ":", "# We'll say it should occur by line 10. Don't forget there's a", "# dummy line at the front.", "for", "line", "in", "range", "(", "1", ",", "min", "(", "len", "(", "lines", ")", ",",...
48.909091
0.012774
def nps_survey_show(self, id, **kwargs): "https://developer.zendesk.com/rest_api/docs/nps-api/surveys#show-survey" api_path = "/api/v2/nps/surveys/{id}" api_path = api_path.format(id=id) return self.call(api_path, **kwargs)
[ "def", "nps_survey_show", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/nps/surveys/{id}\"", "api_path", "=", "api_path", ".", "format", "(", "id", "=", "id", ")", "return", "self", ".", "call", "(", "api_path", "...
50.2
0.011765
def find(file): '''tries to find ``file`` using OS-specific searches and some guessing''' # Try MacOS Spotlight: mdfind = which('mdfind') if mdfind: out = run([mdfind,'-name',file],stderr=None,quiet=None) if out.return_code==0 and out.output: for fname in out.output.split...
[ "def", "find", "(", "file", ")", ":", "# Try MacOS Spotlight:", "mdfind", "=", "which", "(", "'mdfind'", ")", "if", "mdfind", ":", "out", "=", "run", "(", "[", "mdfind", ",", "'-name'", ",", "file", "]", ",", "stderr", "=", "None", ",", "quiet", "=",...
37.942857
0.014684
def _chorder(self): """Add <interleave> if child order is arbitrary.""" if (self.interleave and len([ c for c in self.children if ":" not in c.name ]) > 1): return "<interleave>%s</interleave>" return "%s"
[ "def", "_chorder", "(", "self", ")", ":", "if", "(", "self", ".", "interleave", "and", "len", "(", "[", "c", "for", "c", "in", "self", ".", "children", "if", "\":\"", "not", "in", "c", ".", "name", "]", ")", ">", "1", ")", ":", "return", "\"<in...
41.333333
0.019763
def aeration_data(DO_column, dirpath): """Extract the data from folder containing tab delimited files of aeration data. The file must be the original tab delimited file. All text strings below the header must be removed from these files. The file names must be the air flow rates with units of micromoles...
[ "def", "aeration_data", "(", "DO_column", ",", "dirpath", ")", ":", "#return the list of files in the directory", "filenames", "=", "os", ".", "listdir", "(", "dirpath", ")", "#extract the flowrates from the filenames and apply units", "airflows", "=", "(", "(", "np", "...
61.894737
0.010883
def close(self): '''close the window''' self.close_window.release() count=0 while self.child.is_alive() and count < 30: # 3 seconds to die... time.sleep(0.1) #? count+=1 if self.child.is_alive(): self.child.terminate() self.child.join...
[ "def", "close", "(", "self", ")", ":", "self", ".", "close_window", ".", "release", "(", ")", "count", "=", "0", "while", "self", ".", "child", ".", "is_alive", "(", ")", "and", "count", "<", "30", ":", "# 3 seconds to die...", "time", ".", "sleep", ...
25.916667
0.021739
def run_rnaseq_ann_filter(data): """Run RNA-seq annotation and filtering. """ data = to_single_data(data) if dd.get_vrn_file(data): eff_file = effects.add_to_vcf(dd.get_vrn_file(data), data)[0] if eff_file: data = dd.set_vrn_file(data, eff_file) ann_file = population....
[ "def", "run_rnaseq_ann_filter", "(", "data", ")", ":", "data", "=", "to_single_data", "(", "data", ")", "if", "dd", ".", "get_vrn_file", "(", "data", ")", ":", "eff_file", "=", "effects", ".", "add_to_vcf", "(", "dd", ".", "get_vrn_file", "(", "data", ")...
43.3
0.00113
def remove_son(self, son): """ Remove the son node. Do nothing if the node is not a son Args: fathers: list of fathers to add """ self._sons = [x for x in self._sons if x.node_id != son.node_id]
[ "def", "remove_son", "(", "self", ",", "son", ")", ":", "self", ".", "_sons", "=", "[", "x", "for", "x", "in", "self", ".", "_sons", "if", "x", ".", "node_id", "!=", "son", ".", "node_id", "]" ]
33.285714
0.008368
def open_gateway(self): """ Obtain a socket-like object from `gateway`. :returns: A ``direct-tcpip`` `paramiko.channel.Channel`, if `gateway` was a `.Connection`; or a `~paramiko.proxy.ProxyCommand`, if `gateway` was a string. .. versionadded:: 2.0 ...
[ "def", "open_gateway", "(", "self", ")", ":", "# ProxyCommand is faster to set up, so do it first.", "if", "isinstance", "(", "self", ".", "gateway", ",", "string_types", ")", ":", "# Leverage a dummy SSHConfig to ensure %h/%p/etc are parsed.", "# TODO: use real SSH config once l...
45.820513
0.001096
def _merge_element_contents(el): """ Removes an element, but merges its contents into its place, e.g., given <p>Hi <i>there!</i></p>, if you remove the <i> element you get <p>Hi there!</p> """ parent = el.getparent() text = el.text or '' if el.tail: if not len(el): te...
[ "def", "_merge_element_contents", "(", "el", ")", ":", "parent", "=", "el", ".", "getparent", "(", ")", "text", "=", "el", ".", "text", "or", "''", "if", "el", ".", "tail", ":", "if", "not", "len", "(", "el", ")", ":", "text", "+=", "el", ".", ...
27.636364
0.001059
def create_avg_edisp(skydir, ltc, event_class, event_types, erec, egy, cth_bins, npts=None): """Generate model for exposure-weighted DRM averaged over incidence angle. Parameters ---------- egy : `~numpy.ndarray` True energies in MeV. cth_bins : `~numpy.ndarray` ...
[ "def", "create_avg_edisp", "(", "skydir", ",", "ltc", ",", "event_class", ",", "event_types", ",", "erec", ",", "egy", ",", "cth_bins", ",", "npts", "=", "None", ")", ":", "return", "create_avg_rsp", "(", "create_edisp", ",", "skydir", ",", "ltc", ",", "...
32.5625
0.001866
def _get_plural_legacy(amount, extra_variants): """ Get proper case with value (legacy variant, without absence) @param amount: amount of objects @type amount: C{integer types} @param variants: variants (forms) of object in such form: (1 object, 2 objects, 5 objects, 0-object variant). ...
[ "def", "_get_plural_legacy", "(", "amount", ",", "extra_variants", ")", ":", "absence", "=", "None", "if", "isinstance", "(", "extra_variants", ",", "six", ".", "text_type", ")", ":", "extra_variants", "=", "split_values", "(", "extra_variants", ")", "if", "le...
34.72
0.001121
def get_probs(data, prob_column=None): """ Checks for presence of a probability column and returns the result as a numpy array. If the probabilities are weights (i.e. they don't sum to 1), then this will be recalculated. Parameters ---------- data: pandas.DataFrame Table to sample f...
[ "def", "get_probs", "(", "data", ",", "prob_column", "=", "None", ")", ":", "if", "prob_column", "is", "None", ":", "p", "=", "None", "else", ":", "p", "=", "data", "[", "prob_column", "]", ".", "fillna", "(", "0", ")", ".", "values", "if", "p", ...
26.592593
0.001344
def main(global_config, **settings): """ This function returns a Pyramid WSGI application. """ config = Configurator(settings=settings) config.set_session_factory(session_factory) config.include('pyramid_jinja2') config.add_static_view('static', 'static', cache_max_age=3600) config.add_route...
[ "def", "main", "(", "global_config", ",", "*", "*", "settings", ")", ":", "config", "=", "Configurator", "(", "settings", "=", "settings", ")", "config", ".", "set_session_factory", "(", "session_factory", ")", "config", ".", "include", "(", "'pyramid_jinja2'"...
38.583333
0.00211
def fix_text_escapes(self, txt: str, quote_char: str) -> str: """ Fix the various text escapes """ def _subf(matchobj): return matchobj.group(0).translate(self.re_trans_table) if quote_char: txt = re.sub(r'\\'+quote_char, quote_char, txt) return re.sub(r'\\.', _su...
[ "def", "fix_text_escapes", "(", "self", ",", "txt", ":", "str", ",", "quote_char", ":", "str", ")", "->", "str", ":", "def", "_subf", "(", "matchobj", ")", ":", "return", "matchobj", ".", "group", "(", "0", ")", ".", "translate", "(", "self", ".", ...
52.428571
0.008043
def invite(self, address, text=None, *, mode=InviteMode.DIRECT, allow_upgrade=False): """ Invite another entity to the conversation. :param address: The address of the entity to invite. :type address: :class:`aioxmpp.JID` :param text: A reason/accom...
[ "def", "invite", "(", "self", ",", "address", ",", "text", "=", "None", ",", "*", ",", "mode", "=", "InviteMode", ".", "DIRECT", ",", "allow_upgrade", "=", "False", ")", ":", "raise", "self", ".", "_not_implemented_error", "(", "\"inviting entities\"", ")"...
44.523077
0.001352
def get_pending_computer_name(): ''' Get a pending computer name. If the computer name has been changed, and the change is pending a system reboot, this function will return the pending computer name. Otherwise, ``None`` will be returned. If there was an error retrieving the pending computer name, `...
[ "def", "get_pending_computer_name", "(", ")", ":", "current", "=", "get_computer_name", "(", ")", "pending", "=", "__utils__", "[", "'reg.read_value'", "]", "(", "'HKLM'", ",", "r'SYSTEM\\CurrentControlSet\\Services\\Tcpip\\Parameters'", ",", "'NV Hostname'", ")", "[", ...
34.333333
0.002099
def stack1d(*points): """Fill out the columns of matrix with a series of points. This is because ``np.hstack()`` will just make another 1D vector out of them and ``np.vstack()`` will put them in the rows. Args: points (Tuple[numpy.ndarray, ...]): Tuple of 1D points (i.e. arrays wit...
[ "def", "stack1d", "(", "*", "points", ")", ":", "result", "=", "np", ".", "empty", "(", "(", "2", ",", "len", "(", "points", ")", ")", ",", "order", "=", "\"F\"", ")", "for", "index", ",", "point", "in", "enumerate", "(", "points", ")", ":", "r...
31.888889
0.001692
def get_member_class(resource): """ Returns the registered member class for the given resource. :param resource: registered resource :type resource: class implementing or instance providing or subclass of a registered resource interface. """ reg = get_current_registry() if IInterfac...
[ "def", "get_member_class", "(", "resource", ")", ":", "reg", "=", "get_current_registry", "(", ")", "if", "IInterface", "in", "provided_by", "(", "resource", ")", ":", "member_class", "=", "reg", ".", "getUtility", "(", "resource", ",", "name", "=", "'member...
37.333333
0.001742
def _load_types(root): """Returns {name: Type}""" def text(t): if t.tag == 'name': return '{name}' elif t.tag == 'apientry': return '{apientry}' out = [] if t.text: out.append(_escape_tpl_str(t.text)) for x in t: out.append(...
[ "def", "_load_types", "(", "root", ")", ":", "def", "text", "(", "t", ")", ":", "if", "t", ".", "tag", "==", "'name'", ":", "return", "'{name}'", "elif", "t", ".", "tag", "==", "'apientry'", ":", "return", "'{apientry}'", "out", "=", "[", "]", "if"...
31.290323
0.001
def findStationCodesByCity(city_name, token): """Lookup AQI database for station codes in a given city.""" req = requests.get( API_ENDPOINT_SEARCH, params={ 'token': token, 'keyword': city_name }) if req.status_code == 200 and req.json()["status"] == "ok": ...
[ "def", "findStationCodesByCity", "(", "city_name", ",", "token", ")", ":", "req", "=", "requests", ".", "get", "(", "API_ENDPOINT_SEARCH", ",", "params", "=", "{", "'token'", ":", "token", ",", "'keyword'", ":", "city_name", "}", ")", "if", "req", ".", "...
30.538462
0.002445
def base_object(self, obj): """ Sets the base object to apply the setups to. :param obj: the object to use (must be serializable!) :type obj: JavaObject """ if not obj.is_serializable: raise Exception("Base object must be serializable: " + obj.classname) ...
[ "def", "base_object", "(", "self", ",", "obj", ")", ":", "if", "not", "obj", ".", "is_serializable", ":", "raise", "Exception", "(", "\"Base object must be serializable: \"", "+", "obj", ".", "classname", ")", "javabridge", ".", "call", "(", "self", ".", "jo...
40.3
0.009709
def get_dict(self, u=None): """ A recursive function to return the content of the tree in a dict.""" if u is None: return self.get_dict(self.root) children = [] for v in self.adj_list[u]: children.append(self.get_dict(v)) ret = {"name": u, "children": chil...
[ "def", "get_dict", "(", "self", ",", "u", "=", "None", ")", ":", "if", "u", "is", "None", ":", "return", "self", ".", "get_dict", "(", "self", ".", "root", ")", "children", "=", "[", "]", "for", "v", "in", "self", ".", "adj_list", "[", "u", "]"...
37.333333
0.008721
def pad(text, bits=32): """ Pads the inputted text to ensure it fits the proper block length for encryption. :param text | <str> bits | <int> :return <str> """ return text + (bits - len(text) % bits) * chr(bits - len(text) % bits)
[ "def", "pad", "(", "text", ",", "bits", "=", "32", ")", ":", "return", "text", "+", "(", "bits", "-", "len", "(", "text", ")", "%", "bits", ")", "*", "chr", "(", "bits", "-", "len", "(", "text", ")", "%", "bits", ")" ]
25.727273
0.010239
def schemaNewParserCtxt(URL): """Create an XML Schemas parse context for that file/resource expected to contain an XML Schemas file. """ ret = libxml2mod.xmlSchemaNewParserCtxt(URL) if ret is None:raise parserError('xmlSchemaNewParserCtxt() failed') return SchemaParserCtxt(_obj=ret)
[ "def", "schemaNewParserCtxt", "(", "URL", ")", ":", "ret", "=", "libxml2mod", ".", "xmlSchemaNewParserCtxt", "(", "URL", ")", "if", "ret", "is", "None", ":", "raise", "parserError", "(", "'xmlSchemaNewParserCtxt() failed'", ")", "return", "SchemaParserCtxt", "(", ...
50.166667
0.009804
def bitfield_to_boolean_mask(bitfield, ignore_flags=0, flip_bits=None, good_mask_value=True, dtype=np.bool_): """ bitfield_to_boolean_mask(bitfield, ignore_flags=None, flip_bits=None, \ good_mask_value=True, dtype=numpy.bool\_) Converts an array of bit fields to a boolean (or in...
[ "def", "bitfield_to_boolean_mask", "(", "bitfield", ",", "ignore_flags", "=", "0", ",", "flip_bits", "=", "None", ",", "good_mask_value", "=", "True", ",", "dtype", "=", "np", ".", "bool_", ")", ":", "bitfield", "=", "np", ".", "asarray", "(", "bitfield", ...
49.226804
0.000924
def _constructClassificationRecord(self): """ Construct a _HTMClassificationRecord based on the current state of the htm_prediction_model of this classifier. ***This will look into the internals of the model and may depend on the SP, TM, and KNNClassifier*** """ model = self.htm_prediction_...
[ "def", "_constructClassificationRecord", "(", "self", ")", ":", "model", "=", "self", ".", "htm_prediction_model", "sp", "=", "model", ".", "_getSPRegion", "(", ")", "tm", "=", "model", ".", "_getTPRegion", "(", ")", "tpImp", "=", "tm", ".", "getSelf", "("...
40.229508
0.008751
def _get_localzone(_root='/'): """Tries to find the local timezone configuration. This method prefers finding the timezone name and passing that to pytz, over passing in the localtime file, as in the later case the zoneinfo name is unknown. The parameter _root makes the function look for files lik...
[ "def", "_get_localzone", "(", "_root", "=", "'/'", ")", ":", "tzenv", "=", "_try_tz_from_env", "(", ")", "if", "tzenv", ":", "return", "tzenv", "# Now look for distribution specific configuration files", "# that contain the timezone name.", "for", "configfile", "in", "(...
39.055556
0.000925
def _canonicalize(self, filename): """Use .collection as extension unless provided""" path, ext = os.path.splitext(filename) if not ext: ext = ".collection" return path + ext
[ "def", "_canonicalize", "(", "self", ",", "filename", ")", ":", "path", ",", "ext", "=", "os", ".", "path", ".", "splitext", "(", "filename", ")", "if", "not", "ext", ":", "ext", "=", "\".collection\"", "return", "path", "+", "ext" ]
35.5
0.009174
def getInstalledThemes(self, store): """ Collect themes from all offerings installed on this store, or (if called multiple times) return the previously collected list. """ if not store in self._getInstalledThemesCache: self._getInstalledThemesCache[store] = (self. ...
[ "def", "getInstalledThemes", "(", "self", ",", "store", ")", ":", "if", "not", "store", "in", "self", ".", "_getInstalledThemesCache", ":", "self", ".", "_getInstalledThemesCache", "[", "store", "]", "=", "(", "self", ".", "_realGetInstalledThemes", "(", "stor...
49
0.013363
def clean_time(time_string): """Return a datetime from the Amazon-provided datetime string""" # Get a timezone-aware datetime object from the string time = dateutil.parser.parse(time_string) if not settings.USE_TZ: # If timezone support is not active, convert the time to UTC and # remove...
[ "def", "clean_time", "(", "time_string", ")", ":", "# Get a timezone-aware datetime object from the string", "time", "=", "dateutil", ".", "parser", ".", "parse", "(", "time_string", ")", "if", "not", "settings", ".", "USE_TZ", ":", "# If timezone support is not active,...
45.888889
0.002375
def manage_flags(self): """Manage flags""" self.ignore_blank = False self.case_ins = False self.number = False for n in range(0, len(self.flags)): if len(self.args) >= 2: if self.args[-1] == self.flags[0]: self.ignore_blank = True ...
[ "def", "manage_flags", "(", "self", ")", ":", "self", ".", "ignore_blank", "=", "False", "self", ".", "case_ins", "=", "False", "self", ".", "number", "=", "False", "for", "n", "in", "range", "(", "0", ",", "len", "(", "self", ".", "flags", ")", ")...
39.95
0.002445
def reduce_annotations(self, annotations, options): """Reduce annotations to ones used to identify enrichment (normally exclude ND and NOT).""" getfnc_qual_ev = options.getfnc_qual_ev() return [nt for nt in annotations if getfnc_qual_ev(nt.Qualifier, nt.Evidence_Code)]
[ "def", "reduce_annotations", "(", "self", ",", "annotations", ",", "options", ")", ":", "getfnc_qual_ev", "=", "options", ".", "getfnc_qual_ev", "(", ")", "return", "[", "nt", "for", "nt", "in", "annotations", "if", "getfnc_qual_ev", "(", "nt", ".", "Qualifi...
72.5
0.013652
def set_default_parser(parser): """ Set defaulr parser instance Parameters ---------- parser : instance or string An instance or registered name of parser class. The specified parser instance will be used when user did not specified :attr:`parser` in :func:`maidenhair.functi...
[ "def", "set_default_parser", "(", "parser", ")", ":", "if", "isinstance", "(", "parser", ",", "basestring", ")", ":", "parser", "=", "registry", ".", "find", "(", "parser", ")", "(", ")", "if", "not", "isinstance", "(", "parser", ",", "BaseParser", ")", ...
28.136364
0.001563
def in1d_sorted(ar1, ar2): """ Does the same than np.in1d but uses the fact that ar1 and ar2 are sorted. Is therefore much faster. """ if ar1.shape[0] == 0 or ar2.shape[0] == 0: # check for empty arrays to avoid crash return [] inds = ar2.searchsorted(ar1) inds[inds == len(ar2)] = 0 ...
[ "def", "in1d_sorted", "(", "ar1", ",", "ar2", ")", ":", "if", "ar1", ".", "shape", "[", "0", "]", "==", "0", "or", "ar2", ".", "shape", "[", "0", "]", "==", "0", ":", "# check for empty arrays to avoid crash", "return", "[", "]", "inds", "=", "ar2", ...
33.6
0.008696
def store(bank, key, data, cachedir=None): ''' Lists entries stored in the specified bank. CLI Example: .. code-block:: bash salt-run cache.store mycache mykey 'The time has come the walrus said' ''' if cachedir is None: cachedir = __opts__['cachedir'] try: cache ...
[ "def", "store", "(", "bank", ",", "key", ",", "data", ",", "cachedir", "=", "None", ")", ":", "if", "cachedir", "is", "None", ":", "cachedir", "=", "__opts__", "[", "'cachedir'", "]", "try", ":", "cache", "=", "salt", ".", "cache", ".", "Cache", "(...
25.277778
0.002119
def _mapped_std_streams(lookup_paths, streams=('stdin', 'stdout', 'stderr')): """Get a mapping of standard streams to given paths.""" # FIXME add device number too standard_inos = {} for stream in streams: try: stream_stat = os.fstat(getattr(sys, stream).fileno()) key = s...
[ "def", "_mapped_std_streams", "(", "lookup_paths", ",", "streams", "=", "(", "'stdin'", ",", "'stdout'", ",", "'stderr'", ")", ")", ":", "# FIXME add device number too", "standard_inos", "=", "{", "}", "for", "stream", "in", "streams", ":", "try", ":", "stream...
37.8
0.001032
def rpc_get_name_cost( self, name, **con_info ): """ Return the cost of a given name. Returns {'amount': ..., 'units': ...} """ if not check_name(name): return {'error': 'Invalid name or namespace', 'http_status': 400} db = get_db_state(self.working_dir) ...
[ "def", "rpc_get_name_cost", "(", "self", ",", "name", ",", "*", "*", "con_info", ")", ":", "if", "not", "check_name", "(", "name", ")", ":", "return", "{", "'error'", ":", "'Invalid name or namespace'", ",", "'http_status'", ":", "400", "}", "db", "=", "...
31.5625
0.011538
def _tag(val, tag): """Surround val with <tag></tag>""" if isinstance(val, str): val = bytes(val, 'utf-8') return (bytes('<' + tag + '>', 'utf-8') + val + bytes('</' + tag + '>', 'utf-8'))
[ "def", "_tag", "(", "val", ",", "tag", ")", ":", "if", "isinstance", "(", "val", ",", "str", ")", ":", "val", "=", "bytes", "(", "val", ",", "'utf-8'", ")", "return", "(", "bytes", "(", "'<'", "+", "tag", "+", "'>'", ",", "'utf-8'", ")", "+", ...
39.166667
0.008333
def edit_repo(name, description=None, homepage=None, private=None, has_issues=None, has_wiki=None, has_downloads=None, profile="github"): ''' Updates an existing Github repository. name The name of the...
[ "def", "edit_repo", "(", "name", ",", "description", "=", "None", ",", "homepage", "=", "None", ",", "private", "=", "None", ",", "has_issues", "=", "None", ",", "has_wiki", "=", "None", ",", "has_downloads", "=", "None", ",", "profile", "=", "\"github\"...
28.305882
0.001606
def value_for_keypath(dict, keypath): """ Returns the value of a keypath in a dictionary if the keypath exists or None if the keypath does not exist. """ if len(keypath) == 0: return dict keys = keypath.split('.') value = dict for key in keys: if key in value: ...
[ "def", "value_for_keypath", "(", "dict", ",", "keypath", ")", ":", "if", "len", "(", "keypath", ")", "==", "0", ":", "return", "dict", "keys", "=", "keypath", ".", "split", "(", "'.'", ")", "value", "=", "dict", "for", "key", "in", "keys", ":", "if...
20.157895
0.002494
def find_roots( disconnected, index, shared ): """Find appropriate "root" objects from which to recurse the hierarchies Will generate a synthetic root for anything which doesn't have any parents... """ log.warn( '%s disconnected objects in %s total objects', len(disconnected), len(index)) natur...
[ "def", "find_roots", "(", "disconnected", ",", "index", ",", "shared", ")", ":", "log", ".", "warn", "(", "'%s disconnected objects in %s total objects'", ",", "len", "(", "disconnected", ")", ",", "len", "(", "index", ")", ")", "natural_roots", "=", "[", "x...
38.68
0.017154
def curtailment(network, carrier='solar', filename=None): """ Plot curtailment of selected carrier Parameters ---------- network : PyPSA network container Holds topology of grid including results from powerflow analysis carrier: str Plot curtailemt of this carrier filename:...
[ "def", "curtailment", "(", "network", ",", "carrier", "=", "'solar'", ",", "filename", "=", "None", ")", ":", "p_by_carrier", "=", "network", ".", "generators_t", ".", "p", ".", "groupby", "(", "network", ".", "generators", ".", "carrier", ",", "axis", "...
32.754717
0.001678
def check_for_cygwin_mismatch(): """See https://github.com/pre-commit/pre-commit/issues/354""" if sys.platform in ('cygwin', 'win32'): # pragma: no cover (windows) is_cygwin_python = sys.platform == 'cygwin' toplevel = cmd_output('git', 'rev-parse', '--show-toplevel')[1] is_cygwin_git =...
[ "def", "check_for_cygwin_mismatch", "(", ")", ":", "if", "sys", ".", "platform", "in", "(", "'cygwin'", ",", "'win32'", ")", ":", "# pragma: no cover (windows)", "is_cygwin_python", "=", "sys", ".", "platform", "==", "'cygwin'", "toplevel", "=", "cmd_output", "(...
49.55
0.00099
def list_reference_bases(self, id_, start=0, end=None): """ Returns an iterator over the bases from the server in the form of consecutive strings. This command does not conform to the patterns of the other search and get requests, and is implemented differently. """ ...
[ "def", "list_reference_bases", "(", "self", ",", "id_", ",", "start", "=", "0", ",", "end", "=", "None", ")", ":", "request", "=", "protocol", ".", "ListReferenceBasesRequest", "(", ")", "request", ".", "start", "=", "pb", ".", "int", "(", "start", ")"...
43.380952
0.002148
def _invalidate_entry(self, key): "If exists: Invalidate old entry and return it." old_entry = self.access_lookup.get(key) if old_entry: old_entry.is_valid = False return old_entry
[ "def", "_invalidate_entry", "(", "self", ",", "key", ")", ":", "old_entry", "=", "self", ".", "access_lookup", ".", "get", "(", "key", ")", "if", "old_entry", ":", "old_entry", ".", "is_valid", "=", "False", "return", "old_entry" ]
31.285714
0.008889
def records_iter(fh, buffer_size=1024 * 1024 * 16): """Split up a firehose s3 object into records Firehose cloudwatch log delivery of flow logs does not delimit record boundaries. We have to use knowledge of content to split the records on boundaries. In the context of flow logs we're dealing with ...
[ "def", "records_iter", "(", "fh", ",", "buffer_size", "=", "1024", "*", "1024", "*", "16", ")", ":", "buf", "=", "None", "while", "True", ":", "chunk", "=", "fh", ".", "read", "(", "buffer_size", ")", "if", "not", "chunk", ":", "if", "buf", ":", ...
31.259259
0.001149