content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def other_ops(request):
"""
Other Operations View
"""
args = {
'pending': OtherOperation.objects.filter(status=0).count(),
'active': OtherOperation.objects.filter(status=1).count(),
'done': OtherOperation.objects.filter(status=2).count(),
'cancelled': OtherOperation.objec... | 35,900 |
def verify_input_values(input_values, timeout='0'):
"""Verify input fields have given values.
Accepts a .txt file or Robot FW dictionary as a parameter. If using a text file, the locator
and the expected value should be separated with a comma on each row.
Examples
--------
.. code-block:: robo... | 35,901 |
def distance_point_2_line(point, seg):
"""Finds the minimum distance and closest point between a point and a line
Args:
point ([float, float]): (x,y) point to test
seg ([[float, float], [float, float]]): two points defining the line
Returns:
A list of two items:
* Distance ... | 35,902 |
def load_glove_from_file(glove_filepath):
"""
Load the GloVe embeddings
Args:
glove_filepath (str): path to the glove embeddings file
Returns:
word_to_index (dict), embeddings (numpy.ndarary)
"""
word_to_index = {}
embeddings = []
with open(glove_filepath, "r") as fp:
... | 35,903 |
def save_tabbed_lines(array, path, encode=True):
""" Writes lines from array to path
array: assumes to be an array of arrays
path: path to write to
"""
check_dir(os.path.dirname(path))
concatenated_array= list(map(lambda s: "\t".join(s), array))
# Open a file in write mode
with open(path, "w") as fo:
suc... | 35,904 |
def make_pd(space: gym.Space):
"""Create `ProbabilityDistribution` from gym.Space"""
if isinstance(space, gym.spaces.Discrete):
return CategoricalPd(space.n)
elif isinstance(space, gym.spaces.Box):
assert len(space.shape) == 1
return DiagGaussianPd(space.shape[0])
elif isinstance... | 35,905 |
def download_file_from_google_drive(
gdrive_file_id: typing.AnyStr,
destination: typing.AnyStr,
chunk_size: int = 32768
) -> typing.AnyStr:
"""
Downloads a file from google drive, bypassing the confirmation prompt.
Args:
gdrive_file_id: ID string of the file to download from... | 35,906 |
def attach(func, params):
"""
Given a function and a namespace of possible parameters,
bind any params matching the signature of the function
to that function.
"""
sig = inspect.signature(func)
params = Projection(sig.parameters.keys(), params)
return functools.partial(func, **params) | 35,907 |
def question_route():
"""
題庫畫面
"""
# 取得使用者物件
useruid = current_user.get_id()
# 嘗試保持登入狀態
if not keep_active(useruid):
logout_user()
return question_page(useruid) | 35,908 |
async def test_config_file_passed_to_config_entry(hass):
"""Test that configuration file for a host are loaded via config entry."""
with patch.object(hass, 'config_entries') as mock_config_entries, \
patch.object(deconz, 'configured_hosts', return_value=[]), \
patch.object(deconz, 'load_... | 35,909 |
def generate_qrcode(url: str, should_cache: bool = True) -> str:
"""
Generate a QR code (as data URI) to a given URL.
:param url: the url the QR code should reference
:param should_cache: whether or not the QR code should be cached
:return: a data URI to a base64 encoded SVG image
"""
if sh... | 35,910 |
def print_green(msg: str = None) -> None:
"""Print message to STDOUT in yellow text.
:param msg: {str} - the message to be printed
"""
if msg is None:
raise Exception("msg was not defined")
print(Fore.GREEN + msg)
print(Style.RESET_ALL + "", end="") | 35,911 |
def _process_environment_variables():
"""Process environment variables"""
# pylint: disable=C0103
global parameters
# pylint: enable=C0103
if "STRINGS_DEBUG" in os.environ:
logging.disable(logging.NOTSET)
if "FLAVOUR" in os.environ:
parameters["Command flavour"] = os.environ["F... | 35,912 |
def get_conflict_fks_versions(obj, version, revision, exclude=None):
"""
Lookup for deleted FKs for obj, expects version to be obj
version from the same revision.
If exclude provided - excludes based on that from versions to check.
Expects exclude to be a dict of filter string, value i.e {'pk': 1}.
... | 35,913 |
def create_tbls(conn, c):
""" Create tables """
# dictionary table
sql = """ CREATE TABLE IF NOT EXISTS glossary (
id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
verb TEXT UNIQUE,
explanation TEXT,
date_created TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
);"""
... | 35,914 |
def hz2mel(f):
"""Convert an array of frequency in Hz into mel."""
return 1127.01048 * np.log(f/700 +1) | 35,915 |
def fetchallpages():
"""Fetches all wikipedia date pages one by one saves them on the disk"""
months = range(1,13)
print("Fetching Wiki Pages")
for month in months:
fetchmonth(month)
# map(fetchmonth, months) | 35,916 |
def Logica(line, cell, run_query):
"""Running Logica predicates and storing results."""
predicates = ParseList(line)
if not predicates:
ShowError('No predicates to run.')
return
try:
program = ';\n'.join(s for s in [PREAMBLE, cell] if s)
parsed_rules = parse.ParseFile(program)['rule']
except p... | 35,917 |
def set_address_bitmap(manager_bitmap, address):
"""
Sets the pvscan0 of the worker to the address we want to read/write later through the manager_bitmap
@param manager_bitmap: handle to the manager bitmap
@param address: the address to be set in worker bitmap's pvscan0 pointer
"""
address = c_ulonglong(address)
... | 35,918 |
def figure(figsize=None, logo="iem", title=None, subtitle=None, **kwargs):
"""Return an opinionated matplotlib figure.
Parameters:
figsize (width, height): in inches for the figure, defaults to something
good for twitter.
dpi (int): dots per inch
logo (str): Currently, 'iem', 'dep' is... | 35,919 |
def run_epoch(session, model, eval_op=None, verbose=False):
"""Runs the model on the given data."""
costs = 0.0
iters = 0
state = session.run(model.initial_state)
fetches = {
"cost": model.cost,
"final_state": model.final_state,
"accuracy":model.accuracy,
"y_new":mo... | 35,920 |
def is_scoo(x: Any) -> bool:
"""check if an object is an `SCoo` (a SAX sparse S-matrix representation in COO-format)"""
return isinstance(x, (tuple, list)) and len(x) == 4 | 35,921 |
def createNonce():
"""Creates a new nonce and stores it in the session."""
nonce = base64.b64encode(os.urandom(32))
flask_session['nonce'] = nonce
return nonce | 35,922 |
def project_rename_folder(object_id, input_params={}, always_retry=False, **kwargs):
"""
Invokes the /project-xxxx/renameFolder API method.
For more info, see: https://documentation.dnanexus.com/developer/api/data-containers/folders-and-deletion#api-method-class-xxxx-renamefolder
"""
return DXHTTPR... | 35,923 |
def full(shape, fill_value, dtype=None):
"""Returns a new array of given shape and dtype, filled with a given value.
This function currently does not support ``order`` option.
Args:
shape (tuple of ints): Dimensionalities of the array.
fill_value: A scalar value to fill a new array.
... | 35,924 |
def is_seq(a):
"""Return `True` if `a` is a Z3 sequence expression.
>>> print (is_seq(Unit(IntVal(0))))
True
>>> print (is_seq(StringVal("abc")))
True
"""
return isinstance(a, SeqRef) | 35,925 |
def identity(__obj: T, /) -> T:
"""Identity function"""
return __obj | 35,926 |
def lines_in_file(filename: str) -> int:
"""
Count the number of lines in a file
:param filename: A string containing the relative or absolute path to a file
:returns: The number of lines in the file
"""
with open(filename, "r") as f:
return len(f.readlines()) | 35,927 |
def readargs():
"""
Read input arguments if run as separate program
Returns
-------
None.
"""
parser = argparse.ArgumentParser(description=(
'Convert data from WiPL format to binary SimRadar-compatible format.'
))
parser.add_argument('input',
... | 35,928 |
def make(tag):
"""Create a tag window, representing the given pre-existing tag."""
construct()
gui.cue_top()
gui.title("Panthera: Tag: "+tag)
rec_to_window(tagrecords.find(tag))
gui.cue("$top.tag_frame.widget")
gui.text_ro() | 35,929 |
async def test_gw_query_inst_cc(query_cc, gateway, org1_user, peer):
""" Tests Gateway().query_instantiated_chaincodes """
await _assert_gw_required(
gateway, lambda gw: gw.query_instantiated_chaincodes(),
['channel', 'requestor', 'endorsing_peers']
)
res = await gateway.query_instanti... | 35,930 |
def validate_input_parameters(live_parameters, original_parameters):
"""Return validated input parameters."""
parsed_input_parameters = dict(live_parameters)
for parameter in parsed_input_parameters.keys():
if parameter not in original_parameters:
click.echo(
click.style(... | 35,931 |
def _upper_zero_group(match: ty.Match, /) -> str:
"""
Поднимает все символы в верхний
регистр у captured-группы `let`. Используется
для конвертации snake_case в camelCase.
Arguments:
match: Регекс-группа, полученная в результате `re.sub`
Returns:
Ту же букву из группы, но в верхн... | 35,932 |
def _concatenate_shapes(shapes, axis):
"""Given array shapes, return the resulting shape and slices prefixes.
These help in nested concatenation.
Returns
-------
shape: tuple of int
This tuple satisfies:
```
shape, _ = _concatenate_shapes([arr.shape for shape in arrs], axis)... | 35,933 |
def md_changes(seq, md_tag):
"""Recreates the reference sequence of a given alignment to the extent that the
MD tag can represent.
Note:
Used in conjunction with `cigar_changes` to recreate the
complete reference sequence
Args:
seq (str): aligned segment sequence
md_tag... | 35,934 |
def start_board(stop_area_id):
"""Update a departure board with departures at station STOP_AREA_ID.
Use search to find the STOP_AREA_ID for a station."""
try:
sncf.check_params(stop_area_id)
except commons.SncfException as e:
logger.error("error: %s", str(e))
# start board
boa... | 35,935 |
def _get_partitions(dev):
"""Return partition information (num, size, type) for a device."""
dev_path = utils.make_dev_path(dev)
out, _err = utils.execute('parted', '--script', '--machine',
dev_path, 'unit s', 'print',
run_as_root=True)
lines = [... | 35,936 |
def ping(target, mode="4"):
"""PING a.fi (193.166.4.1) 56(84) bytes of data.
--- a.fi ping statistics ---
10 packets transmitted, 10 received, 0% packet loss, time 8996ms
rtt min/avg/max/mdev = 17.395/23.978/34.866/5.381 ms"""
p = subprocess.Popen(["ping", "-q", "-c", "10", "-%s" % mode, target], st... | 35,937 |
def sort_singlepulse(basename, directory=os.getcwd(), verbose=False):
"""
Accepts the base name (usually Observation ID) and the directory where the relevant files are located.
If no directory argument is given, assumes all files are in current working directory (via os.getcwd())
Creates a total singl... | 35,938 |
def forwards_func(apps, schema_editor):
"""
move relation shit from sponsorship->org to org->sponsorship
to allow a many orgs to many sponsorship relation
"""
Sponsorship = apps.get_model("peeringdb_server", "Sponsorship")
SponsorshipOrganization = apps.get_model(
"peeringdb_server", "Sp... | 35,939 |
def test_get_all_subscriptions(controller: Controller, owner: str):
"""Check that Controller returned correct list of Subscription objects:
- No _id specified in each subscription
- type is not dict, but Subscription
- start_date field type is not datetime, but date
"""
result = cont... | 35,940 |
def interest_coverage_ratio():
"""Interest Coverage Ratio"""
x = float(input("Please Enter Net Income Value: "))
y = float(input("Please Enter Income Tax Expense Value: "))
z = float(input("Please Enter Interest Expense Value: "))
eb = float(x)+float(y)+float(z)
s = (float(x)+float(y)+floa... | 35,941 |
def get_cs_token(accesskey="",secretkey="",identity_url="",tenant_id=""):
"""
Pass our accesskey and secretkey to keystone for tokenization.
"""
identity_request_json = json.dumps({
'auth' : {
'apiAccessKeyCredentials' : {
'accessKey' : accesskey,
'secretKey' : secretkey
},
"tenantId": tenant_i... | 35,942 |
def get_auto_scaling_group(asg, asg_name: str):
"""Get boto3 Auto Scaling Group by name or raise exception"""
result = asg.describe_auto_scaling_groups(AutoScalingGroupNames=[asg_name])
groups = result["AutoScalingGroups"]
if not groups:
raise Exception("Auto Scaling Group {} not found".format(a... | 35,943 |
def guiraud_r(txt_len: int, vocab_size: int) -> np.float64:
"""
The TTR formula underwent simple corrections: RTTR (root type-token ratio), Guiraud, 1960.
"""
return vocab_size / np.sqrt(txt_len) | 35,944 |
def serialize_dagster_namedtuple(nt: tuple, **json_kwargs) -> str:
"""Serialize a whitelisted named tuple to a json encoded string"""
check.tuple_param(nt, "nt")
return _serialize_dagster_namedtuple(nt, whitelist_map=_WHITELIST_MAP, **json_kwargs) | 35,945 |
def test_footprint_antimeridian(benchmark):
"""
When a polygon crosses the antimeridian, check that it's translated correctly.
"""
overview = _create_overview()
footprint_latlon = benchmark(lambda: overview.footprint_wgs84)
assert_shapes_mostly_equal(footprint_latlon, EXPECTED_CLEAN_POLY, 0.1) | 35,946 |
def join_epiweek(year, week):
""" return an epiweek from the (year, week) pair """
return year * 100 + week | 35,947 |
def add_data_associations(db, data_id, tree_identifier, folder_path, profile_id, user_group_id):
"""Creates associations to the active user profile
and personal user group for the given data.
Args:
db (object): The db object
data_id (int): The id of the data
tree_identifier (str)... | 35,948 |
def get_or_create_api_key(datastore: data_store.DataStore,
project_id: str) -> str:
"""Return API key of existing project or create a new project and API key.
If the project exists, return its API key, otherwise create a new project
with the provided project ID and return its API key.
... | 35,949 |
def map_cosh(process):
"""
"""
return map_default(process, 'cosh', 'apply') | 35,950 |
def deploy_mydaemon():
"""Update uwsgi master config conf/pydaemon.service, then restart"""
sudo("systemctl stop pydaemon", warn_only=True)
put("conf/pydaemon.service", "/etc/systemd/system/", use_sudo=True)
sudo("systemctl enable pydaemon")
sudo("systemctl daemon-reload")
sudo("systemctl sta... | 35,951 |
def fs(func):
"""
This is the decorator which performs recursive AST substitution of
functions, and optional JIT-compilation using `numba`_.
This must only be used on functions with positional parameters
defined; this must not be used on functions with keyword parameters.
This decorator modifi... | 35,952 |
def cleanline(line):
"""去除讀入資料中的換行符與 ',' 結尾
"""
line = line.strip('\n')
line = line.strip(',')
return line | 35,953 |
def convert_contrib_box_nms(node, **kwargs):
"""Map MXNet's _contrib_box_nms operator to ONNX
"""
from onnx.helper import make_node
name, input_nodes, attrs = get_inputs(node, kwargs)
input_dtypes = get_input_dtypes(node, kwargs)
dtype = input_dtypes[0]
#dtype_t = onnx.mapping.NP_TYPE_TO_TE... | 35,954 |
def fill76(text):
"""Any text. Wraps the text to fit in 76 columns."""
return fill(text, 76) | 35,955 |
def current_object(cursor_offset, line):
"""If in attribute completion, the object on which attribute should be
looked up."""
match = current_word(cursor_offset, line)
if match is None:
return None
start, end, word = match
matches = current_object_re.finditer(word)
s = ""
for m i... | 35,956 |
def scheduled_job(process=dash_app_process):
"""Schedule a job."""
print('This job is run every weekday at 5pm.')
print('Kill process of a Dash app')
os.killpg(os.getpgid(process.pid), signal.SIGTERM)
cmd = "python3 itcfinally2.py"
subprocess.call(cmd, shell=True)
print('Create a new process... | 35,957 |
def download_zip(url: str) -> BytesIO:
"""Download data from url."""
logger.warning('start chromium download.\n'
'Download may take a few minutes.')
# disable warnings so that we don't need a cert.
# see https://urllib3.readthedocs.io/en/latest/advanced-usage.html for more
urllib... | 35,958 |
def test_nested_condition() -> None:
"""Test a nested condition. """
@argcomb(Or(And("a", "b"), And("c", "d")))
def f(a: Any = None, b: Any = None, c: Any = None, d: Any = None) -> None:
...
# valid
f(a=1, b=1)
f(c=1, d=1)
f(a=1, b=1, c=1, d=1)
# invalid
with pytest.raises... | 35,959 |
def test_handle_requiressl_in_priv_string(input_tuple, output_tuple):
"""Tests the handle_requiressl_in_priv_string funciton."""
assert handle_requiressl_in_priv_string(MagicMock(), *input_tuple) == output_tuple | 35,960 |
def _is_match(option, useful_options, find_perfect_match):
"""
returns True if 'option' is between the useful_options
"""
for useful_option in useful_options:
if len(option) == sum([1 for o in option if o in useful_option]):
if not find_perfect_match or len(set(useful_option)) == len... | 35,961 |
def pass_aligned_filtering(left_read, right_read, counter):
"""
Test if the two reads pass the additional filters such as check for soft-clipped end next to the variant region,
or overlapping region between the two reads.
:param left_read: the left (or 5') most read
:param right_read: the right (or ... | 35,962 |
def load_metaconfig(file_path):
""" Loads a single metaconfig file and returns variable to expression dictionary """
definitions = OrderedDict()
if os.path.isfile(file_path):
with open(file_path) as f:
for line in [l.strip(os.linesep).strip() for l in f.readlines()]:
# sk... | 35,963 |
def detect_slow_oscillation(data: Dataset, algo: str = 'AASM/Massimini2004', start_offset: float = None) -> pd.DataFrame:
"""
Detect slow waves (slow oscillations) locations in an edf file for each channel
:param edf_filepath: path of edf file to load. Will maybe work with other filetypes. untested.
:pa... | 35,964 |
def _map_channels_to_measurement_lists(snirf):
"""Returns a map of measurementList index to measurementList group name."""
prefix = "measurementList"
data_keys = snirf["nirs"]["data1"].keys()
mls = [k for k in data_keys if k.startswith(prefix)]
def _extract_channel_id(ml):
return int(ml[len... | 35,965 |
def is_not_applicable_for_questionnaire(
value: QuestionGroup, responses: QuestionnaireResponses
) -> bool:
"""Returns true if the given group's questions are not answerable for the given responses.
That is, for all the questions in the given question group, only not
applicable answers have been provid... | 35,966 |
def _chebnodes(a,b,n):
"""Chebyshev nodes of rank n on interal [a,b]."""
if not a < b:
raise ValueError('Lower bound must be less than upper bound.')
return np.array([1/2*((a+b)+(b-a)*np.cos((2*k-1)*np.pi/(2*n))) for k in range(1,n+1)]) | 35,967 |
def test_1(test_1_fixture):
"""First test case."""
# store and remove the last item in dictionary.
norm_q_2_true = test_1_fixture.popitem()
p_measures = partial(mc_quantile_measures, **test_1_fixture)
for estimator, n_draws, decimal in zip(
["DLR", "DLR", "DLR", "DLR", "brute force"],
... | 35,968 |
def delcolumn(particles, columns, metadata):
"""
With dataframes, stating dataframe1 = dataframe2 only creates
a reference. Therefore, we must create a copy if we want to leave
the original dataframe unmodified.
"""
nocolparticles = particles.copy()
#Loop through each passed column... | 35,969 |
def Rx_matrix(theta):
"""Rotation matrix around the X axis"""
return np.array([
[1, 0, 0],
[0, np.cos(theta), -np.sin(theta)],
[0, np.sin(theta), np.cos(theta)]
]) | 35,970 |
def spawn_actor(world: carla.World, blueprint: carla.ActorBlueprint, spawn_point: carla.Transform,
attach_to: carla.Actor = None, attachment_type=carla.AttachmentType.Rigid) -> carla.Actor:
"""Tries to spawn an actor in a CARLA simulator.
:param world: a carla.World instance.
:param ... | 35,971 |
def partition(lst, size):
"""Partition list @lst into eveni-sized lists of size @size."""
return [lst[i::size] for i in range(size)] | 35,972 |
def splitFile(file, chunk = 65536, count = 3, lanes = ('hi', 'lo')):
"""Split a ROM file from disk.
See splitRom() arguments.
"""
base, ext = splitName(file)
rom = splitRom(open(file, 'rb').read(), chunk, count, lanes)
for n in rom: open(F"{base}-{n}{ext}", 'wb').write(rom[n]) | 35,973 |
def form_errors_json(form=None):
"""It prints form errors as JSON."""
if form:
return mark_safe(dict(form.errors.items())) # noqa: S703, S308
return {} | 35,974 |
def test_text_handler(regexp, origin, postfix, expected):
"""Test text data handling."""
handler = get_text_handler(re.compile(regexp), postfix)
assert handler(origin) == expected | 35,975 |
def test_find_all_user_authorizations_for_empty(session): # pylint:disable=unused-argument
"""Test with invalid user id and assert that auth is None."""
user = factory_user_model()
org = factory_org_model('TEST')
factory_membership_model(user.id, org.id)
authorizations = Authorization.find_all_aut... | 35,976 |
def echo_bold(message):
"""Write a message in bold (if supported).
Args:
message (string): message to write in bold.
"""
_get_mfutil().mfutil_echo_bold(message.encode('utf8')) | 35,977 |
def get_semantic_ocs_version_from_config():
"""
Returning OCS semantic version from config.
Returns:
semantic_version.base.Version: Object of semantic version for OCS.
"""
return get_semantic_version(config.ENV_DATA["ocs_version"], True) | 35,978 |
def test_pop(doubly_list):
"""Test error for pop of empty list."""
doubly_list.push(1)
assert doubly_list.pop() == 1 | 35,979 |
def do_smooth(fileIn, fileOut, N=3, Wn=1e-3):
"""
Сглаживание с использованием фильтра Баттерворта.
Параметры:
fileIn - имя входного файла. Тип - str.
fileOut - имя выходного файла. Тип - str.
N - порядок фильтра (точность). Тип - int.
Wn - частота Найквиста (половин... | 35,980 |
def leanlauncher_launch_online(version, options):
"""
Launches the specified version of the game in online mode.
Parameters:
version (str): the version of the game to launch
options (Dictionary): used to specify login options for the game
"""
command = minecraft_launcher_lib.command.get_minecraft_co... | 35,981 |
def train_rl(
*,
_run: sacred.run.Run,
_seed: int,
total_timesteps: int,
normalize: bool,
normalize_kwargs: dict,
reward_type: Optional[str],
reward_path: Optional[str],
rollout_save_final: bool,
rollout_save_n_timesteps: Optional[int],
rollout_save_n_episodes: Optional[int],... | 35,982 |
def get_non_ntile_cols(frame: pd.DataFrame) -> List[str]:
"""
:param frame: data frame to get columns of
:return: all columns in the frame that dont contain 'Ntile'
"""
return [col for col in frame.columns if 'Ntile' not in col] | 35,983 |
def deserialize_date(value: Any) -> Optional[datetime.datetime]:
"""A flexible converter for str -> datetime.datetime"""
if value is None:
return None
if isinstance(value, datetime.datetime):
return value
if isinstance(value, str):
# datetime.datetime.fromisoformat(...) can't pa... | 35,984 |
def watch_directory():
"""Watch directory by recursing into it every EVERY_SECONDS_WATCH.
Compare size and mtimes between periods. Is responsible for converting on startup.
"""
log = logging.getLogger(__name__)
previous_hash = None
array = bytearray()
ramp_up = list(range(EVERY_SECONDS_WATC... | 35,985 |
def intersect(x1, x2, y1, y2, a1, a2, b1, b2):
""" Return True if (x1,x2,y1,y2) rectangles intersect. """
return overlap(x1, x2, a1, a2) & overlap(y1, y2, b1, b2) | 35,986 |
def BestEffort(func):
"""Decorator to log and dismiss exceptions if one if already being handled.
Note: This is largely a workaround for the lack of support of exception
chaining in Python 2.7, this decorator will no longer be needed in Python 3.
Typical usage would be in |Close| or |Disconnect| methods, to d... | 35,987 |
def recording_to_chunks(fingerprints: np.ndarray,
samples_per_chunk: int) -> List[np.ndarray]:
"""Breaks fingerprints of a recording into fixed-length chunks."""
chunks = []
for pos in range(0, len(fingerprints), samples_per_chunk):
chunk = fingerprints[pos:pos + samples_per_... | 35,988 |
def coset_enumeration_c(fp_grp, Y):
"""
>>> from sympy.combinatorics.free_group import free_group
>>> from sympy.combinatorics.fp_groups import FpGroup, coset_enumeration_c
>>> F, x, y = free_group("x, y")
>>> f = FpGroup(F, [x**3, y**3, x**-1*y**-1*x*y])
>>> C = coset_enumeration_c(f, [x])
... | 35,989 |
def slr_pulse(
num=N, time_bw=TBW,
ptype=PULSE_TYPE, ftype=FILTER_TYPE,
d_1=PBR, d_2=SBR,
root_flip=ROOT_FLIP,
multi_band = MULTI_BAND,
n_bands = N_BANDS,
phs_type = PHS_TYPE,
band_sep = BAND_SEP
):
"""Use Shinnar-Le Roux algorithm to generate pulse"""
if root_... | 35,990 |
def test_user_not_banned(fixture_message):
"""Test user is not banned."""
message = fixture_message
assert message.banned is False | 35,991 |
def policy_options(state, Q_omega, epsilon=0.1):
""" Epsilon-greedy policy used to select options """
if np.random.uniform() < epsilon:
return np.random.choice(range(Q_omega.shape[1]))
else:
return np.argmax(Q_omega[state]) | 35,992 |
def test_input2() -> None:
""" Test with input """
run_test(['Hello', 'there'], './tests/expected/hello2.txt') | 35,993 |
def test_auto_repr(sample):
"""
Test that the symmetry group created with the automatic representation matrix
is the matches a reference.
"""
pos_In = (0, 0, 0) # pylint: disable=invalid-name
pos_As = (0.25, 0.25, 0.25) # pylint: disable=invalid-name
orbitals = []
for spin in (sr.SPIN... | 35,994 |
def test_ps_s3_creation_triggers_on_master():
""" test object creation s3 notifications in using put/copy/post on master"""
if skip_push_tests:
return SkipTest("PubSub push tests don't run in teuthology")
hostname = get_ip()
proc = init_rabbitmq()
if proc is None:
return SkipTest('e... | 35,995 |
def weights_init(init_type='gaussian'):
"""
from https://github.com/naoto0804/pytorch-inpainting-with-partial-conv/blob/master/net.py
"""
def init_fun(m):
classname = m.__class__.__name__
if (classname.find('Conv') == 0 or classname.find(
'Linear') == 0) and hasattr(m, 'w... | 35,996 |
def title(default=None, level="header"):
"""
A decorator that add an optional title argument to component.
"""
def decorator(fn):
loc = get_argument_default(fn, "where", None) or st
@wraps(fn)
def wrapped(
*args,
title=default,
level=level,
... | 35,997 |
def get_ext(path):
"""
Given a path return the file extension.
**Positional Arguments:**
path: The file whose path we assess
"""
return os.path.splitext(path)[1] | 35,998 |
def _rect_to_css(rect):
"""
Convert a dlib 'rect' object to a plain tuple in (top, right, bottom, left) order
:param rect: a dlib 'rect' object
:return: a plain tuple representation of the rect in (top, right, bottom, left) order
"""
return rect.top(), rect.right(), rect.bottom(), rect.left... | 35,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.