text
stringlengths
75
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
0.18
def _prepare_for_cross_validation(self, corr, clf): """Prepare data for voxelwise cross validation. If the classifier is sklearn.svm.SVC with precomputed kernel, the kernel matrix of each voxel is computed, otherwise do nothing. Parameters ---------- corr: 3D array in s...
[ "def", "_prepare_for_cross_validation", "(", "self", ",", "corr", ",", "clf", ")", ":", "time1", "=", "time", ".", "time", "(", ")", "(", "num_processed_voxels", ",", "num_epochs", ",", "_", ")", "=", "corr", ".", "shape", "if", "isinstance", "(", "clf",...
44.607843
0.00086
def find(pattern, root=os.curdir): '''Helper around 'locate' ''' hits = '' for F in locate(pattern, root): hits = hits + F + '\n' l = hits.split('\n') if(not len(l[-1])): l.pop() if len(l) == 1 and not len(l[0]): return None else: return l
[ "def", "find", "(", "pattern", ",", "root", "=", "os", ".", "curdir", ")", ":", "hits", "=", "''", "for", "F", "in", "locate", "(", "pattern", ",", "root", ")", ":", "hits", "=", "hits", "+", "F", "+", "'\\n'", "l", "=", "hits", ".", "split", ...
25.545455
0.010309
def delete(self, **kwargs): """Deletes a member from a license pool You need to be careful with this method. When you use it, and it succeeds on the remote BIG-IP, the configuration of the BIG-IP will be reloaded. During this process, you will not be able to access the REST inte...
[ "def", "delete", "(", "self", ",", "*", "*", "kwargs", ")", ":", "if", "'id'", "not", "in", "kwargs", ":", "# BIG-IQ requires that you provide the ID of the members to revoke", "# a license from. This ID is already part of the deletion URL though.", "# Therefore, if you do not pr...
44.039216
0.002178
def read_modis_response(filename, scale=1.0): """Read the Terra/Aqua MODIS relative spectral responses. Be aware that MODIS has several detectors (more than one) compared to e.g. AVHRR which has always only one. """ with open(filename, "r") as fid: lines = fid.readlines() nodata = -99.0...
[ "def", "read_modis_response", "(", "filename", ",", "scale", "=", "1.0", ")", ":", "with", "open", "(", "filename", ",", "\"r\"", ")", "as", "fid", ":", "lines", "=", "fid", ".", "readlines", "(", ")", "nodata", "=", "-", "99.0", "# The IR channels seem ...
39.967742
0.001576
def handle_transform(self, task): """Handle a 'transform' callback.""" self.transformed += 1 file = task.result() if file: self.next.append_file(file) self.flush_if_ended()
[ "def", "handle_transform", "(", "self", ",", "task", ")", ":", "self", ".", "transformed", "+=", "1", "file", "=", "task", ".", "result", "(", ")", "if", "file", ":", "self", ".", "next", ".", "append_file", "(", "file", ")", "self", ".", "flush_if_e...
19.888889
0.042781
def add(self, game_object: Hashable, tags: Iterable=())-> None: """ Add a game_object to the scene. game_object: Any GameObject object. The item to be added. tags: An iterable of Hashable objects. Values that can be used to retrieve a group containing the game_object. ...
[ "def", "add", "(", "self", ",", "game_object", ":", "Hashable", ",", "tags", ":", "Iterable", "=", "(", ")", ")", "->", "None", ":", "self", ".", "game_objects", ".", "add", "(", "game_object", ",", "tags", ")" ]
34.285714
0.010142
def correspondence(self): """namedtuple representing the author to whom correspondence should be addressed, in the form (surname, initials, organization, country, city_group). """ fields = 'surname initials organization country city_group' auth = namedtuple('Correspondenc...
[ "def", "correspondence", "(", "self", ")", ":", "fields", "=", "'surname initials organization country city_group'", "auth", "=", "namedtuple", "(", "'Correspondence'", ",", "fields", ")", "corr", "=", "self", ".", "_head", ".", "get", "(", "'correspondence'", ")"...
42
0.00194
def setViewWidget(self, viewWidget): """ Sets the view widget linked with this toolbar. :param viewWidget | <XViewWidget> """ self._viewWidget = viewWidget if viewWidget: viewWidget.resetFinished.connect(self.clearActive)
[ "def", "setViewWidget", "(", "self", ",", "viewWidget", ")", ":", "self", ".", "_viewWidget", "=", "viewWidget", "if", "viewWidget", ":", "viewWidget", ".", "resetFinished", ".", "connect", "(", "self", ".", "clearActive", ")" ]
32.777778
0.009901
def execute(self, method, args, kwargs): """ Execute the given method and stores its result. The result is considered "done" even if the method raises an exception :param method: The method to execute :param args: Method positional arguments :param kwargs: Method keyword...
[ "def", "execute", "(", "self", ",", "method", ",", "args", ",", "kwargs", ")", ":", "# Normalize arguments", "if", "args", "is", "None", ":", "args", "=", "[", "]", "if", "kwargs", "is", "None", ":", "kwargs", "=", "{", "}", "try", ":", "# Call the m...
27.821429
0.002481
def qt_at_least(needed_version, test_version=None): """Check if the installed Qt version is greater than the requested :param needed_version: minimally needed Qt version in format like 4.8.4 :type needed_version: str :param test_version: Qt version as returned from Qt.QT_VERSION. As in 0x040100 T...
[ "def", "qt_at_least", "(", "needed_version", ",", "test_version", "=", "None", ")", ":", "major", ",", "minor", ",", "patch", "=", "needed_version", ".", "split", "(", "'.'", ")", "needed_version", "=", "'0x0%s0%s0%s'", "%", "(", "major", ",", "minor", ","...
32.68
0.001189
def yellow(cls): "Make the text foreground color yellow." wAttributes = cls._get_text_attributes() wAttributes &= ~win32.FOREGROUND_MASK wAttributes |= win32.FOREGROUND_YELLOW cls._set_text_attributes(wAttributes)
[ "def", "yellow", "(", "cls", ")", ":", "wAttributes", "=", "cls", ".", "_get_text_attributes", "(", ")", "wAttributes", "&=", "~", "win32", ".", "FOREGROUND_MASK", "wAttributes", "|=", "win32", ".", "FOREGROUND_YELLOW", "cls", ".", "_set_text_attributes", "(", ...
41.5
0.011811
def EnumerateInterfacesFromClient(args): """Enumerate all MAC addresses.""" del args # Unused libc = ctypes.cdll.LoadLibrary(ctypes.util.find_library("c")) ifa = Ifaddrs() p_ifa = ctypes.pointer(ifa) libc.getifaddrs(ctypes.pointer(p_ifa)) for iface in ParseIfaddrs(p_ifa): yield iface libc.freeif...
[ "def", "EnumerateInterfacesFromClient", "(", "args", ")", ":", "del", "args", "# Unused", "libc", "=", "ctypes", ".", "cdll", ".", "LoadLibrary", "(", "ctypes", ".", "util", ".", "find_library", "(", "\"c\"", ")", ")", "ifa", "=", "Ifaddrs", "(", ")", "p...
24.615385
0.027108
def is_continuous(self): """Boolean denoting whether the data collection is continuous.""" a_per = self.header.analysis_period if self._validated_a_period is True and a_per.st_hour == 0 and a_per.end_hour \ == 23 and len(self.values) == len(a_per.months_per_hour): ret...
[ "def", "is_continuous", "(", "self", ")", ":", "a_per", "=", "self", ".", "header", ".", "analysis_period", "if", "self", ".", "_validated_a_period", "is", "True", "and", "a_per", ".", "st_hour", "==", "0", "and", "a_per", ".", "end_hour", "==", "23", "a...
45
0.008174
def how_similar_dicts(dict1, dict2): """Calculates similarity :param dict1: Dictionary :param dict2: Dictionary :return: measure of how much similar values of dictionaries are """ values = [] for k in dict1: # iterate keys if k in dict2 and dict1[k] and dict2[k]: values...
[ "def", "how_similar_dicts", "(", "dict1", ",", "dict2", ")", ":", "values", "=", "[", "]", "for", "k", "in", "dict1", ":", "# iterate keys", "if", "k", "in", "dict2", "and", "dict1", "[", "k", "]", "and", "dict2", "[", "k", "]", ":", "values", ".",...
29.857143
0.00232
def init_from_storage_write_to_datastore(self): """Init list of sumibssions from Storage and saves them to Datastore. Should be called only once (typically by master) during evaluation of the competition. """ # Load submissions self._attacks = self._load_submissions_from_datastore_dir( ...
[ "def", "init_from_storage_write_to_datastore", "(", "self", ")", ":", "# Load submissions", "self", ".", "_attacks", "=", "self", ".", "_load_submissions_from_datastore_dir", "(", "ATTACK_SUBDIR", ",", "ATTACK_ID_PATTERN", ")", "self", ".", "_targeted_attacks", "=", "se...
43.642857
0.001603
def i2s_frameid(x): """ Get representation name of a pnio frame ID :param x: a key of the PNIO_FRAME_IDS dictionary :returns: str """ try: return PNIO_FRAME_IDS[x] except KeyError: pass if 0x0100 <= x < 0x1000: return "RT_CLASS_3 (%4x)" % x if 0x8000 <= x < 0xC00...
[ "def", "i2s_frameid", "(", "x", ")", ":", "try", ":", "return", "PNIO_FRAME_IDS", "[", "x", "]", "except", "KeyError", ":", "pass", "if", "0x0100", "<=", "x", "<", "0x1000", ":", "return", "\"RT_CLASS_3 (%4x)\"", "%", "x", "if", "0x8000", "<=", "x", "<...
26.368421
0.001927
def put_user_policy(self, user_name, policy_name, policy_json): """ Adds or updates the specified policy document for the specified user. :type user_name: string :param user_name: The name of the user the policy is associated with. :type policy_name: string :param polic...
[ "def", "put_user_policy", "(", "self", ",", "user_name", ",", "policy_name", ",", "policy_json", ")", ":", "params", "=", "{", "'UserName'", ":", "user_name", ",", "'PolicyName'", ":", "policy_name", ",", "'PolicyDocument'", ":", "policy_json", "}", "return", ...
36.222222
0.008969
def wait_socks(sock_events, inmask=1, outmask=2, timeout=None): """wait on a combination of zeromq sockets, normal sockets, and fds .. note:: this method can block it will return once there is relevant activity on any of the descriptors or sockets, or the timeout expires :param sock_event...
[ "def", "wait_socks", "(", "sock_events", ",", "inmask", "=", "1", ",", "outmask", "=", "2", ",", "timeout", "=", "None", ")", ":", "results", "=", "[", "]", "for", "sock", ",", "mask", "in", "sock_events", ":", "if", "isinstance", "(", "sock", ",", ...
32.544118
0.000439
async def check_permission(request, permission, context=None): """Checker that passes only to authoraised users with given permission. If user is not authorized - raises HTTPUnauthorized, if user is authorized and does not have permission - raises HTTPForbidden. """ await check_authorized(requ...
[ "async", "def", "check_permission", "(", "request", ",", "permission", ",", "context", "=", "None", ")", ":", "await", "check_authorized", "(", "request", ")", "allowed", "=", "await", "permits", "(", "request", ",", "permission", ",", "context", ")", "if", ...
35.416667
0.002294
def from_file(self, fname): """read in a file and compute digest""" f = open(fname, "rb") data = f.read() self.update(data) f.close()
[ "def", "from_file", "(", "self", ",", "fname", ")", ":", "f", "=", "open", "(", "fname", ",", "\"rb\"", ")", "data", "=", "f", ".", "read", "(", ")", "self", ".", "update", "(", "data", ")", "f", ".", "close", "(", ")" ]
28
0.011561
def which(cmd, mode=os.F_OK | os.X_OK, path=None): """ Given cmd, check where it is on PATH. Loosely based on the version in python 3.3. """ if os.path.dirname(cmd): if os.path.isfile(cmd) and os.access(cmd, mode): return cmd if path is None: path = os.environ.get(...
[ "def", "which", "(", "cmd", ",", "mode", "=", "os", ".", "F_OK", "|", "os", ".", "X_OK", ",", "path", "=", "None", ")", ":", "if", "os", ".", "path", ".", "dirname", "(", "cmd", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "cmd", ...
24.086957
0.000867
def _read_object(self, path): '''read in object from file at `path`''' if not os.path.exists(path): return None if os.path.isdir(path): raise RuntimeError('%s is a directory, not a file.' % path) with open(path) as f: file_contents = f.read() return file_contents
[ "def", "_read_object", "(", "self", ",", "path", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "None", "if", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "raise", "RuntimeError", "(", "'%s is a...
24.416667
0.013158
def layer_mapproxy(request, catalog_slug, layer_uuid, path_info): """ Get Layer with matching catalog and uuid """ layer = get_object_or_404(Layer, uuid=layer_uuid, catalog__slug=catalog_slug) # for WorldMap layers we need to use the url o...
[ "def", "layer_mapproxy", "(", "request", ",", "catalog_slug", ",", "layer_uuid", ",", "path_info", ")", ":", "layer", "=", "get_object_or_404", "(", "Layer", ",", "uuid", "=", "layer_uuid", ",", "catalog__slug", "=", "catalog_slug", ")", "# for WorldMap layers we ...
34.04878
0.001393
def get_bins_by_query(self, bin_query): """Gets a list of ``Bins`` matching the given bin query. arg: bin_query (osid.resource.BinQuery): the bin query return: (osid.resource.BinList) - the returned ``BinList`` raise: NullArgument - ``bin_query`` is ``null`` raise: Operatio...
[ "def", "get_bins_by_query", "(", "self", ",", "bin_query", ")", ":", "# Implemented from template for", "# osid.resource.BinQuerySession.get_bins_by_query_template", "if", "self", ".", "_catalog_session", "is", "not", "None", ":", "return", "self", ".", "_catalog_session", ...
49.043478
0.001739
def DeviceReadThread(hid_device): """Binds a device to the thread's run loop, then starts the run loop. Args: hid_device: The MacOsHidDevice object The HID manager requires a run loop to handle Report reads. This thread function serves that purpose. """ # Schedule device events with run loop hid_de...
[ "def", "DeviceReadThread", "(", "hid_device", ")", ":", "# Schedule device events with run loop", "hid_device", ".", "run_loop_ref", "=", "cf", ".", "CFRunLoopGetCurrent", "(", ")", "if", "not", "hid_device", ".", "run_loop_ref", ":", "logger", ".", "error", "(", ...
37.540541
0.009123
def cling_wrap(package_name, dir_name, **kw): """Return a Cling that serves from the given package and dir_name. This uses pkg_resources.resource_filename which is not the recommended way, since it extracts the files. I think this works fine unless you have some _very_ serious requirements for sta...
[ "def", "cling_wrap", "(", "package_name", ",", "dir_name", ",", "*", "*", "kw", ")", ":", "resource", "=", "Requirement", ".", "parse", "(", "package_name", ")", "return", "Cling", "(", "resource_filename", "(", "resource", ",", "dir_name", ")", ",", "*", ...
43.75
0.001866
def _check_tcpdump(): """ Return True if the tcpdump command can be started """ with open(os.devnull, 'wb') as devnull: try: proc = subprocess.Popen([conf.prog.tcpdump, "--version"], stdout=devnull, stderr=subprocess.STDOUT) except OSError:...
[ "def", "_check_tcpdump", "(", ")", ":", "with", "open", "(", "os", ".", "devnull", ",", "'wb'", ")", "as", "devnull", ":", "try", ":", "proc", "=", "subprocess", ".", "Popen", "(", "[", "conf", ".", "prog", ".", "tcpdump", ",", "\"--version\"", "]", ...
29.75
0.002037
def _short_color_list(self): """Color list is too long. Discard variations with numbers.""" return [c for c in colors.get_colors() if not re.search(r'\d', c)]
[ "def", "_short_color_list", "(", "self", ")", ":", "return", "[", "c", "for", "c", "in", "colors", ".", "get_colors", "(", ")", "if", "not", "re", ".", "search", "(", "r'\\d'", ",", "c", ")", "]" ]
57.333333
0.011494
def export_defaults(self, buckets=None, group_by='path', prefix='flask', app=None, **kwargs): """ Export the default metrics: - HTTP request latencies - Number of HTTP requests :param buckets: the time buckets for request latencies (wi...
[ "def", "export_defaults", "(", "self", ",", "buckets", "=", "None", ",", "group_by", "=", "'path'", ",", "prefix", "=", "'flask'", ",", "app", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "app", "is", "None", ":", "app", "=", "self", ".", ...
31.27
0.00124
def to_email_attachment(self, filename, filedata, **kw): """Create a new MIME Attachment The Content-Type: header is build from the maintype and subtype of the guessed filename mimetype. Additional parameters for this header are taken from the keyword arguments. """ main...
[ "def", "to_email_attachment", "(", "self", ",", "filename", ",", "filedata", ",", "*", "*", "kw", ")", ":", "maintype", "=", "\"application\"", "subtype", "=", "\"octet-stream\"", "mime_type", "=", "mimetypes", ".", "guess_type", "(", "filename", ")", "[", "...
39.15
0.002494
def run_step(*args, prompt=None): """ Prints out the command and asks if it should be run. If yes (default), runs it. :param args: list of strings (command and args) """ global DRY_RUN cmd = args print(' '.join(cmd)) if skip_step(): print('--- Skipping...') elif DRY_RUN:...
[ "def", "run_step", "(", "*", "args", ",", "prompt", "=", "None", ")", ":", "global", "DRY_RUN", "cmd", "=", "args", "print", "(", "' '", ".", "join", "(", "cmd", ")", ")", "if", "skip_step", "(", ")", ":", "print", "(", "'--- Skipping...'", ")", "e...
24.277778
0.002203
def text(self): """Formatted param definition Equivalent to ``self.template.format(name=self.name, type=self.type)``. """ return self.template.format(name=self.name, type=self.type)
[ "def", "text", "(", "self", ")", ":", "return", "self", ".", "template", ".", "format", "(", "name", "=", "self", ".", "name", ",", "type", "=", "self", ".", "type", ")" ]
34.833333
0.009346
def stop_dunder_call_accept_old_params(fn): """Decorate cls.__call__ method to accept old "stop" signature.""" @_utils.wraps(fn) def new_fn(self, previous_attempt_number=_unset, delay_since_first_attempt=_unset, retry_state=None): if retry_state is None: ...
[ "def", "stop_dunder_call_accept_old_params", "(", "fn", ")", ":", "@", "_utils", ".", "wraps", "(", "fn", ")", "def", "new_fn", "(", "self", ",", "previous_attempt_number", "=", "_unset", ",", "delay_since_first_attempt", "=", "_unset", ",", "retry_state", "=", ...
46.619048
0.001001
def invalidate_cache(self): """ Invalidate httpBL cache """ if self._use_cache: self._cache_version += 1 self._cache.increment('cached_httpbl_{0}_version'.format(self._api_key))
[ "def", "invalidate_cache", "(", "self", ")", ":", "if", "self", ".", "_use_cache", ":", "self", ".", "_cache_version", "+=", "1", "self", ".", "_cache", ".", "increment", "(", "'cached_httpbl_{0}_version'", ".", "format", "(", "self", ".", "_api_key", ")", ...
28.375
0.012821
def generate_config(output_directory): """ Generate a dcm2nii configuration file that disable the interactive mode. """ if not op.isdir(output_directory): os.makedirs(output_directory) config_file = op.join(output_directory, "config.ini") open_file = open(config_file, "w") open_file...
[ "def", "generate_config", "(", "output_directory", ")", ":", "if", "not", "op", ".", "isdir", "(", "output_directory", ")", ":", "os", ".", "makedirs", "(", "output_directory", ")", "config_file", "=", "op", ".", "join", "(", "output_directory", ",", "\"conf...
32.583333
0.002488
def check_for_territories(query): """ Return a geozone queryset of territories given the `query`. Results are sorted by population and area (biggest first). """ if not query or not current_app.config.get('ACTIVATE_TERRITORIES'): return [] dbqs = db.Q() query = query.lower() is_...
[ "def", "check_for_territories", "(", "query", ")", ":", "if", "not", "query", "or", "not", "current_app", ".", "config", ".", "get", "(", "'ACTIVATE_TERRITORIES'", ")", ":", "return", "[", "]", "dbqs", "=", "db", ".", "Q", "(", ")", "query", "=", "quer...
36.904762
0.000629
def get_service(service_type): '''Get available service endpoints for a given service type from the Opencast ServiceRegistry. ''' endpoint = '/services/available.json?serviceType=' + str(service_type) url = '%s%s' % (config()['server']['url'], endpoint) response = http_request(url).decode('utf-8...
[ "def", "get_service", "(", "service_type", ")", ":", "endpoint", "=", "'/services/available.json?serviceType='", "+", "str", "(", "service_type", ")", "url", "=", "'%s%s'", "%", "(", "config", "(", ")", "[", "'server'", "]", "[", "'url'", "]", ",", "endpoint...
48.571429
0.001443
def diff_sevice_by_changeset(service_name, service, environment, cf_client, repo_root): """ If an ef-cf call fails, the error will be logged, the retcode set to 2, but the function will run to completion and return the list of non-error results. """ global ret_code logger.info('Investigatin...
[ "def", "diff_sevice_by_changeset", "(", "service_name", ",", "service", ",", "environment", ",", "cf_client", ",", "repo_root", ")", ":", "global", "ret_code", "logger", ".", "info", "(", "'Investigating changeset for `%s`:`%s` in environment `%s`'", ",", "service", "["...
37.804878
0.001887
def create_paired_device(self, dev_id, agent_path, capability, cb_notify_device, cb_notify_error): """ Creates a new object path for a remote device. This method will connect to the remote device and retrieve all SDP records and then initiate the pairing. ...
[ "def", "create_paired_device", "(", "self", ",", "dev_id", ",", "agent_path", ",", "capability", ",", "cb_notify_device", ",", "cb_notify_error", ")", ":", "return", "self", ".", "_interface", ".", "CreatePairedDevice", "(", "dev_id", ",", "agent_path", ",", "ca...
49.47619
0.001888
def _get_bundle_signature_errors(self, groups): # type: (List[List[Transaction]]) -> List[Text] """ Validates the signature fragments in the bundle. :return: List of error messages. If empty, signature fragments are valid. """ # Start with the cur...
[ "def", "_get_bundle_signature_errors", "(", "self", ",", "groups", ")", ":", "# type: (List[List[Transaction]]) -> List[Text]", "# Start with the currently-supported hash algo.", "current_pos", "=", "None", "current_errors", "=", "[", "]", "for", "current_pos", ",", "group", ...
38.416667
0.001586
def get_sampletype_data(self): """Returns a list of SampleType data """ for obj in self.get_sampletypes(): info = self.get_base_info(obj) yield info
[ "def", "get_sampletype_data", "(", "self", ")", ":", "for", "obj", "in", "self", ".", "get_sampletypes", "(", ")", ":", "info", "=", "self", ".", "get_base_info", "(", "obj", ")", "yield", "info" ]
31.833333
0.010204
def getLogin(filename, user, passwd): ''' write user/passwd to login file or get them from file. This method is not Py3 safe (byte vs. str) ''' if filename is None: return (user, passwd) isPy2 = sys.version_info[0] == 2 if os.path.exists(filename): print("Using file {} for Lo...
[ "def", "getLogin", "(", "filename", ",", "user", ",", "passwd", ")", ":", "if", "filename", "is", "None", ":", "return", "(", "user", ",", "passwd", ")", "isPy2", "=", "sys", ".", "version_info", "[", "0", "]", "==", "2", "if", "os", ".", "path", ...
39.09375
0.00078
def modify_fw_device(self, tenant_id, fw_id, data): """Modifies the firewall cfg. """ drvr_dict, mgmt_ip = self.sched_obj.get_fw_dev_map(fw_id) return drvr_dict.get('drvr_obj').modify_fw(tenant_id, data)
[ "def", "modify_fw_device", "(", "self", ",", "tenant_id", ",", "fw_id", ",", "data", ")", ":", "drvr_dict", ",", "mgmt_ip", "=", "self", ".", "sched_obj", ".", "get_fw_dev_map", "(", "fw_id", ")", "return", "drvr_dict", ".", "get", "(", "'drvr_obj'", ")", ...
56
0.008811
def main(args=sys.argv): """ Main command-line invocation. """ try: opts, args = getopt.gnu_getopt(args[1:], 'p:o:jdt', [ 'jspath=', 'output=', 'private', 'json', 'dependencies', 'test', 'help']) opts = dict(opts) except getopt.GetoptError: usage() ...
[ "def", "main", "(", "args", "=", "sys", ".", "argv", ")", ":", "try", ":", "opts", ",", "args", "=", "getopt", ".", "gnu_getopt", "(", "args", "[", "1", ":", "]", ",", "'p:o:jdt'", ",", "[", "'jspath='", ",", "'output='", ",", "'private'", ",", "...
30.277778
0.001778
def tocimxmlstr(value, indent=None): """ Return the CIM-XML representation of the CIM object or CIM data type, as a :term:`unicode string`. *New in pywbem 0.9.* The returned CIM-XML representation is consistent with :term:`DSP0201`. Parameters: value (:term:`CIM object` or :term:`CIM d...
[ "def", "tocimxmlstr", "(", "value", ",", "indent", "=", "None", ")", ":", "if", "isinstance", "(", "value", ",", "Element", ")", ":", "xml_elem", "=", "value", "else", ":", "xml_elem", "=", "tocimxml", "(", "value", ")", "if", "indent", "is", "None", ...
35.666667
0.001137
def _build_resource_from_properties(obj, filter_fields): """Build a resource based on a ``_properties`` dictionary, filtered by ``filter_fields``, which follow the name of the Python object. """ partial = {} for filter_field in filter_fields: api_field = obj._PROPERTY_TO_API_FIELD.get(filter...
[ "def", "_build_resource_from_properties", "(", "obj", ",", "filter_fields", ")", ":", "partial", "=", "{", "}", "for", "filter_field", "in", "filter_fields", ":", "api_field", "=", "obj", ".", "_PROPERTY_TO_API_FIELD", ".", "get", "(", "filter_field", ")", "if",...
46.117647
0.00125
def HslToRgb(h, s, l): '''Convert the color from HSL coordinates to RGB. Parameters: :h: The Hue component value [0...1] :s: The Saturation component value [0...1] :l: The Lightness component value [0...1] Returns: The color as an (r, g, b) tuple in the rang...
[ "def", "HslToRgb", "(", "h", ",", "s", ",", "l", ")", ":", "if", "s", "==", "0", ":", "return", "(", "l", ",", "l", ",", "l", ")", "# achromatic (gray)", "if", "l", "<", "0.5", ":", "n2", "=", "l", "*", "(", "1.0", "+", "s", ")", "else", ...
20.057143
0.009511
def add_authorizers(self, authorizers): """ Add Authorizer definitions to the securityDefinitions part of Swagger. :param list authorizers: List of Authorizer configurations which get translated to securityDefinitions. """ self.security_definitions = self.security_definitions or...
[ "def", "add_authorizers", "(", "self", ",", "authorizers", ")", ":", "self", ".", "security_definitions", "=", "self", ".", "security_definitions", "or", "{", "}", "for", "authorizer_name", ",", "authorizer", "in", "authorizers", ".", "items", "(", ")", ":", ...
46.6
0.008421
def get_repo_and_project(self): """Returns repository and project.""" app = self.app # Get repo repo = app.data.apply('github-repo', app.args.github_repo, app.prompt_repo, on_load=app.github.get_repo, on_save=lambda r: r.id ) asse...
[ "def", "get_repo_and_project", "(", "self", ")", ":", "app", "=", "self", ".", "app", "# Get repo", "repo", "=", "app", ".", "data", ".", "apply", "(", "'github-repo'", ",", "app", ".", "args", ".", "github_repo", ",", "app", ".", "prompt_repo", ",", "...
28.212121
0.011423
def get_t(self): ''' getter Time. ''' if isinstance(self.__t, int) is False: raise TypeError("The type of __t must be int.") return self.__t
[ "def", "get_t", "(", "self", ")", ":", "if", "isinstance", "(", "self", ".", "__t", ",", "int", ")", "is", "False", ":", "raise", "TypeError", "(", "\"The type of __t must be int.\"", ")", "return", "self", ".", "__t" ]
24.125
0.01
def distort(self, x1=0,y1=0, x2=0,y2=0, x3=0,y3=0, x4=0,y4=0): """Distorts the layer. Distorts the layer by translating the four corners of its bounding box to the given coordinates: upper left (x1,y1), upper right(x2,y2), lower right (x3,y3) and lower left (x4,y4)...
[ "def", "distort", "(", "self", ",", "x1", "=", "0", ",", "y1", "=", "0", ",", "x2", "=", "0", ",", "y2", "=", "0", ",", "x3", "=", "0", ",", "y3", "=", "0", ",", "x4", "=", "0", ",", "y4", "=", "0", ")", ":", "w", ",", "h", "=", "se...
36.071429
0.030888
def get_form(self, request, obj=None, **kwargs): """ Pass the current language to the form. """ form_class = super(TranslatableAdmin, self).get_form(request, obj, **kwargs) if self._has_translatable_model(): form_class.language_code = self.get_form_language(request, o...
[ "def", "get_form", "(", "self", ",", "request", ",", "obj", "=", "None", ",", "*", "*", "kwargs", ")", ":", "form_class", "=", "super", "(", "TranslatableAdmin", ",", "self", ")", ".", "get_form", "(", "request", ",", "obj", ",", "*", "*", "kwargs", ...
38
0.008571
def remove_first(self): """Removes first :return: True iff head has been removed """ if self.head is None: return False self.head = self.head.next_node return True
[ "def", "remove_first", "(", "self", ")", ":", "if", "self", ".", "head", "is", "None", ":", "return", "False", "self", ".", "head", "=", "self", ".", "head", ".", "next_node", "return", "True" ]
19.636364
0.00885
def agent_heartbeat(self, agent_id, metrics, run_states): """Notify server about agent state, receive commands. Args: agent_id (str): agent_id metrics (dict): system metrics run_states (dict): run_id: state mapping Returns: List of commands to exe...
[ "def", "agent_heartbeat", "(", "self", ",", "agent_id", ",", "metrics", ",", "run_states", ")", ":", "mutation", "=", "gql", "(", "'''\n mutation Heartbeat(\n $id: ID!,\n $metrics: JSONString,\n $runState: JSONString\n ) {\n a...
32.025
0.001515
def start(self, acceptor=None, wrapper=None): """ Starts the TendrilManager. :param acceptor: If given, specifies a callable that will be called with each newly received Tendril; that callable is responsible for initial ...
[ "def", "start", "(", "self", ",", "acceptor", "=", "None", ",", "wrapper", "=", "None", ")", ":", "# Don't allow a double-start", "if", "self", ".", "running", ":", "raise", "ValueError", "(", "\"TendrilManager already running\"", ")", "# Look out for conflicts", ...
41.795455
0.001063
def combine(*args): """ tool to perform tree search via recursion useful for developing the grid in a grid search Parameters ---------- args : list of lists Returns ------- list of all the combinations of the elements in the input lists """ if hasattr(args, '__iter__') and ...
[ "def", "combine", "(", "*", "args", ")", ":", "if", "hasattr", "(", "args", ",", "'__iter__'", ")", "and", "(", "len", "(", "args", ")", ">", "1", ")", ":", "subtree", "=", "combine", "(", "*", "args", "[", ":", "-", "1", "]", ")", "tree", "=...
26.68
0.001447
def volreg(dset,suffix='_volreg',base=3,tshift=3,dfile_suffix='_volreg.1D'): '''simple interface to 3dvolreg :suffix: suffix to add to ``dset`` for volreg'ed file :base: either a number or ``dset[#]`` of the base image to register to :tshift: if a number, then tshift ...
[ "def", "volreg", "(", "dset", ",", "suffix", "=", "'_volreg'", ",", "base", "=", "3", ",", "tshift", "=", "3", ",", "dfile_suffix", "=", "'_volreg.1D'", ")", ":", "cmd", "=", "[", "'3dvolreg'", ",", "'-prefix'", ",", "nl", ".", "suffix", "(", "dset",...
50
0.026648
def set_param(self, name: str, v) -> None: """Add or update an existing parameter.""" self.params[zlib.crc32(name.encode())] = v
[ "def", "set_param", "(", "self", ",", "name", ":", "str", ",", "v", ")", "->", "None", ":", "self", ".", "params", "[", "zlib", ".", "crc32", "(", "name", ".", "encode", "(", ")", ")", "]", "=", "v" ]
47.333333
0.013889
def update_specifications(force: bool = False): """Update BEL specifications Collect BEL specifications from Github BELBio BEL Specification folder and store in local directory specified in belbio_conf.yaml Process all BEL Specifications in YAML into an enhanced JSON version and capture all BEL ve...
[ "def", "update_specifications", "(", "force", ":", "bool", "=", "False", ")", ":", "spec_dir", "=", "config", "[", "\"bel\"", "]", "[", "\"lang\"", "]", "[", "\"specifications\"", "]", "if", "not", "os", ".", "path", ".", "isdir", "(", "spec_dir", ")", ...
32.877551
0.001808
def find_obj(self, env, modname, classname, name, type_name, searchmode=0): """Find a Chapel object for "name", possibly with module or class/record name. Returns a list of (name, object entry) tuples. :arg int searchmode: If 1, search more specific names first. Otherwise, search bu...
[ "def", "find_obj", "(", "self", ",", "env", ",", "modname", ",", "classname", ",", "name", ",", "type_name", ",", "searchmode", "=", "0", ")", ":", "if", "name", "[", "-", "2", ":", "]", "==", "'()'", ":", "name", "=", "name", "[", ":", "-", "2...
42.637931
0.001186
def detectS60OssBrowser(self): """Return detection of Symbian S60 Browser Detects if the current browser is the Symbian S60 Open Source Browser. """ #First, test for WebKit, then make sure it's either Symbian or S60. return self.detectWebkit() \ and (UAgentInfo.devic...
[ "def", "detectS60OssBrowser", "(", "self", ")", ":", "#First, test for WebKit, then make sure it's either Symbian or S60.", "return", "self", ".", "detectWebkit", "(", ")", "and", "(", "UAgentInfo", ".", "deviceSymbian", "in", "self", ".", "__userAgent", "or", "UAgentIn...
44.555556
0.00978
def make_sources(comp_key, comp_dict): """Make dictionary mapping component keys to a source or set of sources Parameters ---------- comp_key : str Key used to access sources comp_dict : dict Information used to build sources return `OrderedDict` maping comp_key to `fermi...
[ "def", "make_sources", "(", "comp_key", ",", "comp_dict", ")", ":", "srcdict", "=", "OrderedDict", "(", ")", "try", ":", "comp_info", "=", "comp_dict", ".", "info", "except", "AttributeError", ":", "comp_info", "=", "comp_dict", "try", ":", "spectrum", "=", ...
38.54
0.000506
def getsize(store, path=None): """Compute size of stored items for a given path. If `store` provides a `getsize` method, this will be called, otherwise will return -1.""" path = normalize_storage_path(path) if hasattr(store, 'getsize'): # pass through return store.getsize(path) elif ...
[ "def", "getsize", "(", "store", ",", "path", "=", "None", ")", ":", "path", "=", "normalize_storage_path", "(", "path", ")", "if", "hasattr", "(", "store", ",", "'getsize'", ")", ":", "# pass through", "return", "store", ".", "getsize", "(", "path", ")",...
32
0.002092
def _findLocation(self, reference_name, start, end): """ return a location key form the locationMap """ try: # TODO - sequence_annotations does not have build? return self._locationMap['hg19'][reference_name][start][end] except: return None
[ "def", "_findLocation", "(", "self", ",", "reference_name", ",", "start", ",", "end", ")", ":", "try", ":", "# TODO - sequence_annotations does not have build?", "return", "self", ".", "_locationMap", "[", "'hg19'", "]", "[", "reference_name", "]", "[", "start", ...
34.222222
0.009494
def add_styles(self): """Add the css to the svg""" colors = self.graph.style.get_colors(self.id, self.graph._order) strokes = self.get_strokes() all_css = [] auto_css = ['file://base.css'] if self.graph.style._google_fonts: auto_css.append( '/...
[ "def", "add_styles", "(", "self", ")", ":", "colors", "=", "self", ".", "graph", ".", "style", ".", "get_colors", "(", "self", ".", "id", ",", "self", ".", "graph", ".", "_order", ")", "strokes", "=", "self", ".", "get_strokes", "(", ")", "all_css", ...
37.511111
0.001155
def convert_to_binary(variables, domains, constraints): """ Returns new constraint list, all binary, using hidden variables. You can use it as previous step when creating a problem. """ def wdiff(vars_): def diff(variables, values): hidden, other = variables if hidd...
[ "def", "convert_to_binary", "(", "variables", ",", "domains", ",", "constraints", ")", ":", "def", "wdiff", "(", "vars_", ")", ":", "def", "diff", "(", "variables", ",", "values", ")", ":", "hidden", ",", "other", "=", "variables", "if", "hidden", ".", ...
32.694444
0.00165
def mean_moving_time(self, data_frame): """ This method calculates the mean time (ms) that the hand was moving from one target to the next :param data_frame: the data frame :type data_frame: pandas.DataFrame :return mmt: the mean moving time in ms :rt...
[ "def", "mean_moving_time", "(", "self", ",", "data_frame", ")", ":", "diff", "=", "data_frame", ".", "td", "[", "1", ":", "-", "1", "]", ".", "values", "-", "data_frame", ".", "td", "[", "0", ":", "-", "2", "]", ".", "values", "mmt", "=", "np", ...
36.2
0.008977
def q_if(self, *qregs): """Add controls to this gate.""" self.data = [gate.q_if(qregs) for gate in self.data] return self
[ "def", "q_if", "(", "self", ",", "*", "qregs", ")", ":", "self", ".", "data", "=", "[", "gate", ".", "q_if", "(", "qregs", ")", "for", "gate", "in", "self", ".", "data", "]", "return", "self" ]
35.5
0.013793
def requires_git(func: Callable) -> Callable: """ Decorator to ensure `git` is accessible before calling a function. :param func: the function to wrap :return: the wrapped function """ def decorated(*args, **kwargs): try: run([GIT_COMMAND, "--version"]) except RunExce...
[ "def", "requires_git", "(", "func", ":", "Callable", ")", "->", "Callable", ":", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "run", "(", "[", "GIT_COMMAND", ",", "\"--version\"", "]", ")", "except", "RunExceptio...
32.428571
0.002141
def t_preproc_ID(self, t): r'[_a-zA-Z][_a-zA-Z0-9]*' # preprocessor directives t.type = preprocessor.get(t.value.lower(), 'ID') return t
[ "def", "t_preproc_ID", "(", "self", ",", "t", ")", ":", "# preprocessor directives", "t", ".", "type", "=", "preprocessor", ".", "get", "(", "t", ".", "value", ".", "lower", "(", ")", ",", "'ID'", ")", "return", "t" ]
39.5
0.012422
def update(self, **kwargs): """We need to implement the custom exclusive parameter check.""" self._check_exclusive_parameters(**kwargs) return super(Rule, self)._update(**kwargs)
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_check_exclusive_parameters", "(", "*", "*", "kwargs", ")", "return", "super", "(", "Rule", ",", "self", ")", ".", "_update", "(", "*", "*", "kwargs", ")" ]
49.75
0.009901
def http_log_req(method, uri, args, kwargs): """ When pyrax.get_http_debug() is True, outputs the equivalent `curl` command for the API request being made. """ if not pyrax.get_http_debug(): return string_parts = ["curl -i -X %s" % method] for element in args: string_parts.ap...
[ "def", "http_log_req", "(", "method", ",", "uri", ",", "args", ",", "kwargs", ")", ":", "if", "not", "pyrax", ".", "get_http_debug", "(", ")", ":", "return", "string_parts", "=", "[", "\"curl -i -X %s\"", "%", "method", "]", "for", "element", "in", "args...
38.3
0.001274
def fits_region_objects_to_table(regions): """ Converts list of regions to FITS region table. Parameters ---------- regions : list List of `regions.Region` objects Returns ------- region_string : `~astropy.table.Table` FITS region table Examples -------- >...
[ "def", "fits_region_objects_to_table", "(", "regions", ")", ":", "for", "reg", "in", "regions", ":", "if", "isinstance", "(", "reg", ",", "SkyRegion", ")", ":", "raise", "TypeError", "(", "'Every region must be a pixel region'", ".", "format", "(", "reg", ")", ...
27.757576
0.001055
def oauth(login, password, app_id=4729418, scope=2097151): """ OAuth on vk.com. :param login: login on vk.com. :param password: password on vk.com. :param app_id: vk.com application id (default: 4729418). :param scope: allowed actions (default: 2097151 (all)). :returns: OAuth2 access token ...
[ "def", "oauth", "(", "login", ",", "password", ",", "app_id", "=", "4729418", ",", "scope", "=", "2097151", ")", ":", "session", "=", "authentication", "(", "login", ",", "password", ")", "data", "=", "{", "'response_type'", ":", "'token'", ",", "'client...
30.740741
0.002336
def transform_array_decl_to_malloc(decl, with_init=True): """ Transform ast of "type var_name[N]" to "type* var_name = aligned_malloc(sizeof(type)*N, 32)" In-place operation. :param with_init: if False, ommit malloc """ if type(decl.type) is not c_ast.ArrayDecl: # Not an array declarat...
[ "def", "transform_array_decl_to_malloc", "(", "decl", ",", "with_init", "=", "True", ")", ":", "if", "type", "(", "decl", ".", "type", ")", "is", "not", "c_ast", ".", "ArrayDecl", ":", "# Not an array declaration, can be ignored", "return", "type_", "=", "c_ast"...
32.961538
0.002268
def _GetDateValues( self, number_of_days, epoch_year, epoch_month, epoch_day_of_month): """Determines date values. Args: number_of_days (int): number of days since epoch. epoch_year (int): year that is the start of the epoch e.g. 1970. epoch_month (int): month that is the start of the e...
[ "def", "_GetDateValues", "(", "self", ",", "number_of_days", ",", "epoch_year", ",", "epoch_month", ",", "epoch_day_of_month", ")", ":", "if", "epoch_year", "<", "0", ":", "raise", "ValueError", "(", "'Epoch year value: {0:d} out of bounds.'", ".", "format", "(", ...
25.967742
0.011068
def main(): """ Parse command line argument and output appropriate file type (csv or JSON) """ parser = ArgumentParser() parser.add_argument( "-c", "--clinvarfile", dest="clinvarfile", help="ClinVar VCF file (either this or -C must be specified)", metavar="CLINVARFILE") ...
[ "def", "main", "(", ")", ":", "parser", "=", "ArgumentParser", "(", ")", "parser", ".", "add_argument", "(", "\"-c\"", ",", "\"--clinvarfile\"", ",", "dest", "=", "\"clinvarfile\"", ",", "help", "=", "\"ClinVar VCF file (either this or -C must be specified)\"", ",",...
41.371429
0.00045
def info(message, domain): """Log simple info""" if domain in Logger._ignored_domains: return Logger._log(None, message, INFO, domain)
[ "def", "info", "(", "message", ",", "domain", ")", ":", "if", "domain", "in", "Logger", ".", "_ignored_domains", ":", "return", "Logger", ".", "_log", "(", "None", ",", "message", ",", "INFO", ",", "domain", ")" ]
27.666667
0.011696
def maybe_details(resource, opt): """At the first level of verbosity this will print out detailed change information on for the specified Vault resource""" if opt.verbose == 0: return if not resource.present: return obj = None existing = None if isinstance(resource, Resour...
[ "def", "maybe_details", "(", "resource", ",", "opt", ")", ":", "if", "opt", ".", "verbose", "==", "0", ":", "return", "if", "not", "resource", ".", "present", ":", "return", "obj", "=", "None", "existing", "=", "None", "if", "isinstance", "(", "resourc...
32.552632
0.000785
def container_device_delete(name, device_name, remote_addr=None, cert=None, key=None, verify_cert=True): ''' Delete a container device name : Name of the container device_name : The device name to delete remote_addr : An URL to a remote Server, ...
[ "def", "container_device_delete", "(", "name", ",", "device_name", ",", "remote_addr", "=", "None", ",", "cert", "=", "None", ",", "key", "=", "None", ",", "verify_cert", "=", "True", ")", ":", "container", "=", "container_get", "(", "name", ",", "remote_a...
24.488372
0.000913
async def get_launches(self): """Get launch information.""" from .common import CommonFunctions common = CommonFunctions(self.loop, self.session) all_launches = [] launches = {} data = await common.api_call(BASE_URL) if data is None: LOGGER.error('Erro...
[ "async", "def", "get_launches", "(", "self", ")", ":", "from", ".", "common", "import", "CommonFunctions", "common", "=", "CommonFunctions", "(", "self", ".", "loop", ",", "self", ".", "session", ")", "all_launches", "=", "[", "]", "launches", "=", "{", ...
51.520833
0.000794
def getScriptArgumentParser(args=sys.argv): """Return ArgumentParser object Kwargs: args (list): list of arguments that will be parsed. The default is the sys.argv list, and should be correct for most use cases. components (lis...
[ "def", "getScriptArgumentParser", "(", "args", "=", "sys", ".", "argv", ")", ":", "# Description", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "DESCRIPTION", ")", "# source", "parser", ".", "add_argument", "(", "'config_file'", ","...
33.212121
0.015957
def _get_minimal_core_reservations(core_resource, cores, chip=None): """Yield a minimal set of :py:class:`~rig.place_and_route.constraints.ReserveResourceConstraint` objects which reserve the specified set of cores. Parameters ---------- core_resource : resource type The type of resourc...
[ "def", "_get_minimal_core_reservations", "(", "core_resource", ",", "cores", ",", "chip", "=", "None", ")", ":", "reservation", "=", "None", "# Cores is in ascending order", "for", "core", "in", "cores", ":", "if", "reservation", "is", "None", ":", "reservation", ...
33.617647
0.00085
def focus_next(self, count=1): " Focus the next pane. " panes = self.panes if panes: self.active_pane = panes[(panes.index(self.active_pane) + count) % len(panes)] else: self.active_pane = None
[ "def", "focus_next", "(", "self", ",", "count", "=", "1", ")", ":", "panes", "=", "self", ".", "panes", "if", "panes", ":", "self", ".", "active_pane", "=", "panes", "[", "(", "panes", ".", "index", "(", "self", ".", "active_pane", ")", "+", "count...
34.714286
0.012048
def _set_expressions(self, expressions): """Extract expressions and variables from the user provided expressions.""" self.expressions = {} for key, item in expressions.items(): self.expressions[key] = {'function': item}
[ "def", "_set_expressions", "(", "self", ",", "expressions", ")", ":", "self", ".", "expressions", "=", "{", "}", "for", "key", ",", "item", "in", "expressions", ".", "items", "(", ")", ":", "self", ".", "expressions", "[", "key", "]", "=", "{", "'fun...
50.2
0.011765
def _command(self, commands): """! \~english Send command to ssd1306, DC pin need set to LOW @param commands: an byte or array of bytes \~chinese 发送命令给 SSD1306,DC 需要设定为低电平 LOW @param commands: 一个字节或字节数组 """ if self._spi == None: raise "Do not set...
[ "def", "_command", "(", "self", ",", "commands", ")", ":", "if", "self", ".", "_spi", "==", "None", ":", "raise", "\"Do not setting SPI\"", "GPIO", ".", "output", "(", "self", ".", "_spi_dc", ",", "0", ")", "self", ".", "_spi", ".", "writebytes", "(", ...
30.538462
0.026895
def check_backends(title): """Invoke test() for all backends and fail (raise) if some dep is missing. """ path = os.path.dirname(fulltext.backends.__file__) errs = [] for name in os.listdir(path): if not name.endswith('.py'): continue if name == '__init__.py': ...
[ "def", "check_backends", "(", "title", ")", ":", "path", "=", "os", ".", "path", ".", "dirname", "(", "fulltext", ".", "backends", ".", "__file__", ")", "errs", "=", "[", "]", "for", "name", "in", "os", ".", "listdir", "(", "path", ")", ":", "if", ...
30.911765
0.000923
def copy_extras(config): """copy over "extra" files named in config json: stylesheets, logos, ...""" outdir = config['outdir'] for dst, src in config['extras'].items(): dst_path = os.path.join(outdir, dst) dst_dir = os.path.dirname(dst_path) if not os.path.isdir(dst_dir): os.makedirs(dst_dir) ...
[ "def", "copy_extras", "(", "config", ")", ":", "outdir", "=", "config", "[", "'outdir'", "]", "for", "dst", ",", "src", "in", "config", "[", "'extras'", "]", ".", "items", "(", ")", ":", "dst_path", "=", "os", ".", "path", ".", "join", "(", "outdir...
37.777778
0.014368
def query(url, **kwargs): ''' Query a resource, and decode the return data Passes through all the parameters described in the :py:func:`utils.http.query function <salt.utils.http.query>`: .. autofunction:: salt.utils.http.query CLI Example: .. code-block:: bash salt '*' http.que...
[ "def", "query", "(", "url", ",", "*", "*", "kwargs", ")", ":", "opts", "=", "__opts__", ".", "copy", "(", ")", "if", "'opts'", "in", "kwargs", ":", "opts", ".", "update", "(", "kwargs", "[", "'opts'", "]", ")", "del", "kwargs", "[", "'opts'", "]"...
29.5
0.001172
def get_subscribers(self): """ :calls: `GET /repos/:owner/:repo/subscribers <http://developer.github.com/v3/activity/watching>`_ :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.NamedUser.NamedUser` """ return github.PaginatedList.PaginatedList( g...
[ "def", "get_subscribers", "(", "self", ")", ":", "return", "github", ".", "PaginatedList", ".", "PaginatedList", "(", "github", ".", "NamedUser", ".", "NamedUser", ",", "self", ".", "_requester", ",", "self", ".", "url", "+", "\"/subscribers\"", ",", "None",...
39.181818
0.00907
def update_function(self, param_vals): """Updates the opt_obj, returns new error.""" self.opt_obj.update_function(param_vals) return self.opt_obj.get_error()
[ "def", "update_function", "(", "self", ",", "param_vals", ")", ":", "self", ".", "opt_obj", ".", "update_function", "(", "param_vals", ")", "return", "self", ".", "opt_obj", ".", "get_error", "(", ")" ]
44.5
0.01105
def set_hyperparams(self, new_params): """Set the (free) hyperparameters. Parameters ---------- new_params : :py:class:`Array` or other Array-like New values of the free parameters. Raises ------ ValueError If the length o...
[ "def", "set_hyperparams", "(", "self", ",", "new_params", ")", ":", "new_params", "=", "scipy", ".", "asarray", "(", "new_params", ",", "dtype", "=", "float", ")", "if", "len", "(", "new_params", ")", "==", "len", "(", "self", ".", "free_params", ")", ...
37.047619
0.008772
def get_plugin_actions(self): """Return a list of actions related to plugin.""" create_nb_action = create_action(self, _("New notebook"), icon=ima.icon('filenew'), triggered=se...
[ "def", "get_plugin_actions", "(", "self", ")", ":", "create_nb_action", "=", "create_action", "(", "self", ",", "_", "(", "\"New notebook\"", ")", ",", "icon", "=", "ima", ".", "icon", "(", "'filenew'", ")", ",", "triggered", "=", "self", ".", "create_new_...
55.4
0.001183
def check_write_permission(self, user_id, do_raise=True): """ Check whether this user can write this node """ return self.get_resource().check_write_permission(user_id, do_raise=do_raise)
[ "def", "check_write_permission", "(", "self", ",", "user_id", ",", "do_raise", "=", "True", ")", ":", "return", "self", ".", "get_resource", "(", ")", ".", "check_write_permission", "(", "user_id", ",", "do_raise", "=", "do_raise", ")" ]
43.8
0.013453
def as_required_fields(self, fields=[]): """ set required to True """ fields = self.filter_fields(fields) for f in fields: f = self.fields[f.name] f.required = True
[ "def", "as_required_fields", "(", "self", ",", "fields", "=", "[", "]", ")", ":", "fields", "=", "self", ".", "filter_fields", "(", "fields", ")", "for", "f", "in", "fields", ":", "f", "=", "self", ".", "fields", "[", "f", ".", "name", "]", "f", ...
34.5
0.009434
def rand_sub(arr,*args,**kwargs): ''' arr = ['scheme', 'username', 'password', 'hostname', 'port', 'path', 'params', 'query', 'fragment'] rand_sub(arr,3) rand_sub(arr,3) rand_sub(arr,3) rand_sub(arr) rand_sub(arr) rand_sub(arr) ''' arr = copy.deepcopy(...
[ "def", "rand_sub", "(", "arr", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "arr", "=", "copy", ".", "deepcopy", "(", "arr", ")", "lngth", "=", "arr", ".", "__len__", "(", ")", "args", "=", "list", "(", "args", ")", "if", "(", "args", ...
26.5
0.015175
def sectionsPDF(self,walkTrace=tuple(),case=None,element=None,doc=None): """Prepares section for PDF output. """ import pylatex as pl if case == 'sectionmain': if self.settings['clearpage']: doc.append(pl.utils.NoEscape(r'\clearpage')) with doc.create(pl.Section(s...
[ "def", "sectionsPDF", "(", "self", ",", "walkTrace", "=", "tuple", "(", ")", ",", "case", "=", "None", ",", "element", "=", "None", ",", "doc", "=", "None", ")", ":", "import", "pylatex", "as", "pl", "if", "case", "==", "'sectionmain'", ":", "if", ...
50.333333
0.009171
def parseelement(elem): ''' Convert the content of an element into more ElementTree structures. We do this because sometimes we want to set xml as the content of an element. ''' xml = '<%(tag)s>%(content)s</%(tag)s>' % {'tag' : elem.tag, 'content' : elem.text} et = etree.fromstring(xml) repl...
[ "def", "parseelement", "(", "elem", ")", ":", "xml", "=", "'<%(tag)s>%(content)s</%(tag)s>'", "%", "{", "'tag'", ":", "elem", ".", "tag", ",", "'content'", ":", "elem", ".", "text", "}", "et", "=", "etree", ".", "fromstring", "(", "xml", ")", "replaceele...
41.625
0.014706
def highlight(string, fg=None, bg=None, indices=[], end='\n', target=sys.stdout): """Highlight characters using indices and print it to the target handle. fg and bg specify foreground- and background colors, respectively. The remaining keyword arguments are the same as for Python's built-in p...
[ "def", "highlight", "(", "string", ",", "fg", "=", "None", ",", "bg", "=", "None", ",", "indices", "=", "[", "]", ",", "end", "=", "'\\n'", ",", "target", "=", "sys", ".", "stdout", ")", ":", "if", "not", "string", "or", "not", "indices", "or", ...
32.516129
0.000963
def switch_off(self): """Close the valve.""" success = self.set_status(CONST.STATUS_OFF_INT) if success: self._json_state['status'] = CONST.STATUS_CLOSED return success
[ "def", "switch_off", "(", "self", ")", ":", "success", "=", "self", ".", "set_status", "(", "CONST", ".", "STATUS_OFF_INT", ")", "if", "success", ":", "self", ".", "_json_state", "[", "'status'", "]", "=", "CONST", ".", "STATUS_CLOSED", "return", "success"...
25.875
0.009346