content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def parse_args():
"""to add show versions args in parser"""
parser = argparse.ArgumentParser(
prog="discordRebot", description="Tools for helping with discord-rebot"
)
parser.add_argument("-v", "--version", action="store_true", help="shows the library version")
parser.set_defaults(func=core... | 55,700 |
def layer_stack_from_hparams(hparams, prefix):
"""Create a layer stack based on the hyperparameter values."""
layers = hparams.get(prefix + "layers")
return transformer.LayerStack(
[layers_registry[l](hparams, prefix) for l in layers],
dropout_rate=hparams.layer_prepostprocess_dropout,
norm_epsi... | 55,701 |
def resample_profile(profile, periods):
"""
Resamples a profile to have the number of periods defined by periods.
Uses the mean of the period. The end point of the period is used as the
index.
Parameters
----------
profile : np.Array, pd.Series or pd.DataFrame
An array like object ... | 55,702 |
def quick_sort(S):
"""Sort the elements of queue S using the quick-sort algorithm."""
n = len(S)
if n < 2:
return # list is already sorted
# divide
p = S.first() # using first as arbitrary pivot
L = LinkedQueue()
E = LinkedQueue()
G = Linked... | 55,703 |
def main():
""" operational function """
bst1 = BinarySearchTree()
for elem in [9, 5, 3, 10, 6, 1, 7, 4]:
bst1.insert(elem)
print("is BST?", is_bst(bst1.root))
bst2 = BinarySearchTree()
bst2.root = Node(5)
bst2.root.right = Node(7)
bst2.root.left = Node(5)
bst2.root.left.lef... | 55,704 |
def rs_compose_add(p1, p2):
"""
compute the composed sum ``prod(p2(x - beta) for beta root of p1)``
Examples
========
>>> from sympy.polys.domains import QQ
>>> from sympy.polys.rings import ring
>>> from sympy.polys.ring_series import rs_compose_add
>>> R, x = ring('x', QQ)
>>> f ... | 55,705 |
def rewind(f):
"""[put the cursor back to the beginning]
Args:
f ([file]): [the file to operate on]
"""
f.seek(0) | 55,706 |
def _check(isamAppliance, name, description, authenticateCallbacks, signInCallbacks, localIdCallbacks, signOutCallbacks,
authnPolicyCallbacks):
"""
Check and return True if update needed
"""
update_required = False
poc_id = None
ret_obj = get(isamAppliance, name)
if ret_obj['data... | 55,707 |
def remove_citation(paragraph: str) -> str:
"""Remove all citations (numbers in side square brackets) in paragraph"""
return re.sub(r'\[\d+\]', '', paragraph) | 55,708 |
def test_stc_as_volume():
"""Test previous volume source estimate morph."""
import nibabel as nib
inverse_operator_vol = read_inverse_operator(fname_inv_vol)
# Apply inverse operator
stc_vol = read_source_estimate(fname_vol, 'sample')
img = stc_vol.as_volume(inverse_operator_vol['src'], mri_re... | 55,709 |
def parse_proxy(line):
"""Parses proxies from a string.
Args:
contents: The string that should be parsed.
Returns:
The parsed proxy.
"""
proxy = None
if not (line.strip().startswith('#') or line.strip().startswith('//')):
tokens = line.replace('\n', '').split(' ')
try:
... | 55,710 |
def sg_get_pdt_str(pdt):
"""
Yield string associated with peripheral device type (pdt). Returns
'buff'. If 'pdt' out of range yields "bad pdt" string.
"""
buff = _get_buffer(48)
libsgutils2.sg_get_pdt_str(pdt, 48, ctypes.byref(buff))
return buff.value.decode('utf-8') | 55,711 |
def upload_zip(self, index, *args, **kwargs):
"""
Celery task which unzips files in a .zip archive and ignores folder
structure, taking each file to the top level of the output folder.
"""
self.index = index
self.index.status = "STARTED"
self.index.save()
if not os.path.exists(self.index... | 55,712 |
def log_setup(console_output=True, log_file="", net_stream=None):
"""
Automatically executed method to set up logging.
TODO: Export the setup process to a file in /logs
"""
BOT_LOGGER.setLevel(logging.INFO)
console_handler = logging.StreamHandler() #Defaults to sys.stderr, never disabled
fi... | 55,713 |
def load_audio_RAVDESS(config, save_path):
"""extract the waveforms from .wav files using torchaudio package
Arguments:
config {dictionary} -- configurations imported from the config.yaml file
"""
filepath = Path(__file__).parents[2] / config['raw_audio_data_RAVDESS']
if confi... | 55,714 |
def encode(text):
"""Call the different encoding steps."""
text = rot13(text)
text = prevent_doubled_chars(text)
text = replace_spaces(text)
print(text)
sys.exit() | 55,715 |
def simulation_positions(simulation):
"""
Return atomic coordinates.
Parameters
----------
simulation : Simulation or Context object.
Returns
-------
ndarray
"""
state = simulation_state(simulation, 'positions')
return state.getPositions(asNumpy=True) | 55,716 |
def regex(value, regexflags=None):
"""OpenEmbedded 'regex' type
Acts as a regular expression, returning the pre-compiled regular
expression pattern object. To use this type, set the variable type flag
to 'regex', and optionally, set the 'regexflags' type to a space separated
list of the flags to c... | 55,717 |
def run_global(script_name, *args):
"""Run a script from $VIRTUALENVWRAPPER_HOOK_DIR.
"""
script_path = get_path('$VIRTUALENVWRAPPER_HOOK_DIR', script_name)
run_script(script_path, *args)
return | 55,718 |
def normalized_distance(x, y):
"""Distance between two vectors normalized by the number of elements and
the norm of the first vector"""
return distance(x, y) / torch.sqrt(norm(x) * norm(y)) | 55,719 |
def LoadDebugger(dbgname, use_remote):
"""
Load the debugger
@param dbgname: debugger module name Examples: win32, linux, mac.
@param use_remote: 0/1: use remote debugger or not
@note: This function is needed only when running idc scripts from the command line.
In other cases ID... | 55,720 |
def lv_encode(data: bytes) -> bytes:
"""Encodes data as length-value"""
return serialize_length(len(data)) + data | 55,721 |
def normalize_t(lc: LightCurve, fit: Fit) -> Transit:
""" Normalizer a light curve given a continuum fit.
TODO: more details
Args:
lc: a LightCurve object
fit: a Fit object
Returns:
transit: a LightCurve object
"""
lc_normalized = None
if lc and isinstance(lc, Lig... | 55,722 |
def _unimplemented_calls(self, *input: typing.Any) -> None:
"""
Defines the computation performed at every call.
Should be overridden by all subclasses.
"""
raise NotImplementedError | 55,723 |
def get_model_field(model):
""" get the verbose_name of all fields in the model """
field_dict = dict()
for field in model._fields:
attr = getattr(model, field)
if hasattr(attr, 'verbose_name'):
verbose_name = attr.verbose_name
if verbose_name:
field_d... | 55,724 |
def _get_create_str_fn(opt: str) -> Callable:
""" A tool function to create either a str or bytes from a 8-bit string. """
def _create_str_bytes(name: bytes) -> bytes:
return name
def _create_str_str(name: bytes) -> str:
return name.decode("latin-1")
if opt == "str":
return _cr... | 55,725 |
def admin_required(func):
"""
This is a decorator that can be applied to a Controller method that needs to allow request to process only if checks
are successful.
It checks:
- if the user is logged in (And)
- if the user is an admin
The current object is fetched using the Controller in... | 55,726 |
def test_to_not_overwrite_fields_for_grid():
"""
Test to not overwrite an existing ion field
"""
ds = load(ISO_GALAXY)
val_before = ds.r['H_p0_number_density'][0]
add_ion_fields(ds, ['H'], ftype='gas')
val_after = ds.r['H_p0_number_density'][0]
assert val_before == val_after | 55,727 |
def get_expected_tetranuc_freq(tetranuc, trinuc_freqs, dinuc_freqs):
"""
Returns the expected frequency for the given tetranucleotide.
Args:
tetranuc:
trinuc_freqs:
dinuc_freqs:
Returns:
"""
# get prefix of len 3 of tetranucleotide (n1n2n3)
first3bases = tetranuc[:3]
... | 55,728 |
def AddLocalSSDFlag(parser, suppressed=False, help_text=''):
"""Adds a --local-ssd-count flag to the given parser."""
help_text += """\
The number of local SSD disks to provision on each node, formatted and mounted
in the filesystem.
Local SSDs have a fixed 375 GB capacity per device. The number of disks that
can ... | 55,729 |
def migration_0026_copy_relation_to_repo_attributes(apps, schema_editor):
"""
Copy data in Repository instances to Project.repository_*
attributes.
"""
Project = apps.get_model("base", "Project")
for project in Project.objects.all():
repo = project.repository_set.first()
if repo ... | 55,730 |
def computeLengthsAndAngles(periodicBoxVectors):
"""Convert periodic box vectors to lengths and angles.
Lengths are returned in nanometers and angles in radians.
"""
if is_quantity(periodicBoxVectors):
(a, b, c) = periodicBoxVectors.value_in_unit(nanometers)
else:
a, b, c = periodic... | 55,731 |
def compute_info( image ):
""" Compute information on resampled and original images """
old_size, old_spac, old_orig = image.GetSize(), image.GetSpacing(), \
image.GetOrigin()
new_size, new_spac, new_orig = [], [], old_orig
for i in range(len(old_size)):
new_size.append( int(np.ceil( 1... | 55,732 |
def macro_EmbedObject(macro, target=wikiutil.required_arg(unicode), pagename=None,
width=wikiutil.UnitArgument(None, float, ['px', 'em', 'pt', 'in', 'mm', '%'], defaultunit='px'),
height=wikiutil.UnitArgument(None, float, ['px', 'em', 'pt', 'in', 'mm', '%'], defaultunit='px')... | 55,733 |
def lnprior(theta, y, lower_t_bound, upper_t_bound, transit_params,
skip_priors):
"""
Log prior for `emcee` runs.
Parameters
----------
theta : list
Fitting parameters
y : `numpy.ndarray`
Fluxes
lower_t_bound : float
Earliest in-transit time [JD]
uppe... | 55,734 |
def job_metadata_filename(metadata):
"""Construct relative filename to job metadata."""
return "data/{metadata}".format(metadata=metadata) | 55,735 |
def get_db_cols(cur, table_name, schema='public', type_map=True):
"""
Gets the column names of a given table
if type_map is true, returns also a dictionary
mapping each column name to the corresponding
postgres column type
"""
db_cols_sql = """SELECT column_name, data_type
FROM in... | 55,736 |
def demo():
"""
Perform a basic demonstration of the plotting routines.
"""
from netCDF4 import Dataset
from os.path import join as pjoin, dirname, normpath
baseDir = normpath(pjoin(dirname(__file__), '..'))
inputPath = pjoin(baseDir, 'output', 'hazard')
hazardFile = pjoin(inputPath, '... | 55,737 |
def wrap_elemwise(func, **kwargs):
""" Wrap up numpy function into dask.array """
f = partial(elemwise, func, **kwargs)
f.__doc__ = func.__doc__
f.__name__ = func.__name__
return f | 55,738 |
def parse_player_node(player_node):
"""Parses a player XML node
Parameters
----------
player_node : lxml node
The player node to parse
Returns
-------
A Player database object
"""
db_player = Player(player_id=player_node.get('id'),
first=player_node.g... | 55,739 |
def test_surface_io_export_subfolder(tmp_path):
"""Minimal test surface io with export_subfolder set,
uses tmp_path."""
srf = xtgeo.RegularSurface(
ncol=20, nrow=30, xinc=20, yinc=20, values=np.ma.ones((20, 30)), name="test"
)
fmu.dataio.ExportData.export_root = tmp_path.resolve()
fmu.d... | 55,740 |
def is_fits(input, **kwargs):
"""
Determine whether input is in FITS format
"""
if isinstance(input, six.string_types):
if input.lower().endswith(('.fits', '.fits.gz',
'.fit', '.fit.gz',
'.fits.Z', '.fit.Z')):
retu... | 55,741 |
def calc_moverscore(gold_references, model_generations, n_gram=2, batch_size=16):
"""
Calculate MoverScore
:param gold_references: list of target sections
:param model_generations: list of generated sections
:param n_gram: unigram-based MoverScore (n-gram=1), bigram-based MoverScore (n-gram=2)
... | 55,742 |
def base62_encode(raw_bytes):
"""
Encodes raw bytes into base-62 representation. URL-safe and human safe.
Encode your Unicode strings to a byte encoding before base-62-encoding
them.
Convenience wrapper for consistency.
:param raw_bytes:
Bytes to encode.
:returns:
Base-62 encoded bytes.
"... | 55,743 |
def cmc_score_count(
distances: torch.Tensor, conformity_matrix: torch.Tensor, topk: int = 1,
) -> float:
"""
Function to count CMC from distance matrix and conformity matrix.
Args:
distances: distance matrix shape of (n_embeddings_x, n_embeddings_y)
conformity_matrix: binary matrix wit... | 55,744 |
def time_series_dispatcher(args=sys.argv[1:]):
"""Parses command line and calls the different processing functions
"""
# If --clear-logs the log files are cleared
if "--clear-logs" in args:
clear_log_files(LOG_FILES)
command_args, _, api, session_file, resume = get_context(args, SETTINGS)... | 55,745 |
def run(ctx, args):
"""Runs an experiment
"""
# Strip potential operation from experiment name
exp_name, op_name = _strip_op_name_from_experiment(args)
if op_name is None:
op_name = DEFAULT_OP
log.debug(
"Running experiment: '{}' with default operation: '{}' "
... | 55,746 |
def is_valid(zma):
""" is this a valid vmatrix?
"""
ret = True
try:
assert _is_sequence_of_quadruples(zma)
syms, key_mat, name_mat, val_mat = zip(*zma)
automol.create.zmat.from_data(syms, key_mat, val_mat, name_mat)
except AssertionError:
ret = False
return ret | 55,747 |
def log2die(code, message):
"""Log to STDOUT and file, then die.
Args:
code: Error number
message: Descriptive error string
Returns:
None
"""
_logit(code, message, error=True) | 55,748 |
def timeit_context():
"""
Context manager to measure execution time of code in context.
:return TimeItResult
example:
with timeit_context() as result:
do_long_code()
print("Long code takes ", result.time_passed)
"""
result = TimeItResult()
started_time = time.time()
try... | 55,749 |
def test_config_reader_secrets_path_prop(boto_fs):
"""
Should read the secrets path file from the config yaml
"""
config_file = 'ssm/config.yaml'
session.aws_profile = None
session.aws_region = 'us-east-1'
boto_fs.create_file(config_file, contents=f"""
kms:
arn: {KEY_ARN}
secrets_fi... | 55,750 |
def _read_dot_file(filename, section, username, password):
"""
Handles the parsing of the configuration file for the username
and password.
:param str filename: Path and name of INI file.
:param str section: Name of the section in the INI file to find credentials.
:param str username: Name of t... | 55,751 |
def copy_db_snapshot_instance(source_db_snapshot_identifier,
destination_db_snapshot_identifier, snapshot_tags,
option_group_name=None, kms_key=None):
"""Function to create a copy of a rds snapshot, copying tags by default.
Args:
source_db_snap... | 55,752 |
def w_alpha():
"""
Real Name: b'W ALPHA'
Original Eqn: b'1'
Units: b''
Limits: (None, None)
Type: constant
b''
"""
return 1 | 55,753 |
def posh_execute_enabled(tmp_path_factory):
"""Return check value for whether Powershell script execution is enabled.
Posh may be available interactively, but the security settings may not allow
execution of script files.
# Enable with: PS> Set-ExecutionPolicy -scope currentuser -ExecutionPolicy Bypa... | 55,754 |
def compare_runs (path, constraint):
""" for each optimization attempt, visualize the nsubnetworks that unmet constraints """
bm_path = path + 'runs/benchmark/electronic-circuits/alu/'
# for npart in os.listdir(sol_path):
# if npart.startswith('.') == False and npart != 'best_solns.txt':
# print ('npart', npar... | 55,755 |
def calc_grad(X, Y, theta):
"""Compute the gradient of the loss with respect to theta."""
count, _ = X.shape
probs = 1. / (1 + np.exp(-X.dot(theta)))
grad = (Y - probs).dot(X)
return grad | 55,756 |
def _set_db_writable():
"""Execute a sqlite PRAGMA statement that makes the database writable."""
logger.debug("Make database writable [query_only OFF]")
sesh.execute("PRAGMA query_only = OFF;") | 55,757 |
def _docsubst(f):
"""Perform docstring substitutions"""
f.__doc__ = f.__doc__.format(**_doc_snippets)
return f | 55,758 |
def assert_equal_td_sequences(tds, td_dicts):
"""Asserts that the given sequences ot TDs and TD dicts are equal."""
assert len(tds) == len(td_dicts)
for td_dict in td_dicts:
td_match = next(td.to_dict() for td in tds if td.id == td_dict["id"])
assert_equal_tds(td_match, td_dict) | 55,759 |
def getSourceListOptDict(parser, wildcards = True):
"""
Get the list of tuples and the dictionary with options
returns:
sourceList: a list of tuples with one list element per file
the first tuple entry being the root file,
the second a list of subdirectories,... | 55,760 |
def get_capacities(topology):
"""
Returns a dictionary with all link capacities.
Parameters
----------
topology : Topology
The topology whose link delays are requested
Returns
-------
capacities : dict
Dictionary of link capacities keyed by link.
Examples
-----... | 55,761 |
def make_modbusmap_channel(i, chan, device_type_name):
"""Make a channel object for a row in the CSV."""
json_obj = {
"ah": "",
"bytary": None,
"al": "",
"vn": chan['subTitle'], # Name
"ct": "number", # ChangeType
"le": "16", # Length(16 or 32)
"grp": ... | 55,762 |
def send_img(string):
"""
Handle image request from client.
:param string: image file name
:type string: str
:returns: image file path
:rtype: str
"""
return send_from_directory(os.path.join(os.path.join(execution_path,'static'),'img'), string) | 55,763 |
def select_variables(n=50):
"""12 August 2021 Variables
excluded: ('cropland', 0.8299824473544954),
"""
l = [('nlcd', 0.7202826917050348),
('cultivated', 0.6893999449547821),
('slope', 0.36318373989279606),
('evi_3', 0.21911480248421414),
('nw_3', 0.21308324029642675)... | 55,764 |
def CleanData_CB(X,drop_feature):
"""
This function is to clean the data for training and testing with CatBoost.
X : dataframe type for train
y : dataframe type for test
drop_feature : feature name that is wanted to be dropped , e.g., ['Time']
"""
import numpy as ... | 55,765 |
def add_ind_price_plan(phone_number, ind_price_plan, exp_date=''):
"""
Adds an Individual Price Plan from the line
"""
action = 1
result = ModUserIndiPricePlan(
phone_number, ind_price_plan, action, exp_date)
return result | 55,766 |
def EventsAsEOTimes(events):
"""
:param events:
KernelTime's sorted by ktime.start_time_usec
:return:
"""
TimeType = None
psec_in_usec = None
category_eo_times = np.empty(2*len(events), dtype=py_config.NUMPY_TIME_USEC_TYPE)
for i, ktime in enumerate(events):
if psec_in_us... | 55,767 |
def dct(A):
"""
params: A matrix Nx1
output: compute dct 1D of the matrix A
"""
N = A.shape[0]
C = np.zeros(N, dtype=np.float64)
for k in range(0, N):
a_k = np.sqrt(1.0 / N) if k == 0 else np.sqrt(2.0 / N)
sum = 0
for j in range(N):
sum = sum + A[j] * np... | 55,768 |
def get_valid_tax_number_job(request_id: str):
"""
Route for retrieving job status of a tax number validity from the queue.
:param request_id: the id of the job.
"""
try:
raise NotImplementedError()
except NotImplementedError:
logging.getLogger().info("Could not retrieve status o... | 55,769 |
def all_models(awhere_api_key, awhere_api_secret):
"""Fixture that returns a dataframe containing all aWhere models.
"""
# Get all models
models = awm.get_models(key=awhere_api_key, secret=awhere_api_secret)
# Return crops
return models | 55,770 |
def parse_title(df: pd.DataFrame, source: str, target: str) -> pd.DataFrame:
"""Transformer extracting a person's title from the name string implemented as wrapped stateless function."""
def get_title(name: str) -> str:
"""Auxiliary method for extracting the title."""
if '.' in name:
... | 55,771 |
def train(shortforms, additional=None, n_jobs=1):
"""Train a deft model and produce quality statistics"""
if additional is None:
additional = []
# gather needed data
groundings_path = os.path.join(DATA_PATH, 'groundings')
texts_path = os.path.join(DATA_PATH, 'texts')
models_path = os.pat... | 55,772 |
def _GetMakeConfGenericPath():
"""Get the path to the make.conf.generic-target file."""
return os.path.join(_CHROMIUMOS_CONFIG, 'make.conf.generic-target') | 55,773 |
def levenshtein_ratio_and_distance(s, t, ratio_calc=False):
""" levenshtein_ratio_and_distance:
Calculates levenshtein distance between two strings.
If ratio_calc = True, the function computes the
levenshtein distance ratio of similarity between two strings
For all i and j, distance[... | 55,774 |
async def __resource_group_exists(clients, args):
"""
Check if the given Resource Group Exists
"""
try:
await clients.resource_client.resource_groups.get(args.resource_group_name)
except ResourceNotFoundError:
return False
return True | 55,775 |
def dca(freq_table):
"""
Distinctive Collexeme Analysis
Parameters
----------
freq_table : dict
A frequency table in the format of:
{
C1: {L1: freq, L2: freq, ...},
C2: {L1: freq, L2: freq, ...}
}
where C1 & C2 are labels fo... | 55,776 |
def get_paddings_indicator(actual_num, max_num, axis=0):
"""Create boolean mask by actual number of a padded tensor.
Args:
actual_num ([type]): [description]
max_num ([type]): [description]
Returns:
[type]: [description]
"""
actual_num = torch.unsqueeze(actual_num, axis + ... | 55,777 |
def test_get_device_detects_garagedoor(hass, mock_openzwave):
"""Test device returns garage door."""
node = MockNode()
value = MockValue(data=0, node=node,
command_class=const.COMMAND_CLASS_BARRIER_OPERATOR)
values = MockEntityValues(primary=value, node=node)
device = zwave.ge... | 55,778 |
def _run_jobqueue_multiprocessing(jobqueue, resultqueue, nprocs, clientname):
""" Split the work with jobs in jobqueue and results in
resultqueue into several processes. Launch each process with
factorizer_worker as the worker function, and wait until all are
finished.
"""
procs = _s... | 55,779 |
def create_ffxml_file(
gaff_mol2_filenames,
frcmod_filenames,
ffxml_filename=None,
override_mol2_residue_name=None,
):
"""Process multiple gaff mol2 files and frcmod files using the XML conversion and write to an XML file.
Parameters
----------
gaff_mol2_filenames : list of str
T... | 55,780 |
def get_state_names_and_ids(zfill=False):
""""! Get list of federal state names and IDs sorted according to state ID.
@param zfill [Default: False] Defines whether state IDs are zero-filled to
two digits and returned as a string or returned as an integer.
@return List of federal names and IDs sorte... | 55,781 |
def get_api_name(config: Dict[str, ConfigVO] = None) -> str:
""" 获取API名字 """
key = const.Key.Api.NAME.value
vo = config.get(key) if config else dao.get_config(key)
return vo.value if vo and vo.value else const.Key.Api._NAME_WALLHAVEN.value | 55,782 |
def _run_with_retries(cmd, max_retries=CMD_RETRY_COUNT, retry_exitcodes=(1,),
retry_message="", cmd_env=None):
"""Run a command and retry until success or max_retries is reached.
:param: cmd: str: The apt command to run.
:param: max_retries: int: The number of retries to attempt on a ... | 55,783 |
def agree_within_layers(layer_heights, surface_normal = np.array([0, 0, 1]), cutoff_above_top = None, cutoff_below_bottom = None):
"""Assign mobile atoms to agreement groups based on their layer in the material.
In a system with fixed layers, like a surface slab (especially one with a
fixed bottom layer th... | 55,784 |
def split_indexes(indexes):
"""Split indexes list like 1 2 5 in 1 2 and 5."""
left, right = [indexes[0], ], []
left_now = True
for i in range(1, len(indexes)):
prev = indexes[i - 1]
curr = indexes[i]
if curr > prev + 1 and left_now:
left_now = False
if left_no... | 55,785 |
def _build_path(source: Source, fmt: Format) -> str:
""" Create the relative path for source and fmt """
return f"{_Path[fmt.name].value}/{source.value}.{fmt.value}" | 55,786 |
def handle_button_click(event):
"""Handles response based on action of 'CARD_CLICKED'
Args:
event:
The 'CARD_CLICKED' being parsed by handler
Returns:
dict
dictionary containing event response
"""
event_action = event['action']['actionMethodName']
user_data = get_us... | 55,787 |
def set_cookies(response: Response, data: dict) -> None:
"""
Update a :class:`.Response` with cookies in controller data.
Contollers seeking to update cookies must include a 'cookies' key
in their response data.
"""
# Set the session cookie.
cookies = data.pop('cookies')
if cookies is N... | 55,788 |
def identify(path):
"""Work out what an image is."""
if not os.path.exists(path):
return {}
out, _ = util.execute(None,
'qemu-img info %s' % path)
data = {}
for line in out.split('\n'):
line = line.lstrip().rstrip()
elems = line.split(': ')
... | 55,789 |
def convolve_functions(fn1, fn2, interval, dt, padding_f=0.1, name=None):
"""
Convolve fn1 with fn2.
Parameters
----------
fn1 : sympy expr
An expression that is a function of t only.
fn2 : sympy expr
An expression that is a function of t only.
interv... | 55,790 |
def _plot_seeds(ax, df_da: TfsDataFrame, da_col: str, interpolated: bool) -> Tuple[list, list]:
"""Add the Seed lines to the polar plots, if df_da is given.
Args:
ax: Axes to plot in
df_da: DataFrame with DA information
da_col: Dynamic Aperture column (ALOST1 or ALOST2)
i... | 55,791 |
async def async_setup_platform(
hass, config, async_add_entities, discovery_info=None
): # pylint: disable=unused-argument
"""Setup sensor platform."""
async_add_entities([GtasksSensor(hass, discovery_info)], True) | 55,792 |
def main(args):
"""Select columns from csv file.
Args:
args: args from argparse module.
"""
if not args.output_delimiter:
args.output_delimiter = args.input_delimiter
columns = args.columns.strip().split(',')
if args.pandas:
csv_select_cols_pandas(columns)
else:
... | 55,793 |
def o_table_list(
cells, pgs, outfile=None, name=None, infile=None, output_type=None):
"""Output list of lists"""
outfile = outfile or sys.stdout
tab = table_to_list(cells, pgs)
print(tab) | 55,794 |
def remove_flags(flag_values=FLAGS):
"""Deletes the flag definitions done by the above define_flags()."""
for flag_name in names_of_defined_flags():
module_bar.remove_one_flag(flag_name, flag_values=flag_values)
module_bar.remove_flags(flag_values=flag_values) | 55,795 |
def sockaddr_convert(val: SockaddrConvertType) -> sockaddr_base:
"""Try to convert address into some sort of sockaddr"""
if (
isinstance(val, sockaddr_in)
or isinstance(val, sockaddr_in6)
or isinstance(val, sockaddr_storage)
):
return val
if isinstance(val, IPv4Address):
... | 55,796 |
def scharr3_dxz( input, output=None, full=True, mode="reflect", cval=0.0):
"""Scharr 3 point first derivative along the 1st and last (x and z) axis of input.
Applies a 3 point Scharr first derivative filter along the 1st and last
(x and z) axis of the input array as per:
Scharr, 2005: Optimal derivative filter ... | 55,797 |
def forward_hierarchical_differences(graph, weight=None):
"""Returns the forward hierarchical differences over the edges of a network in the form of a weighted adjacency matrix
Parameters
----------
graph : Graph, array
A NetworkX graph or numpy/sparse array
weight : string
... | 55,798 |
def test_import_issues():
"""Test the Olive XML importer with sample data."""
inp_dir = pkg_resources.resource_filename(
'text_importer',
'data/sample_data/Olive/'
)
access_rights_file = pkg_resources.resource_filename(
'text_importer',
'data/sample_data/Olive/access_ri... | 55,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.