content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_P_HP_cm_d(q_HP_sum_std_test, q_HP_win_std_test, A_p, B_p, theta_hat_bw_cm_d, theta_ex_Nave_d,
theta_star_bw_std, theta_star_ex_sum, P_HP_sum_std_test):
"""日付dにおける制御モードcmのヒートポンプの消費電力(13)
Args:
q_HP_sum_std_test(float): 試験時の夏期標準加熱条件におけるヒートポンプの加熱能力
q_HP_win_std_test(float): 試... | 5,304,400 |
def analyze_top(directory):
"""Analyze output data from the linux 'top' command.
Args:
directory (str): full path to the measurement directory.
For example: 'md-20160406-095339-g0_500-n120000'
"""
# Extract date from directory name
subdir_name = os.path.basename(directory)
parts =... | 5,304,401 |
def test_disconnect():
"""
强制关闭连接处理
"""
sid = request.sid
rooms = signal_get_rooms()
if sid in rooms.mapping:
# 退出房间
roomid = rooms.mapping[sid].roomid
rooms.leave_room(roomid, sid)
# 给房间其他用户发送other_leave事件
signal_send_to_room("other_leave", roomid, roomid... | 5,304,402 |
def data_process(num=250):
"""
从数据集中获取实验评估数据,默认为250条,将数据加载到句子1和2对应的列表中并进行返回
:param num: 实验数据的条数,默认为250
:return: 句子1组成的集合,句子2组成的集合
"""
content = pd.read_csv(util.data_path(), sep='\n', header=None)
content = content.head(num)
sen1_list = []
sen2_list = []
print("开始处理实验数据")
fo... | 5,304,403 |
def create_regression_task_if_needed(testcase):
"""Creates a regression task if needed."""
# We cannot run regression job for custom binaries since we don't have any
# archived builds for previous revisions. We only track the last uploaded
# custom build.
if build_manager.is_custom_binary():
return
tas... | 5,304,404 |
def sample_from_distance_matrix(dist_matrix, dist_mul=1, const_mul=8500, start=None, end=None, **kwargs):
"""Sample TSP qubo from given distance matrix and return lowest-energy sdolution.
This is basically the same as :py:func:`sample_from_locations` except it skips
calculation of distance matrix (which is... | 5,304,405 |
def remove_permissions(study_id: str, user_id: str):
"""
Remove the specified user permissions over the specified study
"""
client_method = "remove_permissions"
fetch_and_output_response(client_method, study_id, user_id) | 5,304,406 |
def _add_embedding_layer(model_1, model_2):
"""
Returns an embedding layer with a weight matrix
of the follwing structure:
[MODEL_1 EMBEDDING MATRIX ; MODEL_2 EMBEDDING MATRIX]
"""
result_layer = torch.nn.Embedding(
model_1.num_embeddings, model_1.embedding_dim + model_2.embedding_di... | 5,304,407 |
def generate_key_lu_dict(
dict_tuple_keys,
unique_identifier,
enduses,
sectors,
technologies
):
"""Generate look_up keys to position in 'load_profiles'
Arguments
----------
dict_tuple_keys : dict
Already existing lu keys
unique_identifier : string... | 5,304,408 |
def dumps(obj):
"""
Similar method to json dumps, prepending data with message length
header. Replaces pickle.dumps, so can be used in place without
the memory leaks on receiving side in pickle.loads (related to
memoization of data)
NOTE: Protocol is ignored when json representation is used
... | 5,304,409 |
def test_monthly_resolution_hindcast(monthly_initialized, monthly_obs):
"""Tests that monthly resolution hindcast predictions work."""
monthly_initialized.lead.attrs["units"] = "months"
assert compute_hindcast(monthly_initialized, monthly_obs).all() | 5,304,410 |
def load_tensor(name: Text) -> Optional[Union["tf.Tensor", List["tf.Tensor"]]]:
"""Load tensor or set it to None"""
tensor_list = tf.get_collection(name)
if not tensor_list:
return None
if len(tensor_list) == 1:
return tensor_list[0]
return tensor_list | 5,304,411 |
def rdns_domain(network):
"""Transform :py:class:`netaddr.IPNetwork` object to rDNS zone name"""
if network.prefixlen == 0:
return "ip6.arpa" if network.version == 6 else "in-addr.arpa"
if network.version == 4:
return ".".join(map(str, reversed(
network.ip.words[:network.prefixle... | 5,304,412 |
def make_dataset(dataset_type, path, args, **kwargs):
"""function to create datasets+tokenizers for common options"""
return get_dataset_by_type(dataset_type, path, args) | 5,304,413 |
def plot(model, f_target_, name='plot', a=0, b=1, steps=100):
"""Plots target function along with approximation.
Parameters
----------
model : Model
function approximation model
f_target_ : function
target function, takes scalar
name : str, optional
name of plot, by defa... | 5,304,414 |
def to_undirected(graph):
"""Returns an undirected view of the graph `graph`.
Identical to graph.to_undirected(as_view=True)
Note that graph.to_undirected defaults to `as_view=False`
while this function always provides a view.
"""
return graph.to_undirected(as_view=True) | 5,304,415 |
def c_str(string : str) -> ctypes.c_char_p:
"""Create ctypes char * from a Python string."""
if sys.version_info[0] > 2:
py_str = lambda x: x.encode('utf-8')
else:
py_str = lambda x: x
return ctypes.c_char_p(py_str(string)) | 5,304,416 |
def CDLUNIQUE3RIVER(df):
"""
函数名:CDLUNIQUE3RIVER
名称:Unique 3 River 奇特三河床
简介:三日K线模式,下跌趋势中,第一日长阴线,第二日为锤头,最低价创新低,第三日开盘价低于第二日收盘价,收阳线,收盘价不高于第二日收盘价,预示着反转,第二日下影线越长可能性越大。
python API
integer=CDLUNIQUE3RIVER(open, high, low, close)
:return:
"""
open = df['open']
high = df['high']
low... | 5,304,417 |
def create_project(TEMPLATE_TYPE,DIR_PATH,FILE_PATH):
"""Create A Project Per the Template,Path and File
using default project folder name
"""
try:
os.makedirs(DIR_PATH)
except:
click.secho("A Similar Project Already Exist", fg="red")
with open(FILE_PATH,"w+") as f:
f.write(TEMPLATE_TYPE)
print("Finished Cr... | 5,304,418 |
def single_leg_credit(trade):
"""Generate a message for a single leg credit trade."""
action = "closed" if trade['close_date'] else "opened"
trade_type = trade['type'].lower()
user = trade['User']['username']
strike = trade['short_put'] if "put" in trade_type else trade['short_call']
symbol = tr... | 5,304,419 |
def test_codebook_serialization():
"""
Test that codebook can be saved to disk and recovered, and that the recovered codebook is
identical to the one that it was serialized from.
"""
# Create a codebook
codebook_array = codebook_json_data_factory()
codebook = Codebook.from_code_array(codeboo... | 5,304,420 |
def makeMacroDemandDict(macroDemandNodes):
""" output should look like this:
dict = {1998 : {3 : 187, 4 : 459}, 1999 : {3 : 193, 4 : 498}}"""
pass | 5,304,421 |
def remove_absolute_impute__roc_auc(X, y, model_generator, method_name, num_fcounts=11):
""" Remove Absolute (impute)
xlabel = "Max fraction of features removed"
ylabel = "1 - ROC AUC"
transform = "one_minus"
sort_order = 9
"""
return __run_measure(measures.remove_mask, X, y, model_generator... | 5,304,422 |
def test_combined_status_daemon_p2p_status_ignore_error(
mock_socket, mock_last_block, mock_monero_rpc, caplog
):
"""Check combined daemon status.
Daemon P2P status is 'ERROR' due to a connection error by the peer, but the P2P status is ignored in the resultng daemon status.
Last block status is fine.
... | 5,304,423 |
def remove_from_import(node, package, name):
"""
Removes the ``from X import Y`` from the module.
"""
root = fixer_util.find_root(node)
import_node = fixer_util.find_binding(name, root, package)
if not import_node:
return
from_imports = get_from_imports(import_node)
from_impor... | 5,304,424 |
def deleteEvents(user_id):
""" deletes event records by set of ids
body shell contain {"ids": [1,2,3] }
"""
controller.deleteEvents( user_id, _get_json_body()["ids"] ) | 5,304,425 |
def getText(rng):
"""
Get the pure text that is included in a js range
@param range js range to get the text of
@return string of the range's text
"""
return rng.toString() | 5,304,426 |
def create_rain_array(rain_file, values):
"""Shuffles the rain distribution columns and creates an array of fractional values the same
length as the precip input. This can be passed to the chop_daily_to_hourly_precip function
Every 24 values should sum to ~1.0.
:param rain_file: path to .csv ppt distri... | 5,304,427 |
def get_Xy_v6(filename='./data/train.csv'):
"""Data Encoding
Version 5
* same as version 4 except encode 3rd class as the number 4
* to better reflect the added difficultly of being in 3rd class
"""
def extract_title(x):
title = x.split(',')[1].split('.')[0].strip()
if title no... | 5,304,428 |
def build_nmet2_nmet2shell_plot(metals, shape, num_shells,
show_ee=True, show=True, save=False,
pctx=False, pcty=False):
"""Plots number of metal2 in shell_i vs number of metal2 in NP
Args:
- metals (str): two metals (element names) in NP
... | 5,304,429 |
def recordPrices(*args, **kwargs):
"""Records the prices today or tomorrow.
:param bool args[0]: If args[0] is True then get today's prices
:return True on success
"""
c = kwargs['Cursor']
servos = c.execute('Select servo_name,servo_id from servo;').fetchall()
if args and args[0]:... | 5,304,430 |
def _asarray1d(arr, copy=False):
"""Ensure 1D array for one array.
"""
if copy:
return asarray(arr).flatten()
else:
return asarray(arr).ravel() | 5,304,431 |
def parse_arguments():
""" A wrapper around the argparse code. """
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-c', '--criterion', action='store',
choices=['suffix', 'mime_name', 'mime_content'],
required=True,
... | 5,304,432 |
def send_notification(uname, planname, course, text):
"""Sends a notification on a channel
Arguments:
COMMON ARGUMENTS
text {str} -- The text to send
"""
directory = "./notifications/{}/{}/{}".format(uname, planname, course)
try:
with open(directory+"/subscribers", "rb") as ... | 5,304,433 |
def pssm1D(seq: Iterable, pssm=None, return_type='Array', **kwargs):
"""Obtain pssm given sequence."""
if pssm is None:
pssm = read_pssm(return_type=return_type, **kwargs)
pssm_values = [pssm[i, aa2index(aa)] for i, aa in enumerate(seq)]
return torch.tensor(pssm_values).unsqueeze(-1) | 5,304,434 |
def _chain_validator(*funcs):
"""Chain a series of validators."""
def chained(value):
for func in funcs:
value = func(value)
return value
return chained | 5,304,435 |
def remove_keys(
_dict: MutableMapping[str, Any] | None, keys: list[str]
) -> MutableMapping[str, Any]:
"""Remove keys from a dictionary."""
if not _dict:
return {}
new = dict(_dict)
for key in keys:
new.pop(key, None)
return new | 5,304,436 |
def delete_contact(id):
"""Removes contact by ID."""
contact = current_user.get_contact_or_404(id)
if contact.is_primary:
flash('Cannot delete primary contact.')
elif list(contact.attendance):
flash('Cannot delete contact involved in events.')
else:
with db.transaction as ses... | 5,304,437 |
def concat_coords_maps(x: TENSOR_OR_SEQ_OF_TENSORS_T, channel_dim: int = 1) -> TENSOR_OR_SEQ_OF_TENSORS_T:
""" Concats N new features maps of euclidian coordinates (1D, 2D, ..., ND coordinates if `x` has N dimensions after `channel_dim`'s dimension) into given `x` tensor. Coordinates are concatenated at `channel_di... | 5,304,438 |
def load_into_collection_from_file(collection, filename,
content_type=None):
"""
Loads resources from the specified file into the given collection
resource.
If no content type is provided, an attempt is made to look up the
extension of the given filename in the MI... | 5,304,439 |
def ProcessCoursesWorksheet(firebase: firebase) -> None:
"""
This method will iterate through the rows in the Courses worksheet
and call a method to make any indicated modifications to the database.
:param firebase: a firebase connection
"""
global workbook
column_knowlegeAr... | 5,304,440 |
def test_callServer_socketError(api_client_class, api_helper_class):
""" test _callServer() - Server raises a socket Error (getaddrinfo failed) """
bad_server_url = 'http://111.222.333.4/testlink/lib/api/xmlrpc.php'
api_client = api_helper_class(bad_server_url).connect(api_client_class)
with pyt... | 5,304,441 |
def cfg_display():
""""
set up the display to work as needed
separate from init because this has to be done after the display has spooled up
"""
pass | 5,304,442 |
def create_payload(data, kwargs):
"""
Creates a new ``PayloadBase`` instance with the given parameters.
Parameters
----------
data : (`list` of ``PayloadBase`` instances), ``BodyPartReader``, `bytes`, `bytearray`, `memoryview`, `str`, \
`BytesIO`, `StringIO`, `TextIOBase`, `Buffered... | 5,304,443 |
def test_response_format_of_ope_estimators_using_random_evaluation_policy(
synthetic_bandit_feedback: BanditFeedback, random_action_dist: np.ndarray
) -> None:
"""
Test the response format of ope estimators using synthetic bandit data and random evaluation policy
"""
expected_reward = np.expand_dims... | 5,304,444 |
def create_app():
"""Creates the Flask app object."""
app = Flask(__name__)
app.config.from_object(AppConfig)
api = Api(app)
configure_resources(api)
configure_extensions(app)
return app | 5,304,445 |
def ymdhms_format_from_tai(tai, sep="T", digits=None, suffix="",
buffer=None):
"""Date and time in ISO format 'yyyy-mm-ddThh:mm:ss....' given seconds TAI.
Works for both scalars and arrays.
Input:
tai number of elapsed seconds from TAI January 1, 2000.
sep... | 5,304,446 |
def _get_project_ids():
"""Return the GCE project IDs."""
return list(local_config.Config(local_config.GCE_CLUSTERS_PATH).get().keys()) | 5,304,447 |
def drop_multiple_fha_numbers(df):
"""drops multiple fha_numbers by dropping issued data when a reissue is available in firm commitment activity"""
#create df of rows unique fha_numbers
unique_fha_list = df.fha_number.value_counts()[df.fha_number.value_counts() == 1]
def in_unique_list(x):
... | 5,304,448 |
def create_accelerate_order() -> jsonify:
"""
生成刷票订单
:return:
"""
try:
data = loads(request.get_data().decode('utf-8'))
except ValueError:
return jsonify({'code': '2000', 'message': '服务器内部错误'})
# 防止重复下单
order_list = TicketOrder().query.filter_by(
user_id=g.user.... | 5,304,449 |
def info():
"""Return information about the module"""
print locals() | 5,304,450 |
def set_volume(intent, session_attributes):
""" set receiver volume (may be capped). """
card_title = intent['name']
should_end_session = not keep_baker_open(session_attributes)
# the value is "?" if it's given bogus input
slot = intent_slot(intent, 'volume_level')
volume_level = numeric_slot_... | 5,304,451 |
def store_embedding_vectors(vocab, lang, version):
"""
This calculates the words that are in the topics, finds fasttext vectors for these words
and stores them in the database for the distance measuring later on.
:param vocab:
:param lang:
:return:
"""
# fasttext.util.download_model('en... | 5,304,452 |
def rect2ang(rect, zenith=False, axis=0):
"""The inverse of ang2rect."""
x,y,z = moveaxis(rect, axis, 0)
r = (x**2+y**2)**0.5
phi = np.arctan2(y,x)
if zenith: theta = np.arctan2(r,z)
else: theta = np.arctan2(z,r)
return moveaxis(np.array([phi,theta]), 0, axis) | 5,304,453 |
def mutate_single_base(base):
"""Takes single nucleic acid and changes it to a different nucleic acid."""
bases = "GATC"
idx = bases.index(base)
return choice(bases[:idx] + bases[idx + 1:]) | 5,304,454 |
def filterFileGroups(filegroups, fixedcols):
"""Filters out empty, duplicate and redundant rows, and empty columns,
from ``filegroups``
:arg filegroups: List of :class:`FileGroup` objects.
:arg fixedcols: List of ``(ftype, { var : value })`` mappings
:returns: A tuple containing the filtere... | 5,304,455 |
def authBuild(SCOPES, PATH=''):
"""Shows basic usage of the Drive v3 API.
Prints the names and ids of the first 10 files the user has access to.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow comp... | 5,304,456 |
def filter_star_import(
line: bytes,
marked_star_import_undefined_name: Iterable[bytes],
) -> bytes:
"""Return line with the star import expanded."""
undefined_name = sorted(set(marked_star_import_undefined_name))
return Regex.STAR.sub(b", ".join(undefined_name), line) | 5,304,457 |
def followBot(address, index):
"""Locates the follow button and clicks it"""
global flag
global mouse_cood
mouse_cood = pyautogui.locateCenterOnScreen(address)
if mouse_cood != None:
print("Follow icon found at " + str(index + 1) + \
" : " + str(mouse_cood))
pyautogui.... | 5,304,458 |
def zeros(shape, dtype, allocator=drv.mem_alloc, order="C"):
"""Returns an array of the given shape and dtype filled with 0's."""
result = GPUArray(shape, dtype, allocator, order=order)
zero = np.zeros((), dtype)
result.fill(zero)
return result | 5,304,459 |
def weighted_geometric_mean(values, weights):
"""
Returns the weighted geometric mean of values.
Args:
values (iterable):
weights (iterable):
Returns:
float:
"""
assert len(values) == len(weights)
return np.exp(sum([weights[i] * np.log(values[i]) for i in range(len... | 5,304,460 |
def make_information_functions() -> Dict[str, ecole.typing.InformationFunction]:
"""Create the information function used in benchmarking the observation.
This is a combination of sloving features such as number of nodes, and the timing of
observation functions.
"""
information_funcs = {
"n_... | 5,304,461 |
def read64(f):
"""Read 8 bytes from a file and return as an 64-bit unsigned int (little endian).
"""
return struct.unpack("<Q", f.read(8))[0] | 5,304,462 |
def get_cosine_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, num_cycles=.5, last_epoch=-1):
""" Create a schedule with a learning rate that decreases following the
values of the cosine function between 0 and `pi * cycles` after a warmup
period during which it increases linearly betwe... | 5,304,463 |
def neighbor_weights(dist):
"""Return the weights of neighbors in time seires estimates.
Params
------
dist (np.ndarray): $M \times (N+1)$ array of Euclidean distances between a
point to its nearest neighbors in the shadow data cloud
(sorted by increasing o... | 5,304,464 |
def get_train_and_validation_loaders(
args: Any, image_size: Tuple[int, ...], task: Optional[Tasks] = None
):
"""
:param args: Object containing relevant configuration for the task
:param image_size: A Tuple of integers representing the shape of input image
:param task: The current task being perfor... | 5,304,465 |
def is_alef(archar):
"""Checks for Arabic Alef forms.
ALEFAT = (ALEF, ALEF_MADDA, ALEF_HAMZA_ABOVE, ALEF_HAMZA_BELOW, ALEF_WASLA, ALEF_MAKSURA )
@param archar: arabic unicode char
@type archar: unicode
@return:
@rtype:Boolean
"""
return archar in ALEFAT | 5,304,466 |
def p_regex(regex, flags=0):
""" p_regex returns a parser that matches a regex at the current offset """
r = re.compile(regex, flags=flags)
@SugarParser
def parse(str, offset=0):
match = r.match(str, offset)
if match is None:
return None, -1
match = match.group(0)
... | 5,304,467 |
def _decode_and_center_crop(
image_bytes: tf.Tensor,
jpeg_shape: Optional[tf.Tensor] = None,
) -> Tuple[tf.Tensor, tf.Tensor]:
"""Crops to center of image with padding then scales."""
if jpeg_shape is None:
if image_bytes.dtype == tf.dtypes.string:
jpeg_shape = tf.image.extract_jpeg_shape(image_by... | 5,304,468 |
def macd(X: pd.DataFrame,
lower: int = 7,
upper: int = 14,
price_window: int = 63,
window: int = 252):
"""
Computes the Moving Average Convergence Divergence.
References:
- https://arxiv.org/pdf/1911.10107.pdf
Arguments:
X : pd.DataFrame
A ... | 5,304,469 |
def probe_video(path):
"""
Returns a probe object with vcodec, acodec and brand fields
Returns None if the file is not a video
If the video has no brand, brand is None
"""
path = os.path.abspath(path)
class Probe:
def __init__(self, vcodec, acodec, brand, duration):
se... | 5,304,470 |
def test_generate_figure_help():
"""Check if CLI script can execute without error"""
result = subprocess.run(['sg_generate_figure', '-h'])
assert result.returncode == 0 | 5,304,471 |
def has_latex():
"""
Test if Latex is available.
EXAMPLES::
sage: from sage.doctest.external import has_latex
sage: has_latex() # random
True
"""
from sage.misc.latex import _run_latex_, _latex_file_
from sage.misc.temporary_file import tmp_filename
try:
f =... | 5,304,472 |
def import_local_module(project_dir, module_name):
"""
Import a module from a pathname.
"""
# get the full path
if not os.path.isdir(project_dir):
raise FileNotFoundError("Project dir does not exist: %s" % project_dir)
# there are 2 possibilities: dir or file
pathname_dir = os.path.... | 5,304,473 |
def release():
"""Creates a github release."""
# get the last release tag
stdout = check_output(["git", "describe", "--abbrev=0", "--tags"])
stdout = stdout.decode("utf-8")
last_version = stdout.strip()
if not recent_changes_to_src(last_version):
print("Nothing to release.")
ex... | 5,304,474 |
def crop_to_bbox(objs, bbox):
"""
Filters objs to only those intersecting the bbox,
and crops the extent of the objects to the bbox.
"""
if isinstance(objs, dict):
return dict((k, crop_to_bbox(v, bbox))
for k,v in objs.items())
initial_type = type(objs)
objs = to_list(ob... | 5,304,475 |
def calibrate_camera(nx=9, ny=6, images_folder='camera_cal/calibration*.jpg'):
""" Use the corners to calibrate camera """
# prepare object points, like (0,0,0), (1,0,0)...(6,5,0)
# further study these two lines
objp = np.zeros((nx*ny,3), np.float32)
objp[:, :2] = np.mgrid[:nx, :ny].T.reshape(-1,2)... | 5,304,476 |
def run_command_async(cmd):
"""
Run a command using the asynchronous `tornado.process.Subprocess`.
Parameters
----------
iterable
An iterable of command-line arguments to run in the subprocess.
Returns
-------
A tuple containing the (return code, stdout)
"""
process = S... | 5,304,477 |
async def webhook(request):
"""Webhook to retrieve action calls."""
action_call = await request.json()
try:
response = await executor.run(action_call)
except ActionExecutionRejection as e:
logger.error(str(e))
response = {"error": str(e), "action_name": e.action_name}
res... | 5,304,478 |
def contain_static(val):
"""
Check if URL is a static resource file
- If URL pattern ends with
"""
if re.match(r'^.*\.(jpg|jpeg|gif|png|css|js|ico|xml|rss|txt).*$', val, re.M|re.I):
# Static file, return True
return True
else:
# Not a static file, return ... | 5,304,479 |
def text_messages_joint_log_prob(count_data, lambda_1, lambda_2, tau):
"""Joint log probability function."""
alpha = (1. / tf.reduce_mean(input_tensor=count_data))
rv_lambda = tfd.Exponential(rate=alpha)
rv_tau = tfd.Uniform()
lambda_ = tf.gather(
[lambda_1, lambda_2],
indices=tf.cast(
... | 5,304,480 |
def build_assets_cache():
""" Force update of asset information.
"""
from ooiservices.app.uframe.asset_tools import verify_cache
try:
asset_list = verify_cache(refresh=True)
print '\n Completed compiling asset information.'
print '\n Number of assets: ', len(asset_list)
r... | 5,304,481 |
def is_dataset(obj):
"""
True if the object is a h5py.Dataset-like object.
:param obj: An object
"""
t = get_h5_class(obj)
return t == H5Type.DATASET | 5,304,482 |
def run(ctx):
"""Runs the application"""
ctx.run(f"python3 {ENTRYPOINT_PATH}", echo=True) | 5,304,483 |
def get_court_id_from_url(url):
"""Extract the court ID from the URL."""
parts = tldextract.extract(url)
return parts.subdomain.split(".")[1] | 5,304,484 |
def insertgroup(request):
"""Insert group in database."""
# Get data
group_name = request.POST.get('group', None)
# Add to inventory
inventory = spotmax.SPOTGroup()
inventory.add_group(group_name)
message = 'Group added!'
return render(
request,
'addgroup.htm',
context={'message': m... | 5,304,485 |
def get_rockets(method=""):
"""Gets information related to SpaceX rockets
Gets information related to rockets from
the API
Parameters
----------
method : str (optional)
the method used for the request
Returns
-------
list
a list of the rocke... | 5,304,486 |
def run_command(command: str, log_file: str = None, line_callback: callable = None):
"""
Runs a shell command with or without log file with STDOUT and STDERR
Args:
command: A unix command to run
log_file: Write stdout and stderr to log file
line_callback: function to call on each li... | 5,304,487 |
def load_config():
"""Load configuration file"""
return load_properties_file(CONFIG_FILE_PATH) | 5,304,488 |
def lerp10(h, h1, h2, o1, o2):
"""Returns 10**o, where o is the linear interpolation of value h between (h1, o1)
and (h2, o2)."""
return 10**np.interp(h, [h1, h2], [o1, o2]) | 5,304,489 |
def _array_to_raster(
base_array, target_nodata, target_path,
creation_options=DEFAULT_GTIFF_CREATION_TUPLE_OPTIONS[1],
pixel_size=_DEFAULT_PIXEL_SIZE, projection_epsg=_DEFAULT_EPSG,
origin=_DEFAULT_ORIGIN):
"""Passthrough to pygeoprocessing.array_to_raster."""
projection =... | 5,304,490 |
def decrypt(message: str) -> None:
"""
>>> decrypt('TMDETUX PMDVU')
Decryption using Key #0: TMDETUX PMDVU
Decryption using Key #1: SLCDSTW OLCUT
Decryption using Key #2: RKBCRSV NKBTS
Decryption using Key #3: QJABQRU MJASR
Decryption using Key #4: PIZAPQT LIZRQ
Decryption using Key #5: ... | 5,304,491 |
def expandElementalMassFracsToNuclides(
massFracs: dict,
elementExpansionPairs: Tuple[elements.Element, List[nuclideBases.NuclideBase]],
):
"""
Expand elemental mass fractions to natural nuclides.
Modifies the input ``massFracs`` in place to contain nuclides.
Notes
-----
This indirectl... | 5,304,492 |
def get_all_urls(titles, title_data):
"""converts every title into """
urls = []
for title in titles:
title_data[title].append(WIKI_URL+title)
return urls | 5,304,493 |
def find_system_symbol(img, instruction_addr, system_info=None):
"""Finds a system symbol."""
return DSymSymbol.objects.lookup_symbol(
instruction_addr=instruction_addr,
image_addr=img['image_addr'],
image_vmaddr=img['image_vmaddr'],
uuid=img['uuid'],
cpu_name=get_cpu_nam... | 5,304,494 |
def make_univariate(F, T):
"""
Given a homogeneous bivariate polynomial `F(xi,xj)`,
sitting inside a ring `K[x0,x1,x2]`, dehomogenise it
into ring T (univariate), for later factoring.
"""
assert(F.is_homogeneous() and len(F.variables())<3)
R = F.base_ring()
S = F.parent()
x0,x1,x2 = ... | 5,304,495 |
def doConvertBlackAndWhiteFilter(image: Image.Image, mode: str):
"""Low level function...
Convert an image to black and white based on a filter: filter-darker and
lighter respectively make pixels darker than the average black and pixels
that are lighter than the average black.
Args:
image (Image.Image): A PIL ... | 5,304,496 |
def train(directory, parfile, makeargs="", output_markdown=True) -> List["LevelStats"]:
"""Make patterns with the given parfile and makeargs.
Supply a parameter name like liang, not out/liang.par or out/liang.
Patterns will be trained on wordlist specified in the Make variable WORDLISTTOUSE."""
ts = t... | 5,304,497 |
def export_profile(profile_id):
"""[it will extract the user profile from device and create file with it's name if not exist]
Args:
profile_id ([int]): [the id of profile that we need to extract data for]
"""
profile_information = profile_info(profile_id)
export_path = args.to[0]
curren... | 5,304,498 |
def copy(
store: BaseAccessStore,
from_principal: str,
from_principal_type: str,
to_principal: str,
to_principal_type: str,
) -> bool:
"""
copies a relationship from the from_principal to the to_principal
for the given types
"""
# print(f'copying from {from_principal_type} {from_... | 5,304,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.