content stringlengths 35 416k | sha1 stringlengths 40 40 | id int64 0 710k |
|---|---|---|
import os
def get_build_repos(directory):
"""
:param directory: Directory that stores all the cloned repositories.
:return: a list which contains the name of repositories under the directory
"""
repos = []
for filename in os.listdir(directory):
repos.append(filename)
return repos | eee2f189fb350d0a6f070a9c202a67e23f2c0db5 | 651,775 |
import functools
def manipulative(function):
"""Mark the operation manipulating itself instead of returning new one."""
@functools.wraps(function)
def wrapped(self, *args, **kwargs):
result = function(self, *args, **kwargs)
self.dirty = True
return result
return wrapped | d64d6aa6da71951a3eafce23d80c3128209c1bbe | 651,776 |
def compare_graphs(before, after):
"""
Compare two (sub)graphs.
Note: a == b != b == a!
:param before: A networkx (sub)graph.
:param after: A networkx (sub)graph.
:returns: A dict with changes.
"""
res = {'added': [],
'removed': [],
'added_edge': [],
'r... | ee89a35da1bb74a42c93787ec138ee416a04c831 | 651,777 |
import re
from typing import Counter
def extract(text_list, regex, key_name, extracted=None, **kwargs):
"""Return a summary dictionary about arbitrary matches in ``text_list``.
This function is used by other specialized functions to extract
certain elements (hashtags, mentions, emojis, etc.).
It can ... | 0b7c0caa736bd68ffe7497dc3f4526735968b385 | 651,778 |
import hashlib
def hash_sha512(*indata):
"""Create SHA512 hash for input arguments."""
hasher = hashlib.sha512()
for data in indata:
if isinstance(data, str):
hasher.update(data.encode('utf-8'))
elif isinstance(data, bytes):
hasher.update(data)
else:
... | e301dd99d91ea57388f8e165791b4e822ca0c582 | 651,779 |
def do_filesizeformat():
"""
Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102
bytes, etc).
"""
def wrapped(env, context, value):
# fail silently
try:
bytes = float(value)
except TypeError:
bytes = 0
if bytes < 1024:
... | bfbebfeafe5c64715b867b891d3a95d3d39770fa | 651,781 |
def clean_up_list(sensor_list):
""" Remove 'bad' database entries """
cleaned_list = []
for sensor in sensor_list:
if sensor in ['None', 'undef', '_old']:
pass
else:
cleaned_list.append(sensor)
return sensor_list | 6f676a0342206432fbbb966cdce31a2f2284369b | 651,782 |
import typing
def read_exact(stream: typing.BinaryIO, byte_count: int) -> bytes:
"""Read byte_count bytes from the stream and raise an exception if too few bytes are read (i. e. if EOF was hit prematurely).
:param stream: The stream to read from.
:param byte_count: The number of bytes to read.
:return: The read... | 29f9d5659a6a55191ee4ba5ae5f1ee1c9f03da3d | 651,783 |
def generate_nih_dict():
"""Generate ddsm dictionary containing important constants of ddsm dataset
Keys:
'csv_path':
'basedir':
'all_dicom_dir':
'imagedir_list':
'maskdir_list':
Args:
Returns:
ddsm_dict: dictionary containing important constants of dds... | 999931d694baba5c521b77f5c779bb108979327f | 651,785 |
def def_itemgetter(attr, default=None):
"""like operator.itemgetter but fills in missing keys with a default value
Args:
attr (str):
default (scalar):
Examples:
>>> records = [{'key': 1}, {'key': 3}, {'value': 3}]
>>> sorted(records, key=operator.itemgetter('key'))[0]
... | d72a72fd87358811ca061e565ba62faa4c99c0a0 | 651,786 |
def CEN_misclassification_calc(
table,
TOP,
P,
i,
j,
subject_class,
modified=False):
"""
Calculate misclassification probability of classifying.
:param table: input matrix
:type table : dict
:param TOP: test outcome positive
:type TOP : in... | 239f11c109a86bddfef3e44df8b05690ce6bfcae | 651,787 |
def _transpose(mat):
""" Transpose matrice made of lists
INPUTS
------
mat: iterable 2d list like
OUTPUTS
-------
r: list of list, 2d list like
transposed matrice
"""
r = [ [x[i] for x in mat] for i in range(len(mat[0])) ]
return r | ce884d2f0a0f2a43ec87a6955a4a0d8499fce846 | 651,788 |
def getFileData(fileName):
"""
Open a file, and read the contents. The with..open operation will auto-close the file as well.
"""
with open(fileName) as handle:
data = handle.read()
return data | b9f8f58246ee59e4377acd60d5a4d3fe2244914c | 651,789 |
from typing import List
import re
def expand_pairlist(wildcardpl: List[str], available_pairs: List[str],
keep_invalid: bool = False) -> List[str]:
"""
Expand pairlist potentially containing wildcards based on available markets.
This will implicitly filter all pairs in the wildcard-list... | 6397c1ff028d3439a9bacc1e337196107d5ae571 | 651,790 |
def _vnorm2(v):
"""Computes vec.vec"""
return v[0]*v[0] + v[1]*v[1] + v[2]*v[2] | 7517c570ae7b83314fa2ecb933a826fa96491992 | 651,791 |
import logging
def newIar(df_in, tech):
"""Replaces the input activity ratio value with a hardcoded value
defined in this function
Arguments:
df = dataframe with a 'TECHNOLOGY' and 'VALUE' column
tech = technology to replace iar for (CCG, HYD, SPV...)
Returns:
df_out = same datafr... | c9c00798c9bd3e3be66448ef0e5cf2af8dfd246c | 651,792 |
def scale_to(x, from_max, to_min, to_max):
"""Scale a value from range [0, from_max] to range [to_min, to_max]."""
return x / from_max * (to_max - to_min) + to_min | e48e1f6556ee39fbdbba3cf2aa62e4efbcefba1c | 651,793 |
def int_to_bits_indexes(n):
"""Return the list of bits indexes set to 1.
:param n: the int to convert
:type n: int
:return: a list of the indexes of bites sets to 1
:rtype: list
"""
L = []
i = 0
while n:
if n % 2:
L.append(i)
n //= 2
i += 1
... | 03f14c3eaca1f45090de94e1884ad207d6f4a502 | 651,794 |
def getTeamGames(formMatches):
"""
input: csv
output: map team -> map of dates -> games
"""
teamGames = {}
for index, row in formMatches.iterrows():
if row['date'] != None:
if row['team'] not in teamGames:
teamGames[row['team']] = {row['date']: row}
... | 693d925df7d54c80a2500fedb0d3cf0f5dee1423 | 651,795 |
def add1_immutable(bla):
"""
TESTS::
sage: from sage.structure.list_clone_timings import *
sage: add1_immutable(IncreasingArrays()([1,4,5]))
[2, 5, 6]
"""
lbla = bla[:]
for i in range(len(lbla)): lbla[i] += 1
return bla.__class__(bla.parent(), lbla) | daaddb0c1915fb6d8450a46becbb5020c9f14b2f | 651,796 |
def getDistances(digraph, path):
"""Returns total & outdoor distances for given path."""
total_dist = 0
outdoor_dist = 0
for i in range(len(path) - 1):
for node, edge in digraph.edges[path[i]]:
if node == path[i + 1]:
total_dist += edge.getTotalDistance()
... | c0578d7254cb78425e460348876f9d773c7d8d0a | 651,797 |
def header_format(morsels):
"""Convert list of morsels to a header string."""
return '; '.join(f'{m["name"]}={m["value"]}' for m in morsels) | 727c794a095d1e7714047f4fa219aeb4b32e63fe | 651,798 |
def create_dict(class_list, version_filter):
"""Create dictionary from class items"""
adict = {}
for i in class_list:
if version_filter:
if i.version != "None": # Filter out files without version
path = i.view_path[:i.view_path.find(i.name)-1]
adict[path... | 4178f7eedcbd1e59f0541f98957e5e393331762f | 651,799 |
def rangeStats(data, start, end, outputType, interDataInterval, tagTime):
"""
Calculate the mean, max, or min during a selected time persegSlopesiod (min).
"""
raise Exception("This function is no longer used.")
indexStart = int((start+(tagTime-5))/interDataInterval)
indexEnd = int((end+(tagTim... | e70fc6b89b041d70f976ecbe6e7daab93c2ae43a | 651,800 |
def app_name_from_ini_parser(ini_parser):
"""
Returns the name of the main application from the given ini file parser.
The name is found as follows:
* If the ini file contains only one app:<app name> section,
return this app name;
* Else, if the ini file contains a pipeline:main section, us... | 1d68cbcd036a6c5ff89728e427e073bee3d99356 | 651,801 |
def smoothbknpo_n(x, p):
"""
Generalised smooth broken power law.
Note: for p[4] == 2 the function is the same as 'smoothbknpo'
Args:
x: (non-zero) frequencies.
p[0]: Normalization.
p[1]: power law index for f--> 0.
p[2]: power law index for f--> oo.
... | 7fcad3273f97323c48475a7f79912f5af1b09d13 | 651,802 |
def rep0(s):
"""REGEX: build repeat 0 or more."""
return s + '*' | 6d92f89d3707452e0ca71e73db318bd9c9b79838 | 651,803 |
import torch
def convolve(bump, field):
"""Convolve field bump with field
"""
return torch.sum(torch.mul(bump, field), dim=0, keepdim=True) | 55cf568cf2cdc696f2982fd243a91f14e94f60be | 651,804 |
def get_axes(self):
"""Return axes list.
Parameters
----------
self: DataND
a DataND object
Returns
-------
axes_list
"""
return self.axes | 12a89faa91d932abf614e3ab8d8813174c6e83c6 | 651,805 |
def get_run_dict4EGU_runs():
"""
Return locations of data to use for analysis/plotting for EGU presentation
"""
RunRoot = '/users/ts551/scratch/GC/rundirs/'
# wds = glob.glob( RunRoot+ '*Oi*' )
# runs = [i.split('Oi.')[-1] for i in wds]
wds = {
# spin up period
# 'Chance2014... | 82784e710b898ffbe1d1c04496564968cba250b3 | 651,806 |
import math
def euclidean_distance_native(u, v):
"""Computes the Euclidean distance between two vectors, represented as Python
lists.
Args:
u (List[float]): A vector, represented as a list of floats.
v (List[float]): A vector, represented as a list of floats.
Returns:
float: ... | df39309f463ffe1901831cbf32eab142caaad0f0 | 651,807 |
def del_pos(s):
"""
Deletes part-of-speech encoding from an entity string, if present.
:param s: Entity string.
:return: Entity string with part-of-speech encoding removed.
"""
if s.endswith("/n") or s.endswith("/a") or s.endswith("/v") or s.endswith("/r"):
s = s[:-2]
return s | ee0930ce32b8e32893fff5bfe25cd67712ae7f2b | 651,808 |
import re
def remove_characters_irregular(corpus):
"""
Corpus: type string
"""
return re.sub(u"([^\u4e00-\u9fa5\u0030-\u0039\u0041-\u005a\u0061-\u007a])", "", corpus) | bb6c4d9e3622c4a268ad729b7ddec52901f90f3c | 651,810 |
def _sortValue_familyName(font):
"""
Returns font.info.familyName.
"""
value = font.info.familyName
if value is None:
value = ""
return value | 58d85b95eff2a6ac1a5958456d87aa7a03350df6 | 651,812 |
import builtins
def builtin_target(obj):
"""Returns mock target string of a builtin"""
return f"{builtins.__name__}.{obj.__name__}" | 0e21e170897a2b7a2f757bd54cf6392f03660db3 | 651,813 |
def get_es_mapping(es, es_index):
"""
Get es mapping for given doc type (so we can handle type=nested)
Note this is the mechanism by which we "enable" the ability to do nested searches
ie: only enabled on single index searches. You could feasibly add more criteria.
:param es: elasticsearch client
... | 6c843f998c4a9e196b8380356d0282562fe6902e | 651,814 |
def parse_txt(txt):
"""Parse_txt
Funcion que parsea el archivo con las
urls y devuelve una lista con ellas
Params:
txt, fichero con las urls
"""
links = []
for line in open(txt, 'r'):
if not line[0].startswith("#"):
links.append(line.rstrip("\n\r"))
return l... | 1c68a85b24dd64085c5e6c51d1f31e908a82cecc | 651,815 |
from functools import reduce
def bits_to_int(list_):
"""
Converts a big-endian bit string to its integer representation.
>>> bits_to_int([1, 0, 1])
5
"""
return reduce(
lambda a, x: a | (1 << x[1]) if x[0] == 1 else a,
zip(list_, range(len(list_) - 1, -1, -1)),
0,
... | b555eb7fb3482dfaebf762d5a3a502ad62d23252 | 651,816 |
import re
def _search(query, choices, accessor=None):
"""Search for matches of query in choices.
query.match(choise)
Optionally provide an accessor:
query.match(accessor(choise))
"""
if query is None:
return choices
regex = re.compile(query.replace("*", ".*").replace(" ", ".*"),
... | 2925fc6890f384b894b98a53f20e1f70a017838e | 651,817 |
def parse_artist(data):
"""parse artist data in to message"""
return "%s - %s followers" % (data["name"], data["followers"]["total"]) | 96c85bba700661967e0ff9c98e65c4fae05fa282 | 651,818 |
def tier_from_site_name(s):
"""
Splits site name by _ (underscore), and takes only the first part that represents tier.
"""
split = s.split('_')
tier = str(split[0])
return tier | 9fb6c531ee413b0a8411d1568d4058572d408a35 | 651,819 |
def _get_line_index(line_or_func, lines):
"""Return the appropriate line index, depending on ``line_or_func`` which
can be either a function, a positive or negative int, or None.
"""
if hasattr(line_or_func, '__call__'):
return line_or_func(lines)
elif line_or_func:
if line_or_func ... | ed82c9d84d25e6f6cdb7a5738bc8498a93bbe09a | 651,820 |
def to_tf_signature(signature):
"""
Converts a Dataset signature to a TensorFlow signature.
:param signature: a Dataset signature.
:return: a TensorFlow signature.
"""
output = []
keys = ["x", "a", "e", "i"]
for k in keys:
if k in signature:
shape = signature[k]["shap... | 6af434428c45f2a911be241571df95ece2dbf315 | 651,821 |
def ToString(bval):
"""Convert a bytes type into a str type
Args:
bval: bytes value to convert
Returns:
Python 3: A bytes type
Python 2: A string type
"""
return bval.decode('utf-8') | 978284dcb33bbf3449eed76ba7e0e320305477e7 | 651,825 |
def parse_image_size(image_size):
"""Parse "100x100" like string into a tuple."""
return tuple(map(int, image_size.split("x"))) | 2712ab9b756db2a2b62ef908b34404d6dc4fd410 | 651,826 |
def stack_3d_on_z(ds, name):
"""Stack 'z' measurments together along new 3D 'z' dimension."""
da = ds.to_array(dim="z")
da = da.assign_coords(z=da.z.astype(float))
dim_order = ['time', 'z', *da.dims[-2:]]
da = da.transpose(*dim_order)
ds3 = da.to_dataset(name=name)
return ds3 | 1ee3b53b85d979a0cfe4fd6cd15f0b8625b0d5c2 | 651,827 |
import os
def check_title(mol, infile):
"""
Check if mol has title which is required for setting up new subdirectories.
If not title listed, rename molecule based on filename. Process filename
to remove dashes and dots due to file name limitations of pipeline.
Parameters
----------
mol : ... | fd52d438a883b1f7e07f38ff8db0825c0a281a61 | 651,828 |
def unwrap_model(model_wrapper):
"""Remove model's wrapper."""
model = model_wrapper.module
return model | ea184f522350e726786961182ccde24e246c6e5e | 651,829 |
import torch
def torch_multinomial(input, num_samples, replacement=False):
"""
Like `torch.multinomial()` but works with cuda tensors.
Does not support keyword argument `out`.
"""
if input.is_cuda:
return torch_multinomial(input.cpu(), num_samples, replacement).cuda()
else:
ret... | bed9ac316c6f54f429d3da86a91d2337cd3b4e22 | 651,830 |
def desired_caps(apk_path, apk_name,
platform_version='4.4',
device_name='Android Emulator'):
"""Return capabilities related to sauce devices."""
return {
'name': apk_name,
'app': 'sauce-storage:{}'.format(apk_name),
'platformName': 'Android',
'd... | 8064ec7584335e7fd7999ba3a038418c0492526f | 651,831 |
def snakemake_workflow_spec_loaded():
"""Scatter-gather Snakemake workflow.
Scope: function
This fixture provides the internal representation of a basic scatter-gather ``snakemake`` workflow loaded as dictionary.
"""
return {
"version": "0.8.0",
"workflow": {
"type": "s... | a41767b70b9b87a944f3db10ab3854f955768119 | 651,832 |
def dna_2_rna(dna_str):
"""
Transcribes DNA into RNA
RNA differs from DNA in that it contains a base called uracil in place of thymine.
An RNA string is formed by replacing all occurrences of 'T' in the DNA string with 'U'.
Params:
-------
dna_str: (str)
DNA string. For example: "GATGGAACTTGACTACGTAAATT"... | 420b6de3def169d43618a18cdc86f119c4b7fae3 | 651,833 |
def _translation_vectors(mtps, vector_table):
"""For a set of maximally translatable patterns, returns the set of
translation vectors for the MTPs.
Finds the common translation vectors for each note of a MTP, enabling
finding all occurrences of the MTP.
Args:
mtps: All MTPs of a point set
vector_table: Vecto... | 5a78fb74d7d8792e030de94a1ca9d07d16abd98f | 651,834 |
import numpy
def score_fusion_strategy(strategy_name="average"):
"""Returns a function to compute a fusion strategy between different scores.
Different strategies are employed:
* ``'average'`` : The averaged score is computed using the :py:func:`numpy.average` function.
* ``'min'`` : The minimum score is ... | b9e44893e50bb8181978a12ecc3ceb72dd4e20ef | 651,835 |
import re
def __get_auth_api_url(module, url):
"""
Return the parsed URL of the specific authentication API.
:param AnsibleModule module: the ansible module
:param str url: the initial URL of API
:rtype: str
"""
# format the input for zmd_port
if module.params['zmf_port'] is None:
... | 92b7fa2a71140b100d5d38ec78bae45d4076cd05 | 651,836 |
def calc_temp_overlap(start_1, end_1, start_2, end_2):
"""
Calculate the portion of the first time span that overlaps with the second
Parameters
----------
start_1: datetime
start of first time span
end_1: datetime
end of first time span
start_2: datetime
start of se... | 2fa9882a90628056fba615c58f2ad8907c4d8315 | 651,837 |
def logo():
""" pySAP logo is ascii art using Big Money-ne.
Returns
-------
logo: str
the logo.
"""
logo = r"""
/$$
| $$
/$$$$$$ /$$ /$$ /$$$$$$$ /$$$$$$ /$$$$$$
/$$__ $$| $$ | $$| ... | 5e9df5ff3bcd4be03a9289d52fbfacfb2757e5f7 | 651,839 |
import socket
def is_port_in_use(port: int) -> bool:
"""
Check if a porty is in use.
"""
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
return s.connect_ex(('localhost', port)) == 0 | 201cbfa3458b1002d975b2abca6b8908ea387e29 | 651,840 |
import os
def get_concat_output_dir(concat_stage_index: int, concat_processing_dir: str):
"""
Get the file name with the list of files to be concatenated for a given stage and batch in the concatenation process
"""
return os.path.join(concat_processing_dir, "vertical_concat", f"stage_{concat_stage_ind... | a32f8fe5d8fcaec86447b0ac14af32b01aaaa494 | 651,841 |
def process_fieldmap_solrf(data):
"""
Processes array of raw data from a rfdataX file into a dict.
From the documentation:
Here, the rfdataV5 file contains the Fourier coefficients for both E fields and B fields.
The first half contains E fields, and the second half contains B fields.
See m... | 4d4aacd0153368c2fbc9938b03e6e0cd51ab419e | 651,842 |
def mendel(k,m,n):
"""
Probabilidade de ter um A
k m n
|AA|Aa|aa
AA| 1| 1| 1
Aa| 1|.75|.5
aa| 1|.5| 0
Probabilidade de ser recessivo -> usei esse pra ficar menor o calculo
|AA|Aa|aa
AA| 0| 0| 0
Aa| 0|.25|.5
aa| 0|.5| 1
Probabilidade de cair cada combinação
total = k+m+n
m (Aa... | 00fcc2c62ca05ece486c5a79d52217e26570bd99 | 651,843 |
def utf8(s):
"""Convert to UTF-8."""
return s.encode("UTF-8") | 7d532c16d144fd307f3a38cb4ec5785c4a95de64 | 651,844 |
def element_is_scrolled_to_left(element):
"""
Is the element scrolled to the left?
:param element:
:return: Boolean
"""
return int(element.get_property('scrollLeft')) == 0 | 3d77d1ec73e86ab87811ffde95d3cc2a14e2c90f | 651,845 |
import pathlib
def as_uri(path):
"""
Converts the supplied path to file URI
:param path: Path to be converted
:return: Path as a fille URI
"""
p = pathlib.Path(path)
return p.as_uri() | 172428ffb0e54159d73d8479598e652b7530e09f | 651,846 |
def parse_proasis(input_string):
"""
Parse proasis contact strings
:param input_string: the Proasis contact string to parse
:return: a tuple of res_name, res_num, chain_id
"""
return (
input_string[:3].strip(),
int(input_string[5:].strip()),
input_string[3:5].strip(),
... | 628679e3f8ca4b06ff3dea8429bec623f7dc610c | 651,848 |
import sys
def get_host_tag_or_die():
"""Return the host tag for this platform. Die if not supported."""
if sys.platform.startswith('linux'):
return 'linux-x86_64'
elif sys.platform == 'darwin':
return 'darwin-x86_64'
elif sys.platform == 'win32' or sys.platform == 'cygwin':
re... | bae7d674d776081c38024ca1ca9629fddc6756ed | 651,849 |
import torch
def _my_collate(batch):
"""Custom collate function to handle images with different depths."""
data = [item[0] for item in batch]
target = [item[1] for item in batch]
return [torch.Tensor(data), torch.Tensor(target)] | d8038856c77bd7de162e32fc0885f2afa9b7749f | 651,850 |
import torch
def _tuple_splice_range(inputs, start, end):
"""
Splices each tensor element of given tuple (inputs) from range start
(inclusive) to end (non-inclusive) on its first dimension. If element
is not a Tensor, it is left unchanged. It is assumed that all tensor elements
have the same first... | 97cda7293986e72650432eeba679bb3e84eb09a4 | 651,851 |
import uuid
def is_uuid(id):
"""Verify if a string is an UUID"""
try:
v = uuid.UUID(id)
except ValueError:
v = None
return isinstance(v, uuid.UUID) | d00c0633d308c95755eeefc6d55218dd173653fa | 651,853 |
def _bump(char, position):
"""
only treats `\n` as newline
"""
line, col = position
if char == '\n':
return (line + 1, 1)
return (line, col + 1) | 92d88865ab29bccee9dbbbf741ae2ce2605e1159 | 651,854 |
import gzip
def gzip_tar_member(member):
"""
Read zipped file and return a list of lines
Zip File -> List
"""
gf = gzip.GzipFile(member)
return gf.readlines() | 03fdbde86638098d1aad270072aeaa2427571e3a | 651,855 |
import secrets
def pick(s, n):
"""Return a string with n randomly picked characters from string s."""
return "".join(secrets.choice(s) for i in range(n)) | 4a04fcf7b0175f7406a52237b43c906b54bfdb70 | 651,856 |
def read_NSFGfile(file_path, col_name_dct):
"""
Read NSFG file
Get each col value based on (start, end) index
:param file_path: input file path
:param col_name_dct: The dictionary that contains colname as well as the index range
:return: extracted data
"""
results = []
with open(file... | 8c0ed9882f4667dd3059d417b1f295b49ce5397d | 651,857 |
import collections
def rankVars(dq):
"""Find the maximal priorities at which variables are requested ... to prioritise checking .. called by sm1"""
cc = collections.defaultdict( set )
ee = {}
ff = {}
for i in dq.coll['var'].items:
s = set()
r = set()
if 'CMORvar' in dq.inx.iref_by_sect[i.uid].a... | ebfe61409f6a494fcbce3c66e95832a3f63ccdbf | 651,858 |
def next(it):
"""Implementation of `next`."""
return it.__myia_next__() | 59e097bddeeabdfe1daf71515e3cac63458af0c4 | 651,859 |
import json
def payload():
"""
example payload from /status?json
"""
return json.loads("""{
"pool":"www",
"process manager":"dynamic",
"start time":1530722898,
"start since":12,
"accepted conn":2,
"listen queue":0,
"max listen queue":0,
"... | ec468b753c061dfe50ba1d50bdb52f4cb1918805 | 651,860 |
import json
import re
def uri_twitch(bot, response, matches):
""" Extract Twitch.tv channel information. """
channel = json.loads(response.text)
title = channel['status'].replace('\n', ' ')
title = re.sub(r'\s+', ' ', title).strip()
game = channel['game'].replace('\n', ' ')
game = re.sub(r'\s... | b211c9fbd4fc3074125c0b7e6cf488c0ca251be7 | 651,861 |
def popup_after_submit(message, result):
""" xxx """
#if result == 1: success else: error
return_data = ''
l_content = '<i class="fas fa-exclamation-circle"></i> '+ str(message)
l_class = ''
l_class_error = 'alert alert-danger'
l_class_success = 'alert alert-success'
if result == 1:... | b5317cf511336efd40e2b1059083ce59d6adcb1c | 651,862 |
def factory(*attributes):
"""Create read-only-attributes"""
def read_only_attributes_wrapper(cls):
class ReadOnlyAttributesClass(cls):
"""Modified class with read only attributes"""
def __setattr__(self, name, value):
"""https://python-reference.readthedocs.io/e... | 06e045d0054e00e3c5c5442ca2219992e8b27f16 | 651,863 |
def delete(flavor_id, **kwargs):
"""Delete flavor."""
# NOTE: flavor_id can be any string, don't convert flavor name to uuid
url = '/flavors/{flavor_id}'.format(flavor_id=flavor_id)
return url, {} | 46208cf3bd57f297626f19d1f3e72de490db22e0 | 651,864 |
def compute_denominator(log_strike, variance, deriv_1, deriv_2):
"""
Compute denominator in local vol equation.
Args:
log_strike: The log-strike.
variance: The variance.
deriv_1: The first derivative of variance wrt log strike.
deriv_2: The second derivative of variance wrt... | ad34e8a7390878ebfba9c12701e83d76f00fcfbc | 651,865 |
def _prepare_padding_argument(x):
"""Helper which processes the padding argument."""
if not hasattr(x, 'upper'):
return tuple(x)
padding = x.upper()
if padding in {'CAUSAL', 'FULL'}:
raise NotImplementedError(
'Argument `padding` value "{}" currently not supported. If you '
'require this... | 650e7df09726ee831c90a65ea403f4f1d950e83b | 651,866 |
def _LookupTargets(names, mapping):
"""Returns a list of the mapping[name] for each value in |names| that is in
|mapping|."""
return [mapping[name] for name in names if name in mapping] | 03a038150f7f757a99e9cfbb9cdaf6e98f441d57 | 651,868 |
import requests
def connect_to_endpoint(url, headers):
"""Fetches latest information of a Twitter handle
Args:
url: URL to make a GET call
headers: Headers need for authentication
Returns:
List of tweets in json format
"""
response = requests.request("GET", url, headers=he... | f66b9079c72956dbca1be1be92015a065f0e157c | 651,869 |
def rotate(x, y, ctx, cty, ang) :
""" Rotate catalog x,y against center (ctx,cty), using specified rotate angle
args:
x: ndarray of x, or scalar
y: ndarray of y
ctx: center x, scalar
cty: center y
ang: rotate angle, 0-7
0 keep original
1 CW 90 deg
... | 540376d71d41d18b0126706222e63fef1020c72b | 651,870 |
def verbose_name(obj):
"""Фильтр получает verbose_name модели.
"""
try:
return getattr(obj._meta, 'verbose_name', '')
except AttributeError:
return '' | feb5777a5260bfca9b7e8ce88cdf2a4927262108 | 651,871 |
def _HexToSignedInt(hex_str):
"""Converts a hex string to a signed integer string.
Args:
hex_str: A string representing a hex number.
Returns:
A string representing the converted signed integer.
"""
int_val = int(hex_str, 16)
if int_val & (1 << 31):
int_val -= 1 << 32
return str(int_val) | 2375c7b838c69b613ba73b95b6b7fe939b5d435a | 651,872 |
def _read_genel_fields_until_char_blank(card_fields, istart):
"""somewhat loose parser helper function for GENEL"""
new_fields = []
i = 0
for i, field in enumerate(card_fields[istart:]):
if field is None:
break
if field.upper() in ['UD', 'K', 'S', 'Z']:
break
... | 51b505658d6e0ad0ef0186f79a1d38e5f7d65314 | 651,873 |
def makeint(number) :
"""Rounds the number"""
rounded = int(round(number))
if rounded > number :
returnval = rounded - 1
else :
returnval = rounded
return returnval | 479c8cbd8ea2df66099e737a842e414e4b51a92f | 651,875 |
def dquote(args):
"""MODIFICATION Wraps elements in double quotes
"""
def _f(input):
return [ '"'+i+'"' for i in input ]
return _f | 5e892fd590ee5550cedd8c679ed3ceea64d01987 | 651,876 |
def divide_delta(td1, td2):
"""Divides two timedeltas and returns the integer result."""
us1 = td1.microseconds + 1000000 * (td1.seconds + 86400 * td1.days)
us2 = td2.microseconds + 1000000 * (td2.seconds + 86400 * td2.days)
# Integer division, fractional division would be float(us1) / us2
return us... | d3d1ad957970c3c7785f17ff83ba0dd57473244e | 651,877 |
def rank_order(df, rank_column, ascending=False):
"""
Given dataframe with a column of numerical values, order and rank those values.
Allows for ties if a value is the same as the previous value.
"""
df = df.sort_values(rank_column, ascending=ascending).reset_index().drop('index', axis=1)
ranki... | 0797fe1d2ff9029241ed50eef0b454ac4a3ec30b | 651,879 |
def sim_flow_expression_rule(mod, g, tmp):
"""
**Expression Name**: Sim_Flow_MW
**Defined Over**: SIM_FLOW_LMT_TMPS
Total flow on lines in each simultaneous flow group.
"""
return sum(mod.Transmit_Power_MW[tx_line, tmp]
* mod.sim_flow_direction[g, tx_line]
for tx_l... | 95f0a375e6a9004c9d002c48b78bb7ff87c22bae | 651,880 |
import copy
def get_descendants(node, include_self=True):
"""
Return a flat list including `node` and all its descendants. Nodes returned
are modified to remove the tree structure between them (set `children=[]`).
"""
results = []
if include_self:
node_copy = copy.deepcopy(node)
... | 0c6f2ac11eb2a8f636da63b3a7b3853f79fe0324 | 651,881 |
def get_activation_wts(attention_model,x):
"""
Get r attention heads
Args:
attention_model : {object} model
x : {torch.Variable} input whose weights we want
Returns:
r different attention weights
"""
attention_model... | f298e1bedc7480de14f07d5c4b589db0de1f192f | 651,882 |
def extend(s):
"""Return a float for `s` extended to machine precision.
Takes a string like '13.6667', passes it to `float()`,
and snaps it to the nearest whole second.
"""
return round(3600 * float(s)) / 3600. | 0e04ae7f2108fb70b9ef7f07335676562a70c745 | 651,884 |
def get_summary_save_keys():
"""
:return: numpyro variables to save, if available
"""
return ["alpha_i"] | 2886279f657f6afd02cfeac9dbade57007b660bb | 651,885 |
import argparse
def parse_commandline():
"""Parse script cl arguments."""
parser = argparse.ArgumentParser()
parser.add_argument("libp2p_node")
config = parser.add_mutually_exclusive_group(required=False)
config.add_argument(
"--config-from-env",
action="store_true",
dest=... | 6aa50284f5647eee6c2c648e4237382bb72907b5 | 651,886 |
import os
def read_gene_pred_file(gene_pred_file_handle):
"""
reads a genePred file as list of lists
:param gene_pred_file_handle: file handle for the genePred input file
:return: list of lists of all entries in the file
"""
print("reading genePred file..... | 353e1a9f6a0eb8f724ba62f0bf6bc25486486439 | 651,887 |
import os
def _realpath(path):
"""
Return the cannonical path with normalized case.
It is useful on Windows to comparision paths in case-insensitive manner.
On Unix and Mac OS X it works as `os.path.realpath()` only.
"""
return os.path.normcase(os.path.realpath(path)) | c4258555bac9c016e7454e024b262c2a88d196c2 | 651,888 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.