content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def _registry_munger(desired_registries_dict, current_registries_json_dict):
"""Generator for iterating through the union of the desired & current registry configurations.
Yields a tuple containing the registry name, desired configuration, & current configuration."""
for key in desired_registries_dict.keys... | 5,342,200 |
def hdi_of_mcmc(sample_vec, cred_mass=0.95):
"""
Highest density interval of sample.
"""
assert len(sample_vec), 'need points to find HDI'
sorted_pts = np.sort(sample_vec)
ci_idx_inc = int(np.floor(cred_mass * len(sorted_pts)))
n_cis = len(sorted_pts) - ci_idx_inc
ci_width = sorted_pts... | 5,342,201 |
def compare_AlphaFz(sq_amp,sq_amp_baseline):
"""
Compare the baseline alpha squared amplitude with that of a single epoch.
Parameters
----------
sq_amp: float
Alpha squared amplitude (Fz) from a single epoch
cnt_baseline: float
Baseline alpha squared amplitude ... | 5,342,202 |
def get_filtered_acc_gas(database_year, start_year, end_year):
"""Returns gas avoided costs data
Parameters
----------
database_year: str
The year corresponding to the database that contains the avoided costs data.
Requires that year's database to have already been downloaded
us... | 5,342,203 |
def test_datetime_dtype_conversion(test_df):
"""Test converting dates to datetime dtype."""
correct_dtype = np.dtype("<M8[ns]")
date_column_type = test_df.adni.standard_dates()["Acq Date"].dtype
assert correct_dtype == date_column_type | 5,342,204 |
def enable_object_storage_access(application_name, instance_id, region,
patterns):
"""
Enable object storage (S3) read-only access for the given instance to
resources matching the given patterns.
"""
log('Enabling object storage (S3) read for instance {} of '
... | 5,342,205 |
def FindZ(outContoursPolygons, in_raster, tempWs, sessid):
""" Use the point within the polygon to determine the low and high
sides of the polygon"""
outEVT = os.path.join(tempWs,'outEVT' + sessid)
outEVTjoinedLayer = os.path.join(tempWs,'outEVTjoinedLayer')
outPolygPoints = os.path.join(tempWs,'outPolygPoints' +... | 5,342,206 |
def emr_app(config_name):
""" Application Factories
"""
app = Flask(__name__, instance_relative_config=True)
app.config.from_object(app_config[config_name])
handler = RotatingFileHandler('emr.log')
handler.setLevel(logging.INFO)
app.logger.addHandler(handler)
app.wsgi_app = ProxyFix(ap... | 5,342,207 |
def _split_datetime_from_line(line):
"""Docker timestamps are in RFC3339 format: 2015-08-03T09:12:43.143757463Z, with everything up to the first space
being the timestamp.
"""
log_line = line
dt = datetime.datetime.utcnow()
pos = line.find(" ")
if pos > 0:
dt = scalyr_util.rfc3339_to... | 5,342,208 |
def set_signal_winch(handler):
""" return the old signal handler """
global winch_handler
old_handler=winch_handler
winch_handler=handler
return old_handler | 5,342,209 |
def entry_text_to_file(
args: argparse.Namespace,
entry: Dict) -> Tuple[Optional[Text], Optional[Text]]:
"""Extract the entry content and write it to the proper file.
Return the wrapped HTML"""
filename = safe_filename(entry.get('title', str(uuid.uuid4())))
html_data = create_html(entr... | 5,342,210 |
def visdom_loss_handler(modules_dict, model_name):
"""
Attaches plots and metrics to trainer.
This handler creates or connects to an environment on a running Visdom dashboard and creates a line plot that tracks the loss function of a
training loop as a function of the number of iterations. This can be a... | 5,342,211 |
def MolToQPixmap(mol, size=(300, 300), kekulize=True, wedgeBonds=True, fitImage=False, options=None,
**kwargs):
""" Generates a drawing of a molecule on a Qt QPixmap
"""
if not mol:
raise ValueError('Null molecule provided')
from rdkit.Chem.Draw.qtCanvas import Canvas
canvas = Canvas(si... | 5,342,212 |
def _unpad(string: str) -> str:
"""Un-pad string."""
return string[: -ord(string[len(string) - 1 :])] | 5,342,213 |
def copy_dir_to_target(source_directory: Path, destination_directory: Path) -> bool:
"""
Args:
source_directory: a folder to copy
destination_directory: the parent directory to copy source_directory into
Returns: True if copy was successful, False otherwise
"""
if source_directory... | 5,342,214 |
def vlanlist_to_config(vlan_list, first_line_len=48, other_line_len=44, min_grouping_size=3):
"""Given a List of VLANs, build the IOS-like vlan list of configurations.
Args:
vlan_list (list): Unsorted list of vlan integers.
first_line_len (int, optional): The maximum length of the line of the f... | 5,342,215 |
def check_type(instance=None, classinfo=None):
"""Raise an exception if object is not an instance of classinfo."""
if not isinstance(instance, classinfo):
raise TypeCheckError(
"expected an instance of {0}, got {1}".format(classinfo, instance)
) | 5,342,216 |
def plot_forecasts(
data: pd.DataFrame,
forecasters: Iterable[str],
plots_dir: str = "./plots",
use_logx: bool = True,
figsize: Tuple[int, int] = (12, 5),
linewidth: float = 2,
):
"""Plot forecasts along with the dataset.
Also plots ``data`` or ``true_probs``, if... | 5,342,217 |
def test_part_1():
"""
Result should be: 40
"""
result = part_1(TEST_INPUT_FILE)
assert result == 40 | 5,342,218 |
async def process_challenge(bot:NoneBot, ctx:Context_T, ch:ParseResult):
"""
处理一条报刀 需要保证challenge['flag']的正确性
"""
bm = BattleMaster(ctx['group_id'])
now = datetime.now() - timedelta(days=ch.get('dayoffset', 0))
clan = _check_clan(bm)
mem = _check_member(bm, ch.uid, ch.alt)
cur_round, c... | 5,342,219 |
def get_next_url(bundle: dict) -> Optional[str]:
"""
Returns the URL for the next page of a paginated ``bundle``.
>>> bundle = {
... 'link': [
... {'relation': 'self', 'url': 'https://example.com/page/2'},
... {'relation': 'next', 'url': 'https://example.com/page/3'},
..... | 5,342,220 |
def convert_sklearn_variance_threshold(operator, device, extra_config):
"""
Converter for `sklearn.feature_selection.VarianceThreshold`.
Args:
operator: An operator wrapping a `sklearn.feature_selection.VarianceThreshold` model
device: String defining the type of device the converted operat... | 5,342,221 |
def test_crop_generator(input_path, batch_size=1, mode="test", num_classes =6, epsilon = 0, resize_params = (224, 224), do_shuffle=True):
"""
Simple data generator that reads all images based on mode, picks up corresponding time series, returns entire list
"""
data_path = os.path.join(input_path, mode)... | 5,342,222 |
def gradient(okay=0.25, warn=0.75, fail=1.0, count=32):
"""
Generate a gradient of *count* steps representing values between 0.0 and
1.0. Until the *okay* value, the gradient is pure green. Until the *warn*
value it gradually fades to orange. As the value approaches *fail*, it
fades to red, and abov... | 5,342,223 |
def query_merchant_users(bc_app, merchant=None, start_time=None, end_time=None):
"""
query merchant users
:param bc_app: beecloud.entity.BCApp
:param merchant: merchant account, if not passed, only users associated with app will be returned
:param start_time: if passed, only users registered after i... | 5,342,224 |
def getUIQM(x):
"""
Function to return UIQM to be called from other programs
x: image
"""
x = x.astype(np.float32)
### UCIQE: https://ieeexplore.ieee.org/abstract/document/7300447
#c1 = 0.4680; c2 = 0.2745; c3 = 0.2576
### UIQM https://ieeexplore.ieee.org/abstract/document/7305804
... | 5,342,225 |
def cart2spher(x, y, z):
"""Cartesian to Spherical coordinate conversion."""
hxy = np.hypot(x, y)
rho = np.hypot(hxy, z)
#if not rho:
# return np.array([0,0,0])
theta = np.arctan2(hxy, z)
phi = np.arctan2(y, x)
return rho, theta, phi | 5,342,226 |
def get_mean_and_stdv(dataset):
"""return means and standard
deviations along 0th axis of tensor"""
means = dataset.mean(0)
stdvs = dataset.std(0)
return means, stdvs | 5,342,227 |
async def test_host_already_configured(hass, auth_error):
"""Test host already configured."""
entry = MockConfigEntry(domain=mikrotik.DOMAIN, data=DEMO_CONFIG_ENTRY)
entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
mikrotik.DOMAIN, context={"source": "user"}
)
... | 5,342,228 |
def create_incident(session: RemedySession, incident_request: dict) -> None:
"""Create Remedy incident and modify status if required"""
return_fields = ["Incident Number", "Request ID"]
incident_data = incident_request.get("values", {})
# logging.info(json.dumps(incident_request, indent=4))
# Creat... | 5,342,229 |
def getBuildRequirements():
"""
Returns a list of essential packages needed for a minimalistic
software installation tree (SIT).
Opposed to getMinRequirements() this contains everything needed to
build software packages.
"""
from ToolBOSCore.Settings.ToolBOSConf import getCo... | 5,342,230 |
def nms_3d(boxes, scores, nms_threshold):
"""
包装一下nms_gpu,该函数接收的数据维度是y1,x1,y2,x2,z1,z2 ,sores
:param boxes: tensor [n,(y1,x1,z1,y2,x2,z2)]
:param scores: tensor [n]
:param nms_threshold: 浮点标量
:return: keep: nms后保留的索引 tensor [m]
"""
# [n,(y1,x1,z1,y2,x2,z2)] => [n,(y1,x1,y2,x2,z1,z2 ,sore... | 5,342,231 |
def report_install_status(ctx, op_id):
"""
:param ctx: CSM Context object
:param op_id: operational ID
Peeks into the install log to see if the install operation is successful or not
"""
failed_oper = r'Install operation {} aborted'.format(op_id)
output = ctx.send("show install log {} detail... | 5,342,232 |
def spltime(tseconds):
""" This gets the time in hours, mins and seconds """
hours = tseconds // 3600
minutes = int(tseconds / 60) % 60
seconds = tseconds % 60
return hours, minutes, seconds | 5,342,233 |
def create_test_player_data(username: str):
"""
Creates all data in database for test users to be able to fight in battle.
Creates test user's deck and all data needed to create deck.
:param username: Test player username, must be unique.
:return: None
"""
# Create test User
test_user ... | 5,342,234 |
def show_many_wrongs_mask(truths,
preds) -> None:
"""
Shows all true/wrong mask pairs.
TODO: Will have to create a limit / range otherwise it will be too big.
:return: None. Just shows image.
"""
assert len(truths) == len(preds) # Make sure same number of images in... | 5,342,235 |
def _getShortName(filePath, classPath):
"""Returns the shortest reference to a class within a file.
Args:
filePath: file path relative to the library root path (e.g., `Buildings/package.mo`).
classPath: full library path of the class to be shortened (e.g., `Buildings.Class`).
"""
pos =... | 5,342,236 |
def mine():
"""
This function will try to mine a new block by joining the negotiation process.
If we are the winner address, we will check the negotiation winner of the neighbour nodes, to grant that no node
has a different winner address.
"""
if blockchain is not None:
last_block = bloc... | 5,342,237 |
def test_local_optimizer_commutable_circuit_U_example_4(U):
"""Us shouldn't merge because they are operating on different qubits."""
local_optimizer = _optimize.LocalOptimizer(m=10)
backend = DummyEngine(save_commands=True)
eng = MainEngine(backend=backend, engine_list=[local_optimizer])
qb0 = eng.a... | 5,342,238 |
def test_user_create_token_view(client, user_data):
""" Teste na view que gera um token JWT """
user = get_user_model().objects.create_user(**user_data)
assert user.email == 'admin@email.com'
url = reverse('authentication:obtain_token')
data = {"email": f"{user_data['email']}", "password": f"{user_data['passw... | 5,342,239 |
def getaddrinfo(host, port, family=0, socktype=0, proto=0, flags=0):
"""
Resolve host and port into list of address info entries.
Translate the host/port argument into a sequence of 5-tuples that contain
all the necessary arguments for creating a socket connected to that service.
host is a domain n... | 5,342,240 |
def export_to_colmap_points3d_txt(colmap_points3d_filepath: str,
colmap_image_ids: Dict[str, int],
points3d: kapture.Points3d = None,
observations: kapture.Observations = None) -> None:
"""
Exports to colmap po... | 5,342,241 |
def create_test_data():
"""Load unit test data in the dev/local environment. Delete all existing test data as a first step."""
execute_script(db.session, 'test_data/postgres_test_reset.sql')
execute_script(db.session, 'test_data/postgres_create_first.sql')
filenames = os.listdir(os.path.join(os.getcwd()... | 5,342,242 |
def atomic_log(using=None):
"""
Decorator that surrounds atomic block, ensures that logged output requests will be stored inside database in case
of DB rollback
"""
if callable(using):
return AtomicLog(DEFAULT_DB_ALIAS)(using)
else:
return AtomicLog(using) | 5,342,243 |
def _readConfigFile(config_file, verbose):
"""Read configuration file options into a dictionary."""
if not os.path.exists(config_file):
raise RuntimeError("Couldn't open configuration file '%s'." % config_file)
try:
import imp
conf = {}
configmodule = imp.load_... | 5,342,244 |
def test_labware_rows_by_name(
decoy: Decoy,
engine_client: ProtocolEngineClient,
subject: Labware,
) -> None:
"""It should return the labware's wells as dictionary of rows."""
decoy.when(
engine_client.state.labware.get_wells(labware_id="labware-id")
).then_return(["A1", "A2"])
dec... | 5,342,245 |
def run_street_queries(es, params_list, queries, formats):
"""Punto de entrada del módulo 'street.py'. Toma una lista de consultas de
calles y las ejecuta, devolviendo los resultados QueryResult.
Args:
es (Elasticsearch): Conexión a Elasticsearch.
params_list (list): Lista de ParametersPars... | 5,342,246 |
def draw_text(text, bgcolor, plt_ax, text_plt):
"""
Render the text
:param str text: text to render
:param str bgcolor: backgroundcolor used to render text
:param matplotlib.axes.Axes plt_ax: figure sub plot instance
:param matplotlib.text.Text text_plt: plot of text
:return matplotlib.text.... | 5,342,247 |
def compute_95confidence_intervals(
record, episode, num_episodes, store_accuracies, metrics=["AccuracyNovel",]
):
"""Computes the 95% confidence interval for the novel class accuracy."""
if episode == 0:
store_accuracies = {metric: [] for metric in metrics}
for metric in metrics:
... | 5,342,248 |
def _pytype(dtype):
""" return a python type for a numpy object """
if dtype in ("int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64"):
return int
elif dtype in ("float16", "float32", "float64", "float128"):
return float
elif dtype in ("complex64", "complex128", "comp... | 5,342,249 |
def pca(x, output_dim, dtype, name=None):
"""Computes pca on the dataset using biased covariance.
The pca analyzer computes output_dim orthonormal vectors that capture
directions/axes corresponding to the highest variances in the input vectors of
x. The output vectors are returned as a rank-2 tensor with shape... | 5,342,250 |
def preorder(root: Node):
"""
Pre-order traversal visits root node, left subtree, right subtree.
>>> preorder(make_tree())
[1, 2, 4, 5, 3]
"""
return [root.data] + preorder(root.left) + preorder(root.right) if root else [] | 5,342,251 |
def main(argv=None):
"""Search a Cheshire3 database based on query in argv."""
global argparser, session, server, db
if argv is None:
args = argparser.parse_args()
else:
args = argparser.parse_args(argv)
session = Session()
server = SimpleServer(session, args.serverconfig)
if... | 5,342,252 |
def generate_uuid() -> str:
"""
Generate UUIDs to use as `sim.base_models.Node` and `sim.base_models.Item` ids.
"""
return str(uuid.uuid4()) | 5,342,253 |
def new_key_generator():
"""Generator of new keys.
Yields: str
"""
def _rnd_key():
return ''.join(nchoice(key_chars, size=next(key_lengths)))
while True:
key = _rnd_key()
while key in storage:
key = _rnd_key()
yield key | 5,342,254 |
def _style_mixture(which_styles, num_styles):
"""Returns a 1-D array mapping style indexes to weights."""
if not isinstance(which_styles, dict):
raise ValueError('Style mixture must be a dictionary.')
mixture = np.zeros([num_styles], dtype=np.float32)
for index in which_styles:
mixture[index] = which_styles[i... | 5,342,255 |
def merge_dicts(a, b):
"""combine two dictionaries, assuming components are arrays"""
result = a
for k, v in b.items():
if k not in result:
result[k] = []
result[k].extend(v)
return result | 5,342,256 |
def test_salesforce_origin_aggregate(sdc_builder, sdc_executor, salesforce):
"""Create data using Salesforce client and then check if Salesforce origin
retrieves correct aggregate data using snapshot.
The pipeline looks like:
salesforce_origin >> trash
Args:
sdc_builder (:py:class:`str... | 5,342,257 |
def parser_content_labelling_Descriptor(data,i,length,end):
"""\
parser_content_labelling_Descriptor(data,i,length,end) -> dict(parsed descriptor elements).
This descriptor is not parsed at the moment. The dict returned is:
{ "type": "content_labelling", "contents" : unparsed_descriptor_contents... | 5,342,258 |
def is_norm(modules):
"""Check if is one of the norms."""
if isinstance(modules, (_BatchNorm, )):
return True
return False | 5,342,259 |
def scheduler(system = system()):
"""Job scheduler for OLCF system."""
if not is_olcf_system(system):
raise RuntimeError('unknown system (' + system + ')')
return _system_params[system].scheduler | 5,342,260 |
def simple_decoder_fn_inference(output_fn, encoder_state, embeddings,
start_of_sequence_id, end_of_sequence_id,
maximum_length, num_decoder_symbols,
dtype=dtypes.int32, name=None):
""" Simple decoder function for a sequenc... | 5,342,261 |
def listdir(path):
"""listdir(path) -> list_of_strings
Return a list containing the names of the entries in the directory.
path: path of directory to list
The list is in arbitrary order. It does not include the special
entries '.' and '..' even if they are present in the directory.
"""
... | 5,342,262 |
def get_scripts_folder():
"""
return data folder to use for future processing
"""
return (pathlib.Path(__file__).parent.parent) | 5,342,263 |
def main(
workdir: Path = typer.Argument(".", help="a directory path for working directory"),
url: Optional[str] = typer.Option(None, help="a download URL"),
directory: Path = typer.Option(None, help="a directory path for test cases"),
no_store: bool = typer.Option(False, help="testcases is shown but no... | 5,342,264 |
def preresnet110(**kwargs):
"""Constructs a PreResNet-110 model.
"""
model = PreResNet(Bottleneck, [18, 18, 18], **kwargs)
return model | 5,342,265 |
def if_action(hass, config):
""" Wraps action method with state based condition. """
value_template = config.get(CONF_VALUE_TEMPLATE)
if value_template is None:
_LOGGER.error("Missing configuration key %s", CONF_VALUE_TEMPLATE)
return False
return lambda: _check_template(hass, value_t... | 5,342,266 |
def test():
"""Module (003)"""
config = terrascript.Terrascript()
config += terrascript.aws.aws(access_key='ACCESS_KEY_HERE',
secret_key='SECRET_KEY_HERE',
region='us-east-1')
config += terrascript.Module('vpc',
... | 5,342,267 |
def get_indy_cli_command_output(output: str, match: str,
return_line_offset: int = 1, remove_ansi_escape_sequences: bool = True,
multi: bool = False) -> Union[List[str],str]:
"""
Get the output for a specific indy cli command from STDOUT captured calling
indy-cli from python.
:param output: STD... | 5,342,268 |
def reports():
"""Returns all reports in the system"""
reports = crud.report.get_reports()
return reports | 5,342,269 |
def test_basic():
"""
Ensure basic decoding works
"""
assert_equal("test", convert_base64(base64.b64encode(b"test"))) | 5,342,270 |
async def test_adding_and_removing_unsupported_reason(coresys: CoreSys):
"""Test adding and removing unsupported reason."""
coresys.core.state = CoreState.RUNNING
assert UnsupportedReason.NETWORK_MANAGER not in coresys.resolution.unsupported
with patch(
"supervisor.resolution.evaluations.networ... | 5,342,271 |
def md_to_rst(s, fname='?'):
"""
Return reStructuredText equiv string contents of Markdown string.
If conversion (via 'pandoc' cmdline) fails, returns raw Markdown.
Requires pandoc system utility: http://johnmacfarlane.net/pandoc/
Optional fname arg used only for logging/error message.
"""
... | 5,342,272 |
def parse_signature(signature):
"""
Parses one signature
:param signature: stanc3 function signature
:return: return type, fucntion name and list of function argument types
"""
return_type, rest = signature.split(" ", 1)
function_name, rest = rest.split("(", 1)
args = re.findall(r"(?:[(]... | 5,342,273 |
def logger(context, name):
"""Get PySpark configured logger
Args:
context: SparkContext
name (str): Name of the logger (category)
Returns:
Logger instance
"""
# TODO: add ccdc version to name
return context._jvm.org.apache.log4j.LogManager.getLogger(name) | 5,342,274 |
def gspan_to_eden(input, options=dict()):
"""Take a string list in the extended gSpan format and yields NetworkX graphs.
Args:
input: data source, can be a list of strings, a file name or a url
Returns:
NetworkX graph generator
Raises:
Exception: if a graph is empty
"""
... | 5,342,275 |
def compute_fps(model, shape, epoch=100, device=None):
"""
frames per second
:param shape: 输入数据大小
"""
total_time = 0.0
if device:
model = model.to(device)
for i in range(epoch):
data = torch.randn(shape)
if device:
data = data.to(device)
start = ... | 5,342,276 |
def onboarding_ml_app_patterns_post(ml_app_pattern): # noqa: E501
"""Create a new MLApp pattern
# noqa: E501
:param ml_app_pattern: MLApp pattern detail description
:type ml_app_pattern: dict | bytes
:rtype: MLAppPattern
"""
if connexion.request.is_json:
ml_app_pattern = MLAppPa... | 5,342,277 |
def get_stats(ns_profnum, clear=False, **kwargs):
""""
Returns and optionally clears the Polyglot-to-ISY stats
:param ns_profnum: Node Server ID (for future use)
:param clear: optional, zero out stats if True
"""
global SLOCK, STATS
SLOCK.acquire()
st = STATS
if clear:
STATS[... | 5,342,278 |
def test_ffmpeg():
""" stream to icecast """
input_url = TestUrl.ro1
password = input("Icecast password: ")
icecast_url = f"icecast://source:{password}@173.249.6.236:8000/babyfoon"
content_type = "-content_type audio/mpeg -f mp3"
bitrate = "-b:a 64K -minrate 64K -maxrate 64K -bufsize 64K"
# ... | 5,342,279 |
def read_log_json():
""" Get all log documents/records from MondoDB """
limit = int(demisto.args().get('limit'))
# Point to all the documents
cursor = COLLECTION.find({}, {'_id': False}).limit(limit)
# Create an empty log list
entries = []
# Iterate through those documents
if cursor is n... | 5,342,280 |
def add_parser(subp, raw):
"""Add a parser to the main subparser. """
tmpp = subp.add_parser('add', help='add an excentury project',
formatter_class=raw,
description=textwrap.dedent(DESC))
tmpp.add_argument('path', type=str,
help='p... | 5,342,281 |
def gen_time_plot_w_tracking(trialdata, no_titles=False, plot_font=PLOT_FONT):
"""Generate time series plot of ground truth and tracked force, sEMG, and
ultrasound data.
Args:
trialdata (dataobj.TrialData): object containing data to be plotted
no_titles (bool): whether to omit axis/title la... | 5,342,282 |
def RecogniseForm(access_token, image, templateSign=None, classifierId=None):
"""
自定义模板文字识别
:param access_token:
:param image:图像数据(string),base64编码,注意大小不超过4M,最短边至少15px,最长边最大4096px,支持jpg/png/bmp格式
:param templateSign:模板ID(string)
:param classifierId:分类器ID(int),这个参数与templateSign至少存在一个,优先使用template... | 5,342,283 |
def rectangle(
func: Callable[..., float], a: float, b: float, eps: float = 0.0001, *args, **kwargs
) -> float:
"""
Metode segi empat adalah metode integrasi paling sederhana.
Metode ini membagi domain integrasi sebanyak n buah
dan menjumlahkan seluruh luas segi empat dengan dimensi
(a + b)/n *... | 5,342,284 |
def _rearrange_axis(data: np.ndarray,
axis: int = 0) -> tuple([np.ndarray, tuple]):
"""rearranges the `numpy.ndarray` as a two-dimensional array of size (n,
-1), where n is the number of elements of the dimension defined by `axis`.
Parameters
----------
data : :class:`numpy.nda... | 5,342,285 |
def landmarks_json():
"""Send landmark data for map layer as Geojson from database."""
features = []
for landmark in Landmark.query.all():
# get the first image of a landmark, if any
image = ""
if len(landmark.images) > 0:
image = landmark.images[0].imageurl
#... | 5,342,286 |
def _verify_kronecker_factored_config(model_config):
"""Verifies that a kronecker_factored model_config is properly specified.
Args:
model_config: Model configuration object describing model architecture.
Should be one of the model configs in `tfl.configs`.
Raises:
ValueError: If there are lattice... | 5,342,287 |
def _tree_cmd(options, user_args):
"""
Return the post_setup hook function for 'openmdao tree'.
Parameters
----------
options : argparse Namespace
Command line options.
user_args : list of str
Args to be passed to the user script.
"""
if options.outfile is None:
... | 5,342,288 |
def new_get_image_collection_gif(
ee_ic,
out_dir,
out_gif,
vis_params,
region,
cmap=None,
proj=None,
fps=10,
mp4=False,
grid_interval=None,
plot_title="",
date_format="YYYY-MM-dd",
fig_size=(10, 10),
dpi_plot=100,
file_format="png",
north_arrow_dict={},
... | 5,342,289 |
def extractTuples(data):
""" Saca las tuplas (palabra,prediccion),
y las devuelve como dos arrays entradas y
salidas """
inp = []
out = []
for r in data:
for i in range(len(r)):
for j in range(-CONTEXT_WINDOW,CONTEXT_WINDOW+1):
if j == CONTEXT_WINDOW or i+j <0... | 5,342,290 |
def read_iter(fp, contig_q):
"""Returns read objects from contigs until someone passes None as a contig
:param fp: BAM file pointer (pysam.AlignmentFile)
:param contig_q: a queue into which we put contig information
(contig, eof_true) - eof_true is set if this is
the last no... | 5,342,291 |
def _GetKeyKind(key):
"""Return the kind of the given key."""
return key.path().element_list()[-1].type() | 5,342,292 |
def main(life, pixel_size=3, wait = 50, gen = -1):
"""Run life simulation."""
pygame.init()
pygame.display.set_caption("PyLife")
mat = mirror(scale(life.view_matrix(), pixel_size))# to find dimensions
screen = pygame.display.set_mode(mat.shape)
while 1: # mainloop
for e in pygame.event.... | 5,342,293 |
def load_config() -> dict:
"""
Loads the config.yml file to memory and returns it as dictionary.
:return: Dictionary containing the config.
"""
with open('config.yml', 'r') as ymlfile:
return yaml.load(ymlfile, Loader=yaml.FullLoader) | 5,342,294 |
def find_column_equivalence(matrix, do_not_care) -> Tuple[List[int], List[Sequence]]:
""" Adapt find_row_equivalence (above) to work on columns instead of rows. """
index, classes = find_row_equivalence(zip(*matrix), do_not_care)
return index, list(zip(*classes)) | 5,342,295 |
def getBaseCount(reads, varPos):
"""
:param reads:
:param varPos:
"""
'''
returns the baseCount for the
'''
baseCount = {'A': 0, 'C': 0, 'G': 0, 'T': 0}
for read in reads:
readPos = 0
mmReadPos = 0
startPos = read.pos
try:
cigarNums ... | 5,342,296 |
def RegisterSpecs(func):
"""The decorator to register the specification for each check item object.
The decorator first tests whether it is involved in the outmost call of the
check item object. If so, it then goes through the args, kwargs, and defaults
to populate the specification.
Args:
func: The __i... | 5,342,297 |
def get_changes_to_be_committed() -> Set[Path]:
"""After every time `add` is performed, the filepath is added to this text file."""
return {Path(path) for path in path_to.changes_to_be_committed.read_text().split("\n") if path} | 5,342,298 |
def write_channels_metadata(meta_data_dict, file_name, access_mode="a"):
"""
Write the channel metadata into the given file. If file doesn't exist create it.
If the file exists, the channel indexes given in the meta_data_dict must be in
the existing range.
Parameters
----------
meta_data_di... | 5,342,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.