content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def compute_embeddings(image):
"""A mock function for a call to a deep learning model or a web service."""
del image # this is just a mock and doesn't do anything with the input
return 42 | 34,400 |
def dir(path: str) -> Path:
"""Get equivalent directory in cache"""
_, filename = os.path.split(path)
if filename: # TODO fix; this won't work as intended
# If file
return __get_cache_filepath(path).parent
else:
# If directory
return __get_cache_filepath(os.path.join(path... | 34,401 |
def text_to_string(filename):
"""Read a text file and return a string."""
with open(filename) as infile:
return infile.read() | 34,402 |
def lgsvlToScenicElevation(pos):
"""Convert LGSVL positions to Scenic elevations."""
return pos.y | 34,403 |
def render_to_string(backend, filename, context):
# type: (str, str, Dict) -> str
"""
Render a template using the specified context
:param backend: The backend for which the template is rendered
:param filename: The template name
:param context: The data to use when rendering the template
:r... | 34,404 |
def work(commits, files, works, bug_commit):
""" Fill given files with random numbers and executes commits,
randomly add !BUG! to a file of given bug_commit """
bug_commited = False
for i in range(commits):
for j in range(randint(1, works)):
filename = choice(files)
fil... | 34,405 |
def customfield_by_name(self, name):
"""
Get the value of a customfield by name
"""
# Get all fields from Jira. This is expensive, so only do it once
if not hasattr(self, '_fields'):
response = self._session.get(
self._base_url.format(
server=self._options['server... | 34,406 |
def download_images(imgs):
"""Save any images on page to local directory"""
had_download_issue = False
for img in imgs:
image_url = 'https://projecteuler.net/{}'.format(img.get('src'))
logger.info(f'downloading image {image_url}')
image_name = Path(image_url).name
image = get... | 34,407 |
def create_data(arguments, event_log, preprocessor, cases_of_fold):
"""
Generates data to train and test/evaluate a model during hyper-parameter optimization (hpo) with Optuna.
Parameters
----------
arguments : Namespace
Settings of the configuration parameters.
event_log : list... | 34,408 |
def admin_order_pdf(request, order_id):
"""
1. Get data (and templates for displaying data)
2. Set type (cuz you'll need to download it, right?)
3. Using the module (configuring stuff, e.g. the CSS :P)
"""
order = get_object_or_404(Order, id=order_id)
html = render_to_string... | 34,409 |
def delete_container(request, container):
""" Deletes a container """
storage_url = request.session.get('storage_url', '')
#meta_storage_url = request.session.get('meta_storage_url', '')
auth_token = request.session.get('auth_token', '')
#meta_auth_token = request.session.get('meta_auth_token', '')... | 34,410 |
def dense_encoder(X, params):
"""Dense model encoder subgraph that produces latent matrix.
Given data matrix tensor X and dictionary of parameters, process through dense
model encoder subgraph and return encoder latent vector for each example in
batch.
Args:
X: tf.float64 matrix tensor of input data.
... | 34,411 |
def __asset_inventory_espanol(asset):
""" Renombra los encabezados del inventario de bases de datos de Datos \
Abiertos Colombia a términos en español.
:param asset: (pandas.DataFrame) - Tabla de inventario del portal de datos\
abiertos Colombia (https://www.datos.gov.co).
:return: ba... | 34,412 |
def end_of_sign_found(token: str, preceding_token: str):
"""
This function receives a token and its preceding token and returns whether that token ends an Akkadian sign.
"""
if not preceding_token:
return False
if '-' in token or '.' in token:
return True
if not preceding_token.e... | 34,413 |
def main(argv=None):
"""Execute the application from CLI."""
if argv is None:
argv = sys.argv[1:]
if not argv:
argv = [curdir]
args = _parse_args(argv)
data = csft2data(args.path)
if args.top:
data = data.head(args.top)
if args.with_raw:
data['raw'] = data[c... | 34,414 |
def translateFrontendStrings(language_code):
"""
Translate all strings used in frontend templates and code
:param language_code: de|en
"""
if sys.platform == 'win32':
pybabel = 'pybabel'
else:
pybabel = 'flask/bin/pybabel'
# frontend pages
os.system(pybabel + ' extract ... | 34,415 |
def build_gemini3d(targets: list[str]):
"""
build targets from gemini3d program
Specify environment variable GEMINI_ROOT to reuse existing development code
"""
if isinstance(targets, str):
targets = [targets]
gem_root = get_gemini_root()
src_dir = Path(gem_root).expanduser()
... | 34,416 |
def get_base_path(node=None):
"""
get the base path for the system
"""
if node==None: node = get_system()
##
## Base path
try:
path = os.environ['sdss_catl_path']
assert(os.path.exists(path))
except:
proj_dict = cookiecutter_paths(__file__)
##
## P... | 34,417 |
def get_loaders(
dataset: str, batch_size: int, num_workers: Optional[int]
) -> Dict[str, DataLoader]:
"""Init loaders based on parsed parametrs.
Args:
dataset: dataset for the experiment
batch_size: batch size for loaders
num_workers: number of workers to process loaders
Retur... | 34,418 |
def pipeline():
""" Creates a pipeline configured to use a given model with a specified configuration.
Notes
-----
Pipeline can be executed only if its config contains the following parameters:
model_class : TFModel
Architecture of model. List of available models is defined at 'AVAILABLE_M... | 34,419 |
def get_screen_point_array(width: float, height: float):
"""Get screen points(corners) in pixels from normalized points_in_square
:param width: screen width
:param height: screen height
:return:
"""
points = copy.deepcopy(points_in_square)
for i in range(len(points_in_square)):
poin... | 34,420 |
def get_spacing_matrix(size, spacing, offset):
"""Returns a sparse matrix LinOp that spaces out an expression.
Parameters
----------
size : tuple
(rows in matrix, columns in matrix)
spacing : int
The number of rows between each non-zero.
offset : int
The number of zero r... | 34,421 |
def next_power2(x):
"""
:param x: an integer number
:return: the power of 2 which is the larger than x but the smallest possible
>>> result = next_power2(5)
>>> np.testing.assert_equal(result, 8)
"""
return 2 ** np.ceil(np.log2(x)).astype(int) | 34,422 |
def category_induced_page():
"""Form to compute the Category induced."""
return render_template('category-induced.html') | 34,423 |
def zext(value, n):
"""Extend `value` by `n` zeros"""
assert (isinstance(value, (UInt, SInt, Bits)) or
(isinstance(value, Array) and issubclass(value.T, Digital)))
if not is_int(n) or n < 0:
raise TypeError(f"Expected non-negative integer, got '{n}'")
if n == 0:
return value
... | 34,424 |
def _distance(point0, point1, point2, seg_len):
"""Compute distance between point0 and segment [point1, point2]. Based on Mark McClure's
PolylineEncoder.js."""
if (point1[0] == point2[0]) and (point1[1] == point2[1]):
out = _dist(point0, point2)
else:
uuu = ((point0[0] - point1[0]) * (po... | 34,425 |
def delete_node(
graph: xpb2.GraphProto,
node_name: str = "",
**kwargs):
""" Add node appends a node to graph g and returns the extended graph
Prints a message and returns False if fails.
Args:
graph: A graph, onnx.onnx_ml_pb2.GraphProto.
node_name: Name of the node... | 34,426 |
def image_to_term256(pil_image):
"""Convert image to a string that resembles it when printed on a terminal
Needs a PIL image as input and a 256-color xterm for output.
"""
result = []
im = pil_image.convert('RGBA')
try:
from PIL import Image
except ImportError:
im.thumbnail(... | 34,427 |
def login(driver, user, pwd):
"""
Type user email and password in the relevant fields and
perform log in on linkedin.com by using the given credentials.
:param driver: selenium chrome driver object
:param user: str username, email
:param pwd: str password
:return: None
"""
username ... | 34,428 |
def false_discovery(alpha,beta,rho):
"""The false discovery rate.
The false discovery rate is the probability that an observed edge is
incorrectly identified, namely that is doesn't exist in the 'true' network.
This is one measure of how reliable the results are.
Parameters
----------
... | 34,429 |
def dis3(y=None):
"""frobnicate classes, methods, functions, or code.
With no argument, frobnicate the last traceback.
"""
if y is None:
distb()
return
if isinstance(y, types.InstanceType):
y = y.__class__
if hasattr(y, 'im_func'):
y = y.im_func
if hasattr(y... | 34,430 |
def assert_almost_equal(
actual: numpy.float64, desired: numpy.float64, err_msg: Literal["orth.legendre(1)"]
):
"""
usage.scipy: 1
"""
... | 34,431 |
def __keep_update_tweets(interval: int) -> None:
"""run update-tweets command with interval on background."""
mzk.set_process_name(f'MocaTwitterUtils({core.VERSION}) -- keep-update-tweets')
while True:
mzk.call(
f'nohup {mzk.executable} "{core.TOP_DIR.joinpath("moca.py")}" update-tweets ... | 34,432 |
def task_rescheduled_handler(sender, **kwargs):
"""
Notify the admins when a task has failed and rescheduled
"""
name = kwargs['task'].verbose_name
attempts = kwargs['task'].attempts
last_error = kwargs['task'].last_error
date_time = kwargs['task'].run_at
task_name = kwargs['task'].task_... | 34,433 |
def repeat_first(iterable):
"""Repeat the first item from an iterable on the end.
Example:
>>> ''.join(repeat_first("ABDC"))
"ABCDA"
Useful for making a closed cycle out of elements.
If iterable is empty, the result will also be empty.
Args:
An iterable series of items.
... | 34,434 |
def add_default_legend(axes, subplots, traces):
"""
Add legend to the axes of the plot. This is needed to be done using matplotlib shapes
rather than the build in matplotlib legend because otherwise the animation will add
a legend at each time step rather than just once.
Parameters
----------
... | 34,435 |
def _conv2d(input,
filter,
bias=False,
strides=[1, 1],
pads=[1, 1, 1, 1],
dilations=[1, 1],
group=1,
debugContext=''):
"""Encapsulation of function get_builder().aiOnnx.conv!
args:
x: input tensor
ksize: i... | 34,436 |
def remove_dir_content(dir_path: str, ignore_files: Iterable[str] = tuple(), force_reset: bool = False) -> None:
"""
Remove the content of dir_path ignoring the files under ignore_files.
If force_reset is False, prompts the user for approval before the deletion.
:param dir_path: path to dir. either rel... | 34,437 |
def StartUpRedis(host_protos):
""" Given a list of host protos, run external program 'mx' that allows one to
start up a program on an running host container. This function will use that
program to start up redis on the appropraite hosts.
Arguments:
host_protos: list of host protobuf messages as ... | 34,438 |
def set_seed(seed: int):
"""
Sets random, numpy, torch, and torch.cuda seeds
"""
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed) | 34,439 |
def split_data(n_samps, percent_test):
"""
:param n_samps: number of data samples
:param percent_test: percent of data to hold out
:return: two sets of indices corresponding to training and validation data
"""
# generate and randomly shuffle
idx = np.arange(n_samps)
np.random.shuffle(id... | 34,440 |
def compute_totals(songs, limit_n, save_file=None):
"""
Return array of shape (4, 3, 35) representing counts for
each group of each context type of each label
"""
totals = np.zeros((4, 3, 35), dtype='int32')
i = 0
for song_path, beatmap_ids in songs:
print('song {}'.format(i))
... | 34,441 |
def _initialize_arrays(initial_values,
num_steps):
"""Construct a structure of `TraceArray`s from initial values."""
trace_arrays = tf.nest.map_structure(
lambda t: tf.TensorArray( # pylint: disable=g-long-lambda
dtype=t.dtype,
size=num_steps, # Initial size.
... | 34,442 |
def blend(image1, image2, factor):
"""Blend image1 and image2 using 'factor'.
Factor can be above 0.0. A value of 0.0 means only image1 is used.
A value of 1.0 means only image2 is used. A value between 0.0 and
1.0 means we linearly interpolate the pixel values between the two
images. A value greater than... | 34,443 |
def AddReservationAffinityFlags(parser, for_node_pool=False):
"""Adds the argument to handle reservation affinity configurations."""
target = 'node pool' if for_node_pool else 'default initial node pool'
group_text = """\
Specifies the reservation for the {}.""".format(target)
group = parser.add_group(help=gro... | 34,444 |
def handle_debug(drive_file, node_id, show_all):
"""Handle the debug verb by toggling the debug flag."""
if drive_file.debug:
print("# handle_debug(node_id: " + str(node_id) + ",")
print("# show_all: " + str(show_all))
drive_file.set_debug(not drive_file.get_debug())
return True | 34,445 |
def start_of_next_clk_period(time: float, clk_period: float):
"""
:return: start time of next clk period
"""
return (start_clk(time, clk_period) + 1) * clk_period | 34,446 |
def eval_formula(formula, assignment):
""" Evaluates a formula represented as a string.
**Attention**: Be extremely careful about what to pass to this function.
All parameters are plugged into the formula and evaluated using `eval()`
which executes arbitrary python code.
Parameters
----------
... | 34,447 |
def verify_hash(path: Path, expected_hash: str) -> None:
"""
Raises:
MissingFileError - path doesn't exist
IntegrityError - path exists with bad hash
"""
if not path.exists():
raise MissingFileError(str(path))
h = hash_file(path)
if h != expected_hash:
raise Inte... | 34,448 |
def soil_temperature(jth: int, states: States, weather: Weather): # j = 1,2,..,5
"""
Equation 2.4 / 8.4
cap_soil_j * soil_j_t = sensible_heat_flux_soil_j_minus_soil_j - sensible_heat_flux_soil_j_soil_j_plus
0 is Floor, 6 is SoOut
"""
h_soil_j_minus = Coefficients.Floor.floor_thickness if jth =... | 34,449 |
def test_metadata_default(metadata_class):
"""Test long_break_clock_count default value."""
metadata_default = metadata_class()
assert metadata_default.long_break_clock_count == 4 | 34,450 |
def clean_user_data(model_fields):
"""
Transforms the user data loaded from
LDAP into a form suitable for creating a user.
"""
# Create an unusable password for the user.
model_fields["password"] = make_password(None)
return model_fields | 34,451 |
def main():
""" Runs data processing scripts to turn raw data from (../raw) into
cleaned data ready to be analyzed (saved in ../processed).
"""
save_path = 'data/raw/data.csv'
model = RecipeModel()
if model.all():
table_to_csv(f'select * from {model.TABLE_NAME}', model.con,sav... | 34,452 |
def case_structure_generator(path):
"""Create test cases from reference data files."""
with open(str(path), 'r') as in_f:
case_data = json.load(in_f)
system_dict = case_data['namelists']['SYSTEM']
ibrav = system_dict['ibrav']
ins = {'ibrav': ibrav, 'cell': case_data['cell']}
if '-' in p... | 34,453 |
def draw_pixel(x, y, pixel, img):
"""
Draw `pixel` onto `img` at the specified coordinates.
Args:
x(int): x coordinate of draw
y(int): y coordinate of draw
pixel(tuple): red, green, blue, and optionally alpha
img(Image): the Image to draw the pixel onto
Raises:
... | 34,454 |
async def source_feeder(tangled_object, source_name):
""" This coroutine will update a Foo or Bar source node with values at
random intervals
"""
for _ in range(4):
await asyncio.sleep(random.uniform(0.5, 2))
setattr(tangled_object, source_name, random.randint(-20, 20)/2.0) | 34,455 |
def load_ascii(file: 'BinaryFile', # pylint: disable=unused-argument,keyword-arg-before-vararg
parser: 'Optional[Type[ASCIIParser]]' = None,
type_hook: 'Optional[Dict[str, Type[BaseType]]]' = None,
enum_namespaces: 'Optional[List[str]]' = None, bare: bool = False,
... | 34,456 |
def test_histcontrol(hist, xession):
"""Test HISTCONTROL=ignoredups,ignoreerr"""
ignore_opts = ",".join(["ignoredups", "ignoreerr", "ignorespace"])
xession.env["HISTCONTROL"] = ignore_opts
assert len(hist) == 0
# An error, items() remains empty
hist.append({"inp": "ls foo", "rtn": 2})
asse... | 34,457 |
def differences_dict(input_dict):
"""Create a dictionary of combinations of readers to create bar graphs"""
# Getting the combinations of the formats
for each_case in input_dict.keys():
comb = combinations(input_dict[each_case].keys(), 2)
x = list(comb)
comp_values = {}
comp_... | 34,458 |
def available_memory():
"""
Returns total system wide available memory in bytes
"""
import psutil
return psutil.virtual_memory().available | 34,459 |
def aslr_for_module(target, module):
"""
Get the aslr offset for a specific module
- parameter target: lldb.SBTarget that is currently being debugged
- parameter module: lldb.SBModule to find the offset for
- returns: the offset as an int
"""
header_address = module.GetObjectFileHeaderAddr... | 34,460 |
def get_hypergraph_incidence_matrix(node_list: List[Node],
hyperedge_list: List[Set[Node]]
) -> numpy.array:
"""Get the incidence matrix of a hypergraph"""
node_to_index = {node: index for index, node in enumerate(node_list)}
incidence_... | 34,461 |
def root_tree_by_phyla(T, phyla):
"""Root the tree next to the phylum that is as far apart as possible from the other phyla"""
phylum_LCA = {}
for p in phyla.unique():
phylum_LCA[p] = T.get_common_ancestor(*tuple(phyla.index[phyla == p].values))
Dist = pd.DataFrame()
for p1, lca1 in phylum... | 34,462 |
def fformat(last_data, last_records):
"""
@param last_data: dictionary(node_name => node's data segment)
@param last_records: dictionary(node_name => timestamp, node when
last transmitted)
@return: html
"""
nodelist = last_data.keys()
a = re... | 34,463 |
def ceil(base):
"""Get the ceil of a number"""
return math.ceil(float(base)) | 34,464 |
def process_raw_data(input_seqs, scaffold_type=None, percentile=None,
binarize_els=True, homogeneous=False, deflank=True,
insert_into_scaffold=True, extra_padding=0,
pad_front=False, report_loss=True, report_times=True,
remove_files=Tru... | 34,465 |
def train(
dir,
input_s3_dir,
output_s3_dir,
hyperparams_file,
ec2_type,
volume_size,
time_out,
docker_tag,
aws_role,
external_id,
base_job_name,
job_name,
use_spot_instances=False,
metric_names=None,
... | 34,466 |
def wikitext_page(d, e, title, fmt='wikitext'):
"""Create infobox with stats about a single page from a category.
Create infobox with stats about a single page from a category. Currently only supports formatting as wikitext.
Only returns the string of the text, does not save any files or modify other data ... | 34,467 |
def _quadratic(
self: qp.utils.Minimize[Vector],
direction: Vector,
step_size_test: float,
state: qp.utils.MinimizeState[Vector],
) -> Tuple[float, float, bool]:
"""Take a quadratic step calculated from an energy-only test step.
Adjusts step size to back off if energy increases."""
# Check ... | 34,468 |
def create_image(ds: "Dataset", data_element: "DataElement") -> "gdcm.Image":
"""Return a ``gdcm.Image``.
Parameters
----------
ds : dataset.Dataset
The :class:`~pydicom.dataset.Dataset` containing the Image
Pixel module.
data_element : gdcm.DataElement
The ``gdcm.DataElemen... | 34,469 |
def linear_interpolate_by_datetime(datetime_axis, y_axis, datetime_new_axis,
enable_warning=True):
"""A datetime-version that takes datetime object list as x_axis
"""
numeric_datetime_axis = [
totimestamp(a_datetime) for a_datetime in datetime_axis
]
numer... | 34,470 |
def calculate_index(
target_ts: pd.Timestamp, timestamps: pd.DatetimeIndex
) -> pd.Timestamp:
"""
Return the first index value after the target timestamp if the exact timestamp is not available
"""
# noinspection PyUnresolvedReferences
target_beyond_available = (target_ts > timestamps).all()
... | 34,471 |
def walk_through_package(package):
"""
Get the documentation for each of the modules in the package:
Args:
package: An imported python package.
Returns:
output: A dictionary with documentation strings for each module.
"""
output = OrderedDict()
modules = pydoc.inspect.get... | 34,472 |
def extract_images_2(f):
"""Extract the images into a 4D uint8 numpy array [index, y, x, depth].
Args:
f: A file object that can be passed into a gzip reader.
Returns:
data: A 4D unit8 numpy array [index, y, x, depth].
Raises:
ValueError: If the bytestream does not start with 2051.
"""
print('Ex... | 34,473 |
def slope_finder(station):
""" This function computes the slope of a least-squares fit of polynomial
of degree p to water level data and return that is it positive or negative"""
try:
dt = 2
dates, levels = fetch_measure_levels(station.measure_id, dt=datetime.timedelta(days=dt))
slop... | 34,474 |
def get_attr_counts(datas, attr):
"""
不同属性值的数量.
:param datas:
:type datas: list[BaseDataSample]
:param attr:
:type attr: str
:return:
"""
results = {}
for data in datas:
value = data.get_value(attr)
if isinstance(value, list):
for v in value:
... | 34,475 |
def restart_processes():
"""
Restart processes on the remote server
"""
for service in env.services_to_restart:
sudo("/bin/systemctl restart {}.service".format(service), shell=False) | 34,476 |
def split(string: str, separator: str = " ") -> list:
"""
Will split the string up into all the values separated by the separator (defaults to spaces)
>>> split("apple#banana#cherry#orange",separator='#')
['apple', 'banana', 'cherry', 'orange']
>>> split("Hello there")
['Hello', 'there... | 34,477 |
def _find_class(name: str, target: ast.Module) -> t.Tuple[int, ast.ClassDef]:
"""Returns tuple containing index of classdef in the module and the ast.ClassDef object"""
for idx, definition in enumerate(target.body):
if isinstance(definition, ast.ClassDef) and definition.name == name:
return ... | 34,478 |
def get_floor_reference_points():
"""
This function get 4 points of reference from the real world, asking the
user to move the baxter arm to the position of each corresponding point
in the image, and then getting the X,Y and Z coordinates of baxter's hand.
Returns an array of size 4 containing 4 coo... | 34,479 |
def tidy_osx_command_line_tools_command(client: TidyClient, **kwargs) -> DemistoResult:
""" Install OSX command line tools
Args:
client: Tidy client object.
**kwargs: command kwargs.
Returns:
DemistoResults: Demisto structured response.
"""
runner: Runner = client.osx_comma... | 34,480 |
def grid_search(parameters, mlflow_client, experiment_name, use_cache=False,
result_file_path=Path("./output/results_reader.csv"), gpu_id=-1,
elasticsearch_hostname="localhost", elasticsearch_port=9200,
yaml_dir_prefix="./output/pipelines/retriever_reader"):
""" Retur... | 34,481 |
def nav_entries(context):
"""
Renders dynamic nav bar entries from nav_registry for the provided user.
"""
context['nav_registry'] = nav_registry
return context | 34,482 |
def get_largest_component(graph: ig.Graph, **kwds: Any) -> ig.Graph:
"""Get largest component of a graph.
``**kwds`` are passed to :py:meth:`igraph.Graph.components`.
"""
vids = None
for component in graph.components(**kwds):
if vids is None or len(component) > len(vids):
vids =... | 34,483 |
def test_download_file(app, default_user, _get_user_mock):
"""Test download_file view."""
with app.test_client() as client:
with patch("reana_server.rest.workflows.requests"):
res = client.get(
url_for(
"workflows.download_file",
workfl... | 34,484 |
def hiring_contests():
"""Gets all the hiring challenges from all the availbale platforms"""
contests_data = get_contests_data()
active_contests = contests_data["active"]
upcoming_contests = contests_data["pending"]
get_challenge_name = lambda x : x.lower().split()
hiring_challenges = [contest for contest i... | 34,485 |
def _find_quantized_op_num(model, white_list, op_count=0):
"""This is a helper function for `_fallback_quantizable_ops_recursively`
Args:
model (object): input model
white_list (list): list of quantizable op types in pytorch
op_count (int, optional): count the quantizable op quantity in... | 34,486 |
def make_withdrawal(account):
"""Adjusts account balance for withdrawal.
Script that verifies withdrawal amount is valid, confirms that withdrawal amount is less than account balance, and adjusts account balance.
Arg:
account(dict): contains pin and balance for account
Return:... | 34,487 |
def monta_reacao(coef, form):
"""
Retorna a estrutura de uma reação química com base em arrays gerados por métodos de sorteio de reações.
:param coefs: Array com coeficientes das substâncias.
:param formulas: Array com fórmulas das substâncias.
:return: string pronta para ser impressa (print())... | 34,488 |
def test_process_bulk_queue_errors(app, queue):
"""Test error handling during indexing."""
with app.app_context():
# Create a test record
r1 = Record.create({
'title': 'invalid', 'reffail': {'$ref': '#/invalid'}})
r2 = Record.create({
'title': 'valid', })
... | 34,489 |
def list_to_string(the_list):
"""Converts list into one string."""
strings_of_list_items = [str(i) + ", " for i in the_list]
the_string = "".join(strings_of_list_items)
return the_string | 34,490 |
def pretty_print_subkey_scores(np_array, limit_rows=20, descending=True):
"""
Print score matrix as a nice table.
:param np_array:
:param limit_rows:
:param descending:
:return:
"""
if type(np_array) != np.ndarray:
raise TypeError("Expected np.ndarray")
elif len(np_array.shap... | 34,491 |
def test_new_feature():
"""
Test that a valid feature function handle is returned when adding new feat.
""" | 34,492 |
def _op_select_format(kernel_info):
"""
call op's op_select_format to get op supported format
Args:
kernel_info (dict): kernel info load by json string
Returns:
op supported format
"""
try:
op_name = kernel_info['op_info']['name']
te_set_version(kernel_info["op_... | 34,493 |
def test_k_command_line_mode(vim_bot):
"""Select line up."""
main, editor_stack, editor, vim, qtbot = vim_bot
editor.stdkey_backspace()
editor.go_to_line(3)
editor.moveCursor(QTextCursor.StartOfLine, QTextCursor.KeepAnchor)
qtbot.keyPress(editor, Qt.Key_Right)
qtbot.keyPress(editor, Qt.Key_R... | 34,494 |
def get_rate_plan(apiproduct_id: Optional[str] = None,
organization_id: Optional[str] = None,
rateplan_id: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetRatePlanResult:
"""
Gets the details of a rate plan.
"""
__ar... | 34,495 |
def detail_blotter(backtest, positions, holdings, mode='simplified'):
"""
分品种获取详细交易状况,合并市场数据、交易情况和账户变动
参数:
backtest, positions, holdings为回测引擎返回的变量
mode: 'simplified'则市场行情数据只保留'close'列
(DataFrame的字典)
返回:
字典,键为symbol,值为DataFrame格式
示例:
blotter = detail_blotter(backtest, positions, ... | 34,496 |
def parameters_create_lcdm(Omega_c, Omega_b, Omega_k, h, norm_pk, n_s, status):
"""parameters_create_lcdm(double Omega_c, double Omega_b, double Omega_k, double h, double norm_pk, double n_s, int * status) -> parameters"""
return _ccllib.parameters_create_lcdm(Omega_c, Omega_b, Omega_k, h, norm_pk, n_s, status) | 34,497 |
def _split_header_params(s):
"""Split header parameters."""
result = []
while s[:1] == b';':
s = s[1:]
end = s.find(b';')
while end > 0 and s.count(b'"', 0, end) % 2:
end = s.find(b';', end + 1)
if end < 0:
end = len(s)
f = s[:end]
resu... | 34,498 |
def test_wuch2_nllmatrix():
""" test wuch2 nllmatrix"""
filename = r"nll_matrix_wuch2.pkl"
with open(filename, "rb") as fhandle:
nll_matrix = pickle.load(fhandle)
triple_set = find_aligned_pairs(nll_matrix)
res = triple_set[0][0] if triple_set else None
assert res == 6, "Expected to be {... | 34,499 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.