text
stringlengths
89
104k
code_tokens
list
avg_line_len
float64
7.91
980
score
float64
0
630
def make_elements(tokens, text, start=0, end=None, fallback=None): """Make elements from a list of parsed tokens. It will turn all unmatched holes into fallback elements. :param tokens: a list of parsed tokens. :param text: the original tet. :param start: the offset of where parsing starts. Default...
[ "def", "make_elements", "(", "tokens", ",", "text", ",", "start", "=", "0", ",", "end", "=", "None", ",", "fallback", "=", "None", ")", ":", "result", "=", "[", "]", "end", "=", "end", "or", "len", "(", "text", ")", "prev_end", "=", "start", "for...
38.409091
15.818182
def create_qcos_client(self, app_uri): """创建资源管理客户端 """ if (self.auth is None): return QcosClient(None) products = self.get_app_region_products(app_uri) auth = self.get_valid_app_auth(app_uri) if products is None or auth is None: return None ...
[ "def", "create_qcos_client", "(", "self", ",", "app_uri", ")", ":", "if", "(", "self", ".", "auth", "is", "None", ")", ":", "return", "QcosClient", "(", "None", ")", "products", "=", "self", ".", "get_app_region_products", "(", "app_uri", ")", "auth", "=...
23.8
18.133333
def decrypt(*args, **kwargs): """ Decrypts legacy or spec-compliant JOSE token. First attempts to decrypt the token in a legacy mode (https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-19). If it is not a valid legacy token then attempts to decrypt it in a spec-compliant way (http://tools.i...
[ "def", "decrypt", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "legacy_decrypt", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "(", "NotYetValid", ",", "Expired", ")", "as", "e", ":", "# these should be raised ...
44.875
15.25
def _apply(self, element, key=None): """ Applies the operation to the element, executing any pre- and post-processor hooks if defined. """ kwargs = {} for hook in self._preprocess_hooks: kwargs.update(hook(self, element)) ret = self._process(element, k...
[ "def", "_apply", "(", "self", ",", "element", ",", "key", "=", "None", ")", ":", "kwargs", "=", "{", "}", "for", "hook", "in", "self", ".", "_preprocess_hooks", ":", "kwargs", ".", "update", "(", "hook", "(", "self", ",", "element", ")", ")", "ret"...
35
7.666667
def reload(self): """ Refreshes the resource with the data from the server. """ try: if hasattr(self, 'href'): data = self._api.get(self.href, append_base=False).json() resource = self.__class__(api=self._api, **data) elif hasattr(s...
[ "def", "reload", "(", "self", ")", ":", "try", ":", "if", "hasattr", "(", "self", ",", "'href'", ")", ":", "data", "=", "self", ".", "_api", ".", "get", "(", "self", ".", "href", ",", "append_base", "=", "False", ")", ".", "json", "(", ")", "re...
39.925926
20.222222
def load_werkzeug(path): """Load werkzeug.""" sys.path[0] = path # get rid of already imported stuff wz.__dict__.clear() for key in sys.modules.keys(): if key.startswith("werkzeug.") or key == "werkzeug": sys.modules.pop(key, None) # import werkzeug again. import werkze...
[ "def", "load_werkzeug", "(", "path", ")", ":", "sys", ".", "path", "[", "0", "]", "=", "path", "# get rid of already imported stuff", "wz", ".", "__dict__", ".", "clear", "(", ")", "for", "key", "in", "sys", ".", "modules", ".", "keys", "(", ")", ":", ...
25.852941
19.147059
def resolve(self, authorization: http.Header): """ Determine the user associated with a request, using HTTP Basic Authentication. """ if authorization is None: return None scheme, token = authorization.split() if scheme.lower() != 'basic': return ...
[ "def", "resolve", "(", "self", ",", "authorization", ":", "http", ".", "Header", ")", ":", "if", "authorization", "is", "None", ":", "return", "None", "scheme", ",", "token", "=", "authorization", ".", "split", "(", ")", "if", "scheme", ".", "lower", "...
31.866667
20.4
def neighbors( adata: AnnData, n_neighbors: int = 15, n_pcs: Optional[int] = None, use_rep: Optional[str] = None, knn: bool = True, random_state: Optional[Union[int, RandomState]] = 0, method: str = 'umap', metric: Union[str, Callable[[np.ndarray, np.ndarray], float]] = 'euclidean', ...
[ "def", "neighbors", "(", "adata", ":", "AnnData", ",", "n_neighbors", ":", "int", "=", "15", ",", "n_pcs", ":", "Optional", "[", "int", "]", "=", "None", ",", "use_rep", ":", "Optional", "[", "str", "]", "=", "None", ",", "knn", ":", "bool", "=", ...
43.824176
23.593407
def minimum_geometries(self, n=None, symmetry_measure_type=None, max_csm=None): """ Returns a list of geometries with increasing continuous symmetry measure in this ChemicalEnvironments object :param n: Number of geometries to be included in the list :return: list of geometries with incr...
[ "def", "minimum_geometries", "(", "self", ",", "n", "=", "None", ",", "symmetry_measure_type", "=", "None", ",", "max_csm", "=", "None", ")", ":", "cglist", "=", "[", "cg", "for", "cg", "in", "self", ".", "coord_geoms", "]", "if", "symmetry_measure_type", ...
57.208333
31.708333
def factorize(cls, pq): """ Factorizes the given large integer. :param pq: the prime pair pq. :return: a tuple containing the two factors p and q. """ if pq % 2 == 0: return 2, pq // 2 y, c, m = randint(1, pq - 1), randint(1, pq - 1), randint(1, pq -...
[ "def", "factorize", "(", "cls", ",", "pq", ")", ":", "if", "pq", "%", "2", "==", "0", ":", "return", "2", ",", "pq", "//", "2", "y", ",", "c", ",", "m", "=", "randint", "(", "1", ",", "pq", "-", "1", ")", ",", "randint", "(", "1", ",", ...
25
18.25
def create(self, module_name, class_name, args=None, kwargs=None, factory_method=None, factory_args=None, factory_kwargs=None, static=False, calls=None): """ Initializes an instance of the service """ if args is None: args = [] if kwargs i...
[ "def", "create", "(", "self", ",", "module_name", ",", "class_name", ",", "args", "=", "None", ",", "kwargs", "=", "None", ",", "factory_method", "=", "None", ",", "factory_args", "=", "None", ",", "factory_kwargs", "=", "None", ",", "static", "=", "Fals...
35
18.891892
def upgrade(self, instance_id, cpus=None, memory=None, nic_speed=None, public=True, preset=None): """Upgrades a VS instance. Example:: # Upgrade instance 12345 to 4 CPUs and 4 GB of memory import SoftLayer client = SoftLayer.create_client_from_env() mgr = So...
[ "def", "upgrade", "(", "self", ",", "instance_id", ",", "cpus", "=", "None", ",", "memory", "=", "None", ",", "nic_speed", "=", "None", ",", "public", "=", "True", ",", "preset", "=", "None", ")", ":", "upgrade_prices", "=", "self", ".", "_get_upgrade_...
40.19403
23.970149
def get_server_session(self): """Start or resume a server session, or raise ConfigurationError.""" with self._lock: session_timeout = self._description.logical_session_timeout_minutes if session_timeout is None: # Maybe we need an initial scan? Can raise ServerSel...
[ "def", "get_server_session", "(", "self", ")", ":", "with", "self", ".", "_lock", ":", "session_timeout", "=", "self", ".", "_description", ".", "logical_session_timeout_minutes", "if", "session_timeout", "is", "None", ":", "# Maybe we need an initial scan? Can raise Se...
50.833333
19.916667
def _os_install(self, package_file): """ take in a dict return a string of docker build RUN directives one RUN per package type one package type per JSON key """ packages = " ".join(json.load(package_file.open())) if packages: for packager in self.pkg_...
[ "def", "_os_install", "(", "self", ",", "package_file", ")", ":", "packages", "=", "\" \"", ".", "join", "(", "json", ".", "load", "(", "package_file", ".", "open", "(", ")", ")", ")", "if", "packages", ":", "for", "packager", "in", "self", ".", "pkg...
37.928571
13.642857
def reorient(self, up, look): ''' Reorient the mesh by specifying two vectors. up: The foot-to-head direction. look: The direction the body is facing. In the result, the up will end up along +y, and look along +z (i.e. facing towards a default OpenGL camera). '...
[ "def", "reorient", "(", "self", ",", "up", ",", "look", ")", ":", "from", "blmath", ".", "geometry", ".", "transform", "import", "rotation_from_up_and_look", "from", "blmath", ".", "numerics", "import", "as_numeric_array", "up", "=", "as_numeric_array", "(", "...
32.789474
22.368421
def prompt_stdin(prompt): """Ask user for agreeing to data set licenses.""" # raw_input returns the empty string for "enter" yes = set(['yes', 'y']) no = set(['no','n']) try: print(prompt) if sys.version_info>=(3,0): choice = input().lower() else: cho...
[ "def", "prompt_stdin", "(", "prompt", ")", ":", "# raw_input returns the empty string for \"enter\"", "yes", "=", "set", "(", "[", "'yes'", ",", "'y'", "]", ")", "no", "=", "set", "(", "[", "'no'", ",", "'n'", "]", ")", "try", ":", "print", "(", "prompt"...
29.071429
18.892857
def ParseGshadowEntry(self, line): """Extract the members of each group from /etc/gshadow. Identifies the groups in /etc/gshadow and several attributes of the group, including how the password is crypted (if set). gshadow files have the format group_name:passwd:admins:members admins are both group...
[ "def", "ParseGshadowEntry", "(", "self", ",", "line", ")", ":", "fields", "=", "(", "\"name\"", ",", "\"passwd\"", ",", "\"administrators\"", ",", "\"members\"", ")", "if", "line", ":", "rslt", "=", "dict", "(", "zip", "(", "fields", ",", "line", ".", ...
39.84
18.88
def execute(self, conn, name='', transaction = False): """ returns id for a given physics group name """ binds={} if name: op = ('=', 'like')['%' in name] sql = self.sql + " WHERE pg.physics_group_name %s :physicsgroup" % (op) binds = {"physic...
[ "def", "execute", "(", "self", ",", "conn", ",", "name", "=", "''", ",", "transaction", "=", "False", ")", ":", "binds", "=", "{", "}", "if", "name", ":", "op", "=", "(", "'='", ",", "'like'", ")", "[", "'%'", "in", "name", "]", "sql", "=", "...
34.529412
13.823529
def documentation_404(self, base_url=None): """Returns a smart 404 page that contains documentation for the written API""" base_url = self.base_url if base_url is None else base_url def handle_404(request, response, *args, **kwargs): url_prefix = request.forwarded_uri[:-1] ...
[ "def", "documentation_404", "(", "self", ",", "base_url", "=", "None", ")", ":", "base_url", "=", "self", ".", "base_url", "if", "base_url", "is", "None", "else", "base_url", "def", "handle_404", "(", "request", ",", "response", ",", "*", "args", ",", "*...
52.076923
29.230769
def get_path(self, path=''): """ Validate incoming path, if path is empty, build it from resource attributes, If path is invalid - raise exception :param path: path to remote file storage :return: valid path or :raise Exception: """ if not path: host...
[ "def", "get_path", "(", "self", ",", "path", "=", "''", ")", ":", "if", "not", "path", ":", "host", "=", "self", ".", "resource_config", ".", "backup_location", "if", "':'", "not", "in", "host", ":", "scheme", "=", "self", ".", "resource_config", ".", ...
44.787879
23.272727
def to_list(file_path): """ Static method. Takes in a file path, and outputs a list of stings. Each element in the list corresponds to a line in the file. :param file_path: string file path :return: A list of strings, with elements in the list corresponding to lines in th...
[ "def", "to_list", "(", "file_path", ")", ":", "l", "=", "[", "]", "f", "=", "open", "(", "file_path", ",", "'r'", ")", "for", "line", "in", "f", ":", "l", ".", "append", "(", "line", ")", "f", ".", "close", "(", ")", "return", "l" ]
34.428571
17.142857
def section_meander_angles(section): '''Inter-segment opening angles in a section''' p = section.points return [mm.angle_3points(p[i - 1], p[i - 2], p[i]) for i in range(2, len(p))]
[ "def", "section_meander_angles", "(", "section", ")", ":", "p", "=", "section", ".", "points", "return", "[", "mm", ".", "angle_3points", "(", "p", "[", "i", "-", "1", "]", ",", "p", "[", "i", "-", "2", "]", ",", "p", "[", "i", "]", ")", "for",...
40.2
9.8
def get_favorite_radio_shows(self, *args, **kwargs): """Convenience method for `get_music_library_information` with ``search_type='radio_stations'``. For details of other arguments, see `that method <#soco.music_library.MusicLibrary.get_music_library_information>`_. """ a...
[ "def", "get_favorite_radio_shows", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "=", "tuple", "(", "[", "'radio_shows'", "]", "+", "list", "(", "args", ")", ")", "return", "self", ".", "get_music_library_information", "(", "*...
52.625
17.125
def get_driver_class(provider): """ Return the driver class :param provider: str - provider name :return: """ if "." in provider: parts = provider.split('.') kls = parts.pop() path = '.'.join(parts) module = import_module(path) if not hasattr(module, kls):...
[ "def", "get_driver_class", "(", "provider", ")", ":", "if", "\".\"", "in", "provider", ":", "parts", "=", "provider", ".", "split", "(", "'.'", ")", "kls", "=", "parts", ".", "pop", "(", ")", "path", "=", "'.'", ".", "join", "(", "parts", ")", "mod...
28.789474
12.052632
def execute(self, commands=None, ignored_commands=('DROP', 'UNLOCK', 'LOCK'), execute_fails=True, max_executions=MAX_EXECUTION_ATTEMPTS): """ Sequentially execute a list of SQL commands. Check if commands property has already been fetched, if so use the fetched_commands ...
[ "def", "execute", "(", "self", ",", "commands", "=", "None", ",", "ignored_commands", "=", "(", "'DROP'", ",", "'UNLOCK'", ",", "'LOCK'", ")", ",", "execute_fails", "=", "True", ",", "max_executions", "=", "MAX_EXECUTION_ATTEMPTS", ")", ":", "# Break connectio...
40.116279
20.953488
def get_subdomain_entry(self, fqn, accepted=True, cur=None): """ Given a fully-qualified subdomain, get its (latest) subdomain record. Raises SubdomainNotFound if there is no such subdomain """ get_cmd = "SELECT * FROM {} WHERE fully_qualified_subdomain=? {} ORDER BY sequence DES...
[ "def", "get_subdomain_entry", "(", "self", ",", "fqn", ",", "accepted", "=", "True", ",", "cur", "=", "None", ")", ":", "get_cmd", "=", "\"SELECT * FROM {} WHERE fully_qualified_subdomain=? {} ORDER BY sequence DESC, parent_zonefile_index DESC LIMIT 1;\"", ".", "format", "(...
37.333333
24.190476
def optical_flow_rad_send(self, time_usec, sensor_id, integration_time_us, integrated_x, integrated_y, integrated_xgyro, integrated_ygyro, integrated_zgyro, temperature, quality, time_delta_distance_us, distance, force_mavlink1=False): ''' Optical flow from an angular rate flow sensor (e...
[ "def", "optical_flow_rad_send", "(", "self", ",", "time_usec", ",", "sensor_id", ",", "integration_time_us", ",", "integrated_x", ",", "integrated_y", ",", "integrated_xgyro", ",", "integrated_ygyro", ",", "integrated_zgyro", ",", "temperature", ",", "quality", ",", ...
112.7
86.6
def fetch_open_orders(self, limit: int) -> List[Order]: """Fetch latest open orders, must provide a limit.""" return self._fetch_orders_limit(self._open_orders, limit)
[ "def", "fetch_open_orders", "(", "self", ",", "limit", ":", "int", ")", "->", "List", "[", "Order", "]", ":", "return", "self", ".", "_fetch_orders_limit", "(", "self", ".", "_open_orders", ",", "limit", ")" ]
60.333333
13.333333
def get_dashboard(self, id, **kwargs): """"Retrieve a (v2) dashboard by id. """ resp = self._get_object_by_name(self._DASHBOARD_ENDPOINT_SUFFIX, id, **kwargs) return resp
[ "def", "get_dashboard", "(", "self", ",", "id", ",", "*", "*", "kwargs", ")", ":", "resp", "=", "self", ".", "_get_object_by_name", "(", "self", ".", "_DASHBOARD_ENDPOINT_SUFFIX", ",", "id", ",", "*", "*", "kwargs", ")", "return", "resp" ]
39.5
11.333333
def _parse_record(self, field, boxscore, index): """ Parse each team's record. Find the record for both the home and away teams which are listed above the basic boxscore stats tables. Depending on whether or not the advanced stats table is included on the page (generally only fo...
[ "def", "_parse_record", "(", "self", ",", "field", ",", "boxscore", ",", "index", ")", ":", "records", "=", "boxscore", "(", "BOXSCORE_SCHEME", "[", "field", "]", ")", ".", "items", "(", ")", "records", "=", "[", "x", ".", "text", "(", ")", "for", ...
40.62069
23.586207
def execute(self): """Execute a system command.""" if self._decode_output: # Capture and decode system output with Popen(self.command, shell=True, stdout=PIPE) as process: self._output = [i.decode("utf-8").strip() for i in process.stdout] self._suc...
[ "def", "execute", "(", "self", ")", ":", "if", "self", ".", "_decode_output", ":", "# Capture and decode system output", "with", "Popen", "(", "self", ".", "command", ",", "shell", "=", "True", ",", "stdout", "=", "PIPE", ")", "as", "process", ":", "self",...
39.166667
15.25
def get_from_postcode(postcode, distance): """ Request all postcode data within `distance` miles of `postcode`. :param postcode: the postcode to search for. The postcode may contain spaces (they will be removed). :param distance: distance in miles to `postcode`. :returns: a ...
[ "def", "get_from_postcode", "(", "postcode", ",", "distance", ")", ":", "postcode", "=", "quote", "(", "postcode", ".", "replace", "(", "' '", ",", "''", ")", ")", "return", "_get_from", "(", "distance", ",", "'postcode=%s'", "%", "postcode", ")" ]
38.642857
20.5
def list_mount(): ''' List mounted zfs filesystems .. versionadded:: 2018.3.1 CLI Example: .. code-block:: bash salt '*' zfs.list_mount ''' ## List mounted filesystem res = __salt__['cmd.run_all']( __utils__['zfs.zfs_command']( command='mount', ),...
[ "def", "list_mount", "(", ")", ":", "## List mounted filesystem", "res", "=", "__salt__", "[", "'cmd.run_all'", "]", "(", "__utils__", "[", "'zfs.zfs_command'", "]", "(", "command", "=", "'mount'", ",", ")", ",", "python_shell", "=", "False", ",", ")", "if",...
20.37931
21.344828
def get_absolute_url(self): """Get model url""" return reverse('trionyx:model-view', kwargs={ 'app': self._meta.app_label, 'model': self._meta.model_name, 'pk': self.id })
[ "def", "get_absolute_url", "(", "self", ")", ":", "return", "reverse", "(", "'trionyx:model-view'", ",", "kwargs", "=", "{", "'app'", ":", "self", ".", "_meta", ".", "app_label", ",", "'model'", ":", "self", ".", "_meta", ".", "model_name", ",", "'pk'", ...
32.142857
10.571429
def full_domain_validator(hostname): """ Fully validates a domain name as compilant with the standard rules: - Composed of series of labels concatenated with dots, as are all domain names. - Each label must be between 1 and 63 characters long. - The entire hostname (including the delimit...
[ "def", "full_domain_validator", "(", "hostname", ")", ":", "HOSTNAME_LABEL_PATTERN", "=", "re", ".", "compile", "(", "\"(?!-)[A-Z\\d-]+(?<!-)$\"", ",", "re", ".", "IGNORECASE", ")", "if", "not", "hostname", ":", "return", "if", "len", "(", "hostname", ")", ">"...
52.956522
27.73913
def append_flipped_images(self): """Only flip boxes coordinates, images will be flipped when loading into network""" logger.info('%s append flipped images to roidb' % self._name) roidb_flipped = [] for roi_rec in self._roidb: boxes = roi_rec['boxes'].copy() oldx1 ...
[ "def", "append_flipped_images", "(", "self", ")", ":", "logger", ".", "info", "(", "'%s append flipped images to roidb'", "%", "self", ".", "_name", ")", "roidb_flipped", "=", "[", "]", "for", "roi_rec", "in", "self", ".", "_roidb", ":", "boxes", "=", "roi_r...
47.25
7.9375
async def _sem_crawl(self, sem, res): """ use semaphore ``encapsulate`` the crawl_media \n with async crawl, should avoid crawl too fast to become DDos attack to the crawled server should set the ``semaphore size``, and take ``a little gap`` between each crawl behavior. :param sem: the ...
[ "async", "def", "_sem_crawl", "(", "self", ",", "sem", ",", "res", ")", ":", "async", "with", "sem", ":", "st_", "=", "await", "self", ".", "crawl_raw", "(", "res", ")", "if", "st_", ":", "self", ".", "result", "[", "'ok'", "]", "+=", "1", "else"...
33.238095
18.809524
def backup_progress(self): """Return status of cloud backup as a dict. Is there a way to get progress for Server version? """ epoch_time = int(time.time() * 1000) if self.deploymentType == 'Cloud': url = self._options['server'] + '/rest/obm/1.0/getprogress?_=%i' % ep...
[ "def", "backup_progress", "(", "self", ")", ":", "epoch_time", "=", "int", "(", "time", ".", "time", "(", ")", "*", "1000", ")", "if", "self", ".", "deploymentType", "==", "'Cloud'", ":", "url", "=", "self", ".", "_options", "[", "'server'", "]", "+"...
38.034483
17.827586
def makeNodeID(Rec, ndType, extras = None): """Helper to make a node ID, extras is currently not used""" if ndType == 'raw': recID = Rec else: recID = Rec.get(ndType) if recID is None: pass elif isinstance(recID, list): recID = tuple(recID) else: recID = r...
[ "def", "makeNodeID", "(", "Rec", ",", "ndType", ",", "extras", "=", "None", ")", ":", "if", "ndType", "==", "'raw'", ":", "recID", "=", "Rec", "else", ":", "recID", "=", "Rec", ".", "get", "(", "ndType", ")", "if", "recID", "is", "None", ":", "pa...
26.4
15.8
def train(self, record): """ Incrementally updates the tree with the given sample record. """ assert self.data.class_attribute_name in record, \ "The class attribute must be present in the record." record = record.copy() self.sample_count += 1 self.tre...
[ "def", "train", "(", "self", ",", "record", ")", ":", "assert", "self", ".", "data", ".", "class_attribute_name", "in", "record", ",", "\"The class attribute must be present in the record.\"", "record", "=", "record", ".", "copy", "(", ")", "self", ".", "sample_...
36.333333
12.777778
def with_arg_count(self, count): """Set the last call to expect an exact argument count. I.E.:: >>> auth = Fake('auth').provides('login').with_arg_count(2) >>> auth.login('joe_user') # forgot password Traceback (most recent call last): ... As...
[ "def", "with_arg_count", "(", "self", ",", "count", ")", ":", "exp", "=", "self", ".", "_get_current_call", "(", ")", "exp", ".", "expected_arg_count", "=", "count", "return", "self" ]
32.533333
20.133333
def pull(self, action, image_name, **kwargs): """ Pulls an image for a container configuration :param action: Action configuration. :type action: dockermap.map.runner.ActionConfig :param image_name: Image name. :type image_name: unicode | str :param kwargs: Addit...
[ "def", "pull", "(", "self", ",", "action", ",", "image_name", ",", "*", "*", "kwargs", ")", ":", "config_id", "=", "action", ".", "config_id", "registry", ",", "__", ",", "image", "=", "config_id", ".", "config_name", ".", "rpartition", "(", "'/'", ")"...
55.857143
26.52381
def analyze(fqdn, result, argl, argd): """Analyzes the result from calling the method with the specified FQDN. Args: fqdn (str): full-qualified name of the method that was called. result: result of calling the method with `fqdn`. argl (tuple): positional arguments passed to the method c...
[ "def", "analyze", "(", "fqdn", ",", "result", ",", "argl", ",", "argd", ")", ":", "package", "=", "fqdn", ".", "split", "(", "'.'", ")", "[", "0", "]", "if", "package", "not", "in", "_methods", ":", "_load_methods", "(", "package", ")", "if", "_met...
41.666667
19.133333
def render(self, request, instance, **kwargs): """ Only render the plugin if the item can be shown to the user """ if instance.get_item(): return super(LinkPlugin, self).render(request, instance, **kwargs) return ""
[ "def", "render", "(", "self", ",", "request", ",", "instance", ",", "*", "*", "kwargs", ")", ":", "if", "instance", ".", "get_item", "(", ")", ":", "return", "super", "(", "LinkPlugin", ",", "self", ")", ".", "render", "(", "request", ",", "instance"...
37.285714
14.714286
def check_db_for_missing_notifications(): """Check the database for missing notifications.""" aws_access_key_id = os.environ['aws_access_key_id'] aws_secret_access_key = os.environ['aws_secret_access_key'] if config.getboolean('Shell Parameters', 'launch_in_sandbox_mode'): conn = MTurkConnection...
[ "def", "check_db_for_missing_notifications", "(", ")", ":", "aws_access_key_id", "=", "os", ".", "environ", "[", "'aws_access_key_id'", "]", "aws_secret_access_key", "=", "os", ".", "environ", "[", "'aws_secret_access_key'", "]", "if", "config", ".", "getboolean", "...
51.824074
21.666667
def _hashes_match(self, a, b): """Constant time comparison of bytes for py3, strings for py2""" if len(a) != len(b): return False diff = 0 if six.PY2: a = bytearray(a) b = bytearray(b) for x, y in zip(a, b): diff |= x ^ y re...
[ "def", "_hashes_match", "(", "self", ",", "a", ",", "b", ")", ":", "if", "len", "(", "a", ")", "!=", "len", "(", "b", ")", ":", "return", "False", "diff", "=", "0", "if", "six", ".", "PY2", ":", "a", "=", "bytearray", "(", "a", ")", "b", "=...
29.363636
13.545455
def delcal(mspath): """Delete the ``MODEL_DATA`` and ``CORRECTED_DATA`` columns from a measurement set. mspath (str) The path to the MS to modify Example:: from pwkit.environments.casa import tasks tasks.delcal('dataset.ms') """ wantremove = 'MODEL_DATA CORRECTED_DATA'.split() ...
[ "def", "delcal", "(", "mspath", ")", ":", "wantremove", "=", "'MODEL_DATA CORRECTED_DATA'", ".", "split", "(", ")", "tb", "=", "util", ".", "tools", ".", "table", "(", ")", "tb", ".", "open", "(", "b", "(", "mspath", ")", ",", "nomodify", "=", "False...
26.777778
18.62963
def head(records, head): """ Limit results to the top N records. With the leading `-', print all but the last N records. """ logging.info('Applying _head generator: ' 'limiting results to top ' + head + ' records.') if head == '-0': for record in records: yi...
[ "def", "head", "(", "records", ",", "head", ")", ":", "logging", ".", "info", "(", "'Applying _head generator: '", "'limiting results to top '", "+", "head", "+", "' records.'", ")", "if", "head", "==", "'-0'", ":", "for", "record", "in", "records", ":", "yi...
33.45
14.85
def store_uploaded_file(title, uploaded_file): """ Stores a temporary uploaded file on disk """ upload_dir_path = '%s/static/taskManager/uploads' % ( os.path.dirname(os.path.realpath(__file__))) if not os.path.exists(upload_dir_path): os.makedirs(upload_dir_path) # A1: Injection (shell)...
[ "def", "store_uploaded_file", "(", "title", ",", "uploaded_file", ")", ":", "upload_dir_path", "=", "'%s/static/taskManager/uploads'", "%", "(", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "realpath", "(", "__file__", ")", ")", ")", "if",...
31.333333
17
def templates(self, timeout=None): """ API call to get a list of templates """ return self._api_request( self.TEMPLATES_ENDPOINT, self.HTTP_GET, timeout=timeout )
[ "def", "templates", "(", "self", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "_api_request", "(", "self", ".", "TEMPLATES_ENDPOINT", ",", "self", ".", "HTTP_GET", ",", "timeout", "=", "timeout", ")" ]
30.857143
10.714286
def read_samples(self, sr=None, offset=0, duration=None): """ Read the samples of the utterance. Args: sr (int): If None uses the sampling rate given by the track, otherwise resamples to the given sampling rate. offset (float): Offset in seconds to ...
[ "def", "read_samples", "(", "self", ",", "sr", "=", "None", ",", "offset", "=", "0", ",", "duration", "=", "None", ")", ":", "read_duration", "=", "self", ".", "duration", "if", "offset", ">", "0", "and", "read_duration", "is", "not", "None", ":", "r...
33.0625
19.5
def get_selection_owner(self, selection): """Return the window that owns selection (an atom), or X.NONE if there is no owner for the selection. Can raise BadAtom.""" r = request.GetSelectionOwner(display = self.display, selection = selection) return ...
[ "def", "get_selection_owner", "(", "self", ",", "selection", ")", ":", "r", "=", "request", ".", "GetSelectionOwner", "(", "display", "=", "self", ".", "display", ",", "selection", "=", "selection", ")", "return", "r", ".", "owner" ]
53.666667
10
def utf8(value): """Converts a string argument to a byte string. If the argument is already a byte string or None, it is returned unchanged. Otherwise it must be a unicode string and is encoded as utf8. """ if isinstance(value, _UTF8_TYPES): return value assert isinstance(value, unicode...
[ "def", "utf8", "(", "value", ")", ":", "if", "isinstance", "(", "value", ",", "_UTF8_TYPES", ")", ":", "return", "value", "assert", "isinstance", "(", "value", ",", "unicode", ")", "return", "value", ".", "encode", "(", "\"utf-8\"", ")" ]
34.5
16.1
def add_data(self, *args): """Add data to signer""" for data in args: self._data.append(to_binary(data))
[ "def", "add_data", "(", "self", ",", "*", "args", ")", ":", "for", "data", "in", "args", ":", "self", ".", "_data", ".", "append", "(", "to_binary", "(", "data", ")", ")" ]
32.25
8.75
def _flann_args(self, X=None): "The dictionary of arguments to give to FLANN." args = {'cores': self._n_jobs} if self.flann_algorithm == 'auto': if X is None or X.dim > 5: args['algorithm'] = 'linear' else: args['algorithm'] = 'kdtree_singl...
[ "def", "_flann_args", "(", "self", ",", "X", "=", "None", ")", ":", "args", "=", "{", "'cores'", ":", "self", ".", "_n_jobs", "}", "if", "self", ".", "flann_algorithm", "==", "'auto'", ":", "if", "X", "is", "None", "or", "X", ".", "dim", ">", "5"...
33.571429
13.666667
def ReadStatusBit(self, bit): ' Report given status bit ' spi.SPI_write_byte(self.CS, 0x39) # Read from address 0x19 (STATUS) spi.SPI_write_byte(self.CS, 0x00) data0 = spi.SPI_read_byte() # 1st byte spi.SPI_write_byte(self.CS, 0x00) data1 = spi.SPI_read_byte()...
[ "def", "ReadStatusBit", "(", "self", ",", "bit", ")", ":", "spi", ".", "SPI_write_byte", "(", "self", ".", "CS", ",", "0x39", ")", "# Read from address 0x19 (STATUS)", "spi", ".", "SPI_write_byte", "(", "self", ".", "CS", ",", "0x00", ")", "data0", "=", ...
44.923077
14.461538
def generate_hooked_command(cmd_name, cmd_cls, hooks): """ Returns a generated subclass of ``cmd_cls`` that runs the pre- and post-command hooks for that command before and after the ``cmd_cls.run`` method. """ def run(self, orig_run=cmd_cls.run): self.run_command_hooks('pre_hooks') ...
[ "def", "generate_hooked_command", "(", "cmd_name", ",", "cmd_cls", ",", "hooks", ")", ":", "def", "run", "(", "self", ",", "orig_run", "=", "cmd_cls", ".", "run", ")", ":", "self", ".", "run_command_hooks", "(", "'pre_hooks'", ")", "orig_run", "(", "self",...
36.9375
16.9375
def read_and_save_data(info_df, raw_dir, sep=";", force_raw=False, force_cellpy=False, export_cycles=False, shifted_cycles=False, export_raw=True, export_ica=False, save=True, use_cellpy_stat_file=False, p...
[ "def", "read_and_save_data", "(", "info_df", ",", "raw_dir", ",", "sep", "=", "\";\"", ",", "force_raw", "=", "False", ",", "force_cellpy", "=", "False", ",", "export_cycles", "=", "False", ",", "shifted_cycles", "=", "False", ",", "export_raw", "=", "True",...
41.657895
21.184211
def zero_state(self, batch_size): """ Initial state of the network """ return torch.zeros(batch_size, self.state_dim, dtype=torch.float32)
[ "def", "zero_state", "(", "self", ",", "batch_size", ")", ":", "return", "torch", ".", "zeros", "(", "batch_size", ",", "self", ".", "state_dim", ",", "dtype", "=", "torch", ".", "float32", ")" ]
50.666667
14
def get_unit_by_name(self, unit_name: str) -> typing.Optional['BaseUnit']: """ Gets a unit from its name Args: unit_name: unit name Returns: """ VALID_STR.validate(unit_name, 'get_unit_by_name') for unit in self.units: if unit.unit_name ...
[ "def", "get_unit_by_name", "(", "self", ",", "unit_name", ":", "str", ")", "->", "typing", ".", "Optional", "[", "'BaseUnit'", "]", ":", "VALID_STR", ".", "validate", "(", "unit_name", ",", "'get_unit_by_name'", ")", "for", "unit", "in", "self", ".", "unit...
24.466667
18.866667
def make_structure_from_geos(geos): '''Creates a structure out of a list of geometry objects.''' model_structure=initialize_res(geos[0]) for i in range(1,len(geos)): model_structure=add_residue(model_structure, geos[i]) return model_structure
[ "def", "make_structure_from_geos", "(", "geos", ")", ":", "model_structure", "=", "initialize_res", "(", "geos", "[", "0", "]", ")", "for", "i", "in", "range", "(", "1", ",", "len", "(", "geos", ")", ")", ":", "model_structure", "=", "add_residue", "(", ...
37.285714
16.428571
def heading(self, column, option=None, **kw): """ Query or modify the heading options for the specified column. If `kw` is not given, returns a dict of the heading option values. If `option` is specified then the value for that option is returned. Otherwise, sets the options to ...
[ "def", "heading", "(", "self", ",", "column", ",", "option", "=", "None", ",", "*", "*", "kw", ")", ":", "if", "kw", ":", "# Set the default image of the heading to the drag icon", "kw", ".", "setdefault", "(", "\"image\"", ",", "self", ".", "_im_drag", ")",...
47.347826
23.434783
def _aspect_preserving_resize(image, resize_min): """Resize images preserving the original aspect ratio. Args: image: A 3-D image `Tensor`. resize_min: A python integer or scalar `Tensor` indicating the size of the smallest side after resize. Returns: resized_image: A 3-D tensor containing the...
[ "def", "_aspect_preserving_resize", "(", "image", ",", "resize_min", ")", ":", "mlperf_log", ".", "resnet_print", "(", "key", "=", "mlperf_log", ".", "INPUT_RESIZE_ASPECT_PRESERVING", ",", "value", "=", "{", "\"min\"", ":", "resize_min", "}", ")", "shape", "=", ...
32.2
22.45
def get_records(cls, ids, with_deleted=False): """Retrieve multiple records by id. :param ids: List of record IDs. :param with_deleted: If `True` then it includes deleted records. :returns: A list of :class:`Record` instances. """ with db.session.no_autoflush: ...
[ "def", "get_records", "(", "cls", ",", "ids", ",", "with_deleted", "=", "False", ")", ":", "with", "db", ".", "session", ".", "no_autoflush", ":", "query", "=", "RecordMetadata", ".", "query", ".", "filter", "(", "RecordMetadata", ".", "id", ".", "in_", ...
42.307692
18.461538
def data(path, hours, offset=0): """ Does the metric at ``path`` have any whisper data newer than ``hours``? If ``offset`` is not None, view the ``hours`` prior to ``offset`` hours ago, instead of from right now. """ now = time.time() end = now - _to_sec(offset) # Will default to now s...
[ "def", "data", "(", "path", ",", "hours", ",", "offset", "=", "0", ")", ":", "now", "=", "time", ".", "time", "(", ")", "end", "=", "now", "-", "_to_sec", "(", "offset", ")", "# Will default to now", "start", "=", "end", "-", "_to_sec", "(", "hours...
35.416667
14.25
def _decrypt_symmetric( self, decryption_algorithm, decryption_key, cipher_text, cipher_mode=None, padding_method=None, iv_nonce=None): """ Decrypt data using symmetric decryption. Args: decryption_a...
[ "def", "_decrypt_symmetric", "(", "self", ",", "decryption_algorithm", ",", "decryption_key", ",", "cipher_text", ",", "cipher_mode", "=", "None", ",", "padding_method", "=", "None", ",", "iv_nonce", "=", "None", ")", ":", "# Set up the algorithm", "algorithm", "=...
39.122449
20.122449
def _handle_error(self, data, params): """Handle an error response from the SABnzbd API""" error = data.get('error', 'API call failed') mode = params.get('mode') raise SabnzbdApiException(error, mode=mode)
[ "def", "_handle_error", "(", "self", ",", "data", ",", "params", ")", ":", "error", "=", "data", ".", "get", "(", "'error'", ",", "'API call failed'", ")", "mode", "=", "params", ".", "get", "(", "'mode'", ")", "raise", "SabnzbdApiException", "(", "error...
46.6
6.4
def _validate(self): """ Step 5 (1st flow) or Step 4 (2nd flow). Process contract for object. """ # disable methods matching before validation self._disable_patching = True # validation by Invariant.validate self._validate_base(self) # enable methods match...
[ "def", "_validate", "(", "self", ")", ":", "# disable methods matching before validation", "self", ".", "_disable_patching", "=", "True", "# validation by Invariant.validate", "self", ".", "_validate_base", "(", "self", ")", "# enable methods matching after validation", "self...
37
9.2
def request(self, method, url, params=None, data=None, headers=None, auth=None, timeout=None, allow_redirects=False): """ Make an HTTP request. """ raise TwilioException('HttpClient is an abstract class')
[ "def", "request", "(", "self", ",", "method", ",", "url", ",", "params", "=", "None", ",", "data", "=", "None", ",", "headers", "=", "None", ",", "auth", "=", "None", ",", "timeout", "=", "None", ",", "allow_redirects", "=", "False", ")", ":", "rai...
41.166667
14.5
def MAE(x1, x2=-1): """ Mean absolute error - this function accepts two series of data or directly one series with error. **Args:** * `x1` - first data series or error (1d array) **Kwargs:** * `x2` - second series (1d array) if first series was not error directly,\\ then this sho...
[ "def", "MAE", "(", "x1", ",", "x2", "=", "-", "1", ")", ":", "e", "=", "get_valid_error", "(", "x1", ",", "x2", ")", "return", "np", ".", "sum", "(", "np", ".", "abs", "(", "e", ")", ")", "/", "float", "(", "len", "(", "e", ")", ")" ]
24.409091
23.772727
def local_pdb_codes(data_dir=None): """ Get list of PDB codes stored in a folder (FileSystem folder hierarchy expected within data_dir). If no folder is specified, use the database_dir defined in settings.json. Parameters ---------- data_dir: str Filepath to a folder containing the PDB fol...
[ "def", "local_pdb_codes", "(", "data_dir", "=", "None", ")", ":", "if", "not", "data_dir", ":", "data_dir", "=", "global_settings", "[", "\"structural_database\"", "]", "[", "\"path\"", "]", "p", "=", "Path", "(", "data_dir", ")", "pdb_parent_dirs", "=", "["...
35.913043
26.304348
def check_the_end_flag(self, state_key): ''' Check the end flag. If this return value is `True`, the learning is end. Args: state_key: The key of state in `self.t`. Returns: bool ''' # As a rule, the learning can not be stoppe...
[ "def", "check_the_end_flag", "(", "self", ",", "state_key", ")", ":", "# As a rule, the learning can not be stopped.", "x", ",", "y", "=", "state_key", "end_point_tuple", "=", "np", ".", "where", "(", "self", ".", "__map_arr", "==", "self", ".", "__end_point_label...
29.55
22.95
def _setup_bindings(self): """ Setup the event bindings for the widgets: Configure for _timeline Horizontal and Vertical scrolling for all widgets """ self._timeline.bind("<Configure>", self.__configure_timeline) for widget in [self, self._canvas_scroll, self._tim...
[ "def", "_setup_bindings", "(", "self", ")", ":", "self", ".", "_timeline", ".", "bind", "(", "\"<Configure>\"", ",", "self", ".", "__configure_timeline", ")", "for", "widget", "in", "[", "self", ",", "self", ".", "_canvas_scroll", ",", "self", ".", "_timel...
54.722222
21.944444
def image_predict(self, X): """ Predicts class label for the entire image. Parameters: ----------- X: array, shape = [n_samples, n_pixels_y, n_pixels_x, n_bands] Array of training images y: array, shape = [n_samples] or [n_samples, n_pixels_y, n_p...
[ "def", "image_predict", "(", "self", ",", "X", ")", ":", "self", ".", "_check_image", "(", "X", ")", "new_shape", "=", "(", "X", ".", "shape", "[", "0", "]", "*", "X", ".", "shape", "[", "1", "]", "*", "X", ".", "shape", "[", "2", "]", ",", ...
28.6
22.44
def printConfig(self, type='simu'): """ print information about element :param type: comm, simu, ctrl, misc, all """ print("{s1}{s2:^22s}{s1}".format(s1="-" * 10, s2="Configuration START")) print("Element name: {en} ({cn})".format(en=self.name, cn=self.__class__.__name__)) ...
[ "def", "printConfig", "(", "self", ",", "type", "=", "'simu'", ")", ":", "print", "(", "\"{s1}{s2:^22s}{s1}\"", ".", "format", "(", "s1", "=", "\"-\"", "*", "10", ",", "s2", "=", "\"Configuration START\"", ")", ")", "print", "(", "\"Element name: {en} ({cn})...
48.363636
21.090909
def cli(ctx, feature_id, attribute_key, attribute_value, organism="", sequence=""): """Delete an attribute from a feature Output: A standard apollo feature dictionary ({"features": [{...}]}) """ return ctx.gi.annotations.delete_attribute(feature_id, attribute_key, attribute_value, organism=organism, s...
[ "def", "cli", "(", "ctx", ",", "feature_id", ",", "attribute_key", ",", "attribute_value", ",", "organism", "=", "\"\"", ",", "sequence", "=", "\"\"", ")", ":", "return", "ctx", ".", "gi", ".", "annotations", ".", "delete_attribute", "(", "feature_id", ","...
41.25
33.5
def xpath_eval(node, extra_ns=None): """ Returns an XPathEvaluator, with namespace prefixes 'bpmn' for http://www.omg.org/spec/BPMN/20100524/MODEL, and additional specified ones """ namespaces = {'bpmn': BPMN_MODEL_NS} if extra_ns: namespaces.update(extra_ns) return lambda path: node...
[ "def", "xpath_eval", "(", "node", ",", "extra_ns", "=", "None", ")", ":", "namespaces", "=", "{", "'bpmn'", ":", "BPMN_MODEL_NS", "}", "if", "extra_ns", ":", "namespaces", ".", "update", "(", "extra_ns", ")", "return", "lambda", "path", ":", "node", ".",...
37.555556
12.222222
def update(self, list_id, webhook_id, data): """ Update the settings for an existing webhook. :param list_id: The unique id for the list :type list_id: :py:class:`str` :param webhook_id: The unique id for the webhook :type webhook_id: :py:class:`str` """ ...
[ "def", "update", "(", "self", ",", "list_id", ",", "webhook_id", ",", "data", ")", ":", "self", ".", "list_id", "=", "list_id", "self", ".", "webhook_id", "=", "webhook_id", "return", "self", ".", "_mc_client", ".", "_patch", "(", "url", "=", "self", "...
39.333333
13.5
def get_python_path(venv_path): """ Get given virtual environment's `python` program path. :param venv_path: Virtual environment directory path. :return: `python` program path. """ # Get `bin` directory path bin_path = get_bin_path(venv_path) # Get `python` program path program_pa...
[ "def", "get_python_path", "(", "venv_path", ")", ":", "# Get `bin` directory path", "bin_path", "=", "get_bin_path", "(", "venv_path", ")", "# Get `python` program path", "program_path", "=", "os", ".", "path", ".", "join", "(", "bin_path", ",", "'python'", ")", "...
27.428571
15.714286
def set_mag_offsets_encode(self, target_system, target_component, mag_ofs_x, mag_ofs_y, mag_ofs_z): ''' Deprecated. Use MAV_CMD_PREFLIGHT_SET_SENSOR_OFFSETS instead. Set the magnetometer offsets target_system : System ID (uint8_t) ...
[ "def", "set_mag_offsets_encode", "(", "self", ",", "target_system", ",", "target_component", ",", "mag_ofs_x", ",", "mag_ofs_y", ",", "mag_ofs_z", ")", ":", "return", "MAVLink_set_mag_offsets_message", "(", "target_system", ",", "target_component", ",", "mag_ofs_x", "...
56.307692
35.692308
def _unpack(self, tar_file, directory): """ Unpacks tar archive to selected directory """ self.log.info("Unpacking %s tar file to %s directory" % (tar_file, directory)) with tarfile.open(tar_file, 'r') as tar: tar.extractall(path=directory) self.log.i...
[ "def", "_unpack", "(", "self", ",", "tar_file", ",", "directory", ")", ":", "self", ".", "log", ".", "info", "(", "\"Unpacking %s tar file to %s directory\"", "%", "(", "tar_file", ",", "directory", ")", ")", "with", "tarfile", ".", "open", "(", "tar_file", ...
33.5
16
def delayed_redraw(self): """Handle delayed redrawing of the canvas.""" # This is the optimized redraw method with self._defer_lock: # pick up the lowest necessary level of redrawing whence = self._defer_whence self._defer_whence = self._defer_whence_reset ...
[ "def", "delayed_redraw", "(", "self", ")", ":", "# This is the optimized redraw method", "with", "self", ".", "_defer_lock", ":", "# pick up the lowest necessary level of redrawing", "whence", "=", "self", ".", "_defer_whence", "self", ".", "_defer_whence", "=", "self", ...
34.928571
13.857143
def _encode(data): """Encode the given data using base-64 :param data: :return: base-64 encoded string """ if not isinstance(data, bytes_types): data = six.b(str(data)) return base64.b64encode(data).decode("utf-8")
[ "def", "_encode", "(", "data", ")", ":", "if", "not", "isinstance", "(", "data", ",", "bytes_types", ")", ":", "data", "=", "six", ".", "b", "(", "str", "(", "data", ")", ")", "return", "base64", ".", "b64encode", "(", "data", ")", ".", "decode", ...
26.555556
12.222222
def set_document(request, doc_id, body, errors): """ Simple handler for set document :param request: aiohttp.web.Request :param errors: aiohttp_apiset.exceptions.ValidationError optional param for manual raise validation errors :return: dict """ if doc_id in DB: errors...
[ "def", "set_document", "(", "request", ",", "doc_id", ",", "body", ",", "errors", ")", ":", "if", "doc_id", "in", "DB", ":", "errors", "[", "'doc_id'", "]", ".", "add", "(", "'Document already exists'", ")", "if", "errors", ":", "raise", "errors", "body"...
27.333333
18.888889
def update_session(request, session_to_set, hproPk): """Update the session with users-realted values""" for key, value in session_to_set.items(): request.session['plugit_' + str(hproPk) + '_' + key] = value
[ "def", "update_session", "(", "request", ",", "session_to_set", ",", "hproPk", ")", ":", "for", "key", ",", "value", "in", "session_to_set", ".", "items", "(", ")", ":", "request", ".", "session", "[", "'plugit_'", "+", "str", "(", "hproPk", ")", "+", ...
43.8
17
def _get_log_lines(self, n=300): """Returns a list with the last ``n`` lines of the nextflow log file Parameters ---------- n : int Number of last lines from the log file Returns ------- list List of strings with the nextflow log ...
[ "def", "_get_log_lines", "(", "self", ",", "n", "=", "300", ")", ":", "with", "open", "(", "self", ".", "log_file", ")", "as", "fh", ":", "last_lines", "=", "fh", ".", "readlines", "(", ")", "[", "-", "n", ":", "]", "return", "last_lines" ]
23.277778
19.666667
def get_content_type(self): """ Returns the ``Content-Type`` header to be used for this request. """ mime_type, encoding = mimetypes.guess_type(self.filepath) if encoding == "gzip": return "application/gzip" elif encoding is not None: return "appli...
[ "def", "get_content_type", "(", "self", ")", ":", "mime_type", ",", "encoding", "=", "mimetypes", ".", "guess_type", "(", "self", ".", "filepath", ")", "if", "encoding", "==", "\"gzip\"", ":", "return", "\"application/gzip\"", "elif", "encoding", "is", "not", ...
37
12
def _explore_storage(self): """Generator of all files contained in media storage.""" path = '' dirs = [path] while dirs: path = dirs.pop() subdirs, files = self.media_storage.listdir(path) for media_filename in files: yield os.path.join...
[ "def", "_explore_storage", "(", "self", ")", ":", "path", "=", "''", "dirs", "=", "[", "path", "]", "while", "dirs", ":", "path", "=", "dirs", ".", "pop", "(", ")", "subdirs", ",", "files", "=", "self", ".", "media_storage", ".", "listdir", "(", "p...
40.9
15.9
def _compute_baseline_survival(self): """ Importantly, this agrees with what the KaplanMeierFitter produces. Ex: Example ------- >>> from lifelines.datasets import load_rossi >>> from lifelines import CoxPHFitter, KaplanMeierFitter >>> rossi = load_rossi() ...
[ "def", "_compute_baseline_survival", "(", "self", ")", ":", "survival_df", "=", "np", ".", "exp", "(", "-", "self", ".", "baseline_cumulative_hazard_", ")", "if", "self", ".", "strata", "is", "None", ":", "survival_df", ".", "columns", "=", "[", "\"baseline ...
37.727273
13.909091
def rectangle(self, x0, y0, x1, y1): """Draw a rectangle""" x0, y0, x1, y1 = self.rect_helper(x0, y0, x1, y1) self.polyline([[x0, y0], [x1, y0], [x1, y1], [x0, y1], [x0, y0]])
[ "def", "rectangle", "(", "self", ",", "x0", ",", "y0", ",", "x1", ",", "y1", ")", ":", "x0", ",", "y0", ",", "x1", ",", "y1", "=", "self", ".", "rect_helper", "(", "x0", ",", "y0", ",", "x1", ",", "y1", ")", "self", ".", "polyline", "(", "[...
49
13.5
def dlogpdf_df_dtheta(self, f, y, Y_metadata=None): """ TODO: Doc strings """ if self.size > 0: if self.not_block_really: raise NotImplementedError("Need to make a decorator for this!") if isinstance(self.gp_link, link_functions.Identity): ...
[ "def", "dlogpdf_df_dtheta", "(", "self", ",", "f", ",", "y", ",", "Y_metadata", "=", "None", ")", ":", "if", "self", ".", "size", ">", "0", ":", "if", "self", ".", "not_block_really", ":", "raise", "NotImplementedError", "(", "\"Need to make a decorator for ...
49.478261
22.695652
def start_update(self, layer_id): """ A shortcut to create a new version and start importing it. Effectively the same as :py:meth:`koordinates.layers.LayerManager.create_draft` followed by :py:meth:`koordinates.layers.LayerManager.start_import`. """ target_url = self.client.get_u...
[ "def", "start_update", "(", "self", ",", "layer_id", ")", ":", "target_url", "=", "self", ".", "client", ".", "get_url", "(", "'LAYER'", ",", "'POST'", ",", "'update'", ",", "{", "'layer_id'", ":", "layer_id", "}", ")", "r", "=", "self", ".", "client",...
60.375
29.375
def parse_URL(cls, url, timeout=None, resolve=True, required=False, unresolved_value=DEFAULT_SUBSTITUTION): """Parse URL :param url: url to parse :type url: basestring :param resolve: if true, resolve substitutions :type resolve: boolean :param unresolved_value: assigned...
[ "def", "parse_URL", "(", "cls", ",", "url", ",", "timeout", "=", "None", ",", "resolve", "=", "True", ",", "required", "=", "False", ",", "unresolved_value", "=", "DEFAULT_SUBSTITUTION", ")", ":", "socket_timeout", "=", "socket", ".", "_GLOBAL_DEFAULT_TIMEOUT"...
48.846154
27.423077
def process_pybel_graph(graph): """Return a PybelProcessor by processing a PyBEL graph. Parameters ---------- graph : pybel.struct.BELGraph A PyBEL graph to process Returns ------- bp : PybelProcessor A PybelProcessor object which contains INDRA Statements in bp.sta...
[ "def", "process_pybel_graph", "(", "graph", ")", ":", "bp", "=", "PybelProcessor", "(", "graph", ")", "bp", ".", "get_statements", "(", ")", "if", "bp", ".", "annot_manager", ".", "failures", ":", "logger", ".", "warning", "(", "'missing %d annotation pairs'",...
27.619048
18.47619
def Draw(self, dc): ''' Draw the tree map on the device context. ''' self.hot_map = [] dc.BeginDrawing() brush = wx.Brush( self.BackgroundColour ) dc.SetBackground( brush ) dc.Clear() if self.model: self.max_depth_seen = 0 font = self.Font...
[ "def", "Draw", "(", "self", ",", "dc", ")", ":", "self", ".", "hot_map", "=", "[", "]", "dc", ".", "BeginDrawing", "(", ")", "brush", "=", "wx", ".", "Brush", "(", "self", ".", "BackgroundColour", ")", "dc", ".", "SetBackground", "(", "brush", ")",...
36.4
15.2
def context_processor(self, fn): """ Like :meth:`flask.Blueprint.context_processor` but for a bundle. This function is only executed for requests handled by a bundle. """ self._defer(lambda bp: bp.context_processor(fn)) return fn
[ "def", "context_processor", "(", "self", ",", "fn", ")", ":", "self", ".", "_defer", "(", "lambda", "bp", ":", "bp", ".", "context_processor", "(", "fn", ")", ")", "return", "fn" ]
38.714286
15.857143
def on_exit(self, info): """ Handles the user attempting to exit Godot. """ if self.prompt_on_exit:# and (not is_ok): retval = confirm(parent = info.ui.control, message = "Exit Godot?", title = "Confirm exit", ...
[ "def", "on_exit", "(", "self", ",", "info", ")", ":", "if", "self", ".", "prompt_on_exit", ":", "# and (not is_ok):", "retval", "=", "confirm", "(", "parent", "=", "info", ".", "ui", ".", "control", ",", "message", "=", "\"Exit Godot?\"", ",", "title", "...
38.083333
9.666667
def sh2(cmd): """Execute command in a subshell, return stdout. Stderr is unbuffered from the subshell.x""" p = Popen(cmd, stdout=PIPE, shell=True, env=sub_environment()) out = p.communicate()[0] retcode = p.returncode if retcode: raise CalledProcessError(retcode, cmd) else: ...
[ "def", "sh2", "(", "cmd", ")", ":", "p", "=", "Popen", "(", "cmd", ",", "stdout", "=", "PIPE", ",", "shell", "=", "True", ",", "env", "=", "sub_environment", "(", ")", ")", "out", "=", "p", ".", "communicate", "(", ")", "[", "0", "]", "retcode"...
29.909091
17.636364
def _netapp_login(self): """ Login to our netapp filer """ self.server = NaServer(self.ip, 1, 3) self.server.set_transport_type('HTTPS') self.server.set_style('LOGIN') self.server.set_admin_user(self.netapp_user, self.netapp_password)
[ "def", "_netapp_login", "(", "self", ")", ":", "self", ".", "server", "=", "NaServer", "(", "self", ".", "ip", ",", "1", ",", "3", ")", "self", ".", "server", ".", "set_transport_type", "(", "'HTTPS'", ")", "self", ".", "server", ".", "set_style", "(...
34.5
13
def _parse_from_import_names(self, is_future_import): """Parse the 'y' part in a 'from x import y' statement.""" if self.current.value == "(": self.consume(tk.OP) expected_end_kinds = (tk.OP,) else: expected_end_kinds = (tk.NEWLINE, tk.ENDMARKER) while...
[ "def", "_parse_from_import_names", "(", "self", ",", "is_future_import", ")", ":", "if", "self", ".", "current", ".", "value", "==", "\"(\"", ":", "self", ".", "consume", "(", "tk", ".", "OP", ")", "expected_end_kinds", "=", "(", "tk", ".", "OP", ",", ...
40.394737
13.605263