code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
genes_to_highlight = kwargs.pop('genes_to_highlight', []) genes_to_highlight.append( (self.upregulated(thresh), up_kwargs or dict(color='r'))) genes_to_highlight.append( (self.downregulated(thresh), dn_kwargs or dict(color='b'))) ...
def ma_plot(self, thresh, up_kwargs=None, dn_kwargs=None, zero_line=None, **kwargs)
MA plot Plots the average read count across treatments (x-axis) vs the log2 fold change (y-axis). Additional kwargs are passed to self.scatter (useful ones might include `genes_to_highlight`) Parameters ---------- thresh : float Features with values...
2.780663
2.767485
1.004762
if self.db is None: raise ValueError("FeatureDB required") db = gffutils.FeatureDB(self.db) def scored_feature_generator(d): for i in range(len(d)): try: feature = db[d.ix[i]] except gffutils.FeatureNotFoundErr...
def colormapped_bedfile(self, genome, cmap=None)
Create a BED file with padj encoded as color Features will be colored according to adjusted pval (phred transformed). Downregulated features have the sign flipped. Parameters ---------- cmap : matplotlib colormap Default is matplotlib.cm.RdBu_r Notes ...
3.806914
3.616009
1.052794
fn = pybedtools.BedTool._tmp() AUTOSQL = dedent( ) fout = open(fn, 'w') fout.write(AUTOSQL) fout.close() return fn
def autosql_file(self)
Generate the autosql for DESeq results (to create bigBed) Returns a temp filename containing the autosql defining the extra fields. This for creating bigBed files from BED files created by colormapped_bed. When a user clicks on a feature, the DESeq results will be reported.
8.761537
8.154624
1.074426
if isinstance(feature, basestring): feature = helpers.tointerval(feature) if stranded: strand = feature.strand else: strand = '.' count = 0 for al in reader[feature]: if stranded and al.strand != strand: continue count += 1 return count
def _local_count(reader, feature, stranded=False)
The count of genomic signal (typcially BED features) found within an interval. Usually this only makes sense for BED or BAM (not bigWig) files. :param feature: pybedtools.Interval object :param stranded: If `stranded=True`, then only counts signal on the same strand as `feature`.
3.421191
3.859311
0.886477
pool = multiprocessing.Pool(processes) chunks = list(chunker(genelist, chunksize)) # pool.map can only pass a single argument to the mapped function, so you # need this trick for passing multiple arguments; idea from # http://stackoverflow.com/questions/5442910/ # python-multi...
def _array_parallel(fn, cls, genelist, chunksize=250, processes=1, **kwargs)
Returns an array of genes in `genelist`, using `bins` bins. `genelist` is a list of pybedtools.Interval objects Splits `genelist` into pieces of size `chunksize`, creating an array for each chunk and merging ret A chunksize of 25-100 seems to work well on 8 cores.
3.892311
4.28489
0.908381
fn, cls, genelist, kwargs = args return _array(fn, cls, genelist, **kwargs)
def _array_star(args)
Unpacks the tuple `args` and calls _array. Needed to pass multiple args to a pool.map-ed function
10.869667
11.185177
0.971792
reader = cls(fn) _local_coverage_func = cls.local_coverage biglist = [] if 'bins' in kwargs: if isinstance(kwargs['bins'], int): kwargs['bins'] = [kwargs['bins']] for gene in genelist: if not isinstance(gene, (list, tuple)): gene = [gene] coverag...
def _array(fn, cls, genelist, **kwargs)
Returns a "meta-feature" array, with len(genelist) rows and `bins` cols. Each row contains the number of reads falling in each bin of that row's modified feature.
3.91786
3.85367
1.016657
def find_spelling(n): r = 0 d = n - 1 # divmod used for large numbers quotient, remainder = divmod(d, 2) # while we can still divide 2's into n-1... while remainder != 1: r += 1 d = quotient # previous quotient before we overwrite it quotient, remainder = ...
Finds d, r s.t. n-1 = 2^r * d
null
null
null
def probably_prime(n, k=10): if n == 2: return True if n % 2 == 0: return False r, d = find_spelling(n) for check in range(k): a = random.randint(2, n - 1) x = pow(a, d, n) # a^d % n if x == 1 or x == n - 1: continue for i i...
Miller-Rabin primality test Input: n > 3 k: accuracy of test Output: True if n is "probably prime", False if it is composite From psuedocode at https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test
null
null
null
if isinstance(bigwig, _genomic_signal.BigWigSignal): bigwig = bigwig.fn if outdir is None: outdir = os.path.dirname(bigwig) basename = os.path.basename(bigwig) windowsize = self.windowsize outfiles = [] for chrom in self.chroms: ...
def to_npz(self, bigwig, metric='mean0', outdir=None)
Bin data for bigwig and save to disk. The .npz file will have the pattern {outdir}/{bigwig}.{chrom}.{windowsize}.{metric}.npz and will have two arrays, x (genomic coordinates of midpoints of each window) and y (metric for each window). It can be loaded like this:: d = np.l...
3.400758
2.868743
1.185452
fout = open(outfn, 'w') fout.write('track type=bedGraph\n') i = 0 this_batch = [] for feature in features: if i <= batchsize: this_batch.append(feature) i += 1 continue if verbose: print 'working on batch of %s' % batchsize ...
def compare(signal1, signal2, features, outfn, comparefunc=np.subtract, batchsize=5000, array_kwargs=None, verbose=False)
Compares two genomic signal objects and outputs results as a bedGraph file. Can be used for entire genome-wide comparisons due to its parallel nature. Typical usage would be to create genome-wide windows of equal size to provide as `features`:: windowsize = 10000 features = pybedtools.BedT...
3.324246
3.000326
1.107962
def is_prime(n): if n % 2 == 0: return False i = 3 while i * i <= n: if n % i: i += 2 else: return False return True if N < 3: return 2 if N % 2 == 0: N += 1 for n in range(N, 2*N, 2)...
def _find_next_prime(N)
Find next prime >= N
2.040351
2.036219
1.00203
import sys import numpy as np import h5py name = name.encode(sys.getfilesystemencoding()) open(name, mode).close() # Just make sure the file exists if mode in [m+b for m in ['w', 'w+', 'r+', 'a', 'a+'] for b in ['', 'b']]: mode = h5py.h5f.ACC_RDWR else: mode = h5py.h5f....
def File(name, mode='a', chunk_cache_mem_size=1024**2, w0=0.75, n_cache_chunks=None, **kwds)
Create h5py File object with cache specification This function is basically just a wrapper around the usual h5py.File constructor, but accepts two additional keywords: Parameters ---------- name : str mode : str **kwds : dict (as keywords) Standard h5py.File arguments, passed to it...
3.034837
3.152735
0.962604
dirname = os.path.dirname(prefix) pybedtools.BedTool(c.features).saveas(prefix + '.intervals') def usepath(f): if relative_paths: return os.path.relpath(f, start=dirname) else: return os.path.abspath(f) with open(prefix + '.info', 'w') as fout: inf...
def save(c, prefix, relative_paths=True)
Save data from a Chipseq object. Parameters ---------- c : Chipseq object Chipseq object, most likely after calling the `diffed_array` method prefix : str Prefix, including any leading directory paths, to save the data. relative_paths : bool If True (default), then the pa...
3.387429
2.124987
1.594093
if thresh is None: thresh = 0 if genome is None: genome = signal.genome() if array_kwargs is None: array_kwargs = {} array_kwargs.pop('read_strand', None) if 'bins' not in array_kwargs: array_kwargs['bins'] = windowsize def add_strand(f, strand): ...
def estimate_shift(signal, genome=None, windowsize=5000, thresh=None, nwindows=1000, maxlag=500, array_kwargs=None, verbose=False)
Experimental: cross-correlation to estimate the shift width of ChIP-seq data This can be interpreted as the binding site footprint. For ChIP-seq, the plus and minus strand reads tend to be shifted in the 5' direction away from each other. Various ChIP-seq peak-callers estimate this distance; this...
2.717839
2.456988
1.106167
xlen = len(x) ylen = len(y) assert xlen == ylen c = np.correlate(x, y, mode=2) # normalize c /= np.sqrt(np.dot(x, x) * np.dot(y, y)) lags = np.arange(-maxlags, maxlags + 1) c = c[xlen - 1 - maxlags:xlen + maxlags] return c
def xcorr(x, y, maxlags)
Streamlined version of matplotlib's `xcorr`, without the plots. :param x, y: NumPy arrays to cross-correlate :param maxlags: Max number of lags; result will be `2*maxlags+1` in length
2.242635
2.570404
0.872483
self.features = list(features) self.browser_local_coverage_kwargs = array_kwargs.copy() self.browser_local_coverage_kwargs.pop('processes', None) self.browser_local_coverage_kwargs.pop('chunksize', 1) self.array_kwargs = array_kwargs.copy() if (self.ip_array is...
def diff_array(self, features, force=True, func=None, array_kwargs=dict(), cache=None)
Scales the control and IP data to million mapped reads, then subtracts scaled control from scaled IP, applies `func(diffed)` to the diffed array, and finally sets `self.diffed_array` to be the result. Arrays `self.ip` and `self.control` are set as well, and if `force=False`, then previo...
3.082096
2.192902
1.405487
nrows = self.diffed_array.shape[0] if row_order is None: row_order = np.arange(nrows) extent = (min(x), max(x), 0, nrows) axes_info = metaseq.plotutils.matrix_and_line_shell(strip=strip) fig, matrix_ax, line_ax, strip_ax, cbar_ax = axes_info _imshow_k...
def plot(self, x, row_order=None, imshow_kwargs=None, strip=True)
Plot the scaled ChIP-seq data. :param x: X-axis to use (e.g, for TSS +/- 1kb with 100 bins, this would be `np.linspace(-1000, 1000, 100)`) :param row_order: Array-like object containing row order -- typically the result of an `np.argsort` call. :param strip: Include axes...
3.009681
2.960015
1.016779
artist = event.artist ind = artist.ind limit = 5 browser = True if len(event.ind) > limit: print "more than %s genes selected; not spawning browsers" % limit browser = False for i in event.ind: feature = artist.features[ind[i]]...
def callback(self, event)
Callback function to spawn a mini-browser when a feature is clicked.
8.12634
6.601864
1.230916
iscoroutine = asyncio.iscoroutinefunction(fn) if not iscoroutine and not isfunction(fn): raise TypeError('paco: fn param must be a callable ' 'object or coroutine function') observers = self._pool.get(event) if not observers: ...
def observe(self, event, fn)
Arguments: event (str): event to subscribe. fn (function|coroutinefunction): function to trigger. Raises: TypeError: if fn argument is not valid
4.927287
5.872838
0.838996
observers = self._pool.get(event) if observers: self._pool[event] = []
def remove(self, event=None)
Remove all the registered observers for the given event name. Arguments: event (str): event name to remove.
7.844879
8.671283
0.904696
observers = self._pool.get(event) # If no observers registered for the event, do no-op if not observers or len(observers) == 0: return None # Trigger observers coroutines in FIFO sequentially for fn in observers: # Review: perhaps this should no...
def trigger(self, event, *args, **kw)
Triggers event observers for the given event name, passing custom variadic arguments.
8.026128
7.587259
1.057843
print("Lexical error:") print("%s" % s[:pos+10]) # + 10 for trailing context print("%s^" % (" "*(pos-1))) for t in self.rv: print(t) raise SystemExit
def error(self, s, pos)
Show text and a caret under that. For example: x = 2y + z ^
9.020558
8.887221
1.015003
@asyncio.coroutine def assert_coro(value): return not value return (yield from whilst(coro, coro_test, assert_coro=assert_coro, *args, **kw))
def until(coro, coro_test, assert_coro=None, *args, **kw)
Repeatedly call `coro` coroutine function until `coro_test` returns `True`. This function is the inverse of `paco.whilst()`. This function is a coroutine. Arguments: coro (coroutinefunction): coroutine function to execute. coro_test (coroutinefunction): coroutine function to test. ...
4.054423
5.594721
0.724687
# Make list to inherit built-in type methods coros = list(coros) @asyncio.coroutine def reducer(acc, coro): return (yield from coro(acc)) @asyncio.coroutine def wrapper(acc): return (yield from reduce(reducer, coros, initializer=acc, right...
def compose(*coros)
Creates a coroutine function based on the composition of the passed coroutine functions. Each function consumes the yielded result of the coroutine that follows. Composing coroutine functions f(), g(), and h() would produce the result of f(g(h())). Arguments: *coros (coroutinefunction): v...
6.03545
8.310752
0.726222
genius_key = input('Enter Genius key : ') bing_key = input('Enter Bing key : ') CONFIG['keys']['bing_key'] = bing_key CONFIG['keys']['genius_key'] = genius_key with open(config_path, 'w') as configfile: CONFIG.write(configfile)
def add_config()
Prompts user for API keys, adds them in an .ini file stored in the same location as that of the script
3.09802
2.948455
1.050727
''' Gets tracks from an album using Spotify's API ''' spotify = spotipy.Spotify() album = spotify.search(q='album:' + album_name, limit=1) album_id = album['tracks']['items'][0]['album']['id'] results = spotify.album_tracks(album_id=str(album_id)) songs = [] for items in results['i...
def get_tracks_from_album(album_name)
Gets tracks from an album using Spotify's API
2.638029
2.298544
1.147695
''' Provides user with a list of songs to choose from returns the url of chosen song. ''' youtube_list = OrderedDict() num = 0 # List of songs index html = requests.get("https://www.youtube.com/results", params={'search_query': song_input}) soup = BeautifulSoup(...
def get_url(song_input, auto)
Provides user with a list of songs to choose from returns the url of chosen song.
4.109431
3.67383
1.118569
''' Prompts for song number from list of songs ''' option = int(input('\nEnter song number > ')) try: song_url = list(youtube_list.values())[option - 1] song_title = list(youtube_list.keys())[option - 1] except IndexError: log.log_error('Invalid Input') exit() ...
def prompt(youtube_list)
Prompts for song number from list of songs
3.270071
3.033427
1.078012
''' Starts here, handles arguments ''' system('clear') # Must be system('cls') for windows setup() parser = argparse.ArgumentParser( description='Download songs with album art and metadata!') parser.add_argument('-c', '--config', action='store_true', help='...
def main()
Starts here, handles arguments
2.938787
2.856513
1.028802
descriptor = _hidraw_report_descriptor() size = ctypes.c_uint() self._ioctl(_HIDIOCGRDESCSIZE, size, True) descriptor.size = size self._ioctl(_HIDIOCGRDESC, descriptor, True) return ''.join(chr(x) for x in descriptor.value[:size.value])
def getRawReportDescriptor(self)
Return a binary string containing the raw HID report descriptor.
5.186255
4.614914
1.123803
devinfo = _hidraw_devinfo() self._ioctl(_HIDIOCGRAWINFO, devinfo, True) return DevInfo(devinfo.bustype, devinfo.vendor, devinfo.product)
def getInfo(self)
Returns a DevInfo instance, a named tuple with the following items: - bustype: one of BUS_USB, BUS_HIL, BUS_BLUETOOTH or BUS_VIRTUAL - vendor: device's vendor number - product: device's product number
9.04359
5.846908
1.54673
name = ctypes.create_string_buffer(length) self._ioctl(_HIDIOCGRAWNAME(length), name, True) return name.value.decode('UTF-8')
def getName(self, length=512)
Returns device name as an unicode object.
6.169719
4.628067
1.333109
name = ctypes.create_string_buffer(length) self._ioctl(_HIDIOCGRAWPHYS(length), name, True) return name.value
def getPhysicalAddress(self, length=512)
Returns device physical address as a string. See hidraw documentation for value signification, as it depends on device's bus type.
9.965783
7.695482
1.295017
length = len(report) + 1 buf = bytearray(length) buf[0] = report_num buf[1:] = report self._ioctl( _HIDIOCSFEATURE(length), (ctypes.c_char * length).from_buffer(buf), True, )
def sendFeatureReport(self, report, report_num=0)
Send a feature report.
4.96821
4.824852
1.029712
length += 1 buf = bytearray(length) buf[0] = report_num self._ioctl( _HIDIOCGFEATURE(length), (ctypes.c_char * length).from_buffer(buf), True, ) return buf
def getFeatureReport(self, report_num=0, length=63)
Receive a feature report. Blocks, unless you configured provided file (descriptor) to be non-blocking.
5.906642
5.690143
1.038048
assert_corofunction(coro=coro) assert_iter(iterable=iterable) # Check valid or empty iterable if len(iterable) == 0: return iterable # Reduced accumulator value results = [None] * len(iterable) # Use a custom or default filter assertion function assert_fn = assert_fn or a...
def filter(coro, iterable, assert_fn=None, limit=0, loop=None)
Returns a list of all the values in coll which pass an asynchronous truth test coroutine. Operations are executed concurrently by default, but results will be in order. You can configure the concurrency via `limit` param. This function is the asynchronous equivalent port Python built-in `filt...
4.925547
5.510214
0.893894
assert_corofunction(coro=coro) assert_iter(iterable=iterable) # Reduced accumulator value passes = True # Handle empty iterables if len(iterable) == 0: return passes # Create concurrent executor pool = ConcurrentExecutor(limit=limit, loop=loop) # Tester function to g...
def every(coro, iterable, limit=1, loop=None)
Returns `True` if every element in a given iterable satisfies the coroutine asynchronous test. If any iteratee coroutine call returns `False`, the process is inmediately stopped, and `False` will be returned. You can increase the concurrency limit for a fast race condition scenario. This function...
7.538273
9.105178
0.827911
if isinstance(model, basestring): model = ctx.env[model] model.create(values).execute()
def define_settings(ctx, model, values)
Define settings like being in the interface Example : - model = 'sale.config.settings' or ctx.env['sale.config.settings'] - values = {'default_invoice_policy': 'delivery'} Be careful, settings onchange are not triggered with this function.
6.779065
5.09688
1.330042
# If no coroutines to schedule, return empty list (as Python stdlib) if len(coros_or_futures) == 0: return [] # Support iterable as first argument for better interoperability if len(coros_or_futures) == 1 and isiter(coros_or_futures[0]): coros_or_futures = coros_or_futures[0] ...
def gather(*coros_or_futures, limit=0, loop=None, timeout=None, preserve_order=False, return_exceptions=False)
Return a future aggregating results from the given coroutine objects with a concurrency execution limit. If all the tasks are done successfully, the returned future’s result is the list of results (in the order of the original sequence, not necessarily the order of results arrival). If return_exce...
3.61925
3.568413
1.014246
@asyncio.coroutine def _timeout(coro): return (yield from asyncio.wait_for(coro, timeout, loop=loop)) @asyncio.coroutine def wrapper(*args, **kw): return (yield from _timeout(coro(*args, **kw))) return _timeout(coro) if asyncio.iscoroutine(coro) else wrapper
def timeout(coro, timeout=None, loop=None)
Wraps a given coroutine function, that when executed, if it takes more than the given timeout in seconds to execute, it will be canceled and raise an `asyncio.TimeoutError`. This function is equivalent to Python standard `asyncio.wait_for()` function. This function can be used as decorator. A...
2.405692
3.082446
0.780449
assert_iter(iterable=iterable) # Store coros and internal state coros = [] resolved = False result = None # Resolve first yielded data from coroutine and stop pending ones @asyncio.coroutine def resolver(index, coro): nonlocal result nonlocal resolved valu...
def race(iterable, loop=None, timeout=None, *args, **kw)
Runs coroutines from a given iterable concurrently without waiting until the previous one has completed. Once any of the tasks completes, the main coroutine is immediately resolved, yielding the first resolved value. All coroutines will be executed in the same loop. This function is a coroutine. ...
5.185411
5.406337
0.959136
if not isfunction(fn): raise TypeError('paco: fn must be a callable object') spec = getargspec(fn) args = spec.args if not spec.varargs and (len(args) < 2 or args[1] != 'iterable'): raise ValueError('paco: invalid function signature or arity') @functools.wraps(fn) def deco...
def overload(fn)
Overload a given callable object to be used with ``|`` operator overloading. This is especially used for composing a pipeline of transformation over a single data set. Arguments: fn (function): target function to decorate. Raises: TypeError: if function or coroutine function is no...
4.388359
4.803545
0.913567
prefix = ' ' if parent and tokens: p_token = tokens[parent] if hasattr(p_token, 'line'): prefix = 'L.%3d.%03d: ' % (p_token.line, p_token.column) pass pass print("%s%s ::= %s" % (prefix, rule[0], ' '.join(rule...
def debug_reduce(self, rule, tokens, parent, i)
Customized format and print for our kind of tokens which gets called in debugging grammar reduce rules
4.581901
4.388877
1.04398
return list(generator) if not PY_35: raise RuntimeError( 'paco: asynchronous iterator protocol not supported') # If asynchronous generator, consume it generator protocol manually buf = [] while True: try: buf.append((yield from generator.__anext__())) ...
def consume(generator): # pragma: no cover # If synchronous generator, just consume and return as list if hasattr(generator, '__next__')
Helper function to consume a synchronous or asynchronous generator. Arguments: generator (generator|asyncgenerator): generator to consume. Returns: list
8.176106
9.969648
0.8201
return any([ inspect.isfunction(x) and not asyncio.iscoroutinefunction(x), inspect.ismethod(x) and not asyncio.iscoroutinefunction(x) ])
def isfunc(x)
Returns `True` if the given value is a function or method object. Arguments: x (mixed): value to check. Returns: bool
3.304436
4.707508
0.70195
for name, value in kw.items(): if not asyncio.iscoroutinefunction(value): raise TypeError( 'paco: {} must be a coroutine function'.format(name))
def assert_corofunction(**kw)
Asserts if a given values are a coroutine function. Arguments: **kw (mixed): value to check if it is an iterable. Raises: TypeError: if assertion fails.
4.820802
4.911672
0.981499
for name, value in kw.items(): if not isiter(value): raise TypeError( 'paco: {} must be an iterable object'.format(name))
def assert_iter(**kw)
Asserts if a given values implements a valid iterable interface. Arguments: **kw (mixed): value to check if it is an iterable. Raises: TypeError: if assertion fails.
6.261176
7.087735
0.883382
assert_corofunction(coro=coro) # Store maximum allowed number of calls times = int(times or 0) or float('inf') @asyncio.coroutine def schedule(times, *args, **kw): while times > 0: # Decrement times counter times -= 1 # Schedule coroutine ...
def interval(coro, interval=1, times=None, loop=None)
Schedules the execution of a coroutine function every `x` amount of seconds. The function returns an `asyncio.Task`, which implements also an `asyncio.Future` interface, allowing the user to cancel the execution cycle. This function can be used as decorator. Arguments: coro (coroutine...
3.906848
5.680393
0.687778
fn = func # remove blanks lines and comment lines, e.g. lines starting with "#" doc = os.linesep.join([s for s in doc.splitlines() if s and not re.match("^\s*#", s)]) rules = doc.split() index = [] for i in range(len(rules)): if rules[i] == '::=': ...
def addRule(self, doc, func, _preprocess=True)
Add a grammar rules to _self.rules_, _self.rule2func_, and _self.rule2name_ Comments, lines starting with # and blank lines are stripped from doc. We also allow limited form of * and + when there it is of the RHS has a single item, e.g. stmts ::= stmt+
3.691353
3.55111
1.039493
# remove blanks lines and comment lines, e.g. lines starting with "#" doc = os.linesep.join([s for s in doc.splitlines() if s and not re.match("^\s*#", s)]) rules = doc.split() index = [] for i in range(len(rules)): if rules[i] == '::=': inde...
def remove_rules(self, doc)
Remove a grammar rules from _self.rules_, _self.rule2func_, and _self.rule2name_
3.452355
3.199772
1.078938
print("\n-- Stacks of completed symbols:") states = [s for s in self.edges.values() if s] # States now has the set of states we are in state_stack = set() for state in states: # Find rules which can follow, but keep only # the part before the dot ...
def errorstack(self, tokens, i, full=False)
Show the stacks of completed symbols. We get this by inspecting the current transitions possible and from that extracting the set of states we are in, and from there we look at the set of symbols before the "dot". If full is True, we show the entire rule with the dot placement. ...
5.474211
4.035235
1.356603
self.tokens = tokens if debug: self.debug = debug sets = [ [(1, 0), (2, 0)] ] self.links = {} if self.ruleschanged: self.computeNull() self.newrules = {} self.new2old = {} self.makeNewRules() sel...
def parse(self, tokens, debug=None)
This is the main entry point from outside. Passing in a debug dictionary changes the default debug setting.
6.019774
5.915961
1.017548
for rule in sorted(self.rule2name.items()): out.write("%s\n" % rule2str(rule[0])) return
def dump_grammar(self, out=sys.stdout)
Print grammar rules
5.144641
4.693903
1.096026
''' Check grammar for: - unused left-hand side nonterminals that are neither start symbols or listed in ok_start_symbols - unused right-hand side nonterminals, i.e. not tokens - right-recursive rules. These can slow down parsing. ''' warnings = 0 ...
def check_grammar(self, ok_start_symbols = set(), out=sys.stderr)
Check grammar for: - unused left-hand side nonterminals that are neither start symbols or listed in ok_start_symbols - unused right-hand side nonterminals, i.e. not tokens - right-recursive rules. These can slow down parsing.
3.214269
2.180014
1.474426
''' Check grammar ''' lhs_set = set() rhs_set = set() rhs_rules_set = {} token_set = set() right_recursive = set() dup_rhs = {} for lhs in self.rules: rules_for_lhs = self.rules[lhs] lhs_set.a...
def check_sets(self)
Check grammar
3.257055
3.132909
1.039626
rule_str = self.reduce_string(rule) if rule_str not in self.profile_info: self.profile_info[rule_str] = 1 else: self.profile_info[rule_str] += 1
def profile_rule(self, rule)
Bump count of the number of times _rule_ was used
2.757777
2.490819
1.107177
return sorted(self.profile_info.items(), key=lambda kv: kv[1], reverse=False) return
def get_profile_info(self)
Show the accumulated results of how many times each rule was used
6.49798
5.671265
1.145773
assert_corofunction(coro=coro) @asyncio.coroutine def wrapper(*_args, **_kw): call_args = args + _args kw.update(_kw) return (yield from coro(*call_args, **kw)) return wrapper
def partial(coro, *args, **kw)
Partial function implementation designed for coroutines, allowing variadic input arguments. This function can be used as decorator. arguments: coro (coroutinefunction): coroutine function to wrap. *args (mixed): mixed variadic arguments for partial application. Raises: TypeErr...
3.719987
6.784095
0.548339
parser_debug = {'rules': False, 'transition': False, 'reduce': showgrammar, 'errorstack': True, 'context': True } parsed = parse_expr(expr_str, show_tokens=show_tokens, parser_debug=parser_debug) if showast: print(parsed) ass...
def eval_expr(expr_str, show_tokens=False, showast=False, showgrammar=False, compile_mode='exec')
evaluate simple expression
8.315786
8.738145
0.951665
length = len(node) if length == 1: self.preorder(node[0]) node.value = node[0].value self.prune() elif length == 3: self.preorder(node[1]) node.value = node[1].value self.prune() else: assert Fal...
def n_atom(self, node)
atom ::= NUMBER | '(' expr ')'
3.340982
2.917134
1.145296
if len(node) == 1: self.preorder(node[0]) node.value = node[0].value self.prune() else: self.preorder(node[0]) self.preorder(node[2]) if node[1].attr == '*': node.value = node[0].value * node[2].value ...
def n_term(self, node)
term ::= term MULT_OP atom | atom
2.842417
2.656798
1.069866
global CONFIG, BING_KEY, GENIUS_KEY, config_path, LOG_FILENAME, LOG_LINE_SEPERATOR LOG_FILENAME = 'musicrepair_log.txt' LOG_LINE_SEPERATOR = '........................\n' CONFIG = configparser.ConfigParser() config_path = realpath(__file__).replace(basename(__file__),'') config_path = co...
def setup()
Gathers all configs
4.743055
4.691912
1.0109
''' Provides a score out of 10 that determines the relevance of the search result ''' match_name = difflib.SequenceMatcher(None, song_name, song_title).ratio() match_title = difflib.SequenceMatcher(None, song_name, artist + song_title).ratio() if max(match_name,match_title) >= 0.55: ...
def matching_details(song_name, song_title, artist)
Provides a score out of 10 that determines the relevance of the search result
3.259427
2.33537
1.395679
''' Scrapes the lyrics of a song since spotify does not provide lyrics takes song title as arguement ''' lyrics = "" url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \ quote(song_name.encode('utf-8')) html = urlopen(url).read() soup = Beauti...
def get_lyrics_letssingit(song_name)
Scrapes the lyrics of a song since spotify does not provide lyrics takes song title as arguement
3.584615
2.80732
1.276882
''' Scrapes the lyrics from Genius.com ''' base_url = "http://api.genius.com" headers = {'Authorization': 'Bearer %s' %(GENIUS_KEY)} search_url = base_url + "/search" data = {'q': song_title} response = requests.get(search_url, data=data, headers=headers) json = response.json() ...
def get_lyrics_genius(song_title)
Scrapes the lyrics from Genius.com
2.18961
2.140193
1.02309
''' Tries finding metadata through Spotify ''' song_name = improvename.songname(song_name) spotify = spotipy.Spotify() results = spotify.search(song_name, limit=1) # Find top result log.log_indented('* Finding metadata from Spotify.') try: album = (results['tracks']['items']...
def get_details_spotify(song_name)
Tries finding metadata through Spotify
4.274178
3.885584
1.100009
''' Gets the song details if song details not found through spotify ''' song_name = improvename.songname(song_name) url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \ quote(song_name.encode('utf-8')) html = urlopen(url).read() soup = BeautifulS...
def get_details_letssingit(song_name)
Gets the song details if song details not found through spotify
3.045968
2.876392
1.058954
''' Adds the album art to the song ''' try: img = urlopen(albumart) # Gets album art from url except Exception: log.log_error("* Could not add album art", indented=True) return None audio = EasyMP3(song_title, ID3=ID3) try: audio.add_tags() except _uti...
def add_albumart(albumart, song_title)
Adds the album art to the song
3.801668
3.678961
1.033354
''' Adds the details to song ''' tags = EasyMP3(file_name) tags["title"] = title tags["artist"] = artist tags["album"] = album tags.save() tags = ID3(file_name) uslt_output = USLT(encoding=3, lang=u'eng', desc=u'desc', text=lyrics) tags["USLT::'eng'"] = uslt_output tag...
def add_details(file_name, title, artist, album, lyrics="")
Adds the details to song
3.860911
3.679063
1.049428
''' Searches for '.mp3' files in directory (optionally recursive) and checks whether they already contain album art and album name tags or not. ''' setup() if not Py3: file_name = file_name.encode('utf-8') tags = File(file_name) log.log(file_name) log.log('> Adding metada...
def fix_music(file_name)
Searches for '.mp3' files in directory (optionally recursive) and checks whether they already contain album art and album name tags or not.
4.961092
4.133483
1.200221
return (yield from filter(coro, iterable, assert_fn=assert_false, limit=limit, loop=loop))
def filterfalse(coro, iterable, limit=0, loop=None)
Returns a list of all the values in coll which pass an asynchronous truth test coroutine. Operations are executed concurrently by default, but results will be in order. You can configure the concurrency via `limit` param. This function is the asynchronous equivalent port Python built-in `filt...
8.213037
12.395675
0.662573
# Call each iterable but collecting yielded values return (yield from each(coro, iterable, limit=limit, loop=loop, timeout=timeout, collect=True, return_exceptions=return_exceptions))
def map(coro, iterable, limit=0, loop=None, timeout=None, return_exceptions=False, *args, **kw)
Concurrently maps values yielded from an iterable, passing then into an asynchronous coroutine function. Mapped values will be returned as list. Items order will be preserved based on origin iterable order. Concurrency level can be configurable via ``limit`` param. This function is the asynchrono...
7.931869
14.015261
0.565945
if not module_list: raise AnthemError(u"You have to provide a list of " "module's name to uninstall") mods = ctx.env['ir.module.module'].search([('name', 'in', module_list)]) try: mods.button_immediate_uninstall() except Exception: raise AnthemErro...
def uninstall(ctx, module_list)
uninstall module
5.635034
5.590962
1.007883
if not module_list: raise AnthemError(u"You have to provide a list of " "module's name to update the translations") for module in module_list: ctx.env['ir.module.module'].with_context(overwrite=True).search( [('name', '=', module)]).update_translations...
def update_translations(ctx, module_list)
Update translations from module list
6.001887
5.593951
1.072925
''' Bing image search ''' setup() album = album + " Album Art" api_key = "Key" endpoint = "https://api.cognitive.microsoft.com/bing/v5.0/images/search" links_dict = {} headers = {'Ocp-Apim-Subscription-Key': str(BING_KEY)} param = {'q': album, 'count': '1'} response = requests.g...
def img_search_bing(album)
Bing image search
3.299646
3.434301
0.960791
''' google image search ''' album = album + " Album Art" url = ("https://www.google.com/search?q=" + quote(album.encode('utf-8')) + "&source=lnms&tbm=isch") header = {'User-Agent': '''Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML,like Gecko...
def img_search_google(album)
google image search
2.632332
2.637509
0.998037
assert_corofunction(coro=coro) assert_iter(iterable=iterable) # By default do not collect yielded values from coroutines results = initializer if isiter(initializer) else [] @asyncio.coroutine def reducer(buf, value): if isiter(value): yield from _reduce(value) ...
def flat_map(coro, iterable, limit=0, loop=None, timeout=None, return_exceptions=False, initializer=None, *args, **kw)
Concurrently iterates values yielded from an iterable, passing them to an asynchronous coroutine. This function is the flatten version of to ``paco.map()``. Mapped values will be returned as an ordered list. Items order is preserved based on origin iterable order. Concurrency level can be configu...
5.780717
7.139307
0.809703
raise TypeError('paco: coro must be a coroutine function') @functools.wraps(coro) @asyncio.coroutine def wrapper(*args, **kw): if len(args) > 1 and isgenerator(args[1]): args = list(args) args[1] = (yield from consume(args[1]) if hasattr(args[1...
def generator_consumer(coro): # pragma: no cover if not asyncio.iscoroutinefunction(coro)
Decorator wrapper that consumes sync/async generators provided as interable input argument. This function is only intended to be used internally. Arguments: coro (coroutinefunction): function to decorate Raises: TypeError: if function or coroutine function is not provided. Return...
2.870955
3.145739
0.912649
if not isfunction(fn): raise TypeError('paco: fn must be a callable object') @functools.wraps(fn) def decorator(*args, **kw): # If coroutine object is passed for arg in args: if iscoro_or_corofunc(arg): return fn(*args, **kw) # Explicit argu...
def decorate(fn)
Generic decorator for coroutines helper functions allowing multiple variadic initialization arguments. This function is intended to be used internally. Arguments: fn (function): target function to decorate. Raises: TypeError: if function or coroutine function is not provided. Ret...
3.938699
4.341936
0.90713
role = matchedVars.get(ROLE) if role is not None and role.strip() == '': role = NULL else: valid = Authoriser.isValidRoleName(role) if valid: role = Authoriser.getRoleFromName(role) else: self.print("Invalid...
def _getRole(self, matchedVars)
:param matchedVars: :return: NULL or the role's integer value
5.121956
4.924736
1.040047
assert_corofunction(coro=coro) # Store execution limits limit = max(int(limit), 1) remaning = limit # Turn seconds in milliseconds timeframe = timeframe * 1000 # Keep call state last_call = now() # Cache latest retuned result result = None def stop(): if rais...
def throttle(coro, limit=1, timeframe=1, return_value=None, raise_exception=False)
Creates a throttled coroutine function that only invokes ``coro`` at most once per every time frame of seconds or milliseconds. Provide options to indicate whether func should be invoked on the leading and/or trailing edge of the wait timeout. Subsequent calls to the throttled coroutine return the...
4.587298
4.998403
0.917753
assert_corofunction(coro=coro, coro_test=coro_test) # Store yielded values by coroutine results = [] # Set assertion coroutine assert_coro = assert_coro or assert_true # Execute coroutine until a certain while (yield from assert_coro((yield from coro_test()))): results.append...
def whilst(coro, coro_test, assert_coro=None, *args, **kw)
Repeatedly call `coro` coroutine function while `coro_test` returns `True`. This function is the inverse of `paco.until()`. This function is a coroutine. Arguments: coro (coroutinefunction): coroutine function to execute. coro_test (coroutinefunction): coroutine function to test. ...
4.853053
6.512345
0.745208
if not os.path.isabs(path): if ctx.options.odoo_data_path: path = os.path.join(ctx.options.odoo_data_path, path) else: raise AnthemError( 'Got a relative path. ' 'Please, provide a value for `ODOO_DATA_PATH` ' 'in your envi...
def load_csv(ctx, model, path, header=None, header_exclude=None, **fmtparams)
Load a CSV from a file path. :param ctx: Anthem context :param model: Odoo model name or model klass from env :param path: absolute or relative path to CSV file. If a relative path is given you must provide a value for `ODOO_DATA_PATH` in your environment or set `--odoo-data-path` o...
3.364909
2.448722
1.374149
_header, _rows = read_csv(data, **fmtparams) header = header if header else _header if _rows: # check if passed header contains all the fields if header != _header and not header_exclude: # if not, we exclude the rest of the fields header_exclude = [x for x in _h...
def load_csv_stream(ctx, model, data, header=None, header_exclude=None, **fmtparams)
Load a CSV from a stream. :param ctx: current anthem context :param model: model name as string or model klass :param data: csv data to load :param header: csv fieldnames whitelist :param header_exclude: csv fieldnames blacklist Usage example:: from pkg_resources import Requirement, res...
4.253392
4.625075
0.919637
modules.update_translations(ctx, module_list) ctx.log_line(u'Deprecated: use anthem.lyrics.modules.update_translations' 'instead of anthem.lyrics.loaders.update_translations')
def update_translations(ctx, module_list)
Update translations from module list :param module_list: a list of modules
12.208756
11.991463
1.018121
parser_debug = {'rules': False, 'transition': False, 'reduce': showgrammar, 'errorstack': True, 'context': True, 'dups': True } parsed = parse_python2(python_stmts, show_tokens=show_tokens, parser_debug=parser_debug) assert parsed == '...
def format_python2_stmts(python_stmts, show_tokens=False, showast=False, showgrammar=False, compile_mode='exec')
formats python2 statements
7.738563
7.977767
0.970016
length = len(node) if length == 1: self.preorder(node[0]) elif length == 3: self.preorder(node[0]) self.preorder(node[1]) self.preorder(node[2]) else: assert False, "Expecting atom to have length 1 or 3" self.pr...
def n_atom(self, node)
atom ::= ('(' [yield_expr|testlist_gexp] ')' | '[' [listmaker] ']' | '{' [dictmaker] '}' | '`' testlist1 '`' | NAME | NUMBER | STRING+)
2.8174
2.80803
1.003337
self.write(self.indent, 'exec ') self.preorder(node[1]) if len(node) > 2: self.write(self.indent, ' in ') self.preorder(node[3]) if len(node) > 5: self.write(self.indent, ', ') self.preorder(node[5]) self.print...
def n_exec_stmt(self, node)
exec_stmt ::= EXEC expr exec_stmt ::= EXEC expr IN test exec_stmt ::= EXEC expr IN test COMMA test
2.854183
2.798034
1.020067
# self.println("-----") # print("XXX", startnode) fmt = entry[0] arg = 1 i = 0 m = escape.search(fmt) while m: i = m.end() self.write(m.group('prefix')) typ = m.group('kind') or '{' node = startnode ...
def template_engine(self, entry, startnode)
The format template interpetation engine. See the comment at the beginning of this module for the how we interpret format specifications such as %c, %C, and so on.
2.773048
2.738805
1.012503
''' Improves file name by removing crap words ''' try: song_name = splitext(song_name)[0] except IndexError: pass # Words to omit from song title for better results through spotify's API chars_filter = "()[]{}-:_/=+\"\'" words_filter = ('official', 'lyrics', 'audio', 're...
def songname(song_name)
Improves file name by removing crap words
4.958609
4.278925
1.158844
def wrapper(func): if info is not None: setattr(func, "_swg_info", info) if input is not None: setattr(func, "_swg_input", input) if output is not None: setattr(func, "_swg_output", output) return func return wrapper
def document(info=None, input=None, output=None)
Add extra information about request handler and its params
2.147964
2.03293
1.056586
assert_corofunction(coro=coro) @asyncio.coroutine def wrapper(): return (yield from coro()) return wrapper
def thunk(coro)
A thunk is a subroutine that is created, often automatically, to assist a call to another subroutine. Creates a thunk coroutine which returns coroutine function that accepts no arguments and when invoked it schedules the wrapper coroutine and returns the final result. See Wikipedia page for more i...
5.888741
11.232433
0.524262
r'\+=|-=|\*=|/=|%=|&=|\|=|^=|<<=|>>=|\*\*=|//=|//|==|<=|>=|<<|>>|[<>%^&+/=~-]' # Operators need to be further classified since the grammar requires this if s in ('<', '>', '==', '>=', '<=', '<>', '!='): self.add_token('COMP_OP', s) elif s in ('+=', '-=', '*=', '/=', '%=', '&...
def t_op(self, s)
r'\+=|-=|\*=|/=|%=|&=|\|=|^=|<<=|>>=|\*\*=|//=|//|==|<=|>=|<<|>>|[<>%^&+/=~-]
4.650622
3.53654
1.31502
r'[A-Za-z_][A-Za-z_0-9]*' if s in RESERVED_WORDS: self.add_token(s.upper(), s) else: self.add_token('NAME', s)
def t_name(self, s)
r'[A-Za-z_][A-Za-z_0-9]*
3.346551
3.172058
1.055009
r'\*\*?' token_name = "STARSTAR" if len(s) == 2 else 'STAR' self.add_token(token_name, s)
def t_star_star(self, s)
r'\*\*?
8.69661
5.757659
1.510442
r'([ \t]*[#].*[^\x04][\n]?)|([ \t]+)' if '#' in s: # We have a comment matches = re.match('(\s+)(.*[\n]?)', s) if matches and self.is_newline: self.handle_indent_dedent(matches.group(1)) s = matches.group(2) if s.endswith("\...
def t_whitespace_or_comment(self, s)
r'([ \t]*[#].*[^\x04][\n]?)|([ \t]+)
4.191565
3.06323
1.368348
assert_corofunction(coro=coro) assert_iter(iterable=iterable) # Reduced accumulator value acc = initializer # If interable is empty, just return the initializer value if len(iterable) == 0: return initializer # Create concurrent executor pool = ConcurrentExecutor(limit=li...
def reduce(coro, iterable, initializer=None, limit=1, right=False, loop=None)
Apply function of two arguments cumulatively to the items of sequence, from left to right, so as to reduce the sequence to a single value. Reduction will be executed sequentially without concurrency, so passed values would be in order. This function is the asynchronous coroutine equivalent to Python s...
5.053209
5.81311
0.869278
assert_corofunction(coro=coro) # Store call times limit = max(limit, 1) times = limit # Store result from last execution result = None @asyncio.coroutine def wrapper(*args, **kw): nonlocal limit nonlocal result # Check execution limit if limit == ...
def times(coro, limit=1, raise_exception=False, return_value=None)
Wraps a given coroutine function to be executed only a certain amount of times. If the execution limit is exceeded, the last execution return value will be returned as result. You can optionally define a custom return value on exceeded via `return_value` param. This function can be used as de...
4.448418
5.175857
0.859455
modules.uninstall(ctx, module_list) ctx.log_line(u'Deprecated: use anthem.lyrics.modules.uninstall instead of ' 'anthem.lyrics.uninstaller.uninstall')
def uninstall(ctx, module_list)
uninstall module
14.260812
13.356079
1.067739