content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def generateWorld2():
"""
Generates world with collidable walls and grass paths\n
Types:\n
Grass -> 0\n
Wall -> 1
"""
walls = 0
grass = 0
#possibility = [None, 0, 1, None, None]
for i in range(0, worldSize):
for j in range(0, worldSize):
worldmap[i][j]["TYPE"... | 52,800 |
def pad_shift(x, shift, padv=0.0):
"""Shift 3D tensor forwards in time with padding."""
if shift > 0:
padding = torch.ones(x.size(0), shift, x.size(2)).to(x.device) * padv
return torch.cat((padding, x[:, :-shift, :]), dim=1)
elif shift < 0:
padding = torch.ones(x.size(0), -shift, x.s... | 52,801 |
async def async_million_state_changed_helper(hass):
"""Run a million events through state changed helper."""
count = 0
entity_id = 'light.kitchen'
event = asyncio.Event(loop=hass.loop)
@core.callback
def listener(*args):
"""Handle event."""
nonlocal count
count += 1
... | 52,802 |
def add_dim(*, opt=False, shapes=None, typ=None, use_var=False):
"""Construct a new dimension type based on the list of 'shapes' that
are present in a dimension.
"""
if use_var:
offsets = [0] + list(accumulate(shapes))
return "%svar(offsets=%s) * %s" % ('?' if opt else '', offsets, ty... | 52,803 |
def _allocate_returned_states(model, inputs, return_states=None):
"""Create empty placeholders for model outputs."""
seq_len = inputs[list(inputs.keys())[0]].shape[0]
vulgar_names = {"reservoir": model.reservoir, "readout": model.readout}
# pre-allocate states
if return_states == "all":
sta... | 52,804 |
def test_sumologic_query_export(sumologic_drv, tmpdir, ext):
"""Check queries with different parameters."""
exp_file = f"sumologic_test.{ext}"
f_path = tmpdir.join(exp_file)
params = {
"exporting": True,
"export_path": str(f_path),
"verbosity": 5,
**_DEF_DATE_PARAMS,
... | 52,805 |
def connect_slider_released_abstract(scene):
"""Be an abstract slider released callback function."""
scene.edit.add_undo_item(scene) | 52,806 |
def from_obographs(
jsondoc: Dict, curie_map: Dict[str, str], meta: Dict[str, str] = None
) -> MappingSetDataFrame:
"""
Converts a obographs json object to an SSSOM data frame
Args:
jsondoc: The JSON object representing the ontology in obographs format
curie_map: The curie map to be... | 52,807 |
def nll_loss_multimodes(pred: List[torch.Tensor], data: torch.Tensor, mask: torch.Tensor, modes_pred: torch.Tensor, noise: Optional[float]=0.0 ) -> float:
"""NLL loss multimodes for training.
Args:
pred is a list (with N modes) of predictions
data is ground truth
noise is optional
"""
modes = le... | 52,808 |
def pmps_to_mpo(pmps):
"""Convert a local purification MPS to a mixed state MPO.
A mixed state on n sites is represented in local purification MPS
form by a MPA with n sites and two physical legs per site. The
first physical leg is a 'system' site, while the second physical
leg is an 'ancilla' site... | 52,809 |
async def test_get_triggers_for_invalid_device_id(hass, caplog):
"""Test error raised for invalid shelly device_id."""
await async_setup_component(hass, "persistent_notification", {})
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
... | 52,810 |
def pynautobot_api():
"""Factory to create pynautobot api instance."""
return Api(url="https://mocknautobot.example.com", token="1234567890abcdefg") | 52,811 |
def actionAngle_physical_input(method):
"""Decorator to convert inputs to actionAngle functions from physical
to internal coordinates"""
@wraps(method)
def wrapper(*args,**kwargs):
if len(args) < 3: # orbit input
return method(*args,**kwargs)
ro= kwargs.get('ro',None)
... | 52,812 |
def import_dicom_directory(parent = None, dtype = numpy.single, recursive=False,
load_all_images=False):
""" Import an image from a directory containing DICOM files
parent : parent wx Window for dialogs
dtype : type to cast images to, or None to preserve original ... | 52,813 |
async def copypasta(cp_e):
""" Copypasta the famous meme """
textx = await cp_e.get_reply_message()
message = cp_e.pattern_match.group(1)
if message:
pass
elif textx:
message = textx.text
else:
await cp_e.edit("`😂🅱️IvE👐sOME👅text👅for✌️Me👌tO👐MAkE👀iT💞funNy!💦`")
... | 52,814 |
def super_reduced_string(s):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/reduced-string/problem
Steve has a string of lowercase characters in range ascii[‘a’..’z’]. He wants to reduce the string to its shortest
length by doing a series of operations. In each operation he selects a pair of ... | 52,815 |
def parsefile(settingfile):
"""Parse the input settingfile"""
def func_remove_comments(string):
if string.find('#') != -1:
string = string[:string.find('#')]
return string.strip()
if not os.path.isfile(settingfile):
print('not a file: {:}'.format(settingfile))
... | 52,816 |
def is_in_notebook():
"""Determines if current code is executed from an ipython notebook.
If is_in_notebook() is True, then is_in_ipython() must also be True.
"""
is_in_notebook = False
if is_in_ipython():
# The import and usage must be valid under the execution path.
from IPython import get_ipython
... | 52,817 |
async def test_real_assign_double(dut):
"""
Assign a random floating point value, read it back from the DUT and check
it matches what we assigned
"""
val = random.uniform(-1e307, 1e307)
log = logging.getLogger("cocotb.test")
timer_shortest = Timer(1, "step")
await timer_shortest
log.... | 52,818 |
def xor_hex_strings(str1, str2):
"""
Return xor of two hex strings.
An XOR of two pieces of data will be as random as the input with the most randomness.
We can thus combine two entropy sources in this way as a safeguard against one source being
compromised in some way.
For details, see http://c... | 52,819 |
def CreateIonDataFromInput(ionInputList):
"""
input: ionInputList <list>(string, string, string, string): list of ions to specify and their properties
summary: takes values in each entry of the ionInputList and makes a IonDataDict
output: dictionary<string, Ionic>: dict of Ionic class wich contains info... | 52,820 |
def batch_img(data, vocab):
"""Pad and batch a sequence of images."""
c = data[0].size(0)
h = max([t.size(1) for t in data])
w = max([t.size(2) for t in data])
imgs = torch.zeros(len(data), c, h, w).fill_(1)
for i, img in enumerate(data):
imgs[i, :, 0:img.size(1), 0:img.size(2)] = img
... | 52,821 |
def _build_neural_network_formulation(block, network_structure, layer_constraints, activation_constraints):
"""
Adds the neural network formulation to the given Pyomo block.
Parameters
----------
block : Block
the Pyomo block
network_structure : NetworkDefinition
the neural netw... | 52,822 |
def test_ds2_base_method():
"""Test DS2 code generation for a simple DS2 method."""
from sasctl.utils.pymas.ds2 import DS2BaseMethod, DS2Variable
# Generate a empty method
target = """
method testmethod(
double a,
double b,
in_out double c,
in_out double d
);
end;
"""
method = ... | 52,823 |
def draw_window_one(window_one):
"""
Draws the left window of the house.
:param window_one: a Turtle object
:return: None
"""
window_one.penup()
window_one.setpos(-75, -75)
window_one.pendown()
window_one.color("teal")
window_one.begin_fill()
for shape in range(4):
w... | 52,824 |
def Add(path, value, ttl_seconds=DEFAULT_TTL_SECONDS):
"""Atomically adds an entry to memcache only if it does not already exist.
Args:
path: A list of items (see ToCacheKey).
value: The value to store in the cache.
ttl_seconds: An integer number of seconds to keep the value in the cache.
Returns:
... | 52,825 |
def node(helper):
"""
Report any storage capacity and useage inconsistencies between the
storage node and the API
"""
# Get a list of active LVM Volumes
lvs = [lv for lv in helper.volumes._scan_volumes()
if lv['origin'] == '']
# Get our node id
node_id = request(helper, 'node... | 52,826 |
def rotate_tour(tour, start=0):
"""
Rotate a tour so that it starts at the given ``start`` index. This is
equivalent to rotate the input list to the left.
Parameters
----------
tour: list
The input tour
start: int, optional (default=0)
New start index for the tour
Returns
-------
rotated: ... | 52,827 |
def get_mesh(X, h=0.02, padding=0.5):
"""Build a regular meshgrid using the range of the features in X
"""
x_min, x_max = X[:, 0].min() - padding, X[:, 0].max() + padding
y_min, y_max = X[:, 1].min() - padding, X[:, 1].max() + padding
xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min,... | 52,828 |
def setting(key, default=None, domain=None):
"""
Settings helper based on saltstack's query
Allows a simple way to query settings from YAML
using the style `path:to:key` to represent
path:
to:
key: value
"""
rtn = settings.PROMGEN
lookup = key.split(":")
if domain:
... | 52,829 |
def add_retryable_error_to_sentry_context(event):
"""Add information about a retryable error to the Sentry context.
If a request raises a retryable error then, if we're not already on this
request's last retry attempt, pyramid_retry calls this IBeforeRetry
subscriber function before it retries the requ... | 52,830 |
def test_eap_proto_ikev2_errors_server(dev, apdev):
"""EAP-IKEV2 local error cases on server"""
check_eap_capa(dev[0], "IKEV2")
params = int_eap_server_params()
params['erp_domain'] = 'example.com'
params['eap_server_erp'] = '1'
hapd = hostapd.add_ap(apdev[0], params)
dev[0].scan_for_bss(hap... | 52,831 |
def literal_schema(literal, theories, default_theory=None,
theory_assertion=None):
"""Return the schema that applies to LITERAL or None.
:param: LITERAL is a Literal for which we want the schema
:param: THEORIES is a dictionary mapping the name of the theory
to the theory obje... | 52,832 |
def green(inputs, value=255, **kwargs):
"""Generate pure green channel"""
x = np.zeros_like(inputs)
x[..., 1] = value
return x | 52,833 |
def solve_kernel(data: torch.Tensor, kernel: Kernel, koopman: bool = True):
"""Pseudoinverse solution for Koopman & Perron-Frobenius operators over RKHS
Args:
data: simulation data (see `prep_snapshots`)
kernel: positive-definite kernel.
koopman: if True, Koopman operator, else Perron-Frobenius operator.
Re... | 52,834 |
def cadindateDetailsofEvent(request):
"""
Returns candidate details
:param request:
:return: boolean
"""
try:
if request.method=='GET':
id=request.GET.copy()
if 'id' in id :
eventRegistrationId = id['id']
if EventRegistration.object... | 52,835 |
def no_space(original_str, keyslist, replace_str):
"""
:param original_str: A string found in the keyslist
:param keyslist: A list of keys found in the each of the two knowledge
graph dictionaries (nodes and edges)
:param replace_str: A string to replace the original_str in the keysl... | 52,836 |
def test_cl_fix():
"""Test fix for ``cl``."""
assert Cl is ClFixHybridPressureCoord | 52,837 |
def generate(proid, name, client=None):
"""Generates a credential spec file for the given GMSA proid and returns
the path to the file.
"""
credential_specs_path = _get_path(client)
dc_name = win32security.DsGetDcName()
account_name = win32security.LookupAccountName(None, dc_name['DomainName'])
... | 52,838 |
def download_test_data():
"""
Download and extract test data and store to the user's local data directory.
"""
filename = os.path.join(app_dirs.user_data_dir, "test_data.tar.gz")
if not os.path.exists(app_dirs.user_data_dir):
os.makedirs(app_dirs.user_data_dir)
# Download data
tes... | 52,839 |
def scipy_expm_solver(
generator: Callable,
t_span: Array,
y0: Array,
max_dt: float,
t_eval: Optional[Union[Tuple, List, Array]] = None,
):
"""Fixed-step size matrix exponential based solver implemented with
``scipy.linalg.expm``. Solves the specified problem by taking steps of
size no l... | 52,840 |
def time_to_hhmmss(tm: datetime.time) -> str:
"""Convert a datetime.time to HHMMSS string."""
if tm is not None:
return "%.2d%.2d%.2d" % (tm.hour, tm.minute, tm.second)
else:
return "" | 52,841 |
def parse_devices(header, lines):
"""Parses output of lsblk"""
cols = parse_header(header)
mappings = {}
flat = {}
parents = []
indent = 0
last = None
for line in lines:
index = 0
name = None
mapping = {'children': [], 'parent': None}
for col in cols:
... | 52,842 |
def _calc_j5_dependants(conf: List[BaseJoint], flag_sum: int, theta123: List[float], j5_solutions: Dict[bool, float],
tf14: np.ndarray, xdir: np.ndarray, zdir: np.ndarray) -> JointSolution:
"""
Calculate the dependant last joint for given j5 solutions
:param conf: Tuple of joints, of... | 52,843 |
def format_data(value):
"""
返回百分数据的值
"""
return round(value*100, 1) | 52,844 |
def check_downsample_queue(args):
"""
Check queue for downsample jobs.
Also marks downsample as in progress if message found.
Args:
(dict): { 'queue_url': <URL of SQS queue>, 'sfn_arn': <arn of the downsample step fcn> }
Returns:
(dict): {
'start_downsample': True | Fa... | 52,845 |
def pindajya(k: int):
"""
Return the kth pindajya computed by the nilakantha recurrence
Inputs:
k (int) : index from 0 to 23
Outputs:
int : kth pindajya
"""
assert ((k>=0) & (k<24)), f"Input must be between 0 and 23 inclusive, got {k}"
return float(_b[k]) | 52,846 |
def main():
"""保存文件"""
path = os.path.dirname(os.path.abspath(__file__))
data = json.loads(openurl()).get('images')[0]
desc = data.get('copyright')
download_url = data.get('url')
filename = os.path.basename(download_url)
with open(path + '/' + filename, 'wb') as f:
f.write(requests.g... | 52,847 |
def g2xys(m: Basemap, coords: Iterable[Tuple[float, float]]) \
-> Tuple[Sequence[float], Sequence[float]]:
"""
Convert an iterable with geographical coordinates into
two sequences with x- and y-coordinates in the plotting space.
Can be used to convert an iterable with geographic coordinates
... | 52,848 |
def create_linear_transform(linear_transform, features):
"""Function for creating linear transforms.
Parameters
----------
linear_transform : {'permutation', 'lu', 'svd'}
Linear transform to use.
featres : int
Number of features.
"""
if linear_transform.lower() == 'permutati... | 52,849 |
def cross_entropy(y_pred,y):
""" Cross entropy loss for classification purposes"""
epsilon = 0.001 # To prevent overflow and ensure numerical stability
return sum(-y*np.log(y_pred+epsilon)) | 52,850 |
def create(name, root, *args, **kwargs):
"""
Create a dataset instance.
Parameters
----------
name : str
The dataset name. Can be one of 'pitts', 'tokyo'.
root : str
The path to the dataset directory.
"""
if name not in __factory:
raise KeyError("Unknown dataset:... | 52,851 |
def get_time_stamp_from_lidar_pc(lidar_pc: LidarPc) -> int:
"""
Extracts the time stamp from a LidarPc.
:param lidar_pc: Input lidar pc.
:return: Timestamp in micro seconds.
"""
return cast(int, lidar_pc.ego_pose.timestamp) | 52,852 |
def test_customized_request_actions(customized_app, users):
"""Test if the action customization mechanism works."""
service = customized_app.extensions["invenio-requests"].requests_service
request = service.create(
system_identity,
{},
CustomizedReferenceRequestType,
receiver... | 52,853 |
def downgrade():
"""Write your downgrade statements here.""" | 52,854 |
def infer_mask(seq, eos_ix, batch_first=True, include_eos=True, dtype=torch.float):
"""
compute length given output indices and eos code
:param seq: tf matrix [time,batch] if batch_first else [batch,time]
:param eos_ix: integer index of end-of-sentence token
:param include_eos: if True, the time-ste... | 52,855 |
def print_alignment(match,test_instance,gold_instance,flip=False):
""" print the alignment based on a match
Args:
match: current match, denoted by a list
test_instance: instances of AMR 1
gold_instance: instances of AMR 2
filp: filp the test/gold or not"""
result=[]
for i... | 52,856 |
def test_prometheus_user(prometheus):
""" Ensure user is 'nobody'
"""
user = prometheus.check_output('whoami')
assert user == "nobody", \
f"Expected prometheus to be running as 'nobody', not '{user}'" | 52,857 |
def request_parameter(context, name, path):
"""Set request parameter."""
context["api_request"]["kwargs"][escape_reserved_keyword(snake_case(name))] = glom(context, path) | 52,858 |
def beta_labelling(LLR,ln_beta):
""" apply a filter to the LLR array :
if the LLR is above log_beta : return 1
else : return 0
"""
beta_func = np.vectorize(lambda a,b: 1 if a>b else 0)
return beta_func(LLR,ln_beta) | 52,859 |
def tr_sqrt(A, rank=None):
"""Return the trace of the sqrt of a positive semidefinite operator.
"""
if rank is None:
el = eigvalsh(A, sort=False)
else:
el = eigvalsh(A, k=rank, which='LM', backend='AUTO')
return np.sum(np.sqrt(el[el > 0.0])) | 52,860 |
def myBasicTreeXMLLines(tree):
"""
Takes:
- tree (ete3.TreeNode)
Returns:
(list): list of xml lines
"""
lines = ["<phylogeny>"]
indentChar = " "
tmp = myBasicTreeXMLLinesAux(tree)
for l in tmp:
lines.append( indentChar + l )
lines.append("</phylogeny>")
... | 52,861 |
def parse(tokens, parse_until=None,
start_from=0):
"""
:param tokens: Tokens to parse
:type tokens: list[Token]
:param parse_until:
:param start_from:
:return: AstTree
"""
tree = AstTree()
it = Iterator(tokens, start_from=start_from)
while not it.is_done():
... | 52,862 |
def test_root_right_left_none(large_tree):
""" Test no node right and left of root
"""
assert large_tree.root.right.left is None | 52,863 |
def silero_lang_detector_116(**kwargs):
"""Silero Language Classifier (116 languages)
Returns a model with a set of utils
Please see https://github.com/snakers4/silero-vad for usage examples
"""
hub_dir = torch.hub.get_dir()
model = init_jit_model(model_path=f'{hub_dir}/snakers4_silero-vad_mast... | 52,864 |
def isPrime(n):
"""Returns True if n is prime."""
if n == 2:
return True
if n == 3:
return True
if n % 2 == 0:
return False
if n % 3 == 0:
return False
i = 5
w = 2
while i * i <= n:
if n % i == 0:
return False
... | 52,865 |
def is_saved(response: Response, name: str, port: int) -> bool:
"""Wait for the response showing that saving has taken place."""
expected_url = f"http://localhost:{port}/api/contents/{name}"
method = response.request.method
try:
t = response.json().get("type")
except AttributeError:
... | 52,866 |
def filter_polygons(state, header):
"""
Removes any non-polygon sources from the state file.
We are only interested in parsing parcel data, which is
marked as Polygon in the state file.
"""
filtered_state = []
for source in state:
if 'Polygon' in source[header.index('geometry type'... | 52,867 |
def conv_out_init(obj: MyArray,
results: ArgTuple[BaseArray],
outputs: OutTuple[BaseArray],
conv: _ty.Sequence[bool] = ()) -> ArgTuple[MyArray]:
"""Process outputs in an __array_ufunc__ method using a constructor.
Creates an instance of ``type(obj)`` with `... | 52,868 |
def test_fill_multiple_columns(df):
"""Fill on multiple columns with a single direction."""
expected = df.copy()
expected.loc[:, ["pet_type", "owner"]] = expected.loc[
:, ["pet_type", "owner"]
].ffill()
assert_frame_equal(
df.fill_direction(**{"pet_type": "down", "owner": "down"}), e... | 52,869 |
def detect_blobs(im,im_out,params):
"""
:param im: input image to track
:param im_out: image to display bounding boxes
:param params: Blob detector params
:return: blob, im_disp, bbox
"""
detector = cv2.SimpleBlobDetector_create(params)
blob_im = im
blob = detector.detect(blob_i... | 52,870 |
def get_thermal_instance(wildcards):
"""
Returns a formatted template
Arguments:
rest_base - Base URL of the RESTful interface
ident - Identifier of the chassis
"""
c = copy.deepcopy(_TEMPLATE)
c['@odata.context'] = c['@odata.context'].format(**wildcards)
c['@odata.id']... | 52,871 |
def getWorldSimState(world):
"""Returns a dict containing a copy of all variables that are
simulated in the world. Can be used with setWorldSimState to save/
restore state.
NOTE: this does not perfectly save the state of a Simulator! To do that,
you must use the Simulator().getState()/saveState()... | 52,872 |
def unicode_normalize(text):
"""Return the given text normalized to Unicode NFKC."""
normalized_text = unicodedata.normalize('NFKC', text)
return normalized_text | 52,873 |
def import_obj(clsname, default_module=None):
"""
Import the object given by clsname.
If default_module is specified, import from this module.
"""
if default_module is not None:
if not clsname.startswith(default_module + '.'):
clsname = '{0}.{1}'.format(default_module, clsname)
... | 52,874 |
def _SelectUploadCompressionStrategy(object_name,
is_component=False,
gzip_exts=False,
gzip_encoded=False):
"""Selects how an upload should be compressed.
This is a helper function for _UploadFileToObject... | 52,875 |
def polynomial_features(X, degree):
""" Make polynomial feature.
Parameters:
-----------
X: ndarray of shape (n_samples, n_features)
The input samples
degree: int
The highest of the degrees of the polynomial's monomials (individual terms) with non-zero coefficients
Returns:
-... | 52,876 |
def test_greedy():
"""URL routing greedy settings"""
map = Map([
Rule('/foo', endpoint='foo'),
Rule('/<path:bar>', endpoint='bar'),
Rule('/<path:bar>/<path:blub>', endpoint='bar')
])
adapter = map.bind('example.org', '/')
assert adapter.match('/foo') == ('foo', {})
asser... | 52,877 |
def main():
"""Start up a simple app server to serve the SRU application."""
from wsgiref.simple_server import make_server
try:
host = sys.argv[1]
except IndexError:
try:
import socket
host = socket.gethostname()
except:
host = 'localhost'
... | 52,878 |
def flesch_reading_ease_score(sentences: int, words: int, syllables: int, *, is_russian: bool = False) -> float:
"""
Calculate the Flesch-Kincaid score.
"""
if not sentences or not words:
return 0.0
# Flesch-Kincaid score constants:
x_grade: float = FRES_RU.X_GRADE if is_russian else FR... | 52,879 |
def freeze_all_bert_layers(l_bert):
"""
Freezes all but LayerNorm and adapter layers - see arXiv:1902.00751.
"""
l_bert.trainable = False
l_bert.encoders_layer.trainable = False
for layer in l_bert.submodules:
if layer.name in ["LayerNorm", "adapter-down", "adapter-up"]:
lay... | 52,880 |
def add_publication_to_group(project, publication_id):
"""
Add a publication to a publication_group
POST data MUST be in JSON format
POST data MUST contain the following:
group_id: numerical ID for the publication_group
"""
request_data = request.get_json()
if not request_data:
... | 52,881 |
def plot_pr_at_k(
results, save_prefix,
p_prefix='precision_score_at_', r_prefix='recall_score_at_', x_value_type='float'):
"""
Plot precision recall curves.
Arguments:
- results: a results DataFrame, with a row for each model,
and with columns for precision and recall at varyi... | 52,882 |
def is_compatible(feature: Feature, other: Feature):
"""Determines if two features are compatible with one another."""
return feature.api == other.api and not (
other.version.major > feature.version.major
or (
other.version.major == feature.version.major
and other.version... | 52,883 |
def test_xml_basics(app, warning):
"""Verify definition of and linking between traceables
.. traceable:: TEST-TRACEDEF
:title: Verify definition of and linking between traceables
:category: Test
:test_type: auto
:parents: REQ-TRACEDIRECTIVE, REQ-ERRORM... | 52,884 |
def get_tworay_path_loss(range_m, freq_hz, tx_ht_m, rx_ht_m, include_atm_loss=True, atmosphere=None):
"""
Computes the two-ray path loss according to
L = 10*log10(R^4/(h_t^2*h_r^2))
This model is generally deemed appropriate for low altitude transmitters and receivers, with a flat Earth model.... | 52,885 |
def check_bots_database():
"""Check for elements in bot's database.
Returns:
int: Size of list if there is any elements
None: If table is empty
"""
db_status = database.get_data("confDB", False,
"SELECT bot_name FROM tokens")
return None if not db_s... | 52,886 |
def run_migrations_online():
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
config_copy = config.get_section(config.config_ini_section).copy()
config_copy['sqlalchemy.url'] = DB_URI
connectable = engine_fro... | 52,887 |
def get_features_for_commit_people(git_commit):
"""Retrieves the people associated with a git commit
Arg:
git_commit(dict): a commit message parsed into a dictionary
Return:
(tuple): relevant people and type extracted from the commit
"""
curr_time = datetime.datetime.utcnow()
git_hash = git_commit... | 52,888 |
def test_the_TESTS():
"""
Run the entire TEST.
"""
for test_data in tests:
test = dict(EMPTY_TEST)
test.update(test_data)
yield test['name'], _run_test, test | 52,889 |
def get_url_source(url_name):
"""
If you already know the url_name or if you have run through the get_noaa_forecast_url(), then you can
send in the url here. Get the source information for the url and place the information into a BeautifulSoup
object, so that we can do any lookups of the data that we ne... | 52,890 |
def norm(x):
""" Normalize (z-norm) from [0,1] range to [-1,1] """
out = (x - 0.5) * 2.0
if isinstance(x, torch.Tensor):
return out.clamp(-1, 1)
elif isinstance(x, np.ndarray):
return np.clip(out, -1, 1)
else:
raise TypeError(
"Got unexpected object type, expecte... | 52,891 |
def main() -> None:
"""Start the bot."""
# Create the Updater and pass it your bot's token.
#token = os.environ['TOKEN']
token = os.getenv('TOKEN')
print (token)
updater = Updater( token )
# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
# on diffe... | 52,892 |
def _add_model_run(
posts: List[YamlDict],
run_id: str,
open_timestamp: dt,
inputs: List[str],
outputs: List[YamlDict],
model_config: YamlDict,
submission_script: YamlDict,
code_repo: YamlDict,
description: str,
) -> None:
"""
Generates the post required for adding a model ru... | 52,893 |
def transform():
"""Transform documents (for testing)""" | 52,894 |
def gen_gp_loss(gp):
"""Generate an internal objective, `dlik_dh * H`, for a given GP layer.
"""
def loss(_, H):
dlik_dh_times_H = H * K.gather(gp.dlik_dh, gp.batch_ids[:gp.batch_sz])
return K.sum(dlik_dh_times_H, axis=1, keepdims=True)
return loss | 52,895 |
def problem3_4(mon, day, year):
""" Takes date such as July 17, 2016 and write it as 7/17/2016 """
month_mapping = {'January':1,
"Febuary":2,
"March":3,
"April":4,
"May" : 5,
"June" : 6,
... | 52,896 |
def set_market(asset_form: NewAssetForm) -> Tuple[Optional[Market], Optional[str]]:
"""Set a market for the to-be-created asset.
Return the market (if available) and an error message."""
market = None
market_error = None
if int(asset_form.market_id.data) == -1:
market_error = "Pick an exist... | 52,897 |
def brnaseq_inc():
"""Call this function when the bulk_rnaseq arguments dictionary is
incomplete."""
msg = CREDITS + """----------
ERROR
You did not specify sufficient options to run the bulk_rnaseq subcommand of
gopher-pipelines. You must specify a FASTQ directory (-f). Additionally, you
must either spec... | 52,898 |
def previous_slice(ax):
"""Multislide viewser as implemented from
https://www.datacamp.com/community/tutorials/matplotlib-3d-volumetric
-data
"""
volume = ax.volume
ax.index = (ax.index - 1) % volume.shape[0] # wrap around using %
ax.images[0].set_array(volume[ax.index]) | 52,899 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.