content
stringlengths
35
762k
sha1
stringlengths
40
40
id
int64
0
3.66M
def state(state_vec): """ Qiskit wrapper of qobj """ return gen_operator.state(state_vec)
74094c7c6e3c33cff28777f54d8852245c31f276
10,149
def get_games_for_platform(platform_id): """Return the list of all the games for a given platform""" controller = GameController return controller.get_list_by_platform(MySQLFactory.get(), platform_id)
83855b6cdb4d39442e255d14d2f94d76a702a0ea
10,151
def validate_dataset(elem: object) -> Dataset: """Check that `elem` is a :class:`~pydicom.dataset.Dataset` instance.""" if not isinstance(elem, Dataset): raise TypeError('Sequence contents must be Dataset instances.') return elem
d4744b06f0ccdc8dca0deab57585706c1ee91db9
10,152
def conv3x3(in_channels, out_channels, stride=1): """3x3 convolution """ weight_shape = (out_channels, in_channels, 3, 3) weight = Tensor(np.ones(weight_shape).astype(np.float32)) conv = Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=0, weight_init=weight, has_...
011a3f74e8665669f9ecf5d4b9e8abf14f52e053
10,154
def _workflow_complete(workflow_stage_dict: dict): """Check if the workflow is complete. This function checks if the entire workflow is complete. This function is used by `execute_processing_block`. Args: workflow_stage_dict (dict): Workflow metadata dictionary. Returns: bool, Tr...
4e5be4c4768d82e8b1e76d1964c3effb2e604dd2
10,155
def get_name(f, opera_format=True): """Load dataset and extract radar name from it""" ds = xr.open_dataset(f) if hasattr(ds, 'source'): radar = ds.source else: filename = osp.splitext(osp.basename(f))[0] radar = filename.split('_')[-1] if opera_format: if '/' in rad...
8c50bebfde1300aa6de55981537cbc23171e6ee8
10,157
import six def range_join(numbers, to_str=False, sep=",", range_sep=":"): """ Takes a sequence of positive integer numbers given either as integer or string types, and returns a sequence 1- and 2-tuples, denoting either single numbers or inclusive start and stop values of possible ranges. When *to_str...
c1b2d10ec1b47fa5c917fccead2ef8d5fc506370
10,158
def power_spectrum(x, fs, N=None): """ Power spectrum of instantaneous signal :math:`x(t)`. :param x: Instantaneous signal :math:`x(t)`. :param fs: Sample frequency :math:`f_s`. :param N: Amount of FFT bins. The power spectrum, or single-sided autospectrum, contains the squared RMS amplitudes ...
f665c529541420ada0ae4819e53de1e73035d83f
10,159
def CreateInstanceTemplate(task, task_dir): """Create the Compute Engine instance template that will be used to create the instances. """ backend_params = task.BackendParams() instance_count = backend_params.get('instance_count', 0) if instance_count <= 0: clovis_logger.info('No template required.') ...
558e4ed3152bb87a51bd2bb7dd107af5dd76bcd1
10,160
def get_config_string(info_type, board_num, dev_num, config_item, max_config_len): """Returns configuration or device information as a null-terminated string. Parameters ---------- info_type : InfoType The configuration information for each board is grouped into different categories. This ...
72a35d984cb35e38a5e0742c7d790dc72ccbc928
10,161
import inspect def _get_kwargs(func, locals_dict, default=None): """ Convert a function's args to a kwargs dict containing entries that are not identically default. Parameters ---------- func : function The function whose args we want to convert to kwargs. locals_dict : dict T...
ae0a06cb4e17b5512a03e89d7ca2119c58ea762b
10,162
from datetime import datetime def iso_to_date(iso_str: str): """Convert a date string with iso formating to a datetime date object""" if not iso_str: return None return datetime.date(*map(int, iso_str.split('-')))
a0d0541298ed538d7df9940ceef7b2bac121af27
10,163
def call_with_error(error_type): """Collects a bunch of errors and returns them all once. Decorator that collects the errors in the decorated function so that the user can see everything they need to fix at once. All errors are thrown with the same error type. The decorated must have an `error` ke...
9a64fb630b0a491bc9e01d77ebe35199df47ab55
10,164
def _get_metadata_and_fingerprint(instance_name, project, zone): """Return the metadata values and fingerprint for the given instance.""" instance_info = _get_instance_info(instance_name, project, zone) if not instance_info: logs.log_error('Failed to fetch instance metadata') return None, None fingerpr...
7049805d538c7942dc8249e91c27faa2c1867936
10,165
def solve_token_pair_and_fee_token_economic_viable( token_pair, accounts, b_orders, s_orders, f_orders, fee, xrate=None ): """Match orders between token pair and the fee token, taking into account all side constraints, including economic viability. If xrate is given, then it will be used instead of...
f6fcf5bccdf498f29852614751cf120a8e2addd4
10,166
def two_categorical(df, x, y, plot_type="Cross tab"): """ ['Cross tab', "Stacked bone_numeric_one_categorical"] """ if plot_type is None: plot_type = 'Cross tab' if plot_type == 'Stacked bar': # 20 df_cross = pd.crosstab(df[x], df[y]) data = [] for x in df_cross....
5c0908055848d9de02920f8e2718de0918f4b460
10,167
def yices_bvconst_one(n): """Set low-order bit to 1, all the other bits to 0. Error report: if n = 0 code = POS_INT_REQUIRED badval = n if n > YICES_MAX_BVSIZE code = MAX_BVSIZE_EXCEEDED badval = n. """ # let yices deal with int32_t excesses if n > MAX_INT...
6a70c4773a6558e068d2bbafb908657d5b5b4d1d
10,168
def showItem(category_id): """Show all Items""" category = session.query(Category).filter_by(id=category_id).one() items = session.query(Item).filter_by( category_id=category_id).all() return render_template('item.html', items=items, category=category)
230cc9b7e8043b0bb3e78866b2a27a0aec287828
10,169
def get_standard_t_d(l, b, d): """ Use NE2001 to estimate scintillation time at 1 GHz and 1 km/s transverse velocity. Parameters ---------- l : float Galactic longitude b : float Galactic latitude d : float Distance in kpc Returns ------- t_d...
e1743ae75a6893376c5e13126deda6f0eb41d38f
10,170
def match(pattern: str, text: str) -> bool: """ 匹配同样长度的字符串 """ if pattern: return True elif pattern == "$" and text == "": return True elif pattern[1] == "?": return _match_question(pattern, text) elif pattern[1] == "*": return _match_star(pattern, text) e...
0dc71f00323502de7c1a2e00c502c99d75f56fc1
10,172
def config_func(tools, index, device_id, config_old: {}, config_new: {}): """ CANedge configuration update function :param tools: A collection of tools used for device configuration :param index: Consecutive device index (from 0) :param device_id: Device ID :param config_old: The current device ...
c0585c3a268fb40e3e00a2613e03001bc561566a
10,173
def load_figure(file_path: str) -> matplotlib.figure.Figure: """Fully loads the saved figure to be able to be modified. It can be easily showed by: fig_object.show() Args: file_path: String file path without file extension. Returns: Figure object. Raises: None. ...
76dcc0a27a3ae04e574a3d69fb431eedbc0c618a
10,174
def cluster_vectors(vectors, k=500, n_init=100, **kwargs): """Build NearestNeighbors tree.""" kwargs.pop('n_clusters', None) kwargs.pop('init', None) kwargs.pop('n_init', None) return KMeans(n_clusters=k, init='k-means++', n_init=n_init, **kwargs).fit(vectors)
28984811ea58a2a2c123d36cdb5e56c1d5b8d0db
10,175
import torch import math def positional_encoding(d_model, length): """ :param d_model: dimension of the model :param length: length of positions :return: length*d_model position matrix """ if d_model % 2 != 0: raise ValueError("Cannot use sin/cos positional encoding with " ...
de41f0c99b46f16dbe300d59527e11b98a0b1f14
10,176
def invert_hilbert_QQ(n=40, system='sage'): """ Runs the benchmark for calculating the inverse of the hilbert matrix over rationals of dimension n. INPUT: - ``n`` - matrix dimension (default: ``300``) - ``system`` - either 'sage' or 'magma' (default: 'sage') EXAMPLES:: sage: impo...
153e7400467a57cf07f839042d31d4800fe161bd
10,179
def getModelListForEnumProperty(self, context): """Returns a list of (str, str, str) elements which contains the models contained in the currently selected model category. If there are no model categories (i.e. '-') return ('-', '-', '-'). Args: context: Returns: """ category = con...
46f642933dd220b0f71431ff4a9cb7410858fbf0
10,180
import logging def run_wcs(*args, **kwargs): """ Set up the environment and run the bundled wcs.exe (from the Talon distribution) using the supplied command line arguments """ # Pull out keyword args that we are interested in write_stdout_to_console = kwargs.get("write_stdout_to_console",...
51461fcbc4ed5a08063d630aea926d312b9da825
10,182
def store_exposure_fp(fp, exposure_type): """ Preserve original exposure file extention if its in a pandas supported compressed format compression : {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}, default ‘infer’ For on-the-fly decompression of on-disk data. If ‘infer’ and ...
c187e79d4cce7ea79b66671a2e7378a35de4841f
10,184
def velocity_genes(data, vkey='velocity', min_r2=0.01, highly_variable=None, copy=False): """Estimates velocities in a gene-specific manner Arguments --------- data: :class:`~anndata.AnnData` Annotated data matrix. vkey: `str` (default: `'velocity'`) Name under which to refer to the...
7d2a0b86d2fb4402cdef9ab56fe2638f89d09fac
10,185
def update_graphics_labels_from_node_data(node, n_id_map, add_new_props): """Updates the graphics labels so they match the node-data""" try: gfx = select_child(node, n_id_map, 'nodegraphics').getchildren()[0].getchildren() except: return None node_label = select_child(node, n_id_map, 'l...
c2d3104dbc3a20ff6c34de754ff681b176091787
10,186
def ProcuraPalavra(dicionário, palavra): """ Procura as possíveis palavras para substituir a palavra passada, e as devolve numa lista """ #Antes de mais nada tornamos a palavra maiuscula #para realizar as comparações palavra = palavra.upper() #Primeiro olhamos para o caso de haver u...
1a283aec6670c0e2fe6ca6f4366ef43c6ba97e9f
10,189
import json import six def _build_auth_record(response): """Build an AuthenticationRecord from the result of an MSAL ClientApplication token request""" try: id_token = response["id_token_claims"] if "client_info" in response: client_info = json.loads(_decode_client_info(response[...
96aed71945c354e41cafd89bf5d7a7d62c31a40a
10,191
def loc_data_idx(loc_idx): """ Return tuple of slices containing the unflipped idx corresponding to loc_idx. By 'unflipped' we mean that if a slice has a negative step, we wish to retrieve the corresponding indices but not in reverse order. Examples -------- >>> loc_data_idx(slice(11, None,...
d30b1b27957e24ff30caf19588487645ac198dc8
10,192
def eat_descriptor(descr): """ Read head of a field/method descriptor. Returns a pair of strings, where the first one is a human-readable string representation of the first found type, and the second one is the tail of the parameter. """ array_dim = 0 while descr[0] == '[': array_di...
411ce48ce250fe15438cd89f43b91ee9b87908a6
10,193
def legendre(a, p): """Legendre symbol""" tmp = pow(a, (p-1)//2, p) return -1 if tmp == p-1 else tmp
66b86dce23ae10ba226ffb19942b98550bb7c218
10,194
def precheck_arguments(args): """ Make sure the argument choices are valid """ any_filelist = (len(args.filelist_name[0]) > 0 or len(args.output_dir[0]) > 0 or args.num_genomes[0] > 0) if len(args.filelist_name[0]) > 0 and len(args.output_dir[0]) == 0: print("Error: Need to specify output directory with -O if...
984865d214cca63eae8bacf5bc7be238e7209ddb
10,196
def get_image_blob(im): """Converts an image into a network input. Arguments: im (ndarray): a color image Returns: blob (ndarray): a data blob holding an image pyramid im_scale_factors (list): list of image scales (relative to im) used in the image pyramid """ im_...
6d72ea1ffcdf20bbf05f75f6084a9027e771196a
10,197
def get_expr_fields(self): """ get the Fields referenced by switch or list expression """ def get_expr_field_names(expr): if expr.op is None: if expr.lenfield_name is not None: return [expr.lenfield_name] else: # constant value expr ...
103aa0ac54be37b23d9695dddfda9972a9f0d7f0
10,198
import math def add_bias_towards_void(transformer_class_logits, void_prior_prob=0.9): """Adds init bias towards the void (no object) class to the class logits. We initialize the void class with a large probability, similar to Section 3.3 of the Focal Loss paper. Reference: Focal Loss for Dense Object De...
f5b3439fc7fbc987bbcbc3b64fd689208db7c5e6
10,199
def trajnet_batch_multi_eval(preds, gt, seq_start_end): """Calculate Top-k ADE, Top-k FDE for batch of samples. pred = Num_modes x Num_ped x Num_timesteps x 2 gt = Num_ped x Num_timesteps x 2 seq_start_end (batch delimiter) = Num_batches x 2 """ s_topk_ade = 0 s_topk_fde = 0 for (start,...
ff93309e61d871a2d337810cc1836950f883c184
10,200
def disemvowel(sentence): """Disemvowel: Given a sentence, return the sentence with all vowels removed. >>> disemvowel('the quick brown fox jumps over the lazy dog') 'th qck brwn fx jmps vr th lzy dg' """ vowels = ('a','e','i','o','u') for x in sentence: if x in vowels: ...
d9b6d873c29e82cb65e43f71e2b6298af18b25fd
10,201
def runPolyReg(xValueList, yValueList, degrees): """ Preforms *Polynomial Regression* based on the arguments provided. Note that we split the data by the *First* 80 percent of the data and then the *Last* 20 percent of the data, rather than randomly splitting the data by 80/20 for the Train/Test split. ...
25d4699f720d943dc49264edc12f2246df51f053
10,202
def unfold_phi_vulpiani(phidp, kdp): """Alternative phase unfolding which completely relies on :math:`K_{DP}`. This unfolding should be used in oder to iteratively reconstruct :math:`Phi_{DP}` and :math:`K_{DP}` (see :cite:`Vulpiani2012`). Parameters ---------- phidp : :class:`numpy:numpy.ndar...
72386a05500c4ba11385e3b57288655e0a207352
10,203
def get_result_df(session): """ query the match table and put results into pandas dataframe, to train the team-level model. """ df_past = pd.DataFrame( np.array( [ [s.fixture.date, s.fixture.home_team, s.fixture.away_team, s.home_score, s.away_score] ...
364d9e7f9ef1a97018402fa964f246954f51f945
10,204
def permute1d(preserve_symmetry = True): """Choose order to rearrange rows or columns of puzzle.""" bp = block_permutation(preserve_symmetry) ip = [block_permutation(False),block_permutation(preserve_symmetry)] if preserve_symmetry: ip.append([2-ip[0][2],2-ip[0][1],2-ip[0][0]]) else: ...
a9ccd2cb486e0ee3d50840c6ab41871396f3ca93
10,205
from typing import Iterable from typing import List def take(n: int, iterable: Iterable[T_]) -> List[T_]: """Return first n items of the iterable as a list""" return list(islice(iterable, n))
491cdaaa20ad67b480ea92acaeb53e4edf2b4d56
10,208
def abs(rv): """ Returns the absolute value of a random variable """ return rv.abs()
6bf2f8420f8a5e883dfddfc9a93106662a8f1a74
10,209
def compute_ssm(X, metric="cosine"): """Computes the self-similarity matrix of X.""" D = distance.pdist(X, metric=metric) D = distance.squareform(D) for i in range(D.shape[0]): for j in range(D.shape[1]): if np.isnan(D[i, j]): D[i, j] = 0 D /= D.max() return 1...
646d9af2134db13b69391817ddfeace0fef1217d
10,210
def escape(instruction): """ Escape used dot graph characters in given instruction so they will be displayed correctly. """ instruction = instruction.replace('<', r'\<') instruction = instruction.replace('>', r'\>') instruction = instruction.replace('|', r'\|') instruction = instruction....
936ed1d6c55650bf5f9ce52af8f113a9d466a534
10,211
def _json_object_hook(d): """ JSON to object helper :param d: data :return: namedtuple """ keys = [] for k in d.keys(): if k[0].isdigit(): k = 'd_{}'.format(k) keys.append(k) return namedtuple('X', keys)(*d.values())
a4a534a975d6faff440f66065d4954e2a5a91ff2
10,212
def _fourier_interpolate(x, y): """ Simple linear interpolation for FFTs""" xs = np.linspace(x[0], x[-1], len(x)) intp = interp1d(x, y, kind="linear", fill_value="extrapolate") ys = intp(xs) return xs, ys
cfe663b9e261bbaea2ab6fe58366f4ec3726468c
10,213
import hashlib def compute_hash_json_digest(*args, **kwargs): """compute json hash of given args and kwargs and return md5 hex digest""" as_json = compute_hash_json(*args, **kwargs) return hashlib.md5(as_json).hexdigest()
98dfedb000e2780dba5007d9fe6abd7a74a43a31
10,214
def hello_world(): """Print welcome message as the response body.""" return '{"info": "Refer to internal http://metadata-db for more information"}'
ecb2208053e4ff530bcc0dcc117172449a51afbd
10,215
import google from datetime import datetime def build_timestamp(timestamp=None) -> google.protobuf.timestamp_pb2.Timestamp: """Convert Python datetime to Protobuf Timestamp""" # https://github.com/protocolbuffers/protobuf/issues/3986 proto_timestamp = google.protobuf.timestamp_pb2.Timestamp() return p...
ae2278b66c200f007240ca5f683a60ebc1ebddf2
10,217
def read_blosum(): """Read blosum dict and delete some keys and values.""" with open('./psiblast/blosum62.pkl', 'rb') as f: blosum_dict = cPickle.load(f) temp = blosum_dict.pop('*') temp = blosum_dict.pop('B') temp = blosum_dict.pop('Z') temp = blosum_dict.pop('X') temp = blosum_dic...
ddbf71c03e05bd156ad688a9fe9692da1d0a3dc4
10,219
from typing import List from typing import Tuple def parse_spans_bio_with_errors(seq: List[str]) -> Tuple[List[Span], List[Error]]: """Parse a sequence of BIO labels into a list of spans but return any violations of the encoding scheme. Note: In the case where labels violate the span encoded scheme, ...
6cea777cfb8bf96325f2695af2c48cc22c4884cf
10,220
from typing import Sequence from typing import Tuple def find_best_similar_match(i1: int, i2: int, j1: int, j2: int, a: Sequence, b: Sequence, sm: SequenceMatcher = None) \ -> Tuple[int, int, float]: """ Finds most similar pair of elements in sequences bounded by indexes a[i1:i2], b[j1: j2]. :par...
ca6e73c2315e2d2419b631cb505131f3daabea4b
10,221
def ConvUpscaleBlock(inputs, n_filters, kernel_size=[3, 3], scale=2): """ Basic conv transpose block for Encoder-Decoder upsampling Apply successivly Transposed Convolution, BatchNormalization, ReLU nonlinearity """ net = slim.conv2d_transpose(inputs, n_filters, kernel_size=[3, 3], stride=[2, 2], ac...
787104a3015bd901105383b203551573f9f07fcb
10,222
def make_random_password(self, length = 10, allowed_chars = 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789'): """ Generate a random password with the given length and given allowed_chars. The default value of allowed_chars does not have "I" or "O" or letters and digits that look similar -- just to avoid c...
be155b2537b062a396ed1d5aed6367857b21d49e
10,224
def autocov_vector(x, nlags=None): """ This method computes the following function .. math:: R_{xx}(k) = E{ x(t)x^{*}(t-k) } = E{ x(t+k)x^{*}(k) } k \in {0, 1, ..., nlags-1} (* := conjugate transpose) Note: this is related to the other commonly used definition for vector autocovarian...
8725b2695b51c014e8234605bc5e64ad1ca0c26b
10,225
def sequence_masking(x, mask, mode=0, axis=None, heads=1): """为序列条件mask的函数 mask: 形如(batch_size, sequence)的0-1矩阵; mode: 如果是0,则直接乘以mask; 如果是1,则在padding部分减去一个大正数。 axis: 序列所在轴,默认为1; heads: 相当于batch这一维要被重复的次数。 """ if mask is None or mode not in [0, 1]: return x else: ...
ac7e0da24eca87ab3510c1c274f0caeb2d527816
10,226
def __long_description() -> str: """Returns project long description.""" return f"{__readme()}\n\n{__changelog()}"
53260637e4e4f1e59e6a67238577fb6969e7769c
10,228
def captains_draft(path=None, config=None): """Similar to captains mode with a 27 heroes, only 3 bans per teams""" game = _default_game(path, config=config) game.options.game_mode = int(DOTA_GameMode.DOTA_GAMEMODE_CD) return game
05af49626cff0827ff1b78ffb1da082bba160d29
10,229
def create(width, height, pattern=None): """Create an image optionally filled with the given pattern. :note: You can make no assumptions about the return type; usually it will be ImageData or CompressedImageData, but patterns are free to return any subclass of AbstractImage. :Parameters: ...
dcd287353c84924afcdd0a56e9b51f00cde7bb85
10,230
import logging def compute_conformer(smile: str, max_iter: int = -1) -> np.ndarray: """Computes conformer. Args: smile: Smile string. max_iter: Maximum number of iterations to perform when optimising MMFF force field. If set to <= 0, energy optimisation is not performed. Returns: A tuple con...
0b923d7616741312d8ac129d7c7c99081a2c3f97
10,231
def get_api_key(): """Load API key.""" api_key_file = open('mailgun_api_key.txt', 'r') api_key = api_key_file.read() api_key_file.close() return api_key.strip()
55c87d15d616f0f6dfbc727253c2222128b63560
10,232
def bitserial_conv2d_strategy_hls(attrs, inputs, out_type, target): """bitserial_conv2d hls strategy""" strategy = _op.OpStrategy() layout = attrs.data_layout if layout == "NCHW": strategy.add_implementation( wrap_compute_bitserial_conv2d(topi.nn.bitserial_conv2d_nchw), w...
f009b1f7ac073573877b1ddab616868cdf1d42c7
10,233
def get_fpga_bypass_mode(serverid): """ Read back FPGA bypass mode setting """ try: interface = get_ipmi_interface(serverid, ["ocsoem", "fpgaread", "mode"]) return parse_get_fpga_bypass_mode(interface, "mode") except Exception, e: return set_failure_dict("get_fpga_bypass_mo...
b572a372c6c73bb0f65686b3235e3362d31e8655
10,235
def lookup_complement(binding): """ Extracts a complement link from the scope of the given binding. Returns an instance of :class:`htsql.core.tr.binding.Recipe` or ``None`` if a complement link is not found. `binding` (:class:`htsql.core.tr.binding.Binding`) A binding node. """ pro...
104f7b0139a8ca6390cb90dc10529d3be9a723ea
10,236
import itertools def flatten(colours): """Flatten the cubular array into one long list.""" return list(itertools.chain.from_iterable(itertools.chain.from_iterable(colours)))
41576ef947354c30d1995fefdd30ad86bddbfe6f
10,237
import numpy def create_word_search_board(number: int): """ This function creates a numpy array of zeros, with dimensions of number x number, which is set by the user. The array is then iterated through, and zeros are replaced with -1's to avoid confusion with the alphabet (A) beginning at 0. ...
31f22d56c947f61840ba87d028eb7de275d33cc9
10,239
def get_parent_choices(menu, menu_item=None): """ Returns flat list of tuples (possible_parent.pk, possible_parent.caption_with_spacer). If 'menu_item' is not given or None, returns every item of the menu. If given, intentionally omit it and its descendant in the list. """ def get_flat_tuples(menu_i...
c88ca93f7e8a7907425a51323ba53bb75bdf29c2
10,240
def _update_jacobian(state, jac): """ we update the jacobian using J(t_{n+1}, y^0_{n+1}) following the scipy bdf implementation rather than J(t_n, y_n) as per [1] """ J = jac(state.y0, state.t + state.h) n_jacobian_evals = state.n_jacobian_evals + 1 LU = jax.scipy.linalg.lu_factor(state.M - ...
31570ad29dca3ee01281819865e6efe1aec4050d
10,241
from typing import Tuple from typing import List def reduce_pad(sess: tf.Session, op_tensor_tuple: Tuple[Op, List[tf.Tensor]], _) -> (str, tf.Operation, tf.Operation): """ Pad module reducer :param sess: current tf session :param op_tensor_tuple: tuple containing the op to reduce, and a list of input ...
29d7e8daf85a9fe8fee118fd5ec5dc00018120a9
10,242
def parse_fastq(fh): """ Parse reads from a FASTQ filehandle. For each read, we return a name, nucleotide-string, quality-string triple. """ reads = [] while True: first_line = fh.readline() if len(first_line) == 0: break # end of file name = first_line[1:].rstr...
d33d3efebdd1c5f61e25397328c6b0412f1911dd
10,243
def minhash_256(features): # type: (List[int]) -> bytes """ Create 256-bit minimum hash digest. :param List[int] features: List of integer features :return: 256-bit binary from the least significant bits of the minhash values :rtype: bytes """ return compress(minhash(features), 4)
1dba3d02dd05bfd2358211fa97d99ce136cc198d
10,244
def coalesce(*values): """Returns the first not-None arguement or None""" return next((v for v in values if v is not None), None)
245177f43962b4c03c2347725a2e87f8eb5dc08a
10,245
from mitsuba.core.xml import load_string def test06_load_various_features(variant_scalar_rgb, mesh_format, features, face_normals): """Tests the OBJ & PLY loaders with combinations of vertex / face normals, presence and absence of UVs, etc. """ def test(): shape = load_string(""" ...
a0117fe48b53e448181014e006ce13368c777d90
10,246
import torch def euc_reflection(x, a): """ Euclidean reflection (also hyperbolic) of x Along the geodesic that goes through a and the origin (straight line) """ xTa = torch.sum(x * a, dim=-1, keepdim=True) norm_a_sq = torch.sum(a ** 2, dim=-1, keepdim=True).clamp_min(MIN_NORM) proj = x...
83b5a8559e783b24d36a18fb30059dce82bf9cf7
10,247
def is_online(): """Check if host is online""" conn = httplib.HTTPSConnection("www.google.com", timeout=1) try: conn.request("HEAD", "/") return True except Exception: return False finally: conn.close()
4dd9d2050c94674ab60e0dfbcfa0c713915aa2f3
10,248
def text_value(s): """Convert a raw Text property value to the string it represents. Returns an 8-bit string, in the encoding of the original SGF string. This interprets escape characters, and does whitespace mapping: - linebreak (LF, CR, LFCR, or CRLF) is converted to \n - any other whitespace c...
24d40367dbefcfbdd0420eb466cf6d09657b2768
10,249
def modifica_immobile_pw(): """La funzione riceve l' ID immobile da modificare e ne modifica un attibuto scelto dall'utente """ s = input("Vuoi la lista degli immobili per scegliere il ID Immobile da modificare? (S/N)") if s == "S" or s =="s": stampa_immobili_pw() s= input("Dammi ID...
99905d61d91178092dba8860265b2034b3f8430b
10,250
def hpat_pandas_series_len(self): """ Pandas Series operator :func:`len` implementation .. only:: developer Test: python -m hpat.runtests hpat.tests.test_series.TestSeries.test_series_len Parameters ---------- series: :class:`pandas.Series` Returns ------- ...
57bdd2a7f7ae54861943fb44f3bc51f1f6544911
10,251
from typing import List def arrays_not_same_size(inputs: List[np.ndarray]) -> bool: """Validates that all input arrays are the same size. Args: inputs (List[np.ndarray]): Input arrays to validate Returns: true if the arrays are the same size and false if they are not """ shapes = ...
8b9988f49d766bc7a27b79cf6495182e98a8fe18
10,252
def GetReaderForFile(filename): """ Given a filename return a VTK reader that can read it """ r = vtkPNGReader() if not r.CanReadFile(filename): r = vtkPNMReader() if not r.CanReadFile(filename): r = vtkJPEGReader() if not r.CanReadFile(filename): ...
f574417df44f8a43277e62967ec6fd4c986fa85a
10,253
def build_figure_nn(df, non_private, semantic): """ Dataframe with one semantic and one model """ l = df.query("epsilon > 0").sort_values(["train_size", "epsilon"]) naive, low, high = get_plot_bounds(df) fig = px.line( l, x="train_size", y="accuracy", range_y=[lo...
5eab366e20eaec721d7155d82e42d9222cacd3b5
10,254
def get_incomplete_sample_nrs(df): """ Returns sample nrs + topologies if at least 1 algorithm result is missing """ topology_incomplete_sample_nr_map = dict() n_samples = df.loc[df['sample_idx'].idxmax()]['sample_idx'] + 1 for ilp_method in np.unique(df['algorithm_complete']): dfx = df[df['algo...
2d816d80bb2f0c2686780ca49d0c01e89c69e7b5
10,255
from typing import Optional def _read_pos_at_ref_pos(rec: AlignedSegment, ref_pos: int, previous: Optional[bool] = None) -> Optional[int]: """ Returns the read or query position at the reference position. If the reference position is not within the span o...
51270a1c1a5f69b179e3623824632443775ec9c7
10,256
from astropy.io import fits as pf import numpy as np import logging def load_gtis(fits_file, gtistring=None): """Load GTI from HDU EVENTS of file fits_file.""" gtistring = _assign_value_if_none(gtistring, 'GTI') logging.info("Loading GTIS from file %s" % fits_file) lchdulist = pf.open(fits_file, chec...
c1a8019d052ce437680e6505e65134a5ed66a1a3
10,257
import requests def macro_australia_unemployment_rate(): """ 东方财富-经济数据-澳大利亚-失业率 http://data.eastmoney.com/cjsj/foreign_5_2.html :return: 失业率 :rtype: pandas.DataFrame """ url = "http://datainterface.eastmoney.com/EM_DataCenter/JS.aspx" params = { "type": "GJZB", "sty": "...
260debcfaf342d08acacfe034da51b3d3162393e
10,258
from typing import List import math def _convert_flattened_paths( paths: List, quantization: float, scale_x: float, scale_y: float, offset_x: float, offset_y: float, simplify: bool, ) -> "LineCollection": """Convert a list of FlattenedPaths to a :class:`LineCollection`. Args: ...
876421cd7f89dc5f3d64357e76f302c633e41ba7
10,259
def _CustomSetAttr(self, sAttr, oValue): """ Our setattr replacement for DispatchBaseClass. """ try: return _g_dCOMForward['setattr'](self, ComifyName(sAttr), oValue) except AttributeError: return _g_dCOMForward['setattr'](self, sAttr, oValue)
8a0fea986531aec66564bafcc679fed3b8631c10
10,260
def reduce_to_contemporaneous(ts): """ Simplify the ts to only the contemporaneous samples, and return the new ts + node map """ samples = ts.samples() contmpr_samples = samples[ts.tables.nodes.time[samples] == 0] return ts.simplify( contmpr_samples, map_nodes=True, keep_...
7661a58b6f4b95d5cb4b711db39bb28852151304
10,261
def get_name(tree, from_='name'): """ Get the name (token) of the AST node. :param tree ast: :rtype: str|None """ # return tree['name']['name'] if 'name' in tree and isinstance(tree['name'], str): return tree['name'] if 'parts' in tree: return djoin(tree['parts']) i...
b5f1e97eb570859b01bf9489c6b9d4874511fdcc
10,264
def pcaTable(labels,vec_mean,vec_std,val_mean,val_std): """Make table with PCA formation mean and std""" header="\\begin{center}\n\\begin{tabular}{| l |"+" c |"*6+"}\\cline{2-7}\n" header+="\\multicolumn{1}{c|}{} & \\multicolumn{2}{c|}{PC1} & \multicolumn{2}{c|}{PC2} & \multicolumn{2}{c|}{PC3} \\...
646fc1b5344a716b8f30714f112a477063bf91ce
10,265
def render_reference_page(conn: Connection, reference: str) -> str: """Create HTML section that lists all notes that cite the reference.""" sql = """ SELECT note, Bibliography.html,Notes.html FROM Citations JOIN Notes ON Citations.note = Notes.id JOIN Bibliography ON Bibliogr...
6ab73d0d85da28676e7bb3cf42b3304cd0d6ad47
10,266
import logging def normalize_bridge_id(bridge_id: str): """Normalize a bridge identifier.""" bridge_id = bridge_id.lower() # zeroconf: properties['id'], field contains semicolons after each 2 char if len(bridge_id) == 17 and sum(True for c in "aa:bb:cc:dd:ee:ff" if...
5370cc49e4c0272da2a471006bbbf3fd5e5521bf
10,267
import imp def pyc_file_from_path(path): """Given a python source path, locate the .pyc. See http://www.python.org/dev/peps/pep-3147/ #detecting-pep-3147-availability http://www.python.org/dev/peps/pep-3147/#file-extension-checks """ has3147 = hasattr(imp, 'get_tag') ...
459011ca1f07a023b139695cd2368767d46ca396
10,268
def get_bytes_per_data_block(header): """Calculates the number of bytes in each 128-sample datablock.""" N = 128 # n of amplifier samples # Each data block contains N amplifier samples. bytes_per_block = N * 4 # timestamp data bytes_per_block += N * 2 * header['num_amplifier_channels'] # ...
524e9015dacaf99042dd1493b24a418fff8c6b04
10,269
def recovered(): """ Real Name: b'Recovered' Original Eqn: b'INTEG ( RR, 0)' Units: b'Person' Limits: (None, None) Type: component b'' """ return integ_recovered()
1a5133a3cc9231e3f7a90b54557ea9e836975eae
10,270