content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_restricted_area(path1, path2, restricted_pos1, restricted_pos2, time_step):
"""Computes the restricted area and the start- and end-time steps for both agents.
* start time-step: The first time step where an agent occupies a position within the restricted
area.
* end time-step... | 12,600 |
def execute_config(config_subparser: argparse.ArgumentParser, argv: List[str]) -> int:
""" Boolean logic of config subparser triggering. """
args = config_subparser.parse_args(argv[1:])
if args.show_settings:
print(settings_msg)
return 0
if args.turn_log_on:
config['LOG-SETTIN... | 12,601 |
def FR_highpass(freq: np.ndarray, hp_freq: float,
trans_width: float) -> np.ndarray:
"""Frequency responce for highpass filter
Parameters
----------
``freq``: np.ndarray
frequency array
``hp_freq``: float
highpass frequency
``trans_width``: float
widt... | 12,602 |
def _rexec(params):
"""Start a subprocess shell to execute the specified command and return its output.
params - a one element list ["/bin/cat /etc/hosts"]
"""
# check that params is a list
if not isinstance(params, list) or len(params) == 0:
return "Parameter must be a not empty list"
command = p... | 12,603 |
def test_control_failures(tmp_path: pathlib.Path) -> None:
"""Test various failure modes."""
part = common.Part(name='foo')
assert ControlIOWriter._get_label(part) == ''
assert ControlIOReader._strip_to_make_ncname('1a@foo') == 'afoo'
with pytest.raises(TrestleError):
ControlIOReader._strip... | 12,604 |
def _get_compose_template(manifest):
"""
Build the service entry for each one of the functions in the given context.
Each docker-compose entry will depend on the same image and it's just a static
definition that gets built from a template. The template is in the artifacts
folder.
"""
artifac... | 12,605 |
def _ParsePackageNode(package_node):
"""Parses a <package> node from the dexdump xml output.
Returns:
A dict in the format:
{
'classes': {
<class_1>: {
'methods': [<method_1>, <method_2>]
},
<class_2>: {
'methods': [<method_1>, <method_2>]
... | 12,606 |
def greet(lang):
"""This function is for printing a greeting in some
selected languages: Spanish, Swedish, and German"""
if lang == 'es':
return 'Hola'
elif lang == 'ge':
return 'Hallo'
elif lang == 'sv':
return 'Halla'
else:
return 'Hello' | 12,607 |
def add_hook(
show_original=False,
show_transformed=False,
predictable_names=False,
verbose_finder=False,
):
"""Creates and adds the import hook in sys.meta_path"""
callback_params = {
"show_original": show_original,
"show_transformed": show_transformed,
"predictable_name... | 12,608 |
def correlate_two_dicts(xdict, ydict, subset_keys=None):
"""Find values with the same key in both dictionary and return two arrays of corresponding values"""
x, y, _ = correlate_two_dicts_verbose(xdict, ydict, subset_keys)
return x, y | 12,609 |
def find_gateways(unicast_gateway, session, apic) -> tuple:
"""Search for ACI Gateways and get configurations"""
get_gateway = get_subnets(session, apic)
aps = []
epgs = []
l3Outs = []
gateways = []
location, bridge_domain, uni_route, scope, unkwn_uni, tenant, bd_vrf, iplearn = ... | 12,610 |
def test_list_date_time_max_length_4_nistxml_sv_iv_list_date_time_max_length_5_4(mode, save_output, output_format):
"""
Type list/dateTime is restricted by facet maxLength with value 10.
"""
assert_bindings(
schema="nistData/list/dateTime/Schema+Instance/NISTSchema-SV-IV-list-dateTime-maxLength-... | 12,611 |
def disable_servo(pin):
"""
Attempt to disable the specified servo by turning off the PWM signal.
Note that this method does NOT work for digital servos--they will
continue to run until they are powered off.
"""
set_pwm(pin, 0) | 12,612 |
def hamming_dist(y_true, y_pred):
"""
Calculate the Hamming distance between a given predicted label and the
true label. Assumes inputs are torch Variables!
Args:
y_true (autograd.Variable): The true label
y_pred (autograd.Variable): The predicted label
Returns:
(float): Th... | 12,613 |
def task_mo():
"""Create bynary wheel distribution"""
return {
"actions": [
"""pybabel compile -D todo -i frontend/po/eng/LC_MESSAGES/todo.po -o frontend/po/eng/LC_MESSAGES/todo.mo"""
],
"file_dep": ["frontend/po/eng/LC_MESSAGES/todo.po"],
"targets": ["frontend... | 12,614 |
def tuple_action_to_int(
action: Tuple[int, int], slot_based: bool, end_trial_action: bool
) -> int:
"""Converts tuple action to integer."""
stone, potion = action
num_special_actions = 2 if end_trial_action else 1
if stone < 0:
return stone + num_special_actions
if slot_based:
potions_and_cauldro... | 12,615 |
def PDM(signal=50, angle=0, n_points=1000, motion_slow=0, motion_size=75, box_size=8, point_size=0.05, point_speed=1, ITI=1000):
"""
Pattern Detection in Motion
"""
angle_rad = np.radians(angle)
y_movement = np.sin(np.radians(angle))*point_speed
x_movement = np.cos(np.radians(angle))*point_spee... | 12,616 |
def warpImage(imIn, pointsIn, pointsOut, delaunayTri):
"""
变换图像
参数:
===========
imIn:输出图像
pointsIn:输入点
pointsOut:输出点:
delaunayTri:三角形
返回值:
============
imgOut:变形之后的图像
"""
pass
h, w, ch = imIn.shape
imOut = np.zeros(imIn.shape, dtype=imIn.dtype)
for j in ... | 12,617 |
def test_check_fields():
"""Check to make sure the right fields have been created.
Check that the sizes of at least one are also correct (they are at node
so if one is the right size, then they all should be)
"""
mg0 = RasterModelGrid((10, 10), xy_spacing=(1, 1))
mg0.add_field(
"topogr... | 12,618 |
def rmchars(value):
"""Remove special characters from alphanumeric values except for period (.)
and negative (-) characters.
:param value: Alphanumeric value
:type value: string
:returns: Alphanumeric value stripped of any special characters
:rtype: string
>>> import utils
>>> utils.rm... | 12,619 |
def test_find_missing(source, target, result):
"""Test that function find_missing returns the missing element between 2 lists."""
from missing_element import find_missing_counter
assert find_missing_counter(source, target) == result | 12,620 |
def ema(x):
"""
[Definition] 以period为周期的指数加权移动平均线
[Category] 技术指标
"""
return 'ema(%s,%s)' %(x, pe.gen_param('ema', 'period')) | 12,621 |
def tokenized(phrase: str) -> Set[str]:
"""Split a phrase into tokens and remove stopwords."""
return set(normalize(phrase).split()) - STOPWORDS | 12,622 |
def synthesize(pipeline_in, net, dev, res_alloc, output_dir, prefix="", override_ibits=0):
"""
Create an FPGA accelerator given a QNN and compute resource allocator.
Returns an ExternalExecutionLayer wrapping the compiled simulation executable.
pipeline_in : list of input layers
res_alloc : function... | 12,623 |
async def server_error(request, exc):
"""
Return an HTTP 500 page.
"""
template = '500.html'
context = {'request': request}
return templates.TemplateResponse(template, context, status_code=500) | 12,624 |
def return_post():
""""
Returns the post-processing plugins.
:param: None
:return: POST_PROCESSING_PLUGINS
"""
return POST_PROCESSING_PLUGINS | 12,625 |
def redis_uri() -> typing.Optional[str]:
"""Connection URI for Redis server."""
value = os.environ.get("REDIS_URI")
if not value:
log.warning('Optional environment variable "REDIS_URI" is missing')
return value | 12,626 |
def numpy_to_b64str(img):
"""
Converts a numpy array into a base 64 string
Args:
img (np.array):
Returns:
str: base 64 representation of the numpy array/image.
"""
img = img[..., ::-1] # flip for cv conversion
_, img = cv2.imencode('.jpg', img) # strips header
image_b... | 12,627 |
def test_top_images_dataset_init_missing_files(top_images_root, subpath,
error_pattern):
"""Test TopImagesDataset.__init__ dies when files are missing."""
path = top_images_root / subpath
if path.is_dir():
shutil.rmtree(path)
else:
assert pa... | 12,628 |
def lennard_jones(r, epsilon, sigma, index=(12, 6)):
"""
General pair potential resembling a Lennard Jones model. Default indexes
values are for a typical LJ potential, also called 12-6 potential.
Parameters
----------
r : float or np.ndarray
Distance between interacting particles. It c... | 12,629 |
def check_mine_detonation(bot):
""" Check if a bot stepped on a mine, and if so, detonate it. """
for mine in arena_globals.mines:
# Don't want bot detonating its own mine
if bot is not mine.owner_bot:
mine_rect = pygame.Rect(mine.x, mine.y, MINE_SIZE, MINE_SIZE)
bo... | 12,630 |
def get_unique_name(x, mult=0, extra=''):
"""
Returns a unique key composed of inchikey and multiplicity
>>> mol = get_mol('[O][O]')
>>> get_unique_name(mol)
'MYMOFIZGZYHOMD-UHFFFAOYSA-N3'
"""
mol = get_mol(x, make3D=True)
if mult == 0:
mult = mol.spin
return mol.write("inchi... | 12,631 |
def get_individual_user(user_id: int) -> JSONResponse:
"""
Lists all information belonging to one user.
:param user_id: the id of the user
:return: status code and response data
"""
user = _get_db()["users"].find_one({"user_id": user_id})
return JSONResponse(status_code=status.HTTP_200_OK, c... | 12,632 |
def portfolio_averages(
df: pd.DataFrame,
groupvar: str,
avgvars: Union[str, List[str]],
ngroups: int = 10,
byvars: Optional[Union[str, List[str]]] = None,
cutdf: pd.DataFrame = None,
wtvar: Optional[str] = None,
count: Union[str, bool] = False,
portvar: str = "portfolio",
avgonl... | 12,633 |
def TestQuery():
"""Runs a test query against the measurement-lab BigQuery database.
Returns:
(string) The query results formatted as an HTML page.
"""
# Certify BigQuery access credentials.
credentials = AppAssertionCredentials(
scope='https://www.googleapis.com/auth/bigquery')... | 12,634 |
def get_zero_crossing_rate(y, get_mean=True):
"""
Compute the Zero Crossing Rate (ZCR)
:param y: np.ndarray [shape=(n,)]
Sampling rate of y
:param get_mean: bool
Whether to instead return the mean of ZCR over all frames
:return: np.ndarray [shape=(1,t)] or float
ZCR for each frame, or th... | 12,635 |
def parse_arguments():
"""
Parse the command line arguments of the program.
"""
parser = argparse.ArgumentParser(description='Train or test the CRNN model.')
parser.add_argument(
"--train",
action="store_true",
help="Define if we train the model"
)
parser.add_ar... | 12,636 |
def UF9(x):
"""
adapted from
https://github.com/Project-Platypus/Platypus/blob/master/platypus/problems.py
"""
nvars = len(x)
count1 = 0
count2 = 0
count3 = 0
sum1 = 0.0
sum2 = 0.0
sum3 = 0.0
E = 0.1
for j in range(3, nvars+1):
yj = x[j-1] - 2.0*x[1]*ma... | 12,637 |
def run_command(cmd_str, stdin=None, stdout_devnull=False):
"""
run command
"""
cmd = shlex.split(cmd_str)
try:
if stdout_devnull: # for pg_ctl command
with open(os.devnull, 'w') as devnull:
res = subprocess.run(cmd, stdout=devnull)
else:
res ... | 12,638 |
def antiderivate(values, ax_val, index, Nper, is_aper, is_phys, is_freqs):
"""Returns the anti-derivate of values along given axis
values is assumed to be periodic and axis is assumed to be a linspace
Parameters
----------
values: ndarray
array to derivate
ax_val: ndarray
axis v... | 12,639 |
def check_tensor_occupied_memory(t):
"""
this is a reminder function.
"""
print(sys.getsizeof(t.storage())) | 12,640 |
def renumber_labels(label_img):
""" Re-number nuclei in a labeled image so the nuclei numbers are unique and consecutive.
"""
new_label = 0
for old_label in np.unique(label_img):
if not old_label == new_label:
label_img[label_img == old_label] = new_label
new_label += 1
... | 12,641 |
def solve():
"""
PART 1:
You've sneaked into another supply closet - this time, it's across from the prototype suit manufacturing lab. You
need to sneak inside and fix the issues with the suit, but there's a guard stationed outside the lab, so this is
as close as you can safely get.
As you sea... | 12,642 |
async def densenet_xgboost_action_localization(
files: List[UploadFile] = File(...),
weights_densenet: Optional[str] = "denseXgB_model_mylayer",
weights_xgboost: Optional[str] = "recognition_xgboost_prev_frames",
classNames: Optional[str] = "classes",
save_upload_to_file: bool = False,
) -> Any:
... | 12,643 |
def callback():
""" Extract the OAuth code from the callback and exchange it for an
access token.
"""
smart_client = _get_smart()
try:
smart_client.handle_callback(request.url)
except Exception as e:
return """<h1>Authorization Error</h1><p>{}</p><p><a href="/logout">Start over</a></p>""".format(e)
logging.d... | 12,644 |
def __virtual__():
"""
Return virtual name of the module.
:return: The virtual name of the module.
"""
return __virtualname__ | 12,645 |
def after_b(session: Session, operation: Operation, model: SQLClass):
"""
after update it is important to call 'merge' if model is changed in this function
since model is not part of the session
"""
print("***************before_name:", operation.command, model, session)
print(model.comment)
... | 12,646 |
def getsamplev3(qcode):
"""Get a sample object of a given identifier
in API V3 style
Returns: A sample (v3) object
"""
scrit = SampleSearchCriteria()
scrit.withCode().thatEquals(qcode)
fetch_opt = SampleFetchOptions()
fetch_opt.withProperties()
fetch_opt.withSpace()
result = a... | 12,647 |
def test_metadata(base_pkg, field, value):
"""Test metadata is available on base package."""
assert getattr(base_pkg, f"__{field}__") is not None | 12,648 |
def k892_distribution(mass):
"""Calculate normalized relativistic Breit-Wigner distribution value for K(892) at given mass"""
if k892_distribution.norm is None:
k892_distribution.norm = _norm(_k892_distribution_unnormalized)
return _k892_distribution_unnormalized(mass) / k892_distribution.norm | 12,649 |
def ProcessMoleculesUsingSingleProcess(Mols, PAINSPatternMols, Writer, WriterFiltered):
"""Process and filter molecules using a single process."""
NegateMatch = OptionsInfo["NegateMatch"]
OutfileFilteredMode = OptionsInfo["OutfileFilteredMode"]
Compute2DCoords = OptionsInfo["OutfileParams"]["Comput... | 12,650 |
def UDiv(a: BitVec, b: BitVec) -> BitVec:
"""Create an unsigned division expression.
:param a:
:param b:
:return:
"""
return _arithmetic_helper(a, b, z3.UDiv) | 12,651 |
def _pressure_level_widths(tro3_cube, ps_cube, top_limit=0.0):
"""Create a cube with pressure level widths.
This is done by taking a 2D surface pressure field as lower bound.
Parameters
----------
tro3_cube : iris.cube.Cube
`Cube` containing `mole_fraction_of_ozone_in_air`.
... | 12,652 |
def load_model_configurations(sender):
"""
Iterates through setting MODELS_CRUD_EVENT searching for the sender
model configurations.
:param sender: Django Model
:return dict
"""
for model_config in settings.MODELS_CRUD_EVENT:
model = model_config['model']
app, model = model.r... | 12,653 |
def _write_csv_file(file_name,
write_data_points,
write_attributes=None,
as_lat_long=False,
delimiter=','):
"""Write a .csv file."""
points = write_data_points
pointattributes = write_attributes
fd = open(file_name, 'w')
... | 12,654 |
def get_user_by_private_or_public_nickname(nickname: str) -> Optional[User]:
"""
Gets the user by his (public) nickname, based on the option, whether his nickname is public or not
:param nickname: Nickname of the user
:return: Current user or None
"""
user: User = get_user_by_case_insensitive_n... | 12,655 |
def copy_file(
file: File,
path: Union[Path, str],
ledger: Ledger,
overwrite: bool = False,
description: Optional[str] = None,
) -> None:
"""
Copy the file from src into dst.
Args:
file: File object representing the file that will be copied.
path: Path to the destination... | 12,656 |
def expose(window, context, name, monitor):
"""REST HTTP/HTTPS API to view tuples from a window on a stream.
Embeds a Jetty web server to provide HTTP REST access to the collection of tuples in `window` at the time of the last eviction for tumbling windows, or last trigger for sliding windows.
Example wit... | 12,657 |
def get_order_args():
"""
Get order arguments, return a dictionary
{ <VIEW_NAME>: (ORDER_COL, ORDER_DIRECTION) }
Arguments are passed like: _oc_<VIEW_NAME>=<COL_NAME>&_od_<VIEW_NAME>='asc'|'desc'
"""
orders = {}
for arg in request.args:
re_match = re.findall('_oc_(.*)',... | 12,658 |
def certreport(req, *opts):
"""
Generate a report of the certificates (optionally limited by expiration time or key size) found in the selection.
:param req: The request
:param opts: Options (not used)
:return: always returns the unmodified working document
**Examples**
.. code-block:: yaml
- certreport:
... | 12,659 |
async def test_ssdp_not_supported(hass: HomeAssistantType, fritz: Mock):
"""Test starting a flow from discovery with unsupported device."""
fritz().get_device_elements.side_effect = HTTPError("Boom")
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_SSDP}, data=M... | 12,660 |
def version_info(): # pragma: no cover
"""
Get version of nameko_kafka package as tuple
"""
return tuple(map(int, __version__.split('.'))) | 12,661 |
def StrokePathCommandAddCapType(builder, capType):
"""This method is deprecated. Please switch to AddCapType."""
return AddCapType(builder, capType) | 12,662 |
def process_images(dummy_request):
"""Downloads and processes all images uploaded before resize logic fix deployment"""
global n_global_resized
media_bucket = storage_client.bucket(MEDIA_BUCKET)
process_global_images(db_pool, media_bucket)
process_user_images(db_pool, media_bucket)
retur... | 12,663 |
def _filename_pattern(ext):
"""Returns an re matching native or tfrecord files of format `ext`."""
return r".*\.{}(\.tfrecord)?(\.gz)?".format(ext) | 12,664 |
def show_images():
"""
Show samples from each class
"""
(X_train, y_train), (X_test, y_test) = cifar10.load_data()
num_train, img_channels, img_rows, img_cols = X_train.shape
num_test, _, _, _ = X_train.shape
num_classes = len(np.unique(y_train))
class_names = ['airplane', 'automobile',... | 12,665 |
def assemble_remote_url():
"""
组装目标服务器URL, 即生成 parse.remote_url 的值
:rtype: str
"""
if parse.is_external_domain:
# 请求的是外部域名 (external domains)
scheme = 'https://' if parse.is_https else 'http://'
return urljoin(scheme + parse.remote_domain, parse.remote_path_query)
else:
... | 12,666 |
def test_add_colormap(attribute):
"""Test directly adding a vispy Colormap object"""
shape = (10, 2)
np.random.seed(0)
data = 20 * np.random.random(shape)
annotations = {'point_type': _make_cycled_properties([0, 1.5], shape[0])}
color_kwarg = f'{attribute}_color'
colormap_kwarg = f'{attribu... | 12,667 |
def test_runClean() -> None:
"""Run `buildnis` with the argument `--clean` to remove generated build data"""
with pytest.raises(expected_exception=SystemExit) as excp:
runBuildnis(["--clean"])
assert excp.value.args[0] == 0 | 12,668 |
def register_blueprints(app):
"""Register Flask blueprints."""
app.register_blueprint(public.views.blueprint)
app.register_blueprint(drawbot.views.blueprint)
app.register_blueprint(user.views.blueprint)
return None | 12,669 |
def figure() -> None:
"""Helper to create new figure"""
plt.close()
plt.figure(figsize=(10, 3)) | 12,670 |
def write_attribute(xml_elem, elem: str=None, attrib: str=None, txt: str=None):
""" Write new text to a xml attribute.
Elem can be used to refer to a subelement of the current xml_elem
Args:
xml_elem: The current xml element
elem (str): The requested element tag name
attrib (str): ... | 12,671 |
def _ndarray_feature(x: np.ndarray) -> tf.train.Feature:
"""Create an ndarray feature stored as bytes."""
x_bytes = x.tostring()
feature = tf.train.Feature(bytes_list=tf.train.BytesList(value=[x_bytes]))
return feature | 12,672 |
def get_img_compliance_level(profile):
""" Try to figure out the IIIF Image API compliance level given the
`profile` value from a info.json.
"""
patt_iiif = re.compile('level([0-2])\.json$')
patt_stan = re.compile('#level([0-2])$')
def get_from_str(s):
m = None
if 'http://i... | 12,673 |
def _extract_protocol_layers(deserialized_data):
"""
Removes unnecessary values from packets dictionaries.
:param deserialized_data: Deserialized data from tshark.
:return: List of filtered packets in dictionary format.
"""
packets_filtered = []
for packet in deserialized_data:
... | 12,674 |
def collect_examples():
"""
Collects test designs that have readme files and converts them for
documentation examples.
"""
# Base directory for tests
tests_dir = os.path.abspath(
os.path.join(
os.path.dirname(__file__),
"../tests"
)
)
# Base dire... | 12,675 |
def calculate_affinity(
adata: AnnData,
level: int = 1,
block_key: Optional[str] = 'nsbm',
group_by: Optional[str] = None,
state: Optional = None,
neighbors_key: Optional[str] = 'neighbors',
adjacency: Optional[sparse.spmatrix] = None,
directed: bool = False,
use_weights: bool = Fals... | 12,676 |
async def scrape_website(client):
"""
:param client: client bot is connected to
:return: only if there's an issue
Type '!scrape' to restart the scraping process.
Note: this function is executed on bot_ready, so
I have to work around not having a convenient
guild object.
r """
debug... | 12,677 |
def _check_spot_bid(spot_bid, spot_history):
"""
Prevents users from potentially over-paying for instances
Note: this checks over the whole region, not a particular zone
:param spot_bid: float
:type spot_history: list[SpotPriceHistory]
:raises UserError: if bid is > 2X the spot price's avera... | 12,678 |
def numpy_dtypes_for_minmax(request):
"""
Fixture of numpy dtypes with min and max values used for testing
cummin and cummax
"""
dtype = request.param
min_val = (
np.iinfo(dtype).min if np.dtype(dtype).kind == "i" else np.finfo(dtype).min
)
max_val = (
np.iinfo(dtype).max... | 12,679 |
def solve(topics):
"""Solve."""
a_words, b_words = get_dicts(topics)
candidates = []
original = []
duplicates = []
for a, b in topics:
# print(a, b)
# print(a_words[a], b_words[b])
if not (a_words[a] == 1 or b_words[b] == 1):
candidates.append((a, b))
... | 12,680 |
def mock_jobflow_settings(memory_jobstore):
"""Mock the jobflow settings to use our specific jobstore (with data store)."""
from unittest import mock
from jobflow.settings import JobflowSettings
settings = JobflowSettings(JOB_STORE=memory_jobstore)
with mock.patch("jobflow.SETTINGS", settings):
... | 12,681 |
def get_package_plugin(package_type):
"""
Get a plugin for a specific package
Parameters
----------
package_type: str
The package type to fetch
Returns
-------
InvirtualEnvPlugin:
The invirtualenv plugin for the specific package_type
"""
for plugin in installed_... | 12,682 |
def _type_annotation(
node: ast.AST, atok: asttokens.ASTTokens
) -> Tuple[Optional[TypeAnnotation], Optional[Error]]:
"""Parse the type annotation."""
if isinstance(node, ast.Name):
return AtomicTypeAnnotation(identifier=Identifier(node.id), node=node), None
elif isinstance(node, ast.Constant):... | 12,683 |
def validate_basic_message(msg):
"""Validate basic messages.
This example just uses basic assertions but you could easily use a schema
library to get more sophisticated validators.
"""
assert msg.type == TYPE
assert "~l10n" in msg
assert "sent_time" in msg
assert "content" in msg
re... | 12,684 |
def _filter_event_queryset(queryset, params, srs=None):
"""
Filter events queryset by params
(e.g. self.request.query_params in EventViewSet)
"""
# Filter by string (case insensitive). This searches from all fields
# which are marked translatable in translation.py
val = params.get('text', No... | 12,685 |
def process_user(enrollment, section):
"""Handle getting assignments for a single user
Args:
enrollment (canvasapi.enrollment.Enrollment): Canvas <Enrollment> object
section (canvasapi.section.Section): Canvas <Section> object
Returns:
[list]: formatted list for writing to the CSV
... | 12,686 |
def op(name,
data,
bucket_count=None,
display_name=None,
description=None,
collections=None):
"""Create a histogram summary op.
Arguments:
name: A unique name for the generated summary node.
data: A `Tensor` of any shape. Must be castable to `float64`.
bucket_count: O... | 12,687 |
def fix_target_not_found(issue: issues.TargetNotFound, tree: Tree, patches: Patches,
opt: options.Options) -> None:
"""Fix a `TargetNotFound` issue. The result of this function's successful run is a patch
added to `patches`.
"""
if opt.mode == '-i':
__fix_target_not_f... | 12,688 |
def doc_iter(limit=None):
"""iterate over all documents (doc = single paragraph)"""
from itertools import islice
for path in islice(list_data_files(),limit):
yield from json_to_docs(path) | 12,689 |
def read_as_str(file):
"""
读取文件,并返回读取到的内容
"""
try:
with open(file, 'r') as f:
return f.read()
except IOError:
return "" | 12,690 |
def test_normalize_text(name: str, expected_output: str) -> None:
"""It normalizes the text."""
assert converter.normalize_text(name) == expected_output | 12,691 |
def has_xml_header(filepath):
"""
Return True if the first line of the file is <?xml
:param filepath:
:return:
"""
return True | 12,692 |
def shikaku(givens):
"""Solver for Shikaku minipuzzles."""
sym = grilops.make_number_range_symbol_set(0, SIZE * SIZE - 1)
sg = grilops.SymbolGrid(LATTICE, sym)
rc = grilops.regions.RegionConstrainer(
LATTICE,
solver=sg.solver,
rectangular=True
)
shifter = Shifter(sg.solver)
for p in LAT... | 12,693 |
def parse_arguments(args_to_parse):
"""Parse the command line arguments.
Parameters
----------
args_to_parse: list of str
Arguments to parse (split on whitespaces).
"""
description = "PyTorch implementation of CNN's for Human Activity Recognition"
default_config = get... | 12,694 |
def test_create_key_pair_file(tmpdir):
"""Tests create_key_pair_file"""
from apyfal._utilities import create_key_pair_file
import apyfal._utilities as _utl
tmp_dir = tmpdir.dirpath()
ssh_dir = tmp_dir.join('.ssh')
key_pair = 'key_pair'
key_content = 'key_content'
# Mock SSH path
ut... | 12,695 |
def invert_qgniw(qh,phi,phih,k,l,f0):
""" Calculate the streamfunction given the potential vorticity.
The algorithm is:
1) Calculate wave potential vorticity
2) Invert for wave, pw, and vortex stremfunctions, pv.
3) Calculate the geostrophic stremfunction... | 12,696 |
def package_ref_key(package_name, ref):
"""Returns ndb.Key corresponding to particular PackageRef."""
assert is_valid_package_ref(ref), ref
return ndb.Key(PackageRef, ref, parent=package_key(package_name)) | 12,697 |
def conv2d_backprop_input(dout, x_size, weight, stride=1, pad=0):
"""Backpropagation input for conv2d."""
filter_num, _, filter_h, filter_w = weight.shape
dout = dout.transpose(0, 2, 3, 1).reshape(-1, filter_num)
col_w = weight.reshape(filter_num, -1).T
dcol = np.dot(dout, col_w.T)
dx = col2im(d... | 12,698 |
def get_feeds_from_url(url: str) -> list:
"""
Try to parse the URL and find any RSS feeds in the webpage
Adapted from: https://gist.github.com/alexmill/9bc634240531d81c3abe
"""
logger.info(f"Attempting to find RSS feeds from {url}...")
# If the URL itself is a proper RSS feed, just return it
... | 12,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.