content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def repos():
"""Display And Add Repos"""
page = Repos(ReposTable, dynamodb_table)
return page.display() | 27,200 |
def lambda_handler(event, _context):
""" Main Handler. """
microservice_name = event.get('MicroserviceName')
environment_name = event.get('EnvironmentName')
new_vn_sha = event.get('Sha')
failure_threshold_value = event.get('FailureThresholdValue')
if not failure_threshold_value:
failure... | 27,201 |
def run(hdf5_data):
"""
Run the solver
Args:
hdf5_data: object, the hdf5 opened storage
Returns:
the output of the fortran function as string if successful
"""
signature = __name__ + '.run(hdf5_data)'
logger = logging.getLogger(__name__)
utility.log_entrance(logger, sign... | 27,202 |
def pytest_addoption(parser):
""" Facilitate command-line test behavior adjustment. """
parser.addoption(
"--logging-level",
default="WARN",
help="Project root logger level to use for tests",
) | 27,203 |
def test_export_as_csl():
"""
CSL export can be tested via curl:
```
curl \
--header "Content-Type: application/json" \
--data '[{"key": "IN22XN53", "itemType": "webpage", "date": "2016-02-09T20:12:00"}]' \
'https://translate.manubot.org/export?format=csljson'
```
"""
zoter... | 27,204 |
def send_multipart_json(sock, idents, reply):
"""helper"""
reply_json = ut.to_json(reply).encode('utf-8')
reply = None
multi_reply = idents + [reply_json]
sock.send_multipart(multi_reply) | 27,205 |
def delete_file(path):
"""Deletes the file at the given path and recursively deletes any empty
directories from the resulting directory tree.
Args:
path: the filepath
Raises:
OSError if the deletion failed
"""
os.remove(path)
try:
os.removedirs(os.path.dirname(path)... | 27,206 |
def masked_crc32c(data):
"""Copied from
https://github.com/TeamHG-Memex/tensorboard_logger/blob/master/tensorboard_logger/tensorboard_logger.py"""
x = u32(crc32c(data)) # pylint: disable=invalid-name
return u32(((x >> 15) | u32(x << 17)) + 0xa282ead8) | 27,207 |
def _printResults(opts, logger, header, content, filename=None):
"""Print header string and content string to file of given
name. If filename is none, then log to info.
If --tostdout option, then instead of logging, print to STDOUT.
"""
cstart = 0
# If the content is a single quote quoted XML do... | 27,208 |
def yaml_dictionary(gra, one_indexed=True):
""" generate a YAML dictionary representing a given graph
"""
if one_indexed:
# shift to one-indexing when we print
atm_key_dct = {atm_key: atm_key+1 for atm_key in atom_keys(gra)}
gra = relabel(gra, atm_key_dct)
yaml_atm_dct = atoms(g... | 27,209 |
def CreateCloudsWeights( weights = None, names = None, n_clusters = None,
save = 1, dirCreate = 1, filename = 'WC',
dirName = 'WCC', number = 50 ):
"""SAME AS CreateClouds but now it takes as inputs a list of each class
... | 27,210 |
def Seqslicer (Sequ, dictORF):
"""Slice sequence in fasta file from dict"""
record = SeqIO.read(Sequ, "fasta")
for keys, value in dictORF.items():
nameORF = "ORF" + keys
seqORF = record.seq[(int(value[0])-1):int(value[1]) ]
if value[2] == "-":
seqORF = inversCo... | 27,211 |
def sigmoid(x, deri=False):
"""
Sigmoid activation function:
Parameters:
x (array) : A numpy array
deri (boolean): If set to True function calulates the derivative of sigmoid
Returns:
x (array) : Numpy array after applying the approprite function
... | 27,212 |
def migrate(env, dry_run=False):
"""
User-friendly frontend to run database migrations.
"""
registry = env['registry']
settings = registry.settings
readonly_backends = ('storage', 'permission')
readonly_mode = asbool(settings.get('readonly', False))
for backend in ('cache', 'storage', '... | 27,213 |
def main(args):
""" Main function operates the following steps:
1. Get fits and aperature datafile
2. Get or guess the passband from filename
3. Get ra and dec from fits
4. Match image and reference with SkyCoord using ra's and dec's
5. Calculate zeropoint
5. Apply zeropoint to aperatur... | 27,214 |
def palindrome_permutation(string):
"""
All palindromes follow the same rule, they have at most one letter whose
count is odd, this letter being the "pivot" of the palindrome. The letters
with an even count can always be permuted to match each other across the
pivot.
"""
string = string.stri... | 27,215 |
def generate_pfm_v2(pfm_header_instance, toc_header_instance, toc_element_list, toc_elements_hash_list,
platform_id_header_instance, flash_device_instance, allowable_fw_list, fw_id_list, hash_type):
"""
Create a PFM V2 object from all the different PFM components
:param pfm_header_instance: Instance of... | 27,216 |
async def handle(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
"""Handles incoming data and returns"""
dispatch = get_dispatch()
while True:
data = await reader.read(100)
message = data.decode().rstrip(' \n')
address = writer.get_extra_info('peername')
... | 27,217 |
def symmetrise_AP(AP):
"""
No checks on this since this is a deep-inside-module helper routine.
AP must be a batch of matrices (n, 1, N, N).
"""
return AP + AP.transpose(2, 3) | 27,218 |
def index():
"""新闻首页"""
#----------------------1.查询用户基本信息展示----------------------
# 需求:发现查询用户基本信息代码在多个地方都需要实现,
# 为了达到代码复用的目的,将这些重复代码封装到装饰器中
# # 1.根据session获取用户user_id
# user_id = session.get("user_id")
#
# user = None
# # 先定义,再使用 否则:local variable 'user_dict' referenced before ass... | 27,219 |
def formatter_message(message, use_color = True):
""" Method to format the pattern in which the log messages will be
displayed.
@param message: message log to be displayed
@param use_color: Flag to indicates the use of colors or not
@type message: str
@type use_color: boolean
@return: the... | 27,220 |
def find_offsets(head_mapping):
"""Find the time offsets that align the series in head_mapping
Finds the set of time offsets that minimize the sum of squared
differences in times at which each series crosses a particular
head. Input is a mapping of head id (a hashable value
corresponding to a head... | 27,221 |
def whoami():
"""
Displays the username.
USAGE
- sniper whoami
"""
try:
with open(TOKEN_FILE) as t:
token = t.read()
except:
raise SniperError('Error reading the credentials file.')
if token == '':
raise SniperError('You are curr... | 27,222 |
def get_argument(value, arg):
"""Get argument by variable"""
return value.get(arg, None) | 27,223 |
def update_user_distances(user, start, end, update_only=True):
"""Update travelled_distances for given user, based on changes to data
between given start and end. If update_only, disallow writing stats on a
new day, do update global stats."""
# Snap to whole days
start = start.replace(hour=0, minut... | 27,224 |
def tokenize(docs, word_tokenize_flag=1):
"""
:param docs:
:param word_tokenize_flag:
:return:
"""
sent_tokenized = []
for d_ in docs:
sent_tokenized += sent_tokenize(d_)
if word_tokenize_flag==1:
word_tokenized = []
for sent in sent_tokenized:
word_t... | 27,225 |
def is_literal(expr):
"""
Returns True if expr is a literal, else False.
Examples
========
>>> is_literal(a)
True
>>> is_literal(~a)
True
>>> is_literal(a + b)
True
>>> is_literal(Or(a, b))
False
"""
if isinstance(expr, Not):
return not isinstance(expr.... | 27,226 |
def get_target_proportions_of_current_trial(individuals, target):
"""Get the proportion waiting times within the target for a given trial of
a threshold
Parameters
----------
individuals : object
A ciw object that contains all individuals records
Returns
-------
int
all... | 27,227 |
def how_many(aDict):
"""
aDict: A dictionary, where all the values are lists.
returns: int, how many values are in the dictionary.
"""
return sum(len(value) for value in aDict.values()) | 27,228 |
def build_model(images, num_classes):
"""Build the model
:param images: Input image placeholder
:param num_classes: Nbr of final output classes
:return: Output of final fc-layer
"""
#####Insert your code here for subtask 1e#####
# It might be useful to define helper functions which add a lay... | 27,229 |
def crop_keypoint_by_coords(keypoint, crop_coords, crop_height, crop_width, rows, cols):
"""Crop a keypoint using the provided coordinates of bottom-left and top-right corners in pixels and the
required height and width of the crop.
"""
x, y, a, s = keypoint
x1, y1, x2, y2 = crop_coords
cropped_... | 27,230 |
def get_tcoeff(epd_model, dF):
"""
Tranmission coefficients beta, gamma and delta
can be directly computed from the time series data.
Here we do not need reference to any compartmental model.
"""
df = dF.copy()
dfc = pd.DataFrame(columns=['date','beta','gamma','delta'])
df['infected'] = df... | 27,231 |
def run(conf: AgentConfig):
"""
This is the main function which start workers by agent by machine.
To ack:
qnames: will be prepended with the name of the cluster, for instance:
qnames = ["default", "control"]; cluster = "gpu"
qnames_fit = ["gpu.default", "gpu.control"]
:param redis_dsn: re... | 27,232 |
async def test_setup_fails_without_config(hass):
"""Test if the MQTT component fails to load with no config."""
assert not await async_setup_component(hass, mqtt.DOMAIN, {}) | 27,233 |
def rx_filter(observable: Observable, predicate: PredicateOperator) -> Observable:
"""Create an observable which event are filtered by a predicate function.
Args:
observable (Observable): observable source
predicate (Operator): predicate function which take on argument and return
a ... | 27,234 |
def remove_tasks_in_namespace(obj, namespace):
"""Remove all scheduled tasks in given namespace."""
api = lib.get_api(**obj)
lib.run_plugins_task(
api,
"remove_scheduled_tasks_in_namespace",
dict(namespace=namespace),
"Removing scheduled tasks",
) | 27,235 |
def map_time_program(raw_time_program, key: Optional[str] = None) \
-> TimeProgram:
"""Map *time program*."""
result = {}
if raw_time_program:
result["monday"] = map_time_program_day(
raw_time_program.get("monday"), key)
result["tuesday"] = map_time_program_day(
... | 27,236 |
def evaluate_expression(pipelineId=None, objectId=None, expression=None):
"""
Task runners call EvaluateExpression to evaluate a string in the context of the specified object. For example, a task runner can evaluate SQL queries stored in Amazon S3.
See also: AWS API Documentation
Exceptions
... | 27,237 |
def _find_tols(equipment_id, start, end):
"""Returns existing TransportOrderLines matching with given arguments.
Matches only if load_in is matching between start and end."""
#logger.error('Trying to find TOL')
#logger.error(equipment_id)
#logger.error(start_time)
#logger.error(end_time)
... | 27,238 |
def MC1(N,g1,x):
""" Calculating the numerical solution to the integral of the agents value by Monte Carlo of policy 1
Args:
N (int): Number of iterations/draws
g1 (float): Agents value of policy 1
x (float): Drawn from a beta distribution (X)
... | 27,239 |
async def fry(message):
""" For .fry command, fries stickers or creates new ones. """
reply_message = await message.get_reply_message()
photo = BytesIO()
if message.media:
await message.edit("Frying...")
await message.download_media(photo)
elif reply_message.media:
await mes... | 27,240 |
def string_between(string, start, end):
"""
Returns a new string between the start and end range.
Args:
string (str): the string to split.
start (str): string to start the split at.
end (str): string to stop the split at.
Returns:
new string between start and end.
"... | 27,241 |
def _parse_line(line: str):
"""
行解析,逗号隔开,目前支持3个字段,第一个是展示的名称,第二个是xml中保存的名称,第三个是附带值value的正则标的形式
:param line:
:return:
"""
line = line.strip()
config = line.split(",")
if len(config) == 2:
return config[0], config[1], ""
elif len(config) == 3:
return config[0] + INTER_FL... | 27,242 |
def harvest_zmat(zmat: str) -> Molecule:
"""Parses the contents of the Cfour ZMAT file into array and
coordinate information. The coordinate info is converted into a
rather dinky Molecule (no fragment, but does read charge, mult,
unit). Return qcdb.Molecule. Written for findif zmat* where
geometry a... | 27,243 |
def test_ensure_env_decorator_sets_gdal_data_wheel(gdalenv, monkeypatch, tmpdir):
"""fiona.env.ensure_env finds GDAL data in a wheel"""
@ensure_env
def f():
return getenv()['GDAL_DATA']
tmpdir.ensure("gdal_data/pcs.csv")
monkeypatch.delenv('GDAL_DATA', raising=False)
monkeypatch.setattr... | 27,244 |
def then_wait(msg_type, criteria_func, context, timeout=None):
"""Wait for a specific message type to fullfil a criteria.
Uses an event-handler to not repeatedly loop.
Args:
msg_type: message type to watch
criteria_func: Function to determine if a message fulfilling the
... | 27,245 |
def interaction_fingerprint_list(interactions, residue_dict, interaction_dict):
"""
Create list of fingerprints for all given structures.
"""
fp_list = []
for sites in interactions.items():
for site_name, site_interactions in sites.items():
if not site_name.startswith("LIG"):
... | 27,246 |
def process_funding_records(max_rows=20, record_id=None):
"""Process uploaded affiliation records."""
set_server_name()
task_ids = set()
funding_ids = set()
"""This query is to retrieve Tasks associated with funding records, which are not processed but are active"""
tasks = (Task.select(
... | 27,247 |
def get_dynamic_client(
access_token: str, project_id: str, cluster_id: str, use_cache: bool = True
) -> CoreDynamicClient:
"""
根据 token、cluster_id 等参数,构建访问 Kubernetes 集群的 Client 对象
:param access_token: bcs access_token
:param project_id: 项目 ID
:param cluster_id: 集群 ID
:param use_cache: 是否使... | 27,248 |
def _launch(url, runtime, **kwargs):
""" Attempt to launch runtime by its name.
Return (runtime_object, is_launched, error_object)
"""
rt = None
launched = False
try:
if runtime.endswith('-app'):
# Desktop-like app runtime
runtime = runtime.split('-... | 27,249 |
def a2b_base64(*args, **kwargs): # real signature unknown
""" Decode a line of base64 data. """
pass | 27,250 |
def bucket(db, dummy_location):
"""File system location."""
b1 = Bucket.create()
db.session.commit()
return b1 | 27,251 |
def standardize_str(string):
"""Returns a standardized form of the string-like argument.
This will convert from a `unicode` object to a `str` object.
"""
return str(string) | 27,252 |
def lambda_handler(event, context):
"""
スタッフの日毎の空き情報を返却する
Parameters
----------
event : dict
フロントからのパラメータ群
context : dict
コンテキスト内容。
Returns
-------
return_calendar : dict
スタッフの日毎の空き情報(予約がある日のみ空き有無の判定結果を返す)
"""
# パラメータログ、チェック
logger.info(event)
... | 27,253 |
def init_process_group_and_set_device(world_size, process_id, device_id, config):
"""
This function needs to be called on each spawned process to initiate learning using DistributedDataParallel.
The function initiates the process' process group and assigns it a single GPU to use during training.
"""
... | 27,254 |
def yes_no(
question : str = '',
options : Tuple[str, str] = ('y', 'n'),
default : str = 'y',
wrappers : Tuple[str, str] = ('[', ']'),
icon : bool = True,
yes : bool = False,
noask : bool = False,
interactive : bool = False,
**kw : Any
) -> boo... | 27,255 |
def load(filename, instrument=None, **kw):
"""
Return a probe for NCNR data.
"""
header, data = parse_file(filename)
return _make_probe(geometry=Polychromatic(), header=header, data=data, **kw) | 27,256 |
def set_mem_lock_xml(params, env):
"""
"""
pass | 27,257 |
def get_repeat():
""" get_repeat() -> (delay, interval)
see how held keys are repeated
"""
check_video()
delay, interval = ffi.new('int*'), ffi.new('int*')
sdl.SDL_GetKeyRepeat(delay, interval)
return (delay[0], interval[0]) | 27,258 |
def growth(params, ns, rho=None, theta=1.0, gamma=None, h=0.5, sel_params=None):
"""
exponential growth or decay model
params = (nu,T)
nu - final size
T - time in past size changes begin
"""
nu,T = params
if rho == None:
print("Warning: no rho value set. Simulating with rho = 0."... | 27,259 |
def mse(y_true, y_pred):
""" Mean Squared Error """
return K.mean(K.square(_error(y_true, y_pred))) | 27,260 |
def knn_name_matching(
A: Iterable[str], B: Iterable[str],
vectorizer_kws: dict = {}, nn_kws: dict = {},
max_distance: float = None, return_B=True) -> list:
"""
Nearest neighbor name matching of sentences in B to A.
"""
from sklearn.neighbors import NearestNeighbors
from skle... | 27,261 |
def context(name: str) -> Generator[str, None, None]:
"""Allows specifying additional information for any logs contained in this block.
The specified string gets included in the log messages.
"""
try:
stack = CTX_STACK.get()
except LookupError:
stack = []
CTX_STACK.set(stack... | 27,262 |
def setup_platform(hass, config, add_devices, discovery_info=None):
""" Sets up the ISY994 platform. """
logger = logging.getLogger(__name__)
devs = []
# verify connection
if ISY is None or not ISY.connected:
logger.error('A connection has not been made to the ISY controller.')
retur... | 27,263 |
def frames_downsample(arFrames:np.array, nFramesTarget:int) -> np.array:
""" Adjust number of frames (eg 123) to nFramesTarget (eg 79)
works also if originally less frames then nFramesTarget
"""
nSamples, _, _, _ = arFrames.shape
if nSamples == nFramesTarget: return arFrames
# down/upsample th... | 27,264 |
def icon_dir():
"""pathname of the directory from which to load custom icons"""
return module_dir()+"/icons" | 27,265 |
def search_pkgs(db, project_type, pkg_list):
"""
Method to search packages in our vulnerability database
:param db: DB instance
:param project_type: Project type
:param pkg_list: List of packages to search
"""
expanded_list = []
pkg_aliases = {}
for pkg in pkg_list:
variatio... | 27,266 |
def test_update_account_without_data_returning_400_status_code(client, session):
"""
GIVEN a Flask application
WHEN the '/account' URL is requested (PUT) without data
THEN check the response HTTP 400 response
"""
user = create_user(session)
tokens = create_tokens(user.username)
endpoint... | 27,267 |
def post_question():
""" Post a question."""
q_data = request.get_json()
# No data provied
if not q_data:
abort(make_response(jsonify({'status': 400, 'message': 'No data sent'}), 400))
else:
try:
data = QuestionSchema().load(q_data)
if not MeetupModel().ex... | 27,268 |
def infinitegenerator(generatorfunction):
"""Decorator that makes a generator replay indefinitely
An "infinite" parameter is added to the generator, that if set to True
makes the generator loop indifenitely.
"""
def infgenerator(*args, **kwargs):
if "infinite" in kwargs:
... | 27,269 |
def clear_punctuation(document):
"""Remove from document all pontuation signals."""
document = str(document)
if sys.version_info[0] < 3:
return document.translate(None, string.punctuation)
else:
return document.translate(str.maketrans("", "", string.punctuation)) | 27,270 |
def test_time_of_use_summer_off_peak_usage():
"""Test Time of Use for summer Off Peak Usage for kwh."""
with patch(PATCH_GET) as session_get, patch(PATCH_POST) as session_post:
session_post.return_value = MOCK_LOGIN_RESPONSE
session_get.side_effect = get_mock_requests(ROUTES)
client = ... | 27,271 |
def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
"""Credit: http://stackoverflow.com/questions/2257441/random-string-generation-with-upper-case-letters-and-digits-in-python"""
return ''.join(random.choice(chars) for _ in range(size)) | 27,272 |
def _update_objective(C_obj, Q, QN, R, R0, xr, z_init, u_init, const_offset, u_prev, N, nx, nu):
"""
Construct MPC objective function
:return:
"""
res = np.hstack(
((C_obj.T @ Q @ (C_obj @ z_init[:, :-1] - xr[:, :-1])).T.flatten(),
C_obj.T @ QN @ (C_obj @ z_init[:, -1] - xr[:, -1]),... | 27,273 |
def absolute_time(arg):
"""Validate user provided absolute time"""
if not all([t.isdigit() for t in arg.split(':')]):
raise argparse.ArgumentTypeError("Invalid time format: {}".format(arg))
# Valid time (e.g. hour must be between 0..23)
try:
datetime.time(*map(int, arg.split(':')))
e... | 27,274 |
def convert(M: any) -> torch.Tensor:
"""
Convert Scipy sparse matrix to pytorch sparse tensor.
Parameters
----------
M : any
Scipy sparse matrix.
Returns
-------
Ms : torch.Tensor
pytorch sparse tensor.
"""
M = M.tocoo()
indices = torch.from_numpy(np.vstack... | 27,275 |
def process_lines(lines):
"""
It classifies the lines and combine them into a CombinedLine
:param lines: np.array with all the lines detected in the image. It should be the output of a HoughLinesP function
:return: np.array with 2 lines
"""
lines_l = CombinedLine()
lines_r = CombinedLine()
... | 27,276 |
def get_balances_with_token(token: str):
"""Returns all entries where a token is involved"""
token = token.lower()
conn = create_connection()
with conn:
cursor = conn.cursor()
fiat = confighandler.get_fiat_currency().lower()
cursor.execute(
f"SELECT date,balance_btc,b... | 27,277 |
def relative_cumulative_gain_curve(df: pd.DataFrame,
treatment: str,
outcome: str,
prediction: str,
min_rows: int = 30,
steps: int = 100,
... | 27,278 |
def setup():
"""
Install project user, structure, env, source, dependencies and providers
"""
from .deploy import install_project, install_virtualenv, \
install_requirements, install_providers
from .project import requirements_txt, use_virtualenv
install_project()
if use_virtualenv... | 27,279 |
def add_curve_scatter(axis, analysis_spot, color_idx):
"""Ad one of more scatter curves that spot events
Arguments:
y_axis : a pyplot x-y axis
analysis : a dictionnary { 'name': [<datetime>, ...], ... }
"""
curves = []
# each spot analysis has a different y value
spot_value... | 27,280 |
def detect_faces(path):
"""Detects faces in an image."""
with io.open(file=path, mode='rb') as image_file:
content = image_file.read()
image = vision.Image(content=content)
response = client.face_detection(image=image)
faces = response.face_annotations
# Names of likelihood from googl... | 27,281 |
def get_character_journal(character_ccp_id, page = 1, page_limit=5):
"""
:param self:
:param character_ccp_id:
:param oldest_entry:
:param page_limit:
:return:
"""
character = EVEPlayerCharacter.get_object(character_ccp_id)
if not character.has_esi_scope('esi-wallet.read_character_w... | 27,282 |
def get_entropy(labels):
"""Calculates entropy using the formula
`-Sum(Prob(class) * log2(Prob(class)))` for each class in labels."""
assert len(labels.shape) == 1
_, count = get_unique_classes_count(labels)
probabilities = count / labels.shape
return -np.sum(probabilities * np.log2(proba... | 27,283 |
def prev_attached_usb():
"""
Returns information about the previously connected
usb drives.
"""
for sub_key in enum_usb():
# Additional information of the connected USB storage device.
extra = list()
with reg.OpenKeyEx(reg.HKEY_LOCAL_MACHINE, sub_key) as usb:
... | 27,284 |
def store():
"""Database storage fixture."""
in_memory_database = Database.in_memory(echo=False)
in_memory_database.create_tables()
return DBResultStorage(in_memory_database) | 27,285 |
def report_tests(test_suite,
label="",
filter=None,
filter_i=None,
first_only=False,
spacer_lines=10):
"""Report tests of a test suite using either:
single line per fail/error, or
stack trace for first error
verbos... | 27,286 |
def test_homology(dash_threaded):
"""Test the display of a basic homology"""
prop_type = 'dict'
prop_val = {
"chrOne": {
"organism": "9606",
"start": [10001, 105101383],
"stop": [27814790, 156030895],
},
"chrTwo": {
"organism": "9606"... | 27,287 |
def coverage():
"""
View a report on test coverage.
Call py.test with coverage turned on.
"""
print("\ncoverage")
return subprocess.run(
[
PYTEST,
"--cov-config",
".coveragerc",
"--cov-report",
"term-missing",
"--co... | 27,288 |
def cmd_session_create(cmd_ctx):
"""Create an HMC session."""
session = cmd_ctx.session
try:
# We need to first log off, to make the logon really create a new
# session. If we don't first log off, the session from the
# ZHMC_SESSION_ID env var will be used and no new session be creat... | 27,289 |
def main():
""" Main entry point for AnsibleModule """
argument_spec = FactsArgs.argument_spec
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=True)
warnings = []
ansible_facts, additional_warnings = Facts(module).get_facts()
warnings.extend(a... | 27,290 |
def get_files(directory):
"""Gets full path of all files within directory, including subdirectories
Returns a list of paths"""
file_paths = []
for root, dirs, files in os.walk(directory):
for f in files:
filepath = os.path.join(root, f)
file_paths.append(filepath)
r... | 27,291 |
def setup_add_ldif(ldb, ldif_path, subst_vars=None,controls=["relax:0"]):
"""Setup a ldb in the private dir.
:param ldb: LDB file to import data into
:param ldif_path: Path of the LDIF file to load
:param subst_vars: Optional variables to subsitute in LDIF.
:param nocontrols: Optional list of contr... | 27,292 |
def log_sheets_with_index(bk: xw.Book):
"""Logs the indicies and name of every sheet in a workbook.
Arguments:
bk {xw.Book} -- The book to log.
"""
for index, sht in enumerate(bk.sheets):
print(index, sht.name) | 27,293 |
def load_vocab(filename):
"""Loads vocab from a file
Args:
filename: (string) the format of the file must be one word per line.
Returns:
d: dict[word] = index
"""
word2id = dict()
with open(filename, 'r', encoding='utf-8') as f:
for idx, word in enumerate(f):
... | 27,294 |
def _log_and_cleanup(sesh: session.Session):
"""
When done, write some logs and drop the db
"""
log_md = format_markdown(sesh.script, sesh.storage)
fn_md = _log_path(sesh.storage.script_path, sesh.storage.description)
fn_md.write_text(log_md)
log_json = format_json(sesh.script, sesh.storage)... | 27,295 |
def select_class_for_slot(class_name, slot_number):
"""
Select a class_name for a certain slot_number.
Class name is selected from one of get_potential_classes_for_slot(slot_number)
Do the necessary manipulation
"""
global valid_schedules
valid_schedules_new = []
class_ID = class_na... | 27,296 |
def load_labels(label_path):
"""
Load labels for VOC2012, Label must be maded txt files and like my label.txt
Label path can be change when run training code , use --label_path
label : { label naem : label color}
index : [ [label color], [label color]]
"""
with open(label_path, "r") as f:
... | 27,297 |
def _make_function_ptr_ctype(restype, argtypes):
"""Return a function pointer ctype for the given return type and argument types.
This ctype can for example be used to cast an existing function to a different signature.
"""
if restype != void:
try:
restype.kind
except AttributeError:
raise TypeError("... | 27,298 |
def parse_matl_results(output):
"""Convert MATL output to a custom data structure.
Takes all of the output and parses it out into sections to pass back
to the client which indicates stderr/stdout/images, etc.
"""
result = list()
parts = re.split(r'(\[.*?\][^\n].*\n?)', output)
for part in... | 27,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.