content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def build_bundletoperfectsensor_pipeline(pan_img, ms_img):
"""
This function builds the a pipeline that performs P+XS pansharpening
:param pan_img: Path to the panchromatic image
:type pan_img: string
:param ms_img: Path to the multispectral image
:type ms_img: string
:returns: resample_ima... | 14,900 |
def get_argparser_ctor_args():
"""
This method returns a dict containing the kwargs for constructing an
argparse.ArgumentParser (either directly or as a subparser).
"""
return {
'prog': 'CodeChecker store',
'formatter_class': arg.RawDescriptionDefaultHelpFormatter,
# Descri... | 14,901 |
def main():
"""
sig: ()-> NoneType
Runs program
"""
update_input()
store_objects()
global waves
init_waves()
turtle.tracer(0, 0)
turtle.onkey(key_y, "y")
turtle.onkey(key_up, "Up")
turtle.onkey(key_down, "Down")
turtle.onkey(key_left, "Left")
turtle.onkey(key_righ... | 14,902 |
def test_census_income():
"""Test correct shape and content of census income data."""
data = datasets.census_income()
# correct number of rows and columns
assert data.shape == (299285, 396)
# correct proportion of target values
assert (
data["income_gt_50k"].value_counts().loc[[0, 1]] ==... | 14,903 |
def castep_geom_count(dot_castep):
"""Count the number of geom cycles"""
count = 0
with open(dot_castep) as fhandle:
for line in fhandle:
if 'starting iteration' in line:
count += 1
return count | 14,904 |
def nav_login(request, text="Login", button=False):
"""Navigation login button
Args:
request (Request): Request object submitted by template
text (str, optional): Text to be shown in button. Defaults to "Login".
button (bool, optional): Is this to be styled as a button or as a link. Def... | 14,905 |
def test_mesh():
"""
mesh should return a meshed array with increasing/decreasing grid size.
"""
dis = mesh(n=100, a=1)
d = dis[1:]-dis[:-1]
assert len(dis) == 100
assert np.all(d[1:] > d[:-1])
dis = mesh(n=100, a=-1)
d = dis[1:]-dis[:-1]
assert np.all(d[1:] < d[:-1]) | 14,906 |
async def main() -> None:
"""Show example on controlling your WLED device."""
async with WLED("10.10.11.135") as led:
device = await led.update()
print(device.info.version)
if isinstance(device.state.preset, Preset):
print(f"Preset active! Name: {device.state.preset.name}")
... | 14,907 |
def crop_image(input_image, output_image, start_x, start_y, width, height):
"""Pass input name image, output name image, x coordinate to start croping, y coordinate to start croping, width to crop, height to crop """
input_img = Image.open(input_image)
box = (start_x, start_y, start_x + width, start_y + hei... | 14,908 |
def parse_adapter(name: str, raw: dict) -> dict:
"""Parse a single adapter."""
parsed = {
"name": strip_right(obj=name, fix="_adapter"),
"name_raw": name,
"name_plugin": raw["unique_plugin_name"],
"node_name": raw["node_name"],
"node_id": raw["node_id"],
"status":... | 14,909 |
def export_phones(ucm_axl):
"""
Export Phones
"""
try:
phone_list = ucm_axl.get_phones(
tagfilter={
"name": "",
"description": "",
"product": "",
"model": "",
"class": "",
"protocol": "",
... | 14,910 |
def is_various_artists(name, mbid):
"""Check if given name or mbid represents 'Various Artists'."""
return name and VA_PAT.match(name) or mbid == VA_MBID | 14,911 |
def validate_ruletype(t):
"""Validate *bounds rule types."""
if t not in ["typebounds"]:
raise exception.InvalidBoundsType("{0} is not a valid *bounds rule type.".format(t))
return t | 14,912 |
def update_betweenness(G, path, pair, count, relevant):
"""
Given a shortest path in G, along with a count of paths
that length, to determine weight, updates the edge and
pair betweenness dicts with the path's new information.
"""
weight = 1./count
pos = 0
while pos < len(path) - 2:
... | 14,913 |
def download_and_unpack_database(db: str, sha256: str) -> Path:
"""Download the given database, unpack it to the local filesystem, and
return the path.
"""
local_dir = cache_path(f"state_transition_dataset/{sha256}")
with _DB_DOWNLOAD_LOCK, InterProcessLock(
transient_cache_path(".state_tran... | 14,914 |
def addMachine(args):
"""
Adds a Machine to a Plant with plantName.
"""
plantName = args[0]
machineName = args[1]
machineQuantity = args[2]
machineDelay = args[3]
machineCanUnhook = args[4]
plantFilename = plantFileExists(plantName)
plant = Plant.fromXmlFile(plantFilename)
plant.addMachine(Machine(name = m... | 14,915 |
def walk_class_hierarchy(clazz, encountered=None):
"""Walk class hierarchy, yielding most derived classes first."""
if not encountered:
encountered = []
for subclass in clazz.__subclasses__():
if subclass not in encountered:
encountered.append(subclass)
# drill down t... | 14,916 |
def test_command_line_interface(training_set_dir_path, cli_output_path, reax_output_dir_path):
"""Test the CLI."""
training_path = str(training_set_dir_path)
population_path = str(cli_output_path)
config_path = str(os.path.join(os.path.abspath(os.path.join(__file__, "../../")),
... | 14,917 |
def decode_section_flags(sflags: str) -> int:
"""Map readelf's representation of section flags to ELF flag values."""
d = {
'W': elftools.elf.constants.SH_FLAGS.SHF_WRITE,
'A': elftools.elf.constants.SH_FLAGS.SHF_ALLOC,
'X': elftools.elf.constants.SH_FLAGS.SHF_EXECINSTR,
'M': elf... | 14,918 |
def nCr(n,r):
"""
Implements multiplicative formula:
https://en.wikipedia.org/wiki/Binomial_coefficient#Multiplicative_formula
"""
if r < 0 or r > n:
return 0
if r == 0 or r == n:
return 1
c = 1
for i in xrange(min(r, n - r)):
c = c * (n - i) // (i + 1)
return c | 14,919 |
def get_test_vesselfile():
"""
return the necessary paths for the testfile tests
Returns
-------
str
absolute file path to the test file
"""
testfile = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'test_data', 'vessel_file.kfc')
return testfile | 14,920 |
def _get_init_arguments(cls, *args, **kwargs):
"""Returns an OrderedDict of args passed to cls.__init__ given [kw]args."""
init_args = inspect.signature(cls.__init__)
bound_args = init_args.bind(None, *args, **kwargs)
bound_args.apply_defaults()
arg_dict = bound_args.arguments
del arg_dict['self... | 14,921 |
def MatchCapture(nfa: NFA, id: CaptureGroup) -> NFA:
"""Handles: (?<id>A)"""
captures = {(s, i): {id} for (s, i) in nfa.transitions if i != Move.EMPTY}
return NFA(nfa.start, nfa.end, nfa.transitions, merge_trans(nfa.captures, captures)) | 14,922 |
def save_private_file_share(request, token):
"""
Save private share file to someone's library.
"""
username = request.user.username
try:
pfs = PrivateFileDirShare.objects.get_priv_file_dir_share_by_token(token)
except PrivateFileDirShare.DoesNotExist:
raise Http404
from_... | 14,923 |
def get_all_state_events(log):
""" Returns a list of tuples of event id, state_change_id, block_number and events"""
return [
(InternalEvent(res[0], res[1], res[2], log.serializer.deserialize(res[3])))
for res in get_db_state_changes(log.storage, 'state_events')
] | 14,924 |
def iff(a: NNF, b: NNF) -> Or[And[NNF]]:
"""``a`` is true if and only if ``b`` is true."""
return (a & b) | (a.negate() & b.negate()) | 14,925 |
def redact_access_token(e: Exception) -> Exception:
"""Remove access token from exception message."""
if not isinstance(e, FacebookError):
return e
e.args = (redact_access_token_from_str(str(e.args[0])),)
return e | 14,926 |
def _get_ext_comm_subtype(type_high):
"""
Returns a ByteEnumField with the right sub-types dict for a given community.
http://www.iana.org/assignments/bgp-extended-communities/bgp-extended-communities.xhtml
"""
return _ext_comm_subtypes_classes.get(type_high, {}) | 14,927 |
def _filter_classes(classes, filters, names_only, iq):
"""
Filter a list of classes for the qualifiers defined by the
qualifier_filter parameter where this parameter is a list of tuples.
each tuple contains the qualifier name and a dictionary with qualifier
name as key and tuple containing the opt... | 14,928 |
def template2():
"""load_cep_homo"""
script = """
## (Store,figure)
<< host = chemml
<< function = SavePlot
<< kwargs = {'normed':True}
<< output_directory = plots
<< filename = amwVSdensity
... | 14,929 |
def get_target_and_encoder_gpu(train: GpuDataset) -> Tuple[Any, type]:
"""Get target encoder and target based on dataset.
Args:
train: Dataset.
Returns:
(Target values, Target encoder).
"""
target = train.target
if isinstance(target, cudf.Series):
target = target.valu... | 14,930 |
def main(inputs_dir):
"""
Entry point for merge and split processing script
Attributes:
------------
:param inputs_dir {string} - Path to the directory containing input data
"""
# Create output directory if it doesn't exist
if not os.path.exists('output/'):
os.mkdir('output')
... | 14,931 |
def addSyntheticToTrainingData(train, synth):
"""
write out new shuffled training data file
:param train: locations of all existing training data files
:param synth: generated data
"""
# create list of generated data with adjusted paths
synth_paths = []
for img in synth:
synth_pa... | 14,932 |
def get_available_languages(domain):
"""Lists the available languages for the given translation domain.
:param domain: the domain to get languages for
"""
if domain in _AVAILABLE_LANGUAGES:
return copy.copy(_AVAILABLE_LANGUAGES[domain])
localedir = os.environ.get(_locale.get_locale_dir_var... | 14,933 |
def once(f):
"""Cache result of a function first call"""
@functools.wraps(f)
def wrapper(*args, **kwargs):
rv = getattr(f, 'rv', MISSING)
if rv is MISSING:
f.rv = f(*args, **kwargs)
return f.rv
return wrapper | 14,934 |
def setup(args):
"""
Create configs and perform basic setups.
"""
cfg = get_cfg()
add_config(args, cfg)
cfg.merge_from_file(args.config_file)
cfg.merge_from_list(args.opts)
cfg.MODEL.BUA.EXTRACTOR.MODE = 1
default_setup(cfg, args)
cfg.MODEL.DEVICE = 'cuda:0' if torch.cuda.is_avai... | 14,935 |
def build_audit_stub(obj):
"""Returns a stub of audit model to which assessment is related to."""
audit_id = obj.audit_id
if audit_id is None:
return None
return {
'type': 'Audit',
'id': audit_id,
'context_id': obj.context_id,
'href': '/api/audits/%d' % audit_id,
'issue_tracker... | 14,936 |
def test_verbose_probability(probability_above_cube, interpreter):
"""Test verbose output for a simple probability diagnostic"""
expected_result = (
"This is a gridded probabilities file\n"
" Source: name, coordinates\n"
"It contains probabilities of air temperature greater than thres... | 14,937 |
def calculate_widths(threshold_img, landmarks):
"""
Calcula a largura dos vasos sanguíneos nos pontos de potenciais
bifurcação. Esse cálculo é feito pegando a menor distância percorrida
a partir do ponto em cada uma das direções (8 direções são utilizadas).
A função retorna o que ser... | 14,938 |
def smi_to_fp(smi: str, fingerprint: str,
radius: int = 2, length: int = 2048) -> Optional[np.ndarray]:
"""fingerprint functions must be wrapped in a static function
so that they may be pickled for parallel processing
Parameters
----------
smi : str
the SMILES string o... | 14,939 |
def f(x, t):
"""function to learn."""
return tf.square(tf.cast(t, tf.float32) / FLAGS.tm) * (tf.math.sin(5 * x) + 1) | 14,940 |
def render_cells(cells, width=80, col_spacing=2):
"""Given a list of short (~10 char) strings, display these aligned in
columns.
Example output::
Something like this can be
used to neatly arrange long
sequences of values in ... | 14,941 |
def separate_types(data):
"""Separate out the points from the linestrings."""
if data['type'] != 'FeatureCollection':
raise TypeError('expected a FeatureCollection, not ' + data['type'])
points = []
linestrings = []
for thing in data['features']:
if thing['type'] != 'Feature':
... | 14,942 |
def state(state_vec):
""" Qiskit wrapper of qobj
"""
return gen_operator.state(state_vec) | 14,943 |
def get_index_path(bam_path: str):
"""
Obtain path to bam index
Returns:
path_to_index(str) : path to the index file, None if not available
"""
for p in [bam_path+'.bai', bam_path.replace('.bam','.bai')]:
if os.path.exists(p):
return p
return None | 14,944 |
def get_games_for_platform(platform_id):
"""Return the list of all the games for a given platform"""
controller = GameController
return controller.get_list_by_platform(MySQLFactory.get(), platform_id) | 14,945 |
def set_entity_variable_types(entity, node_type, db_info):
"""
Sets a featuretools Entity's variable types to match the variable types in db_info[node_type]
"""
for var_name, var_type in entity.variable_types.items():
if not var_type in [Index, Id]:
feat_info = db_info['node_types_an... | 14,946 |
def validate_dataset(elem: object) -> Dataset:
"""Check that `elem` is a :class:`~pydicom.dataset.Dataset` instance."""
if not isinstance(elem, Dataset):
raise TypeError('Sequence contents must be Dataset instances.')
return elem | 14,947 |
def build_array(name: str, variables: Dict[str, Dict[str, Any]],
data: np.ndarray):
"""Builds the array from the data and the variables"""
properties = variables[name]
attrs = copy.deepcopy(properties["attrs"])
# Reading the storage properties of the variable
encoding: Dict[str, Any... | 14,948 |
def conv3x3(in_channels, out_channels, stride=1):
"""3x3 convolution """
weight_shape = (out_channels, in_channels, 3, 3)
weight = Tensor(np.ones(weight_shape).astype(np.float32))
conv = Conv2d(in_channels, out_channels,
kernel_size=3, stride=stride, padding=0, weight_init=weight, has_... | 14,949 |
def _workflow_complete(workflow_stage_dict: dict):
"""Check if the workflow is complete.
This function checks if the entire workflow is complete.
This function is used by `execute_processing_block`.
Args:
workflow_stage_dict (dict): Workflow metadata dictionary.
Returns:
bool, Tr... | 14,950 |
def close_session(*args, **kwargs):
"""
Flask SQLAlchemy will automatically create new sessions for you from
a scoped session factory, given that we are maintaining the same app
context, this ensures tasks have a fresh session (e.g. session errors
won't propagate across tasks)
"""
db.session... | 14,951 |
def set_cpus(instance):
"""Set the number of virtual CPUs for the virtual machine.
:param instance: nova.objects.instance.Instance
"""
host_info = get_host_info()
if instance.vcpus > host_info[constants.HOST_PROCESSOR_COUNT]:
raise nova_exception.ImageNUMATopologyCPUOutOfRange(
... | 14,952 |
def create_output_folder(ProjectDir):
"""Create the output folders starting from the project directory.
Parameters
----------
ProjectDir : str
Name of the project directory.
Returns
-------
type
PicturePath, ResultsPath
"""
npath = os.path.normpath(ProjectDir)
... | 14,953 |
def get_name(f, opera_format=True):
"""Load dataset and extract radar name from it"""
ds = xr.open_dataset(f)
if hasattr(ds, 'source'):
radar = ds.source
else:
filename = osp.splitext(osp.basename(f))[0]
radar = filename.split('_')[-1]
if opera_format:
if '/' in rad... | 14,954 |
def range_join(numbers, to_str=False, sep=",", range_sep=":"):
"""
Takes a sequence of positive integer numbers given either as integer or string types, and
returns a sequence 1- and 2-tuples, denoting either single numbers or inclusive start and stop
values of possible ranges. When *to_str* is *True*, ... | 14,955 |
def power_spectrum(x, fs, N=None):
"""
Power spectrum of instantaneous signal :math:`x(t)`.
:param x: Instantaneous signal :math:`x(t)`.
:param fs: Sample frequency :math:`f_s`.
:param N: Amount of FFT bins.
The power spectrum, or single-sided autospectrum, contains the squared RMS amplitudes ... | 14,956 |
def CreateInstanceTemplate(task, task_dir):
"""Create the Compute Engine instance template that will be used to create the
instances.
"""
backend_params = task.BackendParams()
instance_count = backend_params.get('instance_count', 0)
if instance_count <= 0:
clovis_logger.info('No template required.')
... | 14,957 |
def get_config_string(info_type, board_num, dev_num, config_item, max_config_len):
"""Returns configuration or device information as a null-terminated string.
Parameters
----------
info_type : InfoType
The configuration information for each board is grouped into different categories. This
... | 14,958 |
def test_feature_constraintslist_qaenv(unleash_client):
"""
Feature.constraints.list should NOT be enabled in qa environment
"""
# Set up API
responses.add(responses.POST, URL + REGISTER_URL, json={}, status=202)
responses.add(responses.GET, URL + FEATURES_URL, json=json.loads(MOCK_JSON), status... | 14,959 |
def _get_kwargs(func, locals_dict, default=None):
"""
Convert a function's args to a kwargs dict containing entries that are not identically default.
Parameters
----------
func : function
The function whose args we want to convert to kwargs.
locals_dict : dict
The locals dict fo... | 14,960 |
def iso_to_date(iso_str: str):
"""Convert a date string with iso formating to a datetime date object"""
if not iso_str:
return None
return datetime.date(*map(int, iso_str.split('-'))) | 14,961 |
def replace_X_with_U(fold: data.Fold, Theta: NP.Matrix):
""" Replace X with its rotated/reordered version U."""
column_headings = MultiIndex.from_product(((fold.meta['data']['X_heading'],), ("u{:d}".format(i) for i in range(fold.M))))
X = DataFrame(einsum('MK, NK -> NM', Theta, fold.X, optimize=True, dtype=... | 14,962 |
def call_with_error(error_type):
"""Collects a bunch of errors and returns them all once.
Decorator that collects the errors in the decorated function so that the
user can see everything they need to fix at once. All errors are thrown
with the same error type.
The decorated must have an `error` ke... | 14,963 |
def _get_metadata_and_fingerprint(instance_name, project, zone):
"""Return the metadata values and fingerprint for the given instance."""
instance_info = _get_instance_info(instance_name, project, zone)
if not instance_info:
logs.log_error('Failed to fetch instance metadata')
return None, None
fingerpr... | 14,964 |
def makersslist(xlist, nodes , d={}):
""" recurse until txt is found """
for i in nodes:
if i.nodeType == i.ELEMENT_NODE:
dd = d[i.nodeName] = {}
makersslist(xlist, i.childNodes, dd)
if dd: xlist.append(dd)
txt = gettext(i.childNodes)
if txt: d[i.nodeN... | 14,965 |
def solve_token_pair_and_fee_token_economic_viable(
token_pair, accounts, b_orders, s_orders, f_orders, fee,
xrate=None
):
"""Match orders between token pair and the fee token, taking into
account all side constraints, including economic viability.
If xrate is given, then it will be used instead of... | 14,966 |
def two_categorical(df, x, y, plot_type="Cross tab"):
"""
['Cross tab', "Stacked bone_numeric_one_categorical"]
"""
if plot_type is None:
plot_type = 'Cross tab'
if plot_type == 'Stacked bar': # 20
df_cross = pd.crosstab(df[x], df[y])
data = []
for x in df_cross.... | 14,967 |
def yices_bvconst_one(n):
"""Set low-order bit to 1, all the other bits to 0.
Error report:
if n = 0
code = POS_INT_REQUIRED
badval = n
if n > YICES_MAX_BVSIZE
code = MAX_BVSIZE_EXCEEDED
badval = n.
"""
# let yices deal with int32_t excesses
if n > MAX_INT... | 14,968 |
def showItem(category_id):
"""Show all Items"""
category = session.query(Category).filter_by(id=category_id).one()
items = session.query(Item).filter_by(
category_id=category_id).all()
return render_template('item.html', items=items, category=category) | 14,969 |
def get_standard_t_d(l, b, d):
"""
Use NE2001 to estimate scintillation time at 1 GHz and 1 km/s transverse velocity.
Parameters
----------
l : float
Galactic longitude
b : float
Galactic latitude
d : float
Distance in kpc
Returns
-------
t_d... | 14,970 |
def main(argv=sys.argv):
"""
Entry point
"""
global stats
if len(argv) !=2:
usage(argv)
ifile = argv[1]
try:
f = open(ifile)
except IOError as error:
print ("I/O error while opening file: %s" % error, file=sys.stderr)
return
incomes = {}
i = 0
... | 14,971 |
def get_json_test_data(project, test_name):
"""Get data from json file.
If json data is not of type dict or list of dicts it is ignored.
"""
json_data = None
json_path = json_file_path(project, test_name)
if os.path.isfile(json_path):
try:
with open(json_path, encoding='utf-8... | 14,972 |
def sendsensordata() -> None:
"""
Reads a data structure to configure DHT22 sensors on multiple pins
Example: { "terrarium-cold": 1, "terrarium-center": 2, "terrarium-hot": 3 }
"""
mqtt = MQTT()
for name, pin in config.sensors.items():
print('Measuring sensor', name)
sensor = dht... | 14,973 |
def scrape(start, end, out):
"""
Scrape a MLBAM Data
:param start: Start Day(YYYYMMDD)
:param end: End Day(YYYYMMDD)
:param out: Output directory(default:"../output/mlb")
"""
try:
logging.basicConfig(level=logging.DEBUG)
MlbAm.scrape(start, end, out)
except MlbAmBadParame... | 14,974 |
def match(pattern: str, text: str) -> bool:
"""
匹配同样长度的字符串
"""
if pattern:
return True
elif pattern == "$" and text == "":
return True
elif pattern[1] == "?":
return _match_question(pattern, text)
elif pattern[1] == "*":
return _match_star(pattern, text)
e... | 14,975 |
def config_func(tools, index, device_id, config_old: {}, config_new: {}):
"""
CANedge configuration update function
:param tools: A collection of tools used for device configuration
:param index: Consecutive device index (from 0)
:param device_id: Device ID
:param config_old: The current device ... | 14,976 |
def load_figure(file_path: str) -> matplotlib.figure.Figure:
"""Fully loads the saved figure to be able to be modified.
It can be easily showed by:
fig_object.show()
Args:
file_path: String file path without file extension.
Returns:
Figure object.
Raises:
None.
... | 14,977 |
def cluster_vectors(vectors, k=500, n_init=100, **kwargs):
"""Build NearestNeighbors tree."""
kwargs.pop('n_clusters', None)
kwargs.pop('init', None)
kwargs.pop('n_init', None)
return KMeans(n_clusters=k, init='k-means++', n_init=n_init,
**kwargs).fit(vectors) | 14,978 |
def positional_encoding(d_model, length):
"""
:param d_model: dimension of the model
:param length: length of positions
:return: length*d_model position matrix
"""
if d_model % 2 != 0:
raise ValueError("Cannot use sin/cos positional encoding with "
"odd dim (got ... | 14,979 |
def esx_connect(host, user, pwd, port, ssl):
"""Establish connection with host/vcenter."""
si = None
# connect depending on SSL_VERIFY setting
if ssl is False:
si = SmartConnectNoSSL(host=host, user=user, pwd=pwd, port=port)
current_session = si.content.sessionManager.currentSession.key... | 14,980 |
def get_cropped_face_img(image_path, margin=44, image_size=160, folders=None):
"""return cropped face img if face is detected,
otherwise remove the img
"""
minsize = 20 # minimum size of face
threshold = [0.6, 0.7, 0.7] # three steps's threshold
factor = 0.709 # scale factor
pnet, r... | 14,981 |
def invert_hilbert_QQ(n=40, system='sage'):
"""
Runs the benchmark for calculating the inverse of the hilbert
matrix over rationals of dimension n.
INPUT:
- ``n`` - matrix dimension (default: ``300``)
- ``system`` - either 'sage' or 'magma' (default: 'sage')
EXAMPLES::
sage: impo... | 14,982 |
def getModelListForEnumProperty(self, context):
"""Returns a list of (str, str, str) elements which contains the models
contained in the currently selected model category.
If there are no model categories (i.e. '-') return ('-', '-', '-').
Args:
context:
Returns:
"""
category = con... | 14,983 |
def moveFiles(subsystemDict, dirPrefix):
""" For each subsystem, moves ROOT files that need to be moved from directory that receives HLT histograms into appropriate file structure for processing.
Creates run directory and subsystem directories as needed. Renames files to convention that is later used for extr... | 14,984 |
def h_atom():
"""H atom solved numerically"""
m = 1
eigval = -1/2
rs = np.linspace(0.000001, 5.0, num=2000)
sol = odeint(radial_h_potential,
y0=np.array([1, -0.001]),
t=rs,
args=(m, 0, eigval))
plt.plot(rs, sol[:, 0])
plt.plot(rs, np.exp(-... | 14,985 |
def run_wcs(*args, **kwargs):
"""
Set up the environment and run the bundled wcs.exe (from the Talon distribution)
using the supplied command line arguments
"""
# Pull out keyword args that we are interested in
write_stdout_to_console = kwargs.get("write_stdout_to_console", False)
... | 14,986 |
def read_setup_cfg():
"""
Build an absolute path from *parts* and and return the contents of the
resulting file. Assume UTF-8 encoding.
"""
config_file = os.path.join(HERE, "setup.cfg")
cp = ConfigParser()
cp.read([config_file])
return cp | 14,987 |
def store_exposure_fp(fp, exposure_type):
"""
Preserve original exposure file extention if its in a pandas supported
compressed format
compression : {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}, default ‘infer’
For on-the-fly decompression of on-disk data. If ‘infer’ and
... | 14,988 |
def velocity_genes(data, vkey='velocity', min_r2=0.01, highly_variable=None, copy=False):
"""Estimates velocities in a gene-specific manner
Arguments
---------
data: :class:`~anndata.AnnData`
Annotated data matrix.
vkey: `str` (default: `'velocity'`)
Name under which to refer to the... | 14,989 |
def test_net(net, imdb, max_per_image=100, thresh=0.05, vis=False):
"""Test a Fast R-CNN network on an image database."""
num_images = len(imdb.image_index)
# all attributes are collected into:
# all_probs[image] = 40 x 2 array of attributes in
# (score1, score2)
all_probs = [[] for _ in x... | 14,990 |
def start_cluster_server(ctx, num_gpus=1, rdma=False):
"""*DEPRECATED*. Use higher-level APIs like `tf.keras` or `tf.estimator`"""
raise Exception("DEPRECATED: Use higher-level APIs like `tf.keras` or `tf.estimator`") | 14,991 |
def _init_servers(r_exec, s_execs, binary_dirs, out_dir, sync,
staged_src, singlesrv_cfg):
"""Initializes the receiver and senders.
Args:
r_exec: The receiver executor session.
s_execs: The sender executor sessions.
binary_dirs: Where to fetch binaries (e.g., tc, netpe... | 14,992 |
def update_graphics_labels_from_node_data(node, n_id_map, add_new_props):
"""Updates the graphics labels so they match the node-data"""
try:
gfx = select_child(node, n_id_map, 'nodegraphics').getchildren()[0].getchildren()
except:
return None
node_label = select_child(node, n_id_map, 'l... | 14,993 |
def _evaluate_worker(input_queue, output_queue, logging_queue, glm_mgr):
"""'Worker' function for evaluating individuals in parallel.
This method is designed to be used in a multi-threaded or
multi-processing environment.
:param input_queue: Multiprocessing.JoinableQueue instance. The
objects ... | 14,994 |
def deploy_binary_if_master(args):
"""if the active branch is 'master', deploy binaries for the primary suite to remote maven repository."""
master_branch = 'master'
active_branch = mx.VC.get_vc(SUITE.dir).active_branch(SUITE.dir)
if active_branch == master_branch:
if sys.platform == "darwin":
... | 14,995 |
def fast_spearman(x, y=None, destination=None):
"""calculate the spearman correlation matrix for the columns of x (with dimensions MxN), or optionally, the spearman correlaton
matrix between the columns of x and the columns of y (with dimensions OxP). If destination is provided, put the results there.
In t... | 14,996 |
def test_RootLogger_configure_processors(root_logger_default_params):
"""
Tests if default processors loaded are valid
# C1: All processors returned are functions
# C2: logging_renderer must be the last processor of the list
"""
# C1
processors = root_logger_default_params._configure_proces... | 14,997 |
def test_report_provider_when_vmware_is_installed():
"""Test report_provider."""
with patch.object(mech.vmrun.VMrun, 'installed', return_value=True) as mock_vmrun:
assert not mech.utils.report_provider('atari')
assert mech.utils.report_provider('vmware')
mock_vmrun.assert_called() | 14,998 |
def ProcuraPalavra(dicionário, palavra):
"""
Procura as possíveis palavras para substituir
a palavra passada, e as devolve numa lista
"""
#Antes de mais nada tornamos a palavra maiuscula
#para realizar as comparações
palavra = palavra.upper()
#Primeiro olhamos para o caso de haver u... | 14,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.