content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def detect_ascii_slice(lines):
# type: (List[str]) -> slice
"""
Given a list of strings, this will return the most likely positions of byte
positions. They are returned slice which should be able to extract the
columns from each line.
"""
for line in lines:
# if the content contains ... | 5,335,200 |
def inception_model_pytorch():
"""The InceptionBlocks model the WebGME folks provided as a test case for deepforge."""
class InceptionBlocks(nn.Module):
def __init__(self):
super().__init__()
self.asymmetric_pad = nn.ZeroPad2d((0, 1, 0, 1))
self.conv2d = nn.Conv2d(
... | 5,335,201 |
def check_api_errors(response):
"""
Check that we have enough api points to call to Spoonacular.
:param response: A response object
Raises exception if there are not enough points, otherwise does nothing.
"""
if int(response.headers["X-RateLimit-requests-Remaining"]) <= \
api_out_of... | 5,335,202 |
def get_trained_coefficients(X_train, y_train):
"""
Create and train a model based on the training_data_file data.
Return the model, and the list of coefficients for the 'X_columns' variables in the regression.
"""
# TODO: create regression model and train.
# The following codes are adapte... | 5,335,203 |
def register():
"""Handles the creation of a new user"""
form = dds_web.forms.RegistrationForm()
# Validate form - validators defined in form class
if form.validate_on_submit():
# Create new user row by loading form data into schema
try:
new_user = user_schemas.NewUserSchema... | 5,335,204 |
def project_in_2D(K, camera_pose, mesh, resolution_px):
"""
Project all 3D triangle vertices in the mesh into
the 2D image of given resolution
Parameters
----------
K: ndarray
Camera intrinsics matrix, 3x3
camera_pose: ndarray
Camera pose (inverse of extrinsics), 4x4
mes... | 5,335,205 |
def forbidden(description: Any) -> APIGatewayProxyResult:
"""Return a response with FORBIDDEN status code."""
error = ForbiddenError(description)
return _build_response(error, HTTPStatus.FORBIDDEN) | 5,335,206 |
def str_2_datetime(p_str, fmt="%Y-%m-%d %H:%M:%S"):
""" 将字符串转换成日期
:param p_str: 原始时间字符串
:param fmt: 时间格式
:rtype: datetime.datetime
"""
# don't need to transform
if isinstance(p_str, datetime.datetime):
return p_str
if not isinstance(p_str, str):
raise TypeError("params ... | 5,335,207 |
def traitement(l):
"""Permet de retirer les cartes blanches inutiles"""
while l[-1][1] == 'nan':
del l[-1]
return l | 5,335,208 |
def create_ivr_database(dbname):
"""Create sqlite database schema from sql script file."""
conn = sqlite3.connect(dbname)
cursor = conn.cursor()
parent_directory = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sql_script_path = os.path.join(parent_directory, 'db.sql')
sql_script_fi... | 5,335,209 |
def train(model, data_iterator, optimizer, scheduler, params):
"""Train the model on `steps` batches"""
# set model to training mode
model.train()
# scheduler.step()
# a running average object for loss
loss_avg = utils.RunningAverage()
# Use tqdm for progress bar
one_epoch = trange... | 5,335,210 |
def save_audio(text: str, filename: str, dir: str):
"""
Converts text to audio and saves
Notes
-----
If the .mp3 file extension is missing in the filename, it will be added
If a file with the same name exists, it will not save, only notify the user
Returns
_______
Path : str
""... | 5,335,211 |
def build_report(test_controller):
"""Report on the test results."""
options = test_controller.options
citest_log_dir = os.path.join(options.log_dir, 'citest_logs')
if not os.path.exists(citest_log_dir):
logging.warning('%s does not exist -- no citest logs.', citest_log_dir)
return
response = run_qui... | 5,335,212 |
def group_frames_by_track_date(frames):
"""Classify frames by track and date."""
hits = {}
grouped = {}
dates = {}
footprints = {}
metadata = {}
for h in frames:
if h['_id'] in hits: continue
fields = h['fields']['partial'][0]
#print("h['_id'] : %s" %h['_id'])
... | 5,335,213 |
def generate_violin_figure(dataframe, columns, ytitle, legend_title=None):
""" Plot 2 columns of data as violin plot, grouped by block.
:param dataframe: Variance of projections.
:type dataframe: pandas.DataFrame
:param columns: 2 columns for the negative and the positive side of the violins.
:type... | 5,335,214 |
def measure_single(state, bit):
"""
Method one qubit one time
:param state:
:param bit:
:return:
"""
n = len(state.shape)
axis = list(range(n))
axis.remove(n - 1 - bit)
probs = np.sum(np.abs(state) ** 2, axis=tuple(axis))
rnd = np.random.rand()
# measure single bit
i... | 5,335,215 |
def anchor_to_offset(anchors, ground_truth):
"""Encodes the anchor regression predictions with the
ground truth.
Args:
anchors: A numpy array of shape (N, 6) representing
the generated anchors.
ground_truth: A numpy array of shape (6,) containing
the label boxes in t... | 5,335,216 |
def horizontal_flip(img_array):
"""Flip image horizontally."""
img_array = cv2.flip(img_array, 1)
return img_array | 5,335,217 |
async def repeat(interval, func, *args, **kwargs):
"""Run func every interval seconds.
source: https://stackoverflow.com/a/55505152/13989012
If func has not finished before *interval*, will run again
immediately when the previous iteration finished.
*args and **kwargs are passed as the arguments t... | 5,335,218 |
def chunker(file_path):
"""
Read a block of lines from a file
:param file_path:
:return:
"""
words = []
with open(file_path, 'r') as file_object:
for word in file_object:
word = word.strip()
if word:
words.append(word)
return words | 5,335,219 |
def c2c_dist(commande,octree_lvl=0):
"""
Commande CC cloud2cloud distance
"""
if octree_lvl==0:
commande+=" -C2C_DIST -split_xyz -save_clouds"
else:
commande+=" -C2C_DIST -split_xyz -octree_level "+str(octree_lvl)+" -save_clouds"
subprocess.call(commande)
return True | 5,335,220 |
def main(argv=None):
"""script main.
parses command line options in sys.argv, unless *argv* is given.
"""
if not argv:
argv = sys.argv
# setup command line parser
parser = E.ArgumentParser(description=__doc__)
parser.add_argument("--version", action='version', version="1.0")
... | 5,335,221 |
def legalize_names(varnames):
"""returns a dictionary for conversion of variable names to legal
parameter names.
"""
var_map = {}
for var in varnames:
new_name = var.replace("_", "__").replace("$", "_").replace(".", "_")
assert new_name not in var_map
var_map[var] = new_name
... | 5,335,222 |
def _IsUidUsed(uid):
"""Check if there is any process in the system running with the given user-id
@type uid: integer
@param uid: the user-id to be checked.
"""
pgrep_command = [constants.PGREP, "-u", uid]
result = utils.RunCmd(pgrep_command)
if result.exit_code == 0:
return True
elif result.exit... | 5,335,223 |
def _pyint_to_mpz(n, a):
"""
Set `a` from `n`.
:type n: int,long
:type a: mpz_t
"""
if -sys.maxsize - 1 <= n <= sys.maxsize:
gmp.mpz_set_si(a, n)
elif sys.maxsize < n <= MAX_UI:
gmp.mpz_set_ui(a, n)
else:
gmp.mpz_set_str(a, hex(n).rstrip('L').encode('UTF-8'), 0) | 5,335,224 |
def clean_migrations(c):
"""Removes all migration jobs
Usage: inv pod.clean-migrations
"""
c.run(
f"kubectl delete pods -n {c.config.namespace} -ljob-name=migrate"
) | 5,335,225 |
def main_L8CCA():
""" Demo L8CCA data loading. """
base_path = Path(
"datasets/clouds/"
+ "Landsat-Cloud-Cover-Assessment-Validation-Data-Partial"
)
img_paths = [base_path / "Barren" / "LC81390292014135LGN00",
base_path / "Forest" / "LC80160502014041LGN00"]
spli... | 5,335,226 |
def mobilenetv3_large(data_channel):
"""
Constructs a MobileNetV3-Large model
"""
cfgs = [
# k, t, c, SE, NL, s
[3, 16, 16, 0, 0, 1],
[3, 64, 24, 0, 0, 2],
[3, 72, 24, 0, 0, 1],
[5, 72, 40, 1, 0, 2],
[5, 120, 40, 1, 0, 1],
[5, 120, 40, 1, 0, 1]... | 5,335,227 |
def ravel_lom_dims(tensor, name='ravel_lom_dims'):
"""Assumes LOM is in the last 3 dims."""
return tf.reshape(tensor, tensor.shape_as_list()[:-3] + [-1], name=name) | 5,335,228 |
def run_cv(cfg, df, horiz, freq, cv_start, cv_stride=1, dc_dict=None,
metric="smape"):
"""Run a sliding-window temporal cross-validation (aka backtest) using a
given forecasting function (`func`).
"""
y = df["demand"].values
# allow only 1D time-series arrays
assert(y.ndim == 1)
... | 5,335,229 |
def ST_Area(geos):
"""
Calculate the 2D Cartesian (planar) area of geometry.
:type geos: Series(dtype: object)
:param geos: Geometries in WKB form.
:rtype: Series(dtype: float64)
:return: The value that represents the area of geometry.
:example:
>>> import pandas
>>> import ar... | 5,335,230 |
def check_conda_packages(edit_mode=False, packages=None):
"""Check conda inslalled packages information filtering for packages.
It is Python/Conda environment dependent.
Returns:
dict(str): Dictionary filled with respective information.
"""
info = {'CONDA PACKAGES': {}}
all_packages =... | 5,335,231 |
def prove(domain, account):
"""Create domain based self-verification proof"""
if not domain:
domain = click.prompt("Domain to prove (example: https://example.com/)")
w3 = w3_client()
address = w3.eth.accounts[account]
proof = create_proof(domain, address)
if click.confirm(f"Save {domain... | 5,335,232 |
async def test_get_bluetooth(aresponses: ResponsesMockServer) -> None:
"""Test getting bluetooth information."""
aresponses.add(
"127.0.0.2:4343",
"/api/v2/device/bluetooth",
"GET",
aresponses.Response(
status=200,
headers={"Content-Type": "application/jso... | 5,335,233 |
def P_from_K_R_t(K, R, t):
"""Returns the 3x4 projection matrix P = K [R | t]."""
K = K.astype(np.float64)
R = R.astype(np.float64)
t = t.astype(np.float64)
return matmul(K, np.column_stack((R, t))) | 5,335,234 |
def multi_value_precondition(parameter_selector: List[Union[int, str]], predicate: Callable[..., bool],
exception_factory: Union[Type[BaseException], Callable[[OrderedDict], BaseException]]
=PreconditionViolatedError) -> Any:
"""
This is a factory that w... | 5,335,235 |
def activity_list_retrieve_view(request): # activityListRetrieve
"""
Retrieve activity so we can populate the news page
:param request:
:return:
"""
status = ''
activity_list = []
activity_manager = ActivityManager()
activity_notice_seed_list = []
activity_post_list = []
vot... | 5,335,236 |
def arg_parser() -> argparse.Namespace:
""" Reads command line arguments.
:returns: Values of accepted command line arguments.
"""
_parser = argparse.ArgumentParser(
description=dedent(
"""Find all recipes in a directory,
build them and push all their images to an sregis... | 5,335,237 |
def create(
issue: str,
mine: bool,
assignee: str,
body: str,
type: str,
label: str,
parent: str,
web: bool,
story_points: str,
) -> None:
"""
Create an issue.
ISSUE is the title to be used for the new work item.
"""
work_item_id = cmd_create_issue(
title... | 5,335,238 |
def edit_action(
request: http.HttpRequest,
pk: int,
workflow: Optional[models.Workflow] = None,
action: Optional[models.Action] = None,
) -> http.HttpResponse:
"""Invoke the specific edit view.
:param request: Request object
:param pk: Action PK
:param workflow: Workflow being processe... | 5,335,239 |
def to_set(data: Any) -> Set[Any]:
"""Convert data to a set. A single None value will be converted to the empty set.
```python
x = fe.util.to_set(None) # set()
x = fe.util.to_set([None]) # {None}
x = fe.util.to_set(7) # {7}
x = fe.util.to_set([7, 8]) # {7,8}
x = fe.util.to_set({7}) # {... | 5,335,240 |
def Pei92(wavelength, Av, z, Rv=-99.0, ext_law="smc", Xcut=False):
"""
Extinction laws from Pei 1992 article
Parameters
----------
wavelength: `array` or `float`
wavlength in angstroms
Av: `float`
amount of extinction in the V band
z: `float`
redshift
Rv: `flo... | 5,335,241 |
def is_empty(context: KedroContext, branch: str = "") -> None:
"""Empty pipelines should not swap filepaths on init.
filepaths are only swapped after_catalog_created if they exist
"""
assert context.branch == branch
for dataset in context.catalog.list():
try:
d = getattr(contex... | 5,335,242 |
def plot_profile_avg_with_bounds(
data,
ax=None,
confint_alpha=0.05,
label=None,
xs=None,
axis=0,
bounds: str = "ci",
**kwargs,
):
"""
TODO: Documentation
Parameters
----------
data
ax
confint_alpha
label
kwargs
Returns
-------
"""
... | 5,335,243 |
def get_mimetype(path):
"""
Get (guess) the mimetype of a file.
"""
mimetype, _ = mimetypes.guess_type(path)
return mimetype | 5,335,244 |
async def read_clients_epics(
client_id: int = None, session: Session = Depends(get_session)
):
"""Get epics from a client_id"""
statement = (
select(Client.id, Client.name, Epic.name)
.select_from(Client)
.join(Epic)
.where(Client.id == client_id)
)
results = session... | 5,335,245 |
def id_number_checksum(gd):
"""
Calculates a Swedish ID number checksum, using the Luhn algorithm
"""
n = s = 0
for c in (gd['year'] + gd['month'] + gd['day'] + gd['serial']):
# Letter? It's an interimspersonnummer and we substitute the letter
# with 1.
if c.isalpha():
... | 5,335,246 |
def date_loss_l1(pred,
target_min,
target_max,
mask):
"""L1 loss function for dates."""
pred = jnp.squeeze(pred, 0)
loss = 0.
loss += jnp.abs(pred - target_min) * jnp.less(pred, target_min).astype(
pred.dtype)
loss += jnp.abs(pred - target_max) * jnp.g... | 5,335,247 |
def new_single_genres(genres, val):
"""Takes the genres list and returns only one genre back if multiple genres are present
Also has the parameter val with values "high" and "low"
High picks the genres belonging to the existing genres with the highest examples count
Low picks the genres belonging to the... | 5,335,248 |
def run(funcs_to_test=None, tests_to_run=None, verbosity=2):
"""
run testing routine
args:
- funcs_to_test: dict: {lang_name <str>: lang_func <callable>}
of language processing modules to test
if None `corpus.functions`... | 5,335,249 |
def roparameter(cosphi, hist, s_cosphi=0.25):
"""
...
Parameters
----------
cosphi : ...
hist : ...
s_cosphi : ...
Returns
-------
...
"""
perp=(np.abs(cosphi)>1.-... | 5,335,250 |
def check_gc_referrers(typename: Any, w_obj: Callable, name: str) -> None:
"""
Check if any variable is getting out of control.
Great for checking and tracing memory leaks.
"""
import threading
import time
def checkfn() -> None:
import gc
time.sleep(2)
gc.collect()... | 5,335,251 |
def execute(model_fn, input_fn, **params):
"""Execute train or eval and/or inference graph writing.
Args:
model_fn: An estimator compatible function taking parameters
(features, labels, mode, params) that returns a EstimatorSpec.
input_fn: An estimator compatible function taking 'params' that... | 5,335,252 |
def polyfill_bbox(
min_lng, max_lng, min_lat, max_lat, min_resolution=0, max_resolution=30
):
"""Polyfill a planar bounding box with compact s2 cells between resolution levels"""
check_valid_polyfill_resolution(min_resolution, max_resolution)
rc = s2sphere.RegionCoverer()
rc.min_level = min_resolu... | 5,335,253 |
def whisper(caller, recipients, message):
"""Display a message with a specific format."""
if 'mute' in caller.character.flags:
commands.pemit(caller, caller, "\c(red)!!! Unable to speak, you are muted.")
return
# If you are flagged 'dark' (invisible), everyone hears you as a disemb... | 5,335,254 |
def qa_skysub(param, frame, skymodel, quick_look=False):
"""Calculate QA on SkySubtraction
Note: Pixels rejected in generating the SkyModel (as above), are
not rejected in the stats calculated here. Would need to carry
along current_ivar to do so.
Args:
param : dict of QA parameters : see... | 5,335,255 |
def _code_to_symbol(code):
"""
生成symbol代码标志
"""
if code in ct.INDEX_LABELS:
return ct.INDEX_LIST[code]
else:
if len(code) != 6 :
return ''
else:
return 'sh%s'%code if code[:1] in ['5', '6', '9'] else 'sz%s'%code | 5,335,256 |
def guaranteeFolderExists(path_name):
""" Make sure the given path exists after this call """
path = Path(path_name).absolute()
path.mkdir(parents=True, exist_ok=True) | 5,335,257 |
def classic_rk(solution, deck, dgsolver, limiter, coeffs, alphas, betas):
"""Integrate in time using the classic RK4 scheme"""
# Initialize storage variables
K = [np.zeros(solution.u.shape) for _ in range(len(coeffs))]
us = solution.copy()
uk = solution.copy()
# Output time array (ignore the s... | 5,335,258 |
def gesv(a, b):
"""Solve a linear matrix equation using cusolverDn<t>getr[fs]().
Computes the solution to a system of linear equation ``ax = b``.
Args:
a (cupy.ndarray): The matrix with dimension ``(M, M)``.
b (cupy.ndarray): The matrix with dimension ``(M)`` or ``(M, K)``.
Returns:
... | 5,335,259 |
def del_none(d):
"""
Delete dict keys with None values, and empty lists, recursively.
"""
for key, value in d.items():
if value is None or (isinstance(value, list) and len(value) == 0):
del d[key]
elif isinstance(value, dict):
del_none(value)
return d | 5,335,260 |
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... | 5,335,261 |
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 | 5,335,262 |
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... | 5,335,263 |
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:
... | 5,335,264 |
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 | 5,335,265 |
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... | 5,335,266 |
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..."
)
dir_path =... | 5,335,267 |
def check_operating_system_supported() -> None:
""" Exists code if operating system is not supported. """
for platform in PLATFORMS_SUPPORTED:
# Iterating over all platforms in the supported platforms.
if sys.platform.startswith(platform):
# If current PC is have this platform (Sup... | 5,335,268 |
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... | 5,335,269 |
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 *... | 5,335,270 |
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. If so, this windo... | 5,335,271 |
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... | 5,335,272 |
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... | 5,335,273 |
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_... | 5,335,274 |
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) | 5,335,275 |
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backend_Mp.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's instal... | 5,335,276 |
def command_stop_submission_over_quota(syn, args):
"""
Sets an annotation on Synapse Docker submissions such that it will
be terminated by the orchestrator. Usually applies to submissions
that have been running for longer than the alloted time.
>>> challengeutils stop-submission-over-quota submissi... | 5,335,277 |
def parse(s):
"""Parse a single string. This is just a convenience function."""
return pogo(parseSingleExpression(tokenize(s),
identity_cont)) | 5,335,278 |
def set_default_rio_config(aws=None, cloud_defaults=False, **kwargs):
""" Setup default configuration for rasterio/GDAL.
Doesn't actually activate one, just stores configuration for future
use from IO threads.
:param aws: Dictionary of options for rasterio.session.AWSSession
OR 'auto' ... | 5,335,279 |
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 | 5,335,280 |
def update_safety_check(first_dict, second_dict, compat=operator.eq):
"""Check the safety of updating one dictionary with another.
Raises ValueError if dictionaries have non-compatible values for any key,
where compatibility is determined by identity (they are the same item) or
the `compat` function.
... | 5,335,281 |
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... | 5,335,282 |
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... | 5,335,283 |
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
elif not isinstan... | 5,335,284 |
def HLRBRep_SurfaceTool_Torus(*args):
"""
:param S:
:type S: Standard_Address
:rtype: gp_Torus
"""
return _HLRBRep.HLRBRep_SurfaceTool_Torus(*args) | 5,335,285 |
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... | 5,335,286 |
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... | 5,335,287 |
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))) | 5,335,288 |
def arrange_and_plot(wholedict, ptitle):
"""
Organize and plot data.
Parameters
----------
wholedict : OrderedDict
dictionary of information to be plotted, ordered by input file
required keys are 'ftitle' 'titleMols' 'rmsds'
ptitle : string
Title on plot
"""
# f... | 5,335,289 |
def addMySymbol(command, sortedSymbols, mySymbols):
""" addMySymbol handles add symbol command. """
expression = command.strip().lower()
words = expression.split()
if (words[1].isdigit() and (int(words[1]) <= (len(sortedSymbols) - 1))):
symbol = sortedSymbols[int(words[1]) - 1].upper()
m... | 5,335,290 |
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
-... | 5,335,291 |
def force_remove(*paths):
"""Remove files without printing errors. Like ``rm -f``, does NOT
remove directories."""
for path in paths:
try:
os.remove(path)
except OSError:
pass | 5,335,292 |
def write_mm_atom_properties_txt(cgmodel,list_of_atoms_to_add):
"""
Given a cgmodel and a 'list_of_atoms_to_add', this function adds the atoms to 'mm_atom_properties.txt'.
Parameters
----------
cgmodel: CGModel() class object
list_of_atoms_to_add: List of atom types to... | 5,335,293 |
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... | 5,335,294 |
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, source.hash, carry_error, do_resolve_link)
if is... | 5,335,295 |
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()
... | 5,335,296 |
def remove_body_footer(raw):
"""
Remove a specific body footer starting with the delimiter : -=-=-=-=-=-=-=-=-=-=-=-
"""
body = raw[MELUSINE_COLS[0]]
return body.replace(r'-=-=-=-=.*?$', '') | 5,335,297 |
def get_strategy_name():
"""Return strategy module name."""
return 'store_type' | 5,335,298 |
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
... | 5,335,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.