content
stringlengths
35
416k
sha1
stringlengths
40
40
id
int64
0
710k
def dscp_class(bits_0_2, bit_3, bit_4): """ Takes values of DSCP bits and computes dscp class Bits 0-2 decide major class Bit 3-4 decide drop precedence :param bits_0_2: int: decimal value of bits 0-2 :param bit_3: int: value of bit 3 :param bit_4: int: value of bit 4 :return: DSCP class name """ bits_3_4 = (bit_3 << 1) + bit_4 if bits_3_4 == 0: dscp_cl = "cs{}".format(bits_0_2) elif (bits_0_2, bits_3_4) == (5, 3): dscp_cl = "ef" else: dscp_cl = "af{}{}".format(bits_0_2, bits_3_4) return dscp_cl
79e9881e413a5fcbbbaab110e7b3346a2dbcaa53
705,684
def scale_to_one(iterable): """ Scale an iterable of numbers proportionally such as the highest number equals to 1 Example: >> > scale_to_one([5, 4, 3, 2, 1]) [1, 0.8, 0.6, 0.4, 0.2] """ m = max(iterable) return [v / m for v in iterable]
92cfc7ef586ecfea4300aeedabe2410a247610f7
705,686
def get_total_count(data): """ Retrieves the total count from a Salesforce SOQL query. :param dict data: data from the Salesforce API :rtype: int """ return data['totalSize']
7cb8696c36449425fbcfa944f1f057d063972888
705,688
def dummy_location(db, create_location): """Give you a dummy default location.""" loc = create_location(u'Test') db.session.flush() return loc
ec6ffa3b42e07c88b8224ee2aaaf000853a4169f
705,689
import os def list_profiles_in(path): """list profiles in a given root directory""" files = os.listdir(path) profiles = [] for f in files: full_path = os.path.join(path, f) if os.path.isdir(full_path) and f.startswith('profile_'): profiles.append(f.split('_',1)[-1]) return profiles
1e377b2a686d3c63e569c57af7415a9604b3709e
705,691
def extractLine(shape, z = 0): """ Extracts a line from a shape line. """ x = shape.exteriorpoints()[0][0] - shape.exteriorpoints()[1][0] y = shape.exteriorpoints()[0][1] - shape.exteriorpoints()[1][1] return (x, y, z)
c61021b1e3dc6372d9d7554a7033bbd3ab128343
705,692
def substring_in_list(substr_to_find, list_to_search): """ Returns a boolean value to indicate whether or not a given substring is located within the strings of a list. """ result = [s for s in list_to_search if substr_to_find in s] return len(result) > 0
77521a1c5d487fa110d5adecb884dd298d2515e5
705,693
def getQueryString( bindings, variableName ): """ Columns a bunch of data about the bindings. Will return properly formatted strings for updating, inserting, and querying the SQLite table specified in the bindings dictionary. Will also return the table name and a string that lists the columns (properly formatted for use in an SQLite query). variableName is the name to use for the SQLiteC++ Statement variable in the generated methods. """ table = '' columns = [] queryData = [] insertData = [] updateData = [] whereClaus = [] bindData = [] index = 0 for b in bindings: # Process table if (b['type'] == 'table'): table = b['table'] # Process column elif (b['type'] == 'column'): columns.append( b['column'] ) # Process query data if (b['variableType'] == 'string'): text = '{variable} = std::string( {query}.getColumn({index}).getText() );' text = text.format(variable = b['variable'], index = index, query = variableName) queryData.append( text ) else: text = '{variable} = {query}.getColumn({index});' text = text.format(variable = b['variable'], index = index, query = variableName) queryData.append( text ) index = index + 1 # Process insert data if (b['variableType'] == 'string' or b['variableType'] == 'char*'): insertData.append( "\"'\" << " + b['variable'] + " << \"'\"" ) else: insertData.append( b['variable'] ) # Process id if (b.get('id')): whereClaus.append( b['column'] + ' = ?' ) text = 'query.bind({index}, {variableName});' text = text.format(index = len(whereClaus), variableName = b['variable']) bindData.append( text ) # Process update data for i in range(0, len(columns)): t = columns[i] + '=" << ' + insertData[i] updateData.append(t) columns = ', '.join( columns ) updateData = ' << ", '.join( updateData ) insertData = ' << \", " << '.join( insertData ) queryData = '\n'.join( queryData ) whereClaus = ' AND '.join( whereClaus ) bindData = '\n\t'.join( bindData ) return { 'table': table, 'updateData': updateData, 'columns': columns, 'insertData': insertData, 'queryData': queryData, 'whereClaus': whereClaus, 'bindData': bindData }
9cc81601cde229cc5f5bf53ef73997efc515ed2b
705,694
def average(l): """ Computes average of 2-D list """ llen = len(l) def divide(x): return x / float(llen) return list(map(divide, map(sum, zip(*l))))
67395ce4417022a673565a8227c684b7649a5e6a
705,695
import json def getPath(): """ Gets path of the from ./metadata.json/ """ with open('metadata.json', 'r') as openfile: global path json_object = json.load(openfile) pairs = json_object.items() path = json_object["renamer"]["path"] return path
03047172e653b4b4aee7f096a67291ad460969c9
705,696
def axes_to_list(axes_data: dict) -> list: """helper method to convert a dict of sensor axis graphs to a 2d array for graphing """ axes_tuples = axes_data.items() axes_list = [axes[1].tolist() for axes in axes_tuples] return axes_list
fb2e5ef1f2283e2f31e5c8828a3ec7ef94869c5c
705,697
from typing import Iterable import functools import operator def prod(values: Iterable[int]) -> int: """Compute the product of the integers.""" return functools.reduce(operator.mul, values)
3f03200078daf1b0b27f777e7744144ab72ec7af
705,698
def get_stars_dict(stars): """ Transform list of stars into dictionary where keys are their names Parameters ---------- stars : list, iterable Star objects Return ------ dict Stars dictionary """ x = {} for st in stars: try: x[st.name] = st except: pass return x
6d627be48a96d8ba93bd13511a05c251f3a3f169
705,699
def clean_packages_list(packages): """ Remove comments from the package list """ lines = [] for line in packages: if not line.startswith("#"): lines.append(line) return lines
a6c942f9b90c8f6c610ba0b57728f3da48f35ded
705,700
import random def IndividualBuilder(size, possList, probList): """ Args: size (int) - the list size to be created PossArr - a list of the possible mutations types (mutation, deletion,...) ProbArr - a list of the probibilities of the possible mutations occuring. Returns: individual (list) """ if(len(list(possList)) != len(list(probList))): raise Exception('len(PossArr) != len(ProbArr)') individual = [0]*size random.seed() for i in range(size): for j in range(len(possList)): if(random.random() <= probList[j]): individual[i] = possList[j] return individual
055d582fffbc2e13a25a17012831c098fc89330d
705,701
import os def get_file_open_command(script_path, turls, nthreads): """ :param script_path: path to script (string). :param turls: comma-separated turls (string). :param nthreads: number of concurrent file open threads (int). :return: comma-separated list of turls (string). """ return "%s --turls=%s -w %s -t %s" % (script_path, turls, os.path.dirname(script_path), str(nthreads))
9d85df723cf6512e876c2c953ab2229f947ef40e
705,702
import os import sys def setup_parameters(): """ This function sets up the hyperparameters needed to train the model. Returns: hyperparameters : Dictionary containing the hyperparameters for the model. options : Dictionary containing the options for the dataset location, augmentation, etc. """ # Dataset location for training. dataset_fp = "/file/path/to/dataset" # Indicate if LiDAR data is included. If it is then no padding or augmenting prior to training # will be done. If you still want padding then enable it in the model. use_lidar = True # File with previously trained weights. Leave as None if you don't want to load any pre_trained_weights = None # Starting epoch start_epoch = 1 # Max number of epochs epochs = 80 # Starting learning rate for the Adam optimizer learn_rate = 0.001 # Adjusts the learning rate by (learn_rate / 10) after every lr_change epochs lr_change = 25 # Weighted Cross Entropy (put 1.0 for each class if you don't want to add weights) class_weights = [0.5, 1.0] # Indicate if you want to augment the training images and labels augment = False # Size of the batch fed into the model. Model can handle a larger batch size when training. # Batch size used during training. training_batch_size = 10 # Batch size used during validation. valid_batch_size = 5 # Model's learned parameters (i.e. weights and biases) that achieved the lowest loss. Will be # saved as "saved_model.pt". A file called "saved_model_last_epoch.pt" will also be saved with # the learned parameters in the last completed epoch. saved_model = "saved_model" ### MODEL PARAMETERS ### # Number of input channels in_channels = 4 # Number of output channels n_classes = 2 # How deep the network will be depth = 7 # Number of filters in the first layer (2**wf) wf = 6 # Indicate if you want the model to pad the images back to their original dimensions # Images need to be 256x256 if this is set to False pad = True # Specify if you want to enable batch normalization batch_norm = True # Supported modes are 'upconv' and 'upsample' up_mode = 'upconv' # Store the options in a dictionary options = { 'pre_trained_weights': pre_trained_weights, 'start_epoch': start_epoch, 'dataset_fp': dataset_fp, 'saved_model': saved_model, 'in_channels': in_channels, 'n_classes': n_classes, 'augment': augment, 'use_lidar': use_lidar } # Store the hyperparameters in a dictionary hyperparameters = { 'epochs': epochs, 'learn_rate': learn_rate, 'lr_change': lr_change, 'class_weights': class_weights, 'training_batch_size': training_batch_size, 'valid_batch_size': valid_batch_size, 'in_channels': in_channels, 'depth': depth, 'wf': wf, 'pad': pad, 'batch_norm': batch_norm, 'up_mode': up_mode } # Make sure the file paths exist if pre_trained_weights is not None and not os.path.isfile(pre_trained_weights): sys.exit('Error: Pre-trained weights file does not exist') if not os.path.isdir(dataset_fp): sys.exit('Error: Main file path to the training and validation images does not exist') return hyperparameters, options
0e3c0e30618062b6c3b7b252a714a5dab2b09cba
705,703
def get_genres_from_games(games, their_games): """ From the games we will get the same genres """ genres = set() for d in games: n = d['id'] if n in their_games: genres.add(d['Genre']) return genres
27bbf3c5ba40c6443e12b4119943c40879ceb622
705,704
import pathlib import platform import os def get_candidate_dir(): """ Returns a valid directory name to store the pictures. If it can not be determined, "" is returned. requires: import os import pathlib import platform https://docs.python.org/3/library/pathlib.html#pathlib.Path.home New in version 3.5. https://docs.python.org/3.8/library/platform.html#platform.system Returns the system/OS name, such as 'Linux', 'Darwin', 'Java', 'Windows'. An empty string is returned if the value cannot be determined. """ home_dir = pathlib.Path().home() target_dir = home_dir system = platform.system() if system == "Windows": target_dir = os.path.join(home_dir, "Pictures") elif system == "Darwin": target_dir = os.path.join(home_dir, "Pictures") elif system == "Linux": target_dir = os.path.join(home_dir, "Pictures") if os.path.isdir(target_dir): # pylint: disable=no-else-return return target_dir elif os.path.isdir(home_dir): return home_dir else: return ""
48353d226da4a6fdc4ca3208118b01c406e00dfb
705,706
def add_kwds(dictionary, key, value): """ A simple helper function to initialize our dictionary if it is None and then add in a single keyword if the value is not None. It doesn't add any keywords at all if passed value==None. Parameters ---------- dictionary: dict (or None) A dictionary to copy and update. If none it will instantiate a new dictionary. key: str A the key to add to the dictionary value: object (or None) A value to add to the dictionary. If None then no key, value pair will be added to the dictionary. Returns ------- dictionary A copy of dictionary with (key,value) added into it or a new dictionary with (key,value) in it. """ if dictionary is None: kwds = {} else: kwds = dictionary.copy() if (value is not None) and (key is not None): kwds.update({key: value}) return kwds
96aa104f86e521e419d51096b6c1f86e4b506c57
705,707
def _get_cindex(circ, name, index): """ Find the classical bit index. Args: circ: The Qiskit QuantumCircuit in question name: The name of the classical register index: The qubit's relative index inside the register Returns: The classical bit's absolute index if all registers are concatenated. """ ret = 0 for reg in circ.cregs: if name != reg.name: ret += reg.size else: return ret + index return ret + index
340105a2ddfe5fb2527171a7592390c9dd2937e5
705,708
def get_bin(pdf: str) -> str: """ Get the bins of the pdf, e.g. './00/02/Br_J_Cancer_1977_Jan_35(1)_78-86.tar.gz' returns '00/02'. """ parts = pdf.split('/') return parts[-3] + '/' + parts[-2] + '/'
a1e25162b8a353f508667ccb4fc750e51fcf611d
705,709
def burkert_density(r, r_s, rho_o): """ Burkert dark matter density profile """ x = r / r_s density = rho_o / ( (x) * (1.0 + x)**2) return density.to('g/cm**3')
8293a62b6c52c65e7c5fe7c676fd3807f301e40b
705,711
def area_description(area,theory_expt): """ Generate plain-language name of research area from database codes. """ area_name_by_area = { "As" : "Astrophysics", "BP" : "Biophysics", "CM" : "Condensed matter", "HE" : "High energy", "NS" : "Network science", "NUC" : "Nuclear", "" : None } area_name = area_name_by_area[area] if (area=="As" and theory_expt=="Experimental"): qualifier = "observation" elif (theory_expt=="Experimental"): qualifier = "experiment" elif (theory_expt=="Theory"): qualifier = "theory" else: qualifier = "" return "{} {}".format(area_name,qualifier)
d7743c2d80d9a74dd6a24f735b7c0a389eb36468
705,712
def parse_username_password_hostname(remote_url): """ Parse a command line string and return username, password, remote hostname and remote path. :param remote_url: A command line string. :return: A tuple, containing username, password, remote hostname and remote path. """ assert remote_url assert ':' in remote_url if '@' in remote_url: username, hostname = remote_url.rsplit('@', 1) else: username, hostname = None, remote_url hostname, remote_path = hostname.split(':', 1) password = None if username and ':' in username: username, password = username.split(':', 1) assert hostname assert remote_path return username, password, hostname, remote_path
50410ad87865559af84b83ab6bdfae19e536791d
705,713
import ast def skip_node(node): """Whether to skip a step in the traceback based on ast node type.""" return isinstance(node, (ast.If, ast.While, ast.For))
2406d02190a4dccb3d1f5d743a742f82c97f6541
705,714
def convertASTtoThreeAddrForm(ast): """Convert an AST to a three address form. Three address form is (op, reg1, reg2, reg3), where reg1 is the destination of the result of the instruction. I suppose this should be called three register form, but three address form is found in compiler theory. """ return [(node.value, node.reg) + tuple([c.reg for c in node.children]) for node in ast.allOf('op')]
17bcd628b2b6feb916cdfaea2f6a210f47afa7bf
705,715
def lc_reverse_integer(n): """ Given a 32-bit signed integer, reverse digits of an integer. Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows. Examples: >>> lc_reverse_integer(123) 321 >>> lc_reverse_integer(-123) -321 >>> lc_reverse_integer(120) 21 """ class Solution(object): @staticmethod def reverse(x): neg = x < 0 if neg: x = -x result = 0 while x: result = result * 10 + x % 10 x /= 10 if result > 2 ** 31: return 0 return -result if neg else result return Solution.reverse(n)
eff1054873ef0e77a82e34b7cf7af51d42f27d6c
705,716
from typing import Optional import logging import tempfile import sys import subprocess def install_to_temp_directory(pip_dependency: str, temp_dir: Optional[str] = None) -> str: """Install the given pip dependency specifier to a temporary directory. Args: pip_dependency: Path to a wheel file or a pip dependency specifier (e.g. "setuptools==18.0"). temp_dir: Path to temporary installation location (optional). Returns: Temporary directory where the package was installed, that should be added to the Python import path. """ logging.info('Installing %r to a temporary directory.', pip_dependency) if not temp_dir: temp_dir = tempfile.mkdtemp() install_command = [ sys.executable, '-m', 'pip', 'install', '--target', temp_dir, pip_dependency ] logging.info('Executing: %s', install_command) subprocess.check_call(install_command) logging.info('Successfully installed %r.', pip_dependency) return temp_dir
6f18fd2e3a2ade2c0e770076cc29df8ef4cca5b3
705,717
def alias_phased_obs_with_phase(x, y, start, end): """ :param x: a list containing phases :param y: a list containing observations :param start: start phase :param end: end phase :return: aliased phases and observations """ x = [float(n) for n in x] y = [float(n) for n in y] if start > end: raise ValueError("Start phase can't be larger than stop phase.") if len(x) != len(y): raise ValueError("x and y must be the same size.") distance = int(start - min(x)) if (distance == 0 and min(x) > start) or (distance < 0 < min(x)): distance = distance - 1 x = [phase + distance for phase in x] new_x = x[:] new_y = y[:] i = 1 while max(new_x) < end: x_temp = [phase + i for phase in x] new_x = new_x + x_temp new_y = new_y + y[:] i = i + 1 _x = [] _y = [] for phase, value in zip(new_x, new_y): if start <= phase <= end: _x.append(phase) _y.append(value) return _x, _y
4b9bd3507180d2e7cd2c9957e1c2ea4ce3e17cb6
705,718
import platform def get_os(): """ Checks the OS of the system running and alters the directory structure accordingly :return: The directory location of the Wordlists folder """ if platform.system() == "Windows": wordlist_dir = "Wordlists\\" else: wordlist_dir = "Wordlists/" return wordlist_dir
6f4a6f70505b1512987e75a069a960b136f66d97
705,719
def check_derivation(derivation, premises, conclusion): """Checks if a derivation is ok. If it is, returns an empty list, otherwise returns [step, error] Does not check if the conclusion and premises are ok, for that there is another function""" for step in sorted(derivation): try: # See that the on steps are all between 1 and the current step for s in derivation[step]['on_steps']: if not 0 < s < step: raise ValueError("Incorrect 'on steps' specification") current_sups = derivation[step]['open_sups'][:] previous_sups = list() if step > 1: previous_sups = derivation[step-1]['open_sups'][:] # If the step does not open or close any previous supossitions, or closes the last open one if (current_sups == previous_sups or current_sups == previous_sups[:-1]) and \ derivation[step]['rule'] != 'SUP': if derivation[step]['rule'] == 'PREM': # Check that the formula is a premise if derivation[step]['formula'] not in premises: raise ValueError("Formula given is not among the premises") # Check that this is the first step or that the previous step is also a premise # And that the steps field is empty if (step == 1 or derivation[step-1]['rule'] == 'PREM') and derivation[step]['on_steps'] == list(): pass else: raise ValueError("Premises go at the beggining of the derivation and have empty 'on steps'") else: # A rule is being applied prev_steps = list() for s in derivation[step]['on_steps']: if s not in derivation: raise ValueError(f"Non existent step {s}") prev_steps.append(derivation[s]) results = derivation[step]['rule'](derivation[step], prev_steps) is_ok = False for result in results: if derivation[step]['formula'] == result: is_ok = True if not is_ok: raise ValueError("Rule incorrectly applied") # Y FINALMENTE VER SI LA FORMULA DEL PASO COINCIDE CON ALGUNO DE LOS RETURNS pass # If it contains one more supposition (the current step opens one) elif current_sups[:-1] == previous_sups and current_sups[-1] == step: # The rule must be SUP and the on_steps must be empty if derivation[step]['rule'] == 'SUP' and derivation[step]['on_steps'] == list(): pass else: raise ValueError("Only SUP can open suppositions, and it must have empty 'on steps'") else: raise ValueError("Incorrect handling of suppositions") except ValueError as e: return [step, str(e)] # Lastly, see that the derivation does not contain open suppositions at the last step, # and that the conclusion is the last step last_step = max(derivation) if derivation[last_step]['open_sups'] != list(): return [last_step, 'The derivation ends with open suppositions'] elif derivation[last_step]['formula'] != conclusion: return [last_step, 'The rules are correctly applied but the final formula is not the conclusion'] return []
67c15ae26ee399e95808495845c260ca55808532
705,720
def uniques_only(iterable): """ This works only for sequence, but not for all iterable """ items = [] for i, n in enumerate(iterable): if n not in iterable[:i]: items.append(n) return items
159e220be340fc027053b7dbae0d146ae88ceea9
705,721
def tsallis(ion_temp, avg_temp, n): """ Non-normalized probability of an ion at ion-temp using a Tsallis distribution :param ion_temp: temperature of ion (K) :param avg_temp: average temperature of ions (K) :param n: average harmonic oscillator level :return: value """ kb = 1.38e-23 energy = ion_temp * kb top = (n - 3) * (n - 2) * (n - 1) * energy ** 2 bot = 2 * (n * kb * avg_temp) ** 3 * (1 + energy / (n * kb * avg_temp)) ** n output = top / bot return output
4598c5241fc06219938beced4c9d5a4473cf8363
705,722
def _extractRGBFromHex(hexCode): """ Extract RGB information from an hexadecimal color code Parameters: hexCode (string): an hexadecimal color code Returns: A tuple containing Red, Green and Blue information """ hexCode = hexCode.lstrip('#') # Remove the '#' from the string # Convert each byte into decimal, store it in a tuple and return return tuple(int(hexCode[i:i+2], 16) for i in (0, 2, 4))
e1d67b4f2004e5e2d4a646a3cc5dc49a1e8cd890
705,723
def summarise(indices, fields, **kwargs): """Summarise taxonomy.""" summary = {} meta = kwargs['meta'] try: if 'taxid' in meta.taxon: summary.update({'taxid': meta.taxon['taxid']}) names = [] for rank in ('superkingdom', 'kingdom', 'phylum', 'class', 'order', 'family', 'genus', 'species'): if rank in meta.taxon: names.append(meta.taxon[rank]) if names: summary.update({'lineage': '; '.join(names)}) if 'cat' in meta.plot: rank = meta.plot['cat'].split('_')[-1] summary.update({'targetRank': rank}) summary.update({'target': meta.taxon[rank]}) except Exception: pass return summary
87f04cb86978e2350f3e535b65a1efa14af77ee8
705,724
def get_user_partition_groups(course_key, user_partitions, user, partition_dict_key='name'): """ Collect group ID for each partition in this course for this user. Arguments: course_key (CourseKey) user_partitions (list[UserPartition]) user (User) partition_dict_key - i.e. 'id', 'name' depending on which partition attribute you want as a key. Returns: dict[partition_dict_key: Group]: Mapping from user partitions to the group to which the user belongs in each partition. If the user isn't in a group for a particular partition, then that partition's ID will not be in the dict. """ partition_groups = {} for partition in user_partitions: group = partition.scheme.get_group_for_user( course_key, user, partition, ) if group is not None: partition_groups[getattr(partition, partition_dict_key)] = group return partition_groups
3bb2f76f4a48ce0af745637810903b8086b2fc02
705,725
import os import socket def has_reuse_port(*, use_env=True): """Return true if the platform indicates support for SO_REUSEPORT. Can be overridden by explicitly setting ``AIOCOAP_REUSE_PORT`` to 1 or 0.""" if use_env and os.environ.get('AIOCOAP_REUSE_PORT'): return bool(int(os.environ['AIOCOAP_REUSE_PORT'])) return hasattr(socket, 'SO_REUSEPORT')
142b766f1f38fb671107aa754de5689837b3008e
705,726
import collections def factory_dict(value_factory, *args, **kwargs): """A dict whose values are computed by `value_factory` when a `__getitem__` key is missing. Note that values retrieved by any other method will not be lazily computed; eg: via `get`. :param value_factory: :type value_factory: A function from dict key to value. :param *args: Any positional args to pass through to `dict`. :param **kwrags: Any kwargs to pass through to `dict`. :rtype: dict """ class FactoryDict(collections.defaultdict): @staticmethod def __never_called(): raise AssertionError('The default factory should never be called since we override ' '__missing__.') def __init__(self): super().__init__(self.__never_called, *args, **kwargs) def __missing__(self, key): value = value_factory(key) self[key] = value return value return FactoryDict()
f7d4898e62377958cf9d9c353ed12c8d381f042f
705,727
def build_or_passthrough(model, obj, signal): """Builds the obj on signal, or returns the signal if obj is None.""" return signal if obj is None else model.build(obj, signal)
bee9c8557a89a458cf281b42f968fe588801ed46
705,728
import requests import json def warc_url(url): """ Search the WARC archived version of the URL :returns: The WARC URL if found, else None """ query = "http://archive.org/wayback/available?url={}".format(url) response = requests.get(query) if not response: raise RuntimeError() data = json.loads(response.text) snapshots = data["archived_snapshots"] if not snapshots: return None return snapshots["closest"]["url"]
afc24876f72915ba07233d5fde667dd0ba964f5a
705,729
def array_to_top_genes(data_array, cluster1, cluster2, is_pvals=False, num_genes=10): """ Given a data_array of shape (k, k, genes), this returns two arrays: genes and values. """ data_cluster = data_array[cluster1, cluster2, :] if is_pvals: order = data_cluster.argsort() else: order = data_cluster.argsort()[::-1] genes = order[:num_genes] values = data_cluster[order[:num_genes]] return genes, values
4f9a0ea673f4ddfa59e7d4fc2249597daef4a260
705,730
import os def parse_fastani_write_prophage(CRISPR_mates): """[summary] Args: CRISPR_mates ([type]): [description] Returns: [type]: [description] """ if not os.path.exists('prophageannotations'): os.system('mkdir -p prophageannotations') viral_cluster_prophages = dict() for bacterial_clusters in CRISPR_mates: fileout = os.path.join('prophageannotations',bacterial_clusters+'.prophage.annotations.txt') with open(fileout,'w') as outfile: fastanifile = os.path.join('fastani','bac'+bacterial_clusters+'.viruses.fastani.txt') if os.path.exists(fastanifile): with open(fastanifile,'r') as infile: for line in infile: line = line.strip().split('\t') ANI = float(line[2]) coverage = (int(line[3])/int(line[4]))*100 if ANI >= 95 and coverage >= 75: binid = os.path.basename(line[0]).replace('.fna','') viral_cluster = binid.split('_')[1] viral_sample = binid.split('_')[0] bacterialbin = os.path.basename(line[1]).replace('.fna','') if not viral_cluster in viral_cluster_prophages: viral_cluster_prophages[viral_cluster] = dict() viral_cluster_prophages[viral_cluster][bacterialbin] = 1 else: viral_cluster_prophages[viral_cluster][bacterialbin] = 1 sample = bacterialbin.split('_')[0] lineout = '\t'.join([bacterial_clusters,bacterialbin,sample,viral_cluster,viral_sample,binid,str(ANI),str(coverage)]) outfile.write(lineout+'\n') return viral_cluster_prophages
82cf3bfff65bb57ab33c7a2108734a90da1a4d11
705,731
def set_attrib(node, key, default): """ Parse XML key for a given node If key does not exist, use default value """ return node.attrib[key] if key in node.attrib else default
0e21b6b0e5a64e90ee856d4b413084a8c395b070
705,732
def is_order_exist(context, symbol, side) -> bool: """判断同方向订单是否已经存在 :param context: :param symbol: 交易标的 :param side: 交易方向 :return: bool """ uo = context.unfinished_orders if not uo: return False else: for o in uo: if o.symbol == symbol and o.side == side: context.logger.info("同类型订单已存在:{} - {}".format(symbol, side)) return True return False
42363c8b3261e500a682b65608c27537b93bcfb1
705,733
def average_pool(inputs, masks, axis=-2, eps=1e-10): """ inputs.shape: [A, B, ..., Z, dim] masks.shape: [A, B, ..., Z] inputs.shape[:-1] (A, B, ..., Z) must be match masks.shape """ assert inputs.shape[:-1] == masks.shape, f"inputs.shape[:-1]({inputs.shape[:-1]}) must be equal to masks.shape({masks.shape})" masks_unsq = masks.unsqueeze(-1) return (inputs * masks_unsq).sum(axis) / (masks_unsq.sum(axis)+eps)
e6f99634245a4c46e2b5d776afcd73e855da68de
705,735
def save_ipynb_from_py(folder: str, py_filename: str) -> str: """Save ipynb file based on python file""" full_filename = f"{folder}/{py_filename}" with open(full_filename) as pyfile: code_lines = [line.replace("\n", "\\n").replace('"', '\\"') for line in pyfile.readlines()] pycode = '",\n"'.join(code_lines) with open('template.ipynb') as template: template_body = ''.join(template.readlines()) ipynb_code = template_body.replace('{{TEMPLATE}}', pycode) new_filename = full_filename.replace('.py', '.ipynb') with open(new_filename, "w") as ipynb_file: ipynb_file.write(ipynb_code) return py_filename.replace('.py', '.ipynb')
f2711f0282c2bf40e9da2fec6e372c76038ac04a
705,736
def make_coro(func): """Wrap a normal function with a coroutine.""" async def wrapper(*args, **kwargs): """Run the normal function.""" return func(*args, **kwargs) return wrapper
080e543bc91daee13c012225ba47cd6d054c9ea5
705,737
import math def gvisc(P, T, Z, grav): """Function to Calculate Gas Viscosity in cp""" #P pressure, psia #T temperature, °R #Z gas compressibility factor #grav gas specific gravity M = 28.964 * grav x = 3.448 + 986.4 / T + 0.01009 * M Y = 2.447 - 0.2224 * x rho = (1.4926 / 1000) * P * M / Z / T K = (9.379 + 0.01607 * M) * T ** 1.5 / (209.2 + 19.26 * M + T) return K * math.exp(x * rho ** Y) / 10000
5ff1ad63ef581cea0147348104416913c7b77e37
705,738
def url_mapper(url, package): """ In a package.json, the "url" field is a redirection to a package download URL published somewhere else than on the public npm registry. We map it to a download url. """ if url: package.download_urls.append(url) return package
95d6b67a42cac14110b457b96216a40a5d5430f9
705,739
def mettre_a_jour_uids(nom_fichier, organisateurs, uids): """ Met à jour le fichier CSV UID,EMAIL à partir du dictionnaire """ nouveaux_uids = False for id_reunion in organisateurs: if organisateurs[id_reunion]["id_organisateur"] not in uids: uids[organisateurs[id_reunion]["id_organisateur"]] = organisateurs[id_reunion]["email_organisateur"] nouveaux_uids = True if nouveaux_uids: with open(nom_fichier, "w", encoding="utf-8") as fichier: for uid in uids: fichier.write( "{:s},{:s}\n".format( uid, uids[uid], ) ) return uids
ac0f61b135c8a7bb9de9bb6b5b8e3f9fd7b176f0
705,740
def is_base(base_pattern, str): """ base_pattern is a compiled python3 regex. str is a string object. return True if the string match the base_pattern or False if it is not. """ return base_pattern.match(str, 0, len(str))
d0b0e3291fdbfad49698deffb9f57aefcabdce92
705,741
def stations_by_river(stations): """For a list of MonitoringStation objects (stations), returns a dictionary that maps river names (key) to a list of MonitoringStation objects on a given river.""" # Dictionary containing river names and their corresponding stations rivers = {} for station in stations: # Check if river is already in the dictionary if station.river in rivers: # Check if the station has already been added to the list if station not in rivers[station.river]: rivers[station.river].append(station) else: rivers.update({station.river: [station]}) return rivers
c7fc460aa3e387285abdddfcb216a8ec41d27e06
705,742
def check_double_quote(inpstring): """ Check if some strings needs of a double quote (if some space are inside the string, it will need to be inside two double quote). E.g.: --sfmt="TIFF (unstitched, 3D)" Input: inpstring: input string or array of strings Output: newstring = new string (or array of strings) corrected by quoting if necessary """ if type(inpstring) == list: newstring = [] for index in inpstring: tmp1 = index.find(" ") if tmp1 != -1: tmp2 = index.find('"') if tmp2 == -1: dummy = index.find("=") if dummy != -1: newstring.append( index[0 : dummy + 1] + '"' + index[dummy + 1 :] + '"' ) else: newstring.append('"' + index + '"') else: newstring.append(index) else: newstring.append(index) else: tmp1 = inpstring.find(" ") if tmp1 != -1: tmp2 = inpstring.find('"') if tmp2 == -1: dummy = inpstring.find("=") if dummy != -1: newstring = ( inpstring[0 : dummy + 1] + '"' + inpstring[dummy + 1 :] + '"' ) else: newstring = '"' + inpstring + '"' else: newstring = inpstring else: newstring = inpstring return newstring
3da3941d9cd8c4c72643f87c533bcfbfbd9b9a79
705,744
import fcntl import os import socket import struct def get_linux_ip(eth): """在Linux下获取IP""" assert os.name == 'posix', NotLinuxSystemError('不是Linux系统') s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) ip = socket.inet_ntoa(fcntl.ioctl(s.fileno(), 0x8915, struct.pack('256s', eth[:15]))) return ip[20:24]
381d3681bee21de2f0fca489536e12f997eaaec8
705,745
def split_line(line) -> list: """Split a line from a dmp file""" return [x.strip() for x in line.split(" |")]
e9c5fb93bab1007b3deb11b8d71fe0cffd3f5bab
705,746
def translate(text): """.""" return text
a0732d6a802f9846de5b294863f2c096f72c6c70
705,747
def helper(n, big): """ :param n: int, an integer number :param big: the current largest digit :return: int, the final largest digit """ n = abs(n) if n == 0: return big else: # check the last digit of a number if big < int(n % 10): big = int(n % 10) # check the rest of the digits return helper(n/10, big)
aa7fa862d326d9e3400b58c9c520a10672e7340c
705,748
def getPageNumber(ffile): """ Extract the page number from the file name :param ffile: :return: image URI as a string """ return str(ffile).split('_')[-1].split('.')[0]
f78166ae3da8ea234c98436144e6c815f341ff5e
705,750
import os def get_files_from_folder(directory, extension=None): """Get all files within a folder that fit the extension """ # NOTE Can be replaced by glob for newer python versions label_files = [] for root, _, files in os.walk(directory): for some_file in files: label_files.append(os.path.abspath(os.path.join(root, some_file))) if extension is not None: label_files = list(filter(lambda x: x.endswith(extension), label_files)) return label_files
e572333be8786a32aabf2e217411c9db11e65175
705,751
def predicate(line): """ Remove lines starting with ` # ` """ if "#" in line: return False return True
ff7d67c1fd7273b149c5a2148963bf898d6a3591
705,752
import random def fight(player, enemy): """ This starts a round of combat between the user and their selected enemy. It returns a list of information relating to combat, to be used in the view function to display it, if required. """ # Random player damage based on 80-100% of player damage stat. dmg_range_roll = random.randrange(80, 101) / 100 dmg_roll_player = round(player.damage * dmg_range_roll) looted_power_crystals = 0 looted_gold = 0 if enemy.hp_max <= dmg_roll_player: # Randomly generated loot values, added to player object. resources_range_roll = random.randrange(75, 101) / 100 looted_power_crystals = round( enemy.power_crystals * resources_range_roll) player.power_crystals += looted_power_crystals resources_range_roll = random.randrange(75, 101) / 100 looted_gold = round(enemy.gold * resources_range_roll) player.gold += looted_gold dmg_roll_enemy = 0 result = True else: result = False # Random enemy damage, based on 80-100% of their damage stat. dmg_range_roll = random.randrange(80, 101) / 100 dmg_roll_enemy = round(enemy.damage * dmg_range_roll) player.hp_current -= dmg_roll_enemy return [player, dmg_roll_player, dmg_roll_enemy, result, looted_gold, looted_power_crystals]
bca739be92ccacb92c90d784cdbf5b4abb2e61c0
705,754
def sort_list_by_list(L1,L2): """Sort a list by another list""" return [x for (y,x) in sorted(zip(L2,L1), key=lambda pair: pair[0])]
04b7c02121620be6d9344af6f56f1b8bfe75e9f3
705,755
def unpack_singleton(x): """Gets the first element if the iterable has only one value. Otherwise return the iterable. # Argument: x: A list or tuple. # Returns: The same iterable or the first element. """ if len(x) == 1: return x[0] return x
cf551f242c8ea585c1f91eadbd19b8e5f73f0096
705,756
from typing import List from typing import Dict def make_car_dict(key: str, data: List[str]) -> Dict: """Organize car data for 106 A/B of the debtor :param key: The section id :param data: Content extract from car data section :return: Organized data for automobile of debtor """ return { "key": key, "make": data[0], "model": data[1], "year": data[2], "mileage": data[3], "other_information": data[5], "property_value": data[6], "your_property_value": data[7], }
671cb2f82f15d14345e34e9823ea390d72cf040a
705,757
def draw_support_spring( fig, support, orientation="up", color='orange', show_values=True, row=None, col=None, units="N/m"): """Draw an anchored spring shape on a plotly figure. Parameters ---------- fig : plotly figure plotly figure to append roller shape to. support : Support instance support to be represented on figure orientation : 'up' or 'right, optional direction that the arrow faces, by default "up" color : str, optional color of spring, by default 'orange'. show_values: bool,optional If true annotates numerical force value next to arrow, by default True. row : int or None, Row of subplot to draw line on. If None specified assumes a full plot, by default None. col : int or None, Column of subplot to draw line on. If None specified assumes a full plot, by default None. units: str, The units suffix drawn with the stiffness value. Default is 'N/m'. Returns ------- plotly figure Returns the plotly figure passed into function with the spring shape appended to it.""" x_sup = support._position # x0 and y0 initialised so that when loop through each point in the coords # list will have two points to reference. x0, y0 = 0, 0 # reduction of 0.8 used on coords specified (simple reduction modification) reduce = 0.8 if orientation in ['up', 'right']: # coords are points between lines to be created # label and stiffness are defined for use as meta data to be added to # the hovertemplate if orientation == 'right': coords = [(5, 0), (7, 5), (12, -5), (14, 0), (19, 0)] stiffness = support._stiffness[0] else: coords = [(0, 5), (-5, 7), (5, 12), (0, 14), (0, 19)] stiffness = support._stiffness[1] # x1 and y1 are the ends of the line to be created for x1, y1 in coords: x1, y1 = x1 * reduce, y1 * reduce # Create dictionary for line shape object. Note: multiple lines # added but reference must always be to the same xanchor shape = dict( type="line", xref="x", yref="y", x0=x0, y0=y0, x1=x1, y1=y1, line_color=color, line_width=2, xsizemode='pixel', ysizemode='pixel', xanchor=x_sup, yanchor=0 ) # Append line to plot or subplot if row and col: fig.add_shape(shape, row=row, col=col) else: fig.add_shape(shape) # set end point to be start point for the next line x0, y0 = x1, y1 if show_values: y0 = max(y0, 7) annotation = dict( xref="x", yref="y", x=x_sup, y=0, yshift=y0 * 1.5, xshift=x0 * 2, text=f"{stiffness:.3f} {units}", font_color=color, showarrow=False, ) # Append shape to plot or subplot if row and col: fig.add_annotation(annotation, row=row, col=col) else: fig.add_annotation(annotation) return fig
73c546289ac02d9021375f553504991bdaa4ca89
705,758
def quantity_remover(my_thing): """ removes pint quantities to make json output happy Parameters ---------- my_thing Returns ------- """ if hasattr(my_thing, 'magnitude'): return 'QUANTITY', my_thing.magnitude, my_thing.units.format_babel() elif isinstance(my_thing, dict): newdict = dict() for key, item in my_thing.items(): newdict[key] = quantity_remover(item) return newdict elif hasattr(my_thing, '__iter__') and not isinstance(my_thing, str): my_type = type(my_thing) return my_type([quantity_remover(item) for item in my_thing]) else: return my_thing
54b2db5b638f297ca503513f79eb4eec4ac2afa2
705,759
def cleanse_param_name(name): """Converts Chainer parameter names to ONNX names. Note ONNX identifiers must be a valid C identifier. Args: name (str): A Chainer parameter name (e.g., /l/W). Returns A valid ONNX name (e.g., param_l_W). """ return 'param' + name.replace('/', '_')
9b7774aabeeab322f53321b91195333359c8ee7b
705,760
def _s_to_b(value): """[string to binary single value]""" try: return bytes(value, 'utf-8') except: return value
bbabffa2fbd2ec62778a19c8ab3e1fe410b4640f
705,761
import struct def get_array_of_float(num, data): """Read array of floats Parameters ---------- num : int Number of values to be read (length of array) data : str 4C binary data file Returns ------- str Truncated 4C binary data file list List of floats """ length = 4 results = struct.unpack('f' * num, data[:num * length]) pos = num * length new_data = data[pos:] return new_data, list(results)
92a0a4cc653046826b14c2cd376a42045c4fa641
705,762
def count_routes_graph(graph, source_node, dest_node): """ classic tree-like graph traversal """ if dest_node == source_node or dest_node - source_node == 1: return 1 else: routes = 0 for child in graph[source_node]: routes += count_routes_graph(graph, child, dest_node) return routes
f952b35f101d9f1c42eb1d7444859493701c6838
705,763
import six def inject_timeout(func): """Decorator which injects ``timeout`` parameter into request. On client initiation, default timeout is set. This timeout will be injected into any request if no explicit parameter is set. :return: Value of decorated function. """ @six.wraps(func) def decorator(self, *args, **kwargs): kwargs.setdefault("timeout", self._timeout) return func(self, *args, **kwargs) return decorator
479ed7b6aa7005d528ace0ff662840d14c23035c
705,764
def cver(verstr): """Converts a version string into a number""" if verstr.startswith("b"): return float(verstr[1:])-100000 return float(verstr)
1ad119049b9149efe7df74f5ac269d3dfafad4e2
705,765
def _replace_oov(original_vocab, line): """Replace out-of-vocab words with "UNK". This maintains compatibility with published results. Args: original_vocab: a set of strings (The standard vocabulary for the dataset) line: a unicode string - a space-delimited sequence of words. Returns: a unicode string - a space-delimited sequence of words. """ return u" ".join( [word if word in original_vocab else u"UNK" for word in line.split()])
2e2cb1464484806b79263a14fd32ed4d40d0c9ba
705,768
import os async def stat_data(full_path: str, isFolder=False) -> dict: """ only call this on a validated full path """ file_stats = os.stat(full_path) filename = os.path.basename(full_path) return { 'name': filename, 'path': full_path, 'mtime': int(file_stats.st_mtime*1000), # given in seconds, want ms 'size': file_stats.st_size, 'isFolder': isFolder }
f78a27ac9cbe116c6a04e5a5dbc45e454b26f02b
705,770
import os def fix_path(file_path): """fixes a path so project files can be located via a relative path""" script_path = os.path.dirname(__file__) return os.path.normpath(os.path.join(script_path, file_path))
f733b0c0eb12ced5193393013198d89cd774297a
705,771
import json import subprocess import sys def cmd(cmd_name, source, args: list = [], version={}, params={}): """Wrap command interaction for easier use with python objects.""" in_json = json.dumps({ "source": source, "version": version, "params": params, }) command = ['/opt/resource/' + cmd_name] + args output = subprocess.check_output(command, stderr=sys.stderr, input=bytes(in_json, 'utf-8')) return json.loads(output.decode())
be1ebe77c70ce2b377cb64d6d54f043c39dde85a
705,772
def geq_indicate(var, indicator, var_max, thr): """Generates constraints that make indicator 1 iff var >= thr, else 0. Parameters ---------- var : str Variable on which thresholding is performed. indicator : str Identifier of the indicator variable. var_max : int An upper bound on var. the : int Comparison threshold. Returns ------- List[str] A list holding the two constraints. """ lb = "- %s + %d %s <= 0" % (var, thr, indicator) ub = "- %s + %d %s >= -%d" % (var, var_max - thr + 1, indicator, thr - 1) return [lb, ub]
319f18f5343b806b7108dd9c02ca5d647e132dab
705,773
import re def parse_manpage_number(path): """ Parse number of man page group. """ # Create regular expression number_regex = re.compile(r".*/man(\d).*") # Get number of manpage group number = number_regex.search(path) only_number = "" if number is not None: number = number.group(1) return number
b45edb65705592cd18fd1fd8ee30bb389dbd8dff
705,774
import argparse def ParseArgs(argv): """Parses command line arguments.""" parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '-b', '--bundle-identifier', required=True, help='bundle identifier for the application') parser.add_argument( '-o', '--output', default='-', help='path to the result; - means stdout') return parser.parse_args(argv)
507935ea2ea42dea66bfff545caecb7fc2cded55
705,775
def get_sale(this_line): """Convert the input into a dictionary, with keys matching the CSV column headers in the scrape_util module. """ sale = {} sale['consignor_name'] = this_line.pop(0) sale['consignor_city'] = this_line.pop(0).title() try: maybe_head = this_line[0].split() int(maybe_head[0]) sale['cattle_head'] = maybe_head[0] sale['cattle_cattle'] = ' '.join(maybe_head[1:]) this_line.pop(0) except: sale['cattle_cattle'] = this_line.pop(0) sale['cattle_avg_weight'] = this_line.pop(0) price_string = this_line.pop(0) sale['cattle_price_cwt'] = price_string.replace(',', '') return sale
39fee66b4c92a2cb459722f238e4a3b6e5848f4d
705,776
import logging def filtering_news(news: list, filtered_news: list): """ Filters news to remove unwanted removed articles Args: news (list): List of articles to remove from filtered_news (list): List of titles to filter the unwanted news with Returns: news (list): List of articles with undesired articles removed """ for x in filtered_news: for y in news: # Nested loop to loop through the titles since it is a list of dictionaries if y["title"] == x["title"]: news.remove(y) logging.info("News filtered, removed {}".format(x["title"])) break return news
98049b6bd826109fe7bc8e2e42de4c50970988a9
705,777
from typing import Optional from typing import List import itertools def add_ignore_file_arguments(files: Optional[List[str]] = None) -> List[str]: """Adds ignore file variables to the scope of the deployment""" default_ignores = ["config.json", "Dockerfile", ".dockerignore"] # Combine default files and files ingore_files = default_ignores + (files or []) return list( itertools.chain.from_iterable( [["--ignore-file", filename] for filename in ingore_files] ) )
f7e7487c4a17a761f23628cbb79cbade64237ce6
705,778
import torch def compute_accuracy(logits, targets): """Compute the accuracy""" with torch.no_grad(): _, predictions = torch.max(logits, dim=1) accuracy = torch.mean(predictions.eq(targets).float()) return accuracy.item()
af15e4d077209ff6e790d6fdaa7642bb65ff8dbf
705,779
def gm_put(state, b1, b2): """ If goal is ('pos',b1,b2) and we're holding b1, Generate either a putdown or a stack subtask for b1. b2 is b1's destination: either the table or another block. """ if b2 != 'hand' and state.pos[b1] == 'hand': if b2 == 'table': return [('a_putdown', b1)] elif state.clear[b2]: return [('a_stack', b1, b2)]
c9076ac552529c60b5460740c74b1602c42414f2
705,780
import random import time def hammer_op(context, chase_duration): """what better way to do a lot of gnarly work than to pointer chase?""" ptr_length = context.op_config["chase_size"] data = list(range(0, ptr_length)) random.shuffle(data) curr = random.randint(0, ptr_length - 1) # and away we go start_time = time.time() while (time.time() - start_time) < chase_duration: curr = data[curr] context.log.info("Hammered - start %d end %d" % (start_time, time.time())) return chase_duration
f4a51fe1e2f89443b79fd4c9a5b3f5ee459e79ca
705,781
def get_child(parent, child_index): """ Get the child at the given index, or return None if it doesn't exist. """ if child_index < 0 or child_index >= len(parent.childNodes): return None return parent.childNodes[child_index]
37f7752a4a77f3d750413e54659f907b5531848c
705,782
import os def split_missions_and_dates(fname): """ Examples -------- >>> fname = 'nustar-nicer_gt55000_lt58000.csv' >>> outdict = split_missions_and_dates(fname) >>> outdict['mission1'] 'nustar' >>> outdict['mission2'] 'nicer' >>> outdict['mjdstart'] 'MJD 55000' >>> outdict['mjdstop'] 'MJD 58000' >>> fname = 'nustar-nicer.csv' >>> outdict = split_missions_and_dates(fname) >>> outdict['mission1'] 'nustar' >>> outdict['mission2'] 'nicer' >>> outdict['mjdstart'] 'Mission start' >>> outdict['mjdstop'] 'Today' """ no_ext = os.path.splitext(fname)[0] split_date = no_ext.split('_') mjdstart = 'Mission start' mjdstop = 'Today' if len(split_date) > 1: for date_str in split_date[1:]: if 'gt' in date_str: mjdstart = 'MJD ' + date_str.replace('gt', '') elif 'lt' in date_str: mjdstop = 'MJD ' + date_str.replace('lt', '') mission1, mission2 = split_date[0].split('-') outdict = {'mission1': mission1, 'mission2': mission2, 'mjdstart': mjdstart, 'mjdstop': mjdstop} return outdict
851fa5a85d0acfd9d309725284ebb1859734432e
705,783
def get_renaming(mappers, year): """Get original to final column namings.""" renamers = {} for code, attr in mappers.items(): renamers[code] = attr['df_name'] return renamers
33197b5c748b3ecc43783d5f1f3a3b5a071d3a4e
705,784
async def clap(text, args): """ Puts clap emojis between words. """ if args != []: clap_str = args[0] else: clap_str = "👏" words = text.split(" ") clappy_text = f" {clap_str} ".join(words) return clappy_text
09865461e658213a2f048b89757b75b2a37c0602
705,785
def remove_extra_two_spaces(text: str) -> str: """Replaces two consecutive spaces with one wherever they occur in a text""" return text.replace(" ", " ")
d8b9600d3b442216b1fbe85918f313fec8a5c9cb
705,786
def load_utt_list(utt_list): """Load a list of utterances. Args: utt_list (str): path to a file containing a list of utterances Returns: List[str]: list of utterances """ with open(utt_list) as f: utt_ids = f.readlines() utt_ids = map(lambda utt_id: utt_id.strip(), utt_ids) utt_ids = filter(lambda utt_id: len(utt_id) > 0, utt_ids) return list(utt_ids)
6a77e876b0cc959ac4151b328b718ae45522448b
705,787
def compute_flow_for_supervised_loss( feature_model, flow_model, batch, training ): """Compute flow for an image batch. Args: feature_model: A model to compute features for flow. flow_model: A model to compute flow. batch: A tf.tensor of shape [b, seq, h, w, c] holding a batch of triplets. training: bool that tells the model to use training or inference code. Returns: A tuple consisting of the images, the extracted features, the estimated flows, and the upsampled refined flows. """ feature_dict = feature_model(batch[:, 0], batch[:, 1], training=training) return flow_model(feature_dict, training=training)
a74f392c1d4e234fdb66d18e63d7c733ec6669a7
705,788
import os def _get_filename_from_request(request): """ Gets the filename from an url request. :param request: url request to get filename from :type request: urllib.requests.Request or urllib2.Request :rtype: str """ try: headers = request.headers content = headers["content-disposition"] filename_str = content.split("filename=")[1] return filename_str.strip("\"") except (KeyError, AttributeError): return os.path.basename(request.url)
51d2f79ebc5f2abf57d5b12d0271d6d704a24297
705,789
import os def _find_pkg_info(directory): """find and return the full path to a PKG-INFO file or None if not found""" for root, dirs, files in os.walk(directory): for filename in files: if filename == 'PKG-INFO': return os.path.join(root, filename) # no PKG-INFO file found return None
ada0afe963cb859a5c5b19813ebbdea03cda7db3
705,790
import itertools def labels_to_intervals(labels_list): """ labels_to_intervals() converts list of labels of each frame into set of time intervals where a tag occurs Args: labels_list: list of labels of each frame e.g. [{'person'}, {'person'}, {'person'}, {'surfboard', 'person'}] Returns: tags - set of time intervals where a tag occurs: { (label, start, end) }, a video from time 0 (inclusive) to time T (exclusive) e.g. {('cat', 3, 9), ('dog', 5, 8), ('people', 0, 6)} e.g. {('cat', 0, 1), ('cat', 2, 4), ('cat', 6, 8), ('dog', 0, 3), ('dog', 6, 8), ('people', 0, 2), ('people', 4, 6)} """ labels_dict = dict() for frame, labels in enumerate(labels_list): for label in labels: if label in labels_dict: labels_dict[label].add(frame) else: labels_dict[label] = {frame} output = set() for key, value in labels_dict.items(): frame_list = sorted(value) for interval in [(t[0][1], t[-1][1]) for t in (tuple(g[1]) for g in itertools.groupby(enumerate(frame_list), lambda x: x[0]-x[1]))]: output.add((key, interval[0], interval[1]+1)) return output
65b63ea3e6f097e9605e1c1ddb8dd434d7db9370
705,791
def get_wolfram_query_url(query): """Get Wolfram query URL.""" base_url = 'www.wolframalpha.com' if not query: return 'http://{0}'.format(base_url) return 'http://{0}/input/?i={1}'.format(base_url, query)
0122515f1a666cb897b53ae6bd975f65da072438
705,792
import copy def merge_dictionary(src: dict, dest: dict) -> dict: """ Merge two dictionaries. :param src: A dictionary with the values to merge. :param dest: A dictionary where to merge the values. """ for name, value in src.items(): if name not in dest: # When field is not available in destination add the value from the source if isinstance(value, dict): # A new dictionary is created to avoid keeping references dest[name] = copy.deepcopy(value) elif isinstance(value, list): # A new list is created to avoid keeping references dest[name] = copy.deepcopy(value) else: dest[name] = value elif isinstance(value, dict): # When field exists in destination and is dict merge the source value merge_dictionary(value, dest[name]) elif isinstance(value, list) and isinstance(dest[name], list): # When both values are a list merge them dest[name].extend(copy.deepcopy(value)) return dest
12305510a9a2d50bcdc691cb7fe8d5a573621e69
705,793
import json def scheming_multiple_choice_output(value): """ return stored json as a proper list """ if isinstance(value, list): return value try: return json.loads(value) except ValueError: return [value]
d45bbb1af249d0fed00892ccc55cf8f28f7f099f
705,794
import re import os def get_name(path): """get the name from a repo path""" return re.sub(r"\.git$", "", os.path.basename(path))
42c410fd21e1d50270cf7703b9f054a8455c7efd
705,795