text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def parameters(self) -> List['Parameter']: """Return a list of parameter objects.""" _lststr = self._lststr _type_to_spans = self._type_to_spans return [ Parameter(_lststr, _type_to_spans, span, 'Parameter') for span in self._subspans('Parameter')]
[ "def", "parameters", "(", "self", ")", "->", "List", "[", "'Parameter'", "]", ":", "_lststr", "=", "self", ".", "_lststr", "_type_to_spans", "=", "self", ".", "_type_to_spans", "return", "[", "Parameter", "(", "_lststr", ",", "_type_to_spans", ",", "span", ...
42.571429
11
def get_placeholder_cache_key_for_parent(parent_object, placeholder_name, language_code): """ Return a cache key for a placeholder. This key is used to cache the entire output of a placeholder. """ parent_type = ContentType.objects.get_for_model(parent_object) return _get_placeholder_cache_key_...
[ "def", "get_placeholder_cache_key_for_parent", "(", "parent_object", ",", "placeholder_name", ",", "language_code", ")", ":", "parent_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "parent_object", ")", "return", "_get_placeholder_cache_key_for_id", ...
32.230769
19
def get_distribution_names(self): """ Return all the distribution names known to this locator. """ result = set() page = self.get_page(self.base_url) if not page: raise DistlibException('Unable to get %s' % self.base_url) for match in self._distname_re...
[ "def", "get_distribution_names", "(", "self", ")", ":", "result", "=", "set", "(", ")", "page", "=", "self", ".", "get_page", "(", "self", ".", "base_url", ")", "if", "not", "page", ":", "raise", "DistlibException", "(", "'Unable to get %s'", "%", "self", ...
35.636364
12.909091
def _parseDeclaration(self, src): """declaration : ident S* ':' S* expr prio? | /* empty */ ; """ # property propertyName, src = self._getIdent(src) if propertyName is not None: src = src.lstrip() # S* : S* if src[:1] i...
[ "def", "_parseDeclaration", "(", "self", ",", "src", ")", ":", "# property", "propertyName", ",", "src", "=", "self", ".", "_getIdent", "(", "src", ")", "if", "propertyName", "is", "not", "None", ":", "src", "=", "src", ".", "lstrip", "(", ")", "# S* :...
31.478261
19
def sslv2_derive_keys(self, key_material): """ There is actually only one key, the CLIENT-READ-KEY or -WRITE-KEY. Note that skip_first is opposite from the one with SSLv3 derivation. Also, if needed, the IV should be set elsewhere. """ skip_first = True if ((sel...
[ "def", "sslv2_derive_keys", "(", "self", ",", "key_material", ")", ":", "skip_first", "=", "True", "if", "(", "(", "self", ".", "connection_end", "==", "\"client\"", "and", "self", ".", "row", "==", "\"read\"", ")", "or", "(", "self", ".", "connection_end"...
35.727273
19
def grid_1d(self): """ The arc second-grid of (y,x) coordinates of every pixel. This is defined from the top-left corner, such that the first pixel at location [0, 0] will have a negative x \ value y value in arc seconds. """ return grid_util.regular_grid_1d_from_shape_pixel_sca...
[ "def", "grid_1d", "(", "self", ")", ":", "return", "grid_util", ".", "regular_grid_1d_from_shape_pixel_scales_and_origin", "(", "shape", "=", "self", ".", "shape", ",", "pixel_scales", "=", "self", ".", "pixel_scales", ",", "origin", "=", "self", ".", "origin", ...
60.888889
35.444444
def dist_dir(self): '''The dist dir at which to place the finished distribution.''' if self.distribution is None: warning('Tried to access {}.dist_dir, but {}.distribution ' 'is None'.format(self, self)) exit(1) return self.distribution.dist_dir
[ "def", "dist_dir", "(", "self", ")", ":", "if", "self", ".", "distribution", "is", "None", ":", "warning", "(", "'Tried to access {}.dist_dir, but {}.distribution '", "'is None'", ".", "format", "(", "self", ",", "self", ")", ")", "exit", "(", "1", ")", "ret...
43.857143
16.714286
def save(self, filething=None, v2_version=4, v23_sep='/', padding=None): """Save ID3v2 data to the AIFF file""" fileobj = filething.fileobj iff_file = IFFFile(fileobj) if u'ID3' not in iff_file: iff_file.insert_chunk(u'ID3') chunk = iff_file[u'ID3'] try: ...
[ "def", "save", "(", "self", ",", "filething", "=", "None", ",", "v2_version", "=", "4", ",", "v23_sep", "=", "'/'", ",", "padding", "=", "None", ")", ":", "fileobj", "=", "filething", ".", "fileobj", "iff_file", "=", "IFFFile", "(", "fileobj", ")", "...
29.615385
17.153846
def update_input(filelist, ivmlist=None, removed_files=None): """ Removes files flagged to be removed from the input filelist. Removes the corresponding ivm files if present. """ newfilelist = [] if removed_files == []: return filelist, ivmlist else: sci_ivm = list(zip(filel...
[ "def", "update_input", "(", "filelist", ",", "ivmlist", "=", "None", ",", "removed_files", "=", "None", ")", ":", "newfilelist", "=", "[", "]", "if", "removed_files", "==", "[", "]", ":", "return", "filelist", ",", "ivmlist", "else", ":", "sci_ivm", "=",...
34.3125
14.1875
def magic_read_dict(path, data=None, sort_by_this_name=None, return_keys=False): """ Read a magic-formatted tab-delimited file and return a dictionary of dictionaries, with this format: {'Z35.5a': {'specimen_weight': '1.000e-03', 'er_citation_names': 'This study', 'specimen_volume': '', 'er_location_nam...
[ "def", "magic_read_dict", "(", "path", ",", "data", "=", "None", ",", "sort_by_this_name", "=", "None", ",", "return_keys", "=", "False", ")", ":", "DATA", "=", "{", "}", "#fin = open(path, 'r')", "#first_line = fin.readline()", "lines", "=", "open_file", "(", ...
35.644068
19.881356
def loads(astring): """Decompress and deserialize string into Python object via pickle.""" try: return pickle.loads(zlib.decompress(astring)) except zlib.error as e: raise SerializerError( 'Cannot decompress object ("{}")'.format(str(e)) ) ...
[ "def", "loads", "(", "astring", ")", ":", "try", ":", "return", "pickle", ".", "loads", "(", "zlib", ".", "decompress", "(", "astring", ")", ")", "except", "zlib", ".", "error", "as", "e", ":", "raise", "SerializerError", "(", "'Cannot decompress object (\...
38.25
15.75
def _delete_network(self, network_info): """Send network delete request to DCNM. :param network_info: contains network info to be deleted. """ org_name = network_info.get('organizationName', '') part_name = network_info.get('partitionName', '') segment_id = network_info[...
[ "def", "_delete_network", "(", "self", ",", "network_info", ")", ":", "org_name", "=", "network_info", ".", "get", "(", "'organizationName'", ",", "''", ")", "part_name", "=", "network_info", ".", "get", "(", "'partitionName'", ",", "''", ")", "segment_id", ...
46.4375
16.1875
def fit(self, X, y): """Build an accelerated failure time model. Parameters ---------- X : array-like, shape = (n_samples, n_features) Data matrix. y : structured array, shape = (n_samples,) A structured array containing the binary event indicator ...
[ "def", "fit", "(", "self", ",", "X", ",", "y", ")", ":", "X", ",", "event", ",", "time", "=", "check_arrays_survival", "(", "X", ",", "y", ")", "weights", "=", "ipc_weights", "(", "event", ",", "time", ")", "super", "(", ")", ".", "fit", "(", "...
27.217391
22.26087
def transform_describe(self, node, describes, context_variable): """ Transform a describe node into a ``TestCase``. ``node`` is the node object. ``describes`` is the name of the object being described. ``context_variable`` is the name bound in the context manager (usually ...
[ "def", "transform_describe", "(", "self", ",", "node", ",", "describes", ",", "context_variable", ")", ":", "body", "=", "self", ".", "transform_describe_body", "(", "node", ".", "body", ",", "context_variable", ")", "return", "ast", ".", "ClassDef", "(", "n...
32.238095
19.857143
def FDMT_iteration(datain, maxDT, nchan0, f_min, f_max, iteration_num, dataType): """ Input: Input - 3d array, with dimensions [nint, N_d0, nbl, nchan, npol] f_min,f_max - are the base-band begin and end frequencies. The frequencies can be entered in both MHz and GHz...
[ "def", "FDMT_iteration", "(", "datain", ",", "maxDT", ",", "nchan0", ",", "f_min", ",", "f_max", ",", "iteration_num", ",", "dataType", ")", ":", "nint", ",", "dT", ",", "nbl", ",", "nchan", ",", "npol", "=", "datain", ".", "shape", "# output_dims = l...
51.941176
34.741176
def rejection_sample(self, evidence=None, size=1, return_type="dataframe"): """ Generates sample(s) from joint distribution of the bayesian network, given the evidence. Parameters ---------- evidence: list of `pgmpy.factor.State` namedtuples None if no eviden...
[ "def", "rejection_sample", "(", "self", ",", "evidence", "=", "None", ",", "size", "=", "1", ",", "return_type", "=", "\"dataframe\"", ")", ":", "if", "evidence", "is", "None", ":", "return", "self", ".", "forward_sample", "(", "size", ")", "types", "=",...
40.322034
20.830508
def is_active_trail(self, start, end, observed=None): """ Returns True if there is any active trail between start and end node Parameters ---------- start : Graph Node end : Graph Node observed : List of nodes (optional) If given the active trail would...
[ "def", "is_active_trail", "(", "self", ",", "start", ",", "end", ",", "observed", "=", "None", ")", ":", "if", "end", "in", "self", ".", "active_trail_nodes", "(", "start", ",", "observed", ")", "[", "start", "]", ":", "return", "True", "else", ":", ...
41.642857
21.714286
def add_edge(self, start, end, **kwargs): """ Add an edge between two nodes. The nodes will be automatically added if they are not present in the network. Parameters ---------- start: tuple Both the start and end nodes should specify the time slice as ...
[ "def", "add_edge", "(", "self", ",", "start", ",", "end", ",", "*", "*", "kwargs", ")", ":", "try", ":", "if", "len", "(", "start", ")", "!=", "2", "or", "len", "(", "end", ")", "!=", "2", ":", "raise", "ValueError", "(", "'Nodes must be of type (n...
44.754098
24.295082
def skip_regex(lines, options): """ Optionally exclude lines that match '--skip-requirements-regex' """ skip_regex = options.skip_requirements_regex if options else None if skip_regex: lines = filterfalse(re.compile(skip_regex).search, lines) return lines
[ "def", "skip_regex", "(", "lines", ",", "options", ")", ":", "skip_regex", "=", "options", ".", "skip_requirements_regex", "if", "options", "else", "None", "if", "skip_regex", ":", "lines", "=", "filterfalse", "(", "re", ".", "compile", "(", "skip_regex", ")...
35
17
def load_path_with_default(self, path, default_constructor): ''' Same as `load_path(path)', except uses default_constructor on import errors, or if loaded a auto-generated namespace package (e.g. bare directory). ''' try: imported_obj = self.load_path(path) ...
[ "def", "load_path_with_default", "(", "self", ",", "path", ",", "default_constructor", ")", ":", "try", ":", "imported_obj", "=", "self", ".", "load_path", "(", "path", ")", "except", "(", "ImportError", ",", "ConfigurationError", ")", ":", "imported_obj", "="...
43.176471
21.058824
def set_branch_capacity(network, args): """ Set branch capacity factor of lines and transformers, different factors for HV (110kV) and eHV (220kV, 380kV). Parameters ---------- network : :class:`pypsa.Network Overall container of PyPSA args: dict Settings in appl.py ""...
[ "def", "set_branch_capacity", "(", "network", ",", "args", ")", ":", "network", ".", "lines", "[", "\"s_nom_total\"", "]", "=", "network", ".", "lines", ".", "s_nom", ".", "copy", "(", ")", "network", ".", "transformers", "[", "\"s_nom_total\"", "]", "=", ...
32.714286
24.828571
def execute_command(self, command, tab=None): # TODO DBUS_ONLY """Execute the `command' in the `tab'. If tab is None, the command will be executed in the currently selected tab. Command should end with '\n', otherwise it will be appended to the string. """ # TODO ...
[ "def", "execute_command", "(", "self", ",", "command", ",", "tab", "=", "None", ")", ":", "# TODO DBUS_ONLY", "# TODO CONTEXTMENU this has to be rewriten and only serves the", "# dbus interface, maybe this should be moved to dbusinterface.py", "if", "not", "self", ".", "get_not...
39.235294
16.470588
def get_data_files_tuple(*rel_path, **kwargs): """Return a tuple which can be used for setup.py's data_files :param tuple path: List of path elements pointing to a file or a directory of files :param dict kwargs: Set path_to_file to True is `path` points to a file :return: tuple of install directory an...
[ "def", "get_data_files_tuple", "(", "*", "rel_path", ",", "*", "*", "kwargs", ")", ":", "rel_path", "=", "os", ".", "path", ".", "join", "(", "*", "rel_path", ")", "target_path", "=", "os", ".", "path", ".", "join", "(", "\"share\"", ",", "*", "rel_p...
49.5
21.875
def _create_dir(path): '''Creates necessary directories for the given path or does nothing if the directories already exist. ''' try: os.makedirs(path) except OSError, exc: if exc.errno == errno.EEXIST: pass else: raise
[ "def", "_create_dir", "(", "path", ")", ":", "try", ":", "os", ".", "makedirs", "(", "path", ")", "except", "OSError", ",", "exc", ":", "if", "exc", ".", "errno", "==", "errno", ".", "EEXIST", ":", "pass", "else", ":", "raise" ]
25.181818
20.454545
def cluster(x, cluster='KMeans', n_clusters=3, ndims=None, format_data=True): """ Performs clustering analysis and returns a list of cluster labels Parameters ---------- x : A Numpy array, Pandas Dataframe or list of arrays/dfs The data to be clustered. You can pass a single array/df or a ...
[ "def", "cluster", "(", "x", ",", "cluster", "=", "'KMeans'", ",", "n_clusters", "=", "3", ",", "ndims", "=", "None", ",", "format_data", "=", "True", ")", ":", "if", "cluster", "==", "None", ":", "return", "x", "elif", "(", "isinstance", "(", "cluste...
34.369863
24.780822
async def StartUnitCompletion(self, entities, message): ''' entities : typing.Sequence[~Entity] message : str Returns -> typing.Sequence[~ErrorResult] ''' # map input types to rpc msg _params = dict() msg = dict(type='UpgradeSeries', req...
[ "async", "def", "StartUnitCompletion", "(", "self", ",", "entities", ",", "message", ")", ":", "# map input types to rpc msg", "_params", "=", "dict", "(", ")", "msg", "=", "dict", "(", "type", "=", "'UpgradeSeries'", ",", "request", "=", "'StartUnitCompletion'"...
33.125
11.25
async def client_event_handler(self, client_id, event_tuple, user_data): """Method called to actually send an event to a client. Users of this class should override this method to actually forward device events to their clients. It is called with the client_id passed to (or returned fr...
[ "async", "def", "client_event_handler", "(", "self", ",", "client_id", ",", "event_tuple", ",", "user_data", ")", ":", "conn_string", ",", "event_name", ",", "_event", "=", "event_tuple", "self", ".", "_logger", ".", "debug", "(", "\"Ignoring event %s from device ...
39.233333
26.1
def focusOutEvent(self, event): """Reimplement Qt method to send focus change notification""" self.focus_changed.emit() return super(PageControlWidget, self).focusOutEvent(event)
[ "def", "focusOutEvent", "(", "self", ",", "event", ")", ":", "self", ".", "focus_changed", ".", "emit", "(", ")", "return", "super", "(", "PageControlWidget", ",", "self", ")", ".", "focusOutEvent", "(", "event", ")" ]
49.75
10.5
def _check_useless_super_delegation(self, function): """Check if the given function node is an useless method override We consider it *useless* if it uses the super() builtin, but having nothing additional whatsoever than not implementing the method at all. If the method uses super() to...
[ "def", "_check_useless_super_delegation", "(", "self", ",", "function", ")", ":", "if", "(", "not", "function", ".", "is_method", "(", ")", "# With decorators is a change of use", "or", "function", ".", "decorators", ")", ":", "return", "body", "=", "function", ...
37.12381
22.304762
def moveaxis(a, source, destination): """Move axes of an array to new positions. Other axes remain in their original order. This function is a backport of `numpy.moveaxis` introduced in NumPy 1.11. See Also -------- numpy.moveaxis """ import numpy if hasattr(numpy, 'moveaxis')...
[ "def", "moveaxis", "(", "a", ",", "source", ",", "destination", ")", ":", "import", "numpy", "if", "hasattr", "(", "numpy", ",", "'moveaxis'", ")", ":", "return", "numpy", ".", "moveaxis", "(", "a", ",", "source", ",", "destination", ")", "try", ":", ...
25
21.676471
def update_or_create_candidate( self, candidate, aggregable=True, uncontested=False ): """Create a CandidateElection.""" candidate_election, c = CandidateElection.objects.update_or_create( candidate=candidate, election=self, defaults={"aggregable": aggrega...
[ "def", "update_or_create_candidate", "(", "self", ",", "candidate", ",", "aggregable", "=", "True", ",", "uncontested", "=", "False", ")", ":", "candidate_election", ",", "c", "=", "CandidateElection", ".", "objects", ".", "update_or_create", "(", "candidate", "...
35.272727
21.181818
def invert(self, output_directory=None, catch_output=True, **kwargs): """Invert this instance, and import the result files No directories/files will be overwritten. Raise an IOError if the output directory exists. Parameters ---------- output_directory: string, optional...
[ "def", "invert", "(", "self", ",", "output_directory", "=", "None", ",", "catch_output", "=", "True", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_check_state", "(", ")", "if", "self", ".", "can_invert", ":", "if", "output_directory", "is", "not", ...
35.913043
19.5
def evalall(self, loc=None, defaults=None): """Evaluates all option values in environment `loc`. :See: `eval()` """ self.check() if defaults is None: defaults = cma_default_options # TODO: this needs rather the parameter N instead of loc if 'N' in lo...
[ "def", "evalall", "(", "self", ",", "loc", "=", "None", ",", "defaults", "=", "None", ")", ":", "self", ".", "check", "(", ")", "if", "defaults", "is", "None", ":", "defaults", "=", "cma_default_options", "# TODO: this needs rather the parameter N instead of loc...
36.166667
14.333333
def filter_queryset(self, request, queryset, view): """ This method overrides the standard filter_queryset method. This method will check to see if the view calling this is from a list type action. This function will also route the filter by action type if action_routing is set t...
[ "def", "filter_queryset", "(", "self", ",", "request", ",", "queryset", ",", "view", ")", ":", "# Check if this is a list type request", "if", "view", ".", "lookup_field", "not", "in", "view", ".", "kwargs", ":", "if", "not", "self", ".", "action_routing", ":"...
49.066667
18.4
def send_signal(self, signal): """ Send signal from this node to all connected receivers unless the node is in spectator mode. signal -- (hashable) signal value, see `dispatcher` connect for details Return a list of tuple pairs [(receiver, response), ... ] or None if the node i...
[ "def", "send_signal", "(", "self", ",", "signal", ")", ":", "if", "self", ".", "in_spectator_mode", ":", "return", "None", "logger", ".", "debug", "(", "\"Node %s broadcasts signal %s\"", "%", "(", "self", ",", "signal", ")", ")", "dispatcher", ".", "send", ...
44.625
24.5
def plot_elbo(self, figsize=(15,7)): """ Plots the ELBO progress (if present) """ import matplotlib.pyplot as plt plt.figure(figsize=figsize) plt.plot(self.elbo_records) plt.xlabel("Iterations") plt.ylabel("ELBO") plt.show()
[ "def", "plot_elbo", "(", "self", ",", "figsize", "=", "(", "15", ",", "7", ")", ")", ":", "import", "matplotlib", ".", "pyplot", "as", "plt", "plt", ".", "figure", "(", "figsize", "=", "figsize", ")", "plt", ".", "plot", "(", "self", ".", "elbo_rec...
26.090909
9.363636
def _format(color, style=''): """Return a QTextCharFormat with the given attributes. """ _color = QColor() _color.setNamedColor(color) _format = QTextCharFormat() _format.setForeground(_color) if 'bold' in style: _format.setFontWeight(QFont.Bold) if 'italic' in style: ...
[ "def", "_format", "(", "color", ",", "style", "=", "''", ")", ":", "_color", "=", "QColor", "(", ")", "_color", ".", "setNamedColor", "(", "color", ")", "_format", "=", "QTextCharFormat", "(", ")", "_format", ".", "setForeground", "(", "_color", ")", "...
26.071429
13.285714
def ls_remote(cwd=None, remote='origin', ref=None, opts='', git_opts='', user=None, password=None, identity=None, https_user=None, https_pass=None, ignore_retcode=False, ...
[ "def", "ls_remote", "(", "cwd", "=", "None", ",", "remote", "=", "'origin'", ",", "ref", "=", "None", ",", "opts", "=", "''", ",", "git_opts", "=", "''", ",", "user", "=", "None", ",", "password", "=", "None", ",", "identity", "=", "None", ",", "...
32.865031
24.840491
def set_cognitive_process(self, grade_id=None): """Sets the cognitive process. arg: gradeId (osid.id.Id): the new cognitive process raise: INVALID_ARGUMENT - gradeId is invalid raise: NoAccess - gradeId cannot be modified raise: NullArgument - gradeId is null compl...
[ "def", "set_cognitive_process", "(", "self", ",", "grade_id", "=", "None", ")", ":", "if", "grade_id", "is", "None", ":", "raise", "NullArgument", "(", ")", "metadata", "=", "Metadata", "(", "*", "*", "settings", ".", "METADATA", "[", "'cognitive_process_id'...
39.105263
16.631579
def terminate(self): """Override of PantsService.terminate() that cleans up when the Pailgun server is terminated.""" # Tear down the Pailgun TCPServer. if self.pailgun: self.pailgun.server_close() super(PailgunService, self).terminate()
[ "def", "terminate", "(", "self", ")", ":", "# Tear down the Pailgun TCPServer.", "if", "self", ".", "pailgun", ":", "self", ".", "pailgun", ".", "server_close", "(", ")", "super", "(", "PailgunService", ",", "self", ")", ".", "terminate", "(", ")" ]
36.285714
13.142857
def _adjacency_to_edges(adjacency): """determine from an adjacency the list of edges if (u, v) in edges, then (v, u) should not be""" edges = set() for u in adjacency: for v in adjacency[u]: try: edge = (u, v) if u <= v else (v, u) except TypeError: ...
[ "def", "_adjacency_to_edges", "(", "adjacency", ")", ":", "edges", "=", "set", "(", ")", "for", "u", "in", "adjacency", ":", "for", "v", "in", "adjacency", "[", "u", "]", ":", "try", ":", "edge", "=", "(", "u", ",", "v", ")", "if", "u", "<=", "...
31.25
14.125
def logWrite(self, string): """Only write text to the log file, do not print""" logFile = open(self.logFile, 'at') logFile.write(string + '\n') logFile.close()
[ "def", "logWrite", "(", "self", ",", "string", ")", ":", "logFile", "=", "open", "(", "self", ".", "logFile", ",", "'at'", ")", "logFile", ".", "write", "(", "string", "+", "'\\n'", ")", "logFile", ".", "close", "(", ")" ]
32.6
10
def _checkgrad(self, target_param=None, verbose=False, step=1e-6, tolerance=1e-3, df_tolerance=1e-12): """ Check the gradient of the ,odel by comparing to a numerical estimate. If the verbose flag is passed, individual components are tested (and printed) :param verbose: If True...
[ "def", "_checkgrad", "(", "self", ",", "target_param", "=", "None", ",", "verbose", "=", "False", ",", "step", "=", "1e-6", ",", "tolerance", "=", "1e-3", ",", "df_tolerance", "=", "1e-12", ")", ":", "if", "not", "self", ".", "_model_initialized_", ":", ...
47.016
23.624
def update_parameters(url, parameters, encoding='utf8'): """ Updates a URL's existing GET parameters. :param url: a base URL to which to add additional parameters. :param parameters: a dictionary of parameters, any mix of unicode and string objects as the parameters and the values. :parameter encoding: the...
[ "def", "update_parameters", "(", "url", ",", "parameters", ",", "encoding", "=", "'utf8'", ")", ":", "# Convert the base URL to the default encoding.", "if", "isinstance", "(", "url", ",", "unicode", ")", ":", "url", "=", "url", ".", "encode", "(", "encoding", ...
38.975
19.8
def setup_dashboard_panels_visibility_registry(section_name): """ Initializes the values for panels visibility in registry_records. By default, only users with LabManager or Manager roles can see the panels. :param section_name: :return: An string like: "role1,yes,role2,no,rol3,no" """ regis...
[ "def", "setup_dashboard_panels_visibility_registry", "(", "section_name", ")", ":", "registry_info", "=", "get_dashboard_registry_record", "(", ")", "role_permissions_list", "=", "[", "]", "# Getting roles defined in the system", "roles", "=", "[", "]", "acl_users", "=", ...
38.5
13.766667
def set_lic_id(self, doc, lic_id): """Adds a new extracted license to the document. Raises SPDXValueError if data format is incorrect. """ # FIXME: this state does not make sense self.reset_extr_lics() if validations.validate_extracted_lic_id(lic_id): doc.add_...
[ "def", "set_lic_id", "(", "self", ",", "doc", ",", "lic_id", ")", ":", "# FIXME: this state does not make sense", "self", ".", "reset_extr_lics", "(", ")", "if", "validations", ".", "validate_extracted_lic_id", "(", "lic_id", ")", ":", "doc", ".", "add_extr_lic", ...
40.727273
12.818182
def control_surface_encode(self, target, idSurface, mControl, bControl): ''' Control for surface; pending and order to origin. target : The system setting the commands (uint8_t) idSurface : ID control surface send 0: thr...
[ "def", "control_surface_encode", "(", "self", ",", "target", ",", "idSurface", ",", "mControl", ",", "bControl", ")", ":", "return", "MAVLink_control_surface_message", "(", "target", ",", "idSurface", ",", "mControl", ",", "bControl", ")" ]
54.636364
36.818182
def _run(command, quiet=False, timeout=None): """Run a command, returns command output.""" try: with _spawn(command, quiet, timeout) as child: command_output = child.read().strip().replace("\r\n", "\n") except pexpect.TIMEOUT: logger.info(f"command {command} timed out") r...
[ "def", "_run", "(", "command", ",", "quiet", "=", "False", ",", "timeout", "=", "None", ")", ":", "try", ":", "with", "_spawn", "(", "command", ",", "quiet", ",", "timeout", ")", "as", "child", ":", "command_output", "=", "child", ".", "read", "(", ...
35
18
def is_valid_mac_oui(mac_block): """checks whether mac block is in format of 00-11-22 or 00:11:22. :return: int """ if len(mac_block) != 8: return 0 if ':' in mac_block: if len(mac_block.split(':')) != 3: return 0 elif '-' i...
[ "def", "is_valid_mac_oui", "(", "mac_block", ")", ":", "if", "len", "(", "mac_block", ")", "!=", "8", ":", "return", "0", "if", "':'", "in", "mac_block", ":", "if", "len", "(", "mac_block", ".", "split", "(", "':'", ")", ")", "!=", "3", ":", "retur...
29.142857
11.285714
def vertical_line(self, x: Union[int, float], y1: Union[int, float], y2: Union[int, float], emphasize: bool = False ) -> None: """Adds a line from (x, y1) to (x, y2).""" y1, y2 = sorted([y1, y2]...
[ "def", "vertical_line", "(", "self", ",", "x", ":", "Union", "[", "int", ",", "float", "]", ",", "y1", ":", "Union", "[", "int", ",", "float", "]", ",", "y2", ":", "Union", "[", "int", ",", "float", "]", ",", "emphasize", ":", "bool", "=", "Fal...
42.777778
8.777778
def count(self, field='*'): """ Returns a COUNT of the query by wrapping the query and performing a COUNT aggregate of the specified field :param field: the field to pass to the COUNT aggregate. Defaults to '*' :type field: str :return: The number of rows that the query...
[ "def", "count", "(", "self", ",", "field", "=", "'*'", ")", ":", "rows", "=", "self", ".", "get_count_query", "(", ")", ".", "select", "(", "bypass_safe_limit", "=", "True", ")", "return", "list", "(", "rows", "[", "0", "]", ".", "values", "(", ")"...
35.538462
20
def add_manual_segmentation_to_data_frame(self, data_frame, segmentation_dictionary): """ Utility method to store manual segmentation of gait time series. :param data_frame: The data frame. It should have x, y, and z columns. :type data_frame: pandas.DataFrame :...
[ "def", "add_manual_segmentation_to_data_frame", "(", "self", ",", "data_frame", ",", "segmentation_dictionary", ")", ":", "# add some checks to see if dictionary is in the right format!", "data_frame", "[", "'segmentation'", "]", "=", "'unknown'", "for", "i", ",", "(", "k",...
50.142857
28.392857
def compareValues( self, a, b ): """ Compares two values based on the notches and values for this ruler. :param a | <variant> b | <variant> :return <int> 1 || 0 || -1 """ if ( self.rulerType() in (XChartRuler.Type.Cu...
[ "def", "compareValues", "(", "self", ",", "a", ",", "b", ")", ":", "if", "(", "self", ".", "rulerType", "(", ")", "in", "(", "XChartRuler", ".", "Type", ".", "Custom", ",", "XChartRuler", ".", "Type", ".", "Monthly", ")", ")", ":", "try", ":", "a...
29.08
15.96
def _to_parent_frame(self, *args, **kwargs): """Conversion from Topocentric Frame to parent frame """ lat, lon, _ = self.latlonalt m = rot3(-lon) @ rot2(lat - np.pi / 2.) @ rot3(self.heading) offset = np.zeros(6) offset[:3] = self.coordinates return self._convert(...
[ "def", "_to_parent_frame", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "lat", ",", "lon", ",", "_", "=", "self", ".", "latlonalt", "m", "=", "rot3", "(", "-", "lon", ")", "@", "rot2", "(", "lat", "-", "np", ".", "pi", "/...
40.75
6.625
def import_legislators(src): """ Read the legislators from the csv files into a single Dataframe. Intended for importing new data. """ logger.info("Importing Legislators From: {0}".format(src)) current = pd.read_csv("{0}/{1}/legislators-current.csv".format( src, LEGISLATOR_DIR)) hist...
[ "def", "import_legislators", "(", "src", ")", ":", "logger", ".", "info", "(", "\"Importing Legislators From: {0}\"", ".", "format", "(", "src", ")", ")", "current", "=", "pd", ".", "read_csv", "(", "\"{0}/{1}/legislators-current.csv\"", ".", "format", "(", "src...
35.846154
17.076923
def get_property_name_from_attribute_name(attribute): """ Returns property name from attribute name :param attribute: Attribute name, may contain upper and lower case and spaces :return: string """ if isinstance(attribute, str) or isinstance(attribute, unicode): ...
[ "def", "get_property_name_from_attribute_name", "(", "attribute", ")", ":", "if", "isinstance", "(", "attribute", ",", "str", ")", "or", "isinstance", "(", "attribute", ",", "unicode", ")", ":", "attribute_name", "=", "attribute", "elif", "hasattr", "(", "attrib...
42
18.428571
def hash256(msg_bytes): ''' byte-like -> bytes ''' if 'decred' in riemann.get_current_network_name(): return blake256(blake256(msg_bytes)) return hashlib.sha256(hashlib.sha256(msg_bytes).digest()).digest()
[ "def", "hash256", "(", "msg_bytes", ")", ":", "if", "'decred'", "in", "riemann", ".", "get_current_network_name", "(", ")", ":", "return", "blake256", "(", "blake256", "(", "msg_bytes", ")", ")", "return", "hashlib", ".", "sha256", "(", "hashlib", ".", "sh...
32.428571
21.285714
def log_to_file(filename, level=DEBUG): """send paramiko logs to a logfile, if they're not already going somewhere""" l = logging.getLogger("paramiko") if len(l.handlers) > 0: return l.setLevel(level) f = open(filename, 'w') lh = logging.StreamHandler(f) lh.setFormatter(logging.Forma...
[ "def", "log_to_file", "(", "filename", ",", "level", "=", "DEBUG", ")", ":", "l", "=", "logging", ".", "getLogger", "(", "\"paramiko\"", ")", "if", "len", "(", "l", ".", "handlers", ")", ">", "0", ":", "return", "l", ".", "setLevel", "(", "level", ...
43.727273
18.545455
def prepare(self): ''' Run the preparation sequence required to start a salt minion. If sub-classed, don't **ever** forget to run: super(YourSubClass, self).prepare() ''' super(Minion, self).prepare() try: if self.config['verify_env']: ...
[ "def", "prepare", "(", "self", ")", ":", "super", "(", "Minion", ",", "self", ")", ".", "prepare", "(", ")", "try", ":", "if", "self", ".", "config", "[", "'verify_env'", "]", ":", "confd", "=", "self", ".", "config", ".", "get", "(", "'default_inc...
40.379747
20.151899
def _extract_subscription_url(url): """Extract the first part of the URL, just after subscription: https://management.azure.com/subscriptions/00000000-0000-0000-0000-000000000000/ """ match = re.match(r".*/subscriptions/[a-f0-9-]+/", url, re.IGNORECASE) if not match: raise ValueError("Unable...
[ "def", "_extract_subscription_url", "(", "url", ")", ":", "match", "=", "re", ".", "match", "(", "r\".*/subscriptions/[a-f0-9-]+/\"", ",", "url", ",", "re", ".", "IGNORECASE", ")", "if", "not", "match", ":", "raise", "ValueError", "(", "\"Unable to extract subsc...
47.125
18.75
def summary(self, featuresCol, weightCol=None): """ Returns an aggregate object that contains the summary of the column with the requested metrics. :param featuresCol: a column that contains features Vector object. :param weightCol: a column that contains weigh...
[ "def", "summary", "(", "self", ",", "featuresCol", ",", "weightCol", "=", "None", ")", ":", "featuresCol", ",", "weightCol", "=", "Summarizer", ".", "_check_param", "(", "featuresCol", ",", "weightCol", ")", "return", "Column", "(", "self", ".", "_java_obj",...
45.266667
24.6
def _get_macd(df): """ Moving Average Convergence Divergence This function will initialize all following columns. MACD Line (macd): (12-day EMA - 26-day EMA) Signal Line (macds): 9-day EMA of MACD Line MACD Histogram (macdh): MACD Line - Signal Line :param df: d...
[ "def", "_get_macd", "(", "df", ")", ":", "fast", "=", "df", "[", "'close_12_ema'", "]", "slow", "=", "df", "[", "'close_26_ema'", "]", "df", "[", "'macd'", "]", "=", "fast", "-", "slow", "df", "[", "'macds'", "]", "=", "df", "[", "'macd_9_ema'", "]...
36.142857
17.095238
def get_user(self, user_id, **params): """https://developers.coinbase.com/api/v2#show-a-user""" response = self._get('v2', 'users', user_id, params=params) return self._make_api_object(response, User)
[ "def", "get_user", "(", "self", ",", "user_id", ",", "*", "*", "params", ")", ":", "response", "=", "self", ".", "_get", "(", "'v2'", ",", "'users'", ",", "user_id", ",", "params", "=", "params", ")", "return", "self", ".", "_make_api_object", "(", "...
55.25
10.25
def call_or_cast(self, method, args={}, nowait=False, **kwargs): """Apply remote `method` asynchronously or synchronously depending on the value of `nowait`. :param method: The name of the remote method to perform. :param args: Dictionary of arguments for the method. :keyword no...
[ "def", "call_or_cast", "(", "self", ",", "method", ",", "args", "=", "{", "}", ",", "nowait", "=", "False", ",", "*", "*", "kwargs", ")", ":", "return", "(", "nowait", "and", "self", ".", "cast", "or", "self", ".", "call", ")", "(", "method", ","...
54.538462
21.423077
async def _request( self, method: str, url: str, *, headers: dict = None, params: dict = None, json: dict = None) -> dict: """Make a request against the RainMachine device.""" if not headers: headers = {} ...
[ "async", "def", "_request", "(", "self", ",", "method", ":", "str", ",", "url", ":", "str", ",", "*", ",", "headers", ":", "dict", "=", "None", ",", "params", ":", "dict", "=", "None", ",", "json", ":", "dict", "=", "None", ")", "->", "dict", "...
35.5
17.409091
def get_payload(request): """ Extracts the request's payload information. This method will merge the URL parameter information and the JSON body of the request together to generate a dictionary of key<->value pairings. This method assumes that the JSON body being provided is also a key-valu...
[ "def", "get_payload", "(", "request", ")", ":", "# always extract values from the URL", "payload", "=", "dict", "(", "request", ".", "params", ".", "mixed", "(", ")", ")", "# provide override capability from the JSON body", "try", ":", "json_data", "=", "request", "...
27.647059
19.294118
def compact(self, include=None): """ Return compact views - See: Zendesk API `Reference <https://developer.zendesk.com/rest_api/docs/core/views#list-views---compact>`__ """ return self._get(self._build_url(self.endpoint.compact(include=include)))
[ "def", "compact", "(", "self", ",", "include", "=", "None", ")", ":", "return", "self", ".", "_get", "(", "self", ".", "_build_url", "(", "self", ".", "endpoint", ".", "compact", "(", "include", "=", "include", ")", ")", ")" ]
46.833333
19.166667
def EI(inc): """ Given a mean inclination value of a distribution of directions, this function calculates the expected elongation of this distribution using a best-fit polynomial of the TK03 GAD secular variation model (Tauxe and Kent, 2004). Parameters ---------- inc : inclination in d...
[ "def", "EI", "(", "inc", ")", ":", "poly_tk03", "=", "[", "3.15976125e-06", ",", "-", "3.52459817e-04", ",", "-", "1.46641090e-02", ",", "2.89538539e+00", "]", "return", "poly_tk03", "[", "0", "]", "*", "inc", "**", "3", "+", "poly_tk03", "[", "1", "]"...
27.24
24.84
def _filenames_from_arg(filename): """Utility function to deal with polymorphic filenames argument.""" if isinstance(filename, string_types): filenames = [filename] elif isinstance(filename, (list, tuple)): filenames = filename else: raise Exception('filename argument must be str...
[ "def", "_filenames_from_arg", "(", "filename", ")", ":", "if", "isinstance", "(", "filename", ",", "string_types", ")", ":", "filenames", "=", "[", "filename", "]", "elif", "isinstance", "(", "filename", ",", "(", "list", ",", "tuple", ")", ")", ":", "fi...
39.357143
12.428571
def _get_type(cls, ptr): """Get the subtype class for a pointer""" # fall back to the base class if unknown return cls.__types.get(lib.g_base_info_get_type(ptr), cls)
[ "def", "_get_type", "(", "cls", ",", "ptr", ")", ":", "# fall back to the base class if unknown", "return", "cls", ".", "__types", ".", "get", "(", "lib", ".", "g_base_info_get_type", "(", "ptr", ")", ",", "cls", ")" ]
37.4
18
def check_perms(obj_name, obj_type='file', ret=None, owner=None, grant_perms=None, deny_perms=None, inheritance=True, reset=False): ''' Check owner and permissions for the passed directory. This funct...
[ "def", "check_perms", "(", "obj_name", ",", "obj_type", "=", "'file'", ",", "ret", "=", "None", ",", "owner", "=", "None", ",", "grant_perms", "=", "None", ",", "deny_perms", "=", "None", ",", "inheritance", "=", "True", ",", "reset", "=", "False", ")"...
40.009132
19.296804
def template_heron_tools_hcl(cl_args, masters, zookeepers): ''' template heron tools ''' heron_tools_hcl_template = "%s/standalone/templates/heron_tools.template.hcl" \ % cl_args["config_path"] heron_tools_hcl_actual = "%s/standalone/resources/heron_tools.hcl" \ ...
[ "def", "template_heron_tools_hcl", "(", "cl_args", ",", "masters", ",", "zookeepers", ")", ":", "heron_tools_hcl_template", "=", "\"%s/standalone/templates/heron_tools.template.hcl\"", "%", "cl_args", "[", "\"config_path\"", "]", "heron_tools_hcl_actual", "=", "\"%s/standalon...
50.666667
31.222222
def auto_index(mcs): """Builds all indices, listed in model's Meta class. >>> class SomeModel(Model) ... class Meta: ... indices = ( ... Index('foo'), ... ) .. note:: this will result in calls to :...
[ "def", "auto_index", "(", "mcs", ")", ":", "for", "index", "in", "mcs", ".", "_meta", ".", "indices", ":", "index", ".", "ensure", "(", "mcs", ".", "collection", ")" ]
33.875
13.4375
def get_parent_book_nodes(self): """Gets the parents of this book. return: (osid.commenting.BookNodeList) - the parents of this book *compliance: mandatory -- This method must be implemented.* """ parent_book_nodes = [] for node in self._my_map['parentNo...
[ "def", "get_parent_book_nodes", "(", "self", ")", ":", "parent_book_nodes", "=", "[", "]", "for", "node", "in", "self", ".", "_my_map", "[", "'parentNodes'", "]", ":", "parent_book_nodes", ".", "append", "(", "BookNode", "(", "node", ".", "_my_map", ",", "...
35.1875
14.0625
def references_by_element(self, element_href): """ Return all references to element specified. :param str element_href: element reference :return: list of references where element is used :rtype: list(dict) """ result = self.make_request( method='crea...
[ "def", "references_by_element", "(", "self", ",", "element_href", ")", ":", "result", "=", "self", ".", "make_request", "(", "method", "=", "'create'", ",", "resource", "=", "'references_by_element'", ",", "json", "=", "{", "'value'", ":", "element_href", "}",...
31.285714
11.571429
def __potential_connection_failure(self, e): """ OperationalError's are emitted by the _mysql library for almost every error code emitted by MySQL. Because of this we verify that the error is actually a connection error before terminating the connection and firing off a PoolConnectionEx...
[ "def", "__potential_connection_failure", "(", "self", ",", "e", ")", ":", "try", ":", "self", ".", "_conn", ".", "query", "(", "'SELECT 1'", ")", "except", "(", "IOError", ",", "_mysql", ".", "OperationalError", ")", ":", "# ok, it's actually an issue.", "self...
45.214286
13.142857
def basic_addresses_write(self, cycles, last_op_address, address, word): """ 0113 0019 TXTTAB RMB 2 *PV BEGINNING OF BASIC PROGRAM 0114 001B VARTAB RMB 2 *PV START OF VARIABLES 0115 001D ARYTAB RMB 2 *PV START OF ARRAYS 0116 001F ARYEND RMB 2 *PV END OF ARRAYS (+1) 0117 0...
[ "def", "basic_addresses_write", "(", "self", ",", "cycles", ",", "last_op_address", ",", "address", ",", "word", ")", ":", "log", ".", "critical", "(", "\"%04x| write $%04x to $%04x\"", ",", "last_op_address", ",", "word", ",", "address", ")", "return", "word" ]
50.384615
18.076923
def serveInBackground(port, serverName, prefix='/status/'): """Convenience function: spawn a background server thread that will serve HTTP requests to get the status. Returns the thread.""" import flask, threading from wsgiref.simple_server import make_server app = flask.Flask(__name__) registerStatsHandler...
[ "def", "serveInBackground", "(", "port", ",", "serverName", ",", "prefix", "=", "'/status/'", ")", ":", "import", "flask", ",", "threading", "from", "wsgiref", ".", "simple_server", "import", "make_server", "app", "=", "flask", ".", "Flask", "(", "__name__", ...
42.545455
14.727273
def put_file(self, in_path, out_path): ''' transfer a file from local to remote ''' vvv("PUT %s TO %s" % (in_path, out_path), host=self.host) if not os.path.exists(in_path): raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path) cmd = self._password_c...
[ "def", "put_file", "(", "self", ",", "in_path", ",", "out_path", ")", ":", "vvv", "(", "\"PUT %s TO %s\"", "%", "(", "in_path", ",", "out_path", ")", ",", "host", "=", "self", ".", "host", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "i...
43.136364
21.409091
def perform(self, event): """ Perform the action. """ wizard = NewDotGraphWizard(parent=self.window.control, window=self.window, title="New Graph") # Open the wizard if wizard.open() == OK: wizard.finished = True
[ "def", "perform", "(", "self", ",", "event", ")", ":", "wizard", "=", "NewDotGraphWizard", "(", "parent", "=", "self", ".", "window", ".", "control", ",", "window", "=", "self", ".", "window", ",", "title", "=", "\"New Graph\"", ")", "# Open the wizard", ...
29.888889
13
def git_clean(ctx): """ Delete all files untracked by git. :param ctx: Context object. :return: None. """ # Get command parts cmd_part_s = [ # Program path 'git', # Clean untracked files 'clean', # Remove all untracked files '-x', ...
[ "def", "git_clean", "(", "ctx", ")", ":", "# Get command parts", "cmd_part_s", "=", "[", "# Program path", "'git'", ",", "# Clean untracked files", "'clean'", ",", "# Remove all untracked files", "'-x'", ",", "# Remove untracked directories too", "'-d'", ",", "# Force to ...
19.395349
22.604651
def lazy_val(func, with_del_hook=False): '''A memoize decorator for class properties. Return a cached property that is calculated by function `func` on first access. ''' def hook_for(that): try: orig_del = that.__del__ except AttributeError: orig_del = None ...
[ "def", "lazy_val", "(", "func", ",", "with_del_hook", "=", "False", ")", ":", "def", "hook_for", "(", "that", ")", ":", "try", ":", "orig_del", "=", "that", ".", "__del__", "except", "AttributeError", ":", "orig_del", "=", "None", "def", "del_hook", "(",...
30.113208
17.811321
def subclass(cls, *bases, **kwargs): """ Add bases to class (late subclassing) Annoyingly we cannot yet modify __bases__ of an existing class, instead we must create another subclass, see here; http://bugs.python.org/issue672115 >>> class A(object): pass >>> class B(object): pass >>> c...
[ "def", "subclass", "(", "cls", ",", "*", "bases", ",", "*", "*", "kwargs", ")", ":", "last", "=", "kwargs", ".", "get", "(", "'last'", ",", "False", ")", "bases", "=", "tuple", "(", "bases", ")", "for", "base", "in", "bases", ":", "assert", "insp...
28.038462
16.423077
def call_lights(*args, **kwargs): ''' Get info about all available lamps. Options: * **id**: Specifies a device ID. Can be a comma-separated values. All, if omitted. CLI Example: .. code-block:: bash salt '*' hue.lights salt '*' hue.lights id=1 salt '*' hue.lights id...
[ "def", "call_lights", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "res", "=", "dict", "(", ")", "lights", "=", "_get_lights", "(", ")", "for", "dev_id", "in", "'id'", "in", "kwargs", "and", "_get_devices", "(", "kwargs", ")", "or", "sorted",...
24.652174
24.826087
def find_log_files(self, sp_key, filecontents=True, filehandles=False): """ Return matches log files of interest. :param sp_key: Search pattern key specified in config :param filehandles: Set to true to return a file handle instead of slurped file contents :return: Yields a dict ...
[ "def", "find_log_files", "(", "self", ",", "sp_key", ",", "filecontents", "=", "True", ",", "filehandles", "=", "False", ")", ":", "# Pick up path filters if specified.", "# Allows modules to be called multiple times with different sets of files", "path_filters", "=", "getatt...
55.153846
27.153846
def get_group_list(user, include_default=True): ''' Returns a list of all of the system group names of which the user is a member. ''' if HAS_GRP is False or HAS_PWD is False: return [] group_names = None ugroups = set() if hasattr(os, 'getgrouplist'): # Try os.getgroupli...
[ "def", "get_group_list", "(", "user", ",", "include_default", "=", "True", ")", ":", "if", "HAS_GRP", "is", "False", "or", "HAS_PWD", "is", "False", ":", "return", "[", "]", "group_names", "=", "None", "ugroups", "=", "set", "(", ")", "if", "hasattr", ...
36.561404
20.631579
def project_community(index, start, end): """Compute the metrics for the project community section of the enriched git index. Returns a dictionary containing "author_metrics", "people_top_metrics" and "orgs_top_metrics" as the keys and the related Metrics as the values. :param index: index object ...
[ "def", "project_community", "(", "index", ",", "start", ",", "end", ")", ":", "results", "=", "{", "\"author_metrics\"", ":", "[", "Authors", "(", "index", ",", "start", ",", "end", ")", "]", ",", "\"people_top_metrics\"", ":", "[", "Authors", "(", "inde...
34.05
21.7
def rotate_around(self, axis, theta): """Return the vector rotated around axis through angle theta. Right hand rule applies. """ # Adapted from equations published by Glenn Murray. # http://inside.mines.edu/~gmurray/ArbitraryAxisRotation/ArbitraryAxisRotation.html x, y,...
[ "def", "rotate_around", "(", "self", ",", "axis", ",", "theta", ")", ":", "# Adapted from equations published by Glenn Murray.", "# http://inside.mines.edu/~gmurray/ArbitraryAxisRotation/ArbitraryAxisRotation.html", "x", ",", "y", ",", "z", "=", "self", ".", "x", ",", "se...
40.25
17.75
def get_comments_by_genus_type(self, comment_genus_type): """Gets a ``CommentList`` corresponding to the given comment genus ``Type`` which does not include comments of genus types derived from the specified ``Type``. arg: comment_genus_type (osid.type.Type): a comment genus type ...
[ "def", "get_comments_by_genus_type", "(", "self", ",", "comment_genus_type", ")", ":", "# Implemented from template for", "# osid.resource.ResourceLookupSession.get_resources_by_genus_type", "# NOTE: This implementation currently ignores plenary view", "collection", "=", "JSONClientValidat...
54.73913
21.608696
def header(*msg, level='h1', separator=" ", print_out=print): ''' Print header block in text mode ''' out_string = separator.join(str(x) for x in msg) if level == 'h0': # box_len = 80 if len(msg) < 80 else len(msg) box_len = 80 print_out('+' + '-' * (box_len + 2)) print_o...
[ "def", "header", "(", "*", "msg", ",", "level", "=", "'h1'", ",", "separator", "=", "\" \"", ",", "print_out", "=", "print", ")", ":", "out_string", "=", "separator", ".", "join", "(", "str", "(", "x", ")", "for", "x", "in", "msg", ")", "if", "le...
33.15
12.25
def redo(self): """ Performs the top group on the redo stack, if present. Creates an undo group with the same name. Raises RuntimeError if called while undoing. """ if self._undoing or self._redoing: raise RuntimeError if not self._redo: return ...
[ "def", "redo", "(", "self", ")", ":", "if", "self", ".", "_undoing", "or", "self", ".", "_redoing", ":", "raise", "RuntimeError", "if", "not", "self", ".", "_redo", ":", "return", "group", "=", "self", ".", "_redo", ".", "pop", "(", ")", "self", "....
25.571429
19
def process_files(manager): """ Process a random number of files on a random number of systems across multiple data centers """ # Get a top level progress bar enterprise = manager.counter(total=DATACENTERS, desc='Processing:', unit='datacenters') # Iterate through data centers for dnum in ...
[ "def", "process_files", "(", "manager", ")", ":", "# Get a top level progress bar", "enterprise", "=", "manager", ".", "counter", "(", "total", "=", "DATACENTERS", ",", "desc", "=", "'Processing:'", ",", "unit", "=", "'datacenters'", ")", "# Iterate through data cen...
40.918919
26
def _get_client(self, project_id): """ Provides a client for interacting with the Cloud Spanner API. :param project_id: The ID of the GCP project. :type project_id: str :return: google.cloud.spanner_v1.client.Client :rtype: object """ if not self._client...
[ "def", "_get_client", "(", "self", ",", "project_id", ")", ":", "if", "not", "self", ".", "_client", ":", "self", ".", "_client", "=", "Client", "(", "project", "=", "project_id", ",", "credentials", "=", "self", ".", "_get_credentials", "(", ")", ")", ...
35.75
17.25
def delete(self, uri, default_response=None): """ Call DELETE on the Gitlab server >>> gitlab = Gitlab(host='http://localhost:10080', verify_ssl=False) >>> gitlab.login(user='root', password='5iveL!fe') >>> gitlab.delete('/users/5') :param uri: String with the URI you w...
[ "def", "delete", "(", "self", ",", "uri", ",", "default_response", "=", "None", ")", ":", "url", "=", "self", ".", "api_url", "+", "uri", "response", "=", "requests", ".", "delete", "(", "url", ",", "headers", "=", "self", ".", "headers", ",", "verif...
40.315789
17.684211
def list_all_categories(cls, **kwargs): """List Categories Return a list of Categories This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async=True >>> thread = api.list_all_categories(async=True) >>> result = thre...
[ "def", "list_all_categories", "(", "cls", ",", "*", "*", "kwargs", ")", ":", "kwargs", "[", "'_return_http_data_only'", "]", "=", "True", "if", "kwargs", ".", "get", "(", "'async'", ")", ":", "return", "cls", ".", "_list_all_categories_with_http_info", "(", ...
36.73913
14.695652
def do_check(pool,request,models,include_children_for,modelgb): "request is the output of translate_check. models a dict of {(model_name,pkey_tuple):model}.\ ICF is a {model_name:fields_list} for which we want to add nulls in request for missing children. see AMC for how it's used.\ The caller should have gone th...
[ "def", "do_check", "(", "pool", ",", "request", ",", "models", ",", "include_children_for", ",", "modelgb", ")", ":", "add_missing_children", "(", "models", ",", "request", ",", "include_children_for", ",", "modelgb", ")", "return", "{", "k", ":", "fkapply", ...
89.142857
49.142857
def admin_confirm_sign_up(self, username=None): """ Confirms user registration as an admin without using a confirmation code. Works on any user. :param username: User's username :return: """ if not username: username = self.username self.client...
[ "def", "admin_confirm_sign_up", "(", "self", ",", "username", "=", "None", ")", ":", "if", "not", "username", ":", "username", "=", "self", ".", "username", "self", ".", "client", ".", "admin_confirm_sign_up", "(", "UserPoolId", "=", "self", ".", "user_pool_...
31.846154
10.615385
def circos_radius(n_nodes, node_r): """ Automatically computes the origin-to-node centre radius of the Circos plot using the triangle equality sine rule. a / sin(A) = b / sin(B) = c / sin(C) :param n_nodes: the number of nodes in the plot. :type n_nodes: int :param node_r: the radius of ea...
[ "def", "circos_radius", "(", "n_nodes", ",", "node_r", ")", ":", "A", "=", "2", "*", "np", ".", "pi", "/", "n_nodes", "# noqa", "B", "=", "(", "np", ".", "pi", "-", "A", ")", "/", "2", "# noqa", "a", "=", "2", "*", "node_r", "return", "a", "*...
30.117647
12.823529
def names(self): """ Returns a list of queues available, ``None`` if no such queues found. Remember this will only shows queues with at least one item enqueued. """ data = None if not self.connected: raise ConnectionError('Queue is not connected') ...
[ "def", "names", "(", "self", ")", ":", "data", "=", "None", "if", "not", "self", ".", "connected", ":", "raise", "ConnectionError", "(", "'Queue is not connected'", ")", "try", ":", "data", "=", "self", ".", "rdb", ".", "keys", "(", "\"retaskqueue-*\"", ...
31.8125
16.4375
def _init_io(self): """! GPIO initialization. Set GPIO into BCM mode and init other IOs mode """ GPIO.setwarnings(False) GPIO.setmode( GPIO.BCM ) pins = [ self._spi_dc ] for pin in pins: GPIO.setup( pin, GPIO.OUT )
[ "def", "_init_io", "(", "self", ")", ":", "GPIO", ".", "setwarnings", "(", "False", ")", "GPIO", ".", "setmode", "(", "GPIO", ".", "BCM", ")", "pins", "=", "[", "self", ".", "_spi_dc", "]", "for", "pin", "in", "pins", ":", "GPIO", ".", "setup", "...
28.1
9