content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def parse_date(s):
"""
Convert date string into datetime timestamp.
Parameters
----------
s : str
Date string.
Returns
-------
data : datetime
Timestamp.
"""
return datetime.datetime.strptime(s, '%Y%m%d') | 72,700 |
def create_app():
"""Create and configure an instance of the Flask application."""
app = Flask(__name__)
app.managers = {}
# https://stackoverflow.com/a/32965521/8903959
version = pkg_resources.get_distribution('lib_ddos_simulator').version
template = {
"swagger": "2.0",
"info": {
... | 72,701 |
def get_chromedriver(executable_path=None, cookies=None, proxy=None, user_agent=None,
headless=False, images=False, fast_load=False):
"""Returns a Chrome WebDriver using proxies and user-agent if specified.
"""
drive = None
chrome_options = webdriver.chrome.options.Options()
... | 72,702 |
def getRecommendArticle(request):
"""输入文章id,返回一个list,包括推荐的id
可以假设arxivID=“”时,利用用户浏览记录推荐,非空时按输入推荐。
用户浏览记录可以用session/cookie储存,建议session,读教程。
Args:
request (GET): arxivID:String,article的ID
Returns:
list,[(arxiv_id,title,author,category),...]
"""
try:
arxiv_id = req... | 72,703 |
def tz_path(name):
"""
Return the path to a timezone file.
:param name: The name of the timezone.
:type name: str
:rtype: str
"""
if not name:
raise ValueError('Invalid timezone')
name_parts = name.lstrip('/').split('/')
for part in name_parts:
if part == os.path.... | 72,704 |
def test_print_workout_days(selector: str, expected_output: str, capsys) -> None:
"""Unit-test print_workout_days."""
print_workout_days(selector)
captured = capsys.readouterr()
assert captured.out == expected_output | 72,705 |
def check_callback(callback):
"""
Check if callback is a callable or a list of callables.
"""
if callback is not None:
if isinstance(callback, Callable):
return [callback]
elif (isinstance(callback, list) and
all([isinstance(c, Callable) for c in callback])):
... | 72,706 |
def temp_dir():
"""
A context with a temporary directory that's finally wiped.
"""
dir = tempfile.mkdtemp()
try:
yield dir
finally:
shutil.rmtree(dir) | 72,707 |
def compress_json(json):
"""Compresses json output by removing quotes from keys. This makes the
return value invalid json (all json keys must be double-quoted), but
the result is still valid javascript."""
return re.sub(r'"(\w+)":', r'\1:', json) | 72,708 |
async def test_crawl_case_respect_cli_skip_nonblocking_grandchildren(child_blocking, grandchild_blocking,
crawls_expected, downstream_crawls_expected,
tree, provider_mock, protocol_m... | 72,709 |
def test_soap(water_atoms):
"""Test building SOAP descripters"""
initd = {
'rcut': 10,
'sigma': 0.1,
'lmax': 2,
'nmax': 2,
'species': ['H', 'O']
}
soap = Atoms2Soap(initd)
res = soap.get_desc(water_atoms, 1)
assert res.shape[0] == 3 | 72,710 |
def get_magmom_mae(poscar, mag_init):
"""
mae
"""
mae_magmom = []
sites_dict = poscar.as_dict()['structure']['sites']
# initialize a magnetic moment on the transition metal
# in vector form on the x-direction
for n, s in enumerate(sites_dict):
if Element(s['label']).is_transit... | 72,711 |
def is_bytes(value):
"""Indicate if object is bytes-like.
future.utils.isbytes is deprecated, so re-implementing, as per their
recommendation.
"""
return isinstance(value, builtins.bytes) | 72,712 |
def delete_session_follows(*_, instance: RawImageUploadSession, **__):
"""
Deletes the related follows.
We use a signal rather than overriding delete() to catch usages of
bulk_delete.
"""
ct = ContentType.objects.filter(
app_label=instance._meta.app_label, model=instance._meta.model_nam... | 72,713 |
def test_invalid_object():
"""Ensure there is an error if an object with an unknown state
type is given.
"""
with pytest.raises(KeyError):
state.deserialize_state({
state.LABEL_STATE_TYPE: 'unknown'
})
with pytest.raises(ValueError):
state.deserialize_state({
... | 72,714 |
def parse_ref_input(ref_input):
"""
The reference paths, it support multiple paths, use '|' as the separator between all paths, the format is
'tgt_input_1|tgt_input_2|tgt_input_3'. Each tgt_input is 'key1?=value1,key2?=value2,key3?=value3'.
1. 'path?=path1,name?=name1,audio?=audio_path... | 72,715 |
def find_languages(folders):
""" Find the languages in the translations folders.
Langauges are stored as subfolders with a two letter langauge code
Args:
folders: folders to loo through
Returns:
langauges
"""
languages = []
for folder in folders:
subfolder = os.lis... | 72,716 |
def myDocumentedFunction():
"""This is a comment describing the functionality of this function
Actually it does nothing, but we need to ilustrate how to comment
"""
pass | 72,717 |
def GlorotNormalInitializer(out_dim=0, in_dim=1, scale=onp.sqrt(2)):
"""An initializer function for random Glorot-scaled coefficients."""
def Init(shape, rng):
fan_in, fan_out = shape[in_dim], shape[out_dim]
size = onp.prod(onp.delete(shape, [in_dim, out_dim]))
std = scale / backend.numpy.sqrt((fan_in +... | 72,718 |
def accumulated_timewaste(num=1000):
"""Just waste a little bit of time"""
sum(n ** 2 for n in range(num)) | 72,719 |
def build(output_file):
"""
build to
"""
print "building to: [%s] ..." % output_file
output = open(output_file, 'w')
include(output, "nkuwlan/__init__.py", start_tag=None, end_tag="__name__")
output.write('# THIS FILE AUTO BUILD AT--- %s ---\n' % (time.ctime()))
include(output, "nkuwlan/... | 72,720 |
def dumps(obj: Any) -> str:
"""Generate JSON from a Python object."""
return json.dumps(obj, cls=CanonicalEncoder) | 72,721 |
def get_postal_code_by_coords(latitude, longitude):
"""
Finds the nearest postal code to the provided coordinates.
:param latitude:
:param longitude:
:return:
"""
retn = None
result_count = 0
radius = 1
while result_count == 0:
postal_codes = postal_codes_within_radius(l... | 72,722 |
def GetNumResColumnName(doc:NexDoc, col) -> str:
"""Returns the name of the specified column of the Numerical Results Window."""
return NexRun("GetNumResColumnName", locals()) | 72,723 |
def calc_error(center_value, mc_values, ci=0.683):
"""
Calculate the uncertainties/errors.
"""
data = np.concatenate([[center_value], mc_values])
median, q_lower, q_upper = np.percentile(data, q=(50, 50-50*ci, 50+50*ci))
mean = np.mean(data)
std = np.std(data)
return {
"mean": ... | 72,724 |
def test_domain_info_v3(vtotal_v3):
"""
Test for retrieving domain information from the VirusTotal v3 API.
"""
resp = vtotal_v3.request(f"domains/{URL_DOMAIN}")
assert resp.status_code == 200
assert resp.object_type == "domain"
data = resp.data
assert isinstance(data["links"], dict)
... | 72,725 |
def create_app():
"""
Factory to set up the application
# http://flask.pocoo.org/docs/0.10/patterns/appfactories/
:return:
"""
app = Flask(__name__)
# Load default config
app.config.update(
DEBUG=True,
SECRET_KEY='SECRET_KEY'
)
# Override config from an environmen... | 72,726 |
def get_prob_distribution (df_class, save_full_path=None, label_name=None, cols=None, plot=True):
"""
This function generates and plot the probability distributions for a given dataframe containing the probabilities
for each label in the classification problem.
:param df_class (pd.dataframe or string):... | 72,727 |
def plot_shape(shape, params, row=0, display_values=False):
"""
Plot shape features in a bidimensional plot.
Parameters
----------
shape: 1D array, pd.Series or pd.DataFrame
Shape features computed with shape_features function.
params: pd.DataFrame
Pan... | 72,728 |
def serial_for_url(url, *args, **kwargs):
"""\
Get an instance of the Serial class, depending on port/url. The port is not
opened when the keyword parameter 'do_not_open' is true, by default it
is. All other parameters are directly passed to the __init__ method when
the port is instantiated.
... | 72,729 |
def redirect_with_filter(category='', query=''):
"""Redirects to a multistre.am URL based on filter properties.
Arguments:
category: (str) category by which to filter, e.g. status, game, profile
query: (str) filter to use [OPTIONAL]
If no category argument is given the default behav... | 72,730 |
def csvOutput(csvFile, results):
"""
Output spectra to the given csv file.
Parameters
----------
csvFile: str
Output file name.
results: dict
Results from calWms or calDas.
specType: str
Choose between 'WMS' and 'DAS'.
Returns
-------
error: bool
... | 72,731 |
def create_icon(
app_name: str,
icon_filename=None,
conda_env_name=None,
package_name=None,
dry_run=False,
):
"""
:param app_name: Used for desktop icon name
:param icon_filename: absolute path to icon usually:
pathlib.Path(__file__).parent / pathlib.Path("app_icon512.ico")
... | 72,732 |
def getNamePip(lines):
"""
Used if inPypi == True.
Extracts the pacakgename from lines such as
"%setup -n Jinja2-%realversion", or "%define downloadn cx_Oracle".
Returns None if known patterns are not matched
"""
name = None
for line in lines:
if line.startswith("%setup"):
... | 72,733 |
def zoom_meeting(subject_id, password):
"""func which takes subject id and password as an argument and, basically zoom automation"""
time.sleep(3)
p.click(530, 281)
time.sleep(2)
p.click(651, 323)
time.sleep(1)
p.typewrite(subject_id)
p.press('enter')
time.sleep(5)
p.typewrite(pa... | 72,734 |
def dletseq(tree, *, args, syntax, expander, **kw):
"""[syntax, decorator] Decorator version of letseq, for 'letseq over def'.
Expands to nested function definitions, each with one ``dlet`` decorator.
Example::
@dletseq[x << 1,
x << x + 1,
x << x + 2]
def... | 72,735 |
def run(app=None,
interface='127.0.0.1',
port=8080,
dev=True,
config=None): # pragma: no cover
""" Run a lightweight development server via the
currently-active runtime. Suitable for use
locally, with no required parameters at all.
:param app: Canteen application t... | 72,736 |
def read_phases(paths, index, fractions=None, beta=None):
"""Read the relevant data from a list of exapnded ensemble
simulations with the same reference point.
Args:
paths: A list of directories containing the data to read.
index: The reference subensemble index.
fractions: The refe... | 72,737 |
def fasta_name_seq(s):
"""
Interprets a string as a FASTA record. Does not make any
assumptions about wrapping of the sequence string.
"""
DELIMITER = ">"
try:
lines = s.splitlines()
assert len(lines) > 1
assert lines[0][0] == DELIMITE... | 72,738 |
def show_host(ctx, data, sort, sort_dir, cluster):
"""Show node."""
if ctx.invoked_subcommand is not None:
return
if cluster is None:
hosts = data.client.list("host", "host", sort=sort, sort_dir=sort_dir)
else:
hosts = data.client.list("experimental/cluster/%s/v1/host" % cluster... | 72,739 |
def convert_pem_to_openssh(pem_key):
"""
Converts a given public key from PEM to OpenSSH format.
:param pem_key: PEM-encoded key bytes
:type pem_key: bytearray
:return: OpenSSH-encoded key bytes
:rtype: bytearray
"""
loaded_key = crypto_serialization.load_pem_public_key(pem_key, backend... | 72,740 |
def copy(source, dest, autoflush=True, print_status=None):
"""
Read from the source file handle and write the data to the dest file handle.
"""
n = 0
while True:
buf = source.read(BUFFER_SIZE)
if not buf:
break
dest.write(buf)
n += len(buf)
if auto... | 72,741 |
def diff_kerning(font_before, font_after, thresh=2, scale_upms=True):
"""Find kerning differences between two fonts.
Class kerns are flattened and then tested for differences.
Rows are matched by the left and right glyph keys.
Some fonts use a kern table instead of gpos kerns, test these
if no gp... | 72,742 |
def test_compare_6(BTO):
"""
Test --store_mismatch_locations
"""
# Run program
base = BTO.test_dir + 'testR'
cmd = "inStrain compare -i {1} {2} -o {3} -sc {4} --store_mismatch_locations".format(True, BTO.IS1,
... | 72,743 |
def str_tspec(tspec, arg_names):
""" Turn a single tspec into human readable form"""
# an all "False" will convert to an empty string unless we do the following
# where we create an all False tuple of the appropriate length
if tspec==tuple([False]*len(arg_names)):
return "(nothing)"
return "... | 72,744 |
def get_option(prompt: str, options: list[str] = MENU_OPTIONS) -> int:
"""Gets an option from the user and ensures it's valid."""
while True:
option: int = int(input(prompt))
if option > 0 and option <= len(options):
return option
else:
raise ValueError('No... | 72,745 |
def _validate_dataset(data_path, url=None, file_hash=None, download_if_missing=True):
"""
Checks to see if a dataset is on the local machine,
if not tries to download if download_if_missing is set to true,
also checks that the hash of the file data matches that included in the
metadata
Args:
... | 72,746 |
def form_DateDifferentEmpty(request):
"""
A simple date field but with the ``empty`` attribute value set to todays date
"""
schema = schemaish.Structure()
schema.add('myDateField', schemaish.Date())
form = formish.Form(schema, 'form')
form['myDateField'].widget = formish.Input(empty=datetime... | 72,747 |
def id_split(annotated_path, low_path, high_path):
""" Splits the annotated corpus into low-ID and a high-ID sub-corpora, each containing an identical
number of samples; the so obtained corpora are used in both stages of IDGAN training. """
# Read in the source corpus
df_annotated = pd.read_table(annota... | 72,748 |
def example3():
"""what kind of data is JSON serializable
combination of: string, int, float, list, tuple, dictionary
True, False and None
JSON doesn"t support set
JSON Encoder will do:
change all the string notation to ",
change all the tuple to list
"""
d... | 72,749 |
def render_toolbar(context, config):
"""Render the toolbar for the given config."""
quill_config = getattr(quill_app, config)
t = template.loader.get_template(quill_config['toolbar_template'])
return t.render(context) | 72,750 |
def get_commit_timestamps(commits):
"""Get all commit timestamps for the given ebuild.
Args:
commits (list[Commit]): The commits in question.
Returns:
list[int]: The uprev commit unix timestamps, in order.
"""
return [int(commit.timestamp) for commit in commits] | 72,751 |
def mask_tokens_after_eos(input_ids, input_masks,
eos_token_id=VatexDataset.EOS, pad_token_id=VatexDataset.PAD):
"""replace values after `[EOS]` with `[PAD]`,
used to compute memory for next sentence generation"""
for row_idx in range(len(input_ids)):
# possibly more than o... | 72,752 |
def xywh_to_xyxy(xywh):
"""Convert [x1 y1 w h] box format to [x1 y1 x2 y2] format."""
if isinstance(xywh, (list, tuple)):
# Single box given as a list of coordinates
assert len(xywh) == 4
x1, y1 = xywh[0], xywh[1]
x2 = x1 + np.maximum(0.0, xywh[2] - 1.0)
y2 = y1 + np.maxi... | 72,753 |
def setObjectProperties(agent, object, nameValuePairs, kbResume=False):
"""Sets the value of the properties of object (or unsets the value if None).
Calls associated property change listener functions as a side effect and posts events unless kbResume."""
def callListeners(prop, val):
listenerfac... | 72,754 |
def flush(name):
"""
Flush an ipset.
"""
futils.check_call(["ipset", "flush", name]) | 72,755 |
def get_entry_point(filename: Path, prefix: str, import_path: str) -> List[str]:
"""Returns the entry point string for a given path.
This looks for LIBTBX_SET_DISPATCHER_NAME, and a root function
named 'run'. It can return multiple results for each file, if more
than one dispatcher name is bound.
... | 72,756 |
def DataUsed_TypeInfo():
"""DataUsed_TypeInfo() -> RTTI"""
return _DataModel.DataUsed_TypeInfo() | 72,757 |
def get_min(filename):
"""
Isolate the minimum search size from a file name.
Example
input: github_notebooks_200..203_p3.json
output: 200
"""
return int(filename.split("_")[2].split("..")[0]) | 72,758 |
def scatter_complex(series: pd.Series) -> str:
"""Scatter plot (or hexbin plot) from a series of complex values
Examples:
>>> complex_series = pd.Series([complex(1, 3), complex(3, 1)])
>>> scatter_complex(complex_series)
Args:
series: the Series
Returns:
A string conta... | 72,759 |
def get_operations(managed_portfolio: portfolio.Portfolio
) -> Mapping[Text, operation.Operation]:
"""Gets all the position of all assets in the portfolio.
Args:
managed_portfolio: Portfolio from which to obtain operations.
Returns:
Map of portfolio operations to its ids.
"""
mana... | 72,760 |
def commonprefix(m):
"""Given a list of pathnames, returns the longest common leading component without trailing /"""
if not m:
return ""
m = [p.rstrip("/").split("/") for p in m]
s1 = min(m)
s2 = max(m)
s = s1
for i, (c1, c2) in enumerate(zip(s1, s2)):
if c1 != c2:
... | 72,761 |
def run(resource_name, json_path, mmcif_mode=False, cif_file =None):
"""
Basic example of running the PDBe-KB/FunPDBe validator
:return: None
"""
validator = Validator(resource_name) # Same as in the JSON
validator.load_schema()
for json_file_path in glob.glob('%s*.json' % json_path):
... | 72,762 |
def edgecolor_by_source(G, node_colors):
""" Returns a list of colors to set as edge colors based on the source node for each edge.
Parameters
----------
G : graph.
A networkx graph.
node_colors : list
List of node colors.
Example
--------
>>> colormap = {'male':... | 72,763 |
def on_wheel_event(client: Halo, event: WheelEvent):
"""
:param client: Client handle to communicate with Beoremote Halo
:param event: Wheel Event from Beoremote Halo
"""
button = config[event.id]
if button and button.value is not None:
button.value = clamp(button.value + event.counts *... | 72,764 |
def get_random_colors(n, name="hsv", hex_format=True):
"""Returns a function that maps each index in 0, 1, ..., n-1 to a distinct
RGB color; the keyword argument name must be a standard mpl colormap name."""
cmap = plt.cm.get_cmap(name, n)
result = []
for i in range(n):
color = cmap(i)
... | 72,765 |
def fdwDdz(k,t,a):
"""Function for calculating :math:`\\frac{dt}{dz}` in order to calculate the electric field in x and y direction.
"""
return fdwDdt(k,t)*fdtDdz(a) | 72,766 |
def condition_control_example(score=92):
""" for elif else; while; break continue; pass; else分支
条件分支: if <>: else: if <>: elif <>: else:
条件控制 break 结束当前循环,终止循环, continue 结束当前这一次循环,继续执行循环条件
Python中的pass是空语句,为保证程序结构的完整性。pass不做任何事情,一般用作占位语句。
Python中为循环结构引入了 else 子句,在循环结束时做特定处理。如果whil... | 72,767 |
def _load_credentials_file(credentials_file):
"""Load credentials from the given file handle.
The file is expected to be in this format:
{
"file_version": 2,
"credentials": {
"key": "base64 encoded json representation of credentials."
}
... | 72,768 |
def __CallStoredProcedure(self, sProcedureName, pArguments):
"""Calls the given SQL stored procedure"""
pRows = None
error_string = ""
locked_state = False
try:
# Acquire the database lock
self.database_lock.Acquire(10)
locked_state = True
# Acquire the cursor and in... | 72,769 |
def effective_message_type(entity):
"""
Extracts the type of message as a string identifier from a :class:`telegram.Message` or a
:class:`telegram.Update`.
Args:
entity (:obj:`Update` | :obj:`Message`) The ``update`` or ``message`` to extract from
Returns:
str: One of ``Message.MES... | 72,770 |
def create_post(i):
"""
Helper to create one remote post.
:param i:
:return:
"""
i = i.get('posts')[0]
post = Post()
post.id = i.get('id')
post.author = create_author(i.get('author'))
post.contentType = i.get('contentType')
post.description = i.get('description')
post.pu... | 72,771 |
def parse_internal_field(fn):
"""
parse internal field, extract data to numpy.array
:param fn: file name
:return: numpy array of internal field
"""
if not os.path.exists(fn):
print("Can not open file " + fn)
return None
with open(fn, "rb") as f:
content = f.... | 72,772 |
def get_valid_executable_path_or_empty_path(arg_string: str) -> pathlib.Path:
"""
>>> if lib_detect_testenv.is_doctest_active(): assert get_valid_executable_path_or_empty_path(__main__.__file__) == empty_path
>>> assert get_valid_executable_path_or_empty_path(__file__) == pathlib.Path(__file__).resolve()
... | 72,773 |
def _ignore_filter(referrers, ignore, extraids, getid=id):
""" Ignore objects on the referrers list if ignore(x) is true or if x is in extra """
r = []
for ref in referrers:
if ignore is not None:
extraids.update(set([getid(o) for o in ignore(ref)]))
if getid(ref) in extraids: c... | 72,774 |
def request_fake():
"""Create request with fake i18n subscribers on."""
config = testing.setUp()
config.scan("pyramid_localize.subscribers.fake")
request = Request({})
request.registry = config.registry
return request | 72,775 |
def print_usage():
"""
打印使用信息
"""
print('Usage: python main.py [path to your java source folder]')
print('\nExamples:')
print('\tpython main.py C:\\path\\to\\your\\java\\source\\folder')
print('\tpython main.py /home/user/path/to/your/java/source/folder') | 72,776 |
def test_dtknz(tknzr: CharTknzr) -> None:
"""Detokenize characters back to text."""
# Return empty string when input empty list.
assert tknzr.dtknz([]) == ''
# Normalize with NFKC.
assert tknzr.dtknz(['0', 'é']) == unicodedata.normalize('NFKC', '0é')
# Case-sensitive and case-insensitive.
assert (tknzr.... | 72,777 |
def main():
"""Infinite loop of screenshots."""
args = parse_args()
if not os.path.exists(args.dirname):
print("Created target directory: {0}".format(args.dirname))
os.makedirs(args.dirname)
counter = itertools.count()
print("Waiting {0} seconds to start.".format(args.sleep))
f... | 72,778 |
def run_command(cmd):
"""
Run command as /bin/bash script.
"""
subprocess.Popen(["/bin/bash", "-c", cmd]) | 72,779 |
def test_to_full_model_name():
"""Test to_full_model_name."""
tests = [
{
'root_key': 'catalog',
'name': None,
'expected': f'{const.PACKAGE_OSCAL}.catalog.Catalog',
}, {
'root_key': 'catalog',
'name': 'group',
'expected': f'... | 72,780 |
def concatenate_predictions_dicts(squadjsons_files_dir, output_file=None):
"""
:param squadjsons_files_dir: should be one of "wikipedia-train" "wikipedia-dev" "web-train" "web-dev" "verified-web-dev" "verified-wikipedia-dev"
it is actually a directory with format:
squadjsons_files_dir
├── squadjson... | 72,781 |
def read_settings(key=None):
"""
Read application settings.
Parameters
----------
key : str, optional
Setting key to read, by default `None`.
Returns
-------
str | dict
If `key` is given, the corresponding value. If key is `None`, return all settings in
a dictio... | 72,782 |
def navigable_thresh(img, rgb_thresh=(160, 160, 160)):
"""Identify the image pixels that are above the provided threshold. Each
threshold value can range between 0 and 255, with 160 doing a nice job
of identifying ground pixels only.
:param img: Numpy 3d array (x, y, RGB layers)
:param rgb_threh: 3 ... | 72,783 |
def data():
"""Data processing"""
pass | 72,784 |
def Hbeta(D=np.array([]), sigma=1.0):
"""
Compute the P_ji matrix and the entropy for some data given a sigma value.
Params:
D - Squared difference of two vectors. Must be a numpy array.
sigma - a float
Output:
H, P - Entropy and P_ji matrix
"""
# Compute P-row and corresponding pe... | 72,785 |
def gaia_morph(gaia):
"""Retrieve morphological type for Gaia sources.
Parameters
----------
gaia: :class:`~numpy.ndarray`
Numpy structured array containing at least the columns,
`GAIA_PHOT_G_MEAN_MAG` and `GAIA_ASTROMETRIC_EXCESS_NOISE`.
Returns
-------
:class:`~numpy.arra... | 72,786 |
def motherfucking_rainbows(string, inputmode=False, end="\n"):
"""
I cANtT FeELLE MyYE FACECsEE ANYrrMOROeeee
"""
for character in string:
print(choice(colors) + character, end="")
print('\033[0m', end="")
if inputmode:
return input("")
return print(end, end="") | 72,787 |
def comp_joule_losses(self, out_dict, machine):
"""Compute the electrical Joule losses
Parameters
----------
self : Electrical
an Electrical object
out_dict : dict
Dict containing all magnetic quantities that have been calculated in comp_parameters of EEC
machine : Machine
... | 72,788 |
def negative_distances(
negative_mining_strategy: str,
distances: FloatTensor,
negative_mask: BoolTensor,
positive_mask: BoolTensor,
) -> Tuple[FloatTensor, FloatTensor]:
"""Negative distance computation.
Args:
negative_mining_strategy: What mining strategy to use for select the
... | 72,789 |
def get_courses(input_urls: list[str]):
"""
Return course_dict of list of courses
"""
courses = []
for input_url in input_urls:
course_data = get_course_data(input_url)
course_dict = {}
if course_data:
course_dict = get_course_dict(course_data)
courses.app... | 72,790 |
def get_course_info(orgUnitId):
"""Returns basic info for a course offering"""
url = DOMAIN + "/lp/{}/courses/{}".format(LP_VERSION, orgUnitId)
response = requests.get(url, headers=HEADERS)
code_log(response, "GET course offering info org unit".format(orgUnitId))
return json.loads(response.text) | 72,791 |
def process_remove_outliers_ph(df: pd.DataFrame) -> pd.DataFrame:
"""Remove waters with ph <= 1 or ph>13 and potability=1."""
df = df[
~((df["Potability"] == 1) & (df["ph"].apply(lambda x: x <= 1 or x >= 13)))
].copy()
return df | 72,792 |
def deserialize_numpy(serialized_np, shape):
"""
Deserializes a numpy array from a JSON-compatible string.
from https://stackoverflow.com/questions/30698004/how-can-i-serialize-a-numpy-array-while-preserving-matrix-dimensions#30699208
Parameters
----------
serialized_np : str
A seriali... | 72,793 |
def experiment():
"""
see section 6
"""
pass | 72,794 |
def p_createPrimary(t):
"""createPrimary : R_PRIMARY R_KEY S_PARIZQ idList S_PARDER"""
t[0] = [t[1], t[4]]
repGrammar.append(t.slice) | 72,795 |
def test_pipeline_runner_main_with_context_with_failure():
"""Run main with context with failure argument as expected."""
expected_notify_output = ['sg3', 'fh']
with patch_logger('pypyr.steps.echo', logging.NOTIFY) as mock_log:
with pytest.raises(ValueError) as err:
pipelinerunner.run(
... | 72,796 |
def get_field_data_from_room():
"""
1. Get required arguments
2. Call the worker method
3. Render the response
"""
# 1. Get required arguments
args = Eg003Controller.get_args()
try:
# 2. Call the worker method
results = Eg003Controller.worker(args)
except ApiExceptio... | 72,797 |
def build_tuple_for_feet_structure(quantity):
"""
Builds the tuple required to create a FeetAndInches object
:param quantity: string containing the feet, inches, and fractional inches
:return: tuple containing feet, inches, and calculated fractional inches
"""
feet = float(quantity[0])
inche... | 72,798 |
def _all(itr):
"""Similar to Python's all, but returns the first value that doesn't match."""
any_iterations = False
val = None
for val in itr:
any_iterations = True
if not val:
return val
return val if any_iterations else True | 72,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.