text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def setSr(self, fs): """Sets the samplerate of the input operation being plotted""" self.tracePlot.setSr(fs) self.stimPlot.setSr(fs)
[ "def", "setSr", "(", "self", ",", "fs", ")", ":", "self", ".", "tracePlot", ".", "setSr", "(", "fs", ")", "self", ".", "stimPlot", ".", "setSr", "(", "fs", ")" ]
38.25
9.25
def money_flow_index(close_data, high_data, low_data, volume, period): """ Money Flow Index. Formula: MFI = 100 - (100 / (1 + PMF / NMF)) """ catch_errors.check_for_input_len_diff( close_data, high_data, low_data, volume ) catch_errors.check_for_period_error(close_data, peri...
[ "def", "money_flow_index", "(", "close_data", ",", "high_data", ",", "low_data", ",", "volume", ",", "period", ")", ":", "catch_errors", ".", "check_for_input_len_diff", "(", "close_data", ",", "high_data", ",", "low_data", ",", "volume", ")", "catch_errors", "....
34.606061
23.69697
async def connect(self): """ Perform ICE handshake. This coroutine returns if a candidate pair was successfuly nominated and raises an exception otherwise. """ if not self._local_candidates_end: raise ConnectionError('Local candidates gathering was not perfor...
[ "async", "def", "connect", "(", "self", ")", ":", "if", "not", "self", ".", "_local_candidates_end", ":", "raise", "ConnectionError", "(", "'Local candidates gathering was not performed'", ")", "if", "(", "self", ".", "remote_username", "is", "None", "or", "self",...
33.076923
18
def _setup_xy(self, p): """ Produce pattern coordinate matrices from the bounds and density (or rows and cols), and transforms them according to x, y, and orientation. """ self.debug("bounds=%s, xdensity=%s, ydensity=%s, x=%s, y=%s, orientation=%s",p.bounds, p.xdensity, p...
[ "def", "_setup_xy", "(", "self", ",", "p", ")", ":", "self", ".", "debug", "(", "\"bounds=%s, xdensity=%s, ydensity=%s, x=%s, y=%s, orientation=%s\"", ",", "p", ".", "bounds", ",", "p", ".", "xdensity", ",", "p", ".", "ydensity", ",", "p", ".", "x", ",", "...
52.454545
37.181818
def find_debugged_frame(frame): """Find the first frame that is a debugged frame. We do this Generally we want traceback information without polluting it with debugger frames. We can tell these because those are frames on the top which don't have f_trace set. So we'll look back from the top to find ...
[ "def", "find_debugged_frame", "(", "frame", ")", ":", "f_prev", "=", "f", "=", "frame", "while", "f", "is", "not", "None", "and", "f", ".", "f_trace", "is", "None", ":", "f_prev", "=", "f", "f", "=", "f", ".", "f_back", "pass", "if", "f_prev", ":",...
31.73913
17.956522
def immutable(function): '''Add the instance internal state as the second parameter of the decorated function.''' def wrapper(self, *args, **kwargs): state = freeze(self._get_state()) return function(self, state, *args, **kwargs) return wrapper
[ "def", "immutable", "(", "function", ")", ":", "def", "wrapper", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "state", "=", "freeze", "(", "self", ".", "_get_state", "(", ")", ")", "return", "function", "(", "self", ",", "state...
30
18
def stochastic_choice(machines): """Stochastically choose one random machine distributed along their scores.""" if len(machines) < 4: return random.choice(machines) r = random.random() if r < 0.5: return random.choice(machines[:len(machines)/4]) elif r < 0.75: return ran...
[ "def", "stochastic_choice", "(", "machines", ")", ":", "if", "len", "(", "machines", ")", "<", "4", ":", "return", "random", ".", "choice", "(", "machines", ")", "r", "=", "random", ".", "random", "(", ")", "if", "r", "<", "0.5", ":", "return", "ra...
30.384615
14.923077
def stop(self, nowait=False): """Stop the listener. This asks the thread to terminate, and then waits for it to do so. Note that if you don't call this before your application exits, there may be some records still left on the queue, which won't be processed. If nowait is False ...
[ "def", "stop", "(", "self", ",", "nowait", "=", "False", ")", ":", "self", ".", "_stop", ".", "set", "(", ")", "if", "nowait", ":", "self", ".", "_stop_nowait", ".", "set", "(", ")", "self", ".", "queue", ".", "put_nowait", "(", "self", ".", "_se...
40.842105
20
def update_history(self, it, j=0, M=None, **kwargs): """Add the current state for all kwargs to the history """ # Create a new entry in the history for new variables (if they don't exist) if not np.any([k in self.history[j] for k in kwargs]): for k in kwargs: ...
[ "def", "update_history", "(", "self", ",", "it", ",", "j", "=", "0", ",", "M", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Create a new entry in the history for new variables (if they don't exist)", "if", "not", "np", ".", "any", "(", "[", "k", "in", ...
47.461538
15.884615
def versionString(version): """Create version string. For a sequence containing version information such as (2, 0, 0, 'pre'), this returns a printable string such as '2.0pre'. The micro version number is only excluded from the string if it is zero. """ ver = list(map(str, version)) numbers...
[ "def", "versionString", "(", "version", ")", ":", "ver", "=", "list", "(", "map", "(", "str", ",", "version", ")", ")", "numbers", ",", "rest", "=", "ver", "[", ":", "2", "if", "ver", "[", "2", "]", "==", "'0'", "else", "3", "]", ",", "ver", ...
36.818182
19
def wordnet_annotations(self): """The list of wordnet annotations of ``words`` layer.""" if not self.is_tagged(WORDNET): self.tag_wordnet() return [[a[WORDNET] for a in analysis] for analysis in self.analysis]
[ "def", "wordnet_annotations", "(", "self", ")", ":", "if", "not", "self", ".", "is_tagged", "(", "WORDNET", ")", ":", "self", ".", "tag_wordnet", "(", ")", "return", "[", "[", "a", "[", "WORDNET", "]", "for", "a", "in", "analysis", "]", "for", "analy...
48.2
11.6
def write_table(self, table, rows, append=False, gzip=False): """ Encode and write out *table* to the profile directory. Args: table: The name of the table to write rows: The rows to write to the table append: If `True`, append the encoded rows to any existin...
[ "def", "write_table", "(", "self", ",", "table", ",", "rows", ",", "append", "=", "False", ",", "gzip", "=", "False", ")", ":", "_write_table", "(", "self", ".", "root", ",", "table", ",", "rows", ",", "self", ".", "table_relations", "(", "table", ")...
37.947368
15.315789
def create(cls, files): """Creates file group and returns ``FileGroup`` instance. It expects iterable object that contains ``File`` instances, e.g.:: >>> file_1 = File('6c5e9526-b0fe-4739-8975-72e8d5ee6342') >>> file_2 = File('a771f854-c2cb-408a-8c36-71af77811f3b') ...
[ "def", "create", "(", "cls", ",", "files", ")", ":", "data", "=", "{", "}", "for", "index", ",", "file_", "in", "enumerate", "(", "files", ")", ":", "if", "isinstance", "(", "file_", ",", "File", ")", ":", "file_index", "=", "'files[{index}]'", ".", ...
37.148148
21.518519
def find_clusters(struct, connected_list): """ Finds bonded clusters of atoms in the structure with periodic boundary conditions. If there are atoms that are not bonded to anything, returns [0,1,0].(For faster computation time in FindDimension()) Args: struct (Structure): Input structure ...
[ "def", "find_clusters", "(", "struct", ",", "connected_list", ")", ":", "n_atoms", "=", "len", "(", "struct", ".", "species", ")", "if", "len", "(", "np", ".", "unique", "(", "connected_list", ")", ")", "!=", "n_atoms", ":", "return", "[", "0", ",", ...
43.88
19.44
def __calculate_always_decrease_rw_values( table_name, read_units, provisioned_reads, write_units, provisioned_writes): """ Calculate values for always-decrease-rw-together This will only return reads and writes decreases if both reads and writes are lower than the current provisioning ...
[ "def", "__calculate_always_decrease_rw_values", "(", "table_name", ",", "read_units", ",", "provisioned_reads", ",", "write_units", ",", "provisioned_writes", ")", ":", "if", "read_units", "<=", "provisioned_reads", "and", "write_units", "<=", "provisioned_writes", ":", ...
35.756098
17
def find_key(debug=False, skip=0): """ Locate a connected YubiKey. Throws an exception if none is found. This function is supposed to be possible to extend if any other YubiKeys appear in the future. Attributes : skip -- number of YubiKeys to skip debug -- True or False """ ...
[ "def", "find_key", "(", "debug", "=", "False", ",", "skip", "=", "0", ")", ":", "try", ":", "hid_device", "=", "YubiKeyHIDDevice", "(", "debug", ",", "skip", ")", "yk_version", "=", "hid_device", ".", "status", "(", ")", ".", "ykver", "(", ")", "if",...
35.666667
15.592593
def server_show(endpoint_id, server_id): """ Executor for `globus endpoint server show` """ client = get_client() server_doc = client.get_endpoint_server(endpoint_id, server_id) if not server_doc["uri"]: # GCP endpoint server fields = (("ID", "id"),) text_epilog = dedent( ...
[ "def", "server_show", "(", "endpoint_id", ",", "server_id", ")", ":", "client", "=", "get_client", "(", ")", "server_doc", "=", "client", ".", "get_endpoint_server", "(", "endpoint_id", ",", "server_id", ")", "if", "not", "server_doc", "[", "\"uri\"", "]", "...
29.092593
17.611111
def _case_insensitive_rpartition(input_string: str, separator: str) -> typing.Tuple[str, str, str]: """Same as str.rpartition(), except that the partitioning is done case insensitive.""" lowered_input_string = input_string.lower() lowered_separator = separator.lower() try: sp...
[ "def", "_case_insensitive_rpartition", "(", "input_string", ":", "str", ",", "separator", ":", "str", ")", "->", "typing", ".", "Tuple", "[", "str", ",", "str", ",", "str", "]", ":", "lowered_input_string", "=", "input_string", ".", "lower", "(", ")", "low...
62.642857
28.785714
def get_model_at_related_field(model, attr): """ Looks up ``attr`` as a field of ``model`` and returns the related model class. If ``attr`` is not a relationship field, ``ValueError`` is raised. """ field = model._meta.get_field(attr) if hasattr(field, 'related_model'): return field....
[ "def", "get_model_at_related_field", "(", "model", ",", "attr", ")", ":", "field", "=", "model", ".", "_meta", ".", "get_field", "(", "attr", ")", "if", "hasattr", "(", "field", ",", "'related_model'", ")", ":", "return", "field", ".", "related_model", "ra...
30.117647
20.823529
def new_dot(self, vd, parent, seqnum, rock_ridge, log_block_size, xa, file_mode): # type: (headervd.PrimaryOrSupplementaryVD, DirectoryRecord, int, str, int, bool, int) -> None ''' Create a new 'dot' Directory Record. Parameters: vd - The Volume Descriptor this ...
[ "def", "new_dot", "(", "self", ",", "vd", ",", "parent", ",", "seqnum", ",", "rock_ridge", ",", "log_block_size", ",", "xa", ",", "file_mode", ")", ":", "# type: (headervd.PrimaryOrSupplementaryVD, DirectoryRecord, int, str, int, bool, int) -> None", "if", "self", ".", ...
45.391304
26.956522
def nelson_aalen_estimator(event, time): """Nelson-Aalen estimator of cumulative hazard function. Parameters ---------- event : array-like, shape = (n_samples,) Contains binary event indicators. time : array-like, shape = (n_samples,) Contains event/censoring times. Returns ...
[ "def", "nelson_aalen_estimator", "(", "event", ",", "time", ")", ":", "event", ",", "time", "=", "check_y_survival", "(", "event", ",", "time", ")", "check_consistent_length", "(", "event", ",", "time", ")", "uniq_times", ",", "n_events", ",", "n_at_risk", "...
29.823529
20.911765
def wait(self): """ Waits for the pool to be fully stopped """ while True: if not self.greenlet_watch: break if self.stopping: gevent.sleep(0.1) else: gevent.sleep(1)
[ "def", "wait", "(", "self", ")", ":", "while", "True", ":", "if", "not", "self", ".", "greenlet_watch", ":", "break", "if", "self", ".", "stopping", ":", "gevent", ".", "sleep", "(", "0.1", ")", "else", ":", "gevent", ".", "sleep", "(", "1", ")" ]
23.454545
17.818182
def get_events(self, event_title, regex=False): """ Search for events with the provided title Args: event_title: The title of the event Returns: An event JSON object returned from the server with the following: { "meta":{ ...
[ "def", "get_events", "(", "self", ",", "event_title", ",", "regex", "=", "False", ")", ":", "regex_val", "=", "0", "if", "regex", ":", "regex_val", "=", "1", "r", "=", "requests", ".", "get", "(", "'{0}/events/?api_key={1}&username={2}&c-title='", "'{3}&regex=...
37.612903
18.129032
def remove_node(self, node): """Remove a node from the scheduler. This should be called either when the node crashed or at shutdown time. In the former case any pending items assigned to the node will be re-scheduled. Called by the hooks: - ``DSession.worker_workerfini...
[ "def", "remove_node", "(", "self", ",", "node", ")", ":", "workload", "=", "self", ".", "assigned_work", ".", "pop", "(", "node", ")", "if", "not", "self", ".", "_pending_of", "(", "workload", ")", ":", "return", "None", "# The node crashed, identify test th...
30.65
18.975
def contains_empty(features): """Check features data are not empty :param features: The features data to check. :type features: list of numpy arrays. :return: True if one of the array is empty, False else. """ if not features: return True for feature in features: if featur...
[ "def", "contains_empty", "(", "features", ")", ":", "if", "not", "features", ":", "return", "True", "for", "feature", "in", "features", ":", "if", "feature", ".", "shape", "[", "0", "]", "==", "0", ":", "return", "True", "return", "False" ]
24.2
17.333333
def games(self, platform): """ It returns a list of games given the platform *alias* (usually is the game name separated by "-" instead of white spaces). """ platform = platform.lower() data_list = self.db.get_data(self.games_path, platform=platform) data_list = data_list...
[ "def", "games", "(", "self", ",", "platform", ")", ":", "platform", "=", "platform", ".", "lower", "(", ")", "data_list", "=", "self", ".", "db", ".", "get_data", "(", "self", ".", "games_path", ",", "platform", "=", "platform", ")", "data_list", "=", ...
51.125
14.875
def noNsProp(self, name): """Search and get the value of an attribute associated to a node This does the entity substitution. This function looks in DTD attribute declaration for #FIXED or default declaration values unless DTD use has been turned off. This function is sim...
[ "def", "noNsProp", "(", "self", ",", "name", ")", ":", "ret", "=", "libxml2mod", ".", "xmlGetNoNsProp", "(", "self", ".", "_o", ",", "name", ")", "return", "ret" ]
52.888889
17.111111
def dereference_object(object_type, object_uuid, status): """Show linked persistent identifier(s).""" from .models import PersistentIdentifier pids = PersistentIdentifier.query.filter_by( object_type=object_type, object_uuid=object_uuid ) if status: pids = pids.filter_by(status=stat...
[ "def", "dereference_object", "(", "object_type", ",", "object_uuid", ",", "status", ")", ":", "from", ".", "models", "import", "PersistentIdentifier", "pids", "=", "PersistentIdentifier", ".", "query", ".", "filter_by", "(", "object_type", "=", "object_type", ",",...
32.142857
20.357143
def _set_error_response_with_body(self, bucket_name=None): """ Sets all the error response fields with a valid response body. Raises :exc:`ValueError` if invoked on a zero length body. :param bucket_name: Optional bucket name resource at which error occurred. :para...
[ "def", "_set_error_response_with_body", "(", "self", ",", "bucket_name", "=", "None", ")", ":", "if", "len", "(", "self", ".", "_response", ".", "data", ")", "==", "0", ":", "raise", "ValueError", "(", "'response data has no body.'", ")", "try", ":", "root",...
43.03125
13.71875
def to_python(self, value, resource): """Dictionary to Python object""" if isinstance(value, dict): d = { self.aliases.get(k, k): self.to_python(v, resource) if isinstance(v, (dict, list)) else v for k, v in six.iteritems(value) } retu...
[ "def", "to_python", "(", "self", ",", "value", ",", "resource", ")", ":", "if", "isinstance", "(", "value", ",", "dict", ")", ":", "d", "=", "{", "self", ".", "aliases", ".", "get", "(", "k", ",", "k", ")", ":", "self", ".", "to_python", "(", "...
39.846154
21.923077
def suggestTitle(self, title): """Suggests a title for the entry. If title has been manually edited, suggestion is ignored.""" if not self._title_changed or not str(self.wtitle.text()): self.wtitle.setText(title) self._title_changed = False
[ "def", "suggestTitle", "(", "self", ",", "title", ")", ":", "if", "not", "self", ".", "_title_changed", "or", "not", "str", "(", "self", ".", "wtitle", ".", "text", "(", ")", ")", ":", "self", ".", "wtitle", ".", "setText", "(", "title", ")", "self...
47.166667
6.5
def create_tenant( self, parent, tenant, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates a new tenant entity. Example: >>> from google.cloud import talen...
[ "def", "create_tenant", "(", "self", ",", "parent", ",", "tenant", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT...
40.428571
24.657143
def ray_shooting_partial(self, x, y, alpha_x, alpha_y, z_start, z_stop, kwargs_lens, keep_range=False, include_z_start=False): """ ray-tracing through parts of the coin, starting with (x,y) and angles (alpha_x, alpha_y) at redshift z_start and then backwards to redsh...
[ "def", "ray_shooting_partial", "(", "self", ",", "x", ",", "y", ",", "alpha_x", ",", "alpha_y", ",", "z_start", ",", "z_stop", ",", "kwargs_lens", ",", "keep_range", "=", "False", ",", "include_z_start", "=", "False", ")", ":", "z_lens_last", "=", "z_start...
53.255814
21.069767
def find_nearest_dist_node(self, point, distance, retdistance = False): """! @brief Find nearest neighbor in area with radius = distance. @param[in] point (list): Maximum distance where neighbors are searched. @param[in] distance (double): Maximum distance where neighbors a...
[ "def", "find_nearest_dist_node", "(", "self", ",", "point", ",", "distance", ",", "retdistance", "=", "False", ")", ":", "best_nodes", "=", "self", ".", "find_nearest_dist_nodes", "(", "point", ",", "distance", ")", "if", "best_nodes", "==", "[", "]", ":", ...
43.916667
31.041667
def _align_heavy_atoms(mol1, mol2, vmol1, vmol2, ilabel1, ilabel2, eq_atoms): """ Align the label of topologically identical atoms of second molecule towards first molecule Args: mol1: First molecule. OpenBabel OBMol object mol2: Second...
[ "def", "_align_heavy_atoms", "(", "mol1", ",", "mol2", ",", "vmol1", ",", "vmol2", ",", "ilabel1", ",", "ilabel2", ",", "eq_atoms", ")", ":", "nvirtual", "=", "vmol1", ".", "NumAtoms", "(", ")", "nheavy", "=", "len", "(", "ilabel1", ")", "for", "i", ...
37.439024
14.414634
def jrepr(value): '''customized `repr()`.''' if value is None: return repr(value) t = type(value) if t.__repr__ is not object.__repr__: return repr(value) return 'object ' + t.__name__
[ "def", "jrepr", "(", "value", ")", ":", "if", "value", "is", "None", ":", "return", "repr", "(", "value", ")", "t", "=", "type", "(", "value", ")", "if", "t", ".", "__repr__", "is", "not", "object", ".", "__repr__", ":", "return", "repr", "(", "v...
26.625
13.625
def create_todo_list(self, project_id, milestone_id=None, private=None, tracked=False, name=None, description=None, template_id=None): """ This will create a new, empty list. You can create the list explicitly, or by giving it a list template id to base the new list off of. ...
[ "def", "create_todo_list", "(", "self", ",", "project_id", ",", "milestone_id", "=", "None", ",", "private", "=", "None", ",", "tracked", "=", "False", ",", "name", "=", "None", ",", "description", "=", "None", ",", "template_id", "=", "None", ")", ":", ...
48.761905
17.333333
def _verify_create_args(module_name, class_name, static): """ Verifies a subset of the arguments to create() """ # Verify module name is provided if module_name is None: raise InvalidServiceConfiguration( 'Service configurations must define a module' ) # Non-static services ...
[ "def", "_verify_create_args", "(", "module_name", ",", "class_name", ",", "static", ")", ":", "# Verify module name is provided", "if", "module_name", "is", "None", ":", "raise", "InvalidServiceConfiguration", "(", "'Service configurations must define a module'", ")", "# No...
42.076923
15.769231
def get_key(cls, k, default=None): """Matching get method for ``set_key`` """ k = cls.__name__ + "__" + k if k in session: return session[k] else: return default
[ "def", "get_key", "(", "cls", ",", "k", ",", "default", "=", "None", ")", ":", "k", "=", "cls", ".", "__name__", "+", "\"__\"", "+", "k", "if", "k", "in", "session", ":", "return", "session", "[", "k", "]", "else", ":", "return", "default" ]
27.25
9.875
def get_modules(folder): """Find all valid modules in the given folder which must be in in the same directory as this loader.py module. A valid module has a .py extension, and is importable. @return: all loaded valid modules @rtype: iterator of module """ if is_frozen(): # find modul...
[ "def", "get_modules", "(", "folder", ")", ":", "if", "is_frozen", "(", ")", ":", "# find modules in library.zip filename", "zipname", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ")", "parentmodule", ...
43.8
14.64
def parse_data_df(data_dset, ridx, cidx, row_meta, col_meta): """ Parses in data_df from hdf5, subsetting if specified. Input: -data_dset (h5py dset): HDF5 dataset from which to read data_df -ridx (list): list of indexes to subset from data_df (may be all of them if no subsettin...
[ "def", "parse_data_df", "(", "data_dset", ",", "ridx", ",", "cidx", ",", "row_meta", ",", "col_meta", ")", ":", "if", "len", "(", "ridx", ")", "==", "len", "(", "row_meta", ".", "index", ")", "and", "len", "(", "cidx", ")", "==", "len", "(", "col_m...
47.346154
19.115385
def acquire_lock(path: str, blocking: bool) -> Generator[Optional[int], None, None]: """Raises an OSError if the lock can't be acquired""" try: with open(path, "w+") as lockfile: if not blocking: lock_command = fcntl.LOCK_EX | fcntl.LOCK_NB else: l...
[ "def", "acquire_lock", "(", "path", ":", "str", ",", "blocking", ":", "bool", ")", "->", "Generator", "[", "Optional", "[", "int", "]", ",", "None", ",", "None", "]", ":", "try", ":", "with", "open", "(", "path", ",", "\"w+\"", ")", "as", "lockfile...
35.333333
19.533333
def request(self, type, command_list): ''' Send NX-API JSON request to the NX-OS device. ''' req = self._build_request(type, command_list) if self.nxargs['connect_over_uds']: self.connection.request('POST', req['url'], req['payload'], req['headers']) respo...
[ "def", "request", "(", "self", ",", "type", ",", "command_list", ")", ":", "req", "=", "self", ".", "_build_request", "(", "type", ",", "command_list", ")", "if", "self", ".", "nxargs", "[", "'connect_over_uds'", "]", ":", "self", ".", "connection", ".",...
45.526316
18.894737
def _align(self, axis): """ Align spark bolt array so that axes for iteration are in the keys. This operation is applied before most functional operators. It ensures that the specified axes are valid, and swaps key/value axes so that functional operators can be applied o...
[ "def", "_align", "(", "self", ",", "axis", ")", ":", "# ensure that the specified axes are valid", "inshape", "(", "self", ".", "shape", ",", "axis", ")", "# find the value axes that should be moved into the keys (axis >= split)", "tokeys", "=", "[", "(", "a", "-", "s...
33.129032
24.225806
def _create_justification_button(self): """Creates horizontal justification button""" iconnames = ["JustifyLeft", "JustifyCenter", "JustifyRight"] bmplist = [icons[iconname] for iconname in iconnames] self.justify_tb = _widgets.BitmapToggleButton(self, bmplist) self.justify_tb.S...
[ "def", "_create_justification_button", "(", "self", ")", ":", "iconnames", "=", "[", "\"JustifyLeft\"", ",", "\"JustifyCenter\"", ",", "\"JustifyRight\"", "]", "bmplist", "=", "[", "icons", "[", "iconname", "]", "for", "iconname", "in", "iconnames", "]", "self",...
51.222222
18.888889
def to_bytes(val): """Takes a text message and return a tuple """ if val is NoResponse: return val val = val.replace('\\r', '\r').replace('\\n', '\n') return val.encode()
[ "def", "to_bytes", "(", "val", ")", ":", "if", "val", "is", "NoResponse", ":", "return", "val", "val", "=", "val", ".", "replace", "(", "'\\\\r'", ",", "'\\r'", ")", ".", "replace", "(", "'\\\\n'", ",", "'\\n'", ")", "return", "val", ".", "encode", ...
27.428571
13
def _collect_by_key(self,specs): """ Returns a dictionary like object with the lists of values collapsed by their respective key. Useful to find varying vs constant keys and to find how fast keys vary. """ # Collect (key, value) tuples as list of lists, flatten with chain...
[ "def", "_collect_by_key", "(", "self", ",", "specs", ")", ":", "# Collect (key, value) tuples as list of lists, flatten with chain", "allkeys", "=", "itertools", ".", "chain", ".", "from_iterable", "(", "[", "[", "(", "k", ",", "run", "[", "k", "]", ")", "for", ...
44.666667
13.666667
def dependencies(self, task, params={}, **options): """Returns the compact representations of all of the dependencies of a task. Parameters ---------- task : {Id} The task to get dependencies on. [params] : {Object} Parameters for the request """ path = "/tasks/...
[ "def", "dependencies", "(", "self", ",", "task", ",", "params", "=", "{", "}", ",", "*", "*", "options", ")", ":", "path", "=", "\"/tasks/%s/dependencies\"", "%", "(", "task", ")", "return", "self", ".", "client", ".", "get", "(", "path", ",", "param...
39.2
14.5
def report(data): """Create a Rmd report for small RNAseq analysis""" work_dir = dd.get_work_dir(data[0][0]) out_dir = op.join(work_dir, "report") safe_makedir(out_dir) summary_file = op.join(out_dir, "summary.csv") with file_transaction(summary_file) as out_tx: with open(out_tx, 'w') as...
[ "def", "report", "(", "data", ")", ":", "work_dir", "=", "dd", ".", "get_work_dir", "(", "data", "[", "0", "]", "[", "0", "]", ")", "out_dir", "=", "op", ".", "join", "(", "work_dir", ",", "\"report\"", ")", "safe_makedir", "(", "out_dir", ")", "su...
45.058824
13
def get_short_url(self, obj): """ Get short URL of blog post like '/blog/<slug>/' using ``get_absolute_url`` if available. Removes dependency on reverse URLs of Mezzanine views when deploying Mezzanine only as an API backend. """ try: url = obj.get_absolute_url() ...
[ "def", "get_short_url", "(", "self", ",", "obj", ")", ":", "try", ":", "url", "=", "obj", ".", "get_absolute_url", "(", ")", "except", "NoReverseMatch", ":", "url", "=", "'/blog/'", "+", "obj", ".", "slug", "return", "url" ]
39.4
20
def port_profile_vlan_profile_switchport_access_mac_vlan_classification_access_vlan_access_mac_address(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") port_profile = ET.SubElement(config, "port-profile", xmlns="urn:brocade.com:mgmt:brocade-port-profile") ...
[ "def", "port_profile_vlan_profile_switchport_access_mac_vlan_classification_access_vlan_access_mac_address", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "port_profile", "=", "ET", ".", "SubElement", "(", ...
57.894737
25.421053
def get_port_channel_detail_output_lacp_partner_system_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_port_channel_detail = ET.Element("get_port_channel_detail") config = get_port_channel_detail output = ET.SubElement(get_port_channel_det...
[ "def", "get_port_channel_detail_output_lacp_partner_system_id", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "get_port_channel_detail", "=", "ET", ".", "Element", "(", "\"get_port_channel_detail\"", ")"...
45.538462
16.538462
def _simple_blockify(tuples, dtype): """ return a single array of a block that has a single dtype; if dtype is not None, coerce to this dtype """ values, placement = _stack_arrays(tuples, dtype) # CHECK DTYPE? if dtype is not None and values.dtype != dtype: # pragma: no cover values = ...
[ "def", "_simple_blockify", "(", "tuples", ",", "dtype", ")", ":", "values", ",", "placement", "=", "_stack_arrays", "(", "tuples", ",", "dtype", ")", "# CHECK DTYPE?", "if", "dtype", "is", "not", "None", "and", "values", ".", "dtype", "!=", "dtype", ":", ...
33.416667
15.916667
def is_gzippable(self, path): """ Returns a boolean indicating if the provided file path is a candidate for gzipping. """ # First check if gzipping is allowed by the global setting if not getattr(settings, 'BAKERY_GZIP', False): return False # Then che...
[ "def", "is_gzippable", "(", "self", ",", "path", ")", ":", "# First check if gzipping is allowed by the global setting", "if", "not", "getattr", "(", "settings", ",", "'BAKERY_GZIP'", ",", "False", ")", ":", "return", "False", "# Then check if the content type of this par...
37.133333
16.6
def _countOverlap(rep1, rep2): """ Return the overlap between two representations. rep1 and rep2 are lists of non-zero indices. """ overlap = 0 for e in rep1: if e in rep2: overlap += 1 return overlap
[ "def", "_countOverlap", "(", "rep1", ",", "rep2", ")", ":", "overlap", "=", "0", "for", "e", "in", "rep1", ":", "if", "e", "in", "rep2", ":", "overlap", "+=", "1", "return", "overlap" ]
23.3
17.7
def star(args): """ %prog star folder reference Run star on a folder with reads. """ p = OptionParser(star.__doc__) p.add_option("--single", default=False, action="store_true", help="Single end mapping") p.set_fastq_names() p.set_cpus() opts, args = p.parse_args(arg...
[ "def", "star", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "star", ".", "__doc__", ")", "p", ".", "add_option", "(", "\"--single\"", ",", "default", "=", "False", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Single end mapping\"", ...
30.571429
16.040816
def _requirements_sanitize(req_list): # type: (List[str]) -> List[str] """ Cleanup a list of requirement strings (e.g. from requirements.txt) to only contain entries valid for this platform and with the lowest required version only. Example ------- >>> from sys import version_info ...
[ "def", "_requirements_sanitize", "(", "req_list", ")", ":", "# type: (List[str]) -> List[str]", "filtered_req_list", "=", "(", "_requirement_find_lowest_possible", "(", "req", ")", "for", "req", "in", "(", "pkg_resources", ".", "Requirement", ".", "parse", "(", "s", ...
33.291667
20.541667
def sync_repo_hook(self, repo_id): """Sync a GitHub repo's hook with the locally stored repo.""" # Get the hook that we may have set in the past gh_repo = self.api.repository_with_id(repo_id) hooks = (hook.id for hook in gh_repo.hooks() if hook.config.get('url', '') == s...
[ "def", "sync_repo_hook", "(", "self", ",", "repo_id", ")", ":", "# Get the hook that we may have set in the past", "gh_repo", "=", "self", ".", "api", ".", "repository_with_id", "(", "repo_id", ")", "hooks", "=", "(", "hook", ".", "id", "for", "hook", "in", "g...
47.368421
16.263158
def _create_h(x): """increase between samples""" h = np.zeros_like(x) h[:-1] = x[1:] - x[:-1] # border h[-1] = h[-2] return h
[ "def", "_create_h", "(", "x", ")", ":", "h", "=", "np", ".", "zeros_like", "(", "x", ")", "h", "[", ":", "-", "1", "]", "=", "x", "[", "1", ":", "]", "-", "x", "[", ":", "-", "1", "]", "# border", "h", "[", "-", "1", "]", "=", "h", "[...
23.857143
15.857143
def remove(self, child): """Removes the child element""" if not isinstance(child, AbstractElement): raise ValueError("Expected AbstractElement, got " + str(type(child))) if child.parent == self: child.parent = None self.data.remove(child) #delete from inde...
[ "def", "remove", "(", "self", ",", "child", ")", ":", "if", "not", "isinstance", "(", "child", ",", "AbstractElement", ")", ":", "raise", "ValueError", "(", "\"Expected AbstractElement, got \"", "+", "str", "(", "type", "(", "child", ")", ")", ")", "if", ...
41.8
13.1
def btc_tx_sign_input(tx, idx, prevout_script, prevout_amount, private_key_info, hashcode=SIGHASH_ALL, hashcodes=None, segwit=None, scriptsig_type=None, redeem_script=None, witness_script=None, **blockchain_opts): """ Sign a particular input in the given transaction. @private_key_info can either be a privat...
[ "def", "btc_tx_sign_input", "(", "tx", ",", "idx", ",", "prevout_script", ",", "prevout_amount", ",", "private_key_info", ",", "hashcode", "=", "SIGHASH_ALL", ",", "hashcodes", "=", "None", ",", "segwit", "=", "None", ",", "scriptsig_type", "=", "None", ",", ...
59
44.176471
def _get(self): """get and parse data stored in self.path.""" data, stat = self.zk.get(self.path) if not len(data): return {}, stat.version if self.OLD_SEPARATOR in data: return self._get_old() return json.loads(data), stat.version
[ "def", "_get", "(", "self", ")", ":", "data", ",", "stat", "=", "self", ".", "zk", ".", "get", "(", "self", ".", "path", ")", "if", "not", "len", "(", "data", ")", ":", "return", "{", "}", ",", "stat", ".", "version", "if", "self", ".", "OLD_...
32
11.222222
async def send_chat_action(self, chat_id: typing.Union[base.Integer, base.String], action: base.String) -> base.Boolean: """ Use this method when you need to tell the user that something is happening on the bot's side. The status is set for 5 seconds or less ...
[ "async", "def", "send_chat_action", "(", "self", ",", "chat_id", ":", "typing", ".", "Union", "[", "base", ".", "Integer", ",", "base", ".", "String", "]", ",", "action", ":", "base", ".", "String", ")", "->", "base", ".", "Boolean", ":", "payload", ...
46.608696
25.130435
def backend_to_retrieve(self, namespace, stream): """ Return backend enabled for reading for `stream`. """ if namespace not in self.namespaces: raise NamespaceMissing('`{}` namespace is not configured' .format(namespace)) stream_prefix = self.get_matching_prefix(na...
[ "def", "backend_to_retrieve", "(", "self", ",", "namespace", ",", "stream", ")", ":", "if", "namespace", "not", "in", "self", ".", "namespaces", ":", "raise", "NamespaceMissing", "(", "'`{}` namespace is not configured'", ".", "format", "(", "namespace", ")", ")...
44.909091
13.636364
def consume(self, key, default=None, current=None, print_on_success=False): """ Consume a key from the configuration. When a key is consumed, it is removed from the configuration. If not found, the default is returned. If the current value is not None, it will be returned instea...
[ "def", "consume", "(", "self", ",", "key", ",", "default", "=", "None", ",", "current", "=", "None", ",", "print_on_success", "=", "False", ")", ":", "value", "=", "self", ".", "_configuration", ".", "pop", "(", "key", ",", "default", ")", "if", "cur...
37.391304
18.521739
def read_points(features): """ Iterable of features to a sequence of point tuples Where "features" can be either GeoJSON mappings or objects implementing the geo_interface """ for feature in features: if isinstance(feature, (tuple, list)) and len(feature) == 2: yield feature ...
[ "def", "read_points", "(", "features", ")", ":", "for", "feature", "in", "features", ":", "if", "isinstance", "(", "feature", ",", "(", "tuple", ",", "list", ")", ")", "and", "len", "(", "feature", ")", "==", "2", ":", "yield", "feature", "elif", "ha...
34.810811
16.027027
def convert_coordinates(coords, origin, wgs84, wrapped): """ Convert coordinates from one crs to another """ if isinstance(coords, list) or isinstance(coords, tuple): try: if isinstance(coords[0], list) or isinstance(coords[0], tuple): return [convert_coordinates(list(c), ori...
[ "def", "convert_coordinates", "(", "coords", ",", "origin", ",", "wgs84", ",", "wrapped", ")", ":", "if", "isinstance", "(", "coords", ",", "list", ")", "or", "isinstance", "(", "coords", ",", "tuple", ")", ":", "try", ":", "if", "isinstance", "(", "co...
38.625
21.4375
def send_message_for_lane_change(sender, **kwargs): """ Sends a message to possible owners of the current workflows next lane. Args: **kwargs: ``current`` and ``possible_owners`` are required. sender (User): User object """ current = kwargs['current'] owners = kwargs['possi...
[ "def", "send_message_for_lane_change", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "current", "=", "kwargs", "[", "'current'", "]", "owners", "=", "kwargs", "[", "'possible_owners'", "]", "if", "'lane_change_invite'", "in", "current", ".", "task_data", "...
34.822222
20.6
def show_vcs_output_vcs_nodes_vcs_node_info_node_rbridge_id(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") show_vcs = ET.Element("show_vcs") config = show_vcs output = ET.SubElement(show_vcs, "output") vcs_nodes = ET.SubElement(output, "...
[ "def", "show_vcs_output_vcs_nodes_vcs_node_info_node_rbridge_id", "(", "self", ",", "*", "*", "kwargs", ")", ":", "config", "=", "ET", ".", "Element", "(", "\"config\"", ")", "show_vcs", "=", "ET", ".", "Element", "(", "\"show_vcs\"", ")", "config", "=", "show...
43.571429
15.928571
def _update_hosting_device_exclusivity(self, context, hosting_device, tenant_id): """Make <hosting device> bound or unbound to <tenant_id>. If <tenant_id> is None the device is unbound, otherwise it gets bound to that <tenant_id> """ wi...
[ "def", "_update_hosting_device_exclusivity", "(", "self", ",", "context", ",", "hosting_device", ",", "tenant_id", ")", ":", "with", "context", ".", "session", ".", "begin", "(", "subtransactions", "=", "True", ")", ":", "hosting_device", "[", "'tenant_bound'", ...
49.928571
17.785714
def _check_consider_merging_isinstance(self, node): """Check isinstance calls which can be merged together.""" if node.op != "or": return first_args = self._duplicated_isinstance_types(node) for duplicated_name, class_names in first_args.items(): names = sorted(n...
[ "def", "_check_consider_merging_isinstance", "(", "self", ",", "node", ")", ":", "if", "node", ".", "op", "!=", "\"or\"", ":", "return", "first_args", "=", "self", ".", "_duplicated_isinstance_types", "(", "node", ")", "for", "duplicated_name", ",", "class_names...
39.384615
16.923077
def get_consensus_module(module_name): """Returns a consensus module by name. Args: module_name (str): The name of the module to load. Returns: module: The consensus module. Raises: UnknownConsensusModuleError: Raised if the given module_name does ...
[ "def", "get_consensus_module", "(", "module_name", ")", ":", "module_package", "=", "module_name", "if", "module_name", "==", "'genesis'", ":", "module_package", "=", "(", "'sawtooth_validator.journal.consensus.genesis.'", "'genesis_consensus'", ")", "elif", "module_name", ...
33.1
18.666667
def selected_display_item(self) -> typing.Optional[DisplayItem.DisplayItem]: """Return the selected display item. The selected display is the display ite that has keyboard focus in the data panel or a display panel. """ # first check for the [focused] data browser display_item =...
[ "def", "selected_display_item", "(", "self", ")", "->", "typing", ".", "Optional", "[", "DisplayItem", ".", "DisplayItem", "]", ":", "# first check for the [focused] data browser", "display_item", "=", "self", ".", "focused_display_item", "if", "not", "display_item", ...
50.636364
24.727273
def runSearchCallSets(self, request): """ Runs the specified SearchCallSetsRequest. """ return self.runSearchRequest( request, protocol.SearchCallSetsRequest, protocol.SearchCallSetsResponse, self.callSetsGenerator)
[ "def", "runSearchCallSets", "(", "self", ",", "request", ")", ":", "return", "self", ".", "runSearchRequest", "(", "request", ",", "protocol", ".", "SearchCallSetsRequest", ",", "protocol", ".", "SearchCallSetsResponse", ",", "self", ".", "callSetsGenerator", ")" ...
34.5
4.5
def cublasSgemv(handle, trans, m, n, alpha, A, lda, x, incx, beta, y, incy): """ Matrix-vector product for real general matrix. """ status = _libcublas.cublasSgemv_v2(handle, _CUBLAS_OP[trans], m, n, ctypes.byref(ctypes.c_fl...
[ "def", "cublasSgemv", "(", "handle", ",", "trans", ",", "m", ",", "n", ",", "alpha", ",", "A", ",", "lda", ",", "x", ",", "incx", ",", "beta", ",", "y", ",", "incy", ")", ":", "status", "=", "_libcublas", ".", "cublasSgemv_v2", "(", "handle", ","...
42.25
22.916667
def _cleanup(self): """Remove any stale files from the session storage directory""" for filename in os.listdir(self._storage_dir): file_path = path.join(self._storage_dir, filename) file_stat = os.stat(file_path) evaluate = max(file_stat.st_ctime, file_stat.st_mtime) ...
[ "def", "_cleanup", "(", "self", ")", ":", "for", "filename", "in", "os", ".", "listdir", "(", "self", ".", "_storage_dir", ")", ":", "file_path", "=", "path", ".", "join", "(", "self", ".", "_storage_dir", ",", "filename", ")", "file_stat", "=", "os", ...
52.333333
14.444444
def _Rzderiv(self,R,z,phi=0.,t=0.): """ NAME: _Rzderiv PURPOSE: evaluate the mixed R,z derivative for this potential INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: ...
[ "def", "_Rzderiv", "(", "self", ",", "R", ",", "z", ",", "phi", "=", "0.", ",", "t", "=", "0.", ")", ":", "return", "-", "3.", "*", "R", "*", "z", "*", "(", "R", "**", "2.", "+", "z", "**", "2.", "+", "self", ".", "_b2", ")", "**", "-",...
26.529412
15.470588
def skill_create(self, data, **kwargs): "https://developer.zendesk.com/rest_api/docs/chat/skills#create-skill" api_path = "/api/v2/skills" return self.call(api_path, method="POST", data=data, **kwargs)
[ "def", "skill_create", "(", "self", ",", "data", ",", "*", "*", "kwargs", ")", ":", "api_path", "=", "\"/api/v2/skills\"", "return", "self", ".", "call", "(", "api_path", ",", "method", "=", "\"POST\"", ",", "data", "=", "data", ",", "*", "*", "kwargs"...
55.5
18.5
def _ast_optree_node_to_code(self, node, **kwargs): """Convert an abstract syntax operator tree to python source code.""" opnode = node.opnode if opnode is None: return self._ast_to_code(node.operands[0]) else: operator = opnode.operator if operator is OP_ALTERNATE: return self...
[ "def", "_ast_optree_node_to_code", "(", "self", ",", "node", ",", "*", "*", "kwargs", ")", ":", "opnode", "=", "node", ".", "opnode", "if", "opnode", "is", "None", ":", "return", "self", ".", "_ast_to_code", "(", "node", ".", "operands", "[", "0", "]",...
42.608696
13.086957
def transform_login(config): """ Parse login data as dict. Called from load_from_file and also can be used when collecting information from other sources as well. :param dict data: data representing the valid key/value pairs from smcrc :return: dict dict of settings that can be sent ...
[ "def", "transform_login", "(", "config", ")", ":", "verify", "=", "True", "if", "config", ".", "pop", "(", "'smc_ssl'", ",", "None", ")", ":", "scheme", "=", "'https'", "verify", "=", "config", ".", "pop", "(", "'ssl_cert_file'", ",", "None", ")", "if"...
26.932203
17.881356
def get_tenant( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Retrieves specified tenant. Example: >>> from google.cloud import talent_v4beta1 ...
[ "def", "get_tenant", "(", "self", ",", "name", ",", "retry", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "timeout", "=", "google", ".", "api_core", ".", "gapic_v1", ".", "method", ".", "DEFAULT", ",", "metadata", ...
40.2
24.066667
def genhash(self, package, code): """Generate a hash from code.""" return hex(checksum( hash_sep.join( str(item) for item in (VERSION_STR,) + self.__reduce__()[1] + (package, code) ).encode(default_encoding), ))
[ "def", "genhash", "(", "self", ",", "package", ",", "code", ")", ":", "return", "hex", "(", "checksum", "(", "hash_sep", ".", "join", "(", "str", "(", "item", ")", "for", "item", "in", "(", "VERSION_STR", ",", ")", "+", "self", ".", "__reduce__", "...
33.222222
9.444444
def _depaginate_all(self, url): """GETs the url provided and traverses the 'next' url that's returned while storing the data in a list. Returns a single list of all items. """ items = [] for x in self._depagination_generator(url): items += x return ite...
[ "def", "_depaginate_all", "(", "self", ",", "url", ")", ":", "items", "=", "[", "]", "for", "x", "in", "self", ".", "_depagination_generator", "(", "url", ")", ":", "items", "+=", "x", "return", "items" ]
34.888889
16.111111
def artist_create(self, name, other_names_comma=None, group_name=None, url_string=None, body=None): """Function to create an artist (Requires login) (UNTESTED). Parameters: name (str): other_names_comma (str): List of alternative names for this ...
[ "def", "artist_create", "(", "self", ",", "name", ",", "other_names_comma", "=", "None", ",", "group_name", "=", "None", ",", "url_string", "=", "None", ",", "body", "=", "None", ")", ":", "params", "=", "{", "'artist[name]'", ":", "name", ",", "'artist[...
45.954545
19.363636
def clean_new(self, value): """Return a new object instantiated with cleaned data.""" value = self.schema_class(value).full_clean() return self.object_class(**value)
[ "def", "clean_new", "(", "self", ",", "value", ")", ":", "value", "=", "self", ".", "schema_class", "(", "value", ")", ".", "full_clean", "(", ")", "return", "self", ".", "object_class", "(", "*", "*", "value", ")" ]
46.5
6.75
def _getMatchingRowsWithRetries(self, tableInfo, fieldsToMatch, selectFieldNames, maxRows=None): """ Like _getMatchingRowsNoRetries(), but with retries on transient MySQL failures """ with ConnectionFactory.get() as conn: return self._getMatchingRowsNoRetries(tabl...
[ "def", "_getMatchingRowsWithRetries", "(", "self", ",", "tableInfo", ",", "fieldsToMatch", ",", "selectFieldNames", ",", "maxRows", "=", "None", ")", ":", "with", "ConnectionFactory", ".", "get", "(", ")", "as", "conn", ":", "return", "self", ".", "_getMatchin...
51.375
17.875
def get_plugin_folders(): """Get linkchecker plugin folders. Default is ~/.linkchecker/plugins/.""" folders = [] defaultfolder = normpath("~/.linkchecker/plugins") if not os.path.exists(defaultfolder) and not Portable: try: make_userdir(defaultfolder) except Exception as errm...
[ "def", "get_plugin_folders", "(", ")", ":", "folders", "=", "[", "]", "defaultfolder", "=", "normpath", "(", "\"~/.linkchecker/plugins\"", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "defaultfolder", ")", "and", "not", "Portable", ":", "try", ...
42.285714
14.071429
def parseArgs(): # pragma: no cover """Parses the command line options and arguments. :returns: A :py:class:`argparse.Namespace` object created by the :py:mod:`argparse` module. It contains the values of the different options. ===================== ====== =====================...
[ "def", "parseArgs", "(", ")", ":", "# pragma: no cover", "# The INPUT files", "group", "=", "parser", ".", "add_argument_group", "(", "\"Input File\"", ")", "group", ".", "add_argument", "(", "\"--file\"", ",", "type", "=", "str", ",", "metavar", "=", "\"FILE\""...
43.166667
22.833333
def density(self, R, Rs, rho0): """ three dimenstional NFW profile :param R: radius of interest :type R: float/numpy array :param Rs: scale radius :type Rs: float :param rho0: density normalization (characteristic density) :type rho0: float :retur...
[ "def", "density", "(", "self", ",", "R", ",", "Rs", ",", "rho0", ")", ":", "return", "rho0", "/", "(", "R", "/", "Rs", "*", "(", "1", "+", "R", "/", "Rs", ")", "**", "2", ")" ]
28.923077
10.769231
def _follow_leafref( self, xpath: "Expr", init: "TerminalNode") -> Optional["DataNode"]: """Return the data node referred to by a leafref path. Args: xpath: XPath expression compiled from a leafref path. init: initial context node """ if isinstance(xp...
[ "def", "_follow_leafref", "(", "self", ",", "xpath", ":", "\"Expr\"", ",", "init", ":", "\"TerminalNode\"", ")", "->", "Optional", "[", "\"DataNode\"", "]", ":", "if", "isinstance", "(", "xpath", ",", "LocationPath", ")", ":", "lft", "=", "self", ".", "_...
41.25
13.625
def get_models(app_labels): """ Get a list of models for the given app labels, with some exceptions. TODO: If a required model is referenced, it should also be included. Or at least discovered with a get_or_create() call. """ # These models are not to be output, e.g. because they can be generat...
[ "def", "get_models", "(", "app_labels", ")", ":", "# These models are not to be output, e.g. because they can be generated automatically", "# TODO: This should be \"appname.modelname\" string", "EXCLUDED_MODELS", "=", "(", "ContentType", ",", ")", "models", "=", "[", "]", "# If n...
36.3125
20.9375
def get_uuid_list(dbconn): """ Get a list of tables that exist in dbconn :param dbconn: master database connection :return: List of uuids in the database """ cur = dbconn.cursor() tables = get_table_list(dbconn) uuids = set() for table in tables: cur.execute("SELECT (UUID) FR...
[ "def", "get_uuid_list", "(", "dbconn", ")", ":", "cur", "=", "dbconn", ".", "cursor", "(", ")", "tables", "=", "get_table_list", "(", "dbconn", ")", "uuids", "=", "set", "(", ")", "for", "table", "in", "tables", ":", "cur", ".", "execute", "(", "\"SE...
30.4
12.266667
def node_to_complex_fault_geometry(node): """ Reads a complex fault geometry node and returns an """ assert "complexFaultGeometry" in node.tag intermediate_edges = [] for subnode in node.nodes: if "faultTopEdge" in subnode.tag: top_edge = linestring_node_to_line(subnode.nodes...
[ "def", "node_to_complex_fault_geometry", "(", "node", ")", ":", "assert", "\"complexFaultGeometry\"", "in", "node", ".", "tag", "intermediate_edges", "=", "[", "]", "for", "subnode", "in", "node", ".", "nodes", ":", "if", "\"faultTopEdge\"", "in", "subnode", "."...
42.333333
14.142857
def get_arg_parse_arguments(self): """ During the element declaration, all configuration file requirements and all cli requirements have been described once. This method will build a dict containing all argparse options. It can be used to feed argparse.ArgumentParser. You...
[ "def", "get_arg_parse_arguments", "(", "self", ")", ":", "ret", "=", "dict", "(", ")", "if", "self", ".", "_required", ":", "if", "self", ".", "value", "is", "not", "None", ":", "ret", "[", "\"default\"", "]", "=", "self", ".", "value", "else", ":", ...
38.2
14.2
def ToURN(self): """Converts a reference into an URN.""" if self.path_type in [PathInfo.PathType.OS, PathInfo.PathType.TSK]: return rdfvalue.RDFURN(self.client_id).Add("fs").Add( self.path_type.name.lower()).Add("/".join(self.path_components)) elif self.path_type == PathInfo.PathType.REGIST...
[ "def", "ToURN", "(", "self", ")", ":", "if", "self", ".", "path_type", "in", "[", "PathInfo", ".", "PathType", ".", "OS", ",", "PathInfo", ".", "PathType", ".", "TSK", "]", ":", "return", "rdfvalue", ".", "RDFURN", "(", "self", ".", "client_id", ")",...
45.785714
22.714286
def delete_database(self, database_name): """ Deletes an existing database in CosmosDB. """ if database_name is None: raise AirflowBadRequest("Database name cannot be None.") self.get_conn().DeleteDatabase(get_database_link(database_name))
[ "def", "delete_database", "(", "self", ",", "database_name", ")", ":", "if", "database_name", "is", "None", ":", "raise", "AirflowBadRequest", "(", "\"Database name cannot be None.\"", ")", "self", ".", "get_conn", "(", ")", ".", "DeleteDatabase", "(", "get_databa...
35.625
14.625
def _initApplicationList(self): """Query Asterisk Manager Interface to initialize internal list of available applications. CLI Command - core show applications """ if self.checkVersion('1.4'): cmd = "core show applications" else: ...
[ "def", "_initApplicationList", "(", "self", ")", ":", "if", "self", ".", "checkVersion", "(", "'1.4'", ")", ":", "cmd", "=", "\"core show applications\"", "else", ":", "cmd", "=", "\"show applications\"", "cmdresp", "=", "self", ".", "executeCommand", "(", "cm...
34.470588
10.823529
def tracker(obj): """Returns the :class:`Instance` of the specified object if it is one that we track by default. Args: obj (object): any python object passed as an argument to a method. Returns: Instance: if the object is trackable, the Instance instance of that object; else...
[ "def", "tracker", "(", "obj", ")", ":", "import", "types", "as", "typ", "global", "oids", ",", "uuids", "import", "six", "from", "inspect", "import", "isclass", "untracked", "=", "(", "six", ".", "string_types", ",", "six", ".", "integer_types", ",", "fl...
37.085366
18.341463
def _prepare_orders(self, orders): """ Each order needs to have all it's details filled with default value, or None, in case those are not already filled. """ for detail in PAYU_ORDER_DETAILS: if not any([detail in order for order in orders]): for ord...
[ "def", "_prepare_orders", "(", "self", ",", "orders", ")", ":", "for", "detail", "in", "PAYU_ORDER_DETAILS", ":", "if", "not", "any", "(", "[", "detail", "in", "order", "for", "order", "in", "orders", "]", ")", ":", "for", "order", "in", "orders", ":",...
35.583333
18.583333
def make_lat_lons(cvects): """ Convert from directional cosines to latitidue and longitude Parameters ---------- cvects : directional cosine (i.e., x,y,z component) values returns (np.ndarray(2,nsrc)) with the directional cosine (i.e., x,y,z component) values """ lats = np.degrees(np.arcsi...
[ "def", "make_lat_lons", "(", "cvects", ")", ":", "lats", "=", "np", ".", "degrees", "(", "np", ".", "arcsin", "(", "cvects", "[", "2", "]", ")", ")", "lons", "=", "np", ".", "degrees", "(", "np", ".", "arctan2", "(", "cvects", "[", "0", "]", ",...
34.416667
20.25