code stringlengths 1 18.2k |
|---|
def Flemmer_Banks(Re): r'''Calculates drag coefficient of a smooth sphere using the method in [1]_ as described in [2]_. .. math:: C_D = \frac{24}{Re}10^E E = 0.383Re^{0.356}-0.207Re^{0.396} - \frac{0.143}{1+(\log_{10} Re)^2} Parameters ---------- Re : float Reynolds number of the sphere, [-] Returns ------- Cd : float... |
''' E = 0.383*Re**0.356 - 0.207*Re**0.396 - 0.143/(1 + (log10(Re))**2) Cd = 24./Re*10**E return Cd |
def Clift(Re): r'''Calculates drag coefficient of a smooth sphere using the method in [1]_ as described in [2]_. .. math:: C_D = \left\{ \begin{array}{ll} \frac{24}{Re} + \frac{3}{16} & \mbox{if $Re < 0.01$}\\ \frac{24}{Re}(1 + 0.1315Re^{0.82 - 0.05\log Re}) & \mbox{if $0.01 < Re < 20$}\\ \frac{24}{Re}(1 + 0.1935Re^{0.... |
0.49 & \mbox{if $400000 < Re < 1000000$}\end{array} \right. Parameters ---------- Re : float Reynolds number of the sphere, [-] Returns ------- Cd : float Drag coefficient [-] Notes ----- Range is Re <= 1E6. Examples -------- >>> Clift(200) 0.7756342422322543 References ---------- .. [1] R. Clift, J.R. Grace, M.E. Webe... |
elif Re < 1500: Cd = 10**(1.6435 - 1.1242*log10(Re) + 0.1558*(log10(Re))**2) elif Re < 12000: Cd = 10**(-2.4571 + 2.5558*log10(Re) - 0.9295*(log10(Re))**2 + 0.1049*log10(Re)**3) elif Re < 44000: Cd = 10**(-1.9181 + 0.6370*log10(Re) - 0.0636*(log10(Re))**2) elif Re < 338000: Cd = 10**(-4.3390 + 1.5809*log10(Re) - 0.1546... |
def Almedeij(Re): r'''Calculates drag coefficient of a smooth sphere using the method in [1]_ as described in [2]_. .. math:: C_D = \left[\frac{1}{(\phi_1 + \phi_2)^{-1} + (\phi_3)^{-1}} + \phi_4\right]^{0.1} \phi_1 = (24Re^{-1})^{10} + (21Re^{-0.67})^{10} + (4Re^{-0.33})^{10} + 0.4^{10} \phi_2 = \left[(0.148Re^{0.11})... |
of Empirical Models with High Accuracy for Estimation of Drag Coefficient of Flow around a Smooth Sphere: An Evolutionary Approach." Powder Technology 257 (May 2014): 11-19. doi:10.1016/j.powtec.2014.02.045. ''' phi4 = ((6E-17*Re**2.63)**-10 + 0.2**-10)**-1 phi3 = (1.57E8*Re**-1.625)**10 phi2 = ((0.148*Re**0.11)**-10 +... |
def _build_option_string(self, options): """ :param options: dictionary containing the options :returns: option_string formatted for an API endpoint """ option_string = "" if options is not None: for key in options: option_string += "/%s-%s" % (key, options[key]) return self._quote_url(option_string) |
def start(path=None, host=None, port=None, color=None, cors=None, detach=False, nolog=False): """start web server""" if detach: sys.argv.append('--no-log') idx = sys.argv.index('-d') del sys.argv[idx] cmd = sys.executable + ' ' + ' '.join([sys.argv[0], 'start'] + sys.argv[1:]) if os.name == 'nt': cmd = 'start /B %s' % ... |
def status(host=None, port=None): """status web server""" app.config['HOST'] = first_value(host, app.config.get('HOST',None), '0.0.0.0') app.config['PORT'] = int(first_value(port, app.config.get('PORT',None), 5001)) if app.config['HOST'] == "0.0.0.0": host="127.0.0.1" else: host = app.config['HOST'] port = app.config['... |
def stop(host=None, port=None): """stop of web server""" app.config['HOST'] = first_value(host, app.config.get('HOST',None), '0.0.0.0') app.config['PORT'] = int(first_value(port, app.config.get('PORT',None), 5001)) if app.config['HOST'] == "0.0.0.0": host="127.0.0.1" else: host = app.config['HOST'] port = app.config['P... |
def log(host=None, port=None, limit=0): """view log of web server""" app.config['HOST'] = first_value(host, app.config.get('HOST',None), '0.0.0.0') app.config['PORT'] = int(first_value(port, app.config.get('PORT',None), 5001)) if app.config['HOST'] == "0.0.0.0": host="127.0.0.1" else: host = app.config['HOST'] port = a... |
def find_for_x_in_y_keys(node): """Finds looping against dictionary keys""" return ( isinstance(node, ast.For) and h.call_name_is(node.iter, 'keys') ) |
def find_if_x_retbool_else_retbool(node): """Finds simplifiable if condition""" return ( isinstance(node, ast.If) and isinstance(node.body[0], ast.Return) and h.is_boolean(node.body[0].value) and h.has_else(node) and isinstance(node.orelse[0], ast.Return) and h.is_boolean(node.orelse[0].value) ) |
def find_path_join_using_plus(node): """Finds joining path with plus""" return ( isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add) and isinstance(node.left, ast.BinOp) and isinstance(node.left.op, ast.Add) and isinstance(node.left.right, ast.Str) and node.left.right.s in ['/', "\\"] ) |
def find_assign_to_builtin(node): """Finds assigning to built-ins""" # The list of forbidden builtins is constant and not determined at # runtime anyomre. The reason behind this change is that certain # modules (like `gettext` for instance) would mess with the # builtins module making this practice yield false positive... |
"basestring", "bin", "bool", "bytearray", "callable", "chr", "classmethod", "cmp", "compile", "complex", "delattr", "dict", "dir", "divmod", "enumerate", "eval", "execfile", "file", "filter", "float", "format", "frozenset", "getattr", "globals", "hasattr", "hash", "help", "hex", "id", "import__", "input", "int", "isins... |
def find_silent_exception(node): """Finds silent generic exceptions""" return ( isinstance(node, ast.ExceptHandler) and node.type is None and len(node.body) == 1 and isinstance(node.body[0], ast.Pass) ) |
def find_import_star(node): """Finds import stars""" return ( isinstance(node, ast.ImportFrom) and '*' in h.importfrom_names(node.names) ) |
def find_equals_true_or_false(node): """Finds equals true or false""" return ( isinstance(node, ast.Compare) and len(node.ops) == 1 and isinstance(node.ops[0], ast.Eq) and any(h.is_boolean(n) for n in node.comparators) ) |
def find_poor_default_arg(node): """Finds poor default args""" poor_defaults = [ ast.Call, ast.Dict, ast.DictComp, ast.GeneratorExp, ast.List, ast.ListComp, ast.Set, ast.SetComp, ] # pylint: disable=unidiomatic-typecheck return ( isinstance(node, ast.FunctionDef) and any((n for n in node.args.defaults if type(n) in poo... |
def find_if_expression_as_statement(node): """Finds an "if" expression as a statement""" return ( isinstance(node, ast.Expr) and isinstance(node.value, ast.IfExp) ) |
def find_comprehension_as_statement(node): """Finds a comprehension as a statement""" return ( isinstance(node, ast.Expr) and isinstance(node.value, (ast.ListComp, ast.DictComp, ast.SetComp)) ) |
def find_generator_as_statement(node): """Finds a generator as a statement""" return ( isinstance(node, ast.Expr) and isinstance(node.value, ast.GeneratorExp) ) |
def main(argString=None): """The main function. :param argString: the options. :type argString: list These are the steps performed by this module: 1. Prints the options of the module. 2. Computes the number of markers in the input file (:py:func:`computeNumberOfMarkers`). 3. If there are no markers, the module stops. 4... |
key, value in vars(args).iteritems(): logger.info(" --{} {}".format(key.replace("_", "-"), value)) # Compute the number of markers logger.info("Counting the number of markers") nbMarkers = computeNumberOfMarkers(args.bfile + ".bim") if nbMarkers <= 0: logger.info(" - There are no markers: STOPPING NOW!") else: logger.i... |
args.out + ".threshold_" + args.hwe + ".bim", args.out + ".snp_flag_threshold_" + args.hwe, ) logger.info("Creating the in between SNP list ([{}, {}[)".format( args.hwe, customThreshold, )) file_name = args.out + ".snp_flag_threshold_between_{}-{}".format( args.hwe, customThreshold, ) try: with open(file_name, 'w') as ... |
def compareBIMfiles(beforeFileName, afterFileName, outputFileName): """Compare two BIM files for differences. :param beforeFileName: the name of the file before modification. :param afterFileName: the name of the file after modification. :param outputFileName: the name of the output file (containing the differences bet... |
beforeBIM = CompareBIM.readBIM(options.before) afterBIM = CompareBIM.readBIM(options.after) # Finding the differences CompareBIM.compareSNPs(beforeBIM, afterBIM, options.out) return beforeBIM - afterBIM |
def computeNumberOfMarkers(inputFileName): """Count the number of marker (line) in a BIM file. :param inputFileName: the name of the ``bim`` file. :type inputFileName: str :returns: the number of marker in the ``bim`` file. """ nbLine = 0 with open(inputFileName, "r") as inputFile: nbLine = len(inputFile.readlines()) r... |
def computeHWE(prefix, threshold, outPrefix): """Compute the Hardy Weinberg test using Plink. :param prefix: the prefix of all the files. :param threshold: the Hardy Weinberg threshold. :param outPrefix: the prefix of the output file. :type prefix: str :type threshold: str :type outPrefix: str Uses Plink to exclude mar... |
def checkArgs(args): """Checks the arguments and options. :param args: a :py:class:`argparse.Namespace` object containing the options of the program. :type args: :py:class:`argparse.Namespace` :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`Prog... |
msg = "%s: not a valid HW value" % args.hwe raise ProgramError(msg) return True |
def subset_data(options): """Subset the data. :param options: the options. :type options: argparse.Namespace Subset the data using either ``--exclude`` or ``--extract``for markers or ``--remove`` or ``keep`` for samples. """ # The plink command plinkCommand = ["plink", "--noweb"] # The input file prefix if options.is_b... |
def checkArgs(args): """Checks the arguments and options. :param args: an object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`ProgramError` class, a message is printed to t... |
args.is_tfile and not args.is_file: for fileName in [args.ifile + i for i in [".bed", ".bim", ".fam"]]: if not os.path.isfile(fileName): msg = "{}: no such file".format(fileName) raise ProgramError(msg) elif args.is_tfile and not args.is_bfile and not args.is_file: for fileName in [args.ifile + i for i in [".tped", ".t... |
args.remove is None and args.keep is None: msg = "needs at least one of --exclude, --extract, --remove or --keep" raise ProgramError(msg) # Check for SNPs if args.exclude is not None and args.extract is None: if not os.path.isfile(args.exclude): msg = "{}: no such file".format(args.exclude) raise ProgramError(msg) elif... |
raise ProgramError(msg) elif args.remove is not None and args.keep is not None: msg = "use only one of --keep or --remove" raise ProgramError(msg) return True |
def series2df(Series, layer=2, split_sign = '_'): """expect pass a series that each row is string formated Json data with the same structure""" try: Series.columns Series = Series.iloc[:,0] except: pass def _helper(x, layer=2): try: return flatten_dict(ast.literal_eval(x), layers=layer, split_sign=split_sign) except: t... |
def load_data(self, path, *args, **kwargs): """see print instance.doc, e.g. cat=LoadFile(kind='excel') read how to use cat.load_data, exec: print (cat.doc)""" self.df = self._load(path,*args, **kwargs) self.series = self.df.iloc[:,0] print ("Success! file length: " +str(self.df.shape[0])) |
def convert(self, layer=2, split_sign = '_', *args, **kwargs): """convert data to DataFrame""" return series2df(self.series, *args, **kwargs) |
def main(argString=None): """The main function of this module. :param argString: the options. :type argString: list These are the steps: 1. Runs a plate bias analysis using Plink (:py:func:`executePlateBiasAnalysis`). 2. Extracts the list of significant markers after plate bias analysis (:py:func:`extractSignificantSNP... |
def createSummaryFile(results, maf, prefix): """Creat the final summary file containing plate bias results. :param results: the list of all the significant results. :param maf: the minor allele frequency of the significant results. :param prefix: the prefix of all the files. :type results: list :type maf: dict :type pr... |
def extractSignificantSNPs(prefix): """Extract significant SNPs in the fisher file. :param prefix: the prefix of the input file. :type prefix: str Reads a list of significant markers (``prefix.assoc.fisher``) after plate bias analysis with Plink. Writes a file (``prefix.significant_SNPs.txt``) containing those signific... |
for i in xrange(len(row)) ]) for name in ("CHR", "SNP", "BP", "P", "OR"): if name not in headerIndex: msg = "{}: missing column {}".format( fileName, name, ) raise ProgramError(msg) else: snpName = row[headerIndex["SNP"]] snpNames.add(snpName) assocResults.append(AssocRow( chrom=row[headerIndex["CHR"]], pos=row[headerI... |
def computeFrequencyOfSignificantSNPs(options): """Computes the frequency of the significant markers. :param options: the options. :type options: argparse.Namespace Extract a list of markers (significant after plate bias analysis) and computes their frequencies. """ # The plink command plinkCommand = ["plink", "--noweb... |
def executePlateBiasAnalysis(options): """Execute the plate bias analysis with Plink. :param options: the options. :type options: argparse.Namespace """ # The plink command plinkCommand = ["plink", "--noweb", "--bfile", options.bfile, "--loop-assoc", options.loop_assoc, "--fisher", "--pfilter", str(options.pfilter), "-... |
def checkArgs(args): """Checks the arguments and options. :param args: an object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`ProgramError` class, a message is printed to t... |
def random_variant(variants, weights): """ A generator that, given a list of variants and a corresponding list of weights, returns one random weighted selection. """ total = 0 accumulator = [] for w in weights: total += w accumulator.append(total) r = randint(0, total - 1) yield variants[bisect(accumulator, r)] |
def parse(duration, context=None): """ parse the duration string which contains a human readable duration and return a datetime.timedelta object representing that duration arguments: duration - the duration string following a notation like so: "1 hour" "1 month and 3 days" "1 year 2 weeks and 75 days" "1 year, 75 days ... |
= context.day for (key, value) in matcher.groupdict().items(): weeks = 0 days = 0 hours = 0 minutes = 0 seconds = 0 milliseconds = 0 microseconds = 0 if value is not None: value = float(value) whole = int(value) fraction = abs(whole - value) if key == 'years': start = datetime(year, month, day) end = datetime(year + wh... |
whole years and left over months and # then let pythons datetime do all the work years = whole // 12 months = whole % 12 end_month = month + months if end_month > 12: # detect month overflow and bump the year and calculate # the right end_month to use years += end_month // 12 end_month = end_month % 12 start = datetime... |
calendar.monthrange(end_year, end_month) days_in_month = (datetime(end_year, end_month, end_day) - datetime(end_year, end_month, 1)).days end += timedelta(days=(fraction * days_in_month)) seconds = (end - start).total_seconds() elif key == 'weeks': weeks = whole days = fraction * 7 elif key == 'days': days = whole hour... |
def main(argString=None): """The main function. :param argString: the options. :type argString: list These are the steps: 1. Prints the options. 2. Computes the frequencies using Plinl (:py:func:`computeFrequency`). 3. Finds markers with MAF of 0, and saves them in a file (:py:func:`findSnpWithMaf0`). """ # Getting and... |
def findSnpWithMaf0(freqFileName, prefix): """Finds SNPs with MAF of 0 and put them in a file. :param freqFileName: the name of the frequency file. :param prefix: the prefix of all the files. :type freqFileName: str :type prefix: str Reads a frequency file from Plink, and find markers with a minor allele frequency of z... |
= row[headerIndex["MAF"]] if snpMAF == "0": # We want to flag this SNP maf_0_set.add(snpName) elif snpMAF == "NA": # We want to flag this SNP, because the MAF est NA na_set.add(snpName) except IOError: msg = "%(freqFileName)s: no such file" % locals() raise ProgramError(msg) # Creating the output files if len(maf_0_set... |
marker_name except IOError: msg = "{}.na_list: can't write file".format(prefix) raise ProgramError(msg) |
def init_site(): """Initialize a Bower Cache site using the template.""" site_name = 'bowercachesite' dir_name = sys.argv[1] if len(sys.argv) > 1 else site_name settings = site_name + ".settings" template_filename = resource_filename(bowercache.__name__, 'project_template') cwd = os.getcwd() full_dir_name = os.path.abs... |
def main(self, phase_inc): """ :param phase_inc: amount of rotation applied for next clock cycle, must be normalized to -1 to 1. :rtype: Complex """ self.phase_acc = self.phase_acc + phase_inc start_x = self.INIT_X start_y = Sfix(0.0, 0, -17) x, y, phase = self.cordic.main(start_x, start_y, self.phase_acc) self.out.rea... |
def zotero_tags(parser, token): """ Returns the code to be translated by Zotero. Usage: {% zotero_tags object=object vocabulary=vocabulary output_method=output_method %} Example: {% zotero_tags object=document1 vocabulary="dc" output_method="meta" %} """ default = { 'object': u'', 'vocabulary': u'dc', 'output_method': ... |
syntax error: %s.' % (args[0], arg)) else: key = arg[:i] val = arg[i + 1:] if not key in default.keys(): raise TemplateSyntaxError('%s invalid argument: %s.' % (args[0], key)) else: default[key] = val return ZoteroTagsNode(default) |
def airport_codes(): """ Returns the set of airport codes that is available to be requested. """ html = requests.get(URL).text data_block = _find_data_block(html) return _airport_codes_from_data_block(data_block) |
def json_encode(data): """ The main issues with django's default json serializer is that properties that had been added to an object dynamically are being ignored (and it also has problems with some models). """ def _any(data): ret = None # Opps, we used to check if it is of type list, but that fails # i.e. in the case... |
to encode the string as unicode (otherwise we get utf-16 in the json-response) elif isinstance(data, basestring): ret = unicode(data) # see http://code.djangoproject.com/ticket/5868 elif isinstance(data, Promise): ret = force_unicode(data) else: ret = data return ret def _model(data): ret = {} # If we only have a model... |
ret = _any(data) return json.dumps(ret, cls=DateTimeAwareJSONEncoder) |
def json_template(data, template_name, template_context): """Old style, use JSONTemplateResponse instead of this. """ html = render_to_string(template_name, template_context) data = data or {} data['html'] = html return HttpResponse(json_encode(data), content_type='application/json') |
def check_save(sender, **kwargs): """ Checks item type uniqueness, field applicability and multiplicity. """ tag = kwargs['instance'] obj = Tag.get_object(tag) previous_tags = Tag.get_tags(obj) err_uniq = check_item_type_uniqueness(tag, previous_tags) err_appl = check_field_applicability(tag) err_mult = check_field_mul... |
def check_item_type_uniqueness(tag, previous_tags): """ Check the uniqueness of the 'item type' for an object. """ fail = False #If the tag is being created... if not tag.id: #... and the new item type is different from previous item types (for #example, different from the first of them), fail fail = previous_tags and ... |
def check_field_multiplicity(tag, previous_tags): """ Check the multiplicity of a 'field' for an object. """ fail = False #If the field is single if not tag.field.multiple: #If the tag is being created... if not tag.id: #... and the new field was already included in the previous tags, #fail fail = previous_tags.filter(... |
def generate_error_message(tag, err_uniq, err_appl, err_mult): """ Generate the error message for an object. """ err = [] if err_uniq: err.append('Uniqueness restriction: item type %s' % tag.item_type) if err_appl: err.append('Applicability restriction: field %s' % tag.field) if err_mult: err.append('Multiplicity restr... |
def delete_tags(sender, **kwargs): """ Delete the tags pointing to an object. """ try: obj = kwargs.get('instance') tags = Tag.get_tags(obj) tags.delete() except AttributeError: pass |
def finished(self, filename): """Make Checkystyle ElementTree.""" if len(self.errors) < 1: return element = ET.SubElement(self.checkstyle_element, 'file', name=filename) for error in self.errors: message = error.code + ' ' + error.text prefix = error.code.strip()[0] ET.SubElement(element, 'error', { 'severity': CHECKST... |
def stop(self): """Output Checkstyle XML reports.""" et = ET.ElementTree(self.checkstyle_element) f = BytesIO() et.write(f, encoding='utf-8', xml_declaration=True) xml = f.getvalue().decode('utf-8') if self.output_fd is None: print(xml) else: self.output_fd.write(xml) super(CheckstylePlugin, self).stop() |
def encode_multipart_formdata(self, fields, filename, verbose=False): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, value) elements for data to be uploaded as files Return (content_type, body) ready for httplib.HTTP instance """ BOUNDARY = '---------... |
def main(argString=None): """The main function of the module. :param argString: the options. :type argString: list These are the steps: 1. Prints the options. 2. Reads the ``tfam`` and ``tped`` files and find all heterozygous and all failed markers (:py:func:`processTPEDandTFAM`). """ # Getting and checking the options... |
def processTPEDandTFAM(tped, tfam, prefix): """Process the TPED and TFAM files. :param tped: the name of the ``tped`` file. :param tfam: the name of the ``tfam`` file. :param prefix: the prefix of the output files. :type tped: str :type tfam: str :type prefix: str Copies the original ``tfam`` file into ``prefix.tfam``.... |
prefix + ".tfam" raise ProgramError(msg) try: outputFile = open(prefix + ".tped", "w") except IOError: msg = "%s: can't write to file" % prefix + ".tped" raise ProgramError(msg) # The name of the bad SNPs allFailed = set() allHetero = set() with open(tped, 'r') as inputFile: for line in inputFile: row = line.rstrip("\r... |
SNP is not on a mitochondrial chromosome # (because we want to keep those) allHetero.add(snpInfo[1]) # If the SNP is good (neither in allFailed or allHetero), we keep # the SNP if (snpInfo[1] not in allFailed) and (snpInfo[1] not in allHetero): print >>outputFile, "\t".join(row) outputFile.close() # Now printing the su... |
def checkArgs(args): """Checks the arguments and options. :param args: an object containing the options of the program. :type args: argparse.Namespace :returns: ``True`` if everything was OK. If there is a problem with an option, an exception is raised using the :py:class:`ProgramError` class, a message is printed to t... |
def weld_count(array): """Returns the length of the array. Parameters ---------- array : numpy.ndarray or WeldObject Input array. Returns ------- WeldObject Representation of this computation. """ obj_id, weld_obj = create_weld_object(array) weld_template = _weld_count_code weld_obj.weld_code = weld_template.format(arr... |
def weld_aggregate(array, weld_type, operation): """Returns operation on the elements in the array. Arguments --------- array : WeldObject or numpy.ndarray Input array. weld_type : WeldType Weld type of each element in the input array. operation : {'+', '*', 'min', 'max'} Operation to apply. Returns ------- WeldObject ... |
def weld_mean(array, weld_type): """Returns the mean of the array. Parameters ---------- array : numpy.ndarray or WeldObject Input array. weld_type : WeldType Type of each element in the input array. Returns ------- WeldObject Representation of this computation. """ weld_obj_sum = weld_aggregate(array, weld_type, '+') ... |
def weld_variance(array, weld_type): """Returns the variance of the array. Parameters ---------- array : numpy.ndarray or WeldObject Input array. weld_type : WeldType Type of each element in the input array. Returns ------- WeldObject Representation of this computation. """ weld_obj_mean = weld_mean(array, weld_type) o... |
def weld_standard_deviation(array, weld_type): """Returns the *sample* standard deviation of the array. Parameters ---------- array : numpy.ndarray or WeldObject Input array. weld_type : WeldType Type of each element in the input array. Returns ------- WeldObject Representation of this computation. """ weld_obj_var = w... |
def weld_agg(array, weld_type, aggregations): """Multiple aggregations, optimized. Parameters ---------- array : numpy.ndarray or WeldObject Input array. weld_type : WeldType Type of each element in the input array. aggregations : list of str Which aggregations to compute. Returns ------- WeldObject Representation of t... |
res = merge(res, {});'.format('agg_{}'.format(agg)) for agg in aggregations)) mergers = """let res = appender[f64]; {merges} result(res) """ mergers = mergers.format(merges=merges) weld_template = '{}\n{}'.format(aggs, mergers) weld_obj.weld_code = weld_template.format(array=obj_id, type=weld_type) return weld_obj |
def p_expression_b_op(p): '''expression : expression B_OP expression''' if p[2] == 'AND': p[0] = p[1] & p[3] elif p[2] == 'OR': p[0] = p[1] | p[3] |
def p_expression_ID(p): """expression : FIELD operation value """ lookup = compa2lookup[p[2]] try: field = get_shortcut(p[1]) except KeyError: field = p[1] if lookup: field = '%s__%s' % (field, lookup) # In some situations (which ones?), python # refuses unicode strings as dict keys for # Q(**d) field = str(field) d = ... |
def cholesky(L, b, P=None): ''' P A P' = L L' ''' logger.debug('Solving system of dim {} with cholesky factors'.format(len(b))) ## convert L and U to csr format is_csr = scipy.sparse.isspmatrix_csr(L) is_csc = scipy.sparse.isspmatrix_csc(L) if not is_csr and not is_csc: warnings.warn('cholesky requires L be in CSR or C... |
def captchaform(field_name): """Decorator to add a simple captcha to a form To use this decorator, you must specify the captcha field's name as an argument to the decorator. For example: @captchaform('captcha') class MyForm(Form): pass This would add a new form field named 'captcha' to the Django form MyForm. Nothing e... |
"""The actual function that wraps and modifies the form""" # Get the original init method so we can call it later orig_init = orig_form.__init__ def new_init(self, *args, **kwargs): """This is the captchaform replacement init method This method replaces a decorated form with one that properly handles ensuring that the ... |
captcha}) return orig_form return wrapper |
def _validate_incident_date_range(incident, numdays): """Returns true if incident is within date range""" try: datetime_object = datetime.datetime.strptime(incident.get('date'), '%m/%d/%y %I:%M %p') except ValueError: raise ValueError("Incorrect date format, should be MM/DD/YY HH:MM AM/PM") timedelta = datetime.timedel... |
def _incident_transform(incident): """Get output dict from incident.""" return { 'id': incident.get('cdid'), 'type': incident.get('type'), 'timestamp': incident.get('date'), 'lat': incident.get('lat'), 'lon': incident.get('lon'), 'location': incident.get('address'), 'link': incident.get('link') } |
def get_incidents(self): """Get incidents.""" resp = requests.get(CRIME_URL, params=self._get_params(), headers=self.headers) incidents = [] # type: List[Dict[str, str]] data = resp.json() if ATTR_CRIMES not in data: return incidents for incident in data.get(ATTR_CRIMES): if _validate_incident_date_range(incident, self... |
def _needs_git(func): """ Small decorator to make sure we have the git repo, or report error otherwise. """ @wraps(func) def myfunc(*args, **kwargs): if not WITH_GIT: raise RuntimeError( "Dulwich library not available, can't extract info from the " "git repos." ) return func(*args, **kwargs) return myfunc |
def tag_versions(repo_path): """ Given a repo will add a tag for each major version. Args: repo_path(str): path to the git repository to tag. """ repo = dulwich.repo.Repo(repo_path) tags = get_tags(repo) maj_version = 0 feat_version = 0 fix_version = 0 last_maj_version = 0 last_feat_version = 0 result = [] for commit_s... |
def get_releasenotes(repo_path, from_commit=None, bugtracker_url=''): """ Given a repo and optionally a base revision to start from, will return a text suitable for the relase notes announcement, grouping the bugs, the features and the api-breaking changes. Args: repo_path(str): Path to the code git repository. from_co... |
children in reversed( get_children_per_first_parent(repo_path).items() ): commit = get_repo_object(repo, commit_sha) maj_version, feat_version, fix_version = get_version( commit=commit, tags=tags, maj_version=maj_version, feat_version=feat_version, fix_version=fix_version, children=children, ) version = (maj_version, f... |
bugs = lines releasenotes += u'''New changes for version %s ================================= API Breaking changes -------------------- %s New features ------------ %s Bugfixes and minor changes -------------------------- %s ''' % ( major_version, ( '\n'.join(reversed(api_break_changes)) or 'No new API breaking changes... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.