content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def gaussian_preferences(coords, sizes, scales, rstate=None):
"""
Generate gaussian preference distributions at coordinate and specified size
Parameters
----------
coords : array shaped (a, b)
Centroids of a faction voter preferences.
- rows `a` = coordinate for each ... | 5,290,100 |
def calculate_imf_steadiness(inst, steady_window=15, min_window_frac=0.75,
max_clock_angle_std=(90.0 / np.pi),
max_bmag_cv=0.5):
""" Calculate IMF steadiness using clock angle standard deviation and
the coefficient of variation of the IMF magnitude in th... | 5,290,101 |
def load_image(raw_path):
"""
Function loads images from a list of file paths into ndarrays
Params:
-------
raw_paths (str) -- Paths to the image files
"""
# Iterate through each path in list, load image, and store in an array
start = raw_path.find(FOLDER)
suffix = raw_path[start:]
img_path = DATA_DIR + '/... | 5,290,102 |
def __ior__(self: array, other: array, /) -> array:
"""
Note: __ior__ is a method of the array object.
"""
pass | 5,290,103 |
def test_inputOfChoice():
"""
This function tests if the input of chice argument is likes or author
"""
with pytest.raises(ValueError):
popular('https://stackoverflow.com/questions/49218133/gulp-js-minifies-uglifies-and-copies-all-the-files-but-still-the-app-in-the-dis', 'lalala') | 5,290,104 |
def show_edit_sample_for_sampleset(request, sampleSetItemId):
"""
show the sample edit page
"""
logger.debug("views.show_edit_sample_for_sampleset sampleSetItemId=%s; " % (str(sampleSetItemId)))
sampleSetItem = get_object_or_404(SampleSetItem, pk=sampleSetItemId)
return show_samplesetitem_modal... | 5,290,105 |
def BundleVmFiles(input_proto, output_proto, _config):
"""Tar VM disk and memory files.
Args:
input_proto (BundleVmFilesRequest): The input proto.
output_proto (BundleResponse): The output proto.
_config (api_config.ApiConfig): The API call config.
"""
chroot = controller_util.ParseChroot(input_pro... | 5,290,106 |
def csv_load(file, name, mode):
"""
读取csv文件内容,并写入到数据库中
"""
with open(file, "r") as f:
reader = csv.DictReader(f)
bars = []
reg = "[^A-Za-z]"
#* 提取文件名信息
if mode == 'd':
file_message = name.split('_')
symbol = file_message[0]
... | 5,290,107 |
def perform_test(test_loader, model, args, failed_log, n_dataset):
"""
For classification:
Perform mutli-view testing that uniformly samples
N clips from a video along
its temporal axis. For each clip, it takes 3 crops to cover the spatial
dimension, followed by averaging the softmax scores ... | 5,290,108 |
def Cleanup(config):
"""Preform cleanup on description contents, such as sorting metrics.
Args:
config: The parsed rappor.xml contents.
"""
types = config['parameterTypes']['types']
types.sort(key=lambda x: x['name'])
metrics = config['metrics']['metrics']
metrics.sort(key=lambda x: x['name']) | 5,290,109 |
def hp_qloguniform(min, max, q):
""" Quantized log uniform (base 10) distribution with a quantum of q, bounded by min and max. Returns a
value like round(exp(uniform(low, high)) / q) * q.
:param min: Exponent of the minimum value in base 10 (e.g., -4 for 0.0001).
:param max: Exponent of the maximum va... | 5,290,110 |
def rename_ready_user_story_points_metric(database: Database) -> None: # pragma: no cover-behave
"""Rename the ready_user_story_points metric to user_story_points."""
# Introduced when the most recent version of Quality-time was 3.3.0.
reports = list(database.reports.find({"last": True, "deleted": {"$exist... | 5,290,111 |
def display_account():
"""
function to display existing account
"""
return User.display_account() | 5,290,112 |
def mols_to_pngs(mols, basename="test"):
"""Helper to write RDKit mols to png files."""
filenames = []
for i, mol in enumerate(mols):
filename = "BACE_%s%d.png" % (basename, i)
Draw.MolToFile(mol, filename)
filenames.append(filename)
return filenames | 5,290,113 |
def test_properties():
"""Tests that ProxySimulatorControls implements properties"""
mock_sim_controls = mock.create_autospec(spec=AbstractSimulatorControls)
mock_aircraft_controls = mock.create_autospec(spec=ProxyAircraftControls)
properties_mock = mock.PropertyMock()
properties_mock.return_value ... | 5,290,114 |
def create_game():
"""Post a new game result to the database."""
game = validate_game_submission(request.headers, request.json)
db.session.add(game)
db.session.commit()
print("New game: %s " % str(game))
return jsonify(game.to_dict()), 201 | 5,290,115 |
def rep1(arg):
"""
Matches one or more occurrences of 'arg'.
"""
assert isinstance(arg, ContentModel)
arg.quant = ContentModel.QUANT_PLUS
return arg | 5,290,116 |
async def async_setup_entry(
hass: HomeAssistant,
config_entry: config_entries.ConfigEntry,
async_add_entities: AddEntitiesCallback,
) -> None:
"""Set up number(s) for KNX platform."""
xknx: XKNX = hass.data[DOMAIN].xknx
config: list[ConfigType] = hass.data[DATA_KNX_CONFIG][Platform.NUMBER]
... | 5,290,117 |
def _search_host(host=None, domain=None,
username=None, password=None, **kwargs):
"""Find invalid customer routes received by host."""
result = []
driver = napalm.get_network_driver("ios")
try:
with driver(hostname="{}.{}".format(host, domain),
username=usern... | 5,290,118 |
def wilcoxon(x,y):
"""
One-sided wilcoxon sign-rank test.
p-value is small if \EE x >> \EE y.
"""
d = np.array(x)-np.array(y)
d = np.compress(np.not_equal(d,0), d, axis=-1)
n = len(d)
inds = np.argsort(np.abs(d))
sign_diff = np.sign(d)
W = np.sum([sign_diff[inds[i]]*(i+1) for i... | 5,290,119 |
def bucket(
nodes: Iterable[BaseNode],
contraction_order: Sequence[network_components.CopyNode]
) -> Iterable[BaseNode]:
"""Contract given nodes exploiting copy tensors.
This is based on the Bucket-Elimination-based algorithm described in
`arXiv:quant-ph/1712.05384`_, but avoids explicit construction of ... | 5,290,120 |
def contains_charset(s: str) -> bool:
"""Judge if given str is a valid charset name, return a boolean.
The str could be charset name like 'utf-8' and the code page number
like '65001'. Letter case ignored."""
return EncodingInfo._all_charsets_lower_cased_name.__contains__(s.lower()) | 5,290,121 |
def prioritize_file_types(k):
""" Give a proper priority to certain file types when sorting """
# BN databases should always go first
if k.endswith('.bndb'):
return 0
# Definition files matter more than raw files
if any(k.endswith(e) for e in ('.def', '.idt')):
return 5
return 10 | 5,290,122 |
def set_stylesheet(path):
"""
Set the stylesheet to use the desired path in the Qt resource
system (prefixed by `:/`) or generically (a path to a file on
system).
:path: A full path to a resource or file on system
"""
# get the QApplication instance, or crash if not set
app = QtW... | 5,290,123 |
def cvar_importance_sampling_biasing_density(pdf, function, beta, VaR, tau, x):
"""
Evalute the biasing density used to compute CVaR of the variable
Y=f(X), for some function f, vector X and scalar Y.
The PDF of the biasing density is
q(x) = [ beta/alpha p(x) if f(x)>=VaR
[ (1-b... | 5,290,124 |
def test_minimum_image_distance():
"""Test the method to calculate minimum image distance. Arguments for MC.py are set to be easy ones so that expected value is 2"""
G = mm.geom.Geom(method='random', num_particles=1000, reduced_den=1.0)
trial_point1 = np.array([1, 0, 0])
trial_point2 = np.array([9, 0, ... | 5,290,125 |
def account_invite_get(invite_id: UUID = typer.Argument(..., help="UUID of the invite")):
"""
Gets an specific invitation details, it only works if the invitation was made for the current logged user.
"""
client = Client(profile=global_options['profile'])
dump_json(client.get_invite(invite_id)) | 5,290,126 |
def test_validate_not_success(mock_send, mock_status):
"""Don't update status if submission NOK."""
vsp = Vsp()
vsp._status = const.UPLOADED
mock_send.return_value = {'status': 'not_success'}
vsp._version = "1234"
vsp._identifier = "12345"
vsp.validate()
mock_send.assert_called_once_with... | 5,290,127 |
def is_descendant(path, start):
"""
pathはstartのサブディレクトリにあるか。
ある場合は相対パスを返す。
"""
if not path or not start:
return False
rel = join_paths(relpath(path, start))
if os.path.isabs(rel):
return False
if rel.startswith("../"):
return False
return rel | 5,290,128 |
def get_logger(log_file: str = 'nineturn.log', level_to_file: str = 'INFO'):
"""Return the nineturn logger. Not for used by library users."""
LOGGING = {
"version": 1,
"disable_existing_loggers": "false",
'filters': {'exclude_errors': {'()': _ExcludeErrorsFilter}},
"formatters": ... | 5,290,129 |
def transforms_treeleaffeaturizer(
data,
predictor_model,
output_data=None,
model=None,
suffix=None,
label_permutation_seed=0,
**params):
"""
**Description**
Trains a tree ensemble, or loads it from a file, then maps a numeric
feature vecto... | 5,290,130 |
def _sympysage_im(self):
"""
EXAMPLES::
sage: from sympy import Symbol, im
sage: assert imag_part(x)._sympy_() == im(Symbol('x'))
sage: assert imag_part(x) == im(Symbol('x'))._sage_()
"""
from sage.functions.other import imag_part
return imag_part(self.args[0]._sage_()) | 5,290,131 |
async def fetch(url: str, session: network.Session) -> Comment:
"""
Asynchronously fetch a single comment to a deviation.
Args:
url: The URL to a comment.
session: A session to use for requesting data.
Returns:
A single comment.
Raises:
BadCommentPageError: If inst... | 5,290,132 |
def updater_fields(
fields: Optional[Iterable[str]] = None,
null_fields: Optional[Iterable[str]] = None,
updater_flag_preffix="update_",
**kwargs: Any,
) -> dict[str, Any]:
"""
Prepares the specified fields in **kwargs to be used in an "update"
repository function.
This function is inte... | 5,290,133 |
def reduce_angle(angle: Real) -> float:
"""
Move angle in radians to range (-π, π]
"""
if -PI < angle <= PI:
return angle
n = angle / TWOPI
n = ceil(n) if n < 0 else floor(n)
return angle - n * TWOPI | 5,290,134 |
def getATR(reader):
"""Return the ATR of the card inserted into the reader."""
connection = reader.createConnection()
atr = ""
try:
connection.connect()
atr = smartcard.util.toHexString(connection.getATR())
connection.disconnect()
except smartcard.Exceptions.NoCardException:
... | 5,290,135 |
def create_cnn_model(size_output=None, tf_print=False):
"""
create keras model with convolution layers of MobileNet and added fully connected layers on to top
:param size_output: number of nodes in the output layer
:param tf_print: True/False to print
:return: keras model object
"""
... | 5,290,136 |
def test_create_proxy(nexus_client, repo_format, strict, c_policy, faker):
"""
Test all variations of this command:
nexus3 repo create proxy (npm|pypi|raw|rubygems|yum)
<repo_name> <remote_url>
[--blob=<store_name>] [--strict-content] --cleanup c_policy
"""
strict_name = stric... | 5,290,137 |
def get_vertex_ids(g, my_query, my_query_annot_field, row_or_col):
""" Extract vertices with the values in my_query in my_query_annot_field.
If row_or_col is "row", my_query will only be searched for in row vertices.
If row_or_col is "col", my_query will only be searched for in column
vertices. If row_o... | 5,290,138 |
def transform_sa_geometries(input_filepath: Path, output_filepath: Path) -> None:
"""Transform Small Area geometries.
Args:
input_filepath (Path): Path to Raw Small Area Geometries Data
output_filepath (Path): Path to Clean Small Area Geometries Data
"""
sa_geometries = (
gpd.re... | 5,290,139 |
def test_user_cannot_cancel_broadcast_without_permission(
mocker,
client_request,
service_one,
active_user_view_permissions,
):
"""
separate test for cancel_broadcast endpoint, because admin users are allowed to cancel broadcasts
"""
service_one['permissions'] += ['broadcast']
mocke... | 5,290,140 |
def data_preparation_fr(country_attributes,reversed_dates=True):
"""
Creates an sorted dictionary of dates, new cases and tests for the French Covid-19 data
Parameters
----------
country_attributes : dict
A dictionary containing country attributes
reversed_dates : bool
A boolean... | 5,290,141 |
def get_segment_from_frame(caller_frame: types.FrameType, segment_type, return_locs=False) -> str:
"""Get a segment of a given type from a frame.
*NOTE*: All this is rather hacky and should be changed as soon as python 3.11 becomes widely
available as then it will be possible to get column information from... | 5,290,142 |
def distribute_mpi_all(dimension, mpi_comm=MPI.COMM_WORLD):
"""
Computes the start indexes and bin sizes of all splits to distribute
computations across an MPI communicator.
Parameters
----------
dimension : int
the size of the array to be distributed
mpi_comm : mpi4py.MPI.Comm, opt... | 5,290,143 |
def gradient_cmap(colors, nsteps=256, bounds=None):
"""Return a colormap that interpolates between a set of colors.
Ported from HIPS-LIB plotting functions [https://github.com/HIPS/hips-lib]
"""
ncolors = len(colors)
# assert colors.shape[1] == 3
if bounds is None:
bounds = np.linspace(... | 5,290,144 |
def single_expr(self):
"""Check defining of partition clause with single expr."""
expected = convert_output(
"""
x | s | sum
----+---+------
1 | a | 2
1 | b | 2
2 | b | 2
"""
)
execute_query(
"SELECT x,s, sum(x) OVER (PARTITION BY x) AS sum FROM val... | 5,290,145 |
def get_profile(sqshrc="~/.sqshrc", connector='Sybase',
hostname=None, username=None, password=None):
"""
get database, username, password from .sqshrc file e.g.
\set username="user"
"""
if connector == 'Sybase':
shost, suser, spass = None, None, None
_ = lambda x: x.... | 5,290,146 |
def test_delete_schedule(flask_client, mock_id, db_init, db_teardown):
"""Test getting a schedule."""
response = flask_client.delete(f"/msg-scheduler?id={mock_id}")
assert response.status_code == 200 | 5,290,147 |
def confounder_ppca(X, latent_dim, holdout_portion):
"""
Function to estimate a substitute confounder using PPCA.
Adopted from the deconfounder_tutorial.ipynb
https://github.com/blei-lab/deconfounder_tutorial
Args:
X: A numpy array or pandas dataframe of the original covariates
d... | 5,290,148 |
def test_dict_content_types():
"""Test dict_content_types."""
assert deserialize.dict_content_types(Dict[int, int], "") == (int, int)
assert deserialize.dict_content_types(Dict[str, int], "") == (str, int)
assert deserialize.dict_content_types(Dict[str, Dict[str, str]], "") == (str, Dict[str, str])
... | 5,290,149 |
def create_job(user_folder: str, user_id: str, upload_file: str) -> Tuple[str, str, str]:
"""Upload several files and check they are properly created - utils method."""
file_service.setup_jobs_result_folder(user_id=user_id, job_id='test-job')
job_run_folder = join(user_folder, 'jobs', 'test-job',
... | 5,290,150 |
def get_vserver(svm_cx, vserver_name):
"""
Return vserver information.
:return:
vserver object if vserver found
None if vserver is not found
:rtype: object/None
"""
vserver_info = netapp_utils.zapi.NaElement('vserver-get-iter')
query_details = netapp_utils.zapi.NaElement.cre... | 5,290,151 |
def saveData(dataset={}, filepath= 'defaultFilePath'):
"""
Saves the 'DATA' component of a dataset as an ascii file
in XAYAcore graph format.
"""
return xayacore.writeGraph(dataset['DATA'], filepath) | 5,290,152 |
def _move_cols_to_front(data: pd.DataFrame, column_count: int = 1) -> pd.DataFrame:
"""
Move N columns from end to front of DataFrame.
Parameters
----------
data : pd.DataFrame
The input DataFrame
column_count : int, optional
The number of columns to move (the default is 1)
... | 5,290,153 |
def qual_vector(qual=None, capBQ=45, minBQ=0.25):
"""convert the base call quality score to related values for different genotypes
http://emea.support.illumina.com/bulletins/2016/04/fastq-files-explained.html
https://linkinghub.elsevier.com/retrieve/pii/S0002-9297(12)00478-8
@Note The parameter "q... | 5,290,154 |
def clear_page_cache(request, page):
"""
This will clear Django's entire cache after a page edit. It is ugly, but Django's
cache mechanism doesn't currently support a way to easily clear based on template
fragments specifics.
"""
if get_clear_cache() and isinstance(page, (GridItem, GridIndexPag... | 5,290,155 |
def load_runner(
tag: t.Union[str, Tag],
*,
predict_fn_name: str = "predict",
device_id: str = "CPU:0",
predict_kwargs: t.Optional[t.Dict[str, t.Any]] = None,
resource_quota: t.Union[None, t.Dict[str, t.Any]] = None,
batch_options: t.Union[None, t.Dict[str, t.Any]] = None,
model_store: "... | 5,290,156 |
def random_uuid() -> str:
"""description of random_uuid"""
return str(uuid4()) | 5,290,157 |
def _parse_see_args(dev_id, data):
"""Parse the payload location parameters, into the format see expects."""
kwargs = {
'gps': (data[ATTR_LATITUDE], data[ATTR_LONGITUDE]),
'dev_id': dev_id
}
if ATTR_GPS_ACCURACY in data:
kwargs[ATTR_GPS_ACCURACY] = data[ATTR_GPS_ACCURACY]
if... | 5,290,158 |
def _updateStartTimes(srow, delayDF, temkey):
"""
Update the starttimes to reflect the values trimed in alignement
"""
statsdict = srow.Stats
sdo = srow.Stats
for key in sdo.keys():
temtemkey = temkey.loc[temkey.NAME == key].iloc[0]
delaysamps = delayDF[delayDF.Events == key].ilo... | 5,290,159 |
def playlist_detail(playlist_id, limit=1000):
"""
根据歌单id获取歌单的详情
Args:
playlist_id:
limit:最大歌曲数为1000
"""
for i in range(retry_times):
try:
base_url = 'http://music.163.com/api/playlist/detail?id=%s&limit=%s' % (playlist_id, limit)
res = requests.get(ba... | 5,290,160 |
def _rebuild_sqlite_table(model):
"""Sqlite doesn't support most alter table statments. This streamlines the
rebuild process"""
try:
cursor = connection.cursor()
table_name = model._meta.db_table
# Build create staement from django
model._meta.db_table = "%s_temp" % tabl... | 5,290,161 |
def checksum(s, m):
"""Create a checksum for a string of characters, modulo m"""
# note, I *think* it's possible to have unicode chars in
# a twitter handle. That makes it a bit interesting.
# We don't handle unicode yet, just ASCII
total = 0
for ch in s:
# no non-printable ASCII chars, including space... | 5,290,162 |
def validate_path_file(path_file) -> bool:
"""Validate th path of a file."""
if os.path.exists(path_file) and os.path.isfile(path_file):
if os.access(path_file, os.R_OK):
return True
return False | 5,290,163 |
def save_project_activiteiten(project):
"""
Extract all project activities from Sap import and save them to database.
@param project: project object to link to the project activity
"""
unique_activiteit_codes = Sap.objects.order_by('object').values('object', 'objectomschrijving').distinct()
for... | 5,290,164 |
async def test_zeroconf_ignore(
hass: HomeAssistant,
vizio_connect: pytest.fixture,
vizio_bypass_setup: pytest.fixture,
vizio_guess_device_type: pytest.fixture,
) -> None:
"""Test zeroconf discovery doesn't throw an error when there's an existing ignored source."""
entry = MockConfigEntry(
... | 5,290,165 |
def user(ctx):
"""Remote user actions"""
pass | 5,290,166 |
def getWiFiList():
"""Get a list of WiFi networks"""
data = load(path['config'])
status_wifi = None
if data['Flag']['Wifi'] == "0":
os.system("sudo ifconfig wlan0 up")
status_wifi = True
proc = subprocess.Popen('sudo iwlist scan 2>/dev/null', shell=True, stdout=subprocess.PIPE, )
... | 5,290,167 |
def vol_std(data):
""" Return standard deviation across voxels for 4D array `data`
Parameters
----------
data : 4D array
4D array from FMRI run with last axis indexing volumes. Call the shape
of this array (M, N, P, T) where T is the number of volumes.
Returns
-------
std_... | 5,290,168 |
def parse_component_arg(parser, storage: Storage, component: str):
"""Wrapper around parse_storage_component() to parse CLI arguments into patch elements"""
try:
component = parse_storage_component(storage, component)
except ValueError:
parser.error(f"invalid component: {component}")
if ... | 5,290,169 |
def parse_flags(flags={}, preset="", **other) -> "int":
"""
Optimised for "parse_flags(**settings)" use-case,
returns a flags integer suitable for view.add_regions.
"""
preset = presets[preset].get("flags", {})
orsum_flags = 0
for flag_name, active in ChainMap(flags, preset, dict.fromkeys(toggled_flags, True))... | 5,290,170 |
def osPrefix():
"""Returns system prefix
Args:
No args
Returns:
linux/windows
Raises:
Nothing
"""
name = os.name
if name == "posix": return "linux"
return "windows" | 5,290,171 |
def teardown_module(module=None):
"""
Reset all helper caches when leaving module
:param module:
:return:
"""
helper.teardown() | 5,290,172 |
def _get_uniprot_id(agent):
"""Get the Uniprot ID for an agent, looking up in HGNC if necessary.
If the Uniprot ID is a list then return the first ID by default.
"""
up_id = agent.db_refs.get('UP')
hgnc_id = agent.db_refs.get('HGNC')
if up_id is None:
if hgnc_id is None:
# I... | 5,290,173 |
def adv_rk2(y, t, dt, scratch1, scratch2):
"""Advance the solution one step using the 2nd order R-K method"""
n = len(y)
scratch1 = rhs(y, t)
for i in range(n):
scratch2[i] = y[i] + dt*scratch1[i]
t2 = t + dt
scratch2 = rhs(scratch2, t2)
for i in range(n):
y[i] = y[i] + 0.5*d... | 5,290,174 |
def unit_axial_thermal_deck_load(c: Config, run: bool):
"""Response to unit axial thermal deck loading."""
damage_scenario = thermal_damage(axial_delta_temp=c.unit_axial_delta_temp_c)
c, sim_params = damage_scenario.use(c)
axis_values = pd.read_csv("validation/axis-screenshots/thermal-min-max.csv")
... | 5,290,175 |
def _get_arg(num):
"""
:return:
A unicode string of the requested command line arg
"""
if len(sys.argv) < num + 1:
return None
arg = sys.argv[num]
if isinstance(arg, byte_cls):
arg = arg.decode('utf-8')
return arg | 5,290,176 |
def calc_distance_matrix(mols):
"""
Calculate a full distance matrix for the given molecules. Identical molecules get a score of 0.0 with the maximum
distance possible being 1.0.
:param mols: A list of molecules. It must be possible to iterate through this list multiple times
:return: A NxN 2D array... | 5,290,177 |
def fetch_environment(file_path, file_id, module_id):
"""Return file environment dictionary from *file_path*.
*file_id* represent the identifier of the file.
*module_id* represent the identifier of the module.
Update the *environment* if available and return it as-is if the file
is not readable.
... | 5,290,178 |
def test_medication_3(base_settings):
"""No. 3 tests collection for Medication.
Test File: medicationexample0301.json
"""
filename = base_settings["unittest_data_dir"] / "medicationexample0301.json"
inst = medication.Medication.parse_file(
filename, content_type="application/json", encoding=... | 5,290,179 |
def retrieve_token() -> str:
"""Retrieves token from BEARER_TOKEN_PATH"""
bearer_file_path = Path(BEARER_TOKEN_PATH)
if not bearer_file_path.is_file():
with login_lock:
if not bearer_file_path.is_file():
return login()
with bearer_file_path.open('r') as f:
tok... | 5,290,180 |
def classification_phi_gradient(input_to_class, data):
"""
This is about a very simple model: there's an input layer, and a softmax output layer. There are no hidden layers, and no biases.
This returns the gradient of phi (a.k.a. negative the loss) for the <input_to_class> matrix.
<input_to_class> is a ... | 5,290,181 |
def getData(stops):
"""Retrieves data from the MTA's realtime feed, then creates a train object for each
train described in the feed and stores each train object in a master list.
"""
feed = gtfs_realtime_pb2.FeedMessage()
response = urllib.urlopen('http://datamine.mta.info/mta_esi.php?key=af9eed620... | 5,290,182 |
def ringing(img2d, alpha=0.5, noiseSize=0, noiseValue=2, clip=True, seed=None):
"""
https://bavc.github.io/avaa/artifacts/ringing.html
:param img2d: 2d image
:param alpha: float, reconstruction quality (0-1) optimal values for tv ringing modeling is 0.3-0.99
:param noiseSize: float, noise size (0-1... | 5,290,183 |
def try_rules(
context: Sequence[Expression],
goal: Expression,
general_rules: Sequence[Expression],
verbosity: int = 0,
) -> List[Expression]:
"""context and context_rules are disjoint, all in context_rules satisfy
is_rule(), whereas none of those in context do."""
assert verbosity >= 0
... | 5,290,184 |
def dissimilarity_loss(latents, mask):
"""
Minimize the similarity between the different instrument latent representations
Arguments:
latents {torch.tensor} -- latent matrix from the encoder of shape: (B, 1, T', N)
mask {torch.tensor} -- boolean mask: True when the signal is 0.0; shape (B, ... | 5,290,185 |
def _stdin_ready_other():
"""Return True, assuming there's something to read on stdin."""
return True | 5,290,186 |
def text_objects(text, font, color):
"""
Function for creating text and it's surrounding rectangle.
Args:
text (str): Text to be rendered.
font (Font): Type of font to be used.
color ((int, int, int)): Color to be used. Values should be in range 0-255.
Returns:
Text surf... | 5,290,187 |
def test_date_uses_date_obs(hmi_synoptic):
"""Check that the date uses the date-obs key as well."""
hmi_synoptic.meta['date-obs'] = hmi_synoptic.meta.pop('t_obs')
assert hmi_synoptic.date is not None | 5,290,188 |
def testCustomWebRoot(route, server):
"""
Tests the ability of plugins to serve their own custom server roots.
"""
resp = server.request(route)
assertStatusOk(resp)
assert resp.json == ['custom REST route'] | 5,290,189 |
def split_list(a: List, chunk_size: int):
"""
split a large list to small chunk with the specified size
:param a:
:param chunk_size:
:return:
"""
chunks = []
list_length = len(a)
start_pos = 0
end_pos = start_pos + chunk_size
while end_pos <= list_length:
chunks.appe... | 5,290,190 |
def prepare_logger(logger_name, verbosity, log_file=None):
"""Initialize and set the logger.
:param logger_name: the name of the logger to create
:type logger_name: string
:param verbosity: verbosity level: 0 -> default, 1 -> info, 2 -> debug
:type verbosity: int
:param log_file: if not None, ... | 5,290,191 |
def process_results(news_list):
"""
Function that processes the news result and transform them to a list of Objects
Args:
news_list: A list of dictionaries that contain news sources
Returns :
news_results: A list of news objects
"""
news_results = []
for news_item in news_l... | 5,290,192 |
def slice_slice(old_slice, applied_slice, size):
"""Given a slice and the size of the dimension to which it will be applied,
index it with another slice to return a new slice equivalent to applying
the slices sequentially
"""
step = (old_slice.step or 1) * (applied_slice.step or 1)
# For now, u... | 5,290,193 |
def initialize_lims():
"""Initialize LIMS.""" | 5,290,194 |
def add_bed_output_ids_to_dic(output, ids_dic):
"""
Add column 4 IDs from a BED output on command line (e.g. from
cat test.bed) to ids_dic.
>>> check_cmd = "cat test_data/test3.bed"
>>> output = subprocess.getoutput(check_cmd)
>>> ids_dic = {}
>>> add_bed_output_ids_to_dic(output, ids_dic)
... | 5,290,195 |
def test_hobbyevent_unauthenticated_create(api_client, valid_hobbyevent_data):
""" Unauthenticated user should not be able to create a new HobbyEvent """
url = reverse('hobbyevent-list')
hobbyevent_count = HobbyEvent.objects.count()
response = api_client.post(url, data=valid_hobbyevent_data, format='jso... | 5,290,196 |
def load_spec():
"""Attempts to load the local build specification"""
if not os.path.exists(CONFIG):
raise SpecException("Config file not found: Please create" +
" '{}' in your project directory".format(CONFIG))
else:
spec = toml.load(CONFIG)
missing = []
def ens... | 5,290,197 |
def _parse_compile_log(log):
"""parses the pdflatex compile log"""
if log is None:
return {}
IMAGES = {}
i = 0
image_found = False
for line in log.split('\n'):
if not image_found:
m = re.match("^File: (.*) Graphic file", line)
if m:
IMAGES... | 5,290,198 |
def is_correct(list):
"""
判断一个list中单词是否正确
:param list:待识别的单词列表
:return: 正确的单词列表
"""
temp = []
rightlist = spell.known(list) # {'morning'}
global count
global num
count = count + len(list) - len(rightlist)
num = num + len(list)
for item in rightlist:
temp.append(item)... | 5,290,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.