content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def HVA_TFIM_2D_data(weights, x, wires, n_layers=1, types = 1):
"""
1-d Ising-coupling HVA_TFIM feature map, according to 2008.02941v2.11075.
:param weights: trainable weights of shape 2*n_layers*n_wires
:param 1d x: input, len(x) is <= len(wires)
:param wires: list of wires on which the feature ma... | 25,800 |
def _get_jones_types(name, numba_ndarray_type, corr_1_dims, corr_2_dims):
"""
Determine which of the following three cases are valid:
1. The array is not present (None) and therefore no Jones Matrices
2. single (1,) or (2,) dual correlation
3. (2, 2) full correlation
Parameters
----------
... | 25,801 |
def editing_passport_serial_handler(update: Update,
context: CallbackContext) -> int:
"""Get and save passport serial."""
new_state = editing_pd(update, context,
validator=validators.passport_serial_validator,
attribute='p... | 25,802 |
def get_overview(ticker: str) -> pd.DataFrame:
"""Get alpha vantage company overview
Parameters
----------
ticker : str
Stock ticker
Returns
-------
pd.DataFrame
Dataframe of fundamentals
"""
# Request OVERVIEW data from Alpha Vantage API
s_req = f"https://www.a... | 25,803 |
def effective_sample_size(samples):
"""
Calculates ESS for a matrix of samples.
"""
try:
n_samples, n_params = samples.shape
except (ValueError, IndexError):
raise ValueError('Samples must be given as a 2d array.')
if n_samples < 2:
raise ValueError('At least two samples ... | 25,804 |
def draw_windows():
"""
This draws out a window.
:return:
"""
martin.begin_fill() # lines 88-118 draw out a row consisting of 3 rectangles for windows
for i in range(2):
martin.pendown()
martin.forward(13)
martin.right(90)
martin.forward(20)
martin.right(... | 25,805 |
def test_left_context_third_w():
"""
Test contexte gauche avec mot pivot en 3e position
Résultat chaîne de 2 tokens
"""
sent = "Imagine un monde où les animaux nous mangeraient Ils feraient des ragoûts de nous, des soupes de nous, des burgers de nous"
tokens = sent.split()
l_context = concor... | 25,806 |
def get_credentials(credentials_path):
"""
Gets valid user credentials from storage.
If nothing has been stored, or if the stored credentials are invalid it
returns None.
Returns:
Credentials, the obtained credential or None
"""
store = Storage(credentials_path)
credentials = s... | 25,807 |
def setup(hass, config):
"""Set up this component."""
conf_track = config[DOMAIN][CONF_TRACK]
_LOGGER.info('version %s is starting, if you have ANY issues with this, please report'
' them here: https://github.com/custom-components/custom_updater', __version__)
ha_conf_dir = str(hass.co... | 25,808 |
def coset_enumeration_r(fp_grp, Y, max_cosets=None):
"""
This is easier of the two implemented methods of coset enumeration.
and is often called the HLT method, after Hazelgrove, Leech, Trotter
The idea is that we make use of ``scan_and_fill`` makes new definitions
whenever the scan is incomplete to... | 25,809 |
def get_model(**kwargs):
"""
Returns the model.
"""
model = ShuffleNetV2(**kwargs)
return model | 25,810 |
def absolute_filter_change(baseline_state_dict, target_state_dict):
""" Calculate sum(abs(K2 - K1) / sum(K1))
Args:
baseline_state_dict (dict): state_dict of ori_net
target_state_dict (dict): state_dict of finetune_net
Returns:
sorted_diff (list): sorted values
sorted_index... | 25,811 |
def run_as_admin(argv=None, debug=False):
"""
Helper function to run Python script with admin privileges
"""
shell32 = ctypes.windll.shell32
if argv is None and shell32.IsUserAnAdmin():
return True
if argv is None:
argv = sys.argv
if hasattr(sys, '_MEIPASS'):
# Supp... | 25,812 |
def global_function(a, b, c):
"""global_function documentation.""" | 25,813 |
def load_checkpoints(checkpoint_name):
"""
Load a pretrained checkpoint.
:param checkpoint_name: checkpoint filename
:return: model.state_dict, source_vocabulary, target_vocabulary,
"""
# Get checkpoint from file
checkpoint = torch.load(checkpoint_name, map_location=torch.device('cpu'))
... | 25,814 |
def test_read_latest_all_gsp_historic(db_session):
"""Check main GB/pv/gsp route works"""
forecasts = make_fake_forecasts(
gsp_ids=list(range(0, 10)),
session=db_session,
t0_datetime_utc=datetime.now(tz=timezone.utc),
)
db_session.add_all(forecasts)
update_all_forecast_lates... | 25,815 |
def __update_background():
"""Summary
"""
obj = get_sprite('__backdrop__')
if obj and obj._surf:
backdrop_heigth = obj._surf.get_height()
backdrop_width = obj._surf.get_width()
screen_width, screen_height = this.size
for y in range(0, screen_height, backdrop_heigt... | 25,816 |
def _extract_data(prices, n_markets):
""" Extract the open, close, high and low prices from the price matrix. """
os = prices[:, :, :n_markets]
cs = prices[:, :, n_markets:2*n_markets]
hs = prices[:, :, 2*n_markets:3*n_markets]
ls = prices[:, :, 3*n_markets:4*n_markets]
return os, cs, hs, ls | 25,817 |
def active(run_dir: str = './run',
datasets_dir: str = './data', dataset: str = 'mnist', dataset_size: int=60000,
augmentation: bool = False, validation: int = 0, shuffle: bool = False,
initial_balance : bool = False,
initial_num_per_class: int = 100,
subset_bias... | 25,818 |
def make_screen():
"""creates the code for a new screen"""
return pygame.display.set_mode((800,600)) | 25,819 |
def listFiles(sDir,ext="_du.mpxml"):
"""
return 1 list of files
"""
lsFile = sorted([_fn
for _fn in os.listdir(sDir)
if _fn.lower().endswith(ext) or _fn.lower().endswith(ext)
])
return lsFile | 25,820 |
def flip_vert(r, c, row, col, reversed):
"""1번 연산"""
if reversed:
row, col = col, row
return row - 1 - r, c, reversed | 25,821 |
def periodic_forecast(
covariate,
output_array,
period,
):
"""Repeats the covariate with a periodic schedule.
Args:
covariate: Assumed to have dimensions [# locations x # days].
output_array: The output array where the results will be written.
period: The period with which to repeat the dat... | 25,822 |
def binary_classification():
"""
逻辑回归
:return:
"""
model = Sequential()
model.add(Dense(32, activation='relu', input_dim=100))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop',
loss='binary_crossentropy',
metrics=['accuracy']... | 25,823 |
def get_orders(self, **kwargs):
"""
|
| **Current All Open Orders (USER_DATA)**
| *Get all open orders on a symbol. Careful when accessing this with no symbol.*
| *If the symbol is not sent, orders for all symbols will be returned in an array.*
:API endpoint: ``GET /dapi/v1/openOrders``
:AP... | 25,824 |
def update_amount(amount_id: int):
"""This function update a data of amount
Args:
amount_id (int): id of amount
Returns:
Response: description of amount
"""
current_app.logger.debug('In PUT /api/amounts/<int:amount_id>')
response = None
try:
# Load data
... | 25,825 |
def en_13757(data: bytes) -> int:
"""
Compute a CRC-16 checksum of data with the en_13757 algorithm.
:param bytes data: The data to be computed
:return: The checksum
:rtype: int
:raises TypeError: if the data is not a bytes-like object
"""
_ensure_bytes(data)
return _crc_16_en_13757... | 25,826 |
def DEFINE_multi_enum(name, default, enum_values, help=None, flag_values=_flagvalues.FLAGS, case_sensitive=True,
**args):
"""Registers a flag whose value can be a list strings from enum_values.
Use the flag on the command line multiple times to place multiple
enum values into the list... | 25,827 |
def get_agent_supported_features_list_for_extensions():
"""
List of features that the GuestAgent currently supports (like Extension Telemetry Pipeline, etc) needed by Extensions.
We need to send this list as environment variables when calling extension commands to inform Extensions of all the
features t... | 25,828 |
def test_wps_ext_proto_nack_m3_no_msg_type(dev, apdev):
"""WPS and NACK M3 no Message Type"""
eap_id, e_nonce, r_nonce, bssid = wps_nack_m3(dev, apdev)
logger.debug("Send NACK to STA")
msg, attrs = build_nack(eap_id, e_nonce, r_nonce, msg_type=None)
send_wsc_msg(dev[0], bssid, msg)
dev[0].reques... | 25,829 |
def GCMV(image, mask=None):
"""
:param image: input image, color (3 channels) or gray (1 channel);
:param mask: calc gamma value in the mask area, default is the whole image;
:return: gamma, and output
"""
# Step 1. Check the inputs: image
if np.ndim(image) == 3 and image.shape[-1... | 25,830 |
def downloadStaffFile(request: HttpRequest, filename: str) -> Union[HttpResponse, FileResponse]:
"""Serves the specified 'filename' validating the user is logged in and a staff user"""
return _downloadFileFromStorage(storages.StaffStorage(), filename) | 25,831 |
def get_view_renderer_type(*args):
"""
get_view_renderer_type(v) -> tcc_renderer_type_t
Get the type of renderer currently in use in the given view (
'ui_get_renderer_type' )
@param v (C++: TWidget *)
"""
return _ida_kernwin.get_view_renderer_type(*args) | 25,832 |
async def create(req):
"""
Add a new label to the labels database.
"""
data = req["data"]
async with AsyncSession(req.app["pg"]) as session:
label = Label(
name=data["name"], color=data["color"], description=data["description"]
)
session.add(label)
try:... | 25,833 |
def process_radial_velocity(procstatus, dscfg, radar_list=None):
"""
Estimates the radial velocity respect to the radar from the wind velocity
Parameters
----------
procstatus : int
Processing status: 0 initializing, 1 processing volume,
2 post-processing
dscfg : dictionary of d... | 25,834 |
def brute_force_diagonalize(answers, wordlist=WORDS, quiet=False):
"""
Find the most cromulent diagonalization for a set of answers, trying all
possible orders. See README.md for a cool example of this with 10 answers.
As a somewhat artificial example, let's suppose we have these seven
answers from... | 25,835 |
def train():
"""
MNIST training set creator.
It returns a reader creator, each sample in the reader is image pixels in
[-1, 1] and label in [0, 9].
:return: Training reader creator
:rtype: callable
"""
return reader_creator(
paddle.dataset.common.download(TRAIN_IMAGE_URL, 'mnis... | 25,836 |
def f_setup():
"""Creates test file in `./data/` dir."""
open("../data/test.txt", "w") | 25,837 |
def sign_v2(key, msg):
"""
AWS version 2 signing by sha1 hashing and base64 encode.
"""
return base64.b64encode(hmac.new(key, msg.encode("utf-8"), hashlib.sha1).digest()) | 25,838 |
def graph_apply(fun, *args):
"""Currying wrapper around APP(-,-)."""
result = fun
for arg in args:
arg = as_graph(arg)
result = APP(result, arg)
return result | 25,839 |
def find_hcf(a, b) :
""" Finds the Highest Common Factor among two numbers """
#print('HCF : ', a, b)
if b == 0 :
return a
return find_hcf(b, a%b) | 25,840 |
def GAU_pdf(x: np.ndarray, mu: float, var: float) -> np.ndarray:
"""
Probability function of Guassian distribution
:param x: ndarray input parameters
:param mu: float mean of the distribution
:param var: float variance of the distribution
:return: ndarray probability of each sample
"""
k... | 25,841 |
def version_compare(a, b): # real signature unknown; restored from __doc__
"""
version_compare(a: str, b: str) -> int
Compare the given versions; return a strictly negative value if 'a' is
smaller than 'b', 0 if they are equal, and a strictly positive value if
'a' is larger than 'b'.
"""
... | 25,842 |
def line_status():
"""
设备线路详情
:return:
"""
device_id = request.args.get("device_id")
lines = Line.objects(device_id=device_id).all()
result = Monitor.device_status(device_id, lines)
result.pop(0)
return Success(result) | 25,843 |
def namedPositionals(func, args):
"""Given a function, and a sequence of positional arguments destined
for that function, identifies the name for each positional argument.
Variable positional arguments are given an automatic name.
:arg func: Function which will accept ``args`` as positionals.
:arg ... | 25,844 |
def _hist_fig(df, pred, c):
"""
"""
bins = np.linspace(0, 1, 15)
unlabeled = pred[c][pd.isnull(df[c])].values
fig, (ax1, ax2) = plt.subplots(2,1)
# top plot: training data
pos_labeled = pred[c][(df[c] == 1)&(df["validation"] == False)].values
neg_labeled = pred[c][(df[c] =... | 25,845 |
def is_responsive(url, code=200):
"""Check if something responds to ``url`` syncronously"""
try:
response = requests.get(url)
if response.status_code == code:
return True
except requests.exceptions.RequestException as _e:
pass
return False | 25,846 |
def run_ranking_module():
"""
Ranks the severity of the outliers based on three metrics.
Metric1 - Threshold based.
Metric2 - Uses the Pagerank Algorithm.
Metric3 - By building a feature dependency graph.
final_score of outlier = node_score of outlier * prob_score of outlier.
Input:
... | 25,847 |
def train(dataset_dir):
"""
Use provided dataset to train a classifier and calculate it's performance. Creates pickle files to
store the intermediate results along with the trained classifier.
Parameters
----------
dataset_dir : string
The relative path of the dataset to load. Must be an... | 25,848 |
def fit_and_report(model, X, y, X_valid, y_valid):
"""
It fits a model and returns train and validation scores.
Parameters:
model (sklearn classifier model): The sklearn model
X (numpy.ndarray): The X part of the train set
y (numpy.ndarray): The y part of the train set
... | 25,849 |
def merge(vis: plt.bar,
array: np.ndarray,
array_size: int,
pause_short: float,
i: int = 0,
key: int = -1) \
-> None:
"""Recursively splits input in halves. Sorts each element at each level bottom up.
Complexity: Time - O(nlog(n)), Space - O(n), Stabl... | 25,850 |
def move_all_generation_to_high_voltage(data):
"""Move all generation sources to the high voltage market.
Uses the relative shares in the low voltage market, **ignoring transmission losses**. In theory, using the production volumes would be more correct, but these numbers are no longer updated since ecoinvent ... | 25,851 |
def basic_meas(
user_config_dict,
simulation_config_dict,
btk_input,
):
"""Checks if detection output from the default meas generator matches
the pre-computed value .
The outputs from basic meas generator were visually checked and verified.
This function makes sure that and changes made to... | 25,852 |
def parser_first_text_or_content_if_could(html: etree._Element,
query_path: str) -> Union[str, None]:
"""
如果解析出的内容是一个数组,默认取的第一个
"""
nodes = html.xpath(query_path)
if not nodes:
return None
if len(nodes) > 0:
desc = nodes[0]
if ha... | 25,853 |
def get_file_paths_from(dir: Text) -> List[Text]:
"""
list all file paths inside a directory.
:param dir: a directory path that need to list.
:return: a string list of file paths.
"""
if not os.path.exists(dir):
logging.info('{} does not exist.'.format(dir))
return None
file... | 25,854 |
def get_all_quantity(results, q_func=None):
"""
"""
quantities = []
for res_name in results:
if q_func is not None:
# We change the quantity function
results[res_name].q_func = q_func
min_quantity = results[res_name].min_quantity
quantities.append(min_quan... | 25,855 |
def test_driver_get_latest_version(index_driver, database_conn):
"""
Tests retrieval of the latest record version
"""
baseid = str(uuid.uuid4())
for _ in range(10):
did = str(uuid.uuid4())
rev = str(uuid.uuid4())[:8]
size = 512
form = 'object'
baseid = str(u... | 25,856 |
def generate_example_type_2a(problem, one_step_inferences):
"""Generates a type 2a training example.
Args:
problem: a lib.InferenceProblem instance.
one_step_inferences: the list of one step inferences that can be reahced
form the premises.
Returns:
An instance of "Example", or None if any iss... | 25,857 |
def name_has_type_hint(name: str, frame: types.FrameType) -> str:
"""Identifies if a variable name has a type hint associated with it.
This can be useful if a user write something like::
name : something
use(name)
instead of::
name = something
use(name)
and sees a Na... | 25,858 |
def user_input(address, interface=None, name=None, filename='config.yaml'):
"""
Gather user input for adding an instrument to the YAML configuration file
Parameters
----------
address : dict
The interface as dict key (i.e. 'pyvisa') and the address as the value
name : str
Instru... | 25,859 |
def matchings(A, B):
"""
Iterate through all matchings of the sets `A` and `B`.
EXAMPLES::
sage: from sage.combinat.ncsym.ncsym import matchings
sage: list(matchings([1, 2, 3], [-1, -2]))
[[[1], [2], [3], [-1], [-2]],
[[1], [2], [3, -1], [-2]],
[[1], [2], [3, -2],... | 25,860 |
def query_title_bar_text(shared_state):
"""return text for title bar, updated when screen changes."""
coll_name = shared_state["active_collection"].name
str_value = f"QUERY SOURCE: {coll_name}"
return str_value | 25,861 |
def input_handler2():
"""Run the wx event loop by processing pending events only.
This is like inputhook_wx1, but it keeps processing pending events
until stdin is ready. After processing all pending events, a call to
time.sleep is inserted. This is needed, otherwise, CPU usage is at 100%.
This s... | 25,862 |
def create_upload_record(env, source_id, headers, cookies):
"""Creates an upload resource via the G.h Source API."""
post_api_url = f"{get_source_api_url(env)}/sources/{source_id}/uploads"
print(f"Creating upload via {post_api_url}")
res = requests.post(post_api_url,
json={"statu... | 25,863 |
def get_versions(sys):
"""Import stuff and get versions if module
Parameters
----------
sys : module
The sys module object.
Returns
-------
module_versions : dict
The module names and corresponding versions.
"""
module_versions = {}
for name, module in sys.modul... | 25,864 |
def day05_part1(file: str) -> int:
""" Solves advent of code: day05 part1 """
with open(file) as fid:
seats = [Seat(line.strip()) for line in fid]
highest_seat_num = max(seat.number for seat in seats)
return highest_seat_num | 25,865 |
def GetInput():
"""Get player inputs and lower-case the input"""
Input = str(input("{:>20s}".format("")))
print("\n \n \n \n \n")
return Input.lower() | 25,866 |
def validate_forward():
"""
Validate ports are forwarded
"""
here = os.path.dirname(os.path.abspath(__file__))
manifest = os.path.join(here, "templates", "nginx-pod.yaml")
kubectl("apply -f {}".format(manifest))
wait_for_pod_state("", "default", "running", label="app=nginx")
os.system("k... | 25,867 |
def ldns_fskipcs_l(*args):
"""LDNS buffer."""
return _ldns.ldns_fskipcs_l(*args) | 25,868 |
def specific_parser(parser, log=False, run_folder=None, mode=None, tot_epochs=None, restoring_rep_path=None,
start_from_epoch=None, pretrained_GAN=None, GAN_epoch=None, data_dir_train=None, data_dir_train2=None,
data_dir_test=None, data_dir_test2=None, images_log_freq=None, batch... | 25,869 |
def test_to_dataframe_dir_and_list_raises(
spect_dir_mat, spect_list_mat, annot_list_yarden
):
"""test that calling ``to_dataframe`` with both dir and list raises a ValueError"""
with pytest.raises(ValueError):
vak.io.spect.to_dataframe(
spect_format="mat",
spect_dir=spect_di... | 25,870 |
def to_identifier(text):
"""Converts text to a valid Python identifier by replacing all
whitespace and punctuation and adding a prefix if starting with a digit"""
if text[:1].isdigit():
text = '_' + text
return re.sub('_+', '_', str(text).translate(TRANS_TABLE)) | 25,871 |
def scan(device, pullup, frequencies):
"""
Scan for connected I2C devices
Standard mode: 100kHz
Fast mode: 400kHz
Fast mode plus: 1MHz
high speed mode: 3.2MHz
"""
addr_info = {}
for clkFreq in frequencies:
i2c_bus = I2CBus(device, clock_frequency=clkFreq, ena... | 25,872 |
def estimate_next_pos(measurement, OTHER = None):
"""Estimate the next (x, y) position of the wandering Traxbot
based on noisy (x, y) measurements."""
if OTHER is None:
# Setup Kalman Filter
[u, P, H, R] = setup_kalman_filter()
# OTHER = {'x': x, 'P': P, 'u': u, 'matrices':[H, R]}
... | 25,873 |
def AutoBusList(*args):
"""List of Buses or (File=xxxx) syntax for the AutoAdd solution mode."""
# Getter
if len(args) == 0:
return get_string(lib.Settings_Get_AutoBusList())
# Setter
Value, = args
if type(Value) is not bytes:
Value = Value.encode(codec)
lib.Settings_Set_Au... | 25,874 |
def validate_inputs(*, input_data: pd.DataFrame) -> Tuple[pd.DataFrame, Optional[dict]]:
"""Check model inputs for unprocessable values."""
# convert syntax error field names (beginning with numbers)
# input_data.rename(columns=config.model_config.variables_to_rename, inplace=True)
input_data["TotalCha... | 25,875 |
def params(chrom1, simtype, outdir, alpha, beta,
p_a, p_b, gamma_a, gamma_b, gamma_inter,
seed, chrom2, centerdis, localinds, radius, diffd):
"""
Sample simulation parameters.
"""
simulateyeast.cmd_sample_params(chrom1, simtype, outdir,
alpha=alp... | 25,876 |
def create_env(n_envs, eval_env=False, no_log=False):
"""
Create the environment and wrap it if necessary
:param n_envs: (int)
:param eval_env: (bool) Whether is it an environment used for evaluation or not
:param no_log: (bool) Do not log training when doing hyperparameter optim
(issue with... | 25,877 |
def ellipse(pts, pc=None, ab=None):
""" Distance function for the ellipse
centered at pc = [xc, yc], with a, b = [a, b]
"""
if pc is None:
pc = [0, 0]
if ab is None:
ab = [1., 2.]
return dist((pts - pc)/ab) - 1.0 | 25,878 |
def as_root(ctx):
"""Instruct fabric to use the root user"""
for conn in settings['hosts']:
conn.user = 'root'
# Reconnect as the root user
conn.close()
conn.open() | 25,879 |
def test_ReadFHD_select():
"""
test select on read with FHD files.
Read in FHD files with generic read & select on read, compare to read fhd
files then do select
"""
fhd_uv = UVData()
fhd_uv2 = UVData()
uvtest.checkWarnings(fhd_uv2.read, [testfiles], {'freq_chans': np.arange(2)},
... | 25,880 |
def _transform(
parsed_date_data: ParsedDate,
parsed_output_format_data: ParsedTargetFormat,
output_format: str,
output_timezone: str,
) -> str:
"""
This function transform parsed result into target format
Parameters
----------
parsed_date_data
generated year, month, day, hou... | 25,881 |
def volunteer_dict_from_request(request: flask.Request, actor: str) -> dict:
"""Creates and returns a dict of volunteer info from the request.
`actor` is the ID/email of the person or entity that is triggering this.
"""
logging.debug('gapps.volunteer_dict_from_request: %s', list(request.values.items())... | 25,882 |
def stop_next_turn():
"""
Dirty way to stop the MCTS in a clean way (without SIGINT or SIGTERM)...
the mcts finish current turn save data and stop (if you are using dft it can take some time...)
write "stop" in the file MCTS/stop_mcts
:return: None
"""
with open(p.f_stop) as f:
stop... | 25,883 |
def inner(X):
"""
>>> X = [1, 2, 3, 4, 5]
>>> list(inner(X))
[1, 2, 3, 4, 5]
"""
for x in X:
yield x | 25,884 |
def test_clear_request(state, requested_sls_key):
"""
verify clearing a state request sent to the minion(s)
"""
ret = state.request("requested")
assert ret[requested_sls_key]["result"] is None
ret = state.clear_request()
assert ret is True | 25,885 |
async def flip_next(user_id: int, state: FSMContext):
"""Handles flipping mode - when user views his bookmarks or found comics"""
fsm_list = (await state.get_data()).get('fsm_list')
if fsm_list:
fsm_lang = (await state.get_data()).get('fsm_lang')
comic_lang = 'en' if not fsm_lang else fsm_... | 25,886 |
def pull_request_average_time_between_responses(self, repo_group_id, repo_id=None, group_by='month', time_unit='hours', begin_date=None, end_date=None):
""" Avegage time between responeses with merged_status and the time frame
:param repo_group_id: The repository's repo_group_id
:param repo_id: The reposit... | 25,887 |
def create_money(request):
"""Create money object."""
if request.method == 'POST':
form = MoneyForm(request.POST, request.FILES)
if form.is_valid():
money = form.save(commit=False)
money.owner = request.user
money.save()
return redirect(money)
... | 25,888 |
def stripper(reply: str, prefix=None, suffix=None) -> str:
"""This is a helper function used to strip off reply prefix and
terminator. Standard Python str.strip() doesn't work reliably because
it operates on character-by-character basis, while prefix/terminator
is usually a group of characters.
Arg... | 25,889 |
def resnet_50_generator(block_fn,
lst_layers,
num_classes,
pruning_method=None,
data_format='channels_first',
name=None):
"""Generator for ResNet v1 models.
Args:
block_fn: String that define... | 25,890 |
def bracketBalanced(expression):
"""Check if an expression is balanced.
An expression is balanced if all the opening brackets(i.e. '(, {, [') have
a corresponding closing bracket(i.e. '), }, ]').
Args:
expression (str) : The expression to be checked.
Returns:
bool: True if express... | 25,891 |
def create_index_and_alias(index_name, update_alias=False):
"""
create an empty index and if update_alias is True then update the alias to point to it (default is False)
"""
date = datetime.today().strftime("%Y-%m-%d")
exists = es.indices.exists(f"{index_name}-{date}")
if not exists:
#... | 25,892 |
def load_charachips(dir, file):
"""キャラクターチップをロードしてCharacter.imagesに格納"""
file = os.path.join(dir, file)
fp = open(file, "r")
for line in fp:
line = line.rstrip()
data = line.split(",")
chara_id = int(data[0])
chara_name = data[1]
Character.images[chara_name] = spl... | 25,893 |
def Leq(pressure, reference_pressure=REFERENCE_PRESSURE, axis=-1):
"""
Time-averaged sound pressure level :math:`L_{p,T}` or equivalent-continious sound pressure level :math:`L_{p,eqT}` in dB.
:param pressure: Instantaneous sound pressure :math:`p`.
:param reference_pressure: Reference value :math:`p_0... | 25,894 |
def trimBody(body):
""" Quick function for trimming away the fat from emails """
# Cut away "On $date, jane doe wrote: " kind of texts
body = re.sub(
r"(((?:\r?\n|^)((on .+ wrote:[\r\n]+)|(sent from my .+)|(>+[ \t]*[^\r\n]*\r?\n[^\n]*\n*)+)+)+)",
"",
body,
flags=re.I | re.M,
... | 25,895 |
def check_host_arp_table_deleted(host, asic, neighs):
"""
Verifies the ARP entry is deleted.
Args:
host: instance of SonicHost to run the arp show.
neighbor_ip: IP address of the neighbor to verify.
arptable: Optional arptable output, if not provided it will be fetched from host.
... | 25,896 |
def fit_ellipses(contours):
"""
Fit ellipses to contour(s).
Parameters
----------
contours : ndarray or list
Contour(s) to fit ellipses to.
Returns
-------
ellipses : ndarray or list
An array or list corresponding to dimensions to ellipses fitted.
"""
if isinst... | 25,897 |
def get_argument_parser() -> ArgumentParser:
"""
Get command line arguments.
"""
parser = ArgumentParser(
description="Say Hello")
subparsers = parser.add_subparsers(title="subcommands")
parser_count_above_below = subparsers.add_parser("say-hello")
parser_count_above_below.add_argu... | 25,898 |
def custom_client_datalist_json_path(datalist_json_path: str, client_id: str, prefix: str) -> str:
"""
Customize datalist_json_path for each client
Args:
datalist_json_path: default datalist_json_path
client_id: e.g., site-2
"""
# Customize datalist_json_path for each client
# ... | 25,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.