content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def mock_matviews_qs(monkeypatch):
"""Mocks all matvies to a single mock queryset"""
mock_qs = MockSet() # mock queryset
for k, v in MATERIALIZED_VIEWS.items():
if k not in ["tas_autocomplete_matview"]:
monkeypatch.setattr(
"usaspending_api.awards.models_matviews.{}.obje... | 5,296,400 |
def compute_depth_av_inflow(uv_inflow_3d, uv_inflow_2d):
"""Computes depth average of 3d field. Should only be called once."""
tmp_inflow_3d = Function(solver_obj.function_spaces.P1DGv)
inflow_averager = VerticalIntegrator(uv_inflow_3d,
tmp_inflow_3d,
... | 5,296,401 |
def a_coreProperties():
"""Syntactic sugar to construct a CT_CorePropertiesBuilder instance"""
return CT_CorePropertiesBuilder() | 5,296,402 |
def register_classes():
"""Register these classes with the `LinkFactory` """
PlotCastro.register_class()
PlotCastro_SG.register_class()
PlotSEDSummaryBands.register_class()
PlotSEDSummaryBands_SG.register_class() | 5,296,403 |
def install_pkgs(pkgs, timeout=60, env=None, check_times=False, pkg_cache={}):
"""Install native packages in a system.
:param dict pkgs: specifies a list of packages to be installed
:param int timeout: timeout in number of seconds, after that time the command
is terminated but only ... | 5,296,404 |
def model_builder(features,
labels,
mode,
params,
config,
output_type=ModelBuilderOutputType.MODEL_FN_OPS):
"""Multi-machine batch gradient descent tree model.
Args:
features: `Tensor` or `dict` of `Tensor` objects.
l... | 5,296,405 |
def cli(debug=False):
"""D-Wave Cloud Client interactive configuration tool.""" | 5,296,406 |
def dmax_curve_z(tddose, shot_y, shot_z):
"""
Return dmax Z curve for a shot
Parameters
----------
tddose: 3ddose object
contains dose and boundaries, possible symmetrized
shot_y: float
Y shot position, mm
shot_z: float
Z shot position, mm
returns: tuple of a... | 5,296,407 |
def get_erc20_tokens() -> pd.DataFrame:
"""Helper method that loads ~1500 most traded erc20 token.
[Source: json file]
Returns
-------
pd.DataFrame
ERC20 tokens with address, symbol and name
"""
file_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "..", "dat... | 5,296,408 |
def test_voltage_offset_symmetric():
"""Test extracting the voltage offset for 1D, 2D and 3D data.
"""
current = np.linspace(-1, 1, 101)
voltage = np.concatenate(
(np.linspace(-1, 0, 40), np.zeros(31), np.linspace(0, 1, 30))
)
assert compute_voltage_offset(current, voltage, 10) == 0
... | 5,296,409 |
def _2samp_rotate(sim, x, y, p, degree=90, pow_type="samp"):
"""Generate an independence simulation, rotate it to produce another."""
angle = np.radians(degree)
data = np.hstack([x, y])
same_shape = [
"joint_normal",
"logarithmic",
"sin_four_pi",
"sin_sixteen_pi",
... | 5,296,410 |
def _sort_nd2_files(files):
"""
The script used on the Nikon scopes is not handling > 100 file names
correctly and is generating a pattern like:
ESN_2021_01_08_00_jsp116_00_P_009.nd2
ESN_2021_01_08_00_jsp116_00_P_010.nd2
ESN_2021_01_08_00_jsp116_00_P_0100.nd2
ESN_2021_01_08_0... | 5,296,411 |
def trending_up(df: pd.Series, period: int) -> pd.Series:
"""returns boolean Series if the inputs Series is trending up over last n periods.
:param df: data
:param period: range
:return: result Series
"""
return pd.Series(df.diff(period) > 0, name="trending_up {}".format(period)) | 5,296,412 |
def get_maxtarget(pairs):
"""
This method looks at a set of (before_label, after_label) tuples.
There are a few informative statistics from this set.
- proportion of changed labels: P(before_label != after_label)
- maximum proportional class gain: max_i(P(before_label != after_label AND after_l... | 5,296,413 |
def _get_formats(region=None):
"""Return the formats for the region."""
if region:
region = _clean_region(region)
if region not in _number_formats_per_region:
raise InvalidComponent()
return [_number_formats_per_region[region]]
return _number_formats_per_region.values() | 5,296,414 |
def test_parse_weight_qualifiers_bad_logistic_mid_qualifier_value(sample_dataframe):
"""
Test to ensure the validation on qualifier types is working.
"""
sample_dataframe.loc[sample_dataframe[PathSet.WEIGHTS_COLUMN_WEIGHT_NAME] ==
'depart_early_cost_min.logistic.logistic_mid', '... | 5,296,415 |
def jsonCatalog():
"""
The function that returns a JSON format output that contains
all database data. Including all categories and all items.
"""
output = {}
# Get all the categories from the database
categories = session.query(CatalogCategory).all()
for category in categories:
... | 5,296,416 |
def argmax(values: np.ndarray) -> types.Action:
"""Argmax with random tie-breaking."""
check_numerics(values)
max_value = np.max(values)
return np.int32(np.random.choice(np.flatnonzero(values == max_value))) | 5,296,417 |
def html_parser():
"""
Create an HTML5 parser.
"""
return HTMLParser(strict=True) | 5,296,418 |
def p_mult_or_div_multiplicative_expr_1(p):
"""
mult_or_div_multiplicative_expr : numeric_literal_negative art_mult_or_art_div_unary_expr add_minus_div_mult_expr
"""
if len(p[2]) > 0:
op, right = p[2]
if len(p[3]) > 0:
op2, right2 = p[3]
p[0] = str(p[1])[:1], Ex... | 5,296,419 |
def test_help(cmd, noop_help):
"""Make sure help is available in both long and short forms."""
runner = CliRunner()
cmd.append('--help')
result = runner.invoke(arb, cmd)
assert result.exit_code == 0 and 'Usage: ' in result.output
cmd[-1] = '-h'
result = runner.invoke(arb, cmd)
assert res... | 5,296,420 |
def review_network(net, use_symbol=False, timing=False, num_rep=100, dir_out='', print_model_size=False):
"""inspect the network architecture & input - output
use_symbol: set True to inspect the network in details
timing: set True to estimate inference time of the network
num_rep: number of inference"""... | 5,296,421 |
def setup_seed(seed):
"""
setup seed to make the experiments deterministic
Parameters:
seed(int) -- the random seed
"""
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(seed)
torch.backends.cudnn.deterministic = True | 5,296,422 |
def main() -> int:
"""Entry point function."""
argument_parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
argument_parser.add_argument("INPUT")
argument_parser.add_argument("-o", "--output", default="a.dbg")
argument_parser.add_argument("-f", "--format", default="auto", choices... | 5,296,423 |
def _crop_shape(shape):
"""Calculates a new, smaller shape after cropping.
Args:
shape: A shape.
Returns:
A shape.
"""
return [int(CROP_RATIO * shape[0]), int(CROP_RATIO * shape[1]), shape[2]] | 5,296,424 |
def app_context():
"""Get app context for tests
:return:
"""
return app.app_context() | 5,296,425 |
def fit_linear_least_squares(X, y, weights=None):
"""Fit linear model
Returns
-------
coefs : array
XXinv : array
Inverse of (X*transpose(X)), or None if system is not full rank
"""
num_coefs = np.size(X,1)
if weights is not None:
rtw = np.diag(np.sqrt(weights))
... | 5,296,426 |
def dmp_rem(f, g, u, K):
"""
Returns polynomial remainder in ``K[X]``.
**Examples**
>>> from sympy.polys.domains import ZZ, QQ
>>> from sympy.polys.densearith import dmp_rem
>>> f = ZZ.map([[1], [1, 0], []])
>>> g = ZZ.map([[2], [2]])
>>> dmp_rem(f, g, 1, ZZ)
[[1], [1, 0], []]
... | 5,296,427 |
def post_process_slides_output(file, pdf, python, slides, exc=True,
nblinks=None, fLOG=None,
notebook_replacements=None):
"""
Processes a :epkg:`HTML` file generated from the conversion of a notebook.
@param file filename... | 5,296,428 |
def find_data(*args):
"""find_data(ea_t ea, int sflag) -> ea_t"""
return _idaapi.find_data(*args) | 5,296,429 |
def a_starify(search_map: array):
"""Beings an a-star search through the input numpy array.
:param search_map: Input numpy array.
:return:
"""
end_point = (search_map.shape[1] - 1, search_map.shape[0] - 1)
start_node = Node(0, 0, None, 0, end_point[0], end_point[1])
heap = []
start_node... | 5,296,430 |
def parse_search_article_result(html):
"""
解析一页搜索结果中所有的微信文章条目,包括文章标题、摘要、时间、文章来源
:param html:
:return:list
"""
soup = BeautifulSoup(html, 'html.parser')
ul = soup.find('ul', attrs={'class': 'news-list'})
res = list()
for li in ul.find_all('li'):
item = dict()
txt_box =... | 5,296,431 |
def generate_ground_image(height,
width,
focal,
principal_point,
camera_rotation_matrix,
camera_translation_vector,
ground_color=(0.43, 0.43, 0.8)):
"""Generate a... | 5,296,432 |
def get_config(p):
"""Reads a config file.
:return: dict of ('section.option', value) pairs.
"""
cfg = {}
parser = ConfigParser()
parser.readfp(codecs.open(p, encoding='utf8'))
for section in parser.sections():
for option in parser.options(section):
type_ = option.spli... | 5,296,433 |
def process_key(key):
"""
返回32 bytes 的key
"""
if not isinstance(key, bytes):
key = bytes(key, encoding='utf-8')
if len(key) >= 32:
return key[:32]
return pad(key, 32) | 5,296,434 |
def dobro(valor=0, formatc=False):
"""
-> Dá o dobro de um valor.
Parâmetros opcionais
:param valor: Valor que será dobrado.
:param formatc: Booleano que indica se a formatação no valor será feita
:return: Valor dobrado com a formatação ou não.
"""
res = valor * 2
return res if not f... | 5,296,435 |
def _suppression_polynomial(halo_mass, z, log_half_mode_mass, c_scale, c_power):
"""
:param halo_mass: halo mass
:param z: halo redshift
:param log_half_mode_mass: log10 of half-mode mass
:param c_scale: the scale where the relation turns over
:param c_power: the steepness of the turnover
... | 5,296,436 |
def patch_nx():
"""Temporary fix for NX's watts_strogatz routine, which has a bug in versions 1.1-1.3
"""
import networkx as nx
# Quick test to see if we get the broken version
g = nx.watts_strogatz_graph(2, 0, 0)
if g.number_of_nodes() != 2:
# Buggy version detected. Create a patche... | 5,296,437 |
def KLDiv_loss(x, y):
"""Wrapper for PyTorch's KLDivLoss function"""
x_log = x.log()
return torch.nn.functional.kl_div(x_log, y) | 5,296,438 |
def limit_vals(input_value, low_limit, high_limit):
"""
Apply limits to an input value.
Parameters
----------
input_value : float
Input value.
low_limit : float
Low limit. If value falls below this limit it will be set to this value.
high_limit : float
High limit. If... | 5,296,439 |
def reformat_remove_leading_zeros(x, pos):
"""Format 1 as 1, 0 as 0, and all values whose absolute values is between
0 and 1 without the leading "0." (e.g., 0.7 is formatted as .7 and -0.4 is
formatted as -.4)."""
val_str = '{:g}'.format(x)
if 0 < np.abs(x) < 1:
return val_str.replace("0", "... | 5,296,440 |
def getFormData(page):
"""
Finds form data required to post request for
next page. Returns tuple with data
"""
soup = BeautifulSoup(page, 'html.parser')
viewstate = soup.find('input', {'id': '__VIEWSTATE' })['value']
generator = soup.find('input', {'id': '__VIEWSTATEGENERATOR'})['... | 5,296,441 |
def get_mask(
ref,
sub,
pyg=False
):
"""
Get the mask for a reference list based on a subset list.
Args:
ref: reference list
sub: subset list
pyg: boolean; whether to return torch tensor for PyG
Return:
mask: list or torch.BoolTensor
"""
mask = [it... | 5,296,442 |
def round_m(x):
"""Round meters to an accuracy that avoids machine error."""
return np.around(x, decimals=6) | 5,296,443 |
def _npy2fits(mapfile, mapfile_fits, field_width) -> None:
"""
Convert maps that are stored in .npy into .fits format
(applies only to 'flat' projection maps).
Args:
path : str
field_width : np.float
given in degrees
"""
# Convert .npy to .fits
data = fits.Primar... | 5,296,444 |
def get_merged_overlapping_coords(start_end):
"""merges overlapping spans, assumes sorted by start"""
result = [start_end[0]]
prev_end = result[0][-1]
for i in range(1, len(start_end)):
curr_start, curr_end = start_end[i]
# if we're beyond previous, add and continue
if curr_start... | 5,296,445 |
def create_prime_node():
"""
Return a prime node with no children
OUTPUT:
A node object with node_type set as NodeType.PRIME
EXAMPLES::
sage: from sage.graphs.graph_decompositions.modular_decomposition import create_prime_node
sage: node = create_prime_node()
sage: node
... | 5,296,446 |
def u_from_psi(head, psi):
"""Calculate u_calc from non dimensional psi.
Parameters
----------
head : pint.Quantity, float
Polytropic head.
psi : pint.Quantity, float
Head coefficient.
Returns
-------
u_calc : pint.Quantity, float
Impeller tip speed.
"""
... | 5,296,447 |
def flower(args):
"""Starts Flower, Celery monitoring tool"""
broka = conf.get('celery', 'BROKER_URL')
address = '--address={}'.format(args.hostname)
port = '--port={}'.format(args.port)
api = '' # pylint: disable=redefined-outer-name
if args.broker_api:
api = '--broker_api=' + args.bro... | 5,296,448 |
def collapse_objlist(object_list, keyword, suffix='', doarray = False):
""" Given a LIST of identical objects, collapse the objects to form a
list of only a single keyword.
::
aplist = nsdata.getirafap('ap1')
cenlist = nsdata.collapse_objlist(aplist, 'keyword')
If yo... | 5,296,449 |
def make_deprecate(meth, old_name):
"""TODO Add Docs
"""
new_name = meth.__name__
def deprecated_init(*args, **kwargs):
warn("autogluon.{} is now deprecated in favor of autogluon.{}."
.format(old_name, new_name), AutoGluonWarning)
return meth(*args, **kwargs)
deprecated... | 5,296,450 |
def add_gmail(t=None, u=None, p=None):
"""
Adds server GMail to instance
Adds GMail settings to vim /var/lib/geonode/rogue_geonode/geoshape/local_settings.py
"""
address = _request_input("User", u, True)+'@gmail.com'
host = 'smtp.gmail.com'
return _run_task(_add_email, args=None, kwargs={... | 5,296,451 |
def unpack_mac(sixbytes):
"""Converts a mac address given in a six byte string in network
byte order to a string in colon delimited notation.
>>> unpack_mac(b"012345")
'30:31:32:33:34:35'
>>> unpack_mac(b"bad")
Traceback (most recent call last):
...
ValueError: given buffer is not exactly six bytes long
@typ... | 5,296,452 |
def create_obs_stacker(environment, history_size=4):
"""Creates an observation stacker.
Args:
environment: environment object.
history_size: int, number of steps to stack.
Returns:
An observation stacker object.
"""
return ObservationStacker(history_size,
environment.vectorized_observation_sha... | 5,296,453 |
def s3_name(request):
"""[summary]
Args:
request ([type]): [description]
Returns:
[type]: [description]
"""
bucket_name = "test.bucket"
mock = mock_s3()
mock.start()
conn = boto3.resource("s3", region_name="us-east-1")
conn.create_bucket(Bucket=bucket_name)
requ... | 5,296,454 |
def validate_rid(model, rid):
""" Ensure the resource id is proper """
rid_field = getattr(model, model.rid_field)
if isinstance(rid_field, IntType):
try:
int(rid)
except (TypeError, ValueError):
abort(exceptions.InvalidURL(**{
'detail': 'The resourc... | 5,296,455 |
def zoom_percent(old_path, new_path, percent):
"""
按比例缩放图片 - 指定百分比
"""
img = Image.open(old_path)
w, h = img.size
img.resize(
(int(w*percent), int(h*percent)),
Image.ANTIALIAS
).save(new_path, "JPEG", quality=85) | 5,296,456 |
def git_repo(pip_url_kwargs):
"""Create an git repository for tests. Return repo."""
git_repo = create_repo_from_pip_url(**pip_url_kwargs)
git_repo.obtain()
return git_repo | 5,296,457 |
def copy_network_to_topology(transport_type, network, topology):
"""
Copy the network into topology.
:param tranport_type: transport that the network is representing.
:param network: the graph to be copied.
:param topology: the target topology.
"""
for node, data in network.nodes(data=True... | 5,296,458 |
def schemadocs(args=None):
"""Open buildtest schema docs in web browser. This implements ``buildtest schemadocs``"""
webbrowser.open("https://buildtesters.github.io/buildtest/") | 5,296,459 |
def build_asset_update(
src_asset: Asset, dst_asset: Asset, src_id_dst_map: Dict[int, int], project_src: str, runtime: int, depth: int
) -> Asset:
"""
Makes an updated version of the destination asset based on the corresponding source asset.
Args:
src_asset: The asset from the source to be repl... | 5,296,460 |
def _pathSet(dictionary: dict, path: str, value: _nml_types, sep: str = "%"):
"""
Sets a variable in a dictionary, given the namelist path string.
Assumes the input path uses Fortran-style 1-based indexing of arrays
"""
path = path.split(sep)
key = path[-1]
dictionary = _pathGet(dictionary,... | 5,296,461 |
def test_markdown_code_block():
"""We test that
- A code blocks are supported. Sort of. BUT THE INDENTATION IS CURRENTLY LOST!
- Indented markdown test from editors is supported. The Panel Markdown does not support this.
"""
code_block = """
This is not indented
```python
print("Hello Awesome Pane... | 5,296,462 |
def dw_WriteSegmentOrExchangeData(ttime,fname,datablock,boundids,WriteAscii=True):
"""
Writes a timestep to a segment/exchange data file (appends to an existing
file or creates a new one).
Input:
- time - time for this timestep
- fname - File path of the segment/exchange data... | 5,296,463 |
def euclidean_distance(mov_data, joint1, joint2):
"""Calculate the euclidean distance between the 2 given joints for all the frames of the grasping movement.
Args:
mov_data (pd.DataFrame): A pd.DataFrame containing the skeletal data of the grasping movement and of 9 frames before the beginning of the m... | 5,296,464 |
def ta_iter_SWS(*args):
"""
Function to be optimized for free protons, calls Bohrium version if required
Parameters
----------
mask
Mask indicating which cells to include / exclude from calculation
x
Free protons
k1
k2
k1p
k2p
k3p
st
ks
kf
ft... | 5,296,465 |
def get_integer_attribute(attribute_list, name, default_value=None):
"""Returns the integer value of an attribute, if any, or default_value.
Arguments:
attribute_list: A list of attributes to search.
name: The name of the desired attribute.
default_value: A value to return if name is not found in... | 5,296,466 |
def init_logger(log_file=None, log_file_level=logging.NOTSET):
"""
Example:
init_logger(log_file)
logger.info("abc'")
"""
if isinstance(log_file, Path):
log_file = str(log_file)
log_format = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(name)s - %(message)s... | 5,296,467 |
def pppoe_login(isp, mac=None, eth=None):
"""
获取校园外网pppoe权限
:param isp: ISP类型,1为联通、2为电信、3为移动
:param mac: 指定要获取权限的网卡的mac
:param eth: 指定要获取权限的网卡(用于linux)指定后mac参数将无效
:return:
"""
succeeded = msg = None
if mac is None and eth is None:
succeeded, msg = get_perm(isp)
elif mac a... | 5,296,468 |
def add_news():
"""新闻编辑详情页"""
if not g.user.is_admin:
return redirect('/')
if request.method == 'GET':
# 查询分类的数据
categories = []
try:
categories = Category.query.all()
except Exception as e:
current_app.logger.error(e)
categories_li ... | 5,296,469 |
def get_diag(code, command):
""" Generate diagramm and return data """
import tempfile
import shutil
code = code + u"\n"
try:
tmpdir = tempfile.mkdtemp()
fd, diag_name = tempfile.mkstemp(dir=tmpdir)
f = os.fdopen(fd, "w")
f.write(code.encode("utf-8"))
f.clo... | 5,296,470 |
def get_address(tag_name, region, client):
"""
Collects the addresses of the aws instances being used for the estimation
:param tag_name: aws 'Name' tag of the instances
:param region: aws region
:param client: aws client
:return: list with aws instance addresses
"""
ec2 = boto3.Session(... | 5,296,471 |
def generate_instances_for_appliances_by_dataids(
schema, tables, appliances, dataids, sample_rate=None):
"""
Returns instances for a list of appliances across a set of dataids
"""
#TODO probably a more efficient way to do this
instances = [generate_appliances_instances(schema, tables, appli... | 5,296,472 |
def handle_work(work):
"""Handle work"""
LOG.info('Homework: ' + work.title)
LWORK.append(work)
if work.file is not None:
LOG.info('Homework file: ' + work.file.name)
if work.course + work.file.name not in DOWNLOADED:
work.file.save(os.path.join(SAVE, work.course))
... | 5,296,473 |
async def pmgoldrush(sendable: Sendable):
"""
The user will receive a pm if a goldrush happens at the provided location.
It is checked if it is a valid location.
:param ctx: discord context
"""
view = SelectsView(sendable, options=getgoldrushlocations(),
selectoption=lambd... | 5,296,474 |
def SearchableField(**kw):
# type: (**Any) -> Dict[str, Any]
"""Configure a searchable text field for an Azure Search Index
:param name: Required. The name of the field, which must be unique within the fields collection
of the index or parent field.
:type name: str
:param type: Required. The d... | 5,296,475 |
def geometry_factor_trace(trace, gap, thickness):
"""Return the kinetic inductance geometry factor for the central conducting trace of a CPW.
If the kinetic inductance of the central trace is L_k, its kinetic inductance contribution per unit length is
L = g_c L_k,
where g_c is the geometry factor ret... | 5,296,476 |
def test_copytree():
"""TODO:"""
pass | 5,296,477 |
def list_dir(conn=None):
"""
:param conn:
:return: <list>
"""
available = RBF.filter({PART_FIELD: False}).pluck(PRIMARY_FIELD).run(conn)
return [x[PRIMARY_FIELD] for x in available] | 5,296,478 |
def get_location_in_distance(actor, distance):
"""
Obtain a location in a given distance from the current actor's location.
Note: Search is stopped on first intersection.
@return obtained location and the traveled distance
"""
waypoint = CarlaDataProvider.get_map().get_waypoint(actor.get_locati... | 5,296,479 |
def write_cluster_group_tsv(IDs, quality, output_directory):
"""
Writes a tab-separated cluster_group.tsv file
Inputs:
-------
IDs : list
List of cluster IDs
quality : list
Quality ratings for each unit (same size as IDs)
output_directory : String
Location to save th... | 5,296,480 |
def read_arrays_and_return():
"""
Reads the prepared numpy arrays
# Returns: the read np arrays
"""
X_train = np.load('arrays/X_train_w2v.npy')
y_train = np.load('arrays/y_train_w2v.npy')
X_test = np.load('arrays/X_test_w2v.npy')
y_test = np.load('arrays/y_test_w2v.npy')
retu... | 5,296,481 |
def test_variance_negative(X):
"""Test VarianceThreshold with negative variance."""
var_threshold = VarianceThreshold(threshold=-1.0)
msg = r"^Threshold must be non-negative. Got: -1.0$"
with pytest.raises(ValueError, match=msg):
var_threshold.fit(X) | 5,296,482 |
def HtmlRenderer(tooltip):
"""
A renderer that implements all tooltip features
in html.
"""
ret = []
USE_STYLE = True
lineTpl = '<div style="%s">%s</div>'
sideTpl = '<span style="%s">%s</span>'
for idx, line in enumerate(tooltip):
lineHtml = []
lineStyle = []
if idx == 0:
lineStyle.append("font-size... | 5,296,483 |
def ensure_sun_set(hass):
""" Trigger sun to set if above horizon. """
if sun.is_on(hass):
hass.bus.fire(
EVENT_TIME_CHANGED,
{'now':
sun.next_setting_utc(hass) + timedelta(seconds=10)}) | 5,296,484 |
def linear_v2n(inputs, output_size, bias, w_x_inp, params, concat=False,
dtype=None, scope=None, d2=False):
"""
Linear layer
:param inputs: A Tensor or a list of Tensors with shape [batch, input_size]
:param output_size: An integer specify the output size
:param bias: a boolean value ... | 5,296,485 |
def two_opt_with_cycle(orderedPoseListe):
"""
returns an optimised list from an orderedpose using the 2-opt algo with creating a Hamilton cycle
"""
improve = True #we iterate in the list as long as we find improvements
while improve == True:
improve = False
for i in range(len(ordered... | 5,296,486 |
def html_to_spreadsheet_cell(html_element):
""" Parse HTML elmement, like <a href=www.google.com>Google</a> to =HYPERLINK(www.google.com, Google) """
link = html_element.find("a")
if link:
return '=HYPERLINK("{}", "{}")'.format(link['href'], link.contents[0])
else:
return html_element.te... | 5,296,487 |
def get_bucket(bucket_name):
"""
Established a connection and gets s3 bucket
"""
if '.' in bucket_name:
s3 = boto.connect_s3(calling_format=OrdinaryCallingFormat())
else:
s3 = boto.connect_s3()
return s3.get_bucket(bucket_name) | 5,296,488 |
def _get_class(canonical_name: str):
"""
Gets a class by it's canonical name. Mind that this can only work with classes that does not require
any argument during instantiation.
:param canonical_name: the canonical name of the class to load dynamically, e.g. x.y.Module.Class
:returns: the instance ... | 5,296,489 |
def build_tcp_flags() -> int:
"""
Assembles TCP flags.
"""
flags = 0
for flag in (
TCP_CWR, TCP_ECE, TCP_URG, TCP_ACK,
TCP_PSH, TCP_RST, TCP_SYN, TCP_FIN
):
flags <<= 1
flags |= flag
return flags | 5,296,490 |
def main():
"""
Sample for adding a NIC to vm
"""
parser = cli.Parser()
parser.add_required_arguments(cli.Argument.PORT_GROUP)
parser.add_optional_arguments(cli.Argument.VM_NAME, cli.Argument.UUID)
args = parser.get_args()
si = service_instance.connect(args)
vm = None
if args.uu... | 5,296,491 |
def test_ord_num_th():
"""64738 is 64738th"""
assert ord_num(64738) == '64738th' | 5,296,492 |
def send_to_slack_channel(url, text):
"""Sending messages to Slack channels."""
payload = {
"text": text
}
if settings.DEBUG:
print(text)
else:
requests.post(url=url, data=json.dumps(payload))
return True | 5,296,493 |
def parseOptionWithArgs(plugin: str) -> Tuple[str, str]:
"""Parse the plugin name into name and parameter
@type plugin: str
@param plugin: The plugin argument
@returns tuple[str, str]: The plugin name and parameter
"""
if '=' in plugin:
plugin, param = plugin.split('=', 1)
else:
... | 5,296,494 |
def spm_warp_to_mni(wf_name="spm_warp_to_mni"):
""" Run Gunzip and SPM Normalize12 to the list of files input and outputs the list of warped files.
It does:
- Warp each individual input image to the standard SPM template
Parameters
----------
wf_name: str
Name of the workflow.
Nip... | 5,296,495 |
def dash():
"""Run the rq-dashboard"""
call('rq-dashboard', shell=True) | 5,296,496 |
def build_insert_ddl(table_name: TableName, column_list, query_stmt) -> str:
"""Assemble the statement to insert data based on a query."""
columns = join_with_double_quotes(column_list, sep=",\n ")
insert_stmt = """
-- arthur.insert: {table.identifier}
INSERT INTO {table} (
... | 5,296,497 |
def cli_get_cli(cmd, raw_args):
"""Print a kipoi cli path for a model
"""
parser = argparse.ArgumentParser(
'kipoi env {}'.format(cmd),
description='Print kipoi cli path for specific model.'
)
add_env_args(parser)
parser.add_argument('-a', '--all', action='store_true',
... | 5,296,498 |
def get_user_password(args):
"""
Allows the user to print the credential for a particular keyring entry
to the screen
"""
username = '%s:%s' % (args.env, args.parameter)
warnstring = colors.rwrap("__ WARNING ".ljust(80, '_'))
print("""
%s
If this operation is successful, the credential sto... | 5,296,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.