content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _add_capture_metadata_collate(dataloader: DataLoader) -> None:
"""Wrap default collate function to retrive captured dataset state dict when fault tolerant is enabled."""
faut_tolerant_mode = _FaultTolerantMode.detect_current_mode()
if not faut_tolerant_mode.is_enabled:
return
dataloader.coll... | 5,317,700 |
def predict_posterior_marginals(
F, features, mean, kernel, chol_fact, pred_mat, test_features,
test_intermediates=None):
"""
Computes posterior means and variances for test_features.
If pred_mat is a matrix, so will be posterior_means, but not
posterior_variances. Reflects the fact that... | 5,317,701 |
def ffmpeg_video(
fig: mfig.Figure, update_func: callable, points: int, fps: int, outf: str
):
"""Generates output video given a animation function via ffmpeg
Args:
fig (matplotlib.figure.Figure): matplotlib figure instance
update_func (callable): animation function from Attractors class
... | 5,317,702 |
def rule_ContributesLight_possessions_can_light_person(x, world) : # maybe should handle concealment at some point?
"""A person contributes light if any of their posessions contribute light."""
if any(world[ContributesLight(o)] for o in world[Contents(x)]) :
return True
else : raise NotHandled() | 5,317,703 |
def update_keras_bn_ops_trainable_flag(model: tf.keras.Model, trainable: bool, load_save_path: str) -> tf.keras.Model:
"""
helper method to update Keras BN ops trainable state in a given keras model.
:param model: Keras model to be updated with BN ops trainable flag
:param trainable: bool flag to indic... | 5,317,704 |
def xml():
""" Return an XML response with an HTTP 200 OK status """
data: str = """<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.example.com/</loc>
<lastmod>2005-01-01</lastmod>
<changefreq>monthly</changefreq>
... | 5,317,705 |
def read_device_files(directory_paths: Iterable[pathlib.Path]) -> DeviceFileInfo:
"""Read data from files contained on an mbed enabled device's USB mass storage device.
If details.txt exists and it contains a product code, then we will use that code. If not then we try to grep the
code from the mbed.htm fi... | 5,317,706 |
def max_rl(din):
"""
A MAX function should "go high" only when all of
its inputs have arrived. Thus, AND gates are
used for its implementation.
Input: a list of 1-bit WireVectors
Output: a 1-bit WireVector
"""
if len(din) == 1:
dout = din[0]
else:
... | 5,317,707 |
def compute_success(
classifier: "CLASSIFIER_TYPE",
x_clean: np.ndarray,
labels: np.ndarray,
x_adv: np.ndarray,
targeted: bool = False,
batch_size: int = 1,
) -> float:
"""
Compute the success rate of an attack based on clean samples, adversarial samples and targets or correct labels.
... | 5,317,708 |
def set_up_basic_stubs(app_id):
"""Set up a basic set of stubs.
Configures datastore and memcache stubs for testing.
Args:
app_id: Application ID to configure stubs with.
Returns:
Dictionary mapping stub name to stub.
"""
apiproxy_stub_map.apiproxy = apiproxy_stub_map.APIProxyStubMap()
ds_stub ... | 5,317,709 |
def send_notification(slack, message, channel):
"""Send notification to Slack channel (i.e. sc2)."""
slack.chat.post_message(channel=channel, text=message, username="sc2 bot") | 5,317,710 |
def _repack_archive (archive1, archive2, verbosity=0, interactive=True):
"""Repackage an archive to a different format."""
format1, compression1 = get_archive_format(archive1)
format2, compression2 = get_archive_format(archive2)
if format1 == format2 and compression1 == compression2:
# same form... | 5,317,711 |
def backup_db():
"""
To backup mongo databases and save it to a directory called dump.bak
"""
try:
subprocess.check_output(['ls dump'], shell=True);
subprocess.check_call(['rm -rf dump*'], shell=True)
except subprocess.CalledProcessError:
pass
subprocess.check_call(['mong... | 5,317,712 |
def _load_init_model_weights(
model_fn: Callable[[],
tff.learning.Model]) -> List[tff.learning.ModelWeights]:
"""Load model weights to warm-start HypCluster."""
state_manager = tff.program.FileProgramStateManager(FLAGS.warmstart_root_dir)
learning_process_for_metedata = tff.learning.alg... | 5,317,713 |
def process_request(url, auth):
"""Perform an http request.
:param url: full url to query
:type url: ``str``
:param auth: username, password credentials
:type auth: ``tuple`` || ``None``
:returns: ``dict``
"""
content = requests.get(url, auth=auth)
if content.status_code >= 300:
... | 5,317,714 |
def close_channel(sender_addr, receiver_addr,channel_name):
"""
:param sender_addr: String, the sender address
:param receiver_addr: String, receiver's address
:param channel_name: String, channel name
:return:
"""
sender, receiver = split_channel_name(channel_name)
ch = Channel(sender, ... | 5,317,715 |
def get_proj_edges(edges: Collection[Tuple[int, int]]) -> Iterator[Tuple[int, int]]:
"""Obtain projective edges from a collection of edges of a dependency tree."""
adj_set: dict = defaultdict(set)
for u, v in edges:
adj_set[u].add(v)
def dfs(root: int) -> Set[int]:
stack, seen = [root],... | 5,317,716 |
def convertClrs(clr: Union[dict[Any, Union[str, Color]], Color], conversion: str) -> Union[str, tuple, dict, None]:
"""
Convert color values to HEX and vice-versa
@clr: Color value to convert.
@conversion: Type of conversion to do ('RGB' or 'HEX')
"""
if isinstance(clr, dict): # its a dict, call itself with the... | 5,317,717 |
def fuzzy_op(x, a, y, b, op):
"""Operation of two fuzzy sets.
Operate fuzzy set ``a`` with fuzzy set ``b``,
using +, * or any other binary operator.
Parameters
----------
x : 1d array, length N
Universe variable for fuzzy set ``a``.
a : 1d array, length N
Fuzzy set for ... | 5,317,718 |
def check_int(item):
"""
:param item: txtcrtl containing a value
"""
flag = True
try:
mini = int(item.GetValue())
item.SetBackgroundColour(wx.WHITE)
item.Refresh()
except:
flag = False
item.SetBackgroundColour("pink")
item.Refresh()
return flag | 5,317,719 |
def main():
""" report pv usage """
logger.info('################################################################################')
logger.info(' Starting Volume Snapshot Tag Checks - %s', datetime.datetime.now().strftime("%Y-%m-%d %H:%M"))
logger.info('###############################################... | 5,317,720 |
def assign_incident_role(
db_session: SessionLocal,
incident: Incident,
reporter_email: str,
role: ParticipantRoleType,
):
"""Assigns incident roles."""
# We resolve the incident role email
# default to reporter if we don't have an oncall plugin enabled
assignee_email = reporter_email
... | 5,317,721 |
def _del_func(path: str):
"""Delete a function that is denoted by a path.
Args:
path (str): The path to evaluate.
"""
split_path = path.split('.')
for i in range(len(split_path), 0, -1):
try:
exec('import {}'.format('.'.join(split_path[:i])))
break
e... | 5,317,722 |
def load_h5py(path):
"""Loads datasets from a file.
params:
path: A string, which is a path to the dataset
return: A dictionary, which contains the dataset
"""
dataset = {}
with h5py.File(path, 'r') as hf:
if 'train_x' in hf:
dataset['train_x'] = hf['train_x'][:]
... | 5,317,723 |
def from_timedelta(val):
"""escape a python datetime.timedelta"""
sec = int(val.total_seconds())
hour = sec // 3600
sec = sec % 3600
mns = sec // 60
sec = sec % 60
msec = val.microseconds
return _time(hour, mns, sec, msec) | 5,317,724 |
def read_and_convert_qc(data_group, qc_paths):
"""Converts the QC of Smart Seq2 gene file pipeline outputs to zarr file
Args:
data_group (zarr.hierarchy.Group): zarr group to add the datasets
qc_path (str): path to the QCs csv
"""
# read the QC values
qc_path = [p for p in qc_paths i... | 5,317,725 |
def stringify_column(df: DataFrame, column: str) -> DataFrame:
"""Takes dataframe and column that contains array structures. Stringify that column values."""
array_to_string_udf = udf(array_to_string, StringType())
df = df.withColumn(column, array_to_string_udf(df[column]))
return df | 5,317,726 |
def get_os():
"""
Get operating system.
:return: operating system
:rtype: str or unicode
"""
return platform.platform() | 5,317,727 |
def powerLaw(y, x):
"""
'When the frequency of an event varies as power of some attribute of that
event the frequency is said to follow a power law.' (wikipedia)
This is represented by the following equation, where c and alpha are
constants:
y = c . x ^ alpha
Args
--------
y: array w... | 5,317,728 |
def _separate_talairach_levels(atlas_img, labels, verbose=1):
"""Separate the multiple annotation levels in talairach raw atlas.
The Talairach atlas has five levels of annotation: hemisphere, lobe, gyrus,
tissue, brodmann area. They are mixed up in the original atlas: each label
in the atlas correspond... | 5,317,729 |
def play_animation():
"""
plays opening animation
"""
hou.setFrame(1)
hou.playbar.play() | 5,317,730 |
def merge(a, b):
"""
Hierarchical merge of dictionaries, lists, tuples and sets.
If b is None, it keeps a, otherwise it merges with a.
In case of ambiguities, b overrides a
it returns is a deepcopy, not a reference of the original objects.
"""
if isinstance(b, dict) and isinstance(a, dict):... | 5,317,731 |
def block_inception_a(blk, net):
"""Builds Inception-A block for Inception v4 network."""
# By default use stride=1 and SAME padding
s = net.add(Split('%s/Split' % blk, 4))
br0 = conv2d(net, '%s/Branch_0/Conv2d_0a_1x1' % blk, 96, 1, src=s)
conv2d(net, '%s/Branch_1/Conv2d_0a_1x1' % blk, 64, 1, src=s)... | 5,317,732 |
def project_list(ctx, filter):
"""list all projects"""
logger.debug("")
# try:
check_client_version(ctx.obj, ctx.command.name)
resp = ctx.obj.project.list(filter)
# except ClientException as e:
# print(str(e))
# exit(1)
table = PrettyTable(['name', 'id'])
for proj in resp... | 5,317,733 |
def mgas(sg, sp, gpotential, potential, xv, dt, kappa=1.0, alpha=1.0):
"""
Evolve satellite gas mass due to tidal stripping, by an amount of
[m - m(l_rp)] * dt / t_dyn
where m is the satellite gas mass; m(l_rp) is the satellite gas mass
within ram pressure radius l_rp; dt is the timestep size;... | 5,317,734 |
def genpass(pwds_amount=1, paswd_length=8):
""" Returns a list of 'pwds_amount' random passwords, having length of 'paswd_length' """
import random
return [ ''.join([chr(random.randint(32, 126)) for _ in range(paswd_length)]) for _ in range(pwds_amount)] | 5,317,735 |
def collect_fastq_data_irma(fc_root, fc_proj_src, proj_root=None, pid=None):
"""Collect the fastq files that have to be removed from IRMA
return a tuple with files and total size of collected files"""
size = 0
file_list = {'flowcells': defaultdict(dict)}
fc_proj_path = os.path.join(fc_root, fc_proj_... | 5,317,736 |
def _gini(x):
"""
Memory efficient calculation of Gini coefficient in relative mean difference form
Parameters
----------
x : array-like
Attributes
----------
g : float
Gini coefficient
Notes
-----
Based on http://www.statsdirect.com/help/default.htm#nonparametri... | 5,317,737 |
def _AddListFieldsMethod(message_descriptor, cls):
"""Helper for _AddMessageMethods()."""
# Ensure that we always list in ascending field-number order.
# For non-extension fields, we can do the sort once, here, at import-time.
# For extensions, we sort on each ListFields() call, though
# we could do better i... | 5,317,738 |
def render_edit_view(request, form_name, nid):
"""according resource primary key,render edit view
Arguments:
request {object} -- wsgi http request object
form_name {str} -- resources type name
nid {int} -- resources id
Returns:
html -- html template
"""
... | 5,317,739 |
def seek_table(file_handle):
"""Advance file_handle to the beginning of the table."""
line = ''
pos = 0
while not TABLE_HEADER_PATTERN.match(line):
pos = file_handle.tell()
line = file_handle.readline()
file_handle.seek(pos) | 5,317,740 |
def test_default_str_length():
"""Test the default length of __str__."""
x = UniformUncertain()
s = str(x)
n_lines = len(s.splitlines())
assert_equal(n_lines, 6) | 5,317,741 |
def print_results(args):
"""Print all comics that have at least the given number of minimum comic strips."""
min_comics, filename = args
min_comics = int(min_comics)
with codecs.open(filename, 'a', 'utf-8') as fp:
for name, entry in sorted(load_result(json_file).items()):
if name in ... | 5,317,742 |
def decrypt_default_password(message):
"""
You Can Use this for internal data (Aka Non-User controlled data) that needs to be encrypted.
:param message:
:return:
"""
if type(message) == bytes:
f = Fernet(getkey(Settings.ENCRYPTION_PASSWORD))
decrypted = f.decrypt(message)
... | 5,317,743 |
def getfeed(user):
"""Test post
:user: Stuff from the interwebs
:returns: stuff to the interwebs
"""
response = jsonify({'result_count': 'This is ' + user + '\'s feed!'})
response.headers.add('Access-Control-Allow-Origin', '*')
return response | 5,317,744 |
def plot_confusion_matrix(y_true, y_pred, classes,
normalize=False,
title=None,
cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
# i... | 5,317,745 |
def variables_and_orphans(i, o):
"""
Extract list of variables between i and o nodes via
dfs traversal and chooses the orphans among them
Parameters
----------
i : list
Input variables.
o : list
Output variables.
"""
def expand(r):
if r.owner and r not in... | 5,317,746 |
def p_expression_statement(p):
"""expression_statement : ';'
| expression ';'
""" | 5,317,747 |
def get_collected_quotas():
"""获取我的收藏"""
form = PaginationForm().validate_for_api()
per_page = current_app.config['COUNT_DEFAULT']
current_uer = get_current_user()
paginate = paginate_data(current_uer.not_deleted_collected_quotas, form.page.data, per_page)
return jsonify(paginate) | 5,317,748 |
def main(
gcal_calendar: str,
google_secret: str,
oauth_port: int,
tw_tags: List[str],
tw_project: str,
resolution_strategy: str,
verbose: int,
combination_name: str,
custom_combination_savename: str,
do_list_combinations: bool,
):
"""Synchronize calendars from your Google Ca... | 5,317,749 |
def image_from_url(url):
"""
Download image from url
:param url: url of image
:return: image Pillow object
"""
response = requests.get(url)
return Image.open(BytesIO(response.content)) | 5,317,750 |
def vect3_scale(v, f):
"""
Scales a vector by factor f.
v (3-tuple): 3d vector
f (float): scale factor
return (3-tuple): 3d vector
"""
return (v[0]*f, v[1]*f, v[2]*f) | 5,317,751 |
def update_dummy_points(fisnar_command_list, home_coords):
"""
given a list of fisnar commands and home coordinates, search through the fisnar commands and modify the coordinates
of every Dummy Point with the coordinates [-99, -99, -99] command to be at the home position. This function
essentially inte... | 5,317,752 |
def test_string_trunc_pad():
"""
# Combining truncating and padding
It is also possible to combine truncating and padding:
"""
old_result = '%-10.5s' % ('xylophone', )
new_result = '{:10.5}'.format('xylophone')
assert old_result == new_result
assert new_result == 'xylop ' | 5,317,753 |
def plot_train_val(m_train, m_val, period=1,
al_param=False, metric='Cross-Entropy Loss', save=True, model_name=''):
"""Plot the evolution of the metric evaluated on the training and validation set during the trainining
Args:
m_train: history of the metric evaluated on the train
... | 5,317,754 |
def segment_max(data: Array,
segment_ids: Array,
num_segments: Optional[int] = None,
indices_are_sorted: bool = False,
unique_indices: bool = False,
bucket_size: Optional[int] = None,
mode: Optional[lax.GatherScatterMode] = ... | 5,317,755 |
def _recursive_pad(nested: List[Any], fill_value: Optional[Any] = None) -> np.array:
"""Pads a jagged nested list of lists with the given value such that a proper multi-dimensional array can be
formed with rectangular shape. The padding appends to the incomplete lists.
Example::
>>> _recursive_pad(... | 5,317,756 |
def do_ptp_interface_show(cc, args):
"""Show PTP interface attributes."""
try:
ptp_interface = cc.ptp_interface.get(args.ptp_interface_uuid)
except exc.HTTPNotFound:
raise exc.CommandError('PTP interface not found: %s'
% args.ptp_interface_uuid)
_print_ptp_... | 5,317,757 |
def create_all(checkfirst: bool = True) -> None:
"""Create all tables."""
Base.metadata.create_all(checkfirst=checkfirst) | 5,317,758 |
def create_trigger_body(trigger):
"""Given a trigger, remove all keys that are specific to that trigger
and return keys + values that can be used to clone another trigger
https://googleapis.github.io/google-api-python-client/docs/dyn/tagmanager_v2.accounts.containers.workspaces.triggers.html#create
:p... | 5,317,759 |
def load_logged_in_user():
"""If a user id is stored in the session, load the user object from
the database into ``g.user``"""
user_id = session.get('user_id')
if user_id is None:
g.user = None
else:
g.user = (
get_db().execute('SELECT * FROM user WHERE id = ?', (use... | 5,317,760 |
def is_less_or_equal(hash_1: Union[str, bytes],
hash_2: Union[str, bytes]) -> bool:
"""check hash result."""
if isinstance(hash_1, str):
hash_1 = utils.hex_str_to_bytes(hash_1)
if isinstance(hash_2, str):
hash_2 = utils.hex_str_to_bytes(hash_2)
assert isinstance(hash... | 5,317,761 |
def get_video_id(url):
""" Get YouTube video ID from YouTube URL
Args:
url (str): YouTube URL.
Returns:
YouTube id
"""
if not url:
return ""
# If URL is embedded
if "embed" in url:
return url.split("/")[-1]
parse_result = urlparse(url)
query = par... | 5,317,762 |
def running_under_virtualenv():
# type: () -> bool
"""
Return True if we're running inside a virtualenv, False otherwise.
"""
if hasattr(sys, 'real_prefix'):
# pypa/virtualenv case
return True
elif sys.prefix != getattr(sys, "base_prefix", sys.prefix):
# PEP 405 venv
... | 5,317,763 |
def _tile_to_image_size(tensor, image_shape):
"""Inserts `image_shape` dimensions after `tensor` batch dimension."""
non_batch_dims = len(tensor.shape) - 1
for _ in image_shape:
tensor = tf.expand_dims(tensor, axis=1)
tensor = tf.tile(tensor, [1] + image_shape + [1] * non_batch_dims)
return tensor | 5,317,764 |
def gen_flow_data1(trajectory, time_dividing_point):
"""
:param trajectory:
:param time_dividing_point:
:return: ['time', 'row_id', 'column_id', 'inflow', 'outflow']
"""
trajectory = trajectory[
(trajectory.prev_row_id != trajectory.row_id) |
(trajectory.prev_column_id != traject... | 5,317,765 |
def merge(source, destination):
"""
ensures DESTINATION has a single copy of each song; .m4a format preferred
"""
# DESTINATION
# / <album>
# / song
for path, dirs, files in source.walk():
files.sort(key=lambda f: f.ext)
for song in files:
... | 5,317,766 |
def _expand_paths_itr(paths, marker='*'):
"""Iterator version of :func:`expand_paths`.
"""
for path in paths:
if is_path(path):
if marker in path: # glob path pattern
for ppath in sglob(path):
yield ppath
else:
yield path ... | 5,317,767 |
def icp3d(src, trgt, abs_tol=1e-8, max_iter=500, verbose=True):
"""
Parameters
----------
src : numpy array
Source object. Each row should be a point with (X, Y, Z) columns.
trgt : numpy array
Target object. Each row should be a point with (X, Y, Z) columns.
abs_tol : float, opt... | 5,317,768 |
def event_type(event):
"""
.. function:: event_type(event)
Return pygame event type.
"""
return getattr(pygame, event) | 5,317,769 |
def player_wins(player):
"""Proceed player wins' scenario."""
player.chips.win_bet()
print(f'Congratulations! {player.name} wins the game with {player.hand.value} points!')
print(f'+ {player.chips.bet} chips points. {player.chips.total} chips points total.') | 5,317,770 |
def ULA(step, N, n):
""" MCMC ULA
Args:
step: stepsize of the algorithm
N: burn-in period
n: number of samples after the burn-in
Returns:
traj: a numpy array of size (n, d), where the trajectory is stored
traj_grad: numpy array of size (n, d), where the gradients of t... | 5,317,771 |
def test_init_predictor():
"""Test init method of Predictor class."""
predictor = Predictor()
assert predictor.to_path == "save"
assert predictor.verbose | 5,317,772 |
def run(raven, info):
"""
A dummy model used to check the connections for the EnsembleModel
@ In, raven, object, object to store members on
@ In, info, dict, dictionary containing inputs from RAVEN
@ Out, None
"""
x = np.linspace(0,1,3)
y = np.linspace(0,1,3)
c = np.zeros((len(x), len(y)))
c... | 5,317,773 |
def test_photoslibrary_folder_by_uuid(photoslib):
""" test getting folder by UUID """
import photoscript
folder = photoslib.folder(uuid=FOLDER_UUID)
assert isinstance(folder, photoscript.Folder)
assert folder.name == FOLDER_NAME | 5,317,774 |
def add_new_book(path):
"""Add a new book to the current book list."""
book = Book()
# Add the new book to the list
add_changes(book_list_exists(path)[0], book, path)
# Save the new book to the book list
question = input('Do you want to save the changes?\n> ')
if question in truthy_values:... | 5,317,775 |
def get_parameters(parameters):
"""Get parameters from a function definition"""
params_out = {}
for parameter in parameters:
param_out = {}
# TODO
# Resolve meta refs
# if "$ref" in param.keys():
# meta_path = param["$ref"].split("/")
# del meta_path... | 5,317,776 |
def openbabel_mol_to_rdkit_mol(obmol: 'openbabel.OBMol',
remove_hs: bool = False,
sanitize: bool = True,
embed: bool = True,
) -> 'RWMol':
"""
Convert a OpenBabel molecular structure to a ... | 5,317,777 |
def test_telemetry_server_get_types():
"""Test that the type manifest can be successfully requested."""
server = TelemetryServer(0.01, 0.10, 0.25)
with server.booted():
# add a client
server.udp_clients.add_client(Host())
# get app id
cmd_str = "types?indent=4"
res... | 5,317,778 |
def get_display_name(record):
"""Get the display name for a record.
Args:
record
A record returned by AWS.
Returns:
A display name for the bucket.
"""
return record["Name"] | 5,317,779 |
def RadialToTortoise(r, M):
"""
Convert the radial coordinate to the tortoise coordinate
r = radial coordinate
M = ADMMass used to convert coordinate
return = tortoise coordinate value
"""
return r + 2. * M * math.log( r / (2. * M) - 1.) | 5,317,780 |
def extract_leaves(
tree_dict: StrDict,
) -> Set[str]:
"""
Extract a set with the SMILES of all the leaf nodes, i.e.
starting material
:param tree_dict: the route
:return: a set of SMILE strings
"""
def traverse(tree_dict: StrDict, leaves: Set[str]) -> None:
children = tree_dic... | 5,317,781 |
def Main():
"""Runs the unit test."""
# We must call _ParseAndStripGTestFlags() before calling
# unittest.main(). Otherwise the latter will be confused by the
# --gtest_* flags.
_ParseAndStripGTestFlags(sys.argv)
# The tested binaries should not be writing XML output files unless the
# script explicitly... | 5,317,782 |
def station_matcher(
data_stream_df,
ses_directory="../data/seattle_ses_data/ses_data.shp"):
""" Matches Purple Air data with census tracts
This function reads in the census-tract-level socioenconomic
dataset and joins it with the input Purple Air DataStreams.
Args:
data_stream_df... | 5,317,783 |
def weekdays(start_date, end_date):
"""
Returns a generator with the dates of the week days between the start and end date
.. code-block:: python
start_date = datetime.date(2016, 10, 3) # Monday
end_date = datetime.date(2016, 10, 7) # Friday
days = list(weekdays(start_date, end_d... | 5,317,784 |
def running(pid):
"""
pid: a process id
Return: False if the pid is None or if the pid does not match a
currently-running process.
Derived from code in http://pypi.python.org/pypi/python-daemon/ runner.py
"""
if pid is None:
return False
try:
os.kill(pid, signal.SIG_DFL)
... | 5,317,785 |
def get_pulls_list(project, github_api=3):
"""get pull request list
github_api : version of github api to use
"""
if github_api == 3:
url = f"https://api.github.com/repos/{project}/pulls"
else:
url = f"http://github.com/api/v2/json/pulls/{project}"
response = requests.get(url)
... | 5,317,786 |
def add_card(fname: str, view_id: str, card_config: str,
position: int = None, data_format: str = FORMAT_YAML):
"""Add a card to a view."""
config = load_yaml(fname)
for view in config.get('views', []):
if view.get('id') != view_id:
continue
cards = view.get('cards',... | 5,317,787 |
def get_version(*file_paths):
"""Retrieves the version from flexible_reports/__init__.py"""
filename = os.path.join(os.path.dirname(__file__), *file_paths)
version_file = open(filename).read()
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re... | 5,317,788 |
def get_articles(id):
"""
Function that gets the json response to our url request
"""
get_sources_news_url = source_url.format(id,api_key)
with urllib.request.urlopen(get_sources_news_url)as url:
get_news_data = url.read()
get_news_response = json.loads(get_news_data)
news_r... | 5,317,789 |
def run():
"""Run all the fuzzing tests"""
fuzz_parse_call()
fuzz_parse_peal_speed() | 5,317,790 |
def read_chunk(path, start_offset, end_offset, delete_me_entire_func_maybe):
"""
Return only if 100% successful.
"""
try:
with open(path, 'rb') as f:
f.seek(start_offset)
return f.read(end_offset - start_offset)
except FileNotFoundError as e:
raise e | 5,317,791 |
def returnBestAddress(genes, loop):
"""Searches for available genes matching kegg enzyme entry.
This function searches 'sequentially'. It returns the best available model
organism genes. Organisms phylogenetically closer to Cricetulus griseus are
preferred, but they are chosen by approximation. A detai... | 5,317,792 |
def set_aspect_ratio(obj_axis):
# type: (Tuple) -> object
"""Fine-tune matrix plot aspect ratio
Args:
obj_axis (object): a matplotlib axis object
Returns:
same as inputs
"""
obj_axis.set_aspect(
'auto', adjustable="box-forced", anchor="SW")
return | 5,317,793 |
def is_name_like_value(
value: Any, allow_none: bool = True, allow_tuple: bool = True, check_type: bool = False
) -> bool:
"""
Check the given value is like a name.
Examples
--------
>>> is_name_like_value('abc')
True
>>> is_name_like_value(1)
True
>>> is_name_like_value(None)
... | 5,317,794 |
def get_uptime(then):
"""
then: datetime instance | string
Return a string that informs how much time has pasted from the provided
timestamp.
"""
if isinstance(then, str):
then = dt.datetime.strptime(then, "%Y-%m-%dT%H:%M:%SZ")
now = dt.datetime.now()
diff = now - then.replace(... | 5,317,795 |
def _create_kube_config_gcloud_entry(cluster_name, cluster_zone, project):
"""Uses GCloud CLI to create an entry for Kubectl.
This is needed as we install the charts using kubectl, and it needs the correct config
Args:
cluster_name (str): Name of cluster
cluster_zone (str): Zone of cluster... | 5,317,796 |
def gaussian2kp(heatmap, kp_variance='matrix', clip_variance=None):
"""
Extract the mean and the variance from a heatmap
"""
shape = heatmap.shape
#adding small eps to avoid 'nan' in variance
heatmap = heatmap.unsqueeze(-1) + 1e-7
grid = make_coordinate_grid(shape[3:], heatmap.type()).unsque... | 5,317,797 |
def BRepBlend_HCurve2dTool_Circle(*args):
"""
:param C:
:type C: Handle_Adaptor2d_HCurve2d &
:rtype: gp_Circ2d
"""
return _BRepBlend.BRepBlend_HCurve2dTool_Circle(*args) | 5,317,798 |
def scan_and_create_dir_tree(path, file=True):
"""
Creates all the necessary directories for the file at the end of path to be created.
When specified with a filepath to a file or folder, it creates directories until the path is valid.
:param Path path: must end with a filename, else the final directo... | 5,317,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.