content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_oldest_employees(count_employees: int) -> typing.List[typing.Tuple[str, str]]:
"""
Return a list of pairs in the form of (FirstName, LastName).
The list will consist of the `count` oldest employees from oldest to youngest.
:param count: Number of employees to return.
:type count: int
:r... | 47,700 |
def get_Q_UT_CL_d_t_i(L_CL_d_t_i, Q_T_CL_d_t_i):
"""冷房設備機器の未処理冷房潜熱負荷(MJ/h)(20b)を計算する
Args:
Q_max_CL_d_t_i(ndarray): 最大冷房潜熱出力
L_CL_d_t_i(ndarray): 冷房潜熱負荷
Q_T_CL_d_t_i: returns: 冷房設備機器の未処理冷房潜熱負荷(MJ/h)
Returns:
ndarray: 冷房設備機器の未処理冷房潜熱負荷(MJ/h)
"""
return L_CL_d_t_i - Q_T_CL_d_... | 47,701 |
def html_gscholar_to_json(soup):
"""
"""
# Scrape just PDF links
for pdf_link in soup.select('.gs_or_ggsm a'):
pdf_file_link = pdf_link['href']
print(pdf_file_link)
# JSON data will be collected here
data = []
# Container where all needed data is located
... | 47,702 |
def csi_psroipooling(
cls_prob, roi, spatial_scale, output_dim, group_size, out_dtype, q_params, layer_name=""
):
"""Quantized psroipooling.
Parameters
----------
Returns
-------
result : relay.Expr
"""
return _make.CSIPSROIPooling(
cls_prob, roi, spatial_scale, output_dim, ... | 47,703 |
def test_passwords():
"""
"""
examples = (
(111_111, True),
(223_450, False),
(123_789, False),
)
examples_2= (
(111111, False),
(112233, True),
(123444, False),
(111122, True),
)
for (data, expected) in examples:
verify_pw_te... | 47,704 |
def short_links(link):
"""
Shortening a long url to a short link Byt.ly
: param link: long address
: return: string - short link Byt.ly
"""
url = 'https://api-ssl.bitly.com/v4/groups'
res = get(url=url, headers=head)
group = res.json()['groups'][0]['guid']
url = 'https://api-ssl.bi... | 47,705 |
def parse_page_loaded(msg_type, target, logs, log_begin_idx):
"""
Parse WebViewPageLoadedEvent event logs
:params msg_type
:params target
:return: an instance of event.WebViewPageLoadedEvent
"""
assert len(logs) == 1
log_info = util.extract_info(logs[0])
plid, package = log_info['p... | 47,706 |
def parse_listing(listing_search_url=LISTING_SEARCH_IMMO_PARIS_URL):
"""Parsing a listing of items from a specific search query"""
listing_page = requests.get(listing_search_url)
listing_doc = document_fromstring(listing_page.content)
listing_base_url = listing_doc.base
r = listing_doc.xpath(u'//d... | 47,707 |
def suggest_mappings_by_content(resource, pathway_id):
"""Return list of top matches based on gene set similarity.
---
tags:
- mappings
parameters:
- name: resource
type: string
description: name of the database
required: true
... | 47,708 |
def error_func():
"""..."""
(code, data, custom_pointer) = sys.exc_info() # (type, value, traceback)
if (code == PJON.PJON_Connection_Lost):
print("Connection with device ID %i is lost.\n", bus.packets[data].content[0], file=sys.stderr)
elif(code == PJON.PJON_Packets_Buffer_Full):
print... | 47,709 |
def animation(request):
"""
Controller for the streamflow animation page.
"""
context = {}
return render(request, 'sfpt/animationmap.html', context) | 47,710 |
def init() -> None:
"""
初始化窗口相关参数
:return:
"""
glutInit()
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH) # 使用双缓存及RGB模型
glutInitWindowSize(400, 300) # 指定窗口尺寸
glutInitWindowPosition(100, 100) # 指定窗口在屏幕上的位置
glutCreateWindow("Bouncing Ball")
glClearColor(1.0, 1.0, 1.0, 1... | 47,711 |
def sqlite3_connection(*args, **kwargs):
"""SQLite3 connection context manager. On exit, runs close."""
connection = apsw.Connection(*args, **kwargs)
try:
yield connection
finally:
connection.close() | 47,712 |
def kos_lookup_cmdr_embeds(session, cmdr_name, cmdr_pic=None):
"""
Look up the cmdr in the KOS db, if found return embeds that match (up to 3 closest).
Returns:
[embed, ...]: The discord.py embeds who match the cmdr_name.
[] : No matches in KOS db.
"""
if not cmdr_pic:
cmdr_... | 47,713 |
def check_uncommitted_work() -> None:
"""
See if there are unstaged changes in git repo that would prevent switching branches.
"""
result = subprocess.Popen(
["git", "diff", "--exit-code"], shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
result.communicate()[0]
if resul... | 47,714 |
def get_deep_laser_instrument_status():
""" Generates the instrument status object to send to DL on a regular basis """
# Reuse the function used by the dashboard
raw_runs = get_runs_list(datetime.datetime.now(pytz.UTC) - datetime.timedelta(days=7))
# Pull out a list of fields we want to send to TFC
... | 47,715 |
def decode(s):
"""
Deserialize an MRS object from a SimpleMRS string.
"""
if hasattr(s, 'decode'):
s = s.decode('utf-8')
ms = next(_decode(s.splitlines()))
return ms | 47,716 |
def fidimag_to_finitedifferencefield(sim):
"""
fidimag_to_finitedifferencefield(sim)
This function takes a Fidimag simulation object, and constructs a
Finite Difference Field object which has the magnetisation configuration
from the simulation at the last time step.
"""
cmin = np.array([sim... | 47,717 |
def ERA_IrregularImgGrid(
lons: np.ndarray,
lats: np.ndarray,
bbox: Tuple[float, float, float, float] = None,
) -> CellGrid:
"""
Create a irregular grid from the passed coordinates.
"""
lons_gt_180 = np.where(lons > 180.0)
lons[lons_gt_180] = lons[lons_gt_180] - 360
grid = BasicGrid(... | 47,718 |
def zones(**kw):
"""
List all timezones that match kw['SEARCH'] (everything if kw['SEARCH'] is
empty)
"""
if kw['d']:
pdb.set_trace() # pragma: no cover
zlist = pytz.all_timezones
if kw['SEARCH']:
for each in zlist:
if kw['SEA... | 47,719 |
def create_enforce_validation_serializer(serializer=None, **kwargs):
"""
Public function that creates a copy of a serializer which enforces ``must_validate_fields``.
The difference between this function and ``_create_enforce_validation_serializer``
is that this function can be used both as a direct deco... | 47,720 |
def matchingFiles( path, regexp):
"""Return a list of files matching a regexp"""
# print(path + ' '+ regexp)
pattern = re.compile( regexp )
#files = ls_EOS(path)
files = ls(path)
# print(files)
return [f for f in files if pattern.match(os.path.basename(f)) is not None] | 47,721 |
def read_FDF_cube(filename):
"""Read in a FDF/RMSF cube. Figures out which axis is Faraday depth and
puts it first (in numpy order) to accommodate the rest of the code.
Returns: (complex_cube, header,FD_axis)
"""
HDULst = pf.open(filename, "readonly", memmap=True)
head = HDULst[0].header.copy()
... | 47,722 |
def test_merge_many_intervals(many_intervals):
"""Test if code can handle large number of intervals"""
assert merge(many_intervals) | 47,723 |
def add_genes(cursor):
""" Extract gene entries from the temporary table """
query = "INSERT or IGNORE INTO genes SELECT gene_ID, strand FROM temp_gene;"
cursor.execute(query)
return | 47,724 |
def bert_vector(text, tokenizer, model, args):
"""
BERT-based embedding.
:param text: original text to be embedded.
:param tokenizer: BERT tokenizer.
:param model: BERT model.
:param args: args.
:return: BERT embedded sentence.
"""
text = '[CLS] ' + text + ' [SEP]'
tokenized_text... | 47,725 |
def test_external_entities():
"""
>>> xml = '''<!DOCTYPE doc [
... <!ENTITY entity PUBLIC "http://entity-web" "entity-file">
... ]>
... <doc>&entity;</doc>'''
>>> parse(xml)
>>> parse(xml, "ExternalEntityRefHandler")
XML> ExternalEntityRefHandler(u'entity', N... | 47,726 |
def compute_benchmark_energies(molecule: tq.chemistry.Molecule,
benchmarks: List[str]) -> Dict:
"""
This uses psi4 to perforom the classical benchmarks.
"""
energy_benchmarks = {}
for method in ["hf", "mp2", "ccsd", "fci"]:
if method in benchmarks:
... | 47,727 |
def fine_paid_message(message):
"""Returns true if the format of paid message is fine"""
return (len(message.mentions) > 0 or message.mention_everyone) and get_amount(message) is not None and message.channel.name == "expenses" and (message.content.split(" ")[0] == '!paid' or message.content.split(" ")[0] == '<@... | 47,728 |
def get_tile_summary_on_original_image_path(slide_number):
"""
Convert slide number to a path to a tile summary on original image file.
Example:
5 -> ../data/tile_summary_on_original_png/TUPAC-TR-005-tile_summary.png
Args:
slide_number: The slide number.
Returns:
Path to the tile summary on ori... | 47,729 |
def test_create_feature_set_null_pk(test_app, create_schema):
"""
Tests creating a feature set without a primary key
"""
APP.dependency_overrides[crud.get_db] = lambda: (yield create_schema) # Give the "server" the same db session
response = test_app.post('/feature-sets', json=feature_set_null_pk, ... | 47,730 |
def print_qa(questions, answers_gt, answers_gt_original, answers_pred,
era, similarity=_dirac, path=''):
"""
In:
questions - list of questions
answers_gt - list of answers (after modifications like truncation)
answers_gt_original - list of answers (before modifications)
... | 47,731 |
def plot_heatmap(scores=None, column_labels=None, row_labels=None,
output_path="plot.png"):
"""
Plotting function that can be used to visualize (self-)attention
Args:
scores: attention scores
column_labels: labels for columns (e.g. target tokens)
row_labels: labels f... | 47,732 |
def compute_zhu(props,
zhu_kwargs):
"""
Compute the approximate Zhu-Nakamura hopping probabilities for
each geom in the dataset.
Args:
props (dict): dataset properties
zhu_kwargs (dict): dictionary with information about how
to calculate the hoppin... | 47,733 |
def test_time_of_use_summer_on_peak_usage():
"""Test Time of Use for summer on Peak Usage for kwh."""
with patch(PATCH_GET) as session_get, patch(PATCH_POST) as session_post:
session_post.return_value = MOCK_LOGIN_RESPONSE
session_get.side_effect = get_mock_requests(ROUTES)
client = Sr... | 47,734 |
def disaster_type_card():
"""
:return: A Div containing dashboard title & descriptions.
"""
return html.Div(
children=[
html.H6("Disaster Type"),
dcc.Dropdown(
options=[
{'label': ... | 47,735 |
def retrieve_context_topology_node_node_rule_group_inter_rule_group_risk_characteristic_risk_characteristic(uuid, node_uuid, node_rule_group_uuid, inter_rule_group_uuid): # noqa: E501
"""Retrieve risk-characteristic
Retrieve operation of resource: risk-characteristic # noqa: E501
:param uuid: ID of uuid
... | 47,736 |
def txt2domainname(input, canonical_form=False):
"""turn textual representation of a domain name into its wire format"""
if input == ".":
d = b'\x00'
else:
d = b""
for label in input.split('.'):
label = label.encode('ascii')
if canonical_form:
... | 47,737 |
def create_dir(path_dir):
""" create a folder if it not exists
:param str path_dir:
"""
path_dir = os.path.abspath(path_dir)
if not os.path.isdir(path_dir):
os.makedirs(path_dir, mode=0o775)
else:
logging.warning('Folder already exists: %s', path_dir)
return path_dir | 47,738 |
def openDevice(sbigDeviceType):
"""
sbigDeviceType = DEV_USB1, DEV_USB2, etc.
"""
params = OpenDeviceParams()
params.deviceType = sbigDeviceType
params.lptBaseAddress = 0
params.ipAddress = 0x00000000
results = None
sbigCtrl(CC_OPEN_DEVICE, params, results) | 47,739 |
def request_problem():
"""
Sends the user the user the location of the requested problem's model files
and the problem configuration settings
"""
problem_name = flask.request.form['problem_name']
dimension = flask.request.form['dimension']
cfg_filename = problem_name + ".cfg"
cfg_file_l... | 47,740 |
def hstack(*args):
"""
Stacks images horizontally
If image depths are mismatched then converts grayscale images to bgr before stacking
"""
depths = [depth(im) for im in args]
gray = [d == 1 for d in depths]
if all(gray):
return np.hstack(args)
elif not all(gray):
return ... | 47,741 |
def sample(x, n):
"""
Get n number of rows as a sample
"""
# import random
# print(random.sample(list(x.index), n))
return x.iloc[list(range(n))] | 47,742 |
def collect_files_to_zip(destinationFile, filesToZip):
"""
zip output files and attach a metadata from wav
:return:
"""
with zipfile.ZipFile('%s.zip' %(destinationFile), 'w') as myzip:
for f in filesToZip:
myzip.write(f, "%s.wav" %(f,))
logger.debug('Archiving %s into... | 47,743 |
def floor_div_mul(value, factor):
"""Fuction to get floor number."""
return (((value) // (factor))) *(factor) | 47,744 |
def dup_div(f, g, K):
"""
Polynomial division with remainder in ``K[x]``.
Examples
========
>>> from sympy.polys import ring, ZZ, QQ
>>> R, x = ring("x", ZZ)
>>> R.dup_div(x**2 + 1, 2*x - 4)
(0, x**2 + 1)
>>> R, x = ring("x", QQ)
>>> R.dup_div(x**2 + 1, 2*x - 4)
(1/2*x + ... | 47,745 |
def append_Z_trace_vertical(path, new_point, height, ex, middle_layer=None, middle_taper=False):
"""Adds new_point to the path list plus TWO Z or S manhattan interesections.
Args:
path: list of tuples containing necessary info (pya.DPoint, layer, width)
new_point: tuple ((x, y) or pya.DPoint, la... | 47,746 |
def batch_ext(order: pd.Series, batch: pd.Series, classes: pd.Series,
class_list: List[str], ext: str) -> pd.Series:
"""
get minimum/maximum order of samples of classes in class_list. Auxiliary
function to be used with BatchChecker / FeatureCheckerBatchCorrection
Parameters
----------
... | 47,747 |
def chunk_push(params: dict | None = None) -> Tuple[bool | str, ...]:
"""
A helper function to push the data to database in chunks.
:param params: A dictionary that contains below structure.
{
"data_rowcount": data row count,
"chunksize": chunksize,
... | 47,748 |
def test():
"""Test 8 queens.
"""
N=8
import time
start=time.time()
count=0
for q in queens(N):
count+=1
print "solution: ", count, q
print_solution(q)
print "Solution count:", count
print "time: ", time.time()-start | 47,749 |
def total_error_avgAx0(y_true, y_pred):
"""
"""
avgY = K.mean(y_true, axis=0, keepdims=True) # 0 is sample axis
return K.sum(K.square(y_true - avgY)) | 47,750 |
def test_presale_move_to_wei_tranche_based_crowdsale(chain, presale_fund_collector, wei_tranche_ico, finalizer, token, start_time, team_multisig, customer, customer_2):
"""When pre-ico contract funds are moved to the crowdsale, the pre-sale investors gets tokens with a preferred price and not the current wei_tranch... | 47,751 |
def test_get_values():
"""
tests that config values are loaded properly
"""
expected = [
"path1/*",
"path1/anotherpath/*",
"path1/anotherpath2/",
"path1/anotherpath2/file1.py",
]
load_config(sources=expected)
load_and_validate()
response = config_manager... | 47,752 |
def _ErrorExit(message):
"""Prints the error message and exits with the code 1.
The function never returns.
Args:
message: The error message to be printed to stderr.
"""
print(message, file=sys.stderr)
sys.exit(1) | 47,753 |
def var_aexp(compiler, node):
""" Variable compilation """
if node.context == 'assign':
gc = GC(compiler)
if compiler.environment.is_exist_local_var(node.name):
var = compiler.environment.get_local_var(node.name)
var_type = compiler.environment.get_local_var_runtime_type... | 47,754 |
def resnet50_v1b(pretrained=False, root='~/.mxnet/models', ctx=cpu(0), **kwargs):
"""Constructs a ResNetV1b-50 model.
Parameters
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.mxnet/models'
Location for keeping t... | 47,755 |
def beautifyECDF():
"""Generic formatting of ECDF figures."""
plt.ylim(-0.0, 1.01) # was plt.ylim(-0.01, 1.01)
plt.yticks(np.arange(0., 1.001, 0.2), fontsize=16)
plt.grid(True)
xmin, xmax = plt.xlim()
# plt.xlim(xmin=xmin*0.90) # why this?
c = plt.gca().get_children()
for i in c: # TODO... | 47,756 |
def _f_expl_5_cash_karp_adptv(x0, Y0, dx, *args, dYdx=None, econ=0.0001889568, eps=0.1, pgrow=-0.2, pshrink=-0.25, safety=0.9, **kwargs):
"""Explicit adaptive 5th-order Cash-Karp method
Parameters
----------
x0 : Intvar
Integration variable at beginning of scheme
Y0 : Field
Variable... | 47,757 |
def exec(q, p):
""" Execute a prepared statement """
[db, cursor] = get_connection()
cursor.execute(q, p)
cursor.close()
db.commit()
db.close() | 47,758 |
def issubset(list1, list2):
"""
Examples:
>>> issubset([], [65, 66, 67])
True
>>> issubset([65], [65, 66, 67])
True
>>> issubset([65, 66], [65, 66, 67])
True
>>> issubset([65, 67], [65, 66, 67])
False
"""
n = len(list1)
for startpos in range(len(list2) ... | 47,759 |
def fading_confluence_3():
"""
Fades the lights on arms 1 and 2, then arm 3
"""
sleep_speed = 0.01
# Fade Arm 1 and 2: R
PYGLOW.led(1, 110)
PYGLOW.led(7, 110)
sleep(sleep_speed)
# Fade Arm 1 and 2: R, O
PYGLOW.led(1, 100)
PYGLOW.led(7, 100)
sleep(sleep_spe... | 47,760 |
def make_start_and_end_images_with_words(start_words, end_words, perm: bool = False, repeat=1, size=150):
"""
Make two images from two sets of words.
:param start_words: Words to use for the first image.
:param end_words: Words to use for the second image
:param perm: Whether the words should be per... | 47,761 |
def bbox2corners(bbox):
"""
box parameters to four box corners
"""
x, y, w, h, _ = bbox.tolist()
xy_tl = [x - w/2, y - h/2]
xy_dl = [x - w/2, y + h/2]
xy_dr = [x + w/2, y + h/2]
xy_tr = [x + w/2, y - h/2]
return np.array([xy_tl, xy_dl, xy_dr, xy_tr]) | 47,762 |
def clean_game_data_recent(df: pd.DataFrame, shift=False) -> dict:
"""Clean game data post mid-2018.
Follows a slightly different format than pre-2018 data.
"""
month_game_data = {}
game_type = "tables"
if shift == True: # APR_2021, MAY_2021 had no %diff, so we need to shift
add = 1
... | 47,763 |
def process_data(dataframe : pd.DataFrame,
label_to_id: Dict,
vocab : Dict = None,
vocab_size : int = 10_000,
max_tokens : int = 200,
max_token_size : int = 40) -> (tf.Tensor, tf.Tensor, dict, dict):
"""
Will take a dataframe... | 47,764 |
def tan_to_eq(xiDeg, etaDeg, ra0Deg, dec0Deg):
"""Convert tangential coordinates to equatorial (RA, Dec) in degrees."""
xi = xiDeg * np.pi / 180.
eta = etaDeg * np.pi / 180.
ra0 = ra0Deg * np.pi / 180.
dec0 = dec0Deg * np.pi / 180.
ra = np.arctan(xi / (np.cos(dec0) - eta * np.sin(dec0))) + ra0
... | 47,765 |
def clean(ctx):
"""Clean out generated cookiecutter."""
print(COOKIE)
if os.path.exists(COOKIE):
shutil.rmtree(COOKIE)
print('Removed {0}'.format(COOKIE))
else:
print('App directory does not exist. Skipping.') | 47,766 |
def get_urls() -> List[str]:
"""Will read the rip.txt file to see all links and returns a list."""
if path.exists(rip_file):
rip = open(rip_file, "r")
urls = rip.readlines()
rip.close()
return urls
else:
raise FileNotFoundError("rip file not found") | 47,767 |
def build_docs(ctx, clean=False):
"""Builds the Sphinx docs"""
if clean:
print('Cleaning the docs')
ctx.run("rm -rf docs/sphinx/_build")
print('Building the docs')
os.chdir('docs/sphinx')
ctx.run("make html", pty=True) | 47,768 |
def type_from_tensors(tensors):
"""Builds a `tff.Type` from supplied tensors.
Args:
tensors: A nested structure of tensors.
Returns:
The nested TensorType structure.
"""
def _mapping_fn(x):
if not tf.is_tensor(x):
x = tf.convert_to_tensor(x)
return computation_types.TensorType(x.dtype... | 47,769 |
def roman_to_integer(roman_numeral):
"""
https://gist.github.com/kristopherjohnson/f4eca9018c5085fc736b2f29a202b8f8
"""
total = 0
last_value = sys.maxsize
for char in list(roman_numeral):
value = ROMAN_TO_INTEGER_MAP[char.upper()]
if value > last_value:
total += value... | 47,770 |
def cancel(bot, update, session, chat, user):
"""Send a help text."""
if not send_tagged_count_message(session, bot, user, chat):
keyboard = admin_keyboard if chat.is_maintenance else main_keyboard
call_tg_func(update.message.chat, 'send_message', ['All running commands are canceled'],
... | 47,771 |
def run_this_func(**context):
"""
Print the payload "message" passed to the DagRun conf attribute.
:param context: The execution context
:type context: dict
"""
print("Remotely received value of {} for key=message".format(context["dag_run"].conf["message"])) | 47,772 |
def is_none_or_empty(obj: Any) -> bool:
"""Determine if object is None or empty
:param obj: object
:return: if object is None or empty
"""
return obj is None or len(obj) == 0 | 47,773 |
def session(db, request):
"""
Creates a new database session with (with working transaction)
for test duration.
"""
db.session.begin_nested()
yield db.session
db.session.rollback() | 47,774 |
def create_python27_start_cmd(app_name,
login_ip, port, load_balancer_host, xmpp_ip):
""" Creates the start command to run the python application server.
Args:
app_name: The name of the application to run
login_ip: The public IP
port: The local port the application server will bind to
load_balanc... | 47,775 |
def main():
""" Main logic for program """
# Set up CLI interface
args = setup_cli(sys.argv[1:])
inputFile = 'majestic_million.csv'
print("\nResults:\n--------------------------------------------------------------")
with open(inputFile) as infile:
f_csv = csv.reader(infile)
hea... | 47,776 |
def create_query_constraint():
""" Create a constraint for a query WHERE clause """
op = oneOf("= < > >= <= != <>", caseless=True).setName("operator")
basic_constraint = (var + op + var_val).setResultsName("operator")
between = (
var + Suppress(upkey("between")) + value + Suppress(and_) + value
... | 47,777 |
def test_query_resource(pyoslc):
"""
GIVEN the PyOSLC API
WHEN requesting the query capability endpoint for getting a
specific Resource given the project and resource id
THEN
validating the status code of the response
parsing the response content into a graph in the application/... | 47,778 |
def reshape2D(x):
"""
Reshapes x from (batch, channels, H, W) to (batch, channels, H * W)
"""
return x.view(x.size(0), x.size(1), -1) | 47,779 |
def addNoise(s,x):
""" adds s percent random noise to reduce problems with zero traces """
xdif = max(x)-min(x)
n1,n2,n3 = s1.count,s2.count,s3.count
r = randfloat(n1,n2,n3)
x = add(mul(sub(r,0.5),s*xdif),x)
return x | 47,780 |
def calc_cs_face_area(lon_b, lat_b, r_sphere = 6.375e6):
"""Calculate area of cubed-sphere grid cells on one face
Inputs must be in degrees. Edge arrays must be
shaped [N+1 x N+1]
"""
# Convert inputs to radians
lon_b_rad = lon_b * np.pi / 180.0
lat_b_rad = lat_b * np.pi / 180.0
... | 47,781 |
def get_aliases(f):
"""
Gets aliases on Unix/Mac
"""
if platform.system() is not "Windows":
f.write('\n================ALIASES================\n')
p = subprocess.Popen('alias', shell=True,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
out = p.co... | 47,782 |
def yices_new_param_record():
"""Creates a new param object, an opaque object that stores various search parameters and options that control the heuristics used by the solver."""
return libyices.yices_new_param_record() | 47,783 |
def test_region_codelist():
"""Check replacing top-level hierarchy of yaml file as attribute for regions"""
code = CodeList.from_directory("region", TEST_DATA_DIR / "region_codelist")
assert "World" in code
assert code["World"]["hierarchy"] == "common"
assert "Some Country" in code
assert code... | 47,784 |
def parse_multipart(input, boundary):
""" Parse multipart/form-data
Parse mime-encoded multipart/form-data into a
python dictionary. This function returns a tuple
consisting of post vars, and files.
Attributes:
input -- Input data to be parsed
boundary -- Field bou... | 47,785 |
def get_fr_trj_ntrj(rslt, start, end, a_params):
"""Check whether event exhibits "blowup" behavior."""
# get spks during candidate replay event
spks_evt = rslt.spks[(start <= rslt.ts) & (rslt.ts < end), :]
# get mask over trj and non-trj PCs
pc_mask = rslt.ntwk.types_rcr == 'PC'
sgm_cu... | 47,786 |
def ParseSuppressionOfType(lines, supp_descriptor, def_line_no, report_type):
"""Parse the suppression starting on this line.
Suppressions start with a type, have an optional name and instruction, and a
stack trace that ends in a blank line.
""" | 47,787 |
def split_rows(filename, delimiter=',', row_limit=1000, output_path='.'):
"""
CSV splitter using csv-python library.
Arguments:
`filename`: The Input File Path
`row_limit`: The number of rows every file should have, 1000 by default.
`output_path`: Destination pa... | 47,788 |
def gapfilling(circuit: cirq.Circuit, placeholder: Sequence[Any]) -> cirq.Circuit:
"""
Fill single qubit gates according to placeholder on circuit
:param circuit:
:param placeholder:
:return:
"""
n_circuit = cirq.Circuit()
all_qubits = sorted(circuit.all_qubits())
i = 0
for m in... | 47,789 |
def train_data_from_directory(train_path, val_path, target_size=(224, 224), batch_size=16,
rescale=1. / 255, rotation_range=20, width_shift_range=0.2,
height_shift_range=0.20, zoom_range=0.3, vertical_flip=True,
horizontal_flip=Tr... | 47,790 |
def add_to_group(ctx, user, group):
"""Adds a user into a group.
Returns ``True`` if is just added (not already was there).
:rtype: bool
"""
result = ctx.sudo(f'adduser {user} {group}').stdout.strip()
return 'Adding' in result | 47,791 |
def ifft(X):
"""
Inverse FFT with normalization by N, so that x == ifft(fft(x)) within
round-off errors.
"""
N, x = len(X), fft(X, sign=1) # e^{j2\pi/N}
for i in range(N):
x[i] /= float(N)
return x | 47,792 |
def _validate_fields(fields: List[_Field]
) -> List[mapry.validation.SchemaError]:
"""
Validate the correctness of the the corresponding C++ fields of a composite.
Notably, we validate that there are no duplicates and no reserved keywords
in the C++ fields of a composite.
:pa... | 47,793 |
def calc_bh_bulge(model, gals, snapshot: int) -> None:
"""
Calculates the black hole mass as a function of bulge mass.
The number of galaxies added to ``Model.properties["snapshot_<snapshot>"]["BlackHoleMass"]`` and
``Model.propertiesp["snapshot_<snapshot>"]["BulgeMass"]`` arrays is given by
:py:at... | 47,794 |
def frames_collection(collection):
"""
returns a list of frames extracted from a collection of NAF files.
:param collection: collection of dictionaries with relevant info extracted from NAF files
:param collection: list
"""
collection_frames = []
for info_dict in collection:
for fra... | 47,795 |
def execute(*cmd, **kwargs):
"""Convenience wrapper around oslo's execute() method."""
if 'run_as_root' in kwargs and 'root_helper' not in kwargs:
kwargs['root_helper'] = _get_root_helper()
return processutils.execute(*cmd, **kwargs) | 47,796 |
async def async_build_devices(hass, zha_gateway, config_entry, cluster_ids):
"""Build a zigpy device for each cluster id.
This will build devices for all cluster ids that exist in cluster_ids.
They get added to the network and then the sensor component is loaded
which will cause sensor entities to get ... | 47,797 |
def trim_docstring(docstring):
"""
This is taken from PEP257, and was slightly modified to work with Python 3
(and renamed), but is otherwise included verbatim.
https://www.python.org/dev/peps/pep-0257/
"""
if not docstring:
return ''
# Convert tabs to spaces (following the nor... | 47,798 |
def load_ckp(model, ckp_path, device, parallel=False, strict=True):
"""Load checkpoint
Args:
ckp_path (str): path to checkpoint
Returns:
int, int: current epoch, current iteration
"""
ckp = torch.load(ckp_path, map_location=device)
if parallel:
model.module.load_state_d... | 47,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.