content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def insert_singletons(words, singletons, p=0.5):
"""
Replace singletons by the unknown word with a probability p.
"""
new_words = []
for word in words:
if word in singletons and np.random.uniform() < p:
new_words.append(0)
else:
new_words.append(word)
retu... | 24,500 |
def test_bake_with_apostrophe_and_run_tests(cookies):
"""Ensure that a `full_name` with apostrophes does not break setup.py"""
with bake_in_temp_dir(
cookies,
extra_context={'full_name': "O'connor"}
) as result:
assert result.project.isdir()
run_inside_dir('python setu... | 24,501 |
def talk(text, is_yelling=False, trim=False, verbose=True):
"""
Prints text
is_yelling capitalizes text
trim - trims whitespace from both ends
verbose - if you want to print something on screen
returns transformed text
"""
if trim:
text = text.strip()
if is_yelling:
t... | 24,502 |
def getNorthPoleAngle(target, position, C, B, camera):
"""
Get angle north pole of target makes with image y-axis, in radians.
"""
# get target spin axis
# the last row of the matrix is the north pole vector, *per spice docs*
# seems correct, as it's nearly 0,0,1
Bz = B[2]
print 'Bz=nor... | 24,503 |
def cgr(bundle,
source_node,
contact_graph,
route_list,
contact_list,
current_time,
limbo,
hot_spots=None):
"""Core routing function of SCGR implementation.
Enqueues a bundle (packet) into a contact queue base on CGR.
Args:
bundle (Packet): ... | 24,504 |
def test_work_order_with_no_indata(setup_config):
""" Testing work order request with no indata """
# input file name
request = 'work_order_tests/input/work_order_with_no_indata.json'
work_order_response, generic_params = (work_order_request_params
(setup_con... | 24,505 |
def ray_casting(polygon, ray_line):
""" checks number of intersection a ray makes with polygon
parameters: Polygon, ray (line)
output: number of intersection
"""
vertex_num = polygon.get_count()
ray_casting_result = [False] * vertex_num
''' count for vertices that is colinear and in... | 24,506 |
def main_install(args, config=None):
"""
Main function for the 'install' command.
"""
if not config:
# Load configuration file
config = autokernel.config.load_config(args.autokernel_config)
# Use correct umask when installing
saved_umask = os.umask(config.install.umask.value)
... | 24,507 |
def kmeans_clustering_missing(reduced_components, output_path,
n_clusters=2, max_iter=10):
"""
Performs a K-means clustering with missing data.
:param reduced_components: reduced components matrix
:type reduced_components: np.ndarray
:param output_path: path to output ... | 24,508 |
def test_macc_chardis():
"""tests that the macc_chardis function gives the
right output depending on the string in the Md column
in a dataframe."""
test_df = pd.DataFrame({'ColX': [0, 1, 2],
'Md': ['D', 'C', 'Something else']})
test_row1 = test_df.iloc[0]
test_row2 ... | 24,509 |
def ErrorWrapper(err, resource_name):
"""Wraps http errors to handle resources names with more than 4 '/'s.
Args:
err: An apitools.base.py.exceptions.HttpError.
resource_name: The requested resource name.
Returns:
A googlecloudsdk.api_lib.util.exceptions.HttpException.
"""
exc = exceptions.HttpE... | 24,510 |
def contexts_list_cli(configuration: Configuration, ctx: click.Context) -> None:
"""Print all available contexts."""
if len(configuration.contexts_repository) == 0:
click.echo("No contexts were found.")
ctx.exit(1)
for context in configuration.contexts_repository:
click.echo(f"{name_... | 24,511 |
def test_species_no_spc_nmsc():
"""If there is no scientific name, the string representation of a
species object is just the common name.
"""
attrs = {"spc_nmco": "Salvelinus Sp.", "spc": "086", "tagged": True}
species = Species(
spc_nmco=attrs.get("spc_nmco"),
spc_nmsc=attrs.get("s... | 24,512 |
def get_str_cmd(cmd_lst):
"""Returns a string with the command to execute"""
params = []
for param in cmd_lst:
if len(param) > 12:
params.append('"{p}"'.format(p=param))
else:
params.append(param)
return ' '.join(params) | 24,513 |
def guarded_call(name, function, message=None):
"""
Run a function once by creating a guard file on first run
"""
GUARD_DIRECTORY.mkdir(parents=True, exist_ok=True)
guard_file = GUARD_DIRECTORY / name
if not guard_file.exists():
if message is None:
print("Running {}".format(... | 24,514 |
def calculate_score(arr):
"""Inside calculate_score() check for a blackjack (a hand with only 2 cards: ace + 10) and return 0 instead of the actual score. 0 will represent a blackjack in our game.
It check for an 11 (ace). If the score is already over 21, remove the 11 and replace it with a 1"""
... | 24,515 |
def tt_true(alpha):
"""Is the propositional sentence alpha a tautology? (alpha will be
coerced to an expr.)
>>> tt_true(expr("(P >> Q) <=> (~P | Q)"))
True
"""
return tt_entails(TRUE, expr(alpha)) | 24,516 |
def test_stix_semantics_timestamp_coconstraint(
generator_stix_semantics, num_trials, gen_op, python_op
):
"""
Test value co-constraint satisfaction in the object generator.
"""
for _ in range(num_trials):
value = generator_stix_semantics.generate_from_spec({
"type": "object",
... | 24,517 |
def contrast_jwst_ana_num(matdir, matrix_mode="analytical", rms=1. * u.nm, im_pastis=False, plotting=False):
"""
Calculate the contrast for an RMS WFE with image PASTIS, matrix PASTIS
:param matdir: data directory to use for matrix and calibration coefficients from
:param matrix_mode: use 'analytical or... | 24,518 |
def show_config_data_by_section(data:configparser.ConfigParser, section:str):
"""Print a section's data by section name
Args:
data (configparser.ConfigParser): Data
section (str): Section name
"""
if not _check_data_section_ok(data, section):
return None
val = data[section]... | 24,519 |
def psk_key_get(identity, hint):
"""return PSK string (in hex format without heading 0x) if given identity
and hint pair is allowed to connect else return False or None
""" | 24,520 |
def train_save_tfidf(filein, target):
"""input is a bow corpus saved as a tfidf file. The output is
a saved tfidf corpus"""
try:
corpus = corpora.MmCorpus(filein)
except:
raise NameError('HRMMPH. The file does not seem to exist. Create a file'+
'first by runni... | 24,521 |
def ScrewTrajectoryList(Xstart, Xend, Tf, N, method, gripper_state, traj_list):
""" Modified from the modern_robotics library ScrewTrajectory
Computes a trajectory as a list of SE(3) matrices with a gripper value and
converts into a list of lists
Args:
Xstart : The initial end-effector con... | 24,522 |
def calculate_phase(time, period):
"""Calculates phase based on period.
Parameters
----------
time : type
Description of parameter `time`.
period : type
Description of parameter `period`.
Returns
-------
list
Orbital phase of the object orbiting the star.
"... | 24,523 |
def content_disposition(disposition, filename):
"""
Generates a content disposition hedaer given a
*disposition* and a *filename*. The filename needs
to be the base name of the path, i.e. instead of
``~/file.txt`` you need to pass in ``file.txt``.
The filename is automatically quoted.
"""
... | 24,524 |
def get_sbappname(filepath):
""" Given a file path, find an acceptable name on the BL filesystem """
filename = os.path.split(filepath)[1]
filename = filename.split('.')[0]
return re.sub(r'[:*?"<>|]', "", filename)[:24] | 24,525 |
def perspective_transform(img):
"""
Do a perspective transform over an image.
Points are hardcoded and depend on the camera and it's positioning
:param img:
:return:
"""
pts1 = np.float32([[250, 686], [1040, 680], [740, 490], [523, 492]])
pts2 = np.float32([[295, 724], [980, 724], [988, ... | 24,526 |
def main(output_filepath):
""" Runs data processing scripts to turn raw data from (../raw) into
cleaned data ready to be analyzed (saved in ../processed).
"""
logger = logging.getLogger(__name__)
logger.info('making final data set from raw data')
baseurl = 'http://codeandbeer.org/virtual/Bi... | 24,527 |
def login():
"""Log user in"""
# Forget any user_id
session.clear()
# User reached route via POST (as by submitting a form via POST)
if request.method == "POST":
# Ensure username was submitted
if not request.form.get("username"):
return apology("must provide username"... | 24,528 |
def setup(rank: int, world_size: int, dist_url: str):
"""Setting-up method to be called in the distributed function
Borrowed from https://pytorch.org/tutorials/intermediate/ddp_tutorial.html
Parameters
----------
rank : int
process int
world_size : int
number of porocesses (of... | 24,529 |
def value_iteration(P, nS, nA, gamma=0.9, tol=1e-3):
"""
Learn value function and policy by using value iteration method for a given
gamma and environment.
Parameters:
----------
P, nS, nA, gamma:
defined at beginning of file
tol: float
Terminate value iteration when
max |value(s) - prev_value(s)| < tol
... | 24,530 |
def get_clients():
"""
Determine if the current user has a connected client.
"""
return jsonify(g.user.user_id in clients) | 24,531 |
def get_split_indices(word, curr_tokens, include_joiner_token, joiner):
"""Gets indices for valid substrings of word, for iterations > 0.
For iterations > 0, rather than considering every possible substring, we only
want to consider starting points corresponding to the start of wordpieces in
the curren... | 24,532 |
def main():
"""Main function to list, read and submit images recording the time spent
"""
images = os.listdir(path=IMAGE_PATH)
time_inference = []
for image_name in images:
with open(os.path.join(IMAGE_PATH, image_name), "rb") as image_file:
encoded_string = base64.b64encode(imag... | 24,533 |
def perspective(
vlist: list[list[Number,
Number,
Number]],
rotvec: list[list[float, float],
list[float, float],
list[float, float]],
dispvec: list[Number,
Number,
... | 24,534 |
def test_gcp_iam_project_role_permission_remove_command_exception(client):
"""
Remove permissions from custom project role.
Given:
- User has provided valid credentials.
When:
- gcp-iam-project-role-permission-remove called.
- User has provided invalid command arguments.
Then:
- ... | 24,535 |
def unroll_func_obs(obs):
"""Returns flattened list of FunctionalObservable instances
It inspect recursively the observable content of the argument to yield
all nested FunctionalObservable instances. They are ordered from lower to
deeper layers in nested-ness. If you need to compute f(g(h(x))), where
... | 24,536 |
def _check_shebang(filename, disallow_executable):
"""Return 0 if the filename's executable bit is consistent with the
presence of a shebang line and the shebang line is in the whitelist of
acceptable shebang lines, and 1 otherwise.
If the string "# noqa: shebang" is present in the file, then this chec... | 24,537 |
def test_inspector_adult_easy_py_pipeline_without_inspections():
"""
Tests whether the .py version of the inspector works
"""
inspector_result = PipelineInspector\
.on_pipeline_from_py_file(ADULT_SIMPLE_PY)\
.execute()
extracted_dag = inspector_result.dag
expected_dag = get_expec... | 24,538 |
def actor_is_contact(api_user, nick, potential_contact):
"""Determine if one is a contact.
PARAMETERS:
potential_contact - stalkee.
RETURNS: boolean
"""
nick = clean.user(nick)
potential_contact = clean.user(potential_contact)
key_name = Relation.key_from(relation='contact',
... | 24,539 |
def compute_mem(w, n_ring=1, spectrum='nonzero', tol=1e-10):
"""Compute Moran eigenvectors map.
Parameters
----------
w : BSPolyData, ndarray or sparse matrix, shape = (n_vertices, n_vertices)
Spatial weight matrix or surface. If surface, the weight matrix is
built based on the inverse ... | 24,540 |
def printAb(A, b):
""" printout the matrix A and vector b in a pretty fashion. We
don't use the numpy print here, because we want to make them
side by side"""
N = len(b)
openT = "/"
closeT = "\\"
openB = "\\"
closeB = "/"
# numbers take 6 positions + 2 spaces
aFmt = ... | 24,541 |
def cli(ctx, search):
"""Output quotes."""
ctx.obj = Context(search)
result = ctx.obj.quote.random(search=search)
click.echo(result) | 24,542 |
def gbsShowLayer(mapLayer):
""" Show layer by map object name
"""
if not mapLayer or mapLayer.getLayer() is None:
return
layerId = mapLayer.getLayer().id()
iface.mapLegend.showLayer(layerId) | 24,543 |
def test_correct_digit_required(min_v, dummy_form, dummy_field):
"""
It should pass for the string with correct count of required digit.
"""
dummy_field.data = "asdqwe872536"
validator = digit_required(min_v)
validator(dummy_form, dummy_field) | 24,544 |
def eval_BenchmarkModel(x, a, y, model, loss):
"""
Given a dataset (x, a, y) along with predictions,
loss function name
evaluate the following:
- average loss on the dataset
- DP disp
"""
pred = model(x) # apply model to get predictions
n = len(y)
if loss == "square":
er... | 24,545 |
def parse_sgf_game(s):
"""Read a single SGF game from a string, returning the parse tree.
s -- 8-bit string
Returns a Coarse_game_tree.
Applies the rules for FF[4].
Raises ValueError if can't parse the string.
If a property appears more than once in a node (which is not permitted... | 24,546 |
def mesh_checker(mesh,Dict):
"""Give a mesh and a Dict loaded from HDF5 to compare"""
# print((mesh.elements - Dict['elements']).max())
# print(mesh.elements.dtype, Dict['elements'].dtype)
print("Checking higher order mesh generators results")
if entity_checker(mesh.elements,Dict['elements']):
... | 24,547 |
def retrieve(
framework,
region,
version=None,
py_version=None,
instance_type=None,
accelerator_type=None,
image_scope=None,
container_version=None,
distribution=None,
base_framework_version=None,
):
"""Retrieves the ECR URI for the Docker image matching the given arguments.
... | 24,548 |
def deconstruct_DMC(G, alpha, beta):
"""Deconstruct a DMC graph over a single step."""
# reverse complementation
if G.has_edge(alpha, beta):
G.remove_edge(alpha, beta)
w = 1
else:
w = 0
# reverse mutation
alpha_neighbors = set(G.neighbors(alpha))
beta_neig... | 24,549 |
def write_input_xml(filename):
"""
Write the XML file of this sample model
"""
model_input = create_sample_input_model_with_spherical_cv()
model_input.serialize(filename)
return | 24,550 |
def execute(args):
""" Execute a specified command """
subprocess.run(args) | 24,551 |
def new_followers_view(request):
"""
View to show new followers.
:param request:
:return:
"""
current_author = request.user.user
followers_new = FollowRequest.objects.all().filter(friend=current_author).filter(acknowledged=False)
for follow in followers_new:
follow.acknowledged... | 24,552 |
def dump_sphmap(stream, snake):
""" Ad-hoc sphere mapping dump format:
First Line: [# Vertices, Original Sphere Radius, Original Sphere Center (XYZ)]
Others: [Shape (distance),
Sphere Coords (XYZ),
Sphere Coords (Phi, Theta),
Surface Coords (XYZ)]
... | 24,553 |
def inv(a, p):
"""Inverse of a in :math:`{mathbb Z}_p`
:param a,p: non-negative integers
:complexity: O(log a + log p)
"""
return bezout(a, p)[0] % p | 24,554 |
def test_raw_html_634bb():
"""
Test case 634bb: variation of 634 in block quote
"""
# Arrange
source_markdown = """> <a /><b2
> data="foo" ><c>"""
expected_tokens = [
"[block-quote(1,1)::> \n> ]",
"[para(1,3):\n ]",
"[raw-html(1,3):a /]",
'[raw-html(1,9):b2... | 24,555 |
def get_iSUN(location=None):
"""
Loads or downloads and caches the iSUN dataset.
@type location: string, defaults to `None`
@param location: If and where to cache the dataset. The dataset
will be stored in the subdirectory `iSUN` of
location and read from there... | 24,556 |
def metadata_columns(request, metadata_column_headers):
"""Make a metadata column header and column value dictionary."""
template = 'val{}'
columns = {}
for header in metadata_column_headers:
columns[header] = []
for i in range(0, request.param):
columns[header].append(templa... | 24,557 |
def test_differentiable_sgd():
"""Test second order derivative after taking optimization step."""
policy = torch.nn.Linear(10, 10, bias=False)
lr = 0.01
diff_sgd = DifferentiableSGD(policy, lr=lr)
named_theta = dict(policy.named_parameters())
theta = list(named_theta.values())[0]
meta_loss ... | 24,558 |
def all_done_tasks_for_person(person, client=default):
"""
Returns:
list: Tasks that are done for given person (only for open projects).
"""
person = normalize_model_parameter(person)
return raw.fetch_all("persons/%s/done-tasks" % person["id"], client=client) | 24,559 |
def main(params):
"""
PyRate merge main function. Assembles product tiles in to
single geotiff files
"""
# setup paths
rows, cols = params["rows"], params["cols"]
mpiops.run_once(_merge_stack, rows, cols, params)
mpiops.run_once(_create_png_from_tif, params[cf.OUT_DIR])
if params[cf... | 24,560 |
def transform_cfg_to_wcnf(cfg: CFG) -> CFG:
"""
Transform given cfg into Weakened Normal Chomsky Form (WNCF)
Parameters
----------
cfg: CFG
CFG object to transform to WNCF
Returns
-------
wncf: CFG
CFG in Weakened Normal Chomsky Form (WNCF)
"""
wncf = (
c... | 24,561 |
def add_def() -> bool:
""" Retrieves the definition from the user and
enters it into the database.
"""
logger.info("Start <add_def>")
fields = ["what", "def_body", "subject"]
fields_dict = {"what": '', "def_body": '', "subject": ''}
for fi in fields:
phrase = PHRASES[fi]
fi... | 24,562 |
def test_anonymize_files_bad_input_missing(tmpdir):
"""Test anonymize_files with non-existent input."""
filename = "test.txt"
input_file = tmpdir.join(filename)
output_file = tmpdir.mkdir("out").join(filename)
with pytest.raises(ValueError, match="Input does not exist"):
anonymize_files(
... | 24,563 |
def _cd_step(examples: List[Example]):
"""
CD step to save all beam examples/tests/katas and their outputs on the GCS
"""
cd_helper = CDHelper()
cd_helper.store_examples(examples) | 24,564 |
def insert_scope_name(urls):
"""
given a tuple of URLs for webpy with '%s' as a placeholder for
SCOPE_NAME_REGEXP, return a finalised tuple of URLs that will work for all
SCOPE_NAME_REGEXPs in all schemas
"""
regexps = get_scope_name_regexps()
result = []
for i in range(0, len(urls), 2)... | 24,565 |
def test_read_config_file(mock_config_file):
"""Try to read a configuration file."""
from cdparacord import config
config_file = mock_config_file
# Setup our expectations
var_name = 'editor'
expected_value = 'probably-not-a-real-editor'
# Write them to the file
with open(config_file, ... | 24,566 |
def test_get_worst_match(name, capacity, pref_names):
""" Check that a hospital can return its worst match. """
hospital = Hospital(name, capacity)
others = [Resident(other) for other in pref_names]
hospital.matching = [others[0]]
assert hospital.get_worst_match() == others[0]
hospital.matchi... | 24,567 |
def start_server() -> None:
"""Start the server.
If this was started from the command line the path of the config file may
be passed as the first parameter. Otherwise we take the default config file
from the package.
"""
filename = (
sys.argv[1] if len(sys.argv) == 2 else
pkg_re... | 24,568 |
def fit_cochrane_orcutt(ts, regressors, maxIter=10, sc=None):
"""
Fit linear regression model with AR(1) errors , for references on Cochrane Orcutt model:
See [[https://onlinecourses.science.psu.edu/stat501/node/357]]
See : Applied Linear Statistical Models - Fifth Edition - Michael H. Kutner , page 492... | 24,569 |
def get_nodeweight(obj):
"""
utility function that returns a
node class and it's weight
can be used for statistics
to get some stats when NO Advanced Nodes are available
"""
k = obj.__class__.__name__
if k in ('Text',):
return k, len(obj.caption)
elif k == 'ImageLink' and obj... | 24,570 |
def CMYtoRGB(C, M, Y):
""" convert CMY to RGB color
:param C: C value (0;1)
:param M: M value (0;1)
:param Y: Y value (0;1)
:return: RGB tuple (0;255) """
RGB = [(1.0 - i) * 255.0 for i in (C, M, Y)]
return tuple(RGB) | 24,571 |
def update_local_artella_root():
"""
Updates the environment variable that stores the Artella Local Path
NOTE: This is done by Artella plugin when is loaded, so we should not do it manually again
"""
metadata = get_metadata()
if metadata:
metadata.update_local_root()
return True... | 24,572 |
def app_tests(enable_migrations, tags, verbosity):
"""Gets the TestRunner and runs the tests"""
# prepare the actual test environment
setup(enable_migrations, verbosity)
# reuse Django's DiscoverRunner
if not hasattr(settings, 'TEST_RUNNER'):
settings.TEST_RUNNER = 'django.test.runner.Disc... | 24,573 |
def quicksort(numbers, low, high):
"""Python implementation of quicksort."""
if low < high:
pivot = _partition(numbers, low, high)
quicksort(numbers, low, pivot)
quicksort(numbers, pivot + 1, high)
return numbers | 24,574 |
def __save_dataset(dataset: set, output_csv_path: str):
"""
Function to save the set of dataset in the csv path
Arguments:
dataset {set} -- The set of tuples consisting the triplet dataset
output_csv_path {str} -- The output csv path to save
"""
dataset_list = list(dataset)
... | 24,575 |
def bsput_delta(k, t, *, x0=1., r=0., q=0., sigma=1.):
"""
bsput_delta(k, t, *, x0=1., r=0., q=0., sigma=1.)
Black-Scholes put option delta.
See Also
--------
bscall
"""
r, q = np.asarray(r), np.asarray(q)
d1, d2 = bsd1d2(k, t, x0=x0, r=r, q=q, sigma=sigma)
return -exp(-q*t) * ... | 24,576 |
def regex_filter(patterns: Sequence[Regex], negate: bool = False, **kwargs) -> SigMapper:
"""Filter out the signals that do not match regex patterns (or do match if negate=True)."""
patterns = list(map(re.compile, patterns))
def filt(sigs):
def map_sig(sig):
return _regex_map(sig, patter... | 24,577 |
def cpncc(img, vertices_lst, tri):
"""cython version for PNCC render: original paper"""
h, w = img.shape[:2]
c = 3
pnccs_img = np.zeros((h, w, c))
for i in range(len(vertices_lst)):
vertices = vertices_lst[i]
pncc_img = crender_colors(vertices, tri, pncc_code, h, w, c)
pnccs... | 24,578 |
def run_net(X, y, batch_size, dnn, data_layer_name, label_layer_name,
loss_layer, accuracy_layer, accuracy_sink, is_train):
"""Runs dnn on given data"""
start = time.time()
total_loss = 0.
run_iter = dnn.learn if is_train else dnn.run
math_engine = dnn.math_engine
accuracy_layer.rese... | 24,579 |
def json_safe(arg: Any):
"""
Checks whether arg can be json serialized and if so just returns arg as is
otherwise returns none
"""
try:
json.dumps(arg)
return arg
except:
return None | 24,580 |
def _key_iv_check(key_iv):
"""
密钥或初始化向量检测
"""
# 密钥
if key_iv is None or not isinstance(key_iv, string_types):
raise TypeError('Parameter key or iv:{} not a basestring'.format(key_iv))
if isinstance(key_iv, text_type):
key_iv = key_iv.encode(encoding=E_FMT)
if len(key_iv) > ... | 24,581 |
def decomposeArbitraryLength(number):
"""
Returns decomposition for the numbers
Examples
--------
number 42 : 32 + 8 + 2
powers : 5, 3, 1
"""
if number < 1:
raise WaveletException("Number should be greater than 1")
tempArray = list()
current = number
position = 0
... | 24,582 |
def test_outfile_verbose() -> None:
""" outfile + verbose """
outfile = random_string()
if os.path.isfile(outfile):
os.remove(outfile)
try:
flag = '-v' if random.choice([0, 1]) else '--verbose'
rv, out = getstatusoutput(f'{RUN} {flag} -o {outfile} LSU {LSU}')
assert rv ... | 24,583 |
def ax_draw_macd2(axes, ref, kdata, n1=12, n2=26, n3=9):
"""绘制MACD
:param axes: 指定的坐标轴
:param KData kdata: KData
:param int n1: 指标 MACD 的参数1
:param int n2: 指标 MACD 的参数2
:param int n3: 指标 MACD 的参数3
"""
macd = MACD(CLOSE(kdata), n1, n2, n3)
bmacd, fmacd, smacd = macd.getResult(0),... | 24,584 |
def write_basis(basis, filename):
"""
Writes the given basis to the given file.
:param pd.DataFrame basis
:param str filename
"""
logging.info('Writing basis to {}'.format(filename))
basis.to_csv(filename) | 24,585 |
def scipy_bfgs(
criterion_and_derivative,
x,
*,
convergence_absolute_gradient_tolerance=CONVERGENCE_ABSOLUTE_GRADIENT_TOLERANCE,
stopping_max_iterations=STOPPING_MAX_ITERATIONS,
norm=np.inf,
):
"""Minimize a scalar function of one or more variables using the BFGS algorithm.
For details ... | 24,586 |
def assign_to_coders_backend(sample,
limit_to_unassigned,
shuffle_pieces_before_assigning,
assign_each_piece_n_times,
max_assignments_per_piece,
coders, max_pieces_per_coder,
creation_time, creator):
"""Assignment to coders currently uses the following algorithm:
... | 24,587 |
def mask_rcnn_heads_add_mask_rcnn_losses(model, blob_mask):
"""Add Mask R-CNN specific losses."""
loss_mask = model.net.SigmoidCrossEntropyLoss(
[blob_mask, 'masks_int32'],
'loss_mask',
scale=model.GetLossScale() * cfg.MRCNN.WEIGHT_LOSS_MASK
)
loss_gradients = blob_utils_get_loss... | 24,588 |
def _set_actor(user, sender, instance, signal_duid, **kwargs):
"""Signal receiver with extra 'user' and 'signal_duid' kwargs.
This function becomes a valid signal receiver when it is curried with the actor and a dispatch id.
"""
try:
auditlog = threadlocal.auditlog
except AttributeError:
... | 24,589 |
def parse_ns_headers(ns_headers):
"""Ad-hoc parser for Netscape protocol cookie-attributes.
The old Netscape cookie format for Set-Cookie can for instance contain
an unquoted "," in the expires field, so we have to use this ad-hoc
parser instead of split_header_words.
XXX This may not make the bes... | 24,590 |
def test_extra_010a():
"""
List item with weird progression.
"""
# Arrange
source_markdown = """* First Item
* Second Item
* Third Item
"""
expected_tokens = [
"[ulist(1,1):*::2:]",
"[para(1,3):]",
"[text(1,3):First Item:]",
"[end-para:::True]",
"[... | 24,591 |
def add_newrepo_subparser(subparser):
"""
Function to add a subparser for newrepo repository.
"""
### Base args: should be in every
parser_newrepo = subparser.add_parser('newrepo', help="download from newrepo")
parser_newrepo.add_argument('newrepoid', type=str, nargs='+',
help=... | 24,592 |
def deploy(remote='origin', reload=False):
"""
Deploy the latest app to S3 and, if configured, to our servers.
"""
require('settings', provided_by=[production, staging, electron])
render.render_all()
if env.settings == 'electron':
if not os.path.exists('electron'):
os.maked... | 24,593 |
def main(verbose: str, mt_file: str, target: str) -> None: # pylint: disable=W0613
"""
Move training data to zip model artifact
\f
:param verbose: more extensive logging
:param mt_file: json/yaml file with a mode training resource
:param target: directory where result model will be saved
"... | 24,594 |
def test_conditional_retry_policy_default_parameters():
"""
Ensures that the conditional retry policy has not been implemented.
"""
try:
RequestsStampede.policy.retry.ConditionalRetryPolicy()
except NotImplementedError as e:
assert isinstance(e, NotImplementedError)
else:
... | 24,595 |
def run_experiment(ctx, experiment_name: str):
"""run a single experiment."""
kwargs = {
"flag": "run_experiment",
"experiment_name": experiment_name,
}
_run_nerblackbox_main(ctx.obj, kwargs) | 24,596 |
def vim_instance_api_get_instances(connection, msg):
"""
Handle Get-Instances API request
"""
DLOG.verbose("Get instance, all=%s." % msg.get_all)
instance_table = tables.tables_get_instance_table()
for instance in instance_table.values():
response = rpc.APIResponseGetInstance()
r... | 24,597 |
def same_kind_right_null(a: DataType, _: Null) -> bool:
"""Return whether `a` is nullable."""
return a.nullable | 24,598 |
def unary_col(op, v):
"""
interpretor for executing unary operator expressions on columnars
"""
if op == "+":
return v
if op == "-":
return compute.subtract(0.0, v)
if op.lower() == "not":
return compute.invert(v)
raise Exception("unary op not implemented") | 24,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.