code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
try: swlat, swlng = wgs_to_gk4(swlat, swlng) nelat, nelng = wgs_to_gk4(nelat, nelng) r = requests.get( url='https://www.dvb.de/apps/map/pins', params={ 'showlines': 'true', 'swlat': swlat, 'swlng': swlng, ...
def pins(swlat, swlng, nelat, nelng, pintypes='stop', *, raw=False)
DVB Map Pins (GET https://www.dvb.de/apps/map/pins) :param swlat: South-West Bounding Box Latitude :param swlng: South-West Bounding Box Longitude :param nelat: North-East Bounding Box Latitude :param nelng: North-East Bounding Box Longitude :param pintypes: Types to search for, defaults to 'st...
2.98338
2.659503
1.121781
try: r = requests.get( url='https://www.dvb.de/apps/map/coordinates', params={ 'id': poi_id, }, ) if r.status_code == 200: response = json.loads(r.content.decode('utf-8')) else: raise requests.HTTPError(...
def poi_coords(poi_id, *, raw=False)
DVB Map Coordinates (GET https://www.dvb.de/apps/map/coordinates) :param poi_id: Id of poi :param raw: Return raw response :return: Coordinates of poi
3.450651
2.902404
1.188894
try: lat, lng = wgs_to_gk4(lat, lng) r = requests.get( url='https://www.dvb.de/apps/map/address', params={ 'lat': lat, 'lng': lng, }, ) if r.status_code == 200: response = json.loads(r.content.decode...
def address(lat, lng, *, raw=False)
DVB Map Address (GET https://www.dvb.de/apps/map/address) :param lat: Latitude :param lng: Longitude :param raw: Return raw response :return: Dict of address
3.750075
3.003028
1.248765
digits = list(map(int, string)) odd_sum = sum(digits[-1::-2]) even_sum = sum([sum(divmod(2 * d, 10)) for d in digits[-2::-2]]) return (odd_sum + even_sum) % 10
def checksum(string)
Compute the Luhn checksum for the provided string of digits. Note this assumes the check digit is in place.
2.482711
2.071021
1.198786
blocked = True if ip in self.allowed_admin_ips: blocked = False for allowed_range in self.allowed_admin_ip_ranges: if ipaddress.ip_address(ip) in ipaddress.ip_network(allowed_range): blocked = False return blocked
def is_blocked(self, ip)
Determine if an IP address should be considered blocked.
3.132859
2.970816
1.054545
# Sever's parameters port = args.serve_port or PORT host = "0.0.0.0" # Current working directory dir_path = Path().absolute() web_dir = dir_path / "site" # Update routes utils.set_routes() # Offline mode if args.offline: os.environ["MKINX_OFFLINE"] = "true" ...
def serve(args)
Start a server which will watch .md and .rst files for changes. If a md file changes, the Home Documentation is rebuilt. If a .rst file changes, the updated sphinx project is rebuilt Args: args (ArgumentParser): flags from the CLI
3.551989
3.618966
0.981493
# Proceed? go = False # Current working directory dir_path = Path().resolve() # Set of all available projects in the dir # Projects must contain a PROJECT_MARKER file. all_projects = { m for m in os.listdir(dir_path) if os.path.isdir(m) and "source" in os.listd...
def build(args)
Build the documentation for the projects specified in the CLI. It will do 4 different things for each project the user asks for (see flags): 1. Update mkdocs's index.md file with links to project documentations 2. Build these documentations 3. Update the documentations' index....
3.645025
3.529116
1.032844
# working directory dir_path = Path().absolute() if not args.project_name or args.project_name.find("/") >= 0: print( "{}You should specify a valid project name{}".format( utils.colors.FAIL, utils.colors.ENDC ) ) return project_path ...
def init(args)
Initialize a Home Documentation's folder Args: args (ArgumentParser): Flags from the CLI
2.890129
2.826691
1.022442
while True: print(1) time.sleep(1) if random.randint(0, 9) >= 5: break
def train(self, X_train, Y_train, X_test, Y_test)
Train and validate the LR on a train and test dataset Args: X_train (np.array): Training data Y_train (np.array): Training labels X_test (np.array): Test data Y_test (np.array): Test labels
5.689068
6.200428
0.917528
if kind not in ALLOWED_KINDS: raise ValueError('`kind` must be one of {}, got {}'.format( ALLOWED_KINDS, kind)) # Make sure we have directories to dump files path = op.expanduser(path) if len(path) == 0: raise ValueError('You must specify a path. For current directory ...
def download(url, path, kind='file', progressbar=True, replace=False, timeout=10., verbose=True)
Download a URL. This will download a file and store it in a '~/data/` folder, creating directories if need be. It will also work for zip files, in which case it will unzip all of the files to the desired location. Parameters ---------- url : string The url of the file to download. ...
2.968302
3.00453
0.987942
if 'drive.google.com' in url: # For future support of google drive file_id = url.split('d/')[1].split('/')[0] base_url = 'https://drive.google.com/uc?export=download&id=' out = '{}{}'.format(base_url, file_id) elif 'dropbox.com' in url: if url.endswith('.png'): ...
def _convert_url_to_downloadable(url)
Convert a url to the proper style depending on its website.
2.435019
2.302234
1.057677
# Adapted from NISL and MNE-python: # https://github.com/nisl/tutorial/blob/master/nisl/datasets.py # https://martinos.org/mne if hash_ is not None and (not isinstance(hash_, string_types) or len(hash_) != 32): raise ValueError('Bad hash value given, should be ...
def _fetch_file(url, file_name, resume=True, hash_=None, timeout=10., progressbar=True, verbose=True)
Load requested file, downloading it if needed or requested. Parameters ---------- url: string The url of file to be downloaded. file_name: string Name, along with the path, of where downloaded file will be saved. resume: bool, optional If true, try to resume partially downlo...
3.091456
3.163184
0.977324
# Adapted from: https://pypi.python.org/pypi/fileDownloader.py # but with changes parsed_url = urllib.parse.urlparse(url) file_name = os.path.basename(parsed_url.path) server_path = parsed_url.path.replace(file_name, "") unquoted_server_path = urllib.parse.unquote(server_path) data = ...
def _get_ftp(url, temp_file_name, initial_size, file_size, verbose_bool, progressbar, ncols=80)
Safely (resume a) download to a file from FTP.
2.750156
2.75426
0.99851
# Actually do the reading req = urllib.request.Request(url) if initial_size > 0: req.headers['Range'] = 'bytes=%s-' % (initial_size,) try: response = urllib.request.urlopen(req) except Exception: # There is a problem that may be due to resuming, some # servers ma...
def _get_http(url, temp_file_name, initial_size, file_size, verbose_bool, progressbar, ncols=80)
Safely (resume a) download to a file from http(s).
2.847714
2.876273
0.990071
while True: data = fid.read(block_size) if not data: break md5.update(data) return md5.hexdigest()
def md5sum(fname, block_size=1048576): # 2 ** 20 md5 = hashlib.md5() with open(fname, 'rb') as fid
Calculate the md5sum for a file. Parameters ---------- fname : str Filename. block_size : int Block size to use when reading. Returns ------- hash_ : str The hexadecimal digest of the hash.
2.596098
2.826706
0.918418
local_file.write(chunk) if progress is not None: progress.update(len(chunk))
def _chunk_write(chunk, local_file, progress)
Write a chunk to file and update the progress bar.
2.670988
2.329966
1.146364
units = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'] decimals = [0, 0, 1, 2, 2, 2] if num > 1: exponent = min(int(log(num, 1024)), len(units) - 1) quotient = float(num) / 1024 ** exponent unit = units[exponent] num_decimals = decimals[exponent] format_string = '{0:.%s...
def sizeof_fmt(num)
Turn number of bytes into human-readable str. Parameters ---------- num : int The number of bytes. Returns ------- size : str The size in human-readable format.
1.485527
1.659829
0.894988
exc_classes = tuple(exc_classes) @wraps(f) def deco(*args, **kwargs): failures = 0 while True: try: return f(*args, **kwargs) except exc_classes as e: if logger is not None: logger.log(retry_log_level, ...
def retry(f, exc_classes=DEFAULT_EXC_CLASSES, logger=None, retry_log_level=logging.INFO, retry_log_message="Connection broken in '{f}' (error: '{e}'); " "retrying with new connection.", max_failures=None, interval=0, max_failure_log_level=logging.ERROR...
Decorator to automatically reexecute a function if the connection is broken for any reason.
1.748387
1.801532
0.9705
self.lock.acquire() try: c = self.conn.popleft() yield c except self.exc_classes: # The current connection has failed, drop it and create a new one gevent.spawn_later(1, self._addOne) raise except: self.conn...
def get(self)
Get a connection from the pool, to make and receive traffic. If the connection fails for any reason (socket.error), it is dropped and a new one is scheduled. Please use @retry as a way to automatically retry whatever operation you were performing.
6.26777
5.370054
1.167171
def _transformer(vals): if len(vals) == 0: return fills else: # ignore all but first effect match_eff_main = _prog_eff_main.match(vals[0]) if match_eff_main is None: logging.warning( 'match_eff_main is None: val...
def eff_default_transformer(fills=EFF_DEFAULT_FILLS)
Return a simple transformer function for parsing EFF annotations. N.B., ignores all but the first effect.
4.200841
3.878098
1.083222
def _transformer(vals): if len(vals) == 0: return fills else: # ignore all but first effect ann = vals[0].split(b'|') ann = ann[:11] + _ann_split2(ann[11]) + _ann_split2(ann[12]) + \ _ann_split2(ann[13]) + ann[14:] resu...
def ann_default_transformer(fills=ANN_DEFAULT_FILLS)
Return a simple transformer function for parsing ANN annotations. N.B., ignores all but the first effect.
4.089059
3.76015
1.087472
if sys.version_info < (3, 3): raise OverloadingError("The 'overload' syntax requires Python version 3.3 or higher.") fn = unwrap(func) ensure_function(fn) fname = get_full_name(fn) if fname.find('<locals>') >= 0: raise OverloadingError("The 'overload' syntax cannot be used with ...
def overload(func)
May be used as a shortcut for ``overloaded`` and ``overloads(f)`` when the overloaded function `f` can be automatically identified.
4.831922
4.616402
1.046686
fn = unwrap(func) ensure_function(fn) def dispatcher(*args, **kwargs): resolved = None if dispatcher.__complex_parameters: cache_key_pos = [] cache_key_kw = [] for argset in (0, 1) if kwargs else (0,): if argset == 0: ...
def overloaded(func)
Introduces a new overloaded function and registers its first implementation.
2.889462
2.878132
1.003936
wrapper = None if isinstance(func, (classmethod, staticmethod)): wrapper = type(func) func = func.__func__ ensure_function(func) if isinstance(dispatcher, (classmethod, staticmethod)): wrapper = None dp = unwrap(dispatcher) try: dp.__functions except Attr...
def register(dispatcher, func, *, hook=None)
Registers `func` as an implementation on `dispatcher`.
3.684529
3.643044
1.011388
matches = [] full_args = args full_kwargs = kwargs for func, sig in dispatcher.__functions: params = sig.parameters param_count = len(params) # Filter out arguments that will be consumed by catch-all parameters # or by keyword-only parameters. if sig.has_vara...
def find(dispatcher, args, kwargs)
Given the arguments contained in `args` and `kwargs`, returns the best match from the list of implementations registered on `dispatcher`.
3.469473
3.498439
0.991721
code = func.__code__ # Names of regular parameters parameters = tuple(code.co_varnames[:code.co_argcount]) # Flags has_varargs = bool(code.co_flags & inspect.CO_VARARGS) has_varkw = bool(code.co_flags & inspect.CO_VARKEYWORDS) has_kwonly = bool(code.co_kwonlyargcount) # A mapping...
def get_signature(func)
Gathers information about the call signature of `func`.
2.720997
2.648163
1.027504
if not typing or not isinstance(type_, typing.TypingMeta) or type_ is AnyType: return type_ if isinstance(type_, typing.TypeVar): if type_.__constraints__ or type_.__bound__: return type_ else: return AnyType if issubclass(type_, typing.Union): if...
def normalize_type(type_, level=0)
Reduces an arbitrarily complex type declaration into something manageable.
2.440425
2.441742
0.999461
if (not typing or not isinstance(type_, (typing.TypingMeta, GenericWrapperMeta)) or type_ is AnyType): return 0 if issubclass(type_, typing.Union): return reduce(operator.or_, map(type_complexity, type_.__union_params__)) if issubclass(type_, typing.Tuple): if type_....
def type_complexity(type_)
Computes an indicator for the complexity of `type_`. If the return value is 0, the supplied type is not parameterizable. Otherwise, set bits in the return value denote the following features: - bit 0: The type could be parameterized but is not. - bit 1: The type represents an iterable container with 1 ...
3.281833
3.283706
0.99943
for t in type_.__mro__: if t.__module__ == typing.__name__: return first_origin(t)
def find_base_generic(type_)
Locates the underlying generic whose structure and behavior are known. For example, the base generic of a type that inherits from `typing.Mapping[T, int]` is `typing.Mapping`.
7.014053
7.066732
0.992545
for t in type_.__mro__: if not isinstance(t, typing.GenericMeta): continue yield t t = t.__origin__ while t: yield t t = t.__origin__
def iter_generic_bases(type_)
Iterates over all generics `type_` derives from, including origins. This function is only necessary because, in typing 3.5.0, a generic doesn't get included in the list of bases when it constructs a parameterized version of itself. This was fixed in aab2c59; now it would be enough to just iterate over ...
2.908052
2.994788
0.971038
types1 = sig1.required types2 = sig2.required if len(types1) != len(types2): return False dup_pos = [] dup_kw = {} for t1, t2 in zip(types1, types2): match = type_cmp(t1, t2) if match: dup_pos.append(match) else: break else: ...
def sig_cmp(sig1, sig2)
Compares two normalized type signatures for validation purposes.
2.30035
2.297057
1.001434
try: source = dedent(inspect.getsource(func)) except (OSError, IOError): return False fdef = next(ast.iter_child_nodes(ast.parse(source))) return ( type(fdef) is ast.FunctionDef and len(fdef.body) == 1 and type(fdef.body[0]) is ast.Expr and type(fdef.body[0].value)...
def is_void(func)
Determines if a function is a void function, i.e., one whose body contains nothing but a docstring or an ellipsis. A void function can be used to introduce an overloaded function without actually registering an implementation.
2.768482
2.443
1.13323
doc = dispatcher.__doc__ or '' if inspect.cleandoc(doc).startswith('%s(' % dispatcher.__name__): return sig = '(...)' if func and func.__code__.co_argcount: argspec = inspect.getfullargspec(func) # pylint: disable=deprecated-method if argspec.args and argspec.args[0] in {'se...
def update_docstring(dispatcher, func=None)
Inserts a call signature at the beginning of the docstring on `dispatcher`. The signature is taken from `func` if provided; otherwise `(...)` is used.
3.040376
2.915078
1.042983
base_params = cls.base.__parameters__ if hasattr(cls.type, '__args__'): # typing as of commit abefbe4 tvars = {p: p for p in base_params} types = {} for t in iter_generic_bases(cls.type): if t is cls.base: type_...
def derive_configuration(cls)
Collect the nearest type variables and effective parameters from the type, its bases, and their origins as necessary.
3.292135
3.107684
1.059353
intersection = { 'alphabet': nfa_1['alphabet'].intersection(nfa_2['alphabet']), 'states': set(), 'initial_states': set(), 'accepting_states': set(), 'transitions': dict() } for init_1 in nfa_1['initial_states']: for init_2 in nfa_2['initial_states']: ...
def nfa_intersection(nfa_1: dict, nfa_2: dict) -> dict
Returns a NFA that reads the intersection of the NFAs in input. Let :math:`A_1 = (Σ,S_1,S_1^0,ρ_1,F_1)` and :math:`A_2 =(Σ, S_2,S_2^0,ρ_2,F_2)` be two NFAs. There is a NFA :math:`A_∧` that runs simultaneously both :math:`A_1` and :math:`A_2` on the input word, so :math:`L(A_∧) = L(A_1)∩L(A_2)`....
1.687328
1.714969
0.983882
union = { 'alphabet': nfa_1['alphabet'].union(nfa_2['alphabet']), 'states': nfa_1['states'].union(nfa_2['states']), 'initial_states': nfa_1['initial_states'].union(nfa_2['initial_states']), 'accepting_states': nfa_1['accepting_states'].union(nfa_2['accept...
def nfa_union(nfa_1: dict, nfa_2: dict) -> dict
Returns a NFA that reads the union of the NFAs in input. Let :math:`A_1 = (Σ,S_1,S_1^0,ρ_1,F_1)` and :math:`A_2 =(Σ, S_2,S_2^0,ρ_2,F_2)` be two NFAs. here is a NFA :math:`A_∨` that nondeterministically chooses :math:`A_1` or :math:`A_2` and runs it on the input word. It is defined as: :math:`A...
1.946192
2.043506
0.952379
def state_name(s): return str(set(sorted(s))) dfa = { 'alphabet': nfa['alphabet'].copy(), 'initial_state': None, 'states': set(), 'accepting_states': set(), 'transitions': dict() } if len(nfa['initial_states']) > 0: dfa['initial_state'] = st...
def nfa_determinization(nfa: dict) -> dict
Returns a DFA that reads the same language of the input NFA. Let A be an NFA, then there exists a DFA :math:`A_d` such that :math:`L(A_d) = L(A)`. Intuitively, :math:`A_d` collapses all possible runs of A on a given input word into one run over a larger state set. :math:`A_d` is defined as: :m...
1.811182
1.797055
1.007861
determinized_nfa = nfa_determinization(nfa) return DFA.dfa_complementation(determinized_nfa)
def nfa_complementation(nfa: dict) -> dict
Returns a DFA reading the complemented language read by input NFA. Complement a nondeterministic automaton is possible complementing the determinization of it. The construction is effective, but it involves an exponential blow-up, since determinization involves an unavoidable exponential blow-u...
6.830271
8.105303
0.842692
# BFS queue = list() visited = set() for state in nfa['initial_states']: visited.add(state) queue.append(state) while queue: state = queue.pop(0) visited.add(state) for a in nfa['alphabet']: if (state, a) in nfa['transitions']: ...
def nfa_nonemptiness_check(nfa: dict) -> bool
Checks if the input NFA reads any language other than the empty one, returning True/False. The language L(A) recognized by the automaton A is nonempty iff there are states :math:`s ∈ S_0` and :math:`t ∈ F` such that t is connected to s. Thus, automata nonemptiness is equivalent to graph reachabilit...
2.041513
1.999916
1.020799
# NAIVE Very inefficient (exponential space) : simply # construct Ā and then test its nonemptiness complemented_nfa = nfa_complementation(nfa) return DFA.dfa_nonemptiness_check(complemented_nfa)
def nfa_nonuniversality_check(nfa: dict) -> bool
Checks if the language read by the input NFA is different from Σ∗ (i.e. contains all possible words), returning True/False. To test nfa A for nonuniversality, it suffices to test Ā ( complementary automaton of A) for nonemptiness :param dict nfa: input NFA. :return: *(bool)*, True if input nfa...
28.538349
17.971035
1.588019
current_level = set() current_level = current_level.union(nfa['initial_states']) next_level = set() for action in word: for state in current_level: if (state, action) in nfa['transitions']: next_level.update(nfa['transitions'][state, action]) if len(next_...
def nfa_word_acceptance(nfa: dict, word: list) -> bool
Checks if a given word is accepted by a NFA. The word w is accepted by a NFA if exists at least an accepting run on w. :param dict nfa: input NFA; :param list word: list of symbols ∈ nfa['alphabet']; :return: *(bool)*, True if the word is accepted, False otherwise.
2.506346
2.564158
0.977454
conversion_dict = {} new_states = set() new_initials = set() new_accepting = set() for state in nfa['states']: conversion_dict[state] = '' + suffix + state new_states.add('' + suffix + state) if state in nfa['initial_states']: new_initials.add('' + suffix + s...
def rename_nfa_states(nfa: dict, suffix: str)
Side effect on input! Renames all the states of the NFA adding a **suffix**. It is an utility function to be used to avoid automata to have states with names in common. Avoid suffix that can lead to special name like "as", "and",... :param dict nfa: input NFA. :param str suffix: string to be ...
1.800252
1.91063
0.94223
project_html_location = dir_path / project / HTML_LOCATION if not project_html_location.exists(): return files_to_overwrite = [ f for f in project_html_location.iterdir() if "html" in f.suffix ] for html_file in files_to_overwrite: with open(html_file, "r") as f: ...
def overwrite_view_source(project, dir_path)
In the project's index.html built file, replace the top "source" link with a link to the documentation's home, which is mkdoc's home Args: project (str): project to update dir_path (pathlib.Path): this file's path
2.74632
2.609905
1.052268
index_path = Path().resolve() / "docs" / "index.md" with open(index_path, "r") as index_file: lines = index_file.readlines() listed_projects = set() project_section = False for _, l in enumerate(lines): idx = l.find(PROJECT_KEY) if idx >= 0: project_section ...
def get_listed_projects()
Find the projects listed in the Home Documentation's index.md file Returns: set(str): projects' names, with the '/' in their beginings
4.309828
4.261055
1.011446
os.system("pwd") dir_path = Path(os.getcwd()).absolute() projects = get_listed_projects() routes = [ [p if p[0] == "/" else "/" + p, str(dir_path) + "{}/build/html".format(p)] for p in projects ] os.environ["MKINX_ROUTES"] = json.dumps(routes)
def set_routes()
Set the MKINX_ROUTES environment variable with a serialized list of list of routes, one route being: [pattern to look for, absolute location]
6.267385
4.390648
1.42744
dir_path = Path(os.getcwd()).absolute() css_path = dir_path / "site" / "assets" / "stylesheets" material_css = css_path / "material-style.css" if not material_css.exists(): file_path = Path(__file__).resolve().parent copyfile(file_path / "material-style.css", material_css) ...
def make_offline()
Deletes references to the external google fonts in the Home Documentation's index.html file
2.688756
2.687417
1.000498
''' Returns a *list* of possible conversions for a given chromosome position. The list may be empty (no conversion), have a single element (unique conversion), or several elements (position mapped to several chains). The list contains tuples (target_chromosome, target_position, target_st...
def convert_coordinate(self, chromosome, position, strand='+')
Returns a *list* of possible conversions for a given chromosome position. The list may be empty (no conversion), have a single element (unique conversion), or several elements (position mapped to several chains). The list contains tuples (target_chromosome, target_position, target_strand, conversion_cha...
5.338026
1.896164
2.81517
if isinstance(filename, string_types): filenames = [filename] elif isinstance(filename, (list, tuple)): filenames = filename else: raise Exception('filename argument must be string, list or tuple') for fn in filenames: if not os.path.exists(fn): raise Val...
def _filenames_from_arg(filename)
Utility function to deal with polymorphic filenames argument.
1.851319
1.831541
1.010799
# ensure cache dir exists if cachedir is None: # use the VCF file name as the base for a directory name cachedir = vcf_fn + config.CACHEDIR_SUFFIX if not os.path.exists(cachedir): # ensure cache dir exists os.makedirs(cachedir) else: assert os.path.isdir(cac...
def _mk_cache_fn(vcf_fn, array_type, region=None, cachedir=None, compress=False)
Utility function to construct a filename for a cache file, given a VCF file name (where the original data came from) and other parameters.
2.688677
2.765738
0.972137
# guard condition if isinstance(vcf_fn, (list, tuple)): raise Exception( 'caching only supported when loading from a single VCF file' ) # create cache file name cache_fn = _mk_cache_fn(vcf_fn, array_type=array_type, region=region, cachedir=c...
def _get_cache(vcf_fn, array_type, region, cachedir, compress, log)
Utility function to obtain a cache file name and determine whether or not a fresh cache file is available.
3.280572
2.976462
1.102172
if fields is None: # no fields specified by user # by default extract all standard and INFO fields fields = config.STANDARD_VARIANT_FIELDS + info_ids else: # fields have been specified for f in fields: # check for non-standard fields not declared in INFO ...
def _variants_fields(fields, exclude_fields, info_ids)
Utility function to determine which fields to extract when loading variants.
4.703652
4.442802
1.058713
if arities is None: # no arities specified by user arities = dict() for f, vcf_count in zip(fields, info_counts): if f == 'FILTER': arities[f] = 1 # force one value for the FILTER field elif f not in arities: # arity not specified by user ...
def _variants_arities(fields, arities, info_counts)
Utility function to determine arities (i.e., number of values to expect) for variants fields.
3.86269
3.757801
1.027912
if fills is None: # no fills specified by user fills = dict() for f, vcf_type in zip(fields, info_types): if f == 'FILTER': fills[f] = False elif f not in fills: if f in config.STANDARD_VARIANT_FIELDS: fills[f] = config.DEFAULT_VARIANT...
def _variants_fills(fields, fills, info_types)
Utility function to determine fill values for variants fields with missing values.
3.365443
3.261366
1.031912
if transformers is None: # no transformers specified by user transformers = dict() for f in fields: if f not in transformers: transformers[f] = config.DEFAULT_TRANSFORMER.get(f, None) return tuple(transformers[f] for f in fields)
def _info_transformers(fields, transformers)
Utility function to determine transformer functions for variants fields.
3.46215
3.353515
1.032394
dtype = list() for f, n, vcf_type in zip(fields, arities, info_types): if f == 'FILTER' and flatten_filter: # split FILTER into multiple boolean fields for flt in filter_ids: nm = 'FILTER_' + flt dtype.append((nm, 'b1')) elif f == 'FIL...
def _variants_dtype(fields, dtypes, arities, filter_ids, flatten_filter, info_types)
Utility function to build a numpy dtype for a variants array, given user arguments and information available from VCF header.
3.08236
3.032057
1.01659
if progress > 0: it = _iter_withprogress(it, progress, log) if count is not None: a = np.fromiter(it, dtype=dtype, count=count) else: a = np.fromiter(it, dtype=dtype) return a
def _fromiter(it, dtype, count, progress, log)
Utility function to load an array from an iterator.
2.358512
2.324208
1.01476
before_all = time.time() before = before_all n = 0 for i, o in enumerate(iterable): yield o n = i+1 if n % progress == 0: after = time.time() log('%s rows in %.2fs; batch in %.2fs (%d rows/s)' % (n, after-before_all, after-before, prog...
def _iter_withprogress(iterable, progress, log)
Utility function to load an array from an iterator, reporting progress as we go.
2.531872
2.623351
0.965129
if fields is None: # no fields specified by user # default to all standard fields plus all FORMAT fields in VCF header fields = config.STANDARD_CALLDATA_FIELDS + format_ids else: # fields specified by user for f in fields: # check if field is standard or ...
def _calldata_fields(fields, exclude_fields, format_ids)
Utility function to determine which calldata (i.e., FORMAT) fields to extract.
4.142012
4.0047
1.034288
# stole from https://docs.python.org/3/library/datetime.html#datetime.datetime.timestamp if timezone.is_aware(v): return (v - timezone.datetime(1970, 1, 1, tzinfo=timezone.utc)).total_seconds() else: return (v - timezone.datetime(1970, 1, 1)).total_seconds()
def _datetime_to_timestamp(self, v)
Py2 doesn't supports timestamp()
2.167434
2.076147
1.043969
value = timezone.datetime.utcnow() if settings.USE_TZ: value = timezone.localtime( timezone.make_aware(value, timezone.utc), timezone.get_default_timezone() ) return value
def get_datetimenow(self)
get datetime now according to USE_TZ and default time
3.555758
2.969836
1.197291
if isinstance(value, (six.integer_types, float, six.string_types)): try: return float(value) except ValueError: value = self.datetime_str_to_datetime(value) if isinstance(value, datetime.datetime): return self._datetime_to_tim...
def to_timestamp(self, value)
from value to timestamp format(float)
2.886047
2.770496
1.041708
value = self.to_naive_datetime(value) if timezone.is_naive(value): value = timezone.make_aware(value, timezone.utc) else: value = timezone.localtime(value, timezone.utc) return value
def to_utc_datetime(self, value)
from value to datetime with tzinfo format (datetime.datetime instance)
2.450841
2.253638
1.087505
return timezone.localtime(self.to_utc_datetime(value), timezone.get_default_timezone())
def to_default_timezone_datetime(self, value)
convert to default timezone datetime
4.434756
3.784853
1.171712
if isinstance(value, (six.integer_types, float, six.string_types)): try: return int(value) except ValueError: value = self.datetime_str_to_datetime(value) if isinstance(value, datetime.datetime): if timezone.is_aware(value): ...
def to_timestamp(self, value)
from value to ordinal timestamp format(int)
2.746129
2.63163
1.043509
if isinstance(value, (six.integer_types, float, six.string_types)): try: return self.from_number(value) except ValueError: return self.datetime_str_to_datetime(value) if isinstance(value, datetime.datetime): return value ...
def to_naive_datetime(self, value)
from value to datetime with tzinfo format (datetime.datetime instance)
3.606604
3.373197
1.069194
if isinstance(value, (six.integer_types, float, six.string_types)): value = self.to_naive_datetime(value) if isinstance(value, datetime.datetime): if timezone.is_naive(value): value = timezone.make_aware(value, timezone.utc) else: ...
def to_utc_datetime(self, value)
from value to datetime with tzinfo format (datetime.datetime instance)
2.615808
2.504199
1.044569
return re.sub('|'.join(re.escape(key) for key in repls.keys()), lambda k: repls[k.group(0)], input)
def __replace_all(repls: dict, input: str) -> str
Replaces from a string **input** all the occurrences of some symbols according to mapping **repls**. :param dict repls: where #key is the old character and #value is the one to substitute with; :param str input: original string where to apply the replacements; :return: *(str)* the string with t...
3.072383
4.61906
0.665153
file = open(input_file) json_file = json.load(file) transitions = {} # key [state ∈ states, action ∈ alphabet] # value [arriving state ∈ states] for (origin, action, destination) in json_file['transitions']: transitions[origin, action] = destination dfa = { ...
def dfa_json_importer(input_file: str) -> dict
Imports a DFA from a JSON file. :param str input_file: path + filename to json file; :return: *(dict)* representing a DFA.
3.138534
3.113741
1.007963
out = { 'alphabet': list(dfa['alphabet']), 'states': list(dfa['states']), 'initial_state': dfa['initial_state'], 'accepting_states': list(dfa['accepting_states']), 'transitions': list() } for t in dfa['transitions']: out['transitions'].append( ...
def dfa_to_json(dfa: dict, name: str, path: str = './')
Exports a DFA to a JSON file. If *path* do not exists, it will be created. :param dict dfa: DFA to export; :param str name: name of the output file; :param str path: path where to save the JSON file (default: working directory)
1.800541
1.835039
0.9812
# pyDot Object g = pydot.graph_from_dot_file(input_file)[0] states = set() initial_state = None accepting_states = set() replacements = {'"': '', "'": '', '(': '', ')': '', ' ': ''} for node in g.get_nodes(): if node.get_name() == 'fake' \ or node.get_name() =...
def dfa_dot_importer(input_file: str) -> dict
Imports a DFA from a DOT file. Of DOT files are recognized the following attributes: • nodeX shape=doublecircle -> accepting node; • nodeX root=true -> initial node; • edgeX label="a" -> action in alphabet; • fake [style=invisible] -> dummy invisible node pointing ...
2.072392
1.872512
1.106744
g = graphviz.Digraph(format='svg') g.node('fake', style='invisible') for state in dfa['states']: if state == dfa['initial_state']: if state in dfa['accepting_states']: g.node(str(state), root='true', shape='doublecircle') else: ...
def dfa_to_dot(dfa: dict, name: str, path: str = './')
Generates a DOT file and a relative SVG image in **path** folder of the input DFA using graphviz library. :param dict dfa: DFA to export; :param str name: name of the output file; :param str path: path where to save the DOT/SVG files (default: working directory)
2.163466
2.166021
0.998821
file = open(input_file) json_file = json.load(file) transitions = {} # key [state in states, action in alphabet] # value [Set of arriving states in states] for p in json_file['transitions']: transitions.setdefault((p[0], p[1]), set()).add(p[2]) nfa = { '...
def nfa_json_importer(input_file: str) -> dict
Imports a NFA from a JSON file. :param str input_file: path+filename to JSON file; :return: *(dict)* representing a NFA.
3.130076
3.148985
0.993995
transitions = list() # key[state in states, action in alphabet] # value [Set of arriving states in states] for p in nfa['transitions']: for dest in nfa['transitions'][p]: transitions.append([p[0], p[1], dest]) out = { 'alphabet': list(nfa['alphabe...
def nfa_to_json(nfa: dict, name: str, path: str = './')
Exports a NFA to a JSON file. :param dict nfa: NFA to export; :param str name: name of the output file; :param str path: path where to save the JSON file (default: working directory).
2.843356
2.988473
0.951441
# pyDot Object g = pydot.graph_from_dot_file(input_file)[0] states = set() initial_states = set() accepting_states = set() replacements = {'"': '', "'": '', '(': '', ')': '', ' ': ''} for node in g.get_nodes(): attributes = node.get_attributes() if node.get_name() ==...
def nfa_dot_importer(input_file: str) -> dict
Imports a NFA from a DOT file. Of .dot files are recognized the following attributes • nodeX shape=doublecircle -> accepting node; • nodeX root=true -> initial node; • edgeX label="a" -> action in alphabet; • fakeX style=invisible -> dummy invisible nodes pointing t...
2.088657
1.90973
1.093692
g = graphviz.Digraph(format='svg') fakes = [] for i in range(len(nfa['initial_states'])): fakes.append('fake' + str(i)) g.node('fake' + str(i), style='invisible') for state in nfa['states']: if state in nfa['initial_states']: if state in nfa['accepting_states']...
def nfa_to_dot(nfa: dict, name: str, path: str = './')
Generates a DOT file and a relative SVG image in **path** folder of the input NFA using graphviz library. :param dict nfa: input NFA; :param str name: string with the name of the output file; :param str path: path where to save the DOT/SVG files (default: working directory).
2.137735
2.094981
1.020408
file = open(input_file) json_file = json.load(file) transitions = {} # key [state in states, action in alphabet] # value [string representing boolean expression] for p in json_file['transitions']: transitions[p[0], p[1]] = p[2] # return map afw = { 'alphabet': set(js...
def afw_json_importer(input_file: str) -> dict
Imports a AFW from a JSON file. :param str input_file: path+filename to input JSON file; :return: *(dict)* representing a AFW.
3.920448
3.958482
0.990392
# the word is accepted only if all the final states are # accepting states if len(remaining_word) == 0: if state in afw['accepting_states']: return True else: return False action = remaining_word[0] if (state, action) not in afw['transitions']: r...
def __recursive_acceptance(afw, state, remaining_word)
Recursive call for word acceptance. :param dict afw: input AFW; :param str state: current state; :param list remaining_word: list containing the remaining words. :return: *(bool)*, True if the word is accepted, false otherwise.
4.139259
4.14387
0.998887
return __recursive_acceptance(afw, afw['initial_state'], word)
def afw_word_acceptance(afw: dict, word: list) -> bool
Checks if a **word** is accepted by input AFW, returning True/False. The word w is accepted by a AFW if exists at least an accepting run on w. A run for AFWs is a tree and an alternating automaton can have multiple runs on a given input. A run is accepting if all the leaf nodes are accepting st...
14.209343
12.785245
1.111386
for state in afw['states']: for a in afw['alphabet']: if (state, a) not in afw['transitions']: afw['transitions'][state, a] = 'False' return afw
def afw_completion(afw)
Side effect on input! Complete the afw adding not present transitions and marking them as False. :param dict afw: input AFW.
4.532193
3.668706
1.235366
afw = { 'alphabet': nfa['alphabet'].copy(), 'states': nfa['states'].copy(), 'initial_state': 'root', 'accepting_states': nfa['accepting_states'].copy(), 'transitions': dict() } # Make sure "root" node doesn't already exists, in case rename it i = 0 while...
def nfa_to_afw_conversion(nfa: dict) -> dict
Returns a AFW reading the same language of input NFA. Let :math:`A = (Σ,S,S^0, ρ,F)` be an nfa. Then we define the afw AA such that :math:`L(AA) = L(A)` as follows :math:`AA = (Σ, S ∪ {s_0}, s_0 , ρ_A , F )` where :math:`s_0` is a new state and :math:`ρ_A` is defined as follows: • :math:`ρ_A(s, ...
2.962581
2.892419
1.024257
nfa = { 'alphabet': afw['alphabet'].copy(), 'initial_states': {(afw['initial_state'],)}, 'states': {(afw['initial_state'],)}, 'accepting_states': set(), 'transitions': dict() } # State of the NFA are composed by the union of more states of the AFW boundary...
def afw_to_nfa_conversion(afw: dict) -> dict
Returns a NFA reading the same language of input AFW. Let :math:`A = (Σ, S, s^0 , ρ, F )` be an afw. Then we define the nfa :math:`A_N` such that :math:`L(A_N) = L(A)` as follows :math:`AN = (Σ, S_N , S^0_N , ρ_N , F_N )` where: • :math:`S_N = 2^S` • :math:`S^0_N= \{\{s^0 \}\}` • :math:`F_...
3.579831
3.630411
0.986068
conversion_dictionary = { 'and': 'or', 'or': 'and', 'True': 'False', 'False': 'True' } return re.sub( '|'.join(re.escape(key) for key in conversion_dictionary.keys()), lambda k: conversion_dictionary[k.group(0)], input_formula)
def formula_dual(input_formula: str) -> str
Returns the dual of the input formula. The dual operation on formulas in :math:`B^+(X)` is defined as: the dual :math:`\overline{θ}` of a formula :math:`θ` is obtained from θ by switching :math:`∧` and :math:`∨`, and by switching :math:`true` and :math:`false`. :param str input_formula: original s...
2.978929
3.09826
0.961485
completed_input = afw_completion(deepcopy(afw)) complemented_afw = { 'alphabet': completed_input['alphabet'], 'states': completed_input['states'], 'initial_state': completed_input['initial_state'], 'accepting_states': completed_input['states'].difference(afw['ac...
def afw_complementation(afw: dict) -> dict
Returns a AFW reading the complemented language read by input AFW. Let :math:`A = (Σ, S, s^0 , ρ, F )`. Define :math:`Ā = (Σ, S, s^0 , \overline{ρ}, S − F )`, where :math:`\overline{ρ}(s, a) = \overline{ρ(s, a)}` for all :math:`s ∈ S` and :math:`a ∈ Σ`. That is, :math:`\overline{ρ}` is the dual...
3.641174
3.344487
1.088709
conversion_dict = {} new_states = set() new_accepting = set() for state in afw['states']: conversion_dict[state] = '' + suffix + state new_states.add('' + suffix + state) if state in afw['accepting_states']: new_accepting.add('' + suffix + state) afw['states...
def rename_afw_states(afw: dict, suffix: str)
Side effect on input! Renames all the states of the AFW adding a **suffix**. It is an utility function used during testing to avoid automata to have states with names in common. Avoid suffix that can lead to special name like "as", "and",... :param dict afw: input AFW. :param str suffix: stri...
2.372282
2.403653
0.986948
# make sure new root state is unique initial_state = 'root' i = 0 while initial_state in afw_1['states'] or initial_state in afw_2['states']: initial_state = 'root' + str(i) i += 1 union = { 'alphabet': afw_1['alphabet'].union(afw_2['alphabet']), 'states': ...
def afw_union(afw_1: dict, afw_2: dict) -> dict
Returns a AFW that reads the union of the languages read by input AFWs. Let :math:`A_1 = (Σ, S_1 , s^0_1, ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s^0_2, ρ_2 , F_2 )` be alternating automata accepting the languages :math:`L( A_1)` and :math:`L(A_2)`. Then, :math:`B_∪ = (Σ, S_1 ∪ S_2 ∪ {root}, ρ_...
2.199476
2.089042
1.052864
# make sure new root state is unique initial_state = 'root' i = 0 while initial_state in afw_1['states'] or initial_state in afw_2['states']: initial_state = 'root' + str(i) i += 1 intersection = { 'alphabet': afw_1['alphabet'].union(afw_2['alphabet']), 'states'...
def afw_intersection(afw_1: dict, afw_2: dict) -> dict
Returns a AFW that reads the intersection of the languages read by input AFWs. Let :math:`A_1 = (Σ, S_1 , s^0_1, ρ_1 , F_1 )` and :math:`A_2 = (Σ, S_2 , s^0_2, ρ_2 , F_2 )` be alternating automata accepting the languages :math:`L( A_1)` and :math:`L(A_2)`. Then, :math:`B_∩ = (Σ, S_1 ∪ S_2 ∪ {ro...
2.188237
2.117029
1.033636
nfa = afw_to_nfa_conversion(afw) return NFA.nfa_nonemptiness_check(nfa)
def afw_nonemptiness_check(afw: dict) -> bool
Checks if the input AFW reads any language other than the empty one, returning True/False. The afw is translated into a nfa and then its nonemptiness is checked. :param dict afw: input AFW. :return: *(bool)*, True if input afw is nonempty, False otherwise.
6.509939
4.677668
1.391706
nfa = afw_to_nfa_conversion(afw) return NFA.nfa_nonuniversality_check(nfa)
def afw_nonuniversality_check(afw: dict) -> bool
Checks if the language read by the input AFW is different from Σ∗, returning True/False. The afw is translated into a nfa and then its nonuniversality is checked. :param dict afw: input AFW. :return: *(bool)*, True if input afw is nonuniversal, False otherwise.
6.802397
4.030662
1.687663
if ((isinstance(value, types.UnicodeType) or isinstance(value, str)) and typeof is not dbus.String): # FIXME: This is potentially dangerous since it evaluates # a string in-situ return typeof(eval(value)) else: return typeof(value)
def translate_to_dbus_type(typeof, value)
Helper function to map values from their native Python types to Dbus types. :param type typeof: Target for type conversion e.g., 'dbus.Dictionary' :param value: Value to assign using type 'typeof' :return: 'value' converted to type 'typeof' :rtype: typeof
7.958793
8.99882
0.884426
self.user_callback(self.signal, self.user_arg, *args)
def signal_handler(self, *args)
Method to call in order to invoke the user callback. :param args: list of signal-dependent arguments :return:
10.353129
9.588226
1.079775
if (signal in self._signal_names): s = Signal(signal, callback_fn, user_arg) self._signals[signal] = s self._bus.add_signal_receiver(s.signal_handler, signal, dbus_interface=self._dbu...
def add_signal_receiver(self, callback_fn, signal, user_arg)
Add a signal receiver callback with user argument See also :py:meth:`remove_signal_receiver`, :py:exc:`.BTSignalNameNotRecognisedException` :param func callback_fn: User-defined callback function to call when signal triggers :param str signal: Signal name e.g., ...
4.626717
3.926996
1.178182
if (name): return self._interface.GetProperties()[name] else: return self._interface.GetProperties()
def get_property(self, name=None)
Helper to get a property value by name or all properties as a dictionary. See also :py:meth:`set_property` :param str name: defaults to None which means all properties in the object's dictionary are returned as a dict. Otherwise, the property name key is used and its va...
4.951038
6.328332
0.782361
typeof = type(self.get_property(name)) self._interface.SetProperty(name, translate_to_dbus_type(typeof, value))
def set_property(self, name, value)
Helper to set a property value by name, translating to correct dbus type See also :py:meth:`get_property` :param str name: The property name in the object's dictionary whose value shall be set. :param value: Properties new value to be assigned. :return: :rai...
10.741559
8.838313
1.21534
values = {"desired_state": {"mode": mode}} response = self.api_interface.set_device_state(self, values) self._update_state_from_response(response)
def set_mode(self, mode)
:param mode: a str, one of [home, away, night] :return: nothing
5.69939
6.3356
0.899582
values = {"desired_state": {"private": state}} response = self.api_interface.set_device_state(self, values) self._update_state_from_response(response)
def set_privacy(self, state)
:param state: True or False :return: nothing
6.710955
6.9649
0.963539
if isinstance(o, (datetime.datetime, datetime.date, datetime.time)): return o.isoformat() if isinstance(o, decimal.Decimal): return float(o) return json.JSONEncoder.default(self, o)
def default(self, o)
Encode JSON. :return str: A JSON encoded string
1.871198
2.149133
0.870675
if fields_own is not None: fields_own = {f.name for f in fields_own} else: fields_own = { f.name for f in instance._meta.fields if f.rel is None and f.serialize } fields_own.add('id') fields_own = (fields_own |...
def dump_document(cls, instance, fields_own=None, fields_to_many=None)
Get document for model_instance. redefine dump rule for field x: def dump_document_x :param django.db.models.Model instance: model instance :param list<Field> or None fields: model_instance field to dump :return dict: document Related documents are not included to current one....
4.017797
3.722606
1.079297
_response_json = response_json.get('data') if _response_json is not None: self.json_state = _response_json return True return False
def _update_state_from_response(self, response_json)
:param response_json: the json obj returned from query :return:
3.636784
3.663408
0.992732
attr_name = '_cached_' + f.__name__ def wrapper(obj, *args, **kwargs): if not hasattr(obj, attr_name): setattr(obj, attr_name, f(obj, *args, **kwargs)) return getattr(obj, attr_name) return wrapper
def _cached(f)
Decorator that makes a method cached.
2.060379
1.878383
1.09689
indexes_to_remove = set([]) for index1, field1 in enumerate(fields): for index2, field2 in enumerate(fields): if index1 < index2 and index1 not in indexes_to_remove and\ index2 not in indexes_to_remove: if issubclass(field1...
def _filter_child_model_fields(cls, fields)
Keep only related model fields. Example: Inherited models: A -> B -> C B has one-to-many relationship to BMany. after inspection BMany would have links to B and C. Keep only B. Parent model A could not be used (It would not be in fields) :param list fields: model fields. ...
2.007592
1.942947
1.033272