id stringlengths 20 20 | title stringclasses 1
value | text stringlengths 8 768k |
|---|---|---|
00801a4c71db5d691c66 | def DenseNet(blocks,
include_top=True,
weights='imagenet',
input_tensor=None,
input_shape=None,
pooling=None,
classes=1000,
**kwargs):
global backend, layers, models, keras_utils
backend, layers, models, keras_utils = get... | |
00804751ba70cdedb80d | def banUser(self, nick):
Preferences.syncPreferences()
user = nick.rsplit("@")[0]
bannedUsers = Preferences.getCooperation("BannedUsers")[:]
if user not in bannedUsers:
bannedUsers.append(user)
Preferences.setCooperation("BannedUsers", bannedUsers) | |
00804edc3fcbdc213c1b | def show_widget(self):
# Load the current image
self.update_image()
all_widgets = widgets.VBox([self.index_slider] + self.annotation_buttons + [self.prev_next, self.text_output, self.image_output])
display(all_widgets) | |
00805cb7ddf8782a399b | def test_instance(self):
ins = Place()
self.assertIsInstance(ins, Place) | |
00805fb2e44353c07f80 | def test_reading_color_palette(tmpdir):
# create palette file
palette_file = tmpdir.mkdir('palettes').join('my_rgb.txt')
palette_file.write("""
0 0 0 myBlack
255 255 255 myWhite""")
colorful = core.Colorful(colormode=terminal.ANSI_8_COLORS, colorpalette=str(palette_file))
assert str(colorful.m... | |
00807ddfb468f1499d91 | def create_tasks(self, evidence):
return None | |
00807f0c33c67c20c468 | def get_name(self):
return self.name[1:-1].decode().replace(
'\x03', '.').replace('\x02', '.').replace('\x06', '.').\
replace('\x08', '.') | |
0080a32f9c79ed450b2c | def compute_checksum(filename='api/model'):
return sha256(open(filename + '.py', 'rb').read()).hexdigest() | |
0080d76f41b6ca4a5cae | def getData(self):
package = self.rx.getHeadPayload()
print(binascii.hexlify(package),"getData","linha 57")
data = desempacota(package)
print("***RECEBENDO DATA***")
return(data[0], data[1],(len(data[0])),data[2]) | |
0080d7782b369c1b5b3d | def _ReadApplicationKey(self, application_key):
if self._debug:
self._DebugPrintText(f'Application: {application_key.name:s}\n')
for value in application_key.values:
description = self._APPLICATION_KEY_DESCRIPTIONS.get(
value.name, value.name)
value_data = self._GetValueDataAsObject... | |
0080dbf6382bf6d886f5 | def search(self, **kwargs):
return self.api_list_request(self._get_method_fullname("search"), kwargs) | |
0080eb3ef7fd88272cdd | def argparser():
ap = argparse.ArgumentParser(fromfile_prefix_chars='@',
description='Train and deploy a deep-learned [Fe/H] estimator'
'based on Gaia time-series photometry.',
epilog="")
# use custom... | |
0081101d208508458d59 | def debracket(string):
result = re.sub(BRACKET_RE, ';', string)
result = unidecode.unidecode(result)
return result | |
00811b369cdd747ed922 | def get_distinct_values(schema, table, column, engine):
query = pd.read_sql_query('SELECT DISTINCT '+column+' FROM '+schema+"."+table+';', engine)
return query | |
008131f156ae5c6854bb | def derivatives(self, datadict, parpos, deriv_order=0, **kwargs):
pass | |
00815431604b01204add | def filename(self) -> Optional[Path]:
return self._filename | |
008165920266c7048f9c | def get_table_dhcp_relay(self, dhcp_relay_ipv6=False):
raise SwitchException("Not implemented") | |
00817bf522da295510b2 | def execute(self, cmd):
self.log.debug('Executing `%s`' % cmd)
return self.ssh.exec_command(cmd) | |
0081956090edbb814c39 | def enable_plugin_impl(self, name):
enabled_plugins = {} # plugin_name -> plugin_instance
for p in self.bot.get_plugins(): enabled_plugins[type(p).__name__] = p
if name in enabled_plugins: raise self.plugin_already_enabled(f'cannot enable {name}: plugin already enabled')
if f'plugins.... | |
0081bf837955734eb9a0 | def InitiateFileUpload(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | |
0081d66d00a1c7c3015e | def from_segment(cls, segment):
return cls(segment.sample_rate, segment.shape, segment.size, segment.max(), segment.mean(), segment.min(),
segment.std()) | |
0081e98442398fbf6d81 | def cfghtmlserved(self) :
try :
return self._cfghtmlserved
except Exception as e:
raise e | |
0081ec90cb09e9e0d0a6 | def read(self, scan_list=None):
import spec2nexus
from spec2nexus import utils
# check that scan_list is valid
complete_scan_list = list(self.SPECfile.scans)
if scan_list is None:
scan_list = complete_scan_list
else:
if isinstance(scan_list, int):... | |
008212276995f3a2dadc | def import_submodules(package, recursive=True):
if isinstance(package, str):
package = importlib.import_module(package)
print("{} : imported".format(package))
results = {}
for loader, name, is_pkg in pkgutil.walk_packages(package.__path__):
full_name = package.__name__ + '.' + ... | |
0082177edd110edabeae | def weird_thing(arg: Dict[str, str]) -> Dict:
build = {}
for key, value in arg.items():
build[key.upper()] = value.lower()
return swap(build) | |
00824de09ab3a33cecfe | def set_checksum(self):
if self.checksum_type != "any":
print("Not supported yet!")
self.checksum = str(random.randint(0, 9)) | |
00824eb327c303d2f7a7 | def save(self, *args, **kwargs):
s = 0
i = 0
for r in self.gem.reviews.all():
s += r.rating
i += 1
self.gem.rating = (s + self.rating)/(i + 1)
self.gem.save()
super(Review, self).save(*args, **kwargs) | |
00825949e3e085ab6331 | def current(self):
return max(self._axes, key=self._axes.__getitem__, default=None) | |
00825bebe3e31276d661 | def __setattr__(self, name, value):
# check if the attribute exists, then set it if so.
if name != "_field_names" and name in self._field_names.keys():
object.__getattribute__(self,"_field_names")[name].value = value
elif name in object.__getattribute__(self, "_class_fields").key... | |
008269c34854da9671cd | def remove_task(self, task):
entry = self.entry_finder.pop(task)
entry[-1] = self._removed | |
00826e1495901b2f5a55 | def load_patient_3d_atlas( patient_data, patient_nodules_df=None, discard_empty_nodules=False,
output_rois=False, debug=False, thickness=0, slice_downsample = 10, slice_lung_shape=(20,20)):
X, Y, rois = [], [], []
lung_view = []
total_stats = {}
# load the slices to ... | |
00826f74bfba113022c5 | def plot_xy(x,y):
fig=plt.figure()
ax1=plt.subplot(111)
ax1.plot(x,y)
plt.show() | |
0082847bddbc84bb732c | async def test_file_landing_url_on_failure(self):
response = await self.collect(get_request_json_side_effect=[ConnectionError])
self.assert_measurement(response, landing_url="https://gitlab", connection_error="Traceback") | |
00828f292ebcae2a6750 | def list_of_combs(arr):
combs = []
for i in range(1, len(arr)+1):
listing = [list(x) for x in itertools.combinations(arr, i)]
combs.extend(listing)
return combs | |
008299535d9a40be9dc5 | def make_me_a_file():
print("Seeding...")
pool = multiprocessing.Pool(4)
to_write = pool.map(get_links, SEEDS)
pool.close()
for seed_links in to_write:
write_links(seed_links)
print("Done seeding.")
reduce_links()
for iter_num in range(0, 5):
iterate_links()
prin... | |
0082a519a651fbee6862 | def generate_routes(self):
pass | |
0082a8b043edde4275d2 | def _read_value(self, section, key):
try:
_config_value = self._config.get(section,key)
except configparser.NoSectionError:
logger.info('Section {} not found in config file'.format(section))
raise pycomic_err.NoSectionError
except configparser.NoOptionError:
... | |
0082b3943692d98cb97d | def get_raw_items_younger_than(self, time, *args):
return_values = {}
if args:
for key in args:
return_values[key] = None
if "window_stop" not in args:
return_values["window_stop"] = None
else:
for key in self._data:
... | |
0082cfd4065325c8625f | def _ReadRequest(sock, timeout):
msg = http.HttpMessage()
try:
reader = _HttpClientToServerMessageReader(sock, msg, timeout)
except http.HttpSocketTimeout:
raise http.HttpError("Timeout while reading request")
except socket.error as err:
raise http.HttpError("Error reading request: %s... | |
0082d123f72ed2c93aef | def gid2name(gid: Union[str, int]) -> str:
name_list = [gr.gr_name for gr in grp.getgrall() if gr.gr_gid == int(gid)]
return str(name_list[0]) | |
0082fdc056fc344a4548 | def setUpDatabase():
test_obj = TestVariables()
sql_m = SqlManager()
sql_m.sql_create_exam_database(test_obj.entry_field_content) | |
00834e2773f9a59560db | def get_user_entities(session, user_id):
entities = []
user = session.query(User).filter(User.id == user_id).one()
for permission in user.perms:
for data_perm in permission.data_perms:
entities.append({'in_path': data_perm.in_path, 'out_path': data_perm.out_path, 'mask': data_perm.mask})... | |
0083775074d524f15fba | def addCar(self, ID):
carAdd = Car(ID)
self.cars[carAdd.getID()] = carAdd
self.totalEnergy = self.totalEnergy + carAdd.getCharge()
print("Car", carAdd.getID(), "created.") | |
00839a28fa194bc32178 | def methodLatitude(self, rawLat: str) -> float:
#print(rawLat)
degree = float(rawLat[0:2])
minutes = float(rawLat[-7:])
decimals = minutes / 60.0
#print(degree + decimals)
return (degree + decimals) | |
0083a7bdc8217cf1e6af | def test_array():
import acorn.numpy as np
assert isinstance(np.squeeze(np.array(0.0), 0), np.ndarray) | |
008416880adf5f31ef0d | def test_signup(self):
username = "testuser"
password = "testpassword"
result = Database().add_user(username, password)
self.assertTrue(result) | |
0084269a8b27fa3d0a27 | def get_action(self, observation): | |
00843a327e33ed07d83a | def getAddress(self, aLabel):
return self.labelLocator[aLabel] | |
00843dd19f68edba6a00 | def Homepage():
return (
f"Available Routes:<br/>"
f"/api/v1.0/precipitation<br/>"
f"/api/v1.0/stations<br/>"
f"/api/v1.0/tobs<br/>"
f"/api/v1.0/startdate<br/>"
f"/api/v1.0/startenddate<br/>"
) | |
00844238ec26be9114ea | def is_valid(self, want=PROB):
results = self.validate(want)
return results.ok() | |
00844f19e640ea4f60de | def signal_sources(**sources: SignalSource) -> Callable[[Type], Type]:
def decorator(typ: Type) -> Type:
extra = sorted(set(sources) - set(get_type_hints(typ)))
assert not extra, f"Signal sources {extra} not described with annotations"
typ.__signal_sources__ = {**getattr(typ, "__signal_sour... | |
00846baa14d1dbc684c3 | def textPosition(self):
return core.Point3D() | |
00846e5eca722c9cba45 | def __init__(self, *args, **kwargs):
super(AppswellSimpleModelForm, self).__init__(*args, **kwargs)
self.fields['note'].widget = forms.Textarea(
attrs={ 'class':'appswell_textarea', 'rows':4, 'cols':40 } )
# override labels
self.fields['note'].label = 'why you like it (optio... | |
0084a34f7e91d71d35c5 | def issue_heartbeat():
global heartbeat_timer
connections_to_remove = []
for connection in active_host_screens.keys():
if active_host_screens[connection]['num_retries'] == 0:
player_name = active_host_screens[connection]['name']
global_server_state.remove_player(player_name... | |
0084d680784a5ca30d1e | def gt(self, other): | |
0084e92946ef6701ce87 | def getNeighborMatrix(self, g, o, totalXs):
boundary_id_matrix = []
boundary_matrix = []
for k, neighbor_edge_id in enumerate(self.gmsh_dg_element['neighbors']['neighbor_edge_ids']):
parent_edge_id = self.gmsh_dg_element['neighbors']['parent_edge_ids'][k]
parent_edge_node... | |
00850ccbbc56006fb32a | def calcRates(self,v_bias : float = 0):
#Loading energies and P matrices
P_ts,P_st,P_ss = self.calcPmat()
#Take the energies and calculate all the differences
w = self.structure.getEnergies()
wx,wy = np.meshgrid(w,w)
wv = wy - wx
#Calculation of different rates by... | |
00850f7c6b2f96f06982 | def display(self):
print('{}, written by {}.'.format(self.title, self.author)) | |
00852d2cdd6b200c5b8f | def __index(self, index):
if len(self) - 1 < index or index < -len(self):
raise ValueError("list index out of range")
if index < 0:
index += self.length
for i, item in enumerate(self):
if i == index:
return item
return None | |
008576c4ecfa57277388 | def update(self):
self.image = pygame.image.load(
f"pics/mg_{self.hero.profil}.png"
).convert_alpha()
x, y = self.hero.position.posx, self.hero.position.posy
self.rect.x = x * SPRITE_SIZE_X
self.rect.y = y * SPRITE_SIZE_Y | |
00859634c44074a4c91b | def _terminate(self) -> None:
assert self.started
if not self.stopped:
os.kill(os.getpid(), signal.SIGTERM) | |
00859f041b5541306894 | def main():
logger = start_logger()
parser = configure_args()
args = parser.parse_args()
if args.verbose: logger.setLevel(20)
if args.debug: logger.setLevel(10)
logging.info('** ' + os.path.basename(__file__) + ' begin')
# Check for INSTANCEID environment variables
# If sets, it limits... | |
0085d4a26c6f1864cfb1 | def update(self):
self.board.update() | |
0085d7b7afa1cc498c81 | def do_write(self, data):
try:
if self.trace:
print "===> TX:", repr(data)
self.socket_conn.sendall(data)
except Exception as exc:
raise EOF(exc) | |
0085f1cd7aac161ad969 | def test_instance_creation(self):
my_storage = FileStorage()
self.assertIs(type(my_storage), FileStorage) | |
0086018f520d0086eb88 | def setUpClass(self):
from pythologist_test_images import TestImages
e1 = os.path.join(TestImages().raw('Tiny'),'E1')
print('==========')
print("reading in InForm single sample")
print('----------')
csi = CellSampleInForm()
csi.read_path(e1,sample_name='E1',
... | |
00862050fe0983ceb215 | def tearDown(self):
shutil.rmtree(self.workspace_dir) | |
0086414a60cb8da964b5 | def new_term(command, size=None):
os.system("start %s" % command) | |
0086623d30595a4b9700 | def __contains__(self, line):
# First check for an entry in _lines.
specific = self._lines.get(line)
if specific is not None:
return specific
# Find the position in _ranges for line. The polarity of this position
# determines whether we are inside a range (odd) or outside (even).
pos = bi... | |
00866f060930dcad1d35 | def set_expanded_state(
self, state: list[str], root_index: core.ModelIndex | None = None
):
root = root_index or self.rootIndex()
model = self.model()
self._expanded_ids = state
def _restore_expanded_on_level(index: core.ModelIndex):
model = self.model()
... | |
00869d964c99df59253f | def get_bus_stops(bus_line):
requested_fields = ['StopPointName', 'StopCode1', 'Towards']
selectors = {'LineName': bus_line}
return _get_countdown_data(selectors, STOP_ARRAY, requested_fields) | |
0086bfe7c093fa67b659 | def main(player1, player2, time):
def make_player(name, num):
if name=='ai':
return AIPlayer(num)
elif name=='random':
return RandomPlayer(num)
elif name=='human':
return HumanPlayer(num)
Game(make_player(player1, 1), make_player(player2, 2), time) | |
0086da7fc42f62131e6d | def st_odd0_even1(n_slices, TR):
if n_slices % 2 == 0:
return st_13024(n_slices, TR)
return st_02413(n_slices, TR) | |
008797af21722f9b0d23 | def get_name_and_namespace(resource_list):
logger.debug("Getting resource names in all namespaces")
podnames = []
try:
for item in resource_list:
podnames.append({"name":item.metadata.name, "namespace":item.metadata.namespace})
except ApiException as e:
print("Exception when ... | |
0087c5f3981397ceb09a | def __repr__(self):
return "{TreeStructure with root node "+str(self.rootNode)+"}" | |
0087facc4874c475484d | def filelist_recursive(the_path):
return filelist(the_path, recursive = True) | |
008810b931ef4aff3fb4 | def get_command(self):
return self.o.read_register(self.dev_id, COMMNAND) | |
00881d6c062fd73af09c | def __init__(self, **kwargs):
for name, value in kwargs.items():
self.__setattr__(name, value) | |
00883a7b44805682b4fe | def getInstructions(self):
return self._stmtblock | |
008849441d66ac207e74 | def _headers(self):
auth_token = SendbeeAuth(self.client.api_secret).get_auth_token()
headers = {
'X-Auth-Token': auth_token,
'X-Api-Key': self.client.api_key,
'Accept': 'application/json',
'Content-Type': 'application/json',
... | |
00885aa10ffce7beec57 | def save(self, path):
path = os.path.abspath(path)
if not os.path.exists(path): os.mkdir(path)
self.saveDepository(os.path.join(path, 'depository'))
self.saveLibraries(os.path.join(path, 'libraries'))
self.saveGroups(os.path.join(path, 'groups')) | |
008876f6c112bee36d70 | def clear(self):
for field in self.fields:
setattr(self, field, None) | |
0088847363f028f04128 | def container_image(self) -> Optional[pulumi.Input['GoogleCloudDataplexV1TaskInfrastructureSpecContainerImageRuntimeArgs']]:
return pulumi.get(self, "container_image") | |
008888ec2ee84262e323 | def cli(context):
context.obj = {}
name = input('Hej! vad heter du? ')
context.obj['name'] = name
click.secho("Välkommen {}!!".format(name), fg='green', bg='blue')
click.echo("Vi gör lite skolgrejer") | |
0088901fc0ea4522fbd0 | def compute_error_rate(test_dataset, beta):
errors_count = 0
for row in test_dataset:
real_y = row[-1]
x = np.insert(row[:-1], 0, 1)
predicted_value = h_single(x, beta)
if predicted_value != real_y:
errors_count += 1
return errors_count / len(test_dataset) | |
0088a30d69b38becb565 | def get_entity_types(self):
return super().get_entity_types() | |
0088c599b4462c6a63e4 | def start(filename):
sys.stdout = Logger(filename) | |
0088d0687e0ca6dbb644 | def close(self):
for name, comm in self._all_comms.items():
comm.terminate()
comm.join()
self._running = False
if self._run_mode == 'multithread':
self._polling_loop.join()
elif self._run_mode == 'multiprocess':
self._polling_loop.termina... | |
0088ef073d32ec82ced9 | def run():
# Create the menus.
main_menuitems = [
textmenu.TextMenuItem('1', log_in, 'Log in'),
textmenu.TextMenuItem('2', new_user, 'Create new user'),
textmenu.TextMenuItem('3', secret_code, 'Look at secret code'),
textmenu.TextMenuItem('q', 'quit', 'Quit'),
... | |
0088f19aa6c7fce71fc8 | def _putStream(self, s):
self._out('stream')
self._out(s)
self._out('endstream') | |
00891b2aefccd854f4ea | def rotateXYZ(x, y, z, coeffs):
L = np.array([x.flatten() + coeffs[0],
y.flatten() + coeffs[1],
z.flatten() + coeffs[2]])
xr, yr, zr = np.dot(invRx(coeffs[3]),
np.dot(invRy(coeffs[4]),
np.dot(invRz(coeffs[5]), L))... | |
00892eab7973ae203444 | def update(self, root, append_to=None): | |
0089350e8a1fa4a88e3b | def __call__(self, value):
return self.in_range(value) | |
00893d388502f54cc896 | def get_median(self):
return round(self.dataframe.median()[0],2) | |
0089439b51b0225fbc14 | def boundary(self):
min_x = self.clipping.min_x
max_x = self.clipping.max_x
min_y = self.clipping.min_y
max_y = self.clipping.max_y
min_z = self.clipping.min_z
max_z = self.clipping.max_z
flip_x = self.clipping.flip.x
flip_y = self.clipping.flip.y
... | |
00895766d4deb5571c6a | def change_direction(self, event):
if event.keysym in self.mapping:
self.vector = self.mapping[event.keysym] | |
008999913d5dfe069350 | def imprimir_publicaciones(self, recientes=True):
print(" Tus publicaciones ".center(47, "-"))
lista_posts = posts_filtrar(self.nombre, rec=recientes)
if lista_posts:
print(*lista_posts, sep="")
else:
# Se invita al usuario a publicar un PrograPost
pri... | |
00899996ca7aa2cdb6be | def loadnetworks(self):
networks = {}
result = 0
#if self.path == ""
for dirname, dirnames, filenames in os.walk(self.repo):
for filename in filenames:
if filename.endswith('.vars'):
result += 1
network = NetworkModel()
... | |
0089acd4f0f14d5ea858 | def default(self, line):
name = line.split()[0]
if name in self._action_methods:
return self._action_methods[name](self, line)
print('error: unregonized command:', name, '(enter ? for help)\n') | |
0089ad15ae0b7f284afe | def function_one(x) :
return x/2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.