content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def import_code(code, name):
""" code can be any object containing code -- string, file object, or
compiled code object. Returns a new module object initialized
by dynamically importing the given code. If the module has already
been imported - then it is returned and not imported a second t... | 5,331,200 |
def two(data: np.ndarray) -> int:
"""
Use the binary numbers in your diagnostic report to calculate the oxygen generator rating and CO2 scrubber rating,
then multiply them together. What is the life support rating of the submarine? (Be sure to represent your answer in
decimal, not binary.)
"""
... | 5,331,201 |
def test_get_mutable_mark_dirty():
"""
Ensure that accessing a mutable field type does not mark it dirty
if the field has never been set. If the field has been set, ensure
that it is set to dirty.
"""
class MutableTester(XBlock):
"""Test class with mutable fields."""
list_field =... | 5,331,202 |
def get_lr_fit(sess, model, x_train, y_train, x_test, num_steps=100):
"""Fit a multi-class logistic regression classifier.
Args:
x_train: [N, D]. Training data.
y_train: [N]. Training label, integer classes.
x_test: [M, D]. Test data.
Returns:
y_pred: [M]. Integer class prediction of test data.
... | 5,331,203 |
def make_block_trials(ntrials_block):
"""Creates a matrix of pseudo-random balanced trial parameters for a block of trials.
Parameters
----------
ntrials_block : int
Number of trials in the block.
Returns
-------
block : 2d array
Matrix of trial parameters (this is NOT rand... | 5,331,204 |
def jitter(opts, imax, ibad, mesh=None):
"""
JITTER call JIGSAW iteratively; try to improve topology.
"""
if (not isinstance(opts, jigsaw_jig_t)):
raise Exception("Incorrect type: OPTS.")
if (mesh is not None and not
isinstance(mesh, jigsaw_msh_t)):
raise Exception("In... | 5,331,205 |
def view_user(user_id: int):
"""Return the given user's history."""
return render_user(manager.get_user_by_id(user_id)) | 5,331,206 |
def first(c) -> col:
"""
In contrast to pyspark.sql.functions.first this function uses column name as alias
without prefixing it with the aggregation function name.
"""
if isinstance(c, str):
return F.first(c).alias(c)
columnName = c._jc.toString()
return F.first(c).alias(columnName... | 5,331,207 |
def translate(root_list, use_bag_semantics=False):
"""
Translate a list of relational algebra trees into SQL statements.
:param root_list: a list of tree roots
:param use_bag_semantics: flag for using relational algebra bag semantics
:return: a list of SQL statements
"""
translator = (Trans... | 5,331,208 |
def replace_aliases(record):
"""
Replace all aliases associated with this DID / GUID
"""
# we set force=True so that if MIME type of request is not application/JSON,
# get_json will still throw a UserError.
aliases_json = flask.request.get_json(force=True)
try:
jsonschema.validate(al... | 5,331,209 |
def run_with_output(*args, **kwargs):
"""Run the main multiprocessing function while saving stdout and/or stderr."""
# Get variables
target = kwargs.pop('LP_TARGET_FUNC') # Raise Error. Do not use this if a target was not given
out_queue = kwargs.pop('LP_STDOUT_QUEUE', None)
err_queue = kwargs.pop(... | 5,331,210 |
def pos_tag(docs, language=None, tagger_instance=None, doc_meta_key=None):
"""
Apply Part-of-Speech (POS) tagging to list of documents `docs`. Either load a tagger based on supplied `language`
or use the tagger instance `tagger` which must have a method ``tag()``. A tagger can be loaded via
:func:`~tmto... | 5,331,211 |
def NOBE_GA_SH(G,K,topk):
"""detect SH spanners via NOBE-GA[1].
Parameters
----------
G : easygraph.Graph
An unweighted and undirected graph.
K : int
Embedding dimension k
topk : int
top - k structural hole spanners
Returns
-------
SHS : list
The t... | 5,331,212 |
def calculate_correct_answers(model, dataloader, epoch):
"""Calculate correct over total answers"""
forward_backward_func = get_forward_backward_func()
for m in model:
m.eval()
def loss_func(labels, output_tensor):
logits = output_tensor
loss_dict = {}
# Compute the co... | 5,331,213 |
def set_template_parameters(
template: Template, template_metadata: TemplateMetadata, input_parameters: Dict[str, str], interactive=False
):
"""Set and verify template parameters' values in the template_metadata."""
if interactive and not communication.has_prompt():
raise errors.ParameterError("Cann... | 5,331,214 |
def testRead():
"""
Tests exception raising for invalid property indices and names
on the read side.
"""
a = alembic.Abc.IArchive("testPropException.abc")
t = a.getTop()
props = t.children[0].getProperties()
p = props.getProperty("myprop")
assert p.getName() == "myprop"
try:
... | 5,331,215 |
def calc_roll_pitch_yaw(yag, zag, yag_obs, zag_obs, sigma=None):
"""Calc S/C delta roll, pitch, and yaw for observed star positions relative to reference.
This function computes a S/C delta roll/pitch/yaw that transforms the
reference star positions yag/zag into the observed positions
yag_obs/zag_obs. ... | 5,331,216 |
def make_query_abs(db, table, start_dt, end_dt, dscfg, mode, no_part=False, cols=None):
"""절대 시간으로 질의를 만듦.
Args:
db (str): DB명
table (str): table명
start_dt (date): 시작일
end_dt (date): 종료일
dscfg (ConfigParser): 데이터 스크립트 설정
mode: 쿼리 모드 ('count' - 행 수 구하기, 'preview' ... | 5,331,217 |
def tgl_forward_backward(
emp_cov,
alpha=0.01,
beta=1.0,
max_iter=100,
n_samples=None,
verbose=False,
tol=1e-4,
delta=1e-4,
gamma=1.0,
lamda=1.0,
eps=0.5,
debug=False,
return_history=False,
return_n_iter=True,
choose="gamma",
lamda_criterion="b",
time_... | 5,331,218 |
def validate_task_rel_proposal(header, propose, rel_address, state):
"""Validates that the User exists, the Task exists, and the User is not
in the Task's relationship specified by rel_address.
Args:
header (TransactionHeader): The transaction header.
propose (ProposeAddTask_____): The Task... | 5,331,219 |
def error_handler(update: Update, context: CallbackContext):
"""Log the error and send a telegram message to notify the developer."""
# Log the error before we do anything else, so we can see it even if something breaks.
logger.error(msg="Exception while handling an update:", exc_info=context.error)
# ... | 5,331,220 |
def all_cells_run(event_str: str, expected_count: int) -> bool:
"""Wait for an event signalling all cells have run.
`execution_count` should equal number of nonempty cells.
"""
try:
event = json.loads(event_str)
msg_type = event["msg_type"]
content = event["content"]
exe... | 5,331,221 |
def to_forecasting(
timeseries: np.ndarray,
forecast: int = 1,
axis: Union[int, float] = 0,
test_size: int = None,
):
"""Split a timeseries for forecasting tasks.
Transform a timeseries :math:`X` into a series of
input values :math:`X_t` and a series of output values
:math:`X_{t+\\mathr... | 5,331,222 |
def build_task_environment() -> dm_env.Environment:
"""Returns the environment."""
# We first build the base task that contains the simulation model as well
# as all the initialization logic, the sensors and the effectors.
task, components = task_builder.build_task()
del components
env_builder = subtask_e... | 5,331,223 |
def searchInsert(nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
try:
return nums.index(target)
except ValueError:
nums.append(target)
nums.sort()
return nums.index(target) | 5,331,224 |
def drawButton():
"""绘制按钮"""
pygame.draw.rect(DISPLAYSURF, WHITE, RECT1)
pygame.draw.rect(DISPLAYSURF, WHITE, RECT2)
pygame.draw.rect(DISPLAYSURF, WHITE, RECT3)
pygame.draw.rect(DISPLAYSURF, WHITE, RECT4) | 5,331,225 |
def initialize(slave_address=DEFAULT_SLAVE_ADDRESS, i2c_bus=DEFAULT_I2C_BUS):
"""
:param slave_address: 8-bit I2C slave address. For DPP2607, should be 0x34 or 0x36.
:param i2c_bus: I2C bus number, for Linux only.
"""
global _i2c, _slave_address
if sys.platform == 'win32':
import devasy... | 5,331,226 |
def resource(author, tag) -> Resource:
"""Resource fixture"""
return Resource(
name="Sentiment Algorithm",
url="https://raw.githubusercontent.com/MarcSkovMadsen/awesome-streamlit/master/src/pages/gallery/contributions/marc_skov_madsen/sentiment_analyzer/sentiment_analyzer.py",
is_awesom... | 5,331,227 |
def tick(curtime=''):
""" Acts as a clock, changing the label as time goes up """
newtime = time.strftime('%H:%M:%S')
if newtime != curtime:
curtime = newtime
clockLabel.config(text=curtime)
clockLabel.after(200, tick, curtime) | 5,331,228 |
def FilterBlueScreen():
"""
Does something
@rtype:
""" | 5,331,229 |
def del_list(request, list_id: int, list_slug: str) -> HttpResponse:
"""Delete an entire list. Danger Will Robinson! Only staff members should be allowed to access this view.
"""
task_list = get_object_or_404(TaskList, slug=list_slug)
# Ensure user has permission to delete list. Admins can delete all l... | 5,331,230 |
def new_req(to_id, from_who): # создание нового запроса
"""
:param to_id: to user id
:param from_who: from user id
:return: создание нового запроса
"""
global connect
global cursor
cursor.execute("INSERT INTO Requests VALUES ({0},'{1}',0)".format(to_id, from_who))
connect.c... | 5,331,231 |
def model_softmax(input_data=None,
output_targets=None,
num_words=3000,
num_units=128,
num_layers=2,
num_tags=5,
batchsize=1,
train=True
):
"""
:param input_data:
... | 5,331,232 |
def get_metric_monthly_rating(metric: AnyStr,
tenant_id: AnyStr,
namespaces: List[AnyStr]) -> List[Dict]:
"""
Get the monthly price for a metric.
:metric (AnyStr) A string representing the metric.
:tenant_id (AnyStr) A string representing the ... | 5,331,233 |
def masked_softmax_cross_entropy(preds, labels, mask):
"""Softmax cross-entropy loss with masking."""
loss = tf.nn.softmax_cross_entropy_with_logits(logits=preds, labels=labels)
mask = tf.cast(mask, dtype=tf.float32)
mask /= tf.reduce_mean(mask)
loss *= tf.transpose(mask)
return tf.reduce_... | 5,331,234 |
def u0(x):
"""
Initial Condition
Parameters
----------
x : array or float;
Real space
Returns
-------
array or float : Initial condition evaluated in the real space
"""
return sin(pi * x) | 5,331,235 |
def deploy(upgrade=False):
"""
The master deploy script.
Examples:
fab -H ubuntu@54.244.224.30 deploy
fab -H root@104.131.132.143 deploy
"""
# Ubuntu setup
if upgrade:
update_ubuntu()
setup_ubuntu()
upgrade_pip()
# Fun starts here
clone('https://github.co... | 5,331,236 |
def jsonify(value):
"""
Convert a value into a JSON string that can be used for JSONB queries in
Postgres.
If a string happens to contain the character U+0000, which cannot be
represented in a PostgreSQL value, remove the escape sequence representing
that character, effectively stripping out th... | 5,331,237 |
def add_generated_report_header(report_header):
"""
Upload report history and return the id of the header that was generated
on the server.
Parameters
----------
report_header:
Required Parmeters:
A dictionary of parameters that will be used to describe the report that cons... | 5,331,238 |
def generate_dataset(type = 'nlp', test=1):
"""
Generates a dataset for the model.
"""
if type == 'nlp':
return generate_nlp_dataset(test=test)
elif type == 'non-nlp':
return generate_non_nlp_dataset() | 5,331,239 |
def get_pipes_output(database: Optional[pulumi.Input[str]] = None,
schema: Optional[pulumi.Input[str]] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetPipesResult]:
"""
## Example Usage
```python
import pulumi
import pulumi_snowflak... | 5,331,240 |
def plot_tree_on_terminal(G):
"""
Plots the random tree graph
Parameters
----------
G: nx.Graph
The random tree graph
"""
print(nx.forest_str(G)) | 5,331,241 |
def search(isamAppliance, comment, check_mode=False, force=False):
"""
Retrieve snapshots with given comment contained
"""
ret_obj = isamAppliance.create_return_object()
ret_obj_all = get(isamAppliance)
for obj in ret_obj_all['data']:
if comment in obj['comment']:
logger.deb... | 5,331,242 |
def getAsciiFileExtension(proxyType):
"""
The file extension used for ASCII (non-compiled) proxy source files
for the proxies of specified type.
"""
return '.proxy' if proxyType == 'Proxymeshes' else '.mhclo' | 5,331,243 |
def dist(s1, s2):
"""Given two strings, return the Hamming distance (int)"""
return abs(len(s1) - len(s2)) + sum(
map(lambda p: 0 if p[0] == p[1] else 1, zip(s1.lower(), s2.lower()))) | 5,331,244 |
def test_config():
"""Test create_app for testing pourposes."""
assert not create_app().testing
db_fd, db_path = tempfile.mkstemp()
app = create_app(test=True, db_path=db_path)
assert app.testing
os.close(db_fd)
os.unlink(db_path) | 5,331,245 |
def read_bunch(path):
""" read bunch.
:param path:
:return:
"""
file = open(path, 'rb')
bunch = pickle.load(file)
file.close()
return bunch | 5,331,246 |
def cluster_analysis(L, cluster_alg, args, kwds):
"""Given an input graph (G), and whether the graph
Laplacian is to be normalized (True) or not (False) runs spectral clustering
as implemented in scikit-learn (empirically found to be less effective)
Returns Partitions (list of sets of ints)
"... | 5,331,247 |
def col_index_list(info, key, value):
"""Given a list of dicts 'info', return a list of indices corresponding to
columns in which info[key] == value. Use to build lists of default columns,
non-exportable columns, etc."""
index_list = list()
if info != None:
for i in range(0, len(info)):
... | 5,331,248 |
def sparse_softmax_cross_entropy(logits, labels, weights=1.0, scope=None):
"""Cross-entropy loss using `tf.nn.sparse_softmax_cross_entropy_with_logits`.
`weights` acts as a coefficient for the loss. If a scalar is provided,
then the loss is simply scaled by the given value. If `weights` is a
tensor of size [`b... | 5,331,249 |
def curl(url, headers={}, data=None, verbose=0):
"""Use curl to make a request; return the entire reply as a string."""
import os, tempfile
fd, tempname = tempfile.mkstemp(prefix='scrape')
command = 'curl --include --insecure --silent --max-redirs 0'
if data:
if not isinstance(data, str): # ... | 5,331,250 |
def retr_radihill(smax, masscomp, massstar):
"""
Return the Hill radius of a companion
Arguments
peri: orbital period
rsma: the sum of radii of the two bodies divided by the semi-major axis
cosi: cosine of the inclination
"""
radihill = smax * (masscomp / 3. / massstar)*... | 5,331,251 |
def load_feature_file(in_feature):
"""Load the feature file into a pandas dataframe."""
f = pd.read_csv(feature_path + in_feature, index_col=0)
return f | 5,331,252 |
async def run_command(client, config, log=print):
"""Begin the action specified by command line arguments and config"""
# Always print current height
initial_height, speed = struct.unpack(
"<Hh", await client.read_gatt_char(UUID_HEIGHT)
)
log("Height: {:4.0f}mm".format(rawToMM(initial_height... | 5,331,253 |
def test_get_delivery_pricing(get_order, jwt_token, api_url):
"""
Test getDeliveryPricing
"""
order = get_order()
headers = {"Authorization": jwt_token}
query = """
query($input: DeliveryPricingInput!) {
getDeliveryPricing(input: $input) {
pricing
}
}
"""
v... | 5,331,254 |
def add_observation_noise(obs, noises, stds, only_object_noise=False):
"""Add noise to observations
`noises`: Standard normal noise of same shape as `obs`
`stds`: Standard deviation per dimension of `obs` to scale noise with
"""
assert obs.shape == noises.shape
idxs_object_pos = SENSOR_INFO_PNP... | 5,331,255 |
def test_domains(file_path="../../domains.json"):
"""
Reads a list of domains and see if they respond
"""
# Read file
with open(file_path, 'r') as domain_file:
domains_json = domain_file.read()
# Parse file
domains = json.loads(domains_json)
results = {}
for domain in dom... | 5,331,256 |
async def state(ip):
"""Get the current state of a given bulb."""
click.echo("Get the state from %s" % ip)
bulb = wizlight(ip)
state = await bulb.updateState()
click.echo(state.__dict__["pilotResult"]) | 5,331,257 |
def mix_dirichlet_noise(distribution: Dict[Any, float],
epsilon: float,
alpha: float) -> Dict[Any, float]:
"""Combine values in dictionary with Dirichlet noise. Samples
dirichlet_noise according to dirichlet_alpha in each component. Then
updates the value v fo... | 5,331,258 |
def get_video_ID(video_url: str) -> str:
"""Returns the video ID of a youtube video from a URL"""
try:
return parse_qs(urlparse(video_url).query)['v'][0]
except KeyError:
# The 'v' key isn't there, this could be a youtu.be link
return video_url.split("/")[3][:11] | 5,331,259 |
def profiling_csv(stage, phases, durations):
"""
Dumps the profiling information into a CSV format.
For example, with
stage: `x`
phases: ['a', 'b', 'c']
durations: [1.42, 2.0, 3.4445]
The output will be:
```
x,a,1.42
x,b,2.0
x,c,3.444
```
"""
as... | 5,331,260 |
def int_not_in_range(bounds, inclusive=False):
"""Creates property that must be an int outside bounds[0] and bounds[1].
Parameters:
bounds: Subscriptable with len()==2, where bounds[0] is the lower
bound and bounds[1] is the upper bound.
Requires bounds[1] > bounds[0].
... | 5,331,261 |
def plot_concordance_pr(
pr_df: pd.DataFrame,
snv: bool,
colors: Dict[str, str] = None,
size_prop: str = None,
bins_to_label: List[int] = None,
) -> Column:
"""
Generates plots showing Precision/Recall curves for truth samples:
Two tabs:
- One displaying the PR curve with ranking com... | 5,331,262 |
def typehint_metavar(typehint):
"""Generates a metavar for some types."""
metavar = None
if typehint == bool:
metavar = '{true,false}'
elif is_optional(typehint, bool):
metavar = '{true,false,null}'
elif _issubclass(typehint, Enum):
enum = typehint
metavar = '{'+','.j... | 5,331,263 |
def generate_signed_url(filename):
"""
Generate a signed url to access publicly
"""
found_blob = find(filename)
expiration = datetime.now() + timedelta(hours=1)
return found_blob.generate_signed_url(expiration) | 5,331,264 |
def delete_old_layer_versions(client, table, region, package, prefix):
"""
Loops through all layer versions found in DynamoDB and deletes layer version if it's <maximum_days_older> than
latest layer version.
The latest layer version is always kept
Because lambda functions are created at a maximum... | 5,331,265 |
def _run_simulation(sim_desc):
"""Since _run_simulation() is always run in a separate process, its input
and output params must be pickle-friendly. Keep that in mind when
making changes.
This is what each worker executes.
Given a SimulationDescription object, calls the sequence & binning
code,... | 5,331,266 |
def check_cn_en_match(path="./paddle", diff_file="en_cn_files_diff"):
"""
skip
"""
osp_join = os.path.join
osp_exists = os.path.exists
with open(diff_file, 'w') as fo:
tmpl = "{}\t{}\n"
fo.write(tmpl.format("exist", "not_exits"))
for root, dirs, files in os.walk(path):
... | 5,331,267 |
def _sample_fq_pair(
file1: str,
file2: str,
fraction: float,
output1: str,
output2: str):
"""
Randomly subsample the input fastq file pair
Args:
file1: path-like
The input fastq file 1
file2: path-like
The input... | 5,331,268 |
def test_array_and_stringlike_roundtrip(strtype):
"""
Test that string representations of long-double roundtrip both
for array casting and scalar coercion, see also gh-15608.
"""
o = 1 + LD_INFO.eps
if strtype in (np.bytes_, bytes):
o_str = strtype(repr(o).encode("ascii"))
else:
... | 5,331,269 |
def view_filestorage_file(self, request):
""" Renders the given filestorage file in the browser. """
return getattr(request.app, self.storage).getsyspath(self.path) | 5,331,270 |
def enum_choice_list(data):
""" Creates the argparse choices and type kwargs for a supplied enum type or list of strings """
# transform enum types, otherwise assume list of string choices
if not data:
return {}
try:
choices = [x.value for x in data]
except AttributeError:
c... | 5,331,271 |
def chartset(request):
""" Conjunto de caracteres que determian la pagina
request: respuesta de la url"""
print "--------------- Obteniendo charset -------------------"
try:
charset = request.encoding
except AttributeError as error_atributo:
charset = "NA"
print "charset: " +... | 5,331,272 |
def generate_UUID():
"""
Generate a UUID and return it
"""
return str(uuid.uuid4()) | 5,331,273 |
def streaming_recall_at_thresholds(predictions, labels, thresholds,
ignore_mask=None, metrics_collections=None,
updates_collections=None, name=None):
"""Computes various recall values for different `thresholds` on `predictions`.
The `streaming_r... | 5,331,274 |
def cmd_flush(bot, trigger):
"""
Resets the cached RatNames. Helps with Bugged rat names on !assign
aliases: flush, resetnames, rn, flushnames, fn
"""
flushNames()
bot.say('Cached names flushed!') | 5,331,275 |
def fib(n):
"""Returns the nth Fibonacci number."""
if n == 0:
return 1
elif n == 1:
return 1
else:
return fib(n - 1) + fib(n - 2) | 5,331,276 |
def fuzz_cachew_impl():
"""
Insert random sleeps in cachew_impl to increase likelihood of concurrency issues
"""
import patchy # type: ignore[import]
from .. import cachew_wrapper
patch = '''\
@@ -740,6 +740,11 @@
logger.debug('old hash: %s', prev_hash)
+ from random i... | 5,331,277 |
def CheckStaleSettings():
"""Check various things to make sure they don't get stale."""
die = False
for test in SPECIAL_TESTS:
if not os.path.exists(test):
die = True
logging.error('SPECIAL_TESTS is stale: delete old %s', test)
for test in SLOW_TESTS:
if not os.path.exists(test):
die... | 5,331,278 |
def test_remove_label_raises_error_if_label_not_in_matcher(
matcher: RegexMatcher,
) -> None:
"""It raises a ValueError if trying to remove a label not present."""
with pytest.raises(ValueError):
matcher.remove("TEST") | 5,331,279 |
def load_saved_users(args) -> list:
"""
:param args:
:return: list
"""
data_frame = pd.read_csv(os.path.join(args.data_dir,
args.users_tweets_dir,
args.users_file),
header=None)
retu... | 5,331,280 |
def remove_artifacts_from_biom_table(table_filename,
fasta_filename,
ref_fp,
biom_table_dir,
ref_db_fp,
threads=1,
... | 5,331,281 |
def template_review(context, mapping):
""":phabreview: Object describing the review for this changeset.
Has attributes `url` and `id`.
"""
ctx = context.resource(mapping, b'ctx')
m = _differentialrevisiondescre.search(ctx.description())
if m:
return templateutil.hybriddict({
... | 5,331,282 |
def addRandomEdges(graph: nx.Graph, nEdges: int) -> tuple:
""" Adds random edges to a given graph """
nodes = list(graph.nodes)
n = len(nodes)
edges = []
for i in range(nEdges):
newEdge = False
while not newEdge:
i_u, i_v = np.random.randint(0, n-1), np.random.randint(0, ... | 5,331,283 |
def get_s3_buckets_for_account(account, region='us-east-1'):
""" Get S3 buckets for a specific account.
:param account: AWS account
:param region: AWS region
"""
session = boto3.session.Session() # create session for Thread Safety
assume = rolesession.assume_crossact_audit_role(
session... | 5,331,284 |
def save_greens_hetero_links_plus_one(links, unwrap=0, Kprops_bareWLC=None):
"""Each link in links is the smallest linker length in the heterogenous chain.
Assumes each chain has random sampling of link or (link + 1)bp."""
Klin = np.linspace(0, 10**5, 20000)
Klog = np.logspace(-3, 5, 10000)
Kvals = ... | 5,331,285 |
def test_structuring_enums(converter, choice, enum):
# type: (Converter, Any, Any) -> None
"""Test structuring enums by their values."""
val = choice(list(enum))
assert converter.structure(val.value, enum) == val | 5,331,286 |
def test_nfc_p2p_static_handover_join_tagdev_client(dev):
"""NFC static handover to join a P2P group (NFC Tag device is the P2P Client)"""
set_ip_addr_info(dev[0])
logger.info("Start autonomous GO")
dev[0].p2p_start_go()
dev[1].request("SET ignore_old_scan_res 1")
dev[2].request("SET ignore_old... | 5,331,287 |
def create_uid_email(username=None, hostname=None):
"""Create an email address suitable for a UID on a GnuPG key.
:param str username: The username portion of an email address. If None,
defaults to the username of the running Python
process.
:param str ho... | 5,331,288 |
def get_users():
""" Alle Benutzer aus der Datenbank laden. """
session = get_cassandra_session()
future = session.execute_async("SELECT user_id, username, email FROM users")
try:
rows = future.result()
except Exception:
log.exeception()
users = []
for row in rows:
... | 5,331,289 |
def fastcorrelate(
input1, input2, usefft=True, zeropadding=0, weighting="None", displayplots=False, debug=False,
):
"""Perform a fast correlation between two arrays.
Parameters
----------
input1
input2
usefft
zeropadding
weighting
displayplots
debug
Returns
-------... | 5,331,290 |
def test_bottom_up_coordinate_grabbing(qtbot, p1, p2):
"""
Test coordinate grabbing when grabbing from the 'bottom' of the screen to
the 'top' of the screen.
:param QtBot qtbot:
:return: None
"""
co_widget = CoordinateWidget()
qtbot.addWidget(co_widget)
qtbot.mouseClick(co_widget, Q... | 5,331,291 |
def vgconv(xinput,yinput,fwhm, ppr=None):
"""convolution with a Gaussian in log lambda scale
for a constant resolving power
Parameters
----------
xinput: numpy float array
wavelengths
yinput: numpy array of floats
fluxes
fwhm: float
FWHM of the Gaussian (km/s)
ppr: float, optional
... | 5,331,292 |
def attach_component_to_entity(entity_id, component_name):
# type: (azlmbr.entity.EntityId, str) -> azlmbr.entity.EntityComponentIdPair
"""
Adds the component if not added already.
:param entity_id: EntityId of the entity to attach the component to
:param component_name: name of the component
:r... | 5,331,293 |
def get_raw_samples(sampling_strategy: sample_entry.Strategy, step: int) -> np.ndarray:
"""
Collects raw samples from database associated with sampling strategy. If the raw samples do not exists in
the database new ones will be created by calling the Sobol function
"""
sampling_strategy.reload()
... | 5,331,294 |
def make_hdf(
idir: str,
ofile: str
) -> None:
"""Process a directory of NetCDF RouteLink files to their CSV equivalents.
Parameters
----------
idir: str
Input directory containing Routelink files in CSV format.
ofile: str
Output HDF5 file to store pandas.DataFrame
... | 5,331,295 |
def mix_to_dat(probspec,isStringIO=True):
"""
Reads a YAML mix file and generates all of the GMPL dat components associated with
the mix inputs.
Inputs:
ttspec - the tour type spec object created from the mix file
param_name - string name of paramter in GMPL file
non_shiftlen_pa... | 5,331,296 |
def clear_path(path: Path):
""" Clears folder, including deleting sub folders """
for filename in os.listdir(path):
file_path = path.joinpath(filename)
try:
if os.path.isfile(file_path) or os.path.islink(file_path):
os.unlink(file_path)
elif os.path.isdir... | 5,331,297 |
def taskAcq(timestamp,img):
"""
Task the workers in acquisition mode by splitting the camera image into
segments and dealing them out to the workers
TODO: Check for any busy and skip tasking
"""
global workerLastTasked,outstandingRequests
n = 0
# Keep a place for the result... | 5,331,298 |
def get_setting(setting_name: str, default: Any=None) -> Any:
"""
Convenience wrapper to get the value of a setting.
"""
configuration = get_configuration()
if not configuration: # pragma: no cover
raise Exception('get_setting() called before configuration was initialised')
return confi... | 5,331,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.