content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def find_files(regex, topdir=curdir, exclude=None, exclude_vcs=True, exclude_reproman=False, dirs=False):
"""Generator to find files matching regex
Parameters
----------
regex: basestring
exclude: basestring, optional
Matches to exclude
exclude_vcs:
If True, excludes commonly known ... | 75,300 |
def load_labels_map(labels_map_path):
"""Loads the labels map from the given path.
The labels mmap must be in the following plain text format::
1:label1
2:label2
3:label3
...
The indexes are irrelevant to this function, they can be in any order and
can start from zero,... | 75,301 |
def get_user(email):
"""
Return a user object by email lookup
"""
model = get_user_model()
return model.objects.get(email=email) | 75,302 |
def generate_pruned_random_no_correlations_dataset(n_token, n_docs, n_subjects, min_samples):
"""Generate random data without any subject correlations, but with minimum samples per subject."""
dataset = generate_random_dataset(n_token, n_docs, n_subjects)
return filter_subjects_with_insufficient_samples(dat... | 75,303 |
async def m_aggregate(table, pipeline, **kwargs):
""" aggregate """
db, kwargs = get_motor(**kwargs)
plan = await db.command(SON([("aggregate", table), ("pipeline", pipeline)]))
return plan | 75,304 |
def chatter_bot() -> None:
"""Initiates chatter bot."""
file1 = 'db.sqlite3'
file2 = f"/Users/{os.environ.get('USER')}/nltk_data"
if os.path.isfile(file1) and os.path.isdir(file2):
bot = ChatBot("Chatterbot", storage_adapter="chatterbot.storage.SQLStorageAdapter")
else:
speaker.say('... | 75,305 |
def test_ping_with_key(server, test_user):
""" Tracking server can query by tracking key """
# Create fake ping message
ping_id = 42
message = struct.pack('!IHHQHHI', _server.MAGIC, 0, _server.TYPE_PING,
test_user.tracking_key, ping_id, 0, 0)
message = set_crc(message)
... | 75,306 |
def neurons_values(lstm_layer: md.ml.nn.layers.LSTMLayer, data: List[float], ppty_name: str) -> List[np.ndarray]:
"""
Get the activation values for a LSTM layer
Args:
lstm_layer: LSTM layer
data: data to process
ppty_name: the type of values to get
Returns: List where each position is the activation value fo... | 75,307 |
def band_stop_filter(signal, Fs, Fc=60):
"""
This function filters out frequencies close to a desired cutoff Fc (in Hz).
The default Fc is 60 Hz as that is most common for unwanted noise
:param list signal: input signal
:param int Fs: sampling frequency in Hz
:param int Fc: cutoff frequency in ... | 75,308 |
def bbox_to_integer_coords(t, l, b, r, image_h, image_w):
"""
t, l, b, r:
float
Bbox coordinates in a space where image takes [0; 1] x [0; 1].
image_h, image_w:
int
return: t, l, b, r
int
Bbox coordinates in given image's pixel spa... | 75,309 |
def download_gdocs(
g_ids: Dict[str, str],
format: str = "docx",
dir_path: str = "_word",
chunk_size: int = 8192,
):
""" Downloads specified google docs into /_word as .docx files
Args:
urls (dict): A dict of doc_name, url key value pairs of
e.g. "my post": "1d1N-2... | 75,310 |
def load_config(args):
"""Tries to load the configuration file or throws ExitWithError."""
config = ConfigManager(DEFAULT_CONFIG)
config_dir = home_dir.get()
try:
if args.config_file is not None:
filename_override = os.path.abspath(args.config_file)
else:
filename... | 75,311 |
def circular_layout(G, scale=1, center=None, dim=2):
# dim=2 only
"""Position nodes on a circle.
Parameters
----------
G : NetworkX graph or list of nodes
A position will be assigned to every node in G.
scale : number (default: 1)
Scale factor for positions.
center : array... | 75,312 |
def plot_marginal_lune(filename, ds, var, **kwargs):
""" Plots maximum likelihood values on eigenvalue lune (requires GMT)
.. rubric :: Required input arguments
``filename`` (`str`):
Name of output image file
``ds`` (`DataArray` or `DataFrame`):
Data structure containing moment tensors and co... | 75,313 |
def sdp_sub(f, g, u, O, K):
"""Subtract distributed polynomials in `K[X]`. """
h = dict(f)
for monom, c in g:
if h.has_key(monom):
coeff = h[monom] - c
if not coeff:
del h[monom]
else:
h[monom] = coeff
else:
h[... | 75,314 |
def create_meeting():
"""
При GET запросе возвращает страницу для создания встречи.
При POST запросе, в случае успешной валидации сохраняет
новую встречу в БД.
"""
title = 'Создание встречи'
meeting_form = MeetingForm(request.form)
with db_session() as session:
meet_data = GameMe... | 75,315 |
def correlation_ratio(col1: ndarray, col2: ndarray) -> float:
"""Returns the correlation ratio for col1 and col2.
Used for categorical - numerical variable pairs.
Args:
col1 (ndarray): A categorical column with no null values
col2 (ndarray): A numerical column with no null values"""
uni... | 75,316 |
def test_fake_cmdline_user(fake_user):
"""
"""
game = Game(initial=ASCII_START_BOARD)
game.user.set_moves(['b2 e4'])
assert game.get_move() == ((1, 1), (4, 3)) | 75,317 |
def read_txt_tensor(filePath):
""" read tensor data from text file.
Parameters
----------
filePath : str
the path of file
Returns
-------
tensor
three-way numpy array
"""
tensor = pd.read_csv(filePath, header=0, names= ["v1", "v2", "v3", "v4"])
rowIndices ... | 75,318 |
def train_sequence_model(data: Tuple[Any, Any], output_dir: str, embedding_dim: int = 200, dropout_rate: float = 0.2,
filters: int = 3, kernel_size: int = 3, pool_size: int = 3, num_classes: int = 3,
learning_rate: float = 1e-3, epochs: int = 1000, batch_size: int = 128... | 75,319 |
def execute(*args, **kwargs):
# type: (*Any, **Any) -> psutil.Popen
"""A thin wrapper around 'psutil.Popen'"""
if is_unix:
# Call os.setpgrp to make sure the process starts in a new group
orig = kwargs.get('preexec_fn', None)
def wrapper():
os.setpgrp()
if or... | 75,320 |
def get_pose3_vector(num_poses: int) -> Pose3Vector:
"""Generate camera poses for use in triangulation tests"""
# Looking along X-axis, 1 meter above ground plane (x-y)
upright = Rot3.Ypr(-np.pi / 2, 0.0, -np.pi / 2)
pose1 = Pose3(upright, Point3(0, 0, 1))
# create second camera 1 meter to the rig... | 75,321 |
def test_read_storage_stats(input_filename):
"""Parses up to the STORAGE section."""
target_file = open(input_filename)
test_dmi = parse_dmidecode.read_dmidecode(target_file)
test_os = parse_operating_system.read_operating_system(target_file)
test_cpu_stats = parse_cpu.read_cpu_stats(target_file)
... | 75,322 |
def execute_request_with_global_keys(operation, url, **kwargs):
"""execute_request_with_global_keys helper function
which takes a global CP4S API Key and Secret rather than one
derived from cases.
These API keys use different authentication methods and
API calls using this client will be slightly ... | 75,323 |
def from_datestring(datestring):
"""Parse an arbitrary datestring and return a datetime object using
dateutils' parser.
"""
if dateutil_available:
return parser.parse(datestring)
else:
raise RuntimeError('from_datestring requires the python-dateutil library') | 75,324 |
def clean_word(word):
"""Clean the word.
Parameters
----------
word : str
Returns
-------
str
"""
new_word = (word
.replace('(', '')
.replace(')', '')
.replace(':', '')
.replace(';', '')
.replace('+', '... | 75,325 |
def set_interrupt_handler(interrupt_signal=DEFAULT_SIGNAL):
"""
Set up an interrupt handler, to activate PuDB when Python receives the
signal `interrupt_signal`. By default it is SIGINT (i.e., Ctrl-c).
To use a different signal, pass it as the argument to this function, like
`set_interrupt_handler... | 75,326 |
def test_applies_to_this_folder_files(test_dir):
"""
#60103
"""
result = win_dacl.set_permissions(
obj_name=test_dir,
principal="Backup Operators",
permissions="full_control",
access_mode="grant",
applies_to="this_folder_files",
obj_type="file",
re... | 75,327 |
def CorrMatrix_2700ns(uvd, HHfiles, difffiles, flagfile, JD, N_threads=12):
"""
Plots a matrix representing the 2700ns feature correlation of each baseline.
Parameters:
----------
uvd: UVData Object
Sample observation from the desired night, used for getting antenna information.
HHfiles... | 75,328 |
def register_logger(app):
"""
Usage:
from flask import current_app
current_app.logger.info(...) current_app.logger.debug(...) ... current_app.logger.error(...)
"""
import logging
from logging.handlers import RotatingFileHandler
rfh = RotatingFileHandler('%s/logs/proj.log' % app.config.g... | 75,329 |
def setup_next_command():
"""Gets the next command from the command queue and sets up the state machine"""
global act_st
if(len(cmd.cmdlist) > 0):
command = cmd.cmdlist.popleft()
# print("Next command: " + repr(command))
if(command == Cmd.GO_STRAIGHT):
act_st = States.FOR... | 75,330 |
def getAdminData(self, **params):
"""
Deliver admin content of module maps (ajax)
:return: rendered template as string or json dict
"""
if request.args.get('action') == 'checkpath':
if os.path.exists(request.args.get('path')):
return '1'
return '0'
elif request.args... | 75,331 |
def get_attrib_recursive(element, *attribs):
"""Find the first attribute in attribs in element or its closest ancestor
that has any of the attributes in attribs.
Usage examples:
get_attrib_recursive(el, "fallback-langs")
get_attrib_recursive(el, "xml:lang", "lang")
Args:
elemen... | 75,332 |
def _antisymmetricity_score(v_1: float, v_2: float, coef_lambda: float):
"""
degree of the anti-symmetry between two values.
z = exp(-\lambda*d(v_1,v_2))
d(v_1,v_2) = |v_1 + v_2|
:param v_1: a value
:param v_2: another value
:param lambda: exponential decay parameter.
:return: z
"""
... | 75,333 |
def find_extra_inferred_properties(spec_dict: dict) -> list:
"""Finds if there are any inferred properties which are used.
Args:
spec_dict: Dict obj containing configurations for the import.
Returns:
List of properties that appear in inferredSpec but are not part of 'pvs' section.
"""
re... | 75,334 |
def change_existing_ccx_coaches_to_staff(apps, schema_editor):
"""
Modify all coaches of CCX courses so that they have the staff role on the
CCX course they coach, but retain the CCX Coach role on the parent course.
Arguments:
apps (Applications): Apps in edX platform.
schema_editor (Sc... | 75,335 |
def _setupSession():
"""
Link the user keyring into the session keyring. pam_keyinit.so normally
does this by default, but do it again in case someone made a new session or
the session was revoked.
We want to add keys to the user keyring so that they are reachable across
sessions, and continue ... | 75,336 |
def signup(driver, Users, ISAAC_WEB, WAIT_DUR, **kwargs):
"""Test whether users can sign up to Isaac using an email address.
- 'driver' should be a Selenium WebDriver.
- 'Users' must be a TestUsers object.
- 'ISAAC_WEB' is the string URL of the Isaac website to be tested.
- 'WAIT_DU... | 75,337 |
def show_progress(progress: int) -> None:
"""
Simple progess counter.
"""
sys.stderr.write(f'\r{progress} processed...\r')
sys.stderr.flush() | 75,338 |
def collate(data, tokenizer, block_size, device):
""" Collate formats the data passed to the data loader.
In particular we tokenize the data batch after batch to avoid keeping them
all in memory. We output the data as a namedtuple to fit the original BertAbs's
API.
"""
data = [x for x in data if... | 75,339 |
def setup_boundary_conditions(domain, project):
"""
Edit this if new types of boundary conditions need to be supported
"""
# Dict to hold { boundary_tag: boundary_condition_function }
boundary_tags_and_conditions = {}
for i in range(len(project.boundary_data)):
bd = project.boundary_da... | 75,340 |
def _read_json(nc):
"""
This is easily the laziest piece of code in this library. In the future, I want
to modify this to be a simple CFG parser to identify valid JSON, but in the meantime,
performance wasn't my priority, and this gets the job done.
"""
json_str = ''
last_char = ''
whil... | 75,341 |
def zeroDistanceByFit(analysis, axis='y', useTrap='pm'):
"""
Find the trap distance at which the beads touch and use this as an offset to calculate the extension.
Args:
analysis (:class:`.TweezersAnalysis`): analysis file to check
axis (str): axis on which to do the correction, either 'y' (... | 75,342 |
def log_file_path():
"""
Provides the path where tor's log file resides, if one exists.
:returns: **str** with the absolute path of tor log file, or **None**
if one doesn't exist
"""
controller = tor_controller()
for log_entry in controller.get_conf('Log', [], True):
entry_comp = lo... | 75,343 |
def topics(request):
"""显示所有的主题"""
topics = Topic.objects.order_by('date_added')
context = {'topics': topics}
return render(request, 'learning_logs/topics.html', context) | 75,344 |
def parse_styles(node, source):
"""Return the Styles represented by node."""
styles = []
for style_type, value in node.items():
if style_type == 'opacity':
amount = value
opacity = Opacity(amount)
styles.append(opacity)
elif style_type == 'fill':
... | 75,345 |
def moveYaxis(board, way):
"""
Function used to move in list on y axis a.k.a. vertical axis.
"""
if(way == "up"):
new_board = turn(sanitizey(board, "up"))
for i in range(len(new_board)):
for j in range(len(new_board)):
if(new_board[i][j] in powers_of_two and... | 75,346 |
def calculate_idf(list_books):
"""
IDF = ln((total_numbers of docs)/(number of docs in which the word is present))
:param list_books: list of the all the books
:return: IDF of all the books
"""
total_documents = len(list_books) # total number of documents
master_map = {}
for book in li... | 75,347 |
def _PreprocessComponentCond(
cnxn, cond, project_ids, services, harmonized_config):
"""Preprocess a component= or component:name cond into component_id=IDs."""
exact = _IsEqualityOp(cond.op)
component_ids = []
if project_ids:
# We are searching within specific projects, so harmonized_config
# holds... | 75,348 |
def attention_layer(input_tensor,
attention_mask,
num_attention_heads,
size_per_head,
query_act,
key_act,
value_act,
attention_dropout_prob,
initializer_range,
... | 75,349 |
def _GetAssetName(args):
"""Prepares asset relative path using organization and asset."""
resource_pattern = re.compile("organizations/[0-9]+/assets/[0-9]+")
id_pattern = re.compile("[0-9]+")
assert resource_pattern.match(args.asset) or id_pattern.match(args.asset), (
"Asset must match either organization... | 75,350 |
def main(argv=None):
"""Entry point"""
parser = argparse.ArgumentParser(
description="Test matplotlib's plot3d with a flowing data feed")
parser.add_argument(
'-a', '--animate', dest='method', action='store_const',
const=METHOD_ANIMATE,
help="use matplotlib.animation method")... | 75,351 |
def start():
"""
Starts the Web Server at TCP 5000
:returns: When the server has finished; either normally or abnormally
:raises: any internal exception
"""
app.run(host=ListenIp,port=TCPport, debug=False) | 75,352 |
def tweet(text):
"""tweet"""
auth = tweepy.OAuthHandler(CK, CS)
auth.set_access_token(AT, AS)
api = tweepy.API(auth)
api.update_status(text) | 75,353 |
def get_antithetic_slices(shape: tp.Sequence[int],
antithetic_dimension: int) \
-> tp.Tuple[slice, ...]:
"""
This function generates a tuple of slices to index the original array of
random numbers to take either half or one less than half of the the original
random numb... | 75,354 |
def unquote(string, charset="utf-8"):
"""Unquote and normalize unicode string.
Params:
string : string to be unquoted
charset : string : optional : output encoding
Returns:
string : an unquoted and normalized string
"""
string = unquote_orig(string)
string = force_unic... | 75,355 |
def calculate_panelist_losing_streaks(panelists: List[Dict],
database_connection: mysql.connector.connect):
"""Retrieve panelist stats and calculate their losing streaks"""
losing_streaks = []
for panelist in panelists:
longest_losing_streak = 0
longes... | 75,356 |
def unaccept_application(application):
"""
Deletes the Talk or Workshop created from this PaperApplication.
(idempotent)
"""
if application.has_instance:
application.instance.delete() | 75,357 |
def find_corresponding_basins(pfaf_id_level6,gdf_level7):
"""
Using a pfaf_id from level 6, find all hydrobasins in level 7 that
make up the hydrobasin level 6 polygon.
"""
pfaf_id_level7_min = pfaf_id_level6*10
pfaf_id_level7_max = pfaf_id_level7_min + 9
gdf_level7_selection = gd... | 75,358 |
def import_models():
"""Auto import all classes. Note that this will load all classes, not just model classes.
It also does not support nested packages. """
this_module = sys.modules[__name__]
LOG = logging.getLogger(this_module.__name__)
for loader, module_name, is_pkg in pkgutil.iter_modules(
... | 75,359 |
def repack_ooxml(sourcename, destname):
"""Repak a MS Office file."""
with UnpackedZip(sourcename) as tempdir:
basename, ext = osp.splitext(sourcename)
path_media = osp.join(tempdir, OOXML_MEDIA[ext])
# compress png media
args = [UTIL_EXE.get('optipng', None)]
if args[0]... | 75,360 |
def plotFit(data, fit, is_plot=True):
"""
Plots observed vs. fit
:param array.float data:
:param array.float fit:
"""
plt.scatter(data, fit)
plt.xlabel("Observed")
plt.ylabel("Fitted")
line_x = [data[0], data[-1]]
line_y = [fit[0], fit[-1]]
plt.plot(line_x, line_y, 'r')
if is_plot:
plt.show(... | 75,361 |
def downsize_storm_images(
storm_image_matrix, radar_field_name, num_rows_to_keep=None,
num_columns_to_keep=None):
"""Downsizes storm-centered radar images.
:param storm_image_matrix: See doc for `_check_storm_images`.
:param radar_field_name: Same.
:param num_rows_to_keep: Number of ro... | 75,362 |
def uninitializePlugin(obj):
"""Remove and uninstall plugin."""
print("Removing Azure Batch plug-in")
plugin = MFnPlugin(obj)
plugin.deregisterCommand(cmd_name)
try:
mel.eval('deleteShelfTab %s' % "AzureBatch")
except:
print("Couldn't delete shelf")
global fMayaExitingCB
... | 75,363 |
def apply_tile_blur(tile, circle_blur):
"""
Blur the classification tile by radial distance from robot.
(Less confident in pixels "further" away)
Inputs:
tile: Classification tile (nparray 3 chan RGB)
circle_blur: "kernel" tile of same shape, with circular gradient (1 in center, fades... | 75,364 |
def test_version_cmp_python():
"""
Test package version if falling back to python
:return:
"""
mock_log = MagicMock()
patch_rpm = patch("salt.modules.rpm_lowpkg.HAS_RPM", False)
patch_rpmutils = patch("salt.modules.rpm_lowpkg.HAS_RPMUTILS", False)
mock_version_cmp = MagicMock(return_val... | 75,365 |
def gen_fits(args):
"""
Helper function for generating FITs integrations from a slope image
"""
from .simul.ngNRC import slope_to_ramp
# Must call np.random.seed() for multiprocessing, otherwise
# random numbers for parallel processes start in the same seed state!
np.random.seed()
try:... | 75,366 |
def gaussian_kernel(y,sigma=7):
"""
gaussian_kernel: Gaussian filter.
Arguments:
y (numpy array): input 2D map.
sigma (float) (default=7): effective length of Gaussian smoothing.
--------
Returns:
kerneled image.
"""
return gaussian_filter(y, sigma) | 75,367 |
def get_vid_info_list(mode, img_path, keypoints_path, imgnums_txtfile, i, k=None):
"""
General function to create vid_info_list for all meta-learning datasets
"""
vids = glob.glob(keypoints_path + 'keypoints_*')
n_vids = len(vids)
vid_info_list = []
if mode == ModelMode.train:
for i in range(1, n_vids... | 75,368 |
def set_globals(lo_par, hi_par):
"""
Helper function setting the global variables values.
Computes the number to be guessed and sets the maximal numbers of
guesses for given lo_par : hi_par parameters,
which in turn sets the global range variables: hi and lo
.
"""
global secret_number
... | 75,369 |
def header(buffer: bytes, offset: int = 0) -> Tuple[bytes, str, List[int], int]:
"""
Unpack a Starbound header structure from the buffer at a given offset.
:param buffer: buffer to read
:param offset: offset in buffer
:return: Starbound header
"""
save_format = buffer[offset:offset + 6]
... | 75,370 |
def create_setting_analyzer_ranking(
optimizer_path, mode="final", metric="valid_accuracies"
):
"""Reads in all settings in ``optimizer_path`` and sets up a ranking by returning an ordered list of SettingAnalyzers.
Args:
optimizer_path (str): The path to the optimizer to analyse.
mode (str):... | 75,371 |
async def async_setup_entry(opp, entry):
"""Set up a smarttub config entry."""
controller = SmartTubController(opp)
opp.data.setdefault(DOMAIN, {})
opp.data[DOMAIN][entry.entry_id] = {
SMARTTUB_CONTROLLER: controller,
}
if not await controller.async_setup_entry(entry):
return F... | 75,372 |
def merge_dicts(idx, *args):
"""
Merges lists of dictionaries, by adding each other the values of
corresponding dictionaries
`args` can contain `None` values (except for the first one); in such case,
that argument will be skipped; this is useful if a dataset contains
annotations not for all the... | 75,373 |
def send(signal, sender=dispatcher.Anonymous, *args, **kwargs):
"""
Sends a signal, causing connected handlers to be invoked.
Parameters:
:signal: Signal to be sent. This must be an instance of :class:`wa.core.signal.Signal`
or its subclasses.
:sender: The sender of the si... | 75,374 |
def fp_fn_eval(query_features: torch.Tensor,
query_labels: torch.LongTensor,
ks: List[int],
gallery_features: Optional[torch.Tensor] = None,
gallery_labels: Optional[torch.Tensor] = None,
cosine: bool = False,
threshol... | 75,375 |
def backupFromGoogleSheet(fileUri):
"""Reads google spreadsheet file from given path and make sures backup
is stored for listed reposities in the given fileUri.
"""
cloneCount = fetchCount = failCount = 0
sheetResponse = urllib.request.urlopen(fileUri)
sheetLines = [l.decode('utf-8') for l in sh... | 75,376 |
def get_row_iterator(iterable, options=None):
"""Accepts an interable, options and returns a csv.DictReader object
which can be used to yield CSV rows."""
options = options or {}
def get_csv_quoting(options):
quoting = str(options.get('quoting', "MINIMAL")).upper()
quoting_choices = {
... | 75,377 |
def add_rez_to_path(rez_bin_folder):
"""
Add bin folder of an already installed rez to user's Path env var
"""
try:
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Environment', 0,
winreg.KEY_ALL_ACCESS)
val, type = winreg.QueryValueEx(key, "Path")
i... | 75,378 |
def sort_exptime(table):
"""
Calculate the EPIC exposure time and sort the obsids
in table by this value, in ascending order.
"""
texp_m1 = table['M1_TEXP']
texp_m2 = table['M2_TEXP']
texp_pn = table['PN_TEXP']
table['EP_TEXP'] = (3*texp_pn + texp_m1 + texp_m2)/5
table.sort('EP_TEXP'... | 75,379 |
def get_content_function_ratio(content, function):
""" Calculate the content-function word ratio. """
ratio = float(len(content)) / float(len(function)) if len(function) != 0 else 0
return round(ratio, 4) | 75,380 |
def AdVm(context, machine_type, zone, image):
"""Creates a VM definition for the AD VM.
This VM only has a single boot disk because it will not be a part of the
cluster.
Args:
context: context of the deployment.
machine_type: full path of the machine type.
zone: The zone where the VM will reside.
... | 75,381 |
def calc_diarization_error(pred, label, label_delay=0):
"""
Calculates diarization error stats for reporting.
Args:
pred (ndarray): (T,C)-shaped pre-activation values
label (ndarray): (T,C)-shaped labels in {0,1}
label_delay: if label_delay == 5:
pred: 0 1 2 3 4 | 5 6 ... 99 10... | 75,382 |
def _s3_state_fetch(bucket_name, prefix=""):
"""
This function exists to locate state files from S3
"""
client = boto3.client('s3')
logger.info("Processing bucket: %s" % bucket_name)
items = client.list_objects(Bucket=bucket_name, Prefix=prefix)
# _search_state(bucket_name, "sandbox_main/... | 75,383 |
def lineage_proof_for_coin_spend(coin_spend: CoinSpend) -> Program:
"""Take a coin solution, return a lineage proof for their child to use in spends"""
coin = coin_spend.coin
parent_name = coin.parent_coin_info
amount = coin.amount
inner_puzzle_hash = None
if coin.puzzle_hash == LAUNCHER_PUZZLE... | 75,384 |
def literalquery(statement):
"""NOTE: This is entirely insecure. DO NOT execute the resulting strings."""
import sqlalchemy.orm
if isinstance(statement, sqlalchemy.orm.Query):
statement = statement.statement
return statement.compile(
dialect=LiteralDialect(),
compile_kwargs={'lit... | 75,385 |
def nb_clear_outputs(file_in, file_out=None):
"""clear output cells"""
if file_out is None:
file_out = file_in
data = nbformat.read(file_in, as_version=nbformat.NO_CONVERT)
assert isinstance(data['cells'], list), 'cells is not a list'
cells = []
for cell in data['cells']:
if ce... | 75,386 |
def filter_nb(nb):
"""Returns the parts of nb tagged for export and a list of question metadata."""
new_cells = []
for i, cell in enumerate(nb['cells']):
if is_question_cell(cell):
src = str(cell["source"])
assert len(nb['cells']) > i + 1, 'A response cell must follow questio... | 75,387 |
def get_all_sorted(sort='alphabetical', cb_type='planet'):
"""Lists celesital bodies in our solar system by a specified sorting parameter.
Parameters
----------
sort : string
specified order: 'alphabetical' or 'positional' (increasing distance from Sun)
cb_type : string
celestial b... | 75,388 |
def _assemble_source_procurement_records(id_list):
"""Return a list of dictionaries, in the same structure as `fetchall` when using psycopg2.extras.DictCursor"""
for trx_id in id_list:
dummy_row = _assemble_dummy_source_data()
dummy_row["detached_award_procurement_id"] = trx_id
dummy_row... | 75,389 |
def delete_waf_v1_ipset_ipv6_rule(ipset_id, ip_address, messages):
""" Delete the IP address of an IP Set from AWS WAF v1 """
delete_waf_v1_ipset_ipvx_rule(ipset_id, ip_address, 'IPV6', messages) | 75,390 |
def testAndGetNamesBase(cfg):
"""Gets names for the cell, node, server, etc in a single-server environment.
Stores the values in provided dictionary cfg."""
m = "testAndGetNamesBase:"
sop(m,"Entry.")
# Verify we are running on a single-server.
env = whatEnv()
if 'base' != env:
er... | 75,391 |
def status_embed(ctx, member: Member) -> Embed:
"""
Construct status embed for certain member.
Status will have info such as member device, online status, activity, roles etc.
:param ctx: context variable to get the member
:param member: member to get data from
:return: discord.Embed
"""
... | 75,392 |
def get_fw_version():
"""
Try to get version of the framework. First try pkg_resources.require, if that fails
read from setup.py
:return: Version as str
"""
version = 'unknown'
try:
pkg = require(get_fw_name())[0]
except DistributionNotFound:
# Icetea is not installed. tr... | 75,393 |
def sequentially_resolve_permutation(
blocks: tf.Tensor,
window: tf.Tensor,
loss_fn: LossType = _mag_stft_mse_loss) -> tf.Tensor:
"""Resolves permutation between overlapping blocks.
Args:
blocks: Waveform in blocks (blocks, sources, samples)
window: Window function used to obtain the blocks.
... | 75,394 |
def read_SLR_geocenter(geocenter_file, RADIUS=None, HEADER=0,
COLUMNS=['time','X','Y','Z','X_sigma','Y_sigma','Z_sigma']):
"""
Reads monthly geocenter files from satellite laser ranging
Arguments
---------
geocenter_file: Satellite Laser Ranging file
Keyword arguments
-----------------... | 75,395 |
async def invalid_content_length_and_chunking(request: HttpRequest) -> HttpResponse:
"""A response handler which sends it's body in chunks with an invalid content length"""
headers = [
(b'content-type', b'text/plain'),
(b'content-length',
str(int(len(request.info['text']) / 2)).encode('... | 75,396 |
def get_activity(profile_id):
""" only API_INSTANCE that will be serve /a/.* """
if os.environ['API_INSTANCE'] in request.url_root:
http = credentials.authorize(httplib2.Http(memcache))
service_http = discovery.build("plus", "v1", http=http)
activities = service_http.activities().list(us... | 75,397 |
async def setup_team(user_id, user_name):
"""Add user to users collection and do the initial setup.
The initial setup is basically creating team & queues document for
the user in the database.
Parameters
----------
user_id : int
Telegram user id of the person who issued the /setup comm... | 75,398 |
def linear_increasing_velocity(model_param_set, **kwargs):
""" Friendly wrapper for instantiating the linear-increased-velocity medium model. """
# Setup the defaults
model_config = dict(z_delta=None,
min_ppw_at_freq=(6,10.0), # 6ppw at 10hz
y_length=None, y_... | 75,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.