content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def straightenImage(im, imextent, mvx=1, mvy=None, verbose=0, interpolation=cv2_interpolation):
""" Scale image to make square pixels
Arguments
---------
im: array
input image
imextend: list of 4 floats
coordinates of image region (x0, x1, y0, y1)
mvx, mvy : float
number... | 8,300 |
def H(r2, H_s, H_d, a_s, a_d, gamma_s, gamma_d, G, v):
"""
"""
pi = math.pi
sqrt = math.sqrt
r = sqrt(r2)
H2_s = H_s**2
H2_d = H_d**2
R2_s = r2 + H2_s
R2_d = r2 + H2_d
alpha_s = 1.0 if gamma_s == 1.0 else 4 * H2_s / (pi*R2_s)
alpha_d = 1.0 if gamma_d == 1.0 else 4 * H2_d ... | 8,301 |
def refine_resolution(src_tif_path, dst_tif_path, dst_resolution, resample_alg='near'):
"""
near: nearest neighbour resampling (default, fastest algorithm, worst interpolation quality).
bilinear: bilinear resampling.
cubic: cubic resampling.
cubicspline: cubic spline resampling.
lanczos: Lanczos... | 8,302 |
def test_mystery_3b_4() -> None:
"""Test mystery_3b for an expected return value of 4."""
expected = 4
actual = mystery_3b(-1, 0, -1)
assert actual == expected | 8,303 |
def parse_time(event_time):
"""Take a string representation of time from the blockchain, and parse it into datetime object."""
return datetime.strptime(event_time, '%Y-%m-%dT%H:%M:%S') | 8,304 |
def do_pdftk_cat_first_page(pdf_file):
"""The cmd_args magick identify is very slow on page pages hence it
examines every page. We extract the first page to get some informations
about the dimensions of the PDF file."""
output_file = os.path.join(tmp_dir, 'identify.pdf')
cmd_args = ['pdftk', str(pdf... | 8,305 |
def addBenchmark(df):
"""Add benchmark to df."""
# Compute the inverse of the distance
distance_inv = (1. / df.filter(regex='^distance*', axis=1)).values
# Extract the value at the nearest station
values = df.filter(regex='value_*', axis=1)
# Compute the benchmark
numer = (distance_inv * ... | 8,306 |
def is_file_like(f):
"""Check to see if ```f``` has a ```read()``` method."""
return hasattr(f, 'read') and callable(f.read) | 8,307 |
def before_trading_start(context, data):
"""
Called every day before market open. This is where we get our stocks that made it through the pipeline.
"""
#pipeline_output returns a pandas dataframe that has columns for each factor we added to the pipeline, using pipe.add(), and has a row for each... | 8,308 |
def _string_to_days_since_date(dateStrings, referenceDate='0001-01-01'):
"""
Turn an array-like of date strings into the number of days since the
reference date
"""
dates = [_string_to_datetime(string) for string in dateStrings]
days = _datetime_to_days(dates, referenceDate=referenceDate)
... | 8,309 |
def safe_as_int(val, atol=1e-3):
"""
Attempt to safely cast values to integer format.
Parameters
----------
val : scalar or iterable of scalars
Number or container of numbers which are intended to be interpreted as
integers, e.g., for indexing purposes, but which may not carry integ... | 8,310 |
def check_protocol(protocol):
"""
Check if a given protocol works by computing the qubit excitation probabilities
"""
qubit_weight = {}
qubit_weight[protocol[0][0][0]] = 1.0
for pair_set in protocol:
for i, j, p in pair_set:
qubit_weight[j] = qubit_weight[i] * (1.0 - p)
... | 8,311 |
def detachVolume(**kargs):
""" detachVolume your Additional Volume
* Args:
- zone(String, Required) : [KR-CA, KR-CB, KR-M, KR-M2]
- id(String, Required) : Volume disk ID
* Examples : print(server.detachVolume(zone='KR-M', id='7f933f86-e8bf-4600-9423-09e8f1c84460'))
"""
my_... | 8,312 |
def observe(metric: str,
accept_on: List[Type[Exception]] = [], # pylint: disable=E1136
decline_on: List[Type[Exception]] = [], # pylint: disable=E1136
static_tags: List[str] = [], # pylint: disable=E1136
tags_from: Optional[Dict[str, List[str]]] = None, # pylint: dis... | 8,313 |
def action_load_more_reviews(move_down=False):
"""Load more reviews."""
print 'loading more requests.'
interface = get_interface(_rboard_url)
review_requests = interface.get_review_requests(current_lineval())
current_buffer = vim.current.buffer
for review_request in review_requests:
chan... | 8,314 |
def append_subdirs_to_mypy_paths(root_directory: str) -> str:
"""
Appends all immediate sudirs of the root_directory to the MYPYPATH , separated by column ':' TODO: Windows ?
in order to be able to use that in a shellscript (because the ENV of the subshell gets lost)
we also return it as a string. This ... | 8,315 |
def test__upsert_service_info_insert():
"""Test for creating service info document in database."""
app = Flask(__name__)
app.config['FOCA'] = Config(
db=MongoConfig(**MONGO_CONFIG),
endpoints=ENDPOINT_CONFIG,
)
app.config['FOCA'].db.dbs['drsStore'].collections['service_info'] \
... | 8,316 |
def spherical_to_cartesian(lons, lats, depths):
"""
Return the position vectors (in Cartesian coordinates) of list of spherical
coordinates.
For equations see: http://mathworld.wolfram.com/SphericalCoordinates.html.
Parameters are components of spherical coordinates in a form of scalars,
lists... | 8,317 |
def get_remote_webdriver(hub_url, browser, browser_ver, test_name):
"""
This functions returns remote web-driver instance created in selenoid
machine.
:param hub_url
:param browser: browser name
:param browser_ver: version for browser
:param test_name: test name
:return: remote web-drive... | 8,318 |
def process_images(rel_root_path, item_type, item_ids, skip_test, split_attr,
gen_image_specs_func, trafo_image_func,
trafo_image_extra_kwargs=None, img_obj_type=None,
img_attr=None, dimensions=(256, 256),
max_valset_size=10000):
"""
Th... | 8,319 |
def evaluate(config: Config) -> typing.Dict[str, float]:
"""
Load and evaluate model on a list generator
Return:
dict of metrics for the model run
"""
logger.info('Running evaluation process...')
net_name = config.net_name
pp_dir = config.paths['preprocess_dir']
pr_dir = config... | 8,320 |
def get_transform_dict(args, strong_aug: Callable):
"""
Generates dictionary with transforms for all datasets
Parameters
----------
args: argparse.Namespace
Namespace object that contains all command line arguments with their corresponding values
strong_aug: Callable
Callable ob... | 8,321 |
def choose_first_not_none(*args):
""" Choose first non None alternative in args.
:param args: alternative list
:return: the first non None alternative.
"""
for a in args:
if a is not None:
return a
return None | 8,322 |
def _format_compact(value, short=True):
"""Compact number formatting using proper suffixes based on magnitude.
Compact number formatting has slightly idiosyncratic behavior mainly due to
two rules. First, if the value is below 1000, the formatting should just be a
2 digit decimal formatting. Second, the number... | 8,323 |
def matrix(mat,nrow=1,ncol=1,byrow=False):
"""Given a two dimensional array, write the array in a matrix form"""
nr=len(mat)
rscript='m<-matrix(data=c('
try:
nc=len(mat[0])
for m in mat:
rscript+=str(m)[1:-1]+ ', '
rscript=rscript[:-2]+'), nrow=%d, ncol=%d, by... | 8,324 |
async def test_create_event_invalid_date(
client: _TestClient, mocker: MockFixture, token: MockFixture, event: dict
) -> None:
"""Should return 400 Bad request."""
ID = "290e70d5-0933-4af0-bb53-1d705ba7eb95"
mocker.patch(
"event_service.services.events_service.create_id",
return_value=ID... | 8,325 |
def all(x, axis=None, keepdims=False):
"""Bitwise reduction (logical AND).
"""
return T.all(x, axis=axis, keepdims=keepdims) | 8,326 |
def config_find_permitted(cookie, dn, in_class_id, in_filter, in_hierarchical=YesOrNo.FALSE):
""" Auto-generated UCS XML API Method. """
method = ExternalMethod("ConfigFindPermitted")
method.cookie = cookie
method.dn = dn
method.in_class_id = in_class_id
method.in_filter = in_filter
method.... | 8,327 |
def reformat_medication_statuses(data: FilteredData) -> FilteredData:
"""
Reformats medication statuses to binary indicators.
Args:
data: The data containing medication statuses to reformat.
Returns:
Data with reformatted medication statuses.
"""
for j in data.medications.colu... | 8,328 |
def segmentwidget(img, params=None, alg=None):
"""Generate GUI. Produce slider for each parameter for the current segmentor.
Show both options for the masked image.
Keyword arguments:
img -- original image
gmask -- ground truth segmentation mask for the image
params -- list of parameter o... | 8,329 |
def list_daemons(dut):
"""Get daemon table from ovsdb-server."""
daemon_list = {}
c = ovs_vsctl + "--format json list daemon"
out = dut(c, shell="bash")
json_out = json.loads(out)['data']
# The output is in the following format
# [["uuid","19b943b0-096c-4d7c-bc0c-5b6ac2f83014"],0,true,"ops-... | 8,330 |
def Cleanse(obj, encoding="utf-8"):
"""Makes Python object appropriate for JSON serialization.
- Replaces instances of Infinity/-Infinity/NaN with strings.
- Turns byte strings into unicode strings.
- Turns sets into sorted lists.
- Turns tuples into lists.
Args:
obj: Python data structu... | 8,331 |
def wait_no_exception(lfunction, exc_class=None, exc_matcher=None):
"""Stops waiting on success."""
start_time = time.time()
if exc_matcher is not None:
exc_class = boto.exception.BotoServerError
if exc_class is None:
exc_class = BaseException
while True:
result = None
... | 8,332 |
def testapp(app, init_database):
"""Create Webtest app."""
testapp = TestApp(app)
#testapp = TestApp(app, extra_environ=dict(REMOTE_USE='test'))
# testapp.set_authorization(('Basic', (app.config['USERNAME'],app.config['PASSWORD'])))
# testapp.get_authorization()
return testapp | 8,333 |
def dois(self, key, value):
"""Translates dois fields."""
_identifiers = self.get("identifiers", [])
for v in force_list(value):
material = mapping(
MATERIALS,
clean_val("q", v, str, transform="lower"),
raise_exception=True,
)
doi = {
"... | 8,334 |
def transition(src,
dest,
state=None,
permissions=None,
required=None,
commit_record=True,
**kwargs):
"""Decorator that marks the wrapped function as a state transition.
:params parameters for transition object, see docum... | 8,335 |
def get_html(url):
"""Returns HTML object based on given Gumtree URL.
:param url: Offer URL.
:return: Offer HTML object.
"""
session = HTMLSession()
try:
r = session.get(url)
return r.html
except ParserError:
return None | 8,336 |
def test_default_skorecard_class(df):
"""Test a workflow, when no bucketer is defined."""
X = df.drop("default", axis=1)
y = df["default"]
features = ["LIMIT_BAL", "BILL_AMT1"]
skorecard_model = Skorecard(verbose=0, variables=features)
skorecard_model.fit(X, y)
assert isinstance(skorecard_m... | 8,337 |
def markovtalk_learn(text_line):
""" this is the function were a text line gets learned """
text_line = msg_to_array(text_line)
length = len(text_line)
order = [TOKEN, ] * ORDER_K
for i in range(length-1):
order.insert(0, text_line[i])
order = order[:ORDER_K]
next_word = text... | 8,338 |
def _get_lattice_parameters(lattice):
"""Return basis vector lengths
Parameters
----------
lattice : array_like
Basis vectors given as column vectors
shape=(3, 3), dtype='double'
Returns
-------
ndarray, shape=(3,), dtype='double'
"""
return np.array(np.sqrt(np.do... | 8,339 |
def save_batches(current_memory, id_tmp_dir, batch_num):
"""
batch_num : corresponds to the gradient update number
"""
target_csv = id_tmp_dir + "/batch" + str(batch_num) + ".csv"
obs_copy = deepcopy(current_memory['current_obs'])
reward_copy = deepcopy(current_memory['rewards'])
cur... | 8,340 |
def ikrvea_mm(
reference_point: np.ndarray,
individuals: np.ndarray,
objectives: np.ndarray,
uncertainity: np.ndarray,
problem: MOProblem,
u: int) -> float:
""" Selects the solutions that need to be reevaluated with the original functions.
This model management is based on the following ... | 8,341 |
def main():
"""
Call appropriate drawing functions depending on command-line arguments.
"""
data_path = os.path.dirname(args.measurement_filenames[0])
data_all_files = graph_common.read_latencies_files(
args.measurement_filenames)
if not args.no_histograms:
draw_histograms(data_... | 8,342 |
def pylint():
"""pyltin"""
sh("pylint ./pyfuzzy/") | 8,343 |
def homepage(request):
"""Main view of app.
We will display page with few step CTA links?
:param request: WSGIRequest instance
"""
if logged_as_admin(request):
offers = Offer.objects.get_for_administrator()
else:
offers = Offer.objects.get_weightened()
return render(
... | 8,344 |
def add_dict(dct1, dct2):
"""Returns a new dictionaries where the content of the dictionaries `dct1`
and `dct2` are merged together."""
result = dct1.copy()
result.update(dct2)
return result | 8,345 |
def _handle_cam_removal(serial):
""" Handles removing a camera """
print(serial + ' - removed')
# Remove cam stuff from dict
_SERIAL_DICT.pop(serial, None) | 8,346 |
def edit_temp(contents="", name=""):
"""
Create a temporary file and open it in the system's default editor for the
user to edit. The saved contents of the file will be returned when the
editor is closed.
:param contents: Pre-fill the file with the given text.
:param name: Ensure that the temp ... | 8,347 |
def _new_primitive_control(
rabi_rotation=None,
azimuthal_angle=0.,
maximum_rabi_rate=2. * np.pi,
**kwargs):
"""
Primitive driven control.
Parameters
----------
rabi_rotation : float, optional
The total rabi rotation to be performed by the driven control.
... | 8,348 |
def check_fit_params(
X: TwoDimArrayLikeType,
y: OneDimArrayLikeType,
sample_weight: Optional[OneDimArrayLikeType] = None,
estimator: Optional[BaseEstimator] = None,
**kwargs: Any
) -> Tuple[TwoDimArrayLikeType, OneDimArrayLikeType, OneDimArrayLikeType]:
"""Check `X`, `y` and `sample_weight`.
... | 8,349 |
async def example_quest(request: web.Request) -> web.Response:
"""
Example quest handler that handles a POST request with a computer science trivia question
:param request: The request object
"""
# Verify that it is a POST request, since that's what this quest is supposed to handle
if request.... | 8,350 |
def load_decrypt_bs_data(filepath, shape):
"""
load the encrypted data and reconstruct
"""
part_readers = []
for id in six.moves.range(3):
part_readers.append(mpc_du.load_shares(filepath, id=id, shape=shape))
mpc_share_reader = paddle.reader.compose(part_readers[0], part_readers[1], part... | 8,351 |
def generate_token_backend_conf(fout):
"""
Generate token backend
"""
with open('./conf_templates/token_backend.template') as fin:
template = ConfTemplate(fin.read())
print(template.substitute(options), file=fout) | 8,352 |
def view_api_image(image_type, catalog_name, source_id):
"""Source spectrum image."""
import matplotlib.pyplot as plt
catalog = source_catalogs[catalog_name]
source = catalog[source_id]
plt.style.use('fivethirtyeight')
if image_type == 'spectrum':
fig, ax = plt.subplots()
sour... | 8,353 |
def send_interface_connection_table(dispatcher, connections, filter_type, value):
"""Send request large table to Slack Channel."""
header = ["Device A", "Interface A", "Device B", "Interface B", "Connection Status"]
rows = [
(
add_asterisk(connection._termination_a_device, filter_type, v... | 8,354 |
def get_record_base_model(type_enum):
"""Return the dimension model class for a DimensionType."""
dim_model = _DIMENSION_TO_MODEL.get(type_enum)
if dim_model is None:
raise DSGInvalidDimension(f"no mapping for {type_enum}")
return dim_model | 8,355 |
def cmd(command):
"""
Run a command and return its stdout
"""
try:
completed = subprocess.run(
command.split(" "),
stdout=subprocess.PIPE,
)
except FileNotFoundError:
panic(f"Command `{command}` not found.")
if completed.returncode > 0:
panic(f"Command `{command}` returned ... | 8,356 |
def test_test_image():
"""Make sure our test image, face.jpg, is white on the edges"""
img = _get_test_img()
all = np.all(img[::, :10:] > 240, axis=2)
assert np.all(all) | 8,357 |
def copy_file(from_path, to_path):
"""
Copy file from one path to other, creating the target directory if not exists.
Arguments:
from_path : str
to_path : str
Returns:
None
"""
create_dir(os.path.dirname(to_path))
shutil.copyfile(from_path, to_path) | 8,358 |
def sas_to_pandas(sas_code, wrds_id, fpath):
"""Function that runs SAS code on WRDS or local server
and returns a Pandas data frame."""
p = get_process(sas_code, wrds_id, fpath)
if wrds_id:
df = pd.read_csv(StringIO(p.read().decode('utf-8')))
else:
df = pd.read_csv(StringIO(p.read(... | 8,359 |
def subprocess_run(*popenargs, input=None, timeout=None, check=False, **kwargs): # pylint: disable=redefined-builtin
"""Run command with arguments and return a CompletedProcess instance.
The returned instance will have attributes args, returncode, stdout and
stderr. By default, stdout and stderr are not ca... | 8,360 |
def _client_ip_address(request):
"""Return client ip address for flask `request`.
"""
if request.headers.getlist("X-PNG-Query-For"):
ip_addr = request.headers.getlist("X-PNG-Query-For")[0]
if ip_addr.startswith('::ffff:'):
ip_addr = ip_addr[7:]
elif request.headers.getlist("... | 8,361 |
def rollout_and_save(
path: str,
policy: AnyPolicy,
venv: VecEnv,
sample_until: GenTrajTerminationFn,
*,
unwrap: bool = True,
exclude_infos: bool = True,
verbose: bool = True,
**kwargs,
) -> None:
"""Generate policy rollouts and save them to a pickled list of trajectories.
T... | 8,362 |
def plot_marker(id_marker_ref, id_marker: int, ocp: OptimalControlProgram, nlp: list[NonLinearProgram]):
"""
plot the markers posiions
Parameters
----------
id_marker_ref: int
The marker's id hidden in the cost function
id_marker: int
The marker's id
ocp: OptimalControlPro... | 8,363 |
def create_bb_points(vehicle):
"""
Extract the eight vertices of the bounding box from the vehicle.
Parameters
----------
vehicle : opencda object
Opencda ObstacleVehicle that has attributes.
Returns
-------
bbx : np.ndarray
3d bounding box, shape:(8, 4).
"""
b... | 8,364 |
def _ugly_fix_invalid_coords_inplace(invalid_rows_df, tofix_df):
"""note: used global variable concat_no_invalid_rows"""
concat_no_invalid_rows = raw_concat_traintest_df[ raw_concat_traintest_df['Y'] != 90.0 ]
for row_idx, row in invalid_rows_df.iterrows():
addr_occurences_in_concat = concat_no_inva... | 8,365 |
def LockAllLiveGroups():
"""
Locks the contents of all LiveGroup nodes that are non-editable, starting
from the specified node.
@type node: C{NodegraphAPI.Node}
@param node: The node at which to start locking contents of LiveGroup
nodes.
"""
pass | 8,366 |
def mkstemp(
open_kwargs=None, # type: Optional[Dict[Text, Any]]
text=True, # type: bool
name_only=False, # type: bool
*args,
**kwargs):
# type: (...) -> Union[(IO[AnyStr], Text), Text]
"""
WARNING: the returned file object is strict about its input type,
... | 8,367 |
def greater_than_or_equal_to_zero(param, *args):
# type: (int, *int) -> None
"""
Fails if the input integer parameter is negative.
"""
if args:
# adaptation for attr library
param = args[1]
if 0 >= param:
raise ValueError('{} < 0'.format(get_name_from_param(param))) | 8,368 |
def test_calculate_data_subject_rights(data_subject_rights: dict) -> None:
"""Tests different strategy options for returning data subject rights."""
rights = DataSubjectRights(**data_subject_rights)
return_str_value = export_helpers.calculate_data_subject_rights(rights.dict())
assert return_str_value i... | 8,369 |
def _create_local_dt_indices(time_series, key_prefix):
"""
local_dt is an embedded document, but we will query it using the individual fields
"""
time_series.create_index([("%s.year" % key_prefix, pymongo.DESCENDING)], sparse=True)
time_series.create_index([("%s.month" % key_prefix, pymongo.DESCENDI... | 8,370 |
def featuredrep_set_groups(sender, **kwargs):
"""Set permissions to groups."""
app_label = sender.label
if (isinstance(app_label, basestring) and app_label != 'featuredrep'):
return True
perms = {'can_edit_featured': ['Admin', 'Council', 'Peers'],
'can_delete_featured': ['Admin', '... | 8,371 |
def download(loc, rem):
"""download rem to loc"""
# does the remote file exist
if not rem.exists():
return ReturnCode.NO_SOURCE
# does the local file exist
# if it doesnt, copy rem to loc, isLogged = False
if not loc.is_file():
return do_copy(rem, loc, False)
# is the local... | 8,372 |
def read_dict (conf_dict = {}, filename = "SWIM_config"):
"""
Open and read a dictionary of key-value pairs from the file given by
filename. Use the read-in values to augment or update the dictionary passed
in, then return the new dictionary.
"""
from utils import publish_event
try:
... | 8,373 |
def ordinals_to_ordinals(s):
""" Example:
'third' -> '3rd'
Up to 31st (intended for dates)
"""
for val in ordinals.keys():
s = s.replace(val, ordinals[val])
return s | 8,374 |
def create_dataframe_schema():
"""
Create dataframe schema
"""
return pd.DataFrame(columns=['Station_id', 'Name']) | 8,375 |
def shutdown_check_handler():
"""This checks the AWS instance data URL to see if there's a pending
shutdown for the instance.
This is useful for AWS spot instances. If there is a pending shutdown posted
to the instance data URL, we'll use the result of this function break out of
the processing loop... | 8,376 |
def cal_d(date=cal_date.today(), zf=True):
"""
Month, optionally left-padded with zeroes (default: pad)
"""
day_num = "d" if zf else "-d" # optionally zero fill
return date.strftime(f"%{day_num}") | 8,377 |
def get_max_total(map_of_maps: Mapping[Sequence[str], Mapping[Tuple, float]]) -> float:
"""
>>> df = get_sample_df()
>>> get_max_total(calculate_kls_for_attackers(df, [1]))
1.3861419037664793
>>> get_max_total(calculate_kls_for_attackers(df))
3.0817041659455104
"""
return max(get... | 8,378 |
def get_keeper_token(host: str, username: str, password: str) -> str:
"""Get a temporary auth token from LTD Keeper.
Parameters
----------
host : `str`
Hostname of the LTD Keeper API (e.g., ``'https://keeper.lsst.codes'``).
username : `str`
Username.
password : `str`
Pas... | 8,379 |
def edit_comment(post_id, comment_id):
"""Edit a comment from a specific post"""
post = posts.get(post_id)
if not post:
return json.dumps({"error": "Post Not Found"}), 404
comments = post["comments"]
comment = comments.get(comment_id)
if not comment:
return json.dumps({"error":... | 8,380 |
def update_transition_dirichlet(
pB, B, actions, qs, qs_prev, lr=1.0, return_numpy=True, factors="all"
):
"""
Update Dirichlet parameters that parameterize the transition model of the generative model
(describing the probabilistic mapping between hidden states over time).
Parameters
----------... | 8,381 |
def MRP2Euler231(q):
"""
MRP2Euler231(Q)
E = MRP2Euler231(Q) translates the MRP
vector Q into the (2-3-1) euler angle vector E.
"""
return EP2Euler231(MRP2EP(q)) | 8,382 |
def _convert_from_node_attribute(
G, attr_name, node_types, node_type_name=None, node_type_default=None, dtype="f"
):
"""
Transform the node attributes to feature vectors, for use with machine learning models.
Each node is assumed to have a numeric array stored in the attribute_name and
which is su... | 8,383 |
def handle_args(parser: argparse.ArgumentParser, section: Text) -> argparse.Namespace:
""" Verify default arguments """
hostname = socket.gethostname()
hostname_short = socket.gethostname().split(".")[0]
host_config_name = f"{CONFIG_NAME}-{hostname}"
host_short_config_name = f"{CONFIG_NAME}-{hostn... | 8,384 |
def get_entry_or_none(base: dict, target, var_type=None):
"""Helper function that returns an entry or None if key is missing.
:param base: dictionary to query.
:param target: target key.
:param var_type: Type of variable this is supposed to be (for casting).
:return: entry or None.
"""
if ... | 8,385 |
def group_list(request):
"""
List all gourps, or create a new group.
"""
if request.method == 'GET':
tasks = Group.objects.all()
serializer = GroupSerializer(tasks, many=True)
return Response(serializer.data)
elif request.method == 'POST':
unique_name = request.data.... | 8,386 |
def CreateBooleanSplit(meshesToSplit, meshSplitters, multiple=False):
"""
Splits a set of meshes with another set.
Args:
meshesToSplit (IEnumerable<Mesh>): A list, an array, or any enumerable set of meshes to be split. If this is null, None will be returned.
meshSplitters (IEnumerable<Mesh>... | 8,387 |
def template14():
"""Simple ML workflow"""
script = """
## (Enter,datasets)
<< host = chemml
<< function = load_cep_homo
>> smiles 0
>> homo 4
## (Store,file)
<< host = chemml
... | 8,388 |
def get_group_selector(*args):
"""
get_group_selector(grpsel) -> sel_t
Get common selector for a group of segments.
@param grpsel: selector of group segment (C++: sel_t)
@return: common selector of the group or 'grpsel' if no such group is
found
"""
return _ida_segment.get_group_selector(*... | 8,389 |
def wrap(text=cert_text) -> str:
"""Wraps the given text using '\n' to fit the desired width."""
wrapped_text = textwrap.fill(text, fit_char())
return wrapped_text | 8,390 |
def encode(data):
"""calls simplejson's encoding stuff with our needs"""
return simplejson.dumps(
data,
cls=CahootsEncoder,
ensure_ascii=False,
encoding='utf8',
indent=4
) | 8,391 |
def SE_HRNet_W48_C(pretrained=False, use_ssld=False, **kwargs):
"""
SE_HRNet_W48_C
Args:
pretrained: bool=False or str. If `True` load pretrained parameters, `False` otherwise.
If str, means the path of the pretrained model.
use_ssld: bool=False. Whether using distillatio... | 8,392 |
def manifest(argument: Union[Any, List[Any]], data: bytearray) -> Union[Any, List[Any]]:
"""
Returns the manifestation of a `refinery.lib.argformats.LazyEvaluation`
on the given data. This function can change the data.
"""
if isinstance(argument, (list, tuple)):
return [manifest(x, data) for... | 8,393 |
def get_child_hwnd_by_class(hwnd: int, window_class: str) -> int:
"""Enumerates the child windows that belong to the specified parent window by passing the handle to
each child window.
:param hwnd: HWND in decimal
:param window_class: window class name
:return: window handle (HWND)
"""
def... | 8,394 |
def uniq(lst):
"""
this is like list(set(lst)) except that it gets around
unhashability by stringifying everything. If str(a) ==
str(b) then this will get rid of one of them.
"""
seen = {}
result = []
for item in lst:
if str(item) not in seen:
result.append... | 8,395 |
async def test_dhcp_flow(hass: HomeAssistant) -> None:
"""Test that DHCP discovery works."""
with patch(
"homeassistant.components.qnap_qsw.QnapQswApi.get_live",
return_value=LIVE_MOCK,
):
result = await hass.config_entries.flow.async_init(
DOMAIN,
data=DHCP_S... | 8,396 |
async def test_trigger_flow(server):
"""
test cascading async trigger flow from client to sever and back
Request the server to call us back later
"""
async with WebSocketRpcClient(uri,
ClientMethods(),
default_response_timeout=4) as... | 8,397 |
def write_version_to_file(version_number: str) -> None:
"""
Writes the version to the VERSION.txt file.
Args:
version_number: (str) the version to be written to the file
Returns: None
"""
version_file_path: str = str(pathlib.Path(__file__).parent.absolute()) + "/monolithcaching/version... | 8,398 |
def as_datetime(dct):
"""Decode datetime objects in data responses while decoding json."""
try:
type, val = dct['__jsonclass__']
if type == 'datetime':
# trac doesn't specify an offset for its timestamps, assume UTC
return dateparse(val).astimezone(utc)
except KeyErro... | 8,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.