content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def htmlprint(*values, plain=None, **options):
""" Convert HTML to VTML and then print it.
Follows same semantics as vtmlprint. """
print(*[htmlrender(x, plain=plain) for x in values], **options) | 46,400 |
def photometer_and_plot(kicid, quarter, fake=False, makeplots=True, k2=False):
"""
## inputs:
- `kicid` - KIC number
- `quarter` - Kepler observing quarter (or really place in list of files)
## outputs:
- [some plots]
- `time` - times in KBJD
- `sap_photometry` - home-built SAP equivale... | 46,401 |
def num_prim_vertices(prim: hou.Prim) -> int:
"""Get the number of vertices belonging to the primitive.
:param prim: The primitive to get the vertex count of.
:return: The vertex count.
"""
return prim.intrinsicValue("vertexcount") | 46,402 |
def batch_features_labels(features, labels, batch_size):
"""
Split features and labels into batches
"""
for start in range(0, len(features), batch_size):
end = min(start + batch_size, len(features))
feature_out = [np.expand_dims(f, axis=0) for f in features[start:end]]
lab... | 46,403 |
def read_geoparquet(path: str) -> GeoDataFrame:
"""
Given the path to a parquet file, construct a geopandas GeoDataFrame by:
- loading the file as a pyarrow table
- reading the geometry column name and CRS from the metadata
- deserialising WKB into shapely geometries
"""
# read parquet file ... | 46,404 |
def cmd_run_json_block_file(file):
"""`file` is a file containing a FullBlock in JSON format"""
return run_json_block_file(file) | 46,405 |
def collide_mask(left, right):
"""collision detection between two sprites, using masks.
pygame.sprite.collide_mask(SpriteLeft, SpriteRight): bool
Tests for collision between two sprites by testing if their bitmasks
overlap. If the sprites have a "mask" attribute, that is used as the mask;
otherwis... | 46,406 |
def teardown_cluster(config_file: str, yes: bool, workers_only: bool,
override_cluster_name: Optional[str],
keep_min_workers: bool,
proxy_stop: bool = False) -> None:
"""Destroys all nodes of a cluster described by a config json."""
config = yaml.sa... | 46,407 |
def fetch_production(zone_key='IN-GJ', session=None, target_datetime=None,
logger=getLogger('IN-GJ')) -> list:
"""Requests the last known production mix (in MW) of a given country."""
session = session or requests.session()
if target_datetime:
raise NotImplementedError(
... | 46,408 |
def xyz_order(coordsys, name2xyz=None):
""" Vector of orders for sorting coordsys axes in xyz first order
Parameters
----------
coordsys : ``CoordinateSystem`` instance
name2xyz : None or mapping
Object such that ``name2xyz[ax_name]`` returns 'x', or 'y' or 'z' or
raises a KeyError ... | 46,409 |
def register_specialization(t, cython_c_type=None, cython_cy_type=None,
cython_py_type=None, cython_cimport=None,
cython_cyimport=None, cython_pyimport=None):
"""This function will add a template specialization so that it may be used
normally with the r... | 46,410 |
def parse_item(year, draft_type, row):
"""Parses the given row out into a DraftPick item."""
draft_round = parse_int(row, 'th[data-stat="draft_round"]::text', -1)
draft_pick = parse_int(row, 'td[data-stat="draft_pick"]::text', -1)
franchise = '/'.join(
row.css('td[data-stat="team"] a::attr(href... | 46,411 |
def buildJointChain(prefix, suffix, startPos, endPos, jointNum, orientJoint="xyz", saoType="yup"):
"""
Build a straight joint chain defined by start and end position.
:param prefix: `string` prefix string in joint name
:param suffix: `string` suffix string in joint name
:param startPos: `list` [x,y,... | 46,412 |
def predict(model, img_load, resizeNum, is_silent, gpu=0):
"""
input:
model: model
img_load: A dict of image, which has two keys: 'img_ori' and 'img_data'
the value of the key 'img_ori' means the original numpy array
the value of the key 'img_data' is the list of five resize images
... | 46,413 |
def reverse_preorder(root):
"""
@ input: root of lcrs tree
@ output: integer list of id's reverse preorder
"""
node_list = []
temp_stack = [root]
while len(temp_stack) != 0:
curr = temp_stack.pop()
node_list.append(curr.value)
if curr.child is not None:
... | 46,414 |
def test_is_commit_verified_no_verified_key(commit):
"""
Test is_commit_verified fails correctly when the verification keys are not present
in the GitHub API response object.
"""
with pytest.raises(KeyError):
action.is_commit_verified(commit) | 46,415 |
def calc_binned_percentile(bin_edge,xaxis,data,per=75):
"""Calculate the percentile value of an array in some bins.
per is the percentile at which to extract it. """
percen = np.zeros(np.size(bin_edge)-1)
for i in xrange(0,np.size(bin_edge)-1):
ind = np.where((xaxis > bin_edge[i])*(xaxis < bin_e... | 46,416 |
def run_services(container_factory, config, make_cometd_server, waiter):
""" Returns services runner
"""
def _run(service_class, responses):
"""
Run testing cometd server and example service with tested entrypoints
Before run, the testing cometd server is preloaded with passed
... | 46,417 |
def _process_image_files(name, filenames, data_dir, num_shards):
"""Process and save list of images as TFRecord of Example protos.
Args:
name: string, unique identifier specifying the data set
filenames: list of strings; each string is a path to an image file
synsets: list of strings; each st... | 46,418 |
def cleaned_request(request_type, *args, **kwargs):
""" Perform a cleaned requests request """
s = requests.Session()
# this removes netrc checking
s.trust_env = False
return s.request(request_type, *args, **kwargs) | 46,419 |
def construct_speech_to_text_phrases_context(event: EventIngestionModel) -> List[str]:
"""
Construct a list of phrases to use for Google Speech-to-Text speech adaption.
See: https://cloud.google.com/speech-to-text/docs/speech-adaptation
Parameters
----------
event: EventIngestionModel
... | 46,420 |
def highScore(self):
""" Main program is here. """
try:
self.high_score_file = open("high_score.txt", "r")
self.player.high_score = int(self.high_score_file.read())
self.high_score_file.close()
print("The high score is", self.player.high_score)
except IOError:
pr... | 46,421 |
def data_science_community(articles, authors):
"""
Input: Articles and authors collections. You may use only one of them
Output: 3-tuple reporting on subgraph of authors of data science articles
and their co-authors: (number of connected components,size of largest
connected component, size of smalle... | 46,422 |
def breadth_first_search(G, seed):
"""Breadth First search of a graph.
Parameters
----------
G : csr_matrix, csc_matrix
A sparse NxN matrix where each nonzero entry G[i,j] is the distance
between nodes i and j.
seed : int
Index of the seed location
Returns
-------
... | 46,423 |
def virtualenv(directory, local=False):
"""
Context manager to activate an existing Python `virtual environment`_.
::
from fabric.api import run
from fabtools.python import virtualenv
with virtualenv('/path/to/virtualenv'):
run('python -V')
.. _virtual environment... | 46,424 |
async def test_device_name_from_structure(hass):
"""Test a device without a custom name, inferring name from structure."""
devices = {
"some-device-id": Device.MakeDevice(
{
"name": "some-device-id",
"type": THERMOSTAT_TYPE,
"traits": {
... | 46,425 |
def main_page():
"""
Pass table of latest sensor readings as context for main_page
"""
LOG.info("Main Page triggered")
context = dict(
sub_title="Latest readings:",
table=recent_readings_as_html()
)
return render_template('main_page.html', **context) | 46,426 |
def load_config_file(filename):
"""Load configuration from YAML file."""
docs = yaml.load_all(open(filename, 'r'), Loader=yaml.SafeLoader)
config_dict = dict()
for doc in docs:
for k, v in doc.items():
config_dict[k] = v
return config_dict | 46,427 |
def test_dual_ge_and_le_diff_numbers(df, right):
"""Test output for multiple conditions."""
l_ge, l_le = ["A", "E"]
r_ge, r_le = ["Integers", "Dates"]
columns = ["B", "A", "E", "Floats", "Integers", "Dates"]
expected = (
df.assign(t=1)
.merge(right.assign(t=1), on="t", how="inner", ... | 46,428 |
def CausalConv(x, dilation_rate, filters, kernel_size=2, scope = ""):
"""Performs causal dilated 1D convolutions.
Args:
x : Tensor of shape (batch_size, steps, input_dim).
dilation_rate: Dilation rate of convolution.
filters: Number of convolution filters.
kernel_size: Width of convolution kernel. ... | 46,429 |
def test_FastqParser():
"""
Write your unit test for your FastqParser
class here. You should generate an instance of
your FastqParser class and assert that it properly
reads in the example Fastq File.
"""
# Generating FastqParser instance, and itterating it into a list
parser_obj = Fastq... | 46,430 |
def doPlayerMove(player, board):
"""Ask the player for a move and carry it out on the board."""
validMoves = getValidMoves(player, board)
print('It is player ' + player.upper() + '\'s turn.')
print('Select which pawn you want to move:', ' '.join(validMoves))
print('(Or enter QUIT to quit.)')
wh... | 46,431 |
def process_alias_export_namespace(namespace):
"""
Validate input arguments when the user invokes 'az alias export'.
Args:
namespace: argparse namespace object.
"""
namespace.export_path = os.path.abspath(namespace.export_path)
if os.path.isfile(namespace.export_path):
raise CLI... | 46,432 |
def makeTable(grid):
"""Create a REST table."""
def makeSeparator(num_cols, col_width, header_flag):
if header_flag == 1:
return num_cols * ("+" + (col_width) * "=") + "+\n"
else:
return num_cols * ("+" + (col_width) * "-") + "+\n"
def normalizeCell(string, length):... | 46,433 |
def generate_and_validate(config: Config) -> str:
"""Validate and generate mypy config."""
config_path = config.root / ".strict-typing"
with config_path.open() as fp:
lines = fp.readlines()
# Filter empty and commented lines.
parsed_modules: list[str] = [
line.strip()
for ... | 46,434 |
def coords_to_bin(
x: npt.NDArray,
y: npt.NDArray,
x_bin_width: float,
y_bin_width: float,
) -> tuple[npt.NDArray[np.int_], npt.NDArray[np.int_]]:
"""
x: list of positive east-west coordinates of some sort
y: list of positive north-south coordinates of some sort
x_bin_width: bin width fo... | 46,435 |
def test_fit_sphere_least_squares():
"""Test that it fits a sphere with some gaussian noise"""
x_centre = 1.74839
y_centre = 167.0899222
z_centre = 200.738829
radius = 7.543589
#some arrays to fit data to
coordinates = numpy.ndarray(shape=(1000, 3), dtype=float)
#fill the arrays with ... | 46,436 |
def _gcs_request(func: Callable):
"""
Wrapper function for gcs requests in order to create more helpful error
messages.
"""
@wraps(func)
def wrapper(url: str, *args, **kwargs):
try:
return func(url, *args, **kwargs)
except NotFound:
raise FileNotFoundErro... | 46,437 |
def nllsqfunc(params: np.ndarray, qm: HessianOutput, qm_hessian: np.ndarray, mol: Molecule,
loss: list[float]=None) -> np.ndarray:
"""Residual function for non-linear least-squares optimization based on the difference of MD
and QM hessians.
Keyword arguments
-----------------
para... | 46,438 |
def relist_streaming_server(sender, data, server, game, players, **kwargs):
"""Enable status querying for a streaming server."""
if not server.listed:
server.listed = True
server.save(update_fields=['listed'])
logger.debug('Relisted a streaming server (%s)' % server) | 46,439 |
def autodiscover():
"""
Autodiscover function from django.contrib.admin
"""
for app in settings.INSTALLED_APPS:
mod = import_module(app)
try:
before_import_registry = copy.copy(site._registry)
import_module('%s.admin' % app)
except:
site._... | 46,440 |
def wait_for_mongod_shutdown(mongod_control, timeout=2 * ONE_HOUR_SECS):
"""Wait for for mongod to shutdown; return 0 if shutdown occurs within 'timeout', else 1."""
start = time.time()
status = mongod_control.status()
while status != "stopped":
if time.time() - start >= timeout:
LOG... | 46,441 |
def get_installed_antivirus_software() -> List[dict]:
"""
Not happy with it either. But yet here we are... Thanks Microsoft for not having SecurityCenter2 on WinServers
So we need to detect used AV engines by checking what is installed and do "best guesses"
This test does not detect Windows defender sin... | 46,442 |
def mi(x,y,k=3,base=2):
""" Mutual information of x and y
x,y should be a list of vectors, e.g. x = [[1.3],[3.7],[5.1],[2.4]]
if x is a one-dimensional scalar and we have four samples
"""
x = [[entry] for entry in x]
y = [[entry] for entry in y]
assert len(x)==len(y), "Lists should have ... | 46,443 |
def _xls_cc_ir_impl_wrapper(ctx):
"""The implementation of the 'xls_cc_ir' rule.
Wrapper for xls_cc_ir_impl. See: xls_cc_ir_impl.
Args:
ctx: The current rule's context object.
Returns:
ConvIRInfo provider
DefaultInfo provider
"""
ir_conv_info, built_files, runfiles = _xls_cc... | 46,444 |
def create_dataset(message_sizes: List[int], labels: List[int], window_size: int, num_samples: int, rand: np.random.RandomState) -> Tuple[np.ndarray, np.ndarray]:
"""
Creates the attack dataset by randomly sampling message sizes of the given window.
Args:
message_sizes: The size of each message (in... | 46,445 |
def test_three_related_wout_ac(clean_db, three_family_with_trials, capsys):
"""Test three related experiments with all types of trials."""
orion.core.cli.main(["status"])
captured = capsys.readouterr().out
expected = """\
test_double_exp-v1
==================
status quantity
----------- -----... | 46,446 |
def infer_Tmap_from_clonal_info_alone_private(
adata_orig, method="naive", clonal_time_points=None, selected_fates=None
):
"""
Compute transition map using only the lineage information.
Here, we compute the transition map between neighboring time points.
We simply average transitions across all cl... | 46,447 |
def percentile(seq: t.Iterable[float], percent: float) -> float:
"""
Find the percentile of a list of values.
prometheus-client 0.6.0 doesn't support percentiles, so we use this implementation
Stolen from https://github.com/heaviss/percentiles that was stolen
from http://code.activestate.com/recipes... | 46,448 |
def select_view_by_cursors(**kwargs):
"""
Selects the Text View ( visible selection ) for the given cursors
Keyword Args:
sel (Tuple[XTextRange, XTextRange], XTextRange): selection as tuple of left and right range or as text range.
o_doc (GenericTextDocument, optional): current document (xM... | 46,449 |
def load_types(
directories: List[str],
loads: LoadedFiles = DEFAULT_LOADS,
) -> Dict[str, dict]:
"""Load schema types and optionally register them."""
schema_data: Dict[str, dict] = {}
# load raw data
for directory in directories:
load_dir(directory, schema_data, None, loads)
retu... | 46,450 |
def fit_circle(img, show_rect_or_cut='show'):
"""
fit an ellipse to the contour in the image and find the overlaying square.
Either cut the center square or just plot the resulting square
Code partly taken from here:
https://stackoverflow.com/questions/55621959/opencv-fitting-a-single-circle-to-an-... | 46,451 |
def RunEnvTests():
"""Run several environment tests.
"""
RunTestIf("env", qa_env.TestSshConnection)
RunTestIf("env", qa_env.TestIcmpPing)
RunTestIf("env", qa_env.TestGanetiCommands) | 46,452 |
def install_uuid():
""" Installing UUID package for Testing purpose. """
version = "1.30"
base_path = "/tmp/uuid"
if os.path.exists(path):
run_me_right("%s stop" % base_path)
tar_name = "uuid-%s.tar.gz" % (version)
tar_path = "%s/%s" % (base_path, tar_name)
md5 = "md5=639b310f1fe68... | 46,453 |
def test_mnist_sampler_chain():
"""
Test Mnist sampler chain
"""
logger.info("test_mnist_sampler_chain")
sampler = ds.DistributedSampler(num_shards=1, shard_id=0, shuffle=False, num_samples=3, offset=1)
child_sampler = ds.RandomSampler(replacement=True, num_samples=4)
sampler.add_child(chil... | 46,454 |
def unflatten_dict(
d: Mapping[str, Any],
separator: str = '.',
unflatten_list: bool = False,
sort: bool = False
) -> MutableMapping[str, Any]:
"""
Example:
In []: unflatten_dict({'count.chans.HU_SN': 10})
Out[]: {'count': {'chans': {'HU_SN': 10}}}
In []: unflatten_dict({'a.0.b.f.0': 1, 'a.0.b.f.1': 2, 'a.0.... | 46,455 |
def _xinf_1D(xdot,x0,args=(),xddot=None,xtol=1.49012e-8):
"""Private function for wrapping the solving for x_infinity
for a variable x in 1 dimension"""
try:
if xddot is None:
xinf_val = float(fsolve(xdot,x0,args,xtol=xtol))
else:
xinf_val = float(newton_meth(xdot,x0,... | 46,456 |
def analyze_avg_sgl_num(xl_grp, h5_data_lst):
"""!Analyze the number of singly bound motors or crosslinkers per step
@param xl_grp: TODO
@param h5_data_lst: TODO
@return: TODO
"""
sgl_fil0_num_arr = np.asarray([h5d['analysis/singly_bound_number'][:, 0]
for h5... | 46,457 |
def to_bag_of_words(
doclike: types.DocLike,
*,
by: TokenGroupByType = "lemma_",
weighting: WeightingType = "count",
**kwargs,
) -> Dict[int, int | float] | Dict[str, int | float]:
"""
Transform a ``Doc`` or ``Span`` into a bag-of-words: the set of unique words therein
mapped to their ab... | 46,458 |
def get_trip_info(origin, destination, date):
"""
Provides basic template for response, you can change as many things as you like.
:param origin: from which airport your trip beings
:param destination: where are you flying to
:param date: when
:return:
"""
template = {
"kind": "q... | 46,459 |
def serialise(data, data_type=None):
"""
Serialises the specified data.
The result is a ``bytes`` object. The ``deserialise`` operation turns it
back into a copy of the original object.
:param data: The data that must be serialised.
:param data_type: The type of data that will be provided. If no data type is
pr... | 46,460 |
def localenv(*args, **kwargs):
"""Execute cmd in local environment."""
# Remove empty keys
kwargs = {k: v for k, v in kwargs.items() if v}
template_vars = {
"root_path": ROOT_PATH,
"environment": kwargs.pop("environment", DEFAULT_ENVIRONMENT),
"config_filename": kwargs.pop("con... | 46,461 |
def topopebreptool_RegularizeShells(*args):
"""
* Returns <False> if the shell is valid (the solid is a set of faces connexed by edges with connexity 2). Else, splits faces of the shell; <OldFacesnewFaces> describes (face, splits of face).
:param aSolid:
:type aSolid: TopoDS_Solid &
:param OldSheNewS... | 46,462 |
def _cancel_task_if(
logger: gluetool.log.ContextAdapter,
cancel: threading.Event,
undo: Optional[Callable[[], None]] = None
) -> bool:
"""
Check given cancellation event, and if it's set, call given (optional) undo callback.
Returns ``True`` if task is supposed to be cancelled, ``False`` other... | 46,463 |
def empty_filter(item, *args, **kwargs):
"""
Placeholder function to pass along instead of filters
"""
return True | 46,464 |
def Get_User_Tags(df, json_response, i, github_user):
"""
Calculate the tags for a user.
"""
all_repos_tags = pd.DataFrame(0, columns=df.columns, index=pyjq.all(".[] | .name", json_response))
num_repos = len(pyjq.all(".[] | .name", json_response))
#
new_element = pd.DataFrame(0, np.zeros(... | 46,465 |
def ssize(newsize, cell):
"""
Set the size (maximum cardinality) of a CSPICE cell of any data type.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/ssize_c.html
:param newsize: Size (maximum cardinality) of the cell.
:type newsize: int
:param cell: The cell.
:type cell: spiceypy.ut... | 46,466 |
def env_interactive() -> Optional[bool]:
"""
Check the `GLOBUS_CLI_INTERACTIVE` environment variable for a boolean, and *let*
`strtobool` raise a `ValueError` if it doesn't parse.
"""
explicit_val = os.getenv("GLOBUS_CLI_INTERACTIVE")
if explicit_val is None:
return None
return bool(... | 46,467 |
def extend_data(data, length, offset):
"""Extend data using a length and an offset."""
if length >= offset:
new_data = data[-offset:] * (alignValue(length, offset) // offset)
return data + new_data[:length]
else:
return data + data[-offset:-offset+length] | 46,468 |
def RAND_egd(path): # real signature unknown; restored from __doc__
"""
RAND_egd(path) -> bytes
Queries the entropy gather daemon (EGD) on the socket named by 'path'.
Returns number of bytes read. Raises SSLError if connection to EGD
fails or if it does not provide enough data to seed PRNG.
... | 46,469 |
def get_types_map(types_array: List[Dict[str, Any]]) -> Dict[str, Dict[str, Any]]:
"""Get the type name of a metadata or a functionality."""
return {type_["name"]: type_ for type_ in types_array} | 46,470 |
def update_flavor(request, **kwargs):
"""Update a flavor.
"""
data = request.DATA
flavor_id = data['flavor']['id']
conn = _get_sdk_connection(request)
flavor = conn.load_balancer.update_flavor(
flavor_id,
name=data['flavor'].get('name'),
description=data['flavor'].get('... | 46,471 |
def register_verifier(message_type, handler):
""" Verifies a message is valid before forwarding it,
handling it (should it be different?).
"""
VERIFIER_REGISTER[message_type] = handler | 46,472 |
async def get_all_product_features_from_cluster() -> List[str]:
"""
Returns a list of all product.feature in the cluster.
"""
show_lic_output = await scontrol_show_lic()
PRODUCT_FEATURE = r"LicenseName=(?P<product>[a-zA-Z0-9_]+)[_\-.](?P<feature>\w+)"
RX_PRODUCT_FEATURE = re.compile(PRODUCT_FEA... | 46,473 |
def call_status():
"""
入浴状態を取得
入浴前:0
入浴中:1
入浴後:2
:return:
"""
user_id = "testuser"
result_dict = check_status(user_id)
return jsonify(result_dict) | 46,474 |
def dice_loss(pred, target, smooth=1.):
"""Dice loss
"""
pred = pred.contiguous()
target = target.contiguous()
intersection = (pred * target).sum(dim=2).sum(dim=2)
loss = (1 - ((2. * intersection + smooth) / (pred.sum(dim=2).sum(dim=2) + target.sum(dim=2).sum(dim=2) + smooth)))
return los... | 46,475 |
def _get_scope_contacts_by_object_id(connection, object_id,
object_type, scope_contact_type):
"""Gets scope contacts by object id.
Args:
connection: Database connection.
object_id: An integer value of scope object id.
object_type: A string value of scope object type... | 46,476 |
async def test_bad_posting(aioclient_mock, hass, aiohttp_client):
"""Test that posting to wrong api endpoint fails."""
await async_setup_component(hass, webhook.DOMAIN, {})
await async_setup_component(hass, 'camera', {
'camera': {
'platform': 'push',
'name': 'config_test',
... | 46,477 |
def remove_mentions(text):
"""Remove @-mentions from the text"""
return re.sub('@\w+', '', text) | 46,478 |
def put_thread(req_thread: ReqThreadPut):
"""Put thread for video to DynamoDB"""
input = create_update_item_input(req_thread)
try:
res = client.update_item(**input)
return res
except ClientError as err:
err_message = err.response["Error"]["Message"]
raise HTTPException(... | 46,479 |
def create_app(config_name: str):
"""Application factory
Args:
config_name (str): the application config name to determine which env to run on
Returns:
The Flask application object
"""
app = Flask(__name__)
app.config.from_object(config[config_name])
db.init_app(app)
ma... | 46,480 |
def get_clean_num(num):
"""
Get the closest clean number match to num with bases 1, 2, 5.
Args:
num: the number
Returns:
the closest number
"""
if num == 0: return 0
sign = num > 0 and 1 or -1
exp = get_exp(num)
nums = numpy.array((1, 2, 5, 10))*(10**exp)
return... | 46,481 |
def with_config_error(func):
"""Add config error context."""
@wraps(func)
def wrapper(*args, **kwargs):
with config_key_error():
return func(*args, **kwargs)
return wrapper | 46,482 |
def _flat(l):
"""Flattens a list.
"""
f = []
for x in l:
f += x
return f | 46,483 |
def die(msg):
"""Exit on error"""
sys.exit(msgfmt(msg, prefix="error: ")) | 46,484 |
def axesDict(T_axes):
"""Check connectivity based on Interval Vectors."""
intervalList = [
T_axes[0],
T_axes[1],
T_axes[2],
(12 - T_axes[0]),
(12 - T_axes[1]),
(12 - T_axes[2])]
return intervalList | 46,485 |
def _settings_to_component(
name: str,
settings: configuration.ProjectSettings,
options: amos.Catalog) -> bases.Projectbases.Component:
"""[summary]
Args:
name (str): [description]
settings (configuration.ProjectSettings): [description]
options (amos.Catalog): [description]... | 46,486 |
def iss(data, gamma21, gamma32, KDTree_radius, NMS_radius, max_num=100):
"""
Description: intrinsic shape signatures algorithm based on cuda FRNN and cuda maximum suppression
Args:
data: numpy array of point cloud, shape(num_points, 3)
gamma21:
gamma32:
KDTree_radius: radiusN... | 46,487 |
async def main(request):
"""Handle requests."""
try:
# Get payload
payload = await request.read()
# Get authentication
secret = os.environ.get("GH_SECRET")
token = os.environ.get("GH_AUTH")
bot = os.environ.get("GH_BOT")
event = sansio.Event.from_http(re... | 46,488 |
def mergeConfig(args, testing=False): # pragma: no cover
"""
I take in a namespace created by the ArgumentParser in cmdline.main() and
merge in options from configuration files. The config items only replace
argument items that are set to default value.
Returns: I return a new argparse.Namespace,... | 46,489 |
def login_wechat():
"""
This api logins a user through wechat app.
"""
code = request.json.get('code', None)
wechat_code2session_url = 'https://api.weixin.qq.com/sns/jscode2session'
payload = {
'appid': current_app.config['WECHAT_APPID'],
'secret': current_app.config['WECHAT_APP... | 46,490 |
def set_default():
"""set default"""
check_args(config)
set_seed(config.seed)
context.set_context(
mode=context.GRAPH_MODE,
device_target=config.device_target)
# init distributed
if config.is_distributed:
init('nccl')
config.rank = get_rank()
config.device... | 46,491 |
def _process_dataset(name, directory, all_splits, num_shards, classes):
"""Process a complete data set and save it as a TFRecord.
Args:
name: string, unique identifier specifying the data set.
directory: string, root path to the data set.
all_splits: list of strings, sub-path to the data set.... | 46,492 |
def is_no_entitled(request):
"""Check condition for needing to entitled user."""
no_entitled_list = ["source-status"]
no_auth = any(no_auth_path in request.path for no_auth_path in no_entitled_list)
return no_auth | 46,493 |
def _make_selector_from_key_distribution_options(
options) -> reverb_types.SelectorType:
"""Returns a Selector from its KeyDistributionOptions description."""
one_of = options.WhichOneof('distribution')
if one_of == 'fifo':
return item_selectors.Fifo()
if one_of == 'uniform':
return item_selectors.U... | 46,494 |
def scan_folder(source):
"""
Synchronizes the contents of the sources and destination folder.
"""
# Note: We use listdir i.s.o. walk to we need tighter control over
# iteration to maintain the mapping the the destination
files = listdir(source)
for item in files:
f_source = join(sour... | 46,495 |
def json_numpy_obj_hook(dct):
"""
Decodes a previously encoded numpy ndarray
with proper shape and dtype
from: http://stackoverflow.com/a/27948073/5768001
:param dct: (dict) json encoded ndarray
:return: (ndarray) if input was an encoded ndarray
"""
if isinstance(dct, dict) and '__ndarra... | 46,496 |
def redirect_edge(state: SDFGState,
edge: graph.MultiConnectorEdge[Memlet],
new_src: Optional[nodes.Node] = None,
new_dst: Optional[nodes.Node] = None,
new_src_conn: Optional[str] = None,
new_dst_conn: Optional[str] = None,
... | 46,497 |
def svn_fs_lock(*args):
"""
svn_fs_lock(svn_fs_t fs, char path, char token, char comment, svn_boolean_t is_dav_comment,
apr_time_t expiration_date,
svn_revnum_t current_rev, svn_boolean_t steal_lock,
apr_pool_t pool) -> svn_error_t
"""
return _fs.svn_fs_lock(*args) | 46,498 |
def maybe_double_last(hand):
"""
:param hand: list - cards in hand.
:return: list - hand with Jacks (if present) value doubled.
"""
if hand[-1] == 11:
hand[-1] = 22
return hand | 46,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.