content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def test_gets():
"""test get_first and get_second"""
two_elem_int_list = [1, 2]
two_elem_int_tuple = (1, 2)
with pytest.raises(ValueError):
get_first(1)
with pytest.raises(ValueError):
get_first([])
assert get_first(two_elem_int_list) == 1
assert get_first(two_elem_int_tup... | 3,500 |
def block(**arguments: Any) -> Optional[Blocks]:
"""Python application interface for creating an initial block file from command line or python code.
This method creates an HDF5 file associated with the desired intial flow specification (for each
needed computational field), suitable for input by the FLASH... | 3,501 |
def test__string():
""" test vmatrix.string
"""
vma = vmatrix.from_string(vmatrix.string(CH4O_VMA))
assert vma == CH4O_VMA | 3,502 |
def enable_multivsys(fw_conn):
"""Enable Multi-vsys
Args:
fw_conn (PanDevice): A panos object for device
"""
command = '<set><system><setting><multi-vsys>on</multi-vsys></setting></system></set>'
fw_conn.op(cmd=command, cmd_xml=False) | 3,503 |
def _low_discrepancy(dim, n, seed=0.5):
"""Generate a 1d, 2d, or 3d low discrepancy sequence of coordinates.
Parameters
----------
dim : one of {1, 2, 3}
The dimensionality of the sequence.
n : int
How many points to generate.
seed : float or array of float, shape (dim,)
... | 3,504 |
def get(
url: str
) -> Dict[str, object]:
"""
Returns the sdk GET response
:param url: A string url endpoint.
:type: str
:return: Dict[str, object]
"""
try:
res = requests.get(url, headers=get_headers())
except Exception as e:
handle_request_error(e)
return handl... | 3,505 |
def register(request):
"""Create an account for a new user"""
if request.method == 'POST':
data = request.POST.copy()
form = tcdUserCreationForm(data)
next = request.POST['next']
if form.is_valid():
new_user = User.objects.create_user(username=data['username'],
... | 3,506 |
def set_index_da_ct(da):
"""Stacks all coordinates into one multindex and automatically generates a long_name"""
coordnames = list(da.coords)
da_stacked = da.set_index(ct=coordnames)
if len(coordnames) == 1:
#only one coordinate just rename ct to the coordinate name
da_unstacked = da_s... | 3,507 |
def test_list_ncname_max_length_3_nistxml_sv_iv_list_ncname_max_length_4_1(mode, save_output, output_format):
"""
Type list/NCName is restricted by facet maxLength with value 8.
"""
assert_bindings(
schema="nistData/list/NCName/Schema+Instance/NISTSchema-SV-IV-list-NCName-maxLength-4.xsd",
... | 3,508 |
def showSelectionInTitle(*args, **kwargs):
"""
This command causes the title of the window specified as an argument to be linked to the current file and selection.
Returns: None
"""
pass | 3,509 |
def LikeView(request, pk):
"""Function view that manages the likes and dislikes of a post"""
post = get_object_or_404(Post, id=request.POST.get('post_id'))
liked = False
if post.likes.filter(id=request.user.id).exists():
post.likes.remove(request.user)
liked = False
else:
p... | 3,510 |
def set_edge_color_mapping(table_column, table_column_values=None, colors=None, mapping_type='c', default_color=None,
style_name=None, network=None, base_url=DEFAULT_BASE_URL):
"""Map table column values to colors to set the edge color.
Args:
table_column (str): Name of Cytos... | 3,511 |
def retrieve_tape_recovery_point(TapeARN=None, GatewayARN=None):
"""
Retrieves the recovery point for the specified virtual tape. This operation is only supported in the tape gateway architecture.
A recovery point is a point in time view of a virtual tape at which all the data on the tape is consistent. If ... | 3,512 |
def weld_describe(array, weld_type, aggregations):
""" Aggregate during the same evaluation as opposed to separately as in Series.agg
Parameters
----------
array : np.ndarray or WeldObject
to aggregate on
weld_type : WeldType
of the array
aggregations : list of str
supp... | 3,513 |
def roles_required(*roles):
"""Decorator which specifies that a user must have all the specified roles.
Example::
@app.route('/dashboard')
@roles_required('admin', 'editor')
def dashboard():
return 'Dashboard'
The current user must have both the `admin` role and `editor... | 3,514 |
def get_all_forms(url):
"""Given a `url`, it returns all forms from the HTML content"""
soup = bs(requests.get(url).content, "html.parser")
return soup.find_all("form") | 3,515 |
def cal_max_len(ids, curdepth, maxdepth):
"""calculate max sequence length"""
assert curdepth <= maxdepth
if isinstance(ids[0], list):
res = max([cal_max_len(k, curdepth + 1, maxdepth) for k in ids])
else:
res = len(ids)
return res | 3,516 |
def urlencode(query, doseq=True, quote_via=quote_plus):
"""
An alternate implementation of Python's stdlib
:func:`urllib.parse.urlencode` function which accepts unicode keys and
values within the ``query`` dict/sequence; all Unicode keys and values are
first converted to UTF-8 before being used to c... | 3,517 |
def clip_action(action, action_min, action_max):
""" Truncates the entries in action to the range defined between
action_min and action_max. """
return np.clip(action, action_min, action_max) | 3,518 |
def run_delphi(pdb_file, output_directory, output_filename,
delphi_path, radius_file=None, charge_file=None, grid_size=101, surface=None, center=False):
""" Run Delphi on protein surface created by MSMS program """
# TODO: Rewrite using template string
if not os.path.isdir(output_directory):
os.... | 3,519 |
def isGray(image):
"""Return True if the image has one channel per pixel."""
return image.ndim < 3 | 3,520 |
def prophet_plot(
df,
fig,
today_index,
lookback_days=None,
predict_days=21,
outliers=list()):
"""
Plot the actual, predictions, and anomalous values
Args
----
df : pandas DataFrame
The daily time-series data set contains ds column for
... | 3,521 |
def verbose_traceroute_icmp(dest,
hops = DEFAULT_HOPS,
q = DEFAULT_QUERIES,
timeout = DEFAULT_TIMEOUT,
ttl = DEFAULT_MINTTL,
wait = DEFAULT_WAIT):
"""trace route ... | 3,522 |
def mat2img(input_matrix, index_matrix):
"""
Transforms a batch of features of matrix images in a batch of features of vector images.
Args:
input_matrix (torch.Tensor): The images with shape (batch, features, matrix.size).
index_matrix (torch.Tensor): The index matrix for the images, shape(... | 3,523 |
def _check_molecule_format(val):
"""If it seems to be zmatrix rather than xyz format we convert before returning"""
atoms = [x.strip() for x in val.split(";")]
if atoms is None or len(atoms) < 1: # pylint: disable=len-as-condition
raise QiskitNatureError("Molecule format error: " + val)
# An x... | 3,524 |
def measure_area_perimeter(mask):
"""A function that takes either a segmented image or perimeter
image as input, and calculates the length of the perimeter of a lesion."""
# Measure area: the sum of all white pixels in the mask image
area = np.sum(mask)
# Measure perimeter: first find ... | 3,525 |
def _click_up_params(user_email: str) -> dict:
"""
Load a Click Up parameters for this user.
Args:
user_email (str): Email of user making the request.
Returns:
(dict): A dict containing the elements:
'success': (Boolean) True if successful, otherwise False
'... | 3,526 |
def iset_servo_angle(angle_idx):
"""Set the servomotor angle to -90, -45, 0, 45 or 90 degrees.
"""
vals = [5, 9, 13, 17, 21]
servo.start(vals[angle_idx])
time.sleep(1.5)
servo.start(0) | 3,527 |
def mock_object(**params: Any) -> "Mock": # type: ignore # noqa
"""creates an object using params to set attributes
>>> option = mock_object(verbose=False, index=range(5))
>>> option.verbose
False
>>> option.index
[0, 1, 2, 3, 4]
"""
return type("Mock", (), params)() | 3,528 |
def get_words(message):
"""Get the normalized list of words from a message string.
This function should split a message into words, normalize them, and return
the resulting list. For splitting, you should split on spaces. For
normalization, you should convert everything to lowercase.
Args:
... | 3,529 |
def get_atomic_forces_card(name, **kwargs):
"""
Convert XML data to ATOMIC_FORCES card
:param name: Card name
:param kwargs: Dictionary with converted data from XML file
:return: List of strings
"""
try:
external_atomic_forces = kwargs['external_atomic_forces']
except KeyError:
... | 3,530 |
def hasPathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: bool
"""
if root is None:
return False
if sum - root.val == 0 and root.left is None and root.right is None:
return True
else:
return self.hasPathSum(root.left, sum - root... | 3,531 |
def _(node: IntJoin, ctx: AnnotateContext) -> BoxType:
"""All references available on either side of the Join nodes are available."""
lt = box_type(node.over)
rt = box_type(node.joinee)
t = union(lt, rt)
node.typ = t
return t | 3,532 |
def detect_global_table_updates(record):
"""This will detect DDB Global Table updates that are not relevant to application data updates. These need to be
skipped over as they are pure noise.
:param record:
:return:
"""
# This only affects MODIFY events.
if record['eventName'] == 'MODIFY'... | 3,533 |
def fix_telecined_fades(clip: vs.VideoNode, tff: bool | int | None = None,
thr: float = 2.2) -> vs.VideoNode:
"""
A filter that gives a mathematically perfect solution to fades made *after* telecining
(which made perfect IVTC impossible). This is an improved version of the Fix-Teleci... | 3,534 |
def compute_statistics(provider_slug, tile_grid=get_default_tile_grid(), filename=None):
"""
:param export_task_records: ExporTaskRecords is a list of all export tasks
:param get_group: Function to generate a group id given a DataExportProviderTask
:param tile_grid: Calculate statistics for each tile in... | 3,535 |
def compare_rdf(expected: Union[Graph, str], actual: Union[Graph, str], fmt: Optional[str] = "turtle") -> Optional[str]:
"""
Compare expected to actual, returning a string if there is a difference
:param expected: expected RDF. Can be Graph, file name, uri or text
:param actual: actual RDF. Can be Graph... | 3,536 |
def remove_empty_segments(args):
"""Removes empty segments from corpus component files.
"""
logging.info("Removing empty segments from corpus.")
corpus_iterator = CorpusIterator(args.corpus_dir, args.root_file)
for file_path in corpus_iterator.iter_annotated_files():
file_name = str(file_pat... | 3,537 |
def start_engine(engine_name, tk, context):
"""
Creates an engine and makes it the current engine.
Returns the newly created engine object. Example::
>>> import sgtk
>>> tk = sgtk.sgtk_from_path("/studio/project_root")
>>> ctx = tk.context_empty()
>>> engine = sgtk.platform.... | 3,538 |
def test_datasource():
"""Tests that default dataset on datasource is teams'"""
ds = GithubDataSource(name='mah_ds', domain='test_domain', organization='foorganization')
assert ds.dataset == 'teams' | 3,539 |
def parse_vaulttext(b_vaulttext):
"""Parse the vaulttext.
Args:
b_vaulttext: A byte str containing the vaulttext (ciphertext, salt,
crypted_hmac).
Returns:
A tuple of byte str of the ciphertext suitable for passing to a Cipher
class's decrypt() function, a byte str of the salt, and a byte str... | 3,540 |
def does_column_exist_in_db(db, table_name, col_name):
"""Checks if a specific col exists"""
col_name = col_name.lower()
query = f"pragma table_info('{table_name}');"
all_rows = []
try:
db.row_factory = sqlite3.Row # For fetching columns by name
cursor = db.cursor()
cursor.e... | 3,541 |
def check_min_time(stats, timepiece):
"""检查是否产生了新的最少用时"""
if stats.time < stats.min_time:
stats.min_time = stats.time
timepiece.prep_min_time() | 3,542 |
def make_secure_val(val):
"""Takes hashed pw and adds salt; this will be the cookie"""
return '%s|%s' % (val, hmac.new(secret, val).hexdigest()) | 3,543 |
def get_ad_contents(queryset):
"""
Contents의 queryset을 받아서 preview video가 존재하는 contents를 랜덤으로 1개 리턴
:param queryset: Contents queryset
:return: contents object
"""
contents_list = queryset.filter(preview_video__isnull=False)
max_int = contents_list.count() - 1
if max_int < 0:
ret... | 3,544 |
def Image_CanRead(*args, **kwargs):
"""
Image_CanRead(String filename) -> bool
Returns True if the image handlers can read this file.
"""
return _core_.Image_CanRead(*args, **kwargs) | 3,545 |
def create_without_source_table_privilege(self, node=None):
"""Check that user is unable to create a table without select
privilege on the source table.
"""
user_name = f"user_{getuid()}"
table_name = f"table_{getuid()}"
source_table_name = f"source_table_{getuid()}"
exitcode, message = erro... | 3,546 |
def flatten(lst):
"""Flatten a list."""
return [y for l in lst for y in flatten(l)] if isinstance(lst, (list, np.ndarray)) else [lst] | 3,547 |
def calc_mean_score(movies):
"""Helper method to calculate mean of list of Movie namedtuples,
round the mean to 1 decimal place"""
ratings = [m.score for m in movies]
mean = sum(ratings) / max(1, len(ratings))
return round(mean, 1) | 3,548 |
def srun(hosts, cmd, srun_params=None):
"""Run srun cmd on slurm partition.
Args:
hosts (str): hosts to allocate
cmd (str): cmdline to execute
srun_params(dict): additional params for srun
Returns:
CmdResult: object containing the result (exit status, stdout, etc.) of
... | 3,549 |
def COSclustering(key, emb, oracle_num_speakers=None, max_num_speaker=8, MIN_SAMPLES=6):
"""
input:
key (str): speaker uniq name
emb (np array): speaker embedding
oracle_num_speaker (int or None): oracle number of speakers if known else None
max_num_speakers (int): maximum number of clusters to ... | 3,550 |
def fill_linear_layer(layer, weight, bias):
"""Load weight and bias to a given layer from onnx format."""
with torch.no_grad():
layer.weight.data = torch.from_numpy(onnx.numpy_helper.to_array(weight))
if bias is not None:
layer.bias.data = torch.from_numpy(onnx.numpy_helper.to_array(... | 3,551 |
def gauss_distance(sample_set, query_set, unlabeled_set=None):
""" (experimental) function to try different approaches to model prototypes as gaussians
Args:
sample_set: features extracted from the sample set
query_set: features extracted from the query set
query_set: features extracted ... | 3,552 |
def make_mps_left(mps,truncate_mbd=1e100,split_s=False):
"""
Put an mps into left canonical form
Args:
mps : list of mps tensors
The MPS stored as a list of mps tensors
Kwargs:
truncate_mbd : int
The maximum bond dimension to which the
mps shoul... | 3,553 |
def word_after(line, word):
"""'a black sheep', 'black' -> 'sheep'"""
return line.split(word, 1)[-1].split(' ', 1)[0] | 3,554 |
def domain_in_domain(subdomain, domain):
"""Returns try if subdomain is a sub-domain of domain.
subdomain
A *reversed* list of strings returned by :func:`split_domain`
domain
A *reversed* list of strings as returned by :func:`split_domain`
For example::
>>> domain_in_domain([... | 3,555 |
def polygon_from_boundary(xs, ys, xmin=0.0, xmax=1.0, ymin=0.0, ymax=1.0, xtol=0.0):
"""Polygon within box left of boundary given by (xs, ys)
xs, ys: coordinates of boundary (ys ordered increasingly)
"""
xs = np.asarray(xs)
ys = np.asarray(ys)
xs[xs > xmax-xtol] = xmax
xs[xs < xmin+xt... | 3,556 |
def print_head(df_in):
"""Print head of data set
Parameters
----------
df_in : pd.DataFrame
Dataframe
Returns
-------
head of dataset, shape of dataset
"""
df = df_in.head()
display(df)
print('Dataset shape: ', df_in.shape) | 3,557 |
def type_conversion(self, node="clickhouse1"):
"""Check the type conversion operations with DateTime64.
Cast can be set as Requirement thereby as the module
tests exactly what CAST does.
"""
self.context.node = self.context.cluster.node(node)
for scenario in loads(current_module(), Scenario):
... | 3,558 |
def is_degenerate(op, tol=1e-12):
"""Check if operator has any degenerate eigenvalues, determined relative
to mean spacing of all eigenvalues.
Parameters
----------
op : operator or 1d-array
Operator or assumed eigenvalues to check degeneracy for.
tol : float
How much closer tha... | 3,559 |
def _get_skip_props(mo, include_operational=False, version_filter=True):
"""
Internal function to skip mo property if not to be considered for sync.
"""
skip_props = []
for prop in mo.prop_meta:
mo_property_meta = mo.prop_meta[prop]
if mo_property_meta is None:
continue
... | 3,560 |
def generate_split_problem():
"""Generates a 'Split' problem configuration.
Returns (environment, robot, start configuration, goal configuration)."""
walls = [rectangle(0, 400, 0, 10), rectangle(0, 400, 290, 300),
rectangle(0, 10, 0, 300), rectangle(390, 400, 0, 300),
rectangle(18... | 3,561 |
def problem_generator(difficulty=3):
"""
This function generates mathematical expressions as string. It is not very
smart and will generate expressions that have answers the lex function
cannot accept.
"""
operators = ["/", "*", "+", "-"]
numeric_lim = difficulty * 7
output = ""
... | 3,562 |
async def receive_message_and_update_deployment(app: FastAPI) -> None:
"""
Receives messages from the deployment status update queue and updates the status for
the associated resource in the state store.
Args:
app ([FastAPI]): Handle to the currently running app
"""
receive_message_gen =... | 3,563 |
def logical_factory_dimensions(params: Parameters
) -> Tuple[int, int, float]:
"""Determine the width, height, depth of the magic state factory."""
if params.use_t_t_distillation:
return 12*2, 8*2, 6 # Four T2 factories
l1_distance = params.l1_distance
l2_distanc... | 3,564 |
def parse_list_or_range(arg):
"""
Parses a string that represents either an integer or a range in
the notation ``<start>:<step>:<stop>``.
Parameters
----------
arg : :obj:`str`
Integer or range string.
Returns
-------
int or :obj:`list` of int
Raises
--... | 3,565 |
def data():
"""
Data providing function:
This function is separated from create_model() so that hyperopt
won't reload data for each evaluation run.
"""
d_file = 'data/zinc_100k.h5'
data_train, data_test, props_train, props_test, tokens = utils.load_dataset(d_file, "TRANSFORMER", True)
... | 3,566 |
def make_commands(
script: str,
base_args: Optional[Dict[str, Any]] = None,
common_hyper_args: Optional[Dict[str, List[Any]]] = None,
algorithm_hyper_args: Optional[Dict[str, List[Any]]] = None,
) -> List[str]:
"""Generate command to run.
It will generate a list of commands to be use with the r... | 3,567 |
def dummy_lockfile_path(
dummy_lockfile_proto: lockfile_pb2.LockFile,
) -> pathlib.Path:
"""Yield a path to a lockfile proto."""
with tempfile.TemporaryDirectory() as d:
pbutil.ToFile(dummy_lockfile_proto, pathlib.Path(d) / "LOCK.pbtxt")
yield pathlib.Path(d) / "LOCK.pbtxt" | 3,568 |
def mongos_program(logger, job_num, executable=None, process_kwargs=None, mongos_options=None): # pylint: disable=too-many-arguments
"""Return a Process instance that starts a mongos with arguments constructed from 'kwargs'."""
args = [executable]
mongos_options = mongos_options.copy()
if "port" not ... | 3,569 |
def markerBeings():
"""标记众生区块
Content-Type: application/json
{
"token":"",
"block_id":""
}
返回 json
{
"is_success":bool,
"data":
"""
try:
info = request.get_json()
# 验证token
token = info["token"]
i... | 3,570 |
def get_charges_with_openff(mol):
"""Starting from a openff molecule returns atomic charges
If the charges are already defined will return them without
change
I not will calculate am1bcc charges
Parameters
------------
mol : openff.toolkit.topology.Molecule
Examples
---------
... | 3,571 |
def parse_mdout(file):
"""
Return energies from an AMBER ``mdout` file.
Parameters
----------
file : os.PathLike
Name of Amber output file
Returns
-------
energies : dict
A dictionary containing VDW, electrostatic, bond, angle, dihedral, V14, E14, and total energy.
... | 3,572 |
def import_face_recognition():
""" Import the face_recognition module only when it is required """
global face_recognition
if face_recognition is None:
import face_recognition | 3,573 |
def aa_spectrum(
G: nx.Graph, aggregation_type: Optional[List[str]] = None
) -> nx.Graph:
"""
Calculate the spectrum descriptors of 3-mers for a given protein. Contains the composition values of 8000 3-mers
:param G: Protein Graph to featurise
:type G: nx.Graph
:param aggregation_type: Aggregat... | 3,574 |
def dumppickle(obj, fname, protocol=-1):
"""
Pickle object `obj` to file `fname`.
"""
with open(fname, 'wb') as fout: # 'b' for binary, needed on Windows
pickle.dump(obj, fout, protocol=protocol) | 3,575 |
def get_click_data(api, campaign_id):
"""Return a list of all clicks for a given campaign."""
rawEvents = api.campaigns.get(campaign_id).as_dict()["timeline"]
clicks = list() # Holds list of all users that clicked.
for rawEvent in rawEvents:
if rawEvent["message"] == "Clicked Link":
... | 3,576 |
def test_line_2(style_checker):
"""style_checker on python file with No_Style_Check comment on line 2.
The file has PEP8 errors, but those should be ignored thanks
to the No_Style_Check comment.
"""
p = style_checker.run_style_checker('/trunk/module', 'src/line_2.py')
style_checker.assertEqual(... | 3,577 |
def multi_label_column_to_binary_columns(data_frame: pd.DataFrame, column: str):
"""
assuming that the column contains array objects,
returns a new dataframe with binary columns (True/False)
indicating presence of each distinct array element.
:data_frame: the pandas DataFrame
... | 3,578 |
def subrepositories_changed(all_if_master: bool = False) -> List[str]: # pragma: no cover
"""
Returns a list of the final name components of subrepositories that contain files that are different between the
master branch and the current branch. Subrepositories are defined as the directories immediately und... | 3,579 |
def show_landscape(adata,
Xgrid,
Ygrid,
Zgrid,
basis="umap",
save_show_or_return='show',
save_kwargs={},
):
"""Plot the quasi-potential landscape.
Parameters
----------
... | 3,580 |
def _GetBuilderPlatforms(builders, waterfall):
"""Get a list of PerfBuilder objects for the given builders or waterfall.
Otherwise, just return all platforms.
"""
if builders:
return {b for b in bot_platforms.ALL_PLATFORMS if b.name in
builders}
elif waterfall == 'perf':
return bot_pl... | 3,581 |
def meeting_guide(context):
"""
Display the ReactJS drive Meeting Guide list.
"""
settings = get_meeting_guide_settings()
json_meeting_guide_settings = json_dumps(settings)
return {
"meeting_guide_settings": json_meeting_guide_settings,
"mapbox_key": settings["map"]["key"... | 3,582 |
def generate_input_fn(file_path, shuffle, batch_size, num_epochs):
"""Generates a data input function.
Args:
file_path: Path to the data.
shuffle: Boolean flag specifying if data should be shuffled.
batch_size: Number of records to be read at a time.
num_epochs: Number of times ... | 3,583 |
def amp_phase_to_complex(lookup_table):
"""
This constructs the function to convert from AMP8I_PHS8I format data to complex64 data.
Parameters
----------
lookup_table : numpy.ndarray
Returns
-------
callable
"""
_validate_lookup(lookup_table)
def converter(data):
... | 3,584 |
def combine_aqs_cmaq(model, obs):
"""Short summary.
Parameters
----------
model : type
Description of parameter `model`.
obs : type
Description of parameter `obs`.
Returns
-------
type
Description of returned object.
"""
g = obs.df.groupby('Species')
... | 3,585 |
def bbknn_pca_matrix(
pca,
batch_list,
neighbors_within_batch=3,
n_pcs=50,
trim=None,
approx=True,
n_trees=10,
use_faiss=True,
metric="angular",
set_op_mix_ratio=1,
local_connectivity=1,
):
"""
Scanpy-independent BBKNN variant that runs on a PCA matrix and list of per... | 3,586 |
def autoinstall(ctx, **kwargs):
"""
install a system using an autofile template
"""
bg_flag = kwargs.pop('bg')
request = {'action_type': 'SUBMIT', 'job_type': 'autoinstall'}
for key in ('profile', 'template', 'verbosity'):
if kwargs[key] is None:
kwargs.pop(key)
if not kw... | 3,587 |
async def test_automatic_failover_after_leader_issue(ops_test: OpsTest) -> None:
"""Tests that an automatic failover is triggered after an issue happens in the leader."""
# Find the current primary unit.
primary = await get_primary(ops_test)
# Crash PostgreSQL by removing the data directory.
await ... | 3,588 |
def test_write_rows(tmpdir):
"""Test writing rows to a CSV files."""
filename = os.path.join(tmpdir, 'out.csv')
consumer = Write(file=CSVFile(filename, header=['A', 'B', 'C']))\
.open(['A', 'B', 'C'])
consumer.consume(3, [1, 2, 3])
consumer.consume(2, [4, 5, 6])
consumer.consume(1, [7, 8... | 3,589 |
def _sanitize_anndata(adata: AnnData) -> None:
"""Sanitization and sanity checks on IR-anndata object.
Should be executed by every read_xxx function"""
assert (
len(adata.X.shape) == 2
), "X needs to have dimensions, otherwise concat doesn't work. "
# Pending updates to anndata to properly ... | 3,590 |
def read_1d_spikes(filename):
"""Reads one dimensional binary spike file and returns a td_event event.
The binary file is encoded as follows:
* Each spike event is represented by a 40 bit number.
* First 16 bits (bits 39-24) represent the neuronID.
* Bit 23 represents the sign of spike ... | 3,591 |
def _parse_step_log(lines):
"""Parse the syslog from the ``hadoop jar`` command.
Returns a dictionary which potentially contains the following keys:
application_id: a string like 'application_1449857544442_0002'. Only
set on YARN
counters: a map from counter group -> counter -> amount, or None... | 3,592 |
def is_regex(regex, invert=False):
"""Test that value matches the given regex.
The regular expression is searched against the value, so a match
in the middle of the value will succeed. To specifically match
the beginning or the whole regex, use anchor characters. If
invert is true, then matching ... | 3,593 |
def get_obj(obj):
"""Opens the url of `app_obj`, builds the object from the page and
returns it.
"""
open_obj(obj)
return internal_ui_operations.build_obj(obj) | 3,594 |
def process(frame):
"""Process initial frame and tag recognized objects."""
# 1. Convert initial frame to grayscale
grayframe = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# For every model:
for model, color, parameters in (
(MODEL_FACE, (255, 255, 0), {'scaleFactor': 1.1, 'minNeighbors': ... | 3,595 |
def tzoffset():
"""UTC to America/New_York offset."""
return datetime.timedelta(hours=5) | 3,596 |
def ssh(instance, command, plain=None, extra=None, command_args=None):
"""Run ssh command.
Parameters:
instance(MechInstance): a mech instance
command(str): command to execute (ex: 'chmod +x /tmp/file')
plain(bool): use user/pass auth
extra(str): arguments to pass to ... | 3,597 |
def KICmag(koi,band):
"""
Returns the apparent magnitude of given KOI star in given band. returns KICmags(koi)[band]
"""
return KICmags(koi)[band] | 3,598 |
def list_to_decimal(nums: List[int]) -> int:
"""Accept a list of positive integers in the range(0, 10)
and return a integer where each int of the given list represents
decimal place values from first element to last. E.g
[1,7,5] => 175
[0,3,1,2] => 312
Place values are 10**n w... | 3,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.