content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def get_default_args(func):
"""
returns a dictionary of arg_name:default_values for the input function
"""
if not callable(func):
raise TypeError("%s is not callable" % type(func))
if inspect.isfunction(func):
print('a')
spec = inspect.getargspec(func)
elif hasattr(func, ... | 5,302,400 |
def test_update_conflict():
"""Test that update works when not extending and a field is redefined"""
more_pif = System(
properties=[
Property(name="band gap", scalars=[Scalar(value=1.3)]),
Property(name="phase", scalars=[Scalar(value="gas")]),
]
)
combined = updat... | 5,302,401 |
def git_am_patch_split(f, encoding=None):
"""Parse a git-am-style patch and split it up into bits.
:param f: File-like object to parse
:param encoding: Encoding to use when creating Git objects
:return: Tuple with commit object, diff contents and git version
"""
encoding = encoding or getattr(f... | 5,302,402 |
def compute_retrieval_cosine(dot_product: np.ndarray) -> Tuple[Dict[str, float], np.ndarray, np.ndarray]:
"""
Args:
dot_product: Result of computing cosine similarity between two sets of embeddings (emb1 @ emb2.T)
with shape (num_datapoints, num_datapoints).
Returns:
Retr... | 5,302,403 |
def makeSVGedge(e):
"""
"""
cs = StringIO.StringIO()
curve = e._geomAdaptor() # adapt the edge into curve
start = curve.FirstParameter()
end = curve.LastParameter()
points = GCPnts_QuasiUniformDeflection(curve, DISCRETIZATION_TOLERANCE, start, end)
if points.IsDone():
point... | 5,302,404 |
def create(dst, creator='Pyth'):
"""Create output file. Return handle and first id to use."""
try:
os.unlink(dst)
except os.error:
pass
Res.FSpCreateResFile(dst, creator, 'rsrc', smAllScripts)
return open(dst) | 5,302,405 |
def xmlindent(elem, level=0, spacer=' '):
"""
Indents the inputted XML element based on the given indent level.
:param elem | <xml.etree.Element>
"""
i = "\n" + level * spacer
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + spacer
... | 5,302,406 |
def create_and_join_world(
connection: dm_env_rpc_connection.Connection,
create_world_settings: Mapping[str, Any],
join_world_settings: Mapping[str, Any],
requested_observations: Optional[Iterable[str]] = None,
extensions: Optional[Mapping[str, Any]] = immutabledict.immutabledict()
) -> DmEnvAndWorl... | 5,302,407 |
def setup_stream_handlers(conf):
"""Setup logging stream handlers according to the options."""
class StdoutFilter(logging.Filter):
def filter(self, record):
return record.levelno in (logging.DEBUG, logging.INFO)
log.handlers = []
stdout_handler = logging.StreamHandler(sys.s... | 5,302,408 |
def Hyperparameter_Tune_model(use_choosen_model=True, model=None,
RFR_dict=None, df=None, cv=3,
testset='Test set (strat. 20%)', target='Iodide',
features_used=None, model_name=None,
save_best_estimat... | 5,302,409 |
def test_competitive_reed_frost(network, time_step=(1., 2.), transmission_rate=(.1, .2), verbose=False,
plot=False):
"""Run competitve reedfrost on network"""
epidemic = competitive.SirReedFrost(network, time_step=time_step, transmission_rate=transmission_rate,
... | 5,302,410 |
def process_id(input_ids,
vocab_table,
PAD,
max_len=None,
min_len=None):
"""Converts input ids (in text string) into their indices in vocab
:param input_ids Tensor Id features. Shape=[group_size]
:param vocab_table TFLookupTable Vocab table for id... | 5,302,411 |
def test_recurring_jobs_when_volume_detached_unexpectedly(settings_reset, set_random_backupstore, client, core_api, apps_api, pvc, make_deployment_with_pvc): # NOQA
"""
Test recurring jobs when volume detached unexpectedly
Context:
If the volume is automatically attached by the recurring backup job,
... | 5,302,412 |
def dlcs_parse_xml(data, split_tags=False):
"""Parse any del.icio.us XML document and return Python data structure.
Recognizes all XML document formats as returned by the version 1 API and
translates to a JSON-like data structure (dicts 'n lists).
Returned instance is always a dictionary. Examples::
... | 5,302,413 |
def shutdown_session(exception=None):
"""
Cleans up after a request has been served.
"""
if exception:
## This should include the request and the traceback as well:
app.logger.error(str(exception))
Session.remove() | 5,302,414 |
def now_datetime(offset = 0):
"""
A function to return the current datetime.
"""
return adddays(offset, datetime.datetime.today()) | 5,302,415 |
def generate_data(num_students=NUM_STUDENTS,
num_items=NUM_ITEMS,
num_responses=NUM_RESPONSES,
prob_correct=PROB_CORRECT):
""" Simulate student response data (independently of any parameters).
:param int num_students: Number of unique student ids.
:para... | 5,302,416 |
def ast_name_node(**props):
"""
creates a name ast node with the property names and values
as specified in `props`
"""
node = ast.Name()
for name, value in props.items():
setattr(node, name, value)
return node | 5,302,417 |
def _prepend_min(arr, pad_amt, num, axis=-1):
"""
Prepend `pad_amt` minimum values along `axis`.
Parameters
----------
arr : ndarray
Input array of arbitrary shape.
pad_amt : int
Amount of padding to prepend.
num : int
Depth into `arr` along `axis` to calculate minim... | 5,302,418 |
def list_experiments(ctx):
""" Lists project experiments
"""
log.debug("Listing all project experiments")
# TODO: List experiments
# TODO: Add ability to list trials | 5,302,419 |
def buildX(traj_file, t, X):
"""
Builds the node attribute matrix for a given time step.
Inputs:
traj_file : string indicating the location of the ground truth trajectory data
t : scalar indicating current time step
X : empty node attribute matrix in shape [n_nodes, n_features]
Outputs:
... | 5,302,420 |
def log_error(msg):
"""
记录Error级日志
:param msg:[any]日志内容
:return:[None]
"""
_ErrorLogger.error(msg) | 5,302,421 |
def eval_chain(fractions):
"""Compute best rational approximation of a sequence of fractions
"""
n1, n2 = 1, 0
d1, d2 = 0, 1
for a in fractions:
# print('a', a)
for b in range(int((a+1)/2), a+1):
yield (b*n1+n2, b*d1+d2)
n1, n2 = a*n1+n2, n1
d1, d2 = a*d1... | 5,302,422 |
def get_surface_id_from_canvas(canvas):
"""Get an id representing the surface to render to. The way to
obtain this id differs per platform and GUI toolkit.
"""
win_id = canvas.get_window_id()
if sys.platform.startswith("win"): # no-cover
struct = ffi.new("WGPUSurfaceDescriptorFromWindowsHW... | 5,302,423 |
def get_answer_feedback(answer, player):
""" Render the feedback text, if a review by player was given to answer
"""
qs = Review.objects.filter(answer=answer, reviewer=player)
if not qs.count():
return ''
return qs.get().feedback | 5,302,424 |
def get_token_by_id(ikey, skey, host, token_id, ca=None):
"""
Returns a token.
ikey - Admin API integration ikey
skey - Admin API integration skey
host - Duo host
token_id - Token ID
ca - Optional CA cert
Returns a token object.
"""
url = '/admin/v1/tokens/' + token_id
resp... | 5,302,425 |
def tree_info(folder_path, verbose=False) -> Dict[str, TreeInfo]:
"""Get the total disk space and disk space contributions of all subfolders in the given path.
Returns:
Dictionary: (totals, contributions)
Both are in the form {folder_name: size}
"""
folder_path = str(folder_path)
co... | 5,302,426 |
def ranknoisy(seed: tp.Optional[int] = None) -> tp.Iterator[Experiment]:
"""Noisy optimization methods on a few noisy problems.
Cigar, Altcigar, Ellipsoid, Altellipsoid.
Dimension 200, 2000, 20000.
Budget 25000, 50000, 100000.
No rotation.
Noise level 10.
With or without noise dissymmetry.
... | 5,302,427 |
async def test_unit_install_nonempty_local_nonempty_remote_matching_salt_version(
mock_hub, hub, tmp_path, capfd
):
"""
SCENARIO #5:
- Local versions
- Remote versions
- Matching salt version
"""
# Link the function to the mock_hub
mock_hub.saltenv.cli.install = hub.saltenv.cli.insta... | 5,302,428 |
def frac_prop_calc(df_bin_org, prop, param_dict, catl_keys_dict):
"""
Computes the quenched fractions of satellites in a given mass bin.
Parameters
----------
df_bin_org: pandas DataFrame
Dataframe for the selected group/halo mass bin
prop: string
galaxy property being evaluate... | 5,302,429 |
def move_left(board, row):
"""Move the given row to one position left"""
board[row] = board[row][1:] + board[row][:1]
return board | 5,302,430 |
def deprecation_warning(obj, dep_from, dep_to):
"""Print a deprecation warning.
Parameters
----------
obj: class
The class with the deprecated attribute
dep_from: str
old (deprecated) name of the attribute
dep_to: str
new name for the attribute
"""
warnings.warn(... | 5,302,431 |
async def test_awair_dust(hass):
"""Test that we create a pm25 sensor."""
await setup_awair(hass)
# The Awair Gen1 that we mock actually returns 'DUST', but that
# is mapped to pm25 internally so that it shows up in Homekit
sensor = hass.states.get("sensor.awair_pm2_5")
assert sensor.state == "... | 5,302,432 |
def find_connected_continuations(continuation_arr,
max_face_shape=(1152, 1152)):
"""
Finds the edges of a graph which describes the continuation connectivity
"""
sizes = continuation_arr.shape
face_checked = np.zeros((6,) + continuation_arr.shape, dtype=np.bool)
... | 5,302,433 |
def acp_account():
"""Manage the user account of currently-logged-in users.
This does NOT accept admin-specific options.
"""
if request.args.get('status') == 'pwdchange':
alert = 'You must change your password before proceeding.'
alert_status = 'danger'
pwdchange_skip = True
... | 5,302,434 |
def draw_png(argx: str, argy: str, results: list, xscale: str,
output_path: str, yaxis_max: int = None,
suptitle: str = None, title: str = None) -> None:
"""draw a figure
Generate a PNG file compiling all the provided results.
Args:
argx: an x-axis argument (`lib.figure.b... | 5,302,435 |
def embed_seq(sequence, tokenizer, prottrans_model, device="cpu"):
"""
Embed a single sequence from the tokenizer and prottrans model.
"""
sequences = [sequence]
sep_sequences = []
for seq in sequences:
sep_sequences.append(" ".join([x for x in seq]))
#print(sep_sequences)
clean... | 5,302,436 |
def test_nested_import_playbook(request, include_role_tasks_option, expected_tasks_number):
"""
Test nested import playbook with an import_role and include_tasks
:return:
:rtype:
"""
playbook_path = os.path.join(FIXTURES_DIR, "nested_import_playbook.yml")
svg_path = run_grapher(playbook_path... | 5,302,437 |
def get_tile_from_info_dict(slide: Slide, info: Any):
"""
Get a tile from an info dict.
Args:
slide:
info: info dict
Returns:
patch (PIL image)
"""
patch = slide.get_tile(info['w'], info['h'], info['mag'], info['size'])
return patch | 5,302,438 |
def adc2hdf(adcfile, hdf_file, group=None, replace=True):
"""
Store an ``AdcFile`` in an HDF file or group. ADC
data is represented as a ``pandas.DataFrame`` with
a ``schema`` attribute specifying the name of the
ADC schema.
:param adcfile: the ``AdcFile`` to store
:type adcfile: AdcFile
... | 5,302,439 |
def rotate_via_numpy(xy, radians):
"""Use numpy to build a rotation matrix and take the dot product."""
x, y = xy
c, s = np.cos(radians), np.sin(radians)
j = np.array([[c, -s], [s, c]])
m = np.dot(j, np.array([x, y]))
return m[0], m[1] | 5,302,440 |
def get_quadrant(x, y):
"""
Returns the quadrant as an interger in a mathematical positive system:
1 => first quadrant
2 => second quadrant
3 => third quadrant
4 => fourth quadrant
None => either one or both coordinates are zero
Parameters
----------
x : float
x coordina... | 5,302,441 |
def get_python_script_path(conn: fabric.Connection, envdir: pathlib.Path, scriptname: str = 'python') -> pathlib.Path:
"""Get path to specific script from Python/Anaconda environment."""
if not is_windows(conn):
path = envdir / 'bin' / scriptname
else:
path = None
paths = (
... | 5,302,442 |
def get_nn_avg_dist(emb, query, knn):
"""
Compute the average distance of the `knn` nearest neighbors
for a given set of embeddings and queries.
Use Faiss if available.
"""
if True:
# emb = emb.cpu().numpy()
# query = query.cpu().numpy()
if hasattr(faiss, 'StandardGpuReso... | 5,302,443 |
def test_property_accessors():
"""
Tests that points are accessed via their respective accessors and that these accessors return the right values.
:return:
"""
# Neo4j versions lower than 3.4.0 do not support Point. In that case, skip the test.
check_and_skip_neo4j_least_version(340, 'This ver... | 5,302,444 |
def days_in_month(year, month):
"""
Inputs:
year - an integer between datetime.MINYEAR and datetime.MAXYEAR
representing the year
month - an integer between 1 and 12 representing the month
Returns:
The number of days in the input month.
"""
leapyear=0
if(year%4 ... | 5,302,445 |
def calculateUsedWater(temp_tank_before, temp_tank_after):
"""Calculate amount of used water based on temperature change and tank volume.
:param temp_tank_before: float number
:param temp_tank_after: float number
:return: float used water volume in liters
"""
used_w = (tank_volume * (temp_tank_... | 5,302,446 |
def wait_for_port(port, host='localhost', timeout=5.0):
"""Wait until a port starts accepting TCP connections.
Args:
port (int): Port number.
host (str): Host address on which the port should exist.
timeout (float): In seconds. How long to wait before raising errors.
Raises:
... | 5,302,447 |
def test_ok_003(settings, parser, resolver):
"""
Check candidates correct case 3
"""
candidates = resolver.candidate_paths("components/filename_test_6.plop.scss")
results = resolver.check_candidate_exists(settings.sample_path, candidates)
assert results == [
os.path.join(settings.sampl... | 5,302,448 |
def newt_eval(
x, coefficients, exponents, generating_points, verify_input: bool = False
):
"""Iterative implementation of polynomial evaluation in Newton form
This version able to handle both:
- list of input points x (2D input)
- list of input coefficients (2D input)
Here we use the ... | 5,302,449 |
def _get_token(user, password, host, port):
""" Gets auth token. """
token_url = "{}:{}/api/token/".format(host, port)
response = requests.post(token_url, json={
"username": user,
"password": password
})
if response.ok:
return json.loads(response.text).get("access")
else:... | 5,302,450 |
def get_gin_confg_strs():
"""
Obtain both the operative and inoperative config strs from gin.
The operative configuration consists of all parameter values used by
configurable functions that are actually called during execution of the
current program, and inoperative configuration consists of all p... | 5,302,451 |
def remove_automatic_tags(root, ns):
"""Find and remove all automatic tags."""
for bib in root.iterfind("bib:*", ns):
atags = bib.findall("dc:subject/z:AutomaticTag/..", ns)
for atag in atags:
bib.remove(atag) | 5,302,452 |
def main():
"""
Main function, where we run console application
Returns
-------
None
"""
run_app() | 5,302,453 |
def copy_tree(src, dst, verbose=False):
"""Copies everything under src to dst."""
if verbose:
print('Copying {} to {}'.format(src, dst))
for src_dir, sub_dirs, basenames in tf.io.gfile.walk(src):
rel_dir = os.path.relpath(src_dir, src)
dst_dir = os.path.join(dst, rel_dir)
fo... | 5,302,454 |
def post_queries_for_all_snapshots(network) -> Response:
"""Post query request for all snapshots
Args:
network (str): Network name
Returns:
Response: List[WholeQuerySummaryDict]
Note:
POST parameter:
* query (str): Optional: target query (limit a query)
"""
req = ... | 5,302,455 |
def random_point():
"""Returns a random point on a 100x100 grid."""
return (random.randrange(100), random.randrange(100)) | 5,302,456 |
def list_sharepoint_sites_command(client, *_):
"""
This function runs list tenant site command
:return: human_readable, context, result
"""
result = client.list_sharepoint_sites()
parsed_sites_items = [parse_key_to_context(item) for item in result["value"]]
human_readable_content = [
... | 5,302,457 |
def explode_list_columns(df,explode_cols):
"""Own implementation of pandas explode we need an older version of pandas to run the code"""
no_explode_cols = list(np.setdiff1d( df.columns , explode_cols))
df = df.set_index(no_explode_cols).apply(lambda x: x.apply(pd.Series).stack()).reset_index()
return df | 5,302,458 |
def _sparse_dense_vector_mult(matrix_a, vector_b, scalar=1., transpose=False, out=None, out_scalar=None, out_t=None):
"""
Multiply together a sparse matrix and a dense vector
:param matrix_a: Left (A) matrix
:type matrix_a: sp.spmatrix.csr, sp.spmatrix.csc
:param vector_b: Right (B) vector with sha... | 5,302,459 |
def get_prefix(bot, message):
"""
A callable prefix for the bot separeted into guilds and DM's
Parameters
----------
bot
commands.Bot
message
discord message
"""
prefixes = ['spektrumiter ', '!']
if not message.guild:
return '!'
return commands.when_me... | 5,302,460 |
def test_setup_bucket_with_resources_success(
mocker,
scheduler,
expected_dirs,
expect_upload_hit_resources,
mock_generated_bucket_name,
expected_bucket_name,
provided_bucket_name,
expected_remove_bucket,
):
"""Verify that create_bucket_with_batch_resources behaves as expected."""
... | 5,302,461 |
async def pergamum_login(session):
"""Logins the web session into the pergamum system."""
login_url = '/'.join([BIB_URL, 'pergamum/mobile/login.php'])
data = {
'flag': 'renovacao.php',
'login': PERGAMUM_LOGIN,
'password': PERGAMUM_PASS,
'button': 'Acessar'
}
headers =... | 5,302,462 |
def ans(m, H, c=2, n=32):
"""Method of manufactured solutions test"""
# setup grid
d = H / n
z = np.arange(n) * d + d / 2
zi = np.arange(n + 1) * d
# setup solution
rho = np.exp(-c * z / H)
rhoi = np.exp(-c * zi / H)
# rhoi = centered_to_interface(rho)
w = np.sin(m * np.pi *... | 5,302,463 |
def _align_for_coadd(imglist):
"""
Algin a group of images for coadding with astroalign.
Parameters
----------
imglist : list
list of images to align
Returns
-------
newlist : list
list of new SingleImage instances with aligned images
Notes
-----
We wil... | 5,302,464 |
def _subdivide_context(sequential, branch_count, join_function, name):
"""Creates a context so that branches/joins can be done using 'with'."""
with sequential.g.as_default(), scopes.var_and_name_scope((name, None)):
branches = []
for i in xrange(branch_count):
branches.append(SequentialLayerBuilder(c... | 5,302,465 |
def create_from_json_file(filename, **kwargs):
"""Create a dlapp instance from JSON filename.
Parameters
----------
filename (str): JSON filename.
kwargs (dict): keyword arguments which would use for JSON instantiation.
Returns
-------
DLQuery: a DLQuery instance.
"""
from io i... | 5,302,466 |
def control(
year: int, month: int = 1, day: int = 1, hour: int = 1,
minute: int = 1, half: int = 1, quarter: int = 1, week: int = 1):
"""Control function. Controls if the given time is possible.
:param year: the year to control
:param month: the month
:param day: the day
:param hou... | 5,302,467 |
def repeat(s, n):
""" (str, int) -> str
Return s repeated n times; if n is negative, return empty string.
>>> repeat('yes', 4)
'yesyesyesyes'
>>>repeat('no', 0)
''
"""
return (s * n) | 5,302,468 |
def convert_to_issues(statements):
"""Produce list of offending statements in set of files.
:param statements: one item from list created by add_statement
"""
files = dict()
for statement, path in statements:
if path in files:
files[path].update(statement)
if statem... | 5,302,469 |
def gaussian_mixture_sm(eigvals, eigvecs, n_clusters, n_components=None, weight_by_eigval=False, keep_first=True, positive_eigs=False):
"""
Extends the Shi and Malik method to a GMM with no covariance constraints.
* Use the eigenvectors of L_rw (this doesn't matter for us).
* NO row normalization befor... | 5,302,470 |
def launch_agent(c, conf): # pylint: disable=unused-argument
"""Launch agent and block while it measures. Use Control+C to stop
the program
Example:
inv launch-agent --conf=conf/dev.json
inv launch-agent --conf=conf/prod.json
"""
config = read_conf(conf)
conf_root = os.path.dirn... | 5,302,471 |
def can_translate(user):
"""Checks if a user translate a product"""
return user.permissions['perm_translate'] | 5,302,472 |
def read_xml_file_line_basis(xml_file, element):
"""
Read the xml file and capture only the elements we need.
"""
start_tag = f'<{element}>' # 3
end_tag = f'</{element}>' # 2
start_tag_identified = False # 3
captured_records = list() # 4
captured_line = ''
with open(xml_file) as f: #... | 5,302,473 |
def findDeque(code):
"""
Find the use of deque in the code
Documentation: Fluent Python page 54
https://docs.python.org/2/library/collections.html#collections.deque
https://pymotw.com/2/collections/deque.html
"""
dequeToken = (Token.Name, '^deque$')
dequeIdi... | 5,302,474 |
def create_footer():
"""page footer"""
footer = html.Footer(
[
html.Div(
[
html.P(
[
html.Span(
"{0}, version 0.1.0".format(app_name),
class... | 5,302,475 |
def xyz_string(labels, coords):
""" .xyz format string for this cartesian geometry
:param labels: optional labels for the beginnings of atom lines, by index
:type labels: dict
"""
assert len(labels) == len(coords)
dxyz = '\n'.join(
'{:s} {:s} {:s} {:s}'.format(asymb, *map(repr, xyz))
... | 5,302,476 |
def lazydict(f):
"""Decorator for constructing lazy dicts from a function."""
return LazyDict(f, f.__globals__, f.__name__) | 5,302,477 |
def help():
"""Print out a helpful message."""
print("""\
====================================================================
fab clean Delete the contents of the _build/ directory
fab html Create sphinx documentation as stand-alone HTML files
fab html_full Convert the ipynb files in the ../freqde... | 5,302,478 |
def Protein_translation_Amb(t, y, data, mRNAData):
"""
Defines ODE function Conversion of Amb_mRNA to protein
p1,p2,p3....: Protein concentrations for all ODEs
It will have list of all parameter values for all my ODEs, so 36 values : L, U, D for each mRNA to protein conversion equation
"""
... | 5,302,479 |
def allow_sync_invocation():
"""
A class decorator, used to make all public async methods of the class to be invoke synchronically
This action would take place only if the class has async_mode=False attribute
"""
def allow_sync_mode(func):
def wrapper(self, *args):
should_run_as... | 5,302,480 |
def test_output_galaxy_properties(mock_galaxy):
"""Test of properties and methods outputs."""
g = mock_galaxy
g_test = g.angular_momentum()
assert isinstance(g.kinetic_energy[0], u.Quantity)
assert isinstance(g.kinetic_energy[1], u.Quantity)
assert isinstance(g.kinetic_energy[2], u.Quantity)
... | 5,302,481 |
def IssueRetryableCommand(cmd, env=None):
"""Tries running the provided command until it succeeds or times out.
Args:
cmd: A list of strings such as is given to the subprocess.Popen()
constructor.
env: An alternate environment to pass to the Popen command.
Returns:
A tuple of stdout and stde... | 5,302,482 |
def _get_abs_path(path):
"""Return the absolute path for a given path.
:param path: ``str`` $PATH to be created
:returns: ``str``
"""
return os.path.abspath(
os.path.expanduser(
path
)
) | 5,302,483 |
def square(num):
"""
Return the square values of the input number.
The input number must be integer.
"""
return num ** 2 | 5,302,484 |
def run_ticket_validation(provider_details, key_url=None, key=None, appid=None):
"""
Validates Steam session ticket.
'key' is the access key for Steam API. If not set, then 'key_url' must point to it.
'appid' is the Steam App ID for this application.
Returns a unique ID for this player.
"""
... | 5,302,485 |
def timestamp_to_hex(timestamp):
"""
# 时间戳数转化为十六进制字符串
:param timestamp: 时间戳数
:return: 时间戳对应的十六进制字符串
"""
if timestamp < 0: # 如果输入的时间戳数是负值
timestamp *= -1 # 则转化为正数
timestamp_list = math.modf(timestamp) # 分割整数位和小数位成为元组,第一个位置是小数位,第二个位置是整数位
four_byte_second = hex(int(timestamp_lis... | 5,302,486 |
def launch_file_toucher(f):
"""Launch a loop to touch the given file, and return a function to call to stop and join it."""
halt = threading.Event()
def file_toucher():
while not halt.isSet():
touch(f)
time.sleep(1)
thread = threading.Thread(target=file_toucher)
thread.daemon = True
thread.s... | 5,302,487 |
def wait_for_enforcement_stats(controller, rule_list, wait_time=1,
max_sleep_time=25):
"""
Wait until all rules from rule_list appear in reports from
enforcement_controller to sessiond. This is done by checking the mocked
EnforcementStatsController '_report_usage' method c... | 5,302,488 |
def parse_gcov_file(gcov_file):
"""Parses the content of .gcov file written by gcov --intermediate-format
Returns:
str: Source file name
dict: coverage info { line_number: hits }
"""
count = {}
with open(gcov_file) as fh:
for line in fh:
tag, value = line.split(':')
... | 5,302,489 |
def _sh_wrapper(
func: Callable[[Union[str, Path], Union[str, Path]], Any],
source: Union[str, Path],
destination: Union[str, Path],
) -> None:
"""Runs an 'shutil' function ('func') which takes an 'source' and
a 'destination' argument (e.g. copy/move/etc.), but silently
handles the case where th... | 5,302,490 |
def recover_bad_node(force=False):
""" Recover the bad node assuming it is in a bad state. """
if not force and not run("exec 6<>/dev/tcp/localhost/9160", warn_only=True, quiet=True).failed:
print green("Your cassandra process is fine, we don't need to recover it.")
return
# If it is in a bad state, resta... | 5,302,491 |
def get_default_ophys_metadata():
"""Fill default metadata for optical physiology."""
metadata = get_default_nwbfile_metadata()
metadata.update(
Ophys=dict(
Device=[dict(name="Microscope")],
Fluorescence=dict(
roi_response_series=[
dict(
... | 5,302,492 |
def run_analysis(job):
"""Run analysis."""
from reproducibility_project.src.analysis.rdf import gsd_rdf
# RDF
gsd_rdf(job) | 5,302,493 |
def apply_address_fixups(address: OrderedDict[str, str]) -> OrderedDict[str, str]:
"""Sometimes the usaddress parser makes mistakes. It's an imperfect world.
This function applies transformations to the parsed address to correct specific
known errors.
"""
# Fixup: At least one address has "WI, USA" ... | 5,302,494 |
def validate_args(args):
"""
Validate that arguments are valid.
:param args: An arguments namespace.
:type args: :py:class:`argparse.Namespace`
:return: The validated namespace.
:rtype: :py:class:`argparse.Namespace`
"""
level = V_LEVELS.get(args.verbose, logging.DEBUG)
logging.basi... | 5,302,495 |
def get_slaves():
"""Get the list of slave nodes"""
slaves = range(mpi_comm.Get_size())
slaves.remove(mpi_master)
return slaves | 5,302,496 |
def _validate_metadata(candidates):
"""
Validates the metadata of the plug-in types of a sequence of candidates.
It validates the metadata of each plug-in type each candidate claims to
implement.
:param candidates: A sequence of candidates to validate.
:return: The same sequence, but filtered to only have candid... | 5,302,497 |
def _max(arr, axis = 0):
"""The max function.
Args:
arr -- The array.
axis -- The axis (0 by default)
Returns:
The max value along the axis.
"""
return extrema(max, arr, axis) | 5,302,498 |
def _get_results_socket():
"""Instantiate the results socket for sending binary results."""
client = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
sock = '/_abaco_results.sock'
try:
client.connect(sock)
except (FileNotFoundError, ConnectionError) as e:
msg = "Exception connecting ... | 5,302,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.