content
stringlengths 22
815k
| id
int64 0
4.91M
|
---|---|
def unsorted_array(arr: list) -> Tuple[list, int, Tuple[int, int]]:
"""
Time Complexity: O(n)
"""
start, end = 0, len(arr) - 1
while start < end and arr[start] < arr[start + 1]:
start += 1
while start < end and arr[end] > arr[end - 1]:
end -= 1
for el in arr[start : end + 1]:
# another way of implementing this part would be to find the min and
# max of the subarray and keep on decrementing start/incrementing end
while el < arr[start]:
start -= 1
while el > arr[end]:
end += 1
if start + 1 < end - 1:
return arr[start + 1 : end], end - start - 1, (start + 1, end - 1)
return [], 0, (-1, -1)
| 8,100 |
def get_tol_values(places):
# type: (float) -> list
"""List of tolerances to test
Returns:
list[tuple[float, float]] -- [(abs_tol, rel_tol)]
"""
abs_tol = 1.1 / pow(10, places)
return [(None, None), (abs_tol, None)]
| 8,101 |
def index(atom: Atom) -> int:
"""Index within the parent molecule (int).
"""
return atom.GetIdx()
| 8,102 |
def test_policy_json_one_statement_no_condition(dummy_policy_statement):
"""
GIVEN PolicyCustom and PolicyStatement object.
WHEN Created object with one statement.
THEN Return policy data in JSON format.
"""
test_policy = PolicyDocumentCustom()
test_policy.add_statement( dummy_policy_statement)
desired_policy = {
'Version': '2012-10-17',
'Statement': [
{
'Effect': 'Allow',
'Action': 'execute-api:Invoke',
'Resource': ['execute-api:/*']
}
]
}
assert test_policy.get_json() == json.dumps(desired_policy)
| 8,103 |
def specification_config() -> GeneratorConfig:
"""A spec cache of r4"""
return load_config("python_pydantic")
| 8,104 |
def _wait_for_stack_ready(stack_name, region, proxy_config):
"""
Verify if the Stack is in one of the *_COMPLETE states.
:param stack_name: Stack to query for
:param region: AWS region
:param proxy_config: Proxy configuration
:return: true if the stack is in the *_COMPLETE status
"""
log.info("Waiting for stack %s to be ready", stack_name)
cfn_client = boto3.client("cloudformation", region_name=region, config=proxy_config)
stacks = cfn_client.describe_stacks(StackName=stack_name)
stack_status = stacks["Stacks"][0]["StackStatus"]
log.info("Stack %s is in status: %s", stack_name, stack_status)
return stack_status in [
"CREATE_COMPLETE",
"UPDATE_COMPLETE",
"UPDATE_ROLLBACK_COMPLETE",
"CREATE_FAILED",
"UPDATE_FAILED",
]
| 8,105 |
def create_order_number_sequence(
shop_id: ShopID, prefix: str, *, value: Optional[int] = None
) -> OrderNumberSequence:
"""Create an order number sequence."""
sequence = DbOrderNumberSequence(shop_id, prefix, value=value)
db.session.add(sequence)
try:
db.session.commit()
except IntegrityError as exc:
db.session.rollback()
raise OrderNumberSequenceCreationFailed(
f'Could not create order number sequence with prefix "{prefix}"'
) from exc
return _db_entity_to_order_number_sequence(sequence)
| 8,106 |
def move_wheel_files(name, req, wheeldir, user=False, home=None):
"""Install a wheel"""
scheme = distutils_scheme(name, user=user, home=home)
if scheme['purelib'] != scheme['platlib']:
# XXX check *.dist-info/WHEEL to deal with this obscurity
raise NotImplemented("purelib != platlib")
info_dir = []
data_dirs = []
source = wheeldir.rstrip(os.path.sep) + os.path.sep
location = dest = scheme['platlib']
installed = {}
changed = set()
def normpath(src, p):
return make_path_relative(src, p).replace(os.path.sep, '/')
def record_installed(srcfile, destfile, modified=False):
"""Map archive RECORD paths to installation RECORD paths."""
oldpath = normpath(srcfile, wheeldir)
newpath = normpath(destfile, location)
installed[oldpath] = newpath
if modified:
changed.add(destfile)
def clobber(source, dest, is_base, fixer=None):
if not os.path.exists(dest): # common for the 'include' path
os.makedirs(dest)
for dir, subdirs, files in os.walk(source):
basedir = dir[len(source):].lstrip(os.path.sep)
if is_base and basedir.split(os.path.sep, 1)[0].endswith('.data'):
continue
for s in subdirs:
destsubdir = os.path.join(dest, basedir, s)
if is_base and basedir == '' and destsubdir.endswith('.data'):
data_dirs.append(s)
continue
elif (is_base
and s.endswith('.dist-info')
# is self.req.project_name case preserving?
and s.lower().startswith(req.project_name.replace('-', '_').lower())):
assert not info_dir, 'Multiple .dist-info directories'
info_dir.append(destsubdir)
if not os.path.exists(destsubdir):
os.makedirs(destsubdir)
for f in files:
srcfile = os.path.join(dir, f)
destfile = os.path.join(dest, basedir, f)
shutil.move(srcfile, destfile)
changed = False
if fixer:
changed = fixer(destfile)
record_installed(srcfile, destfile, changed)
clobber(source, dest, True)
assert info_dir, "%s .dist-info directory not found" % req
for datadir in data_dirs:
fixer = None
for subdir in os.listdir(os.path.join(wheeldir, datadir)):
fixer = None
if subdir == 'scripts':
fixer = fix_script
source = os.path.join(wheeldir, datadir, subdir)
dest = scheme[subdir]
clobber(source, dest, False, fixer=fixer)
record = os.path.join(info_dir[0], 'RECORD')
temp_record = os.path.join(info_dir[0], 'RECORD.pip')
with open_for_csv(record, 'r') as record_in:
with open_for_csv(temp_record, 'w+') as record_out:
reader = csv.reader(record_in)
writer = csv.writer(record_out)
for row in reader:
row[0] = installed.pop(row[0], row[0])
if row[0] in changed:
row[1], row[2] = rehash(row[0])
writer.writerow(row)
for f in installed:
writer.writerow((installed[f], '', ''))
shutil.move(temp_record, record)
| 8,107 |
def read_hdulist (fits_file, get_data=True, get_header=False,
ext_name_indices=None, dtype=None, columns=None,
memmap=True):
"""Function to read the data (if [get_data] is True) and/or header (if
[get_header] is True) of the input [fits_file]. The fits file can
be an image or binary table, and can be compressed (with the
compressions that astropy.io can handle, such as .gz and .fz
files). If [ext_name_indices] is defined, which can be an integer,
a string matching the extension's keyword EXTNAME or a list or
numpy array of integers, those extensions are retrieved.
"""
if os.path.exists(fits_file):
fits_file_read = fits_file
else:
# if fits_file does not exist, look for compressed versions or
# files without the .fz or .gz extension
if os.path.exists('{}.fz'.format(fits_file)):
fits_file_read = '{}.fz'.format(fits_file)
elif os.path.exists(fits_file.replace('.fz','')):
fits_file_read = fits_file.replace('.fz','')
elif os.path.exists('{}.gz'.format(fits_file)):
fits_file_read = '{}.gz'.format(fits_file)
elif os.path.exists(fits_file.replace('.gz','')):
fits_file_read = fits_file.replace('.gz','')
else:
raise FileNotFoundError ('file not found: {}'.format(fits_file))
# open fits file into hdulist
with fits.open(fits_file_read, memmap=memmap) as hdulist:
n_exts = len(hdulist)
# if [ext_name_indices] is a range, or list or numpy ndarray
# of integers, loop over these extensions and concatenate the
# data into one astropy Table; it is assumed the extension
# formats are identical to one another - this is used to read
# specific extensions from e.g. the calibration catalog.
if type(ext_name_indices) in [list, range, np.ndarray]:
for i_ext, ext in enumerate(ext_name_indices):
# get header from first extension as they should be
# all identical, except for NAXIS2 (nrows)
if get_header and i_ext==0:
header = hdulist[ext].header
if get_data:
# read extension
data_temp = hdulist[ext].data
# convert to table, as otherwise concatenation of
# extensions below using [stack_arrays] is slow
data_temp = Table(data_temp)
# could also read fits extension into Table directly,
# but this is about twice as slow as the 2 steps above
#data_temp = Table.read(fits_file_read, hdu=ext)
if i_ext==0:
data = data_temp
else:
#data = stack_arrays((data, data_temp),asrecarray=True,
# usemask=False)
# following does not work if data is a fitsrec
# array and the array contains boolean fields, as
# these are incorrectly converted; therefore the
# conversion to a Table above
data = np.concatenate([data, data_temp])
else:
# otherwise read the extension defined by [ext_name_indices]
# or simply the last extension
if type(ext_name_indices) in [int, str]:
ext = ext_name_indices
else:
ext = n_exts-1
if get_data:
data = hdulist[ext].data
# convert to [dtype] if it is defined
if dtype is not None:
data = data.astype(dtype, copy=False)
if get_header:
header = hdulist[ext].header
if columns is not None:
# only return defined columns
return [data[col] for col in columns if col in data.dtype.names]
else:
# return data and header depending on whether [get_data]
# and [get_header] are defined or not
if get_data:
if get_header:
return data, header
else:
return data
else:
if get_header:
return header
else:
return
| 8,108 |
def calcMFCC(signal, sample_rate=16000, win_length=0.025, win_step=0.01,
filters_num=26, NFFT=512, low_freq=0, high_freq=None, pre_emphasis_coeff=0.97,
cep_lifter=22, append_energy=True, append_delta=False):
"""Calculate MFCC Features.
Arguments:
signal: 1-D numpy array.
sample_rate: Sampling rate. Defaulted to 16KHz.
win_length: Window length. Defaulted to 0.025, which is 25ms/frame.
win_step: Interval between the start points of adjacent frames.
Defaulted to 0.01, which is 10ms.
filters_num: Numbers of filters. Defaulted to 26.
NFFT: Size of FFT. Defaulted to 512.
low_freq: Lowest frequency.
high_freq: Highest frequency.
pre_emphasis_coeff: Coefficient for pre-emphasis. Pre-emphasis increase
the energy of signal at higher frequency. Defaulted to 0.97.
cep_lifter: Numbers of lifter for cepstral. Defaulted to 22.
append_energy: Whether to append energy. Defaulted to True.
append_delta: Whether to append delta to feature. Defaulted to False.
Returns:
2-D numpy array with shape (NUMFRAMES, features). Each frame containing filters_num of features.
"""
(feat, energy) = _fbank(signal, sample_rate, win_length, win_step, filters_num, NFFT,
low_freq, high_freq, pre_emphasis_coeff)
feat = np.log(feat)
feat = dct(feat, type=2, axis=1, norm='ortho')
feat = _lifter(feat, cep_lifter)
if append_energy:
feat[:, 0] = np.log(energy)
if append_delta:
feat_delta = _delta(feat)
feat_delta_delta = _delta(feat_delta)
feat = np.concatenate((feat, feat_delta, feat_delta_delta), axis=1)
return feat
| 8,109 |
def get_user(domain_id=None, enabled=None, idp_id=None, name=None, password_expires_at=None, protocol_id=None, region=None, unique_id=None):
"""
Use this data source to get the ID of an OpenStack user.
"""
__args__ = dict()
__args__['domainId'] = domain_id
__args__['enabled'] = enabled
__args__['idpId'] = idp_id
__args__['name'] = name
__args__['passwordExpiresAt'] = password_expires_at
__args__['protocolId'] = protocol_id
__args__['region'] = region
__args__['uniqueId'] = unique_id
__ret__ = pulumi.runtime.invoke('openstack:identity/getUser:getUser', __args__)
return GetUserResult(
default_project_id=__ret__.get('defaultProjectId'),
domain_id=__ret__.get('domainId'),
region=__ret__.get('region'),
id=__ret__.get('id'))
| 8,110 |
def start():
"""
Initializes files sharing
"""
(config, is_first_time) = get_config()
run_now = print_config(config, is_first_time)
if is_first_time:
if run_now:
main_job(config)
else:
print('scorpion exited')
return
else:
main_job(config)
| 8,111 |
def use(workflow_id, version, client=None):
"""
Use like ``import``: load the proxy object of a published `Workflow` version.
Parameters
----------
workflow_id: str
ID of the `Workflow` to retrieve
version: str
Version of the workflow to retrive
client: `.workflows.client.Client`, optional
Allows you to use a specific client instance with non-default
auth and parameters
Returns
-------
obj: Proxytype
Proxy object of the `Workflow` version.
Example
-------
>>> import descarteslabs.workflows as wf
>>> @wf.publish("bob@gmail.com:ndvi", "0.0.1") # doctest: +SKIP
... def ndvi(img: wf.Image) -> wf.Image:
... nir, red = img.unpack_bands("nir red")
... return (nir - red) / (nir + red)
>>> same_function = wf.use("bob@gmail.com:ndvi", "0.0.1") # doctest: +SKIP
>>> same_function # doctest: +SKIP
<descarteslabs.workflows.types.function.function.Function[Image, {}, Image] object at 0x...>
>>> img = wf.Image.from_id("sentinel-2:L1C:2019-05-04_13SDV_99_S2B_v1")
>>> same_function(img).compute(geoctx) # geoctx is an arbitrary geocontext for 'img' # doctest: +SKIP
ImageResult:
...
"""
return VersionedGraft.get(workflow_id, version, client=client).object
| 8,112 |
def logout():
"""
Route for logout page.
"""
logout_user()
return redirect(url_for('index'))
| 8,113 |
def ipv4_size_check(ipv4_long):
"""size chek ipv4 decimal
Args:
ipv4_long (int): ipv4 decimal
Returns:
boole: valid: True
"""
if type(ipv4_long) is not int:
return False
elif 0 <= ipv4_long <= 4294967295:
return True
else:
return False
| 8,114 |
def _validate_config(config):
"""Validate the StreamAlert configuration contains a valid structure.
Checks for `logs.json`:
- each log has a schema and parser declared
Checks for `sources.json`
- the sources contains either kinesis or s3 keys
- each sources has a list of logs declared
"""
# Check the log declarations
for log, attrs in config['logs'].iteritems():
if 'schema' not in attrs:
raise ConfigError('The \'schema\' is missing for {}'.format(log))
if 'parser' not in attrs:
raise ConfigError('The \'parser\' is missing for {}'.format(log))
# Check if the defined sources are supported and report any invalid entries
supported_sources = {'kinesis', 's3', 'sns', 'stream_alert_app'}
if not set(config['sources']).issubset(supported_sources):
missing_sources = supported_sources - set(config['sources'])
raise ConfigError(
'The \'sources.json\' file contains invalid source entries: {}. '
'The following sources are supported: {}'.format(
', '.join('\'{}\''.format(source) for source in missing_sources),
', '.join('\'{}\''.format(source) for source in supported_sources)
)
)
# Iterate over each defined source and make sure the required subkeys exist
for attrs in config['sources'].values():
for entity, entity_attrs in attrs.iteritems():
if 'logs' not in entity_attrs:
raise ConfigError('Missing \'logs\' key for entity: {}'.format(entity))
if not entity_attrs['logs']:
raise ConfigError(
'List of \'logs\' is empty for entity: {}'.format(entity))
| 8,115 |
def generate_gate_hadamard_mat() -> np.ndarray:
"""Return the Hilbert-Schmidt representation matrix for an Hadamard (H) gate with respect to the orthonormal Hermitian matrix basis with the normalized identity matrix as the 0th element.
The result is a 4 times 4 real matrix.
Parameters
----------
Returns
----------
np.ndarray
The real Hilbert-Schmidt representation matrix for the gate.
"""
l = [[1, 0, 0, 0], [0, 0, 0, 1], [0, 0, -1, 0], [0, 1, 0, 0]]
mat = np.array(l, dtype=np.float64)
return mat
| 8,116 |
def dequote(s):
""" Remove outer quotes from string
If a string has single or double quotes around it, remove them.
todo: Make sure the pair of quotes match.
If a matching pair of quotes is not found, return the string unchanged.
"""
if s.startswith(("'", '"', '<')):
return s[1:-1]
return s
| 8,117 |
def display_ordinal_value(glyph: str):
"""Displays the integer value of the given glyph
Examples:
>>> display_ordinal_value('🐍')\n
128013
>>> display_ordinal_value('G')\n
71
>>> display_ordinal_value('g')\n
103
"""
return ord(glyph)
| 8,118 |
def mixture_HPX( gases, Xs ):
"""
Given a mixture of gases and their mole fractions,
this method returns the enthalpy, pressure, and
composition string needed to initialize
the mixture gas in Cantera.
NOTE: The method of setting enthalpy
usually fails, b/c Cantera uses a Newton
iterator to find the temperature that
yields the specified enthalpy, and it
isn't very robust.
Instead, approximate constant Cp's
and find T_mix manually, as with the
mixture_TPX() method above.
"""
# --------------
# X
mixture_d = {}
for gas,wx_i in zip(gases,Xs):
for sp in gas.species_names:
if sp in mixture_d:
mixture_d[sp] += wx_i * gas.mole_fraction(sp)
elif gas.moleFraction(sp) != 0.0:
mixture_d[sp] = wx_i * gas.mole_fraction(sp)
else:
pass
mixture_s = convert_composition_dict_to_string(mixture_d)
# --------------
# H
# Compute Tmix with molar heat capacities
#
# Define:
# h_mix = sum_i n_i h_i
#
# where h is molar enthalpy
# compute H_mix
H_mix = 0
for gas, wx_i in zip(gases,Xs):
Hmix += wx_i * gas.enthalpy_mole
# --------------
# P
press = 0.0
for gas,wx_i in zip(gases,Xs):
press += wx_i * gas.P
# -------------------
# Return HPX
return H_mix, press, mixture_s
| 8,119 |
def _get_rooms_by_live_id(conn, live_id: int, room_status:WaitRoomStatus = WaitRoomStatus.Waiting) -> Iterator[RoomInfo]:
"""list rooms
Args:
conn ([type]): sql connection
live_id (int):
If 0, get all rooms.
Others, get rooms by live_id.
Yields:
[type]: [description]
"""
query: str = " ".join(
[
"SELECT",
", ".join(
(
f"`{ RoomDBTableName.room_id }`",
f"`{ RoomDBTableName.live_id }`",
f"`{ RoomDBTableName.joined_user_count }`",
)
),
f"FROM `{ RoomDBTableName.table_name }`",
f"WHERE `{ RoomDBTableName.status }`=:room_status",
]
+ ([] if live_id == 0 else [f"AND `{ RoomDBTableName.live_id }`=:live_id"])
)
result = conn.execute(text(query), dict(room_status=int(room_status), live_id=live_id))
for row in result.all():
yield RoomInfo.from_orm(row)
| 8,120 |
def gameMode():
"""greet the player, shuffle and print the initial board"""
board = Board()
greetings(board)
board.shuffle()
board.print_ascii()
"""while the game has not ended"""
get_arrow = Getch()
while True:
choice = get_arrow()
"""ensure that the choice is valid"""
if choice not in dict:
print("INVALID CHOICE OF {}".format(str(chr(choice))))
continue
if choice == -1:
print('Thanks for playing.')
break
elif dict[choice] == 'god':
"""find the path to the goal from the current board state"""
global_vars.init(board.board)
performance = time.time()
path = []
"""path is a list which is a mutable object.
Therefore the changes that occur in A* will reflect to this path,
aka it is passed by reference"""
board.ast(path) #choosing A* because it is the fastest
h.clear_scr()
performance = time.time() - performance
"""awesome presentation of GOD MODE and then follow the path to the goal"""
animations.present_god_mode(stars=350) #handles all the complex printing
time.sleep(2)
board.print_ascii()
time.sleep(2)
board.follow(path)
print('Thanks for playing.')
break
proccess(board,choice)
h.clear_scr()
board.print_ascii()
| 8,121 |
def merge_files(input_files, output_path, logger):
"""
Performs the merging across N (usually 1 PE and 1 SE)
htseq counts files. When only 1 is provided no changes are made;
however, we use this as a tool to also gzip all outputs.
:param input_files: list of files to merge
:param output_path: path out output file
:param logger: `logging.Logger` instance
"""
wfunc = get_open_function(output_path)
with wfunc(output_path, 'wt') as o:
if len(input_files) > 1:
logger.info("Multiple files provided, will sum counts")
dic = OrderedDict()
for fil in input_files:
logger.info("Processing {0}".format(fil))
rfunc = get_open_function(fil)
with rfunc(fil, 'rt') as fh:
for line in fh:
gid, counts = line.rstrip('\r\n').split('\t')
if gid not in dic:
dic[gid] = 0
dic[gid] += int(counts)
# Write
for key in dic:
row = [key, str(dic[key])]
o.write('\t'.join(row) + '\n')
else:
logger.info("Single input provided, no changes will be made")
fil = input_files[0]
rfunc = get_open_function(fil)
with rfunc(fil, 'rt') as fh:
for line in fh:
o.write(line)
| 8,122 |
async def async_get_bridges(hass) -> AsyncIterable[HueBridge]:
"""Retrieve Hue bridges from loaded official Hue integration."""
for entry in hass.data[HUE_DOMAIN].values():
if isinstance(entry, HueBridge) and entry.api:
yield entry
| 8,123 |
def authorize(config):
"""Authorize in GSheets."""
json_credential = json.loads(config['credentials']['gspread']['credential'])
credentials = ServiceAccountCredentials.from_json_keyfile_dict(json_credential, scope)
return gspread.authorize(credentials)
| 8,124 |
def _without_command(results):
"""A helper to tune up results so that they lack 'command'
which is guaranteed to differ between different cmd types
"""
out = []
for r in results:
r = r.copy()
r.pop('command')
out.append(r)
return out
| 8,125 |
def b(k, a):
"""
Optimal discretisation of TBSS to minimise error, p. 9.
"""
return ((k**(a+1)-(k-1)**(a+1))/(a+1))**(1/a)
| 8,126 |
def changepoint_loc_and_score(
time_series_data_window: pd.DataFrame,
kM_variance: float = 1.0,
kM_lengthscale: float = 1.0,
kM_likelihood_variance: float = 1.0,
k1_variance: float = None,
k1_lengthscale: float = None,
k2_variance: float = None,
k2_lengthscale: float = None,
kC_likelihood_variance=1.0, #TODO note this seems to work better by resetting this
# kC_likelihood_variance=None,
kC_changepoint_location=None,
kC_steepness=1.0,
) -> Tuple[float, float, float, Dict[str, float], Dict[str, float]]:
"""For a single time-series window, calcualte changepoint score and location as detailed in https://arxiv.org/pdf/2105.13727.pdf
Args:
time_series_data_window (pd.DataFrame): time-series with columns X and Y
kM_variance (float, optional): variance initialisation for Matern 3/2 kernel. Defaults to 1.0.
kM_lengthscale (float, optional): lengthscale initialisation for Matern 3/2 kernel. Defaults to 1.0.
kM_likelihood_variance (float, optional): likelihood variance initialisation for Matern 3/2 kernel. Defaults to 1.0.
k1_variance (float, optional): variance initialisation for Changepoint kernel k1, if None uses fitted variance parameter from Matern 3/2. Defaults to None.
k1_lengthscale (float, optional): lengthscale initialisation for Changepoint kernel k1, if None uses fitted lengthscale parameter from Matern 3/2. Defaults to None.
k2_variance (float, optional): variance initialisation for Changepoint kernel k2, if None uses fitted variance parameter from Matern 3/2. Defaults to None.
k2_lengthscale (float, optional): lengthscale initialisation for for Changepoint kernel k2, if None uses fitted lengthscale parameter from Matern 3/2. Defaults to None.
kC_likelihood_variance ([type], optional): likelihood variance initialisation for Changepoint kernel. Defaults to None.
kC_changepoint_location ([type], optional): changepoint location initialisation for Changepoint, if None uses midpoint of interval. Defaults to None.
kC_steepness (float, optional): changepoint location initialisation for Changepoint. Defaults to 1.0.
Returns:
Tuple[float, float, float, Dict[str, float], Dict[str, float]]: changepoint score, changepoint location,
changepoint location normalised by interval length to [0,1], Matern 3/2 kernel parameters, Changepoint kernel parameters
"""
time_series_data = time_series_data_window.copy()
Y_data = time_series_data[["Y"]].values
time_series_data[["Y"]] = StandardScaler().fit(Y_data).transform(Y_data)
# time_series_data.loc[:, "X"] = time_series_data.loc[:, "X"] - time_series_data.loc[time_series_data.index[0], "X"]
try:
(kM_nlml, kM_params) = fit_matern_kernel(
time_series_data, kM_variance, kM_lengthscale, kM_likelihood_variance
)
except BaseException as ex:
# do not want to optimise again if the hyperparameters
# were already initialised as the defaults
if kM_variance == kM_lengthscale == kM_likelihood_variance == 1.0:
raise BaseException(
"Retry with default hyperparameters - already using default parameters."
) from ex
(
kM_nlml,
kM_params,
) = fit_matern_kernel(time_series_data)
is_cp_location_default = (
(not kC_changepoint_location)
or kC_changepoint_location < time_series_data["X"].iloc[0]
or kC_changepoint_location > time_series_data["X"].iloc[-1]
)
if is_cp_location_default:
# default to midpoint
kC_changepoint_location = (
time_series_data["X"].iloc[-1] + time_series_data["X"].iloc[0]
) / 2.0
if not k1_variance:
k1_variance = kM_params["kM_variance"]
if not k1_lengthscale:
k1_lengthscale = kM_params["kM_lengthscales"]
if not k2_variance:
k2_variance = kM_params["kM_variance"]
if not k2_lengthscale:
k2_lengthscale = kM_params["kM_lengthscales"]
if not kC_likelihood_variance:
kC_likelihood_variance = kM_params["kM_likelihood_variance"]
try:
(changepoint_location, kC_nlml, kC_params) = fit_changepoint_kernel(
time_series_data,
k1_variance=k1_variance,
k1_lengthscale=k1_lengthscale,
k2_variance=k2_variance,
k2_lengthscale=k2_lengthscale,
kC_likelihood_variance=kC_likelihood_variance,
kC_changepoint_location=kC_changepoint_location,
kC_steepness=kC_steepness,
)
except BaseException as ex:
# do not want to optimise again if the hyperparameters
# were already initialised as the defaults
if (
k1_variance
== k1_lengthscale
== k2_variance
== k2_lengthscale
== kC_likelihood_variance
== kC_steepness
== 1.0
) and is_cp_location_default:
raise BaseException(
"Retry with default hyperparameters - already using default parameters."
) from ex
(
changepoint_location,
kC_nlml,
kC_params,
) = fit_changepoint_kernel(time_series_data)
cp_score = changepoint_severity(kC_nlml, kM_nlml)
cp_loc_normalised = (time_series_data["X"].iloc[-1] - changepoint_location) / (
time_series_data["X"].iloc[-1] - time_series_data["X"].iloc[0]
)
return cp_score, changepoint_location, cp_loc_normalised, kM_params, kC_params
| 8,127 |
def get_network_interfaces(properties):
""" Get the configuration that connects the instance to an existing network
and assigns to it an ephemeral public IP if specified.
"""
network_interfaces = []
networks = properties.get('networks', [])
if len(networks) == 0 and properties.get('network'):
network = {
"network": properties.get('network'),
"subnetwork": properties.get('subnetwork'),
"networkIP": properties.get('networkIP'),
}
networks.append(network)
if (properties.get('hasExternalIp')):
network['accessConfigs'] = [{
"type": "ONE_TO_ONE_NAT",
}]
if properties.get('natIP'):
network['accessConfigs'][0]["natIp"] = properties.get('natIP')
for network in networks:
if not '.' in network['network'] and not '/' in network['network']:
network_name = 'global/networks/{}'.format(network['network'])
else:
network_name = network['network']
network_interface = {
'network': network_name,
}
netif_optional_props = ['subnetwork', 'networkIP', 'aliasIpRanges', 'accessConfigs']
for prop in netif_optional_props:
if network.get(prop):
network_interface[prop] = network[prop]
network_interfaces.append(network_interface)
return network_interfaces
| 8,128 |
def setup(bot):
"""Cog creation"""
bot.add_cog(LinkHelper(bot))
| 8,129 |
def MATCH(*args) -> Function:
"""
Returns the relative position of an item in a range that matches a specified
value.
Learn more: https//support.google.com/docs/answer/3093378
"""
return Function("MATCH", args)
| 8,130 |
def set_dict_to_zero_with_list(dictionary, key_list):
""" Set dictionary keys from given list value to zero
Args:
dictionary (dict): dictionary to filter
key_list (list): keys to turn zero in filtered dictionary
Returns:
dictionary (dict): the filtered dictionary with keys from input list turned to zero
"""
#Generate list of unwanted keys
unwanted = (set(dictionary.keys()) - set(key_list))
#Delete keys from dictionary
for unwanted_key in unwanted: dictionary[unwanted_key] = 0
return dictionary
| 8,131 |
def terminal_condition_for_minitaur_extended_env(env):
"""Returns a bool indicating that the extended env is terminated.
This predicate checks whether 1) the legs are bent inward too much or
2) the body is tilted too much.
Args:
env: An instance of MinitaurGymEnv
"""
motor_angles = env.robot.motor_angles
leg_pose = minitaur_pose_utils.motor_angles_to_leg_pose(motor_angles)
swing_threshold = np.radians(35.0)
if (leg_pose[0] > swing_threshold or leg_pose[2] > swing_threshold or # Front
leg_pose[1] < -swing_threshold or leg_pose[3] < -swing_threshold): # Rear
return True
roll, _, _ = env.robot.base_roll_pitch_yaw
if abs(roll) > np.radians(30.0):
return True
return False
| 8,132 |
def save_url_dataset_for_cpp_benchmarks(n_days):
"""Fetches and saves as C++ cereal serialized file the URL dataset
Parameters
----------
n_days : `int`
Number of days kept from the original dataset.
As this dataset is quite big, you might not want to use it in totality.
"""
save_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'../../tools/benchmark/data')
os.makedirs(save_path, exist_ok=True)
label_path = os.path.join(save_path, 'url.{}.labels.cereal'.format(n_days))
features_path = os.path.join(save_path,
'url.{}.features.cereal'.format(n_days))
X, y = fetch_url_dataset(n_days=n_days)
serialize_array(y, label_path)
serialize_array(X, features_path)
| 8,133 |
def data_range(dt_start, dt_end):
"""read raw VP data between datetimes"""
filepath_fmt = path.join(DATA_DIR, DATA_FILE_FMT)
fnames = strftime_date_range(dt_start, dt_end, filepath_fmt)
pns = map(vprhimat2pn, fnames)
pns_out = []
for pn in pns:
if not pn.empty:
pns_out.append(pn)
return pd.concat(pns_out, axis=2, sort=True).loc[:, :, dt_start:dt_end]
| 8,134 |
async def test_call_async_migrate_entry_failure_false(hass):
"""Test migration fails if returns false."""
entry = MockConfigEntry(domain="comp")
entry.version = 2
entry.add_to_hass(hass)
mock_migrate_entry = MagicMock(return_value=mock_coro(False))
mock_setup_entry = MagicMock(return_value=mock_coro(True))
mock_integration(
hass,
MockModule(
"comp",
async_setup_entry=mock_setup_entry,
async_migrate_entry=mock_migrate_entry,
),
)
mock_entity_platform(hass, "config_flow.comp", None)
result = await async_setup_component(hass, "comp", {})
assert result
assert len(mock_migrate_entry.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 0
assert entry.state == config_entries.ENTRY_STATE_MIGRATION_ERROR
| 8,135 |
def init_ltmanager(conf, db, table, reset_db):
"""Initializing ltmanager by loading argument parameters."""
lt_alg = conf.get("log_template", "lt_alg")
ltg_alg = conf.get("log_template", "ltgroup_alg")
post_alg = conf.gettuple("log_template", "post_alg")
sym = conf.get("log_template", "variable_symbol")
ltm = LTManager(conf, db, table, reset_db,
lt_alg, ltg_alg, post_alg)
if lt_alg == "shiso":
import lt_shiso
ltgen = lt_shiso.LTGenSHISO(ltm._table, sym,
threshold = conf.getfloat(
"log_template_shiso", "ltgen_threshold"),
max_child = conf.getint(
"log_template_shiso", "ltgen_max_child")
)
elif lt_alg == "import":
fn = conf.get("log_template_import", "def_path")
mode = conf.get("log_template_import", "mode")
import logparser
lp = logparser.LogParser(conf, sep_variable = True)
import lt_import
ltgen = lt_import.LTGenImport(ltm._table, sym, fn, mode, lp)
elif lt_alg == "crf":
import lt_crf
ltgen = lt_crf.LTGenCRF(ltm._table, sym, conf)
#elif lt_alg == "va":
# import lt_va
# ltm = lt_va.LTManager(conf, self.db, self.table,
# self._reset_db, ltg_alg)
else:
raise ValueError("lt_alg({0}) invalid".format(lt_alg))
ltm._set_ltgen(ltgen)
if ltg_alg == "shiso":
import lt_shiso
ltgroup = lt_shiso.LTGroupSHISO(table,
ngram_length = conf.getint(
"log_template_shiso", "ltgroup_ngram_length"),
th_lookup = conf.getfloat(
"log_template_shiso", "ltgroup_th_lookup"),
th_distance = conf.getfloat(
"log_template_shiso", "ltgroup_th_distance"),
mem_ngram = conf.getboolean(
"log_template_shiso", "ltgroup_mem_ngram")
)
elif ltg_alg == "ssdeep":
import lt_misc
ltgroup = lt_misc.LTGroupFuzzyHash(table)
elif ltg_alg == "none":
ltgroup = LTGroup()
else:
raise ValueError("ltgroup_alg({0}) invalid".format(ltg_alg))
ltm._set_ltgroup(ltgroup)
ltspl = LTPostProcess(conf, ltm._table, ltm._lttable, post_alg)
ltm._set_ltspl(ltspl)
if os.path.exists(ltm.filename) and not reset_db:
ltm.load()
return ltm
| 8,136 |
def print_tree(tree, level=0, current=False):
"""Pretty-print a dictionary configuration `tree`"""
pre = ' ' * level
msg = ''
for k, v in tree.items():
if k == 'self':
msg += print_tree(v, level)
continue
# Detect subdevice
if isinstance(v, dict) and 'self' in v:
msg += pre + '|++> ' + k + '\n'
msg += print_tree(v, level + 1)
continue
if not current:
continue
v = repr(v['current'])
if len(v) > 50:
v = v[:46] + ' ...'
msg += '{}|: {} = {}\n'.format(pre, k, v)
return msg
| 8,137 |
def chaine_polynome(poly):
"""Renvoie la représentation dy polynôme _poly_ (version simple)"""
tab_str = [str(coef) + "*X^" + str(i) if i != 0 else str(coef) for i,coef in enumerate(poly)]
return " + ".join(tab_str[::-1])
| 8,138 |
def dump_config(forza: CarInfo, config_version: ConfigVersion = constants.default_config_version):
"""dump config
Args:
forza (CarInfo): car info
"""
try:
forza.logger.debug(f'{dump_config.__name__} started')
config_name = get_config_name(forza, config_version)
forza.logger.info(f'saving config {config_name}')
config = {
# === dump data and result ===
'version': config_version.name,
'ordinal': forza.ordinal,
'perf': forza.car_perf,
'class': forza.car_class,
'drivetrain': forza.car_drivetrain,
'minGear': forza.minGear,
'maxGear': forza.maxGear,
'gear_ratios': forza.gear_ratios,
'rpm_torque_map': forza.rpm_torque_map,
'shift_point': forza.shift_point,
'records': forza.records,
}
with open(os.path.join(forza.config_folder, config_name), "w") as f:
json.dump(config, f, default=convert, indent=4)
finally:
forza.logger.debug(f'{dump_config.__name__} ended')
| 8,139 |
def get_opr_from_dict(dict_of_opr_vals):
"""Takes in a dictionary where the keys are temperatures and values are optical rotation
values. The dictionary is for all the temperatures and optical rotation values extracted
for one molecule. This function determines which of the values in the dictionary to keep.
Args:
dict_of_opr_vals ([dict]): Keys are temperature and values are optical rotation vals.
Returns:
[String]: Final optical rotation value for a molecule
"""
if len(dict_of_opr_vals) > 0:
dict_keys = list(dict_of_opr_vals.keys())
if dict_keys.count("") == len(dict_keys):
return dict_of_opr_vals[""]
if "" in dict_keys:
dict_keys.remove("")
if dict_keys.count("X") == len(dict_keys):
return dict_of_opr_vals["X"]
else:
try:
dict_keys.remove("X")
except:
pass
return dict_of_opr_vals[dict_keys[abs_distance(dict_keys)]]
else:
return dict_of_opr_vals[0]
| 8,140 |
def tokens(s):
"""Return a list of strings containing individual words from string s.
This function splits on whitespace transitions, and captures apostrophes
(for contractions).
>>> tokens("I'm fine, how are you?")
["I'm", 'fine', 'how', 'are', 'you']
"""
words = re.findall(r"\b[\w']+\b", s)
return words
| 8,141 |
def get_variable_value(schema, definition_ast, input):
"""Given a variable definition, and any value of input, return a value which adheres to the variable definition, or throw an error."""
type = type_from_ast(schema, definition_ast.type)
if not type or not is_input_type(type):
raise GraphQLError(
'Variable ${} expected value of type {} which cannot be used as an input type.'.format(
definition_ast.variable.name.value,
print_ast(definition_ast.type),
),
[definition_ast]
)
if is_valid_value(type, input):
if is_nullish(input):
default_value = definition_ast.default_value
if default_value:
return coerce_value_ast(type, default_value, None)
return coerce_value(type, input)
raise GraphQLError(
'Variable ${} expected value of type {} but got: {}'.format(
definition_ast.variable.name.value,
print_ast(definition_ast.type),
repr(input)
),
[definition_ast]
)
| 8,142 |
def _convert_3d_crop_window_to_2d(crop_window):
"""Converts a 3D crop window to a 2D crop window.
Extracts just the spatial parameters of the crop window and assumes that those
apply uniformly across all channels.
Args:
crop_window: A 3D crop window, expressed as a Tensor in the format
[offset_height, offset_width, offset_channel, crop_height, crop_width,
crop_channels].
Returns:
A 2D crop window as a Tensor in the format [offset_height, offset_width,
crop_height, crop_width].
"""
with tf.name_scope('3d_crop_window_to_2d'):
return tf.gather(crop_window, [0, 1, 3, 4])
| 8,143 |
def era5_download(years, directory, variable="temp"):
"""Download ERA5 data
:param iterable year: year(s) for which data to be downloaded given as single
value or iterable list
:param str directory: path to root directory for ERA5 downloads
:param str: variable to be downloaded, chosen from:
temp {Default} -- dry bulb temperataure, corresponds to ERA5 variable "2m_temperature"
dewpt -- dew point temperature, corresponds to ERA5 variable "2m_dewpoint_temperature"
pres -- surface pressure, corresponds to ERA5 variable "surface_pressure"
:raises ValueError: if the ``variable`` name is invalid or if any values in
``years`` are outside of the valid range.
:raises Exception: if the cdsapi package is not configured properly.
"""
# Check variable input and get associated ERA5 variable name
try:
variable_era5 = variable_names[variable]["era5"]
except KeyError:
raise ValueError(f"Invalid variable name: {variable}")
# Make single year input iterable
if not hasattr(years, "__iter__"):
years = [years]
# Error if "years" includes any years prior to 1950
if min(years) < 1950:
raise ValueError("Input years must be 1950 or later")
# Note if prior to 1979, preliminary version of reanalysis back extension
if min(years) < 1979:
print(
"Data for years 1950-1979 are a preliminary version of reanalysis back extension"
)
try:
c = cdsapi.Client()
except Exception:
raise Exception(
"cdsapi is not configured properly, see https://cds.climate.copernicus.eu/api-how-to"
)
# Create folder to store data for given variable if it doesn"t yet exist
os.makedirs(os.path.join(directory, variable), exist_ok=True)
for year in years:
if year < 1979:
dataset = "reanalysis-era5-single-levels-preliminary-back-extension"
else:
dataset = "reanalysis-era5-single-levels"
print(
f"Retrieving ERA5 {variable_era5} ({variable} input variable) dataset for {year}"
)
c.retrieve(
dataset,
{
"product_type": "reanalysis",
"format": "netcdf",
"variable": variable_era5,
"year": "{:04d}".format(year),
"month": ["{:02d}".format(x) for x in range(1, 13)],
"day": ["{:02d}".format(x) for x in range(1, 32)],
"time": ["{:02d}:00".format(x) for x in range(0, 24)],
"area": [50, -128, 24, -62],
},
os.path.join(directory, variable, f"{variable}s_era5_{year}.nc"),
)
| 8,144 |
def _l2_normalise_rows(t: torch.Tensor):
"""l2-normalise (in place) each row of t: float(n, row_size)"""
t.div_(t.norm(p = 2, dim = 1, keepdim = True).clamp(min = EPSILON))
| 8,145 |
def apply_along_axis(func1d, mat, axis):
"""Numba utility to apply reduction to a given axis."""
assert mat.ndim == 2
assert axis in [0, 1]
if axis == 0:
result = np.empty(mat.shape[1], mat.dtype)
for i in range(len(result)):
result[i, :] = func1d(mat[:, i])
else:
result = np.empty(mat.shape[0], mat.dtype)
for i in range(len(result)):
result[i, :] = func1d(mat[i, :])
return result
| 8,146 |
def get_all_article():
"""
获取所有 文章资讯
---
tags:
- 资讯文章 API
responses:
200:
description: 文章资讯更新成功
404:
description: 资源不存在
500:
description: 服务器异常
"""
articles = ArticleLibrary.get_all()
return jsonify(articles)
| 8,147 |
def cut_fedora_prefix(uri):
"""
Cut the Fedora URI prefix from a URI.
"""
return uri[len(FEDORA_URI_PREFIX):]
| 8,148 |
def get_database_login_connection(user,password,host,database):
""" Return database connection object based on user and database details provided """
connection = psycopg2.connect(user = user,
password = password,
host = host,
port = "5432",
database = database,
sslmode= "prefer")
set_auto_commit(connection)
return connection
| 8,149 |
def getaddrinfo(host,port,family=0,socktype=socket.SOCK_STREAM,proto=0,allow_cname=True):
"""Resolve host and port into addrinfo struct.
Does the same thing as socket.getaddrinfo, but using `pyxmpp.resolver`. This
makes it possible to reuse data (A records from the additional section of
DNS reply) returned with SRV records lookup done using this module.
:Parameters:
- `host`: service domain name.
- `port`: service port number or name.
- `family`: address family.
- `socktype`: socket type.
- `proto`: protocol number or name.
- `allow_cname`: when False CNAME responses are not allowed.
:Types:
- `host`: `unicode` or `str`
- `port`: `int` or `str`
- `family`: `int`
- `socktype`: `int`
- `proto`: `int` or `str`
- `allow_cname`: `bool`
:return: list of (family, socktype, proto, canonname, sockaddr).
:returntype: `list` of (`int`, `int`, `int`, `str`, (`str`, `int`))"""
ret=[]
if proto==0:
proto=socket.getprotobyname("tcp")
elif type(proto)!=int:
proto=socket.getprotobyname(proto)
if type(port)!=int:
port=socket.getservbyname(port,proto)
if family not in (0,socket.AF_INET):
raise NotImplementedError,"Protocol family other than AF_INET not supported, yet"
if ip_re.match(host):
return [(socket.AF_INET,socktype,proto,host,(host,port))]
host=idna.ToASCII(host)
try:
r=dns.resolver.query(host, 'A')
except dns.exception.DNSException:
r=dns.resolver.query(host+".", 'A')
if not allow_cname and r.rrset.name!=dns.name.from_text(host):
raise ValueError,"Unexpected CNAME record found for %s" % (host,)
if r:
for rr in r:
ret.append((socket.AF_INET,socktype,proto,r.rrset.name,(rr.to_text(),port)))
return ret
| 8,150 |
def get_layout_for_dashboard(available_pages_list):
"""
Makes the dictionary that determines the dashboard layout page.
Displays the graphic title to represent the graphic.
:param available_pages_list:
:return:
"""
available_pages_list_copy = copy.deepcopy(available_pages_list)
for available_page_dict in available_pages_list_copy:
graphic_list = available_page_dict[GRAPHIC_CONFIG_FILES]
for graphic_index, graphic_path in enumerate(graphic_list):
graphic_json = json.loads(load_graphic_config_dict(graphic_path))
graphic_list[graphic_index] = {
GRAPHIC_PATH: graphic_path,
GRAPHIC_TITLE: graphic_json[GRAPHIC_TITLE],
}
return available_pages_list_copy
| 8,151 |
def median(list_in):
"""
Calculates the median of the data
:param list_in: A list
:return: float
"""
list_in.sort()
half = int(len(list_in) / 2)
if len(list_in) % 2 != 0:
return float(list_in[half])
elif len(list_in) % 2 ==0:
value = (list_in[half - 1] + list_in[half]) / 2
return float(value)
| 8,152 |
def search_file(expr, path=None, abspath=False, follow_links=False):
"""
Given a search path, recursively descend to find files that match a
regular expression.
Can specify the following options:
path - The directory that is searched recursively
executable_extension - This string is used to see if there is an
implicit extension in the filename
executable - Test if the file is an executable (default=False)
isfile - Test if the file is file (default=True)
"""
ans = []
pattern = re.compile(expr)
if path is None or path == ".":
path = os.getcwd()
elif not os.path.exists(path):
raise IOError, "Unknown directory '"+path+"'"
for root, dirs, files in os.walk(path, topdown=True):
for name in files:
if pattern.match(name):
name = os.path.join(root,name)
if follow_links and os.path.islink(name):
ans.append( os.path.abspath(os.readlink(name)) )
elif abspath:
ans.append( os.path.abspath(name) )
else:
ans.append( name )
return ans
| 8,153 |
def delete_gwlbe(gwlbe_ids):
"""
Deletes VPC Endpoint (GWLB-E).
Accepts:
- gwlbe_ids (list of str): ['vpce-svc-xxxx', 'vpce-svc-yyyy']
Usage:
- delete_gwlbe(['vpce-xxxx', 'vpce-yyyy'])
"""
logging.info("Deleting VPC Endpoint Service:")
try:
response = ec2.delete_vpc_endpoints(
VpcEndpointIds=gwlbe_ids
)
return response
except ClientError as e:
logging.error(e)
return None
| 8,154 |
def subdivide_loop(surface:SurfaceData, number_of_iterations: int = 1) -> SurfaceData:
"""Make a mesh more detailed by subdividing in a loop.
If iterations are high, this can take very long.
Parameters
----------
surface:napari.types.SurfaceData
number_of_iterations:int
See Also
--------
..[0] http://www.open3d.org/docs/0.12.0/tutorial/geometry/mesh.html#Mesh-subdivision
"""
mesh_in = to_mesh(surface)
mesh_out = mesh_in.subdivide_loop(number_of_iterations=number_of_iterations)
return to_surface(mesh_out)
| 8,155 |
def register():
"""Register a new user.
Validates that the username is not already taken. Hashes the
password for security.
"""
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
phone = request.form['full_phone']
channel = request.form['channel']
db = get_db()
error = None
if not username:
error = 'Username is required.'
elif not phone:
error = 'Phone number is required'
elif not password:
error = 'Password is required.'
elif db.execute(
'SELECT id FROM user WHERE username = ?', (username,)
).fetchone() is not None:
error = 'User {0} is already registered.'.format(username)
if error is None:
session['phone'] = phone
vsid = start_verification(phone, channel)
if vsid is not None:
# the verification was sent to the user and the username is valid
# redirect to verification check
db.execute(
'INSERT INTO user (username, password, phone_number) VALUES (?, ?, ?)',
(username, generate_password_hash(password), phone)
)
db.commit()
return redirect(url_for('auth.verify'))
flash(error)
return render_template('auth/register.html')
| 8,156 |
def gen_key():
"""Function to generate a new access key which does not exist already"""
key = ''.join(choice(ascii_letters + digits) for _ in range(16))
folder = storage + key
# Repeat until key generated does not exist
while(os.path.exists(folder)):
key = ''.join(choice(ascii_letters + digits) for _ in range(16))
folder = storage + key
return key
| 8,157 |
async def async_setup_platform(opp, config, add_entities, discovery_info=None):
"""Set up binary sensors."""
if discovery_info is None:
return
sensors = []
for host_config in discovery_info["config"][DOMAIN]:
host_name = host_config["host"]
host_name_coordinators = opp.data[DOMAIN][COORDINATORS][host_name]
if opp.data[PROXMOX_CLIENTS][host_name] is None:
continue
for node_config in host_config["nodes"]:
node_name = node_config["node"]
for vm_id in node_config["vms"]:
coordinator = host_name_coordinators[node_name][vm_id]
coordinator_data = coordinator.data
# unfound vm case
if coordinator_data is None:
continue
vm_name = coordinator_data["name"]
vm_sensor = create_binary_sensor(
coordinator, host_name, node_name, vm_id, vm_name
)
sensors.append(vm_sensor)
for container_id in node_config["containers"]:
coordinator = host_name_coordinators[node_name][container_id]
coordinator_data = coordinator.data
# unfound container case
if coordinator_data is None:
continue
container_name = coordinator_data["name"]
container_sensor = create_binary_sensor(
coordinator, host_name, node_name, container_id, container_name
)
sensors.append(container_sensor)
add_entities(sensors)
| 8,158 |
def double(x):
"""aqui é onde você coloca um docstring (cadeia de caracteres de documentação)
opcional
que explica o que a função faz.
por exemplo, esta função multiplica sua entrada por 2"""
| 8,159 |
def get_url(url, headers=None):
"""
get content from specified URL
"""
reply = requests.get(url, headers=headers)
if reply.status_code != 200:
logging.debug('[get_attribute] Failed to open {0}'.format(url))
return None
else:
return reply.content
| 8,160 |
def Read_FImage(Object, Channel, iFlags=0):
"""
Read_FImage(Object, Channel, iFlags=0) -> bool
Read_FImage(Object, Channel) -> bool
"""
return _Channel.Read_FImage(Object, Channel, iFlags)
| 8,161 |
def Export(message, stream=None, schema_path=None):
"""Writes a message as YAML to a stream.
Args:
message: Message to write.
stream: Output stream, None for writing to a string and returning it.
schema_path: JSON schema file path. If None then all message fields are
written, otherwise only fields in the schema are written.
Returns:
Returns the return value of yaml.dump(). If stream is None then the return
value is the YAML data as a string.
"""
result = _ProtoJsonApiTools.Get().encode_message(message)
message_dict = json.loads(
encoding_helper._IncludeFields(result, message, None))
if schema_path:
_FilterYAML(message_dict, schema_path)
return yaml.dump(message_dict, stream=stream)
| 8,162 |
def user_locale_get(handle, user_name, name, caller="user_locale_get"):
"""
gets locale for the user
Args:
handle (UcsHandle)
user_name (string): username
name (string): locale name
Returns:
AaaUserLocale: managed object
Raises:
UcsOperationError: if AaaUserLocale is not present
Example:
user_locale_get(handle, user_name="test", name="testlocale")
"""
user_dn = _base_dn + "/user-" + user_name
dn = user_dn + "/locale-" + name
mo = handle.query_dn(dn)
if mo is None:
raise UcsOperationError(caller, "User locale '%s' does not exist" % dn)
return mo
| 8,163 |
def get_set_from_dict_from_dict(
instance: Dict[str, Dict[str, List]], field: str
) -> Set[Any]:
"""
Format of template field within payload
Function gets field from instance-dict, which is a dict again.
The values of these dicts have to be joined in a set.
"""
cml = instance.get(field)
if cml:
return reduce(lambda i1, i2: i1 | i2, [set(values) for values in cml.values()])
else:
return set()
| 8,164 |
def initiate_os_session(unscoped: str, project: str) -> keystoneauth1.session.Session:
"""
Create a new openstack session with the unscoped token and project id.
Params:
unscoped: str
project: str
Returns:
A usable keystone session object for OS client connections
Return type:
object(keystoneauth1.session.Session)
"""
os_auth = v3.Token(
auth_url=setd["auth_endpoint_url"], token=unscoped, project_id=project
)
return keystoneauth1.session.Session(
auth=os_auth,
verify=True,
)
| 8,165 |
def test_bv_bad_format():
"""Test that bad formats cause an error."""
raw = _generate_raw()
tmpdir = _mktmpdir()
vhdr_fname = os.path.join(tmpdir, "philistine.vhdr")
vmrk_fname = os.path.join(tmpdir, "philistine.vmrk")
eeg_fname = os.path.join(tmpdir, "philistine.eeg")
# events = np.array([[10, 0, 31]])
assert_raises(ValueError, _write_vhdr_file, vhdr_fname, vmrk_fname,
eeg_fname, raw, orientation='bad')
assert_raises(ValueError, _write_vhdr_file, vhdr_fname, vmrk_fname,
eeg_fname, raw, format='bad')
assert_raises(ValueError, _write_bveeg_file, eeg_fname, raw,
orientation='bad')
assert_raises(ValueError, _write_bveeg_file, eeg_fname, raw,
format='bad')
rmtree(tmpdir)
| 8,166 |
def delete_topic_collection_items(request_ctx, collection_item_id, topic_id, **request_kwargs):
"""
Deletes the discussion topic. This will also delete the assignment, if it's
an assignment discussion.
:param request_ctx: The request context
:type request_ctx: :class:RequestContext
:param collection_item_id: (required) ID
:type collection_item_id: string
:param topic_id: (required) ID
:type topic_id: string
:return: Delete a topic
:rtype: requests.Response (with void data)
"""
path = '/v1/collection_items/{collection_item_id}/discussion_topics/{topic_id}'
url = request_ctx.base_api_url + path.format(collection_item_id=collection_item_id, topic_id=topic_id)
response = client.delete(request_ctx, url, **request_kwargs)
return response
| 8,167 |
def test_metabolomics_dataset_annotate_peaks(test_db, metabolomics_dataset):
"""Uses find_db_hits to try to annotate all unknown peaks in dataset
GIVEN a metabolomics dataset and MINE db
WHEN trying to find hits for every unknown peak in that dataset
THEN make sure all peaks get the correct # of hits
"""
if not test_db.compounds.find_one({"_id": "mass_test"}):
test_db.compounds.insert_one(
{
"_id": "mass_test",
"Mass": 181.007276,
"Charge": 0,
"Formula": "C6H12O2N",
"Generation": 1,
}
)
metabolomics_dataset.annotate_peaks(test_db)
for peak in metabolomics_dataset.unknown_peaks:
if peak.name == "Test1Unknown":
assert len(peak.isomers) == 0
elif peak.name == "Test2Unknown":
assert len(peak.isomers) == 1
| 8,168 |
def xml_section_extract_elsevier(section_root, element_list=None) -> List[ArticleElement]:
"""
Depth-first search of the text in the sections
"""
if element_list is None:
element_list = list()
for child in section_root:
if 'label' in child.tag or 'section-title' in child.tag or 'para' in child.tag:
target_txt = get_xml_text_iter(child)
element_type = None
if 'label' in child.tag:
element_type = ArticleElementType.SECTION_ID
elif 'section-title' in child.tag:
element_type = ArticleElementType.SECTION_TITLE
elif 'para' in child.tag:
element_type = ArticleElementType.PARAGRAPH
element = ArticleElement(type=element_type, content=target_txt)
element_list.append(element)
elif 'section' in child.tag:
xml_section_extract_elsevier(section_root=child, element_list=element_list)
return element_list
| 8,169 |
def get_data_from_string(string, data_type, key=None):
"""
Getting data from string, type can be either int or float or str.
Key is basically starts with necessary string.
Key is need only when we parse strings from execution file
output (not from test.txt)
"""
data = []
if data_type in ("int", "float"):
data = Text.get_numbers(string, type_=data_type)
elif data_type == "str":
if key is None:
data = Text.get_strings_from_tests(string)
else:
data = Text.get_strings_from_exec(string, key)
return data
| 8,170 |
async def on_reaction_remove(reaction, user):
"""Remove user from matchmaking queue based on reaction.
Use the unique match_id present in the message of the appropriate format
and only if the reaction being removed is a thumbs up.
"""
print('reaction removed')
message = reaction.message
content = message.content
if reaction.emoji == "👍" and "Thumbs up to this to join match" in content:
matching = re.match(
r'Thumbs up to this to join match - \"(.*)\"', content)
match_id = matching.group(1)
ctx = await client.get_context(message)
await leave_match(ctx, match_id, user.mention)
| 8,171 |
def greenline(apikey, stop):
"""
Return processed green line data for a stop.
"""
# Only green line trips
filter_route = "Green-B,Green-C,Green-D,Green-E"
# Include vehicle and trip data
include = "vehicle,trip"
# API request
p = {"filter[route]": filter_route, "include": include, "filter[stop]": stop}
result = requests.get("https://api-v3.mbta.com/predictions", params=p).json()
return processGreenlinePredictions(result)
| 8,172 |
def Get_Unread_Messages(service, userId):
"""Retrieves all unread messages with attachments, returns list of message ids.
Args:
service: Authorized Gmail API service instance.
userId: User's email address. The special value "me".
can be used to indicate the authenticated user.
"""
message_list = []
message_ids = service.users().messages().list(userId=userId, labelIds='INBOX', alt="json", q='is:unread has:attachment').execute()
if message_ids['resultSizeEstimate'] > 0:
for message in message_ids['messages']:
message_list.append(message['id'])
return message_list
| 8,173 |
def rmse(y_true, y_pred):
"""
rmse
description:
computes RMSE
"""
return sqrt(mean_squared_error(y_true, y_pred))
| 8,174 |
def doxygen(registry, xml_parent, data):
"""yaml: doxygen
Builds doxygen HTML documentation. Requires the Jenkins
:jenkins-wiki:`Doxygen plugin <Doxygen+Plugin>`.
:arg str doxyfile: The doxyfile path (required)
:arg str install: The doxygen installation to use (required)
:arg bool ignore-failure: Keep executing build even on doxygen generation
failure (default false)
:arg bool unstable-warning: Mark the build as unstable if warnings are
generated (default false)
Example:
.. literalinclude:: /../../tests/builders/fixtures/doxygen001.yaml
:language: yaml
"""
doxygen = XML.SubElement(xml_parent,
'hudson.plugins.doxygen.DoxygenBuilder')
mappings = [
('doxyfile', 'doxyfilePath', None),
('install', 'installationName', None),
('ignore-failure', 'continueOnBuildFailure', False),
('unstable-warning', 'unstableIfWarnings', False)
]
convert_mapping_to_xml(doxygen, data, mappings, fail_required=True)
| 8,175 |
def delete_user(usernames, **boto_options):
"""
Delete specified users, their access keys and their inline policies
s3-credentials delete-user username1 username2
"""
iam = make_client("iam", **boto_options)
for username in usernames:
click.echo("User: {}".format(username))
# Fetch and delete their policies
policy_names_to_delete = list(
paginate(iam, "list_user_policies", "PolicyNames", UserName=username)
)
for policy_name in policy_names_to_delete:
iam.delete_user_policy(
UserName=username,
PolicyName=policy_name,
)
click.echo(" Deleted policy: {}".format(policy_name))
# Fetch and delete their access keys
access_key_ids_to_delete = [
access_key["AccessKeyId"]
for access_key in paginate(
iam, "list_access_keys", "AccessKeyMetadata", UserName=username
)
]
for access_key_id in access_key_ids_to_delete:
iam.delete_access_key(
UserName=username,
AccessKeyId=access_key_id,
)
click.echo(" Deleted access key: {}".format(access_key_id))
iam.delete_user(UserName=username)
click.echo(" Deleted user")
| 8,176 |
def read_model_json(path: Path, model: Type[ModelT]) -> ModelT:
"""
Reading routine. Only keeps Model data
"""
return model.parse_file(path=path)
| 8,177 |
def details(request, id=None):
"""
Show details about alert
:param request:
:param id: alert ID
:return:
"""
alert = get_object_or_404(Alert, id=id)
context = {
"user": request.user,
"alert": alert,
}
return render(request, "alerts/details.html", context)
| 8,178 |
def get_class_id_map():
"""Get mapping between class_id and class_name"""
sql = """
SELECT class_id
, class_name
FROM classes
"""
cur.execute(f"{sql};")
result = [dict(x) for x in cur.fetchall()]
class_map = {}
for r in result:
class_map[r["class_id"]] = r["class_name"]
return class_map
| 8,179 |
def test_cancelAllLinking():
"""Test CancelAllLinking."""
msg = CancelAllLinking()
assert msg.hex == hexmsg(0x02, 0x65)
assert not msg.isack
assert not msg.isnak
assert len(msg.hex) / 2 == msg.sendSize
msg = CancelAllLinking(0x06)
assert msg.hex == hexmsg(0x02, 0x65, 0x06)
assert msg.isack
assert not msg.isnak
assert len(msg.hex) / 2 == msg.receivedSize
msg = CancelAllLinking(0x15)
assert msg.hex == hexmsg(0x02, 0x65, 0x15)
assert not msg.isack
assert msg.isnak
assert len(msg.hex) / 2 == msg.receivedSize
| 8,180 |
def epsilon_nfa_to_nfa(e_nfa: automata.nfa.EpsilonNFA)->automata.nfa.NFA: # todo: add tests
"""
Casts epsilon NFA to NFA.
:param EpsilonNFA e_nfa: original epsilon NFA
:return NFA: cast NFA that takes the same languages.
"""
assert type(e_nfa) is automata.nfa.EpsilonNFA
work = e_nfa.deepcopy()
closure = work.start_state.epsilon_closure # NOT the same as state.indirect_reach
#setting start state as accepting if its' epsilon closure contains an accepting state
for state in closure:
if state.value:
work.start_state.value = 1
break
structure = work.deepcopy()
#hold a structure, but use references from work.
for state in work.states.values():
for single_input in work.inputs - {state.epsilon}:
closure = structure.states[state.name].epsilon_closure
caught_states = set()
for state_of_closure in closure:
# forward = state_of_closure.forward(single_input)
# new_forward = set()
# for one_state in forward:
# new_forward.add(work.states[one_state.name])
caught_states |= state_of_closure.forward(single_input)
state.transitions[single_input] = work.e_closures(*caught_states)
if state.epsilon in state.transitions:
state.transitions.pop(state.epsilon)
for event in work.inputs:
if not state.transitions.get(event, True):
state.transitions.pop(event)
work.inputs.remove(work.epsilon)
for state in work.states:
for event, end_states in work.states[state].transitions.items():
transitions = set()
for end_state in end_states:
transitions.add(work.states[end_state.name])
work.states[state].transitions[event] = transitions
# print(work.states)
return automata.nfa.NFA(work.states, work.inputs, work.start_state)
| 8,181 |
def test_cursor_paginated_searches(collection, session):
"""
Tests that search methods using cursor-pagination are hooked up correctly.
There is no real search logic tested here.
"""
all_runs = [
MaterialRunDataFactory(name="foo_{}".format(i)) for i in range(20)
]
fake_request = make_fake_cursor_request_function(all_runs)
# pretty shady, need to add these methods to the fake session to test their
# interactions with the actual search methods
setattr(session, 'get_resource', fake_request)
setattr(session, 'post_resource', fake_request)
setattr(session, 'cursor_paged_resource', Session.cursor_paged_resource)
assert len(list(collection.list_by_name('unused', per_page=2))) == len(all_runs)
assert len(list(collection.list(per_page=2))) == len(all_runs)
assert len(list(collection.list_by_tag('unused', per_page=2))) == len(all_runs)
assert len(list(collection.list_by_attribute_bounds(
{LinkByUIDFactory(): IntegerBounds(1, 5)}, per_page=2))) == len(all_runs)
# invalid inputs
with pytest.raises(TypeError):
collection.list_by_attribute_bounds([1, 5], per_page=2)
with pytest.raises(NotImplementedError):
collection.list_by_attribute_bounds({
LinkByUIDFactory(): IntegerBounds(1, 5),
LinkByUIDFactory(): IntegerBounds(1, 5),
}, per_page=2)
with pytest.raises(RuntimeError):
collection.dataset_id = None
collection.list_by_name('unused', per_page=2)
| 8,182 |
def test_device_ids(get_system):
"""
This method tests the system device's device_ids() method.
"""
system = get_system
devices = system.device_ids()
connected_devices = []
depthcameras = []
for dev in devices:
check_device_types.check_DeviceID(dev)
if dev['name'] != 'uvccamera':
device = Devices((dev['vendor_id'], dev['product_id']))
connected_devices.append(device)
if dev['name'] == 'depthcamera':
depthcameras.append(device)
# Use the depthcameras to determine what other devices should be present
for camera in depthcameras:
if camera == Devices.depthcamera_g1:
expected_devices = [Devices.depthcamera_g1,
Devices.desklamp,
Devices.hirescamera,
Devices.projector_g1,
Devices.sbuttons,
Devices.touchmat_g1,
]
elif camera == Devices.depthcamera_g2:
expected_devices = [Devices.depthcamera_g2,
Devices.hirescamera,
Devices.projector_g2,
Devices.sbuttons,
Devices.touchmat_g2,
]
elif camera == Devices.depthcamera_z_3d:
expected_devices = [Devices.depthcamera_z_3d,
Devices.hirescamera_z_3d,
]
for item in expected_devices:
assert item in connected_devices
connected_devices.remove(item)
# We didn't add uvccameras to the list, so capturestage should be the
# only other device that could be present.
for item in connected_devices:
assert item == Devices.capturestage
| 8,183 |
def potatoes(p0, w0, p1):
"""
- p1/100 = water1 / water1 + (1 - p0/100) * w0
=> water1 = w0 * p1/100 * (1 - p0/100) / (1 - p1/100)
- dry = w0 * (1 - p0/100)
- w1 = water1 + dry = w0 * (100 - p0) / (100 - p1)
Example:
98/100 = water1 / water1 + (1- 99/100) * 100
water1 = 49
w1 = 49 + 1 = 50
"""
w1 = w0 * (100 - p0) / (100 - p1)
return int(w1)
| 8,184 |
def truncate_results_dir(filter_submitter, backup):
"""Walk result dir and
write a hash of mlperf_log_accuracy.json to accuracy.txt
copy mlperf_log_accuracy.json to a backup location
truncate mlperf_log_accuracy.
"""
for division in list_dir("."):
# we are looking at ./$division, ie ./closed
if division not in ["closed", "open"]:
continue
for submitter in list_dir(division):
# we are looking at ./$division/$submitter, ie ./closed/mlperf_org
if filter_submitter and submitter != filter_submitter:
continue
# process results
for directory in ["results", "compliance"]:
log_path = os.path.join(division, submitter, directory)
if not os.path.exists(log_path):
log.error("no submission in %s", log_path)
continue
for system_desc in list_dir(log_path):
for model in list_dir(log_path, system_desc):
for scenario in list_dir(log_path, system_desc, model):
for test in list_dir(log_path, system_desc, model, scenario):
name = os.path.join(log_path, system_desc, model, scenario)
if directory == "compliance":
name = os.path.join(log_path, system_desc, model, scenario, test)
hash_val = None
acc_path = os.path.join(name, "accuracy")
acc_log = os.path.join(acc_path, "mlperf_log_accuracy.json")
acc_txt = os.path.join(acc_path, "accuracy.txt")
# only TEST01 has an accuracy log
if directory == "compliance" and test != "TEST01":
continue
if not os.path.exists(acc_log):
log.error("%s missing", acc_log)
continue
if not os.path.exists(acc_txt) and directory == "compliance":
# compliance test directory will not have an accuracy.txt file by default
log.info("no accuracy.txt in compliance directory %s", acc_path)
else:
if not os.path.exists(acc_txt):
log.error("%s missing, generate to continue", acc_txt)
continue
with open(acc_txt, "r") as f:
for line in f:
m = re.match(r"^hash=([\w\d]+)$", line)
if m:
hash_val = m.group(1)
break
size = os.stat(acc_log).st_size
if hash_val and size < MAX_ACCURACY_LOG_SIZE:
log.info("%s already has hash and size seems truncated", acc_path)
continue
if backup:
backup_dir = os.path.join(backup, name, "accuracy")
os.makedirs(backup_dir, exist_ok=True)
dst = os.path.join(backup, name, "accuracy", "mlperf_log_accuracy.json")
if os.path.exists(dst):
log.error("not processing %s because %s already exist", acc_log, dst)
continue
shutil.copy(acc_log, dst)
# get to work
hash_val = get_hash(acc_log)
with open(acc_txt, "a", encoding="utf-8") as f:
f.write("hash={0}\n".format(hash_val))
truncate_file(acc_log)
log.info("%s truncated", acc_log)
# No need to iterate on compliance test subdirectories in the results folder
if directory == "results":
break
| 8,185 |
def calc_Cinv_CCGT(CC_size_W, CCGT_cost_data):
"""
Annualized investment costs for the Combined cycle
:type CC_size_W : float
:param CC_size_W: Electrical size of the CC
:rtype InvCa : float
:returns InvCa: annualized investment costs in CHF
..[C. Weber, 2008] C.Weber, Multi-objective design and optimization of district energy systems including
polygeneration energy conversion technologies., PhD Thesis, EPFL
"""
# if the Q_design is below the lowest capacity available for the technology, then it is replaced by the least
# capacity for the corresponding technology from the database
if CC_size_W < CCGT_cost_data['cap_min'][0]:
CC_size_W = CCGT_cost_data['cap_min'][0]
CCGT_cost_data = CCGT_cost_data[
(CCGT_cost_data['cap_min'] <= CC_size_W) & (CCGT_cost_data['cap_max'] > CC_size_W)]
#costs of connection
connection_costs = ngas.calc_Cinv_gas(CC_size_W)
Inv_a = CCGT_cost_data.iloc[0]['a']
Inv_b = CCGT_cost_data.iloc[0]['b']
Inv_c = CCGT_cost_data.iloc[0]['c']
Inv_d = CCGT_cost_data.iloc[0]['d']
Inv_e = CCGT_cost_data.iloc[0]['e']
Inv_IR = (CCGT_cost_data.iloc[0]['IR_%']) / 100
Inv_LT = CCGT_cost_data.iloc[0]['LT_yr']
Inv_OM = CCGT_cost_data.iloc[0]['O&M_%'] / 100
InvC = Inv_a + Inv_b * (CC_size_W) ** Inv_c + (Inv_d + Inv_e * CC_size_W) * log(CC_size_W)
Capex_a_CCGT_USD = (InvC+connection_costs) * (Inv_IR) * (1 + Inv_IR) ** Inv_LT / ((1 + Inv_IR) ** Inv_LT - 1)
Opex_fixed_CCGT_USD = InvC * Inv_OM
Capex_CCGT_USD = InvC
return Capex_a_CCGT_USD, Opex_fixed_CCGT_USD, Capex_CCGT_USD
| 8,186 |
def get_middle_slice_tiles(data, slice_direction):
"""Create a strip of intensity-normalized, square middle slices.
"""
slicer = {"ax": 0, "cor": 1, "sag": 2}
all_data_slicer = [slice(None), slice(None), slice(None)]
num_slices = data.shape[slicer[slice_direction]]
slice_num = int(num_slices / 2)
all_data_slicer[slicer[slice_direction]] = slice_num
middle_slices = data[tuple(all_data_slicer)]
num_slices = middle_slices.shape[2]
slice_tiles = [square_and_normalize_slice(middle_slices[..., mid_slice])
for mid_slice in range(num_slices)]
return slice_tiles
| 8,187 |
def test_add_asset_incomplete_for_asset_json(mocker_http_request, client):
"""
When df-add-assets command is provided valid arguments with valid Contact uuid it should pass
"""
from RiskIQDigitalFootprint import add_assets_command
# Fetching expected raw response from file
with open('TestData/add_and_update_assets_resp.json', encoding='utf-8') as f:
expected_res = json.load(f)
mocker_http_request.return_value = expected_res['taskIncomplete']
# Fetching expected entry context details from file
with open('TestData/add_and_update_assets_custom_ec.json', encoding='utf-8') as f:
expected_custom_ec = json.load(f)
expected_custom_ec = expected_custom_ec['incomplete']
# Fetching expected raw response from file
with open('TestData/add_and_update_assets_asset_json.json', encoding='utf-8') as f:
asset_json_arg = json.load(f)
result = add_assets_command(client, args={'asset_json': asset_json_arg})
assert result.raw_response == expected_res['taskIncomplete']
assert result.outputs == expected_custom_ec
assert result.readable_output == '### The request for adding asset(s) is incomplete.' \
' Reason: An unexpected error occurred.'
assert result.outputs_key_field == 'uuid'
assert result.outputs_prefix == 'RiskIQDigitalFootprint.Task'
| 8,188 |
def function_name():
"""Check if a is a factor of b"""
pass
| 8,189 |
def glewIsSupported(var):
""" Return True if var is valid extension/core pair
Usage: glewIsSupported("GL_VERSION_1_4 GL_ARB_point_sprite")
Note: GLEW API was not well documented and this function was
written in haste so the actual GLEW format for glewIsSupported
might be different.
TODO:
- Only the extension parameter is currently checked. Validate
the core as well. Will likely require scraping opengl docs
for supported functionality
"""
var = re.sub(' +',' ',var)
variables = var.split(' ')
for v in variables:
#if v in GLEW_OGL_INFO[GL_VERSIONS]:
# return True
if v in GLEW_OGL_INFO[GL_EXTENSIONS]:
return True
return False
| 8,190 |
def check_file(file_input, is_json=False, ignore=None):
"""Creates a machine object to process a file of URLs"""
if is_json:
url_machine = url_class.urlAutomationMachine(file_input, is_json, ignore)
url_machine.processFile()
else:
url_machine = url_class.urlAutomationMachine(file_input, False, ignore)
url_machine.processFile()
| 8,191 |
def main(input_filepath, output_filepath):
""" Runs data processing scripts to turn raw data from (../raw) into
cleaned data ready to be analyzed (saved in ../processed).
"""
logger = logging.getLogger(__name__)
logger.info('making data set.')
if not os.path.exists(os.path.join(input_filepath, 'data.zip')):
logger.info("Dataset not already downloaded.")
init_data_dir(input_filepath)
download_dataset(URL, os.path.join(input_filepath, 'data.zip'))
external_dir = os.path.join(*input_filepath.split('/')[:-1], 'external')
download_assets(Geo_URL, os.path.join(external_dir, 'world.json'))
unzip(os.path.join(input_filepath, 'data.zip'))
else:
logger.info('Dataset is already in raw data dir')
| 8,192 |
def example_two():
"""Serve example two page."""
return render_template('public/examples/two.j2')
| 8,193 |
def omegaTurn(r_min, w_row, rows):
"""Determines a path (set of points) representing a omega turn.
The resulting path starts at 0,0 with a angle of 0 deg. (pose = 0,0,0). It
will turn left or right depending on if rows is positive (right turn) or
negative (left turn). Path should be translated and rotated to its proper
position in the field by the calling function.
Parameters
----------
r_min : float
Turning radius of the vehicle.
w_row : float
The width of a row in the field.
rows : int
The number of rows between the current row and the target row
e.g. Vehicle is turning from the mid-point of row i
into the mid-point of row i+N
Returns
----------
path : np.array
[[x1, x2, x3,...]
[y1, y2, y3,...]]
The path that the vehicle is to follow. It is defined by a set of
x,y points.
distance : float
The length of the path that accomplishes the requested pi-turn.
"""
# First check if a omega turn is possible
d = rows * w_row # distance from start path to end path
if rows * w_row > 2 * r_min:
path = np.zeros((0, 0)) # Turn is not possible. Path is empty
distance = np.nan # Distance cannot be calculated
return (path, distance)
if d > 0: # Turn to the right
# Create the starting arc for leaving the path (60 points+endpoint)
# Arc starts at pi/2 and rotates up/back toward 0, angle will be alpha
alpha = np.arccos((r_min + d / 2) / (2 * r_min))
a = np.linspace(np.pi / 2, np.pi / 2 - alpha, 61)
x_start = 0 + r_min * np.cos(a)
y_start = r_min - r_min * np.sin(a)
# Create the final arc for entering the path (60 points+endpoint)
a = np.linspace(-1 * np.pi / 2 + alpha, -1 * np.pi/2, 61)
x_end = 0 + r_min * np.cos(a)
y_end = -1 * d - r_min - r_min * np.sin(a)
# Create bulb section
bulb_center_x = 2 * r_min * np.sqrt(1 -
np.float_power((r_min + d / 2) /
(2 * r_min), 2))
bulb_center_y = -1 * d / 2
a = np.linspace(-1 * np.pi/2 - alpha, np.pi / 2 + alpha, 61)
x_bulb = bulb_center_x + r_min * np.cos(a)
y_bulb = bulb_center_y - r_min * np.sin(a)
else:
# Create the starting arc for leaving the path (60 points+endpoint)
d = d * -1
# Arc starts at pi/2 and rotates up/back toward 0, angle will be alpha
alpha = np.arccos((r_min + d / 2) / (2 * r_min))
a = np.linspace(-1 * np.pi/2, -1 * np.pi / 2 + alpha, 61)
x_start = 0 + r_min * np.cos(a)
y_start = -1 * r_min - r_min * np.sin(a)
# Create the final arc for entering the path (60 points+endpoint)
a = np.linspace(np.pi / 2 - alpha, np.pi / 2, 61)
x_end = 0 + r_min * np.cos(a)
y_end = d + r_min - r_min * np.sin(a)
# Create bulb section
bulb_center_x = 2 * r_min * np.sqrt(1 -
np.float_power((r_min + d / 2) /
(2 * r_min), 2))
bulb_center_y = d / 2
a = np.linspace(np.pi / 2 + alpha, -1 * np.pi/2 - alpha, 61)
x_bulb = bulb_center_x + r_min * np.cos(a)
y_bulb = bulb_center_y - r_min * np.sin(a)
# Connect segments. Each segment repeats the start and end.
x = np.hstack((x_start, x_bulb[1:], x_end[1:]))
y = np.hstack((y_start, y_bulb[1:], y_end[1:]))
path = np.array((x, y))
distance = (4 * alpha + np.pi) * r_min
return path, distance
| 8,194 |
def atomic_call(*funcs):
"""
Call function atomicly
"""
for func in funcs:
if not callable(func):
raise TypeError(f"{func} must be callable!")
func()
| 8,195 |
def sparse_ones(indices, dense_shape, dtype=tf.float32, name="sparse_ones"):
""" Creates a new `SparseTensor` with the given indices having value 1
Args:
indices (`Tensor`): a rank 2 tensor with the `(row,column)` indices for the resulting sparse tensor
dense_shape (`Tensor` or `TensorShape`): the output dense shape
dtype (`tf.DType`): the tensor type for the values
name (`str`): sparse_ones op
Returns:
sp_tensor (`SparseTensor`): a new sparse tensor with values set to 1
"""
with tf.name_scope(name=name):
indices = as_tensor(indices, tf.int64)
dense_shape = as_tensor(dense_shape, tf.int64)
indices_shape = indices.shape
values = tf.ones([indices_shape[0]], dtype)
return tf.SparseTensor(indices, values, dense_shape)
| 8,196 |
def ask(*args: Any, **kwargs: Any) -> Any:
"""Ask a modular question in the statusbar (blocking).
Args:
message: The message to display to the user.
mode: A PromptMode.
default: The default value to display.
text: Additional text to show
option: The option for always/never question answers.
Only available with PromptMode.yesno.
abort_on: A list of signals which abort the question if emitted.
Return:
The answer the user gave or None if the prompt was cancelled.
"""
question = _build_question(*args, **kwargs) # pylint: disable=missing-kwoa
global_bridge.ask(question, blocking=True)
answer = question.answer
question.deleteLater()
return answer
| 8,197 |
def get_sale(this_line, cattle, category):
"""Convert the input into a dictionary, with keys matching
the CSV column headers in the scrape_util module.
"""
cattle = cattle.replace("MARKET","")
cattle = cattle.replace(":","")
cattle = cattle.strip().title()
sale = {'cattle_cattle': cattle}
if bool(re.search("TOWN", str(category))):
for idx,title in enumerate(category):
if title == "TOWN":
sale['consignor_city'] = this_line[idx].strip().title()
if title == "HEAD":
head = this_line[idx]
if '-' in head:
head = head.split('-')[0]
if '/' in head:
head = head.split('/')[0]
sale['cattle_head'] = head
if title == "KIND":
cattle = cattle + ' '+ this_line[idx].title()
sale['cattle_cattle'] = cattle
if title == "WEIGHT":
sale['cattle_avg_weight'] = this_line[idx].replace(",","")
if title == "PRICE":
price = this_line[idx].replace("$","")
price = price.replace(",","")
if bool(re.search("Pairs", cattle)):
sale['cattle_price'] = price
else:
sale['cattle_price_cwt'] = price
else:
sale={}
sale = {k: v.strip() for k, v in sale.items() if v}
return sale
| 8,198 |
def get_request(term, destination, days_input, price_limit, food_preference):
"""
Fetches restaurant information from the Yelp API for a given meal term, meal attribute, destination, number of days of vacation, price limit, and food preference.
Params:
term (str) the specific meal, like "breakfast"
destination (str) the requested destination, like "New York"
days_input (int) the number of days of the vacation, like 3
price_limit (list) the requested list of prices to search going up to the price limit, like [1,2,3] (for $$$)
food_preference (str) the requested food cuisine preferences, like "American, Chinese"
Example:
breakfast_list, lunch_list, dinner_list = get_request(term="breakfast",destination="New York", days_input=3, price_limit=[1,2,3], food_preference="American, Chinese")
Returns the request for a specific meal through "meal_response".
"""
#ACQUIRE API KEY
API_KEY = os.environ.get("YELP_API_KEY")
#Endpoint and headers using API Key
link_endpoint = 'https://api.yelp.com/v3/businesses/search'
link_headers = {'Authorization': 'bearer %s' % API_KEY}
#Read in the inputted parameters for a given meal
meal_parameters = {'term': term,
'limit': days_input, # 1 breakfast per vacation day
'offset': 50, #basically lets you do pages
'price': price_limit, #can change this later
'radius': 10000, #Change later?
'categories': food_preference,
'location': destination,
'attributes': "good_for_" + term,
}
#Make a request to the Yelp API using the correct parameters
meal_response = requests.get(url = link_endpoint,
params = meal_parameters,
headers = link_headers)
print(meal_response)
#Return the request
return meal_response
| 8,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.