content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def dict_merge(lft, rgt):
"""
Recursive dict merge.
Recursively merges dict's. not just simple lft['key'] = rgt['key'], if
both lft and rgt have a key who's value is a dict then dict_merge is
called on both values and the result stored in the returned dictionary.
"""
if not isinstance(rgt, ... | 5,329,500 |
def modified_zscore(x: np.ndarray) -> np.ndarray:
"""
Modified z-score transformation.
The modified z score might be more robust than the standard z-score because
it relies on the median for calculating the z-score. It is less influenced
by outliers when compared to the standard z-score.
Param... | 5,329,501 |
def get_packet_unique(data: Union[bytes, memoryview], packet_type: str) -> Optional[Packet]:
"""
Get all the packets of a particular type. If no type is given, returns all packets.
WARNING: packets are generated with non-header data as a `memoryview`.
:param data: The data to search through.
:par... | 5,329,502 |
def test_get_single_ride(test_client):
"""
Test request returns correct ride with specified ID
"""
response = test_client.get('/api/v1/rides/2')
result = json.loads(response.data)
assert response.status_code == 200
assert result['ride']['origin'] == 'Kisumu'
assert result['ride']['destin... | 5,329,503 |
def update_profile(email, username, name, bio, interest, picture=None):
"""更新 profile"""
db = get_db()
cursor = db.cursor()
# query user
user = get_user_by_email(email)
email = user['email']
profile_id = user['profile_id']
if profile_id is None:
# add profile
cursor.exe... | 5,329,504 |
def serialize(object):
"""
Serialize the data into bytes using marshal and zlib
Args:
object: a value
Returns:
Returns a bytes object containing compressed with zlib data.
"""
return zlib.compress(marshal.dumps(object, 2)) | 5,329,505 |
def logo_if(interp, expr, block, elseBlock=None):
"""
IF tf instructionlist
(IF tf instructionlist1 instructionlist2)
command. If the first input has the value TRUE, then IF runs
the second input. If the first input has the value FALSE, then
IF does nothing. (If given a third input, IF acts ... | 5,329,506 |
def select_model_general(
df,
grid_search,
target_col_name,
frequency,
partition_columns=None,
parallel_over_columns=None,
executor=None,
include_rules=None,
exclude_rules=None,
country_code_column=None,
output_path="",
persist_cv_results=False,
persist_cv_data=False,... | 5,329,507 |
def create_arma_sample(ar_order=1, ma_order=1, size=100):
"""Get a random ARMA sample.
Parameters
----------
ar_order, ma_order, size : int
Values for the desired AR order, MA order and sample size.
Returns
-------
An ARMA sample as a pandas Series.
"""
ar_coeff = np.linspa... | 5,329,508 |
def list_field_to_reference(web2py_path, app , new_table_name , new_list_field , list_field_name , old_table_id_field , old_table):
"""
This method handles the migration in which a new table with a column for the
values they'll get from the list field is made and maybe some empty columns to be filled in la... | 5,329,509 |
def get_img(file_path, gray=False):
"""
获取输入图片
:param file_path: 图片文件位置
:param gray: 是否转换为灰度图
:return: img
"""
try:
img = Image.open(file_path)
if gray:
img = img.convert('L')
return img
except Exception:
print("不支持的图片格式")
return None | 5,329,510 |
def working_days(days: int):
"""Return a list of N workingdays
Keyword arguments:
days -- days past
"""
dates = []
today = datetime.utcnow()
for i in range(days):
day = today - timedelta(days=i)
day = day.date()
dates.append(day)
for idx, date in enumerate(date... | 5,329,511 |
def GetFile(message=None, title=None, directory=None, fileName=None,
allowsMultipleSelection=False, fileTypes=None):
"""
An get file dialog.
Optionally a `message`, `title`, `directory`, `fileName` and
`allowsMultipleSelection` can be provided.
::
from fontParts.ui import GetFi... | 5,329,512 |
def str_to_dtype(s):
"""Convert dtype string to numpy dtype."""
return eval('np.' + s) | 5,329,513 |
def integrate_const(
f: Callable,
t_span: Tuple,
dt: float,
y0: np.ndarray,
method: str = 'runge_kutta4'
) -> Tuple[np.ndarray, np.ndarray]:
"""
A Python wrapper for Boost::odeint runge_kutta4 (the only one supported right now)
stepper and ODE integration.
:param f:
The ODE ... | 5,329,514 |
def test_metadata():
"""The metadata of the json file should be correct."""
# Note: The json file should have been created with previous tests
with open(file_struct.features_file) as f:
data = json.load(f)
assert("metadata" in data.keys())
metadata = data["metadata"]
assert("timestamp" i... | 5,329,515 |
def test_execute_error_response(mocker: MockerFixture) -> None:
"""
Test error response handling on execute.
"""
entry_points = [FakeEntryPoint("gsheetsapi", GSheetsAPI)]
mocker.patch(
"shillelagh.backends.apsw.db.iter_entry_points",
return_value=entry_points,
)
adapter = re... | 5,329,516 |
def cleanup(serialized):
"""
Remove all missing values. Sometimes its useful for object methods
to return missing value in order to not include that value in the
json format.
Examples::
>>> User(Serializable):
... def attributes():
... return ['id', 'name', 'bir... | 5,329,517 |
async def discover_devices(
wave_devices: Optional[List[WaveDevice]] = None,
) -> List[WaveDevice]:
"""Discovers all valid, accessible Airthings Wave devices."""
wave_devices = wave_devices if isinstance(wave_devices, list) else []
device: BLEDevice # Typing annotation
for device in await discover... | 5,329,518 |
def convert_examples_to_feats_lstm(examples, max_seq_length, glove_vocab, feat_file, language):
"""Loads a data file into a list of `InputBatch`s in glove+lstm manner"""
print("#examples", len(examples))
if os.path.exists(feat_file):
with open(feat_file, 'rb') as f:
features = pickle.lo... | 5,329,519 |
def experiments():
"""
All statistics we run for our paper
:return:
"""
logger = logging.getLogger(__name__)
logger.info('====================')
logger.info('Citations aggregate:')
logger.info('====================')
classify_citations_basic()
logger.info('===========... | 5,329,520 |
def PyValueToMessage(message_type, value):
"""Convert the given python value to a message of type message_type."""
return JsonToMessage(message_type, json.dumps(value)) | 5,329,521 |
def istype(obj: Any, annotation: type) -> bool:
"""Check if object is consistent with the annotation"""
if get_origin(annotation) is None:
if annotation is None:
return obj is None
return isinstance(obj, annotation)
else:
raise NotImplementedError("Currently only the basi... | 5,329,522 |
def autolabel(rects):
"""Attach a text label above each bar in *rects*, displaying its height."""
for rect in rects:
height = rect.get_height()
ax.annotate(yformat.format(height),
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 0),
... | 5,329,523 |
def test_cand_gen(caplog):
"""Test extracting candidates from mentions from documents."""
caplog.set_level(logging.INFO)
if platform == "darwin":
logger.info("Using single core.")
PARALLEL = 1
else:
logger.info("Using two cores.")
PARALLEL = 2 # Travis only gives 2 core... | 5,329,524 |
def spending_from_savings(take_home_pay: float, savings: float) -> Decimal:
"""
Calculate your spending based on your take home pay and how much
you save. This is useful if you use what Paula Pant calls the anti-budget,
instead of tracking your spending in detail. This number can be used as
input fo... | 5,329,525 |
def find_all_run_dirs(
base_output_dir: pathlib.Path,
state: str,
site: str,
stage: PipelineStage,
) -> Iterator[pathlib.Path]:
"""Find latest stage output path"""
stage_dir = base_output_dir / state / site / STAGE_OUTPUT_NAME[stage]
if not stage_dir.exists():
return
for run_di... | 5,329,526 |
def stdlib_public_names(module: str, *, version: str = None) -> set[str]:
"""
Return a set of public names of a stdlib module, in specific Python version.
If no version is given, default to the current version.
The `version` parameter takes argument of the form `3.9`, `4.7`, etc.
"""
if modul... | 5,329,527 |
def large_asymmetric_bulge(data):
"""
:param data: image data as array
:return: the width and location of the largest asymmetric bulge (if any) in the sequence
"""
# retrieve the lengths of the bars in the sequences (the counts) from the palindrome function
score, upper_half_counts, lower_half_c... | 5,329,528 |
def test_mcari(spectral_index_test_data):
"""Test for PlantCV."""
index_array = spectral_index.mcari(spectral_index_test_data.load_hsi(), distance=20)
assert np.shape(index_array.array_data) == (1, 1600) and np.nanmax(index_array.pseudo_rgb) == 255 | 5,329,529 |
def test_compound_includes(client, compound_factory, endpoint, substance_factory):
"""Tests that /compound endpoints can be provided an include parameter"""
compound = compound_factory().instance
substance_factory(
associated_compound={"type": compound.serializer_name, "id": compound.pk}
)
... | 5,329,530 |
def request(host, path, bearer_token, url_params):
"""Given a bearer token, send a GET request to the API.
Args:
host (str): The domain host of the API.
path (str): The path of the API after the domain.
bearer_token (str): OAuth bearer token, obtained using client_id and client_secret.
... | 5,329,531 |
def find_unique_distances(distance_ij: pd.Series) -> np.ndarray:
"""Finds the unique distances that define the neighbor groups.
:param distance_ij: A pandas ``Series`` of pairwise neighbor distances.
:return: An array of unique neighbor distances.
"""
unique_floats: np.ndarray = np.sort(distance_ij... | 5,329,532 |
def push_msg(msg_type, content, key):
"""推送消息到企业微信群
content格式参考: https://work.weixin.qq.com/api/doc/90000/90136/91770
"""
api_send = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={}".format(key)
data = {"msgtype": msg_type, msg_type: content}
response = requests.post(api_send, json=data... | 5,329,533 |
def session(monkeypatch: pytest.MonkeyPatch) -> nox.Session:
"""Fixture for a Nox session."""
registry: Dict[str, Any] = {}
monkeypatch.setattr("nox.registry._REGISTRY", registry)
@nox.session(venv_backend="none")
def test(session: nox.Session) -> None:
"""Example session."""
config = ... | 5,329,534 |
def _load_yaml_with_clear_tag(stream):
"""Like yaml.safe_load(), but everything with a !clear tag before it
will be wrapped in ClearedValue()."""
loader = yaml.SafeLoader(stream)
loader.add_constructor('!clear', _cleared_value_constructor)
try:
return loader.get_single_data()
finally:
... | 5,329,535 |
def get_7K_info(device_dict, collection):
"""
Checks Palo firewall to see if model and family are in the 7K family,
sets variables, and then gets 7K info
Parameters
----------
device_dict : dict
A dictionary of Panorama connected devices
collection : Collection
A MongoDB dat... | 5,329,536 |
def highlights(state_importance_df, exec_traces, budget, context_length, minimum_gap=0,
overlay_limit=0):
"""generate highlights summary"""
sorted_df = state_importance_df.sort_values(['importance'], ascending=False)
summary_states, summary_traces, state_trajectories = [], [], {}
seen_in... | 5,329,537 |
def draw_figure(canvas, figure, loc=(0, 0)):
"""
Draw a matplotlib figure onto a Tk grafica
loc: location of top-left corner of figure on grafica in pixels.
Inspired by matplotlib source: lib/matplotlib/backends/backend_tkagg.py
"""
figure_canvas_agg = FigureCanvasAgg(figure)
figure_canvas... | 5,329,538 |
def beautify_file(sources_file_path, len: int):
"""
Check file if everything is aligned
"""
for line in fileinput.input(sources_file_path, inplace=True):
if ".c" in line:
print('{0:{len}}{1}'.format(line.rstrip(), "\t\\\n", len=len), end='')
elif "+=" in line and "_BONUS" not in line:
print('{0:{len}}{1}'... | 5,329,539 |
def rpi_audio_support_install(junk, audio=None):
"""
Install audio support drivers (pimoroni or waveshare) on the remote Raspberry Pi device
"""
if audio=="pimoroni" or audio=="waveshare":
install_audio_drivers(orig_cxn, audio)
else:
print("Please provide a Raspberry Pi audio driver ... | 5,329,540 |
def find_struct(lines):
"""Finds structures in output data"""
struct = ''
name1 = ''
name2 = ''
seq1 = ''
seq2 = ''
result = []
for line in lines:
if line.startswith('; ========'):
break
if line.startswith('; ALIGNING'):
line = line.split()
... | 5,329,541 |
def check_config_db():
"""Check that the config DB has the configured PBs.
Only run this step if the config DB is enabled.
"""
if ska_sdp_config is not None \
and SDPSubarray.is_feature_active('config_db'):
filename = join(dirname(__file__), 'data', 'command_Configure.json')
... | 5,329,542 |
def chain(*fs: Callable) -> Callable:
"""
Compose given functions in reversed order.
Given functions f, g, the result of chain is chain(f, g) = g o f.
>>> def f(x: int) -> int:
... return x + 1
>>> def g(x: int) -> str:
... return str(x)
>>> chain(f, g)(41)
'42'
Chai... | 5,329,543 |
def astra_fp_2d_fan(volume, angles, source_object, object_det):
"""
:param volume:
:param angles: degrees
:return:
"""
detector_size = volume.shape[1]
proj_geom = build_proj_geometry_fan_2d(detector_size, angles, source_object, object_det)
rec = astra_fp_2d(volume, proj_geom)
return... | 5,329,544 |
def get_remappings_prefix() -> Mapping[str, str]:
"""Get the remappings for xrefs based on the prefix.
.. note:: Doesn't take into account the semicolon `:`
"""
return _get_curated_registry()['remappings']['prefix'] | 5,329,545 |
def generate_schema():
""" schema generation from today filename dataset """
today = date.today().strftime("%d_%m_%Y")
complete_dataset = pd.read_csv(f"complete_dataset_{today}.csv")
json_schema = pd.io.json.build_table_schema(complete_dataset)
with open("json_schema_for_big_query.json", "w", encodi... | 5,329,546 |
def upsample_labels_in_dir(labels_dir,
target_res,
result_dir,
path_label_list=None,
path_freesurfer='/usr/local/freesurfer/',
recompute=True):
"""This funtion upsamples all label m... | 5,329,547 |
def test_zamichani_hry():
"""Každá hra by měla být jiná"""
from klondike import udelej_hru
hra1 = udelej_hru()
hra2 = udelej_hru()
# Je šance 1 z 80658175170943878571660636856403766975289505440883277824000000000000,
# že dvě náhodné hry budou stejné.
# Nejspíš je pravděpodobnější, že v průb... | 5,329,548 |
def create_search_index(*args, **kwargs):
"""
Creates the search index in elastic search
"""
manage('setup_index') | 5,329,549 |
def read_hdf5(filename, **kwargs):
"""
read a grid file in hdf5 into a microquake.core.data.grid.GridCollection
object
:param filename: filename
:param kwargs: additional keyword argument passed from wrapper.
:return: microquake.core.data.grid.GridCollection
""" | 5,329,550 |
def binary_truncated_sprt_with_llrs(llrs, labels, alpha, beta, order_sprt):
""" Used in run_truncated_sprt_with_llrs .
Args:
llrs: A Tensor with shape (batch, duration). LLRs (or scores) of all frames.
labels: A Tensor with shape (batch,).
alpha : A float.
beta: A float.
... | 5,329,551 |
def backoff(action, condition, max_attempts=40):
"""
Calls result = action() up to max_attempts times until condition(result) becomes true, with 30 s backoff. Returns a bool flag indicating whether condition(result) was met.
"""
timeout = 30
for attempt in range(max_attempts):
result = action()
if c... | 5,329,552 |
def get_file_info(repo, path):
"""we need change_count, last_change, nbr_committers."""
committers = []
last_change = None
nbr_changes = 0
for commit in repo.iter_commits(paths=path):
#print(dir(commit))
committers.append(commit.committer)
last_change = commit.committed_date... | 5,329,553 |
def retryable_session(session: requests.Session, retries: int = 8) -> requests.Session:
"""
Session with requests to allow for re-attempts at downloading missing data
:param session: Session to download with
:param retries: How many retries to attempt
:return: Session that does downloading
"""
... | 5,329,554 |
def load_model(checkpoint: Dict[str, Dict], model: Optional['BaseMethod'] = None,
buffer: Optional['BufferBase'] = None,
datasets: Optional[Dict[str, Dataset]] = None) -> None:
"""
Loads the state dicts of the model, buffer and datasets
Args:
checkpoint (Dict[str, Dict... | 5,329,555 |
def apply_affine(x, y, z, affine):
""" Apply the affine matrix to the given coordinate.
Parameters
----------
x: number or ndarray
The x coordinates
y: number or ndarray
The y coordinates
z: number or ndarray
The z coordinates
affi... | 5,329,556 |
def binary_dilation_circle(input, radius):
"""Dilate with disk of given radius.
Parameters
----------
input : array_like
Input array
radius : float
Dilation radius (pix)
Returns
-------
TODO
"""
from scipy.ndimage import binary_dilation
structure = binary_di... | 5,329,557 |
def test_default_values():
"""
Tests that default values seem to have a physical meaning,
e.g. rho decreases with T, increases with S
"""
T_ref = 10
S_ref = 35
assert isclose(eos.compute_rho(T=T_ref, S=S_ref, z=0), 1026)
all_T = np.linspace(-1, 30, 10)
all_S = np.linspace(31, 37, 1... | 5,329,558 |
def set_debug(enabled):
"""
Enable or disable the debug mode. In debug mode, a bunch of extra checks in claripy will be executed. You'll want to
disable debug mode if you are running performance critical code.
"""
global _DEBUG
_DEBUG = enabled | 5,329,559 |
def square_valid(board: Board, n: int, pawn_value: int, x: int, y: int) -> bool:
"""Check if the square at x and y is available to put a pawn on it."""
return (coordinates_within_board(n, x, y) and
square_playable(board, pawn_value, x, y)) | 5,329,560 |
def test_Remove_Disk_At__Overflow_Disk(score, max_score):
"""Function remove_disk_at: overflow disk."""
max_score.value += 2
try:
set_up()
disk = Disk.init_disk(Disk.VISIBLE,4)
Board.set_disk_at(test_board_4,(3,5),disk)
Board.remove_disk_at(test_board_4, (3, 5))
asser... | 5,329,561 |
def epb2jd(epb):
""" Besselian epoch to Julian date.
:param epb: Besselian epoch.
:type epb: float
:returns: a tuple of two items:
* MJD zero-point, always 2400000.5 (float)
* modified Julian date (float).
.. seealso:: |MANUAL| page 76
"""
djm0 = _ct.c_double()
djm = ... | 5,329,562 |
def one_hot_decision_function(y):
"""
Examples
--------
>>> y = [[0.1, 0.4, 0.5],
... [0.8, 0.1, 0.1],
... [0.2, 0.2, 0.6],
... [0.3, 0.4, 0.3]]
>>> one_hot_decision_function(y)
array([[ 0., 0., 1.],
[ 1., 0., 0.],
[ 0., 0., 1.],
... | 5,329,563 |
def combine_incomes(toshl_income, excel_income):
"""
Combines two data sources of incomes: toshl incomes and incomes from cashflow excel.
:param toshl_income: Preprocessed dataframe of toshl incomes (after cleaning and splitting)
:param excel_income: Raw excel income data
:return: Total income data
... | 5,329,564 |
def generate_k(data_set, k):
"""
Given `data_set`, which is an array of arrays,
find the minimum and maximum for each coordinate, a range.
Generate `k` random points between the ranges.
Return an array of the random points within the ranges.
"""
centers = []
dimensions = len(data_set[0])
min_max = defaultdict(... | 5,329,565 |
def __ping_url(url: str) -> bool:
"""Check a link for rotting."""
try:
r = requests.head(url)
return r.status_code in (
requests.codes.ok,
requests.codes.created,
requests.codes.no_content,
requests.codes.not_modified,
)
except Exceptio... | 5,329,566 |
def get_all_list_data():
"""
Handles the GET request to '/get-all-list-data'.
:return: Json with all list data
"""
conn = get_db()
all_types = TypeDataAccess(conn).get_types(False)
all_tags = TagDataAccess(conn).get_tags()
all_groups = ResearchGroupDataAccess(conn).get_research_groups(F... | 5,329,567 |
def truncate_range(data, percMin=0.25, percMax=99.75, discard_zeros=True):
"""Truncate too low and too high values.
Parameters
----------
data : np.ndarray
Image to be truncated.
percMin : float
Percentile minimum.
percMax : float
Percentile maximum.
discard_zeros : ... | 5,329,568 |
def obtain_dcdb_to_drugbank(biana_cnx, unification_protocol, output_pickle_file):
"""
Obtain a dictionary {dcdb : drugbank}
"""
up_table = return_unification_protocol_table(biana_cnx, unification_protocol)
query = ('''SELECT DC.value, DB.value FROM externalEntityDCDB_drugID DC, {} U1, {} U2, exter... | 5,329,569 |
def duo_username(user):
""" Return the Duo username for user. """
return user.username | 5,329,570 |
def random_number_list(data=[]):
""" Add random number between 0 and 9 (both inclusive) to a list """
for i in range( 0, list_length ):
# append a random int to the data list
data.append( random.randint(0, 10))
return data | 5,329,571 |
def _UpdateFailureInfoBuilds(failed_steps, builds):
"""Deletes builds that are before the farthest last_pass."""
build_numbers_in_builds = builds.keys()
latest_last_pass = -1
for failed_step in failed_steps.itervalues():
if not failed_step.last_pass:
return
if (latest_last_pass < 0 or latest_last... | 5,329,572 |
def _matrix_method_reshape(df: pd.DataFrame) -> pd.DataFrame:
"""
Reshape df for matrix method and deal with missing values.
We first drop columns which contain all missing values, transpose
the dataframe and then fill the remaining missing values with zero,
to deal with missing items in some period... | 5,329,573 |
def orbitrap(file_path):
"""Import Orbitrap data from XCalibur export. Designed for scan by scan Orbitrap data.
Original export of example data performed by Cech lab @ UNCG. Example data in MS_data external in Cech directory
"""
headers = ["scan", "rt", "mz", "drift", "intensity"]
input_data = []
... | 5,329,574 |
def sim_bursty_oscillator(T, Fs, freq, prob_enter_burst=.1,
prob_leave_burst=.1, cycle_features=None,
return_cycle_df=False):
"""Simulate a band-pass filtered signal with 1/f^2
Input suggestions: f_range=(2,None), Fs=1000, N=1001
Parameters
----------... | 5,329,575 |
def visualize_percent_diff(df):
"""Creates a visualization of difference in percentage of tweets of a topic
across the entire US and returns the mean sentiment felt about the
topic across the entire US
Parameters:
-----------
df: pd.DataFrame
dataframe containing all tweets. Must conta... | 5,329,576 |
def basic_compare(first, second, strict=False):
"""
Comparison used for custom match functions,
can do pattern matching, function evaluation or simple equality.
Returns traceback if something goes wrong.
"""
try:
if is_regex(second):
if not isinstance(first, six.... | 5,329,577 |
def usage():
"""Prints simple usage information."""
print '-o <file> the old bench output file.'
print '-n <file> the new bench output file.'
print '-h causes headers to be output.'
print '-f <fieldSpec> which fields to output and in what order.'
print ' Not specifying is the same as -f "... | 5,329,578 |
def display(lines, out):
"""Display text to user.
Args:
lines (str): lines of text to display
out (object): file object used by interpreter for output
Note:
original behavior: lines displayed in scrollable window, similar to
"less" shell command.
behavior with patch: lines printed... | 5,329,579 |
def parse_line(line,):
"""Return a list of 2-tuples of the possible atomic valences for a given line from
the APS defining sheet."""
possap = []
for valence, entry in enumerate(line[4:]):
if entry != "*":
possap.append((valence, int(entry)))
return possap | 5,329,580 |
def first_order_moments(X, min_words=3):
"""First-Order Moments
Generate first order Moment of document-word frequency matrix.
Parameters
----------
X : array-like or sparse matrix, shape=(n_samples, n_features)
Matrix of Document-word frequency. `n_samples` is the
number of do... | 5,329,581 |
def dashboard():
"""Получить статистику по сайту"""
user = get_user_from_request()
if not user.is_admin:
return errors.no_access()
users = User.select().count()
d = datetime.datetime.now() - datetime.timedelta(days=7)
active_users = User.select().where(User.last_active_date > d).count... | 5,329,582 |
def dct(f, axis=-1):
"""
Compute the Discrete Cosine Transform over the specified axis.
:param f: The input array.
:param axis: Axis along which the DCT is computed. The default is over the last axis.
:return c: The computed DCT.
"""
# Size of the input along the specified axis.
... | 5,329,583 |
def get_create_data_dir():
"""Get the data directory.
When the directory does not exist it is created.
"""
# Calculate the dataset data dir
data_dir = Path(get_data_dir()).expanduser()
dataset = _dataset_settings['name']
dataset_dir = data_dir / dataset
# Ensure that the directlry exis... | 5,329,584 |
def test_gate_translation(gate):
"""Test gate operations with MyQLM interface"""
myqlm_operation = myqlm_call_operation(operation=gate[0],
qureg=qubits)
assert myqlm_operation == gate[1] | 5,329,585 |
def interpolate_bezier(points, steps=100, **kwargs):
"""Generates an array of waypoints which lie on a 2D Bezier curve described by n (x, y) points. The trajectory is
guaranteed to include the start and end points though only on (x, y, z) axes.
The curve generated is of the nth degree, where n = len(points... | 5,329,586 |
def show_update_log_p_src_gives_correct_qualitative_behavior_for_examples(
pos=(1.5, 0.7), dt=0.1, w=0.5,
d=0.05, r=100, a=0.003, tau=1000, src_radius=0.02):
"""
Plot the resulting source posteriors (where prior is uniform) following
miss and hit at given sampling position.
"""
from ... | 5,329,587 |
def update_readme(image_name: str, readme_path: str) -> str:
"""Update README section on DockerHub."""
show_info(f"Updating README seciton for {image_name}")
repo = DOCKER_REPOSITORY.split("/")[-1]
uri = f"{DOCKER_API_URL}/repositories/{repo}/{image_name}/"
with open(readme_path) as fd:
re... | 5,329,588 |
def _EAMS(track, Xmin=0.55, i0=12):
"""
Early-Age Main Sequence. Without this, the low-mass tracks do not
reach an EEP past the ZAMS before 15 Gyr.
"""
i_EAMS = _IorT_AMS(track, Xmin, i0)
return i_EAMS | 5,329,589 |
def neighboring_pairs(dataset, text_key='text', reuse_sentences=True):
"""Create a dataset consisting of neighboring sentence pairs.
The input examples should have a key text_key associated with a tf.string
value.
The output examples have keys 'first' and 'second'.
We only take sentence pairs from within t... | 5,329,590 |
def decode(tokenizer, token):
"""decodes the tokens to the answer with a given tokenizer"""
answer_tokens = tokenizer.convert_ids_to_tokens(
token, skip_special_tokens=True)
return tokenizer.convert_tokens_to_string(answer_tokens) | 5,329,591 |
def test_clear_location():
"""
Tests clear location
:return:
"""
a = ListFile()
# try to clear location that isnt defined
with pytest.raises(AssertionError):
a.clear_location(1234)
a.insert_data(1234, 'AAAA')
assert a.get_starting_data(1234) is 'AAAA'
... | 5,329,592 |
def davis_jaccard_measure(fg_mask, gt_mask):
""" Compute region similarity as the Jaccard Index.
:param fg_mask: (ndarray): binary segmentation map.
:param gt_mask: (ndarray): binary annotation map.
:return: jaccard (float): region similarity
"""
gt_mask = gt_mask.astype(np.bool)
fg_mask =... | 5,329,593 |
def extract_logits(logits = None, seq_pos = None):
"""
Args
logits: Tensor(batch_size,seq_length,vocab_size) e.g.(8,1024,50257)
seq_pos: list(batch_size)
Return:
output_logits: Tensor(batch_size,1,vocab_size) extract the Specified logit according to the seq_pos list .
"""
... | 5,329,594 |
def CollectSONAME(args):
"""Replaces: readelf -d $sofile | grep SONAME"""
toc = ''
readelf = subprocess.Popen(wrapper_utils.CommandToRun(
[args.readelf, '-d', args.sofile]),
stdout=subprocess.PIPE,
bufsize=-1,
universal_n... | 5,329,595 |
def padRect(rect, padTop, padBottom, padLeft, padRight, bounds, clipExcess = True):
"""
Pads a rectangle by the specified values on each individual side,
ensuring the padded rectangle falls within the specified bounds.
The input rectangle, bounds, and return value are all a tuple of (x,y,w,h).
"""
# Unpack th... | 5,329,596 |
def gcs_csv_to_table(full_table_id: str, remote_csv_path: str) -> Table:
"""
Insert CSV from Google Storage to BigQuery Table.
:param full_table_id: Full ID of a Google BigQuery table.
:type full_table_id: str
:param remote_csv_path: Path to uploaded CSV.
:type remote_csv_path: str
:returns... | 5,329,597 |
def _get_client(args: argparse.Namespace) -> NodeClient:
"""Returns a pycspr client instance.
"""
return NodeClient(NodeConnectionInfo(
host=args.node_host,
port_sse=args.node_port_sse
)) | 5,329,598 |
def test_keyword__DeleteForm__1(address_book, KeywordFactory, browser):
"""Deletion can be canceled in the `DeleteForm`."""
KeywordFactory(address_book, u'friend')
browser.login('editor')
browser.open(browser.KEYWORD_EDIT_URL)
browser.getControl('Delete').click()
# There is a confirmation dialog... | 5,329,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.