content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def TraceMainDescendant(istart,ihalo,numsnaps,numhalos,halodata,tree,TEMPORALHALOIDVAL,ireverseorder=False):
"""
Follows a halo along descendant tree to root tails
if reverse order than late times start at 0 and as one moves up in index
one moves backwards in time
"""
#start at this snapshot
... | 5,200 |
def get_service_mapping():
""" Get mapping dict of service types
Returns:
A mapping dict which maps service types names to their ids
"""
# Get all Service types:
all_service_type = requests.get(base_url + 'services/v2/service_types', headers=headers3).json()
# Make Dict of s... | 5,201 |
def get_recently_viewed(request):
""" get settings.PRODUCTS_PER_ROW most recently viewed products for current customer """
t_id = tracking_id(request)
views = ProductView.objects.filter(tracking_id=t_id).values(
'product_id').order_by('-date')[0:PRODUCTS_PER_ROW]
product_ids = [v['product_id'] f... | 5,202 |
def chapter_by_url(url):
"""Helper function that iterates through the chapter scrapers defined in
cu2.scrapers.__init__ and returns an initialized chapter object when it
matches the URL regex.
"""
for Chapter in chapter_scrapers:
if re.match(Chapter.url_re, url):
return Chapter.f... | 5,203 |
def get_model_name(part_num):
"""
根据型号获取设备名称
:param part_num:
:return:
"""
models = current_config.MODELS
for model_name, model_part_num in models.items():
if model_part_num == part_num:
return model_name | 5,204 |
def run_get_pk(process, *args, **inputs):
"""Run the process with the supplied inputs in a local runner that will block until the process is completed.
:param process: the process class or process function to run
:param inputs: the inputs to be passed to the process
:return: tuple of the outputs of the... | 5,205 |
def test_remove_specified_kwargs_empty(empty_kwargs, warn):
"""Test the internal remove_specified_kwargs function on empty kwargs.
Parameters
----------
empty_kwargs : tuple
pytest fixture. See local conftest.py.
warn : bool
``True`` to warn if a specified string key not in kwargs, ... | 5,206 |
def _random_mask(target_tokens, noise_probability=None, target_length=None):
""" target_length其实是mask_length"""
unk = 3
target_masks = get_base_mask(target_tokens)
if target_length is None:
target_length = target_masks.sum(1).float()
if noise_probability is None:
# sample ... | 5,207 |
def test_random_multi_image():
""" Just make sure the image_plot function doesn't crash.
"""
shap.image_plot([np.random.randn(3, 20,20) for i in range(3)], np.random.randn(3, 20,20), show=False) | 5,208 |
def download_and_extract(data_dir, force=False):
"""Download fname from the datasets_url, and save it to target_dir,
unless the file already exists, and force is False.
Parameters
----------
data_dir : str
Directory of where to download cifar10 data
force : bool
Force downloading... | 5,209 |
def EnableDeploymentManager(config):
"""Enables Deployment manager, with role/owners for its service account."""
logging.info('Setting up Deployment Manager...')
project_id = config.project['project_id']
# Enabled Deployment Manger and Cloud Resource Manager for this project.
utils.RunGcloudCommand(['service... | 5,210 |
def raise_if_parameters_are_invalid(parameters):
"""Raises an exception if the specified parameters are not valid.
Args:
parameters (dict): the parameters dict.
"""
if not isinstance(parameters, dict):
raise BadRequest(PARAMETERS_EXCEPTION_MSG)
for key, value in parameters.items():... | 5,211 |
def test_secretsmanager_provider_deploy(
mock_decrypt,
boto_fs,
capsys
):
"""
Should deploy the AWS Secrets Manager changes
"""
mock_decrypt.return_value = b'PlainTextData'
client = boto3.client('secretsmanager')
with patch.object(boto3.Session, 'client') as mock_client:
... | 5,212 |
def calculate(cart):
"""Return the total shipping cost for the cart. """
total = 0
for line in cart.get_lines():
total += line.item.shipping_cost * line.quantity
return total | 5,213 |
def arr_to_rgb(arr, rgb=(0, 0, 0), alpha=1, invert=False, ax=None):
"""
arr to be made a mask
rgb:assumed using floats (0..1,0..1,0..1) or string
"""
# arr should be scaled to 1
img = np.asarray(arr, dtype=np.float64)
img = img - np.nanmin(img)
img = img / np.nanmax(img)
im2 = np.ze... | 5,214 |
def parameters(number, size, v=3):
"""
sets item parameters of items and puts in list
:param number: number of items
:param size: characteristic size of the items
:param v: velocity
:return: list with items
"""
param = []
for i in range(number):
angle = randint(0, int(2 * pi ... | 5,215 |
def _validate_args_for_toeplitz_ops(c_or_cr, b, check_finite, keep_b_shape,
enforce_square=True):
"""Validate arguments and format inputs for toeplitz functions
Parameters
----------
c_or_cr : array_like or tuple of (array_like, array_like)
The vector ``c``, ... | 5,216 |
def test_runner_should_call_hooks_when_running_a_feature(
hook_registry, default_config, mocker
):
"""The Runner should call the ``each_feature`` hooks when running a Feature"""
# given
runner = Runner(default_config, None, hook_registry)
feature_mock = mocker.MagicMock(name="Feature")
# when
... | 5,217 |
def run_dft_en_par(dft_input:str, structure,
dft_loc:str, ncpus:int, dft_out:str ="dft.out",
npool:int =None, mpi:str ="mpi", **dft_kwargs):
"""run DFT calculation with given input template
and atomic configurations. This function is not used atm.
:param dft_input: input template file name
... | 5,218 |
def get_application_id():
"""Returns the app id from the app_identity service."""
return app_identity.get_application_id() | 5,219 |
def prior(X, ls, kernel_func=rbf,
ridge_factor=1e-3, name=None):
"""Defines Gaussian Process prior with kernel_func.
Args:
X: (np.ndarray of float32) input training features.
with dimension (N, D).
kernel_func: (function) kernel function for the gaussian process.
D... | 5,220 |
def some_handler(element, current_thread: threading.Thread = None, *args, **kwargs):
"""Handles the elment received from the stream."""
current_value = counter.count
if SLOW_DOWN:
time.sleep(random.randint(1,5))
counter.update(current_value + 1)
print(f"\033[92mHandling iteration number {ele... | 5,221 |
def ast_for_statement(statement: Ast, ctx: ReferenceDict):
"""
statement
::= (label | let | expr | into | importExpr) [';'];
"""
# assert statement.name == 'statement'
sexpr = statement[0]
s_name: str = sexpr.name
try:
if s_name is UNameEnum.expr: # expr
# Ruiko... | 5,222 |
def test_actual_results_accumulated_cost_matrix(params, arr_desired):
"""Test that the actual results are the expected ones."""
arr_actual = accumulated_cost_matrix(**params)
np.testing.assert_allclose(arr_actual, arr_desired, atol=1e-5, rtol=0.) | 5,223 |
def multiclass_eval(y_hat: FloatTensor, y: IntTensor) -> int:
"""
Returns number correct: how often the rounded predicted value matches gold.
Arguments:
y_hat: 2d (N x C): guesses for each class
y: 2d (N x C): onehot representation of class labels
Returns:
nubmer correct
""... | 5,224 |
def _VMTestChrome(board, sdk_cmd):
"""Run cros_run_test."""
image_dir_symlink = image_lib.GetLatestImageLink(board)
image_path = os.path.join(image_dir_symlink,
constants.VM_IMAGE_BIN)
# Run VM test for boards where we've built a VM.
if image_path and os.path.exists(image_path):
... | 5,225 |
def get_image(bot, update):
"""Gets a random image from unsplash.com with /random command.
Uses the unsplash api and gets the random image from the api. It also
includes the reference of author's name (with unsplash profile link) and
unsplash website as the caption of the image.
"""
# Insert y... | 5,226 |
def punctuation_for_spaces_dict() -> Dict[int, str]:
"""Provide a dictionary for removing punctuation, keeping spaces. Essential for scansion
to keep stress patterns in alignment with original vowel positions in the verse.
:return dict with punctuation from the unicode table
>>> print("I'm ok! Oh #%&*(... | 5,227 |
def extract止めないでお姉さま(item):
"""
Parser for '止めないで、お姉さま…'
"""
badwords = [
'subs',
]
if any([bad in item['tags'] for bad in badwords]):
return None
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'WA... | 5,228 |
def GetExpID(startRow=0,numRows=2000,totalRows = -1):
"""
Queries the Allen Mouse Brain Institute website for all gene expression data available for download.
Returns:
--------
GeneNames: list[dict()]
list of all genes where expression data is available for download. Dict contains experiment/gene metadata.
Se... | 5,229 |
def fsinit(S:Optional[StorageSettings]=None,
check_not_exist:bool=False,
remove_existing:bool=False)->None:
""" Create the storage and/or temp direcory if they don't exist. Default
locations are determined by `PYLIGHTNIX_STORAGE` and `PYLIGHTNIX_TMP` env
variables. """
if remove_existing:
... | 5,230 |
def _add_biotype_attribute(gene_content):
"""
Add `biotype` attribute to all intervals in gene_content.
Parameters
----------
gene_content_ : dict
Intervals in gene separated by transcript id.
Returns
-------
dict
Same gene_content_ object with added `biotype` attribute... | 5,231 |
def test_list_task():
"""测试任务列表,这个接口主要admin用"""
res = get("/v3/databus/tasks/")
assert res["result"]
assert res["data"]["page_total"] == 12
assert res["data"]["page"] == 1
assert len(res["data"]["tasks"]) == 12
res = get("/v3/databus/tasks/?cluster_name=hdfs-kafka_cluster_name-M")
asser... | 5,232 |
def verify_macrotask_request(current_time_ms, scheduler, event_list):
"""Verifies that the provided list of Events contains a single MacrotaskRequest Event.
Also checks that the MacrotaskRequest Event is scheduled for the correct time.
"""
assert len(event_list) == 1
arrival_time_ms, macrotask_request_event ... | 5,233 |
def random_solution(W, D, n):
"""
We generate a solution of size n
"""
sol = np.random.permutation(n) + 1
fitness_sol = fitness(W=W, D=D, sol=sol)
return [fitness_sol, sol] | 5,234 |
def singlePlotMain():
"""Main, but in a single plot and only interesting data
"""
data = []
line = f.readline()
count = 0
while line != "":
data.append(readline(line))
line = f.readline()
count += 1
data.sort()
data = removeStartTime(data)
data = afterAndBefor... | 5,235 |
def connect_host_loop(_ctx: Context, timeout_secs: int = 3) -> None:
"""Tries to connect host in permanent loop."""
i = 0
while i < CONNECT_TO_HOST_MAX_RETRY:
print(f'{format_dt(datetime.datetime.now())} Trying connect to {_ctx.host}:{_ctx.port}...')
if connect_host(_ctx):
break
... | 5,236 |
def format_perm(model, action):
"""
Format a permission string "app.verb_model" for the model and the
requested action (add, change, delete).
"""
return '{meta.app_label}.{action}_{meta.model_name}'.format(
meta=model._meta, action=action) | 5,237 |
def update_variables(params):
"""Updates ILAMB metadata for benchmark data uploaded through the PBS.
Parameters
----------
params : list
The WMT parameters for the ILAMB component.
"""
data_files = get_pbs_listing(data_dir)
# Extract variable names from file list, removing duplicate... | 5,238 |
def verify_password(plain_password: str, hashed_password: str) -> bool:
"""Verify plain password and hashed password.
Args:
plain_password (str): Plain text password.
hashed_password (str): Hashed password.
Returns:
bool: Returns true if secret is verified against given hash.
"... | 5,239 |
def render_siecle2(tpl: str, parts: List[str], data: Dict[str, str]) -> str:
"""
>>> render_siecle2("siècle2", ["1"], defaultdict(str))
'I<sup>er</sup>'
>>> render_siecle2("siècle2", ["I"], defaultdict(str))
'I<sup>er</sup>'
>>> render_siecle2("siècle2", ["i"], defaultdict(str))
'I<sup>er</s... | 5,240 |
def get_interactions(request):
"""Function to get the interactions for a molecule"""
dist_dict = {"SingleAtomAcceptor_SingleAtomDonor": {"dist": 4.0}, # H-bonding
"SingleAtomAcceptor_WeakDonor": {"dist": 3.0}, # Weak H-bond
"Halogen_SingleAtomAcceptor": {"dist": 4.0}, # H... | 5,241 |
def sendmail_action():
"""Send an email to the address entered in the sendmail form."""
if not MSGRAPHAPI.loggedin:
redirect("/sendmail")
email_body = json.dumps(
{
"Message": {
"Subject": request.query.subject,
"Body": {"ContentType": "HTML", "C... | 5,242 |
def parseArg():
"""
CMD argument parsing
:return: the parser
"""
parser = argparse.ArgumentParser(description='SAT solver')
parser.add_argument('infile', nargs=1, type=argparse.FileType('r'))
parser.add_argument('level', nargs='?', default=0, type=int)
return parser | 5,243 |
def test_attachment(testdir, tmpdir):
"""
Test a basic test with an additional property
"""
testdir.makepyfile("""
def test_basic(add_nunit_attachment):
add_nunit_attachment("file.pth", "desc")
assert 1 == 1
""")
outfile = tmpdir.join('out.xml')
outfile_pth = ... | 5,244 |
def normal_to_angle(x, y):
"""
Take two normal vectors and return the angle that they give.
:type x: float
:param x: x normal
:type y: float
:param y: y normal
:rtype: float
:return: angle created by the two normals
"""
return math.atan2(y, x) * 180 / math.pi | 5,245 |
def glDeleteFramebuffersEXT( baseOperation, n, framebuffers=None ):
"""glDeleteFramebuffersEXT( framebuffers ) -> None
"""
if framebuffers is None:
framebuffers = arrays.GLuintArray.asArray( n )
n = arrays.GLuintArray.arraySize( framebuffers )
return baseOperation( n, framebuffers ) | 5,246 |
def enforce(data, service=False, tenant=None):
"""Enforce zone app or service."""
tstr = " -tenant=%s " % (tenant) if tenant else ""
ostr = " -enforce-service " if service else " -enforce-zone-app "
ret_val = {}
if not data:
ret_val['empty'] = {"success": "Empty enforcement request"}
el... | 5,247 |
def outline(image, mask, color):
"""
Give a color to the outline of the mask
Args:
image: an image
mask: a label
color: a RGB color for outline
Return:
image: the image which is drawn outline
"""
mask = np.round(mask)
... | 5,248 |
def test_interpolation():
"""Test string interpolation during execution"""
execute_workflow(r"""
[0: shared='res']
res = ''
b = 200
res += f"{b}"
""")
assert env.sos_dict["res"] == "200" | 5,249 |
def main(ctx, config_file, config_pairs, debug):
"""Buy and sell anything on the internet for bitcoin.
\b
For detailed help, run 21 help --detail.
For full documentation, visit 21.co/learn.
"""
need_wallet_and_account = ctx.invoked_subcommand not in (
'help', 'update', 'login', 'doctor')
# Set UUI... | 5,250 |
def bogen_ab(dl, dr):
"""Bogen abwärts, für weites D (durch usw.).
Ende nur spitz wenn allein steht, sonst letzten Stützpunkt etwas früher,
letzten Kontrollpunkt für Fortsetzung in gleicher Richtung setzen, damit
glatte Verbindung zu Folgekonsonant.
"""
y0 = 0.5 # Höhe Anfang- und Endpu... | 5,251 |
def IterateXmlElements(node):
"""minidom helper function that iterates all the element nodes.
Iteration order is pre-order depth-first."""
if node.nodeType == node.ELEMENT_NODE:
yield node
for child_node in node.childNodes:
for child_node_element in IterateXmlElements(child_node):
yield child_node... | 5,252 |
def is_open_port(port):
"""
Check if port is open
:param port: port number to be checked
:type port: int
:return: is port open
:rtype: bool
"""
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind(("127.0.0.1", port))
except socket.error:
return Fa... | 5,253 |
def stopping_fn_from_metric(metric_name: str):
"""
Returns a stopping function for ignite.handlers.EarlyStopping using the given metric name.
"""
def stopping_fn(engine: Engine):
return engine.state.metrics[metric_name]
return stopping_fn | 5,254 |
def output_formats(cmd, data, output) -> None:
"""Test output formats."""
with requests_mock.Mocker() as mock:
mock.get(
"http://localhost:8123/api/states", text=data, status_code=200
)
runner = CliRunner()
result = runner.invoke(cli.cli, cmd, catch_exceptions=False)... | 5,255 |
def write_to_db(db_name, table_name):
""" Doc string for functionwrite_to_db. """
return | 5,256 |
def deconstruct_proto(model_proto, compression_pipeline):
"""Deconstruct the protobuf.
Args:
model_proto: The protobuf of the model
compression_pipeline: The compression pipeline object
Returns:
protobuf: A protobuf of the model
"""
# extract the tensor_dict and metadata
... | 5,257 |
def cmd_mdremove(bot, trigger, caseid):
"""
Remove a case from the Marked for Deletion List™ (Does NOT reopen the case!)
required parameter: database id
aliases: mdremove, mdr, mdd, mddeny
"""
try:
result = callapi(bot, method='GET', uri='/rescues/' + str(caseid), triggernick=str(trigger... | 5,258 |
def Parallel(*plist):
""" Parallel(P1, [P2, .. ,PN])
"""
_parallel(plist, True) | 5,259 |
def configure_container(container):
"""Configures the container
Params:
container (ServiceContainer)
"""
container.register(ServiceDefinition('command_processor', _make_command_processor))
container.register(ServiceDefinition('logger', _make_logger))
container.register(ServiceDefinition... | 5,260 |
def build_attribute_set(items, attr_name):
"""Build a set off of a particular attribute of a list of
objects. Adds 'None' to the set if one or more of the
objects in items is missing the attribute specified by
attr_name.
"""
attribute_set = set()
for item in items:
attribute_set.add(... | 5,261 |
def potential_fn(q):
"""
- log density for the normal distribution
"""
return 0.5 * np.sum(((q['z'] - true_mean) / true_std) ** 2) | 5,262 |
def estimate_pointcloud_local_coord_frames(
pointclouds: Union[torch.Tensor, "Pointclouds"],
neighborhood_size: int = 50,
disambiguate_directions: bool = True,
) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Estimates the principal directions of curvature (which includes normals)
of a batch of `poin... | 5,263 |
def patch_rbac(rbac_v1: RbacAuthorizationV1Api, yaml_manifest) -> RBACAuthorization:
"""
Patch a clusterrole and a binding.
:param rbac_v1: RbacAuthorizationV1Api
:param yaml_manifest: an absolute path to yaml manifest
:return: RBACAuthorization
"""
with open(yaml_manifest) as f:
do... | 5,264 |
def _shp_to_boundary_gdf(shp_file_path):
""".shpかshpが格納された.zipを指定してgdfを作成する
Args:
shp_file_path (Path): 変換対象のshpファイルを格納するディレクトリのパス文字列
Returns:
gpd.GeoDataFrame: shpを変換したGeoDataFrame
"""
s2g = ShapeToGeoPandas(str(shp_file_path.resolve()))
gdf = s2g.gdf
necessary_columns =... | 5,265 |
def test_from_subpackage():
"""Build the package tree from a package inside another."""
container = PackageTree(
module='packageB', root='TopLevelPackage', directory="tests",
)
assert 2 == len(container.classes)
assert 1 == len(container.subpackages) | 5,266 |
def zip2dir(zip_fname, out_dir):
""" Extract `zip_fname` into output directory `out_dir`
Parameters
----------
zip_fname : str
Filename of zip archive to write
out_dir : str
Directory path containing files to go in the zip archive
"""
# Use unzip command rather than zipfile ... | 5,267 |
def git_repo_parse_stats():
"""
Create a fake git repo with the following properties:
- upstream set to another local git repo
- 3 staged files (1 changed, 2 additions)
- 1 changed file unstaged
- 2 untracked files
- 1 stashed change set
"""
cwd = os.getcwd()
... | 5,268 |
def insert_site(site, seq, offset=None):
"""Inserts a sequence (represeting a site) into a larger sequence (which
is a sequence object rather than a series of letters."""
# inputs:
# site The site to be inserted
# offsets the offset where the site is to be inserted
# ... | 5,269 |
def sex2bpzmags(f, ef, zp=0., sn_min=1., m_lim=None):
"""
This function converts a pair of flux, error flux measurements from SExtractor
into a pair of magnitude, magnitude error which conform to BPZ input standards:
- Nondetections are characterized as mag=99, errormag=m_1sigma
- Objects with absur... | 5,270 |
def get_elk_command(line):
"""Return the 2 character command in the message."""
if len(line) < 4:
return ""
return line[2:4] | 5,271 |
def safe_div(a, b):
"""
Safe division operation. When b is equal to zero, this function returns 0.
Otherwise it returns result of a divided by non-zero b.
:param a: number a
:param b: number b
:return: a divided by b or zero
"""
if b == 0:
return 0
return a / b | 5,272 |
def decrypt_story():
"""
Using the methods you created in this problem set,
decrypt the story given by the function getStoryString().
Use the functions getStoryString and loadWords to get the
raw data you need.
returns: string - story in plain text
"""
story = CiphertextMessage(get_story... | 5,273 |
def shouldAvoidDirectory(root, dirsToAvoid):
"""
Given a directory (root, of type string) and a set of directory
paths to avoid (dirsToAvoid, of type set of strings), return a boolean value
describing whether the file is in that directory to avoid.
"""
subPaths = root.split('/')
for i, sub... | 5,274 |
def atom_explicit_hydrogen_valences(xgr):
""" explicit hydrogen valences, by atom
"""
return dict_.transform_values(atom_explicit_hydrogen_keys(xgr), len) | 5,275 |
def change_account_type(user_id):
"""Change a user's account type."""
if current_user.id == user_id:
flash('You cannot change the type of your own account. Please ask '
'another administrator to do this.', 'error')
return redirect(url_for('admin.user_info', user_id=user_id))
u... | 5,276 |
def test_runner(filtered_tests, args):
"""
Driver function for the unit tests.
Prints information about the tests being run, executes the setup and
teardown commands and the command under test itself. Also determines
success/failure based on the information in the test case and generates
TAP ou... | 5,277 |
def test_get_scores_from_ratings_dataframe_by_inferring_rating_provider_longterm():
"""Tests if function can correctly handle pd.DataFrame objects."""
act = rtg.get_scores_from_ratings(
ratings=conftest.rtg_df_wide_with_err_row, tenor="long-term"
)
# noinspection PyTypeChecker
assert_frame_e... | 5,278 |
def check_downloaded(link, filename, downloader_name, do_not_resume=False, tmp_file=None):
"""Check if downloading filename already exists."""
if os.path.exists(filename):
logger.info('%s already exists', filename)
else:
if not tmp_file:
tmp_file = filename + '.tmp'
if os... | 5,279 |
def omp_set_num_threads(threads: int):
"""omp_set_num_threads
omp_set_num_threadsを呼び出す
バックグランドで学習する場合など、Host側のCPUをすべて使うと
逆に性能が落ちる場合や、運用上不便なケースなどで個数制限できる
Args:
threads (int) : OpenMPでのスレッド数
"""
core.omp_set_num_threads(threads) | 5,280 |
def get_all_infos_about_argument(db_argument: Argument, main_page, db_user, lang) -> dict:
"""
Returns bunch of information about the given argument
:param db_argument: The argument
:param main_page: url of the application
:param db_user: User
:param lang: Language
:rtype: dict
:return:... | 5,281 |
def play(i, arr, num=1):
"""Save wav sequence for num-times into the result"""
for c in range(num):
for x in SND_PARTS[i]:
arr.append(x) | 5,282 |
def average_proxy(ray, method, proxy_type):
""" method to average proxy over the raypath.
Simple method is direct average of the proxy: $\sum proxy(r) / \sum dr$.
Other methods could be: $1/(\sum 1 / proxy)$ (better for computing \delta t)
"""
total_proxy = 0.
try:
methode.evaluation
... | 5,283 |
def test_get_ips_not_empty(
mocker, ip_block_array, ip_v4, ip_v6, service_expired):
"""
Test ip.get_ips task with some IPs returned by API
"""
mocker.patch(
'ovh_api_tasks.api_wrappers.ip.get_ips', return_value=ip_block_array)
get_ip_responses = [ip_v4, ip_v6, service_expired]
... | 5,284 |
def export_graph(filename, graph, num_obs, num_int, fixed_partial_interventions=False):
"""
Takes a graph and samples 'num_obs' observational data points and 'num_int' interventional data points
per variable. All those are saved in the file 'filename'
Parameters
----------
filename : str
... | 5,285 |
def after(base=_datetime, diff=None):
"""
count datetime after diff args
:param base: str/datetime/date
:param diff: str
:return: datetime
"""
_base = parse(base)
if isinstance(_base, datetime.date):
_base = midnight(_base)
result_dict = dp(diff)
for unit in result_dict:
... | 5,286 |
def tmux_call(command_list):
"""Executes a tmux command """
tmux_cmd = ['tmux'] + command_list
# print(' '.join(tmux_cmd))
_safe_call(tmux_cmd) | 5,287 |
def open_lib(ifile):
"""Opens lib with name ifile and returns stationmeta, arraydim, rlengths, heights, sectors, data."""
with open(ifile, 'rb') as f:
lines = f.readlines()
lines = [x.strip() for x in lines]
data = {}
lines = filter(lambda x: x.strip(), lines)
da... | 5,288 |
def convert_examples_to_features(examples, intent_label_list, slot_label_list, max_seq_length,
tokenizer):
"""Convert a set of `InputExample`s to a list of `InputFeatures`."""
features = []
for (ex_index, example) in enumerate(examples):
if ex_index % 10000 == 0:
tf.log... | 5,289 |
def get_blb_links(driver):
"""takes (driver) and returns list of links to scrape"""
homepage = "https://www.bloomberg.com/europe"
rootpage = "https://www.bloomberg.com"
driver.get(homepage)
ssm = driver.find_elements_by_class_name("single-story-module")[0].get_attribute(
"outerHTML"
)
... | 5,290 |
def randomProfile(freq,psd):
"""
Generate a random profile from an input PSD.
freq should be in standard fft.fftfreq format
psd should be symmetric as with a real signal
sqrt(sum(psd)) will equal RMS of profile
"""
amp = np.sqrt(psd)*len(freq)
ph = randomizePh(amp)
f = amp*ph
sig... | 5,291 |
def test_accepts_filenames_with_umlauts(tmp_path):
"""Accepts filenames with umlauts."""
os.chdir(tmp_path)
Path("föö").write_text("foo stuff")
Path("bär").write_text("bar stuff")
assert _ls_visiblefile_paths() == [
str(Path("bär").resolve()),
str(Path("föö").resolve()),
]
as... | 5,292 |
def getP(W, diagRegularize = False):
"""
Turn a similarity matrix into a proability matrix,
with each row sum normalized to 1
:param W: (MxM) Similarity matrix
:param diagRegularize: Whether or not to regularize
the diagonal of this matrix
:returns P: (MxM) Probability matrix
"""
if ... | 5,293 |
def error(message, **formatting):
"""
Return an error message to the command line
"""
click.secho(message, fg = 'red', **formatting) | 5,294 |
def get_structure_index(structure_pattern,stream_index):
"""
Translates the stream index into a sequence of structure indices identifying an item in a hierarchy whose structure is specified by the provided structure pattern.
>>> get_structure_index('...',1)
[1]
>>> get_structure_index('.[.].',1)
... | 5,295 |
def n_knapsack(n_knapsacks=5,
n_items=100, # Should be divisible by n_knapsack
n_weights_per_items=500,
use_constraints=False,
method='trust-constr',
backend='tf'
):
"""
Here we solve a continuous relaxation of the multik... | 5,296 |
def has_url(account: Accounts) -> bool:
"""Return True if the account's note or fields seem to contain a URL."""
if account.note and "http" in account.note.lower():
return True
if "http" in str(account.fields).lower():
return True
return False | 5,297 |
def conv2x2(in_planes, out_planes, stride=1, groups=1, dilation=1, padding=0):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes,
out_planes,
kernel_size=2,
stride=stride,
padding=padding,
groups... | 5,298 |
def face_normals(P,T,normalize=True):
"""Computes normal vectors to triangles (faces).
Args:
P: n*3 float array
T: m*3 int array
normalize: Whether or not to normalize to unit vectors. If False, then the magnitude of each vector is twice the area of the corresponding tria... | 5,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.