content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def train(dataset, val_dataset, v, start_epoch=0):
"""Train the model, evaluate it and store it.
Args:
dataset (dataset.PairDataset): The training dataset.
val_dataset (dataset.PairDataset): The evaluation dataset.
v (vocab.Vocab): The vocabulary built from the training dataset.
... | 24,900 |
def verify_manager_list(clazz):
"""Verifies that managers return List<? extends Parcelable> instead of arrays."""
if not clazz.name.endswith("Manager"): return
for m in clazz.methods:
if m.typ.startswith("android.") and m.typ.endswith("[]"):
warn(clazz, m, None, "Methods should return ... | 24,901 |
def _ge(t1: 'Tensor', t2: 'Tensor', isnew: bool) -> 'Tensor':
"""
Also see
--------
:param t1:
:param t2:
:param isnew:
:return:
"""
data = t1.data >= t2.data
requires_grad = t1.requires_grad or t2.requires_grad
depends_on: List[Dependency] = []
if t1.requires_grad:
... | 24,902 |
def test_haar2d():
"""
Asserts the forwards and inverse wavelet transformations are correct.
"""
assert haar2d(np.random.random([5,3]),2,debug=True).shape == (8,4), \
"Transform data must be padded to compatible shape."
assert haar2d(np.random.random([8,4]),2,debug=True).shape == (8,4), \
... | 24,903 |
def convert_homogeneous_graph(graph: Dict[str, Any],
num_graphs: int,
output_dir: str):
"""Process a homogeneous graph."""
# NOTE(blais): We could in theory stash the data in the same format as their
# heterogeneous graphs in Python and just use convert... | 24,904 |
def create_capacity_to_activity(connector, technology_list):
"""
This function writes the capacity to activity table in Temoa.
"""
table_command = """CREATE TABLE "CapacityToActivity" (
"regions" text,
"tech" text,
"c2a" real,
... | 24,905 |
def create_virtualenv():
"""Create virtualenv for project."""
site = get_project_name()
version = get_config()['version']
virtualenv_dir = "{}/{}/virtualenv".format(SITES_DIR, site)
if cuisine.dir_exists(virtualenv_dir + "/bin"):
fab.puts("virtualenv for {0} already exists".format(site))
... | 24,906 |
def second_deriv_log_pdf(phi, alpha, beta, eps=1e-4):
"""Second derivative of `log_pdf` with respect to latitude."""
return (
log_pdf(phi + eps, alpha, beta)
- 2 * log_pdf(phi, alpha, beta)
+ log_pdf(phi - eps, alpha, beta)
) / eps ** 2 | 24,907 |
def create_map(
tag: Optional[str],
func: Callable,
args_and_kwargs: Iterator[ARGS_AND_KWARGS],
map_options: Optional[options.MapOptions] = None,
) -> maps.Map:
"""
All map calls lead here.
This function performs various checks on the ``tag``,
constructs a submit object that represents t... | 24,908 |
def _fallback_schedule(cfg, wkl):
"""
Get default schedule for the workload
Parameters
----------
cfg : tvm.autotvm.task.space.FallbackConfigEntity
Fallback config to be updated
wkl : topi.nn.depthwise_conv2d.Workload
Convolution workload
"""
simd_width = get_fp32_len()
... | 24,909 |
def normalize_data(data, zp=25., zpsys='ab'):
"""Return a copy of the data with all flux and fluxerr values normalized
to the given zeropoint. Assumes data has already been standardized.
Parameters
----------
data : `~numpy.ndarray`
Structured array.
zp : float
zpsys : str
Retu... | 24,910 |
def CreateMessage(sender, to, subject, message_text):
"""
Creates an object containing a base64url encoded email object.
"""
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
raw_message = base64.urlsafe_b64encode(message.as_bytes())
raw_message ... | 24,911 |
def bg_lookup(bg_name: str) -> str:
"""Look up ANSI escape codes based on background color name.
:param bg_name: background color name to look up ANSI escape code(s) for
:return: ANSI escape code(s) associated with this color
:raises ValueError if the color cannot be found
"""
try:
ansi... | 24,912 |
def readData(f):
"""
Parse taxon count table (from count-taxon.py)
Parameters:
-----------
f : str
file name of taxon count table
Returns:
--------
tuple
a list of taxons and a list of their counts
"""
taxa_lis = []
num_lis = []
for n, line in enumerate... | 24,913 |
def workspace_check(func):
"""
Decorator for confirming <workspace> is defined in the CONFIG_PATH (i.e. kaos workspace set has been run).
"""
def wrapper(*args, **kwargs):
config = ConfigParser(interpolation=ExtendedInterpolation())
config.read(CONFIG_PATH)
if 'pachyderm' not i... | 24,914 |
def test_persistent_group_add_cli_chan(dev):
"""P2P persistent group formation and re-invocation with p2p_add_cli_chan=1"""
dev[0].request("SET p2p_add_cli_chan 1")
dev[1].request("SET p2p_add_cli_chan 1")
form(dev[0], dev[1])
dev[1].request("BSS_FLUSH 0")
dev[1].scan(freq="2412", only_new=True)... | 24,915 |
def detect_onsets_offsets(data, threshold, min_distance):
"""
detects when a when a signal jumps above zero, and when it goes back to zero
"""
on = (data > threshold) # when the data is greater than zero
left_on = np.concatenate(([0], on), axis=0)[0:-1]
onset = np.squeeze(np.where(on & (left_on... | 24,916 |
def main():
""" Script entry point. """
parser = argparse.ArgumentParser(description='This tool analyzes CPU\
utilization and platform metrics\
collected from eris agent and build data\
model for conte... | 24,917 |
def STEPConstruct_PointHasher_IsEqual(*args):
"""
* Returns True when the two keys are the same. Two same keys must have the same hashcode, the contrary is not necessary.
:param Point1:
:type Point1: gp_Pnt
:param Point2:
:type Point2: gp_Pnt
:rtype: bool
"""
return _STEPConstruct.STEP... | 24,918 |
def step_smooth(x) :
""" Smooth polinomial rising step from 0(x=0) to 1(x=1)
"""
return np.select([x>1, x>0], [1, 3*np.square(x)-2*np.power(x,3)], default=0) | 24,919 |
def getBitSizeOfVarInt64(value):
"""
Gets bit size of variable 64-bit signed integer value.
:param value: Value to use for bit size calculation.
:returns: Bit size of the value.
"""
return _getBitSizeOfVarIntImpl(value, VARINT64_MAX_VALUES, signed=True) | 24,920 |
def bf_add_node_role_dimension(dimension):
# type: (NodeRoleDimension) -> None
"""
Adds another role dimension to the active network.
Individual roles within the dimension must have a valid (java) regex.
The node list within those roles, if present, is ignored by the server.
:param dimension: ... | 24,921 |
def nan_if_exception(func):
"""Wrap func such that np.nan is returned if func raises an exception.
KeyboardInterrupt and SystemExit are still raised.
Examples:
>>> @nan_if_exception
... def f(x, y):
... assert x + y >= 5
>>> f(1, 2)
nan
>>> def f(x, y):
... assert x +... | 24,922 |
def func3():
"""
##### Get by name – in a <b>dataset</b>
""" | 24,923 |
def main():
"""Start Flower client
Use first argument passed as workspace name
"""
workspace_name = sys.argv[1]
workspace = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "workspaces", workspace_name
)
fl.client.start_numpy_client(
"0.0.0.0:8080", client=MLCubeC... | 24,924 |
def get_client_public_key(patient_id, study_id):
"""Grabs a user's public key file from s3."""
key_pair_paths = construct_s3_key_paths(study_id, patient_id)
key = s3_retrieve(key_pair_paths['public'], study_id, raw_path=True)
return encryption.import_RSA_key( key ) | 24,925 |
def plot_offset_direction(
dsaimage: Image, coords: SkyCoord, ra_offsets: List[float], dec_offsets: List[float]
) -> Tuple["matplotlib.fig", "matplotlib.axes.Axes"]:
"""Plot measured offsets on an image."""
fig, ax = dsaimage.show()
dsaimage.add_arrows(coords, ra_offsets, dec_offsets)
return fig... | 24,926 |
def get_file_path(mdir=None) -> str:
"""
makes user select a file using a TUI. `mdir` is the main starting directory which defaults to current
working directory.
.. note::
This clears screen a lot of times and might make your app ugly but
provides user with a easy way to choose files.
... | 24,927 |
def sensitivity_metric(event_id_1, event_id_2):
"""Determine similarity between two epochs, given their event ids."""
if event_id_1 == 1 and event_id_2 == 1:
return 0 # Completely similar
if event_id_1 == 2 and event_id_2 == 2:
return 0.5 # Somewhat similar
elif event_id_1 == 1 and eve... | 24,928 |
def duracion_promedio_peliculas(p1: dict, p2: dict, p3: dict, p4: dict, p5: dict) -> str:
"""Calcula la duracion promedio de las peliculas que entran por parametro.
Esto es, la duración total de todas las peliculas dividida sobre el numero de peliculas.
Retorna la duracion promedio en una cadena de ... | 24,929 |
def _to_test_data(text):
"""
Lines should be of this format: <word> <normal_form> <tag>.
Lines that starts with "#" and blank lines are skipped.
"""
return [l.split(None, 2) for l in text.splitlines()
if l.strip() and not l.startswith("#")] | 24,930 |
def append(motion1, motion2):
"""
Combines two motion sequences into one. motion2 is appended to motion1.
The operation is not done in place.
Note that the operation places the sequences next to each other without
attempting to blend between the poses. To interpolate between the end of
motion1 ... | 24,931 |
def service(
fmt: SupportedFormats,
begints: datetime = Query(
..., description="Inclusive UTC timestamp window start for issuance."
),
endts: datetime = Query(
..., description="Exclusive UTC timestamp window end for issuance."
),
wfo: List[str] = Query(
None, descriptio... | 24,932 |
def cols_shuffled(expr_df, dist_df=None, algo="agno", seed=0):
""" Return a copy of the expr_df DataFrame with columns shuffled randomly.
:param pandas.DataFrame expr_df: the DataFrame to copy and shuffle
:param pandas.DataFrame dist_df: the distance DataFrame to inform us about distances between columns
... | 24,933 |
def verify(origin_dir, real_width, real_height, image_suffix):
"""
Verifique o tamanho da imagem
:return:
"""
if not os.path.exists(origin_dir):
print("[Aviso] O diretório {} não pode ser encontrado, ele será criado em breve".format(origin_dir))
os.makedirs(origin_dir)
print("Co... | 24,934 |
def build_model(task_description: Dict[str, Any]) -> Dict[str, Any]:
"""Build the predinet model."""
# ---------------------------
# Setup and process inputs
processors = {"image": process_image, "task_id": process_task_id}
mlp_inputs = utils.factory.create_input_layers(task_description, processors)... | 24,935 |
def create_unet_model(N_classes, input_shape=(None, None, 1), dropout_rate=0.24, learning_rate=1e-5):
"""
Implementation of Unet mode for multiclass semantic segmentation
:param N_classes: Number of classes of segmentation map
:param input_shape: input image shape
:param dropout_rate: dropout rate
... | 24,936 |
def extension(name: str, compile_args=(), link_args=(), include_dirs=(),
libraries=(), language='c++', **kwargs):
"""Build standard Cython extension."""
path = os.path.sep.join(['src', *name.split('.')]) + '.pyx'
include_dirs = ['include', *include_dirs]
return Extension(name,
... | 24,937 |
def load_ipython_extension(ipython):
"""call by ipython"""
from rqalpha.__main__ import inject_mod_commands
inject_mod_commands()
ipython.register_magic_function(run_ipython_cell, 'line_cell', 'rqalpha') | 24,938 |
def push_changes():
"""Pushes commit.
"""
set_url = f'git remote set-url origin https://x-access-token:{GITHUB_TOKEN}@github.com/{TARGET_REPOSITORY}'
git_push = f'git push origin {TARGET_BRANCH}'
sp.check_call(split(set_url))
sp.check_call(split(git_push)) | 24,939 |
def get_5cnn_model(image_size: int = 84,
bn_eps: float = 1e-3,
bn_momentum: float = 0.95,
n_classes: int = 5,
filter_size: int = 32,
levels: Optional = None,
spp: bool = False) -> nn.Module:
"""
Get... | 24,940 |
def valid_extract_input_specification(instance_of_property, depth, language_code, named_entity_label):
""" Checks if the input for the extraction is valid. Both to help
the user get correct input and to sanitize it to avoid
attacks as the values are used to generate filenames.
"""
patte... | 24,941 |
def get_company_data(mid):
"""Looks up stock ticker information for a company via its Freebase ID."""
query = MID_TO_TICKER_QUERY % mid
bindings = make_wikidata_request(query)
if not bindings:
if mid:
print("%s No company data found for MID: %s" % (WARNING, mid))
return Non... | 24,942 |
def helper_promote_field_values_watch_public(handle, gpuIds):
"""
Verifies that dcgm can update a field value watch
"""
fieldId = dcgm_fields.DCGM_FI_DEV_NAME
fieldIds = [fieldId, ]
handleObj = pydcgm.DcgmHandle(handle=handle)
systemObj = handleObj.GetSystem()
groupObj = systemObj.G... | 24,943 |
def ShowPortSendRights(cmd_args=[], cmd_options={}):
""" Display a list of send rights across all tasks for a given port.
Usage: (lldb) showportsendrights <ipc_port_t>
"""
if not cmd_args:
raise ArgumentError("no port address provided")
port = kern.GetValueFromAddress(cmd_args[0], 'struc... | 24,944 |
def embed_data_into_square_lattice(data):
"""Insert MR image into square 2D array."""
dims = np.array(data.shape)
offset_x = int((dims.max() - dims[0]) / 2.)
offset_y = int((dims.max() - dims[1]) / 2.)
temp = np.zeros((dims.max(), dims.max()))
temp[offset_x:offset_x+dims[0], offset_y:offset_y+... | 24,945 |
def is_partial_link_text_selector(selector):
"""
A basic method to determine if a selector is a partial link text selector.
"""
if (
selector.startswith("partial_link=")
or selector.startswith("partial_link_text=")
or selector.startswith("partial_text=")
or selector.start... | 24,946 |
def test_get_virtual_points_vector():
"""
Here, we test that when :math:`v_1 = v_2 = 0`, the virtual points
:math:`x'` are in fact points between :math:`-R_0\sin(\omega T/2)`
and :math:`-R_0\sin(\omega T/2)`
"""
x_prime = DCC.get_virtual_points_vector(0, 0)
omega = p.omega / 360... | 24,947 |
def scell(obj, dims, method=1, **kwds):
"""Build supercell based on `dims`.
Uses coords_frac and cell.
Parameters
----------
obj : Structure or Trajectory
dims : tuple (nx, ny, nz) for a N = nx * ny * nz supercell
method : int, optional
Switch between numpy-ish (1) or loop (2) impl... | 24,948 |
def create_config(device: str = 'CPU', *,
per_process_gpu_memory_fraction: float = 0.0,
log_device_placement: bool = False) -> tf.ConfigProto:
"""Creates tf.ConfigProto for specifi device"""
config = tf.ConfigProto(log_device_placement=log_device_placement)
if is_gpu(devi... | 24,949 |
def dump_feat_name(feat_names, feat_name_file):
"""
save feat_names to feat_name_file
"""
with open(feat_name_file, "wb") as f:
for i,feat_name in enumerate(feat_names):
if feat_name.startswith("count") or feat_name.startswith("pos_of"):
f.write("('%s', SimpleTransform(config.count_feat_... | 24,950 |
def format_childproc(cp: Union[Event, Dict]):
"""Format childproc event into single line."""
return f" @{as_configured_timezone(cp.get('event_timestamp'))}: {cp.get('childproc_cmdline')} - {cp.get('childproc_process_guid')}" | 24,951 |
def create_not_mnist_doubleset() -> (list, list):
"""
A function which iterates through notMNIST images and sorts into two lists of images and arrays.
:return x: images as ndarrays
:return y: labels of images
"""
try:
with np.load("./notMNIST_all/all_data.npz") as f:
x, y = f... | 24,952 |
def format_maven_jar_dep_name(group_id, artifact_id, repository = DEFAULT_REPOSITORY_NAME):
"""
group_id: str
artifact_id: str
repository: str = "maven"
"""
return "@%s//:%s" % (repository, format_maven_jar_name(group_id, artifact_id)) | 24,953 |
def PCO_GetCameraName(handle):
"""
This function retrieves the name of the camera.
"""
f = pixelfly_dll.PCO_GetCameraName
f.argtypes = (ctypes.wintypes.HANDLE, ctypes.c_char_p, ctypes.wintypes.WORD)
f.restype = ctypes.c_int
cameraName = ctypes.create_string_buffer(41)
ret_code = f(handl... | 24,954 |
def import_object(absolute_name):
"""
根据名字 import 对象
:param absolute_name: 按照 module:name 的格式
:return: 返回对应对象
"""
try:
module_name, obj_name = absolute_name.split(':')
module = sys.modules.get(module_name, None)
if not module:
module = import_module(module_nam... | 24,955 |
def issingleton(var):
""" If isunitset(var) is True, this function returns True,
otherwise isscalar(var) is returned.
"""
# Here we define singleton as a unit set or scalar
if isunitset(var):
return True
return isscalar(var) | 24,956 |
def satisfiesF(L):
"""
Assumes L is a list of strings
Assume function f is already defined for you and it maps a string to a Boolean
Mutates L such that it contains all of the strings, s, originally in L such
that f(s) returns True, and no other elements. Remaining elements in L
... | 24,957 |
def calc_circle_radius(area: float) -> float:
"""
Calculate radius from area.
>>> calc_circle_radius(10.0)
1.7841241161527712
"""
assert not area < 0
radius = numpy_to_python_type(np.sqrt(area / np.pi))
assert isinstance(radius, float)
return radius | 24,958 |
def load_imgs(paths, target_size):
"""Load images from `paths`."""
pairs = np.empty((len(paths), 2, *target_size), dtype=np.float32)
for i, row in tqdm(paths.iterrows(), total=len(pairs)):
img1 = img_to_array(load_img(row.p1, target_size=target_size)) / 255
img2 = img_to_array(load_img(row.p... | 24,959 |
async def test_handle_pubsub_msg_old(mocker, monkeypatch, consumer,
publish_time, raw_msg_data,
creation_audit_log_data,
caplog, pubsub_msg, mock_get_and_validate,
mock_cre... | 24,960 |
def load_dict_from_hdf5(h5_filepath):
"""
Load h5 file as a dict
"""
def recursively_load_dict_contents_from_group(h5_obj, path):
"""
Recursively load a dict from h5 file
"""
ans = {}
for key, item in h5_obj[path].items():
if isinstance(item, h5py._hl.... | 24,961 |
def interactive_grid_shape(grid, max_n=200, plotfxn=None, **kwargs):
""" Interactive ipywidgets for select the shape of a grid
Parameters
----------
grid : pygridgen.Gridgen
The base grid from which the grids of new shapes (resolutions) will be
generated.
max_n : int (default = 200)... | 24,962 |
def test_create_test_result_throws_exception():
"""Test that unknown status strings should result in exception.
"""
with pytest.raises(ValueError):
Test.Result.create("unknown_result") | 24,963 |
def generate_initial_state(initial_pos: Transform, initial_speed: Optional[float] = None) -> AgentState:
"""
:param initial_speed: Initial speed in km/h
"""
from lgsvl.utils import transform_to_forward
movement = AgentState()
movement.transform = initial_pos
if initial_speed is not None:
... | 24,964 |
def resolve_ami(ami=None, arch="x86_64", tags=frozenset(), tag_keys=frozenset()):
"""
Find an AMI by ID, name, or tags.
- If an ID is given, it is returned with no validation; otherwise, selects the most recent AMI from:
- All available AMIs in this account with the Owner tag equal to this user's IAM us... | 24,965 |
def _MigrateTestLookupPatterns(old_pattern, new_pattern):
"""Enumerates individual test migration tasks and enqueues them.
Typically, this function is called by a request initiated by the user.
The purpose of this function is to queue up a set of requests which will
do all of the actual work.
Args:
old_... | 24,966 |
def _filter_colors(hcl, ihue, nhues, minsat):
"""
Filter colors into categories.
Parameters
----------
hcl : tuple
The data.
ihue : int
The hue column.
nhues : int
The total number of hues.
minsat : float
The minimum saturation used for the "grays" column... | 24,967 |
def add_file(conn: apsw.Connection, **file_info: Any) -> None:
"""Adds a FileInfo row to the database, with some default values.
Args:
conn: The database to modify.
file_info: A mapping from column names to binding values.
"""
data = dict(updated_at=0, file_index=0, id=111)
data.upd... | 24,968 |
def test_convert(fx_asset):
"""Converts the image format."""
with Image(filename=str(fx_asset.join('mona-lisa.jpg'))) as img:
with img.convert('png') as converted:
assert converted.format == 'PNG'
strio = io.BytesIO()
converted.save(file=strio)
strio.seek(... | 24,969 |
def SWO(
directed = False, preprocess = "auto", load_nodes = True, load_node_types = True,
load_edge_weights = True, auto_enable_tradeoffs = True,
sort_tmp_dir = None, verbose = 2, cache = True, cache_path = None,
cache_sys_var = "GRAPH_CACHE_DIR", version = "swo.owl", **kwargs
) -> Graph:
"""Return... | 24,970 |
def upload_needed_files (handle, bucket, prefix, dir_path, kind, iter):
"""
upload the needed local files of a particular kind
"""
extension = f".{kind}"
count = 0
for uuid in iter:
file_name = uuid + extension
local_path = dir_path / file_name
grid_path = prefix + "/pub... | 24,971 |
def detect_tag(filename):
"""Return type and position of ID3v2 tag in filename.
Returns (tag_class, offset, length), where tag_class
is either Tag22, Tag23, or Tag24, and (offset, length)
is the position of the tag in the file.
"""
with fileutil.opened(filename, "rb") as file:
file.seek(... | 24,972 |
def plot_function_interpolations(function, support_points, interpolations, bases):
""" Plot a grid with the given function, the support points, interpolation and bases in each plot. """
x_f, y_f = function
fig1 = plt.figure()
for i in range(len(support_points)):
x_s, y_s = support_points[i]
... | 24,973 |
def merge_peaks(peaks, start_merge_at, end_merge_at,
max_buffer=int(1e5)):
"""Merge specified peaks with their neighbors, return merged peaks
:param peaks: Record array of strax peak dtype.
:param start_merge_at: Indices to start merge at
:param end_merge_at: EXCLUSIVE indices to end me... | 24,974 |
def batchedpatternsgenerator(generatorfunction):
"""Decorator that assumes patterns (X,y) and stacks them in batches
This can be thought of a specialized version of the batchedgenerator
that assumes the base generator returns instances of data patterns,
as tuples of numpy arrays (X,y). When groupin... | 24,975 |
def reduce_min(raw_tensor, axis, keepdims=False):
"""
calculate reduce_min of raw_tensor, only support float16
Args:
raw_tensor (tvm.tensor.Tensor): input tensor
axis (Union[int, list]): reduce axis (range : [-len(raw_tensor.shape), len(raw_tensor.shape) - 1])
keepdims (bool): if tr... | 24,976 |
def align2local(seq):
"""
Returns list such that
'ATG---CTG-CG' ==> [0,1,2,2,2,3,4,5,5,6,7]
Used to go from align -> local space
"""
i = -1
lookup = []
for c in seq:
if c != "-":
i += 1
lookup.append(i)
return lookup | 24,977 |
def load_nodegraph(filename):
"""Load a nodegraph object from the given filename and return it.
Keyword argument:
filename -- the name of the nodegraph file
"""
nodegraph = _Nodegraph(1, [1])
nodegraph.load(filename)
return nodegraph | 24,978 |
def get_bprop_sqrt(self):
"""Grad definition for `Sqrt` operation."""
mul_func = P.Mul()
fill_func = P.Fill()
div_op = P.RealDiv()
sqrt = P.Sqrt()
dtype = P.DType()
def bprop(x, out, dout):
temp = div_op(fill_func(dtype(x), shape_op(x), 0.5), sqrt(x))
dx = mul_func(dout, tem... | 24,979 |
def hit_or_stand(deck, hand):
"""
Function prompting the Player to Hit or Stand.
This function should accept the deck and the player's hand as arguments,
and assign playing as a global variable.
:param deck:
:param hand:
:return:
"""
global playing # to control an upcoming ... | 24,980 |
def classify_top1_batch(image):
"""Define method `classify_top1` for servable `resnet50`.
The input is `image` and the output is `lable`."""
x = register.add_stage(preprocess_batch, image, outputs_count=1, batch_size=1024)
x = register.add_stage(resnet_model, x, outputs_count=1)
x = register.add_st... | 24,981 |
def notify_post_delete_order_adviser(sender, instance, **kwargs):
"""
Notify people that they have been removed from the order.
Note that `instance` is no longer in the database at this point,
so be very careful what you do with it.
"""
transaction.on_commit(
partial(notify.adviser_remo... | 24,982 |
def ngram_word(max_features=2_000):
"""Word count vectorizer.
Args:
max_features: number of features to consider.
"""
return CountVectorizer(
ngram_range=(1, 3),
analyzer='word',
max_features=max_features,
) | 24,983 |
def func_dispatcher(intent):
"""
Simple effect dispatcher that takes callables taking a box,
and calls them with the given box.
"""
def performer(dispatcher, intent, box):
intent(box)
return performer | 24,984 |
def get_system_path():
""" Get the system path as a list of files
Returns:
List of names in the system path
"""
path = os.getenv('PATH')
if path:
return path.split(os.pathsep)
return [] | 24,985 |
def streaming_stage_current_consumption_test():
"""
:return:
"""
local_file_name = 'streaming_stage_curr.csv'
common.sm.setup_battery_mode()
# ***** Starting ECG, ADXL and PPG stream ******
common.watch_shell.quick_start('ecg', 'ecg')
common.watch_shell.quick_start('adxl', 'adxl')
#... | 24,986 |
def encode(x, bps_arrangement='random', n_bps_points=512, radius=1.5, bps_cell_type='dists',
verbose=1, random_seed=13, x_features=None, custom_basis=None, n_jobs=-1):
"""Converts point clouds to basis point set (BPS) representation, multi-processing version
Parameters
----------
x: numpy ar... | 24,987 |
def parsec_params_list_to_dict(var):
"""
convert parsec parameter array to dictionary
:param var:
:return:
"""
parsec_params = dict()
parsec_params["rle"] = var[0]
parsec_params["x_pre"] = var[1]
parsec_params["y_pre"] = var[2]
parsec_params["d2ydx2_pre"] = var[3]
parsec_para... | 24,988 |
def parse_msiinfo_suminfo_output(output_string):
"""
Return a dictionary containing information from the output of `msiinfo suminfo`
"""
# Split lines by newline and place lines into a list
output_list = output_string.splitlines()
results = {}
# Partition lines by the leftmost ":", use the s... | 24,989 |
def create_indicators_fields(tag_details: Dict[str, Any]) -> Dict[str, Any]:
"""
Returns the indicator fields
Args:
tag_details: a dictionary containing the tag details.
Returns:
A dictionary represents the indicator fields.
"""
fields: Dict[str, Any] = {}
tag = tag_details.... | 24,990 |
def wait_until_edit_or_exit(filename, modified_time, process, sleep_time=0.1):
"""Wait until a file is edited or a process exits.
Positional arguments:
filename: The path to the file to check.
modified_time: The last modified time against which to check.
process: The process whose termi... | 24,991 |
def spatial_difference(gdf1: GeoDataFrame, gdf2: GeoDataFrame) -> GeoDataFrame:
"""Removes polygons from the first GeoDataFrame that intersect with polygons from the second GeoDataFrame
:param gdf1: First input data frame
:param gdf2: Second input data frame
:return: Resulting data frame
"""
gd... | 24,992 |
def frustumShellIxx(rb, rt, t, h, diamFlag=False):
"""This function returns a frustum's mass-moment of inertia (divided by density) about the
transverse x/y-axis passing through the center of mass with radii or diameter inputs.
NOTE: This is for a frustum SHELL, not a solid
INPUTS:
Parameters
... | 24,993 |
def default_shaders():
"""
Returns a list with all thte default shadres of the current DCC
:return: str
"""
return shader_utils.get_default_shaders() | 24,994 |
def get_domains_and_slugs():
"""
returns all the domain names and slugs as dictionary
{domain_name: slug}
"""
return_data = {}
domain_slugs = Domain.objects.filter(active=1).order_by('name')
if domain_slugs:
for domain in domain_slugs:
return_data[domain.name] = domain.sl... | 24,995 |
def has_video_ads() -> bool:
"""has_video_ads() -> bool
(internal)
"""
return bool() | 24,996 |
def _split_words_with_boundaries(
string: str, word_boundaries: Container[str]
) -> Iterator[str]:
"""
Split a string around given separators, conserving the separators.
>>> list(_split_words_with_boundaries("ab cd -ef_gh", " -_"))
['ab', ' ', 'cd', ' ', '-', 'ef', '_', 'gh']
"""
stack = []... | 24,997 |
def calculate_purchasing_plan(total_days, sellers, starting_bread=10, best_before_date=30, debug = False):
"""
total_days : positive int
sellers : list of tuple (day, price)
starting_bread : int, optional
best_before_date : positive int, (how long the bread lasts)
debug : boolean, (prints cost m... | 24,998 |
def compile_sites(inp: NetInput,
y_true: Iterable[np.ndarray],
y_pred: Iterable[np.ndarray],
masks: Iterable[np.ndarray]):
"""
Prepares sites to be dumped in tsv file
:param inp: NetInput
:param y_true: True known classes mapped on templates
:par... | 24,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.