file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
dicer.py
2, cv2.LINE_AA) pos_img = np.zeros(shape=[100, 100, 1], dtype=np.uint8) cv2.imshow('Press any key to exit', grey) print('Error - stopping') cv2.waitKey() # Taste drücken, zum beenden elif GPIO.input(18) == 0 and gpios == True: # Temperaturreais prüfen wenn RPi vorhanden print('Temperature relay is...
or i in range(5): ret, frame = cap.read() #cv2.imwrite('frame.png',frame) # Bildausschnitte von Würfel und Positionserkennung y = 160 h = 240 x = 220 w = 240 dice_image = frame[y:y + h, x:x + w] grey = cv2.cvtColor(dice_image, cv2.COLOR_BGR2GRAY) #cv2.imshow('input', grey)...
s(): f
identifier_name
dicer.py
ptime): GPIO.output(17, GPIO.LOW) GPIO.output(4, GPIO.HIGH) time.sleep(steptime) GPIO.output(4, GPIO.LOW) time.sleep(steptime) def step_minus(steptime): GPIO.output(17, GPIO.HIGH) GPIO.output(4, GPIO.HIGH) time.sleep(steptime) GPIO.output(4, GPIO.LOW) time.sleep(steptime) G...
two = all_numbers[1] three = all_numbers[2] four = all_numbers[3] five = all_numbers[4] six = all_numbers[5] errorcnt = all_numbers[6] success_rolls= all_numbers[7] detector = cv2.SimpleBlobDetector_create(blob_params) keypoints = detector.detect(image) img_with_keypoints = cv2....
identifier_body
dicer.py
log_name = 'log_seite2' # Name der Log Datei (Zusammenfassung der Messreihe): Wird NICHT fortgesetzt raw_numbers_name = 'raw_seite2' # Name der Datei, in der alle Würfe einzeln gespeichert werden: Wird fortgesetzt email_header = 'dicer - seite2' # Emailbetreff darknumbers = False # Dunkle Würfelaugen? send_email = ...
random_line_split
repository.go
Requested record was not found") type conflictErr struct { IDs []string } func (e conflictErr) Error() string { return fmt.Sprintf("Operation failed due to conflicts with: %s", e.IDs) } type repository struct { db *sqlx.DB closers []io.Closer listMoodsAsc, listMoodsDesc, findMood, deleteMood, setMood ...
} var rec moodRec err := r.findMood.Get(&rec, struct{ UserID, Name string }{userID, name}) if err == sql.ErrNoRows { return nil, nil } else if err != nil { return nil, fmt.Errorf("getting user mood: %v", err) } rec.UserDefined = true rec.id = rec.IntID return &rec.Mood, nil } func (r *repository) SetMo...
{ // Copy to prevent modifying builtins by the caller mood := *builtin return &mood, nil }
conditional_block
repository.go
) error { if isBuiltin(mood.Name) { return errBuiltinMood } var id int err := r.setMood.QueryRow(struct { UserID, Name, Eyes, Tongue string }{ userID, mood.Name, mood.Eyes, mood.Tongue, }).Scan(&id) if err != nil { return fmt.Errorf("upserting user mood: %v", err) } if id == 0 { return fmt.Errorf("u...
sortAsc
identifier_name
repository.go
ood(userID string, mood *Mood) error { if isBuiltin(mood.Name) { return errBuiltinMood } var id int err := r.setMood.QueryRow(struct { UserID, Name, Eyes, Tongue string }{ userID, mood.Name, mood.Eyes, mood.Tongue, }).Scan(&id) if err != nil { return fmt.Errorf("upserting user mood: %v", err) } if id ...
random_line_split
repository.go
}, {"borg", "==", " ", false, 0}, {"dead", "xx", "U ", false, 0}, {"greedy", "$$", " ", false, 0}, {"stoned", "**", "U ", false, 0}, {"tired", "--", " ", false, 0}, {"wired", "OO", " ", false, 0}, {"young", "..", " ", false, 0}, } type moodRec struct { IntID int Mood } type lineRec struct { Eyes, Tongu...
{ if isBuiltin(name) { return errBuiltinMood } queryArgs := struct{ UserID, Name string }{userID, name} if err := doDelete(r.deleteMood, queryArgs); err != nil { if dbErr, ok := err.(*pq.Error); !ok || dbErr.Code != dbErrFKViolation { return err } // List the lines that are preventing us from deleting ...
identifier_body
The Movies Database.py
#tmdb_movies = sc.textFile('tmdb_5000_movies.csv') tmdb_movies = sc.textFile(sys.argv[1], 1) #Remove header and split data header = tmdb_movies.first() #Split by , followed by non-whitespace regex = re.compile(',(?=\\S)') tmdb_movies = tmdb_movies.filter(lambda x: x != header).map(lambda x: regex.split(x)) print('N...
if (float(p[0])>0 and float(p[8])>0 and float(p[12])>0 and float(p[13])>0 and float(p[18])>0): if (len(p[1])>2 and len(p[9])>2): return p
conditional_block
The Movies Database.py
2]), # Profit(x[12]-x[0]), Runtime(x[13]), Average Rating(x[18])) tmdb_movies_filtered = tmdb_movies_filtered.map(lambda x: (x[6], float(x[0]), genre(x[1]), float(x[8]), datetime.strptime(x[11], '%Y-%m-%d'), ...
# Revenue(x[5]) # Profit (x[6]) # Runtime(x[7]) # Average Rating(x[8]) ## Top 10 Most Profitable Movie Titles profit_title = tmdb_movies_filtered.map(lambda x: (x[0], x[6])).\ reduceByKey(add) profit_title_top = profit_title.top(20, lambda x: x[1]) print('Titles sorted based on Pro...
# Popularity(x[3]) # Release Date(x[4])
random_line_split
The Movies Database.py
x[1], (x[0], 1))).\ reduceByKey(lambda x,y: (x[0]+y[0], x[1]+y[1])).\ map(lambda x: (x[0], round(x[1][0]/x[1][1],2))) avgRating_genre_top = avgRating_genre.top(20, lambda x: x[1]) print('Genres sorted based on Average Rating:', avgRating_genre_top) x = [i[0] for i in avgRating_g...
return LabeledPoint(line[0], line[1])
identifier_body
The Movies Database.py
flatMapValues(lambda x: x).\ map(lambda x: (x[1], (x[0], 1))).\ reduceByKey(lambda x,y: (x[0]+y[0], x[1]+y[1])).\ map(lambda x: (x[0], round(x[1][0]/x[1][1],2))) avgRating_genre_top = avgRating_genre.top(20, lambda x: x[1]) print('Genres sorted based on Averag...
parsePoint
identifier_name
network.py
stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setFormatter(formatter) logger.addHandler(stdout_handler) def train_emnist(u_epochs): ####################################################### ################### Network setup ##################### # batch_size - Number of images given to ...
trainData = trainData.astype("float32") testData = testData.astype("float32") trainData /= 255 testData /= 255 logger.debug("[INFO] after re-shape") # print new shape logger.debug("[INFO] train data shape: {}".format(trainData.shape)) logger.debug("[INFO] test data shape: {}".format(t...
epochs = u_epochs n_classes = 62 batch_size = 256 train_size = 697932 test_size = 116323 v_length = 784 # split the emnist data into train and test trainData, trainLabels = emnist.extract_training_samples('byclass') testData, testLabels = emnist.extract_test_samples('byclass') # p...
identifier_body
network.py
stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setFormatter(formatter) logger.addHandler(stdout_handler) def
(u_epochs): ####################################################### ################### Network setup ##################### # batch_size - Number of images given to the model at a particular instance # v_length - Dimension of flattened input image size i.e. if input image size is [28x28], then v_length...
train_emnist
identifier_name
network.py
verbose=2) # print the history keys logger.debug(history.history.keys()) # evaluate the model scores = model.evaluate(testData, mTestLabels, verbose=0) # history plot for accuracy plt.plot(history.history["accuracy"]) plt.plot(history.history["val_accuracy"]) plt.title("Model Ac...
original_img = test_image # reshape the test image to [1x784] format so that our model understands test_image = test_image.reshape(1, 784) # make prediction on test image using our trained model prediction = model.predict_classes(test_image, verbose=0) plate_pre...
conditional_block
network.py
stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setFormatter(formatter) logger.addHandler(stdout_handler) def train_emnist(u_epochs): ####################################################### ################### Network setup ##################### # batch_size - Number of images given to ...
# params: 1- mlmodel, 2- root path to the prediction imgs, 3- how many imgs we have in imgs_path def identify_plate(model, imgs_path, test_size): # EMNIST output infos as numbers, so I created a label dict, so it will output it respective class label_value = {'0':'0', '1':'1', '2':'2', '3':'3', '4':'4', '5':'
plt.subplot(220+i) plt.imshow(org_image, cmap=plt.get_cmap('gray')) logger.debug('Press Q to close') plt.show()
random_line_split
HOG_SVM_FaceDetection.py
detector was trained. If you are building a webcam or selfie application that uses face detection, you can significantly improve speed by resizing the image to the appropriate size. # # ## <font style = "color:rgb(50,120,229)">Classifying a patch</font> # # From the previous subsection, we know many patches of the...
der, classLabel): #change image sizes to match width = 128 height = 128 dim = (width, height) images = [] labels = [] imagePaths = getImagePaths(folder, ['.jpg', '.png', '.jpeg']) for imagePath in imagePaths: # print(imagePath) im = cv2.imread(imagePath, cv2.IMREAD_COLOR) resized = cv2.re...
ataset(fol
identifier_name
HOG_SVM_FaceDetection.py
this is a good idea. # In[158]: # ================================ Query Model ============================================= # Run object detector on a query image to find pedestrians # We will load the model again and test the model # This is just to explain how to load an SVM model # You can use the model directl...
# # 1. [https://lear.inrialpes.fr/people/triggs/pubs/Dalal-cvpr05.pdf](https://lear.inrialpes.fr/people/triggs/pubs/Dalal-cvpr05.pdf) # # 3. [https://en.wikipedia.org/wiki/Support_vector_machine](https://en.wikipedia.org/wiki/Support_vector_machine)
random_line_split
HOG_SVM_FaceDetection.py
object detector was trained. If you are building a webcam or selfie application that uses face detection, you can significantly improve speed by resizing the image to the appropriate size. # # ## <font style = "color:rgb(50,120,229)">Classifying a patch</font> # # From the previous subsection, we know many patches...
eturn imagePaths #change image sizes to match width = 128 height = 128 dim = (width, height) # read images in a folder # return list of images and labels def getDataset(folder, classLabel): #change image sizes to match width = 128 height = 128 dim = (width, height) images = [] labels = [] imagePaths ...
h = os.path.join(folder, x) if os.path.splitext(xPath)[1] in imgExts: imagePaths.append(xPath) r
conditional_block
HOG_SVM_FaceDetection.py
object detector was trained. If you are building a webcam or selfie application that uses face detection, you can significantly improve speed by resizing the image to the appropriate size. # # ## <font style = "color:rgb(50,120,229)">Classifying a patch</font> # # From the previous subsection, we know many patches...
redict labels for given samples def svmPredict(model, samples): return model.predict(samples)[1] # evaluate a model by comparing # predicted labels and ground truth def svmEvaluate(model, samples, labels): labels = labels[:, np.newaxis] pred = model.predict(samples)[1] correct = np.sum((labels == pred)) err...
train(samples, cv2.ml.ROW_SAMPLE, labels) # p
identifier_body
cli.py
publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PR...
expose_value=False, is_eager=True) @click.option('--license', '--lic', is_flag=True, callback=show_license, expose_value=False, is_eager=True) def cli(): """ 🗲 Zap: A command line interface to install appimages""" pass @cli.command('install') @click.argument('appname') @click.opti...
ctx.exit() @click.group() @click.option('--version', is_flag=True, callback=show_version,
random_line_split
cli.py
publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PR...
elif p_url.netloc == 'remove': z.remove() else: print("Invalid url") @cli.command() @click.argument('appname') def get_md5(appname): """Get md5 of an appimage""" z = Zap(appname) z.get_md5() @cli.command() @click.argument('appname') def is_integrated(appname): """Checks if appi...
nt(tag, asset_id) z.install(tag_name=tag, download_file_in_tag=asset_id, downloader=gtk_zap_downloader, always_proceed=True)
conditional_block
cli.py
publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PR...
"""Upgrade all appimages using AppImageUpdate""" config = ConfigManager() apps = config['apps'] for i, app in progressbar(enumerate(apps), redirect_stdout=True): z = Zap(app) if i == 0: z.update(show_spinner=False) else: z.update(check_appimage_update=Fal...
rade():
identifier_name
cli.py
publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PR...
@cli.command() @click.argument('appname') def is_integrated(appname): """Checks if appimage is integrated with the desktop""" z = Zap(appname) z.is_integrated() @cli.command('list') def ls(): """Lists all the appimages""" cfgmgr = ConfigManager() apps = cfgmgr['apps'] for i in apps: ...
Get md5 of an appimage""" z = Zap(appname) z.get_md5()
identifier_body
cmpH5Sort.py
keys() for x in alnGroups] uPulseDatasets = reduce(lambda x,y: set.union(set(x), set(y)), pulseDatasets) if (not all(map(lambda x : set(x) == uPulseDatasets, pulseDatasets))): log.error("All alignment groups need to have the same datasets.") raise Exception("Can only repack cmp.h5 files with con...
def write(self, msg, level): if (self.level >= level): sys.stderr.write(str(msg) + "\n
self.level = level
identifier_body
cmpH5Sort.py
keys() for x in alnGroups] uPulseDatasets = reduce(lambda x,y: set.union(set(x), set(y)), pulseDatasets) if (not all(map(lambda x : set(x) == uPulseDatasets, pulseDatasets))): log.error("All alignment groups need to have the same datasets.") raise Exception("Can only repack cmp.h5 files with con...
(inFile, outFile, deep, jobs, log): """ This routine takes a cmp.h5 file and sorts the AlignmentIndex table adding two additional columns for fast access. In addition, a new top-level attribute is added to the indicate that the file has been sorted, as well as a table to indicate the blocks of the ...
sortCmpH5
identifier_name
cmpH5Sort.py
End = currentStart, currentStart + totalSizes[readIdx] newDS[gStart:gEnd] = getDataset(read, pulseDataset)[read[format.OFFSET_BEGIN]:read[format.OFFSET_END]] currentStart = gEnd + 1 newGroup.create_dataset(pulseDataset, data = newDS, dtype = uPDAndType[pulseDataset], maxshape...
cmpH5 = CmpH5Factory.factory.create(outfile, 'a') cmpH5.log("cmpH5Sort.py", __VERSION__, str(datetime.datetime.now()), ' '.join(sys.argv), "Sorting") cmpH5.close() if (len(args) < 2): shutil.copyfile(outfile, infile) ofile.close() exit(0)
conditional_block
cmpH5Sort.py
keys() for x in alnGroups] uPulseDatasets = reduce(lambda x,y: set.union(set(x), set(y)), pulseDatasets) if (not all(map(lambda x : set(x) == uPulseDatasets, pulseDatasets))): log.error("All alignment groups need to have the same datasets.") raise Exception("Can only repack cmp.h5 files with con...
## Don't really have to do anything if there are no references ## which aligned. if (lRow == fRow): continue ## Make a new Group. newGroup = getRefGroup(offsets[row, 0]).create_group(SORTED) log.msg("Created new read group: %s" % SORTED) ## Go throu...
fRow = int(offsets[row, 1]) lRow = int(offsets[row, 2])
random_line_split
main.rs
impl TypeMapKey for db::MyDbContext { type Value = db::MyDbContext; } impl TypeMapKey for autopanic::Gramma { type Value = autopanic::Gramma; } struct Handler; #[async_trait] impl EventHandler for Handler { async fn guild_create(&self, ctx: Context, guild: Guild, is_new: bool) { let mut data = ct...
(ctx: &Context, msg: &Message, error: DispatchError) { if let DispatchError::Ratelimited(info) = error { // We notify them only once. if info.is_first_try { let _ = msg .channel_id .say( &ctx.http, &format!("Try this...
dispatch_error
identifier_name
main.rs
impl TypeMapKey for db::MyDbContext { type Value = db::MyDbContext; } impl TypeMapKey for autopanic::Gramma { type Value = autopanic::Gramma; } struct Handler; #[async_trait] impl EventHandler for Handler { async fn guild_create(&self, ctx: Context, guild: Guild, is_new: bool) { let mut data = ct...
else { Some(out) } } async fn greet_new_guild(ctx: &Context, guild: &Guild) { println!("h"); if let Some(channelvec) = better_default_channel(guild, UserId(802019556801511424_u64)).await { println!("i"); for channel in channelvec { println!("{}", channel.name); ...
{ None }
conditional_block
main.rs
impl TypeMapKey for db::MyDbContext { type Value = db::MyDbContext; } impl TypeMapKey for autopanic::Gramma { type Value = autopanic::Gramma; } struct Handler; #[async_trait] impl EventHandler for Handler { async fn guild_create(&self, ctx: Context, guild: Guild, is_new: bool) { let mut data = ct...
pub async fn better_default_channel(guild: &Guild, uid: UserId) -> Option<Vec<&GuildChannel>> { let member = guild.members.get(&uid)?; let mut out = vec![]; for channel in guild.channels.values() { if channel.kind == ChannelType::Text && guild .user_permissions_in(channe...
random_line_split
charisma.js
+ '<p><b>消息内容:</b>' + obj.guid + '</p>' + content; $('#confirm #txt').html(content); url = js_getEntry(_project_title, 'Message', 'ajaxdel?guid=' + id); $('#confirm #btn-submit').attr('data-url', url); }); $('#confirm #btn-submit').live('click', function(e){ e.preventDefault(); url = $...
'span10'); } //highlight current / active link $('ul.main-menu li a').each(function(){ if($($(this))[0].href==String(window.location)) $(this).parent().addClass('active'); }); //establish history variables var History = window.History, // Note: We are using a capital H instead of a lower h State...
removeClass(
identifier_name
charisma.js
i += 1) d1.push([i, parseInt(Math.random() * 30)]); var d2 = []; for (var i = 0; i <= 10; i += 1) d2.push([i, parseInt(Math.random() * 30)]); var d3 = []; for (var i = 0; i <= 10; i += 1) d3.push([i, parseInt(Math.random() * 30)]); var stack = 0, bars = true, lines = false, steps = false; funct...
} if ( oPaging.iPage === oPaging.iTotalPages-1 || oPaging.iTotalPages === 0 ) { $('li:last', an[i]).addClass('disabled'); } else {
random_line_split
charisma.js
}); $('#addBoard').click(function(e){ e.preventDefault(); $('#myModal1').modal('show'); }); $('#addServer').click(function(e){ e.preventDefault(); $('#myModal2').modal('show'); }); $('.modifyBoard').click(function(e){ e.preventDefault(); var srctxt = $(this).attr('data-json'); var txt = '[' +...
} // we use an inline data source in the example, usually data would // be fetched from a server var data = [], totalPoints = 300; function getRandomData() { if (data.length > 0) data = data.slice(1);
identifier_body
api_op_CreateRoute.go
192.0.2.3 , and the route table includes the following two IPv4 // routes: // - 192.0.2.0/24 (goes to some target A) // - 192.0.2.0/28 (goes to some target B) // // Both routes apply to the traffic destined for 192.0.2.3 . However, the second // route in the list covers a smaller number of IP addresses and is ther...
func (m *opCreateRouteResolveEndpointMiddleware) HandleSerialize(ctx context.Context, in middleware.SerializeInput, next middleware.SerializeHandler) ( out middleware.SerializeOutput, metadata middleware.Metadata, err error, ) { if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { return next.HandleSerialize(ctx, i...
{ return "ResolveEndpointV2" }
identifier_body
api_op_CreateRoute.go
address 192.0.2.3 , and the route table includes the following two IPv4 // routes: // - 192.0.2.0/24 (goes to some target A) // - 192.0.2.0/28 (goes to some target B) // // Both routes apply to the traffic destined for 192.0.2.3 . However, the second // route in the list covers a smaller number of IP addresses and...
for k := range resolvedEndpoint.Headers { req.Header.Set( k, resolvedEndpoint.Headers.Get(k), ) } authSchemes, err := internalauth.GetAuthenticationSchemes(&resolvedEndpoint.Properties) if err != nil { var nfe *internalauth.NoAuthenticationSchemesFoundError if errors.As(err, &nfe) { // if no auth ...
req.URL = &resolvedEndpoint.URI
random_line_split
api_op_CreateRoute.go
192.0.2.3 , and the route table includes the following two IPv4 // routes: // - 192.0.2.0/24 (goes to some target A) // - 192.0.2.0/28 (goes to some target B) // // Both routes apply to the traffic destined for 192.0.2.3 . However, the second // route in the list covers a smaller number of IP addresses and is ther...
else { signingName = *v4Scheme.Sign
{ signingName = "ec2" }
conditional_block
api_op_CreateRoute.go
192.0.2.3 , and the route table includes the following two IPv4 // routes: // - 192.0.2.0/24 (goes to some target A) // - 192.0.2.0/28 (goes to some target B) // // Both routes apply to the traffic destined for 192.0.2.3 . However, the second // route in the list covers a smaller number of IP addresses and is ther...
(stack *middleware.Stack, options Options) (err error) { err = stack.Serialize.Add(&awsEc2query_serializeOpCreateRoute{}, middleware.After) if err != nil { return err } err = stack.Deserialize.Add(&awsEc2query_deserializeOpCreateRoute{}, middleware.After) if err != nil { return err } if err = addlegacyEndpoi...
addOperationCreateRouteMiddlewares
identifier_name
irc_comm.rs
msg: S2, ) -> Result<Option<LibReaction<Message>>> where S1: Borrow<str>, S2: Display,
)); Ok(()) })?; } match wrapped_msg.len() { 0 => Ok(None), 1 => Ok(Some(wrapped_msg.remove(0))), _ => Ok(Some(LibReaction::Multi(wrapped_msg.into_vec()))), } } fn compose_msgs<S1, S2, M>( &self, ...
{ let final_msg = format!( "{}{}{}", addressee.borrow(), if addressee.borrow().is_empty() { "" } else { &self.addressee_suffix }, msg, ); info!("Sending message to {:?}: {:?}", dest, final_ms...
identifier_body
irc_comm.rs
msg: S2, ) -> Result<Option<LibReaction<Message>>> where S1: Borrow<str>, S2: Display, { let final_msg = format!( "{}{}{}", addressee.borrow(), if addressee.borrow().is_empty() { "" } else { &self.addres...
<'a>(msg: Option<Cow<'a, str>>) -> LibReaction<Message> { let quit = aatxe::Command::QUIT( msg.map(Cow::into_owned) .or_else(|| Some(pkg_info::BRIEF_CREDITS_STRING.clone())), ).into(); LibReaction::RawMsg(quit) } pub(super) fn handle_msg( state: &Arc<State>, server_id: ServerId...
mk_quit
identifier_name
irc_comm.rs
msg: S2, ) -> Result<Option<LibReaction<Message>>> where S1: Borrow<str>, S2: Display, { let final_msg = format!( "{}{}{}", addressee.borrow(), if addressee.borrow().is_empty() { "" } else { &self...
state:
random_line_split
irc_comm.rs
msg: S2, ) -> Result<Option<LibReaction<Message>>> where S1: Borrow<str>, S2: Display, { let final_msg = format!( "{}{}{}", addressee.borrow(), if addressee.borrow().is_empty() { "" } else { &self.addres...
_ => Ok(()), } } fn handle_privmsg( state
{ push_to_outbox(outbox, server_id, handle_004(state, server_id)?); Ok(()) }
conditional_block
wechat_mp.go
Config struct { AppId string `json:"app_id"` // 公众号appId AppSecret string `json:"app_secret"` // 公众号appSecret Token string `json:"token"` // 公众号Token EncodingAESKey string `json:"encoding_aes_key,omitempty"` // 公众号EncodingAESKey } ...
ck := CheckWechatAuthSign(msg_signature, timestamp, nonce, wm.Configure.Token, msgEncryptRequest.Encrypt) var message []byte if check { // 验证成功,解密消息,返回正文的二进制数组格式 message, err = wm.aesDecryptMessage(msgEncryptRequest.Encrypt) if err != nil { fmt.Fprintf(common.WechatErrorLoggerWriter, "checkMessageSourc...
st if err = xml.Unmarshal(body, &msgEncryptRequest); err != nil { fmt.Fprintf(common.WechatErrorLoggerWriter, "checkMessageSource xml.Unmarshal(body, &msgEncryptBody) error: %+v\n", err) return false, nil } che
identifier_body
wechat_mp.go
checkWechatSource(r *http.Request) bool { timestamp := r.FormValue(WechatRequestTimestamp) nonce := r.FormValue(WechatRequestNonce) signature := r.FormValue(WechatRequestSignature) return CheckWechatAuthSign(signature, wm.Configure.Token, timestamp, nonce) } // 检验消息来源,并且提取消息 func (wm *WechatMp) checkMessageSource...
identifier_name
wechat_mp.go
微信公众号服务器配置,并开启后,微信会发送一次认证请求,此函数即做此验证用 func (wm *WechatMp) AuthWechatServer(r *http.Request) string { echostr := r.FormValue(WechatRequestEchostr) if wm.checkWechatSource(r) { return echostr } return WechatResponseStringInvalid } // 检验认证来源是否为微信 func (wm *WechatMp) checkWechatSource(r *http.Request) bool { timest...
SetTextHandlerFunc(handlerFunc TextMessageHandlerFunc) { wm.TextMessageHandler = handlerFunc } // 设置处理微信image消息事件方法 func (wm *WechatMp) SetImageHand
conditional_block
wechat_mp.go
MpConfig struct { AppId string `json:"app_id"` // 公众号appId AppSecret string `json:"app_secret"` // 公众号appSecret Token string `json:"token"` // 公众号Token EncodingAESKey string `json:"encoding_aes_key,omitempty"` // 公众号EncodingAESKey ...
// 如果消息未加密 signature := r.FormValue(WechatRequestSignature) return CheckWechatAuthSign(signature, wm.Configure.Token, timestamp, nonce), body } // 加密后的微信消息结构 type MsgEncryptRequest struct { XMLName xml.Name `xml:"xml"` ToUserName string // 开发者微信号 Encrypt string // 加密的消息正文 } // 响应加密消息的结构 type MsgEncryp...
} return check, message }
random_line_split
utils.py
''' Image with dicome attribute [0028,0004] == MONOCHROME1 needs to be inverted. Otherwise, our way to detect the knee will not work. :param image_array: :return: ''' print('Invert Monochrome ') print(image_array.shape, np.mean(image_array), np.min(image_array), np.max(image_array)) ...
if row_start < 0 or row_end > (image_array.shape[0] - 1): row_start = round(image_array.shape[0] / 2) - 512 row_end = round(image_array.shape[0] / 2) + 512 #print('Row Indices Final: ', row_start, row_end) # For right knee, crop columns to be centered at the maximum sum of the LHS of origi...
''' Extrack knee part from image array :param image_array: :param side: 0: left knee; 1: right knee :param offset: if does not work, you can manually change the shape :return: ''' #print('Dimensions of image: ', image_array.shape) # Compute the sum of each row and column col_sums = ...
identifier_body
utils.py
after_y)),'constant'),before_x,before_y def global_contrast_normalization_oulu(img,lim1,multiplier = 255): ''' This part is taken from oulu's lab. This how they did global contrast normalization. :param img: :param lim1: :param multiplier: :return: ''' img -= lim1 img /= img.max() ...
if -1 in bbox: # if the algorithm says there is no knee in the figure. return None,None # process_xray
random_line_split
utils.py
''' Image with dicome attribute [0028,0004] == MONOCHROME1 needs to be inverted. Otherwise, our way to detect the knee will not work. :param image_array: :return: ''' print('Invert Monochrome ') print(image_array.shape, np.mean(image_array), np.min(image_array), np.max(image_array)) # ...
(image_dicom, scaling_factor=0.2): ''' Obtain fixed resolution from image dicom :param image_dicom: :param scaling_factor: :return: ''' print('Obtain Fix Resolution:') image_array = image_dicom.pixel_array print(image_array.shape,np.mean(image_array),np.min(image_array),np.max(image_...
interpolate_resolution
identifier_name
utils.py
''' Image with dicome attribute [0028,0004] == MONOCHROME1 needs to be inverted. Otherwise, our way to detect the knee will not work. :param image_array: :return: ''' print('Invert Monochrome ') print(image_array.shape, np.mean(image_array), np.min(image_array), np.max(image_array)) ...
else: before_x,after_x = 0,0 if y_padding > 0: before_y,after_y = y_padding // 2, y_padding - y_padding // 2 else: before_y,after_y = 0,0 return np.pad(img,((before_x,after_x),(before_y,after_y)),'constant'),before_x,before_y def global_contrast_normalization_oulu(img,lim1,mult...
before_x,after_x = x_padding // 2, x_padding - x_padding // 2
conditional_block
Assignment 3 notes.py
= (ScimEn.merge(energy, on='Country') .merge(GDP, on='Country')) energy[energy['Country'].str.contains('United')] GDP[GDP['Country'].str.contains('United')] sub_str = {'^([^\d\(]+).*' : r'\1'} en2 = energy.iloc[232].replace(to_replace={'Country' : sub_str}, ) energy[energy['Country'].str.contains('Un...
""" Terribly ugly solution, but it works """
random_line_split
Assignment 3 notes.py
,7,6,14,37,32,7,8,8,18,7,5,11,17,7,7,8,14,16,4,7,6,13,16,5,6,7,7,5,9,6,9,7,10,4,9,8,6,13,6,5,8,7,7,5,9,4,4,7,11,6,5,7,5,6,6,10,5,8,6,10,32,6,7,7,7,5,13,9,10,10,6,8,8,4,5,16,10,10,9,6,10,8,10,10,7,10,7,7,5,5,11,13,11,9,5,7,4,24,6,4,8,5,6,16,8,4,11,6,8,11,5,11,19,7,7,18,6,12,21,11,25,32,5,21,12,7,6,10,12,9,12,8,8,15,7,12...
return res print(test_gdp(GDP['Country'])) """ # Alternative merge strategy # merge the first two, then the third in the requested order merged2 = pd.merge(ScimEn, energy, how='inner', left_index=True, right_index=True) merged3 = pd.merge(merged2, GDP, how='inner', left_index=True, right_index=True) result = (Sci...
s += '\nMismatched countries:\n' mismatch = GDP.loc[GDP['tested'] != (GDP['actual']), [ 'original', 'Country', 'tested', 'actual']].values.tolist() res += '\n'.join('"{:}" miss-cleaned as "{:}"'.format(o, r) for o, r, s, v in mismatch)
conditional_block
Assignment 3 notes.py
(): # get the dataframes; all indexed to energy = read_and_clean_energy_dataframe() GDP = read_and_clean_GDP_dataframe() ScimEn = read_and_clean_ScimEn_dataframe() # merge sequence to get columns in the requested order result = ScimEn.merge(energy, on='Country').merge(GDP, on='Country') ...
answer_one
identifier_name
Assignment 3 notes.py
1,7,16,9,7,5,7,8,14,40,7,4,6,13,21,5,14,7,5,9,6,11,13,17,6,7,9,9,4,6,11,9,8,38,7,5,7,9,16,9,9,9,8,11,5,14,7,4,4,7,6,5,7,6,5,10,5,15,8,8,19,11,6,6,49,7,7,7,5,9,25,44,10,13,9,19,19,7,25,9,10,6,16,24,7,6,7,10,8,26,6,16,13,14,4,5,7,50,10,8,24,10,10,9,6,8,13,7,13,5,7,9,11,6,5,5,11,12,4,18,8,6,4,11,5,16,6,24,11,25,8,8,27,25,...
15 = answer_one() Top15['Population Estimate'] = Top15['Energy Supply'] / Top15['Energy Supply per Capita'] Top15.sort_values('Population Estimate', ascending=False, inplace=True) return Top15.iloc[2].name a
identifier_body
estimator.py
flags.DEFINE_string('checkpoint_path', None, 'Path to load checkpoint.') flags.DEFINE_string('gin_file', None, 'Gin config file.') flags.DEFINE_multi_string('gin_param', None, 'Gin config parameters.') FLAGS = flags.FLAGS _CONFIG_GIN = 'operative_config-0.gin' def main(_): if FLAGS.gin_file: gin_paths = ...
(self, batch_size, mode): if mode == tf.estimator.ModeKeys.TRAIN: return self._input_fn_train_or_eval( training=True, batch_size=batch_size) elif mode == tf.estimator.ModeKeys.EVAL: return self._input_fn_train_or_eval( training=False, batch_size=b...
input_fn
identifier_name
estimator.py
flags.DEFINE_string('checkpoint_path', None, 'Path to load checkpoint.') flags.DEFINE_string('gin_file', None, 'Gin config file.') flags.DEFINE_multi_string('gin_param', None, 'Gin config parameters.') FLAGS = flags.FLAGS _CONFIG_GIN = 'operative_config-0.gin' def main(_): if FLAGS.gin_file: gin_paths = ...
else: gin_paths = [] gin.parse_config_files_and_bindings(gin_paths, FLAGS.gin_param) estimator = Estimator() getattr(estimator, FLAGS.do)() class InputFn(object): @staticmethod def create_dir(base_dir): dir_path = os.path.join( base_dir, datetime.date...
checkpoint_dir = FLAGS.checkpoint_dir if checkpoint_dir is None: checkpoint_dir = os.path.dirname(FLAGS.checkpoint_path) gin_paths = [os.path.join(checkpoint_dir, _CONFIG_GIN)]
conditional_block
estimator.py
flags.DEFINE_string('checkpoint_path', None, 'Path to load checkpoint.') flags.DEFINE_string('gin_file', None, 'Gin config file.') flags.DEFINE_multi_string('gin_param', None, 'Gin config parameters.') FLAGS = flags.FLAGS _CONFIG_GIN = 'operative_config-0.gin' def main(_): if FLAGS.gin_file: gin_paths = ...
return self._input_fn_train_or_eval( training=False, batch_size=batch_size) elif mode == tf.estimator.ModeKeys.PREDICT: return self._input_fn_predict( batch_size=batch_size) class ModelFn(object): def _get_global_step(self): return tf_v1.tra...
if mode == tf.estimator.ModeKeys.TRAIN: return self._input_fn_train_or_eval( training=True, batch_size=batch_size) elif mode == tf.estimator.ModeKeys.EVAL:
random_line_split
estimator.py
flags.DEFINE_string('checkpoint_path', None, 'Path to load checkpoint.') flags.DEFINE_string('gin_file', None, 'Gin config file.') flags.DEFINE_multi_string('gin_param', None, 'Gin config parameters.') FLAGS = flags.FLAGS _CONFIG_GIN = 'operative_config-0.gin' def main(_): if FLAGS.gin_file: gin_paths = ...
@property def result_dir_root(self): return os.path.join(self.root_dir, 'results') @property def split_dir_root(self): return os.path.join(self.data_dir, 'splits') @property def tfrecord_dir_root(self): return os.path.join(self.data_dir, 'tfrecords') def _write_t...
return os.path.join(self.root_dir, 'models')
identifier_body
settings.rs
::ParsedPkcs12 doesn't impl Clone yet } #[derive(Clone)] pub struct IdentityStore(Vec<u8>, String); impl TlsSettings { /// Generate a filled out settings struct from the given optional /// option set, interpreted as client options. If `options` is /// `None`, the result is set to defaults (ie empty). ...
{ let options = TlsOptions { crt_path: Some(TEST_PEM_CRT.into()), key_path: Some(TEST_PEM_KEY.into()), ..Default::default() }; let settings = TlsSettings::from_options(&Some(options)).expect("Failed to load PEM certificate"); assert!(settin...
identifier_body
settings.rs
(super) verify_hostname: bool, authority: Option<X509>, pub(super) identity: Option<IdentityStore>, // openssl::pkcs12::ParsedPkcs12 doesn't impl Clone yet } #[derive(Clone)] pub struct IdentityStore(Vec<u8>, String); impl TlsSettings { /// Generate a filled out settings struct from the given optional ...
() { let options = TlsOptions { crt_path: Some(TEST_PKCS12.into()), key_pass: Some("NOPASS".into()), ..Default::default() }; let settings = TlsSettings::from_options(&Some(options)).expect("Failed to load PKCS#12 certificate"); assert!(sett...
from_options_pkcs12
identifier_name
settings.rs
(super) verify_hostname: bool, authority: Option<X509>, pub(super) identity: Option<IdentityStore>, // openssl::pkcs12::ParsedPkcs12 doesn't impl Clone yet } #[derive(Clone)] pub struct IdentityStore(Vec<u8>, String); impl TlsSettings { /// Generate a filled out settings struct from the given optional ...
let name = crt_path.to_string_lossy().to_string(); let cert_data = open_read(crt_path, "certificate")?; let key_pass: &str = options.key_pass.as_ref().map(|s| s.as_str()).unwrap_or(""); match Pkcs12::from_der(&cert_data) { // Certifica...
let identity = match options.crt_path { None => None, Some(ref crt_path) => {
random_line_split
calculate_profiles.py
, type=str, help="Path to the output aligned directory. Required." ) parser.add_argument("--overview", default=None, type=str, help="Path to the output description csv. Required. Pairs with <--aligned...
(df_group, l, dst=dst_func): sqs = df_group.reset_index()['sq'] n = len(sqs) if n <= 1: return np.zeros(n) dst_matrix = np.zeros((n, n)) for i in range(n): for j in range(i): d = dst(sqs[i], sqs[j]) dst_matrix[i, j] = d dst_matrix[j, i] = d ...
cluster_group
identifier_name
calculate_profiles.py
=None, type=str, help="Path to the output aligned directory. Required." ) parser.add_argument("--overview", default=None, type=str, help="Path to the output description csv. Required. Pairs with <--al...
start = time.time() # print(df.groupby(by='length').get_group(longest)) # print("running on shorter") with Bar("Processing length groups...", max=len(unique_lengths) - 1) as bar: for length in unique_lengths[1:]: bar.next() df_group = groups.get_group(length).copy() def getDistanceAndAl...
against.append(alignment) # df.loc[df['sq'].isin(cluster_df['sq']), 'alignment'] = alignment.ident # to each sequence
random_line_split
calculate_profiles.py
, type=str, help="Path to the output aligned directory. Required." ) parser.add_argument("--overview", default=None, type=str, help="Path to the output description csv. Required. Pairs with <--aligned...
def cluster_group(df_group, l, dst=dst_func): sqs = df_group.reset_index()['sq'] n = len(sqs) if n <= 1: return np.zeros(n) dst_matrix = np.zeros((n, n)) for i in range(n): for j in range(i): d = dst(sqs[i], sqs[j]) dst_matrix[i, j] = d dst_m...
for line in open(filename): sq, count = line.strip('\n').split(';') yield sq, np.array([int(x) for x in count.split(',')]), count
identifier_body
calculate_profiles.py
, type=str, help="Path to the output aligned directory. Required." ) parser.add_argument("--overview", default=None, type=str, help="Path to the output description csv. Required. Pairs with <--aligned...
i = offset for base, count in zip(aligned_query, new_counts): x[bases[base], i] += count i += 1 self.profile = x # store new sequence alignment added_alignment = -np.ones(self.profile.shape[1]) for i, char in enumerate(nice['target_aligned']): ...
value = new_counts[index] new_counts = np.insert(new_counts, index, value, axis=0)
conditional_block
game.py
_K: logic.down} self.setWindowFlags( QtCore.Qt.CustomizeWindowHint | QtCore.Qt.FramelessWindowHint) self.setAttribute(Qt.WA_TranslucentBackground, True) self.center() self.settings() self.restoreStates() self.fontDatabase = QFontDatabase() ...
if done: self.stateOfGame() elif strokeText == "D":
conditional_block
game.py
for j in range(c.GRID_LEN): new_number = self.matrix[i][j] if new_number == 0: self.replaceTile("empty", i, j) else: self.replaceTile(new_number, i, j) # Δημιουργία των αριθμητικών πλακιδίων def setTile(self, it...
-1] else: lst=self.settings().value("gameState") nums=[] for i in range(len(lst)): for j in range(len(lst[0])): if lst[i][j]!=0: nums.append(lst[i][j]) print(nums) return nums def bHelpClicked(self): helpDlg...
identifier_body
game.py
def __init__(self, parent=None): # Αρχικοποίηση του γραφικού περιβάλλοντος super(Game, self).__init__(parent) print(APP_FOLDER) self.setupUi(self) c.SCORE=self.settings().value("score", 0, type=int) # Μεταβλητές self.points = [] self.speed = 30 ...
def settings(self): settings = QSettings() return settings
random_line_split
game.py
RID_LEN): for j in range(c.GRID_LEN): self.gridBoard.addWidget(self.setTile("empty"), i, j) def generate_next(self): index = (gen(), gen()) while self.matrix[index[0]][index[1]] != 0: index = (gen(), gen()) self.matrix[index[0]][index[1]] = 2 def...
= self.
identifier_name
key.go
Now := time.Now().UTC().Truncate(time.Second) if tokenBuildRequest.UtcNotBefore == nil { tokenBuildRequest.UtcNotBefore = &utcNow } tokenBuildRequest.Claims.Issued = jwt.NewNumericTime(utcNow) tokenBuildRequest.Claims.NotBefore = jwt.NewNumericTime(*tokenBuildRequest.UtcNotBefore) if tokenBuildRequest.UtcExpires...
{ var cachedItem interface{} var found bool cachedItem, found = cache.Get(cacheKey) if !found { err = DoKeyvaultBackground() if err != nil { log.Fatalf("failed to DoKeyvaultBackground: %v\n", err.Error()) return } cachedItem, found = cache.Get(cacheKey) if !found { err = errors.New("critical f...
identifier_body
key.go
Claims jwt.Claims } type BaseClient2 struct { azKeyvault.BaseClient } func newBaseClient2(base azKeyvault.BaseClient) BaseClient2 { return BaseClient2{ BaseClient: base, } } func getKeysClient() azKeyvault.BaseClient { keyClient := azKeyvault.New() a, _ := iam.GetKeyvaultAuthorizer() keyClient...
(base64EncodedE string) string { sDec, _ := b64.StdEncoding.DecodeString(base64Encoded
fixE
identifier_name
key.go
Claims jwt.Claims } type BaseClient2 struct { azKeyvault.BaseClient } func newBaseClient2(base azKeyvault.BaseClient) BaseClient2 { return BaseClient2{ BaseClient: base, } } func getKeysClient() azKeyvault.BaseClient { keyClient := azKeyvault.New() a, _ := iam.GetKeyvaultAuthorizer() keyClient...
azKeyvault.Encrypt, azKeyvault.Decrypt, }, Kty: azKeyvault.EC, }) } func fixE(base64EncodedE string) string { sDec, _ := b64.StdEncoding.DecodeString(base64EncodedE
Enabled: to.BoolPtr(true), }, KeySize: to.Int32Ptr(2048), // As of writing this sample, 2048 is the only supported KeySize. KeyOps: &[]azKeyvault.JSONWebKeyOperation{
random_line_split
key.go
Claims jwt.Claims } type BaseClient2 struct { azKeyvault.BaseClient } func newBaseClient2(base azKeyvault.BaseClient) BaseClient2 { return BaseClient2{ BaseClient: base, } } func getKeysClient() azKeyvault.BaseClient { keyClient := azKeyvault.New() a, _ := iam.GetKeyvaultAuthorizer() keyClient....
} } if !pageResult.NotDone() { break } err = pageResult.Next() if err != nil { return } } sort.Slice(finalResult[:], func(i, j int) bool { notBeforeA := time.Time(*finalResult[i].Attributes.NotBefore) notBeforeB := time.Time(*finalResult[j].Attributes.NotBefore) return notBeforeA.After(n...
{ parts := strings.Split(*element.Kid, "/") lastItemVersion := parts[len(parts)-1] keyBundle, er := keyClient.GetKey(ctx, keyVaultUrl, keyIdentifier, lastItemVersion) if er != nil { err = er return } fixedE := fixE(*keyBundle.Key.E) *keyBundle.Key.E = fi...
conditional_block
layout_rope.rs
but we might add more stuff. pub struct Layout(PietTextLayout); #[derive(Clone, Default)] pub struct LayoutRope(Node<LayoutInfo>); pub struct LayoutRopeBuilder(TreeBuilder<LayoutInfo>); /// The height metric of the rope, which is in raw Height fractions. struct HeightMetric; /// The base metric of the rope, which ...
(&mut self, index: usize) { let mut b = TreeBuilder::new(); self.push_subseq(&mut b, Interval::new(0, index)); self.push_subseq(&mut b, Interval::new(index + 1, self.len())); self.0 = b.build(); } pub fn set(&mut self, index: usize, item: Layout) { let mut b = TreeBuilde...
remove
identifier_name
layout_rope.rs
but we might add more stuff. pub struct Layout(PietTextLayout); #[derive(Clone, Default)] pub struct LayoutRope(Node<LayoutInfo>); pub struct LayoutRopeBuilder(TreeBuilder<LayoutInfo>); /// The height metric of the rope, which is in raw Height fractions. struct HeightMetric; /// The base metric of the rope, which ...
fn push_subseq(&self, b: &mut TreeBuilder<LayoutInfo>, iv: Interval) { // TODO: if we make the push_subseq method in xi-rope public, we can save some // allocations. b.push(self.0.subseq(iv)); } } impl LayoutRopeBuilder { pub fn new() -> LayoutRopeBuilder { LayoutRopeBuild...
{ self.0 .count_base_units::<HeightMetric>(height.as_raw_frac()) }
identifier_body
layout_rope.rs
but we might add more stuff. pub struct Layout(PietTextLayout); #[derive(Clone, Default)] pub struct LayoutRope(Node<LayoutInfo>); pub struct LayoutRopeBuilder(TreeBuilder<LayoutInfo>); /// The height metric of the rope, which is in raw Height fractions. struct HeightMetric; /// The base metric of the rope, which ...
} } impl From<Vec<(Height, Arc<Layout>)>> for LayoutRope { fn from(v: Vec<(Height, Arc<Layout>)>) -> Self { LayoutRope(Node::from_leaf(LayoutLeaf { data: v })) } } impl LayoutRope { /// The number of layouts in the rope. pub fn len(&self) -> usize { self.0.len() } /// The...
{ let splitpoint = self.len() / 2; let right_vec = self.data.split_off(splitpoint); Some(LayoutLeaf { data: right_vec }) }
conditional_block
layout_rope.rs
, but we might add more stuff. pub struct Layout(PietTextLayout); #[derive(Clone, Default)] pub struct LayoutRope(Node<LayoutInfo>); pub struct LayoutRopeBuilder(TreeBuilder<LayoutInfo>); /// The height metric of the rope, which is in raw Height fractions. struct HeightMetric; /// The base metric of the rope, which...
type Output = Self; fn add(self, other: Self) -> Self { Height(self.0 + other.0) } } impl std::ops::AddAssign for Height { fn add_assign(&mut self, other: Self) { self.0 += other.0 } } impl Height { /// The number of fractional bits in the representation. pub const HEIGHT_...
random_line_split
switching_utils.py
iff you would like to save the simulation as a GIF. ''' #Initialize planners if not yet done for car in world.cars: if (isinstance(car, PlannerCar) and car.planner is None): car.initialize_planner() if (world.verbose): print(f"Executing {exp_name} for {time_steps} time ste...
(reward_ts, model_ts): ''' Displays reward for each time step gained by the car in a plot. Color codes by model used and presents an appropriate legend. ''' plt.title("Reward by Model") start_time = 0 cur_model = model_ts[0] used_models = [cur_model] for t, model in enumerate(m...
display_rewards
identifier_name
switching_utils.py
def execute_many_experiments(exp_name, world, time_steps, experiment_args, ms_car_index = 0): switching_parameters = {"comp_times": {"Naive": experiment_args.naive_ct, "Turn": experiment_args.turn_ct, ...
raise Exception(f"Invalid Experiment Type: {exp_type}")
conditional_block
switching_utils.py
iff you would like to save the simulation as a GIF. ''' #Initialize planners if not yet done for car in world.cars: if (isinstance(car, PlannerCar) and car.planner is None): car.initialize_planner() if (world.verbose): print(f"Executing {exp_name} for {time_steps} time ste...
def execute_many_experiments(exp_name, world, time_steps, experiment_args, ms_car_index = 0): switching_parameters = {"comp_times": {"Naive": experiment_args.naive_ct, "Turn": experiment_args.turn_ct, ...
clip.speedx(0.5).write_gif(f"{exp_name}.gif", program="ffmpeg") #return np.mean(reward_ts), avg_step_times['overall'][-1], model_usage return reward_ts
random_line_split
switching_utils.py
iff you would like to save the simulation as a GIF. ''' #Initialize planners if not yet done for car in world.cars: if (isinstance(car, PlannerCar) and car.planner is None): car.initialize_planner() if (world.verbose): print(f"Executing {exp_name} for {time_steps} time ste...
else: et = (experiment_args.num_run - i) * run_time / (i - 1) print(f"Running Experiment {i + 1}/{experiment_args.num_run}, Expected Time Left: {et:.0f}s ", end = "\r") if (i >= 1): start_time = time.time() #mean_rew, mean_ct, model_u...
switching_parameters = {"comp_times": {"Naive": experiment_args.naive_ct, "Turn": experiment_args.turn_ct, "Tom": experiment_args.tom_ct}, "cooldowns": {"up": experiment_args.up_cd, ...
identifier_body
sectioning.js
cookieStore.get('username')); //$('#loginModal').modal('hide'); } $scope.techTable=[]; $scope.tech={}; $http.get(TECHNICIAN_URL_BASE) .success(function(data) { //alert("success loading technicians") $scope.techTable=data; console.log($scope.techTable); }) .error(...
$http.get(url) .success(function (data) {
random_line_split
Object_detection_image.py
is copied from Google's example at ## https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb ## and some is copied from Dat Tran's example at ## https://github.com/datitran/object_detector_app/blob/master/object_detection_app.py ## but I changed it to make it Suita...
# This is needed since the notebook is stored in the object_detection folder. sys.path.append("..") # Import utilites(utils folder) from utils import label_map_util from utils import visualization_utils as vis_util #CGFC_functions folder from CGFC_functions import colorDetector as color_Detector from CGFC_functions ...
#import__color recognition from sklearn.cluster import KMeans from sklearn import metrics
random_line_split
Object_detection_image.py
copied from Google's example at ## https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb ## and some is copied from Dat Tran's example at ## https://github.com/datitran/object_detector_app/blob/master/object_detection_app.py ## but I changed it to make it Suitable...
#Cloth detection whole process start from here def ClothDetectionAnalyse(image,tagData,gender): min_score_thresh=CGFCConfig.min_score_thresh detectedData=Detect_Cloths(image) boxes=detectedData['boxes'][0] scores=detectedData['scores'][0] classes=detectedData['classes'][0] print("##########...
dominet_colors=color_Detector.dominant_color_detector(crop_img,3)
identifier_body
Object_detection_image.py
copied from Google's example at ## https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb ## and some is copied from Dat Tran's example at ## https://github.com/datitran/object_detector_app/blob/master/object_detection_app.py ## but I changed it to make it Suitable...
(image,tagData,gender): min_score_thresh=CGFCConfig.min_score_thresh detectedData=Detect_Cloths(image) boxes=detectedData['boxes'][0] scores=detectedData['scores'][0] classes=detectedData['classes'][0] print("###################################################################################")...
ClothDetectionAnalyse
identifier_name
Object_detection_image.py
copied from Google's example at ## https://github.com/tensorflow/models/blob/master/research/object_detection/object_detection_tutorial.ipynb ## and some is copied from Dat Tran's example at ## https://github.com/datitran/object_detector_app/blob/master/object_detection_app.py ## but I changed it to make it Suitable...
crop_image_Data = pd.DataFrame() for index,bbox in enumerate(bestBBox): crop_img=cropDetectedCloths(image,bbox) dominet_colors=color_Detector.dominant_color_detector(crop_img,3) colors=[] colorMax=dominet_colors[0] #print("dominet_colors ...
if ((score>=min_score_thresh) &(className in category_Dic.Attributes)): bestResults.append(index) bestBBox.append(normBBoxes[index]) bestScores.append(score) bestClasses.append(normClasses[index])
conditional_block
all8a54.js
-unique-id-'+initIterator; $t.addClass('swiper-'+index + ' initialized').attr('id', index); $t.find('.pagination').addClass('pagination-'+index); var autoPlayVar = parseInt($t.attr('data-autoplay'),10); var slidesPerViewVar = $t.attr('data-slides-per-view'); if(slidesPerViewVar == 'responsive'){ s...
(data){ if (data.status == 'ok') { var popup_cont = ''; if (data.type == 'ajax') { if (data.thumbnail) popup_cont += data.thumbnail; popup_cont += '<div class="team-desc">'; popup_cont += ' <div class="title">'; popup_cont += ' <h4>' + data.time + '</h4>'; popup_cont += ' <h2>' + data....
render_content
identifier_name
all8a54.js
if ($('.home-slider.anime-slide').length) { $('.home-slider.anime-slide').closest('.vc_row').addClass('nrg-prod-row-full-height'); }; if ($('.home-slider.arrow-center').length) { $('.home-slider.arrow-center').closest('.vc_row').addClass('nrg-prod-row-full-height'); }; pageCalculations(); function upda...
{ winW = $(window).width(); winH = $(window).height(); }
identifier_body
all8a54.js
_content(data_query,callback){ $.ajax({ url: data_query.ajax_url, success: function(data){ if (IsJsonString(data)) { data = jQuery.parseJSON(data); data.post_url = data_query.post_url; } else { var data_r = {}; data_r.status = 'ok'; data_r.type = 'html'; data_r.content =...
{ var pageNum = parseInt(load_more_post.startPage) + 1; // The maximum number of pages the current query can return. var max = parseInt(load_more_post.maxPages); // The link of the next page of posts. var nextLink = load_more_post.nextLink; $('.load-more').on('click', function () ...
conditional_block
all8a54.js
if(slidesPerViewVar == 'responsive'){ slidesPerViewVar = updateSlidesPerView($t); } else slidesPerViewVar = parseInt(slidesPerViewVar,10); var directionVar = $t.attr('data-direction'); if(!directionVar){ directionVar='horizontal'; } var loopVar = parseInt($t.attr('data-loop'),10); var speedVar ...
} } ); } else {
random_line_split
test_dbinterface.py
%s' % __name__) def tearDownModule(): """Tear down module after all TestCases are run.""" pass # logPoint('module %s' % __name__) class TestDBInterface(unittest.TestCase): PORT = 29101 HOST = 'localhost' EXP_ID = 'TEST_EXP_ID' DATABASE_NAME = 'TFUTILS_TESTDB' COLLECTION_NAME = 'TFU...
def test_filter_var_list(self): var_list = {var.op.name: var for var in tf.global_variables()} # Test None self.dbinterface.to_restore = None filtered_var_list = self.dbinterface.filter_var_list(var_list) self.assertEqual(filtered_var_list, var_list) # Test list ...
self.log.info('(name, var.name): ({}, {})'.format(name, var.name)) self.assertEqual(var.op.name, mapping[name])
conditional_block
test_dbinterface.py
%s' % __name__) def tearDownModule(): """Tear down module after all TestCases are run.""" pass # logPoint('module %s' % __name__) class TestDBInterface(unittest.TestCase): PORT = 29101 HOST = 'localhost' EXP_ID = 'TEST_EXP_ID' DATABASE_NAME = 'TFUTILS_TESTDB' COLLECTION_NAME = 'TFU...
""" self.setup_model() self.sess = tf.Session( config=tf.ConfigProto( allow_soft_placement=True, gpu_options=tf.GPUOptions(allow_growth=True), log_device_placement=self.params['log_device_placement'], )) # TODO:...
Creates a tensorflow session and instantiates a dbinterface.
random_line_split
test_dbinterface.py
%s' % __name__) def tearDownModule(): """Tear down module after all TestCases are run.""" pass # logPoint('module %s' % __name__) class TestDBInterface(unittest.TestCase): PORT = 29101 HOST = 'localhost' EXP_ID = 'TEST_EXP_ID' DATABASE_NAME = 'TFUTILS_TESTDB' COLLECTION_NAME = 'TFU...
(self): self.log.info('Saving checkpoint to {}'.format(self.save_path)) saved_checkpoint_path = self.dbinterface.tf_saver.save(self.sess, save_path=self.save_path, global_step=se...
save_test_checkpoint
identifier_name
test_dbinterface.py
def tearDownModule(): """Tear down module after all TestCases are run.""" pass # logPoint('module %s' % __name__) class TestDBInterface(unittest.TestCase): PORT = 29101 HOST = 'localhost' EXP_ID = 'TEST_EXP_ID' DATABASE_NAME = 'TFUTILS_TESTDB' COLLECTION_NAME = 'TFUTILS_TESTCOL' ...
"""Set up module once, before any TestCases are run.""" logging.basicConfig() # logPoint('module %s' % __name__)
identifier_body
space_invaders.py
= screen self.sprite = sprite self.rect = rect self.update_dimensions() self.update_mask() self.set_exists(True) # Assigns an id using current time in microseconds def create_random_id(self): self.id = int(time() * SECONDS_TO_MICRO_SECONDS) # Ensures destro...
# Return front ships def get_front_line_ships(self): return self.front_line # Evenly space out ships within initial allowed range def setup_ships(self): start_bottom_edge = int( float(HEIGHT_FRAME_OPPONENTS) * FACTOR_HEIGHT_FRAME_OPPONENTS) horizontal_separation = ...
self.direction = DIRECTION_RIGHT self.direction_previous = self.direction self.screen = screen self.row_and_column_size = row_and_column_size self.ships = {} self.left = {} self.right = {} self.front_line = {} self.setup_ships()
identifier_body
space_invaders.py
= screen self.sprite = sprite self.rect = rect self.update_dimensions() self.update_mask() self.set_exists(True) # Assigns an id using current time in microseconds def create_random_id(self): self.id = int(time() * SECONDS_TO_MICRO_SECONDS) # Ensures destro...
if r == (self.row_and_column_size - 1): self.right[id] = ship if c == (self.row_and_column_size - 1): self.front_line[id] = ship self.ships[id] = ship # Check whether left or right ships reached allowed edge/coordinates de...
self.left[id] = ship
conditional_block
space_invaders.py
Label class Text(BasicSprite): def __init__(self, screen, text, color, font, size): self.text = text self.color = color self.font = font self.size = size self.my_font = pygame.font.SysFont(font, size) self.label = self.my_font.render(text, 1, color) super()._...
self.screen, text, color, "arial", 60)
random_line_split
space_invaders.py
# Move to position unless outside of allowed coordinates; returns actual # position delta in contrast with asked def set_location(self, x, y): center_change = [ self.rect.centerx, self.rect.centery] self.rect.centerx = x self.rect.centery = y # Ensur...
__init__
identifier_name
full-site.js
$choicesModal.find('.modal-footer').html(""); var $firstButton; for (var i in buttons) { var btn = buttons[i]; var attrsString = ""; for (var key in btn.attrs) { var value = btn.attrs[key]; attrsString += key + '="' + value + '" '; } var $button ...
function sharePopup(url, w, h) { var left = (screen.width / 2) - (w / 2); var top = (screen.height / 2) - (h / 2); return window.open(url, "share window", 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, copyhistory=no, width=' + w + ', height=' + h + ', top='...
});
random_line_split
full-site.js
choicesModal.find('.modal-footer').html(""); var $firstButton; for (var i in buttons) { var btn = buttons[i]; var attrsString = ""; for (var key in btn.attrs) { var value = btn.attrs[key]; attrsString += key + '="' + value + '" '; } var $button = ...
function getprayerTimeData() { $.ajax({ url: getPrayerInfoUrl, success: preparePrayerTimeWidget }); } // increaseFontSize and decreaseFontSize var min = 16; var max = 20; function increaseFontSize() { var p = $('.details-text'); for (i = 0; i < p.length; i++...
{ document.getElementById('form_email').value = ""; // $('#form_email').css('text-indent', '35px'); $('#form-modal .help-error').remove(); $('#form-modal .form-group').removeClass('is-invalid'); $('#form-modal').modal('show'); }
identifier_body
full-site.js
$choicesModal.find('.modal-footer').html(""); var $firstButton; for (var i in buttons) { var btn = buttons[i]; var attrsString = ""; for (var key in btn.attrs) { var value = btn.attrs[key]; attrsString += key + '="' + value + '" '; } var $button ...
() { $('#choices-modal').modal('hide'); } function userStateChange(data, triggerLoginEvent) { var data = typeof data == "undefined" ? null : data; // $('.alert-danger').remove(); $('.login-slid-div').slideUp(300); if (data) { if(data.user.avatar){ $(".userImage").html('<i><img sr...
closeDialog
identifier_name