content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def edge_validator_debug(input: 'Socket', output: 'Socket') -> bool:
"""This will consider edge always valid, however writes bunch of debug stuff into console"""
print("VALIDATING:")
print(input, "input" if input.is_input else "output", "of node", input.node)
for s in input.node.inputs+input.node.outpu... | 5,297,300 |
def missing_impact_1v1( # pylint: disable=too-many-locals
df: dd.DataFrame, x: str, y: str, bins: int, ndist_sample: int
) -> Intermediate:
"""
Calculate the distribution change on another column y when
the missing values in x is dropped.
"""
df0 = df[[x, y]]
df1 = df.dropna(subset=[x])
... | 5,297,301 |
def db_connection(f):
"""
Supply the decorated function with a database connection.
Commit/rollback and close the connection after the function call.
"""
def with_connection_(*args, **kwargs):
con = pymysql.connect(
host="localhost",
user=os.environ["DB_USER"],
... | 5,297,302 |
def rle_kyc(seq: str) -> str:
""" Run-length encoding """
counts = []
count = 0
prev = ''
for char in seq:
# We are at the start
if prev == '':
prev = char
count = 1
# This letter is the same as before
elif char == prev:
count += 1... | 5,297,303 |
def test_sprite_box_native_size(run_gui, cat_image):
"""Test SpriteBox without scaling the image."""
layer = SpriteBox(SpriteBoxDefinition(image=cat_image))
assert run_gui(test_sprite_box_native_size, layer) | 5,297,304 |
def is_legal_parameter(name):
"""
Function that returns true if the given name can be used as a
parameter in the c programming language.
"""
if name == "":
return False
if " " in name:
return False
if "." in name:
return False
if not name[0].isalpha():
... | 5,297,305 |
def getDefaultGateway(host, args, session):
"""
Called by the network function. Prints out the DefaultGateway.
@param host: string, the hostname or IP address of the bmc
@param args: contains additional arguments used by the ldap subcommand
args.json: boolean, if this flag ... | 5,297,306 |
async def dev_cmd_reset_transfer_cool(message : discord.Message, args : str, isDM : bool):
"""developer command resetting a user's home guild transfer cooldown.
:param discord.Message message: the discord message calling the command
:param str args: either empty string or string containing a user mention o... | 5,297,307 |
def unity():
"""Return a unity function"""
return lambda x:x | 5,297,308 |
def stash(copy, keep, target, keys):
"""Rename target, writing dropped key-value pairs to a metadata file."""
dest = subprocess.run(
" ".join([
"echo", target,
"|",
"keyname", "keep" if keep else "drop",
] + list(keys)),
shell=True,
stdout=subp... | 5,297,309 |
def tf_idf(search_keys:str, data:List) -> Tuple:
"""calculate the tf-idf matrices for the vocabulary
and keyword matrix"""
tfidf_vectorizer = TfidfVectorizer()
tfidf_weights_matrix = tfidf_vectorizer.fit_transform(data)
search_query_weights = tfidf_vectorizer.transform([search_keys])
return sea... | 5,297,310 |
def scale(prob):
"""Scales a problem to lie in :math:`[-1, +1]^D`.
:param prob: a :ref:`problem <problem>`.
:return: a scaled :ref:`problem <problem>` with the ``limits`` and ``scale`` as additional keys.
"""
lims = limits(prob)
mid = (lims[0] + lims[1])/2
scale = (lims[1] - lims[0])/2
... | 5,297,311 |
def run_opt(mol, prog, meth, bas, mol_is_smiles=True):
"""
Runs a g09 or molpro job for
INPUT:
stoich - stoichiometry of molecule
theory - theory energy should be listed or computed with
basisset - basis set energy should be listed or computed with
prog - program an energy should be ... | 5,297,312 |
def locate_package_directory():
"""Identify directory of the package and its associated files."""
try:
return path.abspath(path.dirname(__file__))
except Exception:
message = ('The directory in which the package and its '
'associated files are stored could not be located.'... | 5,297,313 |
def rf_make_zeros_tile(num_cols: int, num_rows: int, cell_type: Union[str, CellType] = CellType.float64()) -> Column:
"""Create column of constant tiles of zero"""
jfcn = RFContext.active().lookup('rf_make_zeros_tile')
return Column(jfcn(num_cols, num_rows, _parse_cell_type(cell_type))) | 5,297,314 |
def generateAndTrain(generationParameters, trainingParameters,
resultsDir):
"""
Creates a random tree, creates its tuples
and trains a tree from these tuples
Return
generatedTree, trainedTree, purity
"""
generatedObjectTree = simpleRandomBifurcatio... | 5,297,315 |
def amac_person_bond_org_list() -> pd.DataFrame:
"""
中国证券投资基金业协会-信息公示-从业人员信息-债券投资交易相关人员公示
https://human.amac.org.cn/web/org/personPublicity.html
:return: 债券投资交易相关人员公示
:rtype: pandas.DataFrame
"""
url = "https://human.amac.org.cn/web/api/publicityAddress"
params = {"rand": "0.196538382310... | 5,297,316 |
def check_line_comp_options(lam_gal,line_list,comp_options,edge_pad=10,verbose=True):
"""
Checks each entry in the complete (narrow, broad, outflow, absorption, and user) line list
and ensures all necessary keywords are input. It also checks every line entry against the
front-end component options (co... | 5,297,317 |
def parse(address):
"""Parses an address into its components"""
for _, addresser in ADDRESSERS.items():
result = addresser.parse(address=address)
if result:
return result
raise ValueError("parse error, no addresser found for address {}".format(address)) | 5,297,318 |
def notify(message, severity):
"""Creates and displays a notification using a Toast
Args:
message (str): what is displayed inside the notification.
Can be composed of multiple lines
severity (str): type of notification. Can be "INFO", "ERROR"
"WARNING", "DEBUG" or "NONE"... | 5,297,319 |
def inable_all():
"""
Inable all Strike price widgets in PlaceOrder Screen.
"""
strike = [s1,s2,s3,s4]
for i in strike:
i['state'] = 'normal' | 5,297,320 |
def create_app(object_name):
"""
An flask application factory, as explained here:
http://flask.pocoo.org/docs/patterns/appfactories/
Arguments:
object_name: the python path of the config object,
e.g. gordon_cole_gen.settings.ProdConfig
"""
app = Flask(__name__)
... | 5,297,321 |
def insert_db_price_data():
"""
Collect and import instruments price data from Oanda into the database
Args:
None
Returns:
None
"""
log_this('1. oanda_insert_db_price_data', 0)
csvdir = SETT.get_path_r_oanda_src()
connection = pymysql.connect(host=DB_SRV,
... | 5,297,322 |
def calculate_add(values: dict, data: StepData):
"""Die jeweiligen Werte, die in add stehen, werden zu den Werten, die in key stehen, hinzuaddiert.
:param values: Werte aus der JSON-Datei
:param data: Daten aus der API
"""
_bi_calculate(values, data, operator.add) | 5,297,323 |
def num_added_features(include_am, include_lm):
""" Determine the number of added word-level features (specifically AM and LM) """
added_feature_count = 0
if include_am:
added_feature_count += 1
if include_lm:
added_feature_count += 1
return added_feature_count | 5,297,324 |
def introduction(): # noqa: D205, D400
"""Interactively explain the game's input mechanism.
Tell the user to input a number between 1 and 4 corresponding to the
action on screen that they want to take. Give an interactive example of
this by using an example navigation system where the user has to navi... | 5,297,325 |
def split_const_subgraphs(
module: Union[torch.nn.Module, torch.fx.GraphModule]
) -> FoldedGraphModule:
"""
Looks through `module` for any nodes that have all constant attribute inputs
and separates them out into their own constant subgraph, and returns a
FoldedGraphModule which runs that constant s... | 5,297,326 |
def validate_CNPJ(value):
"""
Value can be either a string in the format XX.XXX.XXX/XXXX-XX or a
group of 14 characters.
:type value: object
"""
value = str(value)
if value in EMPTY_VALUES:
return u''
if not value.isdigit():
value = re.sub("[-/\.]", "", value)
orig_va... | 5,297,327 |
def _get_mudata_autodetect_options_and_encoding_modes(
identifier: str, autodetect: dict, encodings: dict[str, dict[str, list[str]]]
) -> tuple[bool, dict | None]:
"""
Extract the index column (if any) and the columns, for obs only (if any) from the given user input.
This function is only called when d... | 5,297,328 |
def load_model(path, run_id=None):
"""
Load an H2O model from a local file (if ``run_id`` is ``None``) or a run.
This function expects there is an H2O instance initialised with ``h2o.init``.
:param path: Local filesystem path or run-relative artifact path to the model saved
by :py:func... | 5,297,329 |
def gzfile_exists():
"""
判断解压.tar.gz文件的目录是否存在
"""
gc = GetConf()
Targzpath = gc.targzpath()["readdict"]["zippath"]
# print(Targzpath) | 5,297,330 |
def multishells():
"""Resolve the path of the "rst_operators/multishells.rst" result file."""
return resolve_test_file("model_with_ns.rst", "", "multishells_rst") | 5,297,331 |
def _get_validator(
cls: Type,
attr_name: str,
type_validators: Dict[Type, AutoHandler],
type_use_values: Dict[Type, T],
) -> PromptFunction:
"""
Gets one of the built-in validators or a type_validator from the user.
This returns a validator for a particular type, it doesn't handle collectio... | 5,297,332 |
def _get_posterior_merge_prob(clusti: Cluster, clustj: Cluster, params: dict):
"""
calculate posterior merge probability for clusters i and j given prior params `params`
:param clusti: cluster i
:param clustj: cluster j
:param params: dictionary of prior parameters
:return: posterior probabilit... | 5,297,333 |
def multiplyMyNumbers(a, b):
""" multiply_my_numbers == PEP8 (forced mixedCase by CodeWars) """
return str(convert_num(a) * convert_num(b)) | 5,297,334 |
def try_to_create_directory(directory_path):
"""Attempt to create a directory that is globally readable/writable.
Args:
directory_path: The path of the directory to create.
"""
logger = logging.getLogger("ray")
directory_path = os.path.expanduser(directory_path)
if not os.path.exists(di... | 5,297,335 |
def _UpdateGeneratedIndexes(spec, count, indexes):
"""Updates the set of generated indexes to cover given query requirements.
It may add "spec" to the "indexes" dict if the latter does not
already have an index suitable for serving the query represented by
"spec". (It may even replace an entry already in the ... | 5,297,336 |
def retrieve_cnv_data(store, solution, chromosome=''):
""" Retrieve copy number data for a specific solution
"""
cnv = store['solutions/solution_{0}/cn'.format(solution)]
if chromosome != '':
cnv = cnv[cnv['chromosome'] == chromosome].copy()
cnv['segment_idx'] = cnv.index
return cnv | 5,297,337 |
def draw_the_baby_line(canvas, first, second, name_color_num):
"""
The function will draw a short line of the data on the canvas
:param canvas: (Tkinter Canvas)The canvas on which we are drawing.
:param first: list, the first point of the line
:param second: list, the second point of the line
:p... | 5,297,338 |
def filter_images_by_size(images, min_size, max_size = None):
"""
usefull to find only high-resolution photos and kicking out
thumbnails and junk on the fly
"""
pass | 5,297,339 |
def max_drawdown(returns):
"""
Determines the maximum drawdown of a strategy.
Parameters
----------
returns : pd.Series
Daily returns of the strategy, noncumulative.
- See full explanation in tears.create_full_tear_sheet.
Returns
-------
float
Maximum drawdown.... | 5,297,340 |
def macys(macys_url : str) -> dict:
"""Scrape product information from macys.com
Keyword arguments:
macys_url -- a product url from macys.com
"""
macys_product = _macys._macys(macys_url)
return macys_product | 5,297,341 |
def square_root_mod_prime(a, p):
"""Modular square root of a, mod p, p prime."""
# Based on the Handbook of Applied Cryptography, algorithms 3.34 to 3.39.
# This module has been tested for all values in [0,p-1] for
# every prime p from 3 to 1229.
assert 0 <= a < p
assert 1 < p
if a == 0:... | 5,297,342 |
def go_term_dict():
"""Parses the Gene Ontology file and returns GO lookup dictionary, version, and date.
The go.obo.gz file is included in the GFFtk package, it can be updated in site-packages/gfftk/data/go.obo.gz
Returns
-------
go : dict of dict
dictionary of go_term: { "name": str, "na... | 5,297,343 |
def parse_export_request():
""" Check if request contains all required fields """
required_headers = {
"X-Requested-By": ["GGRC"],
"Content-Type": ["application/json"],
"X-export-view": ["blocks", "grid"],
}
check_required_headers(required_headers)
return request.json | 5,297,344 |
def parse_cmdline(args):
"""
Parses command line arguments and returns
query and request_options
"""
if not args:
show_usage()
sys.exit(0)
query_string = " ".join(args)
parsed = urlparse.urlparse("https://srv:0/%s" % query_string)
request_options = options.parse_args(
... | 5,297,345 |
def row_count(data):
"""
Return the # of rows/features in the provided data (feature class,
table, feature layer or table view)
"""
return int(arcpy.GetCount_management(data).getOutput(0)) | 5,297,346 |
def p_multipkopt_listopt(p):
"""multikvopt : MULTIKV_LIST_OPT fieldlist"""
p[0] = ParseTreeNode(p[1].upper())
p[0].add_children(p[2].children) | 5,297,347 |
def update_user_profile(sender, instance, created, **kwargs):
"""
Creates a Profile object for the user if it doesn't exist, or updates
it with new information from the User (e.g. the gravatar).
"""
## Compute the email hash
digest = hashlib.md5(instance.email.lower().encode('utf-8')).hexdigest(... | 5,297,348 |
def recipe_image_file_path(instance, file_name):
"""
generate file path for new recipe image
"""
extension = file_name.split('.')[-1] # return tthe last item after spliting
file_name = f'{uuid.uuid4()}.{extension}'
return os.path.join('uploads/recipe/',file_name) | 5,297,349 |
def prepare(core: PatchworkDocker, configuration: PrepareCliConfiguration):
"""
Prepares for patchwork Docker build.
:param core: patchwork Docker core
:param configuration: build configuration
:return:
"""
output = core.prepare(configuration.build_location)
print(output) | 5,297,350 |
def test_enqueue_missing1(worker):
"""Test self-healing enqueueing missing monitor jobs"""
with worker.app.app.app_context():
app = worker.app.app
app.redis.flushall()
for status in [
JobExecution.Status.enqueued,
JobExecution.Status.pulling,
JobExecu... | 5,297,351 |
def harvest_metadata(identifiers: Optional[List[dict]] = None,
eager: bool = False):
"""."""
if identifiers:
identifiers_to_harvest = (dict(identifier=i, scheme=v, providers=None)
for i, v in identifiers)
else: # use queue
identifiers_t... | 5,297,352 |
def colorbar(zlim, ticks=None, lines=None, line_color='k', linewidth=1,
colormap='jet', extend='neither', ticklocation='right',
fontsize_other=18, label=None, fontsize_label=21, figsize=6,
dpi=100, showfig=True, filename=None):
"""
Create colorbar
Parameters
----... | 5,297,353 |
def banner(text: str, *, borderChar: str = '='):
"""Print 'text' as banner, optionally customise 'borderChar'."""
border = borderChar * len(text)
return '\n'.join([border, text, border]) | 5,297,354 |
def add_new_obj_btn(form_obj ,field):
"""put a add btn for foreignkey and m2m field"""
#print("add_new_obj_btn site enabled ",site.enabled_admins)
field_obj = form_obj.instance._meta.get_field(field.name)
field_type = field_obj.get_internal_type()
if field_type in ("ForeignKey", "ManyToManyField"):... | 5,297,355 |
def commit_candidate(self, config):
"""
Commit the candidate configuration.
:param self: object from class
:param config:
:return:
"""
url = self.connection.config["api_url"] + "system/config/cfg_restore"
data = {"server_type": "ST_FLASH", "file_name": config, "is_oobm": False}
cmd_... | 5,297,356 |
def parse_turn(turn):
"""Parse the input from the user for valid player strings and play positions
Args:
turn (string): Input string from the user that contains the played
position (0-8)
Returns:
(int/None): Returns interger on success or None on failure
"""
t... | 5,297,357 |
def main():
"""Main function of the script"""
args=get_args()
# Parameters to control the workflow
with open(args.config) as yamlfile:
config = yaml.load(yamlfile, Loader=yaml.FullLoader)
# Project
if args.project:
project = args.project
else:
project = config["PROJEC... | 5,297,358 |
def execute_export_train(args):
"""Exports parts of the pysarts project needed for TRAIN.
Parts exported are: IFG grid, ifg dates, UTC time of satellite pass.
"""
lons, lats = read_grid_from_file(os.path.join(config.SCRATCH_DIR,
'grid.txt'))
region... | 5,297,359 |
def phonenumber(anon, obj, field, val):
"""
Generates a random US-style phone number
"""
return anon.faker.phone_number(field=field) | 5,297,360 |
def noop(obs):
"""
Transform that does absolutely nothing!
"""
return obs | 5,297,361 |
def RectangularGrid(dX, iMax, dY=None, jMax=None):
"""Return a rectangular uniform rectangular mesh.
X and/or Y grid point locations are computed in a cartesian coordinate
system using the grid step size and grid points.
Call Signature:
RectangularGrid(dX, iMax, dY=None, jMax=None... | 5,297,362 |
def test_sync_hubspot_application(settings, mock_hubspot, hubspot_key):
""" sync_hubspot_application task helper should call tasks if an API key is present """
settings.HUBSPOT_API_KEY = hubspot_key
application = BootcampApplication()
sync_hubspot_application(application)
if hubspot_key is not None:... | 5,297,363 |
def make_2d_link_active_stripes(shape, mu, off):
"""
Stripes mask looks like in the `mu` channel (mu-oriented links)::
1 0 0 0 1 0 0 0 1 0 0
1 0 0 0 1 0 0 0 1 0 0
1 0 0 0 1 0 0 0 1 0 0
1 0 0 0 1 0 0 0 1 0 0
where vertical is the `mu` direction, and the pattern is offset in the nu
... | 5,297,364 |
def clear() -> None:
""" Clear screen (depending on OS) """
if os.name == 'nt':
_ = os.system('cls')
else:
_ = os.system('clear') | 5,297,365 |
def get_job_uri(uuid):
"""
Queries the database for SchemaAnalysisJob objects that
have the uuid as specified by "uuid".
"""
job_query = """
PREFIX ext: <http://mu.semte.ch/vocabularies/ext/>
PREFIX mu: <http://mu.semte.ch/vocabularies/core/>
PREFIX dct: <http://purl.org/dc/t... | 5,297,366 |
def create_export_fc(path, dirname, params):
"""
"""
new_file = render_template(dirname + '/templates/dev/export_fc_var.sh', params)
make_file(path + '/dev/export_fc_var.sh', new_file) | 5,297,367 |
async def test_removing_entity_unavailable(hass):
"""Test removing an entity that is still registered creates an unavailable state."""
entry = entity_registry.RegistryEntry(
entity_id="hello.world",
unique_id="test-unique-id",
platform="test-platform",
disabled_by=None,
)
... | 5,297,368 |
def build_access_required(function_or_param_name):
"""Decorator ensures user has access to the build ID in the request.
May be used in two ways:
@build_access_required
def my_func(build):
...
@build_access_required('custom_build_id_param')
def my_func(build):
... | 5,297,369 |
def add(a,b):
"""
This function returns the sum of the given numbers
"""
return a + b | 5,297,370 |
def schema(
pairs: Iterable[tuple[str, dt.DataType]]
| Mapping[str, dt.DataType]
| None = None,
names: Iterable[str] | None = None,
types: Iterable[str | dt.DataType] | None = None,
) -> sch.Schema:
"""Validate and return an Schema object.
Parameters
----------
pairs
List or... | 5,297,371 |
def mock_args(args):
""" Context manager that mocks sys.args and captures stdout/stderr
:param args: sys.args values to mock
:type args: [str]
:rtype: None
"""
with mock.patch('sys.argv', ['dcos'] + args):
stdout, stderr = sys.stdout, sys.stderr
sys.stdout, sys.stderr = six.Stri... | 5,297,372 |
def command_sync(command: str = None):
"""Executes a synchronous command."""
return runner.execute(asynchronous=False).flask_serialize() | 5,297,373 |
def _is_prime(number, attempts=10):
"""
Miller-Rabin primality test.
A return value of False means n is certainly not prime. A return value of
True means n is very likely a prime.
"""
if number != int(number):
return False
number = int(number)
if attempts != int(atte... | 5,297,374 |
def test_sftp_fetcher(tmp_trestle_dir: pathlib.Path, monkeypatch: MonkeyPatch) -> None:
"""Test the sftp fetcher."""
def ssh_load_host_keys_mock():
return
def ssh_connect_mock():
return
def open_sftp_mock():
return
def sftp_get_mock():
return
uri = 'sftp://so... | 5,297,375 |
def touch(filename, mtime):
""" doc me """
with open(filename, 'a+'):
pass
os.utime(filename, (mtime, mtime))
return 0 | 5,297,376 |
def _save_result(args, result):
"""Save results."""
_output_file = args.output_file
if args.data_format in ["classification", "c"]:
if not _output_file:
_output_file = "./result.csv"
result = [(_file, _data.index(max(_data))) for (_file, _data) in result]
with open(_outpu... | 5,297,377 |
def get_PolyFromPolyFileObj(PolyFileObj, SavePathInp=None, units='m', comments='#', skiprows=0, shape0=2):
""" Return a polygon as a np.ndarray, extracted from a txt file or from a ToFu object, with appropriate units
Useful for :meth:`tofu.plugins.AUG.Ves._create()`
Parameters
----------
PolyFileO... | 5,297,378 |
async def create_server(conf: json.Data,
adapters: typing.Dict[str, common.Adapter],
views: hat.gui.view.ViewManager
) -> 'Server':
"""Create server"""
addr = urllib.parse.urlparse(conf['address'])
initial_view = conf['initial_view']
... | 5,297,379 |
def main(args):
"""
Main entry point
"""
logger.debug('Starting file structure scan.')
for nc_file in ilist_files(args.directory):
nc_file_name = os.path.basename(nc_file)
db_files = DataFile.objects.filter(name=nc_file_name)
if db_files.count() == 0:
logger.err... | 5,297,380 |
def test_file_cloning(renga_client, storage_responses):
"""Test file cloning."""
bucket = renga_client.buckets.create(name='world', backend='local')
assert bucket.id == 1234
file_ = bucket.files.create(name='hello.ipynb')
with file_.open('w') as fp:
fp.write(b'hello world')
cloned_fil... | 5,297,381 |
def test_float_normalization():
"""Test to normalize floats."""
t1 = '42.34-'
assert normalize_to_float(t1) == -42.34 | 5,297,382 |
def on_disconnect(mqttc, obj, rc):
"""MQTT Callback Function upon disconnecting from MQTT Broker"""
if rc == 0:
logger.debug("MQTT DISCONNECTED: rc: " + str(rc))
logger.debug("Disconnected Successfully from MQTT Broker") | 5,297,383 |
def Calc(start,end,data,vsk):
"""Calculates angles and joint values for marker data in a given range
This function is a wrapper around `calcFrames`. It calls `calcFrames`
with the given `data` and `vsk` inputs starting at index `start` and
ending at index `end` in `data`.
Parameters
----------... | 5,297,384 |
def flags_to_release(is_minor=False, is_major=False):
"""Convert flags to release type."""
if is_minor and is_major:
raise ValueError("Both `is_minor` and `is_major` are set to 'True'.")
if is_minor:
return "minor"
if is_major:
return "major"
return "normal" | 5,297,385 |
def _recursive_gf(energy, mat_l_list, mat_d_list, mat_u_list, s_in=0, s_out=0, damp=0.000001j):
"""The recursive Green's function algorithm is taken from
M. P. Anantram, M. S. Lundstrom and D. E. Nikonov, Proceedings of the IEEE, 96, 1511 - 1550 (2008)
DOI: 10.1109/JPROC.2008.927355
In order to get... | 5,297,386 |
def remove_reccuring(list_vertices):
"""Removes recurring vertices, which messes up the triangulation.
Inspired by http://stackoverflow.com/a/1143432"""
# last_point = list_vertices[-1]
list_vertices_without_last = list_vertices[:-1]
found = set()
for item in list_vertices_without_last:
if str(item) not in foun... | 5,297,387 |
def tokenize_chunks(text,
window_size,
overlap_size,
split_regex='\W+',
filter=clean,
lstrip_bag=unicode_punctuation(),
rstrip_bag=unicode_punctuation()):
"""Chunking stream white-space token... | 5,297,388 |
def query_saio(instrument="EIT",
begindate=(TODAY - timedelta(days=1)),
enddate=TODAY,
min_wave=171.0, max_wave=171.0,
resolution=1024,
return_type="VOTABLE"):
"""
Method to query the SAIO server, visit:
http://ssa.esac.esa.int/ssa/... | 5,297,389 |
def test_tell():
"""
adds in the knowledge base a sentence
"""
smaller_family.tell(expr("Male(George)"))
smaller_family.tell(expr("Female(Mum)"))
assert smaller_family.ask(expr("Male(George)")) == {}
assert smaller_family.ask(expr("Female(Mum)")) == {}
assert not smaller_family.ask(expr(... | 5,297,390 |
def init_training(args):
"""Initialize networks, optimizers and the data pipeline."""
# create dataset
dataset = {
'cats': Catfaces64Dataset.create_from_scratch,
'flowers': Flowers64Dataset.create_from_scratch
}[args.dataset](args.data_path)
print('num of images:', len(dataset))
... | 5,297,391 |
def test_auto_loss_scaling_with_const_loss_scale_tensor():
"""
Create a session with auto loss scaling enabled, and with an optimizer
with a constant loss scale value. Observe an error from the auto loss
scale transform
"""
builder = popart.Builder()
t0 = builder.addInputTensor("FLOAT", [2,... | 5,297,392 |
def read_yaml(path: str) -> Union[dict, list]:
"""Loads yaml at given path
Args:
path (str): path to yaml file
Returns:
Union[dict, list]: dictionary or list loaded from yaml depending on the yaml
"""
with open(path, encoding="UTF-8") as yaml_file:
return yaml.saf... | 5,297,393 |
async def test_hash(climate_radio_thermostat_ct100_plus):
"""Test node hash."""
node = climate_radio_thermostat_ct100_plus
assert hash(node) == hash((node.client.driver, node.node_id)) | 5,297,394 |
def is_legal(x, y, img):
"""
Check if (x, y) is a valid coordinate in img
Args:
x (int): x-coordinate
y (int): y-coordinate
img (numpy.array): Image
Returns:
bool -> True if valid, False otherwise
"""
if 0 <= x < img.shape[1] and 0 <= y < img.shape[0]:
... | 5,297,395 |
def test():
"""Test program for parseprefs().
This takes a filename as command line argument;
if no filename is given, it parses ../data/grail-defaults.
It also times how long it takes.
"""
import sys
import time
global debug
debug = 1
if sys.argv[1:]:
fn = sys.argv[1]
... | 5,297,396 |
def scrape_results_page(page_str, xpath_list):
"""Scrapes HTML page and returns dictionary of URL => document title
Args:
page_str -- the entire HTML page as a string
xpath_list -- list of xpath expressions (section and link element)
Returns:
document_ids -- a dictionary of relative URL path =... | 5,297,397 |
def find_special_vertex_groups(special_vertex_group_pattern,
bg_name=None):
"""
While ordinary vertex groups may have little semantic information, we
accept annotated models with special vertex groups, prefixed with a keyword.
This function finds all such vertex group name... | 5,297,398 |
def get_posts():
"""Return all posts from the 'database', most recent first."""
db = psycopg2.connect(database=DBNAME)
c = db.cursor()
query = 'SELECT content,time FROM posts ORDER BY time DESC'
c.execute(query)
posts = c.fetchall()
db.close()
return posts | 5,297,399 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.