content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def pick_an_experiment(i):
"""
Input: {
(repo_uoa) - experiment repository name (defaults to hackathon_local_repo, but can be overridden by '*')
(extra_tags) - extra tags to filter
}
Output: {
return - return code = ... | 800 |
def run(args, image: str) -> str:
"""
Run docker image and mount user-provided folder with C++ files.
Parameters
----------
args : dict-like
User provided arguments parsed by argparse.ArgumentParser instance.
image : str
Name of image from which container is run
Returns
... | 801 |
def get_top_design_list(oProject):
"""
Returns a list of the names of the top-level designs.
Parameters
----------
oProject : pywin32 COMObject
The HFSS project in which the operation will be performed.
designname : str
Name of the design to insert.
Returns
-------
... | 802 |
def gere_operation_unaire(op, valeur1):
"""Redirige vers pourcent, racine_carre, cosinus ou sinus."""
pass | 803 |
def test_atomic_language_pattern_3_nistxml_sv_iv_atomic_language_pattern_4_5(mode, save_output, output_format):
"""
Type atomic/language is restricted by facet pattern with value
([a-zA-Z]{2}|[iI]-[a-zA-Z]+|[xX]-[a-zA-Z]{1,8})(-[a-zA-Z]{3})*.
"""
assert_bindings(
schema="nistData/atomic/lang... | 804 |
def test_amazon_review_dataset_distribution():
"""
Feature: Test AmazonReviewDataset in distribution.
Description: test in a distributed state.
Expectation: the data is processed successfully.
"""
data = ds.AmazonReviewDataset(FULL_DIR, usage='test', shuffle=False, num_shards=2, shard_id=0... | 805 |
def chi01(param_name: Union[str, None], yval: float, **kwargs) -> Dict[str, Any]:
"""Plot defaults for sweep_plotting.chi01"""
kwargs["xlabel"] = kwargs.get("xlabel") or recast_name(param_name)
kwargs["ylabel"] = kwargs.get("ylabel") or r"$\chi_{{01}}$ [{}]".format(
units.get_units()
)
kwarg... | 806 |
def cstring(*args, **kwargs):
"""Return a colored string.
Parameters
----------
args : iterable of str
bold : bool
color : str, {'HEADER', 'LIGHTBLUE', 'LIGHTGREEN', 'WARNING', 'FAIL',
'ENDC', 'BOLD', 'UNDERLINE' 'BLACK', 'RED', 'GREEN',
'YELLOW', 'BLUE', 'MA... | 807 |
def create_app():
"""Construct the core application."""
app = Flask(__name__, instance_relative_config=False)
app.config.from_object('config.Config')
db.init_app(app)
admin.init_app(app)
basic_auth.init_app(app)
with app.app_context():
from . import routes # Import routes
... | 808 |
def bytes_index(x: bytes, sub: bytes, start: int, end: int) -> int:
"""Where is the first location of a subsequence within a given slice of a bytes object?
Compiling bytes.index compiles this function, when sub is a bytes object.
This function is only intended to be executed in this compiled form.
Arg... | 809 |
def pickup_path(start_path, filename, default=None):
"""pickupping the config file path
start path = "/foo/bar/boo", filename = "config.ini"
finding candidates are ["/foo/bar/boo/config.ini", "/foo/bar/config.ini", "/foo/config.ini", "/config.ini"]
"""
start_point = os.path.normpath(os.path.abspath... | 810 |
def uniform(minimum, maximum, shape=[]):
"""uniform(minimum, maximum, shape=[]) returns array of given shape of random reals
in given range"""
if shape == []:
shape = None
return mt.uniform(minimum, maximum, shape) | 811 |
def unquote_to_bytes(urlencoded_string):
"""Replace %xx escapes by their single-character equivalent,
using the “iso-8859-1” encoding to decode all 8-bit values.
"""
return bytes(
unquote(urlencoded_string, encoding='iso-8859-1'),
encoding='iso-8859-1'
) | 812 |
def plot_history(history):
"""Plots training historical training and validation accuracies and losses
Args:
history (dict): training and validation losses and accuracies history.
{'train': {'loss': [], 'acc': []},
'valid': {'loss': [], 'acc': []}}
""... | 813 |
def qualifiedName(item):
"""Return the full name of an item, including any projects that it's in.
If the item does not have a name, return ``None``.
XXX: Doesn't include folders.
"""
names = []
# Note: assumes that the presence of a single null name in the parent tree
# means that the item... | 814 |
def assign_columns_of_sector_levels(df_load):
"""
Add additional column capturing the sector level in the two columns
:param df_load: df with at least on sector column
:param ambiguous_sector_assignment: if there are sectors that can be
assigned to multiple sector lengths (e.g., for government or ho... | 815 |
def add_matrices(matrix_a, matrix_b):
"""Add two n x n matrices
"""
return [[x + y for x, y in zip(matrix_a[i], matrix_b[i])]
for i in range(len(matrix_a))] | 816 |
def dataset() -> Generator[Dataset, None, None]:
"""Fetches a consistent view of the rows to be serialized.
Serializers may further filter this list down if they wish."""
with transaction.atomic():
ds = Dataset()
# The sheer width of the number of columns being pulled out of
# the d... | 817 |
def create_error_handlers(blueprint):
"""Create error handlers on blueprint."""
blueprint.errorhandler(PIDInvalidAction)(create_api_errorhandler(
status=403, message='Invalid action'
))
records_rest_error_handlers(blueprint) | 818 |
def assert_allclose(
actual: int, desired: int, rtol: float, err_msg: Literal["ngroupsfailed"]
):
"""
usage.statsmodels: 1
"""
... | 819 |
def no_pretrain_inner_speech(subject):
"""This function aims at training a model without pretraining by training
only on the inner speech condition of a sigle subject
:return: metric history for every of the n k-folds
:rtype: list of dictonaries
"""
###### DATA
data, events = dp.load_data(s... | 820 |
async def _expect_io():
"""Wait until a line of text comes in from the EQ log."""
try:
with eqlog.tap() as t:
await t.next_line()
except asyncio.CancelledError:
pass | 821 |
def main():
"""Entrypoint"""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'--cpu-arch',
metavar='ARCH',
default=platform.architecture()[0],
choices=('64bit', '32bit'),
help=('Filter build outputs by a target CPU. '
'This is... | 822 |
def build_put_big_decimal_negative_decimal_request(**kwargs: Any) -> HttpRequest:
"""Put big decimal value -99999999.99.
See https://aka.ms/azsdk/python/protocol/quickstart for how to incorporate this request builder
into your code flow.
:keyword json: The default value is -99999999.99. Note that over... | 823 |
def handle_record_end():
"""Forward internal bus message to external bus."""
LOG.info("End Recording...")
context = {'client_name': 'mycroft_listener',
'source': 'audio',
'destination': ["skills"]}
bus.emit(Message('recognizer_loop:record_end', context=context)) | 824 |
def make_subplots(
rows=1,
cols=1,
shared_xaxes=False,
shared_yaxes=False,
start_cell="top-left",
print_grid=False,
horizontal_spacing=None,
vertical_spacing=None,
subplot_titles=None,
column_widths=None,
row_heights=None,
specs=None,
insets=None,
column_titles=No... | 825 |
def op_table(name):
"""Get the symbol `name' as an int8_t[]."""
return gdb.parse_and_eval("&'" + name + "'").cast(T('int8_t').pointer()) | 826 |
def add_pyramid_paths(
spec,
route_name,
request=None,
request_method=None,
operations=None,
autodoc=True,
**kwargs
):
"""
Adds a route and view info to spec
:param spec:
ApiSpec object
:param route_name:
Route name to inspect
:param request:
Req... | 827 |
def nf_masks_to_neurof_dict(binary_masks: np.ndarray, dataset_name: str) -> Dict[str, Any]:
"""
Take as input a tensor of binary mask and produces dict format for neurofinder
Args:
binary_masks: 3d ndarray (components x dimension 1 x dimension 2)
dataset_filename: name of the dataset
Re... | 828 |
def get_domain_machine_command():
"""Retrieves a collection of Machines that have communicated to or from a given domain address.
Returns:
(str, dict, dict). Human readable, context, raw response
"""
headers = ['ID', 'ComputerDNSName', 'OSPlatform', 'LastIPAddress', 'LastExternalIPAddress', 'H... | 829 |
def flatten_dict(source_dict, name_delimiter='_', inner_name=False):
"""
flatten nest dict
Parameters
----------
source_dict : nest dict
name_delimiter : flatten name delimiter(non-use when inner_name is True)
inner_name : False, use innermost name as retrun dict key or not
Returns
... | 830 |
def matrix_multiply(A, B):
""" Multiply two matrices A and B.
:param A: the right matrix
:param B: the left matrix
:return: A * B
"""
# define m and n for the matrix as well as l, the connecting dimension between A and B
m, l, n = len(A), len(A[0]), len(B[0])
# initialize an all zeros ... | 831 |
def create_normalized_frequency_files(scenario, character_set, letter_files, bigram_files):
"""
Filters the given frequency files with respect to the given character set and normalizes the frequencies such
that they sum up to 1.
Takes care of combined characters and distributing the frequencies accordi... | 832 |
def hard_light(image1, image2):
"""
Superimposes two videos on top of each other using the Hard Light algorithm
:rtype: :py:class:`~PIL.Image.Image`
"""
image1.load()
image2.load()
return image1._new(image1.im.chop_hard_light(image2.im)) | 833 |
def carveThumbs(offset, length, thumbfile, thumbname, width, height, export):
"""
:param offset: Offset in thumbnails.data for thumbnail
:param length: Lenght of data to carve for thumbnail in thumbnails.data
:param thumbfile: Source thumbnails.data file to carve from
:param thumbname: Name o... | 834 |
def show(*actors, **options):
"""
Create on the fly an instance of class ``Plotter`` and show the object(s) provided.
Allowed input objects types are:
``str``, ``Mesh``, ``Volume``, ``Picture``, ``Assembly``
``vtkPolyData``, ``vtkActor``, ``vtkActor2D``, ``vtkImageActor``,
``vtkAssembly`` or ``... | 835 |
def assert_allclose(
actual: numpy.ndarray,
desired: numpy.ndarray,
rtol: float,
err_msg: Literal["dx=3 k=0"],
):
"""
usage.scipy: 1
"""
... | 836 |
def compute_on_cpu():
"""Compute all run configurations over a sigle CPU."""
sweep_config = OmegaConf.load("tools/benchmarking/benchmark_params.yaml")
for run_config in get_run_config(sweep_config.grid_search):
model_metrics = sweep(run_config, 0, sweep_config.seed)
write_metrics(model_metri... | 837 |
def convert_book(book):
"""
Attempt to convert any books of type in `CONVERTIBLE_MIMETYPES` to .mobi,
in the same folder as the given temporary path.
"""
tmp_path = book.get_tmp_pathname(u'send_books')
mobi_tmp_path = convert_to_mobi_path(tmp_path)
if mobi_tmp_path is None:
return No... | 838 |
def set_loggers_level(names, level=logging.CRITICAL):
"""
Set a log level on multiple loggers.
Arguments:
names (list): A list of logger names to set level.
Keyword Arguments:
level (integer): Logging level to set on all given logger names. Default to
value from ``logging.C... | 839 |
def get_followup_question_list(intent: str) -> List[str]:
"""
Get all imported followup questions for this intent as a list
* `intent`: name-parameter of the yml-section with which the followup questions were imported
**Returns:** None if no followup questions are known for this intent, otherwise lis... | 840 |
def event_train_test_split(
evs: np.ndarray, n_evs: int, train_split: float, random_seed: int=1
) -> Tuple[np.ndarray, np.ndarray]:
"""[summary]
Args:
n_evs (int): [description]
train_split (float): [description]
random_seed (int, optional): [description]. Defaults to 1.
Re... | 841 |
def get_cd(wcs, n=1):
"""
Get the value of the change in world coordinate per pixel across a linear axis.
Defaults to wcs.wcs.cd if present. Does not support rotated headers (e.g.,
with nonzero CDm_n where m!=n)
"""
if hasattr(wcs.wcs,'cd'):
if wcs.wcs.cd[n-1,n-1] != 0:
re... | 842 |
def mock_clear():
"""Clear MOCK_DATA_HEAP"""
MOCK_DATA_HEAP.clear()
return "" | 843 |
def cls_merge_type(classification):
""" classification type이 2가지일 때 합쳐주는 함수
Parameters
----------
classification: cls
classification 리스트
Returns
-------
list of cls
변환된 classification 리스트
"""
cls_type = {'instant' if cls.get('instant_datetime') else 'not_instant' fo... | 844 |
def complete_source_space_info(this):
"""Add more info on surface
"""
# Main triangulation
print '\tCompleting triangulation info...'
this['tri_area'] = np.zeros(this['ntri'])
r1 = this['rr'][this['tris'][:, 0], :]
r2 = this['rr'][this['tris'][:, 1], :]
r3 = this['rr'][this['tris'][:, ... | 845 |
def duplicate_detector(gate_orders: list[tuple[str]]) -> int:
"""Detects any schematics that have an identical combination of gates."""
difference = len(gate_orders) - len(list(set(gate_orders))) # List - list with no duplicates
return difference | 846 |
def permutations(x):
"""Return all permutations of x"""
def fn(i):
if i == len(x): ans.append(x.copy())
for k in range(i, len(x)):
x[i], x[k] = x[k], x[i]
fn(i+1)
x[i], x[k] = x[k], x[i]
ans = []
fn(0)
return ans | 847 |
def _checkFile(path,suffix=''):
"""
检查该路径是否存在,同时检查路径后缀是否等于suffix
:param path: 文件的路径
:suffix: 文件的后缀,默认为空。当path路径后缀不为suffix的后缀的时候,会报错
"""
if path==None:
raise FileNotFoundError('path路径为空,请设置查找路径!!!')
path = str(path)
if path == "":
raise FileNotFoundError('path路径为空,请设置查找路径... | 848 |
def _add_cobertura_package(packages, package_name, package_data): # type: (SubElement, str, t.Dict[str, t.Dict[str, int]]) -> t.Tuple[int, int]
"""Add a package element to the given packages element."""
elem_package = SubElement(packages, 'package')
elem_classes = SubElement(elem_package, 'classes')
t... | 849 |
def encode(model, text, out_file=None, topic_priors=None, prior_weight=1.0):
"""
Perform text-to-image encoding.
Parameters
----------
model : :obj:`gclda.model.Model`
Model object needed for decoding.
text : :obj:`str` or :obj:`list`
Text to encode into an image.
out_file :... | 850 |
def clean_string(s: str) -> str:
"""Cleans and returns an input string
>>> clean_string(" xYz ")
'XYZ'
"""
return str(s).strip().upper() | 851 |
def get_unique_region_cov_df(unique_region_dict, fuzzer_names):
"""Returns a DataFrame where the two columns are fuzzers and the number
of unique regions covered."""
fuzzers = collections.defaultdict(int)
for region in unique_region_dict:
for fuzzer in unique_region_dict[region]:
fuz... | 852 |
def load_continuous_dataset(
root: str,
name: str,
raw: bool = False,
random_state: Optional[RandomState] = None
) -> Union[
Tuple[np.ndarray, np.ndarray, np.ndarray],
Tuple[UnsupervisedDataset, UnsupervisedDataset, UnsupervisedDataset]
]:
"""
Load a continuous dataset.
All the datas... | 853 |
def plot_emo_num(emo_num, server = "local"):
"""plot distribution of emotion categoriy.
Args:
emo_num(list): list of unique emotion
server(str): local - plot emotion distribution; ssh - without plotting.
Return:
save (or plot) emotion categoriy plot.
"""
fig, ax = plt.sub... | 854 |
def display_generation_hit_results(hit_info, hit_results):
"""Displays the results of a generation HIT
Parameters
----------
hit_info : GenerationHITInfo
HITInfo object storing information regarding the HIT
hit_results : GenerationResults
HIT results object storing the results ... | 855 |
def sub_command_one():
"""Example Sub Command"""
click.echo("{{cookiecutter.project_slug}} sub_command_one") | 856 |
def check_help_all_output(pkg, subcommand=None):
"""test that `python -m PKG --help-all` works"""
cmd = [sys.executable, '-m', pkg]
if subcommand:
cmd.extend(subcommand)
cmd.append('--help-all')
out, err, rc = get_output_error_code(cmd)
nt.assert_equal(rc, 0, err)
nt.assert_not_in("T... | 857 |
def install_consul():
""" install Consul """
if env.host == env.consul_host and not exists("/usr/bin/consul"):
run("rm -f consul.zip consul")
run("curl -L --silent {} -o consul.zip".format(CONSUL_URL))
run("unzip consul.zip")
run("chmod +x consul")
sudo("mv consul /usr/bi... | 858 |
def XOR(v1, v2):
"""
XOR operation element by element from 2 lists
:param v1: [1, 0, 1, 0, 0, 1]
:param v2: [1, 1, 0, 0, 1, 1]
:return: [0, 1, 1, 0, 1, 0]
"""
return [a ^ b for a, b in zip(v1, v2)] | 859 |
def linearly_spaced_combinations(bounds, num_samples):
"""
Return 2-D array with all linearly spaced combinations with the bounds.
Parameters
----------
bounds : sequence of tuples
The bounds for the variables, [(x1_min, x1_max), (x2_min, x2_max), ...]
num_samples : integer or array_lik... | 860 |
def flatten_expressions_tree(
expression: Optional[Expression]) -> Tuple[Expression, ...]:
"""
Flatten expressions tree into a list.
"""
if not expression:
return tuple()
expressions = [expression]
for arg in expression.arguments:
if is_expression(arg):
expre... | 861 |
def workorder(
ctx: typer.Context,
path_in: Path = typer.Argument(
...,
help="Path to the job file(s).",
),
path_out: Path = typer.Argument(
"./tmp",
help="Parent path for saving the new workorder, will be prepended to --file-name.",
),
format_id: FormatChoices = ... | 862 |
def prepare_trans_list_update():
""" Prepares the translation_stats table for a translation list update.
For all translations, available is set to false. The translations that are
currently available will later be set to true. """
cur.execute("UPDATE translation_stats SET available = 0;")
_conn.com... | 863 |
def main():
"""Main script function."""
info = collect_info()
sort_info(info, "Участник:NapalmBot/файлы") | 864 |
def add_tags(recipe_data, recipe_id):
"""Add entries for Tag and RecipeTags and delete removed tags."""
newTags = recipe_data.get("newTags", {})
for tagname, category in newTags.items():
tagname = tagname.lower().strip()
tag = Tag(tagname=tagname, parent=TagCategory.get(TagCategory.categoryn... | 865 |
def policy_head(x, mode, params):
"""
The policy head attached after the residual blocks as described by DeepMind:
1. A convolution of 8 filters of kernel size 3 × 3 with stride 1
2. Batch normalisation
3. A rectifier non-linearity
4. A fully connected linear layer that outputs a vector of size... | 866 |
def _get_doors_gt_nsrts() -> Set[NSRT]:
"""Create ground truth NSRTs for DoorsEnv."""
robot_type, door_type, room_type = _get_types_by_names(
CFG.env, ["robot", "door", "room"])
InRoom, InDoorway, InMainRoom, TouchingDoor, DoorIsOpen, DoorInRoom, \
DoorsShareRoom = _get_predicates_by_names(C... | 867 |
def _get_word_ngrams(n, sentences):
"""Calculates word n-grams for multiple sentences.
"""
assert len(sentences) > 0
assert n > 0
words = sum(sentences, [])
return _get_ngrams(n, words) | 868 |
def untag_domain(
domain_arn: str,
tags: t.List[str],
client: "botocore.client.BaseClient" = None,
) -> None:
"""Remove tags from a domain.
Args:
domain_arn: domain AWS ARN
tags: tags (keys) to remove
client: SWF client
"""
client = _common.ensure_client(client)
... | 869 |
def override_list(base_list: List, dynamic_key: str, val):
"""
Customize the base list by updating with the
dynamic_key and val.
Parameters
----------
base: dict
Dictionary or List to be customized with dynamic args
dynamic_key: str
Key to identify the location the value sho... | 870 |
def c_components(DAG):
"""Return a list of the maximal c-component node sets in DAG."""
G = nx.Graph();
G.add_nodes_from(observable_nodes(DAG))
G.add_edges_from([(u,v) for u,v in observable_pairs(DAG) if
has_confounded_path(DAG, u, v)])
return list(nx.connected_components(G)) | 871 |
def wss_over_number_of_clusters(data, algorithm='kmeans',
max_iter=100, num_repeats = 5, max_num_clusters = 12,
plot_file = None):
"""
Calculates the within-sum-of-squares (WSS) for different numbers of clusters,
averaged over several iteratio... | 872 |
def AptInstall(vm):
"""Installs the mysql package on the VM."""
vm.RemoteCommand('echo "mysql-server-5.5 mysql-server/root_password password '
'%s" | sudo debconf-set-selections' % MYSQL_PSWD)
vm.RemoteCommand('echo "mysql-server-5.5 mysql-server/root_password_again '
'passwo... | 873 |
def plot_original_image(filepath):
"""Plot full-color version of original image"""
plt.imshow(cv2.imread(filepath))
plt.title("Original Image")
plt.xticks([])
plt.yticks([])
plt.show() | 874 |
def __main__():
"""Parse the cmd lne options"""
parser = optparse.OptionParser()
parser.add_option("-i", "--input", default=None, dest="input",
help="The input file")
parser.add_option("-p", "--ptt", default=None, dest="ptt",
help="The output ptt file")
parser.add_option("-r", "--rnt", default... | 875 |
def test_toy_example_collapse_points():
"""Test on a toy example of three points that should collapse
We build a simple example: two points from the same class and a point from
a different class in the middle of them. On this simple example, the new
(transformed) points should all collapse into on... | 876 |
def separate_classes(x: np.ndarray, y: np.ndarray) -> List[Tuple[int, np.ndarray]]:
"""Separate samples by classes into a list.
Args:
x (np.ndarray): Samples.
y (np.ndarray): Target labels (classes).
Returns:
List[Tuple[int, np.ndarray]]: List in the format [(class, samples),...]
... | 877 |
def monitor_threads(threads, arguments):
"""
Monitor the threads.
Parameters
----------
threads: dict
The threads to monitor.
arguments: namespace
The parsed command line.
# --GT-- not used, kept to avoid to break the function call.
Returns
-------
int
... | 878 |
def fetch_cfr_parts(notice_xml):
""" Sometimes we need to read the CFR part numbers from the notice
XML itself. This would need to happen when we've broken up a
multiple-effective-date notice that has multiple CFR parts that
may not be included in each date. """
parts = []
for cfr_el... | 879 |
def get_dayofweek(date):
"""
Returns day of week in string format from date parameter (in datetime format).
"""
return date.strftime("%A") | 880 |
def add_model_output(modelIn, mode=None, num_add=None, activation=None):
""" This function modifies the last dense layer in the passed keras model. The modification includes adding units and optionally changing the activation function.
Parameters
----------
modelIn : keras model
Keras model... | 881 |
def parse(f):
"""Parse ASDL from the given file and return a Module node describing it."""
parser = ASDLParser()
return parser.parse(f) | 882 |
def _assert_put_and_patch(usage_examples: UsageExamples, web_app: WebApp):
"""Test PUT and PATH requests."""
info_name = usage_examples.__class__.__name__
test_params = [
('PUT', usage_examples.put_requests),
('PATCH', usage_examples.patch_requests),
]
for http_method, examples_metho... | 883 |
def distance(xyz, lattice, PBC=[1,2,3]):
"""
Returns the Euclidean distance from the origin for a fractional
displacement vector. Takes into account the lattice metric and periodic
boundary conditions, including up to one non-periodic axis.
Args:
xyz: a fractional 3d displacement vector... | 884 |
def main():
"""Do the main thing here"""
print("\n** Jamf computer group upload script")
print("** Creates a computer group in Jamf Pro.")
# parse the command line arguments
args, cli_custom_keys = get_args()
verbosity = args.verbose
# grab values from a prefs file if supplied
jamf_url... | 885 |
def dobro(n=0, formato=False):
"""
Dobrar número
:param n: número a ser dobrado
:param formato: (opicional) mostrar o moeda
:return: resultado
"""
n = float(n)
n += n
return moeda(n) if formato else n | 886 |
def f_q2d(n, m):
"""Lowercase f term for 2D-Q polynomials. oe-20-3-2483 Eq. (A.18b).
Parameters
----------
n : int
radial order
m : int
azimuthal order
Returns
-------
float
f
"""
if n == 0:
return np.sqrt(F_q2d(n=0, m=m))
else:
ret... | 887 |
def binary_search(data, target, low, high):
"""Return position if target is found in indicated portion of a python list and -1 if target is not found.
"""
if low > high:
return -1
mid = (low + high) // 2
if target == data[mid]:
return mid
elif target < data[mid]:
# recur... | 888 |
def delete_position(id):
"""Delete a post.
Ensures that the post exists and that the logged in user is the
author of the post.
"""
db = get_db()
db.execute('DELETE FROM gatekeeping WHERE id = ?', (id,))
db.commit()
return jsonify(status='ok') | 889 |
def read_string(stream, length):
"""read data from the file and return as a text string
"""
text = struct.unpack('{}s'.format(length), stream.read(length))
try:
result = str(text[0], encoding='utf-8')
except UnicodeDecodeError:
result = str(text[0], encoding='latin-1')
return res... | 890 |
def generate_gate_y_hamiltonian_vec() -> np.ndarray:
"""Return the vector representation for the Hamiltonian of a Y gate with respect to the orthonormal Hermitian matrix basis with the normalized identity matrix as the 0th element.
The result is a real vector with size 4.
Parameters
----------
Re... | 891 |
def _semi_implicit_midpoint(ode_fun, jac_fun, y_olds, t_old, f_old, dt, args,
solver_parameters, J00, I):
"""
Calculate solution at t_old+dt using the semi-implicit midpoint
formula. Based on equations IV.9.16a-b of Ref II.
"""
y_older, y_old = y_olds
je_tot=0
i... | 892 |
def test_create_property_etters_inner_fns():
""" Test BaseStyle.create_domain_mode_etters Method """
## Creates a MockFeature and a BaseStyle Object
f = MockFeature()
s = pmk.BaseStyle(f)
## Set up MagicMock for clear_cache method
s.clear_cache = MagicMock()
## Setup style tree for no ... | 893 |
async def test_list_failure(mock_datagram_client):
"""Test the wifi_list command failing."""
with mock_datagram_client:
with pytest.raises(CommandError) as err:
async with Client("192.168.1.100") as client:
_ = await client.wifi.list()
assert str(err.value) == (
... | 894 |
def freeze_session(session,
keep_var_names=None,
output_names=None,
clear_devices=True):
"""
Freezes the state of a session into a pruned computation graph.
Creates a new computation graph where variable nodes are replaced by
constants taking the... | 895 |
def test_regular_method_used(
assert_errors, parse_ast_tree, method, default_options,
):
"""Testing that other methods are working fine."""
tree = parse_ast_tree(magic_method.format(method))
visitor = WrongClassVisitor(default_options, tree=tree)
visitor.run()
assert_errors(visitor, []) | 896 |
def get_system_cpu_times():
"""Return system CPU times as a namedtuple."""
user, nice, system, idle = _psutil_osx.get_system_cpu_times()
return _cputimes_ntuple(user, nice, system, idle) | 897 |
def Mce1(m, q, ξ, *, p=0):
"""
v = Mce1(m, q, ξ, *, p=0)
Compute the value of the even Radial Mathieu function of the first kind
Mce⁽¹⁾ₘ(q, ξ).
Parameters
----------
m : array_like
interger order of the Mathieu function
q : array_like
positive parameter in the Mathieu d... | 898 |
def exec_sync( cmd ):
""" exec command line.
"""
print( cmd )
p = subprocess.Popen(cmd, shell=True)
ret = p.wait()
print('') | 899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.