content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def pop(snippet, N):
"""
>>> pop('abc')
['abc']
>>> pop('abc+def')
['abc', 'def']
>>> pop('abc$def+ghi')
['abc+def', 'ghi']
"""
def replace(s):
for s1, s2 in reversed(list(zip(SEPARATORS[N+1:], SEPARATORS[N:]))):
s = s.replace(s1, s2)
return s
return [... | 68,600 |
def access_token_list(
ctx: typer.Context, web: bool = typer.Option(False, help="open upm in web browser after showing info"),
):
"""lists all access tokens for the instance"""
try:
upm = UpmCloudApi(ctx.obj.get("base_url"))
access_tokens = upm.list_access_token()
except requests.excepti... | 68,601 |
def validate_metadata(metadata, parameters):
"""validate metatdata.
Ensure metadata references parameter workload_context,
and that it is a string.
Return error message string or None if no errors.
"""
for value in metadata.values():
if isinstance(value, dict):
if "get_param"... | 68,602 |
def id2name(query, tchs, gi):
"""
convert id number to name
"""
if query.isdigit() is True:
if gi is True:
if query in tchs['gi2taxid.tch']:
taxid = tchs['gi2taxid.tch'][query]
else:
query = 'n/a'
else:
taxid = query
... | 68,603 |
def open_json_catalog():
"""Loads local CMIP6 JSON intake catalog"""
data = json.load(open("cmip_catalog.json"))
return data | 68,604 |
def pair_between(frag1: list, frag2: list, start_offset: int = 0) -> tuple:
"""Pairs between two fragments of a larger list
A pairing of a list is a set of pairs of list elements. E.g. a pairing of
labels = [1, 2, 3, 4, 5, 6, 7, 8]
could be
[(1, 2), (3, 4), (5, 6), (7, 8)]
(Note that we ins... | 68,605 |
def quaternions_to_so3_matrix(q):
"""Normalises q and maps to group matrix."""
q = q / q.norm(p=2, dim=-1, keepdim=True)
r, i, j, k = q[..., 0], q[..., 1], q[..., 2], q[..., 3]
return torch.stack(
[
r * r - i * i - j * j + k * k,
2 * (r * i + j * k),
2 * (r *... | 68,606 |
def _recursive_guard(fillvalue='...'):
"""
Like the python 3.2 reprlib.recursive_repr, but forwards *args and **kwargs
Decorates a function such that if it calls itself with the same first
argument, it returns `fillvalue` instead of recursing.
Largely copied from reprlib.recursive_repr
"""
... | 68,607 |
def canConnectPins(src, dst):
"""**Very important fundamental function, it checks if connection between two pins is possible**
:param src: Source pin to connect
:type src: :py:class:`PyFlow.Core.PinBase.PinBase`
:param dst: Destination pin to connect
:type dst: :py:class:`PyFlow.Core.PinBase.PinBas... | 68,608 |
def is_document_public(document: dict) -> bool:
""" checks whether document `visibility` and `revisionState` match
requirements to be considered ready for publication.
:param document: couchdb document
:returns: whether visibility and revision state qualify for publication
"""
if document.get("... | 68,609 |
def read_pom_input():
"""
Description: Opens forcing files reading the paths specified in the pom_input namelist.
:return: data arrays for wind stress, surface salinity, solar radiation, inorganic
suspended matter, salinity and temperature vertical profiles, general circulation
f... | 68,610 |
def raises(exception_type):
"""Make a matcher that checks that a callable raises an exception.
This is a convenience function, exactly equivalent to::
return Raises(MatchesExceptionType(exception_type))
See `Raises` and `MatchesExceptionType` for more information.
"""
return Raises(Matche... | 68,611 |
def test_role_calculation():
"""
Tests that the reducer knows all the possible states.
"""
for state in all_possible_states():
try:
# Raises KeyError if a state is unknown and FundsPullPreApprovalError
# if the state is illegal
reduce_role(**asdict(state))
... | 68,612 |
def relu(Z):
"""
RELU activation function
Arguments:
Z -- numpy array
Returns:
A -- output of rulu(Z)
cache -- Z, useful for back propagation
"""
A = np.maximum(0, Z)
return A | 68,613 |
def get_cache_path(split):
"""Gets cache file name."""
cache_path = os.path.join(os.path.dirname(__file__), "../../../data/mini-imagenet/mini-imagenet-cache-" + split + ".pkl")
return cache_path | 68,614 |
def flux(component):
"""Determine flux in every channel
Parameters
----------
component: `scarlet.Component` or array
Component to analyze or its hyperspectral model
"""
if hasattr(component, "get_model"):
model = component.get_model()
else:
model = component
re... | 68,615 |
def get_current_vistrail():
"""get_current_vistrail():
Returns the currently selected vistrail.
"""
return get_current_controller().vistrail | 68,616 |
def wrap_components(
container: ServiceContainer,
) -> Dict[str, Type]:
""" Wrap component rendering with a partial to gain access to container
"""
# Get all the components, from the container
components: Dict[str, Any] = container.get(IAllComponents)
# For each, wrap them in a partial th... | 68,617 |
def initialize_database( engineCreateArgs,
engineCreateKWargs={},
autocommit=False,
autoflush=False):
"""
Database initialization routine that shall be called prior to any database
operation. Will configure CastLib package-wide datab... | 68,618 |
def test_file_size(loaded_bucket: Bucket) -> None:
"""Tests file_size."""
size_expected = set(["627B", "628B", "629B"])
raw_size_expected = set(["627", "628", "629"])
size_actual = s3_utils.file_size(bucket=loaded_bucket.name, key=CSV_FILE_KEY)
assert size_actual in size_expected
raw_size_actual... | 68,619 |
def p_art_mult_or_div_unary_expr_1(p):
"""
art_mult_or_div_unary_expr : ART_DIV unary_expression art_mult_or_div_unary_expr
"""
if len(p[3]) > 0:
op, right = p[3]
p[0] = p[1], Expression(p[2], op, right)
else:
p[0] = p[1], p[2] | 68,620 |
def curl(url):
""" Test URL, return http code """
try:
return urllib2.urlopen(url, timeout=30).getcode()
except urllib2.HTTPError as e:
return e.fp.getcode()
except Exception:
logger.exception("unknown error")
return 0 | 68,621 |
def BinOpMap(operator):
"""Maps operator strings for binary operations to their _ast node."""
op_dict = {
'+': _ast.Add,
'-': _ast.Sub,
'*': _ast.Mult,
'**': _ast.Pow,
'/': _ast.Div,
'//': _ast.FloorDiv,
'%': _ast.Mod,
'<<': _ast.LShift,
'>>': _ast.RShift,
... | 68,622 |
def test_mining_account_earning():
"""Tests the API endpoint to get account earnings"""
client.mining_account_earning(algo="sha256").should.equal(mock_item) | 68,623 |
def get_cgi_dates(form):
""" Figure out which dates are requested via the form, we shall attempt
to account for invalid dates provided! """
y1 = int(form.get("year1"))
m1 = int(form.get("month1"))
d1 = int(form.get("day1"))
y2 = int(form.get("year2"))
m2 = int(form.get("month2"))
d2 = in... | 68,624 |
def is_current_game_state(handler_input, state):
"""Check the current game state"""
return handler_input.attributes_manager.session_attributes['game_state'] == state | 68,625 |
def verbosity_option(**kwargs):
"""Adds a -v/--verbose option to a click command.
Parameters
----------
**kwargs
All kwargs are passed to click.option.
Returns
-------
``callable``
A decorator to be used for adding this option.
"""
def custom_verbosity_option(f):
... | 68,626 |
def test_temporary_package_file(SystemInfo, File):
"""
Test downloaded package from URL
"""
if SystemInfo.distribution == 'ubuntu':
filename = '/tmp/mongodb-mms_3.4.0.383-1_x86_64.deb'
package = File(filename)
assert package.exists
assert package.is_file | 68,627 |
def get_garmin_client():
"""
General access point for getting an authenticated Garmin Connect session.
Returns
-------
session : Garmin
Connected Garmin Connect API object
"""
# 1. If an email / password is stored, attempt to login with the credentials
while True:
try:
... | 68,628 |
def chdir_back_to_root(mocker):
"""
This fixture sets up and tears down state before each example is run. Certain examples
require that they are run from the local directory in which they reside. This changes
directory and adds the local directory to sys.path. It reverses this after the test
finishe... | 68,629 |
def logout():
"""退出登录"""
logout_user()
return redirect(url_for('backend.login')) | 68,630 |
def AssignSubtypes(tree):
"""Run the subtype assigner visitor over the tree, modifying it in place.
Arguments:
tree: the top-level pytree node to annotate with subtypes.
"""
subtype_assigner = _SubtypeAssigner()
subtype_assigner.Visit(tree) | 68,631 |
def test_execute_link_issue(
mock_config_manager: MockerFixture,
mock_github_service: MockerFixture,
domain_prs: List[pr.PullRequest],
) -> None:
"""It returns success."""
config_manager = mock_config_manager.return_value
github_service = mock_github_service.return_value
request = domain_prs... | 68,632 |
def patient_details(id):
"""Display the full patient details form for an existing user."""
check_patient_permission(id)
patient = Patient.query.get(id)
form = (
get_unsaved_form(request, patient, 'patient_details', PatientForm)
or PatientForm(obj=patient)
)
if request.method == ... | 68,633 |
def usage():
"""Print usage info."""
print(("""%s [-c|--configFile <config file>] [-i|--init] [-o|--outputDir <output dir>]\
[-s|--status] [-f|--force] [-d|--debug] [--nocache] [-t|--timeout <seconds>]\
[-a|--args <input1=val1,input2=val2,...>] [-v|--verbose] [-h|--help] <sciflo doc>""" % sys.argv[0])) | 68,634 |
def test_list_boolean_min_length_4_nistxml_sv_iv_list_boolean_min_length_5_5(mode, save_output, output_format):
"""
Type list/boolean is restricted by facet minLength with value 10.
"""
assert_bindings(
schema="nistData/list/boolean/Schema+Instance/NISTSchema-SV-IV-list-boolean-minLength-5.xsd",... | 68,635 |
def version():
"""Return current package version."""
with open("demo/version/A-major", "rt") as f:
major = f.read().replace("\n", "")
with open("demo/version/B-minor", "rt") as f:
minor = f.read().replace("\n", "")
with open("demo/version/C-patch", "rt") as f:
patch = f.read().re... | 68,636 |
def main():
"""
You should write your code to make Karel do its task in
this function. Make sure to delete the 'pass' line before
starting to write your own code. You should also delete this
comment and replace it with a better, more descriptive one.
"""
# building one
for i in range(3)... | 68,637 |
def schedule_binarize_pack(outs):
"""Schedule for binarize_pack
Parameters
----------
outs: Array of Tensor
The computation graph description of binarize_pack
in the format of an array of tensors.
Returns
-------
sch: Schedule
The computation schedule for the op... | 68,638 |
def stream_result_fixed(input_query: InputFixedQuery,
authorization: str = Header(None),
processor: Processor = Depends(get_processor)):
"""
Create result set of data with temporality type fixed,
and stream result as response.
"""
log.info(f'Entering /... | 68,639 |
def test_3x3_cube(verbose=0):
"""
Read sample openfoam mesh from aggelos and check that the basic information is correct
"""
xmf_base=os.path.join(os.path.dirname(os.path.abspath(__file__)),
'hex_cube_3x3')
h5_base = xmf_base
mesh_info = readMeshXdmf(xmf_base,h5_base,ve... | 68,640 |
def html_to_text(html_text):
"""Strip html_text tags from string and return a plain plain_text version."""
strip_tags = regex.compile(r"<.*?>")
eol_tags = regex.compile(r"</p>")
return strip_tags.sub("", eol_tags.sub("\n", html_text)) | 68,641 |
def test_add_and_create_dataset_with_lfs_warning(directory_tree, runner, project, client_with_lfs_warning):
"""Test add data with lfs warning."""
# Add succeeds with --create
result = runner.invoke(
cli, ["dataset", "add", "--create", "new-dataset", str(directory_tree)], catch_exceptions=False
... | 68,642 |
def listvolumes(ctx,
# Optional main parameter
snapmirrorendpointid = None,
# Optional main parameter
vserver = None,
# Optional main parameter
name = None,
# Optional main parameter
type = None):
"""The SolidFire Element OS web... | 68,643 |
def create_multi_node_optimizer(actual_optimizer, communicator,
double_buffering=False):
"""Create a multi node optimizer from a Chainer optimizer.
Args:
actual_optimizer: Chainer optimizer
(e.g., ``chainer.optimizers.Adam``).
communicator: ChainerMN ... | 68,644 |
def main(bb_root: tp.Optional[str] = None, test_projects: bool = False) -> None:
"""
Main function for the benchbuild config creator.
`vara-gen-bbconfig`
"""
if vara_cfg()["config_file"].value is None:
if cli_yn_choice("Error! No VaRA config found. Should we create one?"):
save_... | 68,645 |
def write_rabbit_config(api: RabbitMQAPI, config_file: Optional[str] = None):
"""
Writes out RabbitMQ config files for persistence on next run
:param api: Configured RabbitMQAPI object
:param config_file: Path to `rabbit_mq_config.json` file to write
"""
config_file = config_file if config_file ... | 68,646 |
def extract_title_from_text(text: str) -> str:
"""Extract and return the title line from a text written in Markdown.
Returns the first line of the original text, minus any header markup ('#') at the start
of the line.
"""
firstline = text.split('\n', 1)[0]
return firstline.lstrip('# ') | 68,647 |
def main_function(dummy_df):
"""
Takes in dummy dataframe and runs all functions based on given year ranges.
Prints out year and accuracy per time range (3 years ranges)
"""
output_list = []
for process_year in range(2004, 2021):
output_df = get_data(dummy_df, process_year)
... | 68,648 |
def clear():
"""
Function Clear, clean the screen.
"""
# Compatibility for Windows:
if name == 'nt':
_ = system('cls')
# Compatibility for Mac and Linux(os.name: "posix"):
else:
_ = system('clear') | 68,649 |
def _all_pairs(i, contextsize, arrlen):
"""
i: index in the array
contextsize: size of the context around i
arrlen: length of the array
Returns iterator for index-tuples near i in a list of size s with
context size @contextsize. Context of k around i-th index means all
substrings/subarrays... | 68,650 |
def swatch_masks(width, height, swatches_h, swatches_v, samples):
"""
Returns swatch masks for given image width and height and swatches count.
Parameters
----------
width : int
Image width.
height : height
Image height.
swatches_h : int
Horizontal swatches count.
... | 68,651 |
def generate_features(landmark_coords):
"""Generate features from landmarks."""
key_points = [18, 22, 23, 27, 37, 40, 43, 46, 28, 32,
34, 36, 5, 9, 13, 49, 55, 52, 58, 61, 63, 65, 67]
combinations = itertools.combinations(key_points, 4)
point1 = []
point2 = []
point3 = []
p... | 68,652 |
def detector_batch_deploy(LogBlobDetector, inbreast_name_list):
"""Batch deploy blob detector
Args:
LogBlobDetector:
inbreast_name_list:
Returns:
"""
inbreast_dict = inbreast.generate_inbreast_dict()
for name in inbreast_name_list:
print(name)
# get paths
... | 68,653 |
def create_path_complete_condition(transmit_node_pairs):
"""
This factory allows us to specify that there are valid directed paths between pairs of nodes.
This returns a function that takes an graph argument (G)
and verifies that for the list of node pairs the graph meets those dependency conditions.
... | 68,654 |
def percentformat(x, pos):
"""
Generic percent formatter, just adds a percent sign
"""
if (x==0): return "0%"
if (x<0.1): return ('%4.3f' % (x)) + "%"
if (x<1): return ('%3.2f' % (x)) + "%"
if (x<5): return ('%2.1f' % (x)) + "%"
return ('%1.0f' % x) + "%" | 68,655 |
def is_hexagonal(hexag: int):
"""any tn in triangle sequence is t = ½n(n+1):
Solving with quadratic formula reveals n is only an integer if (1+8t) ** 0.5 is an integer and odd"""
if int((1+8*hexag)**0.5) == (1+8*hexag)**0.5 and ((1+8*hexag)**0.5)%4 == 3:
return True
return False | 68,656 |
def main():
"""
Workload which:
1. Claims a filename from a Redis Worker Queue
2. Reads the dataset from the file
3. Partially trains the model on the dataset
4. Saves a model checkpoint and generates a report on
the performance of the model after the partial training.
5. ... | 68,657 |
def get_fashion_mnist_labels(labels):
"""返回Fashion-MNIST数据集的文本标签。
Defined in :numref:`sec_fashion_mnist`"""
text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat',
'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot']
return [text_labels[int(i)] for i in labels] | 68,658 |
def bufferParser(readbuffer, burst=16):
""" Parse concatenated frames from a burst
"""
out = b''
offset = 1
while len(readbuffer) > 0:
length = readbuffer[2]
if readbuffer[4] == offset:
out += readbuffer[5:3+length]
offset += 1
readbuffer = readbuffe... | 68,659 |
def aaa_load_profile():
""" this function load the account which will be used as cookie """
account = Account(ES)
return Response(json.dumps(account.load_account_profile(request.args.get("email")))) | 68,660 |
def _pairwise_non_aligned_corr(g1: BaseEstimator,
g2: BaseEstimator,
attr: str, # either metastable_states or absorption_probabilities
key: str):
"""Utility function to handle the case of subsampled data."""
o1, o2 = ... | 68,661 |
def get_fmri(fmri_dir, ROI):
"""This function loads fMRI data into a numpy array for to a given ROI.
Parameters
----------
fmri_dir : str
path to fMRI data.
ROI : str
name of ROI.
Returns
-------
np.array
matrix of dimensions #train_vids x #repetitions x #voxels... | 68,662 |
def iterative_topological_sort(graph, start):
"""doesn't return some nodes"""
seen = set()
stack = [] # path variable is gone, stack and order are new
order = [] # order will be in reverse order at first
queue = [start]
while queue:
node = queue.pop()
if node not in seen:
... | 68,663 |
def calculate_density_values(centers_of_intervals, mean, deviation) :
""" Обчислюємо значення функції щільності """
density_values = np.zeros(centers_of_intervals.size)
t_values = __calculate_t_values_for_density(centers_of_intervals, mean, deviation)
phi_values = __calculate_phi_values_for_density(t_values)
... | 68,664 |
def libc_prctl_pr_set_seccomp_mode_filter(bpf_bytes: bytes) -> None:
"""
Call prctl(PR_SET_SECCOMP, SECCOMP_MODE_FILTER, sock_fprog, 0, 0).
This also _constructs_ the `sock_fprog` argument, because it's so
low-level. The argument `bpf_bytes` must be a `bytes` object produced by
`seccomp_export_bpf(... | 68,665 |
def _helper(length_diff, linked_list):
"""Helper function for longer linked list."""
length_diff = abs(length_diff)
return linked_list[length_diff:] | 68,666 |
def getFuncDict():
"""Directs key word to given function"""
FuncDict = {"Aff": affHeatMap,
"Valency": ValencyPlot,
"Mix": MixPlot}
return FuncDict | 68,667 |
def run(cutouts, hostname="localhost", port=DEFAULT_PORT):
"""Start a local web app on the given port that lets you explore this cutout."""
def handler(*args):
return ViewerServerHandler(cutouts, *args)
myServer = HTTPServer((hostname, port), handler)
print("Viewer server listening to http://{}:{}".format(... | 68,668 |
def account(account):
"""Changing scope of the account fixture to be called after
mailhog_delete_all fixture"""
return account | 68,669 |
def do_configure_op(remote_op):
"""
Perform a /configure operation on all remote nodes
:param remote_op: the operation json string
"""
try:
endpoints = get_cluster_agent_endpoints(include_self=False)
except subprocess.CalledProcessError as e:
print("Could not query for nodes")
... | 68,670 |
def fit_starting_guess_coefficients(degree=4):
"""Fits polynomial coefficients to linear test run that are used as a starting guess for the optimization.
NOTE: One run of this is already stored in the code repo, so this only needs to be done if they corrupt somehow.
generate_starting_guess() must be run b... | 68,671 |
def load_sf133(filename, fiscal_year, fiscal_period, force_load=False):
"""Load SF 133 (budget execution report) lookup table."""
with createApp().app_context():
sess = GlobalDB.db().session
existing_records = sess.query(SF133).filter(
SF133.fiscal_year == fiscal_year, SF133.period... | 68,672 |
def getRefSeq( gene ):
"""Module RefSeq.
Getting gene description thanks to lynx (must be installed)
"""
URL = "http://www.ncbi.nlm.nih.gov/IEB/Research/Acembly/av.cgi?db=human&c=Gene&a=fiche&l=" + gene #Url usage
p = subprocess.Popen(['/usr/bin/lynx', '-dump', URL ], stdout=subprocess.PIPE, stderr=subprocess.PI... | 68,673 |
def writeResponse(func):
"""Prints response objects returned by functions.
Args:
func: Function whose output will be printed to screen.
Returns:
What the function given returns.
"""
def inner(*args, **kwargs):
response = func(*args, **kwargs)
if(verbose):
print response.data
return response
re... | 68,674 |
def get_polygon(aoiSquare):
"""
Translation from PAIRS aoiSquare to Shapely polygon.
:aoiSquare: PAIRS aoiSquare
:returns: Shapely polygon
"""
return box(aoiSquare[1], aoiSquare[0], aoiSquare[3], aoiSquare[2]) | 68,675 |
def base_paginator(seed_url: "URL", session_manager: "SessionManager", schema: Any) -> Iterable[Any]: # type: ignore # noqa: F821, E501
"""Create a paginator using the passed parameters.
Args:
seed_url: The url to get the first batch of results.
session_manager: The session manager that will ... | 68,676 |
def collectComponents(board, components=None):
"""
Collect components template from the board. Include only footprints in
components if specified
"""
d = CommentedMap()
footprints = [f for f in board.GetFootprints()
if components is None or len(components) == 0 or any([re.match(c, f.GetR... | 68,677 |
def _validate_labels(labels):
"""Check for empty labels in the middle of a label sequence,
labels that are too long, and for too many labels.
Raises ``dns.name.NameTooLong`` if the name as a whole is too long.
Raises ``dns.name.EmptyLabel`` if a label is empty (i.e. the root
label) and appears in ... | 68,678 |
def paste_qrcode(pos, qr_img, back_img):
"""
paste the QR code onto the background.
Parameters
------
pos: int
option number for the position which QR code will be pasted
qr_img: SimpleImage
image for QR Code
back_img: SimpleImage
image for background
Returns
----... | 68,679 |
def nucleation_3D(writer, args, R=20):
"""
raise NotImplementedError("Needs some work")
params = {
"A": 3.4,
"B": 13.5,
"k2": 1.0,
"k-2": 0.1,
"k5": 0.9,
"D_G": 1.0,
"D_X": 1.0,
"D_Y": 1.95,
"density_G": 1.0,
"density_X": 0.0002... | 68,680 |
def rsub(self, other):
"""Compute the element-wise subtraction.
Parameters
----------
other : Union[dragon.Tensor, number]
The value to be subtracted.
Returns
-------
dragon.Tensor
The output tensor.
See Also
--------
`dragon.math.sub(...)`_
"""
return... | 68,681 |
def test_SetView_len(testcase, setview, exp_result):
"""
Test function for SetView.__len__() / len(sv)
"""
# The code to be tested
result = len(setview)
# Ensure that exceptions raised in the remainder of this function
# are not mistaken as expected exceptions
assert testcase.exp_exc_t... | 68,682 |
def train_calculator(request: TrainCalculatorRequest) -> TrainCalculatorResponse:
"""Calculate CO2 emissions for a train trip"""
response = build_response(request)
return response | 68,683 |
def socfaker_file_signature_status():
"""
The signature status of a file
Returns:
str: A randomly selected signature status of Verified, Unknown, or Counterfit
"""
if validate_request(request):
return { 'value': socfaker.file.signature_status } | 68,684 |
def lif_asc_aibs_converter(config, tau_syn=[5.5, 8.5, 2.8, 5.8]):
"""
:param config:
:return:
"""
coeffs = config['coeffs']
params = {'V_th': coeffs['th_inf'] * config['th_inf'] * 1.0e03 + config['El_reference'] * 1.0e03,
'g': coeffs['G'] / config['R_input'] * 1.0e09,
... | 68,685 |
def get_routing_best_routes(
device: object,
address: str,
protocol: str,
active_tag: str = "*",
) -> list:
"""Return a list of best routes
Args:
device (object): Device object
address (str): Address to check
protocol (str): Protocol to check
active_tag (str, opt... | 68,686 |
def _proper_delay(q, c):
"""Analytically derived state-space when p = q - 1.
We use this because it is numerically stable for high q
and doesn't have a passthrough.
"""
j = np.arange(q, dtype=np.float64)
u = (q + j) * (q - j) / (c * (j + 1))
A = np.zeros((q, q))
B = np.zeros((q, 1))
... | 68,687 |
def _CommonChecks(input_api, output_api):
"""Checks common to both upload and commit."""
result = []
result.extend(_CheckColorFormat(input_api, output_api))
result.extend(_CheckColorReferences(input_api, output_api))
result.extend(_CheckDuplicateColors(input_api, output_api))
# Add more checks here
return... | 68,688 |
def login_required(f):
""" Decorate routes to require login. """
@wraps(f)
def decorated_function(*args, **kwargs):
if session.get("user_id") is None:
return redirect("/login")
return f(*args, **kwargs)
return decorated_function | 68,689 |
def sensor_qry_single_row_v2(SYSTEM,querySingle, sensor_raw_table):
#{{{APIINFO
"""
{
"API_application":"提供查詢postgresql單一感測器感測資料服務(最新一筆或第一筆),不經過mysql直接抓取postgresql",
"API_path_parameters":{
"SYSTEM":"合法的系統名稱",
"querySingle":"First(取得第一筆資料)/Last(取得最後一筆資料)",
... | 68,690 |
def differential_replication(fitness, individuals):
"""
Individuals are selected into the next generation by a probability proportional to their fitness.
Selected individuals are differentially replicated.
"""
return new_population | 68,691 |
def presco(te: np.ndarray, data: np.ndarray, tesla: float, none: bool = False,
debug: bool = False) -> (np.ndarray, np.ndarray, np.ndarray, np.ndarray, float):
"""
[params sse] = presco(te, data)
[params sse] = presco(imDataParams)
Phase regularized estimation using smoothing and constrained... | 68,692 |
def save_autoreject(ar, subj_id):
"""Save an autoreject object to the predefined folder."""
ar_path = op.join(BAD_AR_PATH, subj_id + "-ar.hdf5")
ar.save(ar_path) | 68,693 |
def test_c_unittests(accelize_drm, exec_func):
"""Test errors when missing arguments are given to DRM Controller Constructor"""
driver = accelize_drm.pytest_fpga_driver[0]
exec_lib = exec_func.load('unittests', driver._fpga_slot_id)
# Test when read register callback is null
exec_lib.run('test_nul... | 68,694 |
def voter_guides_followed_by_organization_retrieve_for_api(voter_device_id, # voterGuidesFollowedByOrganizationRetrieve
voter_linked_organization_we_vote_id,
filter_by_this_google_civic_election_id=Fal... | 68,695 |
def show_questionnaire(request, runinfo, errors={}):
"""
Return the QuestionSet template
Also add the javascript dependency code.
"""
request.runinfo = runinfo
if request.GET.get('show_all') == '1': # for debugging purposes.
questions = runinfo.questionset.questionnaire.questions()
... | 68,696 |
def ib_model(img_in, noise, num_actions, scope, reuse=False, decoder="DECONV"):
"""As described in https://storage.googleapis.com/deepmind-data/assets/papers/DeepMindNature14236Paper.pdf"""
img_size = img_in.shape[1]
with tf.variable_scope(scope, reuse=reuse):
out = img_in
# coordinate = np.... | 68,697 |
def pad_sequence_to_length(
sequence: List,
desired_length: int,
default_value: Callable[[], Any] = lambda: 0,
padding_on_right: bool = True,
) -> List:
"""
Take a list of objects and pads it to the desired length, returning the padded list.
The original list is not modified.
"""
# ... | 68,698 |
def output_path(request):
"""
Returns the desired name for the folder that will store the results of the tests. If no name is provided, it will
default to naming the folder after the timestamp at the moment this test session started. Datetime as string in the
format YYYY-MM-DDTHH_MM_SS_F This fixture i... | 68,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.