id stringlengths 20 20 | title stringclasses 1
value | text stringlengths 8 768k |
|---|---|---|
005a6800b10baa07b356 | def bouquet_design(designs, flowers):
bouquets = ''
while designs:
for design in designs:
bouquet_size = design[1]
counter = 2
flowers_used = {}
while counter < len(design):
flower, amount_flower, counter = get_flower(design, counter)
... | |
005a6938da8476666ec1 | def get_socket(self):
return self.sock | |
005a6ed52de38674dca0 | def post_install_package():
module_name = '.'.join([env.project_package_name,'deploy'])
funcs_run = []
try:
imported = import_module(module_name)
funcs = vars(imported)
for f in env.installed_packages[env.host]:
func = funcs.get(''.join(['post_install_',f.replace... | |
005aa80e62005b053657 | def readStat(self, n):
if self.statpos < 0: return None
f = open(self.file,"rb")
f.seek(self.statpos)
f.seek(self.statpos)
if self.nisomers:
nskip = 7*n
else:
nskip = 6*n
for i in range(nskip):
fortran.skip(f) # Detector Data
total = fortran.read(f)
A = fortran.read(f)
errA = fortran... | |
005ab569ba88f1e529eb | def recv(self, bufsize: int = ...) -> bytes: | |
005afa3401f90996c9de | def sim_model_path(
self,
sim_params: SimParams,
ext: str,
append: str = "",
dirname: Optional[str] = None,
) -> str:
param_str = sim_params.id_str()
append = append if len(append) == 0 else f"-{append}"
filename = f"{self.c.bridge.id_str()}-params={pa... | |
005b012126a8e41b0c03 | async def info(self, context):
await context.message.delete()
embed = discord.Embed(
description="Lous Managment Bot",
color=0x00FF00
)
embed.set_author(
name="Bot Information"
)
embed.add_field(
name="Owner:",
v... | |
005b0c31fa23f1e777be | def _populate_input_data_defaults(self):
for input_data in self.definition['input_data']:
if 'required' not in input_data:
input_data['required'] = True
if input_data['type'] in ['file', 'files'] and 'media_types' not in input_data:
input_data['media_types... | |
005b1ac7c0ba2bb3fe98 | def do_host_route_delete(cc, args):
cc.route.delete(args.route_uuid)
print('Deleted Route: %s' % (args.route_uuid)) | |
005b3284c64e78d239eb | def getUserTokens(self,username):
assert(isinstance(username,basestring))
results=self._userdb.execute('select username, user_type, passprefix,token,created,not_before,not_after from %s where username=:username order by created desc' % self._table_name, {'username':username}).fetchall()
retur... | |
005b38b3d03255b672ff | def angle_between(v1, v2):
v1_u = unit_vector(v1)
v2_u = unit_vector(v2)
return 180/np.pi*np.arccos(np.clip(np.dot(v1_u, v2_u), -1.0, 1.0)) | |
005b654f03879b454522 | def get_collection(scope, name, coll_id=None, session=None):
try:
if coll_id:
collection = session.query(models.Collection).filter_by(coll_id=coll_id).one()
else:
collection = session.query(models.Collection).filter_by(scope=scope, name=name).one()
collection['colle... | |
005b66876d6e8a915f9b | def to_binary(num, bitsNum):
return format(num, '0>'+bitsNum+'b') | |
005b827dd55cafebd2a6 | def d2c(degrees):
ix = round(degrees / (360. / len(CDIRS)))
return CDIRS[ix % len(CDIRS)] | |
005b8ca6a36949c63348 | def media_pause(self):
self._playing = False
self.send_key("KEY_PAUSE") | |
005b8ff97dc5cf177553 | def num_rbs(self):
return self.__num_rbs | |
005ba9c3bc609e85776c | def ike_encryption(self) -> str:
return pulumi.get(self, "ike_encryption") | |
005bbdecd97d84d574a7 | def com_google_fonts_check_valid_glyphnames(ttFont, config):
from fontbakery.utils import pretty_print_list
if (ttFont.sfntVersion == b'\x00\x01\x00\x00'
and ttFont.get("post")
and ttFont["post"].formatType == 3.0):
yield SKIP, ("TrueType fonts with a format 3.0 post table"
... | |
005bcab72eb55902a4af | def succeeded(self, task):
self.display_task_results(task, RETURN_REMOVE_SUCCESS_STRING, RETURN_REMOVE_ERROR_STRING) | |
005bf332b879bf572127 | def OnRxnStatusChoice(self, evt):
selection = self.rxnStatusDropDown.GetSelection()
# TODO this is hardcoded. If the text changes this wouldn't work
if selection == 0:
bezierCurves = True
else:
bezierCurves = False
rxns = get_rxns_by_idx(self.reactions, s... | |
005bf8011b37c3e4ef7b | def zoom(self,xmin,xmax,xlen,ymin,ymax,ylen):
#init the plane
self.xmin = xmin
self.xmax = xmax
self.xlen = xlen
self.ymin = ymin
self.ymax = ymax
self.ylen = ylen
self.__initplane__()
# use numpy vectorize
if len(self.fs) > 0:
... | |
005c0a84a9ccca1ca8ca | def array_to_images(array):
roi_L = np.s_[:,:,175:1609,17:1649]
roi_R = np.s_[:,:,175:1609,3319:4951]
return array[roi_L], array[roi_R] | |
005c0e9e2ca7d6b43c79 | def create_coco_lists(
ids_list,
image_dir,
annotations_dir,
category_mapper,
categories_to_use):
images_list = []
annotations_list = []
count = 0
for image_id in ids_list:
image = cv2.imread(os.path.join(image_dir, image_id) + '.png')
images_lis... | |
005c1ec17e34570e6e93 | def get_aic(self, second_order=False):
if second_order:
sequence_length = sum(
len(self.get_param_value("lht", locus=l).index)
for l in self.locus_names
)
else:
sequence_length = None
lnL = self.get_log_likelihood()
nfp... | |
005c4a0010c7be840e48 | def fromName(cls, conn, pool, name):
instdir = model.InstanceDirectory()
instance = instdir.get(name)
return cls(conn=conn, pool=pool, name=name, data=instance) | |
005c4dbe240906e64030 | def get_file_iterator(path: str, *args, **kwargs) -> Iterator[str]:
with open(path, *args, **kwargs) as file:
for line in file:
yield line | |
005c7cefb8b6b1444de7 | def getList(self) -> [NestedInteger]:
pass | |
005ca2a58ec9822c5348 | def previous_top_stories():
tops = db.top_stories.find_one()
return tops['top'] if tops is not None else [] | |
005cee4b1ff7dc3c6adb | def test_cub_file_creation(self):
os.system("rm dagmc.cub")
cad_to_h5m(
files_with_tags=[
{
"cad_filename": "tests/blanket.stp",
"material_tag": "mat1",
}
],
cubit_filename="dagmc.cub",
... | |
005ceec7cdeb224cd117 | def obj_last_period(d,x,par):
# implied consumption (rest)
c = x-d
return -utility.func(c,d,par) | |
005d14d897fe9ac06391 | def __init__(self, layers, activation=F.relu):
super(MLP, self).__init__()
self.layers = []
self.activation = activation
self.eta = torch.nn.Parameter(Tensor([1]))
for i in range(len(layers)-1):
self.layers.append(torch.nn.Linear(layers[i], layers[i+1]))
self.... | |
005d25bd730df93e0325 | def _flush(self):
updates = self.documents['updates']
inserts = self.documents['inserts']
lookups = {}
# check all insert documents for a 'unique attr' that will allow us
# to search the db for possible duplicates
for document in inserts:
unique = getattr(docu... | |
005d6b6f39d2192bf69e | def login(user_name, user_password):
pass | |
005da9ef026e9f9d67d8 | def speedFactor(self):
return self.__speedFactor | |
005dc9e06453bcee36ef | def __update_left_right(self):
left = self.left_widget.convert_scene_to_numpy_array()
right = self.right_widget.convert_scene_to_numpy_array()
self.left_rescaled = cv2.resize(left, (0, 0), fx=1, fy=0.5)
self.right_rescaled = cv2.resize(right, (0, 0), fx=1, fy=0.5) | |
005de74250fdf29045c8 | def dequeue(self):
with self.__lock__:
return self.__queue__.get() | |
005e0546790e38d1f129 | def add_dpdk_dev_default_rxq(self, value):
path = [u"dpdk", u"dev default", u"num-rx-queues"]
self.add_config_item(self._nodeconfig, value, path) | |
005e1401bbd6956fa8fe | async def up(self, ctx: commands.Context):
send_embed = await self.set_server_state(ctx, True)
if send_embed:
embed = discord.Embed(
title=f"{ctx.author.display_name} has fired up the server!",
colour=discord.Colour.green(),
)
embed.set... | |
005e1aacb108b8156e89 | def create_global_pooling_model(input_size: Tuple[int, ...]) -> Tuple[Union[tf.Tensor, List[tf.Tensor]], tf.Tensor]:
input_cont = keras.Input((2,))
input_conv = keras.Input(input_size)
conv1 = layers.Conv1D(128, kernel_size=10, strides=10, activation='relu')(input_conv)
bn1 = layers.BatchNormalization(... | |
005e843da40c227c694a | def culaDeviceSgeTransposeInplace(n, A, lda):
status = _libcula.culaDeviceSgeTransposeInplace(n, int(A), lda)
culaCheckStatus(status) | |
005e88f49cb0a35982d2 | def v3_listDomainUserRoles(request):
pass | |
005e8ee29c75884ffd52 | def run(cmd, raise_on_err=True, capture=False, **kwargs):
pipe = PIPE if capture else None
proc = Popen(cmd, stdout=pipe, stderr=pipe, **kwargs)
out, err = map(
lambda x: x if x is None else x.decode('utf-8'),
proc.communicate()
)
if raise_on_err and proc.returncode:
raise Ca... | |
005e93c635c7c8221b08 | def _get_students(self, path):
for cwid, name, major in file_reader(path, 3, sep='\t', header=True):
if major not in self._majors:
print(f"Student {cwid} '{name}' has unknown major '{major}'")
else:
self._students[cwid] = Student(cwid, name, self._majors[m... | |
005eac966cc743645e7e | def remove_redundant_data(self):
"""
idx = 1 # Loop through entire gps_data
gps_data_copy = []
prev_angle = self.gps_data[0]["formatted"]["angle"] # Note the first angle seen in GPS
gps_data_copy.append(self.gps_data[0]) # Append the first point to GPS Copy
... | |
005eb975ed1a858cc55f | def latest_version(self) -> str | None:
if self._avm_wrapper.update_available:
return self._avm_wrapper.latest_firmware
return self._avm_wrapper.current_firmware | |
005ed306136535ed2b9f | def test_swap_k_example_3(self):
actual = a1.swap_k([1,2] ,1)
expected = [2,1]
self.assertEqual(expected, actual) | |
005ee5908a1b7efab048 | def get_transition(self, input_symbol, state):
return self.state_transitions.get((input_symbol, state)) | |
005efbbfb6f772a93891 | def update_params(layers, param_grads, learning_rate):
for layer, layer_backprop_grads in zip(layers, param_grads):
for param, grad in zip(layer.get_params_iter(), layer_backprop_grads):
# The parameter returned by the iterator point to the memory space of
# the original layer and c... | |
005f1ea8f1292d4b5a1a | def is_member_suggestions_change_policy(self):
return self._tag == 'member_suggestions_change_policy' | |
005f234984ea21c346b9 | def add_message_callback(self,topic,callback):
self.client.message_callback_add(topic, callback) | |
005f487344a374d2b9a4 | def setStation(self, station):
if self.currentStation == station:
return
self.currentStation = station
self.upcomingSongs = []
self.playedSongs = []
return (self.clearPandoraTailSongs()
.addCallback(lambda _: self.startNewStation())) | |
005f68eb1150bc78cd98 | def dependency(self):
if self.__dependency is None:
self.__dependency = dependency.DependencyManager(os.path.join(
self.path['local']['target'],
'dependency'
))
return self.__dependency | |
005f80bb6d8f7c144051 | def save(self):
new_cp = {}
for key in FileStorage.__objects.keys():
if type(FileStorage.__objects[key]) is not dict:
my_dict = FileStorage.__objects[key].to_json()
new_cp.update({key: my_dict})
else:
new_cp.update({key: my_dict[key... | |
005f86713818a7836818 | def clear_segment_markers(self):
if self.segment_list:
for s in self.segment_list:
s.clear_markers() | |
005fcb3e68366f2bbd8c | def all_constant_input(node):
if node.proto is None:
return False
isConstant = True
for parent in node.parents:
if parent.proto is None or parent.proto.op_type != 'Constant':
isConstant = False
break
return isConstant | |
005fd35da47d013d8ff3 | def __init__(self, fmt=DEFAULT_FORMAT, colors=DEFAULT_COLORS):
assert isinstance(fmt, str)
assert isinstance(colors, dict)
logging.Formatter.__init__(self)
self.fmt = fmt
if colors and colorama:
self.colors = {levelno: colors[levelno] for levelno in colors}
... | |
005ff3b05fffc578e0fb | def before_update(self, actor, algo):
pass | |
006004408681b86399e3 | def activation(status, client_id=None, pin_number=None):
from setting.models import Client
data = {
"is_activated": status
}
client = Client.objects.get(id=client_id)
url = "http://{0}/api/gpio/update/{1}/".format(client.ip_address, pin_number)
log.info("PREPARE to activate modul with p... | |
00603554c9c494a701b4 | def init_model(engine):
DBSession.configure(bind=engine) | |
0060443c9a8b690c7542 | def nodeFromSection(self, section, lang="en"):
sTypes = self.sectionTypes
if len(sTypes) == 0:
return None
(sec1, sec2) = self.api.C.sections.data
sec0node = self._sec0Node(section[0], lang=lang)
if len(section) == 1:
return sec0node
elif len(sect... | |
00605766e0248513fddf | def _get_monthly_contribution_amount(salary: float,
bonus: float,
age: int,
entity: str) -> float:
logger.info(f'_get_monthly_contribution_amount() - salary {round(salary, 2)}; bonus {round(bonus, 2)}... | |
00609345316d83cebe8c | async def poll_top_weekly_posts(self) -> None:
while True:
now = datetime.utcnow()
# Calculate the amount of seconds until midnight next monday.
monday = now + timedelta(days=7 - now.weekday())
monday = monday.replace(hour=0, minute=0, second=0)
until... | |
0060b1bbc73e01706b52 | def label(graph, hi_thres, med_thres):
extended_deg_size = hi_thres
hi_pairs = get_hi_pairs(graph, hi_thres, extended_deg_size)
sorted_hi_nodes = [x[0] for x in hi_pairs]
med_pairs = get_med_pairs(graph, med_thres, hi_thres, sorted_hi_nodes)
return (hi_pairs, med_pairs) | |
0060bfd4aa1c37c4bf5f | def fixed_padding(inputs, kernel_size):
pad_total = kernel_size - 1
pad_beg = pad_total // 2
pad_end = pad_total - pad_beg
padded_inputs = tf.pad(inputs,
[[0, 0], [0, 0], [pad_beg, pad_end], [pad_beg, pad_end]])
return padded_inputs | |
0060e3248c573cf2a88f | def clear_cache(self) -> None:
self.data_cache = {}
self.last_len = -1 | |
0060e4e486a1be8755a6 | def copy_network(self,net):
n,h,fo = net.get_topology()
self.__init__(n,h,fo)
self.set_input_matrix(net.get_input_matrix())
self.set_bias(net.get_bias())
b,b0 = net.get_betas()
self.set_betas(b,b0)
self.set_min_max(net.get_min(),net.get_max()) | |
0060f0a995afe4728cda | def pltView(locs, haloPos, size=10, indx=0, ax=None, Z=None, s=40):
if not ax:
fig = plt.figure(figsize=(8, 8))
ax = fig.gca()
else:
fig = plt.gcf()
# Plot the center location
# ax.scatter(
# haloPos[0], haloPos[1], s=120, facecolors="none", edgecolors="r"
# ) # Plot... | |
0060fb4ae1c32beb5f3d | def accept(self, data): | |
00612ab4346dbfd1c15c | def __getitem__(self, idx):
if idx > len(self):
raise IndexError("idx:{} >= max_idx:{}".format(idx, len(self)))
return self.leaf_nodes[idx] | |
00613538af5b98eb2622 | def parse_payload_01(self, data):
if len(data) != 12:
return False
return self.parse_by_format(data, [
# function, start byte, end byte
( "seq", self.parse_number, 1, 2 ),
( "batt", self.parse_batt, 2, 3 ),
( "w_pressure", self.... | |
006137d93edd2c350f15 | def hash_function_strings(string, max):
return hash(string) % max | |
00613a291af9a14d0107 | def letters2Syllables( letters ):
syllables = []
syllableSegments = []
nbConsonants = 0
consonantDuration = 0
vowelDuration = 0
for label, segment in letters :
#skip all plosives
if label == "P": continue
syllableSegments.append(segment)
#if consonant
if label == "C" :
nbConsonants += 1... | |
00613baf0e5b87f959e4 | def get_paths(target):
full_path = os.path.abspath(target)
if os.path.isdir(full_path):
import glob
file_listing = glob.glob("{}/**".format(full_path), recursive=True)
file_listing.pop(0)
return [ this_file for this_file in file_listing if os.path.isfile(this_file) ]
if no... | |
00616055b895a129b1d8 | def public(self, public):
self._public = public | |
006162e4e33d692ff3ab | def checkValidFileName(self, name, num):
NAME_MAX=50 # allowed filename length
defname = "img%d.png" % num # default name made from line number
strip_name = os.path.basename(name) # strip / and . from the front
length = len(strip_name)
if leng... | |
00617f0ec945e7b0b7ca | def get(self):
if not g.token.has_access('master'):
return {'error': 'Not allowed'}, 401
return {'success': True, 'results': mongo.db.reset_requests.find({}, {'_id': 0})} | |
006180413bd7613a92ce | def dataset_from_tfrcord(tfrecord_lst, num_processors=8):
dataset = tf.data.TFRecordDataset(tfrecord_lst)
dataset = dataset.map(_parse_function, num_processors)
return dataset | |
0061bf86df6c5fee72df | def isPositionInRoom(self, pos):
xPos = pos.getX()
yPos = pos.getY()
if (0 <= xPos < self.width) and (0 <= yPos < self.height):
return True
else:
return False | |
0061bfefaeaaff1ef5b8 | def is_param(name):
if name == 'data':
return False
if name.endswith('weight'):
return True
if name.endswith('bias'):
return True
if name.endswith('beta'):
return True
if name.endswith('gamma'):
return True
return False | |
0061d3a021d86ef4a7cd | def test_problems():
with pytest.raises(ValueError):
check_version('', '<1.0.0')
with pytest.raises(ValueError):
check_version('1.0.0', '')
with pytest.raises(packaging.version.InvalidVersion):
check_version('very bad version', '<1.0.0')
with pytest.raises(packaging.version.In... | |
0061fe021f845d4af4ae | def getFields(jclass):
return jclass.class_.getFields()[:] | |
00621ad52d6f71213d07 | def projection_matrix(camera_parameters, homography):
# Compute rotation along the x and y axis as well as the translation
homography = homography * (-1)
rot_and_transl = np.dot(np.linalg.inv(camera_parameters), homography)
col_1 = rot_and_transl[:, 0]
col_2 = rot_and_transl[:, 1]
col_3 = rot_an... | |
006225de060fea62a472 | def _env(env):
return env if os.getenv(env) else '' | |
0062622bc0ddb2bdc330 | def get_gateway_conf():
with open('conf/gateway.json') as f:
return json.load(f) | |
0062b9340fdfe712275f | def init() :
tt.up()
tt.left(180)
tt.forward(275)
tt.right(180)
tt.down() | |
0062ef867808940fbe17 | def main_method(self):
sample_option = input(
"Your text input method. Either a local text file (\"file\")\nor a string sequence as input (\"input\").\n\tType str: ")
if sample_option == "file":
self.sample_from_file()
elif sample_option == "input":
self.sampl... | |
0062fdc357e42c628ef4 | def test_get_movies_with_no_content(self):
delete_req = self.request_delete(path=CONSTANTS["V1_MOVIE_API"])
status_code = delete_req.status_code
self.assertEqual(204, status_code)
get_req = self.request_get(path=CONSTANTS["V1_MOVIE_API"])
status_code = get_req.status_code
... | |
0062ff7508a7b1acfefb | def draw_road(self) -> None:
self.obstacle_generator.generate(self.obstacles, self.way_segments)
for i in range(c.WAY_SEGMENT_FIRST, c.WAY_SEGMENT_LAST):
if self.way_segments[i].y > c.WINDOW_HEIGHT:
self.way_segments[i] = WaySegment.WaySegment(-c.WAY_LENGTH, self.map.get_ne... | |
006305a155b2ba767b17 | def record():
p = pyaudio.PyAudio() #create stream
stream = p.open(format=FORMAT, channels=1, rate=RATE,
input=True, output=True,
frames_per_buffer=CHUNK_SIZE) #open stream
#init vars
num_silent = 0
snd_started = False
#init recording array
r = array('h')
while 1: #Loop until break
# little endian, s... | |
00631ef59bc319b3fa46 | def update_sigma(self, iter):
self.sigma = self.startSigma * np.exp(-iter/self.tau); | |
006328a4fe99ffc6b7b2 | def _AddMockJSONResponse(self, mock_client, url, response_dict):
def _CreateResponse(request):
return httpclient.HTTPResponse(request, 200,
headers={'Content-Type': 'application/json'},
buffer=StringIO(json.dumps(response_dict)))
... | |
00633cb0455a22c3f804 | def get_temp(runopts):
if runopts.faket:
return 24
run = True
while run:
try:
with Lepton("/dev/spidev0.1") as l:
data,_ = l.capture(retry_limit = 3)
if l is not None:
Ts = NP.amax(data) / 100 - 273;
for line in data:
l = len(line)
if (l ... | |
00635ae312f8f9212f67 | def unicode2str(s):
return s | |
00635e145ce412dd111a | def get_genotypes(gatk_vcf_file, smt_vcf_file) :
stderr.write(timestamper() + " Getting genotypes from GATK VCf file %s\n" %(gatk_vcf_file))
samples = []
variants_dict = {}
num_variants = 0
fGATK = open(gatk_vcf_file, 'r')
for line in fGATK :
if line.startswith('#') :
if line.startswith("#CHROM") :
samp... | |
006365f7eee755e48961 | def sentiments(text):
result = []
for tweet in text:
score = SentimentIntensityAnalyzer().polarity_scores(tweet)
result.append(score)
return result | |
00636bd62f4d536178aa | def _serialize(self, obj: object) -> bytes:
pb: Message = serialize(obj) # type: ignore
return pb.SerializeToString() | |
00637524830e31bc63f3 | def solve(self):
# Solve the velocity-density system
with timed_region("Gusto:VelocityDensitySolve"):
# Assemble the RHS for lambda into self.R
with timed_region("Gusto:HybridRHS"):
self._assemble_Rexp()
# Solve for lambda
with timed_reg... | |
00637b344f22db8c90af | def calculate_rmse(input_seq_length, number_units, number_epochs, batch_size):
model_filename = BASE_MODEL_FILENAME + '_' + str(input_seq_length) + '_' + str(number_units) + '_' + \
str(number_epochs) + '_' + str(batch_size) + '.h5'
X_train, y_train, X_test, y_test = data_preprocessor.prep... | |
0063914e6535719f38a7 | def showpoint(surface_point , T_obj_world=RigidTransform(from_frame='obj', to_frame='world'),color=(0.5,0.5,0),scale=0.001):
surface_point = Point(surface_point, 'obj')
surface_point_tf = T_obj_world.apply(surface_point)
#center_tf = T_obj_world.apply(center)
Visualizer3D.p... | |
00639154fad04fb78520 | def add_class(teacher, class_name):
new_class = Class(class_name=class_name)
db.session.add(new_class)
db.session.commit()
new_class.users.append(teacher)
db.session.commit()
return new_class.class_id |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.