code stringlengths 1 18.2k |
|---|
def Eg(self, **kwargs): ''' Returns the strain-shifted bandgap, ``Eg``. ''' return self.unstrained.Eg(**kwargs) + self.Eg_strain_shift(**kwargs) |
def tokens(self): """ `generator` : the tokens in this segment """ for subsegment_or_token in self: if isinstance(subsegment_or_token, Segment): subsegment = subsegment_or_token for token in subsegment.tokens(): yield token else: token = subsegment_or_token yield token |
def _api_on_write_error(self, status_code, **kwargs): """ Catches errors and renders it as a JSON message. Adds the traceback if debug is enabled. """ return_error = { "code": self.get_status() } exc_info = kwargs.get("exc_info") if exc_info and isinstance(exc_info[1], oz.json_api.ApiError): return_error["error"] = exc... |
def respond(self, obj): """Gives a response JSON(P) message""" # Get the callback argument if JSONP is allowed callback = self.get_argument("callback", None) if oz.settings["allow_jsonp"] else None # We're pretty strict with what callback names are allowed, just in case if callback and not CALLBACK_VALIDATOR.match(call... |
def body(self): """Gets the JSON body of the request""" if self._decoded_body == None: # Try to decode the JSON body. But raise an error if the # content-type is unexpected, or the JSON is invalid. raw_content_type = self.request.headers.get("content-type") or "" content_type = raw_content_type.split(";")[0].strip().lo... |
def _get_id(self): """Construct and return the identifier""" return ''.join(map(str, filter(is_not_None, [self.Prefix, self.Name]))) |
def on(self, val=None): """Turns the MixedParameter ON by setting its Value to val An attempt to turn the parameter on with value 'False' will result in an error, since this is the same as turning the parameter off. Turning the MixedParameter ON without a value or with value 'None' will let the parameter behave as a fl... |
def get_assets(self): ''' Return a flat list of absolute paths to all assets required by this viewer ''' return sum([ [self.prefix_asset(viewer, relpath) for relpath in viewer.assets] for viewer in self.viewers ], []) |
def get_resource(self): ''' Returns a BytesResource to build the viewers JavaScript ''' # Basename could be used for controlling caching # basename = 'viewers_%s' % settings.get_cache_string() node_packages = self.get_node_packages() # sort_keys is essential to ensure resulting string is # deterministic (and thus hasha... |
def main(): """Run the core.""" parser = ArgumentParser() subs = parser.add_subparsers(dest='cmd') setup_parser = subs.add_parser('search') setup_parser.add_argument('-e', '--engine', dest='engine', required=True, help='Search engine to use.', choices=['bing']) setup_parser.add_argument('-d', '--domain', dest='domain',... |
job['project'].upper()) print("\t[*] Engine: %s" % job['engine']) print("\t[*] Domain: %s" % job['domain']) print("\t[*] Modifer: %s" % job['modifier']) print("\t[*] Limit: %d" % job['limit']) print("\t[*] Duration: %s seconds" % job['duration']) print("\n-= Email Results=-") for email in job['results']['emails']: prin... |
def callback(request): """Callback URL for Nexmo.""" message_id = request.GET.get('messageId') status_id = request.GET.get('status') status_msg = NEXMO_STATUSES.get(status_id, UNKNOWN_STATUS) error_id = int(request.GET.get('err-code')) error_msg = NEXMO_MESSAGES.get(error_id, UNKNOWN_MESSAGE) logger.info(u'Nexmo callba... |
def get_hmac_sha1_digest(secret, resource_url, target_type, api_key=None): ''' Utilize hmac module to hash a secret, a string specifying a resource URL, and a string specifying a target type into a (string) hex digest. ''' # Normalize and sanitize input resource URL and target type, and then # convert to bytes target_t... |
def init(provider=None): """ Runs through a questionnaire to set up your project's deploy settings """ if os.path.exists(DEPLOY_YAML): _yellow("\nIt looks like you've already gone through the questionnaire.") cont = prompt("Do you want to go through it again and overwrite the current one?", default="No") if cont.strip(... |
that the file exists # parse the requirements file and warn the user about best practices: # Django==1.4.1 # psycopg2 if they selected PostgreSQL # MySQL-python if they selected MySQL # South for database migrations # dj-database-url pyversion = prompt("* What version of Python does your app need?", default="Python2.7"... |
What's the full instance ID of your Cloud SQL instance\n" "(should be in format \"projectid:instanceid\" found at https://code.google.com/apis/console/)?", validate=r'.+:.+') databasename = prompt("* What's your database name?", validate=r'.+') sdk_location = prompt("* Where is your Google App Engine SDK location?", de... |
password is valid # TODO: let the user choose the admin username instead of hardcoding it to 'admin' admin_password = prompt("* What do you want to set as the admin password?", validate=_validate_admin_password ) import random SECRET_KEY = ''.join([random.SystemRandom().choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%... |
def setup(provider=None): """ Creates the provider config files needed to deploy your project """ site = init(provider) if not site: site = yaml.safe_load(_read_file(DEPLOY_YAML)) provider_class = PROVIDERS[site['provider']] provider_class.init(site) |
def deploy(provider=None): """ Deploys your project """ if os.path.exists(DEPLOY_YAML): site = yaml.safe_load(_read_file(DEPLOY_YAML)) provider_class = PROVIDERS[site['provider']] provider_class.deploy() |
def ida_connect(host='localhost', port=18861, retry=10): """ Connect to an instance of IDA running our server.py. :param host: The host to connect to :param port: The port to connect to :param retry: How many times to try after errors before giving up """ for i in range(retry): try: LOG.debug('Connectint to %s:%d, try ... |
def ida_spawn(ida_binary, filename, port=18861, mode='oneshot', processor_type=None, logfile=None): """ Open IDA on the the file we want to analyse. :param ida_binary: The binary name or path to ida :param filename: The filename to open in IDA :param port: The port on which to serve rpc from ida :param mode: The server... |
% mode) if logfile is None: logfile = LOGFILE.format(port=port) ida_realpath = os.path.expanduser(ida_progname) file_realpath = os.path.realpath(os.path.expanduser(filename)) server_script = os.path.join(MODULE_DIR, 'server.py') LOG.info('Launching IDA (%s) on %s, listening on port %d, logging to %s', ida_realpath, fil... |
to our logfile # -p Set the processor type command = [ ida_realpath, '-A', '-S%s %d %s' % (server_script, port, mode), '-L%s' % logfile, ] if processor_type is not None: command.append('-p%s' % processor_type) command.append(file_realpath) LOG.debug('IDA command is %s', ' '.join("%s" % s for s in command)) return subpr... |
def _clear_cache(url, ts=None): ''' Helper function used by precache and clearcache that clears the cache of a given URL and type ''' if ts is None: # Clears an entire ForeignResource cache res = ForeignResource(url) if not os.path.exists(res.cache_path_base): cli.printerr('%s is not cached (looked at %s)' % (url, res.... |
async def _precache(url, to_type, force=False): ''' Helper function used by precache and precache-named which does the actual precaching ''' if force: cli.print('%s: force clearing' % url) _clear_cache(url) cli.print('%s: precaching "%s"' % (url, to_type)) with autodrain_worker(): await singletons.workers.async_enqueue... |
def expect_exact(self, *args, **kwargs): """This does not attempt to duplicate the expect_exact API, but just sets self.before to the latest response line.""" response = self._recvline() self.before = response.strip() |
def forwards(self, orm): "Write your forwards methods here." for category in orm['document_library.DocumentCategory'].objects.all(): for trans_old in orm['document_library.DocumentCategoryTitle'].objects.filter(category=category): orm['document_library.DocumentCategoryTranslation'].objects.create( master=category, lang... |
def cache_busting_scan(*prefixes): """ (Re-)generates the cache buster values for all files with the specified prefixes. """ redis = oz.redis.create_connection() pipe = redis.pipeline() # Get all items that match any of the patterns. Put it in a set to # prevent duplicates. if oz.settings["s3_bucket"]: bucket = oz.aws_... |
def create_bwa_index_from_fasta_file(fasta_in, params=None): """Create a BWA index from an input fasta file. fasta_in: the input fasta file from which to create the index params: dict of bwa index specific paramters This method returns a dictionary where the keys are the various output suffixes (.amb, .ann, .bwt, .pac,... |
def assign_reads_to_database(query, database_fasta, out_path, params=None): """Assign a set of query sequences to a reference database database_fasta_fp: absolute file path to the reference database query_fasta_fp: absolute file path to query sequences output_fp: absolute file path of the file to be output params: dict... |
dict of params for the bwa aln subcommand * if a temporary directory is not specified in params using dict key "temp_dir", it will be assumed to be /tmp This method returns an open file object (SAM format). """ if params is None: params = {} # set the output path params['-f'] = out_path # if the algorithm is not specif... |
'/tmp' # if the algorithm is bwa-short, we must build use bwa aln to get an sai # file before calling bwa samse on that sai file, so we need to know how # to run bwa aln. Therefore, we must ensure there's an entry containing # those parameters if params['algorithm'] == 'bwa-short': if 'aln_params' not in params: raise ... |
these addendums subcommand_params = {} for k, v in params.iteritems(): if k not in ('algorithm', 'temp_dir', 'aln_params'): subcommand_params[k] = v # build index from database_fasta # get a temporary file name that is not in use _, index_prefix = mkstemp(dir=params['temp_dir'], suffix='') create_bwa_index_from_fasta_f... |
the sai file sai_file_path = bwa_aln(aln_files)['output'].name # we will use that sai file to run samse bwa = BWA_samse(params=subcommand_params) files = {'prefix': index_prefix, 'sai_in': sai_file_path, 'fastq_in': query} # run which ever app controller we decided was correct on the files # we set up result = bwa(file... |
def assign_dna_reads_to_dna_database(query_fasta_fp, database_fasta_fp, out_fp, params={}): """Wraps assign_reads_to_database, setting various parameters. The default settings are below, but may be overwritten and/or added to using the params dict: algorithm: bwasw """ my_params = {'algorithm': 'bwasw'} my_params.updat... |
def check_arguments(self): """Sanity check the arguments passed in. Uses the boolean functions specified in the subclasses in the _valid_arguments dictionary to determine if an argument is valid or invalid. """ for k, v in self.Parameters.iteritems(): if self.Parameters[k].isOn(): if k in self._valid_arguments: if not ... |
def _get_base_command(self): """ Returns the full command string Overridden here because there are positional arguments (specifically the input and output files). """ command_parts = [] # Append a change directory to the beginning of the command to change # to self.WorkingDir before running the command # WorkingDir sho... |
parameters = sorted([str(x) for x in self.Parameters.values() if str(x)]) synonyms = self._synonyms command_parts.append(cd_command) command_parts.append(command) # add in subcommand command_parts.append(subcommand) command_parts += parameters # add in the positional arguments in the correct order for k in self._input_... |
def _input_as_dict(self, data): """Takes dictionary that sets input and output files. Valid keys for the dictionary are specified in the subclasses. File paths must be absolute. """ # clear self._input; ready to receive new input and output files self._input = {} # Check that the arguments to the # subcommand-specific ... |
= "Invalid input arguments (%s)\n" % k error_message += "Valid keys are: %s" % repr(self._input_order) raise InvalidArgumentApplicationError(error_message + '\n') # check for absolute paths if not isabs(data[k][0]): raise InvalidArgumentApplicationError("Only absolute paths " "allowed.\n%s" % repr(data)) self._input[k]... |
def _get_result_paths(self, data): """Gets the results for a run of bwa index. bwa index outputs 5 files when the index is created. The filename prefix will be the same as the input fasta, unless overridden with the -p option, and the 5 extensions are listed below: .amb .ann .bwt .pac .sa and these extentions (includin... |
out_files |
def get_all_paths_from(self, start, seen=None): ''' Return a list of all paths to all nodes from a given start node ''' if seen is None: seen = frozenset() results = [(0, (start, ))] if start in seen or start not in self.edges: return results seen = seen | frozenset((start,)) for node, edge_weight in self.edges[start].... |
def apply(operations, a_tokens, b_tokens): """ Applies a sequences of operations to tokens -- copies tokens from `a_tokens` and `b_tokens` according to `operations`. :Parameters: operations : sequence of :~class:`deltas.Operation` Operations to perform a_tokens : list of `comparable` Starting sequence of comparable tok... |
def create_job(cpu_width, time_height): """ :param cpu_width: number of cpus :param time_height: amount of time :return: the instantiated JobBlock object """ shell_command = stress_string.format(cpu_width, time_height) job = JobBlock(cpu_width, time_height) job.set_job(subprocess.call, shell_command, shell=True) return... |
def cmbuild_from_alignment(aln, structure_string, refine=False, \ return_alignment=False,params=None): """Uses cmbuild to build a CM file given an alignment and structure string. - aln: an Alignment object or something that can be used to construct one. All sequences must be the same length. - structure_string: vienna ... |
= Alignment(aln) if len(structure_string) != aln.SeqLen: raise ValueError, """Structure string is not same length as alignment. Structure string is %s long. Alignment is %s long."""%(len(structure_string),\ aln.SeqLen) else: struct_dict = {'SS_cons':structure_string} #Make new Cmbuild app instance. app = Cmbuild(InputH... |
def cmbuild_from_file(stockholm_file_path, refine=False,return_alignment=False,\ params=None): """Uses cmbuild to build a CM file given a stockholm file. - stockholm_file_path: a path to a stockholm file. This file should contain a multiple sequence alignment formated in Stockholm format. This must contain a sequence s... |
def cmalign_from_alignment(aln, structure_string, seqs, moltype=DNA,\ include_aln=True,refine=False, return_stdout=False,params=None,\ cmbuild_params=None): """Uses cmbuild to build a CM file, then cmalign to build an alignment. - aln: an Alignment object or something that can be used to construct one. All sequences mu... |
to return standard output from infernal. This includes alignment and structure bit scores and average probabilities for each sequence. (Default=False) """ #NOTE: Must degap seqs or Infernal well seg fault! seqs = SequenceCollection(seqs,MolType=moltype).degap() #Create mapping between abbreviated IDs and full IDs int_m... |
seq_constructor=SEQ_CONSTRUCTOR_MAP[moltype]))[0] #Make new dict mapping original IDs new_alignment={} for k,v in aligned.NamedSeqs.items(): new_alignment[int_keys.get(k,k)]=v #Create an Alignment object from alignment dict new_alignment = Alignment(new_alignment,MolType=moltype) std_out = res['StdOut'].read() #clean u... |
def cmalign_from_file(cm_file_path, seqs, moltype=DNA, alignment_file_path=None,\ include_aln=False,return_stdout=False,params=None): """Uses cmalign to align seqs to alignment in cm_file_path. - cm_file_path: path to the file created by cmbuild, containing aligned sequences. This will be used to align sequences in seq... |
infernal. This includes alignment and structure bit scores and average probabilities for each sequence. (Default=False) """ #NOTE: Must degap seqs or Infernal well seg fault! seqs = SequenceCollection(seqs,MolType=moltype).degap() #Create mapping between abbreviated IDs and full IDs int_map, int_keys = seqs.getIntMap()... |
new_alignment = Alignment(new_alignment,MolType=moltype) std_out = res['StdOut'].read() res.cleanUp() if return_stdout: return new_alignment, struct_string, std_out else: return new_alignment, struct_string |
def cmsearch_from_alignment(aln, structure_string, seqs, moltype, cutoff=0.0,\ refine=False,params=None): """Uses cmbuild to build a CM file, then cmsearch to find homologs. - aln: an Alignment object or something that can be used to construct one. All sequences must be the same length. - structure_string: vienna struc... |
realign before building the cm. (Default=False) """ #NOTE: Must degap seqs or Infernal well seg fault! seqs = SequenceCollection(seqs,MolType=moltype).degap() #Create mapping between abbreviated IDs and full IDs int_map, int_keys = seqs.getIntMap() #Create SequenceCollection from int_map. int_map = SequenceCollection(i... |
def cmsearch_from_file(cm_file_path, seqs, moltype, cutoff=0.0, params=None): """Uses cmbuild to build a CM file, then cmsearch to find homologs. - cm_file_path: path to the file created by cmbuild, containing aligned sequences. This will be used to search sequences in seqs. - seqs: SequenceCollection object or somethi... |
int_map = SequenceCollection(int_map,MolType=moltype) app = Cmsearch(InputHandler='_input_as_paths',WorkingDir='/tmp',\ params=params) app.Parameters['--informat'].on('FASTA') app.Parameters['-T'].on(cutoff) seqs_path = app._input_as_multiline_string(int_map.toFasta()) paths = [cm_file_path,seqs_path] _, tmp_file = mks... |
def _tempfile_as_multiline_string(self, data): """Write a multiline string to a temp file and return the filename. data: a multiline string to be written to a file. * Note: the result will be the filename as a FilePath object (which is a string subclass). """ filename = FilePath(self.getTmpFilename(self.TmpDir)) data_f... |
def is_valid_sound_tuple(sound_tuple, final_form=True): """ Check if a character combination complies to Vietnamese phonology. The basic idea is that if one can pronunce a sound_tuple then it's valid. Sound tuples containing consonants exclusively (almost always abbreviations) are also valid. Input: sound_tuple - a Sou... |
def detect(self, path): ''' Guesses a TypeString from the given path ''' typestring = UNKNOWN for detector in self.detectors: if typestring != UNKNOWN and not detector.can_improve(typestring): continue if not detector.can_detect(path): continue detected = detector.detect(path) if detected: typestring = detected return ... |
def set_cache_buster(self, path, hash): """Sets the cache buster value for a given file path""" oz.aws_cdn.set_cache_buster(self.redis(), path, hash) |
def upload_file(self, path, contents, replace=False): """ Uplodas the file to its path with the given `content`, adding the appropriate parent directories when needed. If the path already exists and `replace` is `False`, the file will not be uploaded. """ f = self.get_file(path) f.upload(contents, replace=replace) self... |
def copy_file(self, from_path, to_path, replace=False): """ Copies a file from a given source path to a destination path, adding appropriate parent directories when needed. If the destination path already exists and `replace` is `False`, the file will not be uploaded. """ f = self.get_file(from_path) if f.copy(to_path,... |
def remove_file(self, path): """Removes the given file""" self.get_file(path).remove() self.remove_cache_buster(path) |
def alignUnalignedSeqs(seqs,add_seq_names=True,WorkingDir=None,\ SuppressStderr=None,SuppressStdout=None): """Aligns unaligned sequences seqs: either list of sequence objects or list of strings add_seq_names: boolean. if True, sequence names are inserted in the list of sequences. if False, it assumes seqs is a list of ... |
def alignUnalignedSeqsFromFile(filename,WorkingDir=None,SuppressStderr=None,\ SuppressStdout=None): """Aligns unaligned sequences from some file (file should be right format) filename: string, the filename of the file containing the sequences to be aligned in a valid format. """ app = Clustalw(WorkingDir=WorkingDir,Sup... |
def alignTwoAlignments(aln1,aln2,outfile,WorkingDir=None,SuppressStderr=None,\ SuppressStdout=None): """Aligns two alignments. Individual sequences are not realigned aln1: string, name of file containing the first alignment aln2: string, name of file containing the second alignment outfile: you're forced to specify an ... |
def addSeqsToAlignment(aln1,seqs,outfile,WorkingDir=None,SuppressStderr=None,\ SuppressStdout=None): """Aligns sequences from second profile against first profile aln1: string, name of file containing the alignment seqs: string, name of file containing the sequences that should be added to the alignment. opoutfile: str... |
def buildTreeFromAlignment(filename,WorkingDir=None,SuppressStderr=None): """Builds a new tree from an existing alignment filename: string, name of file containing the seqs or alignment """ app = Clustalw({'-tree':None,'-infile':filename},SuppressStderr=\ SuppressStderr,WorkingDir=WorkingDir) app.Parameters['-align'].o... |
def build_tree_from_alignment(aln, moltype=DNA, best_tree=False, params=None): """Returns a tree from Alignment object aln. aln: an cogent.core.alignment.Alignment object, or data that can be used to build one. moltype: cogent.core.moltype.MolType object best_tree: if True (default:False), uses a slower but more accura... |
bootstrap if best_tree: if '-bootstrap' not in params: app.Parameters['-bootstrap'].on(1000) if '-seed' not in params: app.Parameters['-seed'].on(randint(0,1000)) if '-bootlabels' not in params: app.Parameters['-bootlabels'].on('nodes') else: app.Parameters['-tree'].on() # Setup mapping. Clustalw clips identifiers. We ... |
def bootstrap_tree_from_alignment(aln, seed=None, num_trees=None, params=None): """Returns a tree from Alignment object aln with bootstrap support values. aln: an cogent.core.alignment.Alignment object, or data that can be used to build one. seed: an interger, seed value to use num_trees: an integer, number of trees to... |
clips identifiers. We will need to remap them. seq_collection = SequenceCollection(aln) int_map, int_keys = seq_collection.getIntMap() int_map = SequenceCollection(int_map) # Collect result result = app(int_map.toFasta()) # Build tree tree = DndParser(result['Tree'].read(), constructor=PhyloNode) for node in tree.tips(... |
def align_unaligned_seqs(seqs, moltype=DNA, params=None): """Returns an Alignment object from seqs. seqs: cogent.core.alignment.SequenceCollection object, or data that can be used to build one. moltype: a MolType object. DNA, RNA, or PROTEIN. params: dict of parameters to pass in to the Clustal app controller. Result w... |
up res.cleanUp() del(seq_collection,int_map,int_keys,app,res,alignment) return new_alignment |
def add_seqs_to_alignment(seqs, aln, moltype, params=None): """Returns an Alignment object from seqs and existing Alignment. seqs: a cogent.core.alignment.SequenceCollection object, or data that can be used to build one. aln: a cogent.core.alignment.Alignment object, or data that can be used to build one params: dict o... |
app._tempfile_as_multiline_string(aln_int_map.toFasta())) #Add seq_int_map as profile2 app.Parameters['-profile2'].on(\ app._tempfile_as_multiline_string(seq_int_map.toFasta())) #Get results using int_map as input to app res = app() #Get alignment as dict out of results alignment = dict(ClustalParser(res['Align'].readl... |
def align_two_alignments(aln1, aln2, moltype, params=None): """Returns an Alignment object from two existing Alignments. aln1, aln2: cogent.core.alignment.Alignment objects, or data that can be used to build them. params: dict of parameters to pass in to the Clustal app controller. """ #create SequenceCollection object... |
app res = app() #Get alignment as dict out of results alignment = dict(ClustalParser(res['Align'].readlines())) #Make new dict mapping original IDs new_alignment = {} for k,v in alignment.items(): new_alignment[aln1_int_keys[k]]=v #Create an Alignment object from alignment dict new_alignment = Alignment(new_alignment,M... |
def _input_as_multiline_string(self, data): """Writes data to tempfile and sets -infile parameter data -- list of lines """ if data: self.Parameters['-infile']\ .on(super(Clustalw,self)._input_as_multiline_string(data)) return '' |
def _input_as_lines(self,data): """Writes data to tempfile and sets -infile parameter data -- list of lines, ready to be written to file """ if data: self.Parameters['-infile']\ .on(super(Clustalw,self)._input_as_lines(data)) return '' |
def _suffix(self): """Return appropriate suffix for alignment file""" _output_formats={'GCG':'.msf', 'GDE':'.gde', 'PHYLIP':'.phy', 'PIR':'.pir', 'NEXUS':'.nxs'} if self.Parameters['-output'].isOn(): return _output_formats[self.Parameters['-output'].Value] else: return '.aln' |
def _aln_filename(self,prefix): """Return name of file containing the alignment prefix -- str, prefix of alignment file. """ if self.Parameters['-outfile'].isOn(): aln_filename = self._absolute(self.Parameters['-outfile'].Value) else: aln_filename = prefix + self._suffix() return aln_filename |
def _get_result_paths(self,data): """Return dict of {key: ResultPath} """ #clustalw .aln is used when no or unkown output type specified _treeinfo_formats = {'nj':'.nj', 'dist':'.dst', 'nexus':'.tre'} result = {} par = self.Parameters abs = self._absolute if par['-align'].isOn(): prefix = par['-infile'].Value.rsplit('.... |
if par['-newtree2'].isOn(): dnd2_filename = abs(par['-newtree2'].Value) aln_written=False else: dnd2_filename = abs(prefix2 + '.dnd') result['Align'] = ResultPath(Path=aln_filename, IsWritten=aln_written) result['Dendro1'] = ResultPath(Path=dnd1_filename, IsWritten=tree1_written) result['Dendro2'] = ResultPath(Path=dnd... |
result['TreeInfo'] = ResultPath(Path=treeinfo_filename,\ IsWritten=treeinfo_written) elif par['-bootstrap'].isOn(): prefix = par['-infile'].Value.rsplit('.', 1)[0] #prefix = par['-infile'].Value.split('.')[0] boottree_filename = prefix + '.phb' result['Tree'] = ResultPath(Path=boottree_filename,IsWritten=True) return r... |
def abort(http_status_code, exc=None, **kwargs): """Raise a HTTPException for the given http_status_code. Attach any keyword arguments to the exception for later processing. From Flask-Restful. See NOTICE file for license information. """ try: sanic.exceptions.abort(http_status_code, exc) except sanic.exceptions.SanicE... |
def parse_view_args(self, req, name, field): """Pull a value from the request's ``view_args``.""" return core.get_value(req.match_info, name, field) |
def get_request_from_view_args(self, view, args, kwargs): """Get request object from a handler function or method. Used internally by ``use_args`` and ``use_kwargs``. """ if len(args) > 1 and isinstance(args[1], sanic.request.Request): req = args[1] else: req = args[0] assert isinstance( req, sanic.request.Request ), "... |
def parse_json(self, req, name, field): """Pull a json value from the request.""" if not (req.body and is_json_request(req)): return core.missing json_data = req.json if json_data is None: return core.missing return core.get_value(json_data, name, field, allow_many_nested=True) |
def handle_error(self, error, req, schema): """Handles errors during parsing. Aborts the current HTTP request and responds with a 422 error. """ status_code = getattr(error, "status_code", self.DEFAULT_VALIDATION_STATUS) abort(status_code, exc=error, messages=error.messages, schema=schema) |
def directory_walk(source_d, destination_d): ''' Walk a directory structure and yield full parallel source and destination files, munging filenames as necessary ''' for dirpath, dirnames, filenames in os.walk(source_d): relpath = os.path.relpath(dirpath, source_d) if relpath == '.': relpath = '' # remove implied '.' fo... |
def recursive_symlink_dirs(source_d, destination_d): ''' Create dirs and symlink all files recursively from source_d, ignoring errors (e.g. existing files) ''' func = os.symlink if os.name == 'nt': # NOTE: need to verify that default perms only allow admins to create # symlinks on Windows func = shutil.copy if os.path.... |
def recursive_hardlink_dirs(source_d, destination_d): ''' Same as above, except creating hardlinks for all files ''' func = os.link if os.name == 'nt': func = shutil.copy if os.path.exists(destination_d): os.rmdir(destination_d) shutil.copytree(source_d, destination_d, copy_function=func) |
def flat_git_tree_to_nested(flat_tree, prefix=''): ''' Given an array in format: [ ["100644", "blob", "ab3ce...", "748", ".gitignore" ], ["100644", "blob", "ab3ce...", "748", "path/to/thing" ], ... ] Outputs in a nested format: { "path": "/", "type": "directory", "children": [ { "type": "blob", "size": 748, "sha": "ab3... |
Figure out all descendent directories children_dirs = set( dir_path for dir_path in descendent_dirs if os.path.dirname(dir_path) == prefix ) # Recurse into children dirs, constructing file trees for each of them, # then appending those for dir_path in children_dirs: info = flat_git_tree_to_nested(descendent_files, pref... |
def load_all(self, key, default=None): ''' Import settings key as a dict or list with values of importable paths If a default constructor is specified, and a path is not importable, it falls back to running the given constructor. ''' value = getattr(self, key) if default is not None: def loader(path): return self.load_... |
def load_path(self, path): ''' Load and return a given import path to a module or class ''' containing_module, _, last_item = path.rpartition('.') if last_item[0].isupper(): # Is a class definition, should do an "import from" path = containing_module imported_obj = importlib.import_module(path) if last_item[0].isupper(... |
def load_path_with_default(self, path, default_constructor): ''' Same as `load_path(path)', except uses default_constructor on import errors, or if loaded a auto-generated namespace package (e.g. bare directory). ''' try: imported_obj = self.load_path(path) except (ImportError, ConfigurationError): imported_obj = defau... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.