uid
stringlengths
24
24
split
stringclasses
1 value
category
stringclasses
2 values
content
stringlengths
5
482k
signature
stringlengths
1
14k
suffix
stringlengths
1
482k
prefix
stringlengths
9
14k
prefix_token_count
int64
3
5.01k
prefix_token_budget
int64
64
256
element_token_count
int64
1
292k
signature_token_count
int64
1
5.01k
prefix_context_token_count
int64
0
255
repo
stringlengths
7
112
path
stringlengths
4
208
language
stringclasses
1 value
name
stringlengths
1
218
qualname
stringlengths
1
218
start_line
int64
1
26.7k
end_line
int64
1
26.7k
signature_start_line
int64
1
26.7k
signature_end_line
int64
1
26.7k
source_hash
stringlengths
40
40
source_dataset
stringclasses
1 value
source_split
stringclasses
1 value
2fbaf09b9b799217826ed1e2
train
function
def is_bridge_setup(interface): process = subprocess.run(["brctl", "show"], capture_output=True) output = process.stdout.decode("utf-8") if "rascsi_bridge" in output and interface in output: return True return False
def is_bridge_setup(interface):
process = subprocess.run(["brctl", "show"], capture_output=True) output = process.stdout.decode("utf-8") if "rascsi_bridge" in output and interface in output: return True return False
"-f", image], capture_output=True ) def attach_daynaport(scsi_id): return subprocess.run( ["rasctl", "-i", scsi_id, "-c", "attach", "-t", "daynaport"], capture_output=True, ) def is_bridge_setup(interface):
64
64
56
6
58
hsiboy/RASCSI
src/web/ractl_cmds.py
Python
is_bridge_setup
is_bridge_setup
113
118
113
113
0a7e03a575cc1f0de0776372c76ee5b87cb7aa24
bigcode/the-stack
train
58b3fd0ceba27f4f08328288
train
function
def detach_all(): for scsi_id in range(0, 7): subprocess.run(["rasctl", "-c" "detach", "-i", str(scsi_id)])
def detach_all():
for scsi_id in range(0, 7): subprocess.run(["rasctl", "-c" "detach", "-i", str(scsi_id)])
attach", "-t", device_type, "-i", scsi_id, "-f", image], capture_output=True, ) def detach_by_id(scsi_id): return subprocess.run(["rasctl", "-c" "detach", "-i", scsi_id], capture_output=True) def detach_all():
64
64
38
4
60
hsiboy/RASCSI
src/web/ractl_cmds.py
Python
detach_all
detach_all
85
87
85
85
40f3ea161c4d25225f2c27c35d20d2ed56166abf
bigcode/the-stack
train
e056ac29a749c3125f25ced5
train
function
def get_valid_scsi_ids(devices): invalid_list = EXCLUDE_SCSI_IDS.copy() for device in devices: if device["file"] != "NO MEDIA" and device["file"] != "-": invalid_list.append(int(device["id"])) valid_list = list(range(8)) for id in invalid_list: valid_list.remove(id) vali...
def get_valid_scsi_ids(devices):
invalid_list = EXCLUDE_SCSI_IDS.copy() for device in devices: if device["file"] != "NO MEDIA" and device["file"] != "-": invalid_list.append(int(device["id"])) valid_list = list(range(8)) for id in invalid_list: valid_list.remove(id) valid_list.reverse() return vali...
] ) return files_list def list_config_files(): files_list = [] for root, dirs, files in os.walk(base_dir): for file in files: if file.endswith(".csv"): files_list.append(file) return files_list def get_valid_scsi_ids(devices):
64
64
87
9
54
hsiboy/RASCSI
src/web/ractl_cmds.py
Python
get_valid_scsi_ids
get_valid_scsi_ids
49
60
49
49
105205edcb243ec88c07ce9b45a93b3ed4014257
bigcode/the-stack
train
99bd166a399a380dbb94ffac
train
function
def get_type(scsi_id): return list_devices()[int(scsi_id)]["type"]
def get_type(scsi_id):
return list_devices()[int(scsi_id)]["type"]
file"] != "NO MEDIA" and device["file"] != "-": invalid_list.append(int(device["id"])) valid_list = list(range(8)) for id in invalid_list: valid_list.remove(id) valid_list.reverse() return valid_list def get_type(scsi_id):
64
64
20
7
56
hsiboy/RASCSI
src/web/ractl_cmds.py
Python
get_type
get_type
63
64
63
63
3cf7dab5b4a5e4e1abc888b9e15f788350a3c57c
bigcode/the-stack
train
aca506e792357f9314ed6265
train
function
def is_active(): process = subprocess.run(["systemctl", "is-active", "rascsi"], capture_output=True) return process.stdout.decode("utf-8").strip() == "active"
def is_active():
process = subprocess.run(["systemctl", "is-active", "rascsi"], capture_output=True) return process.stdout.decode("utf-8").strip() == "active"
"*.zip"] valid_file_types = r"|".join([fnmatch.translate(x) for x in valid_file_suffix]) # List of SCSI ID's you'd like to exclude - eg if you are on a Mac, the System is usually 7 EXCLUDE_SCSI_IDS = [7] def is_active():
64
64
42
4
60
hsiboy/RASCSI
src/web/ractl_cmds.py
Python
is_active
is_active
14
16
14
14
5d8d57ddc00696171092d5e063f8b1710493fff0
bigcode/the-stack
train
fcef91d6696e0eeadc56be0f
train
function
def list_files(): files_list = [] for path, dirs, files in os.walk(base_dir): # Only list valid file types files = [f for f in files if re.match(valid_file_types, f)] files_list.extend( [ ( os.path.join(path, file), # TO...
def list_files():
files_list = [] for path, dirs, files in os.walk(base_dir): # Only list valid file types files = [f for f in files if re.match(valid_file_types, f)] files_list.extend( [ ( os.path.join(path, file), # TODO: move formattin...
Mac, the System is usually 7 EXCLUDE_SCSI_IDS = [7] def is_active(): process = subprocess.run(["systemctl", "is-active", "rascsi"], capture_output=True) return process.stdout.decode("utf-8").strip() == "active" def list_files():
64
64
127
4
60
hsiboy/RASCSI
src/web/ractl_cmds.py
Python
list_files
list_files
19
37
19
19
60a145895e3685cd99a630d9682bfc6af71a4050
bigcode/the-stack
train
6a5615393bfdb25c9bfa83c7
train
function
def daynaport_setup_bridge(interface): return subprocess.run( [f"{base_dir}../RASCSI/src/raspberrypi/setup_bridge.sh", interface], capture_output=True, )
def daynaport_setup_bridge(interface):
return subprocess.run( [f"{base_dir}../RASCSI/src/raspberrypi/setup_bridge.sh", interface], capture_output=True, )
def is_bridge_setup(interface): process = subprocess.run(["brctl", "show"], capture_output=True) output = process.stdout.decode("utf-8") if "rascsi_bridge" in output and interface in output: return True return False def daynaport_setup_bridge(interface):
64
64
42
8
55
hsiboy/RASCSI
src/web/ractl_cmds.py
Python
daynaport_setup_bridge
daynaport_setup_bridge
121
125
121
121
075960914d59af46d84dec8a563e14e30fe8cb7b
bigcode/the-stack
train
56b2d050dbb68ca61141b2b0
train
function
def disconnect_by_id(scsi_id): return subprocess.run( ["rasctl", "-c", "disconnect", "-i", scsi_id], capture_output=True )
def disconnect_by_id(scsi_id):
return subprocess.run( ["rasctl", "-c", "disconnect", "-i", scsi_id], capture_output=True )
"-c" "detach", "-i", scsi_id], capture_output=True) def detach_all(): for scsi_id in range(0, 7): subprocess.run(["rasctl", "-c" "detach", "-i", str(scsi_id)]) def disconnect_by_id(scsi_id):
63
64
37
8
55
hsiboy/RASCSI
src/web/ractl_cmds.py
Python
disconnect_by_id
disconnect_by_id
90
93
90
90
6127980dd18e85c875386faf8cbb36410cacfab6
bigcode/the-stack
train
fd206837b658b00262732da2
train
function
def eject_by_id(scsi_id): return subprocess.run(["rasctl", "-i", scsi_id, "-c", "eject"])
def eject_by_id(scsi_id):
return subprocess.run(["rasctl", "-i", scsi_id, "-c", "eject"])
(["rasctl", "-c" "detach", "-i", str(scsi_id)]) def disconnect_by_id(scsi_id): return subprocess.run( ["rasctl", "-c", "disconnect", "-i", scsi_id], capture_output=True ) def eject_by_id(scsi_id):
64
64
30
8
56
hsiboy/RASCSI
src/web/ractl_cmds.py
Python
eject_by_id
eject_by_id
96
97
96
96
d94ae2f8ea0c69d20c4103672f30a29f6bccf2f0
bigcode/the-stack
train
5d1e556445b236d2212753e2
train
class
class Identities: segment = "identities" def __init__(self, http: Http): self._http = http # Read functions. def fetch(self) -> Dict: """Fetch the identities. :return: A list with the Nexus payloads of the identities. """ return self._http.get([self.segment]) ...
class Identities:
segment = "identities" def __init__(self, http: Http): self._http = http # Read functions. def fetch(self) -> Dict: """Fetch the identities. :return: A list with the Nexus payloads of the identities. """ return self._http.get([self.segment]) def fetch_(se...
provides a Python interface for operations on Identities. It is part of the Identity & Access Management API of Blue Brain Nexus v1. https://bluebrain.github.io/nexus/docs/api/iam/iam-identities.html """ from typing import Dict from nexussdk.utils.http import Http class Identities:
64
64
123
4
59
BlueBrain/nexus-python-sdk
nexussdk/identities.py
Python
Identities
Identities
12
32
12
12
c66b6271af8e1e01d9e3074e880784a8caa8aaba
bigcode/the-stack
train
c897f60ef27abd07d2c12153
train
function
def adv_loss(d_source, d_target, openc_target): # d_source, d_target 36,2 # openc_target 36,2,1000 :,0,: -> outer :,1,: ->inter assert len(d_source.size())==2 and len(d_target.size())==2 and d_source.size(1)==2 and d_target.size(1)==2 assert len(openc_target.size())==3 assert openc_target.size(1) ==...
def adv_loss(d_source, d_target, openc_target): # d_source, d_target 36,2 # openc_target 36,2,1000 :,0,: -> outer :,1,: ->inter
assert len(d_source.size())==2 and len(d_target.size())==2 and d_source.size(1)==2 and d_target.size(1)==2 assert len(openc_target.size())==3 assert openc_target.size(1) == 2 d_source = F.softmax(d_source, 1) # 0->source, 1->target d_target = F.softmax(d_target, 1) openc_target = F.softmax(open...
[:, 0, :] + 1e-8) * label_n, 1)[0]) return open_loss_pos, open_loss_neg def adv_loss(d_source, d_target, openc_target): # d_source, d_target 36,2 # openc_target 36,2,1000 :,0,: -> outer :,1,: ->inter
79
79
266
48
30
yangzhaopeng3/visda21
utils/loss.py
Python
adv_loss
adv_loss
36
52
36
38
4d7722f003d0154d04acb8a1723b462e64ed60dd
bigcode/the-stack
train
f0bc40bad00975c74f21b235
train
function
def ova_loss(out_open, label): assert len(out_open.size()) == 3 assert out_open.size(1) == 2 # 36, 2, 1000 out_open = F.softmax(out_open, 1) # 36, 1000 label_p = torch.zeros((out_open.size(0), out_open.size(2))).long().cuda() # label_range = torch.range(0, out_ope...
def ova_loss(out_open, label):
assert len(out_open.size()) == 3 assert out_open.size(1) == 2 # 36, 2, 1000 out_open = F.softmax(out_open, 1) # 36, 1000 label_p = torch.zeros((out_open.size(0), out_open.size(2))).long().cuda() # label_range = torch.range(0, out_open.size(0) - 1).long() # 0, ...
import torch.nn.functional as F def entropy(p, prob=True, mean=True): if prob: p = F.softmax(p) en = -torch.sum(p * torch.log(p+1e-5), 1) if mean: return torch.mean(en) else: return en #TODO: look at here! def ova_loss(out_open, label):
81
81
271
8
73
yangzhaopeng3/visda21
utils/loss.py
Python
ova_loss
ova_loss
14
34
14
14
83dcc6d0741147c056a206e134c30777fc886cb0
bigcode/the-stack
train
d60d2d3d412eaf894b6323de
train
function
def entropy(p, prob=True, mean=True): if prob: p = F.softmax(p) en = -torch.sum(p * torch.log(p+1e-5), 1) if mean: return torch.mean(en) else: return en
def entropy(p, prob=True, mean=True):
if prob: p = F.softmax(p) en = -torch.sum(p * torch.log(p+1e-5), 1) if mean: return torch.mean(en) else: return en
import torch import torch.nn.functional as F def entropy(p, prob=True, mean=True):
20
64
58
10
9
yangzhaopeng3/visda21
utils/loss.py
Python
entropy
entropy
4
11
4
4
be2c8aa866906b2c4e5697fde482f23d38f741f9
bigcode/the-stack
train
d01a6cd898332ee763dc63e9
train
function
def open_entropy(out_open): assert len(out_open.size()) == 3 assert out_open.size(1) == 2 out_open = F.softmax(out_open, 1) # 36, 2, 1000 ent_open = torch.mean(torch.mean(torch.sum(-out_open * torch.log(out_open + 1e-8), 1), 1)) return ent_open
def open_entropy(out_open):
assert len(out_open.size()) == 3 assert out_open.size(1) == 2 out_open = F.softmax(out_open, 1) # 36, 2, 1000 ent_open = torch.mean(torch.mean(torch.sum(-out_open * torch.log(out_open + 1e-8), 1), 1)) return ent_open
(openc_target, dim=1)[1],dim=1), classes) adv_loss = torch.mean(-torch.log(d_source[:,0] + 1e-8) - w_t*torch.log(d_target[:,1]+1e-8)) return adv_loss def open_entropy(out_open):
64
64
87
6
57
yangzhaopeng3/visda21
utils/loss.py
Python
open_entropy
open_entropy
54
59
54
54
2231e0e48b26bbd3bd2c7c19d472cdc3c6d39047
bigcode/the-stack
train
ae8f09833864babe6621708b
train
class
class PAZTestCase(unittest.TestCase): """ Test cases for reading GSE PAZ files. """ def test_read_with_spaces(self): """ Reading PAZ files where PAZ are separated by spaces. """ f = io.StringIO("""CAL1 RJOB LE-3D Z M24 PAZ 010824 0001 2 -4.39823 4...
class PAZTestCase(unittest.TestCase):
""" Test cases for reading GSE PAZ files. """ def test_read_with_spaces(self): """ Reading PAZ files where PAZ are separated by spaces. """ f = io.StringIO("""CAL1 RJOB LE-3D Z M24 PAZ 010824 0001 2 -4.39823 4.48709 -4.39823 -4.48709 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ The paz test suite. """ from __future__ import (absolute_import, division, print_function, unicode_literals) from future.builtins import * # NOQA import io import unittest from obspy.io.gse2 import paz class PAZTestCase(unittest.TestCase):
76
175
585
9
66
earthinversion/Fnet_IRIS_data_automated_download
IRIS_data_download/IRIS_download_support/obspy/io/gse2/tests/test_paz.py
Python
PAZTestCase
PAZTestCase
16
69
16
16
6aa5b24e6513c3541b7ed9a4684dfebf23ac82c0
bigcode/the-stack
train
1595ed553bae2d8f1e4ad14a
train
function
def suite(): return unittest.makeSuite(PAZTestCase, 'test')
def suite():
return unittest.makeSuite(PAZTestCase, 'test')
3.08709, z[1].imag) self.assertAlmostEqual(-1.09823, z[2].real) self.assertAlmostEqual(30.08709, z[2].imag) self.assertAlmostEqual(0.5, k) f.close() def suite():
64
64
16
3
61
earthinversion/Fnet_IRIS_data_automated_download
IRIS_data_download/IRIS_download_support/obspy/io/gse2/tests/test_paz.py
Python
suite
suite
72
73
72
72
b5a723917c1c66b0ff49a9c7edbe957e46fae3c1
bigcode/the-stack
train
282598eb00b65a00313614d9
train
class
class SkpicturePrinter(page_measurement.PageMeasurement): @classmethod def AddCommandLineArgs(cls, parser): parser.add_option('-s', '--skp-outdir', help='Output directory for the SKP files') @classmethod def ProcessCommandLineArgs(cls, parser, args): if not args.skp_outdir: ...
class SkpicturePrinter(page_measurement.PageMeasurement): @classmethod
def AddCommandLineArgs(cls, parser): parser.add_option('-s', '--skp-outdir', help='Output directory for the SKP files') @classmethod def ProcessCommandLineArgs(cls, parser, args): if not args.skp_outdir: parser.error('Please specify --skp-outdir') cls._skp_outdir = args.sk...
# Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import glob import os from telemetry.page import page_measurement _JS = 'chrome.gpuBenchmarking.printToSkPicture("{0}");' class SkpicturePrinter(page_measu...
82
84
283
14
68
justremotephone/android_external_chromium_org
tools/perf/measurements/skpicture_printer.py
Python
SkpicturePrinter
SkpicturePrinter
13
42
13
14
6dfb3858519a69efb6a9b9c8946c193ec2c7ba93
bigcode/the-stack
train
037854c93ac1c0bcd09cc8e4
train
function
def json_to_df(filename): with open(filename, 'r') as f: json_string = json.load(f) df_from_json = pd.read_json(json_string) df_from_json['locations_day_index'] = df_from_json['locations_day_index'].apply(tuple) df_from_json['location_1_2_index'] = df_from_json['location_1_2_index']....
def json_to_df(filename):
with open(filename, 'r') as f: json_string = json.load(f) df_from_json = pd.read_json(json_string) df_from_json['locations_day_index'] = df_from_json['locations_day_index'].apply(tuple) df_from_json['location_1_2_index'] = df_from_json['location_1_2_index'].apply(tuple) return df...
arrows[i][4]) arrow.add_to(feature_group) i+=1 feature_group.add_to(folium_map) folium.LayerControl().add_to(folium_map) folium_map.save('./templates/Belgium_DO_'+map_suffix+'.html') def json_to_df(filename):
64
64
90
6
58
mariusvileiniskisibm/optimal-patient-allocation-vis
run_app.py
Python
json_to_df
json_to_df
181
187
181
181
3a8a8b915f01862fa2022cff37ae2bb52f9ee7e2
bigcode/the-stack
train
0cceab95bc7072b1ffaffbfb
train
function
def get_provinces_routes_dur(file_name): # reading province_coordinates.csv to coordinates_dict body = read_input_file(file_name) coordinates_df = pd.read_csv(body) coordinates_dict = coordinates_df.set_index('Province Name').T.to_dict('list') url = 'http://router.project-osrm.org/table/v1/driv...
def get_provinces_routes_dur(file_name): # reading province_coordinates.csv to coordinates_dict
body = read_input_file(file_name) coordinates_df = pd.read_csv(body) coordinates_dict = coordinates_df.set_index('Province Name').T.to_dict('list') url = 'http://router.project-osrm.org/table/v1/driving/' i=1 for k,v in coordinates_dict.items(): if i<len(coordinates_dict): ...
"].values[0] def get_prov(self, p_id): return self._mp.loc[self._mp.id==p_id, "province_en"].values[0] @property def index_list(self): return list(self._mp.id) province_map = ProvinceMap("province_id_mapping.csv") def get_provinces_routes_dur(file_name): # reading province...
90
90
300
21
69
mariusvileiniskisibm/optimal-patient-allocation-vis
run_app.py
Python
get_provinces_routes_dur
get_provinces_routes_dur
30
51
30
31
67d37feb65dd8721d3db26f1514eb77a9227ee34
bigcode/the-stack
train
5814bcc2771b76b631bc72a2
train
function
def generate_DO_map_data(p1_p2_t_transport_df): p1_p2_transport_df_grouped = p1_p2_t_transport_df.groupby('location_1_2_index').agg( {'location1_name':'first','location2_name':'first',"total_patients_transferred": "sum", 'route_duration':'first', 'cost':'sum'}) df_temp_list = [] for t in p1_p2_t_tr...
def generate_DO_map_data(p1_p2_t_transport_df):
p1_p2_transport_df_grouped = p1_p2_t_transport_df.groupby('location_1_2_index').agg( {'location1_name':'first','location2_name':'first',"total_patients_transferred": "sum", 'route_duration':'first', 'cost':'sum'}) df_temp_list = [] for t in p1_p2_t_transport_df.date_index.unique(): if sum(p1_p2_...
locations[0][1]) p2 = Point(locations[1][0], locations[1][1]) rotation = get_bearing(p1, p2) - 90 arrow_lats = np.linspace(p1.lat, p2.lat, n_arrows + 2)[1:n_arrows+1] arrow_lons = np.linspace(p1.lon, p2.lon, n_arrows + 2)[1:n_arrows+1] arrows = [] for points in zip(arrow_lat...
156
157
525
14
141
mariusvileiniskisibm/optimal-patient-allocation-vis
run_app.py
Python
generate_DO_map_data
generate_DO_map_data
104
126
104
105
df6a19bd916987a3d440d58e8ad4faa882dba2bf
bigcode/the-stack
train
7949d8ddc55ea8ca515345fd
train
function
@atexit.register def shutdown(): if client: client.disconnect()
@atexit.register def shutdown():
if client: client.disconnect()
cenario_3, 'scenario_3') return render_template('index.html') @app.route('/map') def show_map(map_label=None): map_label = request.args.get('scenario_id', '') return render_template('Belgium_DO_'+map_label+'.html') @atexit.register def shutdown():
64
64
16
8
56
mariusvileiniskisibm/optimal-patient-allocation-vis
run_app.py
Python
shutdown
shutdown
233
236
233
234
098087407b6aab1c98a108686fb2b9afa55ebdc4
bigcode/the-stack
train
9101403f1f29f5ff5937eb79
train
function
@app.route('/') def index(): # client_to_COS.download_file(Bucket=COS_BUCKET_NAME, Filename='transfers_scen_1.json', Key='transfers_scen_1.json') # client_to_COS.download_file(Bucket=COS_BUCKET_NAME, Filename='transfers_scen_2.json', Key='transfers_scen_2.json') # client_to_COS.download_file(Bucket=COS_BU...
@app.route('/') def index(): # client_to_COS.download_file(Bucket=COS_BUCKET_NAME, Filename='transfers_scen_1.json', Key='transfers_scen_1.json') # client_to_COS.download_file(Bucket=COS_BUCKET_NAME, Filename='transfers_scen_2.json', Key='transfers_scen_2.json') # client_to_COS.download_file(Bucket=COS_BU...
scenario_1_df = json_to_df('transfers_scen_1.json') scenario_2_df = json_to_df('transfers_scen_2.json') scenario_3_df = json_to_df('transfers_scen_3.json') scenario_1_map_DF = generate_DO_map_data(scenario_1_df) scenario_2_map_DF = generate_DO_map_data(scenario_2_df) scenario_3_map_DF...
_from_json['locations_day_index'].apply(tuple) df_from_json['location_1_2_index'] = df_from_json['location_1_2_index'].apply(tuple) return df_from_json @app.route('/') def index(): # client_to_COS.download_file(Bucket=COS_BUCKET_NAME, Filename='transfers_scen_1.json', Key='transfers_scen_1.json') # ...
156
156
520
113
42
mariusvileiniskisibm/optimal-patient-allocation-vis
run_app.py
Python
index
index
189
226
189
196
7d0723caa748f7aca6fe14c74f751763d44b30e4
bigcode/the-stack
train
ee41d085bf3cb53a5bd67d8e
train
function
def get_bearing(p1, p2): long_diff = np.radians(p2.lon - p1.lon) lat1 = np.radians(p1.lat) lat2 = np.radians(p2.lat) x = np.sin(long_diff) * np.cos(lat2) y = (np.cos(lat1) * np.sin(lat2) - (np.sin(lat1) * np.cos(lat2) * np.cos(long_diff))) bearing = np.degree...
def get_bearing(p1, p2):
long_diff = np.radians(p2.lon - p1.lon) lat1 = np.radians(p1.lat) lat2 = np.radians(p2.lat) x = np.sin(long_diff) * np.cos(lat2) y = (np.cos(lat1) * np.sin(lat2) - (np.sin(lat1) * np.cos(lat2) * np.cos(long_diff))) bearing = np.degrees(np.arctan2(x, y)) i...
= coordinates_df.loc[coordinates_df["p_id"] == prov_id, 'Latitude'].values[0] Long = coordinates_df.loc[coordinates_df["p_id"] == prov_id, 'Longitude'].values[0] return(Lat, Long) def get_bearing(p1, p2):
64
64
137
11
53
mariusvileiniskisibm/optimal-patient-allocation-vis
run_app.py
Python
get_bearing
get_bearing
63
78
63
64
2d53c9aeb177829ae5b523a7077f449f6a6a1f34
bigcode/the-stack
train
cf8e3edbd8851fd679fff257
train
function
def generate_map(DO_output_map, folium_map, map_suffix): for date in DO_output_map.date.unique(): if sum(DO_output_map.loc[DO_output_map.date == date].num_patnts_trnsf.values) > 0: feature_group = folium.FeatureGroup(name='date '+str(date)) for index, row in DO_output_map.loc[DO_out...
def generate_map(DO_output_map, folium_map, map_suffix):
for date in DO_output_map.date.unique(): if sum(DO_output_map.loc[DO_output_map.date == date].num_patnts_trnsf.values) > 0: feature_group = folium.FeatureGroup(name='date '+str(date)) for index, row in DO_output_map.loc[DO_output_map.date == date].iterrows(): folium....
On IBM Cloud Cloud Foundry, get the port number from the environment variable PORT # When running this app on the local machine, default the port to 8000 port = int(os.getenv('PORT', 8000)) def style_function(feature): return {'fillOpacity': 0,'weight': 0.9,'color': 'black','fillColor': 'white'} def generate_map(...
94
95
319
15
79
mariusvileiniskisibm/optimal-patient-allocation-vis
run_app.py
Python
generate_map
generate_map
154
179
154
155
18918bb078972b030acd6d3d0ea0a0e929517f93
bigcode/the-stack
train
098b8d5edf91415c3ecbad9c
train
function
def style_function(feature): return {'fillOpacity': 0,'weight': 0.9,'color': 'black','fillColor': 'white'}
def style_function(feature):
return {'fillOpacity': 0,'weight': 0.9,'color': 'black','fillColor': 'white'}
(signature_version='oauth'), # endpoint_url="") # On IBM Cloud Cloud Foundry, get the port number from the environment variable PORT # When running this app on the local machine, default the port to 8000 port = int(os.getenv('PORT', 8000)) def style_function(feature):
64
64
32
5
59
mariusvileiniskisibm/optimal-patient-allocation-vis
run_app.py
Python
style_function
style_function
149
150
149
149
338687a255b7fb58bd82b357f9eadff99bea6324
bigcode/the-stack
train
0707fc99334fbfba023bb606
train
function
@app.route('/map') def show_map(map_label=None): map_label = request.args.get('scenario_id', '') return render_template('Belgium_DO_'+map_label+'.html')
@app.route('/map') def show_map(map_label=None):
map_label = request.args.get('scenario_id', '') return render_template('Belgium_DO_'+map_label+'.html')
_2_map_DF, folium_map_scenario_2, 'scenario_2') generate_map(scenario_3_map_DF, folium_map_scenario_3, 'scenario_3') return render_template('index.html') @app.route('/map') def show_map(map_label=None):
64
64
38
12
52
mariusvileiniskisibm/optimal-patient-allocation-vis
run_app.py
Python
show_map
show_map
228
231
228
229
defa23561b0b072c66607a382d033a5e3740a13d
bigcode/the-stack
train
5cb2be0820f49881af2bb814
train
function
def get_coordinates(prov_id): coordinates_df = pd.read_csv('province_coordinates.csv') dict_map = {p:province_map.get_id(p) for p in list(coordinates_df['Province Name'])} coordinates_df["p_id"] = coordinates_df["Province Name"].map(dict_map) Lat = coordinates_df.loc[coordinates_df["p_id"] == ...
def get_coordinates(prov_id):
coordinates_df = pd.read_csv('province_coordinates.csv') dict_map = {p:province_map.get_id(p) for p in list(coordinates_df['Province Name'])} coordinates_df["p_id"] = coordinates_df["Province Name"].map(dict_map) Lat = coordinates_df.loc[coordinates_df["p_id"] == prov_id, 'Latitude'].values[0]...
), province_map.get_id(rounded_coord_dict[rounded_destinations[y]])): jsonRes['durations'][x][y] for x, y in list(it.product(range(len(rounded_destinations)), range(len(rounded_destinations))))} return routes_dur def get_coordinates(prov_id):
64
64
119
7
56
mariusvileiniskisibm/optimal-patient-allocation-vis
run_app.py
Python
get_coordinates
get_coordinates
53
61
53
53
dca9b26ad3e27e66259f80d3ba6d1e6bf016cfa4
bigcode/the-stack
train
b4c6b155c7cb00e88eb543cf
train
function
def get_arrows(locations, color='blue', size=6, n_arrows=1): Point = namedtuple('Point', field_names=['lat', 'lon']) p1 = Point(locations[0][0], locations[0][1]) p2 = Point(locations[1][0], locations[1][1]) rotation = get_bearing(p1, p2) - 90 arrow_lats = np.linspace(p1.lat, p2.l...
def get_arrows(locations, color='blue', size=6, n_arrows=1):
Point = namedtuple('Point', field_names=['lat', 'lon']) p1 = Point(locations[0][0], locations[0][1]) p2 = Point(locations[1][0], locations[1][1]) rotation = get_bearing(p1, p2) - 90 arrow_lats = np.linspace(p1.lat, p2.lat, n_arrows + 2)[1:n_arrows+1] arrow_lons = np.linspace(p1.lo...
* np.cos(long_diff))) bearing = np.degrees(np.arctan2(x, y)) if bearing < 0: return bearing + 360 return bearing def get_arrows(locations, color='blue', size=6, n_arrows=1):
64
64
193
22
41
mariusvileiniskisibm/optimal-patient-allocation-vis
run_app.py
Python
get_arrows
get_arrows
80
98
80
81
865b7dea70afbf41f60fa03e3ee3b31a15718717
bigcode/the-stack
train
7f103fd1f7a6722f951190e0
train
class
class ProvinceMap: def __init__(self, province_mapping): self._mp = pd.read_csv('province_id_mapping.csv') def get_id(self, province): return self._mp.loc[self._mp.province_nl.str.contains(province) | self._mp.province_en.str.contains(province), "id"].values[0] def get_prov(sel...
class ProvinceMap:
def __init__(self, province_mapping): self._mp = pd.read_csv('province_id_mapping.csv') def get_id(self, province): return self._mp.loc[self._mp.province_nl.str.contains(province) | self._mp.province_en.str.contains(province), "id"].values[0] def get_prov(self, p_id): r...
, render_template, request, jsonify, url_for import atexit import os import json import folium from botocore.client import Config import ibm_boto3 import pandas as pd import ast from collections import namedtuple import numpy as np class ProvinceMap:
64
64
126
4
59
mariusvileiniskisibm/optimal-patient-allocation-vis
run_app.py
Python
ProvinceMap
ProvinceMap
13
25
13
13
61a87c4fd5c511119948e7a3cb26e653c4f8e85d
bigcode/the-stack
train
95d95f70c642556e04ff956e
train
class
class Eltwise(Op): op = 'Eltwise' def __init__(self, graph: Graph, attrs: dict): operations = { 'sum': ('Add', lambda a, b: a + b), 'mul': ('Mul', lambda a, b: a * b), 'max': ('Max', lambda a, b: np.ma.maximum(a, b)), 'pow': ('Pow', lambda a, b: np.ma.pow...
class Eltwise(Op):
op = 'Eltwise' def __init__(self, graph: Graph, attrs: dict): operations = { 'sum': ('Add', lambda a, b: a + b), 'mul': ('Mul', lambda a, b: a * b), 'max': ('Max', lambda a, b: np.ma.maximum(a, b)), 'pow': ('Pow', lambda a, b: np.ma.power(a, b)), ...
# Copyright (C) 2018-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import numpy as np from openvino.tools.mo.front.common.partial_infer.eltwise import eltwise_infer from openvino.tools.mo.graph.graph import Graph from openvino.tools.mo.ops.op import Op class Eltwise(Op):
75
123
411
6
68
pazamelin/openvino
tools/mo/openvino/tools/mo/ops/eltwise.py
Python
Eltwise
Eltwise
11
42
11
11
82ad29fcb15eae38bc80e13526de7cbd9da5c8b7
bigcode/the-stack
train
99f5f148731f3af3e5a0a741
train
class
class LenValidator(_plotly_utils.basevalidators.NumberValidator): def __init__(self, plotly_name="len", parent_name="contour.colorbar", **kwargs): super(LenValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colo...
class LenValidator(_plotly_utils.basevalidators.NumberValidator):
def __init__(self, plotly_name="len", parent_name="contour.colorbar", **kwargs): super(LenValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "colorbars"), min=kwargs.pop("min", 0), role=kw...
import _plotly_utils.basevalidators class LenValidator(_plotly_utils.basevalidators.NumberValidator):
20
64
104
12
7
acrucetta/Chicago_COVI_WebApp
env/lib/python3.8/site-packages/plotly/validators/contour/colorbar/_len.py
Python
LenValidator
LenValidator
4
13
4
4
d5f83cf55b4d76a857599ead2abec2654abd9d39
bigcode/the-stack
train
33722b615adc7ca83b0648af
train
class
class TracingTestSampling(AmbassadorTest): """ Test for the "sampling" in TracingServices """ def init(self): self.target = HTTP() def manifests(self) -> str: return """ --- apiVersion: v1 kind: Service metadata: name: zipkin-65 spec: selector: app: zipkin-65 ports: - p...
class TracingTestSampling(AmbassadorTest):
""" Test for the "sampling" in TracingServices """ def init(self): self.target = HTTP() def manifests(self) -> str: return """ --- apiVersion: v1 kind: Service metadata: name: zipkin-65 spec: selector: app: zipkin-65 ports: - port: 9411 name: http targetPort: ht...
= self.results[0].backend.request.headers assert self.results[0].status == 200 assert self.results[0].headers["Server"] == ["envoy"] assert extauth_res["request"]["headers"]["x-b3-parentspanid"] == request_headers["x-b3-parentspanid"] assert extauth_res["request"]["headers"]["x-b3-samp...
185
186
622
10
175
blhagadorn/ambassador
python/tests/t_tracing.py
Python
TracingTestSampling
TracingTestSampling
415
512
415
415
927ed847ea609fc2c39e2c32fe5811be5e3e5ca1
bigcode/the-stack
train
1fb3fa9593a9e5c6db9db29a
train
class
class TracingExternalAuthTest(AmbassadorTest): def init(self): self.target = HTTP() self.auth = AHTTP(name="auth") def manifests(self) -> str: return """ --- apiVersion: v1 kind: Service metadata: name: zipkin-auth spec: selector: app: zipkin-auth ports: - port: 9411 na...
class TracingExternalAuthTest(AmbassadorTest):
def init(self): self.target = HTTP() self.auth = AHTTP(name="auth") def manifests(self) -> str: return """ --- apiVersion: v1 kind: Service metadata: name: zipkin-auth spec: selector: app: zipkin-auth ports: - port: 9411 name: http targetPort: http type: NodePort -...
from super().requirements() yield ("url", Query("http://zipkin-64:9411/api/v2/services")) def queries(self): # Speak through each Ambassador to the traced service... yield Query(self.url("target-64/"), phase=1) # ...then ask the Zipkin for services and spans. Including debug=True ...
192
192
642
11
181
blhagadorn/ambassador
python/tests/t_tracing.py
Python
TracingExternalAuthTest
TracingExternalAuthTest
318
412
318
319
f40425dc1d486bd669b2cf4cfadb2d1dd82c2d2b
bigcode/the-stack
train
148d2d0f09d672aa0f238c1f
train
class
class TracingTestLongClusterName(AmbassadorTest): def init(self): self.target = HTTP() def manifests(self) -> str: return """ --- apiVersion: v1 kind: Service metadata: name: zipkinservicenamewithoversixtycharacterstoforcenamecompression spec: selector: app: zipkin-longclustername por...
class TracingTestLongClusterName(AmbassadorTest):
def init(self): self.target = HTTP() def manifests(self) -> str: return """ --- apiVersion: v1 kind: Service metadata: name: zipkinservicenamewithoversixtycharacterstoforcenamecompression spec: selector: app: zipkin-longclustername ports: - port: 9411 name: http targetPort: ...
Name=tracingtest-default", phase=2) yield Query("http://zipkin:9411/api/v2/traces?serviceName=tracingtest-default", phase=2) def check(self): for i in range(100): assert self.results[i].backend.name == self.target.path.k8s assert self.results[100].backend.name == "raw" ...
256
256
866
12
243
blhagadorn/ambassador
python/tests/t_tracing.py
Python
TracingTestLongClusterName
TracingTestLongClusterName
119
227
119
119
3b0d13c27756a5d5aef98427634d08be5b5f61e3
bigcode/the-stack
train
53f4c65046071651dd22094a
train
class
class TracingTestZipkinV1(AmbassadorTest): """ Test for the "collector_endpoint_version" Zipkin config in TracingServices """ def init(self): self.target = HTTP() def manifests(self) -> str: return """ --- apiVersion: v1 kind: Service metadata: name: zipkin-v1 spec: selector: ...
class TracingTestZipkinV1(AmbassadorTest):
""" Test for the "collector_endpoint_version" Zipkin config in TracingServices """ def init(self): self.target = HTTP() def manifests(self) -> str: return """ --- apiVersion: v1 kind: Service metadata: name: zipkin-v1 spec: selector: app: zipkin-v1 ports: - port: 9411 ...
=tracingtestzipkinv2-default", phase=2) def check(self): for i in range(100): assert self.results[i].backend.name == self.target.path.k8s assert self.results[100].backend.name == "raw" assert len(self.results[100].backend.response) == 1 assert self.results[100].backend....
239
239
799
13
225
blhagadorn/ambassador
python/tests/t_tracing.py
Python
TracingTestZipkinV1
TracingTestZipkinV1
627
739
627
627
5b070694bd16c55e0ea16c2bbd04a43ced1881d4
bigcode/the-stack
train
722929ed962794a94f5f7ac5
train
class
class TracingTest(AmbassadorTest): def init(self): self.target = HTTP() def manifests(self) -> str: return """ --- apiVersion: v1 kind: Service metadata: name: zipkin spec: selector: app: zipkin ports: - port: 9411 name: http targetPort: http type: NodePort --- apiVersion:...
class TracingTest(AmbassadorTest):
def init(self): self.target = HTTP() def manifests(self) -> str: return """ --- apiVersion: v1 kind: Service metadata: name: zipkin spec: selector: app: zipkin ports: - port: 9411 name: http targetPort: http type: NodePort --- apiVersion: apps/v1 kind: Deployment metadata:...
import json import pytest from typing import ClassVar, Dict, List, Sequence, Tuple, Union from kat.harness import sanitize, variants, Query, Runner from abstract_tests import AmbassadorTest, HTTP, AHTTP from abstract_tests import MappingTest, OptionTest, ServiceType, Node, Test class TracingTest(AmbassadorTest):
73
211
706
9
63
blhagadorn/ambassador
python/tests/t_tracing.py
Python
TracingTest
TracingTest
12
116
12
12
e8e0454ad14ef85bc73ba34373b8207e4e649f49
bigcode/the-stack
train
844026d0184802cb4a14670f
train
class
class TracingTestZipkinV2(AmbassadorTest): """ Test for the "collector_endpoint_version" Zipkin config in TracingServices """ def init(self): self.target = HTTP() def manifests(self) -> str: return """ --- apiVersion: v1 kind: Service metadata: name: zipkin-v2 spec: selector: ...
class TracingTestZipkinV2(AmbassadorTest):
""" Test for the "collector_endpoint_version" Zipkin config in TracingServices """ def init(self): self.target = HTTP() def manifests(self) -> str: return """ --- apiVersion: v1 kind: Service metadata: name: zipkin-v2 spec: selector: app: zipkin-v2 ports: - port: 9411 ...
-65:9411/api/v2/services")) def queries(self): # Speak through each Ambassador to the traced service... for i in range(0, 100): yield Query(self.url("target-65/"), phase=1, ignore_result=True) # ...then ask the Zipkin for services and spans. Including debug=True in these querie...
239
239
797
13
225
blhagadorn/ambassador
python/tests/t_tracing.py
Python
TracingTestZipkinV2
TracingTestZipkinV2
514
625
514
514
8a7ef0cb8820a8f973ed5bfe8a41b035ef50b050
bigcode/the-stack
train
e8c9a76fb1554b8f91298ccb
train
class
class TracingTestShortTraceId(AmbassadorTest): def init(self): self.target = HTTP() def manifests(self) -> str: return """ --- apiVersion: v1 kind: Service metadata: name: zipkin-64 spec: selector: app: zipkin-64 ports: - port: 9411 name: http targetPort: http type: NodePo...
class TracingTestShortTraceId(AmbassadorTest):
def init(self): self.target = HTTP() def manifests(self) -> str: return """ --- apiVersion: v1 kind: Service metadata: name: zipkin-64 spec: selector: app: zipkin-64 ports: - port: 9411 name: http targetPort: http type: NodePort --- apiVersion: apps/v1 kind: Deployment met...
.response[0] == 'tracingtestlongclustername-default' assert self.results[101].backend.name == "raw" tracelist = { x: True for x in self.results[101].backend.response } assert 'router cluster_tracingtestlongclustername_http_default egress' in tracelist # Look for the host that we actu...
157
157
524
12
144
blhagadorn/ambassador
python/tests/t_tracing.py
Python
TracingTestShortTraceId
TracingTestShortTraceId
229
314
229
229
60a0fd22ea62d3a5184734bef15b02fd7eeb8cf6
bigcode/the-stack
train
a23ce737d3650a26ab6e700d
train
class
class BookCrudViewset(PopupCrudViewSet): model = Book form_class = BookForm list_display = ('title', 'author') list_url = reverse_lazy("books:list") new_url = reverse_lazy("books:create") related_object_popups = { 'author': reverse_lazy("new-author") } legacy_crud = True item...
class BookCrudViewset(PopupCrudViewSet):
model = Book form_class = BookForm list_display = ('title', 'author') list_url = reverse_lazy("books:list") new_url = reverse_lazy("books:create") related_object_popups = { 'author': reverse_lazy("new-author") } legacy_crud = True item_actions = [ ('Up', 'glyphicon gl...
author = self.fields['author'] author.widget = RelatedFieldPopupFormWidget( widget=Select2Widget(choices=author.choices) if _select2 else \ forms.Select(choices=author.choices), new_url=reverse_lazy("new-author")) class BookCrudViewset(PopupCrudViewSet):
68
69
230
11
57
targetsmart-devops/django-popupcrud
test/views.py
Python
BookCrudViewset
BookCrudViewset
72
103
72
72
37db91add50258a726e3115f3e37cc1b5854bb1a
bigcode/the-stack
train
5b5a6fa08cde38c6f1da3083
train
class
class AuthorCrudViewset(PopupCrudViewSet): model = Author fields = ('name', 'age') list_display = ('name', 'age', 'half_age', 'double_age') list_url = reverse_lazy("authors") new_url = reverse_lazy("new-author") page_title = "Author List" """ form_class = AuthorForm list_permission_...
class AuthorCrudViewset(PopupCrudViewSet):
model = Author fields = ('name', 'age') list_display = ('name', 'age', 'half_age', 'double_age') list_url = reverse_lazy("authors") new_url = reverse_lazy("new-author") page_title = "Author List" """ form_class = AuthorForm list_permission_required = ('tests.add_author',) create...
from .models import Author, Book # Create your views here. class AuthorForm(forms.ModelForm): sex = forms.ChoiceField(label="Sex", choices=(('M', 'Male'), ('F', 'Female'))) class Meta: model = Author fields = ('name', 'age') class AuthorCrudViewset(PopupCrudViewSet):
75
75
251
11
64
targetsmart-devops/django-popupcrud
test/views.py
Python
AuthorCrudViewset
AuthorCrudViewset
24
55
24
24
3e8281fc42c2eb5c17a33da1008d1878cc16a523
bigcode/the-stack
train
c77849cd44ad462fe7c1c84b
train
class
class BookForm(forms.ModelForm): class Meta: model = Book fields = ('title', 'author') def __init__(self, *args, **kwargs): super(BookForm, self).__init__(*args, **kwargs) author = self.fields['author'] author.widget = RelatedFieldPopupFormWidget( widget=Sele...
class BookForm(forms.ModelForm):
class Meta: model = Book fields = ('title', 'author') def __init__(self, *args, **kwargs): super(BookForm, self).__init__(*args, **kwargs) author = self.fields['author'] author.widget = RelatedFieldPopupFormWidget( widget=Select2Widget(choices=author.choices)...
.pk = obj.pk or 1 return reverse("edit-author", kwargs={'pk': obj.pk}) def get_delete_url(self, obj): if obj.age < 18: return None return reverse("delete-author", kwargs={'pk': obj.pk}) class BookForm(forms.ModelForm):
64
64
109
7
57
targetsmart-devops/django-popupcrud
test/views.py
Python
BookForm
BookForm
58
69
58
58
674c8d5e05a0c6ad76b4ac806e0bd7e9aa2c7285
bigcode/the-stack
train
c5c57f7cd15628cc7199d44c
train
class
class AuthorForm(forms.ModelForm): sex = forms.ChoiceField(label="Sex", choices=(('M', 'Male'), ('F', 'Female'))) class Meta: model = Author fields = ('name', 'age')
class AuthorForm(forms.ModelForm):
sex = forms.ChoiceField(label="Sex", choices=(('M', 'Male'), ('F', 'Female'))) class Meta: model = Author fields = ('name', 'age')
Select2Widget _select2 = True except ImportError: _select2 = False from popupcrud.widgets import RelatedFieldPopupFormWidget from popupcrud.views import PopupCrudViewSet from .models import Author, Book # Create your views here. class AuthorForm(forms.ModelForm):
64
64
50
7
57
targetsmart-devops/django-popupcrud
test/views.py
Python
AuthorForm
AuthorForm
17
21
17
17
9baeeb0a0045d14b69f4786b6fdd932ba88d2a4d
bigcode/the-stack
train
172e3713be6e7b78b448f93b
train
class
class BookUUIDCrudViewSet(PopupCrudViewSet): '''CRUD views using slug field as url kwarg instead of the default pk''' model = Book form_class = BookForm list_display = ('title', 'author') list_url = reverse_lazy("uuidbooks:list") new_url = reverse_lazy("uuidbooks:create") pk_url_kwarg = Non...
class BookUUIDCrudViewSet(PopupCrudViewSet):
'''CRUD views using slug field as url kwarg instead of the default pk''' model = Book form_class = BookForm list_display = ('title', 'author') list_url = reverse_lazy("uuidbooks:list") new_url = reverse_lazy("uuidbooks:create") pk_url_kwarg = None slug_field = 'uuid' slug_url_kwarg ...
reverse_lazy("books:detail", kwargs={'pk': obj.pk}) def up_vote(self, request, book): return True, "Up vote successful" def down_vote(self, request, book): return True, "Down vote successful" class BookUUIDCrudViewSet(PopupCrudViewSet):
64
64
180
12
52
targetsmart-devops/django-popupcrud
test/views.py
Python
BookUUIDCrudViewSet
BookUUIDCrudViewSet
106
128
106
106
4ce20461ef32043865af0a40bf77cc94467c7767
bigcode/the-stack
train
f033e4db4fb922bfc4d6319c
train
function
def save_segmentation_nifti_from_softmax( segmentation_softmax: Union[str, np.ndarray], out_fname: str, properties_dict: dict, order: int = 1, region_class_order: Tuple[Tuple[int]] = None, seg_postprogess_fn: callable = None, seg_postprocess_args: tuple = None, resampled_npz_fname: str =...
def save_segmentation_nifti_from_softmax( segmentation_softmax: Union[str, np.ndarray], out_fname: str, properties_dict: dict, order: int = 1, region_class_order: Tuple[Tuple[int]] = None, seg_postprogess_fn: callable = None, seg_postprocess_args: tuple = None, resampled_npz_fname: str =...
""" This is a utility for writing segmentations to nifty and npz. It requires the data to have been preprocessed by GenericPreprocessor because it depends on the property dictionary output (dct) to know the geometry of the original data. segmentation_softmax does not have to have the same size in pixels...
distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys from copy import deepcopy from typing import Union...
256
256
1,778
125
131
gasperpodobnik/nnUNet
nnunet/inference/segmentation_export.py
Python
save_segmentation_nifti_from_softmax
save_segmentation_nifti_from_softmax
31
200
31
44
a9344ea4525769ce93ebe59e8ce849a0cdd57a40
bigcode/the-stack
train
c6d260146ae4e1f523b6894e
train
function
def save_segmentation_nifti(segmentation, out_fname, dct, order=1, force_separate_z=None, order_z=0, verbose: bool = False): """ faster and uses less ram than save_segmentation_nifti_from_softmax, but maybe less precise and also does not support softmax export (which is needed for ensembling). So it's a nic...
def save_segmentation_nifti(segmentation, out_fname, dct, order=1, force_separate_z=None, order_z=0, verbose: bool = False):
""" faster and uses less ram than save_segmentation_nifti_from_softmax, but maybe less precise and also does not support softmax export (which is needed for ensembling). So it's a niche function that may be useful in some cases. :param segmentation: :param out_fname: :param dct: :param order...
np.copy(seg_old_size), *seg_postprocess_args ) else: seg_old_size_postprocessed = seg_old_size seg_resized_itk = sitk.GetImageFromArray( seg_old_size_postprocessed.astype(np.uint8) ) seg_resized_itk.SetSpacing(properties_dict["itk_spacing"]) seg_resized_itk.SetOr...
256
256
858
37
219
gasperpodobnik/nnUNet
nnunet/inference/segmentation_export.py
Python
save_segmentation_nifti
save_segmentation_nifti
203
295
203
203
7f0a90b119cf096d240feff2efee1fdc22bcbb91
bigcode/the-stack
train
26b8199ff2e4157612e9c37d
train
class
class DataGenerator(object): def __init__(self, batch_size, is_sparse=False): self.batch_size = batch_size self.is_sparse = is_sparse def fit(self, inputs, targets=None): self.start = 0 self.inputs = inputs self.targets = targets if isinstance(self.inputs, tuple...
class DataGenerator(object):
def __init__(self, batch_size, is_sparse=False): self.batch_size = batch_size self.is_sparse = is_sparse def fit(self, inputs, targets=None): self.start = 0 self.inputs = inputs self.targets = targets if isinstance(self.inputs, tuple) or isinstance(self.inputs, l...
() info = list() seq = '' inf = '' with open(filename, 'r') as f: for line in f: line = line.strip() if line.startswith('>'): if seq != '': seqs.append(seq) info.append(inf) seq = '' ...
104
104
347
5
98
InesGP/deepgoplus
deepgoplus/utils.py
Python
DataGenerator
DataGenerator
203
252
203
204
5f7a3af569e0b0fbf4c8ac2668e30f3485566869
bigcode/the-stack
train
92d913475bcdf4dc20bda63e
train
function
def is_exp_code(code): return code in EXP_CODES
def is_exp_code(code):
return code in EXP_CODES
', '9823', '10090', '10116', '44689', '83333', '99287', '226900', '243273', '284812', '559292']) def is_cafa_target(org): return org in CAFA_TARGETS def is_exp_code(code):
64
64
13
6
57
InesGP/deepgoplus
deepgoplus/utils.py
Python
is_exp_code
is_exp_code
34
35
34
34
124e10aa2de15e16456cab88b919bef1ed7e55b6
bigcode/the-stack
train
04b105fe345cdbee4cbb44f8
train
function
def read_fasta(filename): seqs = list() info = list() seq = '' inf = '' with open(filename, 'r') as f: for line in f: line = line.strip() if line.startswith('>'): if seq != '': seqs.append(seq) info.append(inf) ...
def read_fasta(filename):
seqs = list() info = list() seq = '' inf = '' with open(filename, 'r') as f: for line in f: line = line.strip() if line.startswith('>'): if seq != '': seqs.append(seq) info.append(inf) seq = '...
) while len(q) > 0: t_id = q.popleft() if t_id not in term_set: term_set.add(t_id) for ch_id in self.ont[t_id]['children']: q.append(ch_id) return term_set def read_fasta(filename):
64
64
110
6
57
InesGP/deepgoplus
deepgoplus/utils.py
Python
read_fasta
read_fasta
182
200
182
182
e81b02daee220cc51e867532c57053691dbc5ded
bigcode/the-stack
train
7372fa4d219514127e628e7d
train
function
def is_cafa_target(org): return org in CAFA_TARGETS
def is_cafa_target(org):
return org in CAFA_TARGETS
'6239', '7227', '7955', '9606', '9823', '10090', '10116', '44689', '83333', '99287', '226900', '243273', '284812', '559292']) def is_cafa_target(org):
64
64
16
7
57
InesGP/deepgoplus
deepgoplus/utils.py
Python
is_cafa_target
is_cafa_target
31
32
31
31
0ab2cdedd138e2b189130f0720825beaca46e685
bigcode/the-stack
train
d4a57a821090d3c55c3d678d
train
class
class Ontology(object): def __init__(self, filename='data/go.obo', with_rels=False): self.ont = self.load(filename, with_rels) self.ic = None def has_term(self, term_id): return term_id in self.ont def get_term(self, term_id): if self.has_term(term_id): return ...
class Ontology(object):
def __init__(self, filename='data/go.obo', with_rels=False): self.ont = self.load(filename, with_rels) self.ic = None def has_term(self, term_id): return term_id in self.ont def get_term(self, term_id): if self.has_term(term_id): return self.ont[term_id] ...
ULAR_FUNCTION = 'GO:0003674' CELLULAR_COMPONENT = 'GO:0005575' FUNC_DICT = { 'cc': CELLULAR_COMPONENT, 'mf': MOLECULAR_FUNCTION, 'bp': BIOLOGICAL_PROCESS} NAMESPACES = { 'cc': 'cellular_component', 'mf': 'molecular_function', 'bp': 'biological_process' } EXP_CODES = set([ 'EXP', 'IDA', 'IP...
256
256
1,091
5
250
InesGP/deepgoplus
deepgoplus/utils.py
Python
Ontology
Ontology
38
180
38
39
b2c06f5e478a12e607b2d1792d1f838aa18b4259
bigcode/the-stack
train
6046f7405025a18762639e33
train
class
class OrganizationEventsDistributionEndpoint(OrganizationEventsEndpointBase): def get(self, request, organization): try: params = self.get_filter_params(request, organization) snuba_args = self.get_snuba_query_args(request, organization, params) except OrganizationEventsError...
class OrganizationEventsDistributionEndpoint(OrganizationEventsEndpointBase):
def get(self, request, organization): try: params = self.get_filter_params(request, organization) snuba_args = self.get_snuba_query_args(request, organization, params) except OrganizationEventsError as exc: return Response({'detail': exc.message}, status=400) ...
from __future__ import absolute_import import six from rest_framework.response import Response from sentry.api.bases import OrganizationEventsEndpointBase, OrganizationEventsError, NoProjects from sentry.utils.snuba import get_snuba_column_name, raw_query from sentry import features, tagstore from sentry.tagstore.bas...
121
176
588
11
110
xiaotian45123/sentry
src/sentry/api/endpoints/organization_events_distribution.py
Python
OrganizationEventsDistributionEndpoint
OrganizationEventsDistributionEndpoint
17
100
17
17
3369ab78b1e86f600e0f055c6051e119bca0e97f
bigcode/the-stack
train
fde47ecfde85decb386c3ad2
train
function
def write_to_csv(filename,dict_array): myFile = open(filename, "w") with myFile: fieldnames = ['name', 'job description','location'] writer = csv.DictWriter(myFile, fieldnames=fieldnames) writer.writeheader() for row in dict_array: writer.writerow(row)
def write_to_csv(filename,dict_array):
myFile = open(filename, "w") with myFile: fieldnames = ['name', 'job description','location'] writer = csv.DictWriter(myFile, fieldnames=fieldnames) writer.writeheader() for row in dict_array: writer.writerow(row)
csv from getpass import getpass from selenium import webdriver from time import sleep from random import randrange from selenium.webdriver.common.keys import Keys from parsel import Selector ''' --------------------------------------------------------- This function writes to csv excel file ----------------...
64
64
69
9
55
tal95shah/LinkedIn_Scraper
linkedin_scraper.py
Python
write_to_csv
write_to_csv
13
20
13
13
aa00220feaec614e3deaa6e93f6aff6dc3e7a0b9
bigcode/the-stack
train
7fee23406c55d813b5c54c64
train
function
def validate_field(field): if field: pass else: field = '' return field
def validate_field(field):
if field: pass else: field = '' return field
: fieldnames = ['name', 'job description','location'] writer = csv.DictWriter(myFile, fieldnames=fieldnames) writer.writeheader() for row in dict_array: writer.writerow(row) ''' --------------------------------------------------------- This function validates field ...
64
64
23
5
59
tal95shah/LinkedIn_Scraper
linkedin_scraper.py
Python
validate_field
validate_field
26
31
26
26
8ae5a18cec72f6dfe865bcfa627b2d96dfbbb501
bigcode/the-stack
train
6a7ec5c66ce27ae1bfb12c5d
train
function
def validate_button(button): if button is None: return -1 else: return button
def validate_button(button):
if button is None: return -1 else: return button
fieldnames=fieldnames) writer.writeheader() for row in dict_array: writer.writerow(row) ''' --------------------------------------------------------- This function validates field --------------------------------------------------------- ''' def validate_field(field): if fiel...
64
64
23
5
58
tal95shah/LinkedIn_Scraper
linkedin_scraper.py
Python
validate_button
validate_button
32
36
32
32
d10670bb7fc45ae3304bf7be7cef2a1820248760
bigcode/the-stack
train
a4ba1acd4a1f63523bbbd931
train
class
class ImageSet(Data): def __init__(self, values, label=None, mode='local'): super(ImageSet, self).__init__(values, labels=None, mode='local') if values is not None: self.images = values def max(self): pass def tospark(self): pass def mean(self): pas...
class ImageSet(Data):
def __init__(self, values, label=None, mode='local'): super(ImageSet, self).__init__(values, labels=None, mode='local') if values is not None: self.images = values def max(self): pass def tospark(self): pass def mean(self): pass def baseaxes(se...
list(blocks.blockshape) dims[0] = value_size else: dims = None def f(block): return apply_along_axis(func, 0, block) return blocks.map(f, value_shape=dims, dtype=dtype).toimage() class ImageSet(Data):
64
64
156
5
59
alexandonian/lightning
lightning/image/image.py
Python
ImageSet
ImageSet
562
602
562
562
7e5f667cdd427cca5f96c4b58cd410b65bf14890
bigcode/the-stack
train
6a4ac0740ea3b89d00ccad59
train
class
class Image(Data): """ An image or volume. Backed by an array-like object, including a numpy array (for local computation) or a bolt array (for spark computation). Attributes ---------- values : array-like numpy array or bolt array labels : array-like or list A set of...
class Image(Data):
""" An image or volume. Backed by an array-like object, including a numpy array (for local computation) or a bolt array (for spark computation). Attributes ---------- values : array-like numpy array or bolt array labels : array-like or list A set of labels, one per ch...
import logging from numpy import ndarray, arange, amax, amin, size, asarray, random, prod, \ apply_along_axis from skimage.util import shape from itertools import product from ..base import Data class Image(Data):
54
256
3,971
4
49
alexandonian/lightning
lightning/image/image.py
Python
Image
Image
10
559
10
10
e36d10889dc47db407d8063427e520bc12280810
bigcode/the-stack
train
9ca189861a69eacffceb1a1f
train
class
class TestCoordMap(unittest.TestCase): @classmethod def setUpClass(self): super(TestCoordMap, self).setUpClass() caffe.set_device(0) print('TestCoordMap.setUpClass') @classmethod def tearDownClass(self): super(TestCoordMap, self).tearDownClass() print('TestCoordM...
class TestCoordMap(unittest.TestCase): @classmethod
def setUpClass(self): super(TestCoordMap, self).setUpClass() caffe.set_device(0) print('TestCoordMap.setUpClass') @classmethod def tearDownClass(self): super(TestCoordMap, self).tearDownClass() print('TestCoordMap.tearDownClass') def setUp(self): pass ...
, stride=1, pad=0, pool=2, dstride=2, dpad=0): """ Define net spec for simple conv-pool-deconv pattern common to all coordinate mapping tests. """ n = caffe.NetSpec() n.data = L.Input(shape=dict(dim=[2, 1, 100, 100])) n.aux = L.Input(shape=dict(dim=[2, 1, 20, 20])) n.conv = L.Convolution...
256
256
1,773
12
243
Amanda-Barbara/nvcaffe
python/caffe/test/test_coord_map.py
Python
TestCoordMap
TestCoordMap
34
203
34
35
77b05f1d007245a4205c85a5965938ce8fc2ef33
bigcode/the-stack
train
55c2c6004a7ad7232f300ab4
train
function
def coord_net_spec(ks=3, stride=1, pad=0, pool=2, dstride=2, dpad=0): """ Define net spec for simple conv-pool-deconv pattern common to all coordinate mapping tests. """ n = caffe.NetSpec() n.data = L.Input(shape=dict(dim=[2, 1, 100, 100])) n.aux = L.Input(shape=dict(dim=[2, 1, 20, 20])) ...
def coord_net_spec(ks=3, stride=1, pad=0, pool=2, dstride=2, dpad=0):
""" Define net spec for simple conv-pool-deconv pattern common to all coordinate mapping tests. """ n = caffe.NetSpec() n.data = L.Input(shape=dict(dim=[2, 1, 100, 100])) n.aux = L.Input(shape=dict(dim=[2, 1, 20, 20])) n.conv = L.Convolution( n.data, num_output=10, kernel_size=ks...
import unittest import numpy as np import random import caffe from caffe import layers as L from caffe import params as P from caffe.coord_map import coord_map_from_to, crop def coord_net_spec(ks=3, stride=1, pad=0, pool=2, dstride=2, dpad=0):
71
75
252
31
39
Amanda-Barbara/nvcaffe
python/caffe/test/test_coord_map.py
Python
coord_net_spec
coord_net_spec
12
31
12
12
f3fa67de1241cea7a63de49a3b965bfae24355c0
bigcode/the-stack
train
f69915d3b63037f07aa9e03d
train
function
def getParser(): "Creates and returns the argparse parser object." parser = argparse.ArgumentParser(description=__description__) parser.add_argument('input', help='Source volume (usually a gradient image).') parser.add_argument('output', help='Target volume.') parser.add_argument('--mindist', type=i...
def getParser():
"Creates and returns the argparse parser object." parser = argparse.ArgumentParser(description=__description__) parser.add_argument('input', help='Source volume (usually a gradient image).') parser.add_argument('output', help='Target volume.') parser.add_argument('--mindist', type=int, default=2, he...
(data_input, minima_labels, mask=mask) # save file save(data_output, args.output, header_input, args.force) logger.info('Successfully terminated.') def getArguments(parser): "Provides additional validation of the arguments collected by argparse." return parser.parse_args() def getParser():
64
64
180
4
60
FarnooshKh/JoyOfLearning
PyradiomicsExample/myenv/bin/medpy_watershed.py
Python
getParser
getParser
106
117
106
106
ff241f2848bdfb917303cc3385582a120db8425b
bigcode/the-stack
train
85cb5e3c5c20fea798d962c7
train
function
def getArguments(parser): "Provides additional validation of the arguments collected by argparse." return parser.parse_args()
def getArguments(parser):
"Provides additional validation of the arguments collected by argparse." return parser.parse_args()
) # apply the watershed logger.info('Watershedding...') data_output = watershed(data_input, minima_labels, mask=mask) # save file save(data_output, args.output, header_input, args.force) logger.info('Successfully terminated.') def getArguments(parser):
64
64
23
5
59
FarnooshKh/JoyOfLearning
PyradiomicsExample/myenv/bin/medpy_watershed.py
Python
getArguments
getArguments
102
104
102
102
737e4b103e54f772d922f78f4ebec89488f9e115
bigcode/the-stack
train
60f0585c959d6d976e69ef38
train
function
def main(): # parse cmd arguments parser = getParser() parser.parse_args() args = getArguments(parser) # prepare logger logger = Logger.getInstance() if args.debug: logger.setLevel(logging.DEBUG) elif args.verbose: logger.setLevel(logging.INFO) # check if output image exist...
def main(): # parse cmd arguments
parser = getParser() parser.parse_args() args = getArguments(parser) # prepare logger logger = Logger.getInstance() if args.debug: logger.setLevel(logging.DEBUG) elif args.verbose: logger.setLevel(logging.INFO) # check if output image exists (will also be performed before savin...
. If you require this function, please take a look at the medpy_itk_watershed.py script. Copyright (C) 2013 Oskar Maier This program comes with ABSOLUTELY NO WARRANTY; This is free software, and ...
103
103
345
9
93
FarnooshKh/JoyOfLearning
PyradiomicsExample/myenv/bin/medpy_watershed.py
Python
main
main
60
100
60
61
66dc498f54f00eaf881076d86769fc05b636865f
bigcode/the-stack
train
4487ae4526ae0c8fe1dc232f
train
class
class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UserProfile', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_...
class Migration(migrations.Migration):
dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='UserProfile', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration):
37
64
162
7
29
ank-forked/readthedocs.org
readthedocs/core/migrations/0001_initial.py
Python
Migration
Migration
8
25
8
9
f1e33d5ccfb803267f5b72ed05af1bd6c677d41a
bigcode/the-stack
train
b3fc7112ebd3fad5fbc94e4f
train
class
class Test(TestCase): def setUp(self): Article(headline="headline",content="content").save() def test(self): form = ArticleForm() article = Article.objects.get(pk=1) form = ArticleForm(instance=article) print(form)
class Test(TestCase):
def setUp(self): Article(headline="headline",content="content").save() def test(self): form = ArticleForm() article = Article.objects.get(pk=1) form = ArticleForm(instance=article) print(form)
from django.test import TestCase from .forms import ArticleForm from .models import Article class Test(TestCase):
26
64
58
5
20
looking-for-a-job/django-examples
Forms/modelforms/ModelForm/example/tests.py
Python
Test
Test
5
14
5
5
8d2501304e5b013931f499221cb841a9ef4c9dfa
bigcode/the-stack
train
3f9050478e8dd0bf105c22a9
train
class
class Account: def __init__(self, owner, balance): self.owner = owner self.balance = balance def __str__(self): print('Account owner: {}'.format(self.owner)) print('Account balance: {}'.format(self.balance))
class Account:
def __init__(self, owner, balance): self.owner = owner self.balance = balance def __str__(self): print('Account owner: {}'.format(self.owner)) print('Account balance: {}'.format(self.balance))
from os import system, name def clear(): if name == 'nt': _ = system('cls') clear() class Account:
33
64
56
4
29
EvanthiosPapadopoulos/Python3
.history/Object Oriented Programming/Bank_20200511085454.py
Python
Account
Account
7
15
7
8
26894ce7ef3a0dbe78665fc9b6f52b89e5c78536
bigcode/the-stack
train
5564e865871148d43b68bce6
train
function
def clear(): if name == 'nt': _ = system('cls')
def clear():
if name == 'nt': _ = system('cls')
from os import system, name def clear():
11
64
20
4
6
EvanthiosPapadopoulos/Python3
.history/Object Oriented Programming/Bank_20200511085454.py
Python
clear
clear
2
4
2
2
ee393694fb967f5cbae6135412ad01f5be922d98
bigcode/the-stack
train
cf2a45501a72277e2bdad1c1
train
class
class CosmosDbMongoDbApiCollectionDataset(Dataset): """The CosmosDB (MongoDB API) database dataset. All required parameters must be populated in order to send to Azure. :param additional_properties: Unmatched properties from the message are deserialized this collection :type additional_properties...
class CosmosDbMongoDbApiCollectionDataset(Dataset):
"""The CosmosDB (MongoDB API) database dataset. All required parameters must be populated in order to send to Azure. :param additional_properties: Unmatched properties from the message are deserialized this collection :type additional_properties: dict[str, object] :param description: Dataset ...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
95
208
695
11
83
tzhanl/azure-sdk-for-python
sdk/datafactory/azure-mgmt-datafactory/azure/mgmt/datafactory/models/cosmos_db_mongo_db_api_collection_dataset_py3.py
Python
CosmosDbMongoDbApiCollectionDataset
CosmosDbMongoDbApiCollectionDataset
15
73
15
15
f57b7d54e313d64a93e59757336c9b1e16d290dc
bigcode/the-stack
train
e41f327f361049d18c89a38c
train
function
@pytest.mark.parametrize('server_name,remote_path,project_name,local_path,local_ip,local_port,ssh_port', [ ('server0', '/dev/test0', 'test0', '/tmp/test0', '10.66.6.6', '32045', '2222'), ]) def test_workspace_configuration(server_name, remote_path, project_name, local_path, local_ip, local_port, ssh_port): if n...
@pytest.mark.parametrize('server_name,remote_path,project_name,local_path,local_ip,local_port,ssh_port', [ ('server0', '/dev/test0', 'test0', '/tmp/test0', '10.66.6.6', '32045', '2222'), ]) def test_workspace_configuration(server_name, remote_path, project_name, local_path, local_ip, local_port, ssh_port):
if not os.path.isdir(local_path): os.makedirs(local_path) config_IDE(server_name, remote_path, project_name, local_path, local_ip, local_port, ssh_port) assert os.path.exists(os.path.join(local_path, '.idea')) assert os.path.exists(os.path.join(local_path, '.idea', 'workspace.xml')) workspac...
@pytest.mark.parametrize('server_name,remote_path,project_name,local_path,local_ip,local_port,ssh_port', [ ('server0', '/dev/test0', 'test0', '/tmp/test0', '10.66.6.6', '32045', '2222'), ]) def test_workspace_configuration(server_name, remote_path, project_name, local_path, local_ip, local_port, ssh_port):
88
78
263
88
0
cuyu/pypeep
tests/test_pycharm_config.py
Python
test_workspace_configuration
test_workspace_configuration
9
22
9
12
c6f0f293c3564e5267f76c5628068adabec52756
bigcode/the-stack
train
89931f2288ccdd9b13c3e15b
train
class
class InvalidBlockRequestTest(FujicoinTestFramework): def set_test_params(self): self.num_nodes = 1 self.setup_clean_chain = True self.extra_args = [["-whitelist=noban@127.0.0.1"]] def run_test(self): # Add p2p connection to node0 node = self.nodes[0] # convenience refe...
class InvalidBlockRequestTest(FujicoinTestFramework):
def set_test_params(self): self.num_nodes = 1 self.setup_clean_chain = True self.extra_args = [["-whitelist=noban@127.0.0.1"]] def run_test(self): # Add p2p connection to node0 node = self.nodes[0] # convenience reference to the node node.add_p2p_connection(P2PD...
#!/usr/bin/env python3 # Copyright (c) 2015-2018 The Fujicoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test node responses to invalid blocks. In this test we connect to one node over p2p, and test block r...
196
256
1,239
12
183
fujicoin/fujicoin-0.20.0
test/functional/p2p_invalid_block.py
Python
InvalidBlockRequestTest
InvalidBlockRequestTest
21
134
21
21
7f041e8af45a5df2e573818aaa9f7ce96f268222
bigcode/the-stack
train
628610efbc6bbca36afe333b
train
function
def to_hass_config(data, config): return [sensor.core_to_hass_config(data, config[CONF_TEMPERATURE]), sensor.core_to_hass_config(data, config[CONF_PRESSURE])]
def to_hass_config(data, config):
return [sensor.core_to_hass_config(data, config[CONF_TEMPERATURE]), sensor.core_to_hass_config(data, config[CONF_PRESSURE])]
.Pmqtt_temperature, config[CONF_TEMPERATURE]) sensor.setup_sensor(ms5611.Pget_pressure_sensor(), make.Pmqtt_pressure, config[CONF_PRESSURE]) setup_component(ms5611, config) BUILD_FLAGS = '-DUSE_MS5611' def to_hass_config(data, config):
64
64
42
9
55
Bierchermuesli/esphomeyaml
esphomeyaml/components/sensor/ms5611.py
Python
to_hass_config
to_hass_config
55
57
55
55
b01d33052a47a7fe6779368ff6195d5bad1a01f5
bigcode/the-stack
train
3f0dadd8419472b2967e222b
train
function
def to_code(config): rhs = App.make_ms5611_sensor(config[CONF_TEMPERATURE][CONF_NAME], config[CONF_PRESSURE][CONF_NAME], config.get(CONF_UPDATE_INTERVAL)) make = variable(config[CONF_MAKE_ID], rhs) ms5611 = make.Pms5611 Pvariable(config[C...
def to_code(config):
rhs = App.make_ms5611_sensor(config[CONF_TEMPERATURE][CONF_NAME], config[CONF_PRESSURE][CONF_NAME], config.get(CONF_UPDATE_INTERVAL)) make = variable(config[CONF_MAKE_ID], rhs) ms5611 = make.Pms5611 Pvariable(config[CONF_ID], ms5611) ...
), })), vol.Required(CONF_PRESSURE): cv.nameable(sensor.SENSOR_SCHEMA.extend({ cv.GenerateID(): cv.declare_variable_id(MS5611PressureSensor), })), vol.Optional(CONF_UPDATE_INTERVAL): cv.update_interval, }).extend(cv.COMPONENT_SCHEMA.schema) def to_code(config):
64
64
155
5
59
Bierchermuesli/esphomeyaml
esphomeyaml/components/sensor/ms5611.py
Python
to_code
to_code
34
49
34
34
0d75b360223b49eb130fbfdff08296c523439570
bigcode/the-stack
train
c63ad0b6cfb88ce52383d0d1
train
class
class Flags(object): def __init__(self, input_file, output_file, vocab_file, do_lower_case=False, do_whole_word_mask=True, max_seq_length=512, max_predictions_per_seq=64, random_seed=12345, dupe_factor=10, masked_lm_prob=0.15, short_seq_prob=0.1): self.input_file = input_file self....
class Flags(object):
def __init__(self, input_file, output_file, vocab_file, do_lower_case=False, do_whole_word_mask=True, max_seq_length=512, max_predictions_per_seq=64, random_seed=12345, dupe_factor=10, masked_lm_prob=0.15, short_seq_prob=0.1): self.input_file = input_file self.output_file = output_f...
examples for BERT.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import random from poros.bert import tokenization import tensorflow as tf from absl import flags from absl import app class Flags(object):
64
64
187
4
59
diqiuzhuanzhuan/poros
poros/bert/create_pretraining_data.py
Python
Flags
Flags
29
43
29
30
1849f278aa1698d1fd2964e0b05f05a757bd4800
bigcode/the-stack
train
467479fa6c0b34393b2b96ba
train
function
def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng): """Truncates a pair of sequences to a maximum sequence length.""" while True: total_length = len(tokens_a) + len(tokens_b) if total_length <= max_num_tokens: break trunc_tokens = tokens_a if len(tokens_a) > len(...
def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng):
"""Truncates a pair of sequences to a maximum sequence length.""" while True: total_length = len(tokens_a) + len(tokens_b) if total_length <= max_num_tokens: break trunc_tokens = tokens_a if len(tokens_a) > len(tokens_b) else tokens_b assert len(trunc_tokens) >= 1 ...
masked_lm_labels = [] for p in masked_lms: masked_lm_positions.append(p.index) masked_lm_labels.append(p.label) return (output_tokens, masked_lm_positions, masked_lm_labels) def truncate_seq_pair(tokens_a, tokens_b, max_num_tokens, rng):
64
64
143
16
48
diqiuzhuanzhuan/poros
poros/bert/create_pretraining_data.py
Python
truncate_seq_pair
truncate_seq_pair
398
413
398
398
c258b1a3b8393aef46e87d1b2f50ed50b3303acc
bigcode/the-stack
train
9e51953be45391549e77fb4e
train
function
def create_float_feature(values): feature = tf.train.Feature(float_list=tf.train.FloatList(value=list(values))) return feature
def create_float_feature(values):
feature = tf.train.Feature(float_list=tf.train.FloatList(value=list(values))) return feature
values]))) for writer in writers: writer.close() tf.get_logger().info("Wrote %d total instances", total_written) def create_int_feature(values): feature = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values))) return feature def create_float_feature(values):
64
64
26
6
57
diqiuzhuanzhuan/poros
poros/bert/create_pretraining_data.py
Python
create_float_feature
create_float_feature
154
156
154
154
59302665f9dbf58fa03411f92ff2662cd877208b
bigcode/the-stack
train
761167772be2dca1aef93956
train
function
def create_instances_from_document( all_documents, document_index, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab_words, rng): """Creates `TrainingInstance`s for a single document.""" document = all_documents[document_index] # Account for [CLS], [SEP], [SEP] ...
def create_instances_from_document( all_documents, document_index, max_seq_length, short_seq_prob, masked_lm_prob, max_predictions_per_seq, vocab_words, rng):
"""Creates `TrainingInstance`s for a single document.""" document = all_documents[document_index] # Account for [CLS], [SEP], [SEP] max_num_tokens = max_seq_length - 3 # We *usually* want to fill up the entire sequence since we are padding # to `max_seq_length` anyways, so short sequences are ...
"next sentence prediction" task doesn't span between documents. for input_file in input_files: with tf.io.gfile.GFile(input_file, "r") as reader: while True: line = tokenization.convert_to_unicode(reader.readline()) if not line: break ...
256
256
986
37
218
diqiuzhuanzhuan/poros
poros/bert/create_pretraining_data.py
Python
create_instances_from_document
create_instances_from_document
203
315
203
205
a2fbbb038354e00cdd941a0392761205efd97b6e
bigcode/the-stack
train
ca0910aadbad184f5568766c
train
function
def create_training_instances(input_files, tokenizer, max_seq_length, dupe_factor, short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng): """Create `TrainingInstance`s from raw text.""" all_documents = [[]] # Input file format: # (1) O...
def create_training_instances(input_files, tokenizer, max_seq_length, dupe_factor, short_seq_prob, masked_lm_prob, max_predictions_per_seq, rng):
"""Create `TrainingInstance`s from raw text.""" all_documents = [[]] # Input file format: # (1) One sentence per line. These should ideally be actual sentences, not # entire paragraphs or arbitrary spans of text. (Because we use the # sentence boundaries for the "next sentence prediction" task)...
_logger().info("Wrote %d total instances", total_written) def create_int_feature(values): feature = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values))) return feature def create_float_feature(values): feature = tf.train.Feature(float_list=tf.train.FloatList(value=list(values))) retur...
103
103
345
35
67
diqiuzhuanzhuan/poros
poros/bert/create_pretraining_data.py
Python
create_training_instances
create_training_instances
159
200
159
161
98da9184ebbcb4a0778dafb2c55fb6faacd08843
bigcode/the-stack
train
4f4fef827dec7106dc066075
train
function
def create_int_feature(values): feature = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values))) return feature
def create_int_feature(values):
feature = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values))) return feature
tf.get_logger().info( "%s: %s" % (feature_name, " ".join([str(x) for x in values]))) for writer in writers: writer.close() tf.get_logger().info("Wrote %d total instances", total_written) def create_int_feature(values):
64
64
28
6
58
diqiuzhuanzhuan/poros
poros/bert/create_pretraining_data.py
Python
create_int_feature
create_int_feature
149
151
149
149
86cd4cbd886632b1c95fce605acdd47588c9c1e0
bigcode/the-stack
train
76a8ab0bc55e80e9ced78e16
train
function
def main(_): import logging tf.get_logger().setLevel(logging.INFO) tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) input_files = [] for input_pattern in FLAGS.input_file.split(","): input_files.extend(tf.io.gfile.glob(input_pa...
def main(_):
import logging tf.get_logger().setLevel(logging.INFO) tokenizer = tokenization.FullTokenizer( vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case) input_files = [] for input_pattern in FLAGS.input_file.split(","): input_files.extend(tf.io.gfile.glob(input_pattern)) ...
_b assert len(trunc_tokens) >= 1 # We want to sometimes truncate from the front and sometimes from the # back to add more randomness and avoid biases. if rng.random() < 0.5: del trunc_tokens[0] else: trunc_tokens.pop() def main(_):
69
69
233
4
65
diqiuzhuanzhuan/poros
poros/bert/create_pretraining_data.py
Python
main
main
416
443
416
416
5a932e2ea06b23bf9c8c2c61e812911ee888cc4c
bigcode/the-stack
train
234df38ef937396511975e6a
train
function
def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng): """Creates the predictions for the masked LM objective.""" cand_indexes = [] for (i, token) in enumerate(tokens): if token == "[CLS]" or token == "[SEP]": ...
def create_masked_lm_predictions(tokens, masked_lm_prob, max_predictions_per_seq, vocab_words, rng):
"""Creates the predictions for the masked LM objective.""" cand_indexes = [] for (i, token) in enumerate(tokens): if token == "[CLS]" or token == "[SEP]": continue # Whole Word Masking means that if we mask all of the wordpieces # corresponding to an original word. When ...
for token in tokens_b: tokens.append(token) segment_ids.append(1) tokens.append("[SEP]") segment_ids.append(1) (tokens, masked_lm_positions, masked_lm_labels) = create_masked_lm_predictions( ...
192
193
644
25
167
diqiuzhuanzhuan/poros
poros/bert/create_pretraining_data.py
Python
create_masked_lm_predictions
create_masked_lm_predictions
322
395
322
323
f85c9e1aff7695d6dd1ce9f41d7a57150de3b5b9
bigcode/the-stack
train
e45cb49b24527b45282f8054
train
class
class TrainingInstance(object): """A single training instance (sentence pair).""" def __init__(self, tokens, segment_ids, masked_lm_positions, masked_lm_labels, is_random_next): self.tokens = tokens self.segment_ids = segment_ids self.is_random_next = is_random_next ...
class TrainingInstance(object):
"""A single training instance (sentence pair).""" def __init__(self, tokens, segment_ids, masked_lm_positions, masked_lm_labels, is_random_next): self.tokens = tokens self.segment_ids = segment_ids self.is_random_next = is_random_next self.masked_lm_positions = ...
.max_seq_length = max_seq_length self.max_predictions_per_seq = max_predictions_per_seq self.random_seed = random_seed self.dupe_factor = dupe_factor self.masked_lm_prob = masked_lm_prob self.short_seq_prob = short_seq_prob FLAGS = Flags(input_file=None, output_file=None, vocab...
81
81
271
5
76
diqiuzhuanzhuan/poros
poros/bert/create_pretraining_data.py
Python
TrainingInstance
TrainingInstance
48
73
48
48
6391595c1a62ad34b8c4f303c1ef9c8ba9785555
bigcode/the-stack
train
e766fc965ffd880af6850f38
train
function
def write_instance_to_example_files(instances, tokenizer, max_seq_length, max_predictions_per_seq, output_files): """Create TF example files from `TrainingInstance`s.""" writers = [] for output_file in output_files: writers.append(tf.io.TFRecordWriter(output_file)...
def write_instance_to_example_files(instances, tokenizer, max_seq_length, max_predictions_per_seq, output_files):
"""Create TF example files from `TrainingInstance`s.""" writers = [] for output_file in output_files: writers.append(tf.io.TFRecordWriter(output_file)) writer_index = 0 total_written = 0 for (inst_index, instance) in enumerate(instances): input_ids = tokenizer.convert_tokens_to...
s += "tokens: %s\n" % (" ".join( [tokenization.printable_text(x) for x in self.tokens])) s += "segment_ids: %s\n" % (" ".join([str(x) for x in self.segment_ids])) s += "is_random_next: %s\n" % self.is_random_next s += "masked_lm_positions: %s\n" % (" ".join( [str(x) for ...
190
191
637
24
167
diqiuzhuanzhuan/poros
poros/bert/create_pretraining_data.py
Python
write_instance_to_example_files
write_instance_to_example_files
76
146
76
77
e5d7c9d4f04beb15500879c54d28b6fc62f61208
bigcode/the-stack
train
8516cf10fa03c78c672c8b76
train
function
def maybe_advance_script(is_get_status=False): def inner_advance(func): @wraps(func) def wrapper(self, *args, **kwargs): advance_units = random.randint(1, 500) logger.debug("Advancing script %s units", advance_units) while advance_units > 0 and self.remaining_scri...
def maybe_advance_script(is_get_status=False):
def inner_advance(func): @wraps(func) def wrapper(self, *args, **kwargs): advance_units = random.randint(1, 500) logger.debug("Advancing script %s units", advance_units) while advance_units > 0 and self.remaining_script: units = self.remaining_scri...
import generate_lorem_ipsum from data.buildlogs import RedisBuildLogs logger = logging.getLogger(__name__) random = SystemRandom() get_sentence = partial(generate_lorem_ipsum, html=False, n=1, min=5, max=10) def maybe_advance_script(is_get_status=False):
64
64
131
10
54
giuseppe/quay
test/testlogs.py
Python
maybe_advance_script
maybe_advance_script
19
38
19
19
64df452a406953e4373c254b7a01aba535d934d9
bigcode/the-stack
train
3965c7213f1638b440b6aef5
train
class
class TestBuildLogs(RedisBuildLogs): COMMAND_TYPES = [ "FROM", "MAINTAINER", "RUN", "CMD", "EXPOSE", "ENV", "ADD", "ENTRYPOINT", "VOLUME", "USER", "WORKDIR", ] STATUS_TEMPLATE = { "total_commands": None, ...
class TestBuildLogs(RedisBuildLogs):
COMMAND_TYPES = [ "FROM", "MAINTAINER", "RUN", "CMD", "EXPOSE", "ENV", "ADD", "ENTRYPOINT", "VOLUME", "USER", "WORKDIR", ] STATUS_TEMPLATE = { "total_commands": None, "current_command": None, "pus...
import logging import datetime from random import SystemRandom from functools import wraps, partial from copy import deepcopy from jinja2.utils import generate_lorem_ipsum from data.buildlogs import RedisBuildLogs logger = logging.getLogger(__name__) random = SystemRandom() get_sentence = partial(generate_lorem_i...
223
256
1,606
9
213
giuseppe/quay
test/testlogs.py
Python
TestBuildLogs
TestBuildLogs
41
250
41
41
ea3564bc6721b74ff3d2d43f1801878b7cb544f8
bigcode/the-stack
train
113030ac085eed640101556a
train
class
class Common(Room): def __init__(self): super(Common, self).__init__()
class Common(Room):
def __init__(self): super(Common, self).__init__()
# coding=utf-8 #----------------------------------------------------------- # IMPORTS #----------------------------------------------------------- import enigmus import random from entities import Room #----------------------------------------------------------- # CLASSES #------------------------------------------...
43
64
19
4
39
philiparvidsson/Enigmus-MUD
quests/common/scripts/_common.py
Python
Common
Common
16
18
16
16
98fe55cd978be6d770a00e979effc2bdcd54759c
bigcode/the-stack
train
08e2db5a860b207c99d30b33
train
class
class Group: single_chars = [] ranges = []
class Group:
single_chars = [] ranges = []
me/data/grapheme_break_property.json" pattern = re.compile("^([0-9A-F]+)(\.\.([0-9A-F]+))?\s+;\s*(\w*)\s*#") dir_path = os.path.dirname(os.path.realpath(__file__)) class Group:
63
64
12
3
60
RTNelo/grapheme
unicode-data/read_property_file.py
Python
Group
Group
15
17
15
15
4ac5c41bef7151927856ffed4f340ce10349372b
bigcode/the-stack
train
7e626b9db4db1bbb2ff041dc
train
function
def group(): return dict( single_chars=[], ranges=[] )
def group():
return dict( single_chars=[], ranges=[] )
.compile("^([0-9A-F]+)(\.\.([0-9A-F]+))?\s+;\s*(\w*)\s*#") dir_path = os.path.dirname(os.path.realpath(__file__)) class Group: single_chars = [] ranges = [] def group():
64
64
17
3
61
RTNelo/grapheme
unicode-data/read_property_file.py
Python
group
group
18
22
18
18
5282dd0775683de9dc97f64b42ad080e51dba9d6
bigcode/the-stack
train
55bfa030f423013e5eae70d8
train
function
def flatten_graph_input_values(graph): """ CoreML can't handle nested iterables of tensors, so we flatten the inputs of any graph that expects them. """ new_graph_inputs = graph.inputs all_new_nodes = [] changed = True notified = False while changed: old_graph_inputs = new_g...
def flatten_graph_input_values(graph):
""" CoreML can't handle nested iterables of tensors, so we flatten the inputs of any graph that expects them. """ new_graph_inputs = graph.inputs all_new_nodes = [] changed = True notified = False while changed: old_graph_inputs = new_graph_inputs new_graph_inputs = ...
raise NotImplementedError( "inplace_ops pass doesn't yet support append op inside conditional" ) for block in node.blocks: transform_inplace_ops(block, name_remap_dict) # Replace names in graph outputs for k, v in name_remap_dict.items(): try: ...
97
97
325
7
89
BearerPipelineTest/coremltools
coremltools/converters/mil/frontend/torch/torchir_passes.py
Python
flatten_graph_input_values
flatten_graph_input_values
234
275
234
234
8c44774a98aefde849fcda731fa133d0bc28bec6
bigcode/the-stack
train
52287cd09d0a6b9d0668475d
train
function
def generate_tensor_assignment_ops(graph): """ This graph pass handles inplace tensor assignements, specifically it handles: `torch.Tensor.copy_` and `torch.Tensor.fill_`. There are many other inplace tensor assignments which are currently not handled. for instance: def forward(self, x): ...
def generate_tensor_assignment_ops(graph):
""" This graph pass handles inplace tensor assignements, specifically it handles: `torch.Tensor.copy_` and `torch.Tensor.fill_`. There are many other inplace tensor assignments which are currently not handled. for instance: def forward(self, x): # x a tensor with shape [4,10] ...
# Copyright (c) 2021, Apple Inc. All rights reserved. # # Use of this source code is governed by a BSD-3-clause license that can be # found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause from collections import defaultdict, OrderedDict import logging as _logging from .internal_graph imp...
96
256
1,337
7
88
BearerPipelineTest/coremltools
coremltools/converters/mil/frontend/torch/torchir_passes.py
Python
generate_tensor_assignment_ops
generate_tensor_assignment_ops
11
142
11
11
8c027ad52c9be53f894bf6837d1a2c2db37fe35c
bigcode/the-stack
train
8220658400e6149bb1634de3
train
function
def transform_inplace_ops(graph, name_remap_dict=None): # As we modify ops, we'll need to remap symbols. if name_remap_dict is None: name_remap_dict = {} for node in graph.nodes: for k, v in name_remap_dict.items(): node.replace_name(k, v) if node.kind == "append": ...
def transform_inplace_ops(graph, name_remap_dict=None): # As we modify ops, we'll need to remap symbols.
if name_remap_dict is None: name_remap_dict = {} for node in graph.nodes: for k, v in name_remap_dict.items(): node.replace_name(k, v) if node.kind == "append": if isinstance(node.parent, InternalTorchIRGraph): # If append appears in a graph (out...
_name(output, updated_tensor_count) def remove_getattr_nodes(graph): """ Remove the getattr nodes in the graph """ getattr_nodes = [] new_nodes = [] for node in graph.nodes: for block in node.blocks: remove_getattr_nodes(block) if node.kind == "getattr": ...
166
166
556
27
138
BearerPipelineTest/coremltools
coremltools/converters/mil/frontend/torch/torchir_passes.py
Python
transform_inplace_ops
transform_inplace_ops
172
231
172
174
fb0f76526f1aa4d7282700fe2eef076d13108195
bigcode/the-stack
train
e8433f4b93643b22bdef8d2e
train
function
def flatten_graph_output_values(graph): """ CoreML can't handle nested iterables of tensors, so we flatten the outputs of any graph that produces them. """ node_names = [node.name for node in graph.nodes] new_graph_outputs = graph.outputs changed = True notified = False while change...
def flatten_graph_output_values(graph):
""" CoreML can't handle nested iterables of tensors, so we flatten the outputs of any graph that produces them. """ node_names = [node.name for node in graph.nodes] new_graph_outputs = graph.outputs changed = True notified = False while changed: old_graph_outputs = new_graph...
] = item node_inputs.append(name) new_nodes.append( InternalTorchIRNode( inputs=node_inputs, outputs=[_input_name], kind="tupleconstruct", ) ) e...
110
110
367
7
102
BearerPipelineTest/coremltools
coremltools/converters/mil/frontend/torch/torchir_passes.py
Python
flatten_graph_output_values
flatten_graph_output_values
278
321
278
278
9d3644164c1398b3caec4e6908a12bc81e358c08
bigcode/the-stack
train
4b70156339842ec5e522986c
train
function
def remove_getattr_nodes(graph): """ Remove the getattr nodes in the graph """ getattr_nodes = [] new_nodes = [] for node in graph.nodes: for block in node.blocks: remove_getattr_nodes(block) if node.kind == "getattr": getattr_nodes.append(node) ...
def remove_getattr_nodes(graph):
""" Remove the getattr nodes in the graph """ getattr_nodes = [] new_nodes = [] for node in graph.nodes: for block in node.blocks: remove_getattr_nodes(block) if node.kind == "getattr": getattr_nodes.append(node) else: new_nodes.app...
_node # modify the graph outputs if it is effected by this graph pass for idx in range(len(graph.outputs)): output = graph.outputs[idx] if output in updated_tensor_count: graph.outputs[idx] = _get_updated_name(output, updated_tensor_count) def remove_getattr_nodes(graph):
64
64
132
7
57
BearerPipelineTest/coremltools
coremltools/converters/mil/frontend/torch/torchir_passes.py
Python
remove_getattr_nodes
remove_getattr_nodes
145
169
145
145
1d91195f97c62df279a294cbf3d52220b8af3aff
bigcode/the-stack
train
4ca5b463e3abfd1263e34274
train
class
class TestParse: def test_full(self, yaml_ast): InterfaceType.parse(yaml_ast( """ derived_from: interface_type description: My desc metadata: key: value version: "1.2" inputs: in: type: float ...
class TestParse:
def test_full(self, yaml_ast): InterfaceType.parse(yaml_ast( """ derived_from: interface_type description: My desc metadata: key: value version: "1.2" inputs: in: type: float opera...
from opera.parser.tosca.v_1_3.interface_type import InterfaceType class TestParse:
21
64
106
4
16
sstanovnik/xopera-opera
tests/opera/parser/tosca/v_1_3/test_interface_type.py
Python
TestParse
TestParse
4
26
4
4
a6ac8aa0fb1f79e78f7f77951bf09337c67f74a7
bigcode/the-stack
train
c47e91167610733d666a1c71
train
function
def test_train_small_model_benchmark(subset_moddata, tf_session): """Tests the `fit_preset()` method.""" from modnet.matbench.benchmark import matbench_benchmark data = subset_moddata # set 'optimal' features manually data.optimal_features = [ col for col in data.df_featurized.columns if co...
def test_train_small_model_benchmark(subset_moddata, tf_session):
"""Tests the `fit_preset()` method.""" from modnet.matbench.benchmark import matbench_benchmark data = subset_moddata # set 'optimal' features manually data.optimal_features = [ col for col in data.df_featurized.columns if col.startswith("ElementProperty") ] results = matbench_benc...
#!/usr/bin/env python def test_train_small_model_benchmark(subset_moddata, tf_session):
21
64
209
15
5
fnaccarato/modnet
modnet/tests/test_benchmark.py
Python
test_train_small_model_benchmark
test_train_small_model_benchmark
4
36
4
4
8c8c53febc00dbaf8d4febfb9049edc2d29774d5
bigcode/the-stack
train
2d58b2ec06b6f9148d7c598e
train
function
def test_sflow_ft_multiple_collectors(topology, step): """ Test sflow is able to send packets to multiple collectors """ ops1 = topology.get('ops1') hs1 = topology.get('hs1') hs2 = topology.get('hs2') hs3 = topology.get('hs3') hs4 = topology.get('hs4') assert ops1 is not None as...
def test_sflow_ft_multiple_collectors(topology, step):
""" Test sflow is able to send packets to multiple collectors """ ops1 = topology.get('ops1') hs1 = topology.get('hs1') hs2 = topology.get('hs2') hs3 = topology.get('hs3') hs4 = topology.get('hs4') assert ops1 is not None assert hs1 is not None assert hs2 is not None ass...
# | Switch | # | | # | | # +-+----------+--+ # | | # | | # +-------+--+ +-+--------------+ # | | | | # | | | Host-2 | # ...
256
256
1,222
13
243
umbs/ops-switchd
ops-tests/feature/sflow/test_sflow_ft_multiple_collectors.py
Python
test_sflow_ft_multiple_collectors
test_sflow_ft_multiple_collectors
67
192
67
67
8986530afa9ed9a6310d8e9d9111c7aaebeff6cc
bigcode/the-stack
train
8d9b022292ab76b9b0d4119a
train
function
def test_no_key_or_name_param(app_static): # the API allows you to use App.reords() (without any key or view name) if only # one container has been retrieved. in this case, it's the sideloaded records in # object_3. assert app_static.get()
def test_no_key_or_name_param(app_static): # the API allows you to use App.reords() (without any key or view name) if only # one container has been retrieved. in this case, it's the sideloaded records in # object_3.
assert app_static.get()
.get("all fields") def test_no_key_or_name_param(app_static): # the API allows you to use App.reords() (without any key or view name) if only # one container has been retrieved. in this case, it's the sideloaded records in # object_3.
64
64
65
59
5
gabcoyne/knackpy
tests/test_app.py
Python
test_no_key_or_name_param
test_no_key_or_name_param
147
151
147
150
6d407ea058c23f07e46324f8a41ae09f6cb7eb91
bigcode/the-stack
train
8f440cb672d86db974079a13
train
function
def test_get_by_dupe_name_fail(app_static): # the "all_fields_test" container name exists in our app as both an object # and as a view. so trying to query by that name results in a KeyError. with pytest.raises(ValueError): assert isinstance(app_static.get("all_fields_test"), types.GeneratorType)
def test_get_by_dupe_name_fail(app_static): # the "all_fields_test" container name exists in our app as both an object # and as a view. so trying to query by that name results in a KeyError.
with pytest.raises(ValueError): assert isinstance(app_static.get("all_fields_test"), types.GeneratorType)
with pytest.raises(TypeError): assert app_static.get() def test_get_by_dupe_name_fail(app_static): # the "all_fields_test" container name exists in our app as both an object # and as a view. so trying to query by that name results in a KeyError.
64
64
73
50
14
gabcoyne/knackpy
tests/test_app.py
Python
test_get_by_dupe_name_fail
test_get_by_dupe_name_fail
165
169
165
167
fc4d60911bac5935efd507c785580b74149c64b3
bigcode/the-stack
train
7b0e203c270246e3eb13321f
train
function
def test_info(app_static): assert isinstance(app_static.info(), dict)
def test_info(app_static):
assert isinstance(app_static.info(), dict)
astern", ) def test_invalid_tzinfo(app_data): with pytest.raises(ValueError): assert knackpy.app.App( app_id=app_data["metadata"]["application"]["id"], metadata=app_data["metadata"], tzinfo="Austin, Texas", ) def test_info(app_static):
64
64
15
6
58
gabcoyne/knackpy
tests/test_app.py
Python
test_info
test_info
189
190
189
189
3b81059d2ac6790306d3f19d5618c4ad31d19722
bigcode/the-stack
train
e56c444c5c5286df45c27d42
train
function
def test_generate_records_is_generator(app_static): assert isinstance(app_static.get(OBJ, generate=True), types.GeneratorType)
def test_generate_records_is_generator(app_static):
assert isinstance(app_static.get(OBJ, generate=True), types.GeneratorType)
): assert app_live.get("view_11") def test_get_view_by_name(app_live): assert app_live.get("view_11") def test_get_by_key_refresh(app_live): records = app_live.get(OBJ, refresh=True) assert records def test_generate_records_is_generator(app_static):
64
64
26
9
54
gabcoyne/knackpy
tests/test_app.py
Python
test_generate_records_is_generator
test_generate_records_is_generator
115
116
115
115
711adce34b08d3982d8319c8fb76f1fec473990d
bigcode/the-stack
train
24b102fc42e662f03028047a
train
function
def test_basic_over_the_wire_construction(app_live): assert knackpy.app.App(app_id=APP_ID, api_key=API_KEY)
def test_basic_over_the_wire_construction(app_live):
assert knackpy.app.App(app_id=APP_ID, api_key=API_KEY)
["data"]} return knackpy_app @pytest.fixture def app_live(): # testing on live app (as in over-the-wire data fetch, not side-loaded) return knackpy.app.App(app_id=APP_ID, api_key=API_KEY) def test_basic_over_the_wire_construction(app_live):
64
64
29
11
53
gabcoyne/knackpy
tests/test_app.py
Python
test_basic_over_the_wire_construction
test_basic_over_the_wire_construction
69
70
69
69
419a75e99fed12d46d8e6663b3380edd359c89be
bigcode/the-stack
train
9e9fa7da6c16951fa7a8a02c
train
function
def test_basic_static_app_construction(app_static): assert app_static
def test_basic_static_app_construction(app_static):
assert app_static
): assert knackpy.app.App(app_id=APP_ID, api_key=API_KEY) def test_over_the_wire_construction_with_slug(app_live): assert knackpy.app.App(app_id=APP_ID, api_key=API_KEY, slug="atd") def test_basic_static_app_construction(app_static):
64
64
15
10
54
gabcoyne/knackpy
tests/test_app.py
Python
test_basic_static_app_construction
test_basic_static_app_construction
77
78
77
77
f7d06662d747d159db960bbbd0fbaebc8444769c
bigcode/the-stack
train
feaaea65a128d7d33474019e
train
function
def test_generate_records(app_static): assert len([record for record in app_static.get(OBJ, generate=True)]) > 0
def test_generate_records(app_static):
assert len([record for record in app_static.get(OBJ, generate=True)]) > 0
.get("view_11") def test_get_by_key_refresh(app_live): records = app_live.get(OBJ, refresh=True) assert records def test_generate_records_is_generator(app_static): assert isinstance(app_static.get(OBJ, generate=True), types.GeneratorType) def test_generate_records(app_static):
64
64
28
7
57
gabcoyne/knackpy
tests/test_app.py
Python
test_generate_records
test_generate_records
119
120
119
119
f91d2d57506d8b2eb2f0807bfb07784102e359a9
bigcode/the-stack
train