content
stringlengths 22
815k
| id
int64 0
4.91M
|
---|---|
def index(a: protocols.SupportsIndex) -> int:
"""
Return _a_ converted to an integer. Equivalent to a.__index__().
Example:
>>> class Index:
... def __index__(self) -> int:
... return 0
>>> [1][Index()]
1
Args:
a:
"""
return operator.index(a)
| 7,500 |
def col_to_num(col_str):
""" Convert base26 column string to number. """
expn = 0
col_num = 0
for char in reversed(col_str):
col_num += (ord(char) - ord('A') + 1) * (26 ** expn)
expn += 1
return col_num
| 7,501 |
def process_chunk(chunk, verbose=False):
"""Return a tuple of chunk kind, task-create links, task-create times, task-leave times and the chunk's graph"""
# Make function for looking up event attributes
get_attr = attr_getter(chunk.attr)
# Unpack events from chunk
(_, (first_event, *events, last_event)), = chunk.items()
if verbose and len(events) > 0:
print(chunk)
# Make the graph representing this chunk
g = ig.Graph(directed=True)
prior_node = g.add_vertex(event=first_event)
# Used to save taskgroup-enter event to match to taskgroup-leave event
taskgroup_enter_event = None
# Match master-enter event to corresponding master-leave
master_enter_event = first_event if get_attr(first_event, 'region_type') == 'master' else None
if chunk.kind == 'parallel':
parallel_id = get_attr(first_event, 'unique_id')
prior_node["parallel_sequence_id"] = (parallel_id, get_attr(first_event, 'endpoint'))
task_create_nodes = deque()
task_links = deque()
task_crt_ts = deque()
task_leave_ts = deque()
if type(first_event) is Enter and get_attr(first_event, 'region_type') in ['initial_task']:
task_crt_ts.append((get_attr(first_event, 'unique_id'), first_event.time))
k = 1
for event in chain(events, (last_event,)):
if get_attr(event, 'region_type') in ['implicit_task']:
if type(event) is Enter:
task_links.append((get_attr(event, 'encountering_task_id'), get_attr(event, 'unique_id')))
task_crt_ts.append((get_attr(event, 'unique_id'), event.time))
elif type(event) is Leave:
task_leave_ts.append((get_attr(event, 'unique_id'), event.time))
continue
# The node representing this event
node = g.add_vertex(event=event)
# Add task-leave time
if type(event) is Leave and get_attr(event, 'region_type') == 'explicit_task':
task_leave_ts.append((get_attr(event, 'unique_id'), event.time))
# Add task links and task crt ts
if (type(event) is Enter and get_attr(event, 'region_type') == 'implicit_task') \
or (type(event) is ThreadTaskCreate):
task_links.append((get_attr(event, 'encountering_task_id'), get_attr(event, 'unique_id')))
task_crt_ts.append((get_attr(event, 'unique_id'), event.time))
# Match taskgroup-enter/-leave events
if get_attr(event, 'region_type') in ['taskgroup']:
if type(event) is Enter:
taskgroup_enter_event = event
elif type(event) is Leave:
if taskgroup_enter_event is None:
raise ValueError("taskgroup-enter event was None")
node['taskgroup_enter_event'] = taskgroup_enter_event
taskgroup_enter_event = None
# Match master-enter/-leave events
if get_attr(event, 'region_type') in ['master']:
if type(event) is Enter:
master_enter_event = event
elif type(event) is Leave:
if master_enter_event is None:
raise ValueError("master-enter event was None")
node['master_enter_event'] = master_enter_event
master_enter_event = None
# Label nodes in a parallel chunk by their position for easier merging
if (chunk.kind == 'parallel'
and type(event) is not ThreadTaskCreate
and get_attr(event, 'region_type') != 'master'):
node["parallel_sequence_id"] = (parallel_id, k)
k += 1
if get_attr(event, 'region_type') == 'parallel':
# Label nested parallel regions for easier merging...
if event is not last_event:
node["parallel_sequence_id"] = (get_attr(event, 'unique_id'), get_attr(event, 'endpoint'))
# ... but distinguish from a parallel chunk's terminating parallel-end event
else:
node["parallel_sequence_id"] = (parallel_id, get_attr(event, 'endpoint'))
# Add edge except for (single begin -> single end) and (parallel N begin -> parallel N end)
if events_bridge_region(prior_node['event'], node['event'], ['single_executor', 'single_other', 'master'], get_attr) \
or (events_bridge_region(prior_node['event'], node['event'], ['parallel'], get_attr)
and get_attr(node['event'], 'unique_id') == get_attr(prior_node['event'], 'unique_id')):
pass
else:
g.add_edge(prior_node, node)
# For task_create add dummy nodes for easier merging
if type(event) is ThreadTaskCreate:
node['task_cluster_id'] = (get_attr(event, 'unique_id'), 'enter')
dummy_node = g.add_vertex(event=event, task_cluster_id=(get_attr(event, 'unique_id'), 'leave'))
task_create_nodes.append(dummy_node)
continue
elif len(task_create_nodes) > 0:
task_create_nodes = deque()
prior_node = node
if chunk.kind == 'explicit_task' and len(events) == 0:
g.delete_edges([0])
# Require at least 1 edge between start and end nodes if there are no internal nodes, except for empty explicit
# task chunks
if chunk.kind != "explicit_task" and len(events) == 0 and g.ecount() == 0:
g.add_edge(g.vs[0], g.vs[1])
return chunk.kind, task_links, task_crt_ts, task_leave_ts, g
| 7,502 |
def delazi_wgs84(lat1, lon1, lat2, lon2):
"""delazi_wgs84(double lat1, double lon1, double lat2, double lon2)"""
return _Math.delazi_wgs84(lat1, lon1, lat2, lon2)
| 7,503 |
def clipped_zoom(x: np.ndarray, zoom_factor: float) -> np.ndarray:
"""
Helper function for zoom blur.
Parameters
----------
x
Instance to be perturbed.
zoom_factor
Zoom strength.
Returns
-------
Cropped and zoomed instance.
"""
h = x.shape[0]
ch = int(np.ceil(h / float(zoom_factor))) # ceil crop height(= crop width)
top = (h - ch) // 2
x = zoom(x[top:top + ch, top:top + ch], (zoom_factor, zoom_factor, 1), order=1)
trim_top = (x.shape[0] - h) // 2 # trim off any extra pixels
return x[trim_top:trim_top + h, trim_top:trim_top + h]
| 7,504 |
def NextFchunk(ea):
"""
Get next function chunk
@param ea: any address
@return: the starting address of the next function chunk or BADADDR
@note: This function enumerates all chunks of all functions in the database
"""
func = idaapi.get_next_fchunk(ea)
if func:
return func.startEA
else:
return BADADDR
| 7,505 |
def test_private_access_through_object(enable_accessify):
"""
Case: access to the private member through member's class object.
Expect: inaccessible due to its protection level error message.
"""
car = CarWithPrivateEngine()
expected_error_message = INACCESSIBLE_DUE_TO_ITS_PROTECTION_LEVEL_EXCEPTION_MESSAGE.format(
class_name=CarWithPrivateEngine.__name__, class_method_name='start_engine',
)
with pytest.raises(InaccessibleDueToItsProtectionLevelException) as error:
car.start_engine()
assert expected_error_message == error.value.message
| 7,506 |
def draw():
"""Render everything on the screen once per frame"""
# Clear the screen first
screen.clear() # noqa: F821
# Set the background color to pink
screen.fill("pink") # noqa: F821
# Draw the player
player.draw()
# Draw the remaining coins
for coin in coin_list:
coin.draw()
# Draw the current score at the bottom
screen.draw.text( # noqa: F821
f"Score: {score}",
(50, HEIGHT - 50),
fontsize=48,
color="black",
)
| 7,507 |
def share_to_group(request, repo, group, permission):
"""Share repo to group with given permission.
"""
repo_id = repo.id
group_id = group.id
from_user = request.user.username
if is_org_context(request):
org_id = request.user.org.org_id
group_repo_ids = seafile_api.get_org_group_repoids(org_id, group.id)
else:
group_repo_ids = seafile_api.get_group_repoids(group.id)
if repo.id in group_repo_ids:
return False
try:
if is_org_context(request):
org_id = request.user.org.org_id
seafile_api.add_org_group_repo(repo_id, org_id, group_id,
from_user, permission)
else:
seafile_api.set_group_repo(repo_id, group_id, from_user,
permission)
return True
except Exception as e:
logger.error(e)
return False
| 7,508 |
def test_get_os_platform_windows():
"""Get platform from a patched Windows machine."""
with patch("platform.system", return_value="Windows"):
with patch("platform.release", return_value="10"):
with patch("platform.machine", return_value="AMD64"):
os_platform = get_os_platform()
assert os_platform.system == "Windows"
assert os_platform.release == "10"
assert os_platform.machine == "AMD64"
| 7,509 |
def change_config(python, backend, cheatsheet, asciiart):
"""
Show/update configuration (Python, Backend, Cheatsheet, ASCIIART).
"""
asciiart_file = "suppress_asciiart"
cheatsheet_file = "suppress_cheatsheet"
python_file = 'PYTHON_MAJOR_MINOR_VERSION'
backend_file = 'BACKEND'
if asciiart is not None:
if asciiart:
delete_cache(asciiart_file)
console.print('[bright_blue]Enable ASCIIART![/]')
else:
touch_cache_file(asciiart_file)
console.print('[bright_blue]Disable ASCIIART![/]')
if cheatsheet is not None:
if cheatsheet:
delete_cache(cheatsheet_file)
console.print('[bright_blue]Enable Cheatsheet[/]')
elif cheatsheet is not None:
touch_cache_file(cheatsheet_file)
console.print('[bright_blue]Disable Cheatsheet[/]')
if python is not None:
write_to_cache_file(python_file, python)
console.print(f'[bright_blue]Python default value set to: {python}[/]')
if backend is not None:
write_to_cache_file(backend_file, backend)
console.print(f'[bright_blue]Backend default value set to: {backend}[/]')
def get_status(file: str):
return "disabled" if check_if_cache_exists(file) else "enabled"
console.print()
console.print("[bright_blue]Current configuration:[/]")
console.print()
console.print(f"[bright_blue]* Python: {read_from_cache_file(python_file)}[/]")
console.print(f"[bright_blue]* Backend: {read_from_cache_file(backend_file)}[/]")
console.print(f"[bright_blue]* ASCIIART: {get_status(asciiart_file)}[/]")
console.print(f"[bright_blue]* Cheatsheet: {get_status(cheatsheet_file)}[/]")
console.print()
| 7,510 |
def get_memcached_usage(socket=None):
"""
Returns memcached statistics.
:param socket: Path to memcached's socket file.
"""
cmd = 'echo \'stats\' | nc -U {0}'.format(socket)
output = getoutput(cmd)
curr_items = None
bytes_ = None
rows = output.split('\n')[:-1]
for row in rows:
row = row.split()
if row[1] == 'curr_items':
curr_items = int(row[2])
if row[1] == 'bytes':
bytes_ = int(row[2])
return (bytes_, curr_items)
| 7,511 |
def list_installed(executable=None):
"""
List installed resources
"""
resmgr = OcrdResourceManager()
ret = []
for executable, reslist in resmgr.list_installed(executable):
print_resources(executable, reslist, resmgr)
| 7,512 |
def _process_video_files(name, filenames, labels, num_shards):
"""Process and save list of images as TFRecord of Example protos.
Args:
name: string, unique identifier specifying the data set
filenames: list of strings; each string is a path to an image file
texts: list of strings; each string is human readable, e.g. 'dog'
labels: list of integer; each integer identifies the ground truth
num_shards: integer number of shards for this data set.
"""
assert len(filenames) == len(labels)
# Break all images into batches with a [ranges[i][0], ranges[i][1]].
spacing = np.linspace(0, len(filenames), FLAGS.num_threads + 1).astype(np.int)
ranges = []
for i in range(len(spacing) - 1):
ranges.append([spacing[i], spacing[i + 1]])
# Launch a thread for each batch.
print('Launching %d threads for spacings: %s' % (FLAGS.num_threads, ranges))
sys.stdout.flush()
# Create a mechanism for monitoring when all threads are finished.
coord = tf.train.Coordinator()
# Create a generic TensorFlow-based utility for converting all image codings.
coder = ImageCoder()
threads = []
for thread_index in range(len(ranges)):
args = (coder, thread_index, ranges, name, filenames,
labels, num_shards)
t = threading.Thread(target=_process_video_files_batch, args=args)
threads.append(t)
for t in threads:
t.setDaemon(True)
t.start()
# Wait for all the threads to terminate.
coord.join(threads)
print('%s: Finished writing all %d images in data set.' %
(datetime.now(), len(filenames)))
sys.stdout.flush()
| 7,513 |
def dataset_config():
"""Return a DatasetConfig for testing."""
return hubs.DatasetConfig(factory=Dataset, flag=True)
| 7,514 |
def combinations():
"""Produce all the combinations for different items."""
combined = itertools.combinations('ABC', r=2)
combined = [''.join(possibility) for possibility in combined]
return combined
| 7,515 |
def setup(hass, config):
"""Create a Honeywell (EMEA/EU) evohome CH/DHW system.
One controller with 0+ heating zones (e.g. TRVs, relays) and, optionally, a
DHW controller. Does not work for US-based systems.
"""
evo_data = hass.data[DATA_EVOHOME] = {}
evo_data['timers'] = {}
evo_data['params'] = dict(config[DOMAIN])
evo_data['params'][CONF_SCAN_INTERVAL] = SCAN_INTERVAL_DEFAULT
from evohomeclient2 import EvohomeClient
_LOGGER.debug("setup(): API call [4 request(s)]: client.__init__()...")
try:
# There's a bug in evohomeclient2 v0.2.7: the client.__init__() sets
# the root loglevel when EvohomeClient(debug=?), so remember it now...
log_level = logging.getLogger().getEffectiveLevel()
client = EvohomeClient(
evo_data['params'][CONF_USERNAME],
evo_data['params'][CONF_PASSWORD],
debug=False
)
# ...then restore it to what it was before instantiating the client
logging.getLogger().setLevel(log_level)
except HTTPError as err:
if err.response.status_code == HTTP_BAD_REQUEST:
_LOGGER.error(
"Failed to establish a connection with evohome web servers, "
"Check your username (%s), and password are correct."
"Unable to continue. Resolve any errors and restart HA.",
evo_data['params'][CONF_USERNAME]
)
return False # unable to continue
raise # we dont handle any other HTTPErrors
finally: # Redact username, password as no longer needed.
evo_data['params'][CONF_USERNAME] = 'REDACTED'
evo_data['params'][CONF_PASSWORD] = 'REDACTED'
evo_data['client'] = client
# Redact any installation data we'll never need.
if client.installation_info[0]['locationInfo']['locationId'] != 'REDACTED':
for loc in client.installation_info:
loc['locationInfo']['streetAddress'] = 'REDACTED'
loc['locationInfo']['city'] = 'REDACTED'
loc['locationInfo']['locationOwner'] = 'REDACTED'
loc[GWS][0]['gatewayInfo'] = 'REDACTED'
# Pull down the installation configuration.
loc_idx = evo_data['params'][CONF_LOCATION_IDX]
try:
evo_data['config'] = client.installation_info[loc_idx]
except IndexError:
_LOGGER.warning(
"setup(): Parameter '%s' = %s , is outside its range (0-%s)",
CONF_LOCATION_IDX,
loc_idx,
len(client.installation_info) - 1
)
return False # unable to continue
evo_data['status'] = {}
if _LOGGER.isEnabledFor(logging.DEBUG):
tmp_loc = dict(evo_data['config'])
tmp_loc['locationInfo']['postcode'] = 'REDACTED'
tmp_tcs = tmp_loc[GWS][0][TCS][0]
if 'zones' in tmp_tcs:
tmp_tcs['zones'] = '...'
if 'dhw' in tmp_tcs:
tmp_tcs['dhw'] = '...'
_LOGGER.debug("setup(), location = %s", tmp_loc)
load_platform(hass, 'climate', DOMAIN)
return True
| 7,516 |
def test_api_keys(enter_password, config):
"""
Test creating, revoking, expiring API keys.
Test that they have appropriate scope-limited access.
"""
# Make alice an admin. Leave bob as a user.
config["authentication"]["tiled_admins"] = [{"provider": "toy", "id": "alice"}]
with enter_password("secret1"):
admin_client = from_config(config, username="alice", token_cache={})
with enter_password("secret2"):
user_client = from_config(config, username="bob", token_cache={})
# Make and use an API key. Check that latest_activity is updated.
user_key_info = user_client.context.create_api_key()
assert user_key_info["latest_activity"] is None # never used
user_client_from_key = from_config(config, api_key=user_key_info["secret"])
# Check that api_key property is set.
assert user_client_from_key.context.api_key == user_key_info["secret"]
# Use the key for a couple requests and see that latest_activity becomes set and then increases.
user_client_from_key["A1"]
key_activity1 = user_client_from_key.context.which_api_key()["latest_activity"]
principal_activity1 = user_client_from_key.context.whoami()["latest_activity"]
assert key_activity1 is not None
time.sleep(2) # Ensure time resolution (1 second) has ticked up.
user_client_from_key["A1"]
key_activity2 = user_client_from_key.context.which_api_key()["latest_activity"]
principal_activity2 = user_client_from_key.context.whoami()["latest_activity"]
assert key_activity2 > key_activity1
assert principal_activity2 > principal_activity1
assert len(user_client_from_key.context.whoami()["api_keys"]) == 1
# Unset the API key.
secret = user_client_from_key.context.api_key
user_client_from_key.context.api_key = None
with pytest.raises(RuntimeError):
user_client_from_key.context.which_api_key()
# Set the API key.
user_client_from_key.context.api_key = secret
# Now this works again.
user_client_from_key.context.which_api_key()
# Request a key with reduced scope that cannot read metadata.
admin_key_info = admin_client.context.create_api_key(scopes=["metrics"])
with fail_with_status_code(401):
from_config(config, api_key=admin_key_info["secret"])
# Request a key with reduced scope that can *only* read metadata.
admin_key_info = admin_client.context.create_api_key(scopes=["read:metadata"])
restricted_client = from_config(config, api_key=admin_key_info["secret"])
restricted_client["A1"]
with fail_with_status_code(401):
restricted_client["A1"].read() # no 'read:data' scope
# Try to request a key with more scopes that the user has.
with fail_with_status_code(400):
user_client.context.create_api_key(scopes=["admin:apikeys"])
# Create and revoke key.
user_key_info = user_client.context.create_api_key(note="will revoke soon")
assert len(user_client_from_key.context.whoami()["api_keys"]) == 2
# There should now be two keys, one from above and this new one, with our note.
for api_key in user_client_from_key.context.whoami()["api_keys"]:
if api_key["note"] == "will revoke soon":
break
else:
assert False, "No api keys had a matching note."
# Revoke the new key.
user_client_from_key.context.revoke_api_key(user_key_info["first_eight"])
with fail_with_status_code(401):
from_config(config, api_key=user_key_info["secret"])
assert len(user_client_from_key.context.whoami()["api_keys"]) == 1
# Create a key with a very short lifetime.
user_key_info = user_client.context.create_api_key(
note="will expire very soon", expires_in=1
) # units: seconds
time.sleep(2)
with fail_with_status_code(401):
from_config(config, api_key=user_key_info["secret"])
| 7,517 |
def _check_valid_settings_for_input(input_value: Any, pivot_reg: PivotRegistration):
"""Check input against settings in `pivot_reg`."""
# Must have one of these specified
if not (pivot_reg.func_df_col_param_name or pivot_reg.func_input_value_arg):
raise ValueError(
"A value for one of 'func_df_col_param_name' ",
"or 'func_input_value_arg' must be given",
)
# If the function accepts only value type and cannot iterate. Make sure
# that the input_value is a simple value
if pivot_reg.input_type == "value":
if not pivot_reg.func_input_value_arg:
raise ValueError("No value for pivot func input argument was given")
if not pivot_reg.can_iterate and (
isinstance(input_value, pd.DataFrame)
or (
# pylint: disable=isinstance-second-argument-not-valid-type
isinstance(input_value, pd.DataFrame)
and not isinstance(input_value, str)
# pylint: enable=isinstance-second-argument-not-valid-type
)
):
raise ValueError(
f"This function does not accept inputs of {type(input_value)}"
)
| 7,518 |
def geo_exps_MD(n_nodes, radius, l_0, l_1, K=40, thinRatio=1,
gammas=10, max_iter=100, nSamp=50, Niid=1, seed=0):
"""Solves the Connected Subgraph Detection problem and calculates AUC using
Mirror Descent Optimisation for a random geometric graph.
Parameters
----------
n_nodes : int
Number of nodes for the random graph.
radius : float
Distance threshold value.
l_0 : float
Base rate.
l_1 : float
Anomalous rate.
K : int
Anomaly size.
thinRatio : float
Ratio of max semi axis length to min semi axis length. Determines if graph is an ellipsoid or a sphere.
gammas : int or np.array
Conductance rates.
max_iter : int
Number of iterations.
nSamp : int
Number of samples.
Niid : int
Number of iid runs.
seed : int
Random seed.
Returns
-------
scores_noise : np.array
List of shape (nSamp, gammas_n) with AUC scores of optimisation.
"""
graph = Geo_graph_3d(n_nodes=n_nodes, radius=radius, seed=seed)
A, pts = graph.Adj, graph.pos_array
if type(gammas) == int:
gammas = np.logspace(-3, np.log10(2), gammas)
gammas_n = gammas.shape[0]
yy, S = genMeasurements(pts, K, l_0, l_1, nSamp, thinRatio)
s = S[0]
scores_noise = np.zeros((Niid, nSamp, gammas_n), dtype='float32')
for niid in range(Niid):
print('No of iid run: {}'.format(niid+1))
scores = np.zeros((nSamp, gammas_n))
with trange(nSamp, ncols=100) as tqdm:
for ns in tqdm:
ys = yy[:,ns]
c = ys / np.linalg.norm(ys) * np.sqrt(ys.shape[0])
C = c.reshape(-1,1) @ c.reshape(1,-1)
for gind in range(gammas_n):
tqdm.set_description('MD || Run = {} gamma = {:2f}'.format(niid+1, gammas[gind]))
M = runOpt_md(A=A, C=C, gamma=gammas[gind], s=s, max_iter=max_iter)
scores[ns, gind] = np.trace(ys.reshape(-1,1) @ ys.reshape(1,-1) @ M)
tqdm.set_postfix(Loss='{:8f}'.format(np.trace(C.T @ M)))
scores_noise[niid] = scores
return scores_noise.mean(0)
| 7,519 |
def validate_sig_integrity(signer_info: cms.SignedData,
cert: x509.Certificate,
expected_content_type: str,
actual_digest: bytes) -> Tuple[bool, bool]:
"""
Validate the integrity of a signature for a particular signerInfo object
inside a CMS signed data container.
.. warning::
This function does not do any trust checks, and is considered
"dangerous" API because it is easy to misuse.
:param signer_info:
A :class:`cms.SignerInfo` object.
:param cert:
The signer's certificate.
.. note::
This function will not attempt to extract certificates from
the signed data.
:param expected_content_type:
The expected value for the content type attribute (as a Python string,
see :class:`cms.ContentType`).
:param actual_digest:
The actual digest to be matched to the message digest attribute.
:return:
A tuple of two booleans. The first indicates whether the provided
digest matches the value in the signed attributes.
The second indicates whether the signature of the digest is valid.
"""
signature_algorithm: cms.SignedDigestAlgorithm = \
signer_info['signature_algorithm']
digest_algorithm_obj = signer_info['digest_algorithm']
md_algorithm = digest_algorithm_obj['algorithm'].native
signature = signer_info['signature'].native
# signed_attrs comes with some context-specific tagging.
# We need to re-tag it with a universal SET OF tag.
signed_attrs = signer_info['signed_attrs'].untag()
if not signed_attrs:
embedded_digest = None
prehashed = True
signed_data = actual_digest
else:
prehashed = False
# check the CMSAlgorithmProtection attr, if present
try:
cms_algid_protection, = find_cms_attribute(
signed_attrs, 'cms_algorithm_protection'
)
signed_digest_algorithm = \
cms_algid_protection['digest_algorithm'].native
if signed_digest_algorithm != digest_algorithm_obj.native:
raise SignatureValidationError(
"Digest algorithm does not match CMS algorithm protection "
"attribute."
)
signed_sig_algorithm = \
cms_algid_protection['signature_algorithm'].native
if signed_sig_algorithm is None:
raise SignatureValidationError(
"CMS algorithm protection attribute not valid for signed "
"data"
)
elif signed_sig_algorithm != signature_algorithm.native:
raise SignatureValidationError(
"Signature mechanism does not match CMS algorithm "
"protection attribute."
)
except KeyError:
pass
except SignatureValidationError:
raise
except ValueError:
raise SignatureValidationError(
'Multiple CMS protection attributes present'
)
try:
content_type, = find_cms_attribute(signed_attrs, 'content_type')
content_type = content_type.native
if content_type != expected_content_type:
raise SignatureValidationError(
f'Content type {content_type} did not match expected value '
f'{expected_content_type}'
)
except SignatureValidationError:
raise
except (KeyError, ValueError):
raise SignatureValidationError(
'Content type not found in signature, or multiple content-type '
'attributes present.'
)
try:
embedded_digest, = find_cms_attribute(
signed_attrs, 'message_digest'
)
embedded_digest = embedded_digest.native
except (KeyError, ValueError):
raise SignatureValidationError(
'Message digest not found in signature, or multiple message '
'digest attributes present.'
)
signed_data = signed_attrs.dump()
try:
_validate_raw(
signature, signed_data, cert, signature_algorithm, md_algorithm,
prehashed=prehashed
)
valid = True
except InvalidSignature:
valid = False
intact = (
actual_digest == embedded_digest
if embedded_digest is not None else valid
)
return intact, valid
| 7,520 |
def linemod_dpt(path):
"""
read a depth image
@return uint16 image of distance in [mm]"""
dpt = open(path, "rb")
rows = np.frombuffer(dpt.read(4), dtype=np.int32)[0]
cols = np.frombuffer(dpt.read(4), dtype=np.int32)[0]
return (np.fromfile(dpt, dtype=np.uint16).reshape((rows, cols)) / 1000.).astype(np.float32)
| 7,521 |
def findNode(nodes: Iterable[AstNode], name: str) -> Optional[SExpr]:
"""
Finds a node with given name in a list of nodes
"""
for node in nodes:
if isinstance(node, Atom):
continue
if len(node.items) == 0:
continue
nameNode = node.items[0]
if isinstance(nameNode, Atom) and nameNode.value == name:
return node
return None
| 7,522 |
def test_repository_to_branches(neo4j_session):
"""
Ensure that repositories are connected to branches.
"""
_ensure_local_neo4j_has_test_repositories_data(neo4j_session)
query = """
MATCH(branch:GitHubBranch)<-[:BRANCH]-(repo:GitHubRepository{id:{RepositoryId}})
RETURN branch.name, repo.id, repo.name
"""
expected_repository_id = 'https://fake.github.net/graphql/:MDEwOlJlcG9zaXRvcnkxNg=='
nodes = neo4j_session.run(
query,
RepositoryId=expected_repository_id,
)
actual_nodes = {
(
n['branch.name'],
n['repo.id'],
n['repo.name'],
) for n in nodes
}
expected_nodes = {
(
'master',
'https://fake.github.net/graphql/:MDEwOlJlcG9zaXRvcnkxNg==',
'pythontestlib',
),
}
assert actual_nodes == expected_nodes
| 7,523 |
def search(keywords=None, servicetype=None, waveband=None):
"""
execute a simple query to the RegTAP registry.
Parameters
----------
keywords : list of str
keyword terms to match to registry records.
Use this parameter to find resources related to a
particular topic.
servicetype : str
the service type to restrict results to.
Allowed values include
'conesearch',
'sia' ,
'ssa',
'slap',
'tap'
waveband : str
the name of a desired waveband; resources returned
will be restricted to those that indicate as having
data in that waveband. Allowed values include
'radio',
'millimeter',
'infrared',
'optical',
'uv',
'euv',
'x-ray'
'gamma-ray'
Returns
-------
RegistryResults
a container holding a table of matching resource (e.g. services)
See Also
--------
RegistryResults
"""
if not any((keywords, servicetype, waveband)):
raise dalq.DALQueryError(
"No search parameters passed to registry search")
joins = set(["rr.interface"])
joins = set(["rr.resource"])
wheres = list()
if keywords:
joins.add("rr.res_subject")
joins.add("rr.resource")
wheres.extend(["({})".format(" AND ".join("""
(
1=ivo_nocasematch(res_subject, '%{0}%') OR
1=ivo_hasword(res_description, '{0}') OR
1=ivo_hasword(res_title, '{0}')
)""".format(tap.escape(keyword)) for keyword in keywords
))])
if servicetype:
servicetype = _service_type_map.get(servicetype, servicetype)
joins.add("rr.interface")
wheres.append("standard_id LIKE 'ivo://ivoa.net/std/{}%'".format(
tap.escape(servicetype)))
wheres.append("intf_type = 'vs:paramhttp'")
else:
wheres.append("""(
standard_id LIKE 'ivo://ivoa.net/std/conesearch%' OR
standard_id LIKE 'ivo://ivoa.net/std/sia%' OR
standard_id LIKE 'ivo://ivoa.net/std/ssa%' OR
standard_id LIKE 'ivo://ivoa.net/std/slap%' OR
standard_id LIKE 'ivo://ivoa.net/std/tap%'
)""")
if waveband:
joins.add("rr.resource")
wheres.append("1 = ivo_hashlist_has('{}', waveband)".format(
tap.escape(waveband)))
query = """SELECT DISTINCT rr.interface.*, rr.capability.*, rr.resource.*
FROM rr.capability
{}
{}
""".format(
''.join("NATURAL JOIN {} ".format(j) for j in joins),
("WHERE " if wheres else "") + " AND ".join(wheres)
)
service = tap.TAPService(REGISTRY_BASEURL)
query = tap.TAPQuery(service.baseurl, query, maxrec=service.hardlimit)
query.RESULTS_CLASS = RegistryResults
return query.execute()
| 7,524 |
def shadingLightRelCtx(*args, **kwargs):
"""
This command creates a context that can be used for associating lights to shading groups. You can put the context into
shading-centric mode by using the -shadingCentric flag and specifying true. This means that the shading group is
selected first then lights associated with the shading group are highlighted. Subsequent selections result in
assignments. Specifying -shadingCentric false means that the light is to be selected first. The shading groups
associated with the light will then be selected and subsequent selections will result in assignments being made.
Flags:
- exists : ex (bool) [create]
Returns true or false depending upon whether the specified object exists. Other flags are ignored.
- history : ch (bool) [create]
If this is a tool command, turn the construction history on for the tool in question.
- image1 : i1 (unicode) [create,query,edit]
First of three possible icons representing the tool associated with the context.
- image2 : i2 (unicode) [create,query,edit]
Second of three possible icons representing the tool associated with the context.
- image3 : i3 (unicode) [create,query,edit]
Third of three possible icons representing the tool associated with the context.
- name : n (unicode) [create]
If this is a tool command, name the tool appropriately.
- offCommand : ofc (unicode) [create,query,edit]
command to be issued when context is turned on
- onCommand : onc (unicode) [create,query,edit]
command to be issued when context is turned on
- shadingCentric : s (bool) [create,query,edit]
shading-centric mode. Flag can have multiple arguments, passed either as a tuple or a list.
Derived from mel command `maya.cmds.shadingLightRelCtx`
"""
pass
| 7,525 |
def describe_data_sources(FilterVariable=None, EQ=None, GT=None, LT=None, GE=None, LE=None, NE=None, Prefix=None, SortOrder=None, NextToken=None, Limit=None):
"""
Returns a list of DataSource that match the search criteria in the request.
See also: AWS API Documentation
:example: response = client.describe_data_sources(
FilterVariable='CreatedAt'|'LastUpdatedAt'|'Status'|'Name'|'DataLocationS3'|'IAMUser',
EQ='string',
GT='string',
LT='string',
GE='string',
LE='string',
NE='string',
Prefix='string',
SortOrder='asc'|'dsc',
NextToken='string',
Limit=123
)
:type FilterVariable: string
:param FilterVariable: Use one of the following variables to filter a list of DataSource :
CreatedAt - Sets the search criteria to DataSource creation dates.
Status - Sets the search criteria to DataSource statuses.
Name - Sets the search criteria to the contents of DataSource **** Name .
DataUri - Sets the search criteria to the URI of data files used to create the DataSource . The URI can identify either a file or an Amazon Simple Storage Service (Amazon S3) bucket or directory.
IAMUser - Sets the search criteria to the user account that invoked the DataSource creation.
:type EQ: string
:param EQ: The equal to operator. The DataSource results will have FilterVariable values that exactly match the value specified with EQ .
:type GT: string
:param GT: The greater than operator. The DataSource results will have FilterVariable values that are greater than the value specified with GT .
:type LT: string
:param LT: The less than operator. The DataSource results will have FilterVariable values that are less than the value specified with LT .
:type GE: string
:param GE: The greater than or equal to operator. The DataSource results will have FilterVariable values that are greater than or equal to the value specified with GE .
:type LE: string
:param LE: The less than or equal to operator. The DataSource results will have FilterVariable values that are less than or equal to the value specified with LE .
:type NE: string
:param NE: The not equal to operator. The DataSource results will have FilterVariable values not equal to the value specified with NE .
:type Prefix: string
:param Prefix: A string that is found at the beginning of a variable, such as Name or Id .
For example, a DataSource could have the Name 2014-09-09-HolidayGiftMailer . To search for this DataSource , select Name for the FilterVariable and any of the following strings for the Prefix :
2014-09
2014-09-09
2014-09-09-Holiday
:type SortOrder: string
:param SortOrder: A two-value parameter that determines the sequence of the resulting list of DataSource .
asc - Arranges the list in ascending order (A-Z, 0-9).
dsc - Arranges the list in descending order (Z-A, 9-0).
Results are sorted by FilterVariable .
:type NextToken: string
:param NextToken: The ID of the page in the paginated results.
:type Limit: integer
:param Limit: The maximum number of DataSource to include in the result.
:rtype: dict
:return: {
'Results': [
{
'DataSourceId': 'string',
'DataLocationS3': 'string',
'DataRearrangement': 'string',
'CreatedByIamUser': 'string',
'CreatedAt': datetime(2015, 1, 1),
'LastUpdatedAt': datetime(2015, 1, 1),
'DataSizeInBytes': 123,
'NumberOfFiles': 123,
'Name': 'string',
'Status': 'PENDING'|'INPROGRESS'|'FAILED'|'COMPLETED'|'DELETED',
'Message': 'string',
'RedshiftMetadata': {
'RedshiftDatabase': {
'DatabaseName': 'string',
'ClusterIdentifier': 'string'
},
'DatabaseUserName': 'string',
'SelectSqlQuery': 'string'
},
'RDSMetadata': {
'Database': {
'InstanceIdentifier': 'string',
'DatabaseName': 'string'
},
'DatabaseUserName': 'string',
'SelectSqlQuery': 'string',
'ResourceRole': 'string',
'ServiceRole': 'string',
'DataPipelineId': 'string'
},
'RoleARN': 'string',
'ComputeStatistics': True|False,
'ComputeTime': 123,
'FinishedAt': datetime(2015, 1, 1),
'StartedAt': datetime(2015, 1, 1)
},
],
'NextToken': 'string'
}
:returns:
PENDING - Amazon Machine Learning (Amazon ML) submitted a request to create a DataSource .
INPROGRESS - The creation process is underway.
FAILED - The request to create a DataSource did not run to completion. It is not usable.
COMPLETED - The creation process completed successfully.
DELETED - The DataSource is marked as deleted. It is not usable.
"""
pass
| 7,526 |
def copyFile(filename, sourceDir, targetDir, renameTo=None, silent=True):
""" Copy file from sourceDir to targetDir.
"""
if renameTo == None: renameTo = filename
fullname_source = os.path.join(sourceDir, filename)
fullname_target = os.path.join(targetDir, renameTo)
shutil.copy(fullname_source, fullname_target)
if silent==False:
print("File "+fullname_source+" copied to "+source_dir)
| 7,527 |
def _get_credentials(vcap_services, service_name=None):
"""Retrieves the credentials of the VCAP Service of the specified `service_name`. If
`service_name` is not specified, it takes the information from STREAMING_ANALYTICS_SERVICE_NAME environment
variable.
Args:
vcap_services (dict): A dict representation of the VCAP Services information.
service_name (str): One of the service name stored in `vcap_services`
Returns:
dict: A dict representation of the credentials.
Raises:
ValueError: Cannot find `service_name` in `vcap_services`
"""
service_name = service_name or os.environ.get('STREAMING_ANALYTICS_SERVICE_NAME', None)
# Get the service corresponding to the SERVICE_NAME
services = vcap_services['streaming-analytics']
creds = None
for service in services:
if service['name'] == service_name:
creds = service['credentials']
break
# If no corresponding service is found, error
if creds is None:
raise ValueError("Streaming Analytics service " + str(service_name) + " was not found in VCAP_SERVICES")
return creds
| 7,528 |
def all_are_independent_from_all(program, xs, ys):
"""
Returns true iff all xs are statistially independent from all ys, where the xs are from the current iteration
and the ys are from the previous iteration.
"""
for x in xs:
if not is_independent_from_all(program, x, ys):
return False
return True
| 7,529 |
def save_file(window, txt_edit, event=False):
# print(txt_edit.get(1.0, tk.END))
"""Save the current file as a new file."""
filepath = asksaveasfilename(
defaultextension="txt",
filetypes=[("Text Files", "*.txt"), ("All Files", "*.*")],
)
if not filepath:
return
with open(filepath, "w") as output_file:
text = txt_edit.get(1.0, tk.END)
output_file.write(text)
window.title(f"Текстовый редактор - {filepath}")
| 7,530 |
def get_exc_short():
"""Print only error type and error value.
"""
exType, exValue, exTb = sys.exc_info()
resL1 = traceback.format_exception_only(exType, exValue)
return string.join(resL1, "")
| 7,531 |
def setup_install_dir():
"""Sets up install dir and ensures its owned by Galaxy"""
if not exists(env.install_dir):
sudo("mkdir -p %s" % env.install_dir)
if not exists(env.jars_dir):
sudo("mkdir -p %s" % env.jars_dir)
# TODO: Fix bug here
chown_galaxy(os.path.split(env.install_dir)[0])
| 7,532 |
def is_str_str_dict(x):
"""Tests if something is a str:str dictionary"""
return isinstance(x, dict) and all(
isinstance(k, str) and isinstance(v, str) for k, v in x.items()
)
| 7,533 |
def _ensureListLike(item):
"""
Return the item if it is a list or tuple, otherwise add it to a list and
return that.
"""
return item if (isinstance(item, list) or isinstance(item, tuple)) \
else [item]
| 7,534 |
def rule_asc(n):
"""
Produce the integer partitions of n as ascending compositions.
See: http://jeromekelleher.net/generating-integer-partitions.html
"""
a = [0 for _ in range(n + 1)]
k = 1
a[1] = n
while k != 0:
x = a[k - 1] + 1
y = a[k] - 1
k -= 1
while x <= y:
a[k] = x
y -= x
k += 1
a[k] = x + y
yield a[: k + 1]
| 7,535 |
def get_file_from_gitlab(gitpkg, path, ref="master"):
"""Retrieves a file from a Gitlab repository, returns a (StringIO) file."""
return io.StringIO(gitpkg.files.get(file_path=path, ref=ref).decode())
| 7,536 |
def tsne(x, no_dims=2, initial_dims=50, perplexity=30.0, max_iter=1000):
"""Runs t-SNE on the dataset in the NxD array x
to reduce its dimensionality to no_dims dimensions.
The syntaxis of the function is Y = tsne.tsne(x, no_dims, perplexity),
where x is an NxD NumPy array.
"""
# Check inputs
if isinstance(no_dims, float):
print("Error: array x should have type float.")
return -1
if round(no_dims) != no_dims:
print("Error: number of dimensions should be an integer.")
return -1
# 初始化参数和变量
x = pca(x, initial_dims).real
(n, d) = x.shape
initial_momentum = 0.5
final_momentum = 0.8
eta = 500
min_gain = 0.01
y = np.random.randn(n, no_dims)
dy = np.zeros((n, no_dims))
iy = np.zeros((n, no_dims))
gains = np.ones((n, no_dims))
# 对称化
P = seach_prob(x, 1e-5, perplexity)
P = P + np.transpose(P)
P = P / np.sum(P)
# early exaggeration
P = P * 4
P = np.maximum(P, 1e-12)
# Run iterations
for iter in range(max_iter):
# Compute pairwise affinities
sum_y = np.sum(np.square(y), 1)
num = 1 / (1 + np.add(np.add(-2 * np.dot(y, y.T), sum_y).T, sum_y))
num[range(n), range(n)] = 0
Q = num / np.sum(num)
Q = np.maximum(Q, 1e-12)
# Compute gradient
PQ = P - Q
for i in range(n):
dy[i,:] = np.sum(np.tile(PQ[:,i] * num[:,i], (no_dims, 1)).T * (y[i,:] - y), 0)
# Perform the update
if iter < 20:
momentum = initial_momentum
else:
momentum = final_momentum
gains = (gains + 0.2) * ((dy > 0) != (iy > 0)) + (gains * 0.8) * ((dy > 0) == (iy > 0))
gains[gains < min_gain] = min_gain
iy = momentum * iy - eta * (gains * dy)
y = y + iy
y = y - np.tile(np.mean(y, 0), (n, 1))
# Compute current value of cost function
if (iter + 1) % 100 == 0:
if iter > 100:
C = np.sum(P * np.log(P / Q))
else:
C = np.sum( P/4 * np.log( P/4 / Q))
print("Iteration ", (iter + 1), ": error is ", C)
# Stop lying about P-values
if iter == 100:
P = P / 4
print("finished training!")
return y
| 7,537 |
def add_corp():
"""
添加投顾信息页面,可以让用户手动添加投顾
:by zhoushaobo
:return:
"""
if request.method == 'GET':
fof_list = cache.get(str(current_user.id))
return render_template("add_corp.html", fof_list=fof_list)
if request.method == 'POST':
name = request.form['name']
alias = request.form['alias']
register_capital = request.form['register_capital']
status = request.form['status']
site = request.form['site']
desc = request.form['description']
corp = Invest_corp(name=name, alias=alias, review_status=int(status), address=site, description=desc,
registered_capital=register_capital)
db.session.add(corp)
db.session.commit()
return redirect(url_for('f_app.invest_corp'))
| 7,538 |
def reset_circuit() -> None:
"""
Clear the circuit and create a new one.
"""
global _current_circuit
if _current_circuit is None:
return
try:
_current_circuit.abort(EdzedCircuitError('forced circuit reset'))
# abort is ignored if not running
except Exception as err:
# e.g. RuntimeError: Event loop is closed
_logger.warning("reset_circuit(): %r error ignored", err)
_current_circuit = Circuit()
| 7,539 |
def nll_loss(output: Tensor, target: Tensor):
"""
Negative log likelihood loss function.
## Parameters
output: `Tensor` - model's prediction
target: `Target` - training sample targets
## Example usage
```python
from beacon.tensor import Tensor
from beacon.functional import functions as F
output = Tensor([[0.2, 0.7, 0.1], [0.4, 0.45, 0.15]], requires_grad=True)
target = Tensor([[0, 1, 0], [1, 0, 0]], requires_grad=True)
loss = F.nll_loss(output, target)
```
"""
output, target = fn.to_tensor(output), fn.to_tensor(target)
output = fn.clip(output, 1e-7, 1 - 1e-7)
return -target * fn.log(output)
| 7,540 |
async def album_upload(sessionid: str = Form(...),
files: List[UploadFile] = File(...),
caption: str = Form(...),
usertags: Optional[List[Usertag]] = Form([]),
location: Optional[Location] = Form(None),
clients: ClientStorage = Depends(get_clients)
) -> Media:
"""Upload album to feed
"""
cl = clients.get(sessionid)
return await album_upload_post(
cl, files, caption=caption,
usertags=usertags,
location=location)
| 7,541 |
def mocked_requests_get(*args, **kwargs):
"""Mock requests.get invocations."""
class MockResponse:
"""Class to represent a mocked response."""
def __init__(self, json_data, status_code):
"""Initialize the mock response class."""
self.json_data = json_data
self.status_code = status_code
def json(self):
"""Return the json of the response."""
return self.json_data
if str(args[0]).startswith('https://api.ring.com/clients_api/session'):
return MockResponse({
"profile": {
"authentication_token": "12345678910",
"email": "foo@bar.org",
"features": {
"chime_dnd_enabled": False,
"chime_pro_enabled": True,
"delete_all_enabled": True,
"delete_all_settings_enabled": False,
"device_health_alerts_enabled": True,
"floodlight_cam_enabled": True,
"live_view_settings_enabled": True,
"lpd_enabled": True,
"lpd_motion_announcement_enabled": False,
"multiple_calls_enabled": True,
"multiple_delete_enabled": True,
"nw_enabled": True,
"nw_larger_area_enabled": False,
"nw_user_activated": False,
"owner_proactive_snoozing_enabled": True,
"power_cable_enabled": False,
"proactive_snoozing_enabled": False,
"reactive_snoozing_enabled": False,
"remote_logging_format_storing": False,
"remote_logging_level": 1,
"ringplus_enabled": True,
"starred_events_enabled": True,
"stickupcam_setup_enabled": True,
"subscriptions_enabled": True,
"ujet_enabled": False,
"video_search_enabled": False,
"vod_enabled": False},
"first_name": "Home",
"id": 999999,
"last_name": "Assistant"}
}, 201)
elif str(args[0])\
.startswith("https://api.ring.com/clients_api/ring_devices"):
return MockResponse({
"authorized_doorbots": [],
"chimes": [
{
"address": "123 Main St",
"alerts": {"connection": "online"},
"description": "Downstairs",
"device_id": "abcdef123",
"do_not_disturb": {"seconds_left": 0},
"features": {"ringtones_enabled": True},
"firmware_version": "1.2.3",
"id": 999999,
"kind": "chime",
"latitude": 12.000000,
"longitude": -70.12345,
"owned": True,
"owner": {
"email": "foo@bar.org",
"first_name": "Marcelo",
"id": 999999,
"last_name": "Assistant"},
"settings": {
"ding_audio_id": None,
"ding_audio_user_id": None,
"motion_audio_id": None,
"motion_audio_user_id": None,
"volume": 2},
"time_zone": "America/New_York"}],
"doorbots": [
{
"address": "123 Main St",
"alerts": {"connection": "online"},
"battery_life": 4081,
"description": "Front Door",
"device_id": "aacdef123",
"external_connection": False,
"features": {
"advanced_motion_enabled": False,
"motion_message_enabled": False,
"motions_enabled": True,
"people_only_enabled": False,
"shadow_correction_enabled": False,
"show_recordings": True},
"firmware_version": "1.4.26",
"id": 987652,
"kind": "lpd_v1",
"latitude": 12.000000,
"longitude": -70.12345,
"motion_snooze": None,
"owned": True,
"owner": {
"email": "foo@bar.org",
"first_name": "Home",
"id": 999999,
"last_name": "Assistant"},
"settings": {
"chime_settings": {
"duration": 3,
"enable": True,
"type": 0},
"doorbell_volume": 1,
"enable_vod": True,
"live_view_preset_profile": "highest",
"live_view_presets": [
"low",
"middle",
"high",
"highest"],
"motion_announcement": False,
"motion_snooze_preset_profile": "low",
"motion_snooze_presets": [
"none",
"low",
"medium",
"high"]},
"subscribed": True,
"subscribed_motions": True,
"time_zone": "America/New_York"}]
}, 200)
elif str(args[0]).startswith("https://api.ring.com/clients_api/doorbots"):
return MockResponse([{
"answered": False,
"created_at": "2017-03-05T15:03:40.000Z",
"events": [],
"favorite": False,
"id": 987654321,
"kind": "motion",
"recording": {"status": "ready"},
"snapshot_url": ""
}], 200)
| 7,542 |
def count_disordered(arr, size):
"""Counts the number of items that are out of the expected
order (monotonous increase) in the given list."""
counter = 0
state = {
"expected": next(item for item in range(size) if item in arr),
"checked": []
}
def advance_state():
state["expected"] += 1
while True:
in_arr = state["expected"] in arr
is_overflow = state["expected"] > size
not_checked = state["expected"] not in state["checked"]
if not_checked and (in_arr or is_overflow):
return
state["expected"] += 1
for val in arr:
if val == state["expected"]:
advance_state()
else:
counter += 1
state["checked"].append(val)
return counter
| 7,543 |
def multi_process(directory: str, modifiers: dict, base: str, end: bool = False):
"""
Verarbeitet ein ganzes Verzeichnis mit Emojis
:param directory: Der Ordner
:param modifiers: Die Skin-Modifier
:param base: Der Name des Basis-Typen
:param end: Ob noch eine fe0f-Sequenz angefügt werden soll.
:return: Nix
"""
files = os.listdir(directory)
for file in files:
# Nur SVG wird derzeit unterstützt
if os.path.splitext(file)[-1].lower() in {'.svg'}:
# Erstelle ein Emoji-Objekt
emoji = Emoji(modifiers, os.path.join(directory, file), base, end)
# Und wende die Modifier an
emoji.batch_modify()
| 7,544 |
def lookup_flag_values(flag_list: Iterable[str]) -> collections.OrderedDict:
"""Returns a dictionary of (flag_name, flag_value) pairs for an iterable of flag names."""
flag_odict = collections.OrderedDict()
for flag_name in flag_list:
if not isinstance(flag_name, str):
raise ValueError(
'All flag names must be strings. Flag {} was of type {}.'.format(
flag_name, type(flag_name)))
if flag_name not in flags.FLAGS:
raise ValueError('"{}" is not a defined flag.'.format(flag_name))
flag_odict[flag_name] = flags.FLAGS[flag_name].value
return flag_odict
| 7,545 |
def test_alignment():
"""Ensure A.M. cosine's peaks are aligned across joint slices."""
if skip_all:
return None if run_without_pytest else pytest.skip()
N = 1025
J = 7
Q = 16
Q_fr = 2
F = 4
# generate A.M. cosine ###################################################
f1, f2 = 8, 256
t = np.linspace(0, 1, N, 1)
a = (np.cos(2*np.pi * f1 * t) + 1) / 2
c = np.cos(2*np.pi * f2 * t)
x = a * c
# scatter ################################################################
for out_3D in (True, False):
for sampling_psi_fr in ('resample', 'exclude'):
if sampling_psi_fr == 'exclude' and out_3D:
continue # incompatible
for J_fr in (3, 5):
out_type = ('dict:array' if out_3D else
'dict:list') # for convenience
test_params = dict(out_3D=out_3D,
sampling_filters_fr=(sampling_psi_fr, 'resample'))
test_params_str = '\n'.join(f'{k}={v}' for k, v in
test_params.items())
jtfs = TimeFrequencyScattering1D(
J, N, Q, J_fr=J_fr, Q_fr=Q_fr, F=F, average=True, average_fr=True,
aligned=True, out_type=out_type, frontend=default_backend,
pad_mode='zero', pad_mode_fr='zero', **pad_kw, **test_params)
Scx = jtfs(x)
Scx = drop_batch_dim_jtfs(Scx)
Scx = jtfs_to_numpy(Scx)
# assert peaks share an index #################################
def max_row_idx(c):
coef = c['coef'] if 'list' in out_type else c
return np.argmax(np.sum(coef**2, axis=-1))
first_coef = Scx['psi_t * psi_f_up'][0]
mx_idx = max_row_idx(first_coef)
for pair in Scx:
if pair in ('S0', 'S1'): # joint only
continue
for i, c in enumerate(Scx[pair]):
mx_idx_i = max_row_idx(c)
assert abs(mx_idx_i - mx_idx) < 2, (
"{} != {} -- Scx[{}][{}]\n{}").format(
mx_idx_i, mx_idx, pair, i, test_params_str)
if J_fr == 3:
# assert not all J_pad_frs are same so test covers this case
assert_pad_difference(jtfs, test_params_str)
| 7,546 |
def main():
"""
Create an aligned functional group based on command line arguments.
"""
parser = argparse.ArgumentParser(
description='Create a functional group from a smiles pattern',
epilog='Example usage: %(prog)s -s OPr -n PropylEther -c "Alkyl Ether" -m OCCC')
parser.add_argument('smi_string', help="Smiles string to generate group")
parser.add_argument('-s', '--short-name',
help='Short name (defaults to smiles string)')
parser.add_argument('-n', '--name', required=True,
help='Descriptive name (e.g. PropylEther)')
parser.add_argument('-m', '--mepo-compatible', action='store_true',
help='Record group as compatible with MEPO-QEq')
parser.add_argument('-c', '--classification',
help='General classification (e.g. "Alkyl Halide")')
parser.add_argument('-t', '--terminal', action='store_true',
help='Output to terminal as well as files')
args = parser.parse_args()
fgroup = args.smi_string
if '%99' in fgroup:
print('Do not use ring closure 99')
raise SystemExit
if not args.short_name:
args.short_name = fgroup
# Use an explicitly defined benzene as a base
# Do rings closure at 99 in case functional group has other closures
attached = '[cH]%99[cH][cH][cH][cH]c%99'
# make3D by default gives an optimised structure, great!
pybel_mol = pybel.readstring('smi', attached + fgroup)
pybel_mol.title = "[{}] {}".format(args.short_name, args.name)
pybel_mol.make3D(forcefield='UFF')
uff = ob.OBForceField_FindForceField('uff')
uff.Setup(pybel_mol.OBMol)
uff.GetAtomTypes(pybel_mol.OBMol)
coordinates = []
for ob_atom in pybel_mol:
coordinates.append(ob_atom.coords)
rotated_coordinates = realign(coordinates, 11, 10, 8)
bonds = {}
# look at all the bonds separately from the atoms
for bond in ob.OBMolBondIter(pybel_mol.OBMol):
# These rules are translated from ob/forcefielduff.cpp...
start_idx = bond.GetBeginAtomIdx()
end_idx = bond.GetEndAtomIdx()
start_atom = bond.GetBeginAtom()
end_atom = bond.GetEndAtom()
bond_order = bond.GetBondOrder()
if bond.IsAromatic():
bond_order = 1.5
# e.g., in Cp rings, may not be "aromatic" by OB
# but check for explicit hydrogen counts
#(e.g., biphenyl inter-ring is not aromatic)
#FIXME(tdaff): aromatic C from GetType is "Car" is this correct?
if (start_atom.GetType()[-1] == 'R' and
end_atom.GetType()[-1] == 'R' and
start_atom.ExplicitHydrogenCount() == 1
and end_atom.ExplicitHydrogenCount() == 1):
bond_order = 1.5
if bond.IsAmide():
bond_order = 1.41
# Zero the indicies for the connecting atom so that
# negative indexes are benzene atoms
bond_length = bond.GetLength()
bond_id = tuple(sorted((start_idx-12, end_idx-12)))
bonds[bond_id] = (bond_length, bond_order)
# We can start building our output now!
output_text = [
"[{}]\n".format(args.short_name),
"name = {}\n".format(args.name),
"smiles = {}\n".format(fgroup),
"mepo_compatible = {}\n".format(args.mepo_compatible)]
if args.classification:
output_text.append("class = {}\n".format(args.classification))
# functional group fingerprint
nbins = 10
max_distance = 10.0
bin_width = max_distance/nbins
fingerprint = [0.0]*(nbins*3)
atom_block = []
base_atom = pybel_mol.atoms[10].OBAtom
for ob_atom, coord in zip(pybel_mol, rotated_coordinates):
atom_idx = ob_atom.OBAtom.GetIndex()
if atom_idx > 10:
atomicnum = ob_atom.atomicnum
element = ATOMIC_NUMBER[atomicnum]
ff_type = ob_atom.OBAtom.GetData("FFAtomType").GetValue()
atom_block.append(" {0:4} {1:5} {2[0]:10.6f} {2[1]:10.6f} {2[2]:10.6f}\n".format(element, ff_type, coord))
# Generate fingerprint data
distance = ob_atom.OBAtom.GetDistance(base_atom)
if distance > max_distance:
continue
# Put in distance bin
fingerprint[int(distance/bin_width)] += 1
# Put in electronegativity bin
electronegativity = ob.etab.GetElectroNeg(atomicnum)
fingerprint[nbins + int(distance/bin_width)] += electronegativity
# Put in vdw radii
vdw_radius = ob.etab.GetVdwRad(atomicnum)
fingerprint[2*nbins + int(distance/bin_width)] += vdw_radius
fingerprint = ",".join("{:.2f}".format(i) for i in fingerprint)
#
# 3D fingerprint
#
xmin, xmax = -5.658385, 6.758497
ymin, ymax = -2.506779, 7.580274
zmin, zmax = -2.469688, 4.024162
spacing = 1.0
# make gridpoints have the cartesian coordinates of all the
# points of interest on the grid
x_range = np.arange(xmin-2.0*spacing, xmax+3.0*spacing, spacing)
y_range = np.arange(ymin-2.0*spacing, ymax+3.0*spacing, spacing)
z_range = np.arange(zmin-2.0*spacing, zmax+3.0*spacing, spacing)
gridpoints = [(x, y, z) for x in x_range for y in y_range for z in z_range]
grid_shape = (len(x_range), len(y_range), len(z_range))
# Calculate all the atom-point distances
distance_matrix = cdist(rotated_coordinates, gridpoints)
# Find charges for all the atoms manually.
# Automatically would do gasteiger, but fails for
# some elements and we use qeq anyway
qeq = ob.OBChargeModel_FindType('qeq')
qeq.ComputeCharges(pybel_mol.OBMol)
# coulomb = q1q2/4pie0r no units yet...
coulomb_matrix = np.zeros(len(gridpoints))
for ob_atom, distances in zip(pybel_mol, distance_matrix):
coulomb_matrix += ob_atom.partialcharge/distances
# LJ potential based off UFF also no units yet...
vdw_matrix = np.zeros(len(gridpoints))
for ob_atom, distances in zip(pybel_mol, distance_matrix):
# Lorentz-Berthelot mixing rules
probe = (3.4309, 0.1050) # Carbon
source = UFF[ATOMIC_NUMBER[ob_atom.atomicnum]]
sigma = (source[0] + probe[0]) / 2.0
epsilon = (source[1] * probe[1])**0.5
vdw_matrix += 4*epsilon*((sigma/distances)**12 - (sigma/distances)**6)
# Make into 3D gridded data
coulomb_matrix = np.reshape(coulomb_matrix, grid_shape)
vdw_matrix = np.reshape(vdw_matrix, grid_shape)
# Can clip the maximums here or elsewhere
coulomb_matrix = np.clip(coulomb_matrix, -0.1, 0.1)
vdw_matrix = np.clip(vdw_matrix, -10, 0)
# 3D plotting for visualisation
#from mayavi import mlab
#s = mlab.contour3d(coulomb_matrix)
#s = mlab.contour3d(vdw_matrix)
#mlab.show()
#
# Output
#
output_text.append('atoms =\n')
output_text.extend(atom_block)
output_text.append('orientation = 0.0 1.0 0.0\n')
output_text.append('normal = 0.0 0.0 1.0\n')
output_text.append('carbon_bond = {:.3f}\n'.format(bonds[(-1, 0)][0]))
output_text.append('fingerprint = {}\n'.format(fingerprint))
bonds_block = []
# no bonds < idx 11
for bond in sorted(bonds):
if not bond[0] < 0 and not bond[1] < 0:
bonds_block.append(" {0[0]:4} {0[1]:4} {1[1]:5.2f}\n".format(bond, bonds[bond]))
output_text.append('bonds =\n')
output_text.extend(bonds_block[:])
# Make some pictures; do this now so the ascii can go in the file
# But first get rid of the benzene
for _idx in range(10):
pybel_mol.OBMol.DeleteAtom(pybel_mol.atoms[0].OBAtom)
pybel_mol.atoms[0].OBAtom.SetType('R')
if not 'ascii' in pybel.outformats:
print("Ascii art not available, please upgrade openbabel")
else:
ascii_mol = pybel_mol.write(format='ascii', opt={'a': 2, 'w': 40})
ascii_mol = ['# {}\n'.format(x) for x in ascii_mol.splitlines() if x.strip()]
output_text[2:2] = ['#\n'] + ascii_mol + ['#\n']
basename = args.short_name
pybel_mol.write(format='mol', filename='{}.mol'.format(basename))
# Always output to a library
with open('{}.flib'.format(basename), 'w') as out_lib:
out_lib.writelines(output_text)
# Make the image with R groups and implicit hydrogen
unopt_mol = pybel.readstring('smi', "[*:1]" + fgroup)
unopt_mol.write(format='svg', filename='{}.svg'.format(basename), opt={'C': None})
# Make a table row in html
with open('{}.html'.format(basename), 'w') as out_html:
out_html.write("""\
<td>{args.short_name}</td>
<td><p>name: {args.name}</p>
<p>smiles: {args.smi_string}</p>
<p>MEPO-QEq compatible: {args.mepo_compatible}</td>
<td><a href="img/{args.short_name}.svg">
<img src="img/{args.short_name}.svg"
alt="Group: {args.short_name}"
title="[{args.short_name}]
{args.name}
{args.smi_string})"
style="height: 75px"/></a>
</td>
""".format(args=args))
if args.terminal:
print("".join(output_text))
| 7,547 |
def request_text(photo_file, max_results=5):
"""
Request the Google service to find text in an image
:param photo_file: The filename (or path) of the image in a local directory
:param max_results: The requested maximum number of results
:return: A list of text entries found in the image
Note: The argument max_results does not modify the number of results for text detection
"""
credentials = GoogleCredentials.get_application_default()
service = discovery.build('vision', 'v1', credentials=credentials)
with open(photo_file, 'rb') as phf:
image_content = base64.b64encode(phf.read())
service_request = service.images().annotate(body={
'requests': [{'image': {'content': image_content.decode('UTF-8')},
'features': [{'type': 'TEXT_DETECTION', 'maxResults': max_results}]
}]
})
response = service_request.execute()
text_list = response['responses'][0].get('textAnnotations', None)
if text_list is None:
return []
else:
text_vec = map(lambda s: s['description'].strip().strip('\n'), text_list)
return text_vec
| 7,548 |
def config(request):
"""render a ProsperConfig object for testing"""
return p_config.ProsperConfig(request.config.getini('app_cfg'))
| 7,549 |
def flatatt(attrs):
"""
Convert a dictionary of attributes to a single string.
The returned string will contain a leading space followed by key="value",
XML-style pairs. It is assumed that the keys do not need
to be XML-escaped.
If the passed dictionary is empty, then return an empty string.
If the value passed is None writes only the attribute (eg. required)
"""
ret_arr = []
for k, v in attrs.items():
if v is None:
ret_arr.append(u' %s' % k)
else:
ret_arr.append(u' %s="%s"' % (k, conditional_escape(v)))
return u''.join(ret_arr)
| 7,550 |
def json_io_dump(filename, data):
""" Dumps the the JSON data and returns it as a dictionary from filename
:arg filename <string> - Filename of json to point to
:arg data - The already formatted data to dump to JSON
"""
with open(filename, encoding='utf-8', mode='w') as json_file:
json.dump(data, json_file)
return True
| 7,551 |
def get_restaurants(_lat, _lng):
"""緯度: lat 経度: lng"""
response = requests.get(URL.format(API_KEY, _lat, _lng))
result = json.loads(response.text)
lat_lng = []
for restaurant in result['results']['shop']:
lat = float(restaurant['lat'])
lng = float(restaurant['lng'])
lat_lng.append((lat, lng, restaurant['name']))
r = []
for lat, lng, name in lat_lng:
r2 = []
difference = (_lat - lat) * 3600
r2.append(int(difference * byou))
difference = (lng - _lng) * 3600
r2.append(int(difference * byou))
r2.append(name)
r.append(r2)
return r
| 7,552 |
def geomfill_GetCircle(*args):
"""
:param TConv:
:type TConv: Convert_ParameterisationType
:param ns1:
:type ns1: gp_Vec
:param ns2:
:type ns2: gp_Vec
:param nplan:
:type nplan: gp_Vec
:param pt1:
:type pt1: gp_Pnt
:param pt2:
:type pt2: gp_Pnt
:param Rayon:
:type Rayon: float
:param Center:
:type Center: gp_Pnt
:param Poles:
:type Poles: TColgp_Array1OfPnt
:param Weigths:
:type Weigths: TColStd_Array1OfReal &
:rtype: void
:param TConv:
:type TConv: Convert_ParameterisationType
:param ns1:
:type ns1: gp_Vec
:param ns2:
:type ns2: gp_Vec
:param dn1w:
:type dn1w: gp_Vec
:param dn2w:
:type dn2w: gp_Vec
:param nplan:
:type nplan: gp_Vec
:param dnplan:
:type dnplan: gp_Vec
:param pts1:
:type pts1: gp_Pnt
:param pts2:
:type pts2: gp_Pnt
:param tang1:
:type tang1: gp_Vec
:param tang2:
:type tang2: gp_Vec
:param Rayon:
:type Rayon: float
:param DRayon:
:type DRayon: float
:param Center:
:type Center: gp_Pnt
:param DCenter:
:type DCenter: gp_Vec
:param Poles:
:type Poles: TColgp_Array1OfPnt
:param DPoles:
:type DPoles: TColgp_Array1OfVec
:param Weigths:
:type Weigths: TColStd_Array1OfReal &
:param DWeigths:
:type DWeigths: TColStd_Array1OfReal &
:rtype: bool
:param TConv:
:type TConv: Convert_ParameterisationType
:param ns1:
:type ns1: gp_Vec
:param ns2:
:type ns2: gp_Vec
:param dn1w:
:type dn1w: gp_Vec
:param dn2w:
:type dn2w: gp_Vec
:param d2n1w:
:type d2n1w: gp_Vec
:param d2n2w:
:type d2n2w: gp_Vec
:param nplan:
:type nplan: gp_Vec
:param dnplan:
:type dnplan: gp_Vec
:param d2nplan:
:type d2nplan: gp_Vec
:param pts1:
:type pts1: gp_Pnt
:param pts2:
:type pts2: gp_Pnt
:param tang1:
:type tang1: gp_Vec
:param tang2:
:type tang2: gp_Vec
:param Dtang1:
:type Dtang1: gp_Vec
:param Dtang2:
:type Dtang2: gp_Vec
:param Rayon:
:type Rayon: float
:param DRayon:
:type DRayon: float
:param D2Rayon:
:type D2Rayon: float
:param Center:
:type Center: gp_Pnt
:param DCenter:
:type DCenter: gp_Vec
:param D2Center:
:type D2Center: gp_Vec
:param Poles:
:type Poles: TColgp_Array1OfPnt
:param DPoles:
:type DPoles: TColgp_Array1OfVec
:param D2Poles:
:type D2Poles: TColgp_Array1OfVec
:param Weigths:
:type Weigths: TColStd_Array1OfReal &
:param DWeigths:
:type DWeigths: TColStd_Array1OfReal &
:param D2Weigths:
:type D2Weigths: TColStd_Array1OfReal &
:rtype: bool
"""
return _GeomFill.geomfill_GetCircle(*args)
| 7,553 |
def dwconv3x3_block(in_channels,
out_channels,
stride,
padding=1,
dilation=1,
bias=False,
activation=(lambda: nn.ReLU(inplace=True)),
activate=True):
"""
3x3 depthwise version of the standard convolution block with ReLU6 activation.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
padding : int or tuple/list of 2 int, default 1
Padding value for convolution layer.
dilation : int or tuple/list of 2 int, default 1
Dilation value for convolution layer.
bias : bool, default False
Whether the layer uses a bias vector.
activation : function or str or None, default nn.ReLU(inplace=True)
Activation function or name of activation function.
activate : bool, default True
Whether activate the convolution block.
"""
return conv3x3_block(
in_channels=in_channels,
out_channels=out_channels,
stride=stride,
padding=padding,
dilation=dilation,
groups=out_channels,
bias=bias,
activation=activation,
activate=activate)
| 7,554 |
def predict() -> str:
"""
Creates route for model prediction for given number of inputs.
:return: predicted price
"""
try:
input_params = process_input(request.data)
print(input_params)
predictions = regressor.predict(input_params)
return json.dumps({"predicted_price": predictions.tolist()})
except (KeyError, json.JSONDecodeError, AssertionError):
return json.dumps({"error": "CHECK INPUT"}), 400
except:
return json.dumps({"error": "PREDICTION FAILED"}), 500
| 7,555 |
def all_h2h_pairs_all_lanes(matches_df, file_name=''):
"""Produces all head to head win rates for all lane matchups -- even across different lanes
(eg. TOP_SOLO Renekton vs MID_SOLO Xerath)."""
df = pd.DataFrame()
lanes = dc.get_lanes_roles()
for lane1 in lanes:
print(lane1)
for lane2 in lanes:
print(lane1 + '_' + lane2)
temp = all_h2h_pairs_fixed_lane(matches_df, lane1, lane2)
df[lane1 + '_' + lane2 + '_wr'] = temp['win_rate']
df[lane1 + '_' + lane2 + '_gp'] = temp['games_played']
df[lane1 + '_' + lane2 + '_wins'] = temp['wins']
if file_name != '':
df.to_csv(file_name)
return df
| 7,556 |
def sort_list_of_dates(b):
"""
مرتب سازی
نویسنده: ندا
"""
i = 0
while i<len(b)-1:
#if b.value("year") in b[i]<b.value("year") in b[i+1]:
# if b.value("month") in b[i]<b.value("month") in b[i+1]:
# if b.value("day") in b[i]<b.value("day") in b[i+1]:
if earlier_than(b[i+1], b[i]):
t = b[i+1]
b[i+1] = b[i]
b[i] = t
i = -1
#if b[i] == b[i+1]:
# b.remove(b[i])
#i = 0
i = i+1
return
| 7,557 |
def reload_rules(testcase, rest_url):
"""
:param TestCase self: TestCase object
:param str rest_url: http://host:port
:rtype: dict
"""
resp = requests.get(rest_url + "/rest/reload").json()
print("Reload rules response: {}".format(resp))
testcase.assertEqual(resp.get("success"), True)
return resp
| 7,558 |
def encryptMessage(key: str, message: str) -> str:
"""Vigenère cipher encryption
Wrapper function that encrypts given message with given key using the Vigenère cipher.
Args:
key: String encryption key to encrypt with Vigenère cipher.
message: Message string to encrypt.
Returns:
Encrypted message string.
"""
return translateMessage(key, message, 'encrypt')
| 7,559 |
def pytest_configure(config):
"""Inject documentation."""
config.addinivalue_line(
"markers", "trio: "
"mark the test as an async trio test; "
"it will be run using trio.run"
)
| 7,560 |
def rae(label, pred):
"""computes the relative absolute error
(condensed using standard deviation formula)"""
#compute the root of the sum of the squared error
numerator = np.mean(np.abs(label - pred), axis=None)
#numerator = np.sum(np.abs(label - pred), axis = None)
#compute AE if we were to simply predict the average of the previous values
denominator = np.mean(np.abs(label - np.mean(label, axis=None)), axis=None)
#denominator = np.sum(np.abs(label - np.mean(label, axis = None)), axis=None)
return numerator / denominator
| 7,561 |
def subset_sum(arr, target_sum, i, cache):
"""
Returns whether any subset(not contiguous) of the array has sum equal to target sum.
"""
if target_sum == 0:
return True, {}
if i < 0:
return False, {}
if target_sum in cache[i]:
return cache[i][target_sum]
# Either include this element or not!
sub_ans, sub_ans_indices = subset_sum(arr, target_sum, i - 1, cache)
if not sub_ans and target_sum >= arr[i]:
sub_ans, sub_ans_indices = subset_sum(arr, target_sum - arr[i], i - 1, cache)
sub_ans_indices = set(sub_ans_indices)
sub_ans_indices.add(i)
if not sub_ans:
sub_ans_indices = {}
cache[i][target_sum] = sub_ans, sub_ans_indices
return cache[i][target_sum]
| 7,562 |
def set_runtime_parameter_pb(
pb: pipeline_pb2.RuntimeParameter,
name: Text,
ptype: Type[types.Property],
default_value: Optional[types.Property] = None
) -> pipeline_pb2.RuntimeParameter:
"""Helper function to fill a RuntimeParameter proto.
Args:
pb: A RuntimeParameter proto to be filled in.
name: Name to be set at pb.name.
ptype: The Python type to be set at pb.type.
default_value: Optional. If provided, it will be pb.default_value.
Returns:
A RuntimeParameter proto filled with provided values.
"""
pb.name = name
if ptype == int:
pb.type = pipeline_pb2.RuntimeParameter.Type.INT
if default_value:
pb.default_value.int_value = default_value
elif ptype == float:
pb.type = pipeline_pb2.RuntimeParameter.Type.DOUBLE
if default_value:
pb.default_value.double_value = default_value
elif ptype == str:
pb.type = pipeline_pb2.RuntimeParameter.Type.STRING
if default_value:
pb.default_value.string_value = default_value
else:
raise ValueError("Got unsupported runtime parameter type: {}".format(ptype))
return pb
| 7,563 |
def get_loader(content_type):
"""Returns loader class for specified content type.
:type content_type: constants.ContentType
:param content_type: Content type.
:returns: Loader class for specified content type.
:raise ValueError: If no loader found for specified content type.
"""
for loader_cls in ALL_LOADERS:
content_types = loader_cls.content_types
if not isinstance(loader_cls.content_types, (list, tuple)):
content_types = [content_types]
if content_type in content_types:
return loader_cls
raise ValueError('Loader for content type "{0}" not found'
.format(content_type))
| 7,564 |
def get_basis_script(max_degree: int,
use_pad_trick: bool,
spherical_harmonics: List[Tensor],
clebsch_gordon: List[List[Tensor]],
amp: bool) -> Dict[str, Tensor]:
"""
Compute pairwise bases matrices for degrees up to max_degree
:param max_degree: Maximum input or output degree
:param use_pad_trick: Pad some of the odd dimensions for a better use of Tensor Cores
:param spherical_harmonics: List of computed spherical harmonics
:param clebsch_gordon: List of computed CB-coefficients
:param amp: When true, return bases in FP16 precision
"""
basis = {}
idx = 0
# Double for loop instead of product() because of JIT script
for d_in in range(max_degree + 1):
for d_out in range(max_degree + 1):
key = f'{d_in},{d_out}'
K_Js = []
for freq_idx, J in enumerate(range(abs(d_in - d_out), d_in + d_out + 1)):
Q_J = clebsch_gordon[idx][freq_idx]
K_Js.append(torch.einsum('n f, k l f -> n l k', spherical_harmonics[J].float(), Q_J.float()))
basis[key] = torch.stack(K_Js, 2) # Stack on second dim so order is n l f k
if amp:
basis[key] = basis[key].half()
if use_pad_trick:
basis[key] = F.pad(basis[key], (0, 1)) # Pad the k dimension, that can be sliced later
idx += 1
return basis
| 7,565 |
def get_iterative_process_for_minimal_sum_example():
"""Returns an iterative process for a sum example.
This iterative process contains the fewest components required to compile to
`forms.MapReduceForm`.
"""
@computations.federated_computation
def init_fn():
"""The `init` function for `tff.templates.IterativeProcess`."""
zero = computations.tf_computation(lambda: [0, 0])
return intrinsics.federated_eval(zero, placements.SERVER)
@computations.tf_computation(tf.int32)
def work(client_data):
del client_data # Unused
return 1, 1
@computations.federated_computation([
computation_types.FederatedType([tf.int32, tf.int32], placements.SERVER),
computation_types.FederatedType(tf.int32, placements.CLIENTS),
])
def next_fn(server_state, client_data):
"""The `next` function for `tff.templates.IterativeProcess`."""
del server_state # Unused
# No call to `federated_map` with prepare.
# No call to `federated_broadcast`.
client_updates = intrinsics.federated_map(work, client_data)
unsecure_update = intrinsics.federated_sum(client_updates[0])
secure_update = intrinsics.federated_secure_sum_bitwidth(
client_updates[1], 8)
new_server_state = intrinsics.federated_zip(
[unsecure_update, secure_update])
# No call to `federated_map` with an `update` function.
server_output = intrinsics.federated_value([], placements.SERVER)
return new_server_state, server_output
return iterative_process.IterativeProcess(init_fn, next_fn)
| 7,566 |
def test_nbconv_file_contents(tmp_path: Path):
"""Run ``nbconv`` with the ``exporter`` or ``out_file`` argument."""
nb = make_notebook(tmp_path)
assert nbconv(in_file=nb, exporter="html")[1].startswith("<!DOCTYPE html>")
assert nbconv(in_file=nb, out_file="o.html")[1].startswith("<!DOCTYPE html")
assert nbconv(in_file=nb, out_file="o.___")[1].startswith("<!DOCTYPE html>")
assert nbconv(in_file=nb, out_file="o.asc")[1].startswith("\n[[background]")
assert nbconv(in_file=nb, exporter="rst")[1].startswith("\nBackground\n")
assert nbconv(in_file=nb, out_file="o.rst")[1].startswith("\nBackground\n")
| 7,567 |
def get_r_port_p_d_t(p):
"""玄関ポーチに設置された照明設備の使用時間率
Args:
p(int): 居住人数
Returns:
ndarray: r_port_p_d_t 日付dの時刻tにおける居住人数がp人の場合の玄関ポーチに設置された照明設備の使用時間率
"""
return get_r_i_p_d_t(19, p)
| 7,568 |
def remove_comments_from_json(string):
"""
Removes comments from a JSON string, supports // and /* formats. From Stack Overflow.
@param str string: Original text.
@return: Text without comments.
@rtype: str
"""
pattern = r"((?<!\\)\".*?(?<!\\)\"|\'.*?\')|(/\*.*?\*/|//[^\r\n]*$)"
# first group captures quoted strings (double or single)
# second group captures comments (//single-line or /* multi-line */)
regex = re.compile(pattern, re.MULTILINE | re.DOTALL)
def _replacer(match):
# if the 2nd group (capturing comments) is not None,
# it means we have captured a non-quoted (real) comment string.
if match.group(2) is not None:
return "" # so we will return empty to remove the comment
else: # otherwise, we will return the 1st group
return match.group(1) # captured quoted-string
return regex.sub(_replacer, string)
| 7,569 |
def visualize_depth(visual_dict, disp_or_error="disp", dataset="KITTI"):
"""visual_dict:"left_img": raw left image
"depth_error" or "disp"
"est_left_img": image reprojected from right
"depth": output depth
"photo_error": photometric error
all tensor should be normalized to [0, 1]befor input with
shape [C, H, W] with .detach()
disp_or_error: output "disp"arity when used in training or "error"
dataset: from "KITTI" "CS"
"""
for k, v, in visual_dict.items():
v = v.unsqueeze(0)
if dataset == "KITTI":
v = F.interpolate(v, [375, 1242], mode="bilinear",
align_corners=False)
elif dataset == "CS":
v = F.interpolate(v, [384, 1000], mode="bilinear",
align_corners=False)
v = v.cpu().squeeze(0).permute(1, 2, 0).numpy()
visual_dict[k] = v
left_img = visual_dict["left_img"] * 255
est_left_img = visual_dict["est_left_img"] * 255
if disp_or_error == "error":
error = visual_dict["depth_error"][..., 0]
normal_error = mpl.colors.Normalize(vmin=0,
vmax=1)
mapper_error = cm.ScalarMappable(norm=normal_error, cmap='coolwarm')
error = (mapper_error.to_rgba(error)[:, :, :3] * 255)
else:
error = visual_dict["disp"] * 255
error = cv.applyColorMap(error.astype(np.uint8),
cv.COLORMAP_OCEAN)
depth = visual_dict["depth"][..., 0]
disp = 1 / depth
vmin = np.percentile(disp, 5)
normal_disp = mpl.colors.Normalize(vmin=vmin, vmax=disp.max())
mapper_disp = cm.ScalarMappable(norm=normal_disp, cmap='magma')
depth_color = (mapper_disp.to_rgba(disp)[:, :, :3] * 255)
photo_error = visual_dict["photo_error"] * 255
photo_error = cv.applyColorMap(photo_error.astype(np.uint8), cv.COLORMAP_JET)
photo_error = cv.cvtColor(photo_error, cv.COLOR_RGB2BGR)
fused_img = (left_img + est_left_img)/2
photoerror_img = left_img + 0.5 * photo_error
photoerror_img = photoerror_img / np.max(photoerror_img)
photoerror_img *= 255
depth_img = left_img + 0.8 * depth_color
depth_img = depth_img / np.max(depth_img)
depth_img *= 255
img1 = np.vstack([left_img, est_left_img, depth_color, photo_error])
img2 = np.vstack([error, fused_img, depth_img, photoerror_img])
all_img = np.hstack([img1, img2]).astype(np.uint8)
all_img = cv.cvtColor(all_img, cv.COLOR_RGB2BGR)
return all_img
| 7,570 |
def put_s3_object(bucket, key_name, local_file):
"""Upload a local file in the execution environment to S3
Parameters
----------
bucket: string, required
S3 bucket that will holds the attachment
key_name: string, required
S3 key is the destination of attachment
local_file: string, required
Location of the attachment to process
Returns
-------
boolean (True if successful, False if not successful)
"""
tracer.put_metadata('object', f's3://{bucket}/{key_name}')
try:
s3_resource.Bucket(bucket).upload_file(local_file, key_name)
result = True
tracer.put_annotation('ATTACHMENT_UPLOAD', 'SUCCESS')
except Exception as e:
logger.error(str(e))
tracer.put_annotation('ATTACHMENT_UPLOAD', 'FAILURE')
result = False
return(result)
| 7,571 |
def parse_parionssport(url):
"""
Get ParionsSport odds from url
"""
if "parionssport" not in sb.TOKENS:
try:
token = get_parionssport_token()
sb.TOKENS["parionssport"] = token
except OpenSSL.crypto.Error:
return {}
if "paris-" in url.split("/")[-1] and "?" not in url:
sport = url.split("/")[-1].split("paris-")[-1]
return parse_sport_parionssport(sport)
regex = re.findall(r'\d+', url)
if regex:
id_league = regex[-1]
try:
return parse_parionssport_api("p" + str(id_league))
except TypeError:
return {}
return {}
| 7,572 |
def get_index(channel_urls=(), prepend=True, platform=None,
use_local=False, use_cache=False, unknown=False, prefix=False):
"""
Return the index of packages available on the channels
If prepend=False, only the channels passed in as arguments are used.
If platform=None, then the current platform is used.
If prefix is supplied, then the packages installed in that prefix are added.
"""
if use_local:
channel_urls = ['local'] + list(channel_urls)
channel_urls = normalize_urls(channel_urls, platform)
if prepend:
channel_urls.extend(get_channel_urls(platform))
channel_urls = prioritize_channels(channel_urls)
index = fetch_index(channel_urls, use_cache=use_cache, unknown=unknown)
if prefix:
priorities = {c: p for c, p in itervalues(channel_urls)}
maxp = max(itervalues(priorities)) + 1 if priorities else 1
for dist, info in iteritems(install.linked_data(prefix)):
fn = info['fn']
schannel = info['schannel']
prefix = '' if schannel == 'defaults' else schannel + '::'
priority = priorities.get(schannel, maxp)
key = prefix + fn
if key in index:
# Copy the link information so the resolver knows this is installed
index[key] = index[key].copy()
index[key]['link'] = info.get('link') or True
else:
# only if the package in not in the repodata, use local
# conda-meta (with 'depends' defaulting to [])
info.setdefault('depends', [])
info['priority'] = priority
index[key] = info
return index
| 7,573 |
def is__invsign1(*args):
"""
is__invsign1(ea) -> bool
"""
return _ida_nalt.is__invsign1(*args)
| 7,574 |
def bind(bind_to, bind_with, name):
"""
A cool hata features, that lets you bind object to existing one.
Parameters
----------
bind_to : `type`
The type to bind to.
bind_with : `type`
The type to bind with.
name : `str`
The name of the binding.
Raises
------
TypeError
- If `bind_to` is not a type.
- If `bind_to`-s do not support weakreferencing.
- If `bind_to` has already an attribute named `name`.
Examples
--------
Generic binder:
```py
from hata import ClientUserBase, bind
class Inventory(object):
def __init__(self, parent_self):
self.user = parent_self
self.inv = []
def add_item(self, name):
self.inv.append(name)
def give_user(self, item, recipient):
del self.inv[self.inv.index(item)]
recipient.inventory.add_item(item)
bind(ClientUserBase, Inventory, 'inventory')
# Usage:
user.inventory.add_item('cake')
```
Descriptor binder:
```py
from hata import ClientUserBase, bind
class InventorySize(object):
def __init__(self, parent_self):
self.value = 10
def __get__(self, instance, type_):
return self.value
def __set__(self, instance, value):
self.value = value
bind(ClientUserBase, InventorySize, 'inventory_size')
# Usage:
user.inventory_size += 10
```
Descriptor binders are familiar ot normal descriptors, except, they are created per object and not per class.
"""
if not isinstance(bind_to, type):
raise TypeError(
f'`bind_to` can be `type`, got {bind_to.__class__.__name__}; {bind_to!r}.'
)
name_space = bind_to.__dict__
if ('__weakref__' in name_space) or ('__slots__' not in name_space):
raise TypeError(
f'`bind_to`-s must support weakreferencing, got {bind_to!r}.'
)
if hasattr(bind_to, name):
raise TypeError(
f'`bind_to` already has an attribute named, as bind_to={bind_to!r}, name={name!r}.'
)
if (getattr(bind_with, '__get__', None) is not None):
binder = DescriptorObjectBinder(name, bind_with)
else:
binder = GenericObjectBinder(name, bind_with)
setattr(bind_to, name, binder)
| 7,575 |
def every(n_steps):
"""Returns True every n_steps, for use as *_at functions in various places."""
return lambda step: step % n_steps == 0
| 7,576 |
def read_files(mousefile,humanfile):
""" Read into anndata objects and return """
mouse = sc.read_10x_h5(mousefile)
if humanfile != None:
human = sc.read_10x_h5(humanfile)
else:
human = None
return(mouse,human)
| 7,577 |
def calc_batch_size(num_examples, batches_per_loop, batch_size):
"""Reduce the batch size if needed to cover all examples without a remainder."""
assert batch_size > 0
assert num_examples % batches_per_loop == 0
while num_examples % (batch_size * batches_per_loop) != 0:
batch_size -= 1
return batch_size
| 7,578 |
def test_real_distinct_irrational():
"""
Test that the roots of x^2 - 2 x + (1 - 10**(-10)) = 0 are 1 \pm 1e-5.
"""
roots = (1 + 1e-5, 1 - 1e-5)
assert_allclose(real_quadratic_roots(1, -2.0, 1.0 - 1e-10), roots,
err_msg="Testing x^2-2x+(1-1e-10)=0; roots should be 1 +- 1e-5.")
| 7,579 |
def upload_volume(request, *args, **kwargs):
"""
User upload volume data, delete the original data first.
"""
if not (request.user and request.user.is_authenticated()):
raise PermissionDenied()
user = request.user
assert 'pid' in kwargs
pid = kwargs['pid']
assert 'pk' in kwargs
id = kwargs['pk']
volume = Volume.objects.get(project__id=pid, id=id)
# Check whether the user is the member of this project
if not check_member_in_project(volume.project, user):
raise PermissionDenied(detail="User {} is not in project {}."
.format(user.username, volume.project.name))
if not request.FILES.get('file'):
raise ParseError(detail="There is no upload file.")
logger.info("User {} upload files to volume {}-{}.".format(
user.username, volume.project.name, volume.name))
filename = get_upload_volume_filename(volume, user)
save_upload_file_to_disk(request.FILES['file'], filename)
client = NFSLocalClient()
volume_dir = get_volume_direction_on_nfs(volume)
# Clear the dir first
client.removedir(volume_dir)
client.makedir(volume_dir)
client.copy_file_to_remote_and_untar(filename, volume_dir)
remove_file_from_disk(filename)
return JsonResponse({"detail": "success"})
| 7,580 |
def has_admin_access(user):
"""Check if a user has admin access."""
return user == 'admin'
| 7,581 |
def get_compss_type(value, depth=0):
# type: (object, int) -> int
""" Retrieve the value type mapped to COMPSs types.
:param value: Value to analyse.
:param depth: Collections depth.
:return: The Type of the value.
"""
# First check if it is a PSCO since a StorageNumpy can be detected
# as a numpy object.
if has_id(value):
# If has method getID maybe is a PSCO
try:
if get_id(value) not in [None, 'None']:
# the 'getID' + id == criteria for persistent object
return TYPE.EXTERNAL_PSCO
else:
return TYPE.OBJECT
except TypeError:
# A PSCO class has been used to check its type (when checking
# the return). Since we still don't know if it is going to be
# persistent inside, we assume that it is not. It will be checked
# later on the worker side when the task finishes.
return TYPE.OBJECT
# If it is a numpy scalar, we manage it as all objects to avoid to
# infer its type wrong. For instance isinstance(np.float64 object, float)
# returns true
if np and isinstance(value, np.generic):
return TYPE.OBJECT
if isinstance(value, (bool, str, int, PYCOMPSS_LONG, float)):
value_type = type(value)
if value_type is bool:
return TYPE.BOOLEAN
elif value_type is str:
# Char does not exist as char, only strings.
# Files will be detected as string, since it is a path.
# The difference among them is defined by the parameter
# decoration as FILE.
return TYPE.STRING
elif value_type is int:
if IS_PYTHON3:
if value < PYTHON_MAX_INT: # noqa
return TYPE.INT
else:
return TYPE.LONG
else:
return TYPE.INT
elif value_type is PYCOMPSS_LONG:
return TYPE.LONG
elif value_type is float:
return TYPE.DOUBLE
elif depth > 0 and is_basic_iterable(value):
return TYPE.COLLECTION
elif depth > 0 and is_dict(value):
return TYPE.DICT_COLLECTION
else:
# Default type
return TYPE.OBJECT
| 7,582 |
def pytask_parse_config(config, config_from_cli, config_from_file):
"""Register the r marker."""
config["markers"]["stata"] = "Tasks which are executed with Stata."
config["platform"] = sys.platform
if config_from_file.get("stata"):
config["stata"] = config_from_file["stata"]
else:
config["stata"] = next(
(executable for executable in STATA_COMMANDS if shutil.which(executable)),
None,
)
config["stata_keep_log"] = get_first_non_none_value(
config_from_cli,
config_from_file,
key="stata_keep_log",
callback=convert_truthy_or_falsy_to_bool,
default=False,
)
config["stata_check_log_lines"] = get_first_non_none_value(
config_from_cli,
config_from_file,
key="stata_check_log_lines",
callback=_nonnegative_nonzero_integer,
default=10,
)
config["stata_source_key"] = config_from_file.get("stata_source_key", "source")
| 7,583 |
def set_namedtuple_defaults(namedtuple, default=None):
"""
Set *all* of the fields for a given nametuple to a singular value.
Modifies the tuple in place, but returns it anyway.
More info:
https://stackoverflow.com/a/18348004
:param namedtuple: A constructed collections.namedtuple
:param default: The default value to set.
:return: the modified namedtuple
"""
namedtuple.__new__.__defaults__ = (default,) * len(namedtuple._fields)
return namedtuple
| 7,584 |
def test_tuple_get_item_merge():
"""Test composite function can be merged from pattern containing TupleGetItem nodes."""
pattern_table = [
("bn_relu", make_bn_relu_pattern())
]
def before():
x = relay.var('x', shape=(1, 8))
gamma = relay.var("gamma", shape=(8,))
beta = relay.var("beta", shape=(8,))
moving_mean = relay.var("moving_mean", shape=(8,))
moving_var = relay.var("moving_var", shape=(8,))
bn_node = relay.nn.batch_norm(x, gamma, beta, moving_mean, moving_var)
tuple_get_item_node = bn_node[0]
r = relay.nn.relu(tuple_get_item_node)
return relay.Function([x, gamma, beta, moving_mean, moving_var], r)
def expected():
x = relay.var('x', shape=(1, 8))
beta = relay.var("beta", shape=(8,))
gamma = relay.var("gamma", shape=(8,))
moving_mean = relay.var("moving_mean", shape=(8,))
moving_var = relay.var("moving_var", shape=(8,))
# bn_relu function
in_1 = relay.var('x1', shape=(1, 8))
in_2 = relay.var('gamma1', shape=(8,))
in_3 = relay.var('beta1', shape=(8,))
in_4 = relay.var('moving_mean1', shape=(8,))
in_5 = relay.var('moving_var1', shape=(8,))
bn_node = relay.nn.batch_norm(in_1, in_2, in_3, in_4, in_5)
tuple_get_item_node = bn_node[0]
relu_node = relay.nn.relu(tuple_get_item_node)
bn_relu = relay.Function([in_1, in_2, in_3, in_4, in_5], relu_node)
bn_relu = bn_relu.with_attr("Composite", "bn_relu")
bn_relu = bn_relu.with_attr("PartitionedFromPattern",
"nn.batch_norm_TupleGetItem0_nn.relu_")
# merged function
r = relay.Call(bn_relu, [x, gamma, beta, moving_mean, moving_var])
return relay.Function([x, gamma, beta, moving_mean, moving_var], r)
check_result(pattern_table, before(), expected())
| 7,585 |
def prepare_data_for_storage(major_version, minor_version, patch_version):
"""Prepares data to store to file.
"""
temp = Template(
u'''/*Copyright (c) 2016, Ford Motor Company\n'''
u'''All rights reserved.\n'''
u'''Redistribution and use in source and binary forms, with or without\n'''
u'''modification, are permitted provided that the following conditions are met:\n'''
u'''Redistributions of source code must retain the above copyright notice, this\n'''
u'''list of conditions and the following disclaimer.\n'''
u'''Redistributions in binary form must reproduce the above copyright notice,\n'''
u'''this list of conditions and the following\n'''
u'''disclaimer in the documentation and/or other materials provided with the\n'''
u'''distribution.\n'''
u'''Neither the name of the Ford Motor Company nor the names of its contributors\n'''
u'''may be used to endorse or promote products derived from this software\n'''
u'''without specific prior written permission.\n'''
u'''THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n'''
u'''AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n'''
u'''IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n'''
u'''ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n'''
u'''LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n'''
u'''CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n'''
u'''SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n'''
u'''INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n'''
u'''CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n'''
u'''ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n'''
u'''POSSIBILITY OF SUCH DAMAGE.\n'''
u'''*/\n'''
u'''#ifndef GENERATED_MSG_VERSION_H\n'''
u'''#define GENERATED_MSG_VERSION_H\n\n'''
u'''namespace application_manager {\n\n'''
u'''const uint16_t major_version = $m_version;\n'''
u'''const uint16_t minor_version = $min_version;\n'''
u'''const uint16_t patch_version = $p_version;\n'''
u'''} // namespace application_manager\n'''
u'''#endif // GENERATED_MSG_VERSION_H''')
data_to_file = temp.substitute(m_version = major_version, min_version = minor_version, p_version = patch_version)
return data_to_file
| 7,586 |
def flatten_mock_calls(mock):
"""
Flatten the calls performed on a particular mock object,
into a list of calls with arguments.
"""
result = []
for call in mock.mock_calls:
call = list(call)
call_name = call[0]
if '.' in str(call_name):
call_name = str(call_name).split('.')[-1]
result.append([call_name] + call[1:])
return result
| 7,587 |
def clean_setting(
name: str,
default_value: object,
min_value: int = None,
max_value: int = None,
required_type: type = None,
choices: list = None,
) -> Any:
"""cleans the user input for an app's setting in the Django settings file
Will use default_value if setting is not defined.
Will use minimum or maximum value if respective boundary is exceeded.
Args:
default_value: value to use if setting is not defined
min_value: minimum allowed value (0 assumed for int)
max_value: maximum value value
required_type: Mandatory if `default_value` is `None`,
otherwise derived from default_value
Returns:
cleaned value for setting
This function is designed to be used in a dedicated module like ``app_settings.py``
as layer between the actual settings and all other modules.
``app_settings.py`` will import and clean all settings and all other modules are supposed to import the settings it.
Example for app_settings:
.. code-block:: python
from app_utils.django import clean_setting
EXAMPLE_SETTING = clean_setting("EXAMPLE_SETTING", 10)
"""
if default_value is None and not required_type:
raise ValueError("You must specify a required_type for None defaults")
if not required_type:
required_type = type(default_value)
if min_value is None and issubclass(required_type, int):
min_value = 0
if issubclass(required_type, int) and default_value is not None:
if min_value is not None and default_value < min_value:
raise ValueError("default_value can not be below min_value")
if max_value is not None and default_value > max_value:
raise ValueError("default_value can not be above max_value")
if not hasattr(settings, name):
cleaned_value = default_value
else:
dirty_value = getattr(settings, name)
if dirty_value is None or (
isinstance(dirty_value, required_type)
and (min_value is None or dirty_value >= min_value)
and (max_value is None or dirty_value <= max_value)
and (choices is None or dirty_value in choices)
):
cleaned_value = dirty_value
elif (
isinstance(dirty_value, required_type)
and min_value is not None
and dirty_value < min_value
):
logger.warn(
"You setting for {} it not valid. Please correct it. "
"Using minimum value for now: {}".format(name, min_value)
)
cleaned_value = min_value
elif (
isinstance(dirty_value, required_type)
and max_value is not None
and dirty_value > max_value
):
logger.warn(
"You setting for {} it not valid. Please correct it. "
"Using maximum value for now: {}".format(name, max_value)
)
cleaned_value = max_value
else:
logger.warn(
"You setting for {} it not valid. Please correct it. "
"Using default for now: {}".format(name, default_value)
)
cleaned_value = default_value
return cleaned_value
| 7,588 |
def update_not_existing_kwargs(to_update, update_from):
"""
This function updates the keyword aguments from update_from in
to_update, only if the keys are not set in to_update.
This is used for updated kwargs from the default dicts.
"""
if to_update is None:
to_update = {}
to_update.update({k:v for k,v in update_from.items() if k not in to_update})
return to_update
| 7,589 |
def get_reddit():
"""Returns the reddit dataset, downloading locally if necessary.
This dataset was released here:
https://www.reddit.com/r/redditdev/comments/dtg4j/want_to_help_reddit_build_a_recommender_a_public/
and contains 23M up/down votes from 44K users on 3.4M links.
Returns a CSR matrix of (item, user, rating"""
filename = os.path.join(_download.LOCAL_CACHE_DIR, "reddit.hdf5")
if not os.path.isfile(filename):
log.info("Downloading dataset to '%s'", filename)
_download.download_file(URL, filename)
else:
log.info("Using cached dataset at '%s'", filename)
with h5py.File(filename, "r") as f:
m = f.get("item_user_ratings")
return csr_matrix((m.get("data"), m.get("indices"), m.get("indptr")))
| 7,590 |
def linear_forward(A, W, b):
"""Returns Z, (A, W, b)"""
Z = (W @ A) + b
cache = (A, W, b)
return Z, cache
| 7,591 |
def read_wave(path):
"""Reads a .wav file.
Takes the path, and returns (PCM audio data, sample rate).
"""
with contextlib.closing(wave.open(path, 'rb')) as wf:
num_channels = wf.getnchannels()
assert num_channels == 1
sample_width = wf.getsampwidth()
assert sample_width == 2
sample_rate = wf.getframerate()
assert sample_rate in (16000, 22050, 32000, 48000)
pcm_data = wf.readframes(wf.getnframes())
return pcm_data, sample_rate
| 7,592 |
def update_rho_hat(rho_hat_q, rho_hat_g, phi_hat, K, Q, Y_tp1, gamma_t, W):
"""
rho_hat is an intermediate quantity
rho_hat_{n, nu, theta}(x) = 1/n E[ sum_{t=1}^n s(X_{t-1}, X_t, Y_t | Y_{0:n}, X_n=x)]
where s() are the sufficient statistics
see Cappe (2.5)
In our case (discrete emissions HMM), it be broken down into two separable components:
rho_hat_q{n, nu, theta}(i,j,k; theta) = 1/n E[ sum_{t=1}^n I_{X_{t-1}=i, X_t=j} | Y_{0:n}, X_n=k)]
rho_hat_g{n, nu, theta}(i,k; theta) = 1/n E[ sum_{t=0}^n I_{X_t=i} s(Y_t)| Y_{0:n}, X_n=k)]
where s() here is just a multinoulli vector with W entries, so we can re-express it as
rho_hat_g{n, nu, theta}(i,w,k; theta) = 1/n E[ sum_{t=0}^n I_{X_t=i, Y_t=w}| Y_{0:n}, X_n=k)]
rho_hat_q has KxKxK entries
rho_hat_g has KxWxK entries
"""
rho_hat_q = update_rho_hat_q(rho_hat_q, phi_hat, Q, gamma_t, K)
rho_hat_g = update_rho_hat_g(rho_hat_g, Y_tp1, phi_hat, Q, gamma_t, K, W)
return rho_hat_q, rho_hat_g
| 7,593 |
def obtain_dihedral_angles(system_coords, bond_distance):
"""
system_coords: coords for 1 frame
"""
ref_selection = system_coords[0]
# Process bonds for reference frame (first)
bonds = []
sq_bond_distance = bond_distance**2
for i in range(len(ref_selection)-1):
for j in range(i+1, len(ref_selection)):
if mathTools.sq_distance(ref_selection[i], ref_selection[j]) <= sq_bond_distance:
bonds.append(tuple(sorted([i, j])))
print "DBG: Found %d bonds"%(len(bonds))
# Find angles
angles = []
for i in range(len(bonds)-1):
for j in range(i+1, len(bonds)):
if bonds_are_linked(bonds[i], bonds[j]):
angles.append(tuple(sorted([bonds[i], bonds[j]])))
print "DBG: Found %d angles"%(len(angles))
# Finally, find dihedrals
dihedrals = []
for i in range(len(angles)-1):
for j in range(i+1, len(angles)):
if angles_share_bond(angles[i], angles[j]):
dihedrals.append(tuple(sorted([angles[i], angles[j]])))
print "DBG: Found %d dihedrals"%(len(dihedrals))
# Now reorganize atoms in dihedrals so that
# they are consecutive and we can calculate the
# actual dihedral angle
r_dihedrals = []
for dihedral in dihedrals:
indices = get_dihedral_indices(dihedral)
# Get permutation of minimum distance
distances = []
for perm in itertools.permutations(indices):
#print dihedral, perm
distances.append(( mathTools.sq_distance(ref_selection[perm[0]],ref_selection[perm[1]])+
mathTools.sq_distance(ref_selection[perm[1]],ref_selection[perm[2]])+
mathTools.sq_distance(ref_selection[perm[2]],ref_selection[perm[3]]),
perm))
# We will pick the one which summed distances is smaller
distances.sort()
r_dihedrals.append(distances[0][1])
all_angles = []
for ref in system_coords:
#Calculate the angles for a ref
angles = []
for dihedral_indexes in r_dihedrals:
atom1 = ref[dihedral_indexes[0]]
atom2 = ref[dihedral_indexes[1]]
atom3 = ref[dihedral_indexes[2]]
atom4 = ref[dihedral_indexes[3]]
angles.append( mathTools.calc_dihedral(atom1, atom2, atom3, atom4))
all_angles.append(angles)
return numpy.array(all_angles)
| 7,594 |
def piecewise_accel(duration,initial,final):
"""Defines a piecewise acceleration.
Args:
duration (float): Length of time for the acceleration to complete.
initial (float): Initial value.
final (float): Final value.
"""
a = (final-initial)
return lambda t: initial + a * (
(9./2 * t**3/duration**3) * (t<duration/3)
+ (-9*t**3/duration**3 + 27./2*t**2/duration**2 - 9./2*t/duration + 1./2) * (t<2*duration/3)*(t>=duration/3)
+ (9./2*t**3/duration**3 - 27./2 * t**2/duration**2 + 27./2*t/duration - 7./2) * (t>= 2*duration/3))
| 7,595 |
def download_data(symbols, from_date):
"""Download the desired symbol data from specified date to today, with a daily basis."""
curr_date = datetime.now()
from_date = datetime.strptime(from_date, '%Y-%m-%d')
for symbol in symbols:
link = "http://chart.finance.yahoo.com/table.csv?s={}&a={}&b={}&c={}&d={}&e={}&f={}&g=d&ignore=.csv".format(
symbol, from_date.month - 1, from_date.day, from_date.year, curr_date.month - 1, curr_date.day, curr_date.year)
file_name = "data\{}.csv".format(symbol)
print "Downloading {}...".format(file_name)
urllib.urlretrieve(link, file_name)
| 7,596 |
def get_displayed_views(id):
"""
get views in window rect by view id str
:param res_id:
:return:
"""
return get_solo().get_displayed_views(id)
| 7,597 |
def get_build_version(xform):
"""
there are a bunch of unreliable places to look for a build version
this abstracts that out
"""
version = get_version_from_build_id(xform.domain, xform.build_id)
if version:
return version, BuildVersionSource.BUILD_ID
version = get_version_from_appversion_text(
get_meta_appversion_text(xform)
)
if version:
return version, BuildVersionSource.APPVERSION_TEXT
xform_version = xform.version
if xform_version and xform_version != '1':
return int(xform_version), BuildVersionSource.XFORM_VERSION
return None, BuildVersionSource.NONE
| 7,598 |
def get_shortlist(routing_table: 'TreeRoutingTable', key: bytes,
shortlist: typing.Optional[typing.List['KademliaPeer']]) -> typing.List['KademliaPeer']:
"""
If not provided, initialize the shortlist of peers to probe to the (up to) k closest peers in the routing table
:param routing_table: a TreeRoutingTable
:param key: a 48 byte hash
:param shortlist: optional manually provided shortlist, this is done during bootstrapping when there are no
peers in the routing table. During bootstrap the shortlist is set to be the seed nodes.
"""
if len(key) != constants.HASH_LENGTH:
raise ValueError("invalid key length: %i" % len(key))
return shortlist or routing_table.find_close_peers(key)
| 7,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.