content stringlengths 35 762k | sha1 stringlengths 40 40 | id int64 0 3.66M |
|---|---|---|
def aes_block(ciphertext, key):
"""Uses the AES algorithm in ECB mode to decrypt a 16-byte ciphertext
block with a given key of the same length.
Keyword arguments:
ciphertext -- the byte string to be decrypted
key -- the byte string key
"""
if len(ciphertext) != 16:
raise Val... | b0b894bcf860c92b46235ce45b8fd6c8c045b1ca | 3,643,300 |
import logging
def getLogger(*args, **kwargs):
"""
Wrapper around ``logging.getLogger`` that respects `overrideLogLevel <#setOverrideLogLevel>`_.
"""
logger = logging.getLogger(*args, **kwargs)
if _overrideLogLevel is not None:
logger.setLevel(logging.NOTSET)
return logger | f4ae90925e8bd20a63997e2e5e04924aeeafbcaa | 3,643,301 |
def split_metadata_string(text, chunk_length=None):
"""Split string by length.
Split text to chunks by entered length.
Example:
```python
text = "ABCDEFGHIJKLM"
result = split_metadata_string(text, 3)
print(result)
>>> ['ABC', 'DEF', 'GHI', 'JKL']
```
Ar... | c2e97aa768f64f02ef1a691dfadce3dd9fe5538a | 3,643,302 |
def load_kimmel_data(root_data_path,
flag_size_factor=True, total_ct_per_cell=1e4,
flag_log1p=True):
"""Load normalized data from Kimmel et al, GR, 2019
1. Size factor normalization to counts per 1 million (total_ct_per_cell)
2. log(x+1) transform
Args:
... | 324f5779c180811db0b9316125553f7089d5a34b | 3,643,303 |
import requests
def get_coupon_page() -> bytes:
"""
Gets the coupon page HTML
"""
try:
response = requests.get(COUPONESE_DOMINOS_URL)
return response.content
except RequestException as e:
bot.logger.error(e.response.content)
return None | 919cd65ec9e4f0af7b06a79c8aa962f164fb7af6 | 3,643,304 |
def get_program_similarity(fingerprint_a, fingerprint_b):
"""Find similarity between fingerprint of two programs.
A fingerprint is a subset of k-gram hashes generated from program. Each of
the k-gram hashes is formed by hashing a substring of length K and hence
fingerprint is indirectly based on substr... | c3cc3def2d17657c266e09ce5b05da773e1f6f1a | 3,643,305 |
import os
def load_regions_with_bounding_boxes():
"""Loads bounding boxes as shapely objects.
Returns:
list: list of shapely objects containing regional geometries
"""
print(
"loading region bounding boxes for computing carbon emissions region, this may take a moment..."
)
... | 3ac80793312423df28ed9b6bafc3dfe542319e84 | 3,643,306 |
def create_variables(name, shape, initializer=tf.contrib.layers.xavier_initializer(), is_fc_layer=False):
"""
:param name: A string. The name of the new variable
:param shape: A list of dimensions
:param initializer: User Xavier as default.
:param is_fc_layer: Want to create fc layer variable? May u... | 4197b189c54075a1ce41e6fec85445b86ea26e92 | 3,643,307 |
def linear_transformation(x, y_min, y_max):
"""
x : the range to be transformed
y_min, y_max : lower and upper boundaries for the range into which x
is transformed to
Returns y = f(x), f(x) = m * x + b
"""
x_min = np.min(x)
x_max = np.max(x)
if x_min == x_max:
x_max = x_min *... | ddd6da6b006888a43711dc391948ffce96bd0a81 | 3,643,308 |
import random
def resize_image(image, desired_width=768, desired_height=384, random_pad=False):
"""Resizes an image keeping the aspect ratio mostly unchanged.
Returns:
image: the resized image
window: (x1, y1, x2, y2). If max_dim is provided, padding might
be inserted in the returned image. I... | 9744bb52c58e1049c8cbd6ce9e1f1864f64ac3c5 | 3,643,309 |
def get_state(*names):
"""
Return a list of the values of the given state keys
Paramters
---------
*names : *str
List of name of state values to retreive
Returns
-------
[any, ...]
List of value matching the requested state property names
"""
_app = get_app_inst... | 8f863bdb9f578eb0e12731d1b752f197d4476a2c | 3,643,310 |
def ver_datos_basicos(request, anexo_id):
"""
Visualización de los datos básicos de un anexo.
"""
anexo = __get_anexo(request, anexo_id)
parts = anexo.get_cue_parts()
return my_render(request, 'registro/anexo/ver_datos.html', {
'template': 'registro/anexo/ver_datos_basicos.html... | 63cb5222cad1fa702dd5bd2fc7a14c38f4b71d65 | 3,643,311 |
def fill_sections(source, sections):
"""
>>> fill_sections(\
' /* Begin User Code Section: foobar *//* End User Code Section: foobar */', {'foobar': 'barbaz'})
' /* Begin User Code Section: foobar */\\n barbaz\\n /* End User Code Section: foobar */'
"""
def repl(matches):
indent_... | 6a76826f45aa0880039e70ad6bb41aa93442976b | 3,643,312 |
def CNOT(n):
"""CNOT gate on 2-Qubit system with control qubit = 0 and target qubit = 1"""
x=np.copy(I4)
t=np.copy(x[2,])
x[2,]=x[3,]
x[3,]=t
return x.dot(n) | af72004c9dd6f4a970e95d1da48a9d3776bd730b | 3,643,313 |
import tokenize
def parse(s):
"""Parse a single string. This is just a convenience function."""
return pogo(parseSingleExpression(tokenize(s),
identity_cont)) | 9a7a2f4b2afd1daf22e6d2258e13ac9d13d380b3 | 3,643,314 |
def link_match_check(row):
"""
Indicating that link is already in database
"""
all_objects = Post.objects.all()
try:
row_link = row.a["href"]
for object_founded in all_objects:
return row_link == object_founded.link
except TypeError:
return False | 2d55554248791b8edb5ec6080bc4c4f152a6a23a | 3,643,315 |
def merge_s2_threshold(log_area, gap_thresholds):
"""Return gap threshold for log_area of the merged S2
with linear interpolation given the points in gap_thresholds
:param log_area: Log 10 area of the merged S2
:param gap_thresholds: tuple (n, 2) of fix points for interpolation
"""
for i, (a1, g... | 36dd06c8af828e3dc2ef5f1048046039feaa6c21 | 3,643,316 |
def rename_indatabet_cols(df_orig):
"""
"""
df = df_orig.copy(deep=True)
odds_cols = {'odds_awin_pinn': 'awinOddsPinnIndatabet',
'odds_draw_pinn': 'drawOddsPinnIndatabet',
'odds_hwin_pinn': 'hwinOddsPinnIndatabet',
'odds_awin_bet365': 'awinOddsBet365In... | a07e7c9757e1b207528f7b7fda63e06a1dced47a | 3,643,317 |
import urllib
def get_market_updates(symbols, special_tags):
"""
Get current yahoo quote.
'special_tags' is a list of tags. More info about tags can be found at
http://www.gummy-stuff.org/Yahoo-data.htm
Returns a DataFrame
"""
if isinstance(symbols, str):
sym_list = symbols
e... | d3dd970ef513a131147cc687cb9ad2076ee0b0ff | 3,643,318 |
def HLRBRep_SurfaceTool_Torus(*args):
"""
:param S:
:type S: Standard_Address
:rtype: gp_Torus
"""
return _HLRBRep.HLRBRep_SurfaceTool_Torus(*args) | 46aa63882557b1a2e13cb245f81fcf9871903a18 | 3,643,319 |
def load_augmentation_class():
"""
Loads the user augmentation class.
Similar in spirit to django.contrib.auth.load_backend
"""
try:
class_name = AUTH.USER_AUGMENTOR.get()
i = class_name.rfind('.')
module, attr = class_name[:i], class_name[i + 1:]
mod = import_module(module)
klass = getatt... | 16f737a2687e0b2e5002982adcafef9c32c82e36 | 3,643,320 |
def FieldTypeFor(descriptor, field_desc, nullable):
"""Returns the Javascript type for a given field descriptor.
Args:
descriptor: The descriptor module from the protobuf package, e.g.
google.protobuf.descriptor.
field_desc: A field descriptor for a particular field in a message.
nullable: Whet... | 0e2c2d48dc22d209053d06fda354e4df9912144a | 3,643,321 |
def unadmin(bot, input):
"""Removes person from admins list, owner only"""
if not input.owner: return False
bot.config.set_del('admins',input.group(2).lower())
bot.reply("Unadmin'd {0}".format(input.group(2))) | 1a74ab0a3d3d1b41dd6d1f065b71a48557af84ed | 3,643,322 |
def sim_beta_ratio(table, threshold, prior_strength, hyperparam, N,
return_bayes=False):
"""
Calculates simulated ratios of match probabilites using a beta
distribution and returns corresponding means and 95% credible
intervals, posterior parameters, Bayes factor
Parameters
-... | 01e61719dbecb89e40bdf2688578d493c951591c | 3,643,323 |
def dump_yaml_and_check_difference(obj, filename, sort_keys=False):
"""Dump object to a yaml file, and check if the file content is different
from the original.
Args:
obj (any): The python object to be dumped.
filename (str): YAML filename to dump the object to.
sort_keys (str); Sor... | 47a271a34b0a1774188a725eddf0d6698f76e04c | 3,643,324 |
from re import T
from typing import Optional
def get_data(
db: Redis[bytes],
store: StorageEngine,
source: Artefact[T],
carry_error: Optional[hash_t] = None,
do_resolve_link: bool = True,
) -> Result[T]:
"""Retrieve data corresponding to an artefact."""
stream = get_stream(db, store, sourc... | 1bb07e01ae151f985fcd30e8cca0da1b11213459 | 3,643,325 |
def record_edit(request, pk):
"""拜访记录修改"""
user = request.session.get('user_id')
record = get_object_or_404(Record, pk=pk, user=user, is_valid=True)
if request.method == 'POST':
form = RecordForm(data=request.POST, instance=record)
if form.is_valid():
form.save()
... | d2d610e53641962e913849b4b643f38898b72a3f | 3,643,326 |
def remove_body_footer(raw):
"""
Remove a specific body footer starting with the delimiter : -=-=-=-=-=-=-=-=-=-=-=-
"""
body = raw[MELUSINE_COLS[0]]
return body.replace(r'-=-=-=-=.*?$', '') | 60161b06fe80fd526f66c796657bd9a77cc1bfb9 | 3,643,327 |
def get_strategy_name():
"""Return strategy module name."""
return 'store_type' | bbf1ed9f43f492561ee5c595061f74bea0f5e464 | 3,643,328 |
def pyccel_to_sympy(expr, symbol_map, used_names):
"""
Convert a pyccel expression to a sympy expression saving any pyccel objects
converted to sympy symbols in a dictionary to allow the reverse conversion
to be carried out later
Parameters
----------
expr : PyccelAstNode
... | 1800a41d1d06fbbfd212b3b7b48ddc9f4ae07508 | 3,643,329 |
from pathlib import Path
def get_lockfile_path(repo_name: str) -> Path:
"""Get a lockfile to lock a git repo."""
if not _lockfile_path.is_dir():
_lockfile_path.mkdir()
return _lockfile_path / f"{repo_name}_lock_file.lock" | 5f043b6976921d487054d5c9171c91eb6def19ee | 3,643,330 |
def path_to_graph(hypernym_list, initialnoun):
"""Make a hypernym chain into a graph.
:param hypernym_list: list of hypernyms for a word as obtained from wordnet
:type hypernym_list: [str]
:param initialnoun: the initial noun (we need this to mark it as leaf in the tree)
:type initialnoun: str
... | e80f90490e6376403d511f37a4703a7b867d2738 | 3,643,331 |
def make_3d_grid():
"""Generate a 3d grid of evenly spaced points"""
return np.mgrid[0:21, 0:21, 0:5] | 0eccd9b2320ed28f0d08d40c9d59c22e77b607f4 | 3,643,332 |
def rho(flag, F, K, t, r, sigma):
"""Returns the Black rho of an option.
:param flag: 'c' or 'p' for call or put.
:type flag: str
:param F: underlying futures price
:type F: float
:param K: strike price
:type K: float
:param t: time to expiration in years
:type t: float
:pa... | 62bd0fdfe76319261c89bfa33b02b57fcdafb8df | 3,643,333 |
async def novel_series(id: int, endpoint: PixivEndpoints = Depends(request_client)):
"""
## Name: `novel_series`
> 获取小说系列的信息
---
### Required:
- ***int*** **`id`**
- Description: 小说系列ID
"""
return await endpoint.novel_series(id=id) | 94859a313c823d3fdcf055390473b116ea1229e0 | 3,643,334 |
def to_raw(
y: np.ndarray,
low: np.ndarray,
high: np.ndarray,
eps: float = 1e-4
) -> np.ndarray:
"""Scale the input y in [-1, 1] to [low, high]"""
# Warn the user if the arguments are out of bounds, this shouldn't happend.""""
if not (np.all(y >= -np.ones_like(y) - eps) and np.all(y <= np.o... | 61e916f9f46582fc6b9c135ac53fff3a3939d710 | 3,643,335 |
def etched_lines(image):
"""
Filters the given image to a representation that is similar to a drawing being preprocessed with an Adaptive Gaussian
Threshold
"""
block_size = 61
c = 41
blur = 7
max_value = 255
# image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
img_blur = cv2.Gauss... | 33858c8ee50cd6977f81cc64f55967ecd8849369 | 3,643,336 |
def get_last_position(fit, warmup=False):
"""Parse last position from fit object
Parameters
----------
fit : StanFit4Model
warmup : bool
If True, returns the last warmup position, when warmup has been done.
Otherwise function returns the first sample position.
Returns
-----... | 28ec10c4f90ac786053334f593ffd3ade27b1fc5 | 3,643,337 |
def find_fast_route(objective, init, alpha=1, threshold=1e-3, max_iters=1e3):
"""
Optimizes FastRoute objective using Newton’s method optimizer to
find a fast route between the starting point and finish point.
Arguments:
objective : an initialized FastRoute object with preset start and finis... | ab0d8364a7aab80a735b2b468a45abb5e30b396b | 3,643,338 |
import os
import re
def get_version(filename="telepresence/__init__.py"):
"""Parse out version info"""
base_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(base_dir, filename)) as initfile:
for line in initfile.readlines():
match = re.match("__version__ *= *['\"... | 829c2aad31bffc820a204110306cbbe92feb017b | 3,643,339 |
import os
def find_child_files(path, searchRecursively=False, wildCardPattern="."):
"""在当前目录中查找文件,若选择searchRecursively则代表着搜索包含子目录, wildCardPattern意思是只搜索扩展名为".xxx"的文件,也可留空代表搜索全部文件. """
all_search_list = ['.','.*','*','']
tmp = list()
if not exists_as_dir(path):
return tmp
for fpath, _, fnam... | b6fda66cf95978f778844d7511317658b73d8193 | 3,643,340 |
def check_tx_success(result):
"""
Checks if function :meth:`UcanServer.write_can_msg_ex` successfully wrote all CAN message(s).
:param ReturnCode result: Error code of the function.
:return: True if CAN message(s) was(were) written successfully, otherwise False.
:rtype: bool
"""
return resu... | 815293aafa42b7323414e1cb96d6d150ef16bb48 | 3,643,341 |
from typing import Iterable
from typing import Optional
def cache_contains_keys(connection: 'Connection', cache_info: CacheInfo, keys: Iterable,
query_id: Optional[int] = None) -> 'APIResult':
"""
Returns a value indicating whether all given keys are present in cache.
:param conne... | 48fffa703d7cd120d0faa898e7e94355ec663a84 | 3,643,342 |
def discount_cumsum_trun(x, discount, length):
"""
compute discounted cumulative sums of vectors.
truncate x in length array
:param x:
vector x,
[x0,
x1,
x2,
x3,
x4]
:param length:
vector length,
[3,
2]
:return:
... | 589ac22b19705a7881f91cffe78bed5accafc661 | 3,643,343 |
def get_canonical(flop):
"""
Returns the canonical version of the given flop.
Canonical flops are sorted. The first suit is 'c' and, if applicable,
the second is 'd' and the third is 'h'.
Args:
flop (tuple): three pokertools.Card objects
Returns
A tuple of three pokertools.Car... | 4a797c27e8c32dff18412128d2823a1592c2468e | 3,643,344 |
import os
def normalize_path(path):
"""Normalize and return absolute path.
Expand user symbols like ~ and resolve relative paths.
"""
return os.path.abspath(os.path.expanduser(os.path.normpath(path))) | 108a820df621cca2238feadf8a45eef59e9aa883 | 3,643,345 |
import importlib
def _version(lib_name):
"""
Returns the version of a package.
If version cannot be determined returns "available"
"""
lib = importlib.import_module(lib_name)
if hasattr(lib, "__version__"):
return lib.__version__
else:
return "available" | cec49d2de66d2fc3a7ed3c89259711bdf40bbe8e | 3,643,346 |
def DeltaDeltaP(y, treatment, left_mask):
"""Absolute difference between ATEs of two groups."""
return np.abs(
ATE(y[left_mask], treatment[left_mask])
- ATE(y[~left_mask], treatment[~left_mask])
) | cd7816d2aa02cfb72dccf364cc73e07d596cc6ec | 3,643,347 |
def start(isdsAppliance, serverID='directoryserver', check_mode=False, force=False):
"""
Restart the specified appliance server
"""
if force is True or _check(isdsAppliance, serverID, action='start') is True:
if check_mode is True:
return isdsAppliance.create_return_object(changed=True... | b59941eafff24d9389f91edaa38de7b35eb48660 | 3,643,348 |
import sys
from aiida.common.exceptions import NotExistent
from aiida.orm import Code
from aiida.orm.querybuilder import QueryBuilder
def test_and_get_codenode(codenode, expected_code_type, use_exceptions=False):
"""
Pass a code node and an expected code (plugin) type. Check that the
code exists, is uniqu... | edebd5acb110058b147604c10ddb6bcdb035c714 | 3,643,349 |
from typing import Dict
from typing import Tuple
def reverse_crop(
im_arr: np.array, crop_details: dict
) -> Dict[str, Tuple[Image.Image, int]]:
"""Return the recovered image and the number of annotated pixels per
lat_view. If the lat_view annotation has no annotations, nothing is added
for that image... | 45e373ae8fd0100191796f29f536ab15481a64d4 | 3,643,350 |
def get_dates_keyboard(dates):
"""
Метод получения клавиатуры дат
"""
buttons = []
for date in dates:
button = InlineKeyboardButton(
text=date['entry_date'],
callback_data=date_callback.new(date_str=date['entry_date'], entry_date=date['entry_date'])
)
... | 41a87c64e603d6b19921c3a960743d3d27f2e373 | 3,643,351 |
import logging
import requests
def fetch_price(zone_key='FR', session=None, target_datetime=None,
logger=logging.getLogger(__name__)):
"""Requests the last known power price of a given country
Arguments:
----------
zone_key: used in case a parser is able to fetch multiple countries
... | fa056b8186451cd8d3ab07357faa69fe7a55ab82 | 3,643,352 |
import logging
from pathlib import Path
import os
import requests
import base64
import json
def cmd_asydns(url, generate, revoke, verbose):
"""Requests a DNS domain name based on public and private
RSA keys using the AsyDNS protocol https://github.com/portantier/asydns
Example:
\b
$ habu.asydns ... | b8513e29ea7e97478e6ca157e18e5cf816e9e85a | 3,643,353 |
import os
import pickle
def get_stats(method='histogram', save=True, train=True):
"""
Computes statistics, histogram, dumps the object to file and returns it
"""
if os.path.exists(FILE_STATS):
return pickle.load(open(os.path.join(FILE_STATS), "rb"))
elif train:
dataset = _get_data... | 71e3920ed177494ea03da00a4b3373ad30c8215a | 3,643,354 |
def merge_synset(wn, synsets, reason, lexfile, ssid=None, change_list=None):
"""Create a new synset merging all the facts from other synsets"""
pos = synsets[0].part_of_speech.value
if not ssid:
ssid = new_id(wn, pos, synsets[0].definitions[0].text)
ss = Synset(ssid, "in",
PartOf... | d1d7af2a83d6b7deb506fb69c7cbdb2770735f4f | 3,643,355 |
def __correlate_uniform(im, size, output):
"""
Uses repeated scipy.ndimage.filters.correlate1d() calls to compute a uniform filter. Unlike
scipy.ndimage.filters.uniform_filter() this just uses ones(size) instead of ones(size)/size.
"""
# TODO: smarter handling of in-place convolutions?
ndi = get... | 3571d0cb6dbfbca45f4453077cb3ad789464f919 | 3,643,356 |
def clean_all(record):
""" A really messy function to make sure that the citeproc data
are indeed in the citeproc format. Basically a long list of if/...
conditions to catch all errors I have noticed.
"""
record = clean_fields(record)
for arrayed in ['ISSN']:
if arrayed in record:
... | 28ba59e808e88058c5745c444f1e58cd564c726d | 3,643,357 |
def _create_model() -> Model:
"""Setup code: Load a program minimally"""
model = Model(initial_program, [], load=False)
engine = ApproximateEngine(model, 1, geometric_mean)
model.set_engine(engine)
return model | 71fa7c000e6ed0cd8ad14bb0be3bb617337e7631 | 3,643,358 |
def candidate_elimination(trainingset):
"""Computes the version space containig all hypothesis
from H that are consistent with the examples in the training set"""
G = set()#set of maximally general h in H
S = set()#set of maximally specific h in H
G.add(("?","?","?","?","?","?"))
S.add(("0","0",... | b368cea3b058cc667c41725b0fa6a6b4a51f418b | 3,643,359 |
from pathlib import Path
def mkdir(path_str):
"""
Method to create a new directory or directories recursively.
"""
return Path(path_str).mkdir(parents=True, exist_ok=True) | 1621fd5f4d74b739de0b17933c1804faabf44a2f | 3,643,360 |
def get_image_with_projected_bbox3d(img, proj_bbox3d_pts=[], width=0, color=Color.White):
"""
Draw the outline of a 3D bbox on the image.
Input:
proj_bbox3d_pts: (8,2) array of projected vertices
"""
v = proj_bbox3d_pts
if proj_bbox3d_pts != []:
draw = ImageDraw.Draw(img)
for k in range(0,4):
... | 2ec900c055635adbc6619f8e786e52bd820c6930 | 3,643,361 |
def process_spectrogram_params(fs, nfft, frequency_range, window_start, datawin_size):
""" Helper function to create frequency vector and window indices
Arguments:
fs (float): sampling frequency in Hz -- required
nfft (int): length of signal to calculate fft on -- required
... | 0e8563051a5ee4b48f7e635126ed4e6639e47bdd | 3,643,362 |
from typing import Union
def Hellwig2022_to_XYZ(
specification: CAM_Specification_Hellwig2022,
XYZ_w: ArrayLike,
L_A: FloatingOrArrayLike,
Y_b: FloatingOrArrayLike,
surround: Union[
InductionFactors_CIECAM02, InductionFactors_Hellwig2022
] = VIEWING_CONDITIONS_HELLWIG2022["Average"],
... | ef5f05f32f6871eaa67bb554a23595cedf2a97b1 | 3,643,363 |
def build_exec_file_name(graph: str,
strt: str,
nagts: int,
exec_id: int,
soc_name: str = None):
"""Builds the execution file name of id `exec_id` for the given patrolling
scenario `{graph, nagts, strt}` .
A... | 143731bee19ad8e4b925f07d5449baff83994059 | 3,643,364 |
def set_ticks(ax, tick_locs, tick_labels=None, axis='y'):
"""Sets ticks at standard numerical locations"""
if tick_labels is None:
tick_labels = tick_locs
ax_transformer = AxTransformer()
ax_transformer.fit(ax, axis=axis)
getattr(ax, f'set_{axis}ticks')(ax_transformer.transform(tick_locs))
... | 690179bcb2d2ca4f3b1e5b8cb03f68627168b73a | 3,643,365 |
from typing import List
import re
def extract_discovery(value:str) -> List[dict]:
"""处理show discovery/show onu discovered得到的信息
Args:
value (str): show discovery/show onu discovered命令返回的字符串
Returns:
List[dict]: 包含字典的列表
"""
# ================================================... | 6107d194d10e6b7c1c6e33f7151214152e5bff7d | 3,643,366 |
def dict_to_networkx(data):
"""
Convert data into networkx graph
Args:
data: data in dictionary type
Returns: networkx graph
"""
data_checker(data)
G = nx.Graph(data)
return G | 0a3c670d3bad87bb18212dc6d2e47ac5a1ccc413 | 3,643,367 |
import urllib
def to_url_slug(string):
"""Transforms string into URL-safe slug."""
slug = urllib.parse.quote_plus(string)
return slug | 0976e3d1568f793fa946be9fa67b40cc82e6f4f5 | 3,643,368 |
def is_wrapping(wrapper):
"""Determines if the given callable is a wrapper for another callable"""
return hasattr(wrapper, __WRAPPED) | 16dcff38253424f6b93cee2a887aa7d91afd4f44 | 3,643,369 |
from conekt.models.relationships.sequence_go import SequenceGOAssociation
from typing import Sequence
def sequence_view(sequence_id):
"""
Get a sequence based on the ID and show the details for this sequence
:param sequence_id: ID of the sequence
"""
current_sequence = Sequence.query.get_or_404(... | c9493376b8df2b9dc7585d8b380e54ce4d20f473 | 3,643,370 |
def horner(n,c,x0):
"""
Parameters
----------
n : integer
degree of the polynomial.
c : float
coefficients of the polynomial.
x0 : float
where we are evaluating the polynomial.
Returns
-------
y : float
the value of the function evaluated at x0.... | adf3f3772d12d5bed0158045ad480cee8454cb5c | 3,643,371 |
def linlin(x, smi, sma, dmi, dma):
"""TODO
Arguments:
x {float} -- [description]
smi {float} -- [description]
sma {float} -- [description]
dmi {float} -- [description]
dma {float} -- [description]
Returns:
float -- [description]
"""
return (x-smi)/(... | 10f375e961fa79b3b8bee5eb46f9f3af6663d893 | 3,643,372 |
import gzip
def _compression_safe_opener(fname):
"""Determine whether to use *open* or *gzip.open* to read
the input file, depending on whether or not the file is compressed.
"""
f = gzip.open(fname, "r")
try:
f.read(1)
opener = gzip.open
except IOError:
opener = open
... | 4c44da2ae15c63ccd6467e6e893a3c590c20a7e9 | 3,643,373 |
import sys
def gen_headers(value_type, value, header_type="PacketFilter", direction=None, notFilter=False):
"""
helper function constructs json header format
value: a STRING corresponding to value_type
direction: "src" or "dst"
Parameters
----------
value_type : string
a strin... | 292d34bc44d51685633d7772439fc90d5e92edaf | 3,643,374 |
from typing import List
import json
def read_payload(payload: str) -> OneOf[Issue, List[FileReport]]:
"""Transform an eslint payload to a list of `FileReport` instances.
Args:
payload: The raw payload from eslint.
Returns:
A `OneOf` containing an `Issue` or a list of `FileReport` instanc... | 809e4db54cb8d4c737d9eea7f77f1a1846f24589 | 3,643,375 |
def _ssim_per_channel(img1, img2, img3, max_val=1.0, mode='test',compensation=1):
"""Computes SSIM index between img1 and img2 per color channel.
This function matches the standard SSIM implementation from:
Wang, Z., Bovik, A. C., Sheikh, H. R., & Simoncelli, E. P. (2004). Image
quality assessment: from error ... | 04982dbac0d4d50e0ccaa20733b90ef56cd4084d | 3,643,376 |
from typing import Iterable
from typing import Any
from typing import Iterator
import itertools
def prepend(
iterable: Iterable[Any],
value: Any,
*,
times: int = 1,
) -> Iterator[Any]:
"""Return an iterator with a specified value prepended.
Arguments:
iterable: the ite... | 659bc3616238f5e40865505c006c1369f20e33d3 | 3,643,377 |
from skimage.transform import warp
def apply_transform(transform, source, target,
fill_value=None, propagate_mask=False):
"""Applies the transformation ``transform`` to ``source``.
The output image will have the same shape as ``target``.
Args:
transform: A scikit-image ``Simi... | 97843939a6e03389d8c4741a04cea77ac7e1e0c4 | 3,643,378 |
def _with_extension(base: str, extension: str) -> str:
"""
Adds an extension to a base name
"""
if "sus" in base:
return f"{extension}{base}"
else:
return f"{base}{extension}" | 5a1253763808127f296c3bcb04c07562346dea2d | 3,643,379 |
def putin_rfid_no_order_api():
"""
无订单的情况下入库, 自动创建订单(类型为生产入库), 订单行入库
post req: withlock
{
lines: [{line_id:~, qty, location, lpn='', sku,
rfid_list[rfid1, rfid2, rfid3...],
rfid_details[{rfid1, weight, gross_weight, qty_inner}, {rfid2}, {rfid3}...}],
}...]
... | 6637fba766e86bc25dae733d7ddc102114e79e27 | 3,643,380 |
def GuessLanguage(filename):
""" Attempts to Guess Langauge of `filename`. Essentially, we do a
filename.rsplit('.', 1), and a lookup into a dictionary of extensions."""
try:
(_, extension) = filename.rsplit('.', 1)
except ValueError:
raise ValueError("Could not guess language as '%s' does not have an \... | 3cd1289ab3140256dfbeb3718f30a3ac3ffca6f2 | 3,643,381 |
import numpy
def extract_data_size(series, *names):
"""
Determines series data size from the first available property, which
provides direct values as list, tuple or NumPy array.
Args:
series: perrot.Series
Series from which to extract data size.
names: (str,)... | 39d503b359318d9dc118481baa7f99a43b926711 | 3,643,382 |
def uintToQuint (v, length=2):
""" Turn any integer into a proquint with fixed length """
assert 0 <= v < 2**(length*16)
return '-'.join (reversed ([u16ToQuint ((v>>(x*16))&0xffff) for x in range (length)])) | 96f707ed527e1063d055ab1b6d1f8a17308ed772 | 3,643,383 |
import hashlib
import base64
def alphanumeric_hash(s: str, size=5):
"""Short alphanumeric string derived from hash of given string"""
hash_object = hashlib.md5(s.encode('ascii'))
s = base64.b32encode(hash_object.digest())
result = s[:size].decode('ascii').lower()
return result | 915159aa2242eedfe8dcba682ae4bcf4fdebc3c4 | 3,643,384 |
def fake_execute_default_reply_handler(*ignore_args, **ignore_kwargs):
"""A reply handler for commands that haven't been added to the reply list.
Returns empty strings for stdout and stderr.
"""
return '', '' | e73bd970030c4f78aebf2913b1540fc1b370d906 | 3,643,385 |
from typing import List
from pathlib import Path
def require(section: str = "install") -> List[str]:
""" Requirements txt parser. """
require_txt = Path(".").parent / "requirements.txt"
if not Path(require_txt).is_file():
return []
requires = defaultdict(list) # type: Dict[str, List[str]]
... | efda45491798e5b7b66e0f2d6a4ac7b9fc3324d0 | 3,643,386 |
import ast
def find_pkgutil_ns_hints(tree):
"""
Analyze an AST for hints that we're dealing with a Python module that defines a pkgutil-style namespace package.
:param tree:
The result of :func:`ast.parse()` when run on a Python module (which is
assumed to be an ``__init__.py`` file).
:... | c342bc4f663e52359b420491a8b21fa79cec201a | 3,643,387 |
def string_in_list_of_dicts(key, search_value, list_of_dicts):
"""
Returns True if search_value is list of dictionaries at specified key.
Case insensitive and without leading or trailing whitespaces.
:return: True if found, else False
"""
for item in list_of_dicts:
if equals(item[key], s... | a761e3b44efc6e584c8f9045be307837daad49c4 | 3,643,388 |
import itertools
import pandas
def get_data(station_id, elements=None, update=True, as_dataframe=False):
"""Retrieves data for a given station.
Parameters
----------
station_id : str
Station ID to retrieve data for.
elements : ``None``, str, or list of str
If specified, limits th... | 7eaa0d152a8f76fa7bfc4109fb4e0a5c3d90e318 | 3,643,389 |
def Find_Peaks(profile, scale, **kwargs):
"""
Pulls out the peaks from a radial profile
Inputs:
profile : dictionary, contains intensity profile and pixel scale of
diffraction pattern
calibration : dictionary, contains camera parameters to scale data
... | 3d5cf4a5d559d54aa061d4abd9a02efb96c03d05 | 3,643,390 |
def empty_items(item_list, total):
"""
Returns a list of null objects. Useful when you want to always show n
results and you have a list of < n.
"""
list_length = len(item_list)
expected_total = int(total)
if list_length != expected_total:
return range(0, expected_total-list_length)
... | 12848fe61457b2d138a2fcd074fb6ec6d09cbaf5 | 3,643,391 |
import struct
def _read_string(fp):
"""Read the next sigproc-format string in the file.
Parameters
----------
fp : file
file object to read from.
Returns
-------
str
read value from the file
"""
strlen = struct.unpack("I", fp.read(struct.calcsize("I")))[0]
ret... | 346a65e6be15f593c91dde34cb45c53cb5731877 | 3,643,392 |
def add_optional_parameters(detail_json, detail, rating, rating_n, popularity, current_popularity, time_spent, detailFromGoogle={}):
"""
check for optional return parameters and add them to the result json
:param detail_json:
:param detail:
:param rating:
:param rating_n:
:param popularity:
... | 176fab2255f9302c945cb29ac5f9513da368a57e | 3,643,393 |
def build_get_string_with_null_request(
**kwargs # type: Any
):
# type: (...) -> HttpRequest
"""Get string dictionary value {"0": "foo", "1": null, "2": "foo2"}.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
:return: Retur... | 976b20770b74b4cf8504f673e66aec94fbf55c2b | 3,643,394 |
def get_db_url(db_host, db_name, db_user, db_pass):
"""
Helper function for creating the "pyodbc" connection string.
@see /etc/freetds.conf
@see http://docs.sqlalchemy.org/en/latest/dialects/mssql.html
@see https://code.google.com/p/pyodbc/wiki/ConnectionStrings
"""
params = parse.quote(
... | f0ed18ac321fcc9e93b038dc2f3905af52191c7b | 3,643,395 |
import torch
def boxes_iou3d_cpu(boxes_a, boxes_b, box_mode='wlh', rect=False, need_bev=False):
"""
Input (torch):
boxes_a: (N, 7) [x, y, z, h, w, l, ry], torch tensor with type float32
boxes_b: (M, 7) [x, y, z, h, w, l, ry], torch tensor with type float32
rect: True/False means boxes ... | e3b40e2c4c35a7f423739791cc9268ecd22cdf42 | 3,643,396 |
def make_attrstring(attr):
"""Returns an attribute string in the form key="val" """
attrstring = ' '.join(['%s="%s"' % (k, v) for k, v in attr.items()])
return '%s%s' % (' ' if attrstring != '' else '', attrstring) | fbaf2b763b4b1f4399c45c3a19698d0602f0b224 | 3,643,397 |
from typing import Iterable
from typing import Callable
import random
def distribute(
computation_graph: ComputationGraph,
agentsdef: Iterable[AgentDef],
hints=None,
computation_memory: Callable[[ComputationNode], float] = None,
communication_load: Callable[[ComputationNode, str], float] = None,
)... | 21a0c240e7dab8240269d5bdeadd4fcef49c1a3c | 3,643,398 |
import requests
from bs4 import BeautifulSoup
from datetime import datetime
def depreciated_get_paste(paste_tup):
"""
This takes a tuple consisting of href from a paste link and a name that identify a pastebin paste.
It scrapes the page for the pastes content.
:param paste_tup: (string, string)
:... | 6f3620354827998eade57b989c503be4f093b6d8 | 3,643,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.