code
stringlengths
1
18.2k
def ormSessionCreator(self) -> DbSessionCreator: """ Get Orm Session :return: A SQLAlchemy session scoped for the callers thread.. """ assert self._dbConnectString if self._ScopedSession: return self._ScopedSession self._dbEngine = create_engine( self._dbConnectString, **self._dbEngineArgs ) self._ScopedSession = scope...
def migrate(self) -> None: """ Migrate Perform a database migration, upgrading to the latest schema level. """ assert self.ormSessionCreator, "ormSessionCreator is not defined" connection = self._dbEngine.connect() isDbInitialised = self._dbEngine.dialect.has_table( connection, 'alembic_version', schema=self._metadata....
def checkForeignKeys(self, engine: Engine) -> None: """ Check Foreign Keys Log any foreign keys that don't have indexes assigned to them. This is a performance issue. """ missing = (sqlalchemy_utils.functions .non_indexed_foreign_keys(self._metadata, engine=engine)) for table, keys in missing.items(): for key in keys: ...
def prefetchDeclarativeIds(self, Declarative, count) -> DelcarativeIdGen: """ Prefetch Declarative IDs This function prefetches a chunk of IDs from a database sequence. Doing this allows us to preallocate the IDs before an insert, which significantly speeds up : * Orm inserts, especially those using inheritance * When ...
def temporary_tag(tag): """ Temporarily tags the repo """ if tag: CTX.repo.tag(tag) try: yield finally: if tag: CTX.repo.remove_tag(tag)
def _chglog(amend: bool = False, stage: bool = False, next_version: str = None, auto_next_version: bool = False): """ Writes the changelog Args: amend: amend last commit with changes stage: stage changes """ if config.CHANGELOG_DISABLE(): LOGGER.info('skipping changelog update as per config') else: epab.utils.ensure_ex...
def chglog(amend: bool = False, stage: bool = False, next_version: str = None, auto_next_version: bool = False): """ Writes the changelog Args: amend: amend last commit with changes stage: stage changes next_version: indicates next version auto_next_version: infer next version from VCS """ changed_files = CTX.repo.chan...
def check_rev_options(self, rev, dest, rev_options): """Check the revision options before checkout to compensate that tags and branches may need origin/ as a prefix. Returns the SHA1 of the branch or tag if found. """ revisions = self.get_tag_revs(dest) revisions.update(self.get_branch_revs(dest)) origin_rev = 'origin/...
def savejson(filename, datadict): """Save data from a dictionary in JSON format. Note that this only works to the second level of the dictionary with Numpy arrays. """ for key, value in datadict.items(): if type(value) == np.ndarray: datadict[key] = value.tolist() if type(value) == dict: for key2, value2 in value.items...
def loadjson(filename, asnparrays=False): """Load data from text file in JSON format. Numpy arrays are converted if specified with the `asnparrays` keyword argument. Note that this only works to the second level of the dictionary. Returns a single dict. """ with open(filename) as f: data = json.load(f) if asnparrays: f...
def savecsv(filename, datadict, mode="w"): """Save a dictionary of data to CSV.""" if mode == "a" : header = False else: header = True with open(filename, mode) as f: _pd.DataFrame(datadict).to_csv(f, index=False, header=header)
def loadcsv(filename): """Load data from CSV file. Returns a single dict with column names as keys. """ dataframe = _pd.read_csv(filename) data = {} for key, value in dataframe.items(): data[key] = value.values return data
def savehdf(filename, datadict, groupname="data", mode="a", metadata=None, as_dataframe=False, append=False): """Save a dictionary of arrays to file--similar to how `scipy.io.savemat` works. If `datadict` is a DataFrame, it will be converted automatically. """ if as_dataframe: df = _pd.DataFrame(datadict) df.to_hdf(fil...
def loadhdf(filename, groupname="data", to_dataframe=False): """Load all data from top level of HDF5 file--similar to how `scipy.io.loadmat` works. """ data = {} with _h5py.File(filename, "r") as f: for key, value in f[groupname].items(): data[key] = np.array(value) if to_dataframe: return _pd.DataFrame(data) else: ret...
def save_hdf_metadata(filename, metadata, groupname="data", mode="a"): """"Save a dictionary of metadata to a group's attrs.""" with _h5py.File(filename, mode) as f: for key, val in metadata.items(): f[groupname].attrs[key] = val
def load_hdf_metadata(filename, groupname="data"): """"Load attrs of the desired group into a dictionary.""" with _h5py.File(filename, "r") as f: data = dict(f[groupname].attrs) return data
def authenticate(user=None): # noqa: E501 """Authenticate Authenticate with the API # noqa: E501 :param user: The user authentication object. :type user: dict | bytes :rtype: AuthResponse """ if connexion.request.is_json: user = UserAuth.from_dict(connexion.request.get_json()) # noqa: E501 return 'do some magic!'
def get_param_doc(doc, param): """Get the documentation and datatype for a parameter This function returns the documentation and the argument for a napoleon like structured docstring `doc` Parameters ---------- doc: str The base docstring to use param: str The argument to use Returns ------- str The documentation of th...
def setup_args(self, func=None, setup_as=None, insert_at=None, interprete=True, epilog_sections=None, overwrite=False, append_epilog=True): """ Add the parameters from the given `func` to the parameter settings Parameters ---------- func: function The function to use. If None, a function will be returned that can be us...
None, the :attr:`epilog_sections` attribute is used overwrite: bool If True, overwrite the existing epilog and the existing description of the parser append_epilog: bool If True, append to the existing epilog Returns ------- function Either the function that can be used as a decorator (if `func` is ``None``), or the gi...
>>> parser.parse2func('-a 2'.split()) 3 References ---------- .. [interpretation-docs] http://funcargparse.readthedocs.io/en/latest/docstring_interpretation.html) """ def setup(func): # insert the function if insert_at is None: self._used_functions.append(func) else: self._used_functions.insert(insert_at, func) args_di...
'-'), 'long': arg.replace('_', '-')} if arg_doc: d['help'] = arg_doc if i >= default_min: d['default'] = defaults[i - default_min] else: d['positional'] = True if interprete and dtype == 'bool' and 'default' in d: d['action'] = 'store_false' if d['default'] else \ 'store_true' elif interprete and dtype: if dtype.starts...
def add_subparsers(self, *args, **kwargs): """ Add subparsers to this parser Parameters ---------- ``*args, **kwargs`` As specified by the original :meth:`argparse.ArgumentParser.add_subparsers` method chain: bool Default: False. If True, It is enabled to chain subparsers""" chain = kwargs.pop('chain', None) ret = supe...
def setup_subparser( self, func=None, setup_as=None, insert_at=None, interprete=True, epilog_sections=None, overwrite=False, append_epilog=True, return_parser=False, name=None, **kwargs): """ Create a subparser with the name of the given function Parameters are the same as for the :meth:`setup_args` function, other par...
as a decorator:: >>> from funcargparser import FuncArgParser >>> parser = FuncArgParser() >>> @parser.setup_subparser ... def my_func(my_argument=None): ... pass >>> args = parser.parse_args('my-func -my-argument 1'.split()) """ def setup(func): if self._subparsers_action is None: raise RuntimeError( "No subparsers hav...
def update_arg(self, arg, if_existent=None, **kwargs): """ Update the `add_argument` data for the given parameter Parameters ---------- arg: str The name of the function argument if_existent: bool or None If True, the argument is updated. If None (default), the argument is only updated, if it exists. Otherwise, if Fals...
def _get_corresponding_parsers(self, func): """Get the parser that has been set up by the given `function`""" if func in self._used_functions: yield self if self._subparsers_action is not None: for parser in self._subparsers_action.choices.values(): for sp in parser._get_corresponding_parsers(func): yield sp
def pop_key(self, arg, key, *args, **kwargs): """Delete a previously defined key for the `add_argument` """ return self.unfinished_arguments[arg].pop(key, *args, **kwargs)
def create_arguments(self, subparsers=False): """Create and add the arguments Parameters ---------- subparsers: bool If True, the arguments of the subparsers are also created""" ret = [] if not self._finalized: for arg, d in self.unfinished_arguments.items(): try: not_positional = int(not d.pop('positional', False)) sh...
else: raise ValueError('Parser has already been finalized!') self._finalized = True if subparsers and self._subparsers_action is not None: for parser in self._subparsers_action.choices.values(): parser.create_arguments(True) return ret
def format_epilog_section(self, section, text): """Format a section for the epilog by inserting a format""" try: func = self._epilog_formatters[self.epilog_formatter] except KeyError: if not callable(self.epilog_formatter): raise func = self.epilog_formatter return func(section, text)
def extract_as_epilog(self, text, sections=None, overwrite=False, append=True): """Extract epilog sections from the a docstring Parameters ---------- text The docstring to use sections: list of str The headers of the sections to extract. If None, the :attr:`epilog_sections` attribute is used overwrite: bool If True, ov...
def grouparg(self, arg, my_arg=None, parent_cmds=[]): """ Grouper function for chaining subcommands Parameters ---------- arg: str The current command line argument that is parsed my_arg: str The name of this subparser. If None, this parser is the main parser and has no parent parser parent_cmds: list of str The availa...
we are in or the # name of the subparser itself ret = currentarg or my_arg if currentarg is not None: # if we are already in a sub command, we use the sub parser sp_key = commands[currentarg].grouparg(arg, currentarg, chain( commands, parent_cmds)) if sp_key is None and arg in commands: # if the subparser did not recog...
subparser and this parser can ignore it ret = None else: # otherwise the command belongs to this subparser (if this one # is not the subparser) or the current subparser ret = my_arg or currentarg elif arg in commands: # if the argument is a valid subparser, we return this one self.__currentarg = arg ret = arg elif arg ...
def __parse_main(self, args): """Parse the main arguments only. This is a work around for python 2.7 because argparse does not allow to parse arguments without subparsers """ if six.PY2: self._subparsers_action.add_parser("__dummy") return super(FuncArgParser, self).parse_known_args( list(args) + ['__dummy']) return su...
def update_short(self, **kwargs): """ Update the short optional arguments (those with one leading '-') This method updates the short argument name for the specified function arguments as stored in :attr:`unfinished_arguments` Parameters ---------- ``**kwargs`` Keywords must be keys in the :attr:`unfinished_arguments` d...
def update_long(self, **kwargs): """ Update the long optional arguments (those with two leading '-') This method updates the short argument name for the specified function arguments as stored in :attr:`unfinished_arguments` Parameters ---------- ``**kwargs`` Keywords must be keys in the :attr:`unfinished_arguments` dic...
def parse2func(self, args=None, func=None): """Parse the command line arguments to the setup function This method parses the given command line arguments to the function used in the :meth:`setup_args` method to setup up this parser Parameters ---------- args: list The list of command line arguments func: function An al...
def parse_known2func(self, args=None, func=None): """Parse the command line arguments to the setup function This method parses the given command line arguments to the function used in the :meth:`setup_args` method to setup up this parser Parameters ---------- args: list The list of command line arguments func: function...
def parse_chained(self, args=None): """ Parse the argument directly to the function used for setup This function parses the command line arguments to the function that has been used for the :meth:`setup_args`. Parameters ---------- args: list The arguments parsed to the :meth:`parse_args` function Returns ------- argpa...
def parse_known_chained(self, args=None): """ Parse the argument directly to the function used for setup This function parses the command line arguments to the function that has been used for the :meth:`setup_args` method. Parameters ---------- args: list The arguments parsed to the :meth:`parse_args` function Returns ...
def _parse2subparser_funcs(self, kws): """ Recursive function to parse arguments to chained parsers """ choices = getattr(self._subparsers_action, 'choices', {}) replaced = {key.replace('-', '_'): key for key in choices} sp_commands = set(replaced).intersection(kws) if not sp_commands: if self._setup_as is not None: fu...
def get_subparser(self, name): """ Convenience method to get a certain subparser Parameters ---------- name: str The name of the subparser Returns ------- FuncArgParser The subparsers corresponding to `name` """ if self._subparsers_action is None: raise ValueError("%s has no subparsers defined!" % self) return self._su...
def parse_file(src): """ find file in config and output to dest dir """ #clear the stack between parses if config.dest_dir == None: dest = src.dir else: dest = config.dest_dir output = get_output(src) output_file = dest + '/' + src.basename + '.min.js' f = open(output_file,'w') f.write(jsmin.jsmin(output)) f.close() pr...
def get_output(src): """ parse lines looking for commands """ output = '' lines = open(src.path, 'rU').readlines() for line in lines: m = re.match(config.import_regex,line) if m: include_path = os.path.abspath(src.dir + '/' + m.group('script')); if include_path not in config.sources: script = Script(include_path) scrip...
def get_signed_raw_revocation_document(identity: Identity, salt: str, password: str) -> str: """ Generate account revocation document for given identity :param identity: Self Certification of the identity :param salt: Salt :param password: Password :rtype: str """ revocation = Revocation(PROTOCOL_VERSION, identity.curr...
async def main(): """ Main code """ # Create Client from endpoint string in Duniter format client = Client(BMAS_ENDPOINT) # Get the node summary infos to test the connection response = await client(bma.node.summary) print(response) # prompt hidden user entry salt = getpass.getpass("Enter your passphrase (salt): ") # pr...
document in a file fp = open(REVOCATION_DOCUMENT_FILE_PATH, 'w') fp.write(revocation_signed_raw_document) fp.close() # document saved print("Revocation document saved in %s" % REVOCATION_DOCUMENT_FILE_PATH) # Close client aiohttp session await client.close()
def align_epi(anatomy,epis,suffix='_al',base=3,skull_strip=True): '''[[currently in progress]]: a simple replacement for the ``align_epi_anat.py`` script, because I've found it to be unreliable, in my usage''' for epi in epis: nl.tshift(epi,suffix='_tshift') nl.affine_align(nl.suffix(epi,'_tshift'),'%s[%d]'%(epis[0],ba...
def motion_from_params(param_file,motion_file,individual=True,rms=True): '''calculate a motion regressor from the params file given by 3dAllineate Basically just calculates the rms change in the translation and rotation components. Returns the 6 motion vector (if ``individual`` is ``True``) and the RMS difference (if `...
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 ignoring that many images, if ``None`` then don't ts...
def affine_align(dset_from,dset_to,skull_strip=True,mask=None,suffix='_aff',prefix=None,cost=None,epi=False,resample='wsinc5',grid_size=None,opts=[]): ''' interface to 3dAllineate to align anatomies and EPIs ''' dset_ss = lambda dset: os.path.split(nl.suffix(dset,'_ns'))[1] def dset_source(dset): if skull_strip==True o...
'-autoweight', '-final',resample, '-cmass' ] + opts if grid_size: all_cmd += ['-newgrid',grid_size] if cost: all_cmd += ['-cost',cost] if epi: all_cmd += ['-EPI'] if mask: all_cmd += ['-emask', mask_use] nl.run(all_cmd,products=dset_affine)
def affine_apply(dset_from,affine_1D,master,affine_suffix='_aff',interp='NN',inverse=False,prefix=None): '''apply the 1D file from a previously aligned dataset Applies the matrix in ``affine_1D`` to ``dset_from`` and makes the final grid look like the dataset ``master`` using the interpolation method ``interp``. If ``i...
def convert_coord(coord_from,matrix_file,base_to_aligned=True): '''Takes an XYZ array (in DICOM coordinates) and uses the matrix file produced by 3dAllineate to transform it. By default, the 3dAllineate matrix transforms from base to aligned space; to get the inverse transform set ``base_to_aligned`` to ``False``''' wi...
def qwarp_align(dset_from,dset_to,skull_strip=True,mask=None,affine_suffix='_aff',suffix='_qwarp',prefix=None): '''aligns ``dset_from`` to ``dset_to`` using 3dQwarp Will run ``3dSkullStrip`` (unless ``skull_strip`` is ``False``), ``3dUnifize``, ``3dAllineate``, and then ``3dQwarp``. This method will add suffixes to the...
also be resampled to match the ``dset_to`` grid. :affine_suffix: Suffix applied to ``dset_from`` to name the new dataset, as well as the ``.1D`` file. :suffix: Suffix applied to the final ``dset_from`` dataset. An additional file with the additional suffix ``_WARP`` will be created containing the parameters (e.g., with...
+tlrc datasets because the filenames get mangled ''' dset_ss = lambda dset: os.path.split(nl.suffix(dset,'_ns'))[1] dset_u = lambda dset: os.path.split(nl.suffix(dset,'_u'))[1] def dset_source(dset): if skull_strip==True or skull_strip==dset: return dset_ss(dset) else: return dset dset_affine = os.path.split(nl.suffix(...
'-base', dset_u(dset_source(dset_to)), '-source', dset_affine ] if mask: warp_cmd += ['-emask', mask_use] nl.run(warp_cmd,products=dset_qwarp)
def qwarp_apply(dset_from,dset_warp,affine=None,warp_suffix='_warp',master='WARP',interp=None,prefix=None): '''applies the transform from a previous qwarp Uses the warp parameters from the dataset listed in ``dset_warp`` (usually the dataset name ends in ``_WARP``) to the dataset ``dset_from``. If a ``.1D`` file is giv...
warp_opt] cmd += [ '-source', dset_from, '-master',master, '-prefix', out_dset ] if interp: cmd += ['-interp',interp] nl.run(cmd,products=out_dset)
def qwarp_invert(warp_param_dset,output_dset,affine_1Dfile=None): '''inverts a qwarp (defined in ``warp_param_dset``) (and concatenates affine matrix ``affine_1Dfile`` if given) outputs the inverted warp + affine to ``output_dset``''' cmd = ['3dNwarpCat','-prefix',output_dset] if affine_1Dfile: cmd += ['-warp1','INV(%s...
def qwarp_epi(dset,align_subbrick=5,suffix='_qwal',prefix=None): '''aligns an EPI time-series using 3dQwarp Very expensive and not efficient at all, but it can produce pretty impressive alignment for EPI time-series with significant distortions due to motion''' info = nl.dset_info(dset) if info==None: nl.notify('Error ...
try: os.remove(nl.suffix(dset_sub(i),suffix)) except: pass
def align_epi_anat(anatomy,epi_dsets,skull_strip_anat=True): ''' aligns epis to anatomy using ``align_epi_anat.py`` script :epi_dsets: can be either a string or list of strings of the epi child datasets :skull_strip_anat: if ``True``, ``anatomy`` will be skull-stripped using the default method The default output suffix...
epi_dsets_use[0]] if len(epi_dsets_use)>1: cmd += ['-child_epi'] + epi_dsets_use[1:] out = nl.run(cmd) for dset in epi_dsets: if nl.is_nifti(dset): dset_nifti = nl.nifti_copy(nl.prefix(dset)+'_al+orig') if dset_nifti and os.path.exists(dset_nifti) and dset_nifti.endswith('.nii') and dset.endswith('.gz'): nl.run(['gzip'...
def skullstrip_template(dset,template,prefix=None,suffix=None,dilate=0): '''Takes the raw anatomy ``dset``, aligns it to a template brain, and applies a templated skullstrip. Should produce fairly reliable skullstrips as long as there is a decent amount of normal brain and the overall shape of the brain is normal-ish''...
def printmp(msg): """Print temporarily, until next print overrides it. """ filler = (80 - len(msg)) * ' ' print(msg + filler, end='\r') sys.stdout.flush()
def contacts(github, logins): """Extract public contact info from users. """ printmp('Fetching contacts') users = [github.user(login).as_dict() for login in logins] mails = set() blogs = set() for user in users: contact = user.get('name', 'login') if user['email']: contact += ' <%s>' % user['email'] mails.add(contact) ...
def extract_mail(issues): """Extract mails that sometimes leak from issue comments. """ contacts = set() for idx, issue in enumerate(issues): printmp('Fetching issue #%s' % idx) for comment in issue.comments(): comm = comment.as_dict() emails = list(email[0] for email in re.findall(MAIL_REGEX, comm['body']) if not emai...
def fetch_logins(roles, repo): """Fetch logins for users with given roles. """ users = set() if 'stargazer' in roles: printmp('Fetching stargazers') users |= set(repo.stargazers()) if 'collaborator' in roles: printmp('Fetching collaborators') users |= set(repo.collaborators()) if 'issue' in roles: printmp('Fetching iss...
def high_cli(repo_name, login, with_blog, as_list, role): """Extract mails from stargazers, collaborators and people involved with issues of given repository. """ passw = getpass.getpass() github = gh_login(login, passw) repo = github.repository(login, repo_name) role = [ROLES[k] for k in role] users = fetch_logins(rol...
def __callback(self, data): """ Safely calls back a method :param data: Associated stanza """ method = self.__cb_message if method is not None: try: method(data) except Exception as ex: _logger.exception("Error calling method: %s", ex)
def __on_message(self, msg): """ XMPP message received """ msgtype = msg['type'] msgfrom = msg['from'] if msgtype == 'groupchat': # MUC Room chat if self._nick == msgfrom.resource: # Loopback message return elif msgtype not in ('normal', 'chat'): # Ignore non-chat messages return # Callback self.__callback(msg)
def freeze(ctx, version: str, clean: bool): """ Freeze current package into a single file """ if clean: _clean_spec() ctx.invoke(epab.cmd.compile_qt_resources) _freeze(version)
def setupz(Np: int, zmin: float, gridmin: float, gridmax: float) -> np.ndarray: """ np: number of grid points zmin: minimum STEP SIZE at minimum grid altitude [km] gridmin: minimum altitude of grid [km] gridmax: maximum altitude of grid [km] """ dz = _ztanh(Np, gridmin, gridmax) return np.insert(np.cumsum(dz)+zmin, 0, ...
def _ztanh(Np: int, gridmin: float, gridmax: float) -> np.ndarray: """ typically call via setupz instead """ x0 = np.linspace(0, 3.14, Np) # arbitrarily picking 3.14 as where tanh gets to 99% of asymptote return np.tanh(x0)*gridmax+gridmin
def get(self, name): """Returns a Notification by name. """ if not self.loaded: raise RegistryNotLoaded(self) if not self._registry.get(name): raise NotificationNotRegistered( f"Notification not registered. Got '{name}'." ) return self._registry.get(name)
def register(self, notification_cls=None): """Registers a Notification class unique by name. """ self.loaded = True display_names = [n.display_name for n in self.registry.values()] if ( notification_cls.name not in self.registry and notification_cls.display_name not in display_names ): self.registry.update({notificatio...
def notify(self, instance=None, **kwargs): """A wrapper to call notification.notify for each notification class associated with the given model instance. Returns a dictionary of {notification.name: model, ...} including only notifications sent. """ notified = {} for notification_cls in self.registry.values(): notificat...
def update_notification_list(self, apps=None, schema_editor=None, verbose=False): """Updates the notification model to ensure all registered notifications classes are listed. Typically called from a post_migrate signal. Also, in tests you can register a notification and the Notification class (not model) will automatic...
def delete_unregistered_notifications(self, apps=None): """Delete orphaned notification model instances. """ Notification = (apps or django_apps).get_model("edc_notification.notification") return Notification.objects.exclude( name__in=[n.name for n in site_notifications.registry.values()] ).delete()
def create_mailing_lists(self, verbose=True): """Creates the mailing list for each registered notification. """ responses = {} if ( settings.EMAIL_ENABLED and self.loaded and settings.EMAIL_BACKEND != "django.core.mail.backends.locmem.EmailBackend" ): sys.stdout.write(style.MIGRATE_HEADING(f"Creating mailing lists:\n")...
def autodiscover(self, module_name=None, verbose=False): """Autodiscovers classes in the notifications.py file of any INSTALLED_APP. """ module_name = module_name or "notifications" verbose = True if verbose is None else verbose sys.stdout.write(f" * checking for {module_name} ...\n") for app in django_apps.app_configs...
def add_package(self, package): """ Add a package to this project """ self._data.setdefault('packages', {}) self._data['packages'][package.name] = package.source for package in package.deploy_packages: self.add_package(package) self._save()
def copy(string, cmd=copy_cmd, stdin=PIPE): """Copy given string into system clipboard. """ Popen(cmd, stdin=stdin).communicate(string.encode('utf-8'))
def paste(cmd=paste_cmd, stdout=PIPE): """Returns system clipboard contents. """ return Popen(cmd, stdout=stdout).communicate()[0].decode('utf-8')
def umap(path, name=None, include=None, namespace=None, priority=None): """ Maps a given URL path, name and namespace to a view. Arguments: - path: the URL regex, e.g.: '^teste/(?P<pk>[0-9])/$'. Optional arguments: - name: the URL name, which Django uses to identify the URL; - include: A custom URL list, previously set...
x for x in base if getattr(x, 'namespace', None) == namespace ] # if the list length is different than 1, # then the namespace is either duplicated or doesn't exist if len(urlpatterns_list) != 1: raise ValueError( 'Namespace \'{}\' not in list.'.format(namespace) ) # if the namespace was found, get its object urlpatter...
def touch(): """ Create a .vacationrc file if none exists. """ if not os.path.isfile(get_rc_path()): open(get_rc_path(), 'a').close() print('Created file: {}'.format(get_rc_path()))
def write(entries): """ Write an entire rc file. """ try: with open(get_rc_path(), 'w') as rc: rc.writelines(entries) except IOError: print('Error writing your ~/.vacationrc file!')
def append(entry): """ Append either a list of strings or a string to our file. """ if not entry: return try: with open(get_rc_path(), 'a') as f: if isinstance(entry, list): f.writelines(entry) else: f.write(entry + '\n') except IOError: print('Error writing your ~/.vacationrc file!')
def delete(bad_entry): """ Removes an entry from rc file. """ entries = read() kept_entries = [x for x in entries if x.rstrip() != bad_entry] write(kept_entries)
def normalize(text, variant=VARIANT1, case_sensitive=False): """Create a normalized version of `text`. With `variant` set to ``VARIANT1`` (default), german umlauts are transformed to plain chars: ``ä`` -> ``a``, ``ö`` -> ``o``, ...:: >>> print(normalize("mäßig")) massig With `variant` set to ``VARIANT2``, german umlaut...
def sort_func(variant=VARIANT1, case_sensitive=False): """A function generator that can be used for sorting. All keywords are passed to `normalize()` and generate keywords that can be passed to `sorted()`:: >>> key = sort_func() >>> print(sorted(["fur", "far"], key=key)) [u'far', u'fur'] Please note, that `sort_func` r...
def fetcher(date=datetime.today(), url_pattern=URL_PATTERN): """ Fetch json data from n.pl Args: date (date) - default today url_patter (string) - default URL_PATTERN Returns: dict - data from api """ api_url = url_pattern % date.strftime('%Y-%m-%d') headers = {'Referer': 'http://n.pl/program-tv'} raw_result = requests...
def result_to_dict(raw_result): """ Parse raw result from fetcher into readable dictionary Args: raw_result (dict) - raw data from `fetcher` Returns: dict - readable dictionary """ result = {} for channel_index, channel in enumerate(raw_result): channel_id, channel_name = channel[0], channel[1] channel_result = { 'id':...
def waitForCompletion (self): """Wait for all threads to complete their work The worker threads are told to quit when they receive a task that is a tuple of (None, None). This routine puts as many of those tuples in the task queue as there are threads. As soon as a thread receives one of these tuples, it dies. """ for ...
def run(self): """The main routine for a thread's work. The thread pulls tasks from the manager's task queue and executes them until it encounters a task with a function that is None. """ try: while True: aFunction, arguments = self.manager.taskQueue.get() if aFunction is None: break aFunction(arguments) except Keyboar...