content stringlengths 22 815k | id int64 0 4.91M |
|---|---|
def addToCal(url, date_from, date_end, summary):
""" Add entry in calendar to period date_from, date_end """
vcal_entry = """BEGIN:VCALENDAR
VERSION:2.0
PRODID:Pyvac Calendar
BEGIN:VEVENT
SUMMARY:%s
DTSTART;VALUE=DATE:%s
DTEND;VALUE=DATE:%s
END:VEVENT
END:VCALENDAR
"""
client = caldav.DAVClient(url)
#... | 5,312,000 |
def get_bool_from_environment(env, default):
"""Read an environment variable as a boolean.
:param env: the environment variable name
:param default: the default value
:return:
"""
try:
v = os.environ[env].lower()
if v == 'true':
v = True
elif v == 'false':
... | 5,312,001 |
def remove_tags_from_resource(ResourceARN=None, TagKeys=None):
"""
Removes one or more tags from the specified resource. This operation is supported in storage gateways of all types.
See also: AWS API Documentation
Exceptions
Examples
Lists the iSCSI stored volumes of a gateway. Removes one... | 5,312,002 |
def SetIamPolicy(zone_ref, policy):
"""Set Iam Policy request."""
set_iam_policy_req = dataplex_api.GetMessageModule(
).DataplexProjectsLocationsLakesZonesSetIamPolicyRequest(
resource=zone_ref.RelativeName(),
googleIamV1SetIamPolicyRequest=dataplex_api.GetMessageModule()
.GoogleIamV1SetIamPolic... | 5,312,003 |
def test_main():
"""
tests main for poseidonStorage.
"""
main() | 5,312,004 |
def sticky_attribute_assignment(trackable, name, value):
"""Adds dependencies, generally called from __setattr__.
This behavior is shared between Trackable and Model.
Respects NoDependency indicators, but otherwise makes trackable objects
out of common data structures and tracks objects by their attribute nam... | 5,312,005 |
def raw_to_pos_prob(raw):
"""Raw model output to positive class probability"""
probs_pos_class = []
for out in raw:
out = np.array(out)
if len(out.shape) == 1:
# This is typical style of outputs.
probs_pos_class.append(softmax(out)[1])
elif len(out.shape) == 2... | 5,312,006 |
def test_dismiss_cancelled_notifications():
"""Test various scenarios and return values for
dismiss_cancelled_notifications.
"""
notifications = [
{"title": "Google is a website", "url": "www.google.com"},
{"title": "Exeter has a website", "url": "www.exeter.ac.uk"},
{"title": "Facebook is ... | 5,312,007 |
def is_tt_object(arg) -> bool:
"""Determine whether the object is a `TT-Tensor`, `TT-Matrix` or `WrappedTT` with one of them.
:return: `True` if `TT-object`, `False` otherwise
:rtype: bool
"""
return is_tt_tensor(arg) or is_tt_matrix(arg) | 5,312,008 |
def assert_numerical_grads(
f: Callable[[Sequence[Array]], Array],
f_args: Sequence[Array],
order: int,
atol: float = 0.01,
**check_kwargs):
"""Checks that autodiff and numerical gradients of a function match.
Args:
f: function to check.
f_args: arguments of the function.
order: ord... | 5,312,009 |
def check_that_parameter_is_not_empty(parameter, parameter_name):
"""Function raises ValueError if parameter is empty"""
if not parameter:
raise ValueError(f"parameter {parameter_name} is empty") | 5,312,010 |
def setwindow (w, out):
"""
Set BLC and TRC members on out from OWindow w
Uses first window in first field on w which must be a rectangle
This may be set interactively using tvlod
* w = OWindow object
* out = ObitTask object, BLC and TRC members [0] and [1] are modified
"""
###... | 5,312,011 |
def get_nltk_builder(languages):
"""Returns a builder with stemmers for all languages added to it.
Args:
languages (list): A list of supported languages.
"""
#all_stemmers = []
all_stopwords_filters = []
all_word_characters = set()
for language in languages:
if language == ... | 5,312,012 |
def from_edge_geoms_to_node_geoms(edge_network,logger = None):
"""
Infer the coordinates of the nodes from a DataFrame that describes the coordinates of the edges as Linestrings.
This assumes that coords in the linestring are in the direction 'from' to 'to' the edge ID
A simple check will be carried out... | 5,312,013 |
def from_timestamp(
timestamp, tz=UTC
): # type: (Union[int, float], Union[str, _Timezone]) -> DateTime
"""
Create a DateTime instance from a timestamp.
"""
dt = _datetime.datetime.utcfromtimestamp(timestamp)
dt = datetime(
dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.sec... | 5,312,014 |
def resolve_labels(command: CommandBase, commands: dict):
"""Attempt to resolve any labels in command"""
dex_labels = commands['DexLabel']
command_label_args = command.get_label_args()
for command_arg in command_label_args:
for dex_label in list(dex_labels.values()):
if (os.path.same... | 5,312,015 |
def run_diit():
"""Run Digital Invisible Ink Toolkit from /bin/diit."""
popen('/bin/diit') | 5,312,016 |
def _check_shape_(joint_positions):
""" should be (7, <nb frames>, 38, 2)
7 for the images, some should be 0 because it didn't record the images for these points
1000 for the nb of frames
38 for the features (some for the legs, antennae ...) check skeleton.py in semigh's code
2 for the pose dimensio... | 5,312,017 |
def pool_process_initializer(psi4_config):
"""Initialize a subprocess for pool parallelization."""
molecule, _ = create_water_molecule()
# Use a different scratch dir for each process.
if 'psi4_scratch_dir_path' in psi4_config:
subdir = os.path.join(psi4_config['psi4_scratch_dir_path'], str(os.... | 5,312,018 |
def test_peng_suffix_math(args, ref):
""" Test peng_suffix_math function behavior """
assert putil.eng.peng_suffix_math(*args) == ref | 5,312,019 |
def image_read(path):
"""
Simple abstraction over imread
Parameters
----------
path : string
Path to be loaded
Returns
-------
image : opencv image
"""
if CV_V3 or CV_V4:
return cv2.imread(path, cv2.IMREAD_GRAYSCALE)
else:
return cv2.imread(path, cv2... | 5,312,020 |
def mpg(miles, gallons):
"""Write a program that will compute MPG for a car. Prompt the user to enter
the number of miles driven and the number of gallons used. Print a nice
message with the answer."""
miles = float(miles) / gallons
km = miles * 0.425
print miles, "mpg or in km/liter:", km
r... | 5,312,021 |
def add_genesets_name(df: pd.DataFrame) -> pd.DataFrame:
"""
Add genesets names. Used for genesets analysis.
"""
# if 'geneset' not in df.columns:
genesets = df.index.map(lambda s: s.split("_")[0])
df.insert(loc=0, column="geneset", value=genesets)
return df | 5,312,022 |
def write_index_files(files, regex, hdrnum, print_trace, content_mode="translated",
outpath=None, outstream=sys.stdout, errstream=sys.stderr):
"""Process each file and create JSON index file.
The index file will have common information in the toplevel.
There is then a ``__DIFF__`` key... | 5,312,023 |
def finish(
config: DictConfig,
model: pl.LightningModule,
datamodule: pl.LightningDataModule,
trainer: pl.Trainer,
callbacks: List[pl.Callback],
logger: List[pl.loggers.LightningLoggerBase],
) -> None:
"""Makes sure everything closed properly."""
# without this sweeps with wandb logger ... | 5,312,024 |
def write_tf_records(examples, tf_records_path, num_shards=None):
"""Writes the given ``tf.train.Example`` protos to disk as TFRecords.
Args:
examples: an iterable that emits ``tf.train.Example`` protos
tf_records_path: the path to write the ``.tfrecords`` file. If sharding
is reque... | 5,312,025 |
def set_relation_hierarchy(items_query, type_relation):
"""
Запись иерархических связей и пререквизитов
"""
try:
for key,value in items_query.items():
names = value.split(', ')
items_set = Items.objects.filter(name__in = names)
item1 = Items.objects.get(na... | 5,312,026 |
def get_all_policies():
"""
Get all policies
"""
result = http_request('GET', "/policies")
ec = {'DeepInstinct.Policies(val.id && val.id == obj.id)': result}
return_results(CommandResults(
readable_output=tableToMarkdown('Policies', result),
outputs=ec,
raw_response=res... | 5,312,027 |
def makeTestSuiteV201004():
"""Set up test suite using v201004.
Returns:
TestSuite test suite using v201004.
"""
suite = unittest.TestSuite()
suite.addTests(unittest.makeSuite(ReportServiceTestV201004))
return suite | 5,312,028 |
def copy_data_to_csv(data=[]):
"""
将从飞书下载的数据存储到csv模板里
:param data:
:return:
"""
csv_path = cfg.excel_path
try:
csv_df = open_excel(csv_path)
data_fmt = [str(item[0]) for item in data]
csv_df["完成情况"] = data_fmt
# 保存
csv_df.to_excel(csv_path, index=Fa... | 5,312,029 |
def test_atomic_non_positive_integer_min_inclusive_nistxml_sv_iv_atomic_non_positive_integer_min_inclusive_1_5(mode, save_output, output_format):
"""
Type atomic/nonPositiveInteger is restricted by facet minInclusive
with value -999999999999999999.
"""
assert_bindings(
schema="nistData/atomi... | 5,312,030 |
def add(x, y):
"""add `x` and `y`."""
return x + y | 5,312,031 |
def beale(position):
"""
optimum at (3.0, 0.5) = 0
:param position:
:return:
"""
x, y = position
return (1.5 - x + x * y) ** 2 + (2.25 - x + x * y ** 2) ** 2 + (2.625 - x + x * y ** 3) ** 2 | 5,312,032 |
def cvReleaseHist(*args):
"""cvReleaseHist(PyObject obj)"""
return _cv.cvReleaseHist(*args) | 5,312,033 |
def naive_log_ctz(x: int) -> int:
"""Count trailing zeros, in a O(log(zeros)) steps.
Args:
x: An int.
Returns:
The number of trailing zeros in x, as an int.
This implementation is much faster than the naive linear implementation,
as it performs a logarithmic number of steps relati... | 5,312,034 |
def test_3(df, seed=0):
"""training: unbalanced; test: unbalanced
training: 80k (16k 1, 64k 0)
test: 20k (4k 1, 16k 0)
"""
df_ones = df[df['label'] == 1]
df_zeros = df[df['label'] == 0]
df_ones = df_ones.sample(frac=1, random_state=seed).reset_index(drop=True)
df_zeros = df_zero... | 5,312,035 |
def test_46_optional_elements():
"""
VEN/VTN
Optional elements do not need to be included in outbound payloads, but if
they are, the VEN or VTN receiving the payload must understand and act
upon those optional elements
"""
assert False | 5,312,036 |
def getStores(customer):
"""
This function returns the stores linked to the given customer.
This function does not care about token, it is done before.
Returns the Stores in case of success, otherwise will return an error (OBJECT_NOT_FOUND if the store was not found, DB_ERROR otherwise).
"""
try:
stores... | 5,312,037 |
def create_header(multiobj_bool, constr_func):
""" Creates header to save data.
Args:
multiobj_bool (:obj:`bool`): True if multiobjective function is used.
constr_func (:obj:`list`) : Constraint functions applied.
Returns:
Header.
"""
if multiobj_bool:
header =... | 5,312,038 |
def authenticate_password(dir_cli):
"""
Function to authenticate SSO password
:param dir_cli:
:return:
"""
try:
if password.strip() == '':
logging.info('password should not be empty')
return False
dir_cli.get_services_list()
return True
except ... | 5,312,039 |
def colour_by_year(year, train_thresh, update1_thresh, update2_thresh, colours=None):
"""
Assign/return a colour depending on the year the data point was published.
Parameters
----------
year :
publication year of data point
train_thresh :
Last year threshold to assign to traini... | 5,312,040 |
def main(argv=None):
"""Command line options."""
global TAR
global _bot_logger
global _https_proxy
global _servermode
global playback_current_timestamp
global playback_timer_timestamp
global playback_user_info
global playback_variables
if argv is None:
argv = sys.argv
... | 5,312,041 |
def last_modification_datetime(path):
"""
Returns last modification datetime for a given path
"""
mtime=os.path.getmtime(path)
return datetime.datetime.fromtimestamp(mtime) | 5,312,042 |
def create_text_blocks(font: pygame.freetype.Font, padding: int) -> dict:
"""Initializes all the text blocks for later use.
:param font: The font that will be used to generate the texts.
:param padding: The size of the padding that will be created.
:return: A dictionary containing :py:class:`TextBlock`... | 5,312,043 |
def root_data(path):
"""Root path of data reference. 数据资源引用路径。
1.出于安全原因,该函数不允许客户端直接读取任何*.py代码文件;
2.所有其他类型的文件将被映射到项目的 data 目录中。
"""
state = {
'success' : 0,
'message' : "不允许客户端直接读取任何*.py代码文件"
}
if path.rfind('py') > (len(path)-4):
return json.dumps(stat... | 5,312,044 |
def testable_files(files):
"""
Given a list of files, return the files that have an extension listed in TESTABLE_FILE_EXTENSIONS and are
not blacklisted by NON_TESTABLE_FILES (metrics.yaml, auto_conf.yaml)
"""
return [f for f in files if f.endswith(TESTABLE_FILE_EXTENSIONS) and not f.endswith(NON_TE... | 5,312,045 |
def longest_cont_matrix(pool):
"""Takes in a list of sequences (pool) and returns
a matrix with longest stretch of identity"""
# Make sure pool variable is a list
if type(pool) != list:
raise ValueError('Pool is not a list')
# Array dimension
dimLen = len(pool)
# Gen... | 5,312,046 |
def test_testdict_type():
"""Raise TypeError if input of validate() is not a dict"""
schema = schemadict({'a': {'type': bool}})
schema.validate({'a': True})
with pytest.raises(TypeError):
schema.validate(True)
with pytest.raises(TypeError):
schema.validate(144)
with pytest.r... | 5,312,047 |
def list_endpoints(args):
""" List all available endpoints
"""
table = tt.Texttable()
headings = ['Endpoint Name', 'Status', 'Endpoint ID']
table.header(headings)
config_files = glob.glob('{}/*/config.py'.format(args.config_dir))
for config_file in config_files:
endpoint_dir = os.p... | 5,312,048 |
def as_int(val):
"""
Tries to convert a string to an int.
Returns None if string is empty
"""
try:
return(int(val))
except ValueError:
return(None) | 5,312,049 |
def stream(xp,yp):
"""
Calculates the stream function in physical space.
Clockwise rotation. One full rotation corresponds to 1 (second).
"""
streamValue = np.pi*(xp**2 + yp**2)
return streamValue | 5,312,050 |
def _get_switch_by_ip(switch_ip, session=None, **kwargs):
"""Get switch by switch ip."""
switch_ip_int = long(netaddr.IPAddress(switch_ip))
return utils.get_db_object(
session, models.Switch,
ip_int=switch_ip_int, **kwargs
) | 5,312,051 |
def decodeFont(name):
"""
Parses a font string into a tkinter <code>Font</code> object.
This method accepts a font in either the <code>Font.decode</code>
used by Java or in the form of a CSS-based style string.
"""
font = parseJSFont(name)
if font is None:
font = parseJavaFont(name)
... | 5,312,052 |
def usage():
"""explain usage and exit"""
sys.exit("""countLines - count lines in files
usage:
countLines files[s]""") | 5,312,053 |
def validate_dir(file_path: str, dir_type: str) -> None:
"""入力パラメータがディレクトリであるか
入力パラメータがディレクトリかを判別する
Args:
file_path (str): ファイルパス
dir_type (str): チェックするディレクトリの種類
Raises:
ValidateError: ディレクトリが空のときや,ディレクトリではないときに発生する.
"""
if _is_empty(file_path):
raise ValidateE... | 5,312,054 |
def salsa20_8(B, x, src, s_start, dest, d_start):
"""Salsa20/8 http://en.wikipedia.org/wiki/Salsa20"""
# Merged blockxor for speed
for i in range(16):
x[i] = B[i] = B[i] ^ src[s_start + i]
# This is the actual Salsa 20/8: four identical double rounds
for i in range(4):
a = (x[0]+x[... | 5,312,055 |
def get_value(obj, key, default=None):
"""
Returns dictionary item value by name for dictionary objects or property value by name for other types.
Also list of lists obj is supported.
:param obj: dict or object
:param key: dict item or property name
:param default: default value
:return:
... | 5,312,056 |
def validate_edges(g, max_kmph=200):
"""
Make sure all edges can possibly be traversed with reasonable speed
"""
good_edges, bad_edges = [], []
for u, v, data in g.edges(data=True):
dur, dist_km = data.get("duration"), data.get("distance")
# Distances < 1km are not precise enough
... | 5,312,057 |
def uploadFile(localPath:pathlike, remotePath:Union[str, S3Path]) -> Outcome[str, Union[str, S3Path]]:
"""Assumes AWS credentials exist in the environment
Though the types involved are different, the signature for
downloadFile, uploadFile, and uploadData follows the same pattern:
source -> dest... | 5,312,058 |
def calculate_bayes_probability(df: np.ndarray = 0, clusters_means: np.ndarray = 0, clusters_variances: np.ndarray = 0,
clusters_weights: np.ndarray = 0, k: int = 0):
""" calculate the normalized Bayes probability of each point per all clusters
# Arguments
df: arrays of p... | 5,312,059 |
def comanage_check_person_couid(person_id, couid) -> Tuple[int, bool]:
"""
Check if a given person is a member of couid. Return tuple of API status code
and True or False. Strings or integers accepted as parameters
"""
assert person_id is not None
assert couid is not None
params = {'coid': s... | 5,312,060 |
def tensor_contract(*tensors, output_inds=None, get=None,
backend=None, **contract_opts):
"""Efficiently contract multiple tensors, combining their tags.
Parameters
----------
tensors : sequence of Tensor
The tensors to contract.
output_inds : sequence of str
If ... | 5,312,061 |
def registry(db, term=None):
"""List the organizations available in the registry.
The function will return the list of organizations. If term
parameter is set, it will only return the information about
the organizations which match that term. When the given term does
not match with any organization... | 5,312,062 |
def get_column_names(connection,schema_name, table_name):
"""
Returns a list of column names for a given table.
"""
cur = connection.cursor()
try:
cur.execute("SELECT column_name,data_type FROM information_schema.columns WHERE table_schema = '%s' AND table_name = '%s';" % (schema... | 5,312,063 |
def _write_dataset_files(
root_path: pathlib.Path, namespace: str, datasets: List[str]
) -> str:
"""Write the repo content containing the datasets."""
repo_path = root_path / namespace
# Create all datasets
for ds_name in datasets:
ds_path = repo_path / ds_name / f'{ds_name}.py'
ds_path.parent.mkdir... | 5,312,064 |
def get(params, query, offset, limit):
"""Get the data from BigQuery."""
sql = SQL.format(
table_id='%ss' % params['type'],
where_clause=query.get_where_clause(),
prefix=params['type'],
offset=offset,
limit=limit)
client = big_query.Client()
result = client.query(query=sql, offset=... | 5,312,065 |
def get_rose_username():
"""
Get the Rose username from Subversion's config file
"""
try:
config = SafeConfigParser()
config.read(svn_servers)
return config.get('metofficesharedrepos','username')
except Exception:
return None | 5,312,066 |
def HttpRequest(service, operation, data, uri, extra_headers=None,
url_params=None, escape_params=True, content_type='application/atom+xml'):
"""Performs an HTTP call to the server, supports GET, POST, PUT, and DELETE.
This method is deprecated, use atom.http.HttpClient.request instead.
Usage example, pe... | 5,312,067 |
def findLargestGap(depth_og, min_dist, barrier_h=0, min_gap=0):
"""
Given depth image, find the largest gap that goes from the bottom of
the image to the top. Use min_dist as threshold below which objects are
shown to be too close. Return the position in the middle of the largest
gap.
"""
d... | 5,312,068 |
def read_data(path):
"""
Read in a .csv file. Convert each line to single dict, and then append to a list.
Parameters
----------
filepath : string
This is a directory string to point to the desired file from the BASE_PATH.
Returns
-------
list_of_dicts
Returns a list of... | 5,312,069 |
def _CalcProjectAlert(project):
"""Return a string to be shown as red text explaning the project state."""
project_alert = None
if project.read_only_reason:
project_alert = 'READ-ONLY: %s.' % project.read_only_reason
if project.moved_to:
project_alert = 'This project has moved to: %s.' % project.moved... | 5,312,070 |
def normalized_8UC3_image(image):
"""
:param image: two-dimensional image
:return: normalized to [0, 255] three-dimensional image
"""
assert len(image.shape) == 2, 'two-dimensional images are only supported'
image = normalized_8U_image(image)
return np.stack((image,) * 3, axis=-1) | 5,312,071 |
def _parse_arguments() -> argparse.Namespace:
"""Plot argument parser.
"""
parser = argparse.ArgumentParser(description="Plot")
parser.add_argument(
"--inputs",
type=str,
required=True,
help=
"comma-separated list of input data filenames (e.g., --input input1,input2)\n"
+ "Th... | 5,312,072 |
def _read_plan_yaml(yaml_path: str) -> PlanSchema:
"""Read YAML, either from a path on disk or from stdin."""
try:
if yaml_path == "-":
data = sys.stdin.read()
result = PlanSchema.parse_raw(data)
else:
with open(yaml_path, "r", encoding="utf8") as fp:
... | 5,312,073 |
def remove_sex(beta, array_type='450k'):
"""Remove non-autosomal cpgs from beta matrix.
Parameters
----------
array_type
450k/850k array?
"""
beta = robjects.r("""function (beta,array.type){
featureset<-array.type
autosomal.sites <- meffil.get.autosomal.sites(featureset)... | 5,312,074 |
def gremlin_search_package_in_ecosystem(ecosystem, package):
"""Search packages from the selected ecosystem."""
query = 'g.V().has("ecosystem", "{ecosystem}").has("name", "{package}").out("has_version")'.\
format(ecosystem=ecosystem, package=package)
print(query)
data = post_query(query)
try... | 5,312,075 |
def test_invalid_bbox():
"""
Test an invalid bbox query:
"""
client = TestClient(app)
response = client.get(
url=f"http://localhost/v1/places?bbox={INVALID_BBOX_PARIS_LEFT_PERM_RIGHT}&raw_filter=*,bakery&raw_filter=museum,*&raw_filter=*,place_of_worship"
)
assert response.status_co... | 5,312,076 |
def create_netcdf(valid):
"""Create and return the netcdf file"""
ncfn = "/mesonet/data/iemre/cfs_%s.nc" % (valid.strftime("%Y%m%d%H"), )
nc = ncopen(ncfn, 'w')
nc.title = "IEM Regridded CFS Member 1 Forecast %s" % (valid.year,)
nc.platform = "Grided Forecast"
nc.description = "IEM Regridded CFS... | 5,312,077 |
def check_fortran_type(typestr, error=False):
"""Return <typestr> if a valid Fortran type, otherwise, None
if <error> is True, raise an Exception if <typestr> is not valid.
>>> check_fortran_type("real")
'real'
>>> check_fortran_type("integer")
'integer'
>>> check_fortran_type("InteGer")
... | 5,312,078 |
def pyro_service_process(auto_start=False, *args, **kwargs):
"""Start a pyro service in a separate process."""
# Set up nameserver process.
logger.debug(f'Setting up Pyro service process.')
service_process = Process(target=pyro_service, args=args, kwargs=kwargs)
if auto_start: # noqa
logge... | 5,312,079 |
def plot_transport(gs, transport,
exp_num=None, linewidth=None, linestyle='-',
decorate=True, ylim=None, panel_label=None, legloc=1):
"""Plot the northward freshwater transport"""
ax = plt.subplot(gs)
plt.sca(ax)
if decorate:
labels = ['ocean freshwater tr... | 5,312,080 |
def _encode_str(s,buff):
"""
encode string to a buffer
"""
s = bytearray(s)
l = len(s)
buff.append(bytearray(str(l)+':','utf-8'))
buff.append(s) | 5,312,081 |
def topk_caculate(predict_p, true_labels, k=1, number_cat=None, epsilon=1e-19):
"""
topk准确率计算
Args:
predict_p: 预测的概率分布shape=(N,number_cat)
true_labels: 真实标签,shape=(N,)
k: top k
number_cat: number categories
eposion: e
Returns:
topk acc [top1,top2,...,topk... | 5,312,082 |
def mon_operator(xs):
"""xs = [unary_op, unary] OR primary"""
if not isinstance(xs, list):
return xs
return TokenOperator(xs[0], [xs[1]]) | 5,312,083 |
def chunked_phrase_strict(m) -> List[BasePhraseChunk]:
"""A chunked phrase that must start with dictation.
This capture can be used to insert keywords that would otherwise be handled
as symbols or commands. For example, we could put this in a .talon file:
snake <chunked_phrase_strict>:
... | 5,312,084 |
def merge_nodes(merge_nodes, player_nodes, edge_index):
"""
merge nodes by redirecting any connected edges, only the edges are changed
"""
m_nodes = merge_nodes.copy()
while m_nodes:
node = m_nodes.pop()
#if node not in merged:
# get edges going out from the node
... | 5,312,085 |
def createIngesterH(suffix, headerKeys, dataKeys):
"""createIngesterH.
Args:
suffix:
headerKeys:
dataKeys:
"""
print("cat > DetectionCrossmatcher%s.h <<EOF" % (suffix))
print("/*")
print(" * DetectionCrossmatcher%s.h" % (suffix))
print(" *")
print(" * Created o... | 5,312,086 |
def load_portfolio(portfolio_filepath):
"""
Load Portfolio json file to dataframe
INPUT:
portfolio_filepath: string
OUTPUT:
portfolio: dataframe
"""
portfolio = pd.read_json(portfolio_filepath, orient='records', lines=True)
return portfolio | 5,312,087 |
def transform_group_roles_data(data, okta_org_id):
"""
Transform user role data
:param data: data returned by Okta server
:param okta_org_id: okta organization id
:return: Array of dictionary containing role properties
"""
role_data = json.loads(data)
user_roles = []
for role in ro... | 5,312,088 |
def price_lineplot(card_id, df):
"""in construction"""
fig, ax = plt.subplots()
df_price =(get_price_list_from_redis(card_id))
sns.lineplot(x=df_price.index, y=df_price['price'], ax=ax)
ax.set_title(df.loc[df['id'] == card_id]['name'].values[0])
ax.set_ylim(ymin=0)
return fig | 5,312,089 |
def save_sic_taxonomy():
"""Fetch SIC taxonomy and save as excel file"""
response = requests.get(_SIC_TAXONOMY_URL)
with open(_SIC_OUTPUT_FILE, "wb") as f:
f.write(response.content) | 5,312,090 |
def status_select_block(initial_option: str = None):
"""Builds the incident status select block"""
status_options = [option_from_template(text=x.value, value=x.value) for x in IncidentStatus]
block = {
"block_id": IncidentBlockId.status,
"type": "input",
"label": {"type": "plain_text... | 5,312,091 |
def make_pin_thumbnail(adict):
"""Make the artsy-thumbnail for the pin on the USGS webpages.
"""
imtdict = adict['imtdict']
grid = np.nan_to_num(imtdict['mean'], nan=0.0)
metadata = imtdict['mean_metadata']
num_pixels = 300
randx = np.random.rand(num_pixels)
randy = np.random.rand(num_pi... | 5,312,092 |
def CheckPrerequisites(benchmark_config):
"""Verifies that the required resources are present.
Raises:
perfkitbenchmarker.data.ResourceNotFound: On missing resource.
"""
if FLAGS['num_vms'].present and FLAGS.num_vms < 3:
raise ValueError('Web Serving requires at least 3 VMs') | 5,312,093 |
def streaming_order_filter(
include_overall_position: bool = None,
customer_strategy_refs: list = None,
partition_matched_by_strategy_ref: bool = None,
) -> dict:
"""
:param bool include_overall_position: Returns overall / net position (OrderRunnerChange.mb / OrderRunnerChange.ml)
:param list cu... | 5,312,094 |
def fasterrcnn_resnet_fpn_x(*args, **kwargs):
"""Instantiate FRCNN-ResNet-FPN with extra RoI projection"""
return FasterRCNN_(fasterrcnn_resnet_fpn(*args, **kwargs)) | 5,312,095 |
def circuit_measure_max_once():
"""A fixture of a circuit that measures wire 0 once."""
return qml.expval(qml.PauliX(wires=0)) | 5,312,096 |
def regenerate_image_filename_using_dimensions(filename, height, width):
"""Returns the name of the image file with dimensions in it.
Args:
filename: str. The name of the image file to be renamed.
height: int. Height of the image.
width: int. Width of the image.
Returns:
st... | 5,312,097 |
def calculate_time_matrix(name):
"""Calucation and round in closest 15 minutes, delivery stops"""
gmaps = frappe.db.get_value('Google Maps', None,
['client_key', 'enabled', 'home_address'], as_dict=1)
if not gmaps.enabled:
frappe.throw(_("Google Maps integration is not enabled"))
try:
gmaps_client = google... | 5,312,098 |
def revoke_token():
"""revoke token"""
token_string = get_token_from_headers(request)
try:
token = OARepoAccessToken.get_by_token(token_string)
assert token.is_valid()
except:
time.sleep(INVALID_TOKEN_SLEEP)
json_abort(401, {"message": f"Invalid token. ({token_string})"})... | 5,312,099 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.