content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def psnr_compute(img_batch, ref_batch, batched=False, factor=1.0, clip=False):
"""Standard PSNR."""
if clip:
img_batch = torch.clamp(img_batch, 0, 1)
if batched:
mse = ((img_batch.detach() - ref_batch) ** 2).mean()
if mse > 0 and torch.isfinite(mse):
return 10 * torch.lo... | 5,286,600 |
def solve(input: list) -> dict:
"""Solve equation with the quadratic formula\n
**Please input a list: [a, b, c] for an equation like ax² + bx + c**
Examples of keys: ["step 1"], ["step 2"], etc.
Final answer: ["final answer"]"""
return steps | 5,286,601 |
def main() -> None:
"""The main function."""
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument('input', help='input image file')
ap.add_argument('output', help='output DNG file')
args = ap.parse_args()
image_tmp = np.float32(Image.open(args.input).convert('RGB'))
image = np.... | 5,286,602 |
def test_negative_rotation_from_carla():
""" Test that Rotation throws a ValueError if incorrect carla_rot argument
is passed. """
DummyType = namedtuple("DummyType", "pitch, yaw, roll")
dummy_instance = DummyType(10, 20, 30)
with pytest.raises(ValueError):
Rotation.from_carla_rotation(dummy... | 5,286,603 |
def extend_dict(d1, d2):
"""Extends d1 with d2, removing duplicates from d1"""
d1_keys = set(d1.keys())
d2_keys = set(d2.keys())
intersect_keys = d1_keys.intersection(d2_keys)
return dict(**{o: d1[o] for o in d1_keys - intersect_keys}, **d2) | 5,286,604 |
def test_st_write_svg():
"""Test the write_svg component"""
# Given
svg = """
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
<circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" />
</svg>
"""
# When
components.write_svg(svg=svg)
# Then
# raise notIm... | 5,286,605 |
def gdf_bbox(gdf):
"""Make a bounding box around all geometries in a GeoDataFrame.
Parameters
----------
gdf : :class:`geopandas.GeoDataFrame`
GeoDataFrame with geometries around which to define bounding box
Returns
-------
:class:`geopandas.Polygon`
Bounding box
"""
... | 5,286,606 |
def lint(proto: Proto) -> int:
"""Run default linter on given proto.
Returns number of warning reported.
"""
return Linter().lint(proto) | 5,286,607 |
def login():
"""Redirects the login to the real blaulichtSMS Dashboard API to get a real session token.
Otherwise, the application would not be able to login to the blaulichtSMS Einsatzmonitor web application.
:return: An blaulichtSMS Dashboard API session element in JSON
"""
login_data = request.... | 5,286,608 |
def RemoveTime(output):
"""Removes all time information from a Google Test program's output."""
return re.sub(r'\(\d+ ms', '(? ms', output) | 5,286,609 |
def IsInclude(line):
"""Return True if line is an include of another file."""
return line.startswith("@include ") | 5,286,610 |
def test_pwd_no_normalize(app, client):
"""Verify that can log in with original but not normalized if have
disabled normalization
"""
authenticate(client)
data = dict(
password="password",
new_password="new strong password\N{ROMAN NUMERAL ONE}",
new_password_confirm="new str... | 5,286,611 |
def largest_n_element(m_dict, n):
"""Get the largest n words from the dict
Args:
m_dict (dict): the dict with word as key and the count of word as value
n (int): the number of elements we have to return
Returns:
list_: the n largest pairs in the dict order by value
"""
# u... | 5,286,612 |
def f(x, a):
"""Fitting function"""
return a/np.log2(x) | 5,286,613 |
def err_ratio(predict, dataset, examples=None, verbose=0):
"""Return the proportion of the examples that are NOT correctly predicted.
verbose - 0: No output; 1: Output wrong; 2 (or greater): Output correct"""
examples = examples or dataset.examples
if len(examples) == 0:
return 0.0
right = 0... | 5,286,614 |
def filename_set_error_plot() -> str:
"""Returns filename of set error plot. """
filename = f"set_error_plot{C.postfix_plot_image_format}"
return filename | 5,286,615 |
def test_vat_consistency_value_error(torch_device, simple_classification_model):
""" Test consistency type besides mse, kl, and mse_regress raises ValueError.
Args:
torch_device (torch.device): Device to use
simple_classification_model (pytest.fixture function): Function to create simple model
... | 5,286,616 |
def _get_label_from_dv(dv, i):
"""Return label along with the unit of the dependent variable
Args:
dv: DependentVariable object.
i: integer counter.
"""
name, unit = dv.name, dv.unit
name = name if name != "" else str(i)
label = f"{name} / ({unit})" if unit != "" else name
r... | 5,286,617 |
def test_get_obj_list(provider, mocker):
"""Test that we get the right objects"""
mocked_folder = mocker.MagicMock()
mocked_container = mocker.MagicMock(view=[1, 2, 3])
provider.content.viewManager.CreateContainerView.return_value = mocked_container
object_list = provider._get_obj_list(vim.VirtualMa... | 5,286,618 |
def on_connect(client, user_data, flags, connection_result_code): # (7)
"""on_connect is called when our program connects to the MQTT Broker.
Always subscribe to topics in an on_connect() callback.
This way if a connection is lost, the automatic
re-connection wi... | 5,286,619 |
def upload_blob(bucket_name, source_file_name, destination_blob_name):
"""Uploads a file to the bucket."""
storage_client = storage.Client()
bucket = storage_client.get_bucket(bucket_name)
blob = bucket.blob(destination_blob_name)
blob.upload_from_filename(source_file_name)
print('File {} uplo... | 5,286,620 |
def resample_anglebands(array, imgref, filename_out, filename_intermed=None):
"""Resample angle bands.
Parameters:
array (arr): matrix of angle values.
imgref (str): path to image that will be used as reference.
filename_out (str): filename of the resampled angle band.
filename_inter... | 5,286,621 |
def damaged_now(feat):
"""Pobiera z OSM poprzednią wersję obiektu i sprawdza czy uszkodzenie powstało w wyniku tego changesetu"""
if int(feat["version"]) > 1:
obj_now = get_Object(feat, int(feat["version"]))
obj_before = get_Object(feat,int(feat["version"])-1)
return addr_edited(obj_now,... | 5,286,622 |
def get_land_only(dtset, tolerance=0.5):
"""
Returns True where land.
:param dtset:
:return:
"""
if 'LANDFRAC' in dtset:
mask = dtset['LANDFRAC']>tolerance
if 'time' in mask.dims:
return mask.isel(time=0).squeeze()
else: return mask
else:
print('LA... | 5,286,623 |
def current_tree() -> GameTree:
"""Return the current tree."""
return _current_tree | 5,286,624 |
def lin_segment_from_gcode(command: GCmd, current_pose: np.ndarray, ds: float, is_absolute: bool, curr_vel: float,
curr_acc: float, orig_offset: Optional[Coordinate] = None) -> LinearSegment:
"""
Generates a linear trajectory segment in task space from a linear G-code command.
:pa... | 5,286,625 |
def get_facebook_posts(
profile_id: int,
*,
start_date: Optional[datetime.date] = None,
) -> pd.DataFrame:
"""Read data for posts on Facebook profile via Quintly API.
Args:
profile_id (int): ID of profile to request data for.
start_date (Optional[datetime.date], optional): Date of e... | 5,286,626 |
def tickers_return_rate_plot(Tickers):
"""
Tickers: a dictionary contains objects of class Ticker.
"""
new_feature = 'Return Rate'
for Ticker_name in Tickers:
ticker_return_rate(Tickers[Ticker_name])
for Ticker_name in Tickers:
Tickers[Ticker_name].get_ticker_data()... | 5,286,627 |
def get_seconds(value, scale):
"""Convert time scale dict to seconds
Given a dictionary with keys for scale and value, convert
value into seconds based on scale.
"""
scales = {
'seconds': lambda x: x,
'minutes': lambda x: x * 60,
'hours': lambda x: x * 60 * 60,
'days': lambda x: x * 60 * 60 *... | 5,286,628 |
def selectEvents(hazard_db):
"""
Select all events from _tblEvents_.
:param hazard_db: :class:`HazardDatabase` instance.
:returns: :class:`numpy.recarray` containing the full listing of each
event in the table.
"""
query = "SELECT * FROM tblEvents ORDER BY eventMaxWind ASC"
... | 5,286,629 |
def delete_cutting_plane(n):
"""
Delete the cutting plane with index `n`
"""
gcv().delete_cutting_plane(n) | 5,286,630 |
def remove_surrogates(s, errors='replace'):
"""Replace surrogates generated by fsdecode with '?'"""
return s.encode('utf-8', errors).decode('utf-8') | 5,286,631 |
def fetch_html(page_url):
""" Returns the HTML of the page at page_url """
html = ""
try:
# spoof header for sites like Amazon that make it more dfficult to scrape
req = requests.get(page_url)
html = req.text
except urllib.error.URLError as e:
print("page request failed: ... | 5,286,632 |
def np_mat_to_rot6d(np_mat):
""" Get 6D rotation representation for rotation matrix.
Implementation base on
https://arxiv.org/abs/1812.07035
[Inputs]
flattened rotation matrix (last dimension is 9)
[Returns]
6D rotation representation (last dimension is 6)... | 5,286,633 |
def getHandler(database):
"""
a function instantiating and returning this plugin
"""
return SpamReports(database, 'feedback', public_endpoint_extensions=['insert']) | 5,286,634 |
def test_sampling_is_correct():
""" Check if sampling multiple times we don't get incorrect values"""
buffer = get_filled_buffer_with_dones(frame_history=4)
for i in range(100):
probs, idxs, tree_idxs = buffer.sample_batch_transitions(6)
buffer.get_transitions(idxs)
nt.assert_array... | 5,286,635 |
def createParameterWidgetRemote(instruments, doexec=True):
""" Create a parameter widget in a remote process.
Note: this can only be used if all the Instruments are remote instruments.
"""
p = mp.Process(target=createParameterWidget, args=(instruments,))
p.start()
return p | 5,286,636 |
def generate_query_by_keeping_granularity(
query: SQLQuery,
group_by: list,
current_step_name: str,
query_to_complete: str = "",
aggregated_cols=None,
group_by_except_target_columns=None,
) -> Tuple[SQLQuery, str, list]:
"""
On some steps, when we do the Group By we will need to keep the... | 5,286,637 |
def get_access_token(request):
"""Get the access token, or fetch a new one if it is possible, otherwise return None."""
if not get_setting("STORE_TOKENS", False):
return None
prefix = get_setting("SESSION_KEY_PREFIX", DEFAULT_SESSION_KEY_PREFIX)
access_token = request.session.get(f"{prefix}acce... | 5,286,638 |
def is_some_float(arg, allow_none=False):
"""
>>> is_some_float(3)
False
>>> is_some_float(3.5)
True
>>> import numpy as np
>>> is_some_float(np.float64(3.5))
True
>>> is_some_float(np.double(3.5))
True
>>> is_some_float(None)
False
>>> is_some_float(None... | 5,286,639 |
def auto_delete_service_path_on_delete(sender, instance, **kwargs):
"""
Delete the project file if the service is deleted
"""
if instance.service_path:
path = os.path.join(settings.MEDIA_ROOT, instance.service_path)
if os.path.isdir(path):
shutil.rmtree(path) | 5,286,640 |
def restart_services():
"""
Restart all map services to ensure config file changes are recognized
"""
run('sudo service uwsgi restart && sudo service uwsgi status tilestache')
run('sudo service nginx restart && sudo service nginx status')
run('sudo stop tilemill && sudo start tilemill && sudo st... | 5,286,641 |
def plot_recovery_vs_independent(matrix, output_dir, name):
"""Plot how many factors are recovered and in how many independent groups.
Plot how many factors of variation are independently captured in a
representation at different thresholds. It takes as input a matrix
relating factors of variation and ... | 5,286,642 |
def deletequiz(quizID):
"""Renders the create quiz page for educators."""
if not current_user.check_educator():
return render_template('errors/error403.html'), 403
quiz = validate_quiz_link(current_user, quizID)
delQuizForm = DeleteForm(prefix='quiz')
delQnForm = DeleteForm(prefix='qn')
... | 5,286,643 |
async def _update_model_from_server(
model_server: EndpointConfig, project: "Project"
) -> None:
"""Load a zipped Rasa NLU model from a URL and update the passed
project."""
if not is_url(model_server.url):
raise InvalidURL(model_server)
model_directory = tempfile.mkdtemp()
new_model_... | 5,286,644 |
def get_uframe_calibration_events_by_uid(id, uid):
""" Get list of calibration events from uframe for a specific sensor asset uid.
Function also outfitted for using asset id instead of uid. Both required for error processing at this time.
On status_code(s):
200 Success, return events
20... | 5,286,645 |
def freqz(b, a=1, worN=None, whole=0, plot=None):
"""
Compute the frequency response of a digital filter.
Given the numerator ``b`` and denominator ``a`` of a digital filter compute
its frequency response::
jw -jw -jmw
jw B(e) b[0] + b[1]e + .... + b... | 5,286,646 |
def deploy(ctx, repo=None):
""" Deploy the project to PyPI
Can specify a custom repo defined in your .pypirc file with the
repo keyword. Default is to deploy to standard pypi index.
Parameters:
repo (str):
The pypi repo index to upload to. Defined in .pypirc file.
"""
if ... | 5,286,647 |
def split_amp_phase(array):
"""
takes a complex array and returns the amplitude and the phase
"""
amp = np.abs(array)
phase = np.angle(array)
return amp, phase | 5,286,648 |
def get_project(line):
""" Returns project of reactor line. """
start = re.search(r' ', line).end()
end = re.search(r' ', line[start:]).start() + start
return line[start:end] | 5,286,649 |
def points_2_inches(points) -> float:
"""
Convert points to inches
"""
return points / 72 | 5,286,650 |
def make_optional_parser(arg: t.Any) -> comb.Parser:
"""Return parser for t.Optional[arg]."""
return comb.Or(infer_parser(arg), infer_parser(type(None))) | 5,286,651 |
def clientes():
"""
Rota para aba de clientes. Mostra na tela uma representação do csv de clientes
Não é necessário modificar nada nessa função
"""
df = pd.read_csv('data/clientes.csv', dtype=object, sep=';')
df = df.replace(np.nan, '', regex=True)
return render_template('clientes.htm... | 5,286,652 |
def seq_metrics_path(build: int, data_type: str, data_source: str, version: int) -> str:
"""
Path to metadata file associated with samples in the callset for seqr sample QC.
"""
return f"{sample_qc_folder(build, data_type, data_source, version)}/resources/callset_seq_metrics.txt" | 5,286,653 |
async def test_withdraw():
"""
申请提现虚拟币
address true string 提现地址
amount true string 提币数量
currency true string 资产类型 btc, ltc, bch, eth, etc ...
(火币Pro支持的币种)
fee false string 转账手续费
addr-tag false string 虚拟币共享地址tag,
... | 5,286,654 |
def from_therion_sql(basename):
"""
Creates the Kgraph from on SQL file exported from a Therion survey file.
Parameters
----------
basename : string
The base name used for the input files.
The input file is named using the following convention:
- basename.sql: the containi... | 5,286,655 |
def test_ar(session, app):
"""Assert that an Annual Report document is returned for an AR filing."""
document_meta = DocumentMetaService()
factory_business(identifier='BC1234567', entity_type=Business.LegalTypes.BCOMP.value)
with app.app_context():
filing = {
'filing': {
... | 5,286,656 |
def view_playlist(request, slug):
"""View a playlist"""
playlist = get_playlist_from_slug(slug)
if not playlist.public and (
not request.user.is_authenticated
or playlist.owner != request.user):
return redirect("notifpy:abstract")
playlist.owned = playlist.owner == reques... | 5,286,657 |
def numOfDigits(number, base = 10):
"""
given a list of numbers, return the number of digits that number has
Example:
[567] -> [3]
[5, 77, 435] -> [1, 2, 3]
Parameters:
number: an nDim list of numbers to process
Returns:
an nDim list of values
"""
# natural log (number) / log (base) = l... | 5,286,658 |
def create_validator_delegation_withdrawal(
params: DeployParameters,
amount: int,
public_key_of_delegator: PublicKey,
public_key_of_validator: PublicKey,
path_to_wasm: str
) -> Deploy:
"""Returns a standard withdraw delegation deploy.
:param params: Standard parameters used when creati... | 5,286,659 |
def is_secretary(user):
"""
Check whether the current user is in the 'Secretary' group.
"""
return Group.objects.get(name=settings.GROUP_SECRETARY) in user.groups.all() | 5,286,660 |
def tmp_gz_file(request):
"""
Create a temporary file with a FASTQ GZIP suffix.
:param request: SubRequest with ``param`` member which has \
a FASTQ GZipped suffix
:type request: _pytest.fixtures.SubRequest
:return: path to temporary file
:rtype: str or unicode
"""
_, tmp_gz_file = ... | 5,286,661 |
def parse_dot_data(dotdata):
"""Wrapper for pydot.graph_from_dot_data
Redirects error messages to the log.
"""
parser = dotparsing.DotDataParser()
try:
graph = parser.parse_dot_data(dotdata)
except dotparsing.ParseException:
raise
finally:
del parser
log.debug('P... | 5,286,662 |
async def async_setup(hass: HomeAssistant, global_config: dict):
"""Set up the Climate Scheduler component."""
config = global_config.get(DOMAIN)
if config is None:
return
climate_scheduler = ClimateScheduler(hass, config)
hass.data[DATA_CLIMATE_SCHEDULER] = climate_scheduler
return T... | 5,286,663 |
def sort_partitition(node_set_partition):
"""The set partition has naturally no order,
For the sparse graph, the order can be important when deleting crossgroup varibales in order to avoid
multicoliniarity. This function induces a fixed order (at least in the cases where the elsments sum is unique for
... | 5,286,664 |
def type_to_formatting_tag(type_):
"""Return the HTML tag corresponding to the given formatting type."""
tag = FORMATTING_TYPE_TAG_MAP.get(type_, type_)
return html_safe_string(tag) | 5,286,665 |
def estimate_recording(path):
"""
Args:
Take the path to the folders
Return:
Number of voice recording and total voice recording made.
"""
waves = []
for path , _ , files in os.walk(path):
for record in files:
if record.endswith("wav"):
... | 5,286,666 |
def points_against_by_week(position, team):
"""
INPUT: String
RETURN: Series
Finds sum of points for players of a position that
played against a team by week.
"""
# get points against team
df = position_against_team(position, team)
# get total points against per week
... | 5,286,667 |
def _reset_poll_counter():
"""Reset the poll counter"""
global NUM_POLLS
NUM_POLLS = 0 | 5,286,668 |
def my_import(class_name):
"""Return a python class given a class name.
Usage example::
Report = my_import('myclass.models.Report')
model_instance = Report()
model_instance.name = 'Test'
model_instance.save()
:param str class_name: Class name
:returns: Class object
... | 5,286,669 |
def process_regular_filter(_input: str):
""" Run a regular spatial search filter
Args:
_input (str): The input
Returns:
results (dict): Contains 'looking_for' (list) and 'in' (list)
"""
searcher = Searcher()
search_text = _input.split(",")
results = searcher.search_location... | 5,286,670 |
def mask_array_items(a, mask, verbose=True):
"""
Set `a` items to -1 in the given `mask` positions. This is in-place.
(Basically used to ensure that we do not give known answers to queries.)
Parameters
----------
a: np array, shape (n, m)
Dense array.
mask: sparse csr_matrix, shape ... | 5,286,671 |
def lightlink(q=1,b=1,h=1,l="name",m=1,o="name",set=1,shd=1,shp=1,t=1,ual=1,uao=1):
"""
http://help.autodesk.com/cloudhelp/2019/ENU/Maya-Tech-Docs/CommandsPython/lightlink.html
-----------------------------------------
lightlink is undoable, queryable, and NOT editable.
This command is used to make, break and ... | 5,286,672 |
def pipeline_commands():
"""Pipeline related commands"""
pass | 5,286,673 |
def write_output(matrix, base_fname=None, header="", suffix="",
extension="dat"):
"""
Write output matrix with a nice format, to stdout and optionally a file.
Parameters
----------
matrix : encore.utils.TriangularMatrix
Matrix containing the values to be printed
base_... | 5,286,674 |
def locally_subscribes(*args):
"""
The @subscribes decorator registers a function as being one which clients
may subscribe to via websocket. This decorator may be used to register a
function which shall be called locally anytime a notify occurs, e.g.
@locally_subscribes('example.channel')
def ... | 5,286,675 |
def _calculate_number_of_temperatures(
pvt_collector: pvt.PVT,
) -> Tuple[int, int, int, int, int, int]:
"""
Calculates, based off the PVT collector, the number of temperatures in each layer.
:param pvt_collector:
The PVT collector being modelled.
:return:
A `tuple` containing:
... | 5,286,676 |
def compress(tar_file, members):
"""
Adds files (members) to a tar_file and compress it
"""
# open file for gzip compressed writing
tar = tarfile.open(tar_file, mode="w:gz")
# with progress bar
# set the progress bar
progress = tqdm(members)
for member in progress:
... | 5,286,677 |
def encode_cf_variable(var):
"""Converts an XArray into an XArray suitable for saving as a netCDF
variable
"""
dimensions = var.dimensions
data = var.values
attributes = var.attrs.copy()
encoding = var.encoding.copy()
if (np.issubdtype(data.dtype, np.datetime64)
or (data.dty... | 5,286,678 |
def get_header(element, report_name, region, dates, styles):
"""Method to get header."""
try:
datenow = datetime.now()
tarehe = datenow.strftime("%d, %b %Y %I:%M %p")
url = 'https://childprotection.go.ke'
# Handle headers
address = '<b>MINISTRY OF LABOUR AND SOCIAL... | 5,286,679 |
def get_path_converter(request, task):
"""returns a partial function that converts the given path to another path
that is visible to other OSes.
"""
user_os = get_user_os(request)
repo = task.project.repository
if user_os == 'windows':
return repo.to_windows_path
elif user_os == 'l... | 5,286,680 |
def layout_split(layout, factor=0.0, align=False):
"""Intermediate method for pre and post blender 2.8 split UI function"""
if not hasattr(bpy.app, "version") or bpy.app.version < (2, 80):
return layout.split(percentage=factor, align=align)
return layout.split(factor=factor, align=align) | 5,286,681 |
def getSubmechanismRoots(selection_only=False):
"""
Args:
selection_only: (Default value = False)
Returns:
"""
if selection_only:
objs = bpy.context.selected_objects
else:
objs = bpy.context.scene.objects
return [obj for obj in objs if 'submechanism/name' in obj] | 5,286,682 |
def eda_column_subset(df, list_of_columns):
"""
Generates descriptive statistics, pair plot, and correlation matrix for a subset of columns.
Accepts: dataframe, list of columns
Returns: None, generates descriptive stats, pairplot, and correlation heat map
"""
plt.figure(figsize=(40, 40))
... | 5,286,683 |
def assert_array_equal(x: List[float], y: float):
"""
usage.geopandas: 3
"""
... | 5,286,684 |
def _build_time_predicates(
from_date=None,
to_date=None,
from_included=True,
to_included=False,
):
"""
Build time range predicates for 'where' clause
"""
must = []
if from_date:
must.append("time {} {}".format(
">=" if from_included else ">",
make_t... | 5,286,685 |
def init_bk(P,b,c):
"""
initializes the coefficient of Q(x) after the division of P
Needed in Newton-Raphson method
"""
n = len(P)
i = n-3
solution = np.zeros([1,n])
solution[0,n-1] = P[0]
solution[0,n-2] = P[1] + b * solution[0,n-1]
while i > -1:
solution[0,i] = P[n-i-1]... | 5,286,686 |
def spawn_command(*command):
"""
Run the given command, without waiting for completion. Return the Popen
object (which provides .send_signal, .kill(), .wait(), etc), or None
if the command couldn't be run at all.
The command is created with its own process group; this mean that
signals (eg. Ct... | 5,286,687 |
def app(environ, start_response):
"""Application object"""
if(environ.get("REQUEST_METHOD") == "GET"):
if(environ.get("PATH_INFO") == "/"):
status, data, headers = index()
elif(environ.get("PATH_INFO") == "/joke"):
status, data, headers = joke()
elif(environ.get("... | 5,286,688 |
def p_attritem_aliased(p):
"""attritem : string ASSIGN sname
| string ASSIGN binfunc"""
p[0] = p[3].set_alias(p[1]) | 5,286,689 |
def evaluation_diversity(df_source, df_target, baseline=False, max_k=30):
"""
Source: Mariani, G., Scheidegger, F., Istrate, R., Bekas, C., & Malossi, C. (2018).
BAGAN: Data Augmentation with Balancing GAN, 1–9. Retrieved from http://arxiv.org/abs/1803.09655
For df_source randomly sample one insta... | 5,286,690 |
def print_lustre_versions(log, lustre_versions, status=False,
print_table=True, field_string=None):
"""
Print table of BarreleAgent.
"""
# pylint: disable=too-many-branches,too-many-locals,too-many-statements
if not print_table and len(lustre_versions) > 1:
log.cl_e... | 5,286,691 |
def rename_motifs(motifs, stats=None):
"""Rename motifs to GimmeMotifs_1..GimmeMotifs_N.
If stats object is passed, stats will be copied."""
final_motifs = []
for i, motif in enumerate(motifs):
old = str(motif)
motif.id = "GimmeMotifs_{}".format(i + 1)
final_motifs.append(motif)... | 5,286,692 |
def _get_region(zone):
"""
Get region name from zone
:param zone: str, zone
:return:
"""
return zone if 'gov' in zone else zone[:-1] | 5,286,693 |
def conv_bright_ha_to_lib(brightness) -> int:
"""Convert HA brightness scale 0-255 to library scale 0-16."""
if brightness == 255: # this will end up as 16 which is max
brightness = 256
return int(brightness / 16) | 5,286,694 |
def findIntersection3(p1, p2, p3, p4):
"""
p1, p2 on the same line
p3, p4 on the another line
"""
px = ((p1[0]*p2[1] - p1[1]*p2[0]) * (p3[0]-p4[0]) - (p1[0]-p2[0]) * (p3[0]*p4[1] - p3[1]*p4[0])) / ((p1[0]-p2[0]) * (p3[1]-p4[1]) - (p1[1]-p2[1]) * (p3[0]-p4[0]))
py = ((p1[0]*p2[1] - p1[1]*p2[0]) *... | 5,286,695 |
def vit_relpos_small_patch16_rpn_224(pretrained=False, **kwargs):
""" ViT-Base (ViT-B/16) w/ relative log-coord position and residual post-norm, no class token
"""
model_kwargs = dict(
patch_size=16, embed_dim=384, depth=12, num_heads=6, qkv_bias=False, block_fn=ResPostRelPosBlock, **kwargs)
mod... | 5,286,696 |
def own_OneHotColumnCreator(df, columns):
"""OneHot Encodes categorical features. Adds a column for each unique value per column"""
for col in columns:
for value in df[col].unique():
df[value] = (df[col] == value).astype(int) | 5,286,697 |
def allow_header(cur):
""" allow portion of header """
block_data = [
[
"Total :",
get(cur, "total_allow_enabled") + "/" + get(cur, "total_allow"),
],
["Our Lists :", get(cur, "our_allow_enabled") + "/" + get(cur, "our_allow")],
[
"Others ... | 5,286,698 |
def func_call_runner_chain_simple_example():
"""
Console output:
========================
=== FUNC-CALL-RUNNER-SIMPLE-CHAIN: ===
RESULT FOR "Test Holder Number 1": 625.0
ERROR IN "Test Holder Number 2": Can't compute!
{{CONTEXT_HOLDER_ID(Test Holder Number 2): CONTEXT_HOLDER_INFO(Will fail)}:[
(index(0), dep... | 5,286,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.