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
simpleLSTM.py
_weight(options['dim_proj']), ortho_weight(options['dim_proj']), ortho_weight(options['dim_proj']), ortho_weight(options['dim_proj'])], axis=1) params[_p(prefix, 'W')] = W U = numpy.concatenate([ortho_weight(options['dim_proj']), ortho_weight(options['dim_proj']), ortho_weight(options['dim_proj']), ortho_weight(options['dim_proj'])], axis=1) params[_p(prefix, 'U')] = U b = numpy.zeros((4 * options['dim_proj'],)) # (4*dim) b[options['dim_proj']: 2 * options['dim_proj']] = 5 params[_p(prefix, 'b')] = b.astype(theano.config.floatX) return params def init_params(options): """ 程序用到的全局变量,以有序字典的方式存放在params中 Wemb 是 """ params = OrderedDict() # LSTM层的系数 params = param_init_lstm(options, params, prefix=options['encoder']) # 输出层的系数 params['U'] = 0.1 * numpy.random.randn(options['dim_proj'], options['ydim']).astype(theano.config.floatX) params['b'] = numpy.zeros((options['ydim'],)).astype(theano.config.floatX) return params def init_tparams(params): tparams = OrderedDict() for kk, pp in params.iteritems(): tparams[kk] = theano.shared(params[kk], name=kk) return tparams def lstm_layer(tparams, x_sequence, options, prefix='lstm'): ''' ''' nsteps = x_sequence.shape[0] # (n_t, 4*dim) state_below = (T.dot(x_sequence, tparams[_p(prefix, 'W')]) + tparams[_p(prefix, 'b')]) dim_proj = options['dim_proj'] def _slice(_x, n, dim): if _x.ndim == 3: return _x[:, :, n * dim:(n + 1) * dim] return _x[:, n * dim:(n + 1) * dim] def _step(x_, h_, c_): ''' x_ : 单元的输入数据: W x + b h_ : 前一时刻单元的输出 c_ : 前一时刻单元的Cell值 ''' preact = T.dot(h_, tparams[_p(prefix, 'U')]) # (4*dim) preact += x_ # h 延时后加权的目标维数 和 Wx+b的维数相同,都是LSTM单元的个数的4倍,可以直接相加 i = T.nnet.sigmoid(_slice(preact, 0, dim_proj)) # input gate f = T.nnet.sigmoid(_slice(preact, 1, dim_proj)) # forget gate o = T.nnet.sigmoid(_slice(preact, 2, dim_proj)) # output gate c = T.tanh(_slice(preact, 3, dim_proj)) # cell state pre c = f * c_ + i * c # cell state h = o * T.tanh(c) # unit output return h, c out_h = theano.shared(numpy.zeros((1,dim_proj), dtype=theano.config.floatX), name="out_h") out_c = theano.shared(numpy.zeros((1,dim_proj), dtype=theano.config.floatX), name="out_c") rval, updates = theano.scan(_step, sequences=state_below, outputs_info=[out_h, out_c], name=_p(prefix, '_layers'), n_steps=nsteps) return rval[0] def build_model(tparams, options): # Used for dropout. use_noise = theano.shared(numpy_floatX(0.)) # 以下变量的第1维是:时间 x = T.matrix() y = T.vector() proj = lstm_layer(tparams, x, options, prefix=options['encoder']) proj = theano.tensor.reshape(proj, (proj.shape[0], proj.shape[2])) # pred = T.tanh(T.dot(proj, tparams['U']) + tparams['b']) pred = T.dot(proj, tparams['U']) + tparams['b'] f_pred_prob = theano.function([x], pred, name='f_pred_prob') # # off = 1e-8 # if pred.dtype == 'float16': # off = 1e-6 pred = theano.tensor.flatten(pred) cost = ((pred - y)**2).sum() return use_noise, x, y, f_pred_prob, cost def adadelta(lr, tparams, grads, x, y, cost): """ An adaptive learning rate optimizer Parameters ---------- lr : Theano SharedVariable Initial learning rate tpramas: Theano SharedVariable Model parameters grads: Theano variable Gradients of cost w.r.t to parameres x: Theano variable Model inputs ma
for k, p in tparams.iteritems()] running_grads2 = [theano.shared(p.get_value() * numpy_floatX(0.), name='%s_rgrad2' % k) for k, p in tparams.iteritems()] zgup = [(zg, g) for zg, g in zip(zipped_grads, grads)] rg2up = [(rg2, 0.95 * rg2 + 0.05 * (g ** 2)) for rg2, g in zip(running_grads2, grads)] updates_1 = zgup + rg2up f_grad_shared = theano.function([x, y], cost, updates=updates_1, name='adadelta_f_grad_shared', mode='FAST_COMPILE') updir = [-T.sqrt(ru2 + 1e-6) / T.sqrt(rg2 + 1e-6) * zg for zg, ru2, rg2 in zip(zipped_grads, running_up2, running_grads2)] ru2up = [(ru2, 0.95 * ru2 + 0.05 * (ud ** 2)) for ru2, ud in zip(running_up2, updir)] param_up = [(p, p + ud) for p, ud in zip(tparams.values(), updir)] updates_2 = ru2up + param_up; f_update = theano.function([lr], [], updates=updates_2, on_unused_input='ignore', name='adadelta_f_update', mode='FAST_COMPILE') return updates_1, updates_2,f_grad_shared, f_update def train_lstm( dim_proj=40, # 输入x的个数和LSTM单元个数相等 patience=10, # Number of epoch to wait before early stop if no progress max_epochs=1500, # The maximum number of epoch to run dispFreq=10, # Display to stdout the training progress every N updates decay_c=0., # Weight decay for the classifie r applied to the U weights. lrate=0.0001, # Learning rate for sgd (not used for adadelta and rmsprop) n_words=10000, # Vocabulary size optimizer=adadelta, # sgd, adadelta and rmsprop available, sgd very hard to use, not recommanded (probably need momentum and decaying learning rate). encoder='lstm', # TODO: can be removed must be lstm. saveto='lstm_model.npz', # The best model will be saved there validFreq=370, # Compute the validation error after this number of update. saveFreq=1110, # Save the parameters after every saveFreq updates maxlen=100, # Sequence longer then this get ignored batch_size=16, # The batch size during training. valid_batch_size=64, # The batch size used for validation/test set. dataset='imdb', # Parameter for extra option noise_std=0., use_dropout=True, # if False slightly faster, but worst test error # This frequently need
sk: Theano variable Sequence mask y: Theano variable Targets cost: Theano variable Objective fucntion to minimize Notes ----- For more information, see [ADADELTA]_. .. [ADADELTA] Matthew D. Zeiler, *ADADELTA: An Adaptive Learning Rate Method*, arXiv:1212.5701. """ zipped_grads = [theano.shared(p.get_value() * numpy_floatX(0.), name='%s_grad' % k) for k, p in tparams.iteritems()] running_up2 = [theano.shared(p.get_value() * numpy_floatX(0.), name='%s_rup2' % k)
identifier_body
general.rs
Says pong on \"§ping\"\n"] async fn ping(ctx: &Context, msg: &Message) -> CommandResult { msg.reply(&ctx, "Pong§§§").await?; Ok(()) } #[command] #[description = "Just react to your hi\n"] #[aliases(hello, Hello, Hi)] async fn hi(ctx: &Context, msg: &Message) -> CommandResult { let phrase = format!("HIIII {}",&msg.author.name); msg.reply(&ctx, phrase).await?; // msg.reply(&ctx, msg.author_nick(&ctx).await.unwrap()).await?; // msg.reply(&ctx, &msg.author.name).await?; // msg.reply(&ctx, &msg.member.unwrap().nick.unwrap()).await?; msg.react(ctx, '🔥').await?; Ok(()) } #[command] #[description = "Server's Information\n"] #[aliases(server)] async fn server_info(ctx: &Context, msg: &Message) -> CommandResult { l
if let Some(description) = &guild.description { e.field("Description",description,false); }; e.field("Members",number_users,true) // .field("MSG",number_msgs,true) .field("Channels",number_channels,true) .field("Roles",number_roles,true) .field("Emojis",number_emoji,true) .field("Members in voice",number_voice_user,true); if let Some(icon_url) = guild.icon_url() { e.image(icon_url); }; e // e.footer(|f| f.icon_url(&msg.mem) }) }); msg.await.unwrap(); Ok(()) } // //T ODO mehhhh // #[command] // #[checks(Bot)] // #[description = "Talk with your self\n"] // #[aliases(talk)] // async fn talk_to_self(ctx: &Context, msg: &Message) -> CommandResult { // msg.reply(&ctx, "Hello, myself!").await?; // Ok(()) // } // #[check] // #[name = "Bot"] // async fn bot_check(ctx: &Context, msg: &Message) -> CheckResult { // if let Some(member) = msg.member(&ctx.cache) { // let user = member.user.read(); // user.bot.into() // } else { // false.into() // } // } #[command] #[description = "Bot will reply with pretty embed containing title and description of bot"] async fn about(ctx: & Context, msg: &Message) -> CommandResult { // Obtain Bot's profile pic: cache -> current info -> bot user -> bot icon // let cache_http = &ctx.http; // let current_info = cache_http.get_current_application_info(); // let current_info = match cache_http.get_current_application_info().await { // Ok(c) => c, // Err(err) => return Err(err.to_string()), // }; // // let bot_user = current_info.id.to_user(cache_http); // let bot_user = match current_info.id.to_user(cache_http).await { // Ok(u) => u, // // Err(err) => return Err(CommandError(err.to_string())), // Err(err) => return Err(err.to_string()), // }; // let bot_icon = match bot_user.avatar_url(){ // Some(u) => u, // None => bot_user.default_avatar_url(), // }; // // let bot_icon = &ctx.http.get_current_application_info().await.id.to_user(&ctx.http).avatar_url; // let bot_icon = match &ctx.http.get_current_application_info().await { // Ok(u) => u.id// .to_user(&ctx.http).avatar_url // , // Err(err) => return Err(err.to_string()), // }; // let bot_icon = match &bot_icon.to_user(&ctx.http).await { // Ok(u) => u// .avatar_url() // , // Err(err) => return Err(err.to_string()), // }; // let bot_icon = match bot_icon.avatar_url() { // Some(u) => u, // None => bot_user.default_avatar_url(), // }; let msg = msg.channel_id.send_message(&ctx.http, |m| { m.embed(|e| { e.title("`§23`"); e.description("Hellooooo!!!\nMy name is Caracol Tobias, and I'm a \"carangueijo\"(crab)\n"); //TODO: This dont work // e.thumbnail(bot_icon); // false = not inline; e.fields(vec![ ("Discord", "Mariii_01🌹#2773\nYour Friend Elmo#9329", false), ("Source Code", "[Mariii-23/discord_bot_rust](https://github.com/Mariii-23/discord_bot_rust.git)", false), ]); e }); m }); msg.await.unwrap(); Ok(()) } #[command] #[description = "Bot will generate an embed based on input."] #[usage = "title description <image_link>"] #[example = "rust hihih https://docs.rs/rust-logo-20210302-1.52.0-nightly-35dbef235.png"] async fn embed(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let title = args.single::<String>()?; let description = args.single::<String>()?; let image = args.single::<String>().unwrap_or("false".to_string()); let link = if image == "false" { "https://i.imgur.com/pMBcpoq.png".to_string() } else { image.replace("<", "").replace(">", "") }; let msg = msg.channel_id.send_message(&ctx.http, |m| { m.embed(|e| { e.title(title); e.description(description); e.image(link) }); m }); msg.await.unwrap(); Ok(()) } #[command] #[description = "Create a poll, with or without options\n"] #[usage = "\"title\" \"options\""] #[example = "\"Cinema tonight?\""] #[example = "\"Choose one options\" \"Funny\" \"Great\" \"Cool\""] #[min_args(1)] #[max_args(27)] async fn poll(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { // let abc: Vec<char> = vec![ // '🇦', '🇧', '🇨', '🇩', '🇪', '🇫', '🇬', '🇭', '🇮', '🇯', '🇰', '🇱', '🇲', '🇳', '🇴', '🇵', '🇶', '🇷', // '🇸', '🇹', '🇺', '🇻', '🇼', '🇽', '🇾', '🇿', // ]; let question = args.single_quoted::<String>()?; let answers = args .quoted() .iter::<String>() .filter_map(|x| x.ok()) .collect::<Vec<_>>(); // let args = msg.content[2..].split_once(" ").unwrap(); // let mut title = String::from("Poll: ") + args.1; let title = String::from("Poll: ") + &question; // let options = args.1.split(';'); let mut description = String::new(); // let mut count_options: usize = 0; let count_options: usize = answers.len(); let emojis = (0..count_options) .map(|i| std::char::from_u32('🇦' as u32 + i as u32).expect("Failed to format emoji")) .collect::<Vec<_>>(); let mut count = 0; for &emoji in &emojis { let option = answers.get(count).unwrap(); let string = format!("{} -> {}\n", ReactionType::Unicode(emoji.to_string()), option); description.push_str(&string); count +=1; } let embed = msg.channel_id.send_message(&ctx, |m| { m.embed(|e| { e.title(&title).description(&description).footer(|f| { f.icon_url("https://www.clipartkey.com/mpngs/m/203-2037526_diamonds-clipart-blue-diamond-logo-png-hd.png") .text("React with one emoji") }) }) }); let poll = embed.await.unwrap(); if count_options == 0 { poll.react(&ctx, '✅').await?; poll.react(&ctx, '❌').await?; } else { for &emoji in &
et guild = match ctx.cache.guild(&msg.guild_id.unwrap()).await { Some(guild) => guild, None => { msg.reply(ctx, "Error" ).await; return Ok(()); } }; let number_users = guild.member_count; // let number_msgs = channel.message_count; let number_channels = guild.channels.len(); let number_emoji = guild.emojis.len(); let number_voice_user = guild.voice_states.len(); let number_roles = guild.roles.len(); let msg = msg.channel_id.send_message(&ctx.http, |m| { m.embed(|e| { e.colour(Colour::BLITZ_BLUE) .title(&guild.name);
identifier_body
general.rs
"Bot will reply with pretty embed containing title and description of bot"] async fn about(ctx: & Context, msg: &Message) -> CommandResult { // Obtain Bot's profile pic: cache -> current info -> bot user -> bot icon // let cache_http = &ctx.http; // let current_info = cache_http.get_current_application_info(); // let current_info = match cache_http.get_current_application_info().await { // Ok(c) => c, // Err(err) => return Err(err.to_string()), // }; // // let bot_user = current_info.id.to_user(cache_http); // let bot_user = match current_info.id.to_user(cache_http).await { // Ok(u) => u, // // Err(err) => return Err(CommandError(err.to_string())), // Err(err) => return Err(err.to_string()), // }; // let bot_icon = match bot_user.avatar_url(){ // Some(u) => u, // None => bot_user.default_avatar_url(), // }; // // let bot_icon = &ctx.http.get_current_application_info().await.id.to_user(&ctx.http).avatar_url; // let bot_icon = match &ctx.http.get_current_application_info().await { // Ok(u) => u.id// .to_user(&ctx.http).avatar_url // , // Err(err) => return Err(err.to_string()), // }; // let bot_icon = match &bot_icon.to_user(&ctx.http).await { // Ok(u) => u// .avatar_url() // , // Err(err) => return Err(err.to_string()), // }; // let bot_icon = match bot_icon.avatar_url() { // Some(u) => u, // None => bot_user.default_avatar_url(), // }; let msg = msg.channel_id.send_message(&ctx.http, |m| { m.embed(|e| { e.title("`§23`"); e.description("Hellooooo!!!\nMy name is Caracol Tobias, and I'm a \"carangueijo\"(crab)\n"); //TODO: This dont work // e.thumbnail(bot_icon); // false = not inline; e.fields(vec![ ("Discord", "Mariii_01🌹#2773\nYour Friend Elmo#9329", false), ("Source Code", "[Mariii-23/discord_bot_rust](https://github.com/Mariii-23/discord_bot_rust.git)", false), ]); e }); m }); msg.await.unwrap(); Ok(()) } #[command] #[description = "Bot will generate an embed based on input."] #[usage = "title description <image_link>"] #[example = "rust hihih https://docs.rs/rust-logo-20210302-1.52.0-nightly-35dbef235.png"] async fn embed(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let title = args.single::<String>()?; let description = args.single::<String>()?; let image = args.single::<String>().unwrap_or("false".to_string()); let link = if image == "false" { "https://i.imgur.com/pMBcpoq.png".to_string() } else { image.replace("<", "").replace(">", "") }; let msg = msg.channel_id.send_message(&ctx.http, |m| { m.embed(|e| { e.title(title); e.description(description); e.image(link) }); m }); msg.await.unwrap(); Ok(()) } #[command] #[description = "Create a poll, with or without options\n"] #[usage = "\"title\" \"options\""] #[example = "\"Cinema tonight?\""] #[example = "\"Choose one options\" \"Funny\" \"Great\" \"Cool\""] #[min_args(1)] #[max_args(27)] async fn poll(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { // let abc: Vec<char> = vec![ // '🇦', '🇧', '🇨', '🇩', '🇪', '🇫', '🇬', '🇭', '🇮', '🇯', '🇰', '🇱', '🇲', '🇳', '🇴', '🇵', '🇶', '🇷', // '🇸', '🇹', '🇺', '🇻', '🇼', '🇽', '🇾', '🇿', // ]; let question = args.single_quoted::<String>()?; let answers = args .quoted() .iter::<String>() .filter_map(|x| x.ok()) .collect::<Vec<_>>(); // let args = msg.content[2..].split_once(" ").unwrap(); // let mut title = String::from("Poll: ") + args.1; let title = String::from("Poll: ") + &question; // let options = args.1.split(';'); let mut description = String::new(); // let mut count_options: usize = 0; let count_options: usize = answers.len(); let emojis = (0..count_options) .map(|i| std::char::from_u32('🇦' as u32 + i as u32).expect("Failed to format emoji")) .collect::<Vec<_>>(); let mut count = 0; for &emoji in &emojis { let option = answers.get(count).unwrap(); let string = format!("{} -> {}\n", ReactionType::Unicode(emoji.to_string()), option); description.push_str(&string); count +=1; } let embed = msg.channel_id.send_message(&ctx, |m| { m.embed(|e| { e.title(&title).description(&description).footer(|f| { f.icon_url("https://www.clipartkey.com/mpngs/m/203-2037526_diamonds-clipart-blue-diamond-logo-png-hd.png") .text("React with one emoji") }) }) }); let poll = embed.await.unwrap(); if count_options == 0 { poll.react(&ctx, '✅').await?; poll.react(&ctx, '❌').await?; } else { for &emoji in &emojis { poll .react(&ctx.http, ReactionType::Unicode(emoji.to_string())) .await?; } } Ok(()) } // use std::fs::File; // use std::io::{self, prelude::*, BufReader}; #[command] #[description("I will choose one of your given lines\nBetween the given lines it is necessary to have a enter\n")] #[usage = "\noption 1\noption 2\n..."] #[example = "\nFunny\nGreat\nCool"] #[min_args(1)] //TODO add feature to give a file and choose one random line of that file. //TODO you can give a number and the bot will given x random lines async fn which(ctx: &Context, msg: &Message) -> CommandResult { // let file_name = msg.content[2..].split_once(" ").unwrap(); // if std::path::Path::new(&file_name.1).exists() { // let file = File::open(&file_name.1)?; // let reader = BufReader::new(file); // for line in reader.lines() { // // println!("{}", line?); // msg.channel_id.say(&ctx,line?); // } // } else { // msg.reply(&ctx, "The path given dont exist.").await?; // } let args = msg.content[2..].split_once("\n").unwrap(); let args = args.1.split("\n"); let mut count_options: usize = 0; let mut v: Vec<String> = Vec::new(); for s in args { count_options+=1; v.push(s.to_string()); } extern crate rand; use rand::Rng; let random_number = rand::thread_rng().gen_range(1,&count_options); match v.get(random_number) { Some(elem) => { let string = format!("I choose -> {}\n", elem); msg.reply(&ctx, string).await?; }, None => { msg.reply(&ctx, "Something happen\nError\n").await?;}, } Ok(()) } #[command] #[description = "Shows person's avatar\n"] #[usage = "\"person\""] #[example = "@person1"] #[max_args(1)] async fn avatar(ctx: &Context, msg: &Message) -> CommandResult { let person = &msg.mentions; if person.is_empty() && msg.content.is_empty() { msg.channel_id.say(&ctx.http, "Error! Command is wrong! Try §help").await?; return Ok(()); } let msg = msg.channel_id.send_message(&ctx.http, |m| { m.embed(|e| { use serenity::utils::Colour; e.colour(Colour::BLITZ_BLUE); if person.is_empty() { e.title(&msg.author.name); e.image(&msg.author.avatar_url().unwr
ap()); } else { e.title(&person[0].name); e.image(person[0].av
conditional_block
general.rs
Says pong on \"§ping\"\n"] async fn ping(ctx: &Context, msg: &Message) -> CommandResult { msg.reply(&ctx, "Pong§§§").await?; Ok(()) } #[command] #[description = "Just react to your hi\n"] #[aliases(hello, Hello, Hi)] async fn hi(ctx: &Context, msg: &Message) -> CommandResult { let phrase = format!("HIIII {}",&msg.author.name); msg.reply(&ctx, phrase).await?; // msg.reply(&ctx, msg.author_nick(&ctx).await.unwrap()).await?; // msg.reply(&ctx, &msg.author.name).await?; // msg.reply(&ctx, &msg.member.unwrap().nick.unwrap()).await?; msg.react(ctx, '🔥').await?; Ok(()) } #[command] #[description = "Server's Information\n"] #[aliases(server)] async fn server_info(ctx: &Context, msg: &Message) -> CommandResult { let guild = match ctx.cache.guild(&msg.guild_id.unwrap()).await { Some(guild) => guild, None => { msg.reply(ctx, "Error" ).await; return Ok(()); } }; let number_users = guild.member_count; // let number_msgs = channel.message_count; let number_channels = guild.channels.len(); let number_emoji = guild.emojis.len(); let number_voice_user = guild.voice_states.len(); let number_roles = guild.roles.len(); let msg = msg.channel_id.send_message(&ctx.http, |m| { m.embed(|e| { e.colour(Colour::BLITZ_BLUE) .title(&guild.name); if let Some(description) = &guild.description { e.field("Description",description,false); }; e.field("Members",number_users,true) // .field("MSG",number_msgs,true) .field("Channels",number_channels,true) .field("Roles",number_roles,true) .field("Emojis",number_emoji,true) .field("Members in voice",number_voice_user,true); if let Some(icon_url) = guild.icon_url() { e.image(icon_url); }; e // e.footer(|f| f.icon_url(&msg.mem) }) }); msg.await.unwrap(); Ok(()) } // //TODO mehhhh // #[command] // #[checks(Bot)] // #[description = "Talk with your self\n"] // #[aliases(talk)] // async fn talk_to_self(ctx: &Context, msg: &Message) -> CommandResult { // msg.reply(&ctx, "Hello, myself!").await?; // Ok(())
// } // #[check] // #[name = "Bot"] // async fn bot_check(ctx: &Context, msg: &Message) -> CheckResult { // if let Some(member) = msg.member(&ctx.cache) { // let user = member.user.read(); // user.bot.into() // } else { // false.into() // } // } #[command] #[description = "Bot will reply with pretty embed containing title and description of bot"] async fn about(ctx: & Context, msg: &Message) -> CommandResult { // Obtain Bot's profile pic: cache -> current info -> bot user -> bot icon // let cache_http = &ctx.http; // let current_info = cache_http.get_current_application_info(); // let current_info = match cache_http.get_current_application_info().await { // Ok(c) => c, // Err(err) => return Err(err.to_string()), // }; // // let bot_user = current_info.id.to_user(cache_http); // let bot_user = match current_info.id.to_user(cache_http).await { // Ok(u) => u, // // Err(err) => return Err(CommandError(err.to_string())), // Err(err) => return Err(err.to_string()), // }; // let bot_icon = match bot_user.avatar_url(){ // Some(u) => u, // None => bot_user.default_avatar_url(), // }; // // let bot_icon = &ctx.http.get_current_application_info().await.id.to_user(&ctx.http).avatar_url; // let bot_icon = match &ctx.http.get_current_application_info().await { // Ok(u) => u.id// .to_user(&ctx.http).avatar_url // , // Err(err) => return Err(err.to_string()), // }; // let bot_icon = match &bot_icon.to_user(&ctx.http).await { // Ok(u) => u// .avatar_url() // , // Err(err) => return Err(err.to_string()), // }; // let bot_icon = match bot_icon.avatar_url() { // Some(u) => u, // None => bot_user.default_avatar_url(), // }; let msg = msg.channel_id.send_message(&ctx.http, |m| { m.embed(|e| { e.title("`§23`"); e.description("Hellooooo!!!\nMy name is Caracol Tobias, and I'm a \"carangueijo\"(crab)\n"); //TODO: This dont work // e.thumbnail(bot_icon); // false = not inline; e.fields(vec![ ("Discord", "Mariii_01🌹#2773\nYour Friend Elmo#9329", false), ("Source Code", "[Mariii-23/discord_bot_rust](https://github.com/Mariii-23/discord_bot_rust.git)", false), ]); e }); m }); msg.await.unwrap(); Ok(()) } #[command] #[description = "Bot will generate an embed based on input."] #[usage = "title description <image_link>"] #[example = "rust hihih https://docs.rs/rust-logo-20210302-1.52.0-nightly-35dbef235.png"] async fn embed(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let title = args.single::<String>()?; let description = args.single::<String>()?; let image = args.single::<String>().unwrap_or("false".to_string()); let link = if image == "false" { "https://i.imgur.com/pMBcpoq.png".to_string() } else { image.replace("<", "").replace(">", "") }; let msg = msg.channel_id.send_message(&ctx.http, |m| { m.embed(|e| { e.title(title); e.description(description); e.image(link) }); m }); msg.await.unwrap(); Ok(()) } #[command] #[description = "Create a poll, with or without options\n"] #[usage = "\"title\" \"options\""] #[example = "\"Cinema tonight?\""] #[example = "\"Choose one options\" \"Funny\" \"Great\" \"Cool\""] #[min_args(1)] #[max_args(27)] async fn poll(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { // let abc: Vec<char> = vec![ // '🇦', '🇧', '🇨', '🇩', '🇪', '🇫', '🇬', '🇭', '🇮', '🇯', '🇰', '🇱', '🇲', '🇳', '🇴', '🇵', '🇶', '🇷', // '🇸', '🇹', '🇺', '🇻', '🇼', '🇽', '🇾', '🇿', // ]; let question = args.single_quoted::<String>()?; let answers = args .quoted() .iter::<String>() .filter_map(|x| x.ok()) .collect::<Vec<_>>(); // let args = msg.content[2..].split_once(" ").unwrap(); // let mut title = String::from("Poll: ") + args.1; let title = String::from("Poll: ") + &question; // let options = args.1.split(';'); let mut description = String::new(); // let mut count_options: usize = 0; let count_options: usize = answers.len(); let emojis = (0..count_options) .map(|i| std::char::from_u32('🇦' as u32 + i as u32).expect("Failed to format emoji")) .collect::<Vec<_>>(); let mut count = 0; for &emoji in &emojis { let option = answers.get(count).unwrap(); let string = format!("{} -> {}\n", ReactionType::Unicode(emoji.to_string()), option); description.push_str(&string); count +=1; } let embed = msg.channel_id.send_message(&ctx, |m| { m.embed(|e| { e.title(&title).description(&description).footer(|f| { f.icon_url("https://www.clipartkey.com/mpngs/m/203-2037526_diamonds-clipart-blue-diamond-logo-png-hd.png") .text("React with one emoji") }) }) }); let poll = embed.await.unwrap(); if count_options == 0 { poll.react(&ctx, '✅').await?; poll.react(&ctx, '❌').await?; } else { for &emoji in &emojis {
random_line_split
general.rs
Says pong on \"§ping\"\n"] async fn ping(ctx: &Context, msg: &Message) -> CommandResult { msg.reply(&ctx, "Pong§§§").await?; Ok(()) } #[command] #[description = "Just react to your hi\n"] #[aliases(hello, Hello, Hi)] async fn hi(ct
&Context, msg: &Message) -> CommandResult { let phrase = format!("HIIII {}",&msg.author.name); msg.reply(&ctx, phrase).await?; // msg.reply(&ctx, msg.author_nick(&ctx).await.unwrap()).await?; // msg.reply(&ctx, &msg.author.name).await?; // msg.reply(&ctx, &msg.member.unwrap().nick.unwrap()).await?; msg.react(ctx, '🔥').await?; Ok(()) } #[command] #[description = "Server's Information\n"] #[aliases(server)] async fn server_info(ctx: &Context, msg: &Message) -> CommandResult { let guild = match ctx.cache.guild(&msg.guild_id.unwrap()).await { Some(guild) => guild, None => { msg.reply(ctx, "Error" ).await; return Ok(()); } }; let number_users = guild.member_count; // let number_msgs = channel.message_count; let number_channels = guild.channels.len(); let number_emoji = guild.emojis.len(); let number_voice_user = guild.voice_states.len(); let number_roles = guild.roles.len(); let msg = msg.channel_id.send_message(&ctx.http, |m| { m.embed(|e| { e.colour(Colour::BLITZ_BLUE) .title(&guild.name); if let Some(description) = &guild.description { e.field("Description",description,false); }; e.field("Members",number_users,true) // .field("MSG",number_msgs,true) .field("Channels",number_channels,true) .field("Roles",number_roles,true) .field("Emojis",number_emoji,true) .field("Members in voice",number_voice_user,true); if let Some(icon_url) = guild.icon_url() { e.image(icon_url); }; e // e.footer(|f| f.icon_url(&msg.mem) }) }); msg.await.unwrap(); Ok(()) } // //TODO mehhhh // #[command] // #[checks(Bot)] // #[description = "Talk with your self\n"] // #[aliases(talk)] // async fn talk_to_self(ctx: &Context, msg: &Message) -> CommandResult { // msg.reply(&ctx, "Hello, myself!").await?; // Ok(()) // } // #[check] // #[name = "Bot"] // async fn bot_check(ctx: &Context, msg: &Message) -> CheckResult { // if let Some(member) = msg.member(&ctx.cache) { // let user = member.user.read(); // user.bot.into() // } else { // false.into() // } // } #[command] #[description = "Bot will reply with pretty embed containing title and description of bot"] async fn about(ctx: & Context, msg: &Message) -> CommandResult { // Obtain Bot's profile pic: cache -> current info -> bot user -> bot icon // let cache_http = &ctx.http; // let current_info = cache_http.get_current_application_info(); // let current_info = match cache_http.get_current_application_info().await { // Ok(c) => c, // Err(err) => return Err(err.to_string()), // }; // // let bot_user = current_info.id.to_user(cache_http); // let bot_user = match current_info.id.to_user(cache_http).await { // Ok(u) => u, // // Err(err) => return Err(CommandError(err.to_string())), // Err(err) => return Err(err.to_string()), // }; // let bot_icon = match bot_user.avatar_url(){ // Some(u) => u, // None => bot_user.default_avatar_url(), // }; // // let bot_icon = &ctx.http.get_current_application_info().await.id.to_user(&ctx.http).avatar_url; // let bot_icon = match &ctx.http.get_current_application_info().await { // Ok(u) => u.id// .to_user(&ctx.http).avatar_url // , // Err(err) => return Err(err.to_string()), // }; // let bot_icon = match &bot_icon.to_user(&ctx.http).await { // Ok(u) => u// .avatar_url() // , // Err(err) => return Err(err.to_string()), // }; // let bot_icon = match bot_icon.avatar_url() { // Some(u) => u, // None => bot_user.default_avatar_url(), // }; let msg = msg.channel_id.send_message(&ctx.http, |m| { m.embed(|e| { e.title("`§23`"); e.description("Hellooooo!!!\nMy name is Caracol Tobias, and I'm a \"carangueijo\"(crab)\n"); //TODO: This dont work // e.thumbnail(bot_icon); // false = not inline; e.fields(vec![ ("Discord", "Mariii_01🌹#2773\nYour Friend Elmo#9329", false), ("Source Code", "[Mariii-23/discord_bot_rust](https://github.com/Mariii-23/discord_bot_rust.git)", false), ]); e }); m }); msg.await.unwrap(); Ok(()) } #[command] #[description = "Bot will generate an embed based on input."] #[usage = "title description <image_link>"] #[example = "rust hihih https://docs.rs/rust-logo-20210302-1.52.0-nightly-35dbef235.png"] async fn embed(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { let title = args.single::<String>()?; let description = args.single::<String>()?; let image = args.single::<String>().unwrap_or("false".to_string()); let link = if image == "false" { "https://i.imgur.com/pMBcpoq.png".to_string() } else { image.replace("<", "").replace(">", "") }; let msg = msg.channel_id.send_message(&ctx.http, |m| { m.embed(|e| { e.title(title); e.description(description); e.image(link) }); m }); msg.await.unwrap(); Ok(()) } #[command] #[description = "Create a poll, with or without options\n"] #[usage = "\"title\" \"options\""] #[example = "\"Cinema tonight?\""] #[example = "\"Choose one options\" \"Funny\" \"Great\" \"Cool\""] #[min_args(1)] #[max_args(27)] async fn poll(ctx: &Context, msg: &Message, mut args: Args) -> CommandResult { // let abc: Vec<char> = vec![ // '🇦', '🇧', '🇨', '🇩', '🇪', '🇫', '🇬', '🇭', '🇮', '🇯', '🇰', '🇱', '🇲', '🇳', '🇴', '🇵', '🇶', '🇷', // '🇸', '🇹', '🇺', '🇻', '🇼', '🇽', '🇾', '🇿', // ]; let question = args.single_quoted::<String>()?; let answers = args .quoted() .iter::<String>() .filter_map(|x| x.ok()) .collect::<Vec<_>>(); // let args = msg.content[2..].split_once(" ").unwrap(); // let mut title = String::from("Poll: ") + args.1; let title = String::from("Poll: ") + &question; // let options = args.1.split(';'); let mut description = String::new(); // let mut count_options: usize = 0; let count_options: usize = answers.len(); let emojis = (0..count_options) .map(|i| std::char::from_u32('🇦' as u32 + i as u32).expect("Failed to format emoji")) .collect::<Vec<_>>(); let mut count = 0; for &emoji in &emojis { let option = answers.get(count).unwrap(); let string = format!("{} -> {}\n", ReactionType::Unicode(emoji.to_string()), option); description.push_str(&string); count +=1; } let embed = msg.channel_id.send_message(&ctx, |m| { m.embed(|e| { e.title(&title).description(&description).footer(|f| { f.icon_url("https://www.clipartkey.com/mpngs/m/203-2037526_diamonds-clipart-blue-diamond-logo-png-hd.png") .text("React with one emoji") }) }) }); let poll = embed.await.unwrap(); if count_options == 0 { poll.react(&ctx, '✅').await?; poll.react(&ctx, '❌').await?; } else { for &emoji in &emojis {
x:
identifier_name
xmlReportBuilder.go
Contents string `xml:",chardata"` } // JUnitSkipMessage contains the reason why a testcase was skipped. type JUnitSkipMessage struct { Message string `xml:"message,attr"` } // JUnitProperty represents a key/value pair used to define properties. type JUnitProperty struct { Name string `xml:"name,attr"` Value string `xml:"value,attr"` } // JUnitFailure contains data related to a failed test. type JUnitFailure struct { Message string `xml:"message,attr"` Type string `xml:"type,attr"` Contents string `xml:",chardata"` } type XmlBuilder struct { currentId int suites JUnitTestSuites } func NewXmlBuilder(id int) *XmlBuilder { return &XmlBuilder{currentId: id} } type StepFailure struct { Message string Err string } func (x *XmlBuilder) GetXmlContent(executionSuiteResult *gauge_messages.SuiteExecutionResult) ([]byte, error) { suiteResult := executionSuiteResult.GetSuiteResult() x.suites = JUnitTestSuites{} for _, result := range suiteResult.GetSpecResults() { x.getSpecContent(result) } bytes, err := xml.MarshalIndent(x.suites, "", "\t") if err != nil { return nil, err } return bytes, nil } func (x *XmlBuilder) getSpecContent(result *gauge_messages.ProtoSpecResult) { x.currentId += 1 hostName, err := os.Hostname() if err != nil { hostName = hostname } ts := x.getTestSuite(result, hostName) if hasParseErrors(result.Errors) { ts.Failures++ ts.TestCases = append(ts.TestCases, getErrorTestCase(result)) } else { s := result.GetProtoSpec() ts.Failures += len(s.GetPreHookFailures()) + len(s.GetPostHookFailures()) for _, test := range result.GetProtoSpec().GetItems() { if test.GetItemType() == gauge_messages.ProtoItem_Scenario { x.getScenarioContent(result, test.GetScenario(), &ts) } else if test.GetItemType() == gauge_messages.ProtoItem_TableDrivenScenario { x.getTableDrivenScenarioContent(result, test.GetTableDrivenScenario(), &ts) } } } x.suites.Suites = append(x.suites.Suites, ts) } func getErrorTestCase(result *gauge_messages.ProtoSpecResult) JUnitTestCase { var failures []string for _, e := range result.Errors { t := "Parse" if e.Type == gauge_messages.Error_VALIDATION_ERROR { t = "Validation" } failures = append(failures, fmt.Sprintf("[%s Error] %s", t, e.Message)) } return JUnitTestCase{ Classname: getSpecName(result.GetProtoSpec()), Name: getSpecName(result.GetProtoSpec()), Time: formatTime(int(result.GetExecutionTime())), Failure: &JUnitFailure{ Message: "Parse/Validation Errors", Type: "Parse/Validation Errors", Contents: strings.Join(failures, "\n"), }, } } func (x *XmlBuilder) getScenarioContent(result *gauge_messages.ProtoSpecResult, scenario *gauge_messages.ProtoScenario, ts *JUnitTestSuite) { testCase := JUnitTestCase{ Classname: getSpecName(result.GetProtoSpec()), Name: scenario.GetScenarioHeading(), Time: formatTime(int(scenario.GetExecutionTime())), Failure: nil, } if scenario.GetExecutionStatus() == gauge_messages.ExecutionStatus_FAILED { var errors []string failures := x.getFailure(scenario) message := "Multiple failures" for _, step := range failures { errors = append(errors, fmt.Sprintf("%s\n%s", step.Message, step.Err)) } if len(failures) == 1 { message = failures[0].Message errors = []string{failures[0].Err} } testCase.Failure = &JUnitFailure{ Message: message, Type: message, Contents: strings.Join(errors, "\n\n"), } } else if scenario.GetExecutionStatus() == gauge_messages.ExecutionStatus_SKIPPED { testCase.SkipMessage = &JUnitSkipMessage{ Message: strings.Join(scenario.SkipErrors, "\n"), } } ts.TestCases = append(ts.TestCases, testCase) } func (x *XmlBuilder) getTableDrivenScenarioContent(result *gauge_messages.ProtoSpecResult, tableDriven *gauge_messages.ProtoTableDrivenScenario, ts *JUnitTestSuite) { if tableDriven.GetScenario() != nil { scenario := tableDriven.GetScenario() scenario.ScenarioHeading += " " + strconv.Itoa(int(tableDriven.GetTableRowIndex())+1) x.getScenarioContent(result, scenario, ts) } } func (x *XmlBuilder) getTestSuite(result *gauge_messages.ProtoSpecResult, hostName string) JUnitTestSuite { now := time.Now() formattedNow := fmt.Sprintf(timeStampFormat, now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second()) systemError := SystemErr{} if result.GetScenarioSkippedCount() > 0 { systemError.Contents = fmt.Sprintf("Validation failed, %d Scenarios were skipped.", result.GetScenarioSkippedCount()) } return JUnitTestSuite{ Id: int(x.currentId), Tests: int(result.GetScenarioCount()), Failures: int(result.GetScenarioFailedCount()), Time: formatTime(int(result.GetExecutionTime())), Timestamp: formattedNow, Name: getSpecName(result.GetProtoSpec()), Errors: 0, Hostname: hostName, Package: result.GetProtoSpec().GetFileName(), Properties: []JUnitProperty{}, TestCases: []JUnitTestCase{}, SkippedTestCount: int(result.GetScenarioSkippedCount()), SystemOutput: SystemOut{}, SystemError: systemError, } } func (x *XmlBuilder) getFailure(test *gauge_messages.ProtoScenario) []StepFailure { errInfo := []StepFailure{} hookInfo := x.getFailureFromExecutionResult(test.GetScenarioHeading(), test.GetPreHookFailure(), test.GetPostHookFailure(), nil, "Scenario ") if hookInfo.Message != "" { return append(errInfo, hookInfo) } contextsInfo := x.getFailureFromSteps(test.GetContexts(), "Step ") if len(contextsInfo) > 0 { errInfo = append(errInfo, contextsInfo...) } stepsInfo := x.getFailureFromSteps(test.GetScenarioItems(), "Step ") if len(stepsInfo) > 0 { errInfo = append(errInfo, stepsInfo...) } return errInfo } func (x *XmlBuilder) getFailureFromSteps(items []*gauge_messages.ProtoItem, prefix string) []StepFailure { errInfo := []StepFailure{} for _, item := range items { stepInfo := StepFailure{Message: "", Err: ""} if item.GetItemType() == gauge_messages.ProtoItem_Step { preHookFailure := item.GetStep().GetStepExecutionResult().GetPreHookFailure() postHookFailure := item.GetStep().GetStepExecutionResult().GetPostHookFailure() result := item.GetStep().GetStepExecutionResult().GetExecutionResult() stepInfo = x.getFailureFromExecutionResult(item.GetStep().GetActualText(), preHookFailure, postHookFailure, result, prefix) } else if item.GetItemType() == gauge_messages.ProtoItem_Concept { errInfo = append(errInfo, x.getFailureFromSteps(item.GetConcept().GetSteps(), "Concept ")...) } if stepInfo.Message != "" { errInfo = append(errInfo, stepInfo) } } return errInfo } func (x *XmlBuilder) getFailureFromExecutionResult(name string, preHookFailure *gauge_messages.ProtoHookFailure, postHookFailure *gauge_messages.ProtoHookFailure, stepExecutionResult *gauge_messages.ProtoExecutionResult, prefix string) StepFailure { if len(name) > 0 { name = fmt.Sprintf("%s\n", name) } if preHookFailure != nil { return StepFailure{Message: fmt.Sprintf("%s%s%s: '%s'", name, prefix, preHookFailureMsg, preHookFailure.GetErrorMessage()), Err: preHookFailure.GetStackTrace()} } else if postHookFailure != nil { return StepFailure{Message: fmt.Sprintf("%s%s%s: '%s'", name, prefix, postHookFailureMsg, postHookFailure.GetErrorMessage()), Err: postHookFailure.GetStackTrace()} } else if stepExecutionResult != nil && stepExecutionResult.GetFailed() { return StepFailure{Message: fmt.Sprintf("%s%s%s: '%s'", name, prefix, executionFailureMsg, stepExecutionResult.GetErrorMessage()), Err: stepExecutionResult.GetStackTrace()} } return StepFailure{"", ""} } func getSpecName(spec *gauge_messages.ProtoSpec) string { if strings.TrimSpace(spec.SpecHeading) == "" { return filepath.Base(spec.GetFileName()) } return spec.SpecHeading } func hasParseErrors(errors []*gauge_messages.Error) bool { for _, e := range errors { if e.Type == gauge_messages.Error_PARSE_ERROR { return true } } return false } func
formatTime
identifier_name
xmlReportBuilder.go
// testcases. type JUnitTestSuite struct { XMLName xml.Name `xml:"testsuite"` Id int `xml:"id,attr"` Tests int `xml:"tests,attr"` Failures int `xml:"failures,attr"` Package string `xml:"package,attr"` Time string `xml:"time,attr"` Timestamp string `xml:"timestamp,attr"` Name string `xml:"name,attr"` Errors int `xml:"errors,attr"` SkippedTestCount int `xml:"skipped,attr,omitempty"` Hostname string `xml:"hostname,attr"` Properties []JUnitProperty `xml:"properties>property,omitempty"` TestCases []JUnitTestCase `xml:"testcase"` SystemOutput SystemOut SystemError SystemErr } // JUnitTestCase is a single test case with its result. type JUnitTestCase struct { XMLName xml.Name `xml:"testcase"` Classname string `xml:"classname,attr"` Name string `xml:"name,attr"` Time string `xml:"time,attr"` SkipMessage *JUnitSkipMessage `xml:"skipped,omitempty"` Failure *JUnitFailure `xml:"failure,omitempty"` } type SystemOut struct { XMLName xml.Name `xml:"system-out"` Contents string `xml:",chardata"` } type SystemErr struct { XMLName xml.Name `xml:"system-err"` Contents string `xml:",chardata"` } // JUnitSkipMessage contains the reason why a testcase was skipped. type JUnitSkipMessage struct { Message string `xml:"message,attr"` } // JUnitProperty represents a key/value pair used to define properties. type JUnitProperty struct { Name string `xml:"name,attr"` Value string `xml:"value,attr"` } // JUnitFailure contains data related to a failed test. type JUnitFailure struct { Message string `xml:"message,attr"` Type string `xml:"type,attr"` Contents string `xml:",chardata"` } type XmlBuilder struct { currentId int suites JUnitTestSuites } func NewXmlBuilder(id int) *XmlBuilder { return &XmlBuilder{currentId: id} } type StepFailure struct { Message string Err string } func (x *XmlBuilder) GetXmlContent(executionSuiteResult *gauge_messages.SuiteExecutionResult) ([]byte, error) { suiteResult := executionSuiteResult.GetSuiteResult() x.suites = JUnitTestSuites{} for _, result := range suiteResult.GetSpecResults() { x.getSpecContent(result) } bytes, err := xml.MarshalIndent(x.suites, "", "\t") if err != nil { return nil, err } return bytes, nil } func (x *XmlBuilder) getSpecContent(result *gauge_messages.ProtoSpecResult) { x.currentId += 1 hostName, err := os.Hostname() if err != nil { hostName = hostname } ts := x.getTestSuite(result, hostName) if hasParseErrors(result.Errors) { ts.Failures++ ts.TestCases = append(ts.TestCases, getErrorTestCase(result)) } else { s := result.GetProtoSpec() ts.Failures += len(s.GetPreHookFailures()) + len(s.GetPostHookFailures()) for _, test := range result.GetProtoSpec().GetItems() { if test.GetItemType() == gauge_messages.ProtoItem_Scenario { x.getScenarioContent(result, test.GetScenario(), &ts) } else if test.GetItemType() == gauge_messages.ProtoItem_TableDrivenScenario { x.getTableDrivenScenarioContent(result, test.GetTableDrivenScenario(), &ts) } } } x.suites.Suites = append(x.suites.Suites, ts) } func getErrorTestCase(result *gauge_messages.ProtoSpecResult) JUnitTestCase { var failures []string for _, e := range result.Errors { t := "Parse" if e.Type == gauge_messages.Error_VALIDATION_ERROR { t = "Validation" } failures = append(failures, fmt.Sprintf("[%s Error] %s", t, e.Message)) } return JUnitTestCase{ Classname: getSpecName(result.GetProtoSpec()), Name: getSpecName(result.GetProtoSpec()), Time: formatTime(int(result.GetExecutionTime())), Failure: &JUnitFailure{ Message: "Parse/Validation Errors", Type: "Parse/Validation Errors", Contents: strings.Join(failures, "\n"), }, } } func (x *XmlBuilder) getScenarioContent(result *gauge_messages.ProtoSpecResult, scenario *gauge_messages.ProtoScenario, ts *JUnitTestSuite) { testCase := JUnitTestCase{ Classname: getSpecName(result.GetProtoSpec()), Name: scenario.GetScenarioHeading(), Time: formatTime(int(scenario.GetExecutionTime())), Failure: nil, } if scenario.GetExecutionStatus() == gauge_messages.ExecutionStatus_FAILED { var errors []string failures := x.getFailure(scenario) message := "Multiple failures" for _, step := range failures { errors = append(errors, fmt.Sprintf("%s\n%s", step.Message, step.Err)) } if len(failures) == 1 { message = failures[0].Message errors = []string{failures[0].Err} } testCase.Failure = &JUnitFailure{ Message: message, Type: message, Contents: strings.Join(errors, "\n\n"), } } else if scenario.GetExecutionStatus() == gauge_messages.ExecutionStatus_SKIPPED { testCase.SkipMessage = &JUnitSkipMessage{ Message: strings.Join(scenario.SkipErrors, "\n"), } } ts.TestCases = append(ts.TestCases, testCase) } func (x *XmlBuilder) getTableDrivenScenarioContent(result *gauge_messages.ProtoSpecResult, tableDriven *gauge_messages.ProtoTableDrivenScenario, ts *JUnitTestSuite) { if tableDriven.GetScenario() != nil { scenario := tableDriven.GetScenario() scenario.ScenarioHeading += " " + strconv.Itoa(int(tableDriven.GetTableRowIndex())+1) x.getScenarioContent(result, scenario, ts) } } func (x *XmlBuilder) getTestSuite(result *gauge_messages.ProtoSpecResult, hostName string) JUnitTestSuite { now := time.Now() formattedNow := fmt.Sprintf(timeStampFormat, now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second()) systemError := SystemErr{} if result.GetScenarioSkippedCount() > 0 { systemError.Contents = fmt.Sprintf("Validation failed, %d Scenarios were skipped.", result.GetScenarioSkippedCount()) } return JUnitTestSuite{ Id: int(x.currentId), Tests: int(result.GetScenarioCount()), Failures: int(result.GetScenarioFailedCount()), Time: formatTime(int(result.GetExecutionTime())), Timestamp: formattedNow, Name: getSpecName(result.GetProtoSpec()), Errors: 0, Hostname: hostName, Package: result.GetProtoSpec().GetFileName(), Properties: []JUnitProperty{}, TestCases: []JUnitTestCase{}, SkippedTestCount: int(result.GetScenarioSkippedCount()), SystemOutput: SystemOut{}, SystemError: systemError, } } func (x *XmlBuilder) getFailure(test *gauge_messages.ProtoScenario) []StepFailure { errInfo := []StepFailure{} hookInfo := x.getFailureFromExecutionResult(test.GetScenarioHeading(), test.GetPreHookFailure(), test.GetPostHookFailure(), nil, "Scenario ") if hookInfo.Message != "" { return append(errInfo, hookInfo) } contextsInfo := x.getFailureFromSteps(test.GetContexts(), "Step ") if len(contextsInfo) > 0 { errInfo = append(errInfo, contextsInfo...) } stepsInfo := x.getFailureFromSteps(test.GetScenarioItems(), "Step ") if len(stepsInfo) > 0 { errInfo = append(errInfo, stepsInfo...) } return errInfo } func (x *XmlBuilder) getFailureFromSteps(items []*gauge_messages.ProtoItem, prefix string) []StepFailure
{ errInfo := []StepFailure{} for _, item := range items { stepInfo := StepFailure{Message: "", Err: ""} if item.GetItemType() == gauge_messages.ProtoItem_Step { preHookFailure := item.GetStep().GetStepExecutionResult().GetPreHookFailure() postHookFailure := item.GetStep().GetStepExecutionResult().GetPostHookFailure() result := item.GetStep().GetStepExecutionResult().GetExecutionResult() stepInfo = x.getFailureFromExecutionResult(item.GetStep().GetActualText(), preHookFailure, postHookFailure, result, prefix) } else if item.GetItemType() == gauge_messages.ProtoItem_Concept { errInfo = append(errInfo, x.getFailureFromSteps(item.GetConcept().GetSteps(), "Concept ")...) } if stepInfo.Message != "" { errInfo = append(errInfo, stepInfo) } } return errInfo }
identifier_body
xmlReportBuilder.go
es struct { XMLName xml.Name `xml:"testsuites"` Suites []JUnitTestSuite `xml:"testsuite"` } // JUnitTestSuite is a single JUnit test suite which may contain many // testcases. type JUnitTestSuite struct { XMLName xml.Name `xml:"testsuite"` Id int `xml:"id,attr"` Tests int `xml:"tests,attr"` Failures int `xml:"failures,attr"` Package string `xml:"package,attr"` Time string `xml:"time,attr"` Timestamp string `xml:"timestamp,attr"` Name string `xml:"name,attr"` Errors int `xml:"errors,attr"` SkippedTestCount int `xml:"skipped,attr,omitempty"` Hostname string `xml:"hostname,attr"` Properties []JUnitProperty `xml:"properties>property,omitempty"` TestCases []JUnitTestCase `xml:"testcase"` SystemOutput SystemOut SystemError SystemErr } // JUnitTestCase is a single test case with its result. type JUnitTestCase struct { XMLName xml.Name `xml:"testcase"` Classname string `xml:"classname,attr"` Name string `xml:"name,attr"` Time string `xml:"time,attr"` SkipMessage *JUnitSkipMessage `xml:"skipped,omitempty"` Failure *JUnitFailure `xml:"failure,omitempty"` } type SystemOut struct { XMLName xml.Name `xml:"system-out"` Contents string `xml:",chardata"` } type SystemErr struct { XMLName xml.Name `xml:"system-err"` Contents string `xml:",chardata"` } // JUnitSkipMessage contains the reason why a testcase was skipped. type JUnitSkipMessage struct { Message string `xml:"message,attr"` } // JUnitProperty represents a key/value pair used to define properties. type JUnitProperty struct { Name string `xml:"name,attr"` Value string `xml:"value,attr"` } // JUnitFailure contains data related to a failed test. type JUnitFailure struct { Message string `xml:"message,attr"` Type string `xml:"type,attr"` Contents string `xml:",chardata"` } type XmlBuilder struct { currentId int suites JUnitTestSuites } func NewXmlBuilder(id int) *XmlBuilder { return &XmlBuilder{currentId: id} } type StepFailure struct { Message string Err string } func (x *XmlBuilder) GetXmlContent(executionSuiteResult *gauge_messages.SuiteExecutionResult) ([]byte, error) { suiteResult := executionSuiteResult.GetSuiteResult() x.suites = JUnitTestSuites{} for _, result := range suiteResult.GetSpecResults() { x.getSpecContent(result) } bytes, err := xml.MarshalIndent(x.suites, "", "\t") if err != nil { return nil, err } return bytes, nil } func (x *XmlBuilder) getSpecContent(result *gauge_messages.ProtoSpecResult) { x.currentId += 1 hostName, err := os.Hostname() if err != nil {
ts := x.getTestSuite(result, hostName) if hasParseErrors(result.Errors) { ts.Failures++ ts.TestCases = append(ts.TestCases, getErrorTestCase(result)) } else { s := result.GetProtoSpec() ts.Failures += len(s.GetPreHookFailures()) + len(s.GetPostHookFailures()) for _, test := range result.GetProtoSpec().GetItems() { if test.GetItemType() == gauge_messages.ProtoItem_Scenario { x.getScenarioContent(result, test.GetScenario(), &ts) } else if test.GetItemType() == gauge_messages.ProtoItem_TableDrivenScenario { x.getTableDrivenScenarioContent(result, test.GetTableDrivenScenario(), &ts) } } } x.suites.Suites = append(x.suites.Suites, ts) } func getErrorTestCase(result *gauge_messages.ProtoSpecResult) JUnitTestCase { var failures []string for _, e := range result.Errors { t := "Parse" if e.Type == gauge_messages.Error_VALIDATION_ERROR { t = "Validation" } failures = append(failures, fmt.Sprintf("[%s Error] %s", t, e.Message)) } return JUnitTestCase{ Classname: getSpecName(result.GetProtoSpec()), Name: getSpecName(result.GetProtoSpec()), Time: formatTime(int(result.GetExecutionTime())), Failure: &JUnitFailure{ Message: "Parse/Validation Errors", Type: "Parse/Validation Errors", Contents: strings.Join(failures, "\n"), }, } } func (x *XmlBuilder) getScenarioContent(result *gauge_messages.ProtoSpecResult, scenario *gauge_messages.ProtoScenario, ts *JUnitTestSuite) { testCase := JUnitTestCase{ Classname: getSpecName(result.GetProtoSpec()), Name: scenario.GetScenarioHeading(), Time: formatTime(int(scenario.GetExecutionTime())), Failure: nil, } if scenario.GetExecutionStatus() == gauge_messages.ExecutionStatus_FAILED { var errors []string failures := x.getFailure(scenario) message := "Multiple failures" for _, step := range failures { errors = append(errors, fmt.Sprintf("%s\n%s", step.Message, step.Err)) } if len(failures) == 1 { message = failures[0].Message errors = []string{failures[0].Err} } testCase.Failure = &JUnitFailure{ Message: message, Type: message, Contents: strings.Join(errors, "\n\n"), } } else if scenario.GetExecutionStatus() == gauge_messages.ExecutionStatus_SKIPPED { testCase.SkipMessage = &JUnitSkipMessage{ Message: strings.Join(scenario.SkipErrors, "\n"), } } ts.TestCases = append(ts.TestCases, testCase) } func (x *XmlBuilder) getTableDrivenScenarioContent(result *gauge_messages.ProtoSpecResult, tableDriven *gauge_messages.ProtoTableDrivenScenario, ts *JUnitTestSuite) { if tableDriven.GetScenario() != nil { scenario := tableDriven.GetScenario() scenario.ScenarioHeading += " " + strconv.Itoa(int(tableDriven.GetTableRowIndex())+1) x.getScenarioContent(result, scenario, ts) } } func (x *XmlBuilder) getTestSuite(result *gauge_messages.ProtoSpecResult, hostName string) JUnitTestSuite { now := time.Now() formattedNow := fmt.Sprintf(timeStampFormat, now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second()) systemError := SystemErr{} if result.GetScenarioSkippedCount() > 0 { systemError.Contents = fmt.Sprintf("Validation failed, %d Scenarios were skipped.", result.GetScenarioSkippedCount()) } return JUnitTestSuite{ Id: int(x.currentId), Tests: int(result.GetScenarioCount()), Failures: int(result.GetScenarioFailedCount()), Time: formatTime(int(result.GetExecutionTime())), Timestamp: formattedNow, Name: getSpecName(result.GetProtoSpec()), Errors: 0, Hostname: hostName, Package: result.GetProtoSpec().GetFileName(), Properties: []JUnitProperty{}, TestCases: []JUnitTestCase{}, SkippedTestCount: int(result.GetScenarioSkippedCount()), SystemOutput: SystemOut{}, SystemError: systemError, } } func (x *XmlBuilder) getFailure(test *gauge_messages.ProtoScenario) []StepFailure { errInfo := []StepFailure{} hookInfo := x.getFailureFromExecutionResult(test.GetScenarioHeading(), test.GetPreHookFailure(), test.GetPostHookFailure(), nil, "Scenario ") if hookInfo.Message != "" { return append(errInfo, hookInfo) } contextsInfo := x.getFailureFromSteps(test.GetContexts(), "Step ") if len(contextsInfo) > 0 { errInfo = append(errInfo, contextsInfo...) } stepsInfo := x.getFailureFromSteps(test.GetScenarioItems(), "Step ") if len(stepsInfo) > 0 { errInfo = append(errInfo, stepsInfo...) } return errInfo } func (x *XmlBuilder) getFailureFromSteps(items []*gauge_messages.ProtoItem, prefix string) []StepFailure { errInfo := []StepFailure{} for _, item := range items { stepInfo := StepFailure{Message: "", Err: ""} if item.GetItemType() == gauge_messages.ProtoItem_Step { preHookFailure := item.GetStep().GetStepExecutionResult().GetPreHookFailure() postHookFailure := item.GetStep().GetStepExecutionResult().GetPostHookFailure() result := item.GetStep().GetStepExecutionResult().GetExecutionResult() stepInfo = x.getFailureFromExecutionResult(item.GetStep().GetActualText(), preHookFailure, postHookFailure, result, prefix) } else if item.GetItemType() == gauge_messages.ProtoItem_Concept { errInfo = append(errInfo, x.get
hostName = hostname }
random_line_split
xmlReportBuilder.go
struct { XMLName xml.Name `xml:"testsuites"` Suites []JUnitTestSuite `xml:"testsuite"` } // JUnitTestSuite is a single JUnit test suite which may contain many // testcases. type JUnitTestSuite struct { XMLName xml.Name `xml:"testsuite"` Id int `xml:"id,attr"` Tests int `xml:"tests,attr"` Failures int `xml:"failures,attr"` Package string `xml:"package,attr"` Time string `xml:"time,attr"` Timestamp string `xml:"timestamp,attr"` Name string `xml:"name,attr"` Errors int `xml:"errors,attr"` SkippedTestCount int `xml:"skipped,attr,omitempty"` Hostname string `xml:"hostname,attr"` Properties []JUnitProperty `xml:"properties>property,omitempty"` TestCases []JUnitTestCase `xml:"testcase"` SystemOutput SystemOut SystemError SystemErr } // JUnitTestCase is a single test case with its result. type JUnitTestCase struct { XMLName xml.Name `xml:"testcase"` Classname string `xml:"classname,attr"` Name string `xml:"name,attr"` Time string `xml:"time,attr"` SkipMessage *JUnitSkipMessage `xml:"skipped,omitempty"` Failure *JUnitFailure `xml:"failure,omitempty"` } type SystemOut struct { XMLName xml.Name `xml:"system-out"` Contents string `xml:",chardata"` } type SystemErr struct { XMLName xml.Name `xml:"system-err"` Contents string `xml:",chardata"` } // JUnitSkipMessage contains the reason why a testcase was skipped. type JUnitSkipMessage struct { Message string `xml:"message,attr"` } // JUnitProperty represents a key/value pair used to define properties. type JUnitProperty struct { Name string `xml:"name,attr"` Value string `xml:"value,attr"` } // JUnitFailure contains data related to a failed test. type JUnitFailure struct { Message string `xml:"message,attr"` Type string `xml:"type,attr"` Contents string `xml:",chardata"` } type XmlBuilder struct { currentId int suites JUnitTestSuites } func NewXmlBuilder(id int) *XmlBuilder { return &XmlBuilder{currentId: id} } type StepFailure struct { Message string Err string } func (x *XmlBuilder) GetXmlContent(executionSuiteResult *gauge_messages.SuiteExecutionResult) ([]byte, error) { suiteResult := executionSuiteResult.GetSuiteResult() x.suites = JUnitTestSuites{} for _, result := range suiteResult.GetSpecResults() { x.getSpecContent(result) } bytes, err := xml.MarshalIndent(x.suites, "", "\t") if err != nil { return nil, err } return bytes, nil } func (x *XmlBuilder) getSpecContent(result *gauge_messages.ProtoSpecResult) { x.currentId += 1 hostName, err := os.Hostname() if err != nil { hostName = hostname } ts := x.getTestSuite(result, hostName) if hasParseErrors(result.Errors) { ts.Failures++ ts.TestCases = append(ts.TestCases, getErrorTestCase(result)) } else { s := result.GetProtoSpec() ts.Failures += len(s.GetPreHookFailures()) + len(s.GetPostHookFailures()) for _, test := range result.GetProtoSpec().GetItems() { if test.GetItemType() == gauge_messages.ProtoItem_Scenario { x.getScenarioContent(result, test.GetScenario(), &ts) } else if test.GetItemType() == gauge_messages.ProtoItem_TableDrivenScenario { x.getTableDrivenScenarioContent(result, test.GetTableDrivenScenario(), &ts) } } } x.suites.Suites = append(x.suites.Suites, ts) } func getErrorTestCase(result *gauge_messages.ProtoSpecResult) JUnitTestCase { var failures []string for _, e := range result.Errors { t := "Parse" if e.Type == gauge_messages.Error_VALIDATION_ERROR
failures = append(failures, fmt.Sprintf("[%s Error] %s", t, e.Message)) } return JUnitTestCase{ Classname: getSpecName(result.GetProtoSpec()), Name: getSpecName(result.GetProtoSpec()), Time: formatTime(int(result.GetExecutionTime())), Failure: &JUnitFailure{ Message: "Parse/Validation Errors", Type: "Parse/Validation Errors", Contents: strings.Join(failures, "\n"), }, } } func (x *XmlBuilder) getScenarioContent(result *gauge_messages.ProtoSpecResult, scenario *gauge_messages.ProtoScenario, ts *JUnitTestSuite) { testCase := JUnitTestCase{ Classname: getSpecName(result.GetProtoSpec()), Name: scenario.GetScenarioHeading(), Time: formatTime(int(scenario.GetExecutionTime())), Failure: nil, } if scenario.GetExecutionStatus() == gauge_messages.ExecutionStatus_FAILED { var errors []string failures := x.getFailure(scenario) message := "Multiple failures" for _, step := range failures { errors = append(errors, fmt.Sprintf("%s\n%s", step.Message, step.Err)) } if len(failures) == 1 { message = failures[0].Message errors = []string{failures[0].Err} } testCase.Failure = &JUnitFailure{ Message: message, Type: message, Contents: strings.Join(errors, "\n\n"), } } else if scenario.GetExecutionStatus() == gauge_messages.ExecutionStatus_SKIPPED { testCase.SkipMessage = &JUnitSkipMessage{ Message: strings.Join(scenario.SkipErrors, "\n"), } } ts.TestCases = append(ts.TestCases, testCase) } func (x *XmlBuilder) getTableDrivenScenarioContent(result *gauge_messages.ProtoSpecResult, tableDriven *gauge_messages.ProtoTableDrivenScenario, ts *JUnitTestSuite) { if tableDriven.GetScenario() != nil { scenario := tableDriven.GetScenario() scenario.ScenarioHeading += " " + strconv.Itoa(int(tableDriven.GetTableRowIndex())+1) x.getScenarioContent(result, scenario, ts) } } func (x *XmlBuilder) getTestSuite(result *gauge_messages.ProtoSpecResult, hostName string) JUnitTestSuite { now := time.Now() formattedNow := fmt.Sprintf(timeStampFormat, now.Year(), now.Month(), now.Day(), now.Hour(), now.Minute(), now.Second()) systemError := SystemErr{} if result.GetScenarioSkippedCount() > 0 { systemError.Contents = fmt.Sprintf("Validation failed, %d Scenarios were skipped.", result.GetScenarioSkippedCount()) } return JUnitTestSuite{ Id: int(x.currentId), Tests: int(result.GetScenarioCount()), Failures: int(result.GetScenarioFailedCount()), Time: formatTime(int(result.GetExecutionTime())), Timestamp: formattedNow, Name: getSpecName(result.GetProtoSpec()), Errors: 0, Hostname: hostName, Package: result.GetProtoSpec().GetFileName(), Properties: []JUnitProperty{}, TestCases: []JUnitTestCase{}, SkippedTestCount: int(result.GetScenarioSkippedCount()), SystemOutput: SystemOut{}, SystemError: systemError, } } func (x *XmlBuilder) getFailure(test *gauge_messages.ProtoScenario) []StepFailure { errInfo := []StepFailure{} hookInfo := x.getFailureFromExecutionResult(test.GetScenarioHeading(), test.GetPreHookFailure(), test.GetPostHookFailure(), nil, "Scenario ") if hookInfo.Message != "" { return append(errInfo, hookInfo) } contextsInfo := x.getFailureFromSteps(test.GetContexts(), "Step ") if len(contextsInfo) > 0 { errInfo = append(errInfo, contextsInfo...) } stepsInfo := x.getFailureFromSteps(test.GetScenarioItems(), "Step ") if len(stepsInfo) > 0 { errInfo = append(errInfo, stepsInfo...) } return errInfo } func (x *XmlBuilder) getFailureFromSteps(items []*gauge_messages.ProtoItem, prefix string) []StepFailure { errInfo := []StepFailure{} for _, item := range items { stepInfo := StepFailure{Message: "", Err: ""} if item.GetItemType() == gauge_messages.ProtoItem_Step { preHookFailure := item.GetStep().GetStepExecutionResult().GetPreHookFailure() postHookFailure := item.GetStep().GetStepExecutionResult().GetPostHookFailure() result := item.GetStep().GetStepExecutionResult().GetExecutionResult() stepInfo = x.getFailureFromExecutionResult(item.GetStep().GetActualText(), preHookFailure, postHookFailure, result, prefix) } else if item.GetItemType() == gauge_messages.ProtoItem_Concept { errInfo = append(errInfo, x
{ t = "Validation" }
conditional_block
index.js
// calculate the new cursor position: x0 = x1 - ev.clientX; y0 = y1 - ev.clientY; x1 = ev.clientX; y1 = ev.clientY; // set the element's new position: modalPosition = [(modal.offsetLeft - x0) + "px", (modal.offsetTop - y0) + "px"]; [modal.style.left, modal.style.top] = modalPosition; } function closeDragElement() { /* stop moving when mouse button is released:*/ document.onmouseup = null; document.onmousemove = null; } } // Code to populate code block display of palette as // CSS vars and an array of hex colours as strings. const varSlots = codeBlock.getElementsByClassName(`code-list-item`); const varArray = document.getElementById(`code-item`); // ========================================================================== // Grid of coloured squares const colourGrid = document.getElementById("colour-grid"); initCells((i, j) => (i + j) % 2 ? '#fff' : '#000'); let cells = Array.from(colourGrid.children); cells.forEach(cell => { cell.addEventListener('click', handleClickOnCell); cell.classList.add('cell'); let span = document.createElement(`SPAN`); // default opacity 0 for hex colours span.style.lineHeight = window.getComputedStyle(cell).height; // centre it on y axis span.classList.add(`hex-colour`) cell.appendChild(span); }); // ================================================================================================= // Status indicator const status = document.getElementById("status"); // Listener for 'Show Hex' button document.getElementById("show-hex").addEventListener('click', function() { showHex = !showHex; this.innerText = showHex ? "HIDE HEX" : "SHOW HEX"; for (let paletteSlot of palette) { let colour = paletteSlot.style.backgroundColor; let lum = getLuminance(colour); paletteSlot.innerText = paletteSlot.isActive && showLum ? `${lum.toFixed(2)}` : NBSP; // == &nbsp; let conj = showHex && showLum ? ` / ` : NBSP; paletteSlot.innerText = paletteSlot.isActive ? `${showHex ? rgb2Hex(colour) : NULL_STR}${conj}${showLum ? lum.toFixed(2) : NULL_STR}` : NBSP; } generate(); }); // ================================================================================================= function reset() { activeSliders.clear(); setSliderOpacity(); setSwitches(); generate(); } function handleClickOnCell() { appendPalette(this.style.backgroundColor); } function initCells(setCellColour) { for (let j = 0; j < H; j++) { for (let i = 0; i < W; i++) { let cell = document.createElement("div"); cell.x = i; cell.y = j; // Set some initial colours for the cells... cell.style.backgroundColor = setCellColour(i, j); colourGrid.appendChild(cell); } } } // We only want the two most recent, or one if user changed between RGB and HSL groups. function setSwitches() { for (let i = 0; i < 6; i++) { let sliderIsActive = activeSliders.has(i); onSwitches[i].checked = sliderIsActive; offSwitches[i].checked = !sliderIsActive; switchboxes[i].style.opacity = activeSliders.group == Math.trunc(i / 3) ? 1 : 0.3; } } // As above, we only want the two most recent, or one if user changed between RGB and HSL groups. function setSliderOpacity() { for (let i = 0; i < 6; i++) { sliderWrappers[i].style.opacity = activeSliders.has(i) ? 1 : 0.3; } } // Main function to generate a new colour block and render it. function generate() { switch (activeSliders.group) { case -1: // If no sliders fixed, generate a grid of random colours setStatus(`Random ${randomMode.toUpperCase()}`); cells.forEach(cell => { cell.style.backgroundColor = randomMode == `hsl` ? `hsl(${randInt(360)}, ${randInt(101)}%, ${randInt(101)}%)` : `rgb(${randInt(256)}, ${randInt(256)}, ${randInt(256)})`; }); break; case 0: // Handle RGB cases switch (activeSliders.activeCount) { case 1: setStatus(`${names[activeSliders.first]}: ${values[activeSliders.first]}`); cells.forEach(cell => { let rgb = activeSliders.has(0) ? [values[0], rgbFactor * cell.x, rgbFactor * cell.y] : (activeSliders.has(1) ? [rgbFactor * cell.x, values[1], rgbFactor * cell.y] : [rgbFactor * cell.x, rgbFactor * cell.y, values[2]]); cell.style.backgroundColor = `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`; }); break; case 2: setStatus(`${names[activeSliders.first]}: ${values[activeSliders.first]}, ${names[activeSliders.second]}: ${values[activeSliders.second]}`); cells.forEach(cell => { let rgb = activeSliders.has(1) && activeSliders.has(2) ? [(cell.y * W + cell.x) * rgb1dFactor, values[1], values[2]] : (activeSliders.has(0) && activeSliders.has(2) ? [values[0], (cell.y * W + cell.x) * rgb1dFactor, values[2]] : [values[0], values[1], (cell.y * W + cell.x) * rgb1dFactor]); cell.style.backgroundColor = `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`; }); break; } // END switch break; // not needed at present; leave for safety in case more code added above case 1: // Handle HSL cases switch (activeSliders.activeCount) { case 1: setStatus(`${names[activeSliders.first]}: ${values[activeSliders.first]} `); cells.forEach(cell => { let hsl = activeSliders.has(3) ? [values[3], cell.x * 100 / W, cell.y * maxLightness / (H - 1) + minLightness] : (activeSliders.has(4) ? [cell.x * 360 / W, values[4], cell.y * maxLightness / (H - 1) + minLightness] : [cell.x * 360 / W, cell.y * 100 / H, values[5]]); cell.style.backgroundColor = `hsl(${hsl[0]}, ${hsl[1]}%, ${hsl[2]}%)`; }); break; case 2: setStatus(`${names[activeSliders.first]}: ${values[activeSliders.first]}, ${names[activeSliders.second]}: ${values[activeSliders.second]}`); cells.forEach(cell => { let hsl = activeSliders.has(4) && activeSliders.has(5) ? [(cell.y * W + cell.x) * hueFactor, values[4], values[5]] : (activeSliders.has(3) && activeSliders.has(5) ? [values[3], (cell.y * W + cell.x) * slFactor, values[5]] : [values[3], values[4], (cell.y * W + cell.x) * slFactor]); cell.style.backgroundColor = `hsl(${hsl[0]}, ${hsl[1]}%, ${hsl[2]}%)`; }); break; } // END switch break; // not needed at present; leave for safety in case more code added above } // END outermost switch cells.forEach(cell => { let span = cell.firstChild; colour = cell.style.backgroundColor; hex = rgb2Hex(colour); span.innerText = showLum ? `${getLuminance(colour).toFixed(2)}` : (showHex ? hex : NBSP); // span.style.opacity = showHex ? 1 : 0; span.style.color = getLuminance(cell.style.backgroundColor) > 0.3 ? BLACK : WHITE; }); } // END generate() function setStatus(text) { status.innerHTML = `<pre><code>${text}</code></pre>`; } function simulateSliderInput(slider) { simulateMouseEvent(rangeSliders[slider], `input`); } function getCssVarList(colours) { let prefix = `--col-`; let i = -1; let varList = []; for (let col of colours) { varList[++i] = prefix + i + `: ` + rgb2Hex(col) + SEMICOLON; } return varList; } // https://developer.mozilla.org/samples/domref/dispatchEvent.html function simulateMouseEvent(target, eventType) {
let ev = document.createEvent("MouseEvents"); ev.initMouseEvent(eventType, true, true, window,
random_line_split
index.js
const col1Box = document.getElementById(`contrast-col1`); const contrastDetails = document.getElementById(`contrast-details`); function displayContrastInfo() { dragBar.innerText = `Contrast Info`; const col0 = palette[selectedColours[0]].style.backgroundColor; const col1 = palette[selectedColours[1]].style.backgroundColor; col0Box.style.backgroundColor = col0; col1Box.style.backgroundColor = col1; col0Box.style.color = getLuminance(col0) > 0.3 ? BLACK : WHITE; col1Box.style.color = getLuminance(col1) > 0.3 ? BLACK : WHITE; col0Box.innerText = rgb2Hex(col0); col1Box.innerText = rgb2Hex(col1); contrastDetails.innerText = `Contrast ratio = ${contrastRatio(col0, col1).toFixed(2)}`; modal.replaceChild(contrastInfo, modal.lastElementChild); modal.style.display = `block`; if (modalPosition.length == 0) { modal.style.left = `calc(50% - ${modal.clientWidth / 2}px)`; modal.style.top = `calc(50% - ${modal.clientHeight / 2}px)`; } else { [modal.style.left, modal.style.top] = modalPosition; } } // Modal dialog - let user dismiss it by clicking in the body // but not on buttons obviously; should be intuitive. const codeBlock = document.getElementById(`code-block`); const modal = document.getElementById(`modal`); document.addEventListener('click', ev => { if (modal.style.display = `block` && !Array.from(modal.querySelectorAll("*")).includes(ev.target) && ev.target != modal && !Array.from(document.getElementById(`controls`).querySelectorAll("*")).includes(ev.target)) { modalPosition = [modal.style.left, modal.style.top]; modal.style.display = `none`; } }); // The following code to make the modal draggable adapted frpm // https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_draggable const dragBar = document.getElementById(`modal-drag-bar`); dragModal(); // make modal draggable function dragModal()
y0 = y1 - ev.clientY; x1 = ev.clientX; y1 = ev.clientY; // set the element's new position: modalPosition = [(modal.offsetLeft - x0) + "px", (modal.offsetTop - y0) + "px"]; [modal.style.left, modal.style.top] = modalPosition; } function closeDragElement() { /* stop moving when mouse button is released:*/ document.onmouseup = null; document.onmousemove = null; } } // Code to populate code block display of palette as // CSS vars and an array of hex colours as strings. const varSlots = codeBlock.getElementsByClassName(`code-list-item`); const varArray = document.getElementById(`code-item`); // ========================================================================== // Grid of coloured squares const colourGrid = document.getElementById("colour-grid"); initCells((i, j) => (i + j) % 2 ? '#fff' : '#000'); let cells = Array.from(colourGrid.children); cells.forEach(cell => { cell.addEventListener('click', handleClickOnCell); cell.classList.add('cell'); let span = document.createElement(`SPAN`); // default opacity 0 for hex colours span.style.lineHeight = window.getComputedStyle(cell).height; // centre it on y axis span.classList.add(`hex-colour`) cell.appendChild(span); }); // ================================================================================================= // Status indicator const status = document.getElementById("status"); // Listener for 'Show Hex' button document.getElementById("show-hex").addEventListener('click', function() { showHex = !showHex; this.innerText = showHex ? "HIDE HEX" : "SHOW HEX"; for (let paletteSlot of palette) { let colour = paletteSlot.style.backgroundColor; let lum = getLuminance(colour); paletteSlot.innerText = paletteSlot.isActive && showLum ? `${lum.toFixed(2)}` : NBSP; // == &nbsp; let conj = showHex && showLum ? ` / ` : NBSP; paletteSlot.innerText = paletteSlot.isActive ? `${showHex ? rgb2Hex(colour) : NULL_STR}${conj}${showLum ? lum.toFixed(2) : NULL_STR}` : NBSP; } generate(); }); // ================================================================================================= function reset() { activeSliders.clear(); setSliderOpacity(); setSwitches(); generate(); } function handleClickOnCell() { appendPalette(this.style.backgroundColor); } function initCells(setCellColour) { for (let j = 0; j < H; j++) { for (let i = 0; i < W; i++) { let cell = document.createElement("div"); cell.x = i; cell.y = j; // Set some initial colours for the cells... cell.style.backgroundColor = setCellColour(i, j); colourGrid.appendChild(cell); } } } // We only want the two most recent, or one if user changed between RGB and HSL groups. function setSwitches() { for (let i = 0; i < 6; i++) { let sliderIsActive = activeSliders.has(i); onSwitches[i].checked = sliderIsActive; offSwitches[i].checked = !sliderIsActive; switchboxes[i].style.opacity = activeSliders.group == Math.trunc(i / 3) ? 1 : 0.3; } } // As above, we only want the two most recent, or one if user changed between RGB and HSL groups. function setSliderOpacity() { for (let i = 0; i < 6; i++) { sliderWrappers[i].style.opacity = activeSliders.has(i) ? 1 : 0.3; } } // Main function to generate a new colour block and render it. function generate() { switch (activeSliders.group) { case -1: // If no sliders fixed, generate a grid of random colours setStatus(`Random ${randomMode.toUpperCase()}`); cells.forEach(cell => { cell.style.backgroundColor = randomMode == `hsl` ? `hsl(${randInt(360)}, ${randInt(101)}%, ${randInt(101)}%)` : `rgb(${randInt(256)}, ${randInt(256)}, ${randInt(256)})`; }); break; case 0: // Handle RGB cases switch (activeSliders.activeCount) { case 1: setStatus(`${names[activeSliders.first]}: ${values[activeSliders.first]}`); cells.forEach(cell => { let rgb = activeSliders.has(0) ? [values[0], rgbFactor * cell.x, rgbFactor * cell.y] : (activeSliders.has(1) ? [rgbFactor * cell.x, values[1], rgbFactor * cell.y] : [rgbFactor * cell.x, rgbFactor * cell.y, values[2]]); cell.style.backgroundColor = `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`; }); break; case 2: setStatus(`${names[activeSliders.first]}: ${values[activeSliders.first]}, ${names[activeSliders.second]}: ${values[activeSliders.second]}`); cells.forEach(cell => { let rgb = activeSliders.has(1) && activeSliders.has(2) ? [(cell.y * W + cell.x) * rgb1dFactor, values[1], values[2]] : (activeSliders.has(0) && activeSliders.has(2) ? [values[0], (cell.y * W + cell.x) * rgb1dFactor, values[2]] : [values[0], values[1], (cell.y * W + cell.x) * rgb1dFactor]); cell.style.backgroundColor = `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`; }); break; } // END switch break; // not needed at present; leave for safety in case more code added above case 1: // Handle HSL cases switch (activeSliders.activeCount) { case 1: setStatus(`${names[activeSliders.first]}: ${values[activeSliders.first]} `); cells.forEach(cell => { let hsl = activeSliders.has(3) ? [values[3], cell.x * 100 / W, cell.y * maxLightness / (H - 1) + minLightness] :
{ let [x0, y0, x1, y1] = [0, 0, 0, 0]; dragBar.onmousedown = dragMouseDown; function dragMouseDown(ev) { ev = ev || window.event; ev.preventDefault(); // get the mouse cursor position at startup: x1 = ev.clientX; y1 = ev.clientY; document.onmouseup = closeDragElement; // call a function whenever the cursor moves: document.onmousemove = elementDrag; } function elementDrag(ev) { ev = ev || window.event; ev.preventDefault(); // calculate the new cursor position: x0 = x1 - ev.clientX;
identifier_body
index.js
const col1Box = document.getElementById(`contrast-col1`); const contrastDetails = document.getElementById(`contrast-details`); function
() { dragBar.innerText = `Contrast Info`; const col0 = palette[selectedColours[0]].style.backgroundColor; const col1 = palette[selectedColours[1]].style.backgroundColor; col0Box.style.backgroundColor = col0; col1Box.style.backgroundColor = col1; col0Box.style.color = getLuminance(col0) > 0.3 ? BLACK : WHITE; col1Box.style.color = getLuminance(col1) > 0.3 ? BLACK : WHITE; col0Box.innerText = rgb2Hex(col0); col1Box.innerText = rgb2Hex(col1); contrastDetails.innerText = `Contrast ratio = ${contrastRatio(col0, col1).toFixed(2)}`; modal.replaceChild(contrastInfo, modal.lastElementChild); modal.style.display = `block`; if (modalPosition.length == 0) { modal.style.left = `calc(50% - ${modal.clientWidth / 2}px)`; modal.style.top = `calc(50% - ${modal.clientHeight / 2}px)`; } else { [modal.style.left, modal.style.top] = modalPosition; } } // Modal dialog - let user dismiss it by clicking in the body // but not on buttons obviously; should be intuitive. const codeBlock = document.getElementById(`code-block`); const modal = document.getElementById(`modal`); document.addEventListener('click', ev => { if (modal.style.display = `block` && !Array.from(modal.querySelectorAll("*")).includes(ev.target) && ev.target != modal && !Array.from(document.getElementById(`controls`).querySelectorAll("*")).includes(ev.target)) { modalPosition = [modal.style.left, modal.style.top]; modal.style.display = `none`; } }); // The following code to make the modal draggable adapted frpm // https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_draggable const dragBar = document.getElementById(`modal-drag-bar`); dragModal(); // make modal draggable function dragModal() { let [x0, y0, x1, y1] = [0, 0, 0, 0]; dragBar.onmousedown = dragMouseDown; function dragMouseDown(ev) { ev = ev || window.event; ev.preventDefault(); // get the mouse cursor position at startup: x1 = ev.clientX; y1 = ev.clientY; document.onmouseup = closeDragElement; // call a function whenever the cursor moves: document.onmousemove = elementDrag; } function elementDrag(ev) { ev = ev || window.event; ev.preventDefault(); // calculate the new cursor position: x0 = x1 - ev.clientX; y0 = y1 - ev.clientY; x1 = ev.clientX; y1 = ev.clientY; // set the element's new position: modalPosition = [(modal.offsetLeft - x0) + "px", (modal.offsetTop - y0) + "px"]; [modal.style.left, modal.style.top] = modalPosition; } function closeDragElement() { /* stop moving when mouse button is released:*/ document.onmouseup = null; document.onmousemove = null; } } // Code to populate code block display of palette as // CSS vars and an array of hex colours as strings. const varSlots = codeBlock.getElementsByClassName(`code-list-item`); const varArray = document.getElementById(`code-item`); // ========================================================================== // Grid of coloured squares const colourGrid = document.getElementById("colour-grid"); initCells((i, j) => (i + j) % 2 ? '#fff' : '#000'); let cells = Array.from(colourGrid.children); cells.forEach(cell => { cell.addEventListener('click', handleClickOnCell); cell.classList.add('cell'); let span = document.createElement(`SPAN`); // default opacity 0 for hex colours span.style.lineHeight = window.getComputedStyle(cell).height; // centre it on y axis span.classList.add(`hex-colour`) cell.appendChild(span); }); // ================================================================================================= // Status indicator const status = document.getElementById("status"); // Listener for 'Show Hex' button document.getElementById("show-hex").addEventListener('click', function() { showHex = !showHex; this.innerText = showHex ? "HIDE HEX" : "SHOW HEX"; for (let paletteSlot of palette) { let colour = paletteSlot.style.backgroundColor; let lum = getLuminance(colour); paletteSlot.innerText = paletteSlot.isActive && showLum ? `${lum.toFixed(2)}` : NBSP; // == &nbsp; let conj = showHex && showLum ? ` / ` : NBSP; paletteSlot.innerText = paletteSlot.isActive ? `${showHex ? rgb2Hex(colour) : NULL_STR}${conj}${showLum ? lum.toFixed(2) : NULL_STR}` : NBSP; } generate(); }); // ================================================================================================= function reset() { activeSliders.clear(); setSliderOpacity(); setSwitches(); generate(); } function handleClickOnCell() { appendPalette(this.style.backgroundColor); } function initCells(setCellColour) { for (let j = 0; j < H; j++) { for (let i = 0; i < W; i++) { let cell = document.createElement("div"); cell.x = i; cell.y = j; // Set some initial colours for the cells... cell.style.backgroundColor = setCellColour(i, j); colourGrid.appendChild(cell); } } } // We only want the two most recent, or one if user changed between RGB and HSL groups. function setSwitches() { for (let i = 0; i < 6; i++) { let sliderIsActive = activeSliders.has(i); onSwitches[i].checked = sliderIsActive; offSwitches[i].checked = !sliderIsActive; switchboxes[i].style.opacity = activeSliders.group == Math.trunc(i / 3) ? 1 : 0.3; } } // As above, we only want the two most recent, or one if user changed between RGB and HSL groups. function setSliderOpacity() { for (let i = 0; i < 6; i++) { sliderWrappers[i].style.opacity = activeSliders.has(i) ? 1 : 0.3; } } // Main function to generate a new colour block and render it. function generate() { switch (activeSliders.group) { case -1: // If no sliders fixed, generate a grid of random colours setStatus(`Random ${randomMode.toUpperCase()}`); cells.forEach(cell => { cell.style.backgroundColor = randomMode == `hsl` ? `hsl(${randInt(360)}, ${randInt(101)}%, ${randInt(101)}%)` : `rgb(${randInt(256)}, ${randInt(256)}, ${randInt(256)})`; }); break; case 0: // Handle RGB cases switch (activeSliders.activeCount) { case 1: setStatus(`${names[activeSliders.first]}: ${values[activeSliders.first]}`); cells.forEach(cell => { let rgb = activeSliders.has(0) ? [values[0], rgbFactor * cell.x, rgbFactor * cell.y] : (activeSliders.has(1) ? [rgbFactor * cell.x, values[1], rgbFactor * cell.y] : [rgbFactor * cell.x, rgbFactor * cell.y, values[2]]); cell.style.backgroundColor = `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`; }); break; case 2: setStatus(`${names[activeSliders.first]}: ${values[activeSliders.first]}, ${names[activeSliders.second]}: ${values[activeSliders.second]}`); cells.forEach(cell => { let rgb = activeSliders.has(1) && activeSliders.has(2) ? [(cell.y * W + cell.x) * rgb1dFactor, values[1], values[2]] : (activeSliders.has(0) && activeSliders.has(2) ? [values[0], (cell.y * W + cell.x) * rgb1dFactor, values[2]] : [values[0], values[1], (cell.y * W + cell.x) * rgb1dFactor]); cell.style.backgroundColor = `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`; }); break; } // END switch break; // not needed at present; leave for safety in case more code added above case 1: // Handle HSL cases switch (activeSliders.activeCount) { case 1: setStatus(`${names[activeSliders.first]}: ${values[activeSliders.first]} `); cells.forEach(cell => { let hsl = activeSliders.has(3) ? [values[3], cell.x * 100 / W, cell.y * maxLightness / (H - 1) + minLightness] :
displayContrastInfo
identifier_name
index.js
const col1Box = document.getElementById(`contrast-col1`); const contrastDetails = document.getElementById(`contrast-details`); function displayContrastInfo() { dragBar.innerText = `Contrast Info`; const col0 = palette[selectedColours[0]].style.backgroundColor; const col1 = palette[selectedColours[1]].style.backgroundColor; col0Box.style.backgroundColor = col0; col1Box.style.backgroundColor = col1; col0Box.style.color = getLuminance(col0) > 0.3 ? BLACK : WHITE; col1Box.style.color = getLuminance(col1) > 0.3 ? BLACK : WHITE; col0Box.innerText = rgb2Hex(col0); col1Box.innerText = rgb2Hex(col1); contrastDetails.innerText = `Contrast ratio = ${contrastRatio(col0, col1).toFixed(2)}`; modal.replaceChild(contrastInfo, modal.lastElementChild); modal.style.display = `block`; if (modalPosition.length == 0) { modal.style.left = `calc(50% - ${modal.clientWidth / 2}px)`; modal.style.top = `calc(50% - ${modal.clientHeight / 2}px)`; } else { [modal.style.left, modal.style.top] = modalPosition; } } // Modal dialog - let user dismiss it by clicking in the body // but not on buttons obviously; should be intuitive. const codeBlock = document.getElementById(`code-block`); const modal = document.getElementById(`modal`); document.addEventListener('click', ev => { if (modal.style.display = `block` && !Array.from(modal.querySelectorAll("*")).includes(ev.target) && ev.target != modal && !Array.from(document.getElementById(`controls`).querySelectorAll("*")).includes(ev.target)) { modalPosition = [modal.style.left, modal.style.top]; modal.style.display = `none`; } }); // The following code to make the modal draggable adapted frpm // https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_draggable const dragBar = document.getElementById(`modal-drag-bar`); dragModal(); // make modal draggable function dragModal() { let [x0, y0, x1, y1] = [0, 0, 0, 0]; dragBar.onmousedown = dragMouseDown; function dragMouseDown(ev) { ev = ev || window.event; ev.preventDefault(); // get the mouse cursor position at startup: x1 = ev.clientX; y1 = ev.clientY; document.onmouseup = closeDragElement; // call a function whenever the cursor moves: document.onmousemove = elementDrag; } function elementDrag(ev) { ev = ev || window.event; ev.preventDefault(); // calculate the new cursor position: x0 = x1 - ev.clientX; y0 = y1 - ev.clientY; x1 = ev.clientX; y1 = ev.clientY; // set the element's new position: modalPosition = [(modal.offsetLeft - x0) + "px", (modal.offsetTop - y0) + "px"]; [modal.style.left, modal.style.top] = modalPosition; } function closeDragElement() { /* stop moving when mouse button is released:*/ document.onmouseup = null; document.onmousemove = null; } } // Code to populate code block display of palette as // CSS vars and an array of hex colours as strings. const varSlots = codeBlock.getElementsByClassName(`code-list-item`); const varArray = document.getElementById(`code-item`); // ========================================================================== // Grid of coloured squares const colourGrid = document.getElementById("colour-grid"); initCells((i, j) => (i + j) % 2 ? '#fff' : '#000'); let cells = Array.from(colourGrid.children); cells.forEach(cell => { cell.addEventListener('click', handleClickOnCell); cell.classList.add('cell'); let span = document.createElement(`SPAN`); // default opacity 0 for hex colours span.style.lineHeight = window.getComputedStyle(cell).height; // centre it on y axis span.classList.add(`hex-colour`) cell.appendChild(span); }); // ================================================================================================= // Status indicator const status = document.getElementById("status"); // Listener for 'Show Hex' button document.getElementById("show-hex").addEventListener('click', function() { showHex = !showHex; this.innerText = showHex ? "HIDE HEX" : "SHOW HEX"; for (let paletteSlot of palette) { let colour = paletteSlot.style.backgroundColor; let lum = getLuminance(colour); paletteSlot.innerText = paletteSlot.isActive && showLum ? `${lum.toFixed(2)}` : NBSP; // == &nbsp; let conj = showHex && showLum ? ` / ` : NBSP; paletteSlot.innerText = paletteSlot.isActive ? `${showHex ? rgb2Hex(colour) : NULL_STR}${conj}${showLum ? lum.toFixed(2) : NULL_STR}` : NBSP; } generate(); }); // ================================================================================================= function reset() { activeSliders.clear(); setSliderOpacity(); setSwitches(); generate(); } function handleClickOnCell() { appendPalette(this.style.backgroundColor); } function initCells(setCellColour) { for (let j = 0; j < H; j++)
} // We only want the two most recent, or one if user changed between RGB and HSL groups. function setSwitches() { for (let i = 0; i < 6; i++) { let sliderIsActive = activeSliders.has(i); onSwitches[i].checked = sliderIsActive; offSwitches[i].checked = !sliderIsActive; switchboxes[i].style.opacity = activeSliders.group == Math.trunc(i / 3) ? 1 : 0.3; } } // As above, we only want the two most recent, or one if user changed between RGB and HSL groups. function setSliderOpacity() { for (let i = 0; i < 6; i++) { sliderWrappers[i].style.opacity = activeSliders.has(i) ? 1 : 0.3; } } // Main function to generate a new colour block and render it. function generate() { switch (activeSliders.group) { case -1: // If no sliders fixed, generate a grid of random colours setStatus(`Random ${randomMode.toUpperCase()}`); cells.forEach(cell => { cell.style.backgroundColor = randomMode == `hsl` ? `hsl(${randInt(360)}, ${randInt(101)}%, ${randInt(101)}%)` : `rgb(${randInt(256)}, ${randInt(256)}, ${randInt(256)})`; }); break; case 0: // Handle RGB cases switch (activeSliders.activeCount) { case 1: setStatus(`${names[activeSliders.first]}: ${values[activeSliders.first]}`); cells.forEach(cell => { let rgb = activeSliders.has(0) ? [values[0], rgbFactor * cell.x, rgbFactor * cell.y] : (activeSliders.has(1) ? [rgbFactor * cell.x, values[1], rgbFactor * cell.y] : [rgbFactor * cell.x, rgbFactor * cell.y, values[2]]); cell.style.backgroundColor = `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`; }); break; case 2: setStatus(`${names[activeSliders.first]}: ${values[activeSliders.first]}, ${names[activeSliders.second]}: ${values[activeSliders.second]}`); cells.forEach(cell => { let rgb = activeSliders.has(1) && activeSliders.has(2) ? [(cell.y * W + cell.x) * rgb1dFactor, values[1], values[2]] : (activeSliders.has(0) && activeSliders.has(2) ? [values[0], (cell.y * W + cell.x) * rgb1dFactor, values[2]] : [values[0], values[1], (cell.y * W + cell.x) * rgb1dFactor]); cell.style.backgroundColor = `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`; }); break; } // END switch break; // not needed at present; leave for safety in case more code added above case 1: // Handle HSL cases switch (activeSliders.activeCount) { case 1: setStatus(`${names[activeSliders.first]}: ${values[activeSliders.first]} `); cells.forEach(cell => { let hsl = activeSliders.has(3) ? [values[3], cell.x * 100 / W, cell.y * maxLightness / (H - 1) + minLightness]
{ for (let i = 0; i < W; i++) { let cell = document.createElement("div"); cell.x = i; cell.y = j; // Set some initial colours for the cells... cell.style.backgroundColor = setCellColour(i, j); colourGrid.appendChild(cell); } }
conditional_block
haystack.rs
/// /// The `parent` range should be a valid range relative to a hay *a*, which /// was used to slice out *self*: `self == &a[parent]`. /// /// Similarly, the `original` range should be a valid range relative to /// another hay *b* used to slice out *a*: `a == &b[original]`. /// /// The distance of `parent` must be consistent with the length of `self`. /// /// This method should return a range which satisfies: /// /// ```text /// self == &b[parent][original] == &b[range] /// ``` /// /// Slicing can be destructive and *invalidates* some indices, in particular /// for owned type with a pointer-like index, e.g. linked list. In this /// case, one should derive an entirely new index range from `self`, e.g. /// returning `self.start_index()..self.end_index()`. /// /// # Examples /// /// ```rust /// use pattern_3::Haystack; /// /// let hay = b"This is a sample haystack"; /// let this = hay[2..23][3..19].to_vec(); /// assert_eq!(&*this, &hay[this.restore_range(2..23, 3..19)]); /// ``` fn restore_range( &self, original: Range<<Self::Target as Hay>::Index>, parent: Range<<Self::Target as Hay>::Index>, ) -> Range<<Self::Target as Hay>::Index>; } /// A [`Haystack`] which can be shared and cheaply cloned (e.g. `&H`, `Rc<H>`). /// /// If a haystack implements this marker trait, during internal operations the /// original haystack will be retained in full and cloned, rather than being /// sliced and splitted. Being a shared haystack allows searcher to see the /// entire haystack, including the consumed portion. pub trait SharedHaystack: Haystack + Clone where Self::Target: Hay // FIXME: RFC 2089 or 2289 {} /// The borrowing behavior differs between a (unique) haystack and shared /// haystack. We use *specialization* to distinguish between these behavior: /// /// * When using `split_around()` and `slice_unchecked()` with a unique /// haystack, the original haystack will be splitted or sliced accordingly /// to maintain unique ownership. /// * When using these functions with a shared haystack, the original haystack /// will be cloned in full as that could provide more context into /// searchers. /// /// This trait will never be public. trait SpanBehavior: Haystack where Self::Target: Hay // FIXME: RFC 2089 or 2289 { fn take(&mut self) -> Self; fn from_span(span: Span<Self>) -> Self; unsafe fn split_around_for_span(self, subrange: Range<<Self::Target as Hay>::Index>) -> [Self; 3]; unsafe fn slice_unchecked_for_span(self, subrange: Range<<Self::Target as Hay>::Index>) -> Self; fn borrow_range( &self, range: Range<<Self::Target as Hay>::Index>, ) -> Range<<Self::Target as Hay>::Index>; fn do_restore_range( &self, range: Range<<Self::Target as Hay>::Index>, subrange: Range<<Self::Target as Hay>::Index>, ) -> Range<<Self::Target as Hay>::Index>; } impl<H: Haystack> SpanBehavior for H where H::Target: Hay // FIXME: RFC 2089 or 2289 { #[inline] default fn take(&mut self) -> Self { mem::replace(self, Self::empty()) } #[inline] default fn from_span(span: Span<Self>) -> Self { span.haystack } #[inline] default fn borrow_range(&self, _: Range<<Self::Target as Hay>::Index>) -> Range<<Self::Target as Hay>::Index> { self.start_index()..self.end_index() } #[inline] default fn do_restore_range( &self, range: Range<<Self::Target as Hay>::Index>, subrange: Range<<Self::Target as Hay>::Index>, ) -> Range<<Self::Target as Hay>::Index> { self.restore_range(range, subrange) } #[inline] default unsafe fn split_around_for_span(self, subrange: Range<<Self::Target as Hay>::Index>) -> [Self; 3] { self.split_around(subrange) } #[inline] default unsafe fn slice_unchecked_for_span(self, subrange: Range<<Self::Target as Hay>::Index>) -> Self { self.slice_unchecked(subrange) } } impl<H: SharedHaystack> SpanBehavior for H where H::Target: Hay // FIXME: RFC 2089 or 2289 { #[inline] fn take(&mut self) -> Self { self.clone() } #[inline] fn from_span(span: Span<Self>) -> Self { unsafe { span.haystack.slice_unchecked(span.range) } } #[inline] fn borrow_range(&self, range: Range<<Self::Target as Hay>::Index>) -> Range<<Self::Target as Hay>::Index> { range } #[inline] fn do_restore_range( &self, _: Range<<Self::Target as Hay>::Index>, subrange: Range<<Self::Target as Hay>::Index>, ) -> Range<<Self::Target as Hay>::Index> { subrange } #[inline] unsafe fn split_around_for_span(self, _: Range<<Self::Target as Hay>::Index>) -> [Self; 3] { [self.clone(), self.clone(), self] } #[inline] unsafe fn slice_unchecked_for_span(self, _: Range<<Self::Target as Hay>::Index>) -> Self { self } } /// A span is a haystack coupled with the original range where the haystack is found. /// /// It can be considered as a tuple `(H, Range<H::Target::Index>)` /// where the range is guaranteed to be valid for the haystack. /// /// # Examples /// /// ``` /// use pattern_3::Span; /// /// let orig_str = "Hello世界"; /// let orig_span = Span::<&str>::from(orig_str); /// /// // slice a span. /// let span = unsafe { orig_span.slice_unchecked(3..8) }; /// /// // further slicing (note the range is relative to the original span) /// let subspan = unsafe { span.slice_unchecked(4..8) }; /// /// // obtains the substring. /// let substring = subspan.into(); /// assert_eq!(substring, "o世"); /// ``` /// /// Visualizing the spans: /// /// ```text /// /// 0 1 2 3 4 5 6 7 8 9 10 11 /// +---+---+---+---+---+---+---+---+---+---+---+ /// | H | e | l | l | o | U+4E16 | U+754C | orig_str /// +---+---+---+---+---+---+---+---+---+---+---+ /// /// ^___________________________________________^ orig_span = (orig_str, 0..11) /// /// ^___________________^ span = (orig_str, 3..8) /// /// ^_______________^ subspan = (orig_str, 4..8) /// ``` #[derive(Debug, Clone)] pub struct Span<H: Haystack> where H::Target: Hay // FIXME: RFC 2089 or 2289 { haystack: H, range: Range<<<H as Deref>::Target as Hay>::Index>, //^ The `<H as Trait>` is to trick `#[derive]` not to generate // the where bound for `H::Hay`. } /// Creates a span which covers the entire haystack. impl<H: Haystack> From<H> for Span<H> where H::Target: Hay // FIXME: RFC 2089 or 2289 { #[inline] fn from(haystack: H) -> Self { let range = haystack.start_index()..haystack.end_index(); Self { haystack, range } } } impl<H: SharedHaystack> Span<H> where H::Target: Hay // FIXME: RFC 2089 or 2289 { /// Decomposes this span into the original haystack, and the range it focuses on. #[inline] pub fn into_parts(self) -> (H, Range<<H::Target as Hay>::Index>) { (self.haystack, self.range) } /// Creates a span from a haystack, and a range it should focus on. /// /// # Safety /// /// The `range` must be a valid range relative to `haystack`. #[inline] pub unsafe fn from_parts(haystack: H, range: Range<<H::Target as Hay>::Index>) -> Self { Self { h
aystack, range } } } impl<'h> Span<
identifier_body
haystack.rs
::empty()) } #[inline] default fn from_span(span: Span<Self>) -> Self { span.haystack } #[inline] default fn borrow_range(&self, _: Range<<Self::Target as Hay>::Index>) -> Range<<Self::Target as Hay>::Index> { self.start_index()..self.end_index() } #[inline] default fn do_restore_range( &self, range: Range<<Self::Target as Hay>::Index>, subrange: Range<<Self::Target as Hay>::Index>, ) -> Range<<Self::Target as Hay>::Index> { self.restore_range(range, subrange) } #[inline] default unsafe fn split_around_for_span(self, subrange: Range<<Self::Target as Hay>::Index>) -> [Self; 3] { self.split_around(subrange) } #[inline] default unsafe fn slice_unchecked_for_span(self, subrange: Range<<Self::Target as Hay>::Index>) -> Self { self.slice_unchecked(subrange) } } impl<H: SharedHaystack> SpanBehavior for H where H::Target: Hay // FIXME: RFC 2089 or 2289 { #[inline] fn take(&mut self) -> Self { self.clone() } #[inline] fn from_span(span: Span<Self>) -> Self { unsafe { span.haystack.slice_unchecked(span.range) } } #[inline] fn borrow_range(&self, range: Range<<Self::Target as Hay>::Index>) -> Range<<Self::Target as Hay>::Index> { range } #[inline] fn do_restore_range( &self, _: Range<<Self::Target as Hay>::Index>, subrange: Range<<Self::Target as Hay>::Index>, ) -> Range<<Self::Target as Hay>::Index> { subrange } #[inline] unsafe fn split_around_for_span(self, _: Range<<Self::Target as Hay>::Index>) -> [Self; 3] { [self.clone(), self.clone(), self] } #[inline] unsafe fn slice_unchecked_for_span(self, _: Range<<Self::Target as Hay>::Index>) -> Self { self } } /// A span is a haystack coupled with the original range where the haystack is found. /// /// It can be considered as a tuple `(H, Range<H::Target::Index>)` /// where the range is guaranteed to be valid for the haystack. /// /// # Examples /// /// ``` /// use pattern_3::Span; /// /// let orig_str = "Hello世界"; /// let orig_span = Span::<&str>::from(orig_str); /// /// // slice a span. /// let span = unsafe { orig_span.slice_unchecked(3..8) }; /// /// // further slicing (note the range is relative to the original span) /// let subspan = unsafe { span.slice_unchecked(4..8) }; /// /// // obtains the substring. /// let substring = subspan.into(); /// assert_eq!(substring, "o世"); /// ``` /// /// Visualizing the spans: /// /// ```text /// /// 0 1 2 3 4 5 6 7 8 9 10 11 /// +---+---+---+---+---+---+---+---+---+---+---+ /// | H | e | l | l | o | U+4E16 | U+754C | orig_str /// +---+---+---+---+---+---+---+---+---+---+---+ /// /// ^___________________________________________^ orig_span = (orig_str, 0..11) /// /// ^___________________^ span = (orig_str, 3..8) /// /// ^_______________^ subspan = (orig_str, 4..8) /// ``` #[derive(Debug, Clone)] pub struct Span<H: Haystack> where H::Target: Hay // FIXME: RFC 2089 or 2289 { haystack: H, range: Range<<<H as Deref>::Target as Hay>::Index>, //^ The `<H as Trait>` is to trick `#[derive]` not to generate // the where bound for `H::Hay`. } /// Creates a span which covers the entire haystack. impl<H: Haystack> From<H> for Span<H> where H::Target: Hay // FIXME: RFC 2089 or 2289 { #[inline] fn from(haystack: H) -> Self { let range = haystack.start_index()..haystack.end_index(); Self { haystack, range } } } impl<H: SharedHaystack> Span<H> where H::Target: Hay // FIXME: RFC 2089 or 2289 { /// Decomposes this span into the original haystack, and the range it focuses on. #[inline] pub fn into_parts(self) -> (H, Range<<H::Target as Hay>::Index>) { (self.haystack, self.range) } /// Creates a span from a haystack, and a range it should focus on. /// /// # Safety /// /// The `range` must be a valid range relative to `haystack`. #[inline] pub unsafe fn from_parts(haystack: H, range: Range<<H::Target as Hay>::Index>) -> Self { Self { haystack, range } } } impl<'h> Span<&'h str> { /// Reinterprets the string span as a byte-array span. #[inline] pub fn as_bytes(self) -> Span<&'h [u8]> { Span { haystack: self.haystack.as_bytes(), range: self.range, } } } impl<H: Haystack> Span<H> where H::Target: Hay // FIXME: RFC 2089 or 2289 { /// The range of the span, relative to the ultimate original haystack it was sliced from. #[inline] pub fn original_range(&self) -> Range<<H::Target as Hay>::Index> { self.range.clone() } /// Borrows a shared span. #[inline] pub fn borrow(&self) -> Span<&H::Target> { Span { haystack: &*self.haystack, range: self.haystack.borrow_range(self.range.clone()), } } /// Checks whether this span is empty. #[inline] pub fn is_empty(&self) -> bool { self.range.start == self.range.end } /// Returns this span by value, and replaces the original span by an empty /// span. #[inline] pub fn take(&mut self) -> Self { let haystack = self.haystack.take(); let range = self.range.clone(); self.range.end = self.range.start; Span { haystack, range } } // FIXME: This should be changed to an `impl From<Span<H>> for H`. /// Slices the original haystack to the focused range. #[inline] pub fn into(self) -> H { H::from_span(self) } /// Splits this span into 3 spans around the given range. /// /// # Safety /// /// `subrange` must be a valid range relative to `self.borrow()`. A safe /// usage is like: /// /// ```rust /// # use pattern_3::{Span, Needle, Searcher}; /// # let span = Span::from("foo"); /// # let mut searcher = <&str as Needle<&str>>::into_searcher("o"); /// # (|| -> Option<()> { /// let range = searcher.search(span.borrow())?; /// let [left, middle, right] = unsafe { span.split_around(range) }; /// # Some(()) })(); /// ``` #[inline] pub unsafe fn split_around(self, subrange: Range<<H::Target as Hay>::Index>) -> [Self; 3] { let self_range = self.haystack.borrow_range(self.range.clone()); let [left, middle, right] = self.haystack.split_around_for_span(subrange.clone()); let left_range = left.do_restore_range(self.range.clone(), self_range.start..subrange.start); let right_range = right.do_restore_range(self.range.clone(), subrange.end..self_range.end); let middle_range = middle.do_restore_range(self.range, subrange); [ Self { haystack: left, range: left_range }, Self { haystack: middle, range: middle_range }, Self { haystack: right, range: right_range }, ] } /// Slices this span to the given range. /// /// # Safety /// /// `subrange` must be a valid range relative to `self.borrow()`. #[inline] pub unsafe fn slice_unchecked(self, subrange: Range<<H::Target as Hay>::Index>) -> Self { let haystack = self.haystack.slice_unchecked_for_span(subrange.clone()); let range = haystack.do_restore_range(self.range, subrange); Self { haystack, range } } } unsafe impl<'a, A: Hay + ?Sized + 'a> Haystack for &'a A { #[inline] fn empty() -> Self {
identifier_name
haystack.rs
all valid indices `i` of `self`, we have /// `i <= self.end_index()`. fn end_index(&self) -> Self::Index; /// Returns the next immediate index in this haystack. /// /// # Safety /// /// The `index` must be a valid index, and also must not equal to /// `self.end_index()`. /// /// Implementation must ensure that if `j = self.next_index(i)`, then `j` /// is also a valid index satisfying `j > i`. /// /// # Examples /// /// ```rust /// use pattern_3::Hay; /// /// let sample = "A→😀"; /// unsafe { /// assert_eq!(sample.next_index(0), 1); /// assert_eq!(sample.next_index(1), 4); /// assert_eq!(sample.next_index(4), 8); /// } /// ``` unsafe fn next_index(&self, index: Self::Index) -> Self::Index; /// Returns the previous immediate index in this haystack. /// /// # Safety /// /// The `index` must be a valid index, and also must not equal to /// `self.start_index()`. /// /// Implementation must ensure that if `j = self.prev_index(i)`, then `j` /// is also a valid index satisfying `j < i`. /// /// # Examples /// /// ```rust /// use pattern_3::Hay; /// /// let sample = "A→😀"; /// unsafe { /// assert_eq!(sample.prev_index(8), 4); /// assert_eq!(sample.prev_index(4), 1); /// assert_eq!(sample.prev_index(1), 0); /// } /// ``` unsafe fn prev_index(&self, index: Self::Index) -> Self::Index; /// Obtains a child hay by slicing `self`. /// /// # Safety /// /// The two ends of the range must be valid indices. The start of the range /// must be before the end of the range (`range.start <= range.end`). unsafe fn slice_unchecked(&self, range: Range<Self::Index>) -> &Self; } /// Linear splittable structure. /// /// A `Haystack` is implemented for reference and collection types such as /// `&str`, `&mut [T]` and `Vec<T>`. Every haystack can be borrowed as an /// underlying representation called a [`Hay`]. Multiple haystacks may share the /// same hay type, and thus share the same implementation of string search /// algorithms. /// /// In the other words, a `Haystack` is a generalized reference to `Hay`. /// /// # Safety /// /// This trait is unsafe as there are some unchecked requirements which the /// implementor must uphold. Failing to meet these requirements would lead to /// out-of-bound access. The safety requirements are written in each member of /// this trait. pub unsafe trait Haystack: Deref + Sized where Self::Target: Hay { /// Creates an empty haystack. fn empty() -> Self; /// Splits the haystack into 3 slices around the given range. /// /// This method splits `self` into 3 non-overlapping parts: /// /// 1. Before the range (`self[..range.start]`), /// 2. Inside the range (`self[range]`), and /// 3. After the range (`self[range.end..]`) /// /// The returned array contains these 3 parts in order. /// /// # Safety /// /// Caller should ensure that the starts and end indices of `range` are /// valid indices for the haystack `self` with `range.start <= range.end`. /// /// If the haystack is a mutable reference (`&mut A`), implementation must /// ensure that the 3 returned haystack are truly non-overlapping in memory. /// This is required to uphold the "Aliasing XOR Mutability" guarantee. If a /// haystack cannot be physically split into non-overlapping parts (e.g. in /// `OsStr`), then `&mut A` should not implement `Haystack` either. /// /// # Examples /// /// ```rust /// use pattern_3::Haystack; /// /// let haystack = &mut [0, 1, 2, 3, 4, 5, 6]; /// let [left, middle, right] = unsafe { haystack.split_around(2..6) }; /// assert_eq!(left, &mut [0, 1]); /// assert_eq!(middle, &mut [2, 3, 4, 5]); /// assert_eq!(right, &mut [6]); /// ``` unsafe fn split_around(self, range: Range<<Self::Target as Hay>::Index>) -> [Self; 3]; /// Subslices this haystack. /// /// # Safety /// /// The starts and end indices of `range` must be valid indices for the /// haystack `self` with `range.start <= range.end`. unsafe fn slice_unchecked(self, range: Range<<Self::Target as Hay>::Index>) -> Self { let [_, middle, _] = self.split_around(range); middle } /// Transforms the range from relative to self's parent to the original /// haystack it was sliced from. /// /// Typically this method can be simply implemented as /// /// ```text /// (original.start + parent.start)..(original.start + parent.end) /// ``` /// /// If this haystack is a [`SharedHaystack`], this method would never be /// called. /// /// # Safety /// /// The `parent` range should be a valid range relative to a hay *a*, which /// was used to slice out *self*: `self == &a[parent]`. /// /// Similarly, the `original` range should be a valid range relative to /// another hay *b* used to slice out *a*: `a == &b[original]`. /// /// The distance of `parent` must be consistent with the length of `self`. /// /// This method should return a range which satisfies: /// /// ```text /// self == &b[parent][original] == &b[range] /// ``` /// /// Slicing can be destructive and *invalidates* some indices, in particular /// for owned type with a pointer-like index, e.g. linked list. In this /// case, one should derive an entirely new index range from `self`, e.g. /// returning `self.start_index()..self.end_index()`. /// /// # Examples /// /// ```rust /// use pattern_3::Haystack; /// /// let hay = b"This is a sample haystack"; /// let this = hay[2..23][3..19].to_vec(); /// assert_eq!(&*this, &hay[this.restore_range(2..23, 3..19)]); /// ``` fn restore_range( &self, original: Range<<Self::Target as Hay>::Index>, parent: Range<<Self::Target as Hay>::Index>, ) -> Range<<Self::Target as Hay>::Index>; } /// A [`Haystack`] which can be shared and cheaply cloned (e.g. `&H`, `Rc<H>`). /// /// If a haystack implements this marker trait, during internal operations the /// original haystack will be retained in full and cloned, rather than being /// sliced and splitted. Being a shared haystack allows searcher to see the /// entire haystack, including the consumed portion. pub trait SharedHaystack: Haystack + Clone where Self::Target: Hay // FIXME: RFC 2089 or 2289 {} /// The borrowing behavior differs between a (unique) haystack and shared /// haystack. We use *specialization* to distinguish between these behavior: /// /// * When using `split_around()` and `slice_unchecked()` with a unique /// haystack, the original haystack will be splitted or sliced accordingly /// to maintain unique ownership. /// * When using these functions with a shared haystack, the original haystack /// will be cloned in full as that could provide more context into /// searchers. /// /// This trait will never be public. trait SpanBehavior: Haystack where Self::Target: Hay // FIXME: RFC 2089 or 2289 { fn take(&mut self) -> Self; fn from_span(span: Span<Self>) -> Self; unsafe fn split_around_for_span(self, subrange: Range<<Self::Target as Hay>::Index>) -> [Self; 3]; unsafe fn slice_unchecked_for_span(self, subrange: Range<<Self::Target as Hay>::Index>) -> Self; fn borrow_range(
&self, range: Range<<Self::Target as Hay>::Index>, subrange: Range<<Self::Target as Hay>::Index>, ) -> Range<<Self::Target as Hay>::Index>; } impl<H: Haystack> SpanBehavior
&self, range: Range<<Self::Target as Hay>::Index>, ) -> Range<<Self::Target as Hay>::Index>; fn do_restore_range(
random_line_split
googleMapsImplementation.ts
/** * insers the map to the dom of the html document */ displayMap(): void { this.parentElement.style.display = ""; this.isDisplayed = true; } /** * hides the map */ hideMap(): void { this.parentElement.style.display = "none"; this.isDisplayed = false; } /** * remove the map from the dom of the html document (löscht auch alle gesetzten styles) */ deleteMap(): void { this.parentElement.innerHTML = ""; this.parentElement.removeAttribute("style") this.map = null; this.markers = {}; //this.eventTokens = []; this.isDeleted = true; this.isDisplayed = false; this.isInitialized = false; } /** * sets the new zoom of/for the map * @param newZoom the new zoom */ setZoom(newZoom: number): void { this.map.setZoom(newZoom); } /** * returns the current zoom */ getZoom(): number { return this.map.getZoom(); } /** * sets the center of the map * @param lat the latitude * @param lng the longitude */ setCenter(lat: number, lng: number): void { this.map.setCenter(new google.maps.LatLng(lat, lng)); } /** * returns the current center as a geo location */ getCenter() : LatLng { var latlng = this.map.getCenter(); return {lat: latlng.lat(), lng: latlng.lng()}; } /** * returns true: map is hidde, false: map is not hidden or removed */ isMapDisplayed(): boolean { return this.isDisplayed; } /** * returns true: map is fully removed (from dom and all variables), false: not */ isMapDeleted(): boolean { return this.isDeleted; } /** * returns true: map is already initialized, false: not */ isMapInitialized(): boolean { return this.isInitialized; } //see events https://developers.google.com/maps/documentation/javascript/events //see example https://developers.google.com/maps/documentation/javascript/examples/event-simple //see marker docs https://developers.google.com/maps/documentation/javascript/reference#Marker /** * adds a listener for the specified event * @param eventName the name of the event * @param func the function to execute when the events occurs */ addMarkerListener(eventName: string, marker: GoogleMapsMarker, func: (marker: GoogleMapsMarker, ...originalArgs: any[]) => void): EventToken { var token: google.maps.MapsEventListener = marker.googleMarker.addListener(eventName, (...args: any[]) => { func(marker, args); }); google.maps.event.addListener var listenerToken = { id: this.getNewEventId(), map: this, token: token, eventName: eventName } return listenerToken; } /** * removes the listener from the map * @param marker the marker with the given event token * @param listener the event name */ removeMarkerListener(marker: GoogleMapsMarker, token: EventToken): void { google.maps.event.removeListener(token.token); } /** * adds a listener for map for the specified event * @param eventName the name of the event * @param func the function to execute when the events occurs * @return the event token */ addMapListener(eventName: string, func: (...originalArgs: any[]) => void): EventToken { var token = google.maps.event.addListener(this.map, eventName, (event?: any, ...args: any[]) => { func(event, args); }); var listenerToken = { id: this.getNewEventId(), map: this, token: token, eventName: eventName } return listenerToken; } /** * removes the listener from the map * @param token the event token */ removeMapListener(token: EventToken): void { google.maps.event.removeListener(token.token); } /** * returns a marker for the given geoLocation * @param geoLocation the geo location * @param iconPath the path for the marker icon * @param displayOnMap true: draw the marker on the map, false: not * @param data the data to store in the created marker * @return the added marker or null (if something went wrong) */ addMarkerFromGeoLocation(location: LatLng, iconPath: string = "", displayOnMap: boolean = true, data: any = null): GoogleMapsMarker { var googleMarker: google.maps.Marker = new google.maps.Marker ({ position: new google.maps.LatLng(location.lat, location.lng), map: this.map, visible: displayOnMap, icon: iconPath }); var _marker: GoogleMapsMarker = new GoogleMapsMarker(); _marker.map = this; _marker.googleMarker = googleMarker; _marker.visibility = displayOnMap; _marker.location = location; _marker.iconPath = iconPath; _marker.data = data; _marker.id = this.getNewId(); this.markers['_' + _marker.id] = _marker; //store the marker return _marker; } /** * adds a marker to the map (marker must have no id) * @param marker the marker to add (only the following data will be used: location, iconPath, data) * @param displayOnMap true: draw the marker on the map, false: not * @return the added marker (creates a new marker so parameter marker and returned marker are not equal!) * or null (if the id was already hold by another marker! or something other went wrong) */ addMarker(marker: GoogleMapsMarker, displayOnMap: boolean = true): GoogleMapsMarker { //check for valid marker if (marker.id !== undefined && marker.id !== null) { //check for duplicate if (this.markers['_' + marker.id] !== undefined) return null; } var _marker = this.addMarkerFromGeoLocation( marker.location, marker.getIconPath(), displayOnMap, marker.data ); return _marker; } /** * removes the marker from the map (if possible) * @param marker the marker to remove * @param removeFromMap true: remove the marker from the map (visually), false: not * @return the removed marker (same like parameter marker) or null (if the marker was not on this map) */ removeMarker(marker: GoogleMapsMarker, removeFromMap: boolean = true): GoogleMapsMarker { //check for valid marker if (marker.id === undefined || marker.id === null) return null; this.removeMarkerById(marker.id); //return the parameter marker return marker; } /** * removes the marker with the given id (if possible) * @param markerId the marker id * @return the removed marker or null (the marker was not on this map) */ removeMarkerById(markerId: number): GoogleMapsMarker { var _marker: GoogleMapsMarker = this.markers['_' + markerId]; //check for duplicate if (_marker === undefined) return null; _marker.delete(); delete this.markers["_" + _marker.id] return _marker; } /* * returns all markers on this map */ getAllMarkers(): Array<GoogleMapsMarker> { var markers = [] for(var key in this.markers) { if (this.markers.hasOwnProperty(key)) { var marker = this.markers[key] markers.push(marker) } } return markers; } /* * gets the x y coordinates of the marker (relative the the drawing surface) */ getMarkerXY(marker: GoogleMapsMarker): Point { return this.getXYFromGeoLocation(marker.location); } /* * gets the x y coodinates of the geo location on this map (relative the the drawing surface) */ public getXYFromGeoLocation(location: LatLng): Point { var temp = this.overlay.getProjection().fromLatLngToContainerPixel( new google.maps.LatLng(location.lat, location.lng) ); return {x: temp.x, y: temp.y}; } //from ttp://stackoverflow.com/questions/3723083/how-to-use-frompointtolatlng-on-google-maps-v3 public getGeoLocationFromXY(point: Point) : LatLng { var ne = this.map.getBounds().getNorthEast(); var sw = this.map.getBounds().getSouthWest(); var projection = this.map.getProjection(); var topRight = projection.fromLatLngToPoint(ne); var bottomLeft = projection.fromLatLngToPoint(sw); //var scale = Math.pow(2, map.getZoom()); var scale = 1 << map.getZoom(); var newLatlng = projection.fromPointToLatLng(new google.maps.Point(point.x / scale + bottomLeft.x, point.y / scale + topRight.y)); return { lat: newLatlng.lat(), lng: newLatlng.lng() } } //----------------helper functions----------------- /* * returns a new id */ private getNewId(): number { return this.counter++; }
random_line_split
googleMapsImplementation.ts
} /** * gets the geo map */ getMap() : GeoMap { return this.map; } /** * returns a serialize version of this marker */ toSerializedMarker(): SerializedMarker { return { visibility: this.visibility, iconPath: this.iconPath, location: this.location, data: this.data }; } /** * deletes the marker from the map * @return true: marker was removed from the map, false: not */ delete(): boolean { //returns the marker if removed else null this.googleMarker.setMap(null) return true } /* * gets the icon path for this marker */ getIconPath(): string { return this.iconPath; } /** * sets the icon for this marker */ setIconPath(iconPath: string): void { this.iconPath = iconPath; this.googleMarker.setIcon(iconPath); } /** * sets the visibility for this marker * @param {boolean} visible true: visible, false: not visible */ setVisibility(visible: boolean): void { this.visibility = visible; this.googleMarker.setVisible(visible); } /** * @return {boolean} gets the current visibility of this marker (true: visible, false: not visible) */ getVisibility(): boolean { return this.visibility; } /** * gets the position of this marker on its map */ getXY(): Point { return this.map.getMarkerXY(this); } /** * sets the location for this marker * @param location the new location */ setLocation(location: LatLng) { this.googleMarker.setPosition(new google.maps.LatLng(location.lat, location.lng)); this.location = location; } /* * gets the current location of this marker */ getLocation() : LatLng { return this.location; } } /** * the GeoMap implementation for google maps */ class GoogleMapsMap implements GeoMap { /** * a simple counter for the ids */ private counter: number = 0; /** * a simple counter for the event ids */ private eventCounter: number = 0; /** * the parent element that hosts the map */ public parentElement: HTMLElement; /** * the google maps map */ public map: google.maps.Map = null; //private markers: GoogleMapsPair[] = []; //use _ + id as object key to maybe later access the marker through markers._xxx private markers: any = {}; //private eventTokens: EventToken[] = []; //use _ + id as object key //private eventTokens: any = {}; private isDisplayed: boolean = false; private isDeleted: boolean = false; private isInitialized: boolean = false; private overlay: google.maps.OverlayView; /** * google api script sould be already included and loaded in the html head element */ pre_init(callback: () => void) { //callback(); //return; if (window['googleMapsInitialize_$']) { //only include script once callback(); return } var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://maps.googleapis.com/maps/api/js?v=3.23&signed_in=true&libraries=drawing' + //exp '&signed_in=true&callback=googleMapsInitialize_$'; //we need a function googleMapsInitialize for the callback window['googleMapsInitialize_$'] = function () { console.log('inited') callback(); } document.body.appendChild(script); } /** * creates the google maps map */ init(element: HTMLElement, center: LatLng, zoom: number = 16) { this.markers = []; //this.eventTokens = []; this.parentElement = element; this.map = new google.maps.Map(this.parentElement, { zoom: zoom, center: new google.maps.LatLng(center.lat,center.lng) }); this.isDisplayed = true; this.isInitialized = true; //to get the pixel coordinates from a lat lng ... //from http://stackoverflow.com/questions/2674392/how-to-access-google-maps-api-v3-markers-div-and-its-pixel-position/6671206#6671206 //drawing canvas shoul be initialized var overlay = new google.maps.OverlayView(); overlay.draw = function() {}; overlay.setMap(this.map); this.overlay = overlay } /** * insers the map to the dom of the html document */ displayMap(): void { this.parentElement.style.display = ""; this.isDisplayed = true; } /** * hides the map */ hideMap(): void { this.parentElement.style.display = "none"; this.isDisplayed = false; } /** * remove the map from the dom of the html document (löscht auch alle gesetzten styles) */ deleteMap(): void {
/** * sets the new zoom of/for the map * @param newZoom the new zoom */ setZoom(newZoom: number): void { this.map.setZoom(newZoom); } /** * returns the current zoom */ getZoom(): number { return this.map.getZoom(); } /** * sets the center of the map * @param lat the latitude * @param lng the longitude */ setCenter(lat: number, lng: number): void { this.map.setCenter(new google.maps.LatLng(lat, lng)); } /** * returns the current center as a geo location */ getCenter() : LatLng { var latlng = this.map.getCenter(); return {lat: latlng.lat(), lng: latlng.lng()}; } /** * returns true: map is hidde, false: map is not hidden or removed */ isMapDisplayed(): boolean { return this.isDisplayed; } /** * returns true: map is fully removed (from dom and all variables), false: not */ isMapDeleted(): boolean { return this.isDeleted; } /** * returns true: map is already initialized, false: not */ isMapInitialized(): boolean { return this.isInitialized; } //see events https://developers.google.com/maps/documentation/javascript/events //see example https://developers.google.com/maps/documentation/javascript/examples/event-simple //see marker docs https://developers.google.com/maps/documentation/javascript/reference#Marker /** * adds a listener for the specified event * @param eventName the name of the event * @param func the function to execute when the events occurs */ addMarkerListener(eventName: string, marker: GoogleMapsMarker, func: (marker: GoogleMapsMarker, ...originalArgs: any[]) => void): EventToken { var token: google.maps.MapsEventListener = marker.googleMarker.addListener(eventName, (...args: any[]) => { func(marker, args); }); google.maps.event.addListener var listenerToken = { id: this.getNewEventId(), map: this, token: token, eventName: eventName } return listenerToken; } /** * removes the listener from the map * @param marker the marker with the given event token * @param listener the event name */ removeMarkerListener(marker: GoogleMapsMarker, token: EventToken): void { google.maps.event.removeListener(token.token); } /** * adds a listener for map for the specified event * @param eventName the name of the event * @param func the function to execute when the events occurs * @return the event token */ addMapListener(eventName: string, func: (...originalArgs: any[]) => void): EventToken { var token = google.maps.event.addListener(this.map, eventName, (event?: any, ...args: any[]) => { func(event, args); }); var listenerToken = { id: this.getNewEventId(), map: this, token: token, eventName: eventName } return listenerToken; } /** * removes the listener from the map * @param token the event token */ removeMapListener(token: EventToken): void { google.maps.event.removeListener(token.token); } /** * returns a marker for the given geoLocation * @param geoLocation the geo location * @param iconPath the path for the marker icon * @param displayOnMap true: draw the marker on the map, false: not * @param data the data to store in the created marker * @return the added marker or null (if something went wrong) */ addMarkerFromGeoLocation(location: LatLng, iconPath: string = "", displayOnMap: boolean = true, data: any = null): GoogleMapsMarker { var googleMarker: google.maps.Marker = new google.maps.Marker ({ position: new google.maps.LatLng(location.lat,
this.parentElement.innerHTML = ""; this.parentElement.removeAttribute("style") this.map = null; this.markers = {}; //this.eventTokens = []; this.isDeleted = true; this.isDisplayed = false; this.isInitialized = false; }
identifier_body
googleMapsImplementation.ts
} /** * gets the geo map */ getMap() : GeoMap { return this.map; } /** * returns a serialize version of this marker */ toSerializedMarker(): SerializedMarker { return { visibility: this.visibility, iconPath: this.iconPath, location: this.location, data: this.data }; } /** * deletes the marker from the map * @return true: marker was removed from the map, false: not */ delete(): boolean { //returns the marker if removed else null this.googleMarker.setMap(null) return true } /* * gets the icon path for this marker */ getIconPath(): string { return this.iconPath; } /** * sets the icon for this marker */ setIconPath(iconPath: string): void { this.iconPath = iconPath; this.googleMarker.setIcon(iconPath); } /** * sets the visibility for this marker * @param {boolean} visible true: visible, false: not visible */ setVisibility(visible: boolean): void { this.visibility = visible; this.googleMarker.setVisible(visible); } /** * @return {boolean} gets the current visibility of this marker (true: visible, false: not visible) */ getVisibility(): boolean { return this.visibility; } /** * gets the position of this marker on its map */ getXY(): Point { return this.map.getMarkerXY(this); } /** * sets the location for this marker * @param location the new location */ setLocation(location: LatLng) { this.googleMarker.setPosition(new google.maps.LatLng(location.lat, location.lng)); this.location = location; } /* * gets the current location of this marker */ getLocation() : LatLng { return this.location; } } /** * the GeoMap implementation for google maps */ class GoogleMapsMap implements GeoMap { /** * a simple counter for the ids */ private counter: number = 0; /** * a simple counter for the event ids */ private eventCounter: number = 0; /** * the parent element that hosts the map */ public parentElement: HTMLElement; /** * the google maps map */ public map: google.maps.Map = null; //private markers: GoogleMapsPair[] = []; //use _ + id as object key to maybe later access the marker through markers._xxx private markers: any = {}; //private eventTokens: EventToken[] = []; //use _ + id as object key //private eventTokens: any = {}; private isDisplayed: boolean = false; private isDeleted: boolean = false; private isInitialized: boolean = false; private overlay: google.maps.OverlayView; /** * google api script sould be already included and loaded in the html head element */ pre_init(callback: () => void) { //callback(); //return; if (window['googleMapsInitialize_$']) { //only include script once callback(); return } var script = document.createElement('script'); script.type = 'text/javascript'; script.src = 'https://maps.googleapis.com/maps/api/js?v=3.23&signed_in=true&libraries=drawing' + //exp '&signed_in=true&callback=googleMapsInitialize_$'; //we need a function googleMapsInitialize for the callback window['googleMapsInitialize_$'] = function () { console.log('inited') callback(); } document.body.appendChild(script); } /** * creates the google maps map */ init(element: HTMLElement, center: LatLng, zoom: number = 16) { this.markers = []; //this.eventTokens = []; this.parentElement = element; this.map = new google.maps.Map(this.parentElement, { zoom: zoom, center: new google.maps.LatLng(center.lat,center.lng) }); this.isDisplayed = true; this.isInitialized = true; //to get the pixel coordinates from a lat lng ... //from http://stackoverflow.com/questions/2674392/how-to-access-google-maps-api-v3-markers-div-and-its-pixel-position/6671206#6671206 //drawing canvas shoul be initialized var overlay = new google.maps.OverlayView(); overlay.draw = function() {}; overlay.setMap(this.map); this.overlay = overlay } /** * insers the map to the dom of the html document */ displayMap(): void { this.parentElement.style.display = ""; this.isDisplayed = true; } /** * hides the map */ hideMap(): void { this.parentElement.style.display = "none"; this.isDisplayed = false; } /** * remove the map from the dom of the html document (löscht auch alle gesetzten styles) */ deleteMap(): void { this.parentElement.innerHTML = ""; this.parentElement.removeAttribute("style") this.map = null; this.markers = {}; //this.eventTokens = []; this.isDeleted = true; this.isDisplayed = false; this.isInitialized = false; } /** * sets the new zoom of/for the map * @param newZoom the new zoom */ setZoom(newZoom: number): void { this.map.setZoom(newZoom); } /** * returns the current zoom */ getZoom(): number { return this.map.getZoom(); } /** * sets the center of the map * @param lat the latitude * @param lng the longitude */ setCenter(lat: number, lng: number): void { this.map.setCenter(new google.maps.LatLng(lat, lng)); } /** * returns the current center as a geo location */ getCenter() : LatLng { var latlng = this.map.getCenter(); return {lat: latlng.lat(), lng: latlng.lng()}; } /** * returns true: map is hidde, false: map is not hidden or removed */ isMapDisplayed(): boolean { return this.isDisplayed; } /** * returns true: map is fully removed (from dom and all variables), false: not */ isMapDeleted(): boolean { return this.isDeleted; } /** * returns true: map is already initialized, false: not */ isMapInitialized(): boolean { return this.isInitialized; } //see events https://developers.google.com/maps/documentation/javascript/events //see example https://developers.google.com/maps/documentation/javascript/examples/event-simple //see marker docs https://developers.google.com/maps/documentation/javascript/reference#Marker /** * adds a listener for the specified event * @param eventName the name of the event * @param func the function to execute when the events occurs */ addMarkerListener(eventName: string, marker: GoogleMapsMarker, func: (marker: GoogleMapsMarker, ...originalArgs: any[]) => void): EventToken { var token: google.maps.MapsEventListener = marker.googleMarker.addListener(eventName, (...args: any[]) => { func(marker, args); }); google.maps.event.addListener var listenerToken = { id: this.getNewEventId(), map: this, token: token, eventName: eventName } return listenerToken; } /** * removes the listener from the map * @param marker the marker with the given event token * @param listener the event name */ removeMarkerListener(marker: GoogleMapsMarker, token: EventToken): void { google.maps.event.removeListener(token.token); } /** * adds a listener for map for the specified event * @param eventName the name of the event * @param func the function to execute when the events occurs * @return the event token */ addMapListener(eventName: string, func: (...originalArgs: any[]) => void): EventToken { var token = google.maps.event.addListener(this.map, eventName, (event?: any, ...args: any[]) => { func(event, args); }); var listenerToken = { id: this.getNewEventId(), map: this, token: token, eventName: eventName } return listenerToken; } /** * removes the listener from the map * @param token the event token */ removeMapListener(token: EventToken): void { google.maps.event.removeListener(token.token); } /** * returns a marker for the given geoLocation * @param geoLocation the geo location * @param iconPath the path for the marker icon * @param displayOnMap true: draw the marker on the map, false: not * @param data the data to store in the created marker * @return the added marker or null (if something went wrong) */ ad
ocation: LatLng, iconPath: string = "", displayOnMap: boolean = true, data: any = null): GoogleMapsMarker { var googleMarker: google.maps.Marker = new google.maps.Marker ({ position: new google.maps.LatLng(location.lat
dMarkerFromGeoLocation(l
identifier_name
context.go
Value() JSSrc() Value // Reports whether the app has been updated in background. Use app.Reload() // to load the updated version. AppUpdateAvailable() bool // Reports whether the app is installable. IsAppInstallable() bool // Shows the app install prompt if the app is installable. ShowAppInstallPrompt() // Returns the current page. Page() Page // Executes the given function on the UI goroutine and notifies the // context's nearest component to update its state. Dispatch(fn func(Context)) // Executes the given function on the UI goroutine after notifying the // context's nearest component to update its state. Defer(fn func(Context)) // Registers the handler for the given action name. When an action occurs, // the handler is executed on the UI goroutine. Handle(actionName string, h ActionHandler) // Creates an action with optional tags, to be handled with Context.Handle. // Eg: // ctx.NewAction("myAction") // ctx.NewAction("myAction", app.T("purpose", "test")) // ctx.NewAction("myAction", app.Tags{ // "foo": "bar", // "hello": "world", // }) NewAction(name string, tags ...Tagger) // Creates an action with a value and optional tags, to be handled with // Context.Handle. Eg: // ctx.NewActionWithValue("processValue", 42) // ctx.NewActionWithValue("processValue", 42, app.T("type", "number")) // ctx.NewActionWithValue("myAction", 42, app.Tags{ // "foo": "bar", // "hello": "world", // }) NewActionWithValue(name string, v any, tags ...Tagger) // Executes the given function on a new goroutine. // // The difference versus just launching a goroutine is that it ensures that // the asynchronous function is called before a page is fully pre-rendered // and served over HTTP. Async(fn func()) // Asynchronously waits for the given duration and dispatches the given // function. After(d time.Duration, fn func(Context)) // Executes the given function and notifies the parent components to update // their state. It should be used to launch component custom event handlers. Emit(fn func()) // Reloads the WebAssembly app to the current page. It is like refreshing // the browser page. Reload() // Navigates to the given URL. This is a helper method that converts url to // an *url.URL and then calls ctx.NavigateTo under the hood. Navigate(url string) // Navigates to the given URL. NavigateTo(u *url.URL) // Resolves the given path to make it point to the right location whether // static resources are located on a local directory or a remote bucket. ResolveStaticResource(string) string // Returns a storage that uses the browser local storage associated to the // document origin. Data stored has no expiration time. LocalStorage() BrowserStorage // Returns a storage that uses the browser session storage associated to the // document origin. Data stored expire when the page session ends. SessionStorage() BrowserStorage // Scrolls to the HTML element with the given id. ScrollTo(id string) // Returns a UUID that identifies the app on the current device. DeviceID() string // Encrypts the given value using AES encryption. Encrypt(v any) ([]byte, error) // Decrypts the given encrypted bytes and stores them in the given value. Decrypt(crypted []byte, v any) error // Sets the state with the given value. // Example: // ctx.SetState("/globalNumber", 42, Persistent) // // Options can be added to persist a state into the local storage, encrypt, // expire, or broadcast the state across browser tabs and windows. // Example: // ctx.SetState("/globalNumber", 42, Persistent, Broadcast) SetState(state string, v any, opts ...StateOption) // Stores the specified state value into the given receiver. Panics when the // receiver is not a pointer or nil. GetState(state string, recv any) // Deletes the given state. All value observations are stopped. DelState(state string) // Creates an observer that observes changes for the given state. // Example: // type myComponent struct { // app.Compo // // number int // } // // func (c *myComponent) OnMount(ctx app.Context) { // ctx.ObserveState("/globalNumber").Value(&c.number) // } ObserveState(state string) Observer // Returns the app dispatcher. Dispatcher() Dispatcher // Returns the service to setup and display notifications. Notifications() NotificationService // Prevents the component that contains the context source to be updated. PreventUpdate() } type uiContext struct { context.Context src UI jsSrc Value appUpdateAvailable bool page Page disp Dispatcher } func (ctx uiContext) Src() UI { return ctx.src } func (ctx uiContext) JSSrc() Value { return ctx.jsSrc } func (ctx uiContext) AppUpdateAvailable() bool { return ctx.appUpdateAvailable
func (ctx uiContext) IsAppInstallable() bool { if Window().Get("goappIsAppInstallable").Truthy() { return Window().Call("goappIsAppInstallable").Bool() } return false } func (ctx uiContext) IsAppInstalled() bool { if Window().Get("goappIsAppInstalled").Truthy() { return Window().Call("goappIsAppInstalled").Bool() } return false } func (ctx uiContext) ShowAppInstallPrompt() { if ctx.IsAppInstallable() { Window().Call("goappShowInstallPrompt") } } func (ctx uiContext) Page() Page { return ctx.page } func (ctx uiContext) Dispatch(fn func(Context)) { ctx.Dispatcher().Dispatch(Dispatch{ Mode: Update, Source: ctx.Src(), Function: fn, }) } func (ctx uiContext) Defer(fn func(Context)) { ctx.Dispatcher().Dispatch(Dispatch{ Mode: Defer, Source: ctx.Src(), Function: fn, }) } func (ctx uiContext) Handle(actionName string, h ActionHandler) { ctx.Dispatcher().Handle(actionName, ctx.Src(), h) } func (ctx uiContext) NewAction(name string, tags ...Tagger) { ctx.NewActionWithValue(name, nil, tags...) } func (ctx uiContext) NewActionWithValue(name string, v any, tags ...Tagger) { var tagMap Tags for _, t := range tags { if tagMap == nil { tagMap = t.Tags() continue } for k, v := range t.Tags() { tagMap[k] = v } } ctx.Dispatcher().Post(Action{ Name: name, Value: v, Tags: tagMap, }) } func (ctx uiContext) Async(fn func()) { ctx.Dispatcher().Async(fn) } func (ctx uiContext) After(d time.Duration, fn func(Context)) { ctx.Async(func() { time.Sleep(d) ctx.Dispatch(fn) }) } func (ctx uiContext) Emit(fn func()) { ctx.Dispatcher().Emit(ctx.Src(), fn) } func (ctx uiContext) Reload() { if IsServer { return } ctx.Defer(func(ctx Context) { Window().Get("location").Call("reload") }) } func (ctx uiContext) Navigate(rawURL string) { ctx.Defer(func(ctx Context) { navigate(ctx.Dispatcher(), rawURL) }) } func (ctx uiContext) NavigateTo(u *url.URL) { ctx.Defer(func(ctx Context) { navigateTo(ctx.Dispatcher(), u, true) }) } func (ctx uiContext) ResolveStaticResource(path string) string { return ctx.Dispatcher().resolveStaticResource(path) } func (ctx uiContext) LocalStorage() BrowserStorage { return ctx.Dispatcher().getLocalStorage() } func (ctx uiContext) SessionStorage() BrowserStorage { return ctx.Dispatcher().getSessionStorage() } func (ctx uiContext) ScrollTo(id string) { ctx.Defer(func(ctx Context) { Window().ScrollToID(id) }) } func (ctx uiContext) DeviceID() string { var id string if err := ctx.LocalStorage().Get("/go-app/deviceID", &id); err != nil { panic(errors.New("retrieving device id failed").Wrap(err)) } if id != "" { return id } id = uuid.NewString() if err := ctx.LocalStorage().Set("/go-app/deviceID", id); err != nil { panic(errors.New("creating device id failed").Wrap(err)) } return id } func (ctx uiContext) Encrypt(v any) ([]byte, error) { b, err := json.Marshal(v) if err != nil { return nil, errors.New("encoding value failed").Wrap(err) } b, err = encrypt(ctx.cryptoKey(), b) if err != nil { return nil, errors.New("encrypting value failed").Wrap(err) } return b
}
random_line_split
context.go
() JSSrc() Value // Reports whether the app has been updated in background. Use app.Reload() // to load the updated version. AppUpdateAvailable() bool // Reports whether the app is installable. IsAppInstallable() bool // Shows the app install prompt if the app is installable. ShowAppInstallPrompt() // Returns the current page. Page() Page // Executes the given function on the UI goroutine and notifies the // context's nearest component to update its state. Dispatch(fn func(Context)) // Executes the given function on the UI goroutine after notifying the // context's nearest component to update its state. Defer(fn func(Context)) // Registers the handler for the given action name. When an action occurs, // the handler is executed on the UI goroutine. Handle(actionName string, h ActionHandler) // Creates an action with optional tags, to be handled with Context.Handle. // Eg: // ctx.NewAction("myAction") // ctx.NewAction("myAction", app.T("purpose", "test")) // ctx.NewAction("myAction", app.Tags{ // "foo": "bar", // "hello": "world", // }) NewAction(name string, tags ...Tagger) // Creates an action with a value and optional tags, to be handled with // Context.Handle. Eg: // ctx.NewActionWithValue("processValue", 42) // ctx.NewActionWithValue("processValue", 42, app.T("type", "number")) // ctx.NewActionWithValue("myAction", 42, app.Tags{ // "foo": "bar", // "hello": "world", // }) NewActionWithValue(name string, v any, tags ...Tagger) // Executes the given function on a new goroutine. // // The difference versus just launching a goroutine is that it ensures that // the asynchronous function is called before a page is fully pre-rendered // and served over HTTP. Async(fn func()) // Asynchronously waits for the given duration and dispatches the given // function. After(d time.Duration, fn func(Context)) // Executes the given function and notifies the parent components to update // their state. It should be used to launch component custom event handlers. Emit(fn func()) // Reloads the WebAssembly app to the current page. It is like refreshing // the browser page. Reload() // Navigates to the given URL. This is a helper method that converts url to // an *url.URL and then calls ctx.NavigateTo under the hood. Navigate(url string) // Navigates to the given URL. NavigateTo(u *url.URL) // Resolves the given path to make it point to the right location whether // static resources are located on a local directory or a remote bucket. ResolveStaticResource(string) string // Returns a storage that uses the browser local storage associated to the // document origin. Data stored has no expiration time. LocalStorage() BrowserStorage // Returns a storage that uses the browser session storage associated to the // document origin. Data stored expire when the page session ends. SessionStorage() BrowserStorage // Scrolls to the HTML element with the given id. ScrollTo(id string) // Returns a UUID that identifies the app on the current device. DeviceID() string // Encrypts the given value using AES encryption. Encrypt(v any) ([]byte, error) // Decrypts the given encrypted bytes and stores them in the given value. Decrypt(crypted []byte, v any) error // Sets the state with the given value. // Example: // ctx.SetState("/globalNumber", 42, Persistent) // // Options can be added to persist a state into the local storage, encrypt, // expire, or broadcast the state across browser tabs and windows. // Example: // ctx.SetState("/globalNumber", 42, Persistent, Broadcast) SetState(state string, v any, opts ...StateOption) // Stores the specified state value into the given receiver. Panics when the // receiver is not a pointer or nil. GetState(state string, recv any) // Deletes the given state. All value observations are stopped. DelState(state string) // Creates an observer that observes changes for the given state. // Example: // type myComponent struct { // app.Compo // // number int // } // // func (c *myComponent) OnMount(ctx app.Context) { // ctx.ObserveState("/globalNumber").Value(&c.number) // } ObserveState(state string) Observer // Returns the app dispatcher. Dispatcher() Dispatcher // Returns the service to setup and display notifications. Notifications() NotificationService // Prevents the component that contains the context source to be updated. PreventUpdate() } type uiContext struct { context.Context src UI jsSrc Value appUpdateAvailable bool page Page disp Dispatcher } func (ctx uiContext) Src() UI { return ctx.src } func (ctx uiContext) JSSrc() Value { return ctx.jsSrc } func (ctx uiContext) AppUpdateAvailable() bool { return ctx.appUpdateAvailable } func (ctx uiContext) IsAppInstallable() bool { if Window().Get("goappIsAppInstallable").Truthy() { return Window().Call("goappIsAppInstallable").Bool() } return false } func (ctx uiContext) IsAppInstalled() bool { if Window().Get("goappIsAppInstalled").Truthy() { return Window().Call("goappIsAppInstalled").Bool() } return false } func (ctx uiContext) ShowAppInstallPrompt() { if ctx.IsAppInstallable()
} func (ctx uiContext) Page() Page { return ctx.page } func (ctx uiContext) Dispatch(fn func(Context)) { ctx.Dispatcher().Dispatch(Dispatch{ Mode: Update, Source: ctx.Src(), Function: fn, }) } func (ctx uiContext) Defer(fn func(Context)) { ctx.Dispatcher().Dispatch(Dispatch{ Mode: Defer, Source: ctx.Src(), Function: fn, }) } func (ctx uiContext) Handle(actionName string, h ActionHandler) { ctx.Dispatcher().Handle(actionName, ctx.Src(), h) } func (ctx uiContext) NewAction(name string, tags ...Tagger) { ctx.NewActionWithValue(name, nil, tags...) } func (ctx uiContext) NewActionWithValue(name string, v any, tags ...Tagger) { var tagMap Tags for _, t := range tags { if tagMap == nil { tagMap = t.Tags() continue } for k, v := range t.Tags() { tagMap[k] = v } } ctx.Dispatcher().Post(Action{ Name: name, Value: v, Tags: tagMap, }) } func (ctx uiContext) Async(fn func()) { ctx.Dispatcher().Async(fn) } func (ctx uiContext) After(d time.Duration, fn func(Context)) { ctx.Async(func() { time.Sleep(d) ctx.Dispatch(fn) }) } func (ctx uiContext) Emit(fn func()) { ctx.Dispatcher().Emit(ctx.Src(), fn) } func (ctx uiContext) Reload() { if IsServer { return } ctx.Defer(func(ctx Context) { Window().Get("location").Call("reload") }) } func (ctx uiContext) Navigate(rawURL string) { ctx.Defer(func(ctx Context) { navigate(ctx.Dispatcher(), rawURL) }) } func (ctx uiContext) NavigateTo(u *url.URL) { ctx.Defer(func(ctx Context) { navigateTo(ctx.Dispatcher(), u, true) }) } func (ctx uiContext) ResolveStaticResource(path string) string { return ctx.Dispatcher().resolveStaticResource(path) } func (ctx uiContext) LocalStorage() BrowserStorage { return ctx.Dispatcher().getLocalStorage() } func (ctx uiContext) SessionStorage() BrowserStorage { return ctx.Dispatcher().getSessionStorage() } func (ctx uiContext) ScrollTo(id string) { ctx.Defer(func(ctx Context) { Window().ScrollToID(id) }) } func (ctx uiContext) DeviceID() string { var id string if err := ctx.LocalStorage().Get("/go-app/deviceID", &id); err != nil { panic(errors.New("retrieving device id failed").Wrap(err)) } if id != "" { return id } id = uuid.NewString() if err := ctx.LocalStorage().Set("/go-app/deviceID", id); err != nil { panic(errors.New("creating device id failed").Wrap(err)) } return id } func (ctx uiContext) Encrypt(v any) ([]byte, error) { b, err := json.Marshal(v) if err != nil { return nil, errors.New("encoding value failed").Wrap(err) } b, err = encrypt(ctx.cryptoKey(), b) if err != nil { return nil, errors.New("encrypting value failed").Wrap(err) }
{ Window().Call("goappShowInstallPrompt") }
conditional_block
context.go
() JSSrc() Value // Reports whether the app has been updated in background. Use app.Reload() // to load the updated version. AppUpdateAvailable() bool // Reports whether the app is installable. IsAppInstallable() bool // Shows the app install prompt if the app is installable. ShowAppInstallPrompt() // Returns the current page. Page() Page // Executes the given function on the UI goroutine and notifies the // context's nearest component to update its state. Dispatch(fn func(Context)) // Executes the given function on the UI goroutine after notifying the // context's nearest component to update its state. Defer(fn func(Context)) // Registers the handler for the given action name. When an action occurs, // the handler is executed on the UI goroutine. Handle(actionName string, h ActionHandler) // Creates an action with optional tags, to be handled with Context.Handle. // Eg: // ctx.NewAction("myAction") // ctx.NewAction("myAction", app.T("purpose", "test")) // ctx.NewAction("myAction", app.Tags{ // "foo": "bar", // "hello": "world", // }) NewAction(name string, tags ...Tagger) // Creates an action with a value and optional tags, to be handled with // Context.Handle. Eg: // ctx.NewActionWithValue("processValue", 42) // ctx.NewActionWithValue("processValue", 42, app.T("type", "number")) // ctx.NewActionWithValue("myAction", 42, app.Tags{ // "foo": "bar", // "hello": "world", // }) NewActionWithValue(name string, v any, tags ...Tagger) // Executes the given function on a new goroutine. // // The difference versus just launching a goroutine is that it ensures that // the asynchronous function is called before a page is fully pre-rendered // and served over HTTP. Async(fn func()) // Asynchronously waits for the given duration and dispatches the given // function. After(d time.Duration, fn func(Context)) // Executes the given function and notifies the parent components to update // their state. It should be used to launch component custom event handlers. Emit(fn func()) // Reloads the WebAssembly app to the current page. It is like refreshing // the browser page. Reload() // Navigates to the given URL. This is a helper method that converts url to // an *url.URL and then calls ctx.NavigateTo under the hood. Navigate(url string) // Navigates to the given URL. NavigateTo(u *url.URL) // Resolves the given path to make it point to the right location whether // static resources are located on a local directory or a remote bucket. ResolveStaticResource(string) string // Returns a storage that uses the browser local storage associated to the // document origin. Data stored has no expiration time. LocalStorage() BrowserStorage // Returns a storage that uses the browser session storage associated to the // document origin. Data stored expire when the page session ends. SessionStorage() BrowserStorage // Scrolls to the HTML element with the given id. ScrollTo(id string) // Returns a UUID that identifies the app on the current device. DeviceID() string // Encrypts the given value using AES encryption. Encrypt(v any) ([]byte, error) // Decrypts the given encrypted bytes and stores them in the given value. Decrypt(crypted []byte, v any) error // Sets the state with the given value. // Example: // ctx.SetState("/globalNumber", 42, Persistent) // // Options can be added to persist a state into the local storage, encrypt, // expire, or broadcast the state across browser tabs and windows. // Example: // ctx.SetState("/globalNumber", 42, Persistent, Broadcast) SetState(state string, v any, opts ...StateOption) // Stores the specified state value into the given receiver. Panics when the // receiver is not a pointer or nil. GetState(state string, recv any) // Deletes the given state. All value observations are stopped. DelState(state string) // Creates an observer that observes changes for the given state. // Example: // type myComponent struct { // app.Compo // // number int // } // // func (c *myComponent) OnMount(ctx app.Context) { // ctx.ObserveState("/globalNumber").Value(&c.number) // } ObserveState(state string) Observer // Returns the app dispatcher. Dispatcher() Dispatcher // Returns the service to setup and display notifications. Notifications() NotificationService // Prevents the component that contains the context source to be updated. PreventUpdate() } type uiContext struct { context.Context src UI jsSrc Value appUpdateAvailable bool page Page disp Dispatcher } func (ctx uiContext) Src() UI { return ctx.src } func (ctx uiContext) JSSrc() Value { return ctx.jsSrc } func (ctx uiContext) AppUpdateAvailable() bool { return ctx.appUpdateAvailable } func (ctx uiContext) IsAppInstallable() bool { if Window().Get("goappIsAppInstallable").Truthy() { return Window().Call("goappIsAppInstallable").Bool() } return false } func (ctx uiContext) IsAppInstalled() bool { if Window().Get("goappIsAppInstalled").Truthy() { return Window().Call("goappIsAppInstalled").Bool() } return false } func (ctx uiContext) ShowAppInstallPrompt() { if ctx.IsAppInstallable() { Window().Call("goappShowInstallPrompt") } } func (ctx uiContext) Page() Page { return ctx.page } func (ctx uiContext) Dispatch(fn func(Context)) { ctx.Dispatcher().Dispatch(Dispatch{ Mode: Update, Source: ctx.Src(), Function: fn, }) } func (ctx uiContext) Defer(fn func(Context))
func (ctx uiContext) Handle(actionName string, h ActionHandler) { ctx.Dispatcher().Handle(actionName, ctx.Src(), h) } func (ctx uiContext) NewAction(name string, tags ...Tagger) { ctx.NewActionWithValue(name, nil, tags...) } func (ctx uiContext) NewActionWithValue(name string, v any, tags ...Tagger) { var tagMap Tags for _, t := range tags { if tagMap == nil { tagMap = t.Tags() continue } for k, v := range t.Tags() { tagMap[k] = v } } ctx.Dispatcher().Post(Action{ Name: name, Value: v, Tags: tagMap, }) } func (ctx uiContext) Async(fn func()) { ctx.Dispatcher().Async(fn) } func (ctx uiContext) After(d time.Duration, fn func(Context)) { ctx.Async(func() { time.Sleep(d) ctx.Dispatch(fn) }) } func (ctx uiContext) Emit(fn func()) { ctx.Dispatcher().Emit(ctx.Src(), fn) } func (ctx uiContext) Reload() { if IsServer { return } ctx.Defer(func(ctx Context) { Window().Get("location").Call("reload") }) } func (ctx uiContext) Navigate(rawURL string) { ctx.Defer(func(ctx Context) { navigate(ctx.Dispatcher(), rawURL) }) } func (ctx uiContext) NavigateTo(u *url.URL) { ctx.Defer(func(ctx Context) { navigateTo(ctx.Dispatcher(), u, true) }) } func (ctx uiContext) ResolveStaticResource(path string) string { return ctx.Dispatcher().resolveStaticResource(path) } func (ctx uiContext) LocalStorage() BrowserStorage { return ctx.Dispatcher().getLocalStorage() } func (ctx uiContext) SessionStorage() BrowserStorage { return ctx.Dispatcher().getSessionStorage() } func (ctx uiContext) ScrollTo(id string) { ctx.Defer(func(ctx Context) { Window().ScrollToID(id) }) } func (ctx uiContext) DeviceID() string { var id string if err := ctx.LocalStorage().Get("/go-app/deviceID", &id); err != nil { panic(errors.New("retrieving device id failed").Wrap(err)) } if id != "" { return id } id = uuid.NewString() if err := ctx.LocalStorage().Set("/go-app/deviceID", id); err != nil { panic(errors.New("creating device id failed").Wrap(err)) } return id } func (ctx uiContext) Encrypt(v any) ([]byte, error) { b, err := json.Marshal(v) if err != nil { return nil, errors.New("encoding value failed").Wrap(err) } b, err = encrypt(ctx.cryptoKey(), b) if err != nil { return nil, errors.New("encrypting value failed").Wrap(err) }
{ ctx.Dispatcher().Dispatch(Dispatch{ Mode: Defer, Source: ctx.Src(), Function: fn, }) }
identifier_body
context.go
() JSSrc() Value // Reports whether the app has been updated in background. Use app.Reload() // to load the updated version. AppUpdateAvailable() bool // Reports whether the app is installable. IsAppInstallable() bool // Shows the app install prompt if the app is installable. ShowAppInstallPrompt() // Returns the current page. Page() Page // Executes the given function on the UI goroutine and notifies the // context's nearest component to update its state. Dispatch(fn func(Context)) // Executes the given function on the UI goroutine after notifying the // context's nearest component to update its state. Defer(fn func(Context)) // Registers the handler for the given action name. When an action occurs, // the handler is executed on the UI goroutine. Handle(actionName string, h ActionHandler) // Creates an action with optional tags, to be handled with Context.Handle. // Eg: // ctx.NewAction("myAction") // ctx.NewAction("myAction", app.T("purpose", "test")) // ctx.NewAction("myAction", app.Tags{ // "foo": "bar", // "hello": "world", // }) NewAction(name string, tags ...Tagger) // Creates an action with a value and optional tags, to be handled with // Context.Handle. Eg: // ctx.NewActionWithValue("processValue", 42) // ctx.NewActionWithValue("processValue", 42, app.T("type", "number")) // ctx.NewActionWithValue("myAction", 42, app.Tags{ // "foo": "bar", // "hello": "world", // }) NewActionWithValue(name string, v any, tags ...Tagger) // Executes the given function on a new goroutine. // // The difference versus just launching a goroutine is that it ensures that // the asynchronous function is called before a page is fully pre-rendered // and served over HTTP. Async(fn func()) // Asynchronously waits for the given duration and dispatches the given // function. After(d time.Duration, fn func(Context)) // Executes the given function and notifies the parent components to update // their state. It should be used to launch component custom event handlers. Emit(fn func()) // Reloads the WebAssembly app to the current page. It is like refreshing // the browser page. Reload() // Navigates to the given URL. This is a helper method that converts url to // an *url.URL and then calls ctx.NavigateTo under the hood. Navigate(url string) // Navigates to the given URL. NavigateTo(u *url.URL) // Resolves the given path to make it point to the right location whether // static resources are located on a local directory or a remote bucket. ResolveStaticResource(string) string // Returns a storage that uses the browser local storage associated to the // document origin. Data stored has no expiration time. LocalStorage() BrowserStorage // Returns a storage that uses the browser session storage associated to the // document origin. Data stored expire when the page session ends. SessionStorage() BrowserStorage // Scrolls to the HTML element with the given id. ScrollTo(id string) // Returns a UUID that identifies the app on the current device. DeviceID() string // Encrypts the given value using AES encryption. Encrypt(v any) ([]byte, error) // Decrypts the given encrypted bytes and stores them in the given value. Decrypt(crypted []byte, v any) error // Sets the state with the given value. // Example: // ctx.SetState("/globalNumber", 42, Persistent) // // Options can be added to persist a state into the local storage, encrypt, // expire, or broadcast the state across browser tabs and windows. // Example: // ctx.SetState("/globalNumber", 42, Persistent, Broadcast) SetState(state string, v any, opts ...StateOption) // Stores the specified state value into the given receiver. Panics when the // receiver is not a pointer or nil. GetState(state string, recv any) // Deletes the given state. All value observations are stopped. DelState(state string) // Creates an observer that observes changes for the given state. // Example: // type myComponent struct { // app.Compo // // number int // } // // func (c *myComponent) OnMount(ctx app.Context) { // ctx.ObserveState("/globalNumber").Value(&c.number) // } ObserveState(state string) Observer // Returns the app dispatcher. Dispatcher() Dispatcher // Returns the service to setup and display notifications. Notifications() NotificationService // Prevents the component that contains the context source to be updated. PreventUpdate() } type uiContext struct { context.Context src UI jsSrc Value appUpdateAvailable bool page Page disp Dispatcher } func (ctx uiContext) Src() UI { return ctx.src } func (ctx uiContext) JSSrc() Value { return ctx.jsSrc } func (ctx uiContext) AppUpdateAvailable() bool { return ctx.appUpdateAvailable } func (ctx uiContext) IsAppInstallable() bool { if Window().Get("goappIsAppInstallable").Truthy() { return Window().Call("goappIsAppInstallable").Bool() } return false } func (ctx uiContext) IsAppInstalled() bool { if Window().Get("goappIsAppInstalled").Truthy() { return Window().Call("goappIsAppInstalled").Bool() } return false } func (ctx uiContext) ShowAppInstallPrompt() { if ctx.IsAppInstallable() { Window().Call("goappShowInstallPrompt") } } func (ctx uiContext) Page() Page { return ctx.page } func (ctx uiContext) Dispatch(fn func(Context)) { ctx.Dispatcher().Dispatch(Dispatch{ Mode: Update, Source: ctx.Src(), Function: fn, }) } func (ctx uiContext) Defer(fn func(Context)) { ctx.Dispatcher().Dispatch(Dispatch{ Mode: Defer, Source: ctx.Src(), Function: fn, }) } func (ctx uiContext) Handle(actionName string, h ActionHandler) { ctx.Dispatcher().Handle(actionName, ctx.Src(), h) } func (ctx uiContext) NewAction(name string, tags ...Tagger) { ctx.NewActionWithValue(name, nil, tags...) } func (ctx uiContext) NewActionWithValue(name string, v any, tags ...Tagger) { var tagMap Tags for _, t := range tags { if tagMap == nil { tagMap = t.Tags() continue } for k, v := range t.Tags() { tagMap[k] = v } } ctx.Dispatcher().Post(Action{ Name: name, Value: v, Tags: tagMap, }) } func (ctx uiContext) Async(fn func()) { ctx.Dispatcher().Async(fn) } func (ctx uiContext) After(d time.Duration, fn func(Context)) { ctx.Async(func() { time.Sleep(d) ctx.Dispatch(fn) }) } func (ctx uiContext)
(fn func()) { ctx.Dispatcher().Emit(ctx.Src(), fn) } func (ctx uiContext) Reload() { if IsServer { return } ctx.Defer(func(ctx Context) { Window().Get("location").Call("reload") }) } func (ctx uiContext) Navigate(rawURL string) { ctx.Defer(func(ctx Context) { navigate(ctx.Dispatcher(), rawURL) }) } func (ctx uiContext) NavigateTo(u *url.URL) { ctx.Defer(func(ctx Context) { navigateTo(ctx.Dispatcher(), u, true) }) } func (ctx uiContext) ResolveStaticResource(path string) string { return ctx.Dispatcher().resolveStaticResource(path) } func (ctx uiContext) LocalStorage() BrowserStorage { return ctx.Dispatcher().getLocalStorage() } func (ctx uiContext) SessionStorage() BrowserStorage { return ctx.Dispatcher().getSessionStorage() } func (ctx uiContext) ScrollTo(id string) { ctx.Defer(func(ctx Context) { Window().ScrollToID(id) }) } func (ctx uiContext) DeviceID() string { var id string if err := ctx.LocalStorage().Get("/go-app/deviceID", &id); err != nil { panic(errors.New("retrieving device id failed").Wrap(err)) } if id != "" { return id } id = uuid.NewString() if err := ctx.LocalStorage().Set("/go-app/deviceID", id); err != nil { panic(errors.New("creating device id failed").Wrap(err)) } return id } func (ctx uiContext) Encrypt(v any) ([]byte, error) { b, err := json.Marshal(v) if err != nil { return nil, errors.New("encoding value failed").Wrap(err) } b, err = encrypt(ctx.cryptoKey(), b) if err != nil { return nil, errors.New("encrypting value failed").Wrap(err) }
Emit
identifier_name
tokio_ct.rs
// We can spawn !Send futures here. /// // /// let join_handle = exec.spawn_handle_local( not_send ).expect( "spawn" ); /// /// join_handle.await; /// }); ///``` /// /// ## Unwind Safety. /// /// When a future spawned on this wrapper panics, the panic will be caught by tokio in the poll function. /// /// You must only spawn futures to this API that are unwind safe. Tokio will wrap spawned tasks in /// [`std::panic::AssertUnwindSafe`] and wrap the poll invocation with [`std::panic::catch_unwind`]. /// /// They reason that this is fine because they require `Send + 'static` on the task. As far /// as I can tell this is wrong. Unwind safety can be circumvented in several ways even with /// `Send + 'static` (eg. `parking_lot::Mutex` is `Send + 'static` but `!UnwindSafe`). /// /// You should make sure that if your future panics, no code that lives on after the panic, /// nor any destructors called during the unwind can observe data in an inconsistent state. /// /// Note: the future running from within `block_on` as opposed to `spawn` does not exhibit this behavior and will panic /// the current thread. /// /// Note that these are logic errors, not related to the class of problems that cannot happen /// in safe rust (memory safety, undefined behavior, unsoundness, data races, ...). See the relevant /// [catch_unwind RFC](https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md) /// and it's discussion threads for more info as well as the documentation of [`std::panic::UnwindSafe`] /// for more information. /// // #[ derive( Debug, Clone ) ] // #[ cfg_attr( nightly, doc(cfg( feature = "tokio_ct" )) ) ] // pub struct TokioCt { spawner: Spawner, local: Rc< LocalSet > , } /// Create a `TokioCt` from a `Runtime`. /// /// # Errors /// /// Will fail if you pass a multithreaded runtime. In that case it will return your [`Runtime`]. // impl TryFrom<Runtime> for TokioCt { type Error = Runtime; fn try_from( rt: Runtime ) -> Result<Self, Runtime> { match rt.handle().runtime_flavor() { RuntimeFlavor::CurrentThread => Ok( Self { spawner: Spawner::Runtime( Rc::new(rt) ) , local: Rc::new( LocalSet::new() ) , }), _ => Err( rt ), } } } /// Create a [`TokioCt`] from a [`Handle`]. /// /// # Errors /// Will fail if you pass a handle to a multithreaded runtime. Will return your [`Handle`]. // impl TryFrom<Handle> for TokioCt { type Error = Handle; fn try_from( handle: Handle ) -> Result<Self, Handle> { match handle.runtime_flavor() { RuntimeFlavor::CurrentThread => Ok( Self { spawner: Spawner::Handle( handle ) , local: Rc::new( LocalSet::new() ) , }), _ => Err( handle ), } } } impl TokioCt { /// Create a new `TokioCt`. Uses a default current thread [`Runtime`] setting timers and io depending /// on the features enabled on _async_executors_. // pub fn new() -> Result<Self, TokioCtErr> { let mut builder = Builder::new_current_thread(); #[ cfg( feature = "tokio_io" ) ] // builder.enable_io(); #[ cfg( feature = "tokio_timer" ) ] // builder.enable_time(); let rt = builder.build().map_err( |e| TokioCtErr::Builder(e.kind()) )?; Ok(Self { spawner: Spawner::Runtime(Rc::new( rt )), local : Rc::new( LocalSet::new() ) , }) } /// Try to construct a [`TokioCt`] from the currently entered [`Runtime`]. You can do this /// if you want to construct your runtime with the tokio macros eg: /// /// ``` /// #[ tokio::main(flavor = "current_thread") ] /// async fn main() /// { /// // ... /// } /// ``` /// /// # Warning /// /// `TokioCt::new()` is preferred over this. It's brief, doesn't require macros and is /// the intended behavior for this type. The whole library aims at a paradigm without /// global executors. /// /// The main footgun here is that you are now already in async context, so you must call /// [`TokioCt::run_until`] instead of [`TokioCt::block_on`]. `block_on` will panic when run from /// within an existing async context. This can be surprising for your upstream libraries to /// which you pass a [`TokioCt`] executor. /// /// # Errors /// /// Will fail if trying to construct from a multithreaded runtime or if no runtime /// is running. /// /// pub fn try_current() -> Result< Self, TokioCtErr > { let handle = Handle::try_current() .map_err(|_| TokioCtErr::NoRuntime )?; Self::try_from( handle ) .map_err(|_| TokioCtErr::WrongFlavour ) } /// This is the entry point for this executor. Once this call returns, no remaining tasks shall be polled anymore. /// However the tasks stay in the executor, so if you make a second call to `block_on` with a new task, the older /// tasks will start making progress again. /// /// For simplicity, it's advised to just create top level task that you run through `block_on` and make sure your /// program is done when it returns. /// /// See: [`tokio::runtime::Runtime::block_on`] /// /// ## Panics /// /// This function will panic if it is called from an async context, including but not limited to making a nested /// call. It will also panic if the provided future panics. /// /// When you created this executor with [`TokioCt::try_current`], you should call `run_until` instead. // pub fn block_on<F: Future>( &self, f: F ) -> F::Output { match &self.spawner { Spawner::Runtime( rt ) => rt .block_on( self.local.run_until( f ) ) , Spawner::Handle ( handle ) => handle.block_on( self.local.run_until( f ) ) , } } /// Run the given future to completion. This is the entrypoint for execution of all the code spawned on this /// executor when you are already in an async context. /// Eg. when you have created this executor from an already running runtime with [`TokioCt::try_current`]. /// This will run the [`tokio::task::LocalSet`] which makes spawning possible. /// /// Similarly to [`TokioCt::block_on`], spawned tasks will no longer be polled once the given future /// has ended, but will stay in the executor and you can call this function again to have every task /// continue to make progress. // pub async fn run_until<F: Future>( &self, f: F ) -> F::Output { self.local.run_until( f ).await } } impl Spawn for TokioCt { fn
( &self, future: FutureObj<'static, ()> ) -> Result<(), SpawnError> { // We drop the tokio JoinHandle, so the task becomes detached. // drop( self.local.spawn_local(future) ); Ok(()) } } impl LocalSpawn for TokioCt { fn spawn_local_obj( &self, future: LocalFutureObj<'static, ()> ) -> Result<(), SpawnError> { // We drop the tokio JoinHandle, so the task becomes detached. // drop( self.local.spawn_local(future) ); Ok(()) } } impl<Out: 'static + Send> SpawnHandle<Out> for TokioCt { fn spawn_handle_obj( &self, future: FutureObj<'static, Out> ) -> Result<JoinHandle<Out>, SpawnError> { let handle = match &self.spawner { Spawner::Runtime( rt ) => rt .spawn( future ) , Spawner::Handle ( handle ) => handle.spawn( future ) , }; Ok( JoinHandle::tokio(handle) ) } } impl<Out: 'static> LocalSpawnHandle<Out> for TokioCt { fn spawn_handle_local_obj( &self, future: LocalFutureObj<'static, Out> ) -> Result<JoinHandle<Out>, SpawnError> { let
spawn_obj
identifier_name
tokio_ct.rs
( not_send ).expect( "spawn" ); /// /// join_handle.await; /// }); ///``` /// /// ## Unwind Safety. /// /// When a future spawned on this wrapper panics, the panic will be caught by tokio in the poll function. /// /// You must only spawn futures to this API that are unwind safe. Tokio will wrap spawned tasks in /// [`std::panic::AssertUnwindSafe`] and wrap the poll invocation with [`std::panic::catch_unwind`]. /// /// They reason that this is fine because they require `Send + 'static` on the task. As far /// as I can tell this is wrong. Unwind safety can be circumvented in several ways even with /// `Send + 'static` (eg. `parking_lot::Mutex` is `Send + 'static` but `!UnwindSafe`). /// /// You should make sure that if your future panics, no code that lives on after the panic, /// nor any destructors called during the unwind can observe data in an inconsistent state. /// /// Note: the future running from within `block_on` as opposed to `spawn` does not exhibit this behavior and will panic /// the current thread. /// /// Note that these are logic errors, not related to the class of problems that cannot happen /// in safe rust (memory safety, undefined behavior, unsoundness, data races, ...). See the relevant /// [catch_unwind RFC](https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md) /// and it's discussion threads for more info as well as the documentation of [`std::panic::UnwindSafe`] /// for more information. /// // #[ derive( Debug, Clone ) ] // #[ cfg_attr( nightly, doc(cfg( feature = "tokio_ct" )) ) ] // pub struct TokioCt { spawner: Spawner, local: Rc< LocalSet > , } /// Create a `TokioCt` from a `Runtime`. /// /// # Errors /// /// Will fail if you pass a multithreaded runtime. In that case it will return your [`Runtime`]. // impl TryFrom<Runtime> for TokioCt { type Error = Runtime; fn try_from( rt: Runtime ) -> Result<Self, Runtime> { match rt.handle().runtime_flavor() { RuntimeFlavor::CurrentThread => Ok( Self { spawner: Spawner::Runtime( Rc::new(rt) ) , local: Rc::new( LocalSet::new() ) , }), _ => Err( rt ), } } } /// Create a [`TokioCt`] from a [`Handle`]. /// /// # Errors /// Will fail if you pass a handle to a multithreaded runtime. Will return your [`Handle`]. // impl TryFrom<Handle> for TokioCt { type Error = Handle; fn try_from( handle: Handle ) -> Result<Self, Handle> { match handle.runtime_flavor() { RuntimeFlavor::CurrentThread => Ok( Self { spawner: Spawner::Handle( handle ) , local: Rc::new( LocalSet::new() ) , }), _ => Err( handle ), } } } impl TokioCt { /// Create a new `TokioCt`. Uses a default current thread [`Runtime`] setting timers and io depending /// on the features enabled on _async_executors_. // pub fn new() -> Result<Self, TokioCtErr> { let mut builder = Builder::new_current_thread(); #[ cfg( feature = "tokio_io" ) ] // builder.enable_io(); #[ cfg( feature = "tokio_timer" ) ] // builder.enable_time(); let rt = builder.build().map_err( |e| TokioCtErr::Builder(e.kind()) )?; Ok(Self { spawner: Spawner::Runtime(Rc::new( rt )), local : Rc::new( LocalSet::new() ) , }) } /// Try to construct a [`TokioCt`] from the currently entered [`Runtime`]. You can do this /// if you want to construct your runtime with the tokio macros eg: /// /// ``` /// #[ tokio::main(flavor = "current_thread") ] /// async fn main() /// { /// // ... /// } /// ``` /// /// # Warning /// /// `TokioCt::new()` is preferred over this. It's brief, doesn't require macros and is /// the intended behavior for this type. The whole library aims at a paradigm without /// global executors. /// /// The main footgun here is that you are now already in async context, so you must call /// [`TokioCt::run_until`] instead of [`TokioCt::block_on`]. `block_on` will panic when run from /// within an existing async context. This can be surprising for your upstream libraries to /// which you pass a [`TokioCt`] executor. /// /// # Errors /// /// Will fail if trying to construct from a multithreaded runtime or if no runtime /// is running. /// /// pub fn try_current() -> Result< Self, TokioCtErr > { let handle = Handle::try_current() .map_err(|_| TokioCtErr::NoRuntime )?; Self::try_from( handle ) .map_err(|_| TokioCtErr::WrongFlavour ) } /// This is the entry point for this executor. Once this call returns, no remaining tasks shall be polled anymore. /// However the tasks stay in the executor, so if you make a second call to `block_on` with a new task, the older /// tasks will start making progress again. /// /// For simplicity, it's advised to just create top level task that you run through `block_on` and make sure your /// program is done when it returns. /// /// See: [`tokio::runtime::Runtime::block_on`] /// /// ## Panics /// /// This function will panic if it is called from an async context, including but not limited to making a nested /// call. It will also panic if the provided future panics. /// /// When you created this executor with [`TokioCt::try_current`], you should call `run_until` instead. // pub fn block_on<F: Future>( &self, f: F ) -> F::Output { match &self.spawner { Spawner::Runtime( rt ) => rt .block_on( self.local.run_until( f ) ) , Spawner::Handle ( handle ) => handle.block_on( self.local.run_until( f ) ) , } } /// Run the given future to completion. This is the entrypoint for execution of all the code spawned on this /// executor when you are already in an async context. /// Eg. when you have created this executor from an already running runtime with [`TokioCt::try_current`]. /// This will run the [`tokio::task::LocalSet`] which makes spawning possible. /// /// Similarly to [`TokioCt::block_on`], spawned tasks will no longer be polled once the given future /// has ended, but will stay in the executor and you can call this function again to have every task /// continue to make progress. // pub async fn run_until<F: Future>( &self, f: F ) -> F::Output { self.local.run_until( f ).await } } impl Spawn for TokioCt { fn spawn_obj( &self, future: FutureObj<'static, ()> ) -> Result<(), SpawnError> { // We drop the tokio JoinHandle, so the task becomes detached. // drop( self.local.spawn_local(future) ); Ok(()) } } impl LocalSpawn for TokioCt { fn spawn_local_obj( &self, future: LocalFutureObj<'static, ()> ) -> Result<(), SpawnError> { // We drop the tokio JoinHandle, so the task becomes detached. // drop( self.local.spawn_local(future) ); Ok(()) } } impl<Out: 'static + Send> SpawnHandle<Out> for TokioCt { fn spawn_handle_obj( &self, future: FutureObj<'static, Out> ) -> Result<JoinHandle<Out>, SpawnError> { let handle = match &self.spawner { Spawner::Runtime( rt ) => rt .spawn( future ) , Spawner::Handle ( handle ) => handle.spawn( future ) , }; Ok( JoinHandle::tokio(handle) ) } } impl<Out: 'static> LocalSpawnHandle<Out> for TokioCt { fn spawn_handle_local_obj( &self, future: LocalFutureObj<'static, Out> ) -> Result<JoinHandle<Out>, SpawnError> {
let handle = self.local.spawn_local( future ); Ok( JoinHandle::tokio(handle) ) }
random_line_split
tokio_ct.rs
// We can spawn !Send futures here. /// // /// let join_handle = exec.spawn_handle_local( not_send ).expect( "spawn" ); /// /// join_handle.await; /// }); ///``` /// /// ## Unwind Safety. /// /// When a future spawned on this wrapper panics, the panic will be caught by tokio in the poll function. /// /// You must only spawn futures to this API that are unwind safe. Tokio will wrap spawned tasks in /// [`std::panic::AssertUnwindSafe`] and wrap the poll invocation with [`std::panic::catch_unwind`]. /// /// They reason that this is fine because they require `Send + 'static` on the task. As far /// as I can tell this is wrong. Unwind safety can be circumvented in several ways even with /// `Send + 'static` (eg. `parking_lot::Mutex` is `Send + 'static` but `!UnwindSafe`). /// /// You should make sure that if your future panics, no code that lives on after the panic, /// nor any destructors called during the unwind can observe data in an inconsistent state. /// /// Note: the future running from within `block_on` as opposed to `spawn` does not exhibit this behavior and will panic /// the current thread. /// /// Note that these are logic errors, not related to the class of problems that cannot happen /// in safe rust (memory safety, undefined behavior, unsoundness, data races, ...). See the relevant /// [catch_unwind RFC](https://github.com/rust-lang/rfcs/blob/master/text/1236-stabilize-catch-panic.md) /// and it's discussion threads for more info as well as the documentation of [`std::panic::UnwindSafe`] /// for more information. /// // #[ derive( Debug, Clone ) ] // #[ cfg_attr( nightly, doc(cfg( feature = "tokio_ct" )) ) ] // pub struct TokioCt { spawner: Spawner, local: Rc< LocalSet > , } /// Create a `TokioCt` from a `Runtime`. /// /// # Errors /// /// Will fail if you pass a multithreaded runtime. In that case it will return your [`Runtime`]. // impl TryFrom<Runtime> for TokioCt { type Error = Runtime; fn try_from( rt: Runtime ) -> Result<Self, Runtime> { match rt.handle().runtime_flavor() { RuntimeFlavor::CurrentThread => Ok( Self { spawner: Spawner::Runtime( Rc::new(rt) ) , local: Rc::new( LocalSet::new() ) , }), _ => Err( rt ), } } } /// Create a [`TokioCt`] from a [`Handle`]. /// /// # Errors /// Will fail if you pass a handle to a multithreaded runtime. Will return your [`Handle`]. // impl TryFrom<Handle> for TokioCt { type Error = Handle; fn try_from( handle: Handle ) -> Result<Self, Handle>
} impl TokioCt { /// Create a new `TokioCt`. Uses a default current thread [`Runtime`] setting timers and io depending /// on the features enabled on _async_executors_. // pub fn new() -> Result<Self, TokioCtErr> { let mut builder = Builder::new_current_thread(); #[ cfg( feature = "tokio_io" ) ] // builder.enable_io(); #[ cfg( feature = "tokio_timer" ) ] // builder.enable_time(); let rt = builder.build().map_err( |e| TokioCtErr::Builder(e.kind()) )?; Ok(Self { spawner: Spawner::Runtime(Rc::new( rt )), local : Rc::new( LocalSet::new() ) , }) } /// Try to construct a [`TokioCt`] from the currently entered [`Runtime`]. You can do this /// if you want to construct your runtime with the tokio macros eg: /// /// ``` /// #[ tokio::main(flavor = "current_thread") ] /// async fn main() /// { /// // ... /// } /// ``` /// /// # Warning /// /// `TokioCt::new()` is preferred over this. It's brief, doesn't require macros and is /// the intended behavior for this type. The whole library aims at a paradigm without /// global executors. /// /// The main footgun here is that you are now already in async context, so you must call /// [`TokioCt::run_until`] instead of [`TokioCt::block_on`]. `block_on` will panic when run from /// within an existing async context. This can be surprising for your upstream libraries to /// which you pass a [`TokioCt`] executor. /// /// # Errors /// /// Will fail if trying to construct from a multithreaded runtime or if no runtime /// is running. /// /// pub fn try_current() -> Result< Self, TokioCtErr > { let handle = Handle::try_current() .map_err(|_| TokioCtErr::NoRuntime )?; Self::try_from( handle ) .map_err(|_| TokioCtErr::WrongFlavour ) } /// This is the entry point for this executor. Once this call returns, no remaining tasks shall be polled anymore. /// However the tasks stay in the executor, so if you make a second call to `block_on` with a new task, the older /// tasks will start making progress again. /// /// For simplicity, it's advised to just create top level task that you run through `block_on` and make sure your /// program is done when it returns. /// /// See: [`tokio::runtime::Runtime::block_on`] /// /// ## Panics /// /// This function will panic if it is called from an async context, including but not limited to making a nested /// call. It will also panic if the provided future panics. /// /// When you created this executor with [`TokioCt::try_current`], you should call `run_until` instead. // pub fn block_on<F: Future>( &self, f: F ) -> F::Output { match &self.spawner { Spawner::Runtime( rt ) => rt .block_on( self.local.run_until( f ) ) , Spawner::Handle ( handle ) => handle.block_on( self.local.run_until( f ) ) , } } /// Run the given future to completion. This is the entrypoint for execution of all the code spawned on this /// executor when you are already in an async context. /// Eg. when you have created this executor from an already running runtime with [`TokioCt::try_current`]. /// This will run the [`tokio::task::LocalSet`] which makes spawning possible. /// /// Similarly to [`TokioCt::block_on`], spawned tasks will no longer be polled once the given future /// has ended, but will stay in the executor and you can call this function again to have every task /// continue to make progress. // pub async fn run_until<F: Future>( &self, f: F ) -> F::Output { self.local.run_until( f ).await } } impl Spawn for TokioCt { fn spawn_obj( &self, future: FutureObj<'static, ()> ) -> Result<(), SpawnError> { // We drop the tokio JoinHandle, so the task becomes detached. // drop( self.local.spawn_local(future) ); Ok(()) } } impl LocalSpawn for TokioCt { fn spawn_local_obj( &self, future: LocalFutureObj<'static, ()> ) -> Result<(), SpawnError> { // We drop the tokio JoinHandle, so the task becomes detached. // drop( self.local.spawn_local(future) ); Ok(()) } } impl<Out: 'static + Send> SpawnHandle<Out> for TokioCt { fn spawn_handle_obj( &self, future: FutureObj<'static, Out> ) -> Result<JoinHandle<Out>, SpawnError> { let handle = match &self.spawner { Spawner::Runtime( rt ) => rt .spawn( future ) , Spawner::Handle ( handle ) => handle.spawn( future ) , }; Ok( JoinHandle::tokio(handle) ) } } impl<Out: 'static> LocalSpawnHandle<Out> for TokioCt { fn spawn_handle_local_obj( &self, future: LocalFutureObj<'static, Out> ) -> Result<JoinHandle<Out>, SpawnError> { let
{ match handle.runtime_flavor() { RuntimeFlavor::CurrentThread => Ok( Self { spawner: Spawner::Handle( handle ) , local: Rc::new( LocalSet::new() ) , }), _ => Err( handle ), } }
identifier_body
lib.rs
Use [`MmapBuffer`](struct.MmapBuffer.html) unless: - [slice-deque](https://github.com/gnzlbg/slice_deque) is not available for your platform (e.g. no support for `mmap`), - you need very small buffers (smaller than 1 memory page), - you're about to create a lot of buffers in a short period of time ([`new()`](trait.Buffer.html#tymethod.new) is relatively expensive), - you're expecting buffer to grow a lot (consider, if possible, preallocating larger buffers through [`BufRefReaderBuilder.capacity`](struct.BufRefReaderBuilder.html#method.capacity)), - you have some very special concerns re: memory maps and malloc bypass (special allocators, possible kernel inefficiency due to large amount of mapped memory regions etc.). ## Examples Read data word by word: ``` use buf_ref_reader::*; fn read<B: Buffer>() -> Result<(), Error> where Error: From<B::Error>, // add this if you plan to `unwrap()` errors returned by `read()` et al. //B::Error: std::fmt::Debug, { // &[u8] implements Read, hence we use it as our data source for this example let data = b"lorem ipsum dolor sit amet"; let mut r = BufRefReaderBuilder::new(&data[..]) .capacity(4) .build::<B>()?; assert_eq!(r.read_until(b' ')?, Some(&b"lorem "[..])); assert_eq!(r.read_until(b' ')?, Some(&b"ipsum "[..])); assert_eq!(r.read_until(b' ')?, Some(&b"dolor "[..])); assert_eq!(r.read_until(b' ')?, Some(&b"sit "[..])); assert_eq!(r.read_until(b' ')?, Some(&b"amet"[..])); assert_eq!(r.read_until(b' ')?, None); // EOF assert_eq!(r.read_until(b' ')?, None); Ok(()) } fn main() { read::<VecBuffer>().unwrap(); read::<MmapBuffer>().unwrap(); } ``` */ #![warn(missing_docs)] use quick_error::quick_error; use std::io::{self, Read}; use memchr::memchr; mod buffer; pub use buffer::{ Buffer, VecBuffer, MmapBuffer, }; use slice_deque::AllocError; use std::convert::From; /** Buffering reader. See [module-level docs](index.html) for examples. */ pub struct BufRefReader<R, B> { src: R, buf: B, } /** Builder for [`BufRefReader`](struct.BufRefReader.html). See [module-level docs](index.html) for examples. */ pub struct BufRefReaderBuilder<R> { src: R, bufsize: usize, } impl<R: Read> BufRefReaderBuilder<R> { /// Creates new builder with given reader and default options. pub fn new(src: R) -> Self { BufRefReaderBuilder { src, bufsize: 8192, } } /// Set initial buffer capacity. pub fn capacity(mut self, bufsize: usize) -> Self { self.bufsize = bufsize; self } /// Create actual reader. pub fn build<B: Buffer>(self) -> Result<BufRefReader<R, B>, B::Error> { Ok(BufRefReader { src: self.src, buf: B::new(self.bufsize)?, }) } } quick_error! { /// Error type that reading functions might emit #[derive(Debug)] pub enum Error { /// Error reading from actual reader IO(err: io::Error) { from() } /// Indicates failure to create/grow buffer Buf(err: AllocError) { from() } } } impl From<()> for Error { // VecBuffer never emits errors, it only panics fn from(_: ()) -> Self
} impl<R: Read, B: Buffer> BufRefReader<R, B> where Error: From<B::Error> { /// Creates buffered reader with default options. Look for [`BufRefReaderBuilder`](struct.BufRefReaderBuilder.html) for tweaks. pub fn new(src: R) -> Result<BufRefReader<R, B>, B::Error> { BufRefReaderBuilder::new(src) .build() } // returns Some(where appended data starts within the filled part of the buffer), // or None for EOF #[inline] fn fill(&mut self) -> Result<Option<usize>, Error> { self.buf.enlarge()?; let old_len = self.buf.len(); match self.src.read(self.buf.appendable())? { 0 => Ok(None), // EOF n => { self.buf.grow(n); Ok(Some(old_len)) } } } /** Returns requested amount of bytes, or less if EOF prevents reader from fulfilling the request. Returns: - `Ok(Some(data))` with, well, data, - `Ok(None)` if no more data is available, - `Err(err)`: see `std::io::Read::read()` */ #[inline] pub fn read(&mut self, n: usize) -> Result<Option<&[u8]>, Error> { while n > self.buf.len() { // fill and expand buffer until either: // - buffer starts holding the requested amount of data // - EOF is reached if self.fill()?.is_none() { break }; } if self.buf.len() == 0 { // reading past EOF Ok(None) } else { let output = self.buf.consume(n); Ok(Some(output)) } } /** Returns bytes up until and including `delim`, or until EOF mark. If no content is available, returns `None`. Returns: - `Ok(Some(data))` with, well, data, - `Ok(None)` if no more data is available, - `Err(err)`: see `std::io::Read::read()` */ #[inline] pub fn read_until(&mut self, delim: u8) -> Result<Option<&[u8]>, Error> { let mut len = None; // position within filled part of the buffer, // from which to continue search for character let mut pos = 0; loop { // fill and expand buffer until either: // - `delim` appears in the buffer // - EOF is reached if let Some(n) = memchr(delim, &self.buf.filled()[pos..]) { len = Some(pos+n); break; } pos = match self.fill()? { None => break, // EOF Some(pos) => pos, }; } match len { None => { // EOF if self.buf.len() == 0 { Ok(None) } else { let output = self.buf.consume(self.buf.len()); Ok(Some(output)) } }, Some(len) => { let len = len + 1; // also include matching delimiter let output = self.buf.consume(len); Ok(Some(output)) }, } } } #[cfg(test)] static WORDS: &'static [u8] = include_bytes!("/usr/share/dict/words"); #[cfg(test)] mod tests { use super::*; use std::fmt::Debug; fn read_until_empty_lines<B: Buffer>() where B::Error: Debug, Error: From<B::Error>, { // two spaces, three spaces, two spaces let mut r = BufRefReaderBuilder::new(&b" lorem ipsum "[..]) .capacity(4) .build::<B>() .unwrap(); assert_eq!(r.read_until(b' ').unwrap(), Some(&b" "[..])); assert_eq!(r.read_until(b' ').unwrap(), Some(&b" "[..])); assert_eq!(r.read_until(b' ').unwrap(), Some(&b"lorem "[..])); assert_eq!(r.read_until(b' ').unwrap(), Some(&b" "[..])); assert_eq!(r.read_until(b' ').unwrap(), Some(&b" "[..])); assert_eq!(r.read_until(b' ').unwrap(), Some(&b"ipsum "[..])); assert_eq!(r.read_until(b' ').unwrap(), Some(&b" "[..])); assert_eq!(r.read_until(b' ').unwrap(), None); } #[test] fn read_until_empty_lines_vec() { read_until_empty_lines::<VecBuffer>() } #[test] fn read_until_empty_lines_mmap() { read_until_empty_lines::<MmapBuffer>() } fn read_until_words<B: Buffer>() where B::Error: Debug, Error: From<B::Error>, { let mut r = BufRefReaderBuilder::new(WORDS) .capacity(4) .build::<B>() .unwrap(); let mut words = WORDS.split(|&c| c == b'\n'); while let Ok(Some(slice_buf)) = r.read_until(b'\n') { let mut slice_words = words.next().unwrap() .to_vec(); slice_words.push(b'\n'); assert_eq!(slice_buf, &slice_words[..]); } // reader: returned
{ unimplemented!() }
identifier_body
lib.rs
Use [`MmapBuffer`](struct.MmapBuffer.html) unless: - [slice-deque](https://github.com/gnzlbg/slice_deque) is not available for your platform (e.g. no support for `mmap`), - you need very small buffers (smaller than 1 memory page), - you're about to create a lot of buffers in a short period of time ([`new()`](trait.Buffer.html#tymethod.new) is relatively expensive), - you're expecting buffer to grow a lot (consider, if possible, preallocating larger buffers through [`BufRefReaderBuilder.capacity`](struct.BufRefReaderBuilder.html#method.capacity)), - you have some very special concerns re: memory maps and malloc bypass (special allocators, possible kernel inefficiency due to large amount of mapped memory regions etc.). ## Examples Read data word by word: ``` use buf_ref_reader::*; fn read<B: Buffer>() -> Result<(), Error> where Error: From<B::Error>, // add this if you plan to `unwrap()` errors returned by `read()` et al. //B::Error: std::fmt::Debug, { // &[u8] implements Read, hence we use it as our data source for this example let data = b"lorem ipsum dolor sit amet"; let mut r = BufRefReaderBuilder::new(&data[..]) .capacity(4) .build::<B>()?; assert_eq!(r.read_until(b' ')?, Some(&b"lorem "[..])); assert_eq!(r.read_until(b' ')?, Some(&b"ipsum "[..])); assert_eq!(r.read_until(b' ')?, Some(&b"dolor "[..])); assert_eq!(r.read_until(b' ')?, Some(&b"sit "[..])); assert_eq!(r.read_until(b' ')?, Some(&b"amet"[..])); assert_eq!(r.read_until(b' ')?, None); // EOF assert_eq!(r.read_until(b' ')?, None); Ok(()) } fn main() { read::<VecBuffer>().unwrap(); read::<MmapBuffer>().unwrap(); } ``` */ #![warn(missing_docs)] use quick_error::quick_error; use std::io::{self, Read}; use memchr::memchr; mod buffer; pub use buffer::{ Buffer, VecBuffer, MmapBuffer, }; use slice_deque::AllocError; use std::convert::From; /** Buffering reader. See [module-level docs](index.html) for examples. */ pub struct BufRefReader<R, B> { src: R, buf: B, } /** Builder for [`BufRefReader`](struct.BufRefReader.html). See [module-level docs](index.html) for examples. */ pub struct BufRefReaderBuilder<R> { src: R, bufsize: usize, } impl<R: Read> BufRefReaderBuilder<R> { /// Creates new builder with given reader and default options. pub fn new(src: R) -> Self { BufRefReaderBuilder { src, bufsize: 8192, } } /// Set initial buffer capacity. pub fn capacity(mut self, bufsize: usize) -> Self { self.bufsize = bufsize; self } /// Create actual reader. pub fn build<B: Buffer>(self) -> Result<BufRefReader<R, B>, B::Error> { Ok(BufRefReader { src: self.src, buf: B::new(self.bufsize)?, }) } } quick_error! { /// Error type that reading functions might emit #[derive(Debug)] pub enum Error { /// Error reading from actual reader IO(err: io::Error) { from() } /// Indicates failure to create/grow buffer Buf(err: AllocError) { from() } } } impl From<()> for Error { // VecBuffer never emits errors, it only panics fn from(_: ()) -> Self { unimplemented!() } } impl<R: Read, B: Buffer> BufRefReader<R, B> where Error: From<B::Error> { /// Creates buffered reader with default options. Look for [`BufRefReaderBuilder`](struct.BufRefReaderBuilder.html) for tweaks. pub fn new(src: R) -> Result<BufRefReader<R, B>, B::Error> { BufRefReaderBuilder::new(src) .build() } // returns Some(where appended data starts within the filled part of the buffer), // or None for EOF #[inline] fn fill(&mut self) -> Result<Option<usize>, Error> { self.buf.enlarge()?; let old_len = self.buf.len(); match self.src.read(self.buf.appendable())? { 0 => Ok(None), // EOF n => { self.buf.grow(n); Ok(Some(old_len)) } } } /** Returns requested amount of bytes, or less if EOF prevents reader from fulfilling the request. Returns: - `Ok(Some(data))` with, well, data, - `Ok(None)` if no more data is available, - `Err(err)`: see `std::io::Read::read()` */ #[inline] pub fn read(&mut self, n: usize) -> Result<Option<&[u8]>, Error> { while n > self.buf.len() { // fill and expand buffer until either: // - buffer starts holding the requested amount of data // - EOF is reached if self.fill()?.is_none() { break }; } if self.buf.len() == 0 { // reading past EOF Ok(None) } else { let output = self.buf.consume(n); Ok(Some(output)) } } /** Returns bytes up until and including `delim`, or until EOF mark. If no content is available, returns `None`. Returns: - `Ok(Some(data))` with, well, data, - `Ok(None)` if no more data is available, - `Err(err)`: see `std::io::Read::read()` */ #[inline] pub fn read_until(&mut self, delim: u8) -> Result<Option<&[u8]>, Error> { let mut len = None; // position within filled part of the buffer, // from which to continue search for character let mut pos = 0; loop { // fill and expand buffer until either: // - `delim` appears in the buffer // - EOF is reached if let Some(n) = memchr(delim, &self.buf.filled()[pos..]) { len = Some(pos+n); break; } pos = match self.fill()? { None => break, // EOF Some(pos) => pos, }; } match len { None => { // EOF if self.buf.len() == 0 { Ok(None) } else { let output = self.buf.consume(self.buf.len()); Ok(Some(output)) } }, Some(len) => { let len = len + 1; // also include matching delimiter let output = self.buf.consume(len); Ok(Some(output)) }, } } } #[cfg(test)] static WORDS: &'static [u8] = include_bytes!("/usr/share/dict/words"); #[cfg(test)] mod tests { use super::*;
Error: From<B::Error>, { // two spaces, three spaces, two spaces let mut r = BufRefReaderBuilder::new(&b" lorem ipsum "[..]) .capacity(4) .build::<B>() .unwrap(); assert_eq!(r.read_until(b' ').unwrap(), Some(&b" "[..])); assert_eq!(r.read_until(b' ').unwrap(), Some(&b" "[..])); assert_eq!(r.read_until(b' ').unwrap(), Some(&b"lorem "[..])); assert_eq!(r.read_until(b' ').unwrap(), Some(&b" "[..])); assert_eq!(r.read_until(b' ').unwrap(), Some(&b" "[..])); assert_eq!(r.read_until(b' ').unwrap(), Some(&b"ipsum "[..])); assert_eq!(r.read_until(b' ').unwrap(), Some(&b" "[..])); assert_eq!(r.read_until(b' ').unwrap(), None); } #[test] fn read_until_empty_lines_vec() { read_until_empty_lines::<VecBuffer>() } #[test] fn read_until_empty_lines_mmap() { read_until_empty_lines::<MmapBuffer>() } fn read_until_words<B: Buffer>() where B::Error: Debug, Error: From<B::Error>, { let mut r = BufRefReaderBuilder::new(WORDS) .capacity(4) .build::<B>() .unwrap(); let mut words = WORDS.split(|&c| c == b'\n'); while let Ok(Some(slice_buf)) = r.read_until(b'\n') { let mut slice_words = words.next().unwrap() .to_vec(); slice_words.push(b'\n'); assert_eq!(slice_buf, &slice_words[..]); } // reader: returned
use std::fmt::Debug; fn read_until_empty_lines<B: Buffer>() where B::Error: Debug,
random_line_split
lib.rs
VecBuffer, MmapBuffer, }; use slice_deque::AllocError; use std::convert::From; /** Buffering reader. See [module-level docs](index.html) for examples. */ pub struct BufRefReader<R, B> { src: R, buf: B, } /** Builder for [`BufRefReader`](struct.BufRefReader.html). See [module-level docs](index.html) for examples. */ pub struct BufRefReaderBuilder<R> { src: R, bufsize: usize, } impl<R: Read> BufRefReaderBuilder<R> { /// Creates new builder with given reader and default options. pub fn new(src: R) -> Self { BufRefReaderBuilder { src, bufsize: 8192, } } /// Set initial buffer capacity. pub fn capacity(mut self, bufsize: usize) -> Self { self.bufsize = bufsize; self } /// Create actual reader. pub fn build<B: Buffer>(self) -> Result<BufRefReader<R, B>, B::Error> { Ok(BufRefReader { src: self.src, buf: B::new(self.bufsize)?, }) } } quick_error! { /// Error type that reading functions might emit #[derive(Debug)] pub enum Error { /// Error reading from actual reader IO(err: io::Error) { from() } /// Indicates failure to create/grow buffer Buf(err: AllocError) { from() } } } impl From<()> for Error { // VecBuffer never emits errors, it only panics fn from(_: ()) -> Self { unimplemented!() } } impl<R: Read, B: Buffer> BufRefReader<R, B> where Error: From<B::Error> { /// Creates buffered reader with default options. Look for [`BufRefReaderBuilder`](struct.BufRefReaderBuilder.html) for tweaks. pub fn new(src: R) -> Result<BufRefReader<R, B>, B::Error> { BufRefReaderBuilder::new(src) .build() } // returns Some(where appended data starts within the filled part of the buffer), // or None for EOF #[inline] fn fill(&mut self) -> Result<Option<usize>, Error> { self.buf.enlarge()?; let old_len = self.buf.len(); match self.src.read(self.buf.appendable())? { 0 => Ok(None), // EOF n => { self.buf.grow(n); Ok(Some(old_len)) } } } /** Returns requested amount of bytes, or less if EOF prevents reader from fulfilling the request. Returns: - `Ok(Some(data))` with, well, data, - `Ok(None)` if no more data is available, - `Err(err)`: see `std::io::Read::read()` */ #[inline] pub fn read(&mut self, n: usize) -> Result<Option<&[u8]>, Error> { while n > self.buf.len() { // fill and expand buffer until either: // - buffer starts holding the requested amount of data // - EOF is reached if self.fill()?.is_none() { break }; } if self.buf.len() == 0 { // reading past EOF Ok(None) } else { let output = self.buf.consume(n); Ok(Some(output)) } } /** Returns bytes up until and including `delim`, or until EOF mark. If no content is available, returns `None`. Returns: - `Ok(Some(data))` with, well, data, - `Ok(None)` if no more data is available, - `Err(err)`: see `std::io::Read::read()` */ #[inline] pub fn read_until(&mut self, delim: u8) -> Result<Option<&[u8]>, Error> { let mut len = None; // position within filled part of the buffer, // from which to continue search for character let mut pos = 0; loop { // fill and expand buffer until either: // - `delim` appears in the buffer // - EOF is reached if let Some(n) = memchr(delim, &self.buf.filled()[pos..]) { len = Some(pos+n); break; } pos = match self.fill()? { None => break, // EOF Some(pos) => pos, }; } match len { None => { // EOF if self.buf.len() == 0 { Ok(None) } else { let output = self.buf.consume(self.buf.len()); Ok(Some(output)) } }, Some(len) => { let len = len + 1; // also include matching delimiter let output = self.buf.consume(len); Ok(Some(output)) }, } } } #[cfg(test)] static WORDS: &'static [u8] = include_bytes!("/usr/share/dict/words"); #[cfg(test)] mod tests { use super::*; use std::fmt::Debug; fn read_until_empty_lines<B: Buffer>() where B::Error: Debug, Error: From<B::Error>, { // two spaces, three spaces, two spaces let mut r = BufRefReaderBuilder::new(&b" lorem ipsum "[..]) .capacity(4) .build::<B>() .unwrap(); assert_eq!(r.read_until(b' ').unwrap(), Some(&b" "[..])); assert_eq!(r.read_until(b' ').unwrap(), Some(&b" "[..])); assert_eq!(r.read_until(b' ').unwrap(), Some(&b"lorem "[..])); assert_eq!(r.read_until(b' ').unwrap(), Some(&b" "[..])); assert_eq!(r.read_until(b' ').unwrap(), Some(&b" "[..])); assert_eq!(r.read_until(b' ').unwrap(), Some(&b"ipsum "[..])); assert_eq!(r.read_until(b' ').unwrap(), Some(&b" "[..])); assert_eq!(r.read_until(b' ').unwrap(), None); } #[test] fn read_until_empty_lines_vec() { read_until_empty_lines::<VecBuffer>() } #[test] fn read_until_empty_lines_mmap() { read_until_empty_lines::<MmapBuffer>() } fn read_until_words<B: Buffer>() where B::Error: Debug, Error: From<B::Error>, { let mut r = BufRefReaderBuilder::new(WORDS) .capacity(4) .build::<B>() .unwrap(); let mut words = WORDS.split(|&c| c == b'\n'); while let Ok(Some(slice_buf)) = r.read_until(b'\n') { let mut slice_words = words.next().unwrap() .to_vec(); slice_words.push(b'\n'); assert_eq!(slice_buf, &slice_words[..]); } // reader: returned immediately after hitting EOF past last b'\n' // words: this is .split(), hence empty string past last b'\n' assert_eq!(words.next(), Some(&b""[..])); assert_eq!(words.next(), None); } #[test] fn read_until_words_vec() { read_until_words::<VecBuffer>() } #[test] fn read_until_words_mmap() { read_until_words::<MmapBuffer>() } // like read_until_words, but splits by rarest character, which is b'Q' // also uses slightly bigger initial buffers fn read_until_words_long<B: Buffer>() where B::Error: Debug, Error: From<B::Error>, { let mut r = BufRefReaderBuilder::new(WORDS) .capacity(32) .build::<B>() .unwrap(); let mut words = WORDS.split(|&c| c == b'Q').peekable(); while let Ok(Some(slice_buf)) = r.read_until(b'Q') { let mut slice_words = words.next().unwrap() .to_vec(); if words.peek() != None { slice_words.push(b'Q'); } assert_eq!(slice_buf, &slice_words[..]); } assert_eq!(words.next(), None); } #[test] fn read_until_words_long_vec() { read_until_words_long::<VecBuffer>() } #[test] fn read_until_words_long_mmap() { read_until_words_long::<MmapBuffer>() } fn read<B: Buffer>() where B::Error: Debug, Error: From<B::Error>, { let mut r = BufRefReaderBuilder::new(&b"lorem ipsum dolor sit amet"[..]) .capacity(4) .build::<B>() .unwrap(); assert_eq!(r.read(5).unwrap(), Some(&b"lorem"[..])); assert_eq!(r.read(6).unwrap(), Some(&b" ipsum"[..])); assert_eq!(r.read(1024).unwrap(), Some(&b" dolor sit amet"[..])); assert_eq!(r.read(1).unwrap(), None); } #[test] fn read_vec() { read::<VecBuffer>() } #[test] fn
read_mmap
identifier_name
lrp_processor.go
Request)) desired, err := builder.BuildReplicationController(&desireAppRequest) if err != nil { logger.Error("failed-building-create-desired-lrp-request", err, lager.Data{"process-guid": desireAppRequest.ProcessGuid}) errc <- err return } logger.Debug("succeeded-building-create-desired-lrp-request", desireAppRequestDebugData(&desireAppRequest)) logger.Debug("creating-desired-lrp", createDesiredReqDebugData(desired)) // obtain the namespace from the desired metadata namespace := desired.ObjectMeta.Namespace _, err = l.k8sClient.ReplicationControllers(namespace).Create(desired) if err != nil { logger.Error("failed-creating-desired-lrp", err, lager.Data{"process-guid": desireAppRequest.ProcessGuid}) if models.ConvertError(err).Type == models.Error_InvalidRequest { atomic.AddInt32(invalidCount, int32(1)) } else { errc <- err } return } logger.Debug("succeeded-creating-desired-lrp", createDesiredReqDebugData(desired)) } } throttler, err := workpool.NewThrottler(l.updateLRPWorkPoolSize, works) if err != nil { errc <- err return } logger.Info("processing-batch", lager.Data{"size": len(desireAppRequests)}) throttler.Work() logger.Info("done-processing-batch", lager.Data{"size": len(desireAppRequests)}) } }() return errc } func (l *LRPProcessor) updateStaleDesiredLRPs( logger lager.Logger, cancel <-chan struct{}, stale <-chan []cc_messages.DesireAppRequestFromCC, existingSchedulingInfoMap map[string]*KubeSchedulingInfo, invalidCount *int32, ) <-chan error { logger = logger.Session("update-stale-desired-lrps") errc := make(chan error, 1) go func() { defer close(errc) for { var staleAppRequests []cc_messages.DesireAppRequestFromCC select { case <-cancel: return case selected, open := <-stale: if !open { return } staleAppRequests = selected } works := make([]func(), len(staleAppRequests)) for i, desireAppRequest := range staleAppRequests { desireAppRequest := desireAppRequest builder := l.furnaceBuilders["buildpack"] if desireAppRequest.DockerImageUrl != "" { builder = l.furnaceBuilders["docker"] } if builder == nil { err := errors.New("oh no builder nil") logger.Error("builder cannot be nil", err, lager.Data{"builder": builder}) errc <- err return } works[i] = func() { processGuid, err := helpers.NewProcessGuid(desireAppRequest.ProcessGuid) if err != nil { logger.Error("failed to create new process guid", err) errc <- err return } //existingSchedulingInfo := existingSchedulingInfoMap[processGuid.ShortenedGuid()] //instances := int32(desireAppRequest.NumInstances) logger.Debug("printing desired app req", lager.Data{"data": desireAppRequest}) replicationController, err := builder.BuildReplicationController(&desireAppRequest) if err != nil { logger.Error("failed-to-transform-stale-app-to-rc", err) errc <- err return } // exposedPorts, err := builder.ExtractExposedPorts(&desireAppRequest) // if err != nil { // logger.Error("failed-updating-stale-lrp", err, lager.Data{ // "process-guid": processGuid, // "execution-metadata": desireAppRequest.ExecutionMetadata, // }) // errc <- err // return // } // // routes, err := helpers.CCRouteInfoToRoutes(desireAppRequest.RoutingInfo, exposedPorts) // if err != nil { // logger.Error("failed-to-marshal-routes", err) // errc <- err // return // } // // updateReq.Routes = &routes // // for k, v := range existingSchedulingInfo.Routes { // if k != cfroutes.CF_ROUTER && k != tcp_routes.TCP_ROUTER { // (*updateReq.Routes)[k] = v // } // } logger.Debug("updating-stale-lrp", updateDesiredRequestDebugData(processGuid.String(), replicationController)) _, err1 := l.k8sClient.ReplicationControllers(replicationController.ObjectMeta.Namespace).Update(replicationController) if err1 != nil { logger.Error("failed-updating-stale-lrp", err1, lager.Data{ "process-guid": processGuid, }) errc <- err1 return } logger.Debug("succeeded-updating-stale-lrp", updateDesiredRequestDebugData(processGuid.String(), replicationController)) } } throttler, err := workpool.NewThrottler(l.updateLRPWorkPoolSize, works) if err != nil { errc <- err return } logger.Info("processing-batch", lager.Data{"size": len(staleAppRequests)}) throttler.Work() logger.Info("done-processing-batch", lager.Data{"size": len(staleAppRequests)}) } }() return errc } func (l *LRPProcessor) getSchedulingInfoMap(logger lager.Logger) (map[string]*KubeSchedulingInfo, error) { logger.Info("getting-desired-lrps-from-kube") pguidSelector, err := labels.Parse(PROCESS_GUID_LABEL) if err != nil { logger.Error("failed-getting-desired-lrps-from-kube", err) return nil, err } opts := api.ListOptions{ LabelSelector: pguidSelector, } logger.Debug("opts to list replication controller", lager.Data{"data": opts.LabelSelector.String()}) rcList, err := l.k8sClient.ReplicationControllers(api.NamespaceAll).List(opts) if err != nil { logger.Error("failed-getting-desired-lrps-from-kube", err) return nil, err } logger.Debug("list replication controller", lager.Data{"data": rcList.Items}) existing := make(map[string]*KubeSchedulingInfo) if len(rcList.Items) == 0 { logger.Info("empty kube scheduling info found") return existing, nil } for _, rc := range rcList.Items { shortenedProcessGuid := rc.ObjectMeta.Name // shortened guid, todo: need to convert to original guids existing[shortenedProcessGuid] = &KubeSchedulingInfo{ ProcessGuid: shortenedProcessGuid, Annotation: rc.ObjectMeta.Annotations, Instances: rc.Spec.Replicas, ETag: rc.ObjectMeta.Annotations["cloudfoundry.org/etag"], } } logger.Info("succeeded-getting-desired-lrps-from-kube", lager.Data{"count": len(existing)}) return existing, nil } func (l *LRPProcessor) deleteExcess(logger lager.Logger, cancel <-chan struct{}, excess []string) { logger = logger.Session("delete-excess") logger.Info("processing-batch", lager.Data{"num-to-delete": len(excess), "guids-to-delete": excess}) deletedGuids := make([]string, 0, len(excess)) for _, deleteGuid := range excess { _, err := deleteReplicationController(logger, l.k8sClient, deleteGuid) if err != nil { logger.Error("failed-processing-batch", err, lager.Data{"delete-request": deleteGuid}) } else { deletedGuids = append(deletedGuids, deleteGuid) } } logger.Info("succeeded-processing-batch", lager.Data{"num-deleted": len(deletedGuids), "deleted-guids": deletedGuids}) } func countErrors(source <-chan error) (<-chan error, <-chan int) { count := make(chan int, 1) dest := make(chan error, 1) var errorCount int wg := sync.WaitGroup{} wg.Add(1) go func() { for e := range source { errorCount++ dest <- e } close(dest) wg.Done() }() go func() { wg.Wait() count <- errorCount close(count) }() return dest, count } func mergeErrors(channels ...<-chan error) <-chan error
{ out := make(chan error) wg := sync.WaitGroup{} for _, ch := range channels { wg.Add(1) go func(c <-chan error) { for e := range c { out <- e } wg.Done() }(ch) } go func() { wg.Wait() close(out) }()
identifier_body
lrp_processor.go
(desireAppRequests)) for i, desireAppRequest := range desireAppRequests { desireAppRequest := desireAppRequest builder := l.furnaceBuilders["buildpack"] if desireAppRequest.DockerImageUrl != "" { builder = l.furnaceBuilders["docker"] } works[i] = func() { logger.Debug("building-create-desired-lrp-request", desireAppRequestDebugData(&desireAppRequest)) desired, err := builder.BuildReplicationController(&desireAppRequest) if err != nil { logger.Error("failed-building-create-desired-lrp-request", err, lager.Data{"process-guid": desireAppRequest.ProcessGuid}) errc <- err return } logger.Debug("succeeded-building-create-desired-lrp-request", desireAppRequestDebugData(&desireAppRequest)) logger.Debug("creating-desired-lrp", createDesiredReqDebugData(desired)) // obtain the namespace from the desired metadata namespace := desired.ObjectMeta.Namespace _, err = l.k8sClient.ReplicationControllers(namespace).Create(desired) if err != nil { logger.Error("failed-creating-desired-lrp", err, lager.Data{"process-guid": desireAppRequest.ProcessGuid}) if models.ConvertError(err).Type == models.Error_InvalidRequest { atomic.AddInt32(invalidCount, int32(1)) } else { errc <- err } return } logger.Debug("succeeded-creating-desired-lrp", createDesiredReqDebugData(desired)) } } throttler, err := workpool.NewThrottler(l.updateLRPWorkPoolSize, works) if err != nil { errc <- err return } logger.Info("processing-batch", lager.Data{"size": len(desireAppRequests)}) throttler.Work() logger.Info("done-processing-batch", lager.Data{"size": len(desireAppRequests)}) } }() return errc } func (l *LRPProcessor) updateStaleDesiredLRPs( logger lager.Logger, cancel <-chan struct{}, stale <-chan []cc_messages.DesireAppRequestFromCC, existingSchedulingInfoMap map[string]*KubeSchedulingInfo, invalidCount *int32, ) <-chan error { logger = logger.Session("update-stale-desired-lrps") errc := make(chan error, 1) go func() { defer close(errc) for { var staleAppRequests []cc_messages.DesireAppRequestFromCC select { case <-cancel: return case selected, open := <-stale: if !open { return } staleAppRequests = selected } works := make([]func(), len(staleAppRequests)) for i, desireAppRequest := range staleAppRequests { desireAppRequest := desireAppRequest builder := l.furnaceBuilders["buildpack"] if desireAppRequest.DockerImageUrl != "" { builder = l.furnaceBuilders["docker"] } if builder == nil { err := errors.New("oh no builder nil") logger.Error("builder cannot be nil", err, lager.Data{"builder": builder}) errc <- err return } works[i] = func() { processGuid, err := helpers.NewProcessGuid(desireAppRequest.ProcessGuid) if err != nil { logger.Error("failed to create new process guid", err) errc <- err return } //existingSchedulingInfo := existingSchedulingInfoMap[processGuid.ShortenedGuid()] //instances := int32(desireAppRequest.NumInstances) logger.Debug("printing desired app req", lager.Data{"data": desireAppRequest}) replicationController, err := builder.BuildReplicationController(&desireAppRequest) if err != nil { logger.Error("failed-to-transform-stale-app-to-rc", err) errc <- err return } // exposedPorts, err := builder.ExtractExposedPorts(&desireAppRequest) // if err != nil { // logger.Error("failed-updating-stale-lrp", err, lager.Data{ // "process-guid": processGuid, // "execution-metadata": desireAppRequest.ExecutionMetadata, // }) // errc <- err // return // } // // routes, err := helpers.CCRouteInfoToRoutes(desireAppRequest.RoutingInfo, exposedPorts) // if err != nil { // logger.Error("failed-to-marshal-routes", err) // errc <- err // return // } // // updateReq.Routes = &routes // // for k, v := range existingSchedulingInfo.Routes { // if k != cfroutes.CF_ROUTER && k != tcp_routes.TCP_ROUTER { // (*updateReq.Routes)[k] = v // } // } logger.Debug("updating-stale-lrp", updateDesiredRequestDebugData(processGuid.String(), replicationController)) _, err1 := l.k8sClient.ReplicationControllers(replicationController.ObjectMeta.Namespace).Update(replicationController) if err1 != nil { logger.Error("failed-updating-stale-lrp", err1, lager.Data{ "process-guid": processGuid, }) errc <- err1 return } logger.Debug("succeeded-updating-stale-lrp", updateDesiredRequestDebugData(processGuid.String(), replicationController)) } } throttler, err := workpool.NewThrottler(l.updateLRPWorkPoolSize, works) if err != nil { errc <- err return } logger.Info("processing-batch", lager.Data{"size": len(staleAppRequests)}) throttler.Work() logger.Info("done-processing-batch", lager.Data{"size": len(staleAppRequests)}) } }() return errc } func (l *LRPProcessor) getSchedulingInfoMap(logger lager.Logger) (map[string]*KubeSchedulingInfo, error) { logger.Info("getting-desired-lrps-from-kube") pguidSelector, err := labels.Parse(PROCESS_GUID_LABEL) if err != nil { logger.Error("failed-getting-desired-lrps-from-kube", err) return nil, err } opts := api.ListOptions{ LabelSelector: pguidSelector, } logger.Debug("opts to list replication controller", lager.Data{"data": opts.LabelSelector.String()}) rcList, err := l.k8sClient.ReplicationControllers(api.NamespaceAll).List(opts) if err != nil { logger.Error("failed-getting-desired-lrps-from-kube", err) return nil, err } logger.Debug("list replication controller", lager.Data{"data": rcList.Items}) existing := make(map[string]*KubeSchedulingInfo) if len(rcList.Items) == 0 { logger.Info("empty kube scheduling info found") return existing, nil } for _, rc := range rcList.Items { shortenedProcessGuid := rc.ObjectMeta.Name // shortened guid, todo: need to convert to original guids existing[shortenedProcessGuid] = &KubeSchedulingInfo{ ProcessGuid: shortenedProcessGuid, Annotation: rc.ObjectMeta.Annotations, Instances: rc.Spec.Replicas, ETag: rc.ObjectMeta.Annotations["cloudfoundry.org/etag"], } } logger.Info("succeeded-getting-desired-lrps-from-kube", lager.Data{"count": len(existing)}) return existing, nil } func (l *LRPProcessor) deleteExcess(logger lager.Logger, cancel <-chan struct{}, excess []string) { logger = logger.Session("delete-excess") logger.Info("processing-batch", lager.Data{"num-to-delete": len(excess), "guids-to-delete": excess}) deletedGuids := make([]string, 0, len(excess)) for _, deleteGuid := range excess { _, err := deleteReplicationController(logger, l.k8sClient, deleteGuid) if err != nil { logger.Error("failed-processing-batch", err, lager.Data{"delete-request": deleteGuid}) } else { deletedGuids = append(deletedGuids, deleteGuid) } } logger.Info("succeeded-processing-batch", lager.Data{"num-deleted": len(deletedGuids), "deleted-guids": deletedGuids}) } func countErrors(source <-chan error) (<-chan error, <-chan int) { count := make(chan int, 1) dest := make(chan error, 1) var errorCount int wg := sync.WaitGroup{} wg.Add(1) go func() { for e := range source { errorCount++ dest <- e } close(dest) wg.Done() }() go func() { wg.Wait()
count <- errorCount close(count) }()
random_line_split
lrp_processor.go
-cc"), cancelCh, l.httpClient, appDiffer.Stale(), ) updateErrorCh := l.updateStaleDesiredLRPs(logger, cancelCh, staleAppCh, existingSchedulingInfoMap, &invalidsFound) bumpFreshness := true success := true fingerprintErrorCh, fingerprintErrorCount := countErrors(fingerprintErrorCh) // closes errors when all error channels have been closed. // below, we rely on this behavior to break the process_loop. logger.Debug("merging all errors") errors := mergeErrors( fingerprintErrorCh, diffErrorCh, missingAppsErrorCh, staleAppErrorCh, createErrorCh, updateErrorCh, ) logger.Info("processing-updates-and-creates") process_loop: for { select { case err, open := <-errors: if err != nil { logger.Error("not-bumping-freshness-because-of", err) bumpFreshness = false } if !open { break process_loop } case sig := <-signals: logger.Info("exiting", lager.Data{"received-signal": sig}) close(cancelCh) return true } } logger.Info("done-processing-updates-and-creates") if <-fingerprintErrorCount != 0 { logger.Error("failed-to-fetch-all-cc-fingerprints", nil) success = false } if success { deleteList := <-appDiffer.Deleted() l.deleteExcess(logger, cancelCh, deleteList) } if bumpFreshness && success { logger.Info("bumping-freshness") } // err = l.bbsClient.UpsertDomain(logger, cc_messages.AppLRPDomain, l.domainTTL) // if err != nil { // logger.Error("failed-to-upsert-domain", err) // } // } return false } func (l *LRPProcessor) createMissingDesiredLRPs( logger lager.Logger, cancel <-chan struct{}, missing <-chan []cc_messages.DesireAppRequestFromCC, invalidCount *int32, ) <-chan error { logger = logger.Session("create-missing-desired-lrps") errc := make(chan error, 1) go func() { defer close(errc) for { var desireAppRequests []cc_messages.DesireAppRequestFromCC select { case <-cancel: return case selected, open := <-missing: if !open { return } desireAppRequests = selected } works := make([]func(), len(desireAppRequests)) for i, desireAppRequest := range desireAppRequests { desireAppRequest := desireAppRequest builder := l.furnaceBuilders["buildpack"] if desireAppRequest.DockerImageUrl != "" { builder = l.furnaceBuilders["docker"] } works[i] = func() { logger.Debug("building-create-desired-lrp-request", desireAppRequestDebugData(&desireAppRequest)) desired, err := builder.BuildReplicationController(&desireAppRequest) if err != nil { logger.Error("failed-building-create-desired-lrp-request", err, lager.Data{"process-guid": desireAppRequest.ProcessGuid}) errc <- err return } logger.Debug("succeeded-building-create-desired-lrp-request", desireAppRequestDebugData(&desireAppRequest)) logger.Debug("creating-desired-lrp", createDesiredReqDebugData(desired)) // obtain the namespace from the desired metadata namespace := desired.ObjectMeta.Namespace _, err = l.k8sClient.ReplicationControllers(namespace).Create(desired) if err != nil { logger.Error("failed-creating-desired-lrp", err, lager.Data{"process-guid": desireAppRequest.ProcessGuid}) if models.ConvertError(err).Type == models.Error_InvalidRequest { atomic.AddInt32(invalidCount, int32(1)) } else { errc <- err } return } logger.Debug("succeeded-creating-desired-lrp", createDesiredReqDebugData(desired)) } } throttler, err := workpool.NewThrottler(l.updateLRPWorkPoolSize, works) if err != nil { errc <- err return } logger.Info("processing-batch", lager.Data{"size": len(desireAppRequests)}) throttler.Work() logger.Info("done-processing-batch", lager.Data{"size": len(desireAppRequests)}) } }() return errc } func (l *LRPProcessor) updateStaleDesiredLRPs( logger lager.Logger, cancel <-chan struct{}, stale <-chan []cc_messages.DesireAppRequestFromCC, existingSchedulingInfoMap map[string]*KubeSchedulingInfo, invalidCount *int32, ) <-chan error { logger = logger.Session("update-stale-desired-lrps") errc := make(chan error, 1) go func() { defer close(errc) for { var staleAppRequests []cc_messages.DesireAppRequestFromCC select { case <-cancel: return case selected, open := <-stale: if !open { return } staleAppRequests = selected } works := make([]func(), len(staleAppRequests)) for i, desireAppRequest := range staleAppRequests { desireAppRequest := desireAppRequest builder := l.furnaceBuilders["buildpack"] if desireAppRequest.DockerImageUrl != "" { builder = l.furnaceBuilders["docker"] } if builder == nil { err := errors.New("oh no builder nil") logger.Error("builder cannot be nil", err, lager.Data{"builder": builder}) errc <- err return } works[i] = func() { processGuid, err := helpers.NewProcessGuid(desireAppRequest.ProcessGuid) if err != nil { logger.Error("failed to create new process guid", err) errc <- err return } //existingSchedulingInfo := existingSchedulingInfoMap[processGuid.ShortenedGuid()] //instances := int32(desireAppRequest.NumInstances) logger.Debug("printing desired app req", lager.Data{"data": desireAppRequest}) replicationController, err := builder.BuildReplicationController(&desireAppRequest) if err != nil { logger.Error("failed-to-transform-stale-app-to-rc", err) errc <- err return } // exposedPorts, err := builder.ExtractExposedPorts(&desireAppRequest) // if err != nil { // logger.Error("failed-updating-stale-lrp", err, lager.Data{ // "process-guid": processGuid, // "execution-metadata": desireAppRequest.ExecutionMetadata, // }) // errc <- err // return // } // // routes, err := helpers.CCRouteInfoToRoutes(desireAppRequest.RoutingInfo, exposedPorts) // if err != nil { // logger.Error("failed-to-marshal-routes", err) // errc <- err // return // } // // updateReq.Routes = &routes // // for k, v := range existingSchedulingInfo.Routes { // if k != cfroutes.CF_ROUTER && k != tcp_routes.TCP_ROUTER { // (*updateReq.Routes)[k] = v // } // } logger.Debug("updating-stale-lrp", updateDesiredRequestDebugData(processGuid.String(), replicationController)) _, err1 := l.k8sClient.ReplicationControllers(replicationController.ObjectMeta.Namespace).Update(replicationController) if err1 != nil { logger.Error("failed-updating-stale-lrp", err1, lager.Data{ "process-guid": processGuid, }) errc <- err1 return } logger.Debug("succeeded-updating-stale-lrp", updateDesiredRequestDebugData(processGuid.String(), replicationController)) } } throttler, err := workpool.NewThrottler(l.updateLRPWorkPoolSize, works) if err != nil { errc <- err return } logger.Info("processing-batch", lager.Data{"size": len(staleAppRequests)}) throttler.Work() logger.Info("done-processing-batch", lager.Data{"size": len(staleAppRequests)}) } }() return errc } func (l *LRPProcessor) getSchedulingInfoMap(logger lager.Logger) (map[string]*KubeSchedulingInfo, error) { logger.Info("getting-desired-lrps-from-kube") pguidSelector, err := labels.Parse(PROCESS_GUID_LABEL) if err != nil
{ logger.Error("failed-getting-desired-lrps-from-kube", err) return nil, err }
conditional_block
lrp_processor.go
err := syncDesiredLRPsDuration.Send(duration) if err != nil { logger.Error("failed-to-send-sync-desired-lrps-duration-metric", err) } err = invalidLRPsFound.Send(int(invalidsFound)) if err != nil { logger.Error("failed-to-send-sync-invalid-lrps-found-metric", err) } }() defer logger.Info("done") existingSchedulingInfoMap, err := l.getSchedulingInfoMap(logger) if err != nil { return false } //existingSchedulingInfoMap := organizeSchedulingInfosByProcessGuid(existing) appDiffer := NewAppDiffer(existingSchedulingInfoMap) cancelCh := make(chan struct{}) // from here on out, the fetcher, differ, and processor work across channels in a pipeline fingerprintCh, fingerprintErrorCh := l.fetcher.FetchFingerprints( logger, cancelCh, l.httpClient, ) diffErrorCh := appDiffer.Diff( logger, cancelCh, fingerprintCh, ) missingAppCh, missingAppsErrorCh := l.fetcher.FetchDesiredApps( logger.Session("fetch-missing-desired-lrps-from-cc"), cancelCh, l.httpClient, appDiffer.Missing(), ) createErrorCh := l.createMissingDesiredLRPs(logger, cancelCh, missingAppCh, &invalidsFound) staleAppCh, staleAppErrorCh := l.fetcher.FetchDesiredApps( logger.Session("fetch-stale-desired-lrps-from-cc"), cancelCh, l.httpClient, appDiffer.Stale(), ) updateErrorCh := l.updateStaleDesiredLRPs(logger, cancelCh, staleAppCh, existingSchedulingInfoMap, &invalidsFound) bumpFreshness := true success := true fingerprintErrorCh, fingerprintErrorCount := countErrors(fingerprintErrorCh) // closes errors when all error channels have been closed. // below, we rely on this behavior to break the process_loop. logger.Debug("merging all errors") errors := mergeErrors( fingerprintErrorCh, diffErrorCh, missingAppsErrorCh, staleAppErrorCh, createErrorCh, updateErrorCh, ) logger.Info("processing-updates-and-creates") process_loop: for { select { case err, open := <-errors: if err != nil { logger.Error("not-bumping-freshness-because-of", err) bumpFreshness = false } if !open { break process_loop } case sig := <-signals: logger.Info("exiting", lager.Data{"received-signal": sig}) close(cancelCh) return true } } logger.Info("done-processing-updates-and-creates") if <-fingerprintErrorCount != 0 { logger.Error("failed-to-fetch-all-cc-fingerprints", nil) success = false } if success { deleteList := <-appDiffer.Deleted() l.deleteExcess(logger, cancelCh, deleteList) } if bumpFreshness && success { logger.Info("bumping-freshness") } // err = l.bbsClient.UpsertDomain(logger, cc_messages.AppLRPDomain, l.domainTTL) // if err != nil { // logger.Error("failed-to-upsert-domain", err) // } // } return false } func (l *LRPProcessor)
( logger lager.Logger, cancel <-chan struct{}, missing <-chan []cc_messages.DesireAppRequestFromCC, invalidCount *int32, ) <-chan error { logger = logger.Session("create-missing-desired-lrps") errc := make(chan error, 1) go func() { defer close(errc) for { var desireAppRequests []cc_messages.DesireAppRequestFromCC select { case <-cancel: return case selected, open := <-missing: if !open { return } desireAppRequests = selected } works := make([]func(), len(desireAppRequests)) for i, desireAppRequest := range desireAppRequests { desireAppRequest := desireAppRequest builder := l.furnaceBuilders["buildpack"] if desireAppRequest.DockerImageUrl != "" { builder = l.furnaceBuilders["docker"] } works[i] = func() { logger.Debug("building-create-desired-lrp-request", desireAppRequestDebugData(&desireAppRequest)) desired, err := builder.BuildReplicationController(&desireAppRequest) if err != nil { logger.Error("failed-building-create-desired-lrp-request", err, lager.Data{"process-guid": desireAppRequest.ProcessGuid}) errc <- err return } logger.Debug("succeeded-building-create-desired-lrp-request", desireAppRequestDebugData(&desireAppRequest)) logger.Debug("creating-desired-lrp", createDesiredReqDebugData(desired)) // obtain the namespace from the desired metadata namespace := desired.ObjectMeta.Namespace _, err = l.k8sClient.ReplicationControllers(namespace).Create(desired) if err != nil { logger.Error("failed-creating-desired-lrp", err, lager.Data{"process-guid": desireAppRequest.ProcessGuid}) if models.ConvertError(err).Type == models.Error_InvalidRequest { atomic.AddInt32(invalidCount, int32(1)) } else { errc <- err } return } logger.Debug("succeeded-creating-desired-lrp", createDesiredReqDebugData(desired)) } } throttler, err := workpool.NewThrottler(l.updateLRPWorkPoolSize, works) if err != nil { errc <- err return } logger.Info("processing-batch", lager.Data{"size": len(desireAppRequests)}) throttler.Work() logger.Info("done-processing-batch", lager.Data{"size": len(desireAppRequests)}) } }() return errc } func (l *LRPProcessor) updateStaleDesiredLRPs( logger lager.Logger, cancel <-chan struct{}, stale <-chan []cc_messages.DesireAppRequestFromCC, existingSchedulingInfoMap map[string]*KubeSchedulingInfo, invalidCount *int32, ) <-chan error { logger = logger.Session("update-stale-desired-lrps") errc := make(chan error, 1) go func() { defer close(errc) for { var staleAppRequests []cc_messages.DesireAppRequestFromCC select { case <-cancel: return case selected, open := <-stale: if !open { return } staleAppRequests = selected } works := make([]func(), len(staleAppRequests)) for i, desireAppRequest := range staleAppRequests { desireAppRequest := desireAppRequest builder := l.furnaceBuilders["buildpack"] if desireAppRequest.DockerImageUrl != "" { builder = l.furnaceBuilders["docker"] } if builder == nil { err := errors.New("oh no builder nil") logger.Error("builder cannot be nil", err, lager.Data{"builder": builder}) errc <- err return } works[i] = func() { processGuid, err := helpers.NewProcessGuid(desireAppRequest.ProcessGuid) if err != nil { logger.Error("failed to create new process guid", err) errc <- err return } //existingSchedulingInfo := existingSchedulingInfoMap[processGuid.ShortenedGuid()] //instances := int32(desireAppRequest.NumInstances) logger.Debug("printing desired app req", lager.Data{"data": desireAppRequest}) replicationController, err := builder.BuildReplicationController(&desireAppRequest) if err != nil { logger.Error("failed-to-transform-stale-app-to-rc", err) errc <- err return } // exposedPorts, err := builder.ExtractExposedPorts(&desireAppRequest) // if err != nil { // logger.Error("failed-updating-stale-lrp", err, lager.Data{ // "process-guid": processGuid, // "execution-metadata": desireAppRequest.ExecutionMetadata, // }) // errc <- err // return // } // // routes, err := helpers.CCRouteInfoToRoutes(desireAppRequest.RoutingInfo, exposedPorts) // if err != nil { // logger.Error("failed-to-marshal-routes", err) // errc <- err // return // } // // updateReq.Routes = &routes // // for k, v := range existingSchedulingInfo.Routes { // if k != cfroutes.CF_ROUTER && k != tcp_routes.TCP_ROUTER { // (*updateReq
createMissingDesiredLRPs
identifier_name
Main.go
ализирован нулём, p больше не содержит nil s := make([]int, 20) // Выделение единого блока памяти под 20 int-ов s[3] = 7 // Присвоить значение одному из них r := -2 // определить ещё одну локальную переменную return &s[3], &r // Амперсанд(&) обозначает получение адреса переменной } func expensiveComputation() float64 { return m.Exp(10) } func learnFlowControl() { // if-ы всегда требуют наличия фигурных скобок, но не круглых if true { fmt.Println("told ya") } // форматирование кода стандартизировано утилитой "go fmt" if false { // не выполняется } else { // выполняется } // вместо нескольких if исползуется switch x := 42.0 switch x { case 0: case 1: case 42: // Case-ы в Go не "проваливаются" (неявный break) case 43: // не выполняется } // for, как и if не требует круглх скобок // переменные, объявленные в for и if являются локальными for x := 0; x < 3; x++ { // ++ - это операция fmt.Println("итерация", x) } // здесь x == 42 // for - единственный цикл в Go, но у него есть альтернативные формы for { // бесконечный цикл break // не такой уж бесконечный continue // не выполнится } // как и в for, := в if-е означает объявление и присвоение значения y, // проверка y > x происходит после if y := expensiveComputation(); y > x { x = y } // Функции являются замыканиями xBig := func() bool { return x > 10000 // Ссылается на x, объявленный выше switch } fmt.Println("xBig", xBig()) // true (т.к. мы присвоили x = e^10) x = 1.3e3 // тут x == 1300 fmt.Println("xBig", xBig()) // Теперь false // метки goto love love: learnDefer() learnInterfaces() } func learnDefer() (ok bool) { // отложенные (deferred) выражения выполняются сразу перед тем, как функция // возвратит значения defer fmt.Println("deferred statements execute in reverse (LIFO) order.") defer fmt.Println("\nThis line is being printed first because") // defer широко используется для закрытия файлов, чтобы закрывающая файл // функция находилась близко к открывающей return true } // Stringer объявление как интерфейса с одним методом, String type Stringer interface { String() string } // объявление pair как структуры с двумя полями x и y типа int type pair struct { x, y int } // объявление метода для типа pair; теперь pair реализует интерфейс Stringer func (p pair) String() string { // p в данном случае называют receiver-ом // Sprintf - ещё одна функция из пакета fmt // Обращение к полям p через точчку return fmt.Sprintf("(%d, %d)", p.x, p.y) } func learnInterfaces() { // синтаксис с фигурными скобками это "литерал структуры". Он возвращает // проинициализированную структуру, а оператор := присваивает её p p := pair{3, 4} fmt.Println(p.String()) // вызов метода String у переменной p типа pair var i Stringer // объявление i как типа с интерфейсом Stringer i = p // валидно, т.к. pair реализует Stringer // Вызов метода String у i типа Stringer fmt.Println(i.String()) // Функция в пакете fmt сами всегда вызывают метод String у объектов для // получения их строкового представления fmt.Println(p) // вывод такой-же, как и выше fmt.Println(i) // вывод такой-же, как и выше learnVariadicParams("Learn", "learn", "learn again") } // функции могут иметь варьируемое количество параметров func learnVariadicParams(myStrings ...interface{}) { // вывести все параметры с помощью итерации for _, param := range myStrings { fmt.Println("param:", param) } // передать все варьируемые параметры fmt.Println("params:", fmt.Sprintln(myStrings...)) learnErrorHandling() } func learnErrorHandling() { // идиома ", ok" служит для обозначения корректного срабатывания чего-либо m := map[int]string{3: "three", 4: "four"} if x, ok := m[1]; !ok { // ок будет false, потому что 1 нет в map-е fmt.Println("тут ничего нет") } else { fmt.Println(x) // x содержал бы значение, если бы 1 был в map-e } // идиома ", err" служит для обозначения того, была ли ошибка или нет if _, err := strconv.Atoi("non-int"); err != nil { // _ игнорирует значение // выведет "strconv.ParseInt: parsing "non-int": invalid syntax" fmt.Println(err) } learnConcurrency() } func inc(i int, c chan int) { c <- i + 1 // когда channel слева, <- является оператором "отправки" } // будем ипользовать функцию inc для конкурентной инкрементации чисел func learnConcurrency() { // тот же make, что и в случае со slice. Он предназначен для выделения // памяти и инициализации типов slice, map и channel c := make(chan int) // старт трех конкурентнов gorutine. Числа будут инкрементированы // конкурентно и, может быть параллельно, если машинка // правильно сконфигурирована и позволяет это делать. Все они будут отправлены в один // и тот же канал go inc(0, c) // Go начинает новую горутину go inc(10, c) go inc(-805, c) // Считывание всех трёх результатов из канала и вывод на экран // Нет никакой гарантии в каком порядке они будут выведены fmt.Println(<-c, <-c, <-c) // канал справа, <- обозначает "получение" cs := make(chan string) // другой канал содержит строки cc := make(chan chan string) // канал каналов со строками go func() { c <- 84 }() // пуск новой горутины для отправки значения go func() { cs <- "wordy" }() // ещё раз, теперь для cs // select тоже что и switch, но работает с каналами. Он случайно выбирает // готовый для взаимодействия канал select { case i := <-c: // получченное значение можно присвоить переменной fmt.Printf("это %T", i) case <-cs: // либо это значение можно игнорировать fmt.Println("это строка") case <-cc: // пустой канал, не готтов для коммуникации fmt.Println("это не выполняется") } // В этой точке значение будет получено из c или cs. Одна горутина будет // завершена, другая останется заблокированной learnWebProgramming() } func learnWebProgramming() { // у ListenAndServe первый параметр это TCP адрес, который нужно слушать // второй параметр это интерфейс типа http.Handler err := http.ListenAndServe(":8080", pair{}) fmt.Println(err) // не игнорируйте сообщения об ошибках } // Реализация интерфейса http.Handler для pair, только один метод ServerHTTP func (p pair) ServeHTTP(w http.ResponseWriter, r *http.Request) { // Обработка запроса и отправка данных методом из http.ResponseWriter w.Write([]byte("You learned Go in Y minutes!")) } func requestServer() { resp, err := http.Get("http://localhost:8080") fmt.Println(err) defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) fmt.Printf("\nWebserver said :`%s`", string(body)) }
identifier_name
Main.go
x + y, x * y // возврат двух значений } func learnTypes() { // тип string s := "Learn Go!" s2 := `"Чистый" строковый литерал может содержать переносы строк` // Символы не из ASCII g := 'Σ' // тип rune - алиас для типа int32, содержит символ юникода f := 3.141595 // float64, 64-х битное число с плавающей точкой c := 3 + 4i // complex128, внутри себя содержит два float64 // Синтаксис var с инициализ0ациями var u uint = 7 // беззнаковое, но размер зависит от реализации, как и у int var pi float32 = 22. / 7 // Синтаксис приведения типа с определением n := byte('\n') // byte - это алиас для uint8 // Массивы имеют фиксированный размер на момент компиляции var a4 [4]int // массив из 4-х int, инициализирован нулями a3 := [...]int{3, 1, 5} // массив из 3-х int, ручная инициализация // Слайсы (slices) имеют динамическую длину. И массивы, и слайсы имеют свои // преимущества, но слайсы используются гораздо чаще s3 := []int{4, 5, 9} // в отличие от a3, тут нет троеточия s4 := make([]int, 4) // выделение памяти для слайса из 4-х int (нули) var d2 [][]float64 // только объявление, память не выделяется bs := []byte("a slice") // синтаксис приведения типов p, q := learnMemory() // объявление p и q как указателей на int fmt.Println(*p, *q) // * извлекает указатель. Печатает два int-а // Map, также как и словарь или хэш из некоторых других языков, является // ассоциативным массивом с динамически изменяемым размером. m := map[string]int{"three": 3, "four": 4} m["one"] = 1 delete(m, "three") // встроенная функция, удаляет элемент из map-а // неиспользуемые переменные в Go считаются ошибкой // Нижнее подчеркивание позволяет игнорировать такие переменные _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs // Вывод считается использованием переменной fmt.Println(s, c, a4, s3, d2, m) learnFlowControl() // управление потоком } // у Go есть сборщик мусора. В нём есть указатели, но нет арифметики // указателей. Вы можете допустить ошибку с указателем на nil, но не с // инкрементацией указателя func learnMemory() (p, q *int) { // именованные возвращаемые значения p и q являются указателями на int p = new(int) // встроенная функция new выделяет память // выделенный int проинициализирован нулём, p больше не содержит nil s := make([]int, 20) // Выделение единого блока памяти под 20 int-ов s[3] = 7 // Присвоить значение одному из них r := -2 // определить ещё одну локальную переменную return &s[3], &r // Амперсанд(&) обозначает получение адреса переменной } func expensiveComputation() float64 { return m.Exp(10) } func learnFlowControl() { // if-ы всегда требуют наличия фигурных скобок, но не круглых if true { fmt.Println("told ya") } // форматирование кода стандартизировано утилитой "go fmt" if false { // не выполняется } else { // выполняется } // вместо нескольких if исползуется switch x := 42.0 switch x { case 0: case 1: case 42: // Case-ы в Go не "проваливаются" (неявный break) case 43: // не выполняется } // for, как и if не требует круглх скобок // переменные, объявленные в for и if являются локальными for x := 0; x < 3; x++ { // ++ - это операция fmt.Println("итерация", x) } // здесь x == 42 // for - единственный цикл в Go, но у него есть альтернативные формы for { // бесконечный цикл break // не такой уж бесконечный continue // не выполнится } // как и в for, := в if-е означает объявление и присвоение значения y, // проверка y > x происходит после if y := expensiveComputation(); y > x { x = y } // Функции являются замыканиями xBig := func() bool { return x > 10000 // Ссылается на x, объявленный выше switch } fmt.Println("xBig", xBig()) // true (т.к. мы присвоили x = e^10) x = 1.3e3 // тут x == 1300 fmt.Println("xBig", xBig()) // Теперь false // метки goto love love: learnDefer() learnInterfaces() } func learnDefer() (ok bool) { // отложенные (deferred) выражения выполняются сразу перед тем, как функция // возвратит значения defer fmt.Println("deferred statements execute in reverse (LIFO) order.") defer fmt.Println("\nThis line is being printed first because") // defer широко используется для закрытия файлов, чтобы закрывающая файл // функция находилась близко к открывающей return true } // Stringer объявление как интерфейса с одним методом, String type Stringer interface { String() string } // объявление pair как структуры с двумя полями x и y типа int type pair struct { x, y int } // объявление метода для типа pair; теперь pair реализует интерфейс Stringer func (p pair) String() string { // p в данном случае называют receiver-ом // Sprintf - ещё одна функция из пакета fmt // Обращение к
fmt.Sprintf("(%d, %d)", p.x, p.y) } func learnInterfaces() { // синтаксис с фигурными скобками это "литерал структуры". Он возвращает // проинициализированную структуру, а оператор := присваивает её p p := pair{3, 4} fmt.Println(p.String()) // вызов метода String у переменной p типа pair var i Stringer // объявление i как типа с интерфейсом Stringer i = p // валидно, т.к. pair реализует Stringer // Вызов метода String у i типа Stringer fmt.Println(i.String()) // Функция в пакете fmt сами всегда вызывают метод String у объектов для // получения их строкового представления fmt.Println(p) // вывод такой-же, как и выше fmt.Println(i) // вывод такой-же, как и выше learnVariadicParams("Learn", "learn", "learn again") } // функции могут иметь варьируемое количество параметров func learnVariadicParams(myStrings ...interface{}) { // вывести все параметры с помощью итерации for _, param := range myStrings { fmt.Println("param:", param) } // передать все варьируемые параметры fmt.Println("params:", fmt.Sprintln(myStrings...)) learnErrorHandling() } func learnErrorHandling() { // идиома ", ok" служит для обозначения корректного срабатывания чего-либо m := map[int]string{3: "three", 4: "four"} if x, ok := m[1];
полям p через точчку return
conditional_block
Main.go
return x + y, x * y // возврат двух значений } func learnTypes() { // тип string s := "Learn Go!" s2 := `"Чистый" строковый литерал может содержать переносы строк` // Символы не из ASCII g := 'Σ' // тип rune - алиас для типа int32, содержит символ юникода f := 3.141595 // float64, 64-х битное число с плавающей точкой c := 3 + 4i // complex128, внутри себя содержит два float64 // Синтаксис var с инициализ0ациями var u uint = 7 // беззнаковое, но размер зависит от реализации, как и у int var pi float32 = 22. / 7 // Синтаксис приведения типа с определением n := byte('\n') // byte - это алиас для uint8 // Массивы имеют фиксированный размер на момент компиляции var a4 [4]int // массив из 4-х int, инициализирован нулями a3 := [...]int{3, 1, 5} // массив из 3-х int, ручная инициализация // Слайсы (slices) имеют динамическую длину. И массивы, и слайсы имеют свои // преимущества, но слайсы используются гораздо чаще s3 := []int{4, 5, 9} // в отличие от a3, тут нет троеточия s4 := make([]int, 4) // выделение памяти для слайса из 4-х int (нули) var d2 [][]float64 // только объявление, память не выделяется bs := []byte("a slice") // синтаксис приведения типов p, q := learnMemory() // объявление p и q как указателей на int fmt.Println(*p, *q) // * извлекает указатель. Печатает два int-а // Map, также как и словарь или хэш из некоторых других языков, является // ассоциативным массивом с динамически изменяемым размером. m := map[string]int{"three": 3, "four": 4} m["one"] = 1 delete(m, "three") // встроенная функция, удаляет элемент из map-а // неиспользуемые переменные в Go считаются ошибкой // Нижнее подчеркивание позволяет игнорировать такие переменные _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs // Вывод считается использованием переменной fmt.Println(s, c, a4, s3, d2, m) learnFlowControl() // управление потоком } // у Go есть сборщик мусора. В нём есть указатели, но нет арифметики // указателей. Вы можете допустить ошибку с указателем на nil, но не с // инкрементацией указателя func learnMemory() (p, q *int) { // именованные возвращаемые значения p и q являются указателями на int p = new(int) // встроенная функция new выделяет память // выделенный int проинициализирован нулём, p больше не содержит nil s := make([]int, 20) // Выделение единого блока памяти под 20 int-ов s[3] = 7 // Присвоить значение одному из них r := -2 // определить ещё одну локальную переменную return &s[3], &r // Амперсанд(&) обозначает получение адреса переменной } func expensiveComputation() float64 { return m.Exp(10) } func learnFlowControl() { // if-ы всегда требуют наличия фигурных скобок, но не круглых if true { fmt.Println("told ya") } // форматирование кода стандартизировано утилитой "go fmt" if false { // не выполняется } else { // выполняется } // вместо нескольких if исползуется switch x := 42.0 switch x { case 0: case 1: case 42: // Case-ы в Go не "проваливаются" (неявный break) case 43: // не выполняется } // for, как и if не требует круглх скобок // переменные, объявленные в for и if являются локальными for x := 0; x < 3; x++ { // ++ - это операция fmt.Println("итерация", x) } // здесь x == 42 // for - единственный цикл в Go, но у него есть альтернативные формы for { // бесконечный цикл break // не такой уж бесконечный continue // не выполнится } // как и в for, := в if-е означает объявление и присвоение значения y, // проверка y > x происходит после if y := expensiveComputation(); y > x { x = y } // Функции являются замыканиями xBig := func() bool { return x > 10000 // Ссылается на x, объявленный выше switch } fmt.Println("xBig", xBig()) // true (т.к. мы присвоили x = e^10) x = 1.3e3 // тут x == 1300 fmt.Println("xBig", xBig()) // Теперь false // метки goto love love: learnDefer() learnInterfaces() } func learnDefer() (ok bool) { // отложенные (deferred) выражения выполняются сразу перед тем, как функция // возвратит значения defer fmt.Println("deferred statements execute in reverse (LIFO) order.") defer fmt.Println("\nThis line is being printed first because") // defer широко используется для закрытия файлов, чтобы закрывающая файл // функция находилась близко к открывающей return true } // Stringer объявление как интерфейса с одним методом, String type Stringer interface { String() string } // объявление pair как структуры с двумя полями x и y типа int type pair struct { x, y int } // объявление метода для типа pair; теперь pa
с Stringer func (p pair) String() string { // p в данном случае называют receiver-ом // Sprintf - ещё одна функция из пакета fmt // Обращение к полям p через точчку return fmt.Sprintf("(%d, %d)", p.x, p.y) } func learnInterfaces() { // синтаксис с фигурными скобками это "литерал структуры". Он возвращает // проинициализированную структуру, а оператор := присваивает её p p := pair{3, 4} fmt.Println(p.String()) // вызов метода String у переменной p типа pair var i Stringer // объявление i как типа с интерфейсом Stringer i = p // валидно, т.к. pair реализует Stringer // Вызов метода String у i типа Stringer fmt.Println(i.String()) // Функция в пакете fmt сами всегда вызывают метод String у объектов для // получения их строкового представления fmt.Println(p) // вывод такой-же, как и выше fmt.Println(i) // вывод такой-же, как и выше learnVariadicParams("Learn", "learn", "learn again") } // функции могут иметь варьируемое количество параметров func learnVariadicParams(myStrings ...interface{}) { // вывести все параметры с помощью итерации for _, param := range myStrings { fmt.Println("param:", param) } // передать все варьируемые параметры fmt.Println("params:", fmt.Sprintln(myStrings...)) learnErrorHandling() } func learnErrorHandling() { // идиома ", ok" служит для обозначения корректного срабатывания чего-либо m := map[int]string{3: "three", 4: "four"} if x, ok := m[1]; !
ir реализует интерфей
identifier_body
Main.go
return x + y, x * y // возврат двух значений } func learnTypes() { // тип string s := "Learn Go!" s2 := `"Чистый" строковый литерал может содержать переносы строк` // Символы не из ASCII g := 'Σ' // тип rune - алиас для типа int32, содержит символ юникода f := 3.141595 // float64, 64-х битное число с плавающей точкой c := 3 + 4i // complex128, внутри себя содержит два float64 // Синтаксис var с инициализ0ациями var u uint = 7 // беззнаковое, но размер зависит от реализации, как и у int var pi float32 = 22. / 7 // Синтаксис приведения типа с определением n := byte('\n') // byte - это алиас для uint8 // Массивы имеют фиксированный размер на момент компиляции var a4 [4]int // массив из 4-х int, инициализирован нулями a3 := [...]int{3, 1, 5} // массив из 3-х int, ручная инициализация // Слайсы (slices) имеют динамическую длину. И массивы, и слайсы имеют свои // преимущества, но слайсы используются гораздо чаще s3 := []int{4, 5, 9} // в отличие от a3, тут нет троеточия s4 := make([]int, 4) // выделение памяти для слайса из 4-х int (нули) var d2 [][]float64 // только объявление, память не выделяется bs := []byte("a slice") // синтаксис приведения типов p, q := learnMemory() // объявление p и q как указателей на int fmt.Println(*p, *q) // * извлекает указатель. Печатает два int-а // Map, также как и словарь или хэш из некоторых других языков, является // ассоциативным массивом с динамически изменяемым размером. m := map[string]int{"three": 3, "four": 4} m["one"] = 1 delete(m, "three") // встроенная функция, удаляет элемент из map-а // неиспользуемые переменные в Go считаются ошибкой // Нижнее подчеркивание позволяет игнорировать такие переменные _, _, _, _, _, _, _, _, _ = s2, g, f, u, pi, n, a3, s4, bs // Вывод считается использованием переменной fmt.Println(s, c, a4, s3, d2, m) learnFlowControl() // управление потоком } // у Go есть сборщик мусора. В нём есть указатели, но нет арифметики // указателей. Вы можете допустить ошибку с указателем на nil, но не с // инкрементацией указателя func learnMemory() (p, q *int) { // именованные возвращаемые значения p и q являются указателями на int p = new(int) // встроенная функция new выделяет память // выделенный int проинициализирован нулём, p больше не содержит nil s := make([]int, 20) // Выделение единого блока памяти под 20 int-ов s[3] = 7 // Присвоить значение одному из них r := -2 // определить ещё одну локальную переменную return &s[3], &r // Амперсанд(&) обозначает получение адреса переменной } func expensiveComputation() float64 { return m.Exp(10) } func learnFlowControl() { // if-ы всегда требуют наличия фигурных скобок, но не круглых if true { fmt.Println("told ya") } // форматирование кода стандартизировано утилитой "go fmt" if false { // не выполняется } else { // выполняется } // вместо нескольких if исползуется switch x := 42.0 switch x { case 0: case 1: case 42: // Case-ы в Go не "проваливаются" (неявный break) case 43: // не выполняется } // for, как и if не требует круглх скобок // переменные, объявленные в for и if являются локальными for x := 0; x < 3; x++ { // ++ - это операция fmt.Println("итерация", x) } // здесь x == 42 // for - единственный цикл в Go, но у него есть альтернативные формы for { // бесконечный цикл break // не такой уж бесконечный continue // не выполнится } // как и в for, := в if-е означает объявление и присвоение значения y, // проверка y > x происходит после if y := expensiveComputation(); y > x { x = y } // Функции являются замыканиями xBig := func() bool { return x > 10000 // Ссылается на x, объявленный выше switch } fmt.Println("xBig", xBig()) // true (т.к. мы присвоили x = e^10) x = 1.3e3 // тут x == 1300 fmt.Println("xBig", xBig()) // Теперь false // метки goto love love: learnDefer() learnInterfaces() } func learnDefer() (ok bool) { // отложенные (deferred) выражения выполняются сразу перед тем, как функция // возвратит значения defer fmt.Println("deferred statements execute in reverse (LIFO) order.") defer fmt.Println("\nThis line is being printed first because") // defer широко используется для закрытия файлов, чтобы закрывающая файл // функция находилась близко к открывающей return true } // Stringer объявление как интерфейса с одним методом, String type Stringer interface { String() string } // объявление pair как структуры с двумя полями x и y типа int type pair struct { x, y int } // объявление метода для типа pair; теперь pair реализует интерфейс Stringer func (p pair) String() string { // p в данном случае называют receiver-ом // Sprintf - ещё одна функция из пакета fmt // Обращение к полям p через точчку return fmt.Sprintf("(%d, %d)", p.x, p.y) } func learnInterfaces() { // синтаксис с фигурными скобками это "литерал структуры". Он возвращает // проинициализированную структуру, а оператор := присваивает её p p := pair{3, 4} fmt.Println(p.String()) // вызов метода String у переменной p типа pair var i Stringer // объявление i как типа с интерфейсом Stringer i = p // валидно, т.к. pair реализует Stringer // Вызов метода String у i типа Stringer fmt.Println(i.String())
learnVariadicParams("Learn", "learn", "learn again") } // функции могут иметь варьируемое количество параметров func learnVariadicParams(myStrings ...interface{}) { // вывести все параметры с помощью итерации for _, param := range myStrings { fmt.Println("param:", param) } // передать все варьируемые параметры fmt.Println("params:", fmt.Sprintln(myStrings...)) learnErrorHandling() } func learnErrorHandling() { // идиома ", ok" служит для обозначения корректного срабатывания чего-либо m := map[int]string{3: "three", 4: "four"} if x, ok := m[1]; !
// Функция в пакете fmt сами всегда вызывают метод String у объектов для // получения их строкового представления fmt.Println(p) // вывод такой-же, как и выше fmt.Println(i) // вывод такой-же, как и выше
random_line_split
descriptive_stats_04022018.py
['YearBuilt'].between(1940, 2015)] df = df.drop_duplicates(['YearBuilt', 'Single Family Homes']) df_cluster = Main[['YearBuilt', 'hoa_neigh', 'YearBuilt_mode']].dropna() df_cluster = df_cluster[df_cluster['hoa_neigh'].isin([0,1])] df_cluster['mode_dist'] = df_cluster['YearBuilt'] - df_cluster['YearBuilt_mode'] df_cluster = df_cluster[df_cluster['mode_dist'].between(-5,5)] df_cluster['Single Family Homes Built in a New Subdivision'] = df_cluster.groupby('YearBuilt')['hoa_neigh'].transform(pd.Series.mean) df_cluster = df_cluster[df_cluster['YearBuilt'].between(1940, 2015)] df_cluster = df_cluster.drop_duplicates(['YearBuilt', 'Single Family Homes Built in a New Subdivision']) '''df_cluster = Main[['YearBuilt', 'hoa_neigh']].dropna() df_cluster = df_cluster[df_cluster['hoa_cluster'].isin([0,1])] df_cluster['Single Family Homes Built in a New Subdivision'] = df_cluster.groupby('YearBuilt')['hoa_cluster'].transform(pd.Series.mean) df_cluster = df_cluster[df_cluster['YearBuilt'].between(1940, 2015)] df_cluster = df_cluster.drop_duplicates(['YearBuilt', 'Single Family Homes Built in a New Subdivision'])''' df = df.merge(df_cluster, on='YearBuilt', how='inner') df = df.sort_values(by='YearBuilt') ax = plt.subplot(111) plt.plot(df['YearBuilt'], df['Single Family Homes']) plt.plot(df['YearBuilt'], df['Single Family Homes Built in a New Subdivision']) plt.legend() plt.savefig(r'G:\Zillow\Created\Figures\hoa_pct_yr.pdf') ############################################################################### # By county, MSA and Census division # MSA df = Main[['hoa', 'cbsacode']].dropna() df['hoa_pct'] = df.groupby('cbsacode')['hoa'].transform(pd.Series.mean) df = df.drop_duplicates('cbsacode') df1 = Main[['hoa', 'cbsacode', 'YearBuilt']].dropna() df1 = df1[df1['YearBuilt'].between(2000, 2015)] df1['hoa_pct_new'] = df1.groupby('cbsacode')['hoa'].transform(pd.Series.mean) df1 = df1.drop_duplicates('cbsacode') df = df[['cbsacode', 'hoa_pct']].merge(df1[['cbsacode', 'hoa_pct_new']], on='cbsacode', how='left') df.to_csv(r'G:\Zillow\Created\Figures\hoa_pct_msa.csv') # County df = Main[['hoa', 'county']].dropna() df['hoa_pct'] = df.groupby('county')['hoa'].transform(pd.Series.mean) df = df.drop_duplicates('county') df1 = Main[['hoa_neigh', 'county', 'YearBuilt', 'YearBuilt_mode']].dropna() df1 = df1[df1['YearBuilt'].between(2000, 2015)] df1 = df1[df1['hoa_neigh'].isin([0,1])] df1['mode_dist'] = df1['YearBuilt'] - df1['YearBuilt_mode'] df1 = df1[df1['mode_dist'].between(-5,5)] df1['hoa_pct_new'] = df1.groupby('county')['hoa_neigh'].transform(pd.Series.mean) df1 = df1.drop_duplicates('county') df = df[['county', 'hoa_pct']].merge(df1[['county', 'hoa_pct_new']], on='county', how='left') df['GISJOIN'] = "G" + df['county'].str[:2] + "0" + df['county'].str[2:] + "0" df.to_csv(r'G:\Zillow\Created\Figures\hoa_pct_county.csv') # Census division df = Main[['hoa', 'division_code']].dropna() df['hoa_pct'] = df.groupby('division_code')['hoa'].transform(pd.Series.mean) df = df.drop_duplicates('division_code') df1 = Main[['hoa_neigh', 'division_code', 'YearBuilt', 'YearBuilt_mode']].dropna() df1 = df1[df1['YearBuilt'].between(2000, 2015)] df1 = df1[df1['hoa_neigh'].isin([0,1])] df1['mode_dist'] = df1['YearBuilt'] - df1['YearBuilt_mode'] df1 = df1[df1['mode_dist'].between(-5,5)] df1['hoa_pct_new'] = df1.groupby('division_code')['hoa_neigh'].transform(pd.Series.mean) df1 = df1.drop_duplicates('division_code') df = df[['division_code', 'hoa_pct']].merge(df1[['division_code', 'hoa_pct_new']], on='division_code', how='left') df['hoa_pct'] = df['hoa_pct'].round(2)*100 df['hoa_pct_new'] = df['hoa_pct_new'].round(2)*100 df.to_csv(r'G:\Zillow\Created\Figures\hoa_pct_division.csv') # TIED TO CENSUS CHARACTERISTICS ############################################################################### ############################################################################### # Create summary measures by geoid Main['geoid'] = Main['PropertyAddressCensusTractAndBlock'].astype(str).str[:9] + Main['PropertyAddressCensusTractAndBlock'].astype(str).str[10:13] Main['records_n'] = Main.groupby(['geoid'])['RowID'].transform(pd.Series.count) Main['hoa_geoid'] = Main.groupby(['geoid'])['hoa'].transform(pd.Series.mean) chars = Main[['geoid', 'hoa_geoid', 'records_n']].dropna().drop_duplicates() chars = chars[chars['records_n']>=30] # Merge to Census data # Load data census_chars = pd.read_csv(r'C:\Users\wyatt\Research\Zillow\IPUMS_blockgrp_07012017.csv') census_chars = census_chars[census_chars['total_pop']>0] # Reformat to allow a merge census_chars['st'] = census_chars['GISJOIN'].str[1:3] census_chars['co'] = census_chars['GISJOIN'].str[4:7] census_chars['tract'] = census_chars['GISJOIN'].str[8:12] census_chars['blkgrp'] = census_chars['GISJOIN'].str[12:15] census_chars['geoid'] = census_chars['st'] + census_chars['co'] + census_chars['tract'] + census_chars['blkgrp'] census_chars = census_chars.drop(['st', 'co', 'tract', 'blkgrp', 'GISJOIN'], axis=1) # Calculate race as a percentage of total population colors = ['white', 'black', 'asian', 'hispanic', 'other_race'] for color in colors: census_chars['{}_geoid'.format(color)] = census_chars['{}'.format(color)] / census_chars['total_pop'] census_chars.info() # Merge chars = chars.merge(census_chars, on='geoid', how='inner') # Assign weight for hoa and non-hoa characteristics chars['geoid_hoa_wt'] = chars['total_pop'] * chars['hoa_geoid'] chars['geoid_nonhoa_wt'] = chars['total_pop'] * (1-chars['hoa_geoid']) # Race colors_geoid = ['white_geoid', 'black_geoid', 'asian_geoid', 'hispanic_geoid', 'other_race_geoid'] race_hoa = np.average(chars[colors_geoid], axis=0, weights=chars['geoid_hoa_wt']) race_nonhoa = np.average(chars[colors_geoid], axis=0, weights=chars['geoid_nonhoa_wt']) # Median income foo = chars[chars['med_hs_income'].notnull()] income_hoa = np.average(foo[['med_hs_income']], axis=0, weights=foo['geoid_hoa_wt']) income_nonhoa = np.average(foo[['med_hs_income']], axis=0, weights=foo['geoid_nonhoa_wt']) # Racial isolation isol = pd.DataFrame(columns=colors) for color in colors:
isol.to_csv(r'G:\Zillow\Created\Figures\
chars['{}_hoa_wt'.format(color)] = chars['{}'.format(color)] * chars['hoa_geoid'] chars['{}_nonhoa_wt'.format(color)] = chars['{}'.format(color)] * (1-chars['hoa_geoid']) isol_hoa = np.average(chars[colors_geoid], axis=0, weights=chars['{}_hoa_wt'.format(color)]) isol_nonhoa = np.average(chars[colors_geoid], axis=0, weights=chars['{}_nonhoa_wt'.format(color)]) df = pd.DataFrame([isol_hoa, isol_nonhoa], columns=colors, index=['{}_hoa'.format(color), '{}_nonhoa'.format(color)]) #df_hoa = pd.DataFrame(isol_hoa, columns=['{}'.format(color)]) #df_nonhoa = pd.DataFrame(isol_nonhoa, columns=['{}'.format(color)]) isol = isol.append(df)
conditional_block
descriptive_stats_04022018.py
['YearBuilt'].between(1940, 2015)] df = df.drop_duplicates(['YearBuilt', 'Single Family Homes']) df_cluster = Main[['YearBuilt', 'hoa_neigh', 'YearBuilt_mode']].dropna() df_cluster = df_cluster[df_cluster['hoa_neigh'].isin([0,1])] df_cluster['mode_dist'] = df_cluster['YearBuilt'] - df_cluster['YearBuilt_mode'] df_cluster = df_cluster[df_cluster['mode_dist'].between(-5,5)] df_cluster['Single Family Homes Built in a New Subdivision'] = df_cluster.groupby('YearBuilt')['hoa_neigh'].transform(pd.Series.mean) df_cluster = df_cluster[df_cluster['YearBuilt'].between(1940, 2015)] df_cluster = df_cluster.drop_duplicates(['YearBuilt', 'Single Family Homes Built in a New Subdivision']) '''df_cluster = Main[['YearBuilt', 'hoa_neigh']].dropna() df_cluster = df_cluster[df_cluster['hoa_cluster'].isin([0,1])] df_cluster['Single Family Homes Built in a New Subdivision'] = df_cluster.groupby('YearBuilt')['hoa_cluster'].transform(pd.Series.mean) df_cluster = df_cluster[df_cluster['YearBuilt'].between(1940, 2015)] df_cluster = df_cluster.drop_duplicates(['YearBuilt', 'Single Family Homes Built in a New Subdivision'])''' df = df.merge(df_cluster, on='YearBuilt', how='inner') df = df.sort_values(by='YearBuilt') ax = plt.subplot(111) plt.plot(df['YearBuilt'], df['Single Family Homes']) plt.plot(df['YearBuilt'], df['Single Family Homes Built in a New Subdivision']) plt.legend() plt.savefig(r'G:\Zillow\Created\Figures\hoa_pct_yr.pdf') ############################################################################### # By county, MSA and Census division # MSA df = Main[['hoa', 'cbsacode']].dropna() df['hoa_pct'] = df.groupby('cbsacode')['hoa'].transform(pd.Series.mean) df = df.drop_duplicates('cbsacode') df1 = Main[['hoa', 'cbsacode', 'YearBuilt']].dropna() df1 = df1[df1['YearBuilt'].between(2000, 2015)] df1['hoa_pct_new'] = df1.groupby('cbsacode')['hoa'].transform(pd.Series.mean) df1 = df1.drop_duplicates('cbsacode') df = df[['cbsacode', 'hoa_pct']].merge(df1[['cbsacode', 'hoa_pct_new']], on='cbsacode', how='left') df.to_csv(r'G:\Zillow\Created\Figures\hoa_pct_msa.csv') # County df = Main[['hoa', 'county']].dropna() df['hoa_pct'] = df.groupby('county')['hoa'].transform(pd.Series.mean) df = df.drop_duplicates('county') df1 = Main[['hoa_neigh', 'county', 'YearBuilt', 'YearBuilt_mode']].dropna() df1 = df1[df1['YearBuilt'].between(2000, 2015)] df1 = df1[df1['hoa_neigh'].isin([0,1])] df1['mode_dist'] = df1['YearBuilt'] - df1['YearBuilt_mode'] df1 = df1[df1['mode_dist'].between(-5,5)] df1['hoa_pct_new'] = df1.groupby('county')['hoa_neigh'].transform(pd.Series.mean) df1 = df1.drop_duplicates('county') df = df[['county', 'hoa_pct']].merge(df1[['county', 'hoa_pct_new']], on='county', how='left') df['GISJOIN'] = "G" + df['county'].str[:2] + "0" + df['county'].str[2:] + "0" df.to_csv(r'G:\Zillow\Created\Figures\hoa_pct_county.csv') # Census division df = Main[['hoa', 'division_code']].dropna() df['hoa_pct'] = df.groupby('division_code')['hoa'].transform(pd.Series.mean) df = df.drop_duplicates('division_code') df1 = Main[['hoa_neigh', 'division_code', 'YearBuilt', 'YearBuilt_mode']].dropna() df1 = df1[df1['YearBuilt'].between(2000, 2015)] df1 = df1[df1['hoa_neigh'].isin([0,1])] df1['mode_dist'] = df1['YearBuilt'] - df1['YearBuilt_mode'] df1 = df1[df1['mode_dist'].between(-5,5)] df1['hoa_pct_new'] = df1.groupby('division_code')['hoa_neigh'].transform(pd.Series.mean) df1 = df1.drop_duplicates('division_code') df = df[['division_code', 'hoa_pct']].merge(df1[['division_code', 'hoa_pct_new']], on='division_code', how='left') df['hoa_pct'] = df['hoa_pct'].round(2)*100 df['hoa_pct_new'] = df['hoa_pct_new'].round(2)*100 df.to_csv(r'G:\Zillow\Created\Figures\hoa_pct_division.csv') # TIED TO CENSUS CHARACTERISTICS ############################################################################### ###############################################################################
chars = Main[['geoid', 'hoa_geoid', 'records_n']].dropna().drop_duplicates() chars = chars[chars['records_n']>=30] # Merge to Census data # Load data census_chars = pd.read_csv(r'C:\Users\wyatt\Research\Zillow\IPUMS_blockgrp_07012017.csv') census_chars = census_chars[census_chars['total_pop']>0] # Reformat to allow a merge census_chars['st'] = census_chars['GISJOIN'].str[1:3] census_chars['co'] = census_chars['GISJOIN'].str[4:7] census_chars['tract'] = census_chars['GISJOIN'].str[8:12] census_chars['blkgrp'] = census_chars['GISJOIN'].str[12:15] census_chars['geoid'] = census_chars['st'] + census_chars['co'] + census_chars['tract'] + census_chars['blkgrp'] census_chars = census_chars.drop(['st', 'co', 'tract', 'blkgrp', 'GISJOIN'], axis=1) # Calculate race as a percentage of total population colors = ['white', 'black', 'asian', 'hispanic', 'other_race'] for color in colors: census_chars['{}_geoid'.format(color)] = census_chars['{}'.format(color)] / census_chars['total_pop'] census_chars.info() # Merge chars = chars.merge(census_chars, on='geoid', how='inner') # Assign weight for hoa and non-hoa characteristics chars['geoid_hoa_wt'] = chars['total_pop'] * chars['hoa_geoid'] chars['geoid_nonhoa_wt'] = chars['total_pop'] * (1-chars['hoa_geoid']) # Race colors_geoid = ['white_geoid', 'black_geoid', 'asian_geoid', 'hispanic_geoid', 'other_race_geoid'] race_hoa = np.average(chars[colors_geoid], axis=0, weights=chars['geoid_hoa_wt']) race_nonhoa = np.average(chars[colors_geoid], axis=0, weights=chars['geoid_nonhoa_wt']) # Median income foo = chars[chars['med_hs_income'].notnull()] income_hoa = np.average(foo[['med_hs_income']], axis=0, weights=foo['geoid_hoa_wt']) income_nonhoa = np.average(foo[['med_hs_income']], axis=0, weights=foo['geoid_nonhoa_wt']) # Racial isolation isol = pd.DataFrame(columns=colors) for color in colors: chars['{}_hoa_wt'.format(color)] = chars['{}'.format(color)] * chars['hoa_geoid'] chars['{}_nonhoa_wt'.format(color)] = chars['{}'.format(color)] * (1-chars['hoa_geoid']) isol_hoa = np.average(chars[colors_geoid], axis=0, weights=chars['{}_hoa_wt'.format(color)]) isol_nonhoa = np.average(chars[colors_geoid], axis=0, weights=chars['{}_nonhoa_wt'.format(color)]) df = pd.DataFrame([isol_hoa, isol_nonhoa], columns=colors, index=['{}_hoa'.format(color), '{}_nonhoa'.format(color)]) #df_hoa = pd.DataFrame(isol_hoa, columns=['{}'.format(color)]) #df_nonhoa = pd.DataFrame(isol_nonhoa, columns=['{}'.format(color)]) isol = isol.append(df) isol.to_csv(r'G:\Zillow\Created\Fig
# Create summary measures by geoid Main['geoid'] = Main['PropertyAddressCensusTractAndBlock'].astype(str).str[:9] + Main['PropertyAddressCensusTractAndBlock'].astype(str).str[10:13] Main['records_n'] = Main.groupby(['geoid'])['RowID'].transform(pd.Series.count) Main['hoa_geoid'] = Main.groupby(['geoid'])['hoa'].transform(pd.Series.mean)
random_line_split
game_engine.py
or json type provided') # CLASS Game # stores screen resolution and background color # initializes the players starting location # define control and drawing methods # TODO: add wall member as array of tiles # TODO: add floor member as array of tiles class Game: current_level = None current_map = None player = None dark_grey = (20, 12, 28) white = (223, 239, 215) blue = (89, 125, 207) background_color = dark_grey # screen size (in 32*32 squares) needs to be odd numbers because of player in center screen_size = (45, 23) screen_resolution = (screen_size[0] * 32, screen_size[1] * 32) screen_x_buffer = int((screen_size[0]-1)/2) screen_y_buffer = int((screen_size[1]-1)/2) key_delay = 200 key_repeat = 50 current_map = [] current_object_map = [] os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (0, 32) def __init__(self): pygame.init() self.font_1 = pygame.font.Font('fonts/victor-pixel.ttf', 32) pygame.key.set_repeat(self.key_delay, self.key_repeat) flags = DOUBLEBUF | HWACCEL self.screen = pygame.display.set_mode(self.screen_resolution,flags) pygame.event.set_allowed([QUIT, KEYDOWN, KEYUP]) # setup display and background color/size pygame.display.set_icon(pygame.image.load('graphics/icon.png')) pygame.display.set_caption('A simple roguelike') self.background = pygame.Surface(self.screen_resolution) self.background.fill(self.background_color) # initialize game to first level current_level = Level() current_level.loadLevel('town') # make the wall and floor class self.floor_1 = [] self.floor_1.append(load_image(os.path.join(graphics_dir, "floor_1_1.png"))) self.floor_1.append(load_image(os.path.join(graphics_dir, "floor_1_2.png"))) self.floor_1.append(load_image(os.path.join(graphics_dir, "floor_1_3.png"))) self.floor_1.append(load_image(os.path.join(graphics_dir, "floor_1_4.png"))) self.floor_1.append(load_image(os.path.join(graphics_dir, "floor_1_5.png"))) self.floor_1.append(load_image(os.path.join(graphics_dir, "floor_1_6.png"))) self.floor_1.append(load_image(os.path.join(graphics_dir, "floor_1_7.png"))) self.floor_1.append(load_image(os.path.join(graphics_dir, "floor_1_8.png"))) self.floor_1.append(load_image(os.path.join(graphics_dir, "floor_1_9.png"))) self.floor_2 = [] self.floor_2.append(load_image(os.path.join(graphics_dir, "floor_2.png"))) self.wall = [] self.wall.append(load_image(os.path.join(graphics_dir, "wall_1.png"))) self.wall.append(load_image(os.path.join(graphics_dir, "wall_2.png"))) self.warp = load_image(os.path.join(graphics_dir, "warp.png")) # CONTROL TICK # this function will handle all input functions # returns false when game is ready to quit def control_tick(self): if joystick_count > 0: joystick = pygame.joystick.Joystick(0) joystick.init() # pos_east = self.current_map[self.player.y_pos][self.player.x_pos + 1] # pos_west = self.current_map[self.player.y_pos][self.player.x_pos - 1] # pos_north = self.current_map[self.player.y_pos - 1][self.player.x_pos] # pos_south = self.current_map[self.player.y_pos + 1][self.player.x_pos] # get enemies in close proximity and forbid moving in those directions # need to detect enemies that are adjacent to player # TODO: this is linear time and need to be improved # for npc in self.current_level.npcs: # if npc.x_pos == self.player.x_pos: # if npc.y_pos == (self.player.y_pos + 1): # print("south") # pos_south = 61 # # collide with npc to the south # elif npc.y_pos == (self.player.y_pos - 1): # print("north") # pos_north = 61 # # collide with npc to the north # elif npc.y_pos == self.player.y_pos: # if npc.x_pos == (self.player.x_pos + 1): # print("east") # pos_east = 61 # # collide with npc to the east # elif npc.x_pos == (self.player.x_pos - 1): # print("west") # pos_west = 61 # # collide with npc to the west while True: # improve performance by waiting to draw until new event is on event queue event = pygame.event.wait() if event.type == pygame.QUIT: return False if event.type == KEYDOWN: if event.key == K_RIGHT and self.current_level.getObjAt(self.player.x_pos + 1, self.player.y_pos) == None: self.player.x_pos += 1 return True elif event.key == K_LEFT and self.current_level.getObjAt(self.player.x_pos - 1, self.player.y_pos) == None: self.player.x_pos -= 1 return True elif event.key == K_UP and self.current_level.getObjAt(self.player.x_pos, self.player.y_pos - 1) == None: self.player.y_pos -= 1 return True elif event.key == K_DOWN and self.current_level.getObjAt(self.player.x_pos, self.player.y_pos + 1) == None: self.player.y_pos += 1 return True elif event.key == K_ESCAPE: return False # xinput controls # need to implement repeat on hold down. no pygame methods available for this # if event.type == JOYHATMOTION: # hat = joystick.get_hat(0) # if hat == (1, 0) and (pos_east < 61): # self.player.x_pos += 1 # return True # if hat == (-1, 0) and (pos_west < 61): # self.player.x_pos -= 1 # return True # if hat == (0, 1) and (pos_north < 61): # self.player.y_pos -= 1 # return True # if hat == (0, -1) and (pos_south < 61): # self.player.y_pos += 1 # return True # DRAW TICK # this function handles all of the rendering functionality # has no return value def draw_tick(self): # check for warp # needs reworking # pos = self.current_map[self.player.y_pos][self.player.x_pos] # if pos == 0: # position_key = str(self.player.x_pos) + ',' + str(self.player.y_pos) # if self.current_level.warp_list[position_key]: # warp = self.current_level.warp_list[position_key] # self.load_level(warp.new_level) # self.player.x_pos = warp.new_x # self.player.y_pos = warp.new_y # draw the current_map matrix # scroll the map based on the player # TODO: fix this to include variable resolution values self.screen.blit(self.background, (0, 0)) for x in range(self.player.x_pos - self.screen_x_buffer, self.player.x_pos + self.screen_x_buffer + 1): for y in range(self.player.y_pos - self.screen_y_buffer, self.player.y_pos + self.screen_y_buffer + 1): if x in range(len(self.current_map[0])) and y in range(len(self.current_map)): # draw the background if self.current_map[y][x] > 80: self.screen.blit(self.wall[1], ((x - self.player.x_pos + self.screen_x_buffer) * 32,
(y - self.player.y_pos + self.screen_y_buffer) * 32)) elif self.current_map[y][x] > 60: self.screen.blit(self.wall[0], ((x - self.player.x_pos + self.screen_x_buffer) * 32,
random_line_split
game_engine.py
1): # print("north") # pos_north = 61 # # collide with npc to the north # elif npc.y_pos == self.player.y_pos: # if npc.x_pos == (self.player.x_pos + 1): # print("east") # pos_east = 61 # # collide with npc to the east # elif npc.x_pos == (self.player.x_pos - 1): # print("west") # pos_west = 61 # # collide with npc to the west while True: # improve performance by waiting to draw until new event is on event queue event = pygame.event.wait() if event.type == pygame.QUIT: return False if event.type == KEYDOWN: if event.key == K_RIGHT and self.current_level.getObjAt(self.player.x_pos + 1, self.player.y_pos) == None: self.player.x_pos += 1 return True elif event.key == K_LEFT and self.current_level.getObjAt(self.player.x_pos - 1, self.player.y_pos) == None: self.player.x_pos -= 1 return True elif event.key == K_UP and self.current_level.getObjAt(self.player.x_pos, self.player.y_pos - 1) == None: self.player.y_pos -= 1 return True elif event.key == K_DOWN and self.current_level.getObjAt(self.player.x_pos, self.player.y_pos + 1) == None: self.player.y_pos += 1 return True elif event.key == K_ESCAPE: return False # xinput controls # need to implement repeat on hold down. no pygame methods available for this # if event.type == JOYHATMOTION: # hat = joystick.get_hat(0) # if hat == (1, 0) and (pos_east < 61): # self.player.x_pos += 1 # return True # if hat == (-1, 0) and (pos_west < 61): # self.player.x_pos -= 1 # return True # if hat == (0, 1) and (pos_north < 61): # self.player.y_pos -= 1 # return True # if hat == (0, -1) and (pos_south < 61): # self.player.y_pos += 1 # return True # DRAW TICK # this function handles all of the rendering functionality # has no return value def draw_tick(self): # check for warp # needs reworking # pos = self.current_map[self.player.y_pos][self.player.x_pos] # if pos == 0: # position_key = str(self.player.x_pos) + ',' + str(self.player.y_pos) # if self.current_level.warp_list[position_key]: # warp = self.current_level.warp_list[position_key] # self.load_level(warp.new_level) # self.player.x_pos = warp.new_x # self.player.y_pos = warp.new_y # draw the current_map matrix # scroll the map based on the player # TODO: fix this to include variable resolution values self.screen.blit(self.background, (0, 0)) for x in range(self.player.x_pos - self.screen_x_buffer, self.player.x_pos + self.screen_x_buffer + 1): for y in range(self.player.y_pos - self.screen_y_buffer, self.player.y_pos + self.screen_y_buffer + 1): if x in range(len(self.current_map[0])) and y in range(len(self.current_map)): # draw the background if self.current_map[y][x] > 80: self.screen.blit(self.wall[1], ((x - self.player.x_pos + self.screen_x_buffer) * 32, (y - self.player.y_pos + self.screen_y_buffer) * 32)) elif self.current_map[y][x] > 60: self.screen.blit(self.wall[0], ((x - self.player.x_pos + self.screen_x_buffer) * 32, (y - self.player.y_pos + self.screen_y_buffer) * 32)) elif self.current_map[y][x] > 20: self.screen.blit(self.floor_2[0], ((x - self.player.x_pos + self.screen_x_buffer) * 32, (y - self.player.y_pos + self.screen_y_buffer) * 32)) elif self.current_map[y][x] > 0: self.screen.blit(self.floor_1[self.current_map[y][x]-1], ((x - self.player.x_pos + self.screen_x_buffer) * 32, (y - self.player.y_pos + self.screen_y_buffer) * 32)) elif self.current_map[y][x] == 0: self.screen.blit(self.warp, ((x - self.player.x_pos + self.screen_x_buffer) * 32, (y - self.player.y_pos + self.screen_y_buffer) * 32)) # update and draw npcs on the screen #if len(self.current_level.obj) > 0: for obj in self.current_level.object_list: # obj.update(self.player, self.current_map) # eventually get to this step if obj.x_pos in range(len(self.current_map[0])) and obj.y_pos in range(len(self.current_map)): self.screen.blit(obj.image, ((obj.x_pos - self.player.x_pos + self.screen_x_buffer) * 32, (obj.y_pos - self.player.y_pos + self.screen_y_buffer) * 32)) # draw player in the center of the screen self.screen.blit(self.player.image, (self.screen_x_buffer * 32, self.screen_y_buffer * 32)) pygame.display.flip() def loadLevel(self, levelName): self.current_level.loadLevel(levelName) self.current_map = self.current_level.getMap() # main game loop def play(self): while True: self.draw_tick() # return if control returns false if not self.control_tick(): return def new_game(self): # TODO: consolidate all npc spawn points # self.load_level(self.town_level) # starting level self.current_level = Level() self.loadLevel('town') self.player = Player(5,5) self.play() def main_menu(self): resolution_672_480 = (21, 15) resolution_1056_608 = (33, 19) resolution_1440_736 = (45, 23) while True: # declare menues menu_main = [ self.font_1.render('(n)ew game', False, self.white), self.font_1.render('change (r)esolution', False, self.white), self.font_1.render('(q)uit', False, self.white) ] menu_resolution = [ self.font_1.render('(1) 672x480', False, self.white), self.font_1.render('(2) 1056x608', False, self.white), self.font_1.render('(3) 1440x736', False, self.white) ] # draw main menu to screen self.screen.blit(self.background, (0, 0)) for i in range(len(menu_main)): self.screen.blit(menu_main[i], (32 * int(self.screen_x_buffer / 2), (32 * int(self.screen_y_buffer / 2)) + (32 * i))) pygame.display.flip() event = pygame.event.wait() # get user input if event.type == KEYDOWN: if event.key == K_n: return 'new' elif event.key == K_r: res_menu = True while res_menu is True: # display resolution menu self.screen.blit(self.background, (0, 0)) for i in range(len(menu_resolution)): self.screen.blit(menu_resolution[i], (32 * int(self.screen_x_buffer / 2), (32 * int(self.screen_y_buffer / 2)) + (32 * i))) pygame.display.flip() event = pygame.event.wait() # get user input if event.type == KEYDOWN:
if event.key == K_1: self.screen_size = resolution_672_480 res_menu = False elif event.key == K_2: self.screen_size = resolution_1056_608 res_menu = False elif event.key == K_3: self.screen_size = resolution_1440_736 res_menu = False
conditional_block
game_engine.py
# Class Level # this stores the information for a level in one class # this class should be treated like a singleton class Level(object): _map_name = None _map = [] _object_matrix = [] object_list = [] _json = {} def __init__(self): self._map = None def __load_json(self, file_name): with open(file_name) as infile: return json.load(infile) def __save_json(self, file_name, data): with open(file_name, 'w') as outfile: json.dump(data, outfile, indent=4) # handler for when objects get updated in the object matrix def onObjectMove(self, sender, eventArgs): self._object_matrix[sender.y_pos][sender.x_pos] = sender.getRef() self._object_matrix[eventArgs[1]][eventArgs[0]] = None def getObjAt(self, x, y): return self._object_matrix[x][y] def getMapAt(self, x, y): return self._map[x][y] def getMap(self): return self._map # saveLevel takes the current level in memory and saves it to Json format def saveLevel(self): self._json['objects'] = [] for obj in self.object_list: self._json['objects'].append(obj.toDict()) path = 'levels/' + self._map_name + '.json' self.__save_json(path, self._json) # Load Level # len(self._map) is height of map # len(self._map[0]) is width of map def loadLevel(self,level_name): self._json = self.__load_json('levels/' + level_name + '.json') self._map_name = self._json["name"] self._map = self._json['map'] self._object_matrix = [[None] * len(self._map[0]) for i in range(len(self._map))] # sets objects matrix to a matrix of all None the size of _map for i in range(len(self._json['objects'])): if self._json['objects'][i]['type'] == 'warp': self.object_list.append(LevelWarp(self._json['objects'][i])) elif self._json['objects'][i]['type'] == 'chest': self.object_list.append(Chest(self._json['objects'][i])) elif self._json['objects'][i]['type'] == 'enemy': self.object_list.append(Enemy(self._json['objects'][i])) self.object_list[-1].moved_event += self.onObjectMove elif self._json['objects'][i]['type'] == 'friendly': self.object_list.append(Friendly(self._json['objects'][i])) self._object_matrix[self.object_list[-1].y_pos][self.object_list[-1].x_pos] = self.object_list[-1].getRef() self.enumerateLevel() def switchLevel(self, level_name): if self._map != None: self.saveLevel() self.loadLevel(level_name) # put wall instances in the object matrix for y in range(len(self._map)): for x in range(len(self._map[0])): if self._map[y][x] == '1': self._object_matrix[y][x] = Wall.getInstance() # enumerateLevel # enumerates levels character values by convention # corresponding wall floor class is +/- 60 # floors 1('.'): 1 - 20 # floors 2(','): 21 - 40 # floors 3('`'): 41 - 60 # walls 1('1'): 61 - 80 # walls 2('2'): 81 - 100 # walls 3('3'): 101 - 120 # warp: 0 # nullspace('_'): -1 def enumerateLevel(self): for i in range(len(self._map)): for j in range(len(self._map[0])): if self._map[i][j] == '_': # set null self._map[i][j] = -1 elif self._map[i][j] == '.': # set floors self._map[i][j] = 1 rand = random.randint(1, 400) if rand > 50: self._map[i][j] = 1 elif rand > 45: self._map[i][j] = 2 elif rand > 40: self._map[i][j] = 3 elif rand > 35: self._map[i][j] = 4 elif rand > 30: self._map[i][j] = 5 elif rand > 25: self._map[i][j] = 6 elif rand > 20: self._map[i][j] = 7 elif rand > 15: self._map[i][j] = 8 else: self._map[i][j] = 9 elif self._map[i][j] == ',': self._map[i][j] = 21 elif self._map[i][j] == '`': self._map[i][j] = 41 elif self._map[i][j] == '1': # set walls self._map[i][j] = 61 elif self._map[i][j] == '2': self._map[i][j] = 81 elif self._map[i][j] == '3': self._map[i][j] = 101 # CLASS LevelWarp # handles changing the level and moving player to correct location class LevelWarp(): def getRef(self): return self def toDict(self): return { 'type':'warp','next_level':self.next_level, 'x_pos':self.x_pos, 'y_pos':self.y_pos, 'x_dest':self.x_dest, 'y_dest':self.y_dest } def __init__(self, json_obj): if type(json_obj) == dict: self.image = load_image('warp.png') self.next_level = json_obj['next_level'] self.x_pos = json_obj['x_pos'] self.y_pos = json_obj['y_pos'] self.x_dest = json_obj['x_dest'] self.y_dest = json_obj['y_dest'] else: raise Exception('non dictionary or json type provided') # CLASS Game # stores screen resolution and background color # initializes the players starting location # define control and drawing methods # TODO: add wall member as array of tiles # TODO: add floor member as array of tiles class Game: current_level = None current_map = None player = None dark_grey = (20, 12, 28) white = (223, 239, 215) blue = (89, 125, 207) background_color = dark_grey # screen size (in 32*32 squares) needs to be odd numbers because of player in center screen_size = (45, 23) screen_resolution = (screen_size[0] * 32, screen_size[1] * 32) screen_x_buffer = int((screen_size[0]-1)/2) screen_y_buffer = int((screen_size[1]-1)/2) key_delay = 200 key_repeat = 50 current_map = [] current_object_map = [] os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (0, 32) def __init__(self): pygame.init() self.font_1 = pygame.font.Font('fonts/victor-pixel.ttf', 32) pygame.key.set_repeat(self.key_delay, self.key_repeat) flags = DOUBLEBUF | HWACCEL self.screen = pygame.display.set_mode(self.screen_resolution,flags) pygame.event.set_allowed([QUIT, KEYDOWN, KEYUP]) # setup display and background color/size pygame.display.set_icon(pygame.image.load('graphics/icon.png')) pygame.display.set_caption('A simple roguelike') self.background = pygame.Surface(self.screen_resolution) self.background.fill(self.background_color) # initialize game to first level current_level = Level() current_level.loadLevel('town') # make the wall and floor class self.floor_1 = [] self.floor_1.append(load_image(os.path.join(graphics_dir, "floor_1_1.png"))) self.floor_1.append(load_image(os.path.join(graphics_dir, "floor_1_2.png"))) self.floor_1.append(load_image(os.path.join(graphics_dir, "floor
__instance = None @staticmethod def getInstance(): if Wall.__instance == None: Wall() return Wall.__instance def __init__(self): if Wall.__instance != None: raise Exception("this class is a singleton. use getinstance() instead") else: Wall.__instance = self
identifier_body
game_engine.py
._json["name"] self._map = self._json['map'] self._object_matrix = [[None] * len(self._map[0]) for i in range(len(self._map))] # sets objects matrix to a matrix of all None the size of _map for i in range(len(self._json['objects'])): if self._json['objects'][i]['type'] == 'warp': self.object_list.append(LevelWarp(self._json['objects'][i])) elif self._json['objects'][i]['type'] == 'chest': self.object_list.append(Chest(self._json['objects'][i])) elif self._json['objects'][i]['type'] == 'enemy': self.object_list.append(Enemy(self._json['objects'][i])) self.object_list[-1].moved_event += self.onObjectMove elif self._json['objects'][i]['type'] == 'friendly': self.object_list.append(Friendly(self._json['objects'][i])) self._object_matrix[self.object_list[-1].y_pos][self.object_list[-1].x_pos] = self.object_list[-1].getRef() self.enumerateLevel() def switchLevel(self, level_name): if self._map != None: self.saveLevel() self.loadLevel(level_name) # put wall instances in the object matrix for y in range(len(self._map)): for x in range(len(self._map[0])): if self._map[y][x] == '1': self._object_matrix[y][x] = Wall.getInstance() # enumerateLevel # enumerates levels character values by convention # corresponding wall floor class is +/- 60 # floors 1('.'): 1 - 20 # floors 2(','): 21 - 40 # floors 3('`'): 41 - 60 # walls 1('1'): 61 - 80 # walls 2('2'): 81 - 100 # walls 3('3'): 101 - 120 # warp: 0 # nullspace('_'): -1 def enumerateLevel(self): for i in range(len(self._map)): for j in range(len(self._map[0])): if self._map[i][j] == '_': # set null self._map[i][j] = -1 elif self._map[i][j] == '.': # set floors self._map[i][j] = 1 rand = random.randint(1, 400) if rand > 50: self._map[i][j] = 1 elif rand > 45: self._map[i][j] = 2 elif rand > 40: self._map[i][j] = 3 elif rand > 35: self._map[i][j] = 4 elif rand > 30: self._map[i][j] = 5 elif rand > 25: self._map[i][j] = 6 elif rand > 20: self._map[i][j] = 7 elif rand > 15: self._map[i][j] = 8 else: self._map[i][j] = 9 elif self._map[i][j] == ',': self._map[i][j] = 21 elif self._map[i][j] == '`': self._map[i][j] = 41 elif self._map[i][j] == '1': # set walls self._map[i][j] = 61 elif self._map[i][j] == '2': self._map[i][j] = 81 elif self._map[i][j] == '3': self._map[i][j] = 101 # CLASS LevelWarp # handles changing the level and moving player to correct location class LevelWarp(): def getRef(self): return self def toDict(self): return { 'type':'warp','next_level':self.next_level, 'x_pos':self.x_pos, 'y_pos':self.y_pos, 'x_dest':self.x_dest, 'y_dest':self.y_dest } def __init__(self, json_obj): if type(json_obj) == dict: self.image = load_image('warp.png') self.next_level = json_obj['next_level'] self.x_pos = json_obj['x_pos'] self.y_pos = json_obj['y_pos'] self.x_dest = json_obj['x_dest'] self.y_dest = json_obj['y_dest'] else: raise Exception('non dictionary or json type provided') # CLASS Game # stores screen resolution and background color # initializes the players starting location # define control and drawing methods # TODO: add wall member as array of tiles # TODO: add floor member as array of tiles class Game: current_level = None current_map = None player = None dark_grey = (20, 12, 28) white = (223, 239, 215) blue = (89, 125, 207) background_color = dark_grey # screen size (in 32*32 squares) needs to be odd numbers because of player in center screen_size = (45, 23) screen_resolution = (screen_size[0] * 32, screen_size[1] * 32) screen_x_buffer = int((screen_size[0]-1)/2) screen_y_buffer = int((screen_size[1]-1)/2) key_delay = 200 key_repeat = 50 current_map = [] current_object_map = [] os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (0, 32) def
(self): pygame.init() self.font_1 = pygame.font.Font('fonts/victor-pixel.ttf', 32) pygame.key.set_repeat(self.key_delay, self.key_repeat) flags = DOUBLEBUF | HWACCEL self.screen = pygame.display.set_mode(self.screen_resolution,flags) pygame.event.set_allowed([QUIT, KEYDOWN, KEYUP]) # setup display and background color/size pygame.display.set_icon(pygame.image.load('graphics/icon.png')) pygame.display.set_caption('A simple roguelike') self.background = pygame.Surface(self.screen_resolution) self.background.fill(self.background_color) # initialize game to first level current_level = Level() current_level.loadLevel('town') # make the wall and floor class self.floor_1 = [] self.floor_1.append(load_image(os.path.join(graphics_dir, "floor_1_1.png"))) self.floor_1.append(load_image(os.path.join(graphics_dir, "floor_1_2.png"))) self.floor_1.append(load_image(os.path.join(graphics_dir, "floor_1_3.png"))) self.floor_1.append(load_image(os.path.join(graphics_dir, "floor_1_4.png"))) self.floor_1.append(load_image(os.path.join(graphics_dir, "floor_1_5.png"))) self.floor_1.append(load_image(os.path.join(graphics_dir, "floor_1_6.png"))) self.floor_1.append(load_image(os.path.join(graphics_dir, "floor_1_7.png"))) self.floor_1.append(load_image(os.path.join(graphics_dir, "floor_1_8.png"))) self.floor_1.append(load_image(os.path.join(graphics_dir, "floor_1_9.png"))) self.floor_2 = [] self.floor_2.append(load_image(os.path.join(graphics_dir, "floor_2.png"))) self.wall = [] self.wall.append(load_image(os.path.join(graphics_dir, "wall_1.png"))) self.wall.append(load_image(os.path.join(graphics_dir, "wall_2.png"))) self.warp = load_image(os.path.join(graphics_dir, "warp.png")) # CONTROL TICK # this function will handle all input functions # returns false when game is ready to quit def control_tick(self): if joystick_count > 0: joystick = pygame.joystick.Joystick(0) joystick.init() # pos_east = self.current_map[self.player.y_pos][self.player.x_pos + 1] # pos_west = self.current_map[self.player.y_pos][self.player.x_pos - 1] # pos_north = self.current_map[self.player.y_pos - 1][self.player.x_pos] # pos_south = self.current_map[self.player.y_pos + 1][self.player.x_pos] # get enemies in close proximity and forbid moving in those directions # need to detect enemies that are adjacent to player # TODO: this is linear time and need to be improved # for npc in self.current_level.n
__init__
identifier_name
mod.rs
_specs!` macro to generate such arrays. Complex(&'static [&'static dyn UntypedProperty]), // /// Same a `Complex`, but with a callback function used to set the default block state. // ComplexWithDefault(&'static [&'static dyn UntypedProperty], fn(&BlockState) -> &BlockState) } impl Block { /// Construct a new block, this method should be used to define blocks statically. /// The preferred way of defining static blocks is to use the `blocks!` macro. pub const fn new(name: &'static str, spec: BlockSpec) -> Self { Self { name, spec, states: OnceCell::new() } } #[inline] pub fn get_name(&self) -> &'static str { self.name } #[inline] pub fn get_key(&'static self) -> BlockKey { OpaquePtr::new(self) } fn get_storage(&'static self) -> &'static BlockStorage { self.states.get_or_init(|| self.make_storage()) } fn make_storage(&'static self) -> BlockStorage { // Internal function to generate new BlockStorage from properties, // if there are no properties, BlockStorage::Single is returned. fn new_storage(properties: &'static [&'static dyn UntypedProperty]) -> BlockStorage { if properties.is_empty() { BlockStorage::Single(BlockState::build_singleton()) } else { let ( properties, states ) = BlockState::build_complex(properties); BlockStorage::Complex { states, properties, default_state_index: 0 } } } // let mut default_supplier = None; let mut storage = match self.spec { BlockSpec::Single => BlockStorage::Single(BlockState::build_singleton()), BlockSpec::Complex(properties) => new_storage(properties), /*BlockSpec::ComplexWithDefault(properties, fun) => { default_supplier = Some(fun); new_storage(properties) }*/ }; let block_ptr = NonNull::from(self); match &mut storage { BlockStorage::Single( state) => { state.set_block(block_ptr); }, BlockStorage::Complex { states, /*default_state_index,*/ .. } => { for state in states { state.set_block(block_ptr); } /*if let Some(default_supplier) = default_supplier { *default_state_index = default_supplier(&states[0]).get_index() as usize; }*/ } } storage } #[inline] pub fn get_default_state(&'static self) -> &'static BlockState { self.get_storage().get_default_state() } #[inline] pub fn get_states(&'static self) -> &'static [BlockState] { self.get_storage().get_states() } } impl PartialEq for &'static Block { fn eq(&self, other: &Self) -> bool { std::ptr::eq(*self, *other) } } impl Eq for &'static Block {} impl BlockStorage { pub fn get_default_state(&self) -> &BlockState { match self { BlockStorage::Single(state) => state, BlockStorage::Complex { states, default_state_index, .. } => &states[*default_state_index] } } pub fn get_states(&self) -> &[BlockState] { match self { BlockStorage::Single(state) => std::slice::from_ref(state), BlockStorage::Complex { states, .. } => &states[..] } } /// Internal method for neighbor and values resolution of `BlockState`. fn get_shared_prop(&self, name: &str) -> Option<&SharedProperty> { match self { BlockStorage::Single(_) => None, BlockStorage::Complex { properties, .. } => properties.get(name) } } /// Internal method for Debug implementation of `BlockState` and values iteration. /// None is returned if there is no properties and the block has a single state. fn get_shared_props(&self) -> Option<&HashMap<&'static str, SharedProperty>> { match self { BlockStorage::Single(_) => None, BlockStorage::Complex { properties, .. } => Some(properties) } } /// Internal method for `BlockState` to get a state a specific index. fn get_state_unchecked(&self, index: usize) -> &BlockState { match self { BlockStorage::Single(state) => { debug_assert!(index == 0, "index != 0 with BlockStorage::Single"); state }, BlockStorage::Complex { states, .. } => &states[index] } } } /// This is a global blocks palette, it is used in chunk storage to store block states. /// It allows you to register individual blocks in it as well as static blocks arrays /// defined using the macro `blocks!`. pub struct GlobalBlocks { next_sid: u32, /// Each registered block is mapped to a tuple (index, sid), where index is the index of /// insertion of the block and sid being the save ID of the first state of this block. block_to_indices: HashMap<BlockKey, (usize, u32)>, /// A vector storing references to each block state, the index of each state is called /// its "save ID". ordered_states: Vec<&'static BlockState>, /// A mapping of block's names to them. name_to_blocks: HashMap<&'static str, &'static Block>, /// Contains stores of each tag type. For each tag, either small of big stores are used. tag_stores: HashMap<TagTypeKey, TagStore> } impl GlobalBlocks { pub fn new() -> Self { Self { next_sid: 0, block_to_indices: HashMap::new(), ordered_states: Vec::new(), name_to_blocks: HashMap::new(), tag_stores: HashMap::new() } } /// A simple constructor to directly call `register_all` with given blocks slice. pub fn with_all(slice: &[&'static Block]) -> Result<Self, ()> { let mut blocks = Self::new(); blocks.register_all(slice)?; Ok(blocks) } /// Register a single block to this palette, returns `Err` if no more save ID (SID) is /// available, `Ok` is returned if successful, if a block was already in the palette /// it also returns `Ok`. pub fn register(&mut self, block: &'static Block) -> Result<(), ()> { let states = block.get_states(); let states_count = states.len(); let sid = self.next_sid; let idx = self.block_to_indices.len(); let next_sid = sid.checked_add(states_count as u32).ok_or(())?; for store in self.tag_stores.values_mut() { if let TagStore::Big(store) = store { store.push(false); } } if self.block_to_indices.insert(block.get_key(), (idx, sid)).is_none() { self.next_sid = next_sid; self.name_to_blocks.insert(block.name, block); self.ordered_states.reserve(states_count); for state in states { self.ordered_states.push(state); } } Ok(()) } /// An optimized way to call `register` multiple times for each given block, /// the returned follow the same rules as `register`, if an error happens, it /// return without and previous added blocks are kept. pub fn register_all(&mut self, slice: &[&'static Block]) -> Result<(), ()> { let count = slice.len(); self.block_to_indices.reserve(count); self.name_to_blocks.reserve(count); for store in self.tag_stores.values_mut() { if let TagStore::Big(store) = store { store.reserve(count); } } for &block in slice { self.register(block)?; } Ok(()) }
/// Get the block state from the given save ID. pub fn get_state_from(&self, sid: u32) -> Option<&'static BlockState> { self.ordered_states.get(sid as usize).copied() } /// Get the default state from the given block name. pub fn get_block_from_name(&self, name: &str) -> Option<&'static Block> { self.name_to_blocks.get(name).cloned() } /// Return true if the palette contains the given block. pub fn has_block(&self, block: &'static Block) -> bool { self.block_to_indices.contains_key(&block.get_key()) } /// Return true if the palette contains the given block state. pub fn has_state(&self, state: &'static BlockState) -> bool { self.has_block(state.get_block()) } /// Check if the given state is registered in this palette, `Ok` is returned if true, in /// the other case `Err` is returned with the error created by the given `err` closure. pub fn check_state<E>(&self, state: &'static BlockState, err: impl Fn
/// Get the save ID from the given state. pub fn get_sid_from(&self, state: &'static BlockState) -> Option<u32> { let (_, block_offset) = *self.block_to_indices.get(&state.get_block().get_key())?; Some(block_offset + state.get_index() as u32) }
random_line_split
mod.rs
], fn(&BlockState) -> &BlockState) } impl Block { /// Construct a new block, this method should be used to define blocks statically. /// The preferred way of defining static blocks is to use the `blocks!` macro. pub const fn new(name: &'static str, spec: BlockSpec) -> Self { Self { name, spec, states: OnceCell::new() } } #[inline] pub fn get_name(&self) -> &'static str { self.name } #[inline] pub fn get_key(&'static self) -> BlockKey { OpaquePtr::new(self) } fn get_storage(&'static self) -> &'static BlockStorage { self.states.get_or_init(|| self.make_storage()) } fn make_storage(&'static self) -> BlockStorage { // Internal function to generate new BlockStorage from properties, // if there are no properties, BlockStorage::Single is returned. fn new_storage(properties: &'static [&'static dyn UntypedProperty]) -> BlockStorage { if properties.is_empty() { BlockStorage::Single(BlockState::build_singleton()) } else { let ( properties, states ) = BlockState::build_complex(properties); BlockStorage::Complex { states, properties, default_state_index: 0 } } } // let mut default_supplier = None; let mut storage = match self.spec { BlockSpec::Single => BlockStorage::Single(BlockState::build_singleton()), BlockSpec::Complex(properties) => new_storage(properties), /*BlockSpec::ComplexWithDefault(properties, fun) => { default_supplier = Some(fun); new_storage(properties) }*/ }; let block_ptr = NonNull::from(self); match &mut storage { BlockStorage::Single( state) => { state.set_block(block_ptr); }, BlockStorage::Complex { states, /*default_state_index,*/ .. } => { for state in states { state.set_block(block_ptr); } /*if let Some(default_supplier) = default_supplier { *default_state_index = default_supplier(&states[0]).get_index() as usize; }*/ } } storage } #[inline] pub fn get_default_state(&'static self) -> &'static BlockState { self.get_storage().get_default_state() } #[inline] pub fn get_states(&'static self) -> &'static [BlockState] { self.get_storage().get_states() } } impl PartialEq for &'static Block { fn eq(&self, other: &Self) -> bool { std::ptr::eq(*self, *other) } } impl Eq for &'static Block {} impl BlockStorage { pub fn get_default_state(&self) -> &BlockState { match self { BlockStorage::Single(state) => state, BlockStorage::Complex { states, default_state_index, .. } => &states[*default_state_index] } } pub fn get_states(&self) -> &[BlockState] { match self { BlockStorage::Single(state) => std::slice::from_ref(state), BlockStorage::Complex { states, .. } => &states[..] } } /// Internal method for neighbor and values resolution of `BlockState`. fn get_shared_prop(&self, name: &str) -> Option<&SharedProperty> { match self { BlockStorage::Single(_) => None, BlockStorage::Complex { properties, .. } => properties.get(name) } } /// Internal method for Debug implementation of `BlockState` and values iteration. /// None is returned if there is no properties and the block has a single state. fn get_shared_props(&self) -> Option<&HashMap<&'static str, SharedProperty>> { match self { BlockStorage::Single(_) => None, BlockStorage::Complex { properties, .. } => Some(properties) } } /// Internal method for `BlockState` to get a state a specific index. fn get_state_unchecked(&self, index: usize) -> &BlockState { match self { BlockStorage::Single(state) => { debug_assert!(index == 0, "index != 0 with BlockStorage::Single"); state }, BlockStorage::Complex { states, .. } => &states[index] } } } /// This is a global blocks palette, it is used in chunk storage to store block states. /// It allows you to register individual blocks in it as well as static blocks arrays /// defined using the macro `blocks!`. pub struct GlobalBlocks { next_sid: u32, /// Each registered block is mapped to a tuple (index, sid), where index is the index of /// insertion of the block and sid being the save ID of the first state of this block. block_to_indices: HashMap<BlockKey, (usize, u32)>, /// A vector storing references to each block state, the index of each state is called /// its "save ID". ordered_states: Vec<&'static BlockState>, /// A mapping of block's names to them. name_to_blocks: HashMap<&'static str, &'static Block>, /// Contains stores of each tag type. For each tag, either small of big stores are used. tag_stores: HashMap<TagTypeKey, TagStore> } impl GlobalBlocks { pub fn new() -> Self { Self { next_sid: 0, block_to_indices: HashMap::new(), ordered_states: Vec::new(), name_to_blocks: HashMap::new(), tag_stores: HashMap::new() } } /// A simple constructor to directly call `register_all` with given blocks slice. pub fn with_all(slice: &[&'static Block]) -> Result<Self, ()> { let mut blocks = Self::new(); blocks.register_all(slice)?; Ok(blocks) } /// Register a single block to this palette, returns `Err` if no more save ID (SID) is /// available, `Ok` is returned if successful, if a block was already in the palette /// it also returns `Ok`. pub fn register(&mut self, block: &'static Block) -> Result<(), ()> { let states = block.get_states(); let states_count = states.len(); let sid = self.next_sid; let idx = self.block_to_indices.len(); let next_sid = sid.checked_add(states_count as u32).ok_or(())?; for store in self.tag_stores.values_mut() { if let TagStore::Big(store) = store { store.push(false); } } if self.block_to_indices.insert(block.get_key(), (idx, sid)).is_none() { self.next_sid = next_sid; self.name_to_blocks.insert(block.name, block); self.ordered_states.reserve(states_count); for state in states { self.ordered_states.push(state); } } Ok(()) } /// An optimized way to call `register` multiple times for each given block, /// the returned follow the same rules as `register`, if an error happens, it /// return without and previous added blocks are kept. pub fn register_all(&mut self, slice: &[&'static Block]) -> Result<(), ()> { let count = slice.len(); self.block_to_indices.reserve(count); self.name_to_blocks.reserve(count); for store in self.tag_stores.values_mut() { if let TagStore::Big(store) = store { store.reserve(count); } } for &block in slice { self.register(block)?; } Ok(()) } /// Get the save ID from the given state. pub fn get_sid_from(&self, state: &'static BlockState) -> Option<u32> { let (_, block_offset) = *self.block_to_indices.get(&state.get_block().get_key())?; Some(block_offset + state.get_index() as u32) } /// Get the block state from the given save ID. pub fn get_state_from(&self, sid: u32) -> Option<&'static BlockState> { self.ordered_states.get(sid as usize).copied() } /// Get the default state from the given block name. pub fn get_block_from_name(&self, name: &str) -> Option<&'static Block> { self.name_to_blocks.get(name).cloned() } /// Return true if the palette contains the given block. pub fn has_block(&self, block: &'static Block) -> bool { self.block_to_indices.contains_key(&block.get_key()) } /// Return true if the palette contains the given block state. pub fn has_state(&self, state: &'static BlockState) -> bool { self.has_block(state.get_block()) } /// Check if the given state is registered in this palette, `Ok` is returned if true, in /// the other case `Err` is returned with the error created by the given `err` closure. pub fn check_state<E>(&self, state: &'static BlockState, err: impl FnOnce() -> E) -> Result<&'static BlockState, E> { if self.has_state(state) { Ok(state) } else { Err(err()) } } /// Register a tag type that will be later possible to set to blocks. pub fn
register_tag_type
identifier_name
mod.rs
_complex(properties); BlockStorage::Complex { states, properties, default_state_index: 0 } } } // let mut default_supplier = None; let mut storage = match self.spec { BlockSpec::Single => BlockStorage::Single(BlockState::build_singleton()), BlockSpec::Complex(properties) => new_storage(properties), /*BlockSpec::ComplexWithDefault(properties, fun) => { default_supplier = Some(fun); new_storage(properties) }*/ }; let block_ptr = NonNull::from(self); match &mut storage { BlockStorage::Single( state) => { state.set_block(block_ptr); }, BlockStorage::Complex { states, /*default_state_index,*/ .. } => { for state in states { state.set_block(block_ptr); } /*if let Some(default_supplier) = default_supplier { *default_state_index = default_supplier(&states[0]).get_index() as usize; }*/ } } storage } #[inline] pub fn get_default_state(&'static self) -> &'static BlockState { self.get_storage().get_default_state() } #[inline] pub fn get_states(&'static self) -> &'static [BlockState] { self.get_storage().get_states() } } impl PartialEq for &'static Block { fn eq(&self, other: &Self) -> bool { std::ptr::eq(*self, *other) } } impl Eq for &'static Block {} impl BlockStorage { pub fn get_default_state(&self) -> &BlockState { match self { BlockStorage::Single(state) => state, BlockStorage::Complex { states, default_state_index, .. } => &states[*default_state_index] } } pub fn get_states(&self) -> &[BlockState] { match self { BlockStorage::Single(state) => std::slice::from_ref(state), BlockStorage::Complex { states, .. } => &states[..] } } /// Internal method for neighbor and values resolution of `BlockState`. fn get_shared_prop(&self, name: &str) -> Option<&SharedProperty> { match self { BlockStorage::Single(_) => None, BlockStorage::Complex { properties, .. } => properties.get(name) } } /// Internal method for Debug implementation of `BlockState` and values iteration. /// None is returned if there is no properties and the block has a single state. fn get_shared_props(&self) -> Option<&HashMap<&'static str, SharedProperty>> { match self { BlockStorage::Single(_) => None, BlockStorage::Complex { properties, .. } => Some(properties) } } /// Internal method for `BlockState` to get a state a specific index. fn get_state_unchecked(&self, index: usize) -> &BlockState { match self { BlockStorage::Single(state) => { debug_assert!(index == 0, "index != 0 with BlockStorage::Single"); state }, BlockStorage::Complex { states, .. } => &states[index] } } } /// This is a global blocks palette, it is used in chunk storage to store block states. /// It allows you to register individual blocks in it as well as static blocks arrays /// defined using the macro `blocks!`. pub struct GlobalBlocks { next_sid: u32, /// Each registered block is mapped to a tuple (index, sid), where index is the index of /// insertion of the block and sid being the save ID of the first state of this block. block_to_indices: HashMap<BlockKey, (usize, u32)>, /// A vector storing references to each block state, the index of each state is called /// its "save ID". ordered_states: Vec<&'static BlockState>, /// A mapping of block's names to them. name_to_blocks: HashMap<&'static str, &'static Block>, /// Contains stores of each tag type. For each tag, either small of big stores are used. tag_stores: HashMap<TagTypeKey, TagStore> } impl GlobalBlocks { pub fn new() -> Self { Self { next_sid: 0, block_to_indices: HashMap::new(), ordered_states: Vec::new(), name_to_blocks: HashMap::new(), tag_stores: HashMap::new() } } /// A simple constructor to directly call `register_all` with given blocks slice. pub fn with_all(slice: &[&'static Block]) -> Result<Self, ()> { let mut blocks = Self::new(); blocks.register_all(slice)?; Ok(blocks) } /// Register a single block to this palette, returns `Err` if no more save ID (SID) is /// available, `Ok` is returned if successful, if a block was already in the palette /// it also returns `Ok`. pub fn register(&mut self, block: &'static Block) -> Result<(), ()> { let states = block.get_states(); let states_count = states.len(); let sid = self.next_sid; let idx = self.block_to_indices.len(); let next_sid = sid.checked_add(states_count as u32).ok_or(())?; for store in self.tag_stores.values_mut() { if let TagStore::Big(store) = store { store.push(false); } } if self.block_to_indices.insert(block.get_key(), (idx, sid)).is_none() { self.next_sid = next_sid; self.name_to_blocks.insert(block.name, block); self.ordered_states.reserve(states_count); for state in states { self.ordered_states.push(state); } } Ok(()) } /// An optimized way to call `register` multiple times for each given block, /// the returned follow the same rules as `register`, if an error happens, it /// return without and previous added blocks are kept. pub fn register_all(&mut self, slice: &[&'static Block]) -> Result<(), ()> { let count = slice.len(); self.block_to_indices.reserve(count); self.name_to_blocks.reserve(count); for store in self.tag_stores.values_mut() { if let TagStore::Big(store) = store { store.reserve(count); } } for &block in slice { self.register(block)?; } Ok(()) } /// Get the save ID from the given state. pub fn get_sid_from(&self, state: &'static BlockState) -> Option<u32> { let (_, block_offset) = *self.block_to_indices.get(&state.get_block().get_key())?; Some(block_offset + state.get_index() as u32) } /// Get the block state from the given save ID. pub fn get_state_from(&self, sid: u32) -> Option<&'static BlockState> { self.ordered_states.get(sid as usize).copied() } /// Get the default state from the given block name. pub fn get_block_from_name(&self, name: &str) -> Option<&'static Block> { self.name_to_blocks.get(name).cloned() } /// Return true if the palette contains the given block. pub fn has_block(&self, block: &'static Block) -> bool { self.block_to_indices.contains_key(&block.get_key()) } /// Return true if the palette contains the given block state. pub fn has_state(&self, state: &'static BlockState) -> bool { self.has_block(state.get_block()) } /// Check if the given state is registered in this palette, `Ok` is returned if true, in /// the other case `Err` is returned with the error created by the given `err` closure. pub fn check_state<E>(&self, state: &'static BlockState, err: impl FnOnce() -> E) -> Result<&'static BlockState, E> { if self.has_state(state) { Ok(state) } else { Err(err()) } } /// Register a tag type that will be later possible to set to blocks. pub fn register_tag_type(&mut self, tag_type: &'static TagType) { self.tag_stores.insert(tag_type.get_key(), TagStore::Small(Vec::new())); } /// Set or unset a tag to some blocks. pub fn set_blocks_tag<I>(&mut self, tag_type: &'static TagType, enabled: bool, blocks: I) -> Result<(), ()> where I: IntoIterator<Item = &'static Block>
{ const MAX_SMALL_LEN: usize = 8; let store = self.tag_stores.get_mut(&tag_type.get_key()).ok_or(())?; for block in blocks { if let TagStore::Small(vec) = store { let idx = vec.iter().position(move |&b| b == block); if enabled { if idx.is_none() { if vec.len() >= MAX_SMALL_LEN { // If the small vector is too big, migrate to a big bit vector. let mut new_vec = BitVec::from_elem(self.block_to_indices.len(), false); for old_block in vec { let (idx, _) = *self.block_to_indices.get(&old_block.get_key()).ok_or(())?; new_vec.set(idx, true); } *store = TagStore::Big(new_vec);
identifier_body
convert.py
1 :].replace(" ", "").strip() ) if re.match(reg_str, new_text_test) and el_text.lower().startswith(value_name): return el_text[: len(value_name)] + "\u2028" + v else: el_new = get_replacement_mapping_value(k, v, el_text) if el_new: return el_new return "" def get_suit_tags_and_key(key: str) -> Tuple[List[str], str]: # Short tags to match the suits in the template documents suit_tags: List[str] = [] suit_key: str = "" if key == "suits": suit_tags = ["VE", "AT", "SM", "AZ", "CR", "CO", "WC"] suit_key = "cards" elif key == "paragraphs": suit_tags = ["Common"] suit_key = "sentences" return suit_tags, suit_key def get_tag_for_suit_name(suit: Dict[str, Any], suit_tag: str) -> Dict[str, str]: data: Dict[str, str] = {} logging.debug(f" --- suit_tag = {suit_tag}, suit[name] = {suit['name']}") if convert_vars.making_template: data[suit["name"]] = "${{{}}}".format(suit_tag + "_suit") if suit_tag == "WC": data["Joker"] = "${WC_Joker}" else: data["${{{}}}".format(suit_tag + "_suit")] = suit["name"] if suit_tag == "WC": data["${WC_Joker}"] = "Joker" logging.debug(f" --- making_template {convert_vars.making_template}. suit_tag dict = {data}") return data def get_template_doc(file_type: str, style: str = "static") -> str: template_doc: str args_input_file: str = convert_vars.args.inputfile sfile_ext = file_type.replace("pdf", "docx") # Pdf output uses docx source file if args_input_file: # Input file was specified if os.path.isabs(args_input_file): template_doc = args_input_file elif os.path.isfile(convert_vars.BASE_PATH + os.sep + args_input_file): template_doc = os.path.normpath(convert_vars.BASE_PATH + os.sep + args_input_file) elif os.path.isfile(convert_vars.BASE_PATH + os.sep + args_input_file.replace(".." + os.sep, "")): template_doc = os.path.normpath( convert_vars.BASE_PATH + os.sep + args_input_file.replace(".." + os.sep, "") ) elif args_input_file.find("..") == -1 and os.path.isfile( convert_vars.BASE_PATH + os.sep + ".." + os.sep + args_input_file ): template_doc = os.path.normpath(convert_vars.BASE_PATH + os.sep + ".." + os.sep + args_input_file) elif os.path.isfile(convert_vars.BASE_PATH + os.sep + args_input_file.replace("scripts" + os.sep, "")): template_doc = os.path.normpath( convert_vars.BASE_PATH + os.sep + args_input_file.replace("scripts" + os.sep, "") ) else: template_doc = args_input_file logging.debug(f" --- Template_doc NOT found. Input File = {args_input_file}") else: # No input file specified - using defaults if convert_vars.making_template: template_doc = os.sep.join( [convert_vars.BASE_PATH, "resources", "originals", "owasp_cornucopia_en_static." + sfile_ext] ) else: template_doc = os.path.normpath( convert_vars.BASE_PATH + os.sep + convert_vars.DEFAULT_TEMPLATE_FILENAME + "_" + style + "." + sfile_ext ) template_doc = template_doc.replace("\\ ", " ") if os.path.isfile(template_doc): template_doc = check_fix_file_extension(template_doc, sfile_ext) logging.debug(f" --- Returning template_doc = {template_doc}") return template_doc else: logging.error(f"Source file not found: {template_doc}. Please ensure file exists and try again.") return "None" def get_valid_file_types() -> List[str]: if not convert_vars.args.outputfiletype: file_type = os.path.splitext(os.path.basename(convert_vars.args.outputfile))[1].strip(".") if file_type in ("", None): file_type = "docx" return [file_type] if convert_vars.args.outputfiletype.lower() == "pdf": if convert_vars.can_convert_to_pdf: return ["pdf"] else: logging.error("PDF output selected but currently unable to output PDF on this OS.") return [] if convert_vars.args.outputfiletype.lower() == "all": file_types = [] for file_type in convert_vars.FILETYPE_CHOICES: if file_type != "all" and (file_type != "pdf" or convert_vars.can_convert_to_pdf): file_types.append(file_type) return file_types if convert_vars.args.outputfiletype.lower() in convert_vars.FILETYPE_CHOICES: return [convert_vars.args.outputfiletype.lower()] return [] def get_valid_language_choices() -> List[str]: languages = [] if convert_vars.args.language.lower() == "all": for language in convert_vars.LANGUAGE_CHOICES: if language not in ("all", "template"): languages.append(language) elif convert_vars.args.language == "": languages.append("en") else: languages.append(convert_vars.args.language) return languages def get_valid_styles() -> List[str]: styles = [] if convert_vars.args.style.lower() == "all": for style in convert_vars.STYLE_CHOICES: if style != "all": styles.append(style) elif convert_vars.args.style == "": styles.append("static") else: styles.append(convert_vars.args.style) return styles def group_number_ranges(data: List[str]) -> List[str]: if len(data) < 2 or len([s for s in data if not s.isnumeric()]): return data list_ranges: List[str] = [] data_numbers = [int(s) for s in data] for k, g in groupby(enumerate(data_numbers), lambda x: x[0] - x[1]): group: List[int] = list(map(itemgetter(1), g)) group = list(map(int, group)) if group[0] == group[-1]: list_ranges.append(str(group[0])) else: list_ranges.append(str(group[0]) + "-" + str(group[-1])) return list_ranges def save_docx_file(doc: docx.Document, output_file: str) -> None: ensure_folder_exists(os.path.dirname(output_file)) doc.save(output_file) def save_idml_file(template_doc: str, language_dict: Dict[str, str], output_file: str) -> None: # Get the output path and temp output path to put the temp xml files output_path = convert_vars.BASE_PATH + os.sep + "output" temp_output_path = output_path + os.sep + "temp" # Ensure the output folder and temp output folder exist ensure_folder_exists(temp_output_path) logging.debug(" --- temp_folder for extraction of xml files = " + str(temp_output_path)) # Unzip source xml files and place in temp output folder with zipfile.ZipFile(template_doc) as idml_archive: idml_archive.extractall(temp_output_path) logging.debug(" --- namelist of first few files in archive = " + str(idml_archive.namelist()[:5])) xml_files = get_files_from_of_type(temp_output_path, "xml") # Only Stories files have content to update for file in fnmatch.filter(xml_files, "*Stories*Story*"): if os.path.getsize(file) == 0: continue replace_text_in_xml_file(file, language_dict) # Zip the files as an idml file in output folder logging.debug(" --- finished replacing text in xml files. Now zipping into idml file") zip_dir(temp_output_path, output_file) # If not debugging, delete temp folder and files if not convert_vars.args.debug and os.path.exists(temp_output_path): shutil.rmtree(temp_output_path, ignore_errors=True) def save_qrcode_image(card_id: str, location_url: str = "https://copi.securedelivery.io/cards") -> None: output_file = os.sep.join([convert_vars.BASE_PATH, "resources", "images", card_id + ".png"]) ensure_folder_exists(os.path.dirname(output_file)) if os.path.exists(output_file): pass else: url = location_url + "/" + card_id img = pyqrcode.create(url) img.svg(output_file, scale=8) def set_can_convert_to_pdf() -> bool: operating_system: str = sys.platform.lower() can_convert = operating_system.find("win") != -1 or operating_system.find("darwin") != -1 convert_vars.can_convert_to_pdf = can_convert logging.debug(f" --- operating system = {operating_system}, can_convert_to_pdf = {convert_vars.can_convert_to_pdf}") return can_convert def set_logging() -> None: lo
gging.basicConfig( format="%(asctime)s %(filename)s | %(levelname)s | %(funcName)s | %(message)s", ) if convert_vars.args.debug: logging.getLogger().setLevel(logging.DEBUG) else: logging.getLogger().setLevel(logging.INFO)
identifier_body
convert.py
.debug(f" --- suit_key = {suit_key}") for suit, suit_tag in zip(input_data[key], suit_tags): logging.debug(f" --- suit [name] = {suit['name']}") logging.debug(f" --- suit_tag = {suit_tag}") tag_for_suit_name = get_tag_for_suit_name(suit, suit_tag) data.update(tag_for_suit_name) card_tag = "" for card in suit[suit_key]: for tag, text_output in card.items(): if tag == "value": continue full_tag = get_full_tag(suit_tag, card["value"], tag) # Add a translation for "Joker" if suit_tag == "WC" and tag == "value": full_tag = "${{{}}}".format("_".join([suit_tag, card_tag, tag])) # Mappings is sometimes loaded as a list. Convert to string if convert_vars.making_template: text1 = check_make_list_into_text(text_output, False) data[text1] = full_tag if mappings: data[text1.replace(", ", ",")] = full_tag text1 = check_make_list_into_text(text_output, True) data[text1] = full_tag else: data[full_tag] = check_make_list_into_text(text_output, True) if convert_vars.args.debug and not mappings: debug_txt = " --- Translation data showing First 4 (key: text):\n* " debug_txt += "\n* ".join(l1 + ": " + str(data[l1]) for l1 in list(data.keys())[:4]) logging.debug(debug_txt) debug_txt = " --- Translation data showing Last 4 (key: text):\n* " debug_txt += "\n* ".join(l1 + ": " + str(data[l1]) for l1 in list(data.keys())[-4:]) logging.debug(debug_txt) return data def get_replacement_mapping_value(k: str, v: str, el_text: str) -> str: reg_str: str = "^(OWASP SCP|OWASP ASVS|OWASP AppSensor|CAPEC|SAFECODE)\u2028" + k.replace("$", "\\$").strip() + "$" if re.match(reg_str, el_text.strip()): pretext = el_text[: el_text.find("\u2028")] v_new = v if len(v) + len(pretext) > 60: v_new = v.replace(", ", ",") if len(v_new) >= 34: v_split = v_new.find(",", 25 - len(pretext)) + 1 el_new = pretext + " " + v_new[:v_split] + "\u2028" + v_new[v_split:].strip() return el_new else: return el_text.replace(k, v) return "" def get_replacement_value_from_dict(el_text: str, replacement_values: List[Tuple[str, str]]) -> str: for k, v in replacement_values: k2: str = k.replace("'", "’").strip() v2: str = v.strip() if el_text == k: return v elif el_text.strip() == k2: return v2 elif el_text.lower() == k.lower(): return v elif el_text.strip().lower() == k2.lower(): return v2 elif convert_vars.making_template: reg_str = "^(OWASP SCP|OWASP ASVS|OWASP AppSensor|CAPEC|SAFECODE)\u2028" + k.replace(" ", "").strip() + "$" value_name = v[9:-1].replace("_", " ").lower().strip() new_text_test = ( el_text[: len(value_name)] + "\u2028" + el_text[len(value_name) + 1 :].replace(" ", "").strip() ) if re.match(reg_str, new_text_test) and el_text.lower().startswith(value_name): return el_text[: len(value_name)] + "\u2028" + v else: el_new = get_replacement_mapping_value(k, v, el_text) if el_new: return el_new return "" def get_suit_tags_and_key(key: str) -> Tuple[List[str], str]: # Short tags to match the suits in the template documents suit_tags: List[str] = [] suit_key: str = "" if key == "suits": suit_tags = ["VE", "AT", "SM", "AZ", "CR", "CO", "WC"] suit_key = "cards" elif key == "paragraphs": suit_tags = ["Common"] suit_key = "sentences" return suit_tags, suit_key def get_tag_for_suit_name(suit: Dict[str, Any], suit_tag: str) -> Dict[str, str]: data: Dict[str, str] = {} logging.debug(f" --- suit_tag = {suit_tag}, suit[name] = {suit['name']}") if convert_vars.making_template: data[suit["name"]] = "${{{}}}".format(suit_tag + "_suit") if suit_tag == "WC": data["Joker"] = "${WC_Joker}" else: data["${{{}}}".format(suit_tag + "_suit")] = suit["name"] if suit_tag == "WC": data["${WC_Joker}"] = "Joker" logging.debug(f" --- making_template {convert_vars.making_template}. suit_tag dict = {data}") return data def get_template_doc(file_type: str, style: str = "static") -> str: template_doc: str args_input_file: str = convert_vars.args.inputfile sfile_ext = file_type.replace("pdf", "docx") # Pdf output uses docx source file if args_input_file: # Input file was specified if os.path.isabs(args_input_file): template_doc = args_input_file elif os.path.isfile(convert_vars.BASE_PATH + os.sep + args_input_file): template_doc = os.path.normpath(convert_vars.BASE_PATH + os.sep + args_input_file) elif os.path.isfile(convert_vars.BASE_PATH + os.sep + args_input_file.replace(".." + os.sep, "")): template_doc = os.path.normpath( convert_vars.BASE_PATH + os.sep + args_input_file.replace(".." + os.sep, "") ) elif args_input_file.find("..") == -1 and os.path.isfile( convert_vars.BASE_PATH + os.sep + ".." + os.sep + args_input_file ): template_doc = os.path.normpath(convert_vars.BASE_PATH + os.sep + ".." + os.sep + args_input_file) elif os.path.isfile(convert_vars.BASE_PATH + os.sep + args_input_file.replace("scripts" + os.sep, "")): template_doc = os.path.normpath( convert_vars.BASE_PATH + os.sep + args_input_file.replace("scripts" + os.sep, "") ) else: template_doc = args_input_file logging.debug(f" --- Template_doc NOT found. Input File = {args_input_file}") else: # No input file specified - using defaults if convert_vars.making_template: template_doc = os.sep.join( [convert_vars.BASE_PATH, "resources", "originals", "owasp_cornucopia_en_static." + sfile_ext] ) else: template_doc = os.path.normpath( convert_vars.BASE_PATH + os.sep + convert_vars.DEFAULT_TEMPLATE_FILENAME + "_" + style + "." + sfile_ext ) template_doc = template_doc.replace("\\ ", " ") if os.path.isfile(template_doc): template_doc = check_fix_file_extension(template_doc, sfile_ext) logging.debug(f" --- Returning template_doc = {template_doc}") return template_doc else: logging.error(f"Source file not found: {template_doc}. Please ensure file exists and try again.") return "None" def get_valid_file_types() -> List[str]: if not convert_vars.args.outputfiletype: file_type = os.path.splitext(os.path.basename(convert_vars.args.outputfile))[1].strip(".") if file_type in ("", None): file_type = "docx" return [file_type] if convert_vars.args.outputfiletype.lower() == "pdf": if convert_vars.can_convert_to_pdf: return ["pdf"] else: logging.error("PDF output selected but currently unable to output PDF on this OS.") return [] if convert_vars.args.outputfiletype.lower() == "all": file_types = [] for file_type in convert_vars.FILETYPE_CHOICES: if file_type != "all" and (file_type != "pdf" or convert_vars.can_convert_to_pdf): file_types.append(file_type) return file_types if convert_vars.args.outputfiletype.lower() in convert_vars.FILETYPE_CHOICES: return [convert_vars.args.outputfiletype.lower()] return [] def get_valid_language_choices() -> List[str]: languages = [] if convert_vars.args.language.lower() == "all": for language in convert_vars.LANGUAGE_CHOICES: if language not in ("all", "template"): languages.append(language) elif convert_vars.args.language == "": languages.append("en") else: languages.append(convert_vars.args.language) return languages
def get_valid_styles() -> List[str]:
random_line_split
convert.py
URL will be suffixed with / and the card ID). " ), ) args = parser.parse_args(input_args) return args def get_card_ids(language_data: Union[Dict[Any, Any], List[Any]], key: str = "id") -> Generator[str, None, None]: if isinstance(language_data, dict): for k, v in language_data.items(): if k == key: yield v if isinstance(v, (dict, list)): yield from get_card_ids(v, key) elif isinstance(language_data, list): for d in language_data: yield from get_card_ids(d, key) def get_document_paragraphs(doc: docx) -> List[docx.Document]: paragraphs = list(doc.paragraphs) l1 = len(paragraphs) for table in doc.tables: paragraphs += get_paragraphs_from_table_in_doc(table) l2 = len(paragraphs) if not len(paragraphs): logging.error("No paragraphs found in doc") logging.debug(f" --- count doc paragraphs = {l1}, with table paragraphs = {l2}") return paragraphs def get_docx_document(docx_file: str) -> docx.Document: """Open the file and return the docx document.""" if os.path.isfile(docx_file): return docx.Document(docx_file) else: logging.error("Could not find file at: " + str(docx_file)) return docx.Document() def get_files_from_of_type(path: str, ext: str) -> List[str]: """Get a list of files from a specified folder recursively, that have the specified extension.""" files = [] for root, dirnames, filenames in os.walk(path): for filename in fnmatch.filter(filenames, "*." + str(ext)): files.append(os.path.join(root, filename)) if not files: logging.error("No language files found in folder: " + str(os.sep.join([convert_vars.BASE_PATH, "source"]))) logging.debug(f" --- found {len(files)} files of type {ext}. Showing first few:\n* " + str("\n* ".join(files[:3]))) return files def get_find_replace_list(meta: Dict[str, str]) -> List[Tuple[str, str]]: ll: List[Tuple[str, str]] = [ ("_type", "_" + meta["edition"].lower()), ("_edition", "_" + meta["edition"].lower()), ("_component", "_" + meta["component"].lower()), ("_language", "_" + meta["language"].lower()), ("_lang", "_" + meta["language"].lower()), ("_version", "_" + meta["version"].lower()), ("_ver", "_" + meta["version"].lower()), ] if not convert_vars.making_template: ll.append(("_template", "")) return ll def get_full_tag(suit_tag: str, card: str, tag: str) -> str: if suit_tag == "WC": full_tag = "${{{}}}".format("_".join([suit_tag, card, tag])) elif suit_tag == "Common": full_tag = "${{{}}}".format("_".join([suit_tag, card])) else: full_tag = "${{{}}}".format("_".join([suit_tag, suit_tag + card, tag])) return full_tag def get_mapping_dict(yaml_files: List[str]) -> Dict[str, str]: mapping_data: Dict[str, Dict[str, str]] = get_replacement_data(yaml_files, "mappings") if not mapping_data: return {} return get_replacement_dict(mapping_data, True) def get_meta_data(language_data: Dict[str, Dict[str, str]]) -> Dict[str, str]: meta = {} if "meta" in list(language_data.keys()): for key, value in language_data["meta"].items(): if key in ("edition", "component", "language", "version"): meta[key] = value return meta else: logging.error( "Could not find meta tag in the language data. " "Please ensure required language file is in the source folder." ) logging.debug(f" --- meta data = {meta}") return meta def get_paragraphs_from_table_in_doc(doc_table: docx.Document) -> List[docx.Document]: paragraphs: List[docx.Document] = [] for row in doc_table.rows: for cell in row.cells: for paragraph in cell.paragraphs: if len(paragraph.runs): paragraphs.append(paragraph) for t2 in cell.tables: paragraphs += get_paragraphs_from_table_in_doc(t2) return paragraphs def get_replacement_data( yaml_files: List[str], data_type: str = "translation", language: str = "" ) -> Dict[Any, Dict[Any, Any]]: """Get the raw data of the replacement text from correct yaml file""" data = {} logging.debug(f" --- Starting get_replacement_data() for data_type = {data_type} and language = {language}") if convert_vars.making_template: lang = "en" else: lang = language for file in yaml_files: if os.path.splitext(file)[1] in (".yaml", ".yml") and ( os.path.basename(file).find("-" + lang + ".") >= 0 or os.path.basename(file).find("-" + lang.replace("-", "_") + ".") >= 0 or os.path.basename(file).find("mappings") >= 0 ): with open(file, "r", encoding="utf-8") as f: try: data = yaml.load(f, Loader=yaml.BaseLoader) except yaml.YAMLError as e: logging.info(f"Error loading yaml file: {file}. Error = {e}") continue if data_type in ("translation", "translations") and ( (data["meta"]["language"].lower() == language) or (data["meta"]["language"].lower() == "en" and language == "template") ): logging.debug(" --- found source language file: " + os.path.split(file)[1]) break elif ( data_type in ("mapping", "mappings") and "meta" in data.keys() and "component" in data["meta"].keys() and data["meta"]["component"] == "mappings" ): logging.debug(" --- found mappings file: " + os.path.split(file)[1]) break else: logging.debug(" --- found source file: " + os.path.split(file)[1]) if "meta" in list(data.keys()): meta_keys = data["meta"].keys() logging.debug(f" --- data.keys() = {data.keys()}, data[meta].keys() = {meta_keys}") data = {} continue if not data or "suits" not in list(data.keys()): logging.error("Could not get language data from yaml " + os.path.split(file)[1]) logging.debug(f" --- Len = {len(data)}.") return data def get_replacement_dict(input_data: Dict[str, Any], mappings: bool = False) -> Dict[str, str]: """Loop through language file data and build up a find-replace dict""" data = {} for key in list(k for k in input_data.keys() if k != "meta"): suit_tags, suit_key = get_suit_tags_and_key(key) logging.debug(f" --- key = {key}.") logging.debug(f" --- suit_tags = {suit_tags}") logging.debug(f" --- suit_key = {suit_key}") for suit, suit_tag in zip(input_data[key], suit_tags): logging.debug(f" --- suit [name] = {suit['name']}") logging.debug(f" --- suit_tag = {suit_tag}") tag_for_suit_name = get_tag_for_suit_name(suit, suit_tag) data.update(tag_for_suit_name) card_tag = "" for card in suit[suit_key]: for tag, text_output in card.items(): if tag == "value": continue full_tag = get_full_tag(suit_tag, card["value"], tag) # Add a translation for "Joker" if suit_tag == "WC" and tag == "value": full_tag = "${{{}}}".format("_".join([suit_tag, card_tag, tag])) # Mappings is sometimes loaded as a list. Convert to string if convert_vars.making_template: text1 = check_make_list_into_text(text_output, False) data[text1] = full_tag if mappings: data[text1.replace(", ", ",")] = full_tag text1 = check_make_list_into_text(text_output, True) data[text1] = full_tag else: data[full_tag] = check_make_list_into_text(text_output, True) if convert_vars.args.debug and not mappings: debug_txt = " --- Translation data showing First 4 (key: text):\n* " debug_txt += "\n* ".join(l1 + ": " + str(data[l1]) for l1 in list(data.keys())[:4]) logging.debug(debug_txt) debug_txt = " --- Translation data showing Last 4 (key: text):\n* " debug_txt += "\n* ".join(l1 + ": " + str(data[l1]) for l1 in list(data.keys())[-4:]) logging.debug(debug_txt) return data def
get_replacement_mapping_value
identifier_name
convert.py
_en_static." + sfile_ext] ) else: template_doc = os.path.normpath( convert_vars.BASE_PATH + os.sep + convert_vars.DEFAULT_TEMPLATE_FILENAME + "_" + style + "." + sfile_ext ) template_doc = template_doc.replace("\\ ", " ") if os.path.isfile(template_doc): template_doc = check_fix_file_extension(template_doc, sfile_ext) logging.debug(f" --- Returning template_doc = {template_doc}") return template_doc else: logging.error(f"Source file not found: {template_doc}. Please ensure file exists and try again.") return "None" def get_valid_file_types() -> List[str]: if not convert_vars.args.outputfiletype: file_type = os.path.splitext(os.path.basename(convert_vars.args.outputfile))[1].strip(".") if file_type in ("", None): file_type = "docx" return [file_type] if convert_vars.args.outputfiletype.lower() == "pdf": if convert_vars.can_convert_to_pdf: return ["pdf"] else: logging.error("PDF output selected but currently unable to output PDF on this OS.") return [] if convert_vars.args.outputfiletype.lower() == "all": file_types = [] for file_type in convert_vars.FILETYPE_CHOICES: if file_type != "all" and (file_type != "pdf" or convert_vars.can_convert_to_pdf): file_types.append(file_type) return file_types if convert_vars.args.outputfiletype.lower() in convert_vars.FILETYPE_CHOICES: return [convert_vars.args.outputfiletype.lower()] return [] def get_valid_language_choices() -> List[str]: languages = [] if convert_vars.args.language.lower() == "all": for language in convert_vars.LANGUAGE_CHOICES: if language not in ("all", "template"): languages.append(language) elif convert_vars.args.language == "": languages.append("en") else: languages.append(convert_vars.args.language) return languages def get_valid_styles() -> List[str]: styles = [] if convert_vars.args.style.lower() == "all": for style in convert_vars.STYLE_CHOICES: if style != "all": styles.append(style) elif convert_vars.args.style == "": styles.append("static") else: styles.append(convert_vars.args.style) return styles def group_number_ranges(data: List[str]) -> List[str]: if len(data) < 2 or len([s for s in data if not s.isnumeric()]): return data list_ranges: List[str] = [] data_numbers = [int(s) for s in data] for k, g in groupby(enumerate(data_numbers), lambda x: x[0] - x[1]): group: List[int] = list(map(itemgetter(1), g)) group = list(map(int, group)) if group[0] == group[-1]: list_ranges.append(str(group[0])) else: list_ranges.append(str(group[0]) + "-" + str(group[-1])) return list_ranges def save_docx_file(doc: docx.Document, output_file: str) -> None: ensure_folder_exists(os.path.dirname(output_file)) doc.save(output_file) def save_idml_file(template_doc: str, language_dict: Dict[str, str], output_file: str) -> None: # Get the output path and temp output path to put the temp xml files output_path = convert_vars.BASE_PATH + os.sep + "output" temp_output_path = output_path + os.sep + "temp" # Ensure the output folder and temp output folder exist ensure_folder_exists(temp_output_path) logging.debug(" --- temp_folder for extraction of xml files = " + str(temp_output_path)) # Unzip source xml files and place in temp output folder with zipfile.ZipFile(template_doc) as idml_archive: idml_archive.extractall(temp_output_path) logging.debug(" --- namelist of first few files in archive = " + str(idml_archive.namelist()[:5])) xml_files = get_files_from_of_type(temp_output_path, "xml") # Only Stories files have content to update for file in fnmatch.filter(xml_files, "*Stories*Story*"): if os.path.getsize(file) == 0: continue replace_text_in_xml_file(file, language_dict) # Zip the files as an idml file in output folder logging.debug(" --- finished replacing text in xml files. Now zipping into idml file") zip_dir(temp_output_path, output_file) # If not debugging, delete temp folder and files if not convert_vars.args.debug and os.path.exists(temp_output_path): shutil.rmtree(temp_output_path, ignore_errors=True) def save_qrcode_image(card_id: str, location_url: str = "https://copi.securedelivery.io/cards") -> None: output_file = os.sep.join([convert_vars.BASE_PATH, "resources", "images", card_id + ".png"]) ensure_folder_exists(os.path.dirname(output_file)) if os.path.exists(output_file): pass else: url = location_url + "/" + card_id img = pyqrcode.create(url) img.svg(output_file, scale=8) def set_can_convert_to_pdf() -> bool: operating_system: str = sys.platform.lower() can_convert = operating_system.find("win") != -1 or operating_system.find("darwin") != -1 convert_vars.can_convert_to_pdf = can_convert logging.debug(f" --- operating system = {operating_system}, can_convert_to_pdf = {convert_vars.can_convert_to_pdf}") return can_convert def set_logging() -> None: logging.basicConfig( format="%(asctime)s %(filename)s | %(levelname)s | %(funcName)s | %(message)s", ) if convert_vars.args.debug: logging.getLogger().setLevel(logging.DEBUG) else: logging.getLogger().setLevel(logging.INFO) def sort_keys_longest_to_shortest(replacement_dict: Dict[str, str]) -> List[Tuple[str, str]]: new_list = list((k, v) for k, v in replacement_dict.items()) return sorted(new_list, key=lambda s: len(s[0]), reverse=True) def remove_short_keys(replacement_dict: Dict[str, str], min_length: int = 8) -> Dict[str, str]: data2: Dict[str, str] = {} for key, value in replacement_dict.items(): if len(key) >= min_length: data2[key] = value logging.debug( " --- Making template. Removed card_numbers. len replacement_dict = " f"{len(replacement_dict)}, len data2 = {len(data2)}" ) return data2 def rename_output_file(file_type: str, style: str, meta: Dict[str, str]) -> str: """Rename output file replacing place-holders from meta dict (edition, component, language, version).""" args_output_file: str = convert_vars.args.outputfile logging.debug(f" --- args_output_file = {args_output_file}") if args_output_file: # Output file is specified as an argument if os.path.isabs(args_output_file): output_filename = args_output_file else: output_filename = os.path.normpath(convert_vars.BASE_PATH + os.sep + args_output_file) else: # No output file specified - using default output_filename = os.path.normpath( convert_vars.BASE_PATH + os.sep + convert_vars.DEFAULT_OUTPUT_FILENAME + ("_template" if convert_vars.making_template else "") + "_" + style + "." + file_type.strip(".") ) logging.debug(f" --- output_filename before fix extension = {output_filename}") output_filename = check_fix_file_extension(output_filename, file_type) logging.debug(f" --- output_filename AFTER fix extension = {output_filename}") # Do the replacement of filename place-holders with meta data find_replace = get_find_replace_list(meta) f = os.path.basename(output_filename) for r in find_replace: f = f.replace(*r) output_filename = os.path.dirname(output_filename) + os.sep + f logging.debug(f" --- output_filename = {output_filename}") return output_filename def replace_docx_inline_text(doc: docx.Document, data: Dict[str, str]) -> docx.Document: """Replace the text in the docx document.""" logging.debug(" --- starting docx_replace") if convert_vars.making_template: replacement_values = sort_keys_longest_to_shortest(data) else: replacement_values = list(data.items()) paragraphs = get_document_paragraphs(doc) for p in paragraphs: runs_text = "".join(r.text for r in p.runs) if runs_text.strip() == "" or ( convert_vars.making_template and re.search(re.escape("${") + ".*" + re.escape("}"), runs_text) ): continue for key, val in replacement_values: replaced_key = False for i, run in enumerate(p.runs): if run.text.find(key) != -1: p.runs[i].text = run.text.replace(key, val) replaced_key = True runs_text = runs_text.replace(key, val) if not replaced_key: if runs_text.find(key) != -1: runs_text = runs_text.replace(key, val) for i, r in enumerate(p.runs): p.
runs[i].text = ""
conditional_block
lib.rs
/////////////////////////////////////////////////////////////////////////////// // TESTS /////////////////////////////////////////////////////////////////////////////// #[cfg(test)] mod tests { use super::*; use num_bigint::{Sign, ToBigInt}; #[test] fn should_hash_strings() { let str_claim = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."; let b64_hash = digest_string_claim(str_claim); assert_eq!(b64_hash, "iV5141xlrW8I217IitUHtoDC/gd/LMsgcF0zpDfUaiM="); } #[test] fn should_hash_hex_claims() { let hex_claim = "0x045a126cbbd3c66b6d542d40d91085e3f2b5db3bbc8cda0d59615deb08784e4f833e0bb082194790143c3d01cedb4a9663cb8c7bdaaad839cb794dd309213fcf30"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "nGOYvS4aqqUVAT9YjWcUzA89DlHPWaooNpBTStOaHRA="); let hex_claim = "0x049969c7741ade2e9f89f81d12080651038838e8089682158f3d892e57609b64e2137463c816e4d52f6688d490c35a0b8e524ac6d9722eed2616dbcaf676fc2578"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "j7jJlnBN73ORKWbNbVCHG9WkoqSr+IEKDwjcsb6N4xw="); let hex_claim = "0x049622878da186a8a31f4dc03454dbbc62365060458db174618218b51d5014fa56c8ea772234341ae326ce278091c39e30c02fa1f04792035d79311fe3283f1380"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "6CUGhnmKQchF6Ter05laVgQYcEWm0p2qlLzX24rk3Ck="); let hex_claim = "0x04e355263aa6cbc99d2fdd0898f5ed8630115ad54e9073c41a8aa0df6d75842d8b8309d0d26a95565996b17da48f8ddff704ebcd1d8a982dc5ba8be7458c677b17"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "k0UwNtWW4UQifisXuoDiO/QGRZNNTY7giWK1Nx/hoSo="); let hex_claim = "0x04020d62c94296539224b885c6cdf79d0c2dd437471425be26bf62ab522949f83f3eed34528b0b9a7fbe96e50ca85471c894e1aa819bbf12ff78ad07ce8b4117b2"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "5EhP0859lic41RIpIrnotv/BCR7v5nVcXsXkTXlbuhI="); let hex_claim = "0x046bd65449f336b888fc36c64708940da0d1c864a0ac46236f60b455841a4d15c9b815ed725093b3266aaca2f15210d14a1eadf34efeda3bd44a803fbf1590cfba"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "oseI7fM8wWIYslDUOXJne7AOiK+IpFL3q8MTqiZHWw8="); let hex_claim = "0x0412cf2bd4a9613ad988f7f008a5297b8e8c98df8759a2ef9d3dfae63b3870cfbb78d35789745f82710da61a61a9c06c6f6166bf1d5ce73f9416e6b67713001aa2"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "9Y3JcjUHZLGmENRQpnML/+TG2EbHWjU46h+LtT9sQi8="); let hex_claim = "0x04a2e6914db4a81ea9ec72e71b41cf88d4bc19ea54f29ae2beb3db8e4acf6531b5c163e58427831832b10fce899a030d12e82a398d4eeefe451c7e261fba973be4"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "Llx5F6lP/hbU6ZTT10Q5PF+7o1VdylvrolT8vSHJMAA="); let hex_claim = "0x041508189a6f1737f50dd2c603c1ded8a83f97073d33cbb317e7409c1487b8351aa2b89455cda61ce8ed3ba3c130372870b187239b900da8948a53ca3e02db9aaf"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "MyRpb4ZDTwtJNflc8ZbZdmKOf+fuZjUEZkgZMCmlKxw="); let hex_claim = "0x04f11597483032666b20ec51b27e1337577f63a5e1d5962575b555bf899380ae15482f031a297094b0c60980f3c4f1f7ad2346de5357ad82a6a3d4eef2bd1956c6"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "y
{ let mut claim_bytes = num.to_bytes_be().1; while claim_bytes.len() < 32 { claim_bytes = [&[0], &claim_bytes[..]].concat(); } claim_bytes }
identifier_body
lib.rs
() { let hex_claim = "0x045a126cbbd3c66b6d542d40d91085e3f2b5db3bbc8cda0d59615deb08784e4f833e0bb082194790143c3d01cedb4a9663cb8c7bdaaad839cb794dd309213fcf30"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "nGOYvS4aqqUVAT9YjWcUzA89DlHPWaooNpBTStOaHRA="); let hex_claim = "0x049969c7741ade2e9f89f81d12080651038838e8089682158f3d892e57609b64e2137463c816e4d52f6688d490c35a0b8e524ac6d9722eed2616dbcaf676fc2578"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "j7jJlnBN73ORKWbNbVCHG9WkoqSr+IEKDwjcsb6N4xw="); let hex_claim = "0x049622878da186a8a31f4dc03454dbbc62365060458db174618218b51d5014fa56c8ea772234341ae326ce278091c39e30c02fa1f04792035d79311fe3283f1380"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "6CUGhnmKQchF6Ter05laVgQYcEWm0p2qlLzX24rk3Ck="); let hex_claim = "0x04e355263aa6cbc99d2fdd0898f5ed8630115ad54e9073c41a8aa0df6d75842d8b8309d0d26a95565996b17da48f8ddff704ebcd1d8a982dc5ba8be7458c677b17"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "k0UwNtWW4UQifisXuoDiO/QGRZNNTY7giWK1Nx/hoSo="); let hex_claim = "0x04020d62c94296539224b885c6cdf79d0c2dd437471425be26bf62ab522949f83f3eed34528b0b9a7fbe96e50ca85471c894e1aa819bbf12ff78ad07ce8b4117b2"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "5EhP0859lic41RIpIrnotv/BCR7v5nVcXsXkTXlbuhI="); let hex_claim = "0x046bd65449f336b888fc36c64708940da0d1c864a0ac46236f60b455841a4d15c9b815ed725093b3266aaca2f15210d14a1eadf34efeda3bd44a803fbf1590cfba"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "oseI7fM8wWIYslDUOXJne7AOiK+IpFL3q8MTqiZHWw8="); let hex_claim = "0x0412cf2bd4a9613ad988f7f008a5297b8e8c98df8759a2ef9d3dfae63b3870cfbb78d35789745f82710da61a61a9c06c6f6166bf1d5ce73f9416e6b67713001aa2"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "9Y3JcjUHZLGmENRQpnML/+TG2EbHWjU46h+LtT9sQi8="); let hex_claim = "0x04a2e6914db4a81ea9ec72e71b41cf88d4bc19ea54f29ae2beb3db8e4acf6531b5c163e58427831832b10fce899a030d12e82a398d4eeefe451c7e261fba973be4"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "Llx5F6lP/hbU6ZTT10Q5PF+7o1VdylvrolT8vSHJMAA="); let hex_claim = "0x041508189a6f1737f50dd2c603c1ded8a83f97073d33cbb317e7409c1487b8351aa2b89455cda61ce8ed3ba3c130372870b187239b900da8948a53ca3e02db9aaf"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "MyRpb4ZDTwtJNflc8ZbZdmKOf+fuZjUEZkgZMCmlKxw="); let hex_claim = "0x04f11597483032666b20ec51b27e1337577f63a5e1d5962575b555bf899380ae15482f031a297094b0c60980f3c4f1f7ad2346de5357ad82a6a3d4eef2bd1956c6"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "ytwkzcBixiBMsblxEEPpiDFV6MCBG/IY+XUc6/+xIQ8="); let hex_claim = "0x044c01f3d0ef3d60652aa7c6489b2f10edcae1b04a10460ab2d5e4bd752eb0686cac7aa6057fd4c65606e8a4c33c0b519b1764229395cde2c8537ee01136ef0776"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "VS5c2JQT3x++ltSQHqnCFIBHttdjU2Lk2RuCGkUhnQ8="); } #[test] fn should_return_32_byte_hashes() { let hex_claim = "0x04c94699a259ec27e1cf67fe
should_hash_hex_claims
identifier_name
lib.rs
48f8ddff704ebcd1d8a982dc5ba8be7458c677b17"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "k0UwNtWW4UQifisXuoDiO/QGRZNNTY7giWK1Nx/hoSo="); let hex_claim = "0x04020d62c94296539224b885c6cdf79d0c2dd437471425be26bf62ab522949f83f3eed34528b0b9a7fbe96e50ca85471c894e1aa819bbf12ff78ad07ce8b4117b2"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "5EhP0859lic41RIpIrnotv/BCR7v5nVcXsXkTXlbuhI="); let hex_claim = "0x046bd65449f336b888fc36c64708940da0d1c864a0ac46236f60b455841a4d15c9b815ed725093b3266aaca2f15210d14a1eadf34efeda3bd44a803fbf1590cfba"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "oseI7fM8wWIYslDUOXJne7AOiK+IpFL3q8MTqiZHWw8="); let hex_claim = "0x0412cf2bd4a9613ad988f7f008a5297b8e8c98df8759a2ef9d3dfae63b3870cfbb78d35789745f82710da61a61a9c06c6f6166bf1d5ce73f9416e6b67713001aa2"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "9Y3JcjUHZLGmENRQpnML/+TG2EbHWjU46h+LtT9sQi8="); let hex_claim = "0x04a2e6914db4a81ea9ec72e71b41cf88d4bc19ea54f29ae2beb3db8e4acf6531b5c163e58427831832b10fce899a030d12e82a398d4eeefe451c7e261fba973be4"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "Llx5F6lP/hbU6ZTT10Q5PF+7o1VdylvrolT8vSHJMAA="); let hex_claim = "0x041508189a6f1737f50dd2c603c1ded8a83f97073d33cbb317e7409c1487b8351aa2b89455cda61ce8ed3ba3c130372870b187239b900da8948a53ca3e02db9aaf"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "MyRpb4ZDTwtJNflc8ZbZdmKOf+fuZjUEZkgZMCmlKxw="); let hex_claim = "0x04f11597483032666b20ec51b27e1337577f63a5e1d5962575b555bf899380ae15482f031a297094b0c60980f3c4f1f7ad2346de5357ad82a6a3d4eef2bd1956c6"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "ytwkzcBixiBMsblxEEPpiDFV6MCBG/IY+XUc6/+xIQ8="); let hex_claim = "0x044c01f3d0ef3d60652aa7c6489b2f10edcae1b04a10460ab2d5e4bd752eb0686cac7aa6057fd4c65606e8a4c33c0b519b1764229395cde2c8537ee01136ef0776"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "VS5c2JQT3x++ltSQHqnCFIBHttdjU2Lk2RuCGkUhnQ8="); } #[test] fn should_return_32_byte_hashes() { let hex_claim = "0x04c94699a259ec27e1cf67fe46653f0dc2f38e6d32abb33b45fc9ffe793171a44b4ff5c9517c1be22f8a47915debcf1e512717fe33986f287e79d2f3099725f179"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "uJM6qiWAIIej9CGonWlR0cU64wqtdlh+csikpC6wSgA="); let len = base64::decode(b64_hash) .expect("The hash is not a valid base64") .len(); assert_eq!(len, 32); let hex_claim = "0x0424a71e7c24b38aaeeebbc334113045885bfae154071426e21c021ebc47a5a85a3a691a76d8253ce6e03bf4e8fe154c89b2d967765bb060e61360305d1b8df7c5"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "9wxP7eLFnTk5VDsj9rXL63r7QPKTTjCkNhjZri1nEQA="); let len = base64::decode(b64_hash) .expect("The hash is not a valid base64") .len(); assert_eq!(len, 32); let hex_claim = "0x04ff51151c6bd759d723af2d0571df5e794c28b204242f4b540b0d3449eab192cafd44b241c96b39fa7dd7ead2d2265a598a23cba0f54cb79b9829d355d74304a2"; let b64_hash = digest_hex_claim(hex_claim); assert_eq!(b64_hash, "iS7BUPgGpY/WAdWyZb0s1wE21tMz5ZWBc8LJ6jgqSwA="); let len = base64::decode(b64_hash) .expect("The hash is not a valid base64") .len();
assert_eq!(len, 32);
random_line_split
OutMMOperationCtrl.js
else { $scope.changeSelection($scope.order.product[key]); keepGoing = false; } } }); $scope.tableParams = new ngTableParams({//未完成料号名称规格及剩余数量表格 page: 1, count: 10, filter: { }, sorting: { 'PD_PDNO': 'asc' } }, { total: $scope.order.product.length, getData: function ($defer, params) { var filteredData = params.filter() ? $filter('filter')($scope.order.product, params.filter()) : data; var orderedData = params.sorting() ? $filter('orderBy')(filteredData, params.orderBy()) : data; params.total(orderedData.length); // set total for recalc pagination $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); } }); } var checkBar = function(defer) { OutOper.checkOutqty({},{pi_id:$scope.order.PI_ID,pd_id:$scope.pd_id,pr_fbzs:$scope.pr_fbzs, barcode:$scope.bi_barcode, whcode:$scope.order.PI_WHCODE,prodcode:$scope.bi_prodcode}, function(data){ if(data.exceptionInfo){ defer.reject(data.exceptionInfo); }else defer.resolve(data.message); }, function(response){ if(response.status == 0){ //无网络错误 Online.setOnline(false);//修改网络状态 toaster.pop('error', '失败',"网络连接不可用,请稍后再试"); } defer.reject(response.data.exceptionInfo); }); }; var checkOutBox = function(defer) { OutOper.checkOutBoxqty({},{pi_id:$scope.order.PI_ID,pd_id:$scope.pd_id,pr_fbzs:$scope.pr_fbzs, outboxcode:$scope.bi_outboxcode, whcode:$scope.order.PI_WHCODE,prodcode:$scope.bi_prodcode}, function(data){ if(data.exceptionInfo){ defer.reject(data.exceptionInfo); }else defer.resolve(data.message); }, function(response){ if(response.status == 0){ //无网络错误 Online.setOnline(false);//修改网络状态 toaster.pop('error', '失败',"网络连接不可用,请稍后再试"); } defer.reject(response.data.exceptionInfo); }); }; //进入界面,表单值默认为grid中的第一行 var check = function (productCode){ //校验:1、物料编号存在, 2、数量不超过剩余数量,3、条码号唯一性 //条码储位不允许为空 var defer = $q.defer(); var reg = /^[0-9]*[1-9][0-9]*$/; if(!$scope.bi_barcode && !$scope.bi_outboxcode){ document.getElementById("bi_barcode").focus(); defer.reject("请输入条码或者箱号!"); }else{ var item = SupportUtil.contains(JSON.stringify($scope.order.product),productCode,"PD_PRODCODE"); if(item){ //是否条码校验 if($scope.ifbarcodecheck == '1'){ var pr_idlen =$scope.order.barcodeset.BS_LENPRID; //比较物料ID的前几位是否等于条码号的前几位 var pr_id = new String($scope.pr_id); var bar_code = new String($scope.bi_barcode); if (SupportUtil.lapAft(pr_id,pr_idlen) != SupportUtil.lapFor(bar_code,pr_idlen)){ Ring.error(); $scope.bi_barcode =''; defer.reject("条码校验错误,该条码与物料不匹配") } } if($rootScope.outMMgrid){ if($scope.bi_barcode && (SupportUtil.contains(JSON.stringify($rootScope.outMMgrid) ,$scope.bi_barcode,"bi_barcode"))){ document.getElementById("bi_barcode").focus(); document.getElementById("bi_barcode").select(); defer.reject("条码号重复"); } else if($scope.bi_outboxcode && (SupportUtil.contains(JSON.stringify($rootScope.outMMgrid) ,$scope.bi_outboxcode,"bi_outboxcode"))){ document.getElementById("bi_outboxcode").focus(); document.getElementById("bi_outboxcode").select(); defer.reject("箱号重复"); } } if($scope.bi_barcode){ checkBar(defer); }else if($scope.bi_outboxcode){ checkOutBox(defer); } } else { Ring.error(); defer.reject("物料不存在"); } } return defer.promise; } $scope.scan = function(){//确认按钮事件 var q = check($scope.bi_prodcode); q.then(function(message){ if(message.data.bar_code){//对箱号中所有的条码号进行判断是否存在重复在JS[已采集列表]的列表中 var codes = message.bar_code.split(","); for(var i=0;i<codes.length;i++){ if(SupportUtil.contains(JSON.stringify($rootScope.outMMgrid) ,codes[i],"bi_barcode")){ toaster.pop('error',"箱号包含已采集列表中的条码!"); return ; } } }else if(message.data.pa_outboxcode){ if(SupportUtil.contains(JSON.stringify($rootScope.outMMgrid) ,message.pa_out
e};} } }); modalInstance.result.then(function(s){ if(s) {//判断数量是否需要拆分 OutOper.ifNeedBatch({},{bar_code:$scope.bi_barcode,pr_fbzs:$scope.pr_fbzs, whcode:$scope.order.PI_WHCODE},function(data){ },function(res){ if(res.data.exceptionInfo.indexOf('拆批') >=0){ if(confirm("确认拆批")){ batchSplit(); } }else{ toaster.pop('error',res.data.exceptionInfo); return; } }); }else{ $scope.bi_barcode = ''; } }); return; } $scope.barcodes = {}; $scope.barcodes.bi_barcode = $scope.bi_barcode ; $scope.barcodes.bi_outboxcode = $scope.bi_outboxcode ; $scope.barcodes.bi_prodcode = $scope.bi_prodcode ; $scope.barcodes.bi_prodid = $scope.bi_prodid ; $scope.barcodes.bi_inoutno = $scope.order.PI_INOUTNO; $scope.barcodes.bi_outqty = message.remain; $scope.barcodes.bi_whcode = $scope.order.PI_WHCODE; $scope.barcodes.bi_prodname = $scope.bi_prodname; $scope.barcodes.bi_pdno = $scope.detno; $scope.barcodes.bi_pdid = $scope.pd_id; $scope.barcodes.bi_piid = $scope.order.PI_ID; //插入数据到待提交缓存列表中grid(barcode,prodcode,inqty,location) $scope.grid.push($scope.barcodes); $rootScope.outMMgrid = $scope.grid; $scope.pr_fbzs -= message.remain; $scope.bi_barcode =''; $scope.bi_outboxcode =''; angular.forEach($scope.order.product, function(value, key){ if(value.PD_ID == $scope.pd_id) { value.PD_OUTQTY = $scope.pr_fbzs ; $scope.tableParams.reload(); if(value.PD_OUTQTY == 0 && $scope.order.product[key+1] ){ $scope.changeSelection($scope.order.product[key+1]); } } }); var keepGoing = true; angular.forEach($scope.order.product, function(value, key){ if(keepGoing){ if(value.PD_OUTQTY != 0 ){ keepGoing = false ; } } }); if(keepGoing){ setTimeout( function(){ try{ if(confirm("已完成,请提交采集")){ $location.path('outMMWaitSubmit/' + $scope.order.PI_INOUTNO); } } catch(e){} }, 200); } }, function(error){ toaster.pop('error', '错误',error); setTimeout( function(){ try{ if(error.indexOf('拆批') >=0){ if(confirm("确认拆批")){ batchSplit(); } }else{ $scope.barcode =
boxcode,"bi_outboxcode")){ toaster.pop('error',"条码所在的箱号在已采集列表中存在!"); return ; } }else if(message.isMsd){//湿敏元件弹出显示湿敏元件的相关记录 MSDlog //拆分湿敏元件提示剩余寿命等信息 var modalInstance = $modal.open({ templateUrl: 'resources/tpl/output/msdConfirm.html', controller: 'SplitModalCtrl', resolve: { items: function(){return {'bar_code':$scope.bi_barcod
conditional_block
OutMMOperationCtrl.js
}else { $scope.changeSelection($scope.order.product[key]); keepGoing = false; } } }); $scope.tableParams = new ngTableParams({//未完成料号名称规格及剩余数量表格 page: 1, count: 10, filter: { }, sorting: { 'PD_PDNO': 'asc' } }, { total: $scope.order.product.length, getData: function ($defer, params) { var filteredData = params.filter() ? $filter('filter')($scope.order.product, params.filter()) : data; var orderedData = params.sorting() ? $filter('orderBy')(filteredData, params.orderBy()) : data; params.total(orderedData.length); // set total for recalc pagination $defer.resolve(orderedData.slice((params.page() - 1) * params.count(), params.page() * params.count())); } });
defer.reject(data.exceptionInfo); }else defer.resolve(data.message); }, function(response){ if(response.status == 0){ //无网络错误 Online.setOnline(false);//修改网络状态 toaster.pop('error', '失败',"网络连接不可用,请稍后再试"); } defer.reject(response.data.exceptionInfo); }); }; var checkOutBox = function(defer) { OutOper.checkOutBoxqty({},{pi_id:$scope.order.PI_ID,pd_id:$scope.pd_id,pr_fbzs:$scope.pr_fbzs, outboxcode:$scope.bi_outboxcode, whcode:$scope.order.PI_WHCODE,prodcode:$scope.bi_prodcode}, function(data){ if(data.exceptionInfo){ defer.reject(data.exceptionInfo); }else defer.resolve(data.message); }, function(response){ if(response.status == 0){ //无网络错误 Online.setOnline(false);//修改网络状态 toaster.pop('error', '失败',"网络连接不可用,请稍后再试"); } defer.reject(response.data.exceptionInfo); }); }; //进入界面,表单值默认为grid中的第一行 var check = function (productCode){ //校验:1、物料编号存在, 2、数量不超过剩余数量,3、条码号唯一性 //条码储位不允许为空 var defer = $q.defer(); var reg = /^[0-9]*[1-9][0-9]*$/; if(!$scope.bi_barcode && !$scope.bi_outboxcode){ document.getElementById("bi_barcode").focus(); defer.reject("请输入条码或者箱号!"); }else{ var item = SupportUtil.contains(JSON.stringify($scope.order.product),productCode,"PD_PRODCODE"); if(item){ //是否条码校验 if($scope.ifbarcodecheck == '1'){ var pr_idlen =$scope.order.barcodeset.BS_LENPRID; //比较物料ID的前几位是否等于条码号的前几位 var pr_id = new String($scope.pr_id); var bar_code = new String($scope.bi_barcode); if (SupportUtil.lapAft(pr_id,pr_idlen) != SupportUtil.lapFor(bar_code,pr_idlen)){ Ring.error(); $scope.bi_barcode =''; defer.reject("条码校验错误,该条码与物料不匹配") } } if($rootScope.outMMgrid){ if($scope.bi_barcode && (SupportUtil.contains(JSON.stringify($rootScope.outMMgrid) ,$scope.bi_barcode,"bi_barcode"))){ document.getElementById("bi_barcode").focus(); document.getElementById("bi_barcode").select(); defer.reject("条码号重复"); } else if($scope.bi_outboxcode && (SupportUtil.contains(JSON.stringify($rootScope.outMMgrid) ,$scope.bi_outboxcode,"bi_outboxcode"))){ document.getElementById("bi_outboxcode").focus(); document.getElementById("bi_outboxcode").select(); defer.reject("箱号重复"); } } if($scope.bi_barcode){ checkBar(defer); }else if($scope.bi_outboxcode){ checkOutBox(defer); } } else { Ring.error(); defer.reject("物料不存在"); } } return defer.promise; } $scope.scan = function(){//确认按钮事件 var q = check($scope.bi_prodcode); q.then(function(message){ if(message.data.bar_code){//对箱号中所有的条码号进行判断是否存在重复在JS[已采集列表]的列表中 var codes = message.bar_code.split(","); for(var i=0;i<codes.length;i++){ if(SupportUtil.contains(JSON.stringify($rootScope.outMMgrid) ,codes[i],"bi_barcode")){ toaster.pop('error',"箱号包含已采集列表中的条码!"); return ; } } }else if(message.data.pa_outboxcode){ if(SupportUtil.contains(JSON.stringify($rootScope.outMMgrid) ,message.pa_outboxcode,"bi_outboxcode")){ toaster.pop('error',"条码所在的箱号在已采集列表中存在!"); return ; } }else if(message.isMsd){//湿敏元件弹出显示湿敏元件的相关记录 MSDlog //拆分湿敏元件提示剩余寿命等信息 var modalInstance = $modal.open({ templateUrl: 'resources/tpl/output/msdConfirm.html', controller: 'SplitModalCtrl', resolve: { items: function(){return {'bar_code':$scope.bi_barcode};} } }); modalInstance.result.then(function(s){ if(s) {//判断数量是否需要拆分 OutOper.ifNeedBatch({},{bar_code:$scope.bi_barcode,pr_fbzs:$scope.pr_fbzs, whcode:$scope.order.PI_WHCODE},function(data){ },function(res){ if(res.data.exceptionInfo.indexOf('拆批') >=0){ if(confirm("确认拆批")){ batchSplit(); } }else{ toaster.pop('error',res.data.exceptionInfo); return; } }); }else{ $scope.bi_barcode = ''; } }); return; } $scope.barcodes = {}; $scope.barcodes.bi_barcode = $scope.bi_barcode ; $scope.barcodes.bi_outboxcode = $scope.bi_outboxcode ; $scope.barcodes.bi_prodcode = $scope.bi_prodcode ; $scope.barcodes.bi_prodid = $scope.bi_prodid ; $scope.barcodes.bi_inoutno = $scope.order.PI_INOUTNO; $scope.barcodes.bi_outqty = message.remain; $scope.barcodes.bi_whcode = $scope.order.PI_WHCODE; $scope.barcodes.bi_prodname = $scope.bi_prodname; $scope.barcodes.bi_pdno = $scope.detno; $scope.barcodes.bi_pdid = $scope.pd_id; $scope.barcodes.bi_piid = $scope.order.PI_ID; //插入数据到待提交缓存列表中grid(barcode,prodcode,inqty,location) $scope.grid.push($scope.barcodes); $rootScope.outMMgrid = $scope.grid; $scope.pr_fbzs -= message.remain; $scope.bi_barcode =''; $scope.bi_outboxcode =''; angular.forEach($scope.order.product, function(value, key){ if(value.PD_ID == $scope.pd_id) { value.PD_OUTQTY = $scope.pr_fbzs ; $scope.tableParams.reload(); if(value.PD_OUTQTY == 0 && $scope.order.product[key+1] ){ $scope.changeSelection($scope.order.product[key+1]); } } }); var keepGoing = true; angular.forEach($scope.order.product, function(value, key){ if(keepGoing){ if(value.PD_OUTQTY != 0 ){ keepGoing = false ; } } }); if(keepGoing){ setTimeout( function(){ try{ if(confirm("已完成,请提交采集")){ $location.path('outMMWaitSubmit/' + $scope.order.PI_INOUTNO); } } catch(e){} }, 200); } }, function(error){ toaster.pop('error', '错误',error); setTimeout( function(){ try{ if(error.indexOf('拆批') >=0){ if(confirm("确认拆批")){ batchSplit(); } }else{ $scope.barcode = '';
} var checkBar = function(defer) { OutOper.checkOutqty({},{pi_id:$scope.order.PI_ID,pd_id:$scope.pd_id,pr_fbzs:$scope.pr_fbzs, barcode:$scope.bi_barcode, whcode:$scope.order.PI_WHCODE,prodcode:$scope.bi_prodcode}, function(data){ if(data.exceptionInfo){
random_line_split
cronjob.go
Find(&jobs). Error }) eg.Go(func() error { pagination.Total = int64(page) return query.Count(&pagination.Total).Error }) err = eg.Wait() if err != nil { return } for _, job := range jobs { timers := make([]view.CronJobTimer, 0) for _, timer := range job.Timers { timers = append(timers, view.CronJobTimer{ ID: timer.ID, JobID: timer.JobID, Cron: timer.Cron, }) } item := view.CronJobListItem{ CronJob: view.CronJob{ ID: job.ID, Name: job.Name, Username: job.User.Nickname, AppName: job.AppName, Env: job.Env, Zone: job.Zone, Timeout: job.Timeout, RetryCount: job.RetryCount, RetryInterval: job.RetryInterval, Script: job.Script, Timers: timers, Enable: job.Enable, JobType: job.JobType, Nodes: job.Nodes, }, } var lastTask db.CronTask err = j.db.Where("job_id = ?", item.ID).Last(&lastTask).Error if err != nil { if err == gorm.ErrRecordNotFound { err = nil } else { return } } else { item.LastExecutedAt = lastTask.ExecutedAt item.Status = &lastTask.Status } list = append(list, item) } return } // Create 创建 Job func (j *CronJob) Create(uid uint, params view.CronJob) (err error) { var timers = make([]db.CronJobTimer, len(params.Timers)) var job = db.CronJob{ Uid: uid, Name: params.Name, AppName: params.AppName, Env: params.Env, Zone: params.Zone, Timeout: params.Timeout, RetryCount: params.RetryCount, RetryInterval: params.RetryInterval, Script: params.Script, Enable: params.Enable, JobType: params.JobType, Nodes: params.Nodes, } for idx, timer := range params.Timers { _, err := cronParser.Parse(timer.Cron) if err != nil { return errors.Wrapf(err, "parse cron failed: %s", timer.Cron) } timers[idx] = db.CronJobTimer{ Cron: timer.Cron, } } job.Timers = timers err = j.db.Create(&job).Error if err != nil { return } err = j.dispatcher.dispatchJob(makeJob(job)) if err != nil { return errors.Wrapf(err, "job-dispatching failed") } return } // Update .. func (j *CronJob) Update(params view.CronJob) (err error) { var job d
Job var timers = make([]db.CronJobTimer, len(params.Timers)) var oldTimers []db.CronJobTimer for idx, timer := range params.Timers { _, err := cronParser.Parse(timer.Cron) if err != nil { return errors.Wrapf(err, "parse cron failed: %s", timer.Cron) } timers[idx] = db.CronJobTimer{ Cron: timer.Cron, } } //begin tx := j.db.Begin() err = tx.Where("id = ?", params.ID).First(&job).Error if err != nil { tx.Rollback() return errors.Wrap(err, "can not found params") } err = tx.Model(&job).Association("Timers").Find(&oldTimers) if err != nil { tx.Rollback() return } for _, t := range oldTimers { err = tx.Delete(&t).Error if err != nil { tx.Rollback() return } } err = tx.Model(&job).Association("Timers").Append(timers) if err != nil { tx.Rollback() return } job.Name = params.Name job.AppName = params.AppName job.Env = params.Env job.Zone = params.Zone job.Timeout = params.Timeout job.RetryCount = params.RetryCount job.RetryInterval = params.RetryInterval job.Script = params.Script job.Enable = params.Enable job.JobType = params.JobType job.Nodes = params.Nodes err = tx.Save(&job).Error if err != nil { tx.Rollback() return } //commit err = tx.Commit().Error if err != nil { return } if params.Enable { err = j.dispatcher.dispatchJob(makeJob(job)) if err != nil { return errors.Wrapf(err, "job-dispatching failed") } } else { err = j.dispatcher.revokeJob(makeJob(job)) if err != nil { return errors.Wrapf(err, "job-revoking failed") } } return } // Delete 删除 id 对应的 Job func (j *CronJob) Delete(id uint) (err error) { var job db.CronJob tx := j.db.Begin() { err = tx.Where("id = ?", id).First(&job).Error if err != nil { tx.Rollback() return errors.Wrap(err, "cannot found job") } err = j.dispatcher.revokeJob(makeJob(job)) if err != nil { tx.Rollback() return errors.Wrap(err, "revoke job failed") } err = tx.Delete(&job).Error if err != nil { tx.Rollback() return errors.Wrap(err, "delete failed") } } tx.Commit() return } // DispatchOnce 下发任务手动执行单次 func (j *CronJob) DispatchOnce(id uint, node string) (err error) { var job db.CronJob err = j.db.Where("id = ?", id).First(&job).Error if err != nil { return errors.Wrapf(err, "cannot found job") } task := db.CronTask{ JobID: job.ID, Timeout: job.Timeout, Node: node, Status: db.CronTaskStatusWaiting, ExecuteType: db.ExecuteTypeManual, FinishedAt: nil, Script: job.Script, } tx := j.db.Begin() { err := tx.Save(&task).Error if err != nil { tx.Rollback() return err } jobPayload := makeOnceJob(job, task.ID) err = j.dispatcher.dispatchOnceJob(jobPayload, node) if err != nil { tx.Rollback() return err } } return tx.Commit().Error } // ListTask 任务列表 func (j *CronJob) ListTask(params view.ReqQueryTasks) (list []view.CronTask, pagination view.Pagination, err error) { var tasks []db.CronTask page := params.Page if page == 0 { page = 1 } pageSize := params.PageSize if pageSize > 100 { pageSize = 100 } offset := (page - 1) * pageSize query := j.db.Where("job_id = ?", params.ID) if len(params.ExecutedAt) == 2 { query = query.Where("executed_at >= ? and executed_at <= ?", params.ExecutedAt[0], params.ExecutedAt[1]) } eg := errgroup.Group{} eg.Go(func() error { return query.Select([]string{"id", "job_id", "executed_at", "finished_at", "retry_count", "execute_type", "status", "node"}). Limit(pageSize). Offset(offset). Order("created_at desc"). Find(&tasks). Error }) eg.Go(func() error { pagination.Current = int(page) pagination.PageSize = int(pageSize) return query.Model(&db.CronTask{}).Count(&pagination.Total).Error }) err = eg.Wait() if err != nil { return } for _, task := range tasks { list = append(list, view.CronTask{ ID: strconv.FormatUint(task.ID, 10), JobID: task.JobID, Node: task.Node, ExecutedAt: task.ExecutedAt, FinishedAt: task.FinishedAt, RetryCount: task.RetryCount, Status: task.Status, ExecuteType: task.ExecuteType, }) } return } // TaskDetail Task 详情 func (j *CronJob) TaskDetail(id uint) (detail view.CronTaskDetail, err error) { var task db.CronTask err = j.db.Where("id = ?", id).First(&task).Error if err != nil { return } detail = view.CronTaskDetail{ CronTask: view.CronTask{ ID:
b.Cron
identifier_name
cronjob.go
page = 1 // from 1 on } pageSize := params.PageSize if pageSize > 100 { pageSize = 100 } offset := (page - 1) * pageSize query := j.db.Model(&db.CronJob{}) if params.Enable != nil { query = query.Where("enable = ?", *params.Enable) } if params.Name != nil { query = query.Where("name like ?", "%"+*params.Name+"%") } if params.AppName != nil { query = query.Where("app_name = ?", *params.AppName) } if params.User != nil { username := "%" + *params.User + "%" query = query.Joins("left join user on cron_job.uid = user.uid") query = query.Where("user.username like ? or user.nickname like ?", username, username) } eg := errgroup.Group{} eg.Go(func() error { return query.Table("cron_job").Offset(offset). Preload("Timers"). Preload("User"). Limit(pageSize). Order("id desc"). Find(&jobs). Error }) eg.Go(func() error { pagination.Total = int64(page) return query.Count(&pagination.Total).Error }) err = eg.Wait() if err != nil { return } for _, job := range jobs { timers := make([]view.CronJobTimer, 0) for _, timer := range job.Timers { timers = append(timers, view.CronJobTimer{ ID: timer.ID, JobID: timer.JobID, Cron: timer.Cron, }) } item := view.CronJobListItem{ CronJob: view.CronJob{ ID: job.ID, Name: job.Name, Username: job.User.Nickname, AppName: job.AppName, Env: job.Env, Zone: job.Zone, Timeout: job.Timeout, RetryCount: job.RetryCount, RetryInterval: job.RetryInterval, Script: job.Script, Timers: timers, Enable: job.Enable, JobType: job.JobType, Nodes: job.Nodes, }, } var lastTask db.CronTask err = j.db.Where("job_id = ?", item.ID).Last(&lastTask).Error if err != nil { if err == gorm.ErrRecordNotFound { err = nil } else { return } } else { item.LastExecutedAt = lastTask.ExecutedAt item.Status = &lastTask.Status } list = append(list, item) } return } // Create 创建 Job func (j *CronJob) Create(uid uint, params view.CronJob) (err error) { var timers = make([]db.CronJobTimer, len(params.Timers)) var job = db.CronJob{ Uid: uid, Name: params.Name, AppName: params.AppName, Env: params.Env, Zone: params.Zone, Timeout: params.Timeout, RetryCount: params.RetryCount, RetryInterval: params.RetryInterval, Script: params.Script, Enable: params.Enable, JobType: params.JobType, Nodes: params.Nodes, } for idx, timer := range params.Timers { _, err := cronParser.Parse(timer.Cron) if err != nil { return errors.Wrapf(err, "parse cron failed: %s", timer.Cron) } timers[idx] = db.CronJobTimer{ Cron: timer.Cron, } } job.Timers = timers err = j.db.Create(&job).Error if err != nil { return } err = j.dispatcher.dispatchJob(makeJob(job)) if err != nil { return errors.Wrapf(err, "job-dispatching failed") } return } // Update .. func (j *CronJob) Update(params view.CronJob) (err error) { var job db.CronJob var timers = make([]db.CronJobTimer, len(params.Timers)) var oldTimers []db.CronJobTimer for idx, timer := range params.Timers { _, err := cronParser.Parse(timer.Cron) if err != nil { return errors.Wrapf(err, "parse cron failed: %s", timer.Cron) } timers[idx] = db.CronJobTimer{ Cron: timer.Cron, } } //begin tx := j.db.Begin() err = tx.Where("id = ?", params.ID).First(&job).Error if err != nil { tx.Rollback() return errors.Wrap(err, "can not found params") } err = tx.Model(&job).Association("Timers").Find(&oldTimers) if err != nil { tx.Rollback() return } for _, t := range oldTimers { err = tx.Delete(&t).Error if err != nil { tx.Rollback() return } } err = tx.Model(&job).Association("Timers").Append(timers) if err != nil { tx.Rollback() return } job.Name = params.Name job.AppName = params.AppName job.Env = params.Env job.Zone = params.Zone job.Timeout = params.Timeout job.RetryCount = params.RetryCount job.RetryInterval = params.RetryInterval job.Script = params.Script job.Enable = params.Enable job.JobType = params.JobType job.Nodes = params.Nodes err = tx.Save(&job).Error if err != nil { tx.Rollback() return } //commit err = tx.Commit().Error if err != nil { return } if params.Enable { err = j.dispatcher.dispatchJob(makeJob(job)) if err != nil { return errors.Wrapf(err, "job-dispatching failed") } } else { err = j.dispatcher.revokeJob(makeJob(job)) if err != nil { return errors.Wrapf(err, "job-revoking failed") } } return } // Delete 删除 id 对应的 Job func (j *CronJob) Delete(id uint) (err error) { var job db.CronJob tx := j.db.Begin() { err = tx.Where("id = ?", id).First(&job).Error if err != nil { tx.Rollback() return errors.Wrap(err, "cannot found job") } err = j.dispatcher.revokeJob(makeJob(job)) if err != nil { tx.Rollback() return errors.Wrap(err, "revoke job failed") } err = tx.Delete(&job).Error if err != nil { tx.Rollback() return errors.Wrap(err, "delete failed") } } tx.Commit() return } // DispatchOnce 下发任务手动执行单次 func (j *CronJob) DispatchOnce(id uint, node string) (err error) { var job db.CronJob err = j.db.Where("id = ?", id).First(&job).Error if err != nil { return errors.Wrapf(err, "cannot found job") } task := db.CronTask{ JobID: job.ID, Timeout: job.Timeout, Node: node, Status: db.CronTaskStatusWaiting, ExecuteType: db.ExecuteTypeManual, FinishedAt: nil, Script: job.Script, } tx := j.db.Begin() { err := tx.Save(&task).Error if err != nil { tx.Rollback() return err } jobPayload := makeOnceJob(job, task.ID) err = j.dispatcher.dispatchOnceJob(jobPayload, node) if err != nil { tx.Rollback() return err } } return tx.Commit().Error } // ListTask 任务列表 func (j *CronJob) ListTask(params view.ReqQueryTasks) (list []view.CronTask, pagination view.Pagination, err error) { var tasks []db.CronTask page := params.Page if page == 0 { page = 1 } pageSize := params.PageSize if pageSize > 100 { pageSize = 100 } offset := (page - 1) * pageSize query := j.db.Where("job_id = ?", params.ID) if len(params.ExecutedAt) == 2 { query = query.Where("executed_at >= ? and executed_at <= ?", params.ExecutedAt[0], params.ExecutedAt[1]) } eg := errgroup.Group{} eg.Go(func() error { return query.Select([]string{"id", "job_id", "executed_at", "finished_at", "retry_count", "execute_type", "status", "node"}). Limit(pageSize). Offset(offset). Order("created_at desc"). Find(&tasks). Error }) eg.Go(func() error { p
if page == 0 {
random_line_split
cronjob.go
Find(&jobs). Error }) eg.Go(func() error { pagination.Total = int64(page) return query.Count(&pagination.Total).Error }) err = eg.Wait() if err != nil { return } for _, job := range jobs { timers := make([]view.CronJobTimer, 0) for _, timer := range job.Timers { timers = append(timers, view.CronJobTimer{ ID: timer.ID, JobID: timer.JobID, Cron: timer.Cron, }) } item := view.CronJobListItem{ CronJob: view.CronJob{ ID: job.ID, Name: job.Name, Username: job.User.Nickname, AppName: job.AppName, Env: job.Env, Zone: job.Zone, Timeout: job.Timeout, RetryCount: job.RetryCount, RetryInterval: job.RetryInterval, Script: job.Script, Timers: timers, Enable: job.Enable, JobType: job.JobType, Nodes: job.Nodes, }, } var lastTask db.CronTask err = j.db.Where("job_id = ?", item.ID).Last(&lastTask).Error if err != nil { if err == gorm.ErrRecordNotFound { err = nil } else { return } } else { item.LastExecutedAt = lastTask.ExecutedAt item.Status = &lastTask.Status } list = append(list, item) } return } // Create 创建 Job func (j *CronJob) Create(uid uint, params view.CronJob) (err error) { var timers = make([]db.CronJobTimer, len(params.Timers)) var job = db.CronJob{ Uid: uid, Name: params.Name, AppName: params.AppName, Env: params.Env, Zone: params.Zone, Timeout: params.Timeout, RetryCount: params.RetryCount, RetryInterval: params.RetryInterval, Script: params.Script, Enable: params.Enable, JobType: params.JobType, Nodes: params.Nodes, } for idx, timer := range params.Timers { _, err := cronParser.Parse(timer.Cron) if err != nil { return errors.Wrapf(err, "parse cron failed: %s", timer.Cron) } timers[idx] = db.CronJobTimer{ Cron: timer.Cron, } } job.Timers = timers err = j.db.Create(&job).Error if err != nil { return } err = j.dispatcher.dispatchJob(makeJob(job)) if err != nil { return errors.Wrapf(err, "job-dispatching failed") } return } // Update .. func (j *CronJob) Update(params view.CronJob) (err error) { var job db.CronJob var timers = make([]db.CronJobTimer, len(params.Timers)) var oldTimers []db.CronJobTimer for idx, timer := range params.Timers { _, err := cronParser.Parse(timer.Cron) if err != nil { return errors.Wrapf(err, "parse cron failed: %s", timer.Cron) } timers[idx] = db.CronJobTimer{ Cron: timer.Cron, } } //begin tx := j.db.Begin() err = tx.Where("id = ?", params.ID).First(&job).Error if err != nil { tx.Rollback() return errors.Wrap(err, "can not found params") } err = tx.Model(&job).Association("Timers").Find(&oldTimers) if err != nil { tx.Rollback() return } for _, t := range oldTimers { err = tx.Delete(&t).Error if err != nil { tx.Rollback() return } } err = tx.Model(&job).Association("Timers").Append(timers) if err != nil { tx.Rollback() return } job.Name = params.Name job.AppName = params.AppName job.Env = params.Env job.Zone = params.Zone job.Timeout = params.Timeout job.RetryCount = params.RetryCount job.RetryInterval = params.RetryInterval job.Script = params.Script job.Enable = params.Enable job.JobType = params.JobType job.Nodes = params.Nodes err = tx.Save(&job).Error if err != nil { tx.Rollback() return } //commit err = tx.Commit().Error if err != nil { return } if params.Enable { err = j.dispatcher.dispatchJob(makeJob(job)) if err != nil { return errors.Wrapf(err, "job-dispatching failed") } } else { err = j.dispatcher.revokeJob(makeJob(job)) if err != nil { return errors.Wrapf(err, "job-revoking failed") } } return } // Delete 删除 id 对应的 Job func (j *CronJob) Delete(id uint) (err error) { var job db.CronJob tx := j.db.Begin() { err = tx.Where("id = ?", id).First(&job).Error if err != nil { tx.Rollback() return errors.Wrap(err, "cannot found job") } err = j.dispatcher.revokeJob(makeJob(job)) if err != nil { tx.Rollback() return errors.Wrap(err, "revoke job failed") } err = tx.Delete(&job).Error if err != nil { tx.Rollback() return errors.Wrap(err, "delete failed") } } tx.Commit() return } // DispatchOnce 下发任务手动执行单次 func (j *CronJob) DispatchOnce(id uint, node string) (err error) { var job db.CronJob err = j.db.Where("id = ?", id).First(&job).Error if err != nil { return errors.Wrapf(err, "cannot found job") } task := db.CronTask{ JobID: job.ID, Timeout: job.Timeout, Node: node, Status: db.CronTaskStatusWaiting, ExecuteType: db.ExecuteTypeManual, FinishedAt: nil, Script: job.Script, } tx := j.db.Begin() { err := tx.Save(&task).Error if err != nil { tx.Rollback() return err } jobPayload := makeOnceJob(job, task.ID)
obPayload, node) if err != nil { tx.Rollback() return err } } return tx.Commit().Error } // ListTask 任务列表 func (j *CronJob) ListTask(params view.ReqQueryTasks) (list []view.CronTask, pagination view.Pagination, err error) { var tasks []db.CronTask page := params.Page if page == 0 { page = 1 } pageSize := params.PageSize if pageSize > 100 { pageSize = 100 } offset := (page - 1) * pageSize query := j.db.Where("job_id = ?", params.ID) if len(params.ExecutedAt) == 2 { query = query.Where("executed_at >= ? and executed_at <= ?", params.ExecutedAt[0], params.ExecutedAt[1]) } eg := errgroup.Group{} eg.Go(func() error { return query.Select([]string{"id", "job_id", "executed_at", "finished_at", "retry_count", "execute_type", "status", "node"}). Limit(pageSize). Offset(offset). Order("created_at desc"). Find(&tasks). Error }) eg.Go(func() error { pagination.Current = int(page) pagination.PageSize = int(pageSize) return query.Model(&db.CronTask{}).Count(&pagination.Total).Error }) err = eg.Wait() if err != nil { return } for _, task := range tasks { list = append(list, view.CronTask{ ID: strconv.FormatUint(task.ID, 10), JobID: task.JobID, Node: task.Node, ExecutedAt: task.ExecutedAt, FinishedAt: task.FinishedAt, RetryCount: task.RetryCount, Status: task.Status, ExecuteType: task.ExecuteType, }) } return } // TaskDetail Task 详情 func (j *CronJob) TaskDetail(id uint) (detail view.CronTaskDetail, err error) { var task db.CronTask err = j.db.Where("id = ?", id).First(&task).Error if err != nil { return } detail = view.CronTaskDetail{ CronTask: view.CronTask{ ID:
err = j.dispatcher.dispatchOnceJob(j
conditional_block
cronjob.go
username := "%" + *params.User + "%" query = query.Joins("left join user on cron_job.uid = user.uid") query = query.Where("user.username like ? or user.nickname like ?", username, username) } eg := errgroup.Group{} eg.Go(func() error { return query.Table("cron_job").Offset(offset). Preload("Timers"). Preload("User"). Limit(pageSize). Order("id desc"). Find(&jobs). Error }) eg.Go(func() error { pagination.Total = int64(page) return query.Count(&pagination.Total).Error }) err = eg.Wait() if err != nil { return } for _, job := range jobs { timers := make([]view.CronJobTimer, 0) for _, timer := range job.Timers { timers = append(timers, view.CronJobTimer{ ID: timer.ID, JobID: timer.JobID, Cron: timer.Cron, }) } item := view.CronJobListItem{ CronJob: view.CronJob{ ID: job.ID, Name: job.Name, Username: job.User.Nickname, AppName: job.AppName, Env: job.Env, Zone: job.Zone, Timeout: job.Timeout, RetryCount: job.RetryCount, RetryInterval: job.RetryInterval, Script: job.Script, Timers: timers, Enable: job.Enable, JobType: job.JobType, Nodes: job.Nodes, }, } var lastTask db.CronTask err = j.db.Where("job_id = ?", item.ID).Last(&lastTask).Error if err != nil { if err == gorm.ErrRecordNotFound { err = nil } else { return } } else { item.LastExecutedAt = lastTask.ExecutedAt item.Status = &lastTask.Status } list = append(list, item) } return } // Create 创建 Job func (j *CronJob) Create(uid uint, params view.CronJob) (err error) { var timers = make([]db.CronJobTimer, len(params.Timers)) var job = db.CronJob{ Uid: uid, Name: params.Name, AppName: params.AppName, Env: params.Env, Zone: params.Zone, Timeout: params.Timeout, RetryCount: params.RetryCount, RetryInterval: params.RetryInterval, Script: params.Script, Enable: params.Enable, JobType: params.JobType, Nodes: params.Nodes, } for idx, timer := range params.Timers { _, err := cronParser.Parse(timer.Cron) if err != nil { return errors.Wrapf(err, "parse cron failed: %s", timer.Cron) } timers[idx] = db.CronJobTimer{ Cron: timer.Cron, } } job.Timers = timers err = j.db.Create(&job).Error if err != nil { return } err = j.dispatcher.dispatchJob(makeJob(job)) if err != nil { return errors.Wrapf(err, "job-dispatching failed") } return } // Update .. func (j *CronJob) Update(params view.CronJob) (err error) { var job db.CronJob var timers = make([]db.CronJobTimer, len(params.Timers)) var oldTimers []db.CronJobTimer for idx, timer := range params.Timers { _, err := cronParser.Parse(timer.Cron) if err != nil { return errors.Wrapf(err, "parse cron failed: %s", timer.Cron) } timers[idx] = db.CronJobTimer{ Cron: timer.Cron, } } //begin tx := j.db.Begin() err = tx.Where("id = ?", params.ID).First(&job).Error if err != nil { tx.Rollback() return errors.Wrap(err, "can not found params") } err = tx.Model(&job).Association("Timers").Find(&oldTimers) if err != nil { tx.Rollback() return } for _, t := range oldTimers { err = tx.Delete(&t).Error if err != nil { tx.Rollback() return } } err = tx.Model(&job).Association("Timers").Append(timers) if err != nil { tx.Rollback() return } job.Name = params.Name job.AppName = params.AppName job.Env = params.Env job.Zone = params.Zone job.Timeout = params.Timeout job.RetryCount = params.RetryCount job.RetryInterval = params.RetryInterval job.Script = params.Script job.Enable = params.Enable job.JobType = params.JobType job.Nodes = params.Nodes err = tx.Save(&job).Error if err != nil { tx.Rollback() return } //commit err = tx.Commit().Error if err != nil { return } if params.Enable { err = j.dispatcher.dispatchJob(makeJob(job)) if err != nil { return errors.Wrapf(err, "job-dispatching failed") } } else { err = j.dispatcher.revokeJob(makeJob(job)) if err != nil { return errors.Wrapf(err, "job-revoking failed") } } return } // Delete 删除 id 对应的 Job func (j *CronJob) Delete(id uint) (err error) { var job db.CronJob tx := j.db.Begin() { err = tx.Where("id = ?", id).First(&job).Error if err != nil { tx.Rollback() return errors.Wrap(err, "cannot found job") } err = j.dispatcher.revokeJob(makeJob(job)) if err != nil { tx.Rollback() return errors.Wrap(err, "revoke job failed") } err = tx.Delete(&job).Error if err != nil { tx.Rollback() return errors.Wrap(err, "delete failed") } } tx.Commit() return } // DispatchOnce 下发任务手动执行单次 func (j *CronJob) DispatchOnce(id uint, node string) (err error) { var job db.CronJob err = j.db.Where("id = ?", id).First(&job).Error if err != nil { return errors.Wrapf(err, "cannot found job") } task := db.CronTask{ JobID: job.ID, Timeout: job.Timeout, Node: node, Status: db.CronTaskStatusWaiting, ExecuteType: db.ExecuteTypeManual, FinishedAt: nil, Script: job.Script, } tx := j.db.Begin() { err := tx.Save(&task).Error if err != nil { tx.Rollback() return err } jobPayload := makeOnceJob(job, task.ID) err = j.dispatcher.dispatchOnceJob(jobPayload, node) if err != nil { tx.Rollback() return err } } return tx.Commit().Error } // ListTask 任务列表 func (j *CronJob) ListTask(params view.ReqQueryTasks) (list []view.CronTask, pagination view.Pagination, err error) { var tasks []db.CronTask page := params.Page if page == 0 { page = 1 } pageSize := params.PageSize if pageSize > 100 { pageSize = 100 } offset := (page - 1) * pageSize query := j.db.Where("job_id = ?", params.ID) if len(params.ExecutedAt) == 2 { query = query.Where("executed_at >= ? and executed_at <= ?", params.ExecutedAt[0], params.ExecutedAt[1]) } eg := errgroup.Group{} eg.Go(func() error { return query.Select([]string{"id", "job_id", "executed_at", "finished_at", "retry_count", "execute_type", "status", "node"}). Limit(pageSize). Offset(offset). Order("created_at desc"). Find(&tasks). Error }) eg.Go(func() error {
if page == 0 { page = 1 // from 1 on } pageSize := params.PageSize if pageSize > 100 { pageSize = 100 } offset := (page - 1) * pageSize query := j.db.Model(&db.CronJob{}) if params.Enable != nil { query = query.Where("enable = ?", *params.Enable) } if params.Name != nil { query = query.Where("name like ?", "%"+*params.Name+"%") } if params.AppName != nil { query = query.Where("app_name = ?", *params.AppName) } if params.User != nil {
identifier_body
config.go
initialize a PkgrConfig passed in by caller func NewConfig(cfgPath string, cfg *PkgrConfig) { err := loadConfigFromPath(cfgPath) if err != nil { log.Fatal("could not detect config at supplied path: " + cfgPath) } err = viper.Unmarshal(cfg) if err != nil { log.Fatalf("error parsing pkgr.yml: %s\n", err) } if len(cfg.Library) == 0 { rs := rcmd.NewRSettings(cfg.RPath) rVersion := rcmd.GetRVersion(&rs) cfg.Library = getLibraryPath(cfg.Lockfile.Type, cfg.RPath, rVersion, rs.Platform, cfg.Library) } // For all cfg values that can be repos, make sure that ~ is expanded to the home directory. cfg.Library = expandTilde(cfg.Library) cfg.RPath = expandTilde(cfg.RPath) cfg.Tarballs = expandTildes(cfg.Tarballs) cfg.Descriptions = expandTildes(cfg.Descriptions) cfg.Repos = expandTildesRepos(cfg.Repos) cfg.Logging.All = expandTilde(cfg.Logging.All) cfg.Logging.Install = expandTilde(cfg.Logging.Install) cfg.Cache = expandTilde(cfg.Cache) return } /// expand the ~ at the beginning of a path to the home directory. /// consider any problems a fatal error. func expandTilde(p string) string { expanded, err := homedir.Expand(p) if err != nil { log.WithFields(log.Fields{ "path": p, "error": err, }).Fatal("problem parsing config file -- could not expand path") } return expanded } /// For a list of repos, expand the ~ at the beginning of each path to the home directory. /// consider any problems a fatal error. func expandTildes(paths []string) []string { var expanded []string for _, p := range paths { newPath := expandTilde(p) expanded = append(expanded, newPath) } return expanded } /// In the PkgrConfig object, Repos are stored as a list of key-value pairs. /// Keys are repo names and values are repos to those repos /// For each key-value pair, expand the prefix ~ to be the home directory, if applicable. /// consider any problems a fatal error. func expandTildesRepos(repos []map[string]string) []map[string]string { var expanded []map[string]string //expanded := make(map[string]string) for _, keyValuePair := range repos { kvpExpanded := make(map[string]string) for key, p := range keyValuePair { // should only be one pair, but loop just in case kvpExpanded[key] = expandTilde(p) } expanded = append(expanded, kvpExpanded) } return expanded } // getRenvLibrary calls renv to discover the library path for the // current working directory. This enables matching renv's location // without trying to implement custom logic that needs to align and // stay up to date with renv's own. func getRenvLibrary(rpath string) (string, error) { log.Trace("invoking renv to get library path") rs := rcmd.NewRSettings(rpath) res, err := rcmd.RunRscriptWithArgs( afero.NewOsFs(), "", rs, []string{"-e", "cat('\n_pkgr_', renv::paths$library(), '_pkgr_\n', sep = '')"}, "") if err != nil { if exerr, ok := err.(*exec.ExitError); ok { log.Warnf("error getting library path from renv: %s\n", exerr.Stderr) } else { log.Warnf("error getting library path from renv: %s\n", err) } return "", err } marker := "_pkgr_" var lib string lines := rp.ScanLines(res) for _, l := range lines { if strings.HasPrefix(l, marker) && strings.HasSuffix(l, marker) { lib = strings.TrimSuffix(strings.TrimPrefix(l, marker), marker) break } } if lib == "" { log.Warnf("did not find renv library in output:\n %q\n", lines) return "", errors.New("Malformed renv library path") } return lib, nil } func getLibraryPath(lockfileType string, rpath string, rversion cran.RVersion, platform string, library string) string { switch lockfileType { case "packrat": library = filepath.Join("packrat", "lib", packratPlatform(platform), rversion.ToFullString()) case "renv": var err error library, err = getRenvLibrary(rpath) if err != nil { log.Fatal("Lockfile type is renv, but calling renv to find library path failed.\n" + "Check that renv is installed or consider using `Library:` instead.") } case "pkgr": default: } if library == "" { log.Fatal("must specify either a Lockfile Type or Library path") } return library } // loadConfigFromPath loads pkc configuration into the global Viper func loadConfigFromPath(configFilename string) error { if configFilename == "" { configFilename = "pkgr.yml" } viper.SetEnvPrefix("pkgr") err := viper.BindEnv("rpath") if err != nil { log.Fatalf("error binding env: %s\n", err) } err = viper.BindEnv("library") if err != nil { log.Fatalf("error binding env: %s\n", err) } configFilename, _ = homedir.Expand(filepath.Clean(configFilename)) viper.SetConfigFile(configFilename) b, err := ioutil.ReadFile(configFilename) // panic if can't find or parse config as this could be explicit to user expectations if err != nil { // panic if can't find or parse config as this could be explicit to user expectations if _, ok := err.(*os.PathError); ok { log.Fatalf("could not find a config file at path: %s", configFilename) } } expb := []byte(os.ExpandEnv(string(b))) err = viper.ReadConfig(bytes.NewReader(expb)) if err != nil { if _, ok := err.(viper.ConfigParseError); ok { // found config file but couldn't parse it, should error log.Fatalf("unable to parse config file with error (%s)", err) } // maybe could be more loose on this later, but for now will require a config file fmt.Println("Error with pkgr config file:") fmt.Println(err) os.Exit(1) } loadDefaultSettings() return nil } // loadDefaultSettings load default settings func loadDefaultSettings()
// IsCustomizationSet ... func IsCustomizationSet(key string, elems []interface{}, elem string) bool { for _, v := range elems { for k, iv := range v.(map[interface{}]interface{}) { if k == elem { for k2 := range iv.(map[interface{}]interface{}) { if k2 == key { return true } } } } } return false } // RemovePackage remove a package from the Package section of the yml config file func RemovePackage(name string) error { cfgname := viper.ConfigFileUsed() err := remove(cfgname, name) if err != nil { return err } return nil } // remove remove a package from the Package section of the yml config file func remove(ymlfile string, packageName string) error { appFS := afero.NewOsFs() yf, _ := afero.ReadFile(appFS, ymlfile) fi, err := os.Stat(ymlfile) if err != nil { return err } var out []byte i := 0 lines := bytes.Split(yf, []byte("\n")) for _, line := range lines { i++ // trim the line to detect the start of the list of packages // but do not write the trimmed string as it may cause an // unneeded file diff to the yml file sline := bytes.TrimLeft(line, " ") if bytes.HasPrefix(sline, []byte("- "+packageName)) { continue } out = append(out, line...) if i < len(lines) { out = append(out, []byte("\n")...) } } err = afero.WriteFile(appFS, ymlfile, out, fi.Mode()) if err != nil { return err } return nil } // SetCustomizations ... set ENV values in Rsettings func SetCustomizations(rSettings rcmd.RSettings, cfg PkgrConfig) rcmd.RSettings { pkgCustomizationsSlice := cfg.Customizations.Packages for _, pkgCustomizations := range pkgCustomizationsSlice { for n, v := range pkgCustom
{ // should be one of Debug,Info,Warn,Error,Fatal,Panic viper.SetDefault("loglevel", "info") // path to R on system, defaults to R in path viper.SetDefault("rpath", "R") // setting this to GOMAXPROCS(0) because NumCPU() won't work well with the scheduler. viper.SetDefault("threads", runtime.GOMAXPROCS(0)) }
identifier_body
config.go
initialize a PkgrConfig passed in by caller func NewConfig(cfgPath string, cfg *PkgrConfig) { err := loadConfigFromPath(cfgPath) if err != nil { log.Fatal("could not detect config at supplied path: " + cfgPath) } err = viper.Unmarshal(cfg) if err != nil { log.Fatalf("error parsing pkgr.yml: %s\n", err) } if len(cfg.Library) == 0 { rs := rcmd.NewRSettings(cfg.RPath) rVersion := rcmd.GetRVersion(&rs) cfg.Library = getLibraryPath(cfg.Lockfile.Type, cfg.RPath, rVersion, rs.Platform, cfg.Library) } // For all cfg values that can be repos, make sure that ~ is expanded to the home directory. cfg.Library = expandTilde(cfg.Library) cfg.RPath = expandTilde(cfg.RPath) cfg.Tarballs = expandTildes(cfg.Tarballs) cfg.Descriptions = expandTildes(cfg.Descriptions) cfg.Repos = expandTildesRepos(cfg.Repos) cfg.Logging.All = expandTilde(cfg.Logging.All) cfg.Logging.Install = expandTilde(cfg.Logging.Install) cfg.Cache = expandTilde(cfg.Cache) return } /// expand the ~ at the beginning of a path to the home directory. /// consider any problems a fatal error. func expandTilde(p string) string { expanded, err := homedir.Expand(p) if err != nil
return expanded } /// For a list of repos, expand the ~ at the beginning of each path to the home directory. /// consider any problems a fatal error. func expandTildes(paths []string) []string { var expanded []string for _, p := range paths { newPath := expandTilde(p) expanded = append(expanded, newPath) } return expanded } /// In the PkgrConfig object, Repos are stored as a list of key-value pairs. /// Keys are repo names and values are repos to those repos /// For each key-value pair, expand the prefix ~ to be the home directory, if applicable. /// consider any problems a fatal error. func expandTildesRepos(repos []map[string]string) []map[string]string { var expanded []map[string]string //expanded := make(map[string]string) for _, keyValuePair := range repos { kvpExpanded := make(map[string]string) for key, p := range keyValuePair { // should only be one pair, but loop just in case kvpExpanded[key] = expandTilde(p) } expanded = append(expanded, kvpExpanded) } return expanded } // getRenvLibrary calls renv to discover the library path for the // current working directory. This enables matching renv's location // without trying to implement custom logic that needs to align and // stay up to date with renv's own. func getRenvLibrary(rpath string) (string, error) { log.Trace("invoking renv to get library path") rs := rcmd.NewRSettings(rpath) res, err := rcmd.RunRscriptWithArgs( afero.NewOsFs(), "", rs, []string{"-e", "cat('\n_pkgr_', renv::paths$library(), '_pkgr_\n', sep = '')"}, "") if err != nil { if exerr, ok := err.(*exec.ExitError); ok { log.Warnf("error getting library path from renv: %s\n", exerr.Stderr) } else { log.Warnf("error getting library path from renv: %s\n", err) } return "", err } marker := "_pkgr_" var lib string lines := rp.ScanLines(res) for _, l := range lines { if strings.HasPrefix(l, marker) && strings.HasSuffix(l, marker) { lib = strings.TrimSuffix(strings.TrimPrefix(l, marker), marker) break } } if lib == "" { log.Warnf("did not find renv library in output:\n %q\n", lines) return "", errors.New("Malformed renv library path") } return lib, nil } func getLibraryPath(lockfileType string, rpath string, rversion cran.RVersion, platform string, library string) string { switch lockfileType { case "packrat": library = filepath.Join("packrat", "lib", packratPlatform(platform), rversion.ToFullString()) case "renv": var err error library, err = getRenvLibrary(rpath) if err != nil { log.Fatal("Lockfile type is renv, but calling renv to find library path failed.\n" + "Check that renv is installed or consider using `Library:` instead.") } case "pkgr": default: } if library == "" { log.Fatal("must specify either a Lockfile Type or Library path") } return library } // loadConfigFromPath loads pkc configuration into the global Viper func loadConfigFromPath(configFilename string) error { if configFilename == "" { configFilename = "pkgr.yml" } viper.SetEnvPrefix("pkgr") err := viper.BindEnv("rpath") if err != nil { log.Fatalf("error binding env: %s\n", err) } err = viper.BindEnv("library") if err != nil { log.Fatalf("error binding env: %s\n", err) } configFilename, _ = homedir.Expand(filepath.Clean(configFilename)) viper.SetConfigFile(configFilename) b, err := ioutil.ReadFile(configFilename) // panic if can't find or parse config as this could be explicit to user expectations if err != nil { // panic if can't find or parse config as this could be explicit to user expectations if _, ok := err.(*os.PathError); ok { log.Fatalf("could not find a config file at path: %s", configFilename) } } expb := []byte(os.ExpandEnv(string(b))) err = viper.ReadConfig(bytes.NewReader(expb)) if err != nil { if _, ok := err.(viper.ConfigParseError); ok { // found config file but couldn't parse it, should error log.Fatalf("unable to parse config file with error (%s)", err) } // maybe could be more loose on this later, but for now will require a config file fmt.Println("Error with pkgr config file:") fmt.Println(err) os.Exit(1) } loadDefaultSettings() return nil } // loadDefaultSettings load default settings func loadDefaultSettings() { // should be one of Debug,Info,Warn,Error,Fatal,Panic viper.SetDefault("loglevel", "info") // path to R on system, defaults to R in path viper.SetDefault("rpath", "R") // setting this to GOMAXPROCS(0) because NumCPU() won't work well with the scheduler. viper.SetDefault("threads", runtime.GOMAXPROCS(0)) } // IsCustomizationSet ... func IsCustomizationSet(key string, elems []interface{}, elem string) bool { for _, v := range elems { for k, iv := range v.(map[interface{}]interface{}) { if k == elem { for k2 := range iv.(map[interface{}]interface{}) { if k2 == key { return true } } } } } return false } // RemovePackage remove a package from the Package section of the yml config file func RemovePackage(name string) error { cfgname := viper.ConfigFileUsed() err := remove(cfgname, name) if err != nil { return err } return nil } // remove remove a package from the Package section of the yml config file func remove(ymlfile string, packageName string) error { appFS := afero.NewOsFs() yf, _ := afero.ReadFile(appFS, ymlfile) fi, err := os.Stat(ymlfile) if err != nil { return err } var out []byte i := 0 lines := bytes.Split(yf, []byte("\n")) for _, line := range lines { i++ // trim the line to detect the start of the list of packages // but do not write the trimmed string as it may cause an // unneeded file diff to the yml file sline := bytes.TrimLeft(line, " ") if bytes.HasPrefix(sline, []byte("- "+packageName)) { continue } out = append(out, line...) if i < len(lines) { out = append(out, []byte("\n")...) } } err = afero.WriteFile(appFS, ymlfile, out, fi.Mode()) if err != nil { return err } return nil } // SetCustomizations ... set ENV values in Rsettings func SetCustomizations(rSettings rcmd.RSettings, cfg PkgrConfig) rcmd.RSettings { pkgCustomizationsSlice := cfg.Customizations.Packages for _, pkgCustomizations := range pkgCustomizationsSlice { for n, v := range pkgCustom
{ log.WithFields(log.Fields{ "path": p, "error": err, }).Fatal("problem parsing config file -- could not expand path") }
conditional_block
config.go
Config initialize a PkgrConfig passed in by caller func NewConfig(cfgPath string, cfg *PkgrConfig) { err := loadConfigFromPath(cfgPath) if err != nil { log.Fatal("could not detect config at supplied path: " + cfgPath) } err = viper.Unmarshal(cfg) if err != nil { log.Fatalf("error parsing pkgr.yml: %s\n", err) } if len(cfg.Library) == 0 { rs := rcmd.NewRSettings(cfg.RPath) rVersion := rcmd.GetRVersion(&rs) cfg.Library = getLibraryPath(cfg.Lockfile.Type, cfg.RPath, rVersion, rs.Platform, cfg.Library) } // For all cfg values that can be repos, make sure that ~ is expanded to the home directory. cfg.Library = expandTilde(cfg.Library) cfg.RPath = expandTilde(cfg.RPath) cfg.Tarballs = expandTildes(cfg.Tarballs) cfg.Descriptions = expandTildes(cfg.Descriptions) cfg.Repos = expandTildesRepos(cfg.Repos) cfg.Logging.All = expandTilde(cfg.Logging.All) cfg.Logging.Install = expandTilde(cfg.Logging.Install) cfg.Cache = expandTilde(cfg.Cache) return } /// expand the ~ at the beginning of a path to the home directory. /// consider any problems a fatal error. func expandTilde(p string) string { expanded, err := homedir.Expand(p) if err != nil { log.WithFields(log.Fields{ "path": p, "error": err, }).Fatal("problem parsing config file -- could not expand path") } return expanded } /// For a list of repos, expand the ~ at the beginning of each path to the home directory. /// consider any problems a fatal error. func expandTildes(paths []string) []string { var expanded []string for _, p := range paths { newPath := expandTilde(p) expanded = append(expanded, newPath) } return expanded } /// In the PkgrConfig object, Repos are stored as a list of key-value pairs. /// Keys are repo names and values are repos to those repos /// For each key-value pair, expand the prefix ~ to be the home directory, if applicable. /// consider any problems a fatal error. func expandTildesRepos(repos []map[string]string) []map[string]string { var expanded []map[string]string //expanded := make(map[string]string) for _, keyValuePair := range repos { kvpExpanded := make(map[string]string) for key, p := range keyValuePair { // should only be one pair, but loop just in case kvpExpanded[key] = expandTilde(p) } expanded = append(expanded, kvpExpanded) } return expanded } // getRenvLibrary calls renv to discover the library path for the // current working directory. This enables matching renv's location // without trying to implement custom logic that needs to align and // stay up to date with renv's own. func getRenvLibrary(rpath string) (string, error) { log.Trace("invoking renv to get library path") rs := rcmd.NewRSettings(rpath) res, err := rcmd.RunRscriptWithArgs( afero.NewOsFs(), "", rs, []string{"-e", "cat('\n_pkgr_', renv::paths$library(), '_pkgr_\n', sep = '')"}, "") if err != nil { if exerr, ok := err.(*exec.ExitError); ok { log.Warnf("error getting library path from renv: %s\n", exerr.Stderr) } else { log.Warnf("error getting library path from renv: %s\n", err) } return "", err } marker := "_pkgr_" var lib string lines := rp.ScanLines(res) for _, l := range lines { if strings.HasPrefix(l, marker) && strings.HasSuffix(l, marker) { lib = strings.TrimSuffix(strings.TrimPrefix(l, marker), marker) break } } if lib == "" { log.Warnf("did not find renv library in output:\n %q\n", lines) return "", errors.New("Malformed renv library path") } return lib, nil } func getLibraryPath(lockfileType string, rpath string, rversion cran.RVersion, platform string, library string) string { switch lockfileType { case "packrat": library = filepath.Join("packrat", "lib", packratPlatform(platform), rversion.ToFullString()) case "renv": var err error library, err = getRenvLibrary(rpath) if err != nil { log.Fatal("Lockfile type is renv, but calling renv to find library path failed.\n" + "Check that renv is installed or consider using `Library:` instead.") } case "pkgr": default: }
return library } // loadConfigFromPath loads pkc configuration into the global Viper func loadConfigFromPath(configFilename string) error { if configFilename == "" { configFilename = "pkgr.yml" } viper.SetEnvPrefix("pkgr") err := viper.BindEnv("rpath") if err != nil { log.Fatalf("error binding env: %s\n", err) } err = viper.BindEnv("library") if err != nil { log.Fatalf("error binding env: %s\n", err) } configFilename, _ = homedir.Expand(filepath.Clean(configFilename)) viper.SetConfigFile(configFilename) b, err := ioutil.ReadFile(configFilename) // panic if can't find or parse config as this could be explicit to user expectations if err != nil { // panic if can't find or parse config as this could be explicit to user expectations if _, ok := err.(*os.PathError); ok { log.Fatalf("could not find a config file at path: %s", configFilename) } } expb := []byte(os.ExpandEnv(string(b))) err = viper.ReadConfig(bytes.NewReader(expb)) if err != nil { if _, ok := err.(viper.ConfigParseError); ok { // found config file but couldn't parse it, should error log.Fatalf("unable to parse config file with error (%s)", err) } // maybe could be more loose on this later, but for now will require a config file fmt.Println("Error with pkgr config file:") fmt.Println(err) os.Exit(1) } loadDefaultSettings() return nil } // loadDefaultSettings load default settings func loadDefaultSettings() { // should be one of Debug,Info,Warn,Error,Fatal,Panic viper.SetDefault("loglevel", "info") // path to R on system, defaults to R in path viper.SetDefault("rpath", "R") // setting this to GOMAXPROCS(0) because NumCPU() won't work well with the scheduler. viper.SetDefault("threads", runtime.GOMAXPROCS(0)) } // IsCustomizationSet ... func IsCustomizationSet(key string, elems []interface{}, elem string) bool { for _, v := range elems { for k, iv := range v.(map[interface{}]interface{}) { if k == elem { for k2 := range iv.(map[interface{}]interface{}) { if k2 == key { return true } } } } } return false } // RemovePackage remove a package from the Package section of the yml config file func RemovePackage(name string) error { cfgname := viper.ConfigFileUsed() err := remove(cfgname, name) if err != nil { return err } return nil } // remove remove a package from the Package section of the yml config file func remove(ymlfile string, packageName string) error { appFS := afero.NewOsFs() yf, _ := afero.ReadFile(appFS, ymlfile) fi, err := os.Stat(ymlfile) if err != nil { return err } var out []byte i := 0 lines := bytes.Split(yf, []byte("\n")) for _, line := range lines { i++ // trim the line to detect the start of the list of packages // but do not write the trimmed string as it may cause an // unneeded file diff to the yml file sline := bytes.TrimLeft(line, " ") if bytes.HasPrefix(sline, []byte("- "+packageName)) { continue } out = append(out, line...) if i < len(lines) { out = append(out, []byte("\n")...) } } err = afero.WriteFile(appFS, ymlfile, out, fi.Mode()) if err != nil { return err } return nil } // SetCustomizations ... set ENV values in Rsettings func SetCustomizations(rSettings rcmd.RSettings, cfg PkgrConfig) rcmd.RSettings { pkgCustomizationsSlice := cfg.Customizations.Packages for _, pkgCustomizations := range pkgCustomizationsSlice { for n, v := range pkgCustomizations
if library == "" { log.Fatal("must specify either a Lockfile Type or Library path") }
random_line_split
config.go
initialize a PkgrConfig passed in by caller func NewConfig(cfgPath string, cfg *PkgrConfig) { err := loadConfigFromPath(cfgPath) if err != nil { log.Fatal("could not detect config at supplied path: " + cfgPath) } err = viper.Unmarshal(cfg) if err != nil { log.Fatalf("error parsing pkgr.yml: %s\n", err) } if len(cfg.Library) == 0 { rs := rcmd.NewRSettings(cfg.RPath) rVersion := rcmd.GetRVersion(&rs) cfg.Library = getLibraryPath(cfg.Lockfile.Type, cfg.RPath, rVersion, rs.Platform, cfg.Library) } // For all cfg values that can be repos, make sure that ~ is expanded to the home directory. cfg.Library = expandTilde(cfg.Library) cfg.RPath = expandTilde(cfg.RPath) cfg.Tarballs = expandTildes(cfg.Tarballs) cfg.Descriptions = expandTildes(cfg.Descriptions) cfg.Repos = expandTildesRepos(cfg.Repos) cfg.Logging.All = expandTilde(cfg.Logging.All) cfg.Logging.Install = expandTilde(cfg.Logging.Install) cfg.Cache = expandTilde(cfg.Cache) return } /// expand the ~ at the beginning of a path to the home directory. /// consider any problems a fatal error. func expandTilde(p string) string { expanded, err := homedir.Expand(p) if err != nil { log.WithFields(log.Fields{ "path": p, "error": err, }).Fatal("problem parsing config file -- could not expand path") } return expanded } /// For a list of repos, expand the ~ at the beginning of each path to the home directory. /// consider any problems a fatal error. func expandTildes(paths []string) []string { var expanded []string for _, p := range paths { newPath := expandTilde(p) expanded = append(expanded, newPath) } return expanded } /// In the PkgrConfig object, Repos are stored as a list of key-value pairs. /// Keys are repo names and values are repos to those repos /// For each key-value pair, expand the prefix ~ to be the home directory, if applicable. /// consider any problems a fatal error. func expandTildesRepos(repos []map[string]string) []map[string]string { var expanded []map[string]string //expanded := make(map[string]string) for _, keyValuePair := range repos { kvpExpanded := make(map[string]string) for key, p := range keyValuePair { // should only be one pair, but loop just in case kvpExpanded[key] = expandTilde(p) } expanded = append(expanded, kvpExpanded) } return expanded } // getRenvLibrary calls renv to discover the library path for the // current working directory. This enables matching renv's location // without trying to implement custom logic that needs to align and // stay up to date with renv's own. func getRenvLibrary(rpath string) (string, error) { log.Trace("invoking renv to get library path") rs := rcmd.NewRSettings(rpath) res, err := rcmd.RunRscriptWithArgs( afero.NewOsFs(), "", rs, []string{"-e", "cat('\n_pkgr_', renv::paths$library(), '_pkgr_\n', sep = '')"}, "") if err != nil { if exerr, ok := err.(*exec.ExitError); ok { log.Warnf("error getting library path from renv: %s\n", exerr.Stderr) } else { log.Warnf("error getting library path from renv: %s\n", err) } return "", err } marker := "_pkgr_" var lib string lines := rp.ScanLines(res) for _, l := range lines { if strings.HasPrefix(l, marker) && strings.HasSuffix(l, marker) { lib = strings.TrimSuffix(strings.TrimPrefix(l, marker), marker) break } } if lib == "" { log.Warnf("did not find renv library in output:\n %q\n", lines) return "", errors.New("Malformed renv library path") } return lib, nil } func
(lockfileType string, rpath string, rversion cran.RVersion, platform string, library string) string { switch lockfileType { case "packrat": library = filepath.Join("packrat", "lib", packratPlatform(platform), rversion.ToFullString()) case "renv": var err error library, err = getRenvLibrary(rpath) if err != nil { log.Fatal("Lockfile type is renv, but calling renv to find library path failed.\n" + "Check that renv is installed or consider using `Library:` instead.") } case "pkgr": default: } if library == "" { log.Fatal("must specify either a Lockfile Type or Library path") } return library } // loadConfigFromPath loads pkc configuration into the global Viper func loadConfigFromPath(configFilename string) error { if configFilename == "" { configFilename = "pkgr.yml" } viper.SetEnvPrefix("pkgr") err := viper.BindEnv("rpath") if err != nil { log.Fatalf("error binding env: %s\n", err) } err = viper.BindEnv("library") if err != nil { log.Fatalf("error binding env: %s\n", err) } configFilename, _ = homedir.Expand(filepath.Clean(configFilename)) viper.SetConfigFile(configFilename) b, err := ioutil.ReadFile(configFilename) // panic if can't find or parse config as this could be explicit to user expectations if err != nil { // panic if can't find or parse config as this could be explicit to user expectations if _, ok := err.(*os.PathError); ok { log.Fatalf("could not find a config file at path: %s", configFilename) } } expb := []byte(os.ExpandEnv(string(b))) err = viper.ReadConfig(bytes.NewReader(expb)) if err != nil { if _, ok := err.(viper.ConfigParseError); ok { // found config file but couldn't parse it, should error log.Fatalf("unable to parse config file with error (%s)", err) } // maybe could be more loose on this later, but for now will require a config file fmt.Println("Error with pkgr config file:") fmt.Println(err) os.Exit(1) } loadDefaultSettings() return nil } // loadDefaultSettings load default settings func loadDefaultSettings() { // should be one of Debug,Info,Warn,Error,Fatal,Panic viper.SetDefault("loglevel", "info") // path to R on system, defaults to R in path viper.SetDefault("rpath", "R") // setting this to GOMAXPROCS(0) because NumCPU() won't work well with the scheduler. viper.SetDefault("threads", runtime.GOMAXPROCS(0)) } // IsCustomizationSet ... func IsCustomizationSet(key string, elems []interface{}, elem string) bool { for _, v := range elems { for k, iv := range v.(map[interface{}]interface{}) { if k == elem { for k2 := range iv.(map[interface{}]interface{}) { if k2 == key { return true } } } } } return false } // RemovePackage remove a package from the Package section of the yml config file func RemovePackage(name string) error { cfgname := viper.ConfigFileUsed() err := remove(cfgname, name) if err != nil { return err } return nil } // remove remove a package from the Package section of the yml config file func remove(ymlfile string, packageName string) error { appFS := afero.NewOsFs() yf, _ := afero.ReadFile(appFS, ymlfile) fi, err := os.Stat(ymlfile) if err != nil { return err } var out []byte i := 0 lines := bytes.Split(yf, []byte("\n")) for _, line := range lines { i++ // trim the line to detect the start of the list of packages // but do not write the trimmed string as it may cause an // unneeded file diff to the yml file sline := bytes.TrimLeft(line, " ") if bytes.HasPrefix(sline, []byte("- "+packageName)) { continue } out = append(out, line...) if i < len(lines) { out = append(out, []byte("\n")...) } } err = afero.WriteFile(appFS, ymlfile, out, fi.Mode()) if err != nil { return err } return nil } // SetCustomizations ... set ENV values in Rsettings func SetCustomizations(rSettings rcmd.RSettings, cfg PkgrConfig) rcmd.RSettings { pkgCustomizationsSlice := cfg.Customizations.Packages for _, pkgCustomizations := range pkgCustomizationsSlice { for n, v := range pkgCustomizations
getLibraryPath
identifier_name
groups.component.ts
-column'; import { FilterService } from '../../services/filter-service/filter.service'; import { AuthService } from './../../services/auth.service'; import { BlockingGroupResponseDTO, GroupDataService, GroupResponseDTO } from './../../services/dataServices/group-data.service'; import { NO_LOGO, DELETE_SUCCESSFUL, ERROR_DELETE_GROUP, EDIT_SUCCESSFUL, EDIT_FAILED, NAME_FIELD_EMPTY, CREATE_SUCCESSFUL, CREATE_FAILED, ERROR_LOADING_GROUP } from 'src/app/globals'; @Component({ selector: 'app-groups', templateUrl: './groups.component.html', styleUrls: ['./groups.component.css'] }) export class GroupsComponent implements OnInit, OnDestroy { @ViewChild('logoBox', { static: true}) logoBoxRef: ElementRef<HTMLDivElement>; subscriptions: Subscription = new Subscription(); @Input() stateNotNecessary: boolean; SheetMode: typeof SheetMode = SheetMode; groups: GroupResponseDTO[] = []; columns: TableColumn[] = []; group: { id?: string,
primaryColor: string = ''; accentColor: string = ''; warnColor = ''; sheetMode: SheetMode = SheetMode.Closed; fields: DetailedField[]; title: string = 'Group'; userName: string; userToken: any; private memberID: string; sysAdmin: boolean = false; disableSaveButton: boolean = false; showBlocks: boolean = false; blockingGroupsLists: BlockingGroupResponseDTO; selectedAvatar: string = './../../assets/avatar/round default.svg'; logoPath: string = ''; subscriptionHotkey: Subscription[] = []; constructor( private readonly router: Router, private readonly route: ActivatedRoute, private readonly filterService: FilterService, private readonly messageService: MessageService, private readonly groupDataService: GroupDataService, private readonly authService: AuthService, private readonly userDataService: UserDataService, private readonly themeDataService: ThemeDataService, private readonly hotkeys: Hotkeys) { this.fields = [ { title: 'Name', key: 'name', type: FieldType.Text, readonly: false }, { title: 'Description', key: 'description', type: FieldType.Text_Variable, readonly: false, minRows: 3, maxRows: 10 } ]; this.deleteGroups = this.deleteGroups.bind(this); // Decode UserToken to check for SysAdmin this.authService.getUserToken().then((value: string) => { this.userToken = value; let parts: string[]; if (this.userToken) { parts = this.userToken.split('.'); this.userToken = JSON.parse(atob(parts[1])); if (this.userToken.isSystemAdmin === true) { this.sysAdmin = true; } else { this.sysAdmin = false; } }}); // get the icon from backend this.userDataService.getIcon(this.authService.getUserID(), this.userName).then(value => { if (value) { this.selectedAvatar = value; } }); this.themeDataService.getLogo().then((value: any) => { if (value !== null) { const doc = new DOMParser().parseFromString(value, 'image/svg+xml'); console.log(doc); doc.documentElement.setAttribute('height', '100%'); this.logoBoxRef.nativeElement.appendChild( this.logoBoxRef.nativeElement.ownerDocument.importNode(doc.documentElement, true) ); } else { this.messageService.add({ severity: 'warn', summary: NO_LOGO}); } }).catch((error: HttpErrorResponse) => { console.log(NO_LOGO); }); } ngOnInit(): void { this.userName = this.authService.getUserName(); this.userDataService.getTheme(this.authService.getUserID()).then(value => { if (value !== null) { this.themeDataService.getThemeByID(value).then(value => { if (value !== null) { let color: string = value.colors; let parts = color.split('_'); this.primaryColor = parts[0]; this.accentColor = parts[1]; this.warnColor = parts[2]; this.setColors(); } }); } }); this.subscriptions.add(this.route.paramMap.subscribe((params: ParamMap) => { this.memberID = this.authService.getUserID(); if (params.get('showBlocks') && params.get('showBlocks').toLowerCase() === 'true') { this.groupDataService.getAllBlockingGroupsOfUser(this.memberID).then((value: BlockingGroupResponseDTO) => { this.deletionState = true; this.blockingGroupsLists = value; this.initColumns(); this.loadData(); console.log(this.blockingGroupsLists); }); } else { this.initColumns(); this.loadData(); } })); this.hotkeys.newMap(); this.subscriptionHotkey.push(this.hotkeys.addShortcut({ keys: 'shift.control.n', description: 'Create Group' }).subscribe(() => { this.createGroup(); })); this.subscriptionHotkey.push(this.hotkeys.addShortcut({ keys: 'shift.control.p', description: 'Project Selection' }).subscribe(() => { this.router.navigate(['/project-overview']); })); this.stateNotNecessary = false; } deleteGroups($event): void { const list: any[] = $event; if (list.length === 0) { return; } Promise.all(list.map((elem: any) => { return this.groupDataService.deleteGroup(elem.id); })).then(() => { this.messageService.add({ severity: 'success', summary: DELETE_SUCCESSFUL }); }).catch((response: HttpErrorResponse) => { this.messageService.add({ severity: 'error', summary: ERROR_DELETE_GROUP, detail: response.message }); }).finally(() => { this.loadData(); }); } createGroup(): void { this.sheetMode = SheetMode.New; this.group = { name: '', description: '' }; } saveGroup(group): void { this.filterService.ClearSelectionEmitter.emit(true); this.disableSaveButton = true; if (group.mode === SheetMode.EditWithLock) { if (this.group.name !== '') { const groupEntity: { name: string, description: string } = { name: group.ent.name, description: group.ent.description }; this.groupDataService.alterGroup(group.id, groupEntity) .then(() => { this.messageService.add({ severity: 'success', summary: EDIT_SUCCESSFUL }); this.closeSheet(); }).catch((response: HttpErrorResponse) => { this.messageService.add({ severity: 'error', summary: EDIT_FAILED, detail: response.message }); }).finally(() => { this.disableSaveButton = false; this.loadData(); }); } else { this.messageService.add({ severity: 'error', summary: NAME_FIELD_EMPTY }); this.disableSaveButton = false; } } else if (group.mode === SheetMode.New) { if (this.group.name !== '') { this.groupDataService.createGroup(group.ent) .then(() => { this.messageService.add({ severity: 'success', summary: CREATE_SUCCESSFUL }); this.closeSheet(); }).catch((response: HttpErrorResponse) => { this.messageService.add({ severity: 'error', summary: CREATE_FAILED, detail: response.message }); }).finally(() => { this.disableSaveButton = false; this.loadData(); }); } else { this.messageService.add({ severity: 'error', summary: NAME_FIELD_EMPTY }); this.disableSaveButton = false; } } } private initColumns(): void { this.columns = [ { key: 'select', title: 'Select', type: ColumnType.Checkbox, style: { width: '10%' } }, { key: 'name', title: 'Group-Name', type: ColumnType.Text, style: { width: '62%' } }, { key: 'accessLevel', title: 'Role', type: ColumnType.Text, style: { width: '19%' } }, { key: 'edit', title: 'Edit', type: ColumnType.Button, style: { width: '3%' } }, { key: 'show', title: 'Show', type: ColumnType.Button, style: { width: '3%' } }, { key: 'members', title: 'Members', type: ColumnType.Button, style: { width: '3%' } } ]; if (this.deletionState) { this.columns[1].style = { width: '52%' }; this.columns.splice(2, 0, { key: 'deletion', title: 'Allows Deletion', type: ColumnType.Group_Deletion, style: { 'width': '10%'} }); } } private loadData(): void { this.groupDataService.getAllGroupsOfUser(this.memberID).then((value: GroupResponseDTO[]) => { this.groups = value; if (this.deletionState) { this.groups = this.groups.map((ele: GroupResponseDTO) => ({ ...ele, deletion: this.getGroupDeletionTooltipp(ele.id), })); } }).catch((response: HttpErrorResponse) => { this.messageService.add({ severity: 'error', summary: ERROR_LOADING_GROUP, detail: response.message }); }); } private getGroupDeletionTooltipp(groupId: string): string { if (this.blocking
name: string, description: string }; deletionState: boolean = false;
random_line_split
groups.component.ts
: string = 'Group'; userName: string; userToken: any; private memberID: string; sysAdmin: boolean = false; disableSaveButton: boolean = false; showBlocks: boolean = false; blockingGroupsLists: BlockingGroupResponseDTO; selectedAvatar: string = './../../assets/avatar/round default.svg'; logoPath: string = ''; subscriptionHotkey: Subscription[] = []; constructor( private readonly router: Router, private readonly route: ActivatedRoute, private readonly filterService: FilterService, private readonly messageService: MessageService, private readonly groupDataService: GroupDataService, private readonly authService: AuthService, private readonly userDataService: UserDataService, private readonly themeDataService: ThemeDataService, private readonly hotkeys: Hotkeys) { this.fields = [ { title: 'Name', key: 'name', type: FieldType.Text, readonly: false }, { title: 'Description', key: 'description', type: FieldType.Text_Variable, readonly: false, minRows: 3, maxRows: 10 } ]; this.deleteGroups = this.deleteGroups.bind(this); // Decode UserToken to check for SysAdmin this.authService.getUserToken().then((value: string) => { this.userToken = value; let parts: string[]; if (this.userToken) { parts = this.userToken.split('.'); this.userToken = JSON.parse(atob(parts[1])); if (this.userToken.isSystemAdmin === true) { this.sysAdmin = true; } else { this.sysAdmin = false; } }}); // get the icon from backend this.userDataService.getIcon(this.authService.getUserID(), this.userName).then(value => { if (value) { this.selectedAvatar = value; } }); this.themeDataService.getLogo().then((value: any) => { if (value !== null) { const doc = new DOMParser().parseFromString(value, 'image/svg+xml'); console.log(doc); doc.documentElement.setAttribute('height', '100%'); this.logoBoxRef.nativeElement.appendChild( this.logoBoxRef.nativeElement.ownerDocument.importNode(doc.documentElement, true) ); } else { this.messageService.add({ severity: 'warn', summary: NO_LOGO}); } }).catch((error: HttpErrorResponse) => { console.log(NO_LOGO); }); } ngOnInit(): void { this.userName = this.authService.getUserName(); this.userDataService.getTheme(this.authService.getUserID()).then(value => { if (value !== null) { this.themeDataService.getThemeByID(value).then(value => { if (value !== null) { let color: string = value.colors; let parts = color.split('_'); this.primaryColor = parts[0]; this.accentColor = parts[1]; this.warnColor = parts[2]; this.setColors(); } }); } }); this.subscriptions.add(this.route.paramMap.subscribe((params: ParamMap) => { this.memberID = this.authService.getUserID(); if (params.get('showBlocks') && params.get('showBlocks').toLowerCase() === 'true') { this.groupDataService.getAllBlockingGroupsOfUser(this.memberID).then((value: BlockingGroupResponseDTO) => { this.deletionState = true; this.blockingGroupsLists = value; this.initColumns(); this.loadData(); console.log(this.blockingGroupsLists); }); } else { this.initColumns(); this.loadData(); } })); this.hotkeys.newMap(); this.subscriptionHotkey.push(this.hotkeys.addShortcut({ keys: 'shift.control.n', description: 'Create Group' }).subscribe(() => { this.createGroup(); })); this.subscriptionHotkey.push(this.hotkeys.addShortcut({ keys: 'shift.control.p', description: 'Project Selection' }).subscribe(() => { this.router.navigate(['/project-overview']); })); this.stateNotNecessary = false; } deleteGroups($event): void { const list: any[] = $event; if (list.length === 0) { return; } Promise.all(list.map((elem: any) => { return this.groupDataService.deleteGroup(elem.id); })).then(() => { this.messageService.add({ severity: 'success', summary: DELETE_SUCCESSFUL }); }).catch((response: HttpErrorResponse) => { this.messageService.add({ severity: 'error', summary: ERROR_DELETE_GROUP, detail: response.message }); }).finally(() => { this.loadData(); }); } createGroup(): void { this.sheetMode = SheetMode.New; this.group = { name: '', description: '' }; } saveGroup(group): void { this.filterService.ClearSelectionEmitter.emit(true); this.disableSaveButton = true; if (group.mode === SheetMode.EditWithLock) { if (this.group.name !== '') { const groupEntity: { name: string, description: string } = { name: group.ent.name, description: group.ent.description }; this.groupDataService.alterGroup(group.id, groupEntity) .then(() => { this.messageService.add({ severity: 'success', summary: EDIT_SUCCESSFUL }); this.closeSheet(); }).catch((response: HttpErrorResponse) => { this.messageService.add({ severity: 'error', summary: EDIT_FAILED, detail: response.message }); }).finally(() => { this.disableSaveButton = false; this.loadData(); }); } else { this.messageService.add({ severity: 'error', summary: NAME_FIELD_EMPTY }); this.disableSaveButton = false; } } else if (group.mode === SheetMode.New) { if (this.group.name !== '') { this.groupDataService.createGroup(group.ent) .then(() => { this.messageService.add({ severity: 'success', summary: CREATE_SUCCESSFUL }); this.closeSheet(); }).catch((response: HttpErrorResponse) => { this.messageService.add({ severity: 'error', summary: CREATE_FAILED, detail: response.message }); }).finally(() => { this.disableSaveButton = false; this.loadData(); }); } else { this.messageService.add({ severity: 'error', summary: NAME_FIELD_EMPTY }); this.disableSaveButton = false; } } } private initColumns(): void { this.columns = [ { key: 'select', title: 'Select', type: ColumnType.Checkbox, style: { width: '10%' } }, { key: 'name', title: 'Group-Name', type: ColumnType.Text, style: { width: '62%' } }, { key: 'accessLevel', title: 'Role', type: ColumnType.Text, style: { width: '19%' } }, { key: 'edit', title: 'Edit', type: ColumnType.Button, style: { width: '3%' } }, { key: 'show', title: 'Show', type: ColumnType.Button, style: { width: '3%' } }, { key: 'members', title: 'Members', type: ColumnType.Button, style: { width: '3%' } } ]; if (this.deletionState) { this.columns[1].style = { width: '52%' }; this.columns.splice(2, 0, { key: 'deletion', title: 'Allows Deletion', type: ColumnType.Group_Deletion, style: { 'width': '10%'} }); } } private loadData(): void { this.groupDataService.getAllGroupsOfUser(this.memberID).then((value: GroupResponseDTO[]) => { this.groups = value; if (this.deletionState) { this.groups = this.groups.map((ele: GroupResponseDTO) => ({ ...ele, deletion: this.getGroupDeletionTooltipp(ele.id), })); } }).catch((response: HttpErrorResponse) => { this.messageService.add({ severity: 'error', summary: ERROR_LOADING_GROUP, detail: response.message }); }); } private getGroupDeletionTooltipp(groupId: string): string { if (this.blockingGroupsLists.ONLY_ADMIN_MULTI_USER.includes(groupId)) { return 'Make someone admin or remove all other users'; } else if (this.blockingGroupsLists.ONLY_USER_GROUP_WITH_PROJECTS.includes(groupId)) { return 'Delete all projects or add users'; } return undefined; } /** * Toggles the DetailedSheet * 1. Click Edit-/View button or on table row --> onClickEdit(...) of main-Table is called * 2. onClickEdit fires toggleEvent EventEmitter * 3. toggleEvent emitter triggers toggleSheet function in the .html-part of the component * 4. In toggleSheet function the detailed sheet content can be accessed (data is the selected element) * @param data: the data coming from the mainTable */ toggleSheet(data): void { this.disableSaveButton = false; let id: string; if (this.group) { id = this.group.id; } this.sheetMode = DetailedSheetUtils.toggle(id, data.entity.id, this.sheetMode, data.mode); this.group = { id: data.entity.id, description: data.entity.description, name: data.entity.name }; }
closeSheet
identifier_name
groups.component.ts
-column'; import { FilterService } from '../../services/filter-service/filter.service'; import { AuthService } from './../../services/auth.service'; import { BlockingGroupResponseDTO, GroupDataService, GroupResponseDTO } from './../../services/dataServices/group-data.service'; import { NO_LOGO, DELETE_SUCCESSFUL, ERROR_DELETE_GROUP, EDIT_SUCCESSFUL, EDIT_FAILED, NAME_FIELD_EMPTY, CREATE_SUCCESSFUL, CREATE_FAILED, ERROR_LOADING_GROUP } from 'src/app/globals'; @Component({ selector: 'app-groups', templateUrl: './groups.component.html', styleUrls: ['./groups.component.css'] }) export class GroupsComponent implements OnInit, OnDestroy { @ViewChild('logoBox', { static: true}) logoBoxRef: ElementRef<HTMLDivElement>; subscriptions: Subscription = new Subscription(); @Input() stateNotNecessary: boolean; SheetMode: typeof SheetMode = SheetMode; groups: GroupResponseDTO[] = []; columns: TableColumn[] = []; group: { id?: string, name: string, description: string }; deletionState: boolean = false; primaryColor: string = ''; accentColor: string = ''; warnColor = ''; sheetMode: SheetMode = SheetMode.Closed; fields: DetailedField[]; title: string = 'Group'; userName: string; userToken: any; private memberID: string; sysAdmin: boolean = false; disableSaveButton: boolean = false; showBlocks: boolean = false; blockingGroupsLists: BlockingGroupResponseDTO; selectedAvatar: string = './../../assets/avatar/round default.svg'; logoPath: string = ''; subscriptionHotkey: Subscription[] = []; constructor( private readonly router: Router, private readonly route: ActivatedRoute, private readonly filterService: FilterService, private readonly messageService: MessageService, private readonly groupDataService: GroupDataService, private readonly authService: AuthService, private readonly userDataService: UserDataService, private readonly themeDataService: ThemeDataService, private readonly hotkeys: Hotkeys) { this.fields = [ { title: 'Name', key: 'name', type: FieldType.Text, readonly: false }, { title: 'Description', key: 'description', type: FieldType.Text_Variable, readonly: false, minRows: 3, maxRows: 10 } ]; this.deleteGroups = this.deleteGroups.bind(this); // Decode UserToken to check for SysAdmin this.authService.getUserToken().then((value: string) => { this.userToken = value; let parts: string[]; if (this.userToken) { parts = this.userToken.split('.'); this.userToken = JSON.parse(atob(parts[1])); if (this.userToken.isSystemAdmin === true) { this.sysAdmin = true; } else { this.sysAdmin = false; } }}); // get the icon from backend this.userDataService.getIcon(this.authService.getUserID(), this.userName).then(value => { if (value) { this.selectedAvatar = value; } }); this.themeDataService.getLogo().then((value: any) => { if (value !== null) { const doc = new DOMParser().parseFromString(value, 'image/svg+xml'); console.log(doc); doc.documentElement.setAttribute('height', '100%'); this.logoBoxRef.nativeElement.appendChild( this.logoBoxRef.nativeElement.ownerDocument.importNode(doc.documentElement, true) ); } else { this.messageService.add({ severity: 'warn', summary: NO_LOGO}); } }).catch((error: HttpErrorResponse) => { console.log(NO_LOGO); }); } ngOnInit(): void { this.userName = this.authService.getUserName(); this.userDataService.getTheme(this.authService.getUserID()).then(value => { if (value !== null)
}); this.subscriptions.add(this.route.paramMap.subscribe((params: ParamMap) => { this.memberID = this.authService.getUserID(); if (params.get('showBlocks') && params.get('showBlocks').toLowerCase() === 'true') { this.groupDataService.getAllBlockingGroupsOfUser(this.memberID).then((value: BlockingGroupResponseDTO) => { this.deletionState = true; this.blockingGroupsLists = value; this.initColumns(); this.loadData(); console.log(this.blockingGroupsLists); }); } else { this.initColumns(); this.loadData(); } })); this.hotkeys.newMap(); this.subscriptionHotkey.push(this.hotkeys.addShortcut({ keys: 'shift.control.n', description: 'Create Group' }).subscribe(() => { this.createGroup(); })); this.subscriptionHotkey.push(this.hotkeys.addShortcut({ keys: 'shift.control.p', description: 'Project Selection' }).subscribe(() => { this.router.navigate(['/project-overview']); })); this.stateNotNecessary = false; } deleteGroups($event): void { const list: any[] = $event; if (list.length === 0) { return; } Promise.all(list.map((elem: any) => { return this.groupDataService.deleteGroup(elem.id); })).then(() => { this.messageService.add({ severity: 'success', summary: DELETE_SUCCESSFUL }); }).catch((response: HttpErrorResponse) => { this.messageService.add({ severity: 'error', summary: ERROR_DELETE_GROUP, detail: response.message }); }).finally(() => { this.loadData(); }); } createGroup(): void { this.sheetMode = SheetMode.New; this.group = { name: '', description: '' }; } saveGroup(group): void { this.filterService.ClearSelectionEmitter.emit(true); this.disableSaveButton = true; if (group.mode === SheetMode.EditWithLock) { if (this.group.name !== '') { const groupEntity: { name: string, description: string } = { name: group.ent.name, description: group.ent.description }; this.groupDataService.alterGroup(group.id, groupEntity) .then(() => { this.messageService.add({ severity: 'success', summary: EDIT_SUCCESSFUL }); this.closeSheet(); }).catch((response: HttpErrorResponse) => { this.messageService.add({ severity: 'error', summary: EDIT_FAILED, detail: response.message }); }).finally(() => { this.disableSaveButton = false; this.loadData(); }); } else { this.messageService.add({ severity: 'error', summary: NAME_FIELD_EMPTY }); this.disableSaveButton = false; } } else if (group.mode === SheetMode.New) { if (this.group.name !== '') { this.groupDataService.createGroup(group.ent) .then(() => { this.messageService.add({ severity: 'success', summary: CREATE_SUCCESSFUL }); this.closeSheet(); }).catch((response: HttpErrorResponse) => { this.messageService.add({ severity: 'error', summary: CREATE_FAILED, detail: response.message }); }).finally(() => { this.disableSaveButton = false; this.loadData(); }); } else { this.messageService.add({ severity: 'error', summary: NAME_FIELD_EMPTY }); this.disableSaveButton = false; } } } private initColumns(): void { this.columns = [ { key: 'select', title: 'Select', type: ColumnType.Checkbox, style: { width: '10%' } }, { key: 'name', title: 'Group-Name', type: ColumnType.Text, style: { width: '62%' } }, { key: 'accessLevel', title: 'Role', type: ColumnType.Text, style: { width: '19%' } }, { key: 'edit', title: 'Edit', type: ColumnType.Button, style: { width: '3%' } }, { key: 'show', title: 'Show', type: ColumnType.Button, style: { width: '3%' } }, { key: 'members', title: 'Members', type: ColumnType.Button, style: { width: '3%' } } ]; if (this.deletionState) { this.columns[1].style = { width: '52%' }; this.columns.splice(2, 0, { key: 'deletion', title: 'Allows Deletion', type: ColumnType.Group_Deletion, style: { 'width': '10%'} }); } } private loadData(): void { this.groupDataService.getAllGroupsOfUser(this.memberID).then((value: GroupResponseDTO[]) => { this.groups = value; if (this.deletionState) { this.groups = this.groups.map((ele: GroupResponseDTO) => ({ ...ele, deletion: this.getGroupDeletionTooltipp(ele.id), })); } }).catch((response: HttpErrorResponse) => { this.messageService.add({ severity: 'error', summary: ERROR_LOADING_GROUP, detail: response.message }); }); } private getGroupDeletionTooltipp(groupId: string): string { if (this.block
{ this.themeDataService.getThemeByID(value).then(value => { if (value !== null) { let color: string = value.colors; let parts = color.split('_'); this.primaryColor = parts[0]; this.accentColor = parts[1]; this.warnColor = parts[2]; this.setColors(); } }); }
conditional_block
groups.component.ts
title: string = 'Group'; userName: string; userToken: any; private memberID: string; sysAdmin: boolean = false; disableSaveButton: boolean = false; showBlocks: boolean = false; blockingGroupsLists: BlockingGroupResponseDTO; selectedAvatar: string = './../../assets/avatar/round default.svg'; logoPath: string = ''; subscriptionHotkey: Subscription[] = []; constructor( private readonly router: Router, private readonly route: ActivatedRoute, private readonly filterService: FilterService, private readonly messageService: MessageService, private readonly groupDataService: GroupDataService, private readonly authService: AuthService, private readonly userDataService: UserDataService, private readonly themeDataService: ThemeDataService, private readonly hotkeys: Hotkeys) { this.fields = [ { title: 'Name', key: 'name', type: FieldType.Text, readonly: false }, { title: 'Description', key: 'description', type: FieldType.Text_Variable, readonly: false, minRows: 3, maxRows: 10 } ]; this.deleteGroups = this.deleteGroups.bind(this); // Decode UserToken to check for SysAdmin this.authService.getUserToken().then((value: string) => { this.userToken = value; let parts: string[]; if (this.userToken) { parts = this.userToken.split('.'); this.userToken = JSON.parse(atob(parts[1])); if (this.userToken.isSystemAdmin === true) { this.sysAdmin = true; } else { this.sysAdmin = false; } }}); // get the icon from backend this.userDataService.getIcon(this.authService.getUserID(), this.userName).then(value => { if (value) { this.selectedAvatar = value; } }); this.themeDataService.getLogo().then((value: any) => { if (value !== null) { const doc = new DOMParser().parseFromString(value, 'image/svg+xml'); console.log(doc); doc.documentElement.setAttribute('height', '100%'); this.logoBoxRef.nativeElement.appendChild( this.logoBoxRef.nativeElement.ownerDocument.importNode(doc.documentElement, true) ); } else { this.messageService.add({ severity: 'warn', summary: NO_LOGO}); } }).catch((error: HttpErrorResponse) => { console.log(NO_LOGO); }); } ngOnInit(): void { this.userName = this.authService.getUserName(); this.userDataService.getTheme(this.authService.getUserID()).then(value => { if (value !== null) { this.themeDataService.getThemeByID(value).then(value => { if (value !== null) { let color: string = value.colors; let parts = color.split('_'); this.primaryColor = parts[0]; this.accentColor = parts[1]; this.warnColor = parts[2]; this.setColors(); } }); } }); this.subscriptions.add(this.route.paramMap.subscribe((params: ParamMap) => { this.memberID = this.authService.getUserID(); if (params.get('showBlocks') && params.get('showBlocks').toLowerCase() === 'true') { this.groupDataService.getAllBlockingGroupsOfUser(this.memberID).then((value: BlockingGroupResponseDTO) => { this.deletionState = true; this.blockingGroupsLists = value; this.initColumns(); this.loadData(); console.log(this.blockingGroupsLists); }); } else { this.initColumns(); this.loadData(); } })); this.hotkeys.newMap(); this.subscriptionHotkey.push(this.hotkeys.addShortcut({ keys: 'shift.control.n', description: 'Create Group' }).subscribe(() => { this.createGroup(); })); this.subscriptionHotkey.push(this.hotkeys.addShortcut({ keys: 'shift.control.p', description: 'Project Selection' }).subscribe(() => { this.router.navigate(['/project-overview']); })); this.stateNotNecessary = false; } deleteGroups($event): void { const list: any[] = $event; if (list.length === 0) { return; } Promise.all(list.map((elem: any) => { return this.groupDataService.deleteGroup(elem.id); })).then(() => { this.messageService.add({ severity: 'success', summary: DELETE_SUCCESSFUL }); }).catch((response: HttpErrorResponse) => { this.messageService.add({ severity: 'error', summary: ERROR_DELETE_GROUP, detail: response.message }); }).finally(() => { this.loadData(); }); } createGroup(): void { this.sheetMode = SheetMode.New; this.group = { name: '', description: '' }; } saveGroup(group): void { this.filterService.ClearSelectionEmitter.emit(true); this.disableSaveButton = true; if (group.mode === SheetMode.EditWithLock) { if (this.group.name !== '') { const groupEntity: { name: string, description: string } = { name: group.ent.name, description: group.ent.description }; this.groupDataService.alterGroup(group.id, groupEntity) .then(() => { this.messageService.add({ severity: 'success', summary: EDIT_SUCCESSFUL }); this.closeSheet(); }).catch((response: HttpErrorResponse) => { this.messageService.add({ severity: 'error', summary: EDIT_FAILED, detail: response.message }); }).finally(() => { this.disableSaveButton = false; this.loadData(); }); } else { this.messageService.add({ severity: 'error', summary: NAME_FIELD_EMPTY }); this.disableSaveButton = false; } } else if (group.mode === SheetMode.New) { if (this.group.name !== '') { this.groupDataService.createGroup(group.ent) .then(() => { this.messageService.add({ severity: 'success', summary: CREATE_SUCCESSFUL }); this.closeSheet(); }).catch((response: HttpErrorResponse) => { this.messageService.add({ severity: 'error', summary: CREATE_FAILED, detail: response.message }); }).finally(() => { this.disableSaveButton = false; this.loadData(); }); } else { this.messageService.add({ severity: 'error', summary: NAME_FIELD_EMPTY }); this.disableSaveButton = false; } } } private initColumns(): void { this.columns = [ { key: 'select', title: 'Select', type: ColumnType.Checkbox, style: { width: '10%' } }, { key: 'name', title: 'Group-Name', type: ColumnType.Text, style: { width: '62%' } }, { key: 'accessLevel', title: 'Role', type: ColumnType.Text, style: { width: '19%' } }, { key: 'edit', title: 'Edit', type: ColumnType.Button, style: { width: '3%' } }, { key: 'show', title: 'Show', type: ColumnType.Button, style: { width: '3%' } }, { key: 'members', title: 'Members', type: ColumnType.Button, style: { width: '3%' } } ]; if (this.deletionState) { this.columns[1].style = { width: '52%' }; this.columns.splice(2, 0, { key: 'deletion', title: 'Allows Deletion', type: ColumnType.Group_Deletion, style: { 'width': '10%'} }); } } private loadData(): void { this.groupDataService.getAllGroupsOfUser(this.memberID).then((value: GroupResponseDTO[]) => { this.groups = value; if (this.deletionState) { this.groups = this.groups.map((ele: GroupResponseDTO) => ({ ...ele, deletion: this.getGroupDeletionTooltipp(ele.id), })); } }).catch((response: HttpErrorResponse) => { this.messageService.add({ severity: 'error', summary: ERROR_LOADING_GROUP, detail: response.message }); }); } private getGroupDeletionTooltipp(groupId: string): string { if (this.blockingGroupsLists.ONLY_ADMIN_MULTI_USER.includes(groupId)) { return 'Make someone admin or remove all other users'; } else if (this.blockingGroupsLists.ONLY_USER_GROUP_WITH_PROJECTS.includes(groupId)) { return 'Delete all projects or add users'; } return undefined; } /** * Toggles the DetailedSheet * 1. Click Edit-/View button or on table row --> onClickEdit(...) of main-Table is called * 2. onClickEdit fires toggleEvent EventEmitter * 3. toggleEvent emitter triggers toggleSheet function in the .html-part of the component * 4. In toggleSheet function the detailed sheet content can be accessed (data is the selected element) * @param data: the data coming from the mainTable */ toggleSheet(data): void
{ this.disableSaveButton = false; let id: string; if (this.group) { id = this.group.id; } this.sheetMode = DetailedSheetUtils.toggle(id, data.entity.id, this.sheetMode, data.mode); this.group = { id: data.entity.id, description: data.entity.description, name: data.entity.name }; }
identifier_body
genjobs.go
.Name) } // remove volumes from spec filteredVolumes := []coreapi.Volume{} for _, volume := range pod.Volumes { if !removeVolumeNames.Has(volume.Name) { filteredVolumes = append(filteredVolumes, volume) } } pod.Volumes = filteredVolumes // remove env and volume mounts from containers for i := range pod.Containers { filteredEnv := []coreapi.EnvVar{} for _, env := range pod.Containers[i].Env { if !removeEnvNames.Has(env.Name) { filteredEnv = append(filteredEnv, env) } } pod.Containers[i].Env = filteredEnv filteredVolumeMounts := []coreapi.VolumeMount{} for _, mount := range pod.Containers[i].VolumeMounts { if !removeVolumeMountNames.Has(mount.Name) { filteredVolumeMounts = append(filteredVolumeMounts, mount) } } pod.Containers[i].VolumeMounts = filteredVolumeMounts } } // undo merged presets from loaded presubmit and its children func undoPresubmitPresets(presets []config.Preset, presubmit *config.Presubmit) { if presubmit.Spec == nil { return } for _, preset := range presets { undoPreset(&preset, presubmit.Labels, presubmit.Spec) } } // convert a kubernetes/kubernetes job to a kubernetes-security/kubernetes job // dropLabels should be a set of "k: v" strings // xref: prow/config/config_test.go replace(...) // it will return the same job mutated, or nil if the job should be removed func convertJobToSecurityJob(j *config.Presubmit, dropLabels sets.String, defaultDecoration *prowapi.DecorationConfig, podNamespace string) *config.Presubmit { // if a GKE job, disable it if strings.Contains(j.Name, "gke") { return nil } // filter out the unwanted labels if len(j.Labels) > 0 { filteredLabels := make(map[string]string) for k, v := range j.Labels { if !dropLabels.Has(fmt.Sprintf("%s: %s", k, v)) { filteredLabels[k] = v } } j.Labels = filteredLabels } originalName := j.Name // fix name and triggers for all jobs j.Name = strings.Replace(originalName, "pull-kubernetes", "pull-security-kubernetes", -1) j.RerunCommand = strings.Replace(j.RerunCommand, "pull-kubernetes", "pull-security-kubernetes", -1) j.Trigger = strings.Replace(j.Trigger, "pull-kubernetes", "pull-security-kubernetes", -1) j.Context = strings.Replace(j.Context, "pull-kubernetes", "pull-security-kubernetes", -1) if j.Namespace != nil && *j.Namespace == podNamespace { j.Namespace = nil } if j.DecorationConfig != nil && reflect.DeepEqual(j.DecorationConfig, defaultDecoration) { j.DecorationConfig = nil } // handle k8s job args, volumes etc if j.Agent == "kubernetes" { j.Cluster = "security" container := &j.Spec.Containers[0] // check for args that need hijacking endsWithScenarioArgs := false needGCSFlag := false needGCSSharedFlag := false needStagingFlag := false isGCPe2e := false for i, arg := range container.Args { if arg == "--" { endsWithScenarioArgs = true // handle --repo substitution for main repo } else if arg == "--repo=k8s.io/kubernetes" || strings.HasPrefix(arg, "--repo=k8s.io/kubernetes=") || arg == "--repo=k8s.io/$(REPO_NAME)" || strings.HasPrefix(arg, "--repo=k8s.io/$(REPO_NAME)=") { container.Args[i] = strings.Replace(arg, "k8s.io/", "github.com/kubernetes-security/", 1) // handle upload bucket } else if strings.HasPrefix(arg, "--upload=") { container.Args[i] = "--upload=gs://kubernetes-security-prow/pr-logs" // check if we need to change staging artifact location for bazel-build and e2es } else if strings.HasPrefix(arg, "--release") { needGCSFlag = true needGCSSharedFlag = true } else if strings.HasPrefix(arg, "--stage") { needStagingFlag = true } else if strings.HasPrefix(arg, "--use-shared-build") { needGCSSharedFlag = true } } // NOTE: this needs to be before the bare -- and then bootstrap args so we prepend it container.Args = append([]string{"--ssh=/etc/ssh-security/ssh-security"}, container.Args...) // check for scenario specific tweaks // NOTE: jobs are remapped to their original name in bootstrap to de-dupe config scenario := "" for _, arg := range container.Args { if strings.HasPrefix(arg, "--scenario=") { scenario = strings.TrimPrefix(arg, "--scenario=") } } // check if we need to change staging artifact location for bazel-build and e2es if scenario == "kubernetes_bazel" { for _, arg := range container.Args { if strings.HasPrefix(arg, "--release") { needGCSFlag = true needGCSSharedFlag = true break } } } if scenario == "kubernetes_e2e" { for _, arg := range container.Args { if strings.Contains(arg, "gcp") { isGCPe2e = true } if strings.HasPrefix(arg, "--stage") { needStagingFlag = true } else if strings.HasPrefix(arg, "--use-shared-build") { needGCSSharedFlag = true } } } // NOTE: these needs to be at the end and after a -- if there is none (it's a scenario arg) if !endsWithScenarioArgs && (needGCSFlag || needGCSSharedFlag || needStagingFlag) { container.Args = append(container.Args, "--") } if needGCSFlag { container.Args = append(container.Args, "--gcs=gs://kubernetes-security-prow/ci/"+j.Name) } if needGCSSharedFlag { container.Args = append(container.Args, "--gcs-shared=gs://kubernetes-security-prow/bazel") } if needStagingFlag { container.Args = append(container.Args, "--stage=gs://kubernetes-security-prow/ci/"+j.Name) } // GCP e2e use a fixed project for security testing if isGCPe2e { container.Args = append(container.Args, "--gcp-project=k8s-jkns-pr-gce-etcd3") } // add ssh key volume / mount container.VolumeMounts = append( container.VolumeMounts, coreapi.VolumeMount{ Name: "ssh-security", MountPath: "/etc/ssh-security", }, ) defaultMode := int32(0400) j.Spec.Volumes = append( j.Spec.Volumes, coreapi.Volume{ Name: "ssh-security", VolumeSource: coreapi.VolumeSource{ Secret: &coreapi.SecretVolumeSource{ SecretName: "ssh-security", DefaultMode: &defaultMode, }, }, }, ) } return j } // these are unnecessary, and make the config larger so we strip them out func yamlBytesStripNulls(yamlBytes []byte) []byte { nullRE := regexp.MustCompile("(?m)[\n]+^[^\n]+: null$") return nullRE.ReplaceAll(yamlBytes, []byte{}) } func yamlBytesToEntry(yamlBytes []byte, indent int) []byte { var buff bytes.Buffer // spaces of length indent prefix := bytes.Repeat([]byte{32}, indent) // `- ` before the first field of a yaml entry prefix[len(prefix)-2] = byte(45) buff.Write(prefix) // put back space prefix[len(prefix)-2] = byte(32) for i, b := range yamlBytes { buff.WriteByte(b) // indent after newline, except the last one if b == byte(10) && i+1 != len(yamlBytes) { buff.Write(prefix) } } return buff.Bytes() } func copyFile(srcPath, destPath string) error
{ // fallback to copying the file instead src, err := os.Open(srcPath) if err != nil { return err } dst, err := os.OpenFile(destPath, os.O_WRONLY, 0666) if err != nil { return err } _, err = io.Copy(dst, src) if err != nil { return err } dst.Sync() dst.Close() src.Close() return nil }
identifier_body
genjobs.go
") var jobsPath = flag.String("jobs", "", "path to prowjobs, defaults to $PWD/../") var outputPath = flag.String("output", "", "path to output the generated jobs to, defaults to $PWD/generated-security-jobs.yaml") // remove merged presets from a podspec func undoPreset(preset *config.Preset, labels map[string]string, pod *coreapi.PodSpec) { // skip presets that do not match the job labels for l, v := range preset.Labels { if v2, ok := labels[l]; !ok || v2 != v { return } } // collect up preset created keys removeEnvNames := sets.NewString() for _, e1 := range preset.Env { removeEnvNames.Insert(e1.Name) } removeVolumeNames := sets.NewString() for _, volume := range preset.Volumes { removeVolumeNames.Insert(volume.Name) } removeVolumeMountNames := sets.NewString() for _, volumeMount := range preset.VolumeMounts { removeVolumeMountNames.Insert(volumeMount.Name) } // remove volumes from spec filteredVolumes := []coreapi.Volume{} for _, volume := range pod.Volumes { if !removeVolumeNames.Has(volume.Name) { filteredVolumes = append(filteredVolumes, volume) } } pod.Volumes = filteredVolumes // remove env and volume mounts from containers for i := range pod.Containers { filteredEnv := []coreapi.EnvVar{} for _, env := range pod.Containers[i].Env { if !removeEnvNames.Has(env.Name) { filteredEnv = append(filteredEnv, env) } } pod.Containers[i].Env = filteredEnv filteredVolumeMounts := []coreapi.VolumeMount{} for _, mount := range pod.Containers[i].VolumeMounts { if !removeVolumeMountNames.Has(mount.Name) { filteredVolumeMounts = append(filteredVolumeMounts, mount) } } pod.Containers[i].VolumeMounts = filteredVolumeMounts } } // undo merged presets from loaded presubmit and its children func undoPresubmitPresets(presets []config.Preset, presubmit *config.Presubmit) { if presubmit.Spec == nil { return } for _, preset := range presets { undoPreset(&preset, presubmit.Labels, presubmit.Spec) } } // convert a kubernetes/kubernetes job to a kubernetes-security/kubernetes job // dropLabels should be a set of "k: v" strings // xref: prow/config/config_test.go replace(...) // it will return the same job mutated, or nil if the job should be removed func convertJobToSecurityJob(j *config.Presubmit, dropLabels sets.String, defaultDecoration *prowapi.DecorationConfig, podNamespace string) *config.Presubmit { // if a GKE job, disable it if strings.Contains(j.Name, "gke") { return nil } // filter out the unwanted labels if len(j.Labels) > 0 { filteredLabels := make(map[string]string) for k, v := range j.Labels { if !dropLabels.Has(fmt.Sprintf("%s: %s", k, v)) { filteredLabels[k] = v } } j.Labels = filteredLabels } originalName := j.Name // fix name and triggers for all jobs j.Name = strings.Replace(originalName, "pull-kubernetes", "pull-security-kubernetes", -1) j.RerunCommand = strings.Replace(j.RerunCommand, "pull-kubernetes", "pull-security-kubernetes", -1) j.Trigger = strings.Replace(j.Trigger, "pull-kubernetes", "pull-security-kubernetes", -1) j.Context = strings.Replace(j.Context, "pull-kubernetes", "pull-security-kubernetes", -1) if j.Namespace != nil && *j.Namespace == podNamespace { j.Namespace = nil } if j.DecorationConfig != nil && reflect.DeepEqual(j.DecorationConfig, defaultDecoration) { j.DecorationConfig = nil } // handle k8s job args, volumes etc if j.Agent == "kubernetes" { j.Cluster = "security" container := &j.Spec.Containers[0] // check for args that need hijacking endsWithScenarioArgs := false needGCSFlag := false needGCSSharedFlag := false needStagingFlag := false isGCPe2e := false for i, arg := range container.Args
} // NOTE: this needs to be before the bare -- and then bootstrap args so we prepend it container.Args = append([]string{"--ssh=/etc/ssh-security/ssh-security"}, container.Args...) // check for scenario specific tweaks // NOTE: jobs are remapped to their original name in bootstrap to de-dupe config scenario := "" for _, arg := range container.Args { if strings.HasPrefix(arg, "--scenario=") { scenario = strings.TrimPrefix(arg, "--scenario=") } } // check if we need to change staging artifact location for bazel-build and e2es if scenario == "kubernetes_bazel" { for _, arg := range container.Args { if strings.HasPrefix(arg, "--release") { needGCSFlag = true needGCSSharedFlag = true break } } } if scenario == "kubernetes_e2e" { for _, arg := range container.Args { if strings.Contains(arg, "gcp") { isGCPe2e = true } if strings.HasPrefix(arg, "--stage") { needStagingFlag = true } else if strings.HasPrefix(arg, "--use-shared-build") { needGCSSharedFlag = true } } } // NOTE: these needs to be at the end and after a -- if there is none (it's a scenario arg) if !endsWithScenarioArgs && (needGCSFlag || needGCSSharedFlag || needStagingFlag) { container.Args = append(container.Args, "--") } if needGCSFlag { container.Args = append(container.Args, "--gcs=gs://kubernetes-security-prow/ci/"+j.Name) } if needGCSSharedFlag { container.Args = append(container.Args, "--gcs-shared=gs://kubernetes-security-prow/bazel") } if needStagingFlag { container.Args = append(container.Args, "--stage=gs://kubernetes-security-prow/ci/"+j.Name) } // GCP e2e use a fixed project for security testing if isGCPe2e { container.Args = append(container.Args, "--gcp-project=k8s-jkns-pr-gce-etcd3") } // add ssh key volume / mount container.VolumeMounts = append( container.VolumeMounts, coreapi.VolumeMount{ Name: "ssh-security", MountPath: "/etc/ssh-security", }, ) defaultMode := int32(0400) j.Spec.Volumes = append( j.Spec.Volumes, coreapi.Volume{ Name: "ssh-security", VolumeSource: coreapi.VolumeSource{ Secret: &coreapi.SecretVolumeSource{ SecretName: "ssh-security", DefaultMode: &defaultMode, }, }, }, ) } return j } // these are unnecessary, and make the config larger so we strip them out func yamlBytesStripNulls(yamlBytes []byte) []byte { nullRE := regexp.MustCompile("(?m)[\n]+^[^\n]+: null$") return nullRE.ReplaceAll(yamlBytes, []byte{}) } func yamlBytesToEntry(yamlBytes []byte, indent int) []byte { var buff bytes.Buffer // spaces of length indent prefix := bytes.Repeat([]
{ if arg == "--" { endsWithScenarioArgs = true // handle --repo substitution for main repo } else if arg == "--repo=k8s.io/kubernetes" || strings.HasPrefix(arg, "--repo=k8s.io/kubernetes=") || arg == "--repo=k8s.io/$(REPO_NAME)" || strings.HasPrefix(arg, "--repo=k8s.io/$(REPO_NAME)=") { container.Args[i] = strings.Replace(arg, "k8s.io/", "github.com/kubernetes-security/", 1) // handle upload bucket } else if strings.HasPrefix(arg, "--upload=") { container.Args[i] = "--upload=gs://kubernetes-security-prow/pr-logs" // check if we need to change staging artifact location for bazel-build and e2es } else if strings.HasPrefix(arg, "--release") { needGCSFlag = true needGCSSharedFlag = true } else if strings.HasPrefix(arg, "--stage") { needStagingFlag = true } else if strings.HasPrefix(arg, "--use-shared-build") { needGCSSharedFlag = true }
conditional_block
genjobs.go
") var jobsPath = flag.String("jobs", "", "path to prowjobs, defaults to $PWD/../") var outputPath = flag.String("output", "", "path to output the generated jobs to, defaults to $PWD/generated-security-jobs.yaml") // remove merged presets from a podspec func undoPreset(preset *config.Preset, labels map[string]string, pod *coreapi.PodSpec) { // skip presets that do not match the job labels for l, v := range preset.Labels { if v2, ok := labels[l]; !ok || v2 != v { return } } // collect up preset created keys removeEnvNames := sets.NewString() for _, e1 := range preset.Env { removeEnvNames.Insert(e1.Name) } removeVolumeNames := sets.NewString() for _, volume := range preset.Volumes { removeVolumeNames.Insert(volume.Name) } removeVolumeMountNames := sets.NewString() for _, volumeMount := range preset.VolumeMounts { removeVolumeMountNames.Insert(volumeMount.Name) } // remove volumes from spec filteredVolumes := []coreapi.Volume{} for _, volume := range pod.Volumes { if !removeVolumeNames.Has(volume.Name) { filteredVolumes = append(filteredVolumes, volume) } } pod.Volumes = filteredVolumes // remove env and volume mounts from containers for i := range pod.Containers { filteredEnv := []coreapi.EnvVar{} for _, env := range pod.Containers[i].Env { if !removeEnvNames.Has(env.Name) { filteredEnv = append(filteredEnv, env) } } pod.Containers[i].Env = filteredEnv filteredVolumeMounts := []coreapi.VolumeMount{} for _, mount := range pod.Containers[i].VolumeMounts { if !removeVolumeMountNames.Has(mount.Name) { filteredVolumeMounts = append(filteredVolumeMounts, mount) } } pod.Containers[i].VolumeMounts = filteredVolumeMounts } } // undo merged presets from loaded presubmit and its children func undoPresubmitPresets(presets []config.Preset, presubmit *config.Presubmit) { if presubmit.Spec == nil { return } for _, preset := range presets { undoPreset(&preset, presubmit.Labels, presubmit.Spec) } } // convert a kubernetes/kubernetes job to a kubernetes-security/kubernetes job // dropLabels should be a set of "k: v" strings // xref: prow/config/config_test.go replace(...) // it will return the same job mutated, or nil if the job should be removed func convertJobToSecurityJob(j *config.Presubmit, dropLabels sets.String, defaultDecoration *prowapi.DecorationConfig, podNamespace string) *config.Presubmit { // if a GKE job, disable it if strings.Contains(j.Name, "gke") { return nil } // filter out the unwanted labels if len(j.Labels) > 0 { filteredLabels := make(map[string]string) for k, v := range j.Labels { if !dropLabels.Has(fmt.Sprintf("%s: %s", k, v)) { filteredLabels[k] = v } } j.Labels = filteredLabels } originalName := j.Name // fix name and triggers for all jobs j.Name = strings.Replace(originalName, "pull-kubernetes", "pull-security-kubernetes", -1) j.RerunCommand = strings.Replace(j.RerunCommand, "pull-kubernetes", "pull-security-kubernetes", -1) j.Trigger = strings.Replace(j.Trigger, "pull-kubernetes", "pull-security-kubernetes", -1) j.Context = strings.Replace(j.Context, "pull-kubernetes", "pull-security-kubernetes", -1) if j.Namespace != nil && *j.Namespace == podNamespace { j.Namespace = nil } if j.DecorationConfig != nil && reflect.DeepEqual(j.DecorationConfig, defaultDecoration) { j.DecorationConfig = nil } // handle k8s job args, volumes etc if j.Agent == "kubernetes" { j.Cluster = "security" container := &j.Spec.Containers[0] // check for args that need hijacking endsWithScenarioArgs := false needGCSFlag := false needGCSSharedFlag := false
needStagingFlag := false isGCPe2e := false for i, arg := range container.Args { if arg == "--" { endsWithScenarioArgs = true // handle --repo substitution for main repo } else if arg == "--repo=k8s.io/kubernetes" || strings.HasPrefix(arg, "--repo=k8s.io/kubernetes=") || arg == "--repo=k8s.io/$(REPO_NAME)" || strings.HasPrefix(arg, "--repo=k8s.io/$(REPO_NAME)=") { container.Args[i] = strings.Replace(arg, "k8s.io/", "github.com/kubernetes-security/", 1) // handle upload bucket } else if strings.HasPrefix(arg, "--upload=") { container.Args[i] = "--upload=gs://kubernetes-security-prow/pr-logs" // check if we need to change staging artifact location for bazel-build and e2es } else if strings.HasPrefix(arg, "--release") { needGCSFlag = true needGCSSharedFlag = true } else if strings.HasPrefix(arg, "--stage") { needStagingFlag = true } else if strings.HasPrefix(arg, "--use-shared-build") { needGCSSharedFlag = true } } // NOTE: this needs to be before the bare -- and then bootstrap args so we prepend it container.Args = append([]string{"--ssh=/etc/ssh-security/ssh-security"}, container.Args...) // check for scenario specific tweaks // NOTE: jobs are remapped to their original name in bootstrap to de-dupe config scenario := "" for _, arg := range container.Args { if strings.HasPrefix(arg, "--scenario=") { scenario = strings.TrimPrefix(arg, "--scenario=") } } // check if we need to change staging artifact location for bazel-build and e2es if scenario == "kubernetes_bazel" { for _, arg := range container.Args { if strings.HasPrefix(arg, "--release") { needGCSFlag = true needGCSSharedFlag = true break } } } if scenario == "kubernetes_e2e" { for _, arg := range container.Args { if strings.Contains(arg, "gcp") { isGCPe2e = true } if strings.HasPrefix(arg, "--stage") { needStagingFlag = true } else if strings.HasPrefix(arg, "--use-shared-build") { needGCSSharedFlag = true } } } // NOTE: these needs to be at the end and after a -- if there is none (it's a scenario arg) if !endsWithScenarioArgs && (needGCSFlag || needGCSSharedFlag || needStagingFlag) { container.Args = append(container.Args, "--") } if needGCSFlag { container.Args = append(container.Args, "--gcs=gs://kubernetes-security-prow/ci/"+j.Name) } if needGCSSharedFlag { container.Args = append(container.Args, "--gcs-shared=gs://kubernetes-security-prow/bazel") } if needStagingFlag { container.Args = append(container.Args, "--stage=gs://kubernetes-security-prow/ci/"+j.Name) } // GCP e2e use a fixed project for security testing if isGCPe2e { container.Args = append(container.Args, "--gcp-project=k8s-jkns-pr-gce-etcd3") } // add ssh key volume / mount container.VolumeMounts = append( container.VolumeMounts, coreapi.VolumeMount{ Name: "ssh-security", MountPath: "/etc/ssh-security", }, ) defaultMode := int32(0400) j.Spec.Volumes = append( j.Spec.Volumes, coreapi.Volume{ Name: "ssh-security", VolumeSource: coreapi.VolumeSource{ Secret: &coreapi.SecretVolumeSource{ SecretName: "ssh-security", DefaultMode: &defaultMode, }, }, }, ) } return j } // these are unnecessary, and make the config larger so we strip them out func yamlBytesStripNulls(yamlBytes []byte) []byte { nullRE := regexp.MustCompile("(?m)[\n]+^[^\n]+: null$") return nullRE.ReplaceAll(yamlBytes, []byte{}) } func yamlBytesToEntry(yamlBytes []byte, indent int) []byte { var buff bytes.Buffer // spaces of length indent prefix := bytes.Repeat([]byte{
random_line_split
genjobs.go
} // remove volumes from spec filteredVolumes := []coreapi.Volume{} for _, volume := range pod.Volumes { if !removeVolumeNames.Has(volume.Name) { filteredVolumes = append(filteredVolumes, volume) } } pod.Volumes = filteredVolumes // remove env and volume mounts from containers for i := range pod.Containers { filteredEnv := []coreapi.EnvVar{} for _, env := range pod.Containers[i].Env { if !removeEnvNames.Has(env.Name) { filteredEnv = append(filteredEnv, env) } } pod.Containers[i].Env = filteredEnv filteredVolumeMounts := []coreapi.VolumeMount{} for _, mount := range pod.Containers[i].VolumeMounts { if !removeVolumeMountNames.Has(mount.Name) { filteredVolumeMounts = append(filteredVolumeMounts, mount) } } pod.Containers[i].VolumeMounts = filteredVolumeMounts } } // undo merged presets from loaded presubmit and its children func undoPresubmitPresets(presets []config.Preset, presubmit *config.Presubmit) { if presubmit.Spec == nil { return } for _, preset := range presets { undoPreset(&preset, presubmit.Labels, presubmit.Spec) } } // convert a kubernetes/kubernetes job to a kubernetes-security/kubernetes job // dropLabels should be a set of "k: v" strings // xref: prow/config/config_test.go replace(...) // it will return the same job mutated, or nil if the job should be removed func convertJobToSecurityJob(j *config.Presubmit, dropLabels sets.String, defaultDecoration *prowapi.DecorationConfig, podNamespace string) *config.Presubmit { // if a GKE job, disable it if strings.Contains(j.Name, "gke") { return nil } // filter out the unwanted labels if len(j.Labels) > 0 { filteredLabels := make(map[string]string) for k, v := range j.Labels { if !dropLabels.Has(fmt.Sprintf("%s: %s", k, v)) { filteredLabels[k] = v } } j.Labels = filteredLabels } originalName := j.Name // fix name and triggers for all jobs j.Name = strings.Replace(originalName, "pull-kubernetes", "pull-security-kubernetes", -1) j.RerunCommand = strings.Replace(j.RerunCommand, "pull-kubernetes", "pull-security-kubernetes", -1) j.Trigger = strings.Replace(j.Trigger, "pull-kubernetes", "pull-security-kubernetes", -1) j.Context = strings.Replace(j.Context, "pull-kubernetes", "pull-security-kubernetes", -1) if j.Namespace != nil && *j.Namespace == podNamespace { j.Namespace = nil } if j.DecorationConfig != nil && reflect.DeepEqual(j.DecorationConfig, defaultDecoration) { j.DecorationConfig = nil } // handle k8s job args, volumes etc if j.Agent == "kubernetes" { j.Cluster = "security" container := &j.Spec.Containers[0] // check for args that need hijacking endsWithScenarioArgs := false needGCSFlag := false needGCSSharedFlag := false needStagingFlag := false isGCPe2e := false for i, arg := range container.Args { if arg == "--" { endsWithScenarioArgs = true // handle --repo substitution for main repo } else if arg == "--repo=k8s.io/kubernetes" || strings.HasPrefix(arg, "--repo=k8s.io/kubernetes=") || arg == "--repo=k8s.io/$(REPO_NAME)" || strings.HasPrefix(arg, "--repo=k8s.io/$(REPO_NAME)=") { container.Args[i] = strings.Replace(arg, "k8s.io/", "github.com/kubernetes-security/", 1) // handle upload bucket } else if strings.HasPrefix(arg, "--upload=") { container.Args[i] = "--upload=gs://kubernetes-security-prow/pr-logs" // check if we need to change staging artifact location for bazel-build and e2es } else if strings.HasPrefix(arg, "--release") { needGCSFlag = true needGCSSharedFlag = true } else if strings.HasPrefix(arg, "--stage") { needStagingFlag = true } else if strings.HasPrefix(arg, "--use-shared-build") { needGCSSharedFlag = true } } // NOTE: this needs to be before the bare -- and then bootstrap args so we prepend it container.Args = append([]string{"--ssh=/etc/ssh-security/ssh-security"}, container.Args...) // check for scenario specific tweaks // NOTE: jobs are remapped to their original name in bootstrap to de-dupe config scenario := "" for _, arg := range container.Args { if strings.HasPrefix(arg, "--scenario=") { scenario = strings.TrimPrefix(arg, "--scenario=") } } // check if we need to change staging artifact location for bazel-build and e2es if scenario == "kubernetes_bazel" { for _, arg := range container.Args { if strings.HasPrefix(arg, "--release") { needGCSFlag = true needGCSSharedFlag = true break } } } if scenario == "kubernetes_e2e" { for _, arg := range container.Args { if strings.Contains(arg, "gcp") { isGCPe2e = true } if strings.HasPrefix(arg, "--stage") { needStagingFlag = true } else if strings.HasPrefix(arg, "--use-shared-build") { needGCSSharedFlag = true } } } // NOTE: these needs to be at the end and after a -- if there is none (it's a scenario arg) if !endsWithScenarioArgs && (needGCSFlag || needGCSSharedFlag || needStagingFlag) { container.Args = append(container.Args, "--") } if needGCSFlag { container.Args = append(container.Args, "--gcs=gs://kubernetes-security-prow/ci/"+j.Name) } if needGCSSharedFlag { container.Args = append(container.Args, "--gcs-shared=gs://kubernetes-security-prow/bazel") } if needStagingFlag { container.Args = append(container.Args, "--stage=gs://kubernetes-security-prow/ci/"+j.Name) } // GCP e2e use a fixed project for security testing if isGCPe2e { container.Args = append(container.Args, "--gcp-project=k8s-jkns-pr-gce-etcd3") } // add ssh key volume / mount container.VolumeMounts = append( container.VolumeMounts, coreapi.VolumeMount{ Name: "ssh-security", MountPath: "/etc/ssh-security", }, ) defaultMode := int32(0400) j.Spec.Volumes = append( j.Spec.Volumes, coreapi.Volume{ Name: "ssh-security", VolumeSource: coreapi.VolumeSource{ Secret: &coreapi.SecretVolumeSource{ SecretName: "ssh-security", DefaultMode: &defaultMode, }, }, }, ) } return j } // these are unnecessary, and make the config larger so we strip them out func yamlBytesStripNulls(yamlBytes []byte) []byte { nullRE := regexp.MustCompile("(?m)[\n]+^[^\n]+: null$") return nullRE.ReplaceAll(yamlBytes, []byte{}) } func yamlBytesToEntry(yamlBytes []byte, indent int) []byte { var buff bytes.Buffer // spaces of length indent prefix := bytes.Repeat([]byte{32}, indent) // `- ` before the first field of a yaml entry prefix[len(prefix)-2] = byte(45) buff.Write(prefix) // put back space prefix[len(prefix)-2] = byte(32) for i, b := range yamlBytes { buff.WriteByte(b) // indent after newline, except the last one if b == byte(10) && i+1 != len(yamlBytes) { buff.Write(prefix) } } return buff.Bytes() } func copyFile(srcPath, destPath string) error { // fallback to copying the file instead src, err := os.Open(srcPath) if err != nil { return err } dst, err := os.OpenFile(destPath, os.O_WRONLY, 0666) if err != nil { return err } _, err = io.Copy(dst, src) if err != nil { return err } dst.Sync() dst.Close() src.Close() return nil } func
main
identifier_name
UserRole.ts
Equips[i][j] && tempChangeEquips[i][j].handle != SubRoles.ins().getSubRoleByIndex(i).equipsData[j].item.handle) { if (isWear && roleIndex == i) { UserEquip.ins().sendWearEquipment(tempChangeEquips[i][j].handle, j, roleIndex); this.canChangeEquips[i][j] = false; } else { this.canChangeEquips[i][j] = true; } } } if (this.canChangeEquips[i].indexOf(true) < 0) this.canChangeEquips[i].length = 0; } this.showNavBtnRedPoint(); } /** 对比装备返回高战力的装备 */ private contrastEquip(sourceItem: ItemData, item: ItemData): ItemData { if (!sourceItem || sourceItem.handle == 0) return item; if (!item || item.handle == 0) return sourceItem; let sourceItemScore: number = sourceItem.point; let itemScore: number = item.point; if (itemScore > sourceItemScore) return item; else return sourceItem; } public getCanChangeEquips(): boolean { //是否有装备可以穿戴 for (let i: number = 0; i < this.canChangeEquips.length; i++) { for (let j: number = 0; j < this.canChangeEquips[i].length; j++) { if (this.canChangeEquips[i][j]) { return true; } } } return false; } /** 检查是否需要显示红点 */ public showNavBtnRedPoint(b: boolean = false): void { //是否有装备可以穿戴 for (let i: number = 0; i < this.canChangeEquips.length; i++) { for (let j: number = 0; j < this.canChangeEquips[i].length; j++) { if (this.canChangeEquips[i][j]) { b = true; break; } } if (b) break; } if (!b && SamsaraModel.ins().isCanAddSpirit()) {//检测是否有装备能附灵 b = true; } //面板的灵戒是否有可以升级的 if (!b && OpenSystem.ins().checkSysOpen(SystemType.RING) && UserTask.ins().checkAwakeRedPoint()[0]>0 || (SpecialRing.ins().checkHaveUpRing() || SpecialRing.ins().isCanStudySkill() || SpecialRing.ins().isCanUpgradeSkill() || SpecialRing.ins().fireRingRedPoint())) { b = true; } if (!b && UserSkill.ins().canHejiEquip()) { b = true; } if (!b && UserSkill.ins().canExchange()) { b = true; } if (!b && UserSkill.ins().canSolve()) { b = true; } //玉佩界面红点 if (!b && JadeNew.ins().checkRed()) { b = true; } //面板的龙印护盾血玉是否有可以升级的 if (!b && LongHun.ins().canShowRedPointInAll()) { b = true; } //转生是否有可以升级 else if (!b && UserZs.ins().canOpenZSWin() && !UserZs.ins().isMaxLv() && (UserZs.ins().canGet() > 0 || UserZs.ins().canUpgrade())) { b = true; } //翅膀是否有可以升级 else if (!b && this.and(Wing.ins().canGradeupWing()) || this.and(Wing.ins().canItemGradeupWing()) || Wing.ins().isHaveActivationWing()) { b = true; } //是否可以时装激活 if (!b && Dress.ins().redPoint()) { b = true; } //是否有符文替换 或者升级 或者有符文可兑换 if (!b && RuneRedPointMgr.ins().checkAllSituation()) { b = true; } //神装 if (!b) { let len: number = SubRoles.ins().subRolesLen; for (let a: number = 0; a < len; a++) { let model: Role = SubRoles.ins().getSubRoleByIndex(a); for (let i = 0; i < 8; i++) { let equipItem: eui.Component = this["equip" + i]; b = UserEquip.ins().setOrangeEquipItemState(i, model); if (!b && i < 2) b = UserEquip.ins().setLegendEquipItemState(i > 0 ? 2 : 0, model); if (b) { let eb = UserBag.ins().checkEqRedPoint(i, model); b = eb != null ? eb : b; } if (b) break; } if (b) break; } // if (!b) // b = UserEquip.ins().checkRedPoint(4); if (!b) for (let i = 0; i < len; i++) { b = UserEquip.ins().checkRedPoint(5, i); if (b) break; } if (!b) b = UserBag.ins().getLegendHasResolve(); if (!b) b = Boolean(UserBag.ins().getHuntGoods(0).length); if (!b) { b = ExtremeEquipModel.ins().getRedPoint(); } } // MessageCenter.ins().dispatch(MessagerEvent.ROLE_HINT, b); @setattr 4 99999999 if (!b) b = SubRoles.ins().isLockRole(); if (!b) b = GodWingRedPoint.ins().getGodWingRedPoint(); if (!b) //可以升级或者可以兑换时候人物图标有红点 b = SamsaraModel.ins().isOpen() && (SamsaraModel.ins().isCanUpgrade() || SamsaraModel.ins().isCanItemExchange() || (Actor.level >= GlobalConfig.ReincarnationBase.levelLimit && SamsaraModel.ins().getExpExchangeTimes() > 0)); if (!b) b = SamsaraModel.ins().isCanUpgradeSoul(); // 飞剑 if (!b) b = FlySwordRedPoint.ins().totalRedPoint.indexOf(true) != -1; // 宠物 if (!b) { b = HuanShouRedPoint.ins().isRed; } // 天仙 if (!b) { b = ZhanLing.ins().checkRedPoint(); } this.postRoleHint(b); } /** * 派发角色按钮提示 * 此函数只能由 showNavBtnRedPoint() 传参调用,不可直接调用(设计思路待完善) * */ public postRoleHint(b: boolean): number { return b ? 1 : 0; } private and(list): boolean { for (let k in list) { if (list[k] == true) return true; } return false; } private seekRoleItem(): boolean { let isReturn: boolean = false; let len: number = UserBag.ins().getBagItemNum(0); for (let i: number = 0; i < len; i++) { if (isReturn) return isReturn; let item: ItemData = UserBag.ins().getItemByIndex(0, i); switch (item.itemConfig.id) { case 200001://翅膀 break; case 200004://经脉丹 isReturn = this.roleHint(5); break; case 200013://晕眩碎片 isReturn = this.roleHint(0); break; case 200014://护身碎片 isReturn = this.roleHint(1); break; } } return isReturn; } /** * 角色提示 */ public roleHint(type: number): boolean { let len: number = SubRoles.ins().subRolesLen; let flag: boolean = false; for (let i: number = 0; i < len; i++) { let role: Role = SubRoles.ins().getSubRoleByIndex(i); flag = this.roleHintCheck(role, type); if (flag) { return flag; } } return flag; } /** * 查找角色提示 */ public roleHintCheck(role: Role, type: number): boolean { let lv: number = 1; let costNum: number = 0; let itemNum: number = 0; let itemId: number = 0; switch (type) { case 0:
lv
identifier_name
UserRole.ts
item, item); } } let len = tempChangeEquips.length; for (let i: number = 0; i < len; i++) { for (let j: number = 0; j < tempChangeEquips[i].length; j++) { this.canChangeEquips[i][j] = false; if (tempChangeEquips[i][j] && tempChangeEquips[i][j].handle != SubRoles.ins().getSubRoleByIndex(i).equipsData[j].item.handle) { if (isWear && roleIndex == i) { UserEquip.ins().sendWearEquipment(tempChangeEquips[i][j].handle, j, roleIndex); this.canChangeEquips[i][j] = false; } else { this.canChangeEquips[i][j] = true; } } } if (this.canChangeEquips[i].indexOf(true) < 0) this.canChangeEquips[i].length = 0; } this.showNavBtnRedPoint(); } /** 对比装备返回高战力的装备 */ private contrastEquip(sourceItem: ItemData, item: ItemData): ItemData { if (!sourceItem || sourceItem.handle == 0) return item; if (!item || item.handle == 0) return sourceItem; let sourceItemScore: number = sourceItem.point; let itemScore: number = item.point; if (itemScore > sourceItemScore) return item; else return sourceItem; } public getCanChangeEquips(): boolean { //是否有装备可以穿戴 for (let i: number = 0; i < this.canChangeEquips.length; i++) { for (let j: number = 0; j < this.canChangeEquips[i].length; j++) { if (this.canChangeEquips[i][j]) { return true; } } } return false; } /** 检查是否需要显示红点 */ public showNavBtnRedPoint(b: boolean = false): void { //是否有装备可以穿戴 for (let i: number = 0; i < this.canChangeEquips.length; i++) { for (let j: number = 0; j < this.canChangeEquips[i].length; j++) { if (this.canChangeEquips[i][j]) { b = true; break; } } if (b) break; } if (!b && SamsaraModel.ins().isCanAddSpirit()) {//检测是否有装备能附灵 b = true; } //面板的灵戒是否有可以升级的 if (!b && OpenSystem.ins().checkSysOpen(SystemType.RING) && UserTask.ins().checkAwakeRedPoint()[0]>0 || (SpecialRing.ins().checkHaveUpRing() || SpecialRing.ins().isCanStudySkill() || SpecialRing.ins().isCanUpgradeSkill() || SpecialRing.ins().fireRingRedPoint())) { b = true; } if (!b && UserSkill.ins().canHejiEquip()) { b = true; } if (!b && UserSkill.ins().canExchange()) { b = true; } if (!b && UserSkill.ins().canSolve()) { b = true; } //玉佩界面红点 if (!b && JadeNew.ins().checkRed()) { b = true; } //面板的龙印护盾血玉是否有可以升级的 if (!b && LongHun.ins().canShowRedPointInAll()) { b = true; } //转生是否有可以升级 else if (!b && UserZs.ins().canOpenZSWin() && !UserZs.ins().isMaxLv() && (UserZs.ins().canGet() > 0 || UserZs.ins().canUpgrade())) { b = true; } //翅膀是否有可以升级 else if (!b && this.and(Wing.ins().canGradeupWing()) || this.and(Wing.ins().canItemGradeupWing()) || Wing.ins().isHaveActivationWing()) { b = true; } //是否可以时装激活 if (!b && Dress.ins().redPoint()) { b = true; } //是否有符文替换 或者升级 或者有符文可兑换 if (!b && RuneRedPointMgr.ins().checkAllSituation()) { b = true; } //神装 if (!b) { let len: number = SubRoles.ins().subRolesLen; for (let a: number = 0; a < len; a++) { let model: Role = SubRoles.ins().getSubRoleByIndex(a); for (let i = 0; i < 8; i++) { let equipItem: eui.Component = this["equip" + i]; b = UserEquip.ins().setOrangeEquipItemState(i, model); if (!b && i < 2) b = UserEquip.ins().setLegendEquipItemState(i > 0 ? 2 : 0, model); if (b) { let eb = UserBag.ins().checkEqRedPoint(i, model); b = eb != null ? eb : b; } if (b) break; } if (b) break; } // if (!b) // b = UserEquip.ins().checkRedPoint(4); if (!b) for (let i = 0; i < len; i++) { b = UserEquip.ins().checkRedPoint(5, i); if (b) break; } if (!b) b = UserBag.ins().getLegendHasResolve(); if (!b) b = Boolean(UserBag.ins().getHuntGoods(0).length); if (!b) { b = ExtremeEquipModel.ins().getRedPoint(); } } // MessageCenter.ins().dispatch(MessagerEvent.ROLE_HINT, b); @setattr 4 99999999 if (!b) b = SubRoles.ins().isLockRole(); if (!b) b = GodWingRedPoint.ins().getGodWingRedPoint(); if (!b) //可以升级或者可以兑换时候人物图标有红点 b = SamsaraModel.ins().isOpen() && (SamsaraModel.ins().isCanUpgrade() || SamsaraModel.ins().isCanItemExchange() || (Actor.level >= GlobalConfig.ReincarnationBase.levelLimit && SamsaraModel.ins().getExpExchangeTimes() > 0)); if (!b) b = SamsaraModel.ins().isCanUpgradeSoul(); // 飞剑 if (!b) b = FlySwordRedPoint.ins().totalRedPoint.indexOf(true) != -1; // 宠物 if (!b) { b = HuanShouRedPoint.ins().isRed; } // 天仙 if (!b) { b = ZhanLing.ins().checkRedPoint(); } this.postRoleHint(b); } /** * 派发角色按钮提示 * 此函数只能由 showNavBtnRedPoint() 传参调用,不可直接调用(设计思路待完善) * */ public postRoleHint(b: boolean): number { return b ? 1 : 0; } private and(list): boolean { for (let k in list) { if (list[k] == true) return true; } return false; } private seekRoleItem(): boolean { let isReturn: boolean = false; let len: number = UserBag.ins().getBagItemNum(0); for (let i: number = 0; i < len; i++) { if (isReturn) return isReturn; let item: ItemData = UserBag.ins().getItemByIndex(0, i); switch (item.itemConfig.id) { case 200001://翅膀 break; case 200004://经脉丹 isReturn = this.roleHint(5); break; case 200013://晕眩碎片 isReturn = this.roleHint(0); break; case 200014://护身碎片 isReturn = this.roleHint(1);
break; } } return isReturn; } /** * 角色提示 */ public roleHint(type: number): boolean { let len: number = SubRoles.ins().subRolesLen; let flag: boolean = false; for (let i: number = 0; i < len; i++) { let role: Role = SubRoles.ins().getSubRoleByIndex(i); flag = this.roleHintCheck(role, type); if (flag) { return flag; } } return flag;
identifier_body
UserRole.ts
this.canChangeEquips[i][j]) { return true; } } } return false; } /** 检查是否需要显示红点 */ public showNavBtnRedPoint(b: boolean = false): void { //是否有装备可以穿戴 for (let i: number = 0; i < this.canChangeEquips.length; i++) { for (let j: number = 0; j < this.canChangeEquips[i].length; j++) { if (this.canChangeEquips[i][j]) { b = true; break; } } if (b) break; } if (!b && SamsaraModel.ins().isCanAddSpirit()) {//检测是否有装备能附灵 b = true; } //面板的灵戒是否有可以升级的 if (!b && OpenSystem.ins().checkSysOpen(SystemType.RING) && UserTask.ins().checkAwakeRedPoint()[0]>0 || (SpecialRing.ins().checkHaveUpRing() || SpecialRing.ins().isCanStudySkill() || SpecialRing.ins().isCanUpgradeSkill() || SpecialRing.ins().fireRingRedPoint())) { b = true; } if (!b && UserSkill.ins().canHejiEquip()) { b = true; } if (!b && UserSkill.ins().canExchange()) { b = true; } if (!b && UserSkill.ins().canSolve()) { b = true; } //玉佩界面红点 if (!b && JadeNew.ins().checkRed()) { b = true; } //面板的龙印护盾血玉是否有可以升级的 if (!b && LongHun.ins().canShowRedPointInAll()) { b = true; } //转生是否有可以升级 else if (!b && UserZs.ins().canOpenZSWin() && !UserZs.ins().isMaxLv() && (UserZs.ins().canGet() > 0 || UserZs.ins().canUpgrade())) { b = true; } //翅膀是否有可以升级 else if (!b && this.and(Wing.ins().canGradeupWing()) || this.and(Wing.ins().canItemGradeupWing()) || Wing.ins().isHaveActivationWing()) { b = true; } //是否可以时装激活 if (!b && Dress.ins().redPoint()) { b = true; } //是否有符文替换 或者升级 或者有符文可兑换 if (!b && RuneRedPointMgr.ins().checkAllSituation()) { b = true; } //神装 if (!b) { let len: number = SubRoles.ins().subRolesLen; for (let a: number = 0; a < len; a++) { let model: Role = SubRoles.ins().getSubRoleByIndex(a); for (let i = 0; i < 8; i++) { let equipItem: eui.Component = this["equip" + i]; b = UserEquip.ins().setOrangeEquipItemState(i, model); if (!b && i < 2) b = UserEquip.ins().setLegendEquipItemState(i > 0 ? 2 : 0, model); if (b) { let eb = UserBag.ins().checkEqRedPoint(i, model); b = eb != null ? eb : b; } if (b) break; } if (b) break; } // if (!b) // b = UserEquip.ins().checkRedPoint(4); if (!b) for (let i = 0; i < len; i++) { b = UserEquip.ins().checkRedPoint(5, i); if (b) break; } if (!b) b = UserBag.ins().getLegendHasResolve(); if (!b) b = Boolean(UserBag.ins().getHuntGoods(0).length); if (!b) { b = ExtremeEquipModel.ins().getRedPoint(); } } // MessageCenter.ins().dispatch(MessagerEvent.ROLE_HINT, b); @setattr 4 99999999 if (!b) b = SubRoles.ins().isLockRole(); if (!b) b = GodWingRedPoint.ins().getGodWingRedPoint(); if (!b) //可以升级或者可以兑换时候人物图标有红点 b = SamsaraModel.ins().isOpen() && (SamsaraModel.ins().isCanUpgrade() || SamsaraModel.ins().isCanItemExchange() || (Actor.level >= GlobalConfig.ReincarnationBase.levelLimit && SamsaraModel.ins().getExpExchangeTimes() > 0)); if (!b) b = SamsaraModel.ins().isCanUpgradeSoul(); // 飞剑 if (!b) b = FlySwordRedPoint.ins().totalRedPoint.indexOf(true) != -1; // 宠物 if (!b) { b = HuanShouRedPoint.ins().isRed; } // 天仙 if (!b) { b = ZhanLing.ins().checkRedPoint(); } this.postRoleHint(b); } /** * 派发角色按钮提示 * 此函数只能由 showNavBtnRedPoint() 传参调用,不可直接调用(设计思路待完善) * */ public postRoleHint(b: boolean): number { return b ? 1 : 0; } private and(list): boolean { for (let k in list) { if (list[k] == true) return true; } return false; } private seekRoleItem(): boolean { let isReturn: boolean = false; let len: number = UserBag.ins().getBagItemNum(0); for (let i: number = 0; i < len; i++) { if (isReturn) return isReturn; let item: ItemData = UserBag.ins().getItemByIndex(0, i); switch (item.itemConfig.id) { case 200001://翅膀 break; case 200004://经脉丹 isReturn = this.roleHint(5); break; case 200013://晕眩碎片 isReturn = this.roleHint(0); break; case 200014://护身碎片 isReturn = this.roleHint(1); break; } } return isReturn; } /** * 角色提示 */ public roleHint(type: number): boolean { let len: number = SubRoles.ins().subRolesLen; let flag: boolean = false; for (let i: number = 0; i < len; i++) { let role: Role = SubRoles.ins().getSubRoleByIndex(i); flag = this.roleHintCheck(role, type); if (flag) { return flag; } } return flag; } /** * 查找角色提示 */ public roleHintCheck(role: Role, type: number): boolean { let lv: number = 1; let costNum: number = 0; let itemNum: number = 0; let itemId: number = 0; switch (type) { case 0: lv = role.getExRingsData(0); let ring0Config: ExRing0Config = GlobalConfig[`ExRing${0}Config`][lv]; if (lv >= 1) return false; if (ring0Config) { costNum = ring0Config.cost; itemId = GlobalConfig.ExRingConfig[0].costItem; } break; case 1: lv = role.getExRingsData(1); let ring1Config: ExRing0Config = GlobalConfig[`ExRing${1}Config`][lv]; if (lv >= 1) return false; if (ring1Config) { costNum = ring1Config.cost; itemId = GlobalConfig.ExRingConfig[1].costItem; } break; case LongHun.TYPE_LONG_HUN: lv += role.loongSoulData.level; let loongSoulConfig: LoongSoulConfig = GlobalConfig.LoongSoulConfig[lv]; let loongSoulStageConfig: LoongSoulStageConfig = GlobalConfig.LoongSoulStageConfig[role.loongSoulData.stage]; if (loongSoulConfig) { costNum = loongSoulStageConfig.normalCost; itemId = loongSoulConfig.itemId; } break; case LongHun.TYPE_HU_DUN: lv += ro
le.shieldData.level; let shieldConfig: ShieldConfig = GlobalConfig.ShieldConfig[lv];
conditional_block
UserRole.ts
BtnRedPoint(b: boolean = false): void { //是否有装备可以穿戴 for (let i: number = 0; i < this.canChangeEquips.length; i++) { for (let j: number = 0; j < this.canChangeEquips[i].length; j++) { if (this.canChangeEquips[i][j]) { b = true; break; } } if (b) break; } if (!b && SamsaraModel.ins().isCanAddSpirit()) {//检测是否有装备能附灵 b = true; } //面板的灵戒是否有可以升级的 if (!b && OpenSystem.ins().checkSysOpen(SystemType.RING) && UserTask.ins().checkAwakeRedPoint()[0]>0 || (SpecialRing.ins().checkHaveUpRing() || SpecialRing.ins().isCanStudySkill() || SpecialRing.ins().isCanUpgradeSkill() || SpecialRing.ins().fireRingRedPoint())) { b = true; } if (!b && UserSkill.ins().canHejiEquip()) { b = true; } if (!b && UserSkill.ins().canExchange()) { b = true; } if (!b && UserSkill.ins().canSolve()) { b = true; } //玉佩界面红点 if (!b && JadeNew.ins().checkRed()) { b = true; } //面板的龙印护盾血玉是否有可以升级的 if (!b && LongHun.ins().canShowRedPointInAll()) { b = true; } //转生是否有可以升级 else if (!b && UserZs.ins().canOpenZSWin() && !UserZs.ins().isMaxLv() && (UserZs.ins().canGet() > 0 || UserZs.ins().canUpgrade())) { b = true; } //翅膀是否有可以升级 else if (!b && this.and(Wing.ins().canGradeupWing()) || this.and(Wing.ins().canItemGradeupWing()) || Wing.ins().isHaveActivationWing()) { b = true; } //是否可以时装激活 if (!b && Dress.ins().redPoint()) { b = true; } //是否有符文替换 或者升级 或者有符文可兑换 if (!b && RuneRedPointMgr.ins().checkAllSituation()) { b = true; } //神装 if (!b) { let len: number = SubRoles.ins().subRolesLen; for (let a: number = 0; a < len; a++) { let model: Role = SubRoles.ins().getSubRoleByIndex(a); for (let i = 0; i < 8; i++) { let equipItem: eui.Component = this["equip" + i]; b = UserEquip.ins().setOrangeEquipItemState(i, model); if (!b && i < 2) b = UserEquip.ins().setLegendEquipItemState(i > 0 ? 2 : 0, model); if (b) { let eb = UserBag.ins().checkEqRedPoint(i, model); b = eb != null ? eb : b; } if (b) break; } if (b) break; } // if (!b) // b = UserEquip.ins().checkRedPoint(4); if (!b) for (let i = 0; i < len; i++) { b = UserEquip.ins().checkRedPoint(5, i); if (b) break; } if (!b) b = UserBag.ins().getLegendHasResolve(); if (!b) b = Boolean(UserBag.ins().getHuntGoods(0).length); if (!b) { b = ExtremeEquipModel.ins().getRedPoint(); } } // MessageCenter.ins().dispatch(MessagerEvent.ROLE_HINT, b); @setattr 4 99999999 if (!b) b = SubRoles.ins().isLockRole(); if (!b) b = GodWingRedPoint.ins().getGodWingRedPoint(); if (!b) //可以升级或者可以兑换时候人物图标有红点 b = SamsaraModel.ins().isOpen() && (SamsaraModel.ins().isCanUpgrade() || SamsaraModel.ins().isCanItemExchange() || (Actor.level >= GlobalConfig.ReincarnationBase.levelLimit && SamsaraModel.ins().getExpExchangeTimes() > 0)); if (!b) b = SamsaraModel.ins().isCanUpgradeSoul(); // 飞剑 if (!b) b = FlySwordRedPoint.ins().totalRedPoint.indexOf(true) != -1; // 宠物 if (!b) { b = HuanShouRedPoint.ins().isRed; } // 天仙 if (!b) { b = ZhanLing.ins().checkRedPoint(); } this.postRoleHint(b); } /** * 派发角色按钮提示 * 此函数只能由 showNavBtnRedPoint() 传参调用,不可直接调用(设计思路待完善) * */ public postRoleHint(b: boolean): number { return b ? 1 : 0; } private and(list): boolean { for (let k in list) { if (list[k] == true) return true; } return false; } private seekRoleItem(): boolean { let isReturn: boolean = false; let len: number = UserBag.ins().getBagItemNum(0); for (let i: number = 0; i < len; i++) { if (isReturn) return isReturn; let item: ItemData = UserBag.ins().getItemByIndex(0, i); switch (item.itemConfig.id) { case 200001://翅膀 break; case 200004://经脉丹 isReturn = this.roleHint(5); break; case 200013://晕眩碎片 isReturn = this.roleHint(0); break; case 200014://护身碎片 isReturn = this.roleHint(1); break; } } return isReturn; } /** * 角色提示 */ public roleHint(type: number): boolean { let len: number = SubRoles.ins().subRolesLen; let flag: boolean = false; for (let i: number = 0; i < len; i++) { let role: Role = SubRoles.ins().getSubRoleByIndex(i); flag = this.roleHintCheck(role, type); if (flag) { return flag; } } return flag; } /** * 查找角色提示 */ public roleHintCheck(role: Role, type: number): boolean { let lv: number = 1; let costNum: number = 0; let itemNum: number = 0; let itemId: number = 0; switch (type) { case 0: lv = role.getExRingsData(0); let ring0Config: ExRing0Config = GlobalConfig[`ExRing${0}Config`][lv]; if (lv >= 1) return false; if (ring0Config) { costNum = ring0Config.cost; itemId = GlobalConfig.ExRingConfig[0].costItem; } break; case 1: lv = role.getExRingsData(1); let ring1Config: ExRing0Config = GlobalConfig[`ExRing${1}Config`][lv]; if (lv >= 1) return false; if (ring1Config) { costNum = ring1Config.cost; itemId = GlobalConfig.ExRingConfig[1].costItem; } break; case LongHun.TYPE_LONG_HUN: lv += role.loongSoulData.level; let loongSoulConfig: LoongSoulConfig = GlobalConfig.LoongSoulConfig[lv]; let loongSoulStageConfig: LoongSoulStageConfig = GlobalConfig.LoongSoulStageConfig[role.loongSoulData.stage]; if (loongSoulConfig) { costNum = loongSoulStageConfig.normalCost; itemId = loongSoulConfig.itemId; } break; case LongHun.TYPE_HU_DUN:
lv += role.shieldData.level; let shieldConfig: ShieldConfig = GlobalConfig.ShieldConfig[lv]; let shieldStageConfig: LoongSoulStageConfig = GlobalConfig.ShieldStageConfig[role.loongSoulData.stage]; if (shieldConfig) { costNum = shieldStageConfig.normalCost;
random_line_split
reader.rs
: [u8; BUFFER_SIZE], /// Offset of the first byte within the internal buffer that is valid start : usize, /// `Offset of the last byte + 1 within the internal buffer that is valid end : usize, /// `valid_end` is the last byte + 1 within the internal buffer /// used by a valid UTF-8 byte stream that begins with `start` As /// such `start` <= `valid_end` <= `end` If `start` < `valid_end` /// then the bytes in the buffer between the two are a valid UTF-8 /// byte stream; this should perhaps be kept in a string inside /// the structure for performance valid_end : usize, /// position in the file stream_pos : StreamPosition, } //ip Reader impl <R:std::io::Read> Reader<R> { //fp new /// Returns a new UTF-8 character [Reader], with a stream position /// set to the normal start of the file - byte 0, line 1, /// character 1 /// /// The [Reader] will default to handling zero bytes returned by /// the stream as an EOF; to modify this default behavior use the /// [set_eof_on_no_data](Reader::set_eof_on_no_data) builder to /// modify the construction. pub fn new(buf_reader: R) -> Self { Self { buf_reader, eof_on_no_data : true, eof : false, current : [0; BUFFER_SIZE], start : 0, end : 0, valid_end : 0, stream_pos : StreamPosition::new(), } } //cp set_eof_on_no_data /// Build pattern function to set the `eof_on_no_data` on the [Reader] to true or false /// /// This should not need to be set dynamically; an external source /// can set the eof flag directly if required using the /// [set_eof](Reader::set_eof) method pub fn set_eof_on_no_data(mut self, eof_on_no_data:bool) -> Self { self.eof_on_no_data = eof_on_no_data; self } //mp set_position /// Set the current stream position /// /// This may be used if, for example, a stream is being restarted; /// or if a UTF8 encoded stream occurs in the middle of a byte /// file. pub fn set_position(&mut self, stream_pos:StreamPosition) { self.stream_pos = stream_pos; } //mp set_eof /// Set the eof indicator as required; when `true` this will halt /// any new data being returned, and the internal buffer points /// will not change when more data is requested of the [Reader]. /// /// This method may be invoked on behalf of a stream that has /// completed, but that cannot indicate this by a read operation /// returning zero bytes. For example, it may be used by an /// application which uses a TcpStream for data, and which needs /// to ensure future operations on the [Reader] return no more /// data after the TcpStream has closed. pub fn set_eof(&mut self, eof:bool) { self.eof = eof; } //mp eof /// Get the current eof indicator value. /// /// The `EOF` indication is normally set for [Reader]s that have a /// stream that returns no data on a read operation, with that /// behavior modified by the /// [set_eof_on_no_data](Reader::set_eof_on_no_data) method. pub fn eof(&self) -> bool { self.eof } //mp complete /// Finish with the stream, returning the buffer handle, the /// position of the *next* character in the stream (if there were /// to be one), and any unused buffer data. pub fn complete(self) -> (R, StreamPosition, Vec<u8>) { (self.buf_reader, self.stream_pos, self.current[self.start..self.end].into()) } //mp drop_buffer /// Drop the unconsumed data, for example after it has been borrowed and used, and before [complete](Reader::complete) is invoked pub fn drop_buffer(&mut self) { self.stream_pos.move_on_bytes(self.end - self.start); self.start = self.end; } //mp buffer_is_empty /// Returns true if the internal buffer is empty pub fn buffer_is_empty(&self) -> bool { self.start == self.end } //mp borrow_buffer /// Borrow the data held in the [Reader]'s buffer. pub fn borrow_buffer(&self) -> &[u8] { &self.current[self.start..self.end] } //mp borrow_pos /// Borrow the stream position of the next character to be returned pub fn borrow_pos(&self) -> &StreamPosition { &self.stream_pos } //mp borrow /// Borrow the underlying stream pub fn borrow(&self) -> &R { &self.buf_reader } //mp borrow_mut /// Borrow the underlying stream as a mutable reference pub fn borrow_mut(&mut self) -> &mut R { &mut self.buf_reader } //fi fetch_input /// Fetch input from the underlying stream into the internal buffer, /// moving valid data to the start of the buffer first if /// required. This method should only be invoked if more data is /// required; it is relatively code-heavy. fn fetch_input(&mut self) -> Result<usize> { if self.start>BUFFER_SIZE-BUFFER_SLACK { // Move everything down by self.start let n = self.end - self.start; if n>0 { for i in 0..n { self.current[i] = self.current[self.start+i]; } } self.valid_end -= self.start; self.start = 0; // == self.start - self.start self.end = n; // == self.end - self.start } let n = self.buf_reader.read( &mut self.current[self.end..BUFFER_SIZE] )?; self.end += n; if n==0 && self.eof_on_no_data { self.eof = true; } Ok(n) } //mp next_char /// Return the next character from the stream, if one is available, or [EOF](Char::Eof). /// /// If there is no data - or not enough data - from the underlying stream, and the [Reader] is operating with the underlying stream *not* indicating EOF with a zero-byte read result, then [NoData](Char::NoData) is returned. /// /// # Errors /// /// May return [Error::MalformedUtf8] if the next bytes in the stream do not make a well-formed UTF8 character. /// /// May return [Error::IoError] if the underlying stream has an IO Error. pub fn next_char(&mut self) -> Result<Char> { if self.eof { Ok(Char::Eof) } else if self.start == self.end { // no data present, try reading data if self.fetch_input()? == 0 { Ok(Char::NoData) } else { self.next_char() } } else if self.start < self.valid_end { // there is valid UTF-8 data at buffer+self.start let s = { // std::str::from_utf8(&self.current[self.start..self.valid_end]).unwrap() unsafe { std::str::from_utf8_unchecked(&self.current[self.start..self.valid_end]) } }; let ch = s.chars().next().unwrap(); let n = ch.len_utf8(); self.start += n; self.stream_pos.move_by(n, ch); Ok(Char::Char(ch)) } else { // there is data but it may or may not be valid match std::str::from_utf8(&self.current[self.start..self.end]) { Ok(_) => { // the data is valid, mark it and the return from there self.valid_end = self.end; self.next_char() } Err(e) => { // the data is not all valid if e.valid_up_to()>0 { // some bytes form valid UTF-8 - mark them and return that data self.valid_end = self.start+e.valid_up_to(); self.next_char() } else
{ // no valid data - check it is just incomplete, or an actual error match e.error_len() { None => { // incomplete UTF-8 fetch more match self.fetch_input()? { 0 => { // ... and eof reached when incomplete UTF8 is present if self.eof { Error::malformed_utf8(self.stream_pos, self.end-self.start) } else { Ok(Char::NoData) } } _ => { // ... but got more data so try that! self.next_char() } } } Some(n) => { // Bad UTF-8 with n bytes used let r = Error::malformed_utf8(self.stream_pos, n); self.stream_pos.move_on_bytes(n); self.start += n;
conditional_block
reader.rs
`valid_end` <= `end` If `start` < `valid_end` /// then the bytes in the buffer between the two are a valid UTF-8 /// byte stream; this should perhaps be kept in a string inside /// the structure for performance valid_end : usize, /// position in the file stream_pos : StreamPosition, } //ip Reader impl <R:std::io::Read> Reader<R> { //fp new /// Returns a new UTF-8 character [Reader], with a stream position /// set to the normal start of the file - byte 0, line 1, /// character 1 /// /// The [Reader] will default to handling zero bytes returned by /// the stream as an EOF; to modify this default behavior use the /// [set_eof_on_no_data](Reader::set_eof_on_no_data) builder to /// modify the construction. pub fn new(buf_reader: R) -> Self { Self { buf_reader, eof_on_no_data : true, eof : false, current : [0; BUFFER_SIZE], start : 0, end : 0, valid_end : 0, stream_pos : StreamPosition::new(), } } //cp set_eof_on_no_data /// Build pattern function to set the `eof_on_no_data` on the [Reader] to true or false /// /// This should not need to be set dynamically; an external source /// can set the eof flag directly if required using the /// [set_eof](Reader::set_eof) method pub fn set_eof_on_no_data(mut self, eof_on_no_data:bool) -> Self { self.eof_on_no_data = eof_on_no_data; self } //mp set_position /// Set the current stream position /// /// This may be used if, for example, a stream is being restarted; /// or if a UTF8 encoded stream occurs in the middle of a byte /// file. pub fn set_position(&mut self, stream_pos:StreamPosition) { self.stream_pos = stream_pos; } //mp set_eof /// Set the eof indicator as required; when `true` this will halt /// any new data being returned, and the internal buffer points /// will not change when more data is requested of the [Reader]. /// /// This method may be invoked on behalf of a stream that has /// completed, but that cannot indicate this by a read operation /// returning zero bytes. For example, it may be used by an /// application which uses a TcpStream for data, and which needs /// to ensure future operations on the [Reader] return no more /// data after the TcpStream has closed. pub fn set_eof(&mut self, eof:bool) { self.eof = eof; } //mp eof /// Get the current eof indicator value. /// /// The `EOF` indication is normally set for [Reader]s that have a /// stream that returns no data on a read operation, with that /// behavior modified by the /// [set_eof_on_no_data](Reader::set_eof_on_no_data) method. pub fn eof(&self) -> bool { self.eof } //mp complete /// Finish with the stream, returning the buffer handle, the /// position of the *next* character in the stream (if there were /// to be one), and any unused buffer data. pub fn complete(self) -> (R, StreamPosition, Vec<u8>) { (self.buf_reader, self.stream_pos, self.current[self.start..self.end].into()) } //mp drop_buffer /// Drop the unconsumed data, for example after it has been borrowed and used, and before [complete](Reader::complete) is invoked pub fn drop_buffer(&mut self) { self.stream_pos.move_on_bytes(self.end - self.start); self.start = self.end; } //mp buffer_is_empty /// Returns true if the internal buffer is empty pub fn buffer_is_empty(&self) -> bool { self.start == self.end } //mp borrow_buffer /// Borrow the data held in the [Reader]'s buffer. pub fn borrow_buffer(&self) -> &[u8] { &self.current[self.start..self.end] } //mp borrow_pos /// Borrow the stream position of the next character to be returned pub fn borrow_pos(&self) -> &StreamPosition { &self.stream_pos } //mp borrow /// Borrow the underlying stream pub fn borrow(&self) -> &R { &self.buf_reader } //mp borrow_mut /// Borrow the underlying stream as a mutable reference pub fn borrow_mut(&mut self) -> &mut R { &mut self.buf_reader } //fi fetch_input /// Fetch input from the underlying stream into the internal buffer, /// moving valid data to the start of the buffer first if /// required. This method should only be invoked if more data is /// required; it is relatively code-heavy. fn fetch_input(&mut self) -> Result<usize> { if self.start>BUFFER_SIZE-BUFFER_SLACK { // Move everything down by self.start let n = self.end - self.start; if n>0 { for i in 0..n { self.current[i] = self.current[self.start+i]; } } self.valid_end -= self.start; self.start = 0; // == self.start - self.start self.end = n; // == self.end - self.start } let n = self.buf_reader.read( &mut self.current[self.end..BUFFER_SIZE] )?; self.end += n; if n==0 && self.eof_on_no_data { self.eof = true; } Ok(n) } //mp next_char /// Return the next character from the stream, if one is available, or [EOF](Char::Eof). /// /// If there is no data - or not enough data - from the underlying stream, and the [Reader] is operating with the underlying stream *not* indicating EOF with a zero-byte read result, then [NoData](Char::NoData) is returned. /// /// # Errors /// /// May return [Error::MalformedUtf8] if the next bytes in the stream do not make a well-formed UTF8 character. /// /// May return [Error::IoError] if the underlying stream has an IO Error. pub fn next_char(&mut self) -> Result<Char> { if self.eof { Ok(Char::Eof) } else if self.start == self.end { // no data present, try reading data if self.fetch_input()? == 0 { Ok(Char::NoData) } else { self.next_char() } } else if self.start < self.valid_end { // there is valid UTF-8 data at buffer+self.start let s = { // std::str::from_utf8(&self.current[self.start..self.valid_end]).unwrap() unsafe { std::str::from_utf8_unchecked(&self.current[self.start..self.valid_end]) } }; let ch = s.chars().next().unwrap(); let n = ch.len_utf8(); self.start += n; self.stream_pos.move_by(n, ch); Ok(Char::Char(ch)) } else { // there is data but it may or may not be valid match std::str::from_utf8(&self.current[self.start..self.end]) { Ok(_) => { // the data is valid, mark it and the return from there self.valid_end = self.end; self.next_char() } Err(e) => { // the data is not all valid if e.valid_up_to()>0 { // some bytes form valid UTF-8 - mark them and return that data self.valid_end = self.start+e.valid_up_to(); self.next_char() } else { // no valid data - check it is just incomplete, or an actual error match e.error_len() { None => { // incomplete UTF-8 fetch more match self.fetch_input()? { 0 => { // ... and eof reached when incomplete UTF8 is present if self.eof { Error::malformed_utf8(self.stream_pos, self.end-self.start) } else { Ok(Char::NoData) } } _ => { // ... but got more data so try that! self.next_char() } } } Some(n) => { // Bad UTF-8 with n bytes used let r = Error::malformed_utf8(self.stream_pos, n); self.stream_pos.move_on_bytes(n); self.start += n; r }, } } }, } } } //zz All done } //ip Iterator for Reader - iterate over characters // // allow missing doc code examples for this as it *has* an example but // rustdoc does not pick it up. #[allow(missing_doc_code_examples)]
impl <'a, R:std::io::Read> Iterator for &'a mut Reader<R> { // we will be counting with usize
random_line_split
reader.rs
that implements the [std::io::Read] stream trait. /// /// It utilizes an internal buffer of bytes that are filled as /// required from the read stream; it maintains a position with the /// stream (line and character) for the next character, and provides /// the ability to get a stream of characters from the stream with any /// UTF-8 encoding errors reported by line and character. /// /// The stream can be reclaimed by completing the use of the /// [Reader], in which case any unused bytes that have been read from /// the stream are also returned. /// /// If simple short files are to be read, using /// [std::fs::read_to_string] may a better approach than using the /// `Reader` /// /// # Example /// /// ``` /// use utf8_read::Reader; /// let str = "This is a \u{1f600} string\nWith a newline\n"; /// let mut buf_bytes = str.as_bytes(); /// let mut reader = Reader::new(&mut buf_bytes); /// for x in reader.into_iter() { /// // use char x /// } /// ``` /// /// This example could just as easily use 'for x in str' /// /// The [Reader], though, can be used over any object supporting the /// [Read](std::io::Read) trait such as a a /// [TcpStrema](std::net::TcpStream). /// pub struct Reader<R:std::io::Read> { /// The reader from which data is to be fetched buf_reader : R, /// `eof_on_no_data` defaults to true; it can be set to false to indicate that /// if the stream has no data then the reader should return Char::NoData /// when its buffer does not contain a complete UTF-8 character eof_on_no_data : bool, /// `eof` is set when the stream is complete - any character /// requested once `eof` is asserted will be `Char::Eof`. eof : bool, /// Internal buffer current : [u8; BUFFER_SIZE], /// Offset of the first byte within the internal buffer that is valid start : usize, /// `Offset of the last byte + 1 within the internal buffer that is valid end : usize, /// `valid_end` is the last byte + 1 within the internal buffer /// used by a valid UTF-8 byte stream that begins with `start` As /// such `start` <= `valid_end` <= `end` If `start` < `valid_end` /// then the bytes in the buffer between the two are a valid UTF-8 /// byte stream; this should perhaps be kept in a string inside /// the structure for performance valid_end : usize, /// position in the file stream_pos : StreamPosition, } //ip Reader impl <R:std::io::Read> Reader<R> { //fp new /// Returns a new UTF-8 character [Reader], with a stream position /// set to the normal start of the file - byte 0, line 1, /// character 1 /// /// The [Reader] will default to handling zero bytes returned by /// the stream as an EOF; to modify this default behavior use the /// [set_eof_on_no_data](Reader::set_eof_on_no_data) builder to /// modify the construction. pub fn new(buf_reader: R) -> Self { Self { buf_reader, eof_on_no_data : true, eof : false, current : [0; BUFFER_SIZE], start : 0, end : 0, valid_end : 0, stream_pos : StreamPosition::new(), } } //cp set_eof_on_no_data /// Build pattern function to set the `eof_on_no_data` on the [Reader] to true or false /// /// This should not need to be set dynamically; an external source /// can set the eof flag directly if required using the /// [set_eof](Reader::set_eof) method pub fn set_eof_on_no_data(mut self, eof_on_no_data:bool) -> Self { self.eof_on_no_data = eof_on_no_data; self } //mp set_position /// Set the current stream position /// /// This may be used if, for example, a stream is being restarted; /// or if a UTF8 encoded stream occurs in the middle of a byte /// file. pub fn set_position(&mut self, stream_pos:StreamPosition) { self.stream_pos = stream_pos; } //mp set_eof /// Set the eof indicator as required; when `true` this will halt /// any new data being returned, and the internal buffer points /// will not change when more data is requested of the [Reader]. /// /// This method may be invoked on behalf of a stream that has /// completed, but that cannot indicate this by a read operation /// returning zero bytes. For example, it may be used by an /// application which uses a TcpStream for data, and which needs /// to ensure future operations on the [Reader] return no more /// data after the TcpStream has closed. pub fn set_eof(&mut self, eof:bool) { self.eof = eof; } //mp eof /// Get the current eof indicator value. /// /// The `EOF` indication is normally set for [Reader]s that have a /// stream that returns no data on a read operation, with that /// behavior modified by the /// [set_eof_on_no_data](Reader::set_eof_on_no_data) method. pub fn eof(&self) -> bool { self.eof } //mp complete /// Finish with the stream, returning the buffer handle, the /// position of the *next* character in the stream (if there were /// to be one), and any unused buffer data. pub fn complete(self) -> (R, StreamPosition, Vec<u8>) { (self.buf_reader, self.stream_pos, self.current[self.start..self.end].into()) } //mp drop_buffer /// Drop the unconsumed data, for example after it has been borrowed and used, and before [complete](Reader::complete) is invoked pub fn drop_buffer(&mut self) { self.stream_pos.move_on_bytes(self.end - self.start); self.start = self.end; } //mp buffer_is_empty /// Returns true if the internal buffer is empty pub fn
(&self) -> bool { self.start == self.end } //mp borrow_buffer /// Borrow the data held in the [Reader]'s buffer. pub fn borrow_buffer(&self) -> &[u8] { &self.current[self.start..self.end] } //mp borrow_pos /// Borrow the stream position of the next character to be returned pub fn borrow_pos(&self) -> &StreamPosition { &self.stream_pos } //mp borrow /// Borrow the underlying stream pub fn borrow(&self) -> &R { &self.buf_reader } //mp borrow_mut /// Borrow the underlying stream as a mutable reference pub fn borrow_mut(&mut self) -> &mut R { &mut self.buf_reader } //fi fetch_input /// Fetch input from the underlying stream into the internal buffer, /// moving valid data to the start of the buffer first if /// required. This method should only be invoked if more data is /// required; it is relatively code-heavy. fn fetch_input(&mut self) -> Result<usize> { if self.start>BUFFER_SIZE-BUFFER_SLACK { // Move everything down by self.start let n = self.end - self.start; if n>0 { for i in 0..n { self.current[i] = self.current[self.start+i]; } } self.valid_end -= self.start; self.start = 0; // == self.start - self.start self.end = n; // == self.end - self.start } let n = self.buf_reader.read( &mut self.current[self.end..BUFFER_SIZE] )?; self.end += n; if n==0 && self.eof_on_no_data { self.eof = true; } Ok(n) } //mp next_char /// Return the next character from the stream, if one is available, or [EOF](Char::Eof). /// /// If there is no data - or not enough data - from the underlying stream, and the [Reader] is operating with the underlying stream *not* indicating EOF with a zero-byte read result, then [NoData](Char::NoData) is returned. /// /// # Errors /// /// May return [Error::MalformedUtf8] if the next bytes in the stream do not make a well-formed UTF8 character. /// /// May return [Error::IoError] if the underlying stream has an IO Error. pub fn next_char(&mut self) -> Result<Char> { if self.eof { Ok(Char::Eof) } else if self.start == self.end { // no data present, try reading
buffer_is_empty
identifier_name
reader.rs
ip Reader impl <R:std::io::Read> Reader<R> { //fp new /// Returns a new UTF-8 character [Reader], with a stream position /// set to the normal start of the file - byte 0, line 1, /// character 1 /// /// The [Reader] will default to handling zero bytes returned by /// the stream as an EOF; to modify this default behavior use the /// [set_eof_on_no_data](Reader::set_eof_on_no_data) builder to /// modify the construction. pub fn new(buf_reader: R) -> Self { Self { buf_reader, eof_on_no_data : true, eof : false, current : [0; BUFFER_SIZE], start : 0, end : 0, valid_end : 0, stream_pos : StreamPosition::new(), } } //cp set_eof_on_no_data /// Build pattern function to set the `eof_on_no_data` on the [Reader] to true or false /// /// This should not need to be set dynamically; an external source /// can set the eof flag directly if required using the /// [set_eof](Reader::set_eof) method pub fn set_eof_on_no_data(mut self, eof_on_no_data:bool) -> Self { self.eof_on_no_data = eof_on_no_data; self } //mp set_position /// Set the current stream position /// /// This may be used if, for example, a stream is being restarted; /// or if a UTF8 encoded stream occurs in the middle of a byte /// file. pub fn set_position(&mut self, stream_pos:StreamPosition) { self.stream_pos = stream_pos; } //mp set_eof /// Set the eof indicator as required; when `true` this will halt /// any new data being returned, and the internal buffer points /// will not change when more data is requested of the [Reader]. /// /// This method may be invoked on behalf of a stream that has /// completed, but that cannot indicate this by a read operation /// returning zero bytes. For example, it may be used by an /// application which uses a TcpStream for data, and which needs /// to ensure future operations on the [Reader] return no more /// data after the TcpStream has closed. pub fn set_eof(&mut self, eof:bool) { self.eof = eof; } //mp eof /// Get the current eof indicator value. /// /// The `EOF` indication is normally set for [Reader]s that have a /// stream that returns no data on a read operation, with that /// behavior modified by the /// [set_eof_on_no_data](Reader::set_eof_on_no_data) method. pub fn eof(&self) -> bool { self.eof } //mp complete /// Finish with the stream, returning the buffer handle, the /// position of the *next* character in the stream (if there were /// to be one), and any unused buffer data. pub fn complete(self) -> (R, StreamPosition, Vec<u8>) { (self.buf_reader, self.stream_pos, self.current[self.start..self.end].into()) } //mp drop_buffer /// Drop the unconsumed data, for example after it has been borrowed and used, and before [complete](Reader::complete) is invoked pub fn drop_buffer(&mut self) { self.stream_pos.move_on_bytes(self.end - self.start); self.start = self.end; } //mp buffer_is_empty /// Returns true if the internal buffer is empty pub fn buffer_is_empty(&self) -> bool { self.start == self.end } //mp borrow_buffer /// Borrow the data held in the [Reader]'s buffer. pub fn borrow_buffer(&self) -> &[u8] { &self.current[self.start..self.end] } //mp borrow_pos /// Borrow the stream position of the next character to be returned pub fn borrow_pos(&self) -> &StreamPosition { &self.stream_pos } //mp borrow /// Borrow the underlying stream pub fn borrow(&self) -> &R { &self.buf_reader } //mp borrow_mut /// Borrow the underlying stream as a mutable reference pub fn borrow_mut(&mut self) -> &mut R { &mut self.buf_reader } //fi fetch_input /// Fetch input from the underlying stream into the internal buffer, /// moving valid data to the start of the buffer first if /// required. This method should only be invoked if more data is /// required; it is relatively code-heavy. fn fetch_input(&mut self) -> Result<usize> { if self.start>BUFFER_SIZE-BUFFER_SLACK { // Move everything down by self.start let n = self.end - self.start; if n>0 { for i in 0..n { self.current[i] = self.current[self.start+i]; } } self.valid_end -= self.start; self.start = 0; // == self.start - self.start self.end = n; // == self.end - self.start } let n = self.buf_reader.read( &mut self.current[self.end..BUFFER_SIZE] )?; self.end += n; if n==0 && self.eof_on_no_data { self.eof = true; } Ok(n) } //mp next_char /// Return the next character from the stream, if one is available, or [EOF](Char::Eof). /// /// If there is no data - or not enough data - from the underlying stream, and the [Reader] is operating with the underlying stream *not* indicating EOF with a zero-byte read result, then [NoData](Char::NoData) is returned. /// /// # Errors /// /// May return [Error::MalformedUtf8] if the next bytes in the stream do not make a well-formed UTF8 character. /// /// May return [Error::IoError] if the underlying stream has an IO Error. pub fn next_char(&mut self) -> Result<Char> { if self.eof { Ok(Char::Eof) } else if self.start == self.end { // no data present, try reading data if self.fetch_input()? == 0 { Ok(Char::NoData) } else { self.next_char() } } else if self.start < self.valid_end { // there is valid UTF-8 data at buffer+self.start let s = { // std::str::from_utf8(&self.current[self.start..self.valid_end]).unwrap() unsafe { std::str::from_utf8_unchecked(&self.current[self.start..self.valid_end]) } }; let ch = s.chars().next().unwrap(); let n = ch.len_utf8(); self.start += n; self.stream_pos.move_by(n, ch); Ok(Char::Char(ch)) } else { // there is data but it may or may not be valid match std::str::from_utf8(&self.current[self.start..self.end]) { Ok(_) => { // the data is valid, mark it and the return from there self.valid_end = self.end; self.next_char() } Err(e) => { // the data is not all valid if e.valid_up_to()>0 { // some bytes form valid UTF-8 - mark them and return that data self.valid_end = self.start+e.valid_up_to(); self.next_char() } else { // no valid data - check it is just incomplete, or an actual error match e.error_len() { None => { // incomplete UTF-8 fetch more match self.fetch_input()? { 0 => { // ... and eof reached when incomplete UTF8 is present if self.eof { Error::malformed_utf8(self.stream_pos, self.end-self.start) } else { Ok(Char::NoData) } } _ => { // ... but got more data so try that! self.next_char() } } } Some(n) => { // Bad UTF-8 with n bytes used let r = Error::malformed_utf8(self.stream_pos, n); self.stream_pos.move_on_bytes(n); self.start += n; r }, } } }, } } } //zz All done } //ip Iterator for Reader - iterate over characters // // allow missing doc code examples for this as it *has* an example but // rustdoc does not pick it up. #[allow(missing_doc_code_examples)] impl <'a, R:std::io::Read> Iterator for &'a mut Reader<R> { // we will be counting with usize type Item = Result<char>; //mp next - return next character or None if end of file fn next(&mut self) -> Option<Self::Item>
{ match self.next_char() { Ok(Char::Char(ch)) => Some(Ok(ch)), Ok(_) => None, Err(x) => Some(Err(x)), } }
identifier_body
address.rs
//bech32 #[derive(Debug)] pub enum AddressError { InvalidAddressVersion, InvalidAddressSize, InvalidNetworkPrefix, InvalidHash, Bech32(bech32::Error), } impl From<bech32::Error> for AddressError { fn from(e: bech32::Error) -> Self { AddressError::Bech32(e) } } impl From<AddressError> for DecodingError { fn from(e: AddressError) -> DecodingError { DecodingError::InvalidData(format!("{:?}", e)) } } impl fmt::Display for AddressError { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { match self { _ => formatter.write_str("todo"), } } } // #[derive(PartialEq, Clone, Debug, Copy)] #[derive(PartialEq, Clone, Debug)] pub enum Payload { PubkeyHash(Buffer), ScriptHash(Buffer), Unknown(Buffer), } impl Payload { pub fn len(&self) -> usize { match self { Payload::PubkeyHash(hash) => hash.len(), Payload::ScriptHash(hash) => hash.len(), Payload::Unknown(hash) => hash.len(), } } pub fn is_empty(&self) -> bool { match self { Payload::PubkeyHash(hash) => hash.is_empty(), Payload::ScriptHash(hash) => hash.is_empty(), Payload::Unknown(hash) => hash.is_empty(), } } pub fn to_hash(self) -> Buffer { match self { Payload::PubkeyHash(hash) => hash, Payload::ScriptHash(hash) => hash, Payload::Unknown(hash) => hash, } } pub fn as_hash(&self) -> &Buffer { match self { Payload::PubkeyHash(hash) => hash, Payload::ScriptHash(hash) => hash, Payload::Unknown(hash) => hash, } } pub fn from_hash(hash: Buffer) -> Result<Payload, AddressError> { match hash.len() { 20 => Ok(Payload::PubkeyHash(hash)), 32 => Ok(Payload::ScriptHash(hash)), _ => Ok(Payload::Unknown(hash)), } } } //@todo Impl FromHex, ToHex //@todo ideally implement copy here, but we need to implement it for Buffer, and we really need to //look into performance degration there. // #[derive(PartialEq, Clone, Debug, Copy)] #[derive(PartialEq, Clone, Debug)] pub struct Address { //Can we make this u8? TODO //And do we even need this? pub version: u8, pub hash: Payload, } impl Address { pub fn new(version: u8, hash: Payload) -> Self { Address { version, hash } } //TODO // pub fn is_null(&self) -> bool { // self.hash.is_null() // } pub fn is_null_data(&self) -> bool { self.version == 31 } pub fn is_unspendable(&self) -> bool { self.is_null_data() } pub fn to_bech32(&self) -> String { //Also todo this should probably just be in toString, and should use writers so that we //don't allocate. //@todo this should be network dependant. Need to put work into this. //Right now this will only support mainnet addresses. // let mut data = vec![self.version]; let mut data = vec![bech32::u5::try_from_u8(self.version).unwrap()]; data.extend_from_slice(&self.hash.clone().to_hash().to_base32()); bech32::encode("hs", data).unwrap() } } //@todo review if this is a good default. Should be triggered on "null" impl Default for Address { fn default() -> Self { Address { version: 0, hash: Payload::PubkeyHash(Buffer::new()), } } } impl Decodable for Address { type Err = DecodingError; fn decode(buffer: &mut Buffer) -> Result<Self, Self::Err> { let version = buffer.read_u8()?; if version > 31 { return Err(DecodingError::InvalidData( "Invalid Address Version".to_string(), )); } let size = buffer.read_u8()?; if size < 2 || size > 40 { return Err(DecodingError::InvalidData( "Invalid Address Size".to_string(), )); } let hash = buffer.read_bytes(size as usize)?; let hash = Payload::from_hash(Buffer::from(hash))?; Ok(Address { version, hash }) } } impl Encodable for Address { fn size(&self) -> usize { 1 + 1 + self.hash.len() } fn encode(&self) -> Buffer { let mut buffer = Buffer::new(); buffer.write_u8(self.version); buffer.write_u8(self.hash.len() as u8); //TODO fix this buffer.extend(self.hash.as_hash().clone()); buffer } } impl FromStr for Address { type Err = AddressError; fn from_str(s: &str) -> Result<Self, Self::Err> { //@todo should we be checking network here? let (_hrp, data) = bech32::decode(s)?; let (version, hash) = version_hash_from_bech32(data); let hash = Payload::from_hash(hash)?; Ok(Address { version, hash }) } } // //TODO eq, partial eq, ordering. fn version_hash_from_bech32(data: Vec<u5>) -> (u8, Buffer) { let (version, d) = data.split_at(1); let hash_data = Vec::from_base32(d).unwrap(); let mut hash = Buffer::new(); for elem in hash_data.iter() { hash.write_u8(*elem); } (version[0].to_u8(), hash) } #[cfg(feature = "json")] impl serde::Serialize for Address { fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> { let mut state = s.serialize_struct("Address", 2)?; state.serialize_field("version", &self.version)?; state.serialize_field("hash", &self.hash.as_hash().to_hex())?; state.end() } } #[cfg(feature = "json")] impl<'de> Deserialize<'de> for Address { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { enum Field { Version, Hash, Str, }; impl<'de> Deserialize<'de> for Field { fn deserialize<D>(deserializer: D) -> Result<Field, D::Error> where D: Deserializer<'de>,
} } deserializer.deserialize_identifier(FieldVisitor) } } struct AddressVisitor; impl<'de> Visitor<'de> for AddressVisitor { type Value = Address; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("struct Address") } fn visit_seq<V>(self, mut seq: V) -> Result<Address, V::Error> where V: SeqAccess<'de>, { //Skip string seq.next_element()? .ok_or_else(|| de::Error::invalid_length(0, &self))?; let version = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(1, &self))?; let hash_raw: Buffer = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(2, &self))?; let hash = Payload::from_hash(hash_raw).map_err(de::Error::custom)?; Ok(Address::new(version, hash)) } fn visit_str<E>(self, value: &str) -> Result<Address, E> where E: de::Error, { Ok(Address::from_str(value).map_err(de::Error::custom)?) } fn visit_map<V>(self, mut map: V) -> Result<Address, V::Error> where V: MapAccess<'de>, { let mut version = None; let mut hash = None; while let Some(key) = map.next_key()? { match key { Field::Version => { if version.is_some() { return Err(de::Error::duplicate_field("version")); } version = Some(map.next_value()?); } Field
{ struct FieldVisitor; impl<'de> Visitor<'de> for FieldVisitor { type Value = Field; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("`version` or `hash`") } fn visit_str<E>(self, value: &str) -> Result<Field, E> where E: de::Error, { match value { "version" => Ok(Field::Version), "hash" => Ok(Field::Hash), "string" => Ok(Field::Str), _ => Err(de::Error::unknown_field(value, FIELDS)), }
identifier_body
address.rs
//bech32 #[derive(Debug)] pub enum AddressError { InvalidAddressVersion, InvalidAddressSize, InvalidNetworkPrefix, InvalidHash, Bech32(bech32::Error), } impl From<bech32::Error> for AddressError { fn from(e: bech32::Error) -> Self { AddressError::Bech32(e) } } impl From<AddressError> for DecodingError { fn from(e: AddressError) -> DecodingError { DecodingError::InvalidData(format!("{:?}", e)) } } impl fmt::Display for AddressError { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { match self { _ => formatter.write_str("todo"), } } } // #[derive(PartialEq, Clone, Debug, Copy)] #[derive(PartialEq, Clone, Debug)] pub enum Payload { PubkeyHash(Buffer), ScriptHash(Buffer), Unknown(Buffer), } impl Payload { pub fn len(&self) -> usize { match self { Payload::PubkeyHash(hash) => hash.len(), Payload::ScriptHash(hash) => hash.len(), Payload::Unknown(hash) => hash.len(), } } pub fn is_empty(&self) -> bool { match self { Payload::PubkeyHash(hash) => hash.is_empty(), Payload::ScriptHash(hash) => hash.is_empty(), Payload::Unknown(hash) => hash.is_empty(), } } pub fn to_hash(self) -> Buffer { match self { Payload::PubkeyHash(hash) => hash, Payload::ScriptHash(hash) => hash, Payload::Unknown(hash) => hash, } } pub fn as_hash(&self) -> &Buffer { match self { Payload::PubkeyHash(hash) => hash, Payload::ScriptHash(hash) => hash, Payload::Unknown(hash) => hash, } } pub fn from_hash(hash: Buffer) -> Result<Payload, AddressError> { match hash.len() { 20 => Ok(Payload::PubkeyHash(hash)), 32 => Ok(Payload::ScriptHash(hash)), _ => Ok(Payload::Unknown(hash)), } } } //@todo Impl FromHex, ToHex //@todo ideally implement copy here, but we need to implement it for Buffer, and we really need to //look into performance degration there. // #[derive(PartialEq, Clone, Debug, Copy)] #[derive(PartialEq, Clone, Debug)] pub struct Address { //Can we make this u8? TODO //And do we even need this? pub version: u8, pub hash: Payload, } impl Address { pub fn new(version: u8, hash: Payload) -> Self { Address { version, hash } } //TODO // pub fn is_null(&self) -> bool { // self.hash.is_null() // } pub fn is_null_data(&self) -> bool { self.version == 31 } pub fn is_unspendable(&self) -> bool { self.is_null_data() } pub fn to_bech32(&self) -> String { //Also todo this should probably just be in toString, and should use writers so that we //don't allocate. //@todo this should be network dependant. Need to put work into this. //Right now this will only support mainnet addresses. // let mut data = vec![self.version]; let mut data = vec![bech32::u5::try_from_u8(self.version).unwrap()]; data.extend_from_slice(&self.hash.clone().to_hash().to_base32()); bech32::encode("hs", data).unwrap() } } //@todo review if this is a good default. Should be triggered on "null" impl Default for Address { fn default() -> Self { Address { version: 0, hash: Payload::PubkeyHash(Buffer::new()), } } } impl Decodable for Address { type Err = DecodingError; fn decode(buffer: &mut Buffer) -> Result<Self, Self::Err> { let version = buffer.read_u8()?; if version > 31 { return Err(DecodingError::InvalidData( "Invalid Address Version".to_string(), )); } let size = buffer.read_u8()?; if size < 2 || size > 40 { return Err(DecodingError::InvalidData( "Invalid Address Size".to_string(), )); } let hash = buffer.read_bytes(size as usize)?; let hash = Payload::from_hash(Buffer::from(hash))?; Ok(Address { version, hash }) } } impl Encodable for Address { fn size(&self) -> usize { 1 + 1 + self.hash.len() } fn encode(&self) -> Buffer { let mut buffer = Buffer::new(); buffer.write_u8(self.version); buffer.write_u8(self.hash.len() as u8); //TODO fix this buffer.extend(self.hash.as_hash().clone()); buffer } } impl FromStr for Address { type Err = AddressError; fn from_str(s: &str) -> Result<Self, Self::Err> { //@todo should we be checking network here? let (_hrp, data) = bech32::decode(s)?; let (version, hash) = version_hash_from_bech32(data); let hash = Payload::from_hash(hash)?; Ok(Address { version, hash }) } } // //TODO eq, partial eq, ordering. fn version_hash_from_bech32(data: Vec<u5>) -> (u8, Buffer) { let (version, d) = data.split_at(1); let hash_data = Vec::from_base32(d).unwrap(); let mut hash = Buffer::new(); for elem in hash_data.iter() { hash.write_u8(*elem);
#[cfg(feature = "json")] impl serde::Serialize for Address { fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> { let mut state = s.serialize_struct("Address", 2)?; state.serialize_field("version", &self.version)?; state.serialize_field("hash", &self.hash.as_hash().to_hex())?; state.end() } } #[cfg(feature = "json")] impl<'de> Deserialize<'de> for Address { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { enum Field { Version, Hash, Str, }; impl<'de> Deserialize<'de> for Field { fn deserialize<D>(deserializer: D) -> Result<Field, D::Error> where D: Deserializer<'de>, { struct FieldVisitor; impl<'de> Visitor<'de> for FieldVisitor { type Value = Field; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("`version` or `hash`") } fn visit_str<E>(self, value: &str) -> Result<Field, E> where E: de::Error, { match value { "version" => Ok(Field::Version), "hash" => Ok(Field::Hash), "string" => Ok(Field::Str), _ => Err(de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(FieldVisitor) } } struct AddressVisitor; impl<'de> Visitor<'de> for AddressVisitor { type Value = Address; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("struct Address") } fn visit_seq<V>(self, mut seq: V) -> Result<Address, V::Error> where V: SeqAccess<'de>, { //Skip string seq.next_element()? .ok_or_else(|| de::Error::invalid_length(0, &self))?; let version = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(1, &self))?; let hash_raw: Buffer = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(2, &self))?; let hash = Payload::from_hash(hash_raw).map_err(de::Error::custom)?; Ok(Address::new(version, hash)) } fn visit_str<E>(self, value: &str) -> Result<Address, E> where E: de::Error, { Ok(Address::from_str(value).map_err(de::Error::custom)?) } fn visit_map<V>(self, mut map: V) -> Result<Address, V::Error> where V: MapAccess<'de>, { let mut version = None; let mut hash = None; while let Some(key) = map.next_key()? { match key { Field::Version => { if version.is_some() { return Err(de::Error::duplicate_field("version")); } version = Some(map.next_value()?); } Field
} (version[0].to_u8(), hash) }
random_line_split
address.rs
//bech32 #[derive(Debug)] pub enum AddressError { InvalidAddressVersion, InvalidAddressSize, InvalidNetworkPrefix, InvalidHash, Bech32(bech32::Error), } impl From<bech32::Error> for AddressError { fn from(e: bech32::Error) -> Self { AddressError::Bech32(e) } } impl From<AddressError> for DecodingError { fn from(e: AddressError) -> DecodingError { DecodingError::InvalidData(format!("{:?}", e)) } } impl fmt::Display for AddressError { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { match self { _ => formatter.write_str("todo"), } } } // #[derive(PartialEq, Clone, Debug, Copy)] #[derive(PartialEq, Clone, Debug)] pub enum Payload { PubkeyHash(Buffer), ScriptHash(Buffer), Unknown(Buffer), } impl Payload { pub fn len(&self) -> usize { match self { Payload::PubkeyHash(hash) => hash.len(), Payload::ScriptHash(hash) => hash.len(), Payload::Unknown(hash) => hash.len(), } } pub fn is_empty(&self) -> bool { match self { Payload::PubkeyHash(hash) => hash.is_empty(), Payload::ScriptHash(hash) => hash.is_empty(), Payload::Unknown(hash) => hash.is_empty(), } } pub fn to_hash(self) -> Buffer { match self { Payload::PubkeyHash(hash) => hash, Payload::ScriptHash(hash) => hash, Payload::Unknown(hash) => hash, } } pub fn as_hash(&self) -> &Buffer { match self { Payload::PubkeyHash(hash) => hash, Payload::ScriptHash(hash) => hash, Payload::Unknown(hash) => hash, } } pub fn from_hash(hash: Buffer) -> Result<Payload, AddressError> { match hash.len() { 20 => Ok(Payload::PubkeyHash(hash)), 32 => Ok(Payload::ScriptHash(hash)), _ => Ok(Payload::Unknown(hash)), } } } //@todo Impl FromHex, ToHex //@todo ideally implement copy here, but we need to implement it for Buffer, and we really need to //look into performance degration there. // #[derive(PartialEq, Clone, Debug, Copy)] #[derive(PartialEq, Clone, Debug)] pub struct Address { //Can we make this u8? TODO //And do we even need this? pub version: u8, pub hash: Payload, } impl Address { pub fn new(version: u8, hash: Payload) -> Self { Address { version, hash } } //TODO // pub fn is_null(&self) -> bool { // self.hash.is_null() // } pub fn is_null_data(&self) -> bool { self.version == 31 } pub fn is_unspendable(&self) -> bool { self.is_null_data() } pub fn to_bech32(&self) -> String { //Also todo this should probably just be in toString, and should use writers so that we //don't allocate. //@todo this should be network dependant. Need to put work into this. //Right now this will only support mainnet addresses. // let mut data = vec![self.version]; let mut data = vec![bech32::u5::try_from_u8(self.version).unwrap()]; data.extend_from_slice(&self.hash.clone().to_hash().to_base32()); bech32::encode("hs", data).unwrap() } } //@todo review if this is a good default. Should be triggered on "null" impl Default for Address { fn default() -> Self { Address { version: 0, hash: Payload::PubkeyHash(Buffer::new()), } } } impl Decodable for Address { type Err = DecodingError; fn decode(buffer: &mut Buffer) -> Result<Self, Self::Err> { let version = buffer.read_u8()?; if version > 31 { return Err(DecodingError::InvalidData( "Invalid Address Version".to_string(), )); } let size = buffer.read_u8()?; if size < 2 || size > 40 { return Err(DecodingError::InvalidData( "Invalid Address Size".to_string(), )); } let hash = buffer.read_bytes(size as usize)?; let hash = Payload::from_hash(Buffer::from(hash))?; Ok(Address { version, hash }) } } impl Encodable for Address { fn size(&self) -> usize { 1 + 1 + self.hash.len() } fn encode(&self) -> Buffer { let mut buffer = Buffer::new(); buffer.write_u8(self.version); buffer.write_u8(self.hash.len() as u8); //TODO fix this buffer.extend(self.hash.as_hash().clone()); buffer } } impl FromStr for Address { type Err = AddressError; fn from_str(s: &str) -> Result<Self, Self::Err> { //@todo should we be checking network here? let (_hrp, data) = bech32::decode(s)?; let (version, hash) = version_hash_from_bech32(data); let hash = Payload::from_hash(hash)?; Ok(Address { version, hash }) } } // //TODO eq, partial eq, ordering. fn version_hash_from_bech32(data: Vec<u5>) -> (u8, Buffer) { let (version, d) = data.split_at(1); let hash_data = Vec::from_base32(d).unwrap(); let mut hash = Buffer::new(); for elem in hash_data.iter() { hash.write_u8(*elem); } (version[0].to_u8(), hash) } #[cfg(feature = "json")] impl serde::Serialize for Address { fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> { let mut state = s.serialize_struct("Address", 2)?; state.serialize_field("version", &self.version)?; state.serialize_field("hash", &self.hash.as_hash().to_hex())?; state.end() } } #[cfg(feature = "json")] impl<'de> Deserialize<'de> for Address { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { enum Field { Version, Hash, Str, }; impl<'de> Deserialize<'de> for Field { fn deserialize<D>(deserializer: D) -> Result<Field, D::Error> where D: Deserializer<'de>, { struct FieldVisitor; impl<'de> Visitor<'de> for FieldVisitor { type Value = Field; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("`version` or `hash`") } fn visit_str<E>(self, value: &str) -> Result<Field, E> where E: de::Error, { match value { "version" => Ok(Field::Version), "hash" => Ok(Field::Hash), "string" => Ok(Field::Str), _ => Err(de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(FieldVisitor) } } struct AddressVisitor; impl<'de> Visitor<'de> for AddressVisitor { type Value = Address; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("struct Address") } fn visit_seq<V>(self, mut seq: V) -> Result<Address, V::Error> where V: SeqAccess<'de>, { //Skip string seq.next_element()? .ok_or_else(|| de::Error::invalid_length(0, &self))?; let version = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(1, &self))?; let hash_raw: Buffer = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(2, &self))?; let hash = Payload::from_hash(hash_raw).map_err(de::Error::custom)?; Ok(Address::new(version, hash)) } fn visit_str<E>(self, value: &str) -> Result<Address, E> where E: de::Error, { Ok(Address::from_str(value).map_err(de::Error::custom)?) } fn visit_map<V>(self, mut map: V) -> Result<Address, V::Error> where V: MapAccess<'de>, { let mut version = None; let mut hash = None; while let Some(key) = map.next_key()? { match key { Field::Version => { if version.is_some()
version = Some(map.next_value()?); }
{ return Err(de::Error::duplicate_field("version")); }
conditional_block
address.rs
//bech32 #[derive(Debug)] pub enum AddressError { InvalidAddressVersion, InvalidAddressSize, InvalidNetworkPrefix, InvalidHash, Bech32(bech32::Error), } impl From<bech32::Error> for AddressError { fn from(e: bech32::Error) -> Self { AddressError::Bech32(e) } } impl From<AddressError> for DecodingError { fn from(e: AddressError) -> DecodingError { DecodingError::InvalidData(format!("{:?}", e)) } } impl fmt::Display for AddressError { fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result { match self { _ => formatter.write_str("todo"), } } } // #[derive(PartialEq, Clone, Debug, Copy)] #[derive(PartialEq, Clone, Debug)] pub enum Payload { PubkeyHash(Buffer), ScriptHash(Buffer), Unknown(Buffer), } impl Payload { pub fn len(&self) -> usize { match self { Payload::PubkeyHash(hash) => hash.len(), Payload::ScriptHash(hash) => hash.len(), Payload::Unknown(hash) => hash.len(), } } pub fn is_empty(&self) -> bool { match self { Payload::PubkeyHash(hash) => hash.is_empty(), Payload::ScriptHash(hash) => hash.is_empty(), Payload::Unknown(hash) => hash.is_empty(), } } pub fn to_hash(self) -> Buffer { match self { Payload::PubkeyHash(hash) => hash, Payload::ScriptHash(hash) => hash, Payload::Unknown(hash) => hash, } } pub fn as_hash(&self) -> &Buffer { match self { Payload::PubkeyHash(hash) => hash, Payload::ScriptHash(hash) => hash, Payload::Unknown(hash) => hash, } } pub fn from_hash(hash: Buffer) -> Result<Payload, AddressError> { match hash.len() { 20 => Ok(Payload::PubkeyHash(hash)), 32 => Ok(Payload::ScriptHash(hash)), _ => Ok(Payload::Unknown(hash)), } } } //@todo Impl FromHex, ToHex //@todo ideally implement copy here, but we need to implement it for Buffer, and we really need to //look into performance degration there. // #[derive(PartialEq, Clone, Debug, Copy)] #[derive(PartialEq, Clone, Debug)] pub struct Address { //Can we make this u8? TODO //And do we even need this? pub version: u8, pub hash: Payload, } impl Address { pub fn new(version: u8, hash: Payload) -> Self { Address { version, hash } } //TODO // pub fn is_null(&self) -> bool { // self.hash.is_null() // } pub fn
(&self) -> bool { self.version == 31 } pub fn is_unspendable(&self) -> bool { self.is_null_data() } pub fn to_bech32(&self) -> String { //Also todo this should probably just be in toString, and should use writers so that we //don't allocate. //@todo this should be network dependant. Need to put work into this. //Right now this will only support mainnet addresses. // let mut data = vec![self.version]; let mut data = vec![bech32::u5::try_from_u8(self.version).unwrap()]; data.extend_from_slice(&self.hash.clone().to_hash().to_base32()); bech32::encode("hs", data).unwrap() } } //@todo review if this is a good default. Should be triggered on "null" impl Default for Address { fn default() -> Self { Address { version: 0, hash: Payload::PubkeyHash(Buffer::new()), } } } impl Decodable for Address { type Err = DecodingError; fn decode(buffer: &mut Buffer) -> Result<Self, Self::Err> { let version = buffer.read_u8()?; if version > 31 { return Err(DecodingError::InvalidData( "Invalid Address Version".to_string(), )); } let size = buffer.read_u8()?; if size < 2 || size > 40 { return Err(DecodingError::InvalidData( "Invalid Address Size".to_string(), )); } let hash = buffer.read_bytes(size as usize)?; let hash = Payload::from_hash(Buffer::from(hash))?; Ok(Address { version, hash }) } } impl Encodable for Address { fn size(&self) -> usize { 1 + 1 + self.hash.len() } fn encode(&self) -> Buffer { let mut buffer = Buffer::new(); buffer.write_u8(self.version); buffer.write_u8(self.hash.len() as u8); //TODO fix this buffer.extend(self.hash.as_hash().clone()); buffer } } impl FromStr for Address { type Err = AddressError; fn from_str(s: &str) -> Result<Self, Self::Err> { //@todo should we be checking network here? let (_hrp, data) = bech32::decode(s)?; let (version, hash) = version_hash_from_bech32(data); let hash = Payload::from_hash(hash)?; Ok(Address { version, hash }) } } // //TODO eq, partial eq, ordering. fn version_hash_from_bech32(data: Vec<u5>) -> (u8, Buffer) { let (version, d) = data.split_at(1); let hash_data = Vec::from_base32(d).unwrap(); let mut hash = Buffer::new(); for elem in hash_data.iter() { hash.write_u8(*elem); } (version[0].to_u8(), hash) } #[cfg(feature = "json")] impl serde::Serialize for Address { fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> { let mut state = s.serialize_struct("Address", 2)?; state.serialize_field("version", &self.version)?; state.serialize_field("hash", &self.hash.as_hash().to_hex())?; state.end() } } #[cfg(feature = "json")] impl<'de> Deserialize<'de> for Address { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { enum Field { Version, Hash, Str, }; impl<'de> Deserialize<'de> for Field { fn deserialize<D>(deserializer: D) -> Result<Field, D::Error> where D: Deserializer<'de>, { struct FieldVisitor; impl<'de> Visitor<'de> for FieldVisitor { type Value = Field; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("`version` or `hash`") } fn visit_str<E>(self, value: &str) -> Result<Field, E> where E: de::Error, { match value { "version" => Ok(Field::Version), "hash" => Ok(Field::Hash), "string" => Ok(Field::Str), _ => Err(de::Error::unknown_field(value, FIELDS)), } } } deserializer.deserialize_identifier(FieldVisitor) } } struct AddressVisitor; impl<'de> Visitor<'de> for AddressVisitor { type Value = Address; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("struct Address") } fn visit_seq<V>(self, mut seq: V) -> Result<Address, V::Error> where V: SeqAccess<'de>, { //Skip string seq.next_element()? .ok_or_else(|| de::Error::invalid_length(0, &self))?; let version = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(1, &self))?; let hash_raw: Buffer = seq .next_element()? .ok_or_else(|| de::Error::invalid_length(2, &self))?; let hash = Payload::from_hash(hash_raw).map_err(de::Error::custom)?; Ok(Address::new(version, hash)) } fn visit_str<E>(self, value: &str) -> Result<Address, E> where E: de::Error, { Ok(Address::from_str(value).map_err(de::Error::custom)?) } fn visit_map<V>(self, mut map: V) -> Result<Address, V::Error> where V: MapAccess<'de>, { let mut version = None; let mut hash = None; while let Some(key) = map.next_key()? { match key { Field::Version => { if version.is_some() { return Err(de::Error::duplicate_field("version")); } version = Some(map.next_value()?); }
is_null_data
identifier_name
path.py
_direction(self, DIRECTIONS=DIRECTIONS): """ Get the current facing direction of the map_obstacle. """ return self.map_obstacle.get_current_facing_direction(DIRECTIONS=DIRECTIONS) # this isn't used anywhere yet def is_map_obstacle_in_screen_range(self): """ Determines if the map_obstacle is within the bounds of whatever is on screen at the moment. If the object is of a type that is capable of moving, and it is not on screen, then it is not moving. """ raise NotImplementedError def mark_nodes_as_members_of_threat_zone(self): """ Based on the nodes in this threat zone, mark each main graph's nodes as members of this threat zone. """ for y in range(self.top_left_y, self.top_left_y + self.height): for x in range(self.top_left_x, self.top_left_x + self.width): main_node = self.main_graph[y][x] main_node.threat_zones.add(self) self.nodes.append(main_node) def update_obstacle_location(self): """ Updates which node has the obstacle. This does not recompute the graph based on this new information. Each threat zone is responsible for updating its own map objects. So there will never be a time when the current x value attached to the map_obstacle does not represent the actual previous location. """ # find the previous location of the obstacle old_y = self.map_obstacle.y old_x = self.map_obstacle.x # remove it from the main graph self.main_graph[old_y][old_x].contents.remove(self.map_obstacle) # get the latest location self.map_obstacle.update_location() (new_y, new_x) = (self.map_obstacle.y, self.map_obstacle.x) # add it back into the main graph self.main_graph[new_y][new_x].contents.add(self.map_obstacle) # update the map obstacle (not necessary, but it doesn't hurt) self.map_obstacle.y = new_y self.map_obstacle.x = new_x def is_node_in_threat_zone(self, y, x): """ Checks if the node is in the range of the threat zone. """ y_condition = self.top_left_y <= y < self.top_left_y + self.height x_condition = self.top_left_x <= x < self.top_left_x + self.width return y_condition and x_condition def is_node_in_sight_range(self, y, x, skip_range_check=False): """ Checks if the node is in the sight range of the threat. """ if not skip_range_check: if not self.is_node_in_threat_zone(y, x): return False if self.sight_range == 0: return False # TODO: sight range can be blocked by collidable map objects. But this # node wouldn't be in the threat zone anyway. y_condition = self.map_obstacle.y == y x_condition = self.map_obstacle.x == x # this probably only happens if the player warps to the exact spot if y_condition and x_condition: raise Exception( "Don't know the meaning of being on top of the map_obstacle." ) # check if y or x matches the map object return y_condition or x_condition def is_node_in_active_sight_range(self, y, x, skip_sight_range_check=False, skip_range_check=False, DIRECTIONS=DIRECTIONS): """ Checks if the node has active sight range lock. """ if not skip_sight_range_check: # can't be in active sight range if not in sight range if not self.is_in_sight_range(y, x, skip_range_check=skip_range_check): return False y_condition = self.map_obstacle.y == y x_condition = self.map_obstacle.x == x # this probably only happens if the player warps to the exact spot if y_condition and x_condition: raise Exception( "Don't know the meaning of being on top of the map_obstacle." ) current_facing_direction = self.get_current_facing_direction(DIRECTIONS=DIRECTIONS) if current_facing_direction not in DIRECTIONS.keys(): raise Exception( "Invalid direction." ) if current_facing_direction in [DIRECTIONS["UP"], DIRECTIONS["DOWN"]]: # map_obstacle is looking up/down but player doesn't match y if not y_condition: return False if current_facing_direction == DIRECTIONS["UP"]: return y < self.map_obstacle.y elif current_facing_direction == DIRECTIONS["DOWN"]: return y > self.map_obstacle.y else: # map_obstacle is looking left/right but player doesn't match x if not x_condition: return False if current_facing_direction == DIRECTIONS["LEFT"]: return x < self.map_obstacle.x elif current_facing_direction == DIRECTIONS["RIGHT"]: return x > self.map_obstacle.x def calculate_node_cost(self, y, x, consider_sight_range=True, PENALTIES=PENALTIES): """ Calculates the cost of the node w.r.t this threat zone. Turn off consider_sight_range when not in the threat zone. """ penalty = 0 # The node is probably in the threat zone because otherwise why would # this cost function be called? Only the nodes that are members of the # current threat zone would have a reference to this threat zone and # this function. if not self.is_node_in_threat_zone(y, x): penalty += PENALTIES["NONE"] # Additionally, if htis codepath is ever hit, the other node cost # function will have already used the "NONE" penalty, so this would # really be doubling the penalty of the node.. raise Exception( "Didn't expect to calculate a non-threat-zone node's cost, " "since this is a threat zone function." ) else: penalty += PENALTIES["THREAT_ZONE"] if consider_sight_range: if self.is_node_in_sight_range(y, x, skip_range_check=True): penalty += PENALTIES["SIGHT_RANGE"] params = { "skip_sight_range_check": True, "skip_range_check": True, } active_sight_range = self.is_node_in_active_sight_range(y, x, **params) if active_sight_range: penalty += PENALTIES["ACTIVE_SIGHT_RANGE"] return penalty def create_graph(some_map): """ Creates the array of nodes representing the in-game map. """ map_height = some_map.height map_width = some_map.width map_obstacles = some_map.obstacles nodes = [[None] * map_width] * map_height # create a node representing each position on the map for y in range(0, map_height): for x in range(0, map_width): position = (y, x) # create a node describing this position node = Node(position=position) # store it on the graph nodes[y][x] = node # look through all moving characters, non-moving characters, and items for map_obstacle in map_obstacles: # all characters must start somewhere node = nodes[map_obstacle.y][map_obstacle.x] # store the map_obstacle on this node. node.contents.add(map_obstacle) # only create threat zones for moving/turning entities if map_obstacle.can_move() or map_obstacle.can_turn_without_moving(): threat_zone = ThreatZone(map_obstacle, nodes, some_map) threat_zone.mark_nodes_as_members_of_threat_zone() some_map.nodes = nodes return nodes class Map(object): """ The ``Map`` class provides an interface for reading the currently loaded map. """ def __init__(self, cry, parsed_map, height, width, map_group_id, map_id, config=config): """ :param cry: pokemon crystal emulation interface :type cry: crystal """ self.config = config self.cry = cry self.threat_zones = set() self.obstacles = set() self.parsed_map = parsed_map self.map_group_id = map_group_id self.map_id = map_id self.height = height self.width = width def travel_to(self, destination_location): """ Does path planning and figures out the quickest way to get to the destination. """ raise NotImplementedError @staticmethod def from_rom(cry, address): """ Loads a map from bytes in ROM at the given address. :param cry: pokemon crystal wrapper """ raise NotImplementedError @staticmethod def from_wram(cry): """ Loads a map from bytes in WRAM. :param cry: pokemon crystal wrapper """ raise NotImplementedError def draw_path(self, path): """ Draws a path on an image of the current map. The path must be an
iterable of nodes to visit in (y, x) format. """ palettes = pokemontools.map_gfx.read_palettes(self.config)
random_line_split
path.py
_graph = main_graph self.sight_range = self.calculate_sight_range() self.top_left_y = None self.top_left_x = None self.bottom_right_y = None self.bottom_right_x = None self.height = None self.width = None self.size = self.calculate_size() # nodes specific to this threat zone self.nodes = [] def calculate_size(self): """ Calculate the bounds of the threat zone based on the map obstacle. Returns the top left corner (y, x) and the bottom right corner (y, x) in the form of ((y, x), (y, x), height, width). """ top_left_y = 0 top_left_x = 0 bottom_right_y = 1 bottom_right_x = 1 # TODO: calculate the correct bounds of the threat zone. raise NotImplementedError # if there is a sight_range for this map_obstacle then increase the size of the zone. if self.sight_range > 0: top_left_y += self.sight_range top_left_x += self.sight_range bottom_right_y += self.sight_range bottom_right_x += self.sight_range top_left = (top_left_y, top_left_x) bottom_right = (bottom_right_y, bottom_right_x) height = bottom_right_y - top_left_y width = bottom_right_x - top_left_x self.top_left_y = top_left_y self.top_left_x = top_left_x self.bottom_right_y = bottom_right_y self.bottom_right_x = bottom_right_x self.height = height self.width = width return (top_left, bottom_right, height, width) def is_player_near(self, y, x): """ Applies a boundary of one around the threat zone, then checks if the player is inside. This is how the threatzone activates to calculate an updated graph or set of penalties for each step. """ y_condition = (self.top_left_y - 1) <= y < (self.bottom_right_y + 1) x_condition = (self.top_left_x - 1) <= x < (self.bottom_right_x + 1) return y_condition and x_condition def check_map_obstacle_has_sight(self): """ Determines if the map object has the sight feature. """ return self.map_obstacle.sight_range > 0 def calculate_sight_range(self): """ Calculates the range that the object is able to see. """ if not self.check_map_obstacle_has_sight(): return 0 else: return self.map_obstacle.sight_range def get_current_facing_direction(self, DIRECTIONS=DIRECTIONS): """ Get the current facing direction of the map_obstacle. """ return self.map_obstacle.get_current_facing_direction(DIRECTIONS=DIRECTIONS) # this isn't used anywhere yet def is_map_obstacle_in_screen_range(self): """ Determines if the map_obstacle is within the bounds of whatever is on screen at the moment. If the object is of a type that is capable of moving, and it is not on screen, then it is not moving. """ raise NotImplementedError def mark_nodes_as_members_of_threat_zone(self): """ Based on the nodes in this threat zone, mark each main graph's nodes as members of this threat zone. """ for y in range(self.top_left_y, self.top_left_y + self.height): for x in range(self.top_left_x, self.top_left_x + self.width): main_node = self.main_graph[y][x] main_node.threat_zones.add(self) self.nodes.append(main_node) def update_obstacle_location(self): """ Updates which node has the obstacle. This does not recompute the graph based on this new information. Each threat zone is responsible for updating its own map objects. So there will never be a time when the current x value attached to the map_obstacle does not represent the actual previous location. """ # find the previous location of the obstacle old_y = self.map_obstacle.y old_x = self.map_obstacle.x # remove it from the main graph self.main_graph[old_y][old_x].contents.remove(self.map_obstacle) # get the latest location self.map_obstacle.update_location() (new_y, new_x) = (self.map_obstacle.y, self.map_obstacle.x) # add it back into the main graph self.main_graph[new_y][new_x].contents.add(self.map_obstacle) # update the map obstacle (not necessary, but it doesn't hurt) self.map_obstacle.y = new_y self.map_obstacle.x = new_x def is_node_in_threat_zone(self, y, x): """ Checks if the node is in the range of the threat zone. """ y_condition = self.top_left_y <= y < self.top_left_y + self.height x_condition = self.top_left_x <= x < self.top_left_x + self.width return y_condition and x_condition def is_node_in_sight_range(self, y, x, skip_range_check=False): """ Checks if the node is in the sight range of the threat. """ if not skip_range_check: if not self.is_node_in_threat_zone(y, x): return False if self.sight_range == 0: return False # TODO: sight range can be blocked by collidable map objects. But this # node wouldn't be in the threat zone anyway. y_condition = self.map_obstacle.y == y x_condition = self.map_obstacle.x == x # this probably only happens if the player warps to the exact spot if y_condition and x_condition: raise Exception( "Don't know the meaning of being on top of the map_obstacle." ) # check if y or x matches the map object return y_condition or x_condition def is_node_in_active_sight_range(self, y, x, skip_sight_range_check=False, skip_range_check=False, DIRECTIONS=DIRECTIONS): """ Checks if the node has active sight range lock. """ if not skip_sight_range_check: # can't be in active sight range if not in sight range if not self.is_in_sight_range(y, x, skip_range_check=skip_range_check): return False y_condition = self.map_obstacle.y == y x_condition = self.map_obstacle.x == x # this probably only happens if the player warps to the exact spot if y_condition and x_condition: raise Exception( "Don't know the meaning of being on top of the map_obstacle." ) current_facing_direction = self.get_current_facing_direction(DIRECTIONS=DIRECTIONS) if current_facing_direction not in DIRECTIONS.keys(): raise Exception( "Invalid direction." ) if current_facing_direction in [DIRECTIONS["UP"], DIRECTIONS["DOWN"]]: # map_obstacle is looking up/down but player doesn't match y if not y_condition: return False if current_facing_direction == DIRECTIONS["UP"]: return y < self.map_obstacle.y elif current_facing_direction == DIRECTIONS["DOWN"]: return y > self.map_obstacle.y else: # map_obstacle is looking left/right but player doesn't match x if not x_condition: return False if current_facing_direction == DIRECTIONS["LEFT"]: return x < self.map_obstacle.x elif current_facing_direction == DIRECTIONS["RIGHT"]: return x > self.map_obstacle.x def calculate_node_cost(self, y, x, consider_sight_range=True, PENALTIES=PENALTIES): """ Calculates the cost of the node w.r.t this threat zone. Turn off consider_sight_range when not in the threat zone. """ penalty = 0 # The node is probably in the threat zone because otherwise why would # this cost function be called? Only the nodes that are members of the # current threat zone would have a reference to this threat zone and # this function. if not self.is_node_in_threat_zone(y, x): penalty += PENALTIES["NONE"] # Additionally, if htis codepath is ever hit, the other node cost # function will have already used the "NONE" penalty, so this would # really be doubling the penalty of the node.. raise Exception( "Didn't expect to calculate a non-threat-zone node's cost, " "since this is a threat zone function." ) else:
penalty += PENALTIES["THREAT_ZONE"] if consider_sight_range: if self.is_node_in_sight_range(y, x, skip_range_check=True): penalty += PENALTIES["SIGHT_RANGE"] params = { "skip_sight_range_check": True, "skip_range_check": True, } active_sight_range = self.is_node_in_active_sight_range(y, x, **params) if active_sight_range: penalty += PENALTIES["ACTIVE_SIGHT_RANGE"]
conditional_block
path.py
the map. """ def __init__(self, some_map, identifier, sight_range=None, movement=None, turn=None, simulation=False, facing_direction=DIRECTIONS["DOWN"]): """ :param some_map: a reference to the map that this object belongs to :param identifier: which object on the map does this correspond to? :param simulation: set to False to not read from RAM """ self.simulation = simulation self.some_map = some_map self.identifier = identifier self._sight_range = sight_range if self._sight_range is None: self._sight_range = self._get_sight_range() self._movement = movement if self._movement is None: self._movement = self._get_movement() self._turn = turn if self._turn is None: self._turn = self._get_turn() self.facing_direction = facing_direction if not self.facing_direction: self.facing_direction = self.get_current_facing_direction() self.update_location() def update_location(self): """ Determines the (y, x) location of the given map_obstacle object, which can be a reference to an item, npc or trainer npc. """ if self.simulation: return (self.y, self.x) else: raise NotImplementedError self.y = new_y self.x = new_x return (new_y, new_x) def _get_current_facing_direction(self, DIRECTIONS=DIRECTIONS): """ Get the current facing direction of the map_obstacle. """ raise NotImplementedError def get_current_facing_direction(self, DIRECTIONS=DIRECTIONS):
def _get_movement(self): """ Figures out the "movement" variable. Also, this converts from the internal game's format into True or False for whether or not the object is capable of moving. """ raise NotImplementedError @property def movement(self): if self._movement is None: self._movement = self._get_movement() return self._movement def can_move(self): """ Checks if this map_obstacle is capable of movement. """ return self.movement def _get_turn(self): """ Checks whether or not the map_obstacle can turn. This only matters for trainers. """ raise NotImplementedError @property def turn(self): if self._turn is None: self._turn = self._get_turn() return self._turn def can_turn_without_moving(self): """ Checks whether or not the map_obstacle can turn. This only matters for trainers. """ return self.turn def _get_sight_range(self): """ Figure out the sight range of this map_obstacle. """ raise NotImplementedError @property def sight_range(self): if self._sight_range is None: self._sight_range = self._get_sight_range() return self._sight_range class ThreatZone(object): """ A ``ThreatZone`` represents the area surrounding a moving or turning object that the player can try to avoid. """ def __init__(self, map_obstacle, main_graph): """ Constructs a ``ThreatZone`` based on a graph of a map and a particular object on that map. :param map_obstacle: the subject based on which to build a threat zone :param main_graph: a reference to the map's nodes """ self.map_obstacle = map_obstacle self.main_graph = main_graph self.sight_range = self.calculate_sight_range() self.top_left_y = None self.top_left_x = None self.bottom_right_y = None self.bottom_right_x = None self.height = None self.width = None self.size = self.calculate_size() # nodes specific to this threat zone self.nodes = [] def calculate_size(self): """ Calculate the bounds of the threat zone based on the map obstacle. Returns the top left corner (y, x) and the bottom right corner (y, x) in the form of ((y, x), (y, x), height, width). """ top_left_y = 0 top_left_x = 0 bottom_right_y = 1 bottom_right_x = 1 # TODO: calculate the correct bounds of the threat zone. raise NotImplementedError # if there is a sight_range for this map_obstacle then increase the size of the zone. if self.sight_range > 0: top_left_y += self.sight_range top_left_x += self.sight_range bottom_right_y += self.sight_range bottom_right_x += self.sight_range top_left = (top_left_y, top_left_x) bottom_right = (bottom_right_y, bottom_right_x) height = bottom_right_y - top_left_y width = bottom_right_x - top_left_x self.top_left_y = top_left_y self.top_left_x = top_left_x self.bottom_right_y = bottom_right_y self.bottom_right_x = bottom_right_x self.height = height self.width = width return (top_left, bottom_right, height, width) def is_player_near(self, y, x): """ Applies a boundary of one around the threat zone, then checks if the player is inside. This is how the threatzone activates to calculate an updated graph or set of penalties for each step. """ y_condition = (self.top_left_y - 1) <= y < (self.bottom_right_y + 1) x_condition = (self.top_left_x - 1) <= x < (self.bottom_right_x + 1) return y_condition and x_condition def check_map_obstacle_has_sight(self): """ Determines if the map object has the sight feature. """ return self.map_obstacle.sight_range > 0 def calculate_sight_range(self): """ Calculates the range that the object is able to see. """ if not self.check_map_obstacle_has_sight(): return 0 else: return self.map_obstacle.sight_range def get_current_facing_direction(self, DIRECTIONS=DIRECTIONS): """ Get the current facing direction of the map_obstacle. """ return self.map_obstacle.get_current_facing_direction(DIRECTIONS=DIRECTIONS) # this isn't used anywhere yet def is_map_obstacle_in_screen_range(self): """ Determines if the map_obstacle is within the bounds of whatever is on screen at the moment. If the object is of a type that is capable of moving, and it is not on screen, then it is not moving. """ raise NotImplementedError def mark_nodes_as_members_of_threat_zone(self): """ Based on the nodes in this threat zone, mark each main graph's nodes as members of this threat zone. """ for y in range(self.top_left_y, self.top_left_y + self.height): for x in range(self.top_left_x, self.top_left_x + self.width): main_node = self.main_graph[y][x] main_node.threat_zones.add(self) self.nodes.append(main_node) def update_obstacle_location(self): """ Updates which node has the obstacle. This does not recompute the graph based on this new information. Each threat zone is responsible for updating its own map objects. So there will never be a time when the current x value attached to the map_obstacle does not represent the actual previous location. """ # find the previous location of the obstacle old_y = self.map_obstacle.y old_x = self.map_obstacle.x # remove it from the main graph self.main_graph[old_y][old_x].contents.remove(self.map_obstacle) # get the latest location self.map_obstacle.update_location() (new_y, new_x) = (self.map_obstacle.y, self.map_obstacle.x) # add it back into the main graph self.main_graph[new_y][new_x].contents.add(self.map_obstacle) # update the map obstacle (not necessary, but it doesn't hurt) self.map_obstacle.y = new_y self.map_obstacle.x = new_x def is_node_in_threat_zone(self, y, x): """ Checks if the node is in the range of the threat zone. """ y_condition = self.top_left_y <= y < self.top_left_y + self.height x_condition = self.top_left_x <= x < self.top_left_x + self.width return y_condition and x_condition def is_node_in_sight_range(self, y, x, skip_range_check=False): """ Checks if the node is in the sight range of the threat. """ if not skip_range_check: if not self.is_node_in_threat_zone(y, x): return False if self.sight_range == 0: return False # TODO:
""" Get the current facing direction of the map_obstacle. """ if not self.simulation: self.facing_direction = self._get_current_facing_direction(DIRECTIONS=DIRECTIONS) return self.facing_direction
identifier_body
path.py
the map. """ def __init__(self, some_map, identifier, sight_range=None, movement=None, turn=None, simulation=False, facing_direction=DIRECTIONS["DOWN"]): """ :param some_map: a reference to the map that this object belongs to :param identifier: which object on the map does this correspond to? :param simulation: set to False to not read from RAM """ self.simulation = simulation self.some_map = some_map self.identifier = identifier self._sight_range = sight_range if self._sight_range is None: self._sight_range = self._get_sight_range() self._movement = movement if self._movement is None: self._movement = self._get_movement() self._turn = turn if self._turn is None: self._turn = self._get_turn() self.facing_direction = facing_direction if not self.facing_direction: self.facing_direction = self.get_current_facing_direction() self.update_location() def update_location(self): """ Determines the (y, x) location of the given map_obstacle object, which can be a reference to an item, npc or trainer npc. """ if self.simulation: return (self.y, self.x) else: raise NotImplementedError self.y = new_y self.x = new_x return (new_y, new_x) def _get_current_facing_direction(self, DIRECTIONS=DIRECTIONS): """ Get the current facing direction of the map_obstacle. """ raise NotImplementedError def get_current_facing_direction(self, DIRECTIONS=DIRECTIONS): """ Get the current facing direction of the map_obstacle. """ if not self.simulation: self.facing_direction = self._get_current_facing_direction(DIRECTIONS=DIRECTIONS) return self.facing_direction def _get_movement(self): """ Figures out the "movement" variable. Also, this converts from the internal game's format into True or False for whether or not the object is capable of moving. """ raise NotImplementedError @property def movement(self): if self._movement is None: self._movement = self._get_movement() return self._movement def can_move(self): """ Checks if this map_obstacle is capable of movement. """ return self.movement def _get_turn(self): """ Checks whether or not the map_obstacle can turn. This only matters for trainers. """ raise NotImplementedError @property def turn(self): if self._turn is None: self._turn = self._get_turn() return self._turn def can_turn_without_moving(self): """ Checks whether or not the map_obstacle can turn. This only matters for trainers. """ return self.turn def _get_sight_range(self): """ Figure out the sight range of this map_obstacle. """ raise NotImplementedError @property def sight_range(self): if self._sight_range is None: self._sight_range = self._get_sight_range() return self._sight_range class ThreatZone(object): """ A ``ThreatZone`` represents the area surrounding a moving or turning object that the player can try to avoid. """ def __init__(self, map_obstacle, main_graph): """ Constructs a ``ThreatZone`` based on a graph of a map and a particular object on that map. :param map_obstacle: the subject based on which to build a threat zone :param main_graph: a reference to the map's nodes """ self.map_obstacle = map_obstacle self.main_graph = main_graph self.sight_range = self.calculate_sight_range() self.top_left_y = None self.top_left_x = None self.bottom_right_y = None self.bottom_right_x = None self.height = None self.width = None self.size = self.calculate_size() # nodes specific to this threat zone self.nodes = [] def calculate_size(self): """ Calculate the bounds of the threat zone based on the map obstacle. Returns the top left corner (y, x) and the bottom right corner (y, x) in the form of ((y, x), (y, x), height, width). """ top_left_y = 0 top_left_x = 0 bottom_right_y = 1 bottom_right_x = 1 # TODO: calculate the correct bounds of the threat zone. raise NotImplementedError # if there is a sight_range for this map_obstacle then increase the size of the zone. if self.sight_range > 0: top_left_y += self.sight_range top_left_x += self.sight_range bottom_right_y += self.sight_range bottom_right_x += self.sight_range top_left = (top_left_y, top_left_x) bottom_right = (bottom_right_y, bottom_right_x) height = bottom_right_y - top_left_y width = bottom_right_x - top_left_x self.top_left_y = top_left_y self.top_left_x = top_left_x self.bottom_right_y = bottom_right_y self.bottom_right_x = bottom_right_x self.height = height self.width = width return (top_left, bottom_right, height, width) def
(self, y, x): """ Applies a boundary of one around the threat zone, then checks if the player is inside. This is how the threatzone activates to calculate an updated graph or set of penalties for each step. """ y_condition = (self.top_left_y - 1) <= y < (self.bottom_right_y + 1) x_condition = (self.top_left_x - 1) <= x < (self.bottom_right_x + 1) return y_condition and x_condition def check_map_obstacle_has_sight(self): """ Determines if the map object has the sight feature. """ return self.map_obstacle.sight_range > 0 def calculate_sight_range(self): """ Calculates the range that the object is able to see. """ if not self.check_map_obstacle_has_sight(): return 0 else: return self.map_obstacle.sight_range def get_current_facing_direction(self, DIRECTIONS=DIRECTIONS): """ Get the current facing direction of the map_obstacle. """ return self.map_obstacle.get_current_facing_direction(DIRECTIONS=DIRECTIONS) # this isn't used anywhere yet def is_map_obstacle_in_screen_range(self): """ Determines if the map_obstacle is within the bounds of whatever is on screen at the moment. If the object is of a type that is capable of moving, and it is not on screen, then it is not moving. """ raise NotImplementedError def mark_nodes_as_members_of_threat_zone(self): """ Based on the nodes in this threat zone, mark each main graph's nodes as members of this threat zone. """ for y in range(self.top_left_y, self.top_left_y + self.height): for x in range(self.top_left_x, self.top_left_x + self.width): main_node = self.main_graph[y][x] main_node.threat_zones.add(self) self.nodes.append(main_node) def update_obstacle_location(self): """ Updates which node has the obstacle. This does not recompute the graph based on this new information. Each threat zone is responsible for updating its own map objects. So there will never be a time when the current x value attached to the map_obstacle does not represent the actual previous location. """ # find the previous location of the obstacle old_y = self.map_obstacle.y old_x = self.map_obstacle.x # remove it from the main graph self.main_graph[old_y][old_x].contents.remove(self.map_obstacle) # get the latest location self.map_obstacle.update_location() (new_y, new_x) = (self.map_obstacle.y, self.map_obstacle.x) # add it back into the main graph self.main_graph[new_y][new_x].contents.add(self.map_obstacle) # update the map obstacle (not necessary, but it doesn't hurt) self.map_obstacle.y = new_y self.map_obstacle.x = new_x def is_node_in_threat_zone(self, y, x): """ Checks if the node is in the range of the threat zone. """ y_condition = self.top_left_y <= y < self.top_left_y + self.height x_condition = self.top_left_x <= x < self.top_left_x + self.width return y_condition and x_condition def is_node_in_sight_range(self, y, x, skip_range_check=False): """ Checks if the node is in the sight range of the threat. """ if not skip_range_check: if not self.is_node_in_threat_zone(y, x): return False if self.sight_range == 0: return False # TODO
is_player_near
identifier_name
time_driver.rs
DRIVER.on_interrupt() } }; (TIM4, timer, $block:ident, UP, $irq:ident) => { #[cfg(time_driver_tim4)] #[interrupt] fn $irq() { DRIVER.on_interrupt() } }; (TIM5, timer, $block:ident, UP, $irq:ident) => { #[cfg(time_driver_tim5)] #[interrupt] fn $irq() { DRIVER.on_interrupt() } }; (TIM12, timer, $block:ident, UP, $irq:ident) => { #[cfg(time_driver_tim12)] #[interrupt] fn $irq() { DRIVER.on_interrupt() } }; (TIM15, timer, $block:ident, UP, $irq:ident) => { #[cfg(time_driver_tim15)] #[interrupt] fn $irq() { DRIVER.on_interrupt() } }; } // Clock timekeeping works with something we call "periods", which are time intervals // of 2^15 ticks. The Clock counter value is 16 bits, so one "overflow cycle" is 2 periods. // // A `period` count is maintained in parallel to the Timer hardware `counter`, like this: // - `period` and `counter` start at 0 // - `period` is incremented on overflow (at counter value 0) // - `period` is incremented "midway" between overflows (at counter value 0x8000) // // Therefore, when `period` is even, counter is in 0..0x7FFF. When odd, counter is in 0x8000..0xFFFF // This allows for now() to return the correct value even if it races an overflow. // // To get `now()`, `period` is read first, then `counter` is read. If the counter value matches // the expected range for the `period` parity, we're done. If it doesn't, this means that // a new period start has raced us between reading `period` and `counter`, so we assume the `counter` value // corresponds to the next period. // // `period` is a 32bit integer, so It overflows on 2^32 * 2^15 / 32768 seconds of uptime, which is 136 years. fn calc_now(period: u32, counter: u16) -> u64 { ((period as u64) << 15) + ((counter as u32 ^ ((period & 1) << 15)) as u64) } struct AlarmState { timestamp: Cell<u64>, // This is really a Option<(fn(*mut ()), *mut ())> // but fn pointers aren't allowed in const yet callback: Cell<*const ()>, ctx: Cell<*mut ()>, } unsafe impl Send for AlarmState {} impl AlarmState { const fn new() -> Self { Self { timestamp: Cell::new(u64::MAX), callback: Cell::new(ptr::null()), ctx: Cell::new(ptr::null_mut()), } } } struct RtcDriver { /// Number of 2^15 periods elapsed since boot. period: AtomicU32, alarm_count: AtomicU8, /// Timestamp at which to fire alarm. u64::MAX if no alarm is scheduled. alarms: Mutex<CriticalSectionRawMutex, [AlarmState; ALARM_COUNT]>, } const ALARM_STATE_NEW: AlarmState = AlarmState::new(); embassy_time::time_driver_impl!(static DRIVER: RtcDriver = RtcDriver { period: AtomicU32::new(0), alarm_count: AtomicU8::new(0), alarms: Mutex::const_new(CriticalSectionRawMutex::new(), [ALARM_STATE_NEW; ALARM_COUNT]), }); impl RtcDriver { fn init(&'static self) { let r = T::regs_gp16(); <T as RccPeripheral>::enable(); <T as RccPeripheral>::reset(); let timer_freq = T::frequency(); // NOTE(unsafe) Critical section to use the unsafe methods critical_section::with(|_| unsafe { r.cr1().modify(|w| w.set_cen(false)); r.cnt().write(|w| w.set_cnt(0)); let psc = timer_freq.0 / TICK_HZ as u32 - 1; let psc: u16 = match psc.try_into() { Err(_) => panic!("psc division overflow: {}", psc), Ok(n) => n, }; r.psc().write(|w| w.set_psc(psc)); r.arr().write(|w| w.set_arr(u16::MAX)); // Set URS, generate update and clear URS r.cr1().modify(|w| w.set_urs(vals::Urs::COUNTERONLY)); r.egr().write(|w| w.set_ug(true)); r.cr1().modify(|w| w.set_urs(vals::Urs::ANYEVENT)); // Mid-way point r.ccr(0).write(|w| w.set_ccr(0x8000)); // Enable overflow and half-overflow interrupts r.dier().write(|w| { w.set_uie(true); w.set_ccie(0, true); }); let irq: <T as BasicInstance>::Interrupt = core::mem::transmute(()); irq.unpend(); irq.enable(); r.cr1().modify(|w| w.set_cen(true)); }) } fn on_interrupt(&self) { let r = T::regs_gp16(); // NOTE(unsafe) Use critical section to access the methods // XXX: reduce the size of this critical section ? critical_section::with(|cs| unsafe { let sr = r.sr().read(); let dier = r.dier().read(); // Clear all interrupt flags. Bits in SR are "write 0 to clear", so write the bitwise NOT. // Other approaches such as writing all zeros, or RMWing won't work, they can // miss interrupts. r.sr().write_value(regs::SrGp(!sr.0)); // Overflow if sr.uif() { self.next_period(); } // Half overflow if sr.ccif(0) { self.next_period(); } for n in 0..ALARM_COUNT { if sr.ccif(n + 1) && dier.ccie(n + 1) { self.trigger_alarm(n, cs); } } }) } fn next_period(&self) { let r = T::regs_gp16(); let period = self.period.fetch_add(1, Ordering::Relaxed) + 1; let t = (period as u64) << 15; critical_section::with(move |cs| unsafe { r.dier().modify(move |w| { for n in 0..ALARM_COUNT { let alarm = &self.alarms.borrow(cs)[n]; let at = alarm.timestamp.get(); if at < t + 0xc000 { // just enable it. `set_alarm` has already set the correct CCR val. w.set_ccie(n + 1, true); } } }) }) } fn get_alarm<'a>(&'a self, cs: CriticalSection<'a>, alarm: AlarmHandle) -> &'a AlarmState { // safety: we're allowed to assume the AlarmState is created by us, and // we never create one that's out of bounds. unsafe { self.alarms.borrow(cs).get_unchecked(alarm.id() as usize) } } fn trigger_alarm(&self, n: usize, cs: CriticalSection) { let alarm = &self.alarms.borrow(cs)[n]; alarm.timestamp.set(u64::MAX); // Call after clearing alarm, so the callback can set another alarm. // safety: // - we can ignore the possiblity of `f` being unset (null) because of the safety contract of `allocate_alarm`. // - other than that we only store valid function pointers into alarm.callback let f: fn(*mut ()) = unsafe { mem::transmute(alarm.callback.get()) }; f(alarm.ctx.get()); } } impl Driver for RtcDriver { fn now(&self) -> u64 { let r = T::regs_gp16(); let period = self.period.load(Ordering::Relaxed); compiler_fence(Ordering::Acquire); // NOTE(unsafe) Atomic read with no side-effects let counter = unsafe { r.cnt().read().cnt() }; calc_now(period, counter) } unsafe fn allocate_alarm(&self) -> Option<AlarmHandle> { let id = self.alarm_count.fetch_update(Ordering::AcqRel, Ordering::Acquire, |x| { if x < ALARM_COUNT as u8 { Some(x + 1) } else { None } }); match id { Ok(id) => Some(AlarmHandle::new(id)), Err(_) => None, } } fn
set_alarm_callback
identifier_name
time_driver.rs
cfg(time_driver_tim3)] type T = peripherals::TIM3; #[cfg(time_driver_tim4)] type T = peripherals::TIM4; #[cfg(time_driver_tim5)] type T = peripherals::TIM5; #[cfg(time_driver_tim12)] type T = peripherals::TIM12; #[cfg(time_driver_tim15)] type T = peripherals::TIM15; foreach_interrupt! { (TIM2, timer, $block:ident, UP, $irq:ident) => { #[cfg(time_driver_tim2)] #[interrupt] fn $irq() { DRIVER.on_interrupt() } }; (TIM3, timer, $block:ident, UP, $irq:ident) => { #[cfg(time_driver_tim3)] #[interrupt] fn $irq() { DRIVER.on_interrupt() } }; (TIM4, timer, $block:ident, UP, $irq:ident) => { #[cfg(time_driver_tim4)] #[interrupt] fn $irq() { DRIVER.on_interrupt() } }; (TIM5, timer, $block:ident, UP, $irq:ident) => { #[cfg(time_driver_tim5)] #[interrupt] fn $irq() { DRIVER.on_interrupt() } }; (TIM12, timer, $block:ident, UP, $irq:ident) => { #[cfg(time_driver_tim12)] #[interrupt] fn $irq() { DRIVER.on_interrupt() } }; (TIM15, timer, $block:ident, UP, $irq:ident) => {
#[cfg(time_driver_tim15)] #[interrupt] fn $irq() { DRIVER.on_interrupt() } }; } // Clock timekeeping works with something we call "periods", which are time intervals // of 2^15 ticks. The Clock counter value is 16 bits, so one "overflow cycle" is 2 periods. // // A `period` count is maintained in parallel to the Timer hardware `counter`, like this: // - `period` and `counter` start at 0 // - `period` is incremented on overflow (at counter value 0) // - `period` is incremented "midway" between overflows (at counter value 0x8000) // // Therefore, when `period` is even, counter is in 0..0x7FFF. When odd, counter is in 0x8000..0xFFFF // This allows for now() to return the correct value even if it races an overflow. // // To get `now()`, `period` is read first, then `counter` is read. If the counter value matches // the expected range for the `period` parity, we're done. If it doesn't, this means that // a new period start has raced us between reading `period` and `counter`, so we assume the `counter` value // corresponds to the next period. // // `period` is a 32bit integer, so It overflows on 2^32 * 2^15 / 32768 seconds of uptime, which is 136 years. fn calc_now(period: u32, counter: u16) -> u64 { ((period as u64) << 15) + ((counter as u32 ^ ((period & 1) << 15)) as u64) } struct AlarmState { timestamp: Cell<u64>, // This is really a Option<(fn(*mut ()), *mut ())> // but fn pointers aren't allowed in const yet callback: Cell<*const ()>, ctx: Cell<*mut ()>, } unsafe impl Send for AlarmState {} impl AlarmState { const fn new() -> Self { Self { timestamp: Cell::new(u64::MAX), callback: Cell::new(ptr::null()), ctx: Cell::new(ptr::null_mut()), } } } struct RtcDriver { /// Number of 2^15 periods elapsed since boot. period: AtomicU32, alarm_count: AtomicU8, /// Timestamp at which to fire alarm. u64::MAX if no alarm is scheduled. alarms: Mutex<CriticalSectionRawMutex, [AlarmState; ALARM_COUNT]>, } const ALARM_STATE_NEW: AlarmState = AlarmState::new(); embassy_time::time_driver_impl!(static DRIVER: RtcDriver = RtcDriver { period: AtomicU32::new(0), alarm_count: AtomicU8::new(0), alarms: Mutex::const_new(CriticalSectionRawMutex::new(), [ALARM_STATE_NEW; ALARM_COUNT]), }); impl RtcDriver { fn init(&'static self) { let r = T::regs_gp16(); <T as RccPeripheral>::enable(); <T as RccPeripheral>::reset(); let timer_freq = T::frequency(); // NOTE(unsafe) Critical section to use the unsafe methods critical_section::with(|_| unsafe { r.cr1().modify(|w| w.set_cen(false)); r.cnt().write(|w| w.set_cnt(0)); let psc = timer_freq.0 / TICK_HZ as u32 - 1; let psc: u16 = match psc.try_into() { Err(_) => panic!("psc division overflow: {}", psc), Ok(n) => n, }; r.psc().write(|w| w.set_psc(psc)); r.arr().write(|w| w.set_arr(u16::MAX)); // Set URS, generate update and clear URS r.cr1().modify(|w| w.set_urs(vals::Urs::COUNTERONLY)); r.egr().write(|w| w.set_ug(true)); r.cr1().modify(|w| w.set_urs(vals::Urs::ANYEVENT)); // Mid-way point r.ccr(0).write(|w| w.set_ccr(0x8000)); // Enable overflow and half-overflow interrupts r.dier().write(|w| { w.set_uie(true); w.set_ccie(0, true); }); let irq: <T as BasicInstance>::Interrupt = core::mem::transmute(()); irq.unpend(); irq.enable(); r.cr1().modify(|w| w.set_cen(true)); }) } fn on_interrupt(&self) { let r = T::regs_gp16(); // NOTE(unsafe) Use critical section to access the methods // XXX: reduce the size of this critical section ? critical_section::with(|cs| unsafe { let sr = r.sr().read(); let dier = r.dier().read(); // Clear all interrupt flags. Bits in SR are "write 0 to clear", so write the bitwise NOT. // Other approaches such as writing all zeros, or RMWing won't work, they can // miss interrupts. r.sr().write_value(regs::SrGp(!sr.0)); // Overflow if sr.uif() { self.next_period(); } // Half overflow if sr.ccif(0) { self.next_period(); } for n in 0..ALARM_COUNT { if sr.ccif(n + 1) && dier.ccie(n + 1) { self.trigger_alarm(n, cs); } } }) } fn next_period(&self) { let r = T::regs_gp16(); let period = self.period.fetch_add(1, Ordering::Relaxed) + 1; let t = (period as u64) << 15; critical_section::with(move |cs| unsafe { r.dier().modify(move |w| { for n in 0..ALARM_COUNT { let alarm = &self.alarms.borrow(cs)[n]; let at = alarm.timestamp.get(); if at < t + 0xc000 { // just enable it. `set_alarm` has already set the correct CCR val. w.set_ccie(n + 1, true); } } }) }) } fn get_alarm<'a>(&'a self, cs: CriticalSection<'a>, alarm: AlarmHandle) -> &'a AlarmState { // safety: we're allowed to assume the AlarmState is created by us, and // we never create one that's out of bounds. unsafe { self.alarms.borrow(cs).get_unchecked(alarm.id() as usize) } } fn trigger_alarm(&self, n: usize, cs: CriticalSection) { let alarm = &self.alarms.borrow(cs)[n]; alarm.timestamp.set(u64::MAX); // Call after clearing alarm, so the callback can set another alarm. // safety: // - we can ignore the possiblity of `f` being unset (null) because of the safety contract of `allocate_alarm`. // - other than that we only store valid function pointers into alarm.callback let f: fn(*mut ()) = unsafe { mem::transmute(alarm.callback.get()) }; f(alarm.ctx.get()); } } impl Driver for RtcDriver { fn now(&self) -> u64 { let r
random_line_split
time_driver.rs
$irq() { DRIVER.on_interrupt() } }; (TIM4, timer, $block:ident, UP, $irq:ident) => { #[cfg(time_driver_tim4)] #[interrupt] fn $irq() { DRIVER.on_interrupt() } }; (TIM5, timer, $block:ident, UP, $irq:ident) => { #[cfg(time_driver_tim5)] #[interrupt] fn $irq() { DRIVER.on_interrupt() } }; (TIM12, timer, $block:ident, UP, $irq:ident) => { #[cfg(time_driver_tim12)] #[interrupt] fn $irq() { DRIVER.on_interrupt() } }; (TIM15, timer, $block:ident, UP, $irq:ident) => { #[cfg(time_driver_tim15)] #[interrupt] fn $irq() { DRIVER.on_interrupt() } }; } // Clock timekeeping works with something we call "periods", which are time intervals // of 2^15 ticks. The Clock counter value is 16 bits, so one "overflow cycle" is 2 periods. // // A `period` count is maintained in parallel to the Timer hardware `counter`, like this: // - `period` and `counter` start at 0 // - `period` is incremented on overflow (at counter value 0) // - `period` is incremented "midway" between overflows (at counter value 0x8000) // // Therefore, when `period` is even, counter is in 0..0x7FFF. When odd, counter is in 0x8000..0xFFFF // This allows for now() to return the correct value even if it races an overflow. // // To get `now()`, `period` is read first, then `counter` is read. If the counter value matches // the expected range for the `period` parity, we're done. If it doesn't, this means that // a new period start has raced us between reading `period` and `counter`, so we assume the `counter` value // corresponds to the next period. // // `period` is a 32bit integer, so It overflows on 2^32 * 2^15 / 32768 seconds of uptime, which is 136 years. fn calc_now(period: u32, counter: u16) -> u64 { ((period as u64) << 15) + ((counter as u32 ^ ((period & 1) << 15)) as u64) } struct AlarmState { timestamp: Cell<u64>, // This is really a Option<(fn(*mut ()), *mut ())> // but fn pointers aren't allowed in const yet callback: Cell<*const ()>, ctx: Cell<*mut ()>, } unsafe impl Send for AlarmState {} impl AlarmState { const fn new() -> Self { Self { timestamp: Cell::new(u64::MAX), callback: Cell::new(ptr::null()), ctx: Cell::new(ptr::null_mut()), } } } struct RtcDriver { /// Number of 2^15 periods elapsed since boot. period: AtomicU32, alarm_count: AtomicU8, /// Timestamp at which to fire alarm. u64::MAX if no alarm is scheduled. alarms: Mutex<CriticalSectionRawMutex, [AlarmState; ALARM_COUNT]>, } const ALARM_STATE_NEW: AlarmState = AlarmState::new(); embassy_time::time_driver_impl!(static DRIVER: RtcDriver = RtcDriver { period: AtomicU32::new(0), alarm_count: AtomicU8::new(0), alarms: Mutex::const_new(CriticalSectionRawMutex::new(), [ALARM_STATE_NEW; ALARM_COUNT]), }); impl RtcDriver { fn init(&'static self) { let r = T::regs_gp16(); <T as RccPeripheral>::enable(); <T as RccPeripheral>::reset(); let timer_freq = T::frequency(); // NOTE(unsafe) Critical section to use the unsafe methods critical_section::with(|_| unsafe { r.cr1().modify(|w| w.set_cen(false)); r.cnt().write(|w| w.set_cnt(0)); let psc = timer_freq.0 / TICK_HZ as u32 - 1; let psc: u16 = match psc.try_into() { Err(_) => panic!("psc division overflow: {}", psc), Ok(n) => n, }; r.psc().write(|w| w.set_psc(psc)); r.arr().write(|w| w.set_arr(u16::MAX)); // Set URS, generate update and clear URS r.cr1().modify(|w| w.set_urs(vals::Urs::COUNTERONLY)); r.egr().write(|w| w.set_ug(true)); r.cr1().modify(|w| w.set_urs(vals::Urs::ANYEVENT)); // Mid-way point r.ccr(0).write(|w| w.set_ccr(0x8000)); // Enable overflow and half-overflow interrupts r.dier().write(|w| { w.set_uie(true); w.set_ccie(0, true); }); let irq: <T as BasicInstance>::Interrupt = core::mem::transmute(()); irq.unpend(); irq.enable(); r.cr1().modify(|w| w.set_cen(true)); }) } fn on_interrupt(&self) { let r = T::regs_gp16(); // NOTE(unsafe) Use critical section to access the methods // XXX: reduce the size of this critical section ? critical_section::with(|cs| unsafe { let sr = r.sr().read(); let dier = r.dier().read(); // Clear all interrupt flags. Bits in SR are "write 0 to clear", so write the bitwise NOT. // Other approaches such as writing all zeros, or RMWing won't work, they can // miss interrupts. r.sr().write_value(regs::SrGp(!sr.0)); // Overflow if sr.uif() { self.next_period(); } // Half overflow if sr.ccif(0) { self.next_period(); } for n in 0..ALARM_COUNT { if sr.ccif(n + 1) && dier.ccie(n + 1) { self.trigger_alarm(n, cs); } } }) } fn next_period(&self) { let r = T::regs_gp16(); let period = self.period.fetch_add(1, Ordering::Relaxed) + 1; let t = (period as u64) << 15; critical_section::with(move |cs| unsafe { r.dier().modify(move |w| { for n in 0..ALARM_COUNT { let alarm = &self.alarms.borrow(cs)[n]; let at = alarm.timestamp.get(); if at < t + 0xc000 { // just enable it. `set_alarm` has already set the correct CCR val. w.set_ccie(n + 1, true); } } }) }) } fn get_alarm<'a>(&'a self, cs: CriticalSection<'a>, alarm: AlarmHandle) -> &'a AlarmState { // safety: we're allowed to assume the AlarmState is created by us, and // we never create one that's out of bounds. unsafe { self.alarms.borrow(cs).get_unchecked(alarm.id() as usize) } } fn trigger_alarm(&self, n: usize, cs: CriticalSection) { let alarm = &self.alarms.borrow(cs)[n]; alarm.timestamp.set(u64::MAX); // Call after clearing alarm, so the callback can set another alarm. // safety: // - we can ignore the possiblity of `f` being unset (null) because of the safety contract of `allocate_alarm`. // - other than that we only store valid function pointers into alarm.callback let f: fn(*mut ()) = unsafe { mem::transmute(alarm.callback.get()) }; f(alarm.ctx.get()); } } impl Driver for RtcDriver { fn now(&self) -> u64 { let r = T::regs_gp16(); let period = self.period.load(Ordering::Relaxed); compiler_fence(Ordering::Acquire); // NOTE(unsafe) Atomic read with no side-effects let counter = unsafe { r.cnt().read().cnt() }; calc_now(period, counter) } unsafe fn allocate_alarm(&self) -> Option<AlarmHandle>
{ let id = self.alarm_count.fetch_update(Ordering::AcqRel, Ordering::Acquire, |x| { if x < ALARM_COUNT as u8 { Some(x + 1) } else { None } }); match id { Ok(id) => Some(AlarmHandle::new(id)), Err(_) => None, } }
identifier_body
mathMode.ts
', inline: 'yes', notation: 'auto', precision: '4', align: 'left', }; function truthy(s: string) { s = s.toLowerCase(); return s.startsWith('t') || s.startsWith('y') || s === '1'; } function falsey(s: string) { s = s.toLowerCase(); return s.startsWith('f') || s.startsWith('n') || s === '0'; } // if is in a block return {start, end} // where start is the first math line of a block // and end is the close tag of the block (last line + 1) // otherwise returns false function find_block(cm: any, lineno: number): Block { if (!lineno && lineno !== 0) lineno = cm.lastLine(); let start = -1; // A line is in a block if it is wrapped in a ```math and ``` // We start at lineno - 1 to ensure that event the trailing // ``` will be treated as part of a block for (let i = lineno; i >= cm.firstLine(); i--) { const line = cm.getLine(i); // If we encounter an end of block marker // then we know we wer not in a block if (line === '```') { return null; } else if (line === '```math') { start = i + 1; break; } } if (start === -1) return null; for (let i = start; i < cm.lineCount(); i++) { const line = cm.getLine(i); if (line.indexOf('```') === 0) { if (line.trim() === '```') { return { start: start, end: i - 1 }; } return null; } } return null; } function find_inline_math(cm: any, lineno: number): Block { const line = cm.getLine(lineno); if (line.match(inline_math_regex)) { return { start: lineno, end: lineno }; } return null; } function find_math(cm: any, lineno: number): Block { const block = find_block(cm, lineno); const inline = find_inline_math(cm, lineno); // It's possible that a user may input an inline math style line into a block // and we don't want that to prevent this system from finding the block // so we check for the block first and check for inline if no block is found return block ? block : inline; } // We sometimes we will want to find all the math blocks in order // to re-process an entire note function reprocess_all(cm: any) { cm.state.mathMode.scope = {}; cm.state.mathMode.lineData = {}; let noteConfig = Object.assign({}, defaultConfig); for (let i = cm.firstLine(); i < cm.lineCount(); i++) { const to_process = find_math(cm, i); if (!to_process) continue; process_block(cm, to_process, noteConfig) // Jump to end of the block // This does nothing for inline math, and prevents duplicated // running of larger blocks i = to_process.end; } refresh_widgets(cm, { start: cm.firstLine(), end: cm.lineCount() - 1 }); } function insert_math_at(cm: any, lineno: number) { const line = cm.getLine(lineno); const result = cm.state.mathMode.lineData[lineno]; cm.replaceRange(line + equation_result_separator + result, { line: lineno, ch: 0 }, { line: lineno, ch:line.length }); } function
(line: string): string { return line.replace(inline_math_regex, ''); } function process_block(cm: any, block: Block, noteConfig: any) { // scope is global to the note let scope = cm.state.mathMode.scope; let config = Object.assign({}, noteConfig); const math = mathjs.create(mathjs.all, { number: 'BigNumber' }); for (let i = block.start; i <= block.end; i++) { const full_line = cm.getLine(i).split(equation_result_separator); const line = full_line[0]; if (!line) continue; // This is configuration, not math // current system is fairly simplistic (maybe even ugly) // but it's small enough now that I can justify it // remember to re-evaulate this if/when things get more complex if (line.includes(':')) { const [ key, value ] = line.split(':', 2); config[key.trim()] = value.trim(); cm.state.mathMode.lineData[i] = { isConfig: true }; if (falsey(config.simplify)) { math.config({ number: 'BigNumber', precision: 64 }); } else { math.config({ number: 'number' }); } continue; } // Process one line let result = ''; try { const p = math.parse(get_line_equation(line)); if (falsey(config.simplify)) result = p.evaluate(scope); else result = math.simplify(p) result = math.format(result, { precision: Number(config.precision), notation: config.notation, }); if (p.name && truthy(config.verbose)) result = p.name + ': ' + result; } catch(e) { result = e.message; if (e.message.indexOf('Cannot create unit') === 0) { result = ''; } } cm.state.mathMode.lineData[i] = { result: result, inputHidden: config.hide === 'expression', resultHidden: config.hide === 'result', inline: truthy(config.inline), alignRight: config.align === 'right', } } if (truthy(config.global)) { noteConfig = Object.assign(noteConfig, config, {global: 'block'}); } } function clear_math_widgets(cm: any, lineInfo: any) { // This could potentially cause a conflict with another plugin cm.removeLineClass(lineInfo.handle, 'wrap', 'cm-comment'); if (lineInfo.widgets) { cm.removeLineClass(lineInfo.handle, 'text', 'math-hidden'); cm.removeLineClass(lineInfo.handle, 'text', 'math-input-inline'); for (const wid of lineInfo.widgets) { if (wid.className === 'math-result-line') wid.clear(); } } } function refresh_widgets(cm: any, block: Block) { for (let i = block.start; i <= block.end; i++) { const line = cm.lineInfo(i); clear_math_widgets(cm, line); const full_line = line.text.split(equation_result_separator); const lineData = cm.state.mathMode.lineData[i]; // Don't bother showing the result if it has already been inserted into the text if (full_line[1]) continue; if (!lineData) continue; if (lineData.isConfig) { cm.addLineClass(i, 'wrap', 'cm-comment'); continue; } if (lineData.resultHidden) continue; if (lineData.inputHidden) cm.addLineClass(i, 'text', 'math-hidden'); else if (lineData.inline) cm.addLineClass(i, 'text', 'math-input-inline'); const marker = lineData.inputHidden ? equation_result_collapsed : equation_result_separator; const res = document.createElement('div'); const node = document.createTextNode(marker + lineData.result); res.appendChild(node); if (lineData.alignRight) res.setAttribute('class', 'math-result-right'); // handleMouseEvents gives control of mouse handling for the widget to codemirror // This is necessary to get the cursor to be placed in the right location ofter // clicking on a widget // The downside is that it breaks copying of widget text (for textareas, it never // works on contenteditable) // I'm okay with this because I want the user to be able to select a block // without accidently grabbing the result cm.addLineWidget(i, res, { className: 'math-result-line', handleMouseEvents: true }); } } // If there are lines that don't belong to a block and contain math-result-line // widgets, then we should clear them function clean_up(cm: any) { for (let i = cm.firstLine(); i < cm.lineCount(); i++) { if (!find_math(cm, i)) { const line = cm.lineInfo(i); clear_math_widgets(cm, line); } } } // On each change we're going to scan for function on_change(cm: any, change: any) { clean_up(cm); // Most changes are the user typing a single character // If this doesn't happen inside a math block, we shouldn't re-process // +input means the user input the text (as opposed to joplin/plugin
get_line_equation
identifier_name
mathMode.ts
inline: 'yes', notation: 'auto', precision: '4', align: 'left', }; function truthy(s: string) { s = s.toLowerCase(); return s.startsWith('t') || s.startsWith('y') || s === '1'; } function falsey(s: string) { s = s.toLowerCase(); return s.startsWith('f') || s.startsWith('n') || s === '0'; } // if is in a block return {start, end} // where start is the first math line of a block // and end is the close tag of the block (last line + 1) // otherwise returns false function find_block(cm: any, lineno: number): Block { if (!lineno && lineno !== 0) lineno = cm.lastLine(); let start = -1; // A line is in a block if it is wrapped in a ```math and ``` // We start at lineno - 1 to ensure that event the trailing // ``` will be treated as part of a block for (let i = lineno; i >= cm.firstLine(); i--) { const line = cm.getLine(i); // If we encounter an end of block marker // then we know we wer not in a block if (line === '```') { return null; } else if (line === '```math') { start = i + 1; break; } } if (start === -1) return null; for (let i = start; i < cm.lineCount(); i++) { const line = cm.getLine(i); if (line.indexOf('```') === 0) { if (line.trim() === '```') { return { start: start, end: i - 1 }; } return null; } } return null; } function find_inline_math(cm: any, lineno: number): Block { const line = cm.getLine(lineno); if (line.match(inline_math_regex)) { return { start: lineno, end: lineno }; } return null; } function find_math(cm: any, lineno: number): Block { const block = find_block(cm, lineno); const inline = find_inline_math(cm, lineno); // It's possible that a user may input an inline math style line into a block // and we don't want that to prevent this system from finding the block // so we check for the block first and check for inline if no block is found return block ? block : inline; } // We sometimes we will want to find all the math blocks in order // to re-process an entire note function reprocess_all(cm: any) { cm.state.mathMode.scope = {}; cm.state.mathMode.lineData = {}; let noteConfig = Object.assign({}, defaultConfig); for (let i = cm.firstLine(); i < cm.lineCount(); i++) { const to_process = find_math(cm, i); if (!to_process) continue; process_block(cm, to_process, noteConfig) // Jump to end of the block // This does nothing for inline math, and prevents duplicated // running of larger blocks i = to_process.end; } refresh_widgets(cm, { start: cm.firstLine(), end: cm.lineCount() - 1 }); } function insert_math_at(cm: any, lineno: number) { const line = cm.getLine(lineno); const result = cm.state.mathMode.lineData[lineno]; cm.replaceRange(line + equation_result_separator + result, { line: lineno, ch: 0 }, { line: lineno, ch:line.length }); } function get_line_equation(line: string): string { return line.replace(inline_math_regex, ''); } function process_block(cm: any, block: Block, noteConfig: any) { // scope is global to the note let scope = cm.state.mathMode.scope; let config = Object.assign({}, noteConfig); const math = mathjs.create(mathjs.all, { number: 'BigNumber' }); for (let i = block.start; i <= block.end; i++) { const full_line = cm.getLine(i).split(equation_result_separator); const line = full_line[0]; if (!line) continue; // This is configuration, not math // current system is fairly simplistic (maybe even ugly) // but it's small enough now that I can justify it // remember to re-evaulate this if/when things get more complex if (line.includes(':')) { const [ key, value ] = line.split(':', 2); config[key.trim()] = value.trim(); cm.state.mathMode.lineData[i] = { isConfig: true }; if (falsey(config.simplify)) { math.config({ number: 'BigNumber', precision: 64 }); } else { math.config({ number: 'number' }); } continue; } // Process one line let result = ''; try { const p = math.parse(get_line_equation(line)); if (falsey(config.simplify)) result = p.evaluate(scope); else result = math.simplify(p) result = math.format(result, { precision: Number(config.precision), notation: config.notation, }); if (p.name && truthy(config.verbose)) result = p.name + ': ' + result; } catch(e) { result = e.message; if (e.message.indexOf('Cannot create unit') === 0) { result = ''; } } cm.state.mathMode.lineData[i] = { result: result, inputHidden: config.hide === 'expression', resultHidden: config.hide === 'result', inline: truthy(config.inline), alignRight: config.align === 'right', } } if (truthy(config.global)) { noteConfig = Object.assign(noteConfig, config, {global: 'block'}); } } function clear_math_widgets(cm: any, lineInfo: any) { // This could potentially cause a conflict with another plugin cm.removeLineClass(lineInfo.handle, 'wrap', 'cm-comment'); if (lineInfo.widgets) { cm.removeLineClass(lineInfo.handle, 'text', 'math-hidden'); cm.removeLineClass(lineInfo.handle, 'text', 'math-input-inline'); for (const wid of lineInfo.widgets) { if (wid.className === 'math-result-line') wid.clear(); } } } function refresh_widgets(cm: any, block: Block) { for (let i = block.start; i <= block.end; i++) { const line = cm.lineInfo(i); clear_math_widgets(cm, line); const full_line = line.text.split(equation_result_separator); const lineData = cm.state.mathMode.lineData[i]; // Don't bother showing the result if it has already been inserted into the text if (full_line[1]) continue; if (!lineData) continue; if (lineData.isConfig) { cm.addLineClass(i, 'wrap', 'cm-comment'); continue; } if (lineData.resultHidden) continue; if (lineData.inputHidden) cm.addLineClass(i, 'text', 'math-hidden'); else if (lineData.inline) cm.addLineClass(i, 'text', 'math-input-inline'); const marker = lineData.inputHidden ? equation_result_collapsed : equation_result_separator; const res = document.createElement('div'); const node = document.createTextNode(marker + lineData.result); res.appendChild(node); if (lineData.alignRight) res.setAttribute('class', 'math-result-right'); // handleMouseEvents gives control of mouse handling for the widget to codemirror // This is necessary to get the cursor to be placed in the right location ofter // clicking on a widget // The downside is that it breaks copying of widget text (for textareas, it never // works on contenteditable) // I'm okay with this because I want the user to be able to select a block // without accidently grabbing the result cm.addLineWidget(i, res, { className: 'math-result-line', handleMouseEvents: true }); } } // If there are lines that don't belong to a block and contain math-result-line // widgets, then we should clear them function clean_up(cm: any)
// On each change we're going to scan for function on_change(cm: any, change: any) { clean_up(cm); // Most changes are the user typing a single character // If this doesn't happen inside a math block, we shouldn't re-process // +input means the user input the text (as opposed to joplin/plugin
{ for (let i = cm.firstLine(); i < cm.lineCount(); i++) { if (!find_math(cm, i)) { const line = cm.lineInfo(i); clear_math_widgets(cm, line); } } }
identifier_body
mathMode.ts
inline: 'yes', notation: 'auto', precision: '4', align: 'left', }; function truthy(s: string) { s = s.toLowerCase(); return s.startsWith('t') || s.startsWith('y') || s === '1'; } function falsey(s: string) { s = s.toLowerCase(); return s.startsWith('f') || s.startsWith('n') || s === '0'; } // if is in a block return {start, end} // where start is the first math line of a block // and end is the close tag of the block (last line + 1) // otherwise returns false function find_block(cm: any, lineno: number): Block { if (!lineno && lineno !== 0) lineno = cm.lastLine(); let start = -1; // A line is in a block if it is wrapped in a ```math and ``` // We start at lineno - 1 to ensure that event the trailing // ``` will be treated as part of a block for (let i = lineno; i >= cm.firstLine(); i--) { const line = cm.getLine(i); // If we encounter an end of block marker // then we know we wer not in a block if (line === '```') { return null; } else if (line === '```math') { start = i + 1; break; } } if (start === -1) return null; for (let i = start; i < cm.lineCount(); i++) { const line = cm.getLine(i); if (line.indexOf('```') === 0) { if (line.trim() === '```') { return { start: start, end: i - 1 }; } return null; } } return null; } function find_inline_math(cm: any, lineno: number): Block { const line = cm.getLine(lineno); if (line.match(inline_math_regex)) { return { start: lineno, end: lineno }; } return null; } function find_math(cm: any, lineno: number): Block { const block = find_block(cm, lineno); const inline = find_inline_math(cm, lineno); // It's possible that a user may input an inline math style line into a block // and we don't want that to prevent this system from finding the block // so we check for the block first and check for inline if no block is found return block ? block : inline; } // We sometimes we will want to find all the math blocks in order // to re-process an entire note function reprocess_all(cm: any) { cm.state.mathMode.scope = {}; cm.state.mathMode.lineData = {}; let noteConfig = Object.assign({}, defaultConfig); for (let i = cm.firstLine(); i < cm.lineCount(); i++) { const to_process = find_math(cm, i); if (!to_process) continue; process_block(cm, to_process, noteConfig) // Jump to end of the block // This does nothing for inline math, and prevents duplicated // running of larger blocks i = to_process.end; } refresh_widgets(cm, { start: cm.firstLine(), end: cm.lineCount() - 1 }); } function insert_math_at(cm: any, lineno: number) { const line = cm.getLine(lineno); const result = cm.state.mathMode.lineData[lineno]; cm.replaceRange(line + equation_result_separator + result, { line: lineno, ch: 0 }, { line: lineno, ch:line.length }); } function get_line_equation(line: string): string { return line.replace(inline_math_regex, ''); } function process_block(cm: any, block: Block, noteConfig: any) { // scope is global to the note let scope = cm.state.mathMode.scope; let config = Object.assign({}, noteConfig); const math = mathjs.create(mathjs.all, { number: 'BigNumber' }); for (let i = block.start; i <= block.end; i++) { const full_line = cm.getLine(i).split(equation_result_separator); const line = full_line[0]; if (!line) continue; // This is configuration, not math // current system is fairly simplistic (maybe even ugly) // but it's small enough now that I can justify it // remember to re-evaulate this if/when things get more complex if (line.includes(':')) { const [ key, value ] = line.split(':', 2); config[key.trim()] = value.trim(); cm.state.mathMode.lineData[i] = { isConfig: true }; if (falsey(config.simplify)) { math.config({ number: 'BigNumber', precision: 64 }); } else
continue; } // Process one line let result = ''; try { const p = math.parse(get_line_equation(line)); if (falsey(config.simplify)) result = p.evaluate(scope); else result = math.simplify(p) result = math.format(result, { precision: Number(config.precision), notation: config.notation, }); if (p.name && truthy(config.verbose)) result = p.name + ': ' + result; } catch(e) { result = e.message; if (e.message.indexOf('Cannot create unit') === 0) { result = ''; } } cm.state.mathMode.lineData[i] = { result: result, inputHidden: config.hide === 'expression', resultHidden: config.hide === 'result', inline: truthy(config.inline), alignRight: config.align === 'right', } } if (truthy(config.global)) { noteConfig = Object.assign(noteConfig, config, {global: 'block'}); } } function clear_math_widgets(cm: any, lineInfo: any) { // This could potentially cause a conflict with another plugin cm.removeLineClass(lineInfo.handle, 'wrap', 'cm-comment'); if (lineInfo.widgets) { cm.removeLineClass(lineInfo.handle, 'text', 'math-hidden'); cm.removeLineClass(lineInfo.handle, 'text', 'math-input-inline'); for (const wid of lineInfo.widgets) { if (wid.className === 'math-result-line') wid.clear(); } } } function refresh_widgets(cm: any, block: Block) { for (let i = block.start; i <= block.end; i++) { const line = cm.lineInfo(i); clear_math_widgets(cm, line); const full_line = line.text.split(equation_result_separator); const lineData = cm.state.mathMode.lineData[i]; // Don't bother showing the result if it has already been inserted into the text if (full_line[1]) continue; if (!lineData) continue; if (lineData.isConfig) { cm.addLineClass(i, 'wrap', 'cm-comment'); continue; } if (lineData.resultHidden) continue; if (lineData.inputHidden) cm.addLineClass(i, 'text', 'math-hidden'); else if (lineData.inline) cm.addLineClass(i, 'text', 'math-input-inline'); const marker = lineData.inputHidden ? equation_result_collapsed : equation_result_separator; const res = document.createElement('div'); const node = document.createTextNode(marker + lineData.result); res.appendChild(node); if (lineData.alignRight) res.setAttribute('class', 'math-result-right'); // handleMouseEvents gives control of mouse handling for the widget to codemirror // This is necessary to get the cursor to be placed in the right location ofter // clicking on a widget // The downside is that it breaks copying of widget text (for textareas, it never // works on contenteditable) // I'm okay with this because I want the user to be able to select a block // without accidently grabbing the result cm.addLineWidget(i, res, { className: 'math-result-line', handleMouseEvents: true }); } } // If there are lines that don't belong to a block and contain math-result-line // widgets, then we should clear them function clean_up(cm: any) { for (let i = cm.firstLine(); i < cm.lineCount(); i++) { if (!find_math(cm, i)) { const line = cm.lineInfo(i); clear_math_widgets(cm, line); } } } // On each change we're going to scan for function on_change(cm: any, change: any) { clean_up(cm); // Most changes are the user typing a single character // If this doesn't happen inside a math block, we shouldn't re-process // +input means the user input the text (as opposed to joplin/plugin
{ math.config({ number: 'number' }); }
conditional_block
mathMode.ts
', inline: 'yes', notation: 'auto', precision: '4', align: 'left', }; function truthy(s: string) { s = s.toLowerCase(); return s.startsWith('t') || s.startsWith('y') || s === '1'; } function falsey(s: string) { s = s.toLowerCase(); return s.startsWith('f') || s.startsWith('n') || s === '0'; } // if is in a block return {start, end} // where start is the first math line of a block // and end is the close tag of the block (last line + 1) // otherwise returns false function find_block(cm: any, lineno: number): Block { if (!lineno && lineno !== 0) lineno = cm.lastLine(); let start = -1; // A line is in a block if it is wrapped in a ```math and ``` // We start at lineno - 1 to ensure that event the trailing // ``` will be treated as part of a block for (let i = lineno; i >= cm.firstLine(); i--) { const line = cm.getLine(i); // If we encounter an end of block marker // then we know we wer not in a block if (line === '```') { return null; } else if (line === '```math') { start = i + 1; break; } } if (start === -1) return null; for (let i = start; i < cm.lineCount(); i++) { const line = cm.getLine(i); if (line.indexOf('```') === 0) { if (line.trim() === '```') { return { start: start, end: i - 1 }; } return null; } } return null; } function find_inline_math(cm: any, lineno: number): Block { const line = cm.getLine(lineno); if (line.match(inline_math_regex)) { return { start: lineno, end: lineno }; } return null; } function find_math(cm: any, lineno: number): Block { const block = find_block(cm, lineno); const inline = find_inline_math(cm, lineno); // It's possible that a user may input an inline math style line into a block // and we don't want that to prevent this system from finding the block // so we check for the block first and check for inline if no block is found return block ? block : inline; } // We sometimes we will want to find all the math blocks in order // to re-process an entire note function reprocess_all(cm: any) { cm.state.mathMode.scope = {}; cm.state.mathMode.lineData = {}; let noteConfig = Object.assign({}, defaultConfig); for (let i = cm.firstLine(); i < cm.lineCount(); i++) { const to_process = find_math(cm, i); if (!to_process) continue; process_block(cm, to_process, noteConfig) // Jump to end of the block // This does nothing for inline math, and prevents duplicated // running of larger blocks i = to_process.end; } refresh_widgets(cm, { start: cm.firstLine(), end: cm.lineCount() - 1 }); } function insert_math_at(cm: any, lineno: number) { const line = cm.getLine(lineno); const result = cm.state.mathMode.lineData[lineno]; cm.replaceRange(line + equation_result_separator + result, { line: lineno, ch: 0 }, { line: lineno, ch:line.length }); } function get_line_equation(line: string): string { return line.replace(inline_math_regex, ''); } function process_block(cm: any, block: Block, noteConfig: any) { // scope is global to the note let scope = cm.state.mathMode.scope; let config = Object.assign({}, noteConfig); const math = mathjs.create(mathjs.all, { number: 'BigNumber' }); for (let i = block.start; i <= block.end; i++) { const full_line = cm.getLine(i).split(equation_result_separator); const line = full_line[0]; if (!line) continue; // This is configuration, not math // current system is fairly simplistic (maybe even ugly) // but it's small enough now that I can justify it // remember to re-evaulate this if/when things get more complex if (line.includes(':')) { const [ key, value ] = line.split(':', 2); config[key.trim()] = value.trim(); cm.state.mathMode.lineData[i] = { isConfig: true }; if (falsey(config.simplify)) { math.config({ number: 'BigNumber', precision: 64 }); } else { math.config({ number: 'number' }); } continue; } // Process one line let result = ''; try { const p = math.parse(get_line_equation(line)); if (falsey(config.simplify)) result = p.evaluate(scope); else result = math.simplify(p) result = math.format(result, { precision: Number(config.precision), notation: config.notation, }); if (p.name && truthy(config.verbose)) result = p.name + ': ' + result; } catch(e) { result = e.message; if (e.message.indexOf('Cannot create unit') === 0) { result = ''; } } cm.state.mathMode.lineData[i] = { result: result, inputHidden: config.hide === 'expression', resultHidden: config.hide === 'result', inline: truthy(config.inline), alignRight: config.align === 'right', } } if (truthy(config.global)) { noteConfig = Object.assign(noteConfig, config, {global: 'block'}); } } function clear_math_widgets(cm: any, lineInfo: any) { // This could potentially cause a conflict with another plugin cm.removeLineClass(lineInfo.handle, 'wrap', 'cm-comment'); if (lineInfo.widgets) { cm.removeLineClass(lineInfo.handle, 'text', 'math-hidden'); cm.removeLineClass(lineInfo.handle, 'text', 'math-input-inline'); for (const wid of lineInfo.widgets) { if (wid.className === 'math-result-line') wid.clear(); } } } function refresh_widgets(cm: any, block: Block) { for (let i = block.start; i <= block.end; i++) { const line = cm.lineInfo(i); clear_math_widgets(cm, line); const full_line = line.text.split(equation_result_separator); const lineData = cm.state.mathMode.lineData[i]; // Don't bother showing the result if it has already been inserted into the text if (full_line[1]) continue; if (!lineData) continue; if (lineData.isConfig) { cm.addLineClass(i, 'wrap', 'cm-comment'); continue; } if (lineData.resultHidden) continue; if (lineData.inputHidden) cm.addLineClass(i, 'text', 'math-hidden'); else if (lineData.inline) cm.addLineClass(i, 'text', 'math-input-inline'); const marker = lineData.inputHidden ? equation_result_collapsed : equation_result_separator; const res = document.createElement('div'); const node = document.createTextNode(marker + lineData.result); res.appendChild(node);
// This is necessary to get the cursor to be placed in the right location ofter // clicking on a widget // The downside is that it breaks copying of widget text (for textareas, it never // works on contenteditable) // I'm okay with this because I want the user to be able to select a block // without accidently grabbing the result cm.addLineWidget(i, res, { className: 'math-result-line', handleMouseEvents: true }); } } // If there are lines that don't belong to a block and contain math-result-line // widgets, then we should clear them function clean_up(cm: any) { for (let i = cm.firstLine(); i < cm.lineCount(); i++) { if (!find_math(cm, i)) { const line = cm.lineInfo(i); clear_math_widgets(cm, line); } } } // On each change we're going to scan for function on_change(cm: any, change: any) { clean_up(cm); // Most changes are the user typing a single character // If this doesn't happen inside a math block, we shouldn't re-process // +input means the user input the text (as opposed to joplin/plugin)
if (lineData.alignRight) res.setAttribute('class', 'math-result-right'); // handleMouseEvents gives control of mouse handling for the widget to codemirror
random_line_split
activity.go
(float64(from.Y)*pixelToTuxelScaleY), input.TouchCoord(float64(to.X)*pixelToTuxelScaleX), input.TouchCoord(float64(to.Y)*pixelToTuxelScaleY), t); err != nil { return errors.Wrap(err, "failed to start the swipe gesture") } if err := testing.Sleep(ctx, delayToPreventGesture); err != nil { return errors.Wrap(err, "timeout while sleeping") } return nil } // initTouchscreenLazily lazily initializes the touchscreen. // Touchscreen initialization is not needed, unless swipe() is called. func (ac *Activity) initTouchscreenLazily(ctx context.Context) error { if ac.tew != nil { return nil } var err error ac.tew, err = input.Touchscreen(ctx) if err != nil { return errors.Wrap(err, "could not open touchscreen device") } return nil } // getTasksInfo returns a list of all the active ARC tasks records. func (ac *Activity) getTasksInfo(ctx context.Context) (tasks []taskInfo, err error) { // TODO(ricardoq): parse the dumpsys protobuf output instead. // As it is now, it gets complex and error-prone to parse each ActivityRecord. cmd := ac.a.Command(ctx, "dumpsys", "activity", "activities") out, err := cmd.Output() if err != nil { return nil, errors.Wrap(err, "could not get 'dumpsys activity activities' output") } output := string(out) // Looking for: // Stack #2: type=standard mode=freeform // isSleeping=false // mBounds=Rect(0, 0 - 0, 0) // Task id #5 // mBounds=Rect(1139, 359 - 1860, 1640) // mMinWidth=-1 // mMinHeight=-1 // mLastNonFullscreenBounds=Rect(1139, 359 - 1860, 1640) // * TaskRecordArc{TaskRecordArc{TaskRecord{54ef88b #5 A=com.android.settings.root U=0 StackId=2 sz=1}, WindowState{freeform restore-bounds=Rect(1139, 359 - 1860, 1640)}} , WindowState{freeform restore-bounds=Rect(1139, 359 - 1860, 1640)}} // userId=0 effectiveUid=1000 mCallingUid=1000 mUserSetupComplete=true mCallingPackage=org.chromium.arc.applauncher // affinity=com.android.settings.root // intent={act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10210000 cmp=com.android.settings/.Settings} // origActivity=com.android.settings/.Settings // realActivity=com.android.settings/.Settings // autoRemoveRecents=false isPersistable=true numFullscreen=1 activityType=1 // rootWasReset=true mNeverRelinquishIdentity=true mReuseTask=false mLockTaskAuth=LOCK_TASK_AUTH_PINNABLE // Activities=[ActivityRecord{64b5e83 u0 com.android.settings/.Settings t5}] // askedCompatMode=false inRecents=true isAvailable=true // mRootProcess=ProcessRecord{8dc5d68 5809:com.android.settings/1000} // stackId=2 // hasBeenVisible=true mResizeMode=RESIZE_MODE_RESIZEABLE_VIA_SDK_VERSION mSupportsPictureInPicture=false isResizeable=true lastActiveTime=1470240 (inactive for 4s) // Arc Window State: // mWindowMode=5 mRestoreBounds=Rect(1139, 359 - 1860, 1640) taskWindowState=0 // * Hist #2: ActivityRecord{2f9c16c u0 com.android.settings/.SubSettings t8} // packageName=com.android.settings processName=com.android.settings // [...] Abbreviated to save space // state=RESUMED stopped=false delayedResume=false finishing=false // keysPaused=false inHistory=true visible=true sleeping=false idle=true mStartingWindowState=STARTING_WINDOW_NOT_SHOWN regStr := `(?m)` + // Enable multiline. `^\s+Task id #(\d+)` + // Grab task id (group 1). `\s+mBounds=Rect\((-?\d+),\s*(-?\d+)\s*-\s*(\d+),\s*(\d+)\)` + // Grab bounds (groups 2-5). `(?:\n.*?)*` + // Non-greedy skip lines. `.*TaskRecord{.*StackId=(\d+)\s+sz=(\d*)}.*$` + // Grab stack Id (group 6) and stack size (group 7). `(?:\n.*?)*` + // Non-greedy skip lines. `\s+realActivity=(.*)\/(.*)` + // Grab package name (group 8) and activity name (group 9). `(?:\n.*?)*` + // Non-greedy skip lines. `.*\s+isResizeable=(\S+).*$` + // Grab window resizeablitiy (group 10). `(?:\n.*?)*` + // Non-greedy skip lines. `\s+mWindowMode=\d+.*taskWindowState=(\d+).*$` + // Grab window state (group 11). `(?:\n.*?)*` + // Non-greedy skip lines. `\s+ActivityRecord{.*` + // At least one ActivityRecord must be present. `(?:\n.*?)*` + // Non-greedy skip lines. `.*\s+idle=(\S+)` // Idle state (group 12). re := regexp.MustCompile(regStr) matches := re.FindAllStringSubmatch(string(output), -1) // At least it must match one activity. Home and/or Dummy activities must be present. if len(matches) == 0 { testing.ContextLog(ctx, "Using regexp: ", regStr) testing.ContextLog(ctx, "Output for regexp: ", string(output)) return nil, errors.New("could not match any activity; regexp outdated perhaps?") } for _, groups := range matches { var t taskInfo var windowState int t.bounds, err = parseBounds(groups[2:6]) if err != nil { return nil, err } for _, dst := range []struct { v *int group int }{ {&t.id, 1}, {&t.stackID, 6}, {&t.stackSize, 7}, {&windowState, 11}, } { *dst.v, err = strconv.Atoi(groups[dst.group]) if err != nil { return nil, errors.Wrapf(err, "could not parse %q", groups[dst.group]) } } t.pkgName = groups[8] t.activityName = groups[9] t.resizable, err = strconv.ParseBool(groups[10]) if err != nil { return nil, err } t.idle, err = strconv.ParseBool(groups[12]) if err != nil { return nil, err } t.windowState = WindowState(windowState) tasks = append(tasks, t) } return tasks, nil } // getTaskInfo returns the task record associated for the current activity. func (ac *Activity) getTaskInfo(ctx context.Context) (taskInfo, error) { tasks, err := ac.getTasksInfo(ctx) if err != nil { return taskInfo{}, errors.Wrap(err, "could not get task info") } for _, task := range tasks { if task.pkgName == ac.pkgName && task.activityName == ac.activityName { return task, nil } } return taskInfo{}, errors.Errorf("could not find task info for %s/%s", ac.pkgName, ac.activityName) } // Helper functions. // parseBounds returns a Rect by parsing a slice of 4 strings. // Each string represents the left, top, right and bottom values, in that order. func parseBounds(s []string) (bounds Rect, err error) { if len(s) != 4 { return Rect{}, errors.Errorf("expecting a slice of length 4, got %d", len(s)) } var right, bottom int for i, dst := range []*int{&bounds.Left, &bounds.Top, &right, &bottom}
{ *dst, err = strconv.Atoi(s[i]) if err != nil { return Rect{}, errors.Wrapf(err, "could not parse %q", s[i]) } }
conditional_block
activity.go
json:"width"` Height int `json:"height"` } // String returns the string representation of Rect. func (r *Rect) String() string { return fmt.Sprintf("(%d, %d) - (%d x %d)", r.Left, r.Top, r.Width, r.Height) } // NewActivity returns a new Activity instance. // The caller is responsible for closing a. // Returned Activity instance must be closed when the test is finished. func NewActivity(a *ARC, pkgName, activityName string) (*Activity, error) { disp, err := NewDisplay(a, DefaultDisplayID) if err != nil { return nil, errors.Wrap(err, "could not create a new Display") } return &Activity{ a: a, pkgName: pkgName, activityName: activityName, disp: disp, }, nil } // Start starts the activity by invoking "am start". func (ac *Activity) Start(ctx context.Context) error { cmd := ac.a.Command(ctx, "am", "start", "-W", ac.pkgName+"/"+ac.activityName) output, err := cmd.Output() if err != nil { return errors.Wrap(err, "failed to start activity") } // "adb shell" doesn't distinguish between a failed/successful run. For that we have to parse the output. // Looking for: // Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example.name/.ActvityName } // Error type 3 // Error: Activity class {com.example.name/com.example.name.ActvityName} does not exist. re := regexp.MustCompile(`(?m)^Error:\s*(.*)$`) groups := re.FindStringSubmatch(string(output)) if len(groups) == 2 { testing.ContextLog(ctx, "Failed to start activity: ", groups[1]) return errors.New("failed to start activity") } return nil } // Stop stops the activity by invoking "am force-stop" with the package name. // If there are multiple activities that belong to the same package name, all of // them will be stopped. func (ac *Activity) Stop(ctx context.Context) error { // "adb shell am force-stop" has no output. So the error from Run() is returned. return ac.a.Command(ctx, "am", "force-stop", ac.pkgName).Run() } // WindowBounds returns the window bounding box of the activity in pixels. // The caption bounds, in case it is present, is included as part of the window bounds. // This is the size that the activity thinks it has, although the surface size could be smaller. // See: SurfaceBounds func (ac *Activity) WindowBounds(ctx context.Context) (Rect, error) { t, err := ac.getTaskInfo(ctx) if err != nil { return Rect{}, errors.Wrap(err, "failed to get task info") } // Fullscreen and maximized windows already include the caption height. PiP windows don't have caption. if t.windowState == WindowStateFullscreen || t.windowState == WindowStateMaximized || t.windowState == WindowStatePIP { return t.bounds, nil } // But the rest must have the caption height added to their bounds. captionHeight, err := ac.disp.CaptionHeight(ctx) if err != nil { return Rect{}, errors.Wrap(err, "failed to get caption height") } t.bounds.Top -= captionHeight t.bounds.Height += captionHeight return t.bounds, nil } // SurfaceBounds returns the surface bounds in pixels. A surface represents the buffer used to store // the window content. This is the buffer used by SurfaceFlinger and Wayland. // The surface bounds might be smaller than the window bounds since the surface does not // include the caption. // And does not include the shelf size if the activity is fullscreen/maximized and the shelf is in "always show" mode. // See: WindowBounds func (ac *Activity) SurfaceBounds(ctx context.Context) (Rect, error) { cmd := ac.a.Command(ctx, "dumpsys", "window", "windows") output, err := cmd.Output() if err != nil { return Rect{}, errors.Wrap(err, "failed to launch dumpsys") } // Looking for: // Window #0 Window{a486f07 u0 com.android.settings/com.android.settings.Settings}: // mDisplayId=0 stackId=2 mSession=Session{dd34b88 2586:1000} mClient=android.os.BinderProxy@705e146 // mHasSurface=true isReadyForDisplay()=true mWindowRemovalAllowed=false // [...many other properties...] // mFrame=[0,0][1536,1936] last=[0,0][1536,1936] // We are interested in "mFrame=" regStr := `(?m)` + // Enable multiline. `^\s*Window #\d+ Window{\S+ \S+ ` + regexp.QuoteMeta(ac.pkgName+"/"+ac.pkgName+ac.activityName) + `}:$` + // Match our activity `(?:\n.*?)*` + // Skip entire lines with a non-greedy search... `^\s*mFrame=\[(\d+),(\d+)\]\[(\d+),(\d+)\]` // ...until we match the first mFrame= re := regexp.MustCompile(regStr) groups := re.FindStringSubmatch(string(output)) if len(groups) != 5 { testing.ContextLog(ctx, string(output)) return Rect{}, errors.New("failed to parse dumpsys output; activity not running perhaps?") } bounds, err := parseBounds(groups[1:5]) if err != nil { return Rect{}, err } return bounds, nil } // Close closes the resources associated with the Activity instance. // Calling Close() does not stop the activity. func (ac *Activity) Close() { ac.disp.Close() if ac.tew != nil { ac.tew.Close() } } // MoveWindow moves the activity's window to a new location. // to represents the coordinates (top-left) for the new position, in pixels. // t represents the duration of the movement. // MoveWindow only works with WindowStateNormal and WindowStatePIP windows. Will fail otherwise. // MoveWindow performs the movement by injecting Touch events in the kernel. // If the device does not have a touchscreen, it will fail. func (ac *Activity)
(ctx context.Context, to Point, t time.Duration) error { task, err := ac.getTaskInfo(ctx) if err != nil { return errors.Wrap(err, "could not get task info") } if task.windowState != WindowStateNormal && task.windowState != WindowStatePIP { return errors.Errorf("cannot move window in state %d", int(task.windowState)) } bounds, err := ac.WindowBounds(ctx) if err != nil { return errors.Wrap(err, "could not get activity bounds") } var from Point captionHeight, err := ac.disp.CaptionHeight(ctx) if err != nil { return errors.Wrap(err, "could not get caption height") } halfWidth := bounds.Width / 2 from.X = bounds.Left + halfWidth to.X += halfWidth if task.windowState == WindowStatePIP { // PiP windows are dragged from its center halfHeight := bounds.Height / 2 from.Y = bounds.Top + halfHeight to.Y += halfHeight } else { // Normal-state windows are dragged from its caption from.Y = bounds.Top + captionHeight/2 to.Y += captionHeight / 2 } return ac.swipe(ctx, from, to, t) } // ResizeWindow resizes the activity's window. // border represents from where the resize should start. // to represents the coordinates for for the new border's position, in pixels. // t represents the duration of the resize. // ResizeWindow only works with WindowStateNormal and WindowStatePIP windows. Will fail otherwise. // For PiP windows, they must have the PiP Menu Activity displayed. Will fail otherwise. // ResizeWindow performs the resizing by injecting Touch events in the kernel. // If the device does not have a touchscreen, it will fail. func (ac *Activity) ResizeWindow(ctx context.Context, border BorderType, to Point, t time.Duration) error { task, err := ac.getTaskInfo(ctx) if err != nil { return errors.Wrap(err, "could not get task info") } if task.windowState != WindowStateNormal && task.windowState != WindowStatePIP { return errors.Errorf("cannot move window in state %d", int(task.windowState)) } // Default value: center of window. bounds, err := ac.WindowBounds(ctx) if err != nil { return errors.Wrap(err, "could not get activity bounds") } src := Point{ bounds.Left + bounds.Width/2, bounds.Top + bounds.Height/2, } borderOffset := borderOffsetForNormal if task.windowState == WindowStatePIP { borderOffset = borderOffsetForPIP } // Top & Bottom are exclusive. if border&BorderTop != 0 { src.Y = bounds.Top - borderOffset } else if border&BorderBottom != 0 { src.Y = bounds.Top + bounds.Height + borderOffset
MoveWindow
identifier_name
activity.go
.Wrap(err, "failed to launch dumpsys") } // Looking for: // Window #0 Window{a486f07 u0 com.android.settings/com.android.settings.Settings}: // mDisplayId=0 stackId=2 mSession=Session{dd34b88 2586:1000} mClient=android.os.BinderProxy@705e146 // mHasSurface=true isReadyForDisplay()=true mWindowRemovalAllowed=false // [...many other properties...] // mFrame=[0,0][1536,1936] last=[0,0][1536,1936] // We are interested in "mFrame=" regStr := `(?m)` + // Enable multiline. `^\s*Window #\d+ Window{\S+ \S+ ` + regexp.QuoteMeta(ac.pkgName+"/"+ac.pkgName+ac.activityName) + `}:$` + // Match our activity `(?:\n.*?)*` + // Skip entire lines with a non-greedy search... `^\s*mFrame=\[(\d+),(\d+)\]\[(\d+),(\d+)\]` // ...until we match the first mFrame= re := regexp.MustCompile(regStr) groups := re.FindStringSubmatch(string(output)) if len(groups) != 5 { testing.ContextLog(ctx, string(output)) return Rect{}, errors.New("failed to parse dumpsys output; activity not running perhaps?") } bounds, err := parseBounds(groups[1:5]) if err != nil { return Rect{}, err } return bounds, nil } // Close closes the resources associated with the Activity instance. // Calling Close() does not stop the activity. func (ac *Activity) Close() { ac.disp.Close() if ac.tew != nil { ac.tew.Close() } } // MoveWindow moves the activity's window to a new location. // to represents the coordinates (top-left) for the new position, in pixels. // t represents the duration of the movement. // MoveWindow only works with WindowStateNormal and WindowStatePIP windows. Will fail otherwise. // MoveWindow performs the movement by injecting Touch events in the kernel. // If the device does not have a touchscreen, it will fail. func (ac *Activity) MoveWindow(ctx context.Context, to Point, t time.Duration) error { task, err := ac.getTaskInfo(ctx) if err != nil { return errors.Wrap(err, "could not get task info") } if task.windowState != WindowStateNormal && task.windowState != WindowStatePIP { return errors.Errorf("cannot move window in state %d", int(task.windowState)) } bounds, err := ac.WindowBounds(ctx) if err != nil { return errors.Wrap(err, "could not get activity bounds") } var from Point captionHeight, err := ac.disp.CaptionHeight(ctx) if err != nil { return errors.Wrap(err, "could not get caption height") } halfWidth := bounds.Width / 2 from.X = bounds.Left + halfWidth to.X += halfWidth if task.windowState == WindowStatePIP { // PiP windows are dragged from its center halfHeight := bounds.Height / 2 from.Y = bounds.Top + halfHeight to.Y += halfHeight } else { // Normal-state windows are dragged from its caption from.Y = bounds.Top + captionHeight/2 to.Y += captionHeight / 2 } return ac.swipe(ctx, from, to, t) } // ResizeWindow resizes the activity's window. // border represents from where the resize should start. // to represents the coordinates for for the new border's position, in pixels. // t represents the duration of the resize. // ResizeWindow only works with WindowStateNormal and WindowStatePIP windows. Will fail otherwise. // For PiP windows, they must have the PiP Menu Activity displayed. Will fail otherwise. // ResizeWindow performs the resizing by injecting Touch events in the kernel. // If the device does not have a touchscreen, it will fail. func (ac *Activity) ResizeWindow(ctx context.Context, border BorderType, to Point, t time.Duration) error { task, err := ac.getTaskInfo(ctx) if err != nil { return errors.Wrap(err, "could not get task info") } if task.windowState != WindowStateNormal && task.windowState != WindowStatePIP { return errors.Errorf("cannot move window in state %d", int(task.windowState)) } // Default value: center of window. bounds, err := ac.WindowBounds(ctx) if err != nil { return errors.Wrap(err, "could not get activity bounds") } src := Point{ bounds.Left + bounds.Width/2, bounds.Top + bounds.Height/2, } borderOffset := borderOffsetForNormal if task.windowState == WindowStatePIP { borderOffset = borderOffsetForPIP } // Top & Bottom are exclusive. if border&BorderTop != 0 { src.Y = bounds.Top - borderOffset } else if border&BorderBottom != 0 { src.Y = bounds.Top + bounds.Height + borderOffset } // Left & Right are exclusive. if border&BorderLeft != 0 { src.X = bounds.Left - borderOffset } else if border&BorderRight != 0 { src.X = bounds.Left + bounds.Width + borderOffset } // After updating src, clamp it to valid display bounds. ds, err := ac.disp.Size(ctx) if err != nil { return errors.Wrap(err, "could not get display size") } src.X = int(math.Max(0, math.Min(float64(ds.W-1), float64(src.X)))) src.Y = int(math.Max(0, math.Min(float64(ds.H-1), float64(src.Y)))) return ac.swipe(ctx, src, to, t) } // SetWindowState sets the window state. Note this method is async, so ensure to call WaitForIdle after this. // Supported states: WindowStateNormal, WindowStateMaximized, WindowStateFullscreen, WindowStateMinimized func (ac *Activity) SetWindowState(ctx context.Context, state WindowState) error { t, err := ac.getTaskInfo(ctx) if err != nil { return errors.Wrap(err, "could not get task info") } switch state { case WindowStateNormal, WindowStateMaximized, WindowStateFullscreen, WindowStateMinimized: default: return errors.Errorf("unsupported window state %d", state) } if err = ac.a.Command(ctx, "am", "task", "set-winstate", strconv.Itoa(t.id), strconv.Itoa(int(state))).Run(); err != nil { return errors.Wrap(err, "could not execute 'am task set-winstate'") } return nil } // GetWindowState returns the window state. func (ac *Activity) GetWindowState(ctx context.Context) (WindowState, error) { task, err := ac.getTaskInfo(ctx) if err != nil { return WindowStateNormal, errors.Wrap(err, "could not get task info") } return task.windowState, nil } // WaitForIdle returns whether the activity is idle. // If more than one activity belonging to the same task are present, it returns the idle state // of the most recent one. func (ac *Activity) WaitForIdle(ctx context.Context, timeout time.Duration) error { return testing.Poll(ctx, func(ctx context.Context) error { task, err := ac.getTaskInfo(ctx) if err != nil { return err } if !task.idle { return errors.New("activity is not idle yet") } return nil }, &testing.PollOptions{Timeout: timeout}) } // PackageName returns the activity package name. func (ac *Activity) PackageName() string { return ac.pkgName } // Resizable returns the window resizability. func (ac *Activity) Resizable(ctx context.Context) (bool, error) { task, err := ac.getTaskInfo(ctx) if err != nil { return false, errors.Wrap(err, "could not get task info") } return task.resizable, nil } // swipe injects touch events in a straight line. The line is defined by from and to, in pixels. // t represents the duration of the swipe. // The last touch event will be held in its position for a few ms to prevent triggering "minimize" or similar gestures. func (ac *Activity) swipe(ctx context.Context, from, to Point, t time.Duration) error
{ if err := ac.initTouchscreenLazily(ctx); err != nil { return errors.Wrap(err, "could not initialize touchscreen device") } stw, err := ac.tew.NewSingleTouchWriter() if err != nil { return errors.Wrap(err, "could not get a new TouchEventWriter") } defer stw.Close() // TODO(ricardoq): Fetch stableSize directly from Chrome OS, and not from Android. // It is not clear whether Android can have a display bounds different than Chrome OS. // Using "non-rotated" display bounds for calculating the scale factor since // touchscreen bounds are also "non-rotated". dispSize, err := ac.disp.stableSize(ctx) if err != nil { return errors.Wrap(err, "could not get stable bounds for display") }
identifier_body
activity.go
json:"width"` Height int `json:"height"` } // String returns the string representation of Rect. func (r *Rect) String() string { return fmt.Sprintf("(%d, %d) - (%d x %d)", r.Left, r.Top, r.Width, r.Height) } // NewActivity returns a new Activity instance. // The caller is responsible for closing a. // Returned Activity instance must be closed when the test is finished. func NewActivity(a *ARC, pkgName, activityName string) (*Activity, error) { disp, err := NewDisplay(a, DefaultDisplayID) if err != nil { return nil, errors.Wrap(err, "could not create a new Display") } return &Activity{ a: a, pkgName: pkgName, activityName: activityName, disp: disp, }, nil } // Start starts the activity by invoking "am start". func (ac *Activity) Start(ctx context.Context) error { cmd := ac.a.Command(ctx, "am", "start", "-W", ac.pkgName+"/"+ac.activityName) output, err := cmd.Output() if err != nil { return errors.Wrap(err, "failed to start activity") } // "adb shell" doesn't distinguish between a failed/successful run. For that we have to parse the output. // Looking for: // Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.example.name/.ActvityName } // Error type 3 // Error: Activity class {com.example.name/com.example.name.ActvityName} does not exist. re := regexp.MustCompile(`(?m)^Error:\s*(.*)$`) groups := re.FindStringSubmatch(string(output)) if len(groups) == 2 { testing.ContextLog(ctx, "Failed to start activity: ", groups[1]) return errors.New("failed to start activity") } return nil } // Stop stops the activity by invoking "am force-stop" with the package name. // If there are multiple activities that belong to the same package name, all of // them will be stopped. func (ac *Activity) Stop(ctx context.Context) error { // "adb shell am force-stop" has no output. So the error from Run() is returned. return ac.a.Command(ctx, "am", "force-stop", ac.pkgName).Run() } // WindowBounds returns the window bounding box of the activity in pixels. // The caption bounds, in case it is present, is included as part of the window bounds. // This is the size that the activity thinks it has, although the surface size could be smaller. // See: SurfaceBounds func (ac *Activity) WindowBounds(ctx context.Context) (Rect, error) { t, err := ac.getTaskInfo(ctx) if err != nil { return Rect{}, errors.Wrap(err, "failed to get task info") } // Fullscreen and maximized windows already include the caption height. PiP windows don't have caption. if t.windowState == WindowStateFullscreen || t.windowState == WindowStateMaximized || t.windowState == WindowStatePIP { return t.bounds, nil } // But the rest must have the caption height added to their bounds. captionHeight, err := ac.disp.CaptionHeight(ctx) if err != nil { return Rect{}, errors.Wrap(err, "failed to get caption height") } t.bounds.Top -= captionHeight t.bounds.Height += captionHeight return t.bounds, nil } // SurfaceBounds returns the surface bounds in pixels. A surface represents the buffer used to store // the window content. This is the buffer used by SurfaceFlinger and Wayland. // The surface bounds might be smaller than the window bounds since the surface does not // include the caption. // And does not include the shelf size if the activity is fullscreen/maximized and the shelf is in "always show" mode. // See: WindowBounds func (ac *Activity) SurfaceBounds(ctx context.Context) (Rect, error) { cmd := ac.a.Command(ctx, "dumpsys", "window", "windows") output, err := cmd.Output() if err != nil { return Rect{}, errors.Wrap(err, "failed to launch dumpsys") } // Looking for: // Window #0 Window{a486f07 u0 com.android.settings/com.android.settings.Settings}: // mDisplayId=0 stackId=2 mSession=Session{dd34b88 2586:1000} mClient=android.os.BinderProxy@705e146 // mHasSurface=true isReadyForDisplay()=true mWindowRemovalAllowed=false // [...many other properties...] // mFrame=[0,0][1536,1936] last=[0,0][1536,1936] // We are interested in "mFrame=" regStr := `(?m)` + // Enable multiline. `^\s*Window #\d+ Window{\S+ \S+ ` + regexp.QuoteMeta(ac.pkgName+"/"+ac.pkgName+ac.activityName) + `}:$` + // Match our activity `(?:\n.*?)*` + // Skip entire lines with a non-greedy search... `^\s*mFrame=\[(\d+),(\d+)\]\[(\d+),(\d+)\]` // ...until we match the first mFrame= re := regexp.MustCompile(regStr) groups := re.FindStringSubmatch(string(output)) if len(groups) != 5 { testing.ContextLog(ctx, string(output)) return Rect{}, errors.New("failed to parse dumpsys output; activity not running perhaps?") } bounds, err := parseBounds(groups[1:5]) if err != nil { return Rect{}, err } return bounds, nil } // Close closes the resources associated with the Activity instance. // Calling Close() does not stop the activity. func (ac *Activity) Close() { ac.disp.Close() if ac.tew != nil { ac.tew.Close() } } // MoveWindow moves the activity's window to a new location. // to represents the coordinates (top-left) for the new position, in pixels. // t represents the duration of the movement. // MoveWindow only works with WindowStateNormal and WindowStatePIP windows. Will fail otherwise. // MoveWindow performs the movement by injecting Touch events in the kernel. // If the device does not have a touchscreen, it will fail. func (ac *Activity) MoveWindow(ctx context.Context, to Point, t time.Duration) error { task, err := ac.getTaskInfo(ctx) if err != nil { return errors.Wrap(err, "could not get task info") } if task.windowState != WindowStateNormal && task.windowState != WindowStatePIP { return errors.Errorf("cannot move window in state %d", int(task.windowState)) } bounds, err := ac.WindowBounds(ctx) if err != nil { return errors.Wrap(err, "could not get activity bounds") } var from Point captionHeight, err := ac.disp.CaptionHeight(ctx) if err != nil { return errors.Wrap(err, "could not get caption height") } halfWidth := bounds.Width / 2 from.X = bounds.Left + halfWidth to.X += halfWidth if task.windowState == WindowStatePIP { // PiP windows are dragged from its center halfHeight := bounds.Height / 2 from.Y = bounds.Top + halfHeight to.Y += halfHeight } else { // Normal-state windows are dragged from its caption from.Y = bounds.Top + captionHeight/2 to.Y += captionHeight / 2 }
// ResizeWindow resizes the activity's window. // border represents from where the resize should start. // to represents the coordinates for for the new border's position, in pixels. // t represents the duration of the resize. // ResizeWindow only works with WindowStateNormal and WindowStatePIP windows. Will fail otherwise. // For PiP windows, they must have the PiP Menu Activity displayed. Will fail otherwise. // ResizeWindow performs the resizing by injecting Touch events in the kernel. // If the device does not have a touchscreen, it will fail. func (ac *Activity) ResizeWindow(ctx context.Context, border BorderType, to Point, t time.Duration) error { task, err := ac.getTaskInfo(ctx) if err != nil { return errors.Wrap(err, "could not get task info") } if task.windowState != WindowStateNormal && task.windowState != WindowStatePIP { return errors.Errorf("cannot move window in state %d", int(task.windowState)) } // Default value: center of window. bounds, err := ac.WindowBounds(ctx) if err != nil { return errors.Wrap(err, "could not get activity bounds") } src := Point{ bounds.Left + bounds.Width/2, bounds.Top + bounds.Height/2, } borderOffset := borderOffsetForNormal if task.windowState == WindowStatePIP { borderOffset = borderOffsetForPIP } // Top & Bottom are exclusive. if border&BorderTop != 0 { src.Y = bounds.Top - borderOffset } else if border&BorderBottom != 0 { src.Y = bounds.Top + bounds.Height + borderOffset
return ac.swipe(ctx, from, to, t) }
random_line_split
planner.go
.Collection } // InternalPlannerParamsOption is an option that can be passed to // NewInternalPlanner. type InternalPlannerParamsOption func(*internalPlannerParams) // WithDescCollection configures the planner with the provided collection // instead of the default (creating a new one from scratch). func WithDescCollection(collection *descs.Collection) InternalPlannerParamsOption { return func(params *internalPlannerParams) { params.collection = collection } } // NewInternalPlanner is an exported version of newInternalPlanner. It // returns an interface{} so it can be used outside of the sql package. func NewInternalPlanner( opName string, txn *kv.Txn, user security.SQLUsername, memMetrics *MemoryMetrics, execCfg *ExecutorConfig, sessionData sessiondatapb.SessionData, opts ...InternalPlannerParamsOption, ) (interface{}, func()) { return newInternalPlanner(opName, txn, user, memMetrics, execCfg, sessionData, opts...) } // newInternalPlanner creates a new planner instance for internal usage. This // planner is not associated with a sql session. // // Since it can't be reset, the planner can be used only for planning a single // statement. // // Returns a cleanup function that must be called once the caller is done with // the planner. func newInternalPlanner( opName string, txn *kv.Txn, user security.SQLUsername, memMetrics *MemoryMetrics, execCfg *ExecutorConfig, sessionData sessiondatapb.SessionData, opts ...InternalPlannerParamsOption, ) (*planner, func()) { // Default parameters which may be override by the supplied options. params := &internalPlannerParams{ // The table collection used by the internal planner does not rely on the // deprecatedDatabaseCache and there are no subscribers to the // deprecatedDatabaseCache, so we can leave it uninitialized. // Furthermore, we're not concerned about the efficiency of querying tables // with user-defined types, hence the nil hydratedTables. collection: descs.NewCollection(execCfg.Settings, execCfg.LeaseManager, nil /* hydratedTables */), } for _, opt := range opts { opt(params) } // We need a context that outlives all the uses of the planner (since the // planner captures it in the EvalCtx, and so does the cleanup function that // we're going to return. We just create one here instead of asking the caller // for a ctx with this property. This is really ugly, but the alternative of // asking the caller for one is hard to explain. What we need is better and // separate interfaces for planning and running plans, which could take // suitable contexts. ctx := logtags.AddTag(context.Background(), opName, "") sd := &sessiondata.SessionData{ SessionData: sessionData, SearchPath: sessiondata.DefaultSearchPathForUser(user), SequenceState: sessiondata.NewSequenceState(), Location: time.UTC, } sd.SessionData.Database = "system" sd.SessionData.UserProto = user.EncodeProto() dataMutator := &sessionDataMutator{ data: sd, defaults: SessionDefaults(map[string]string{ "application_name": "crdb-internal", "database": "system", }), settings: execCfg.Settings, paramStatusUpdater: &noopParamStatusUpdater{}, setCurTxnReadOnly: func(bool) {}, } var ts time.Time if txn != nil { readTimestamp := txn.ReadTimestamp() if readTimestamp.IsEmpty() { panic("makeInternalPlanner called with a transaction without timestamps") } ts = readTimestamp.GoTime() } p := &planner{execCfg: execCfg, alloc: &rowenc.DatumAlloc{}} p.txn = txn p.stmt = Statement{} p.cancelChecker = cancelchecker.NewCancelChecker(ctx) p.isInternalPlanner = true p.semaCtx = tree.MakeSemaContext() p.semaCtx.SearchPath = sd.SearchPath p.semaCtx.TypeResolver = p plannerMon := mon.NewUnlimitedMonitor(ctx, fmt.Sprintf("internal-planner.%s.%s", user, opName), mon.MemoryResource, memMetrics.CurBytesCount, memMetrics.MaxBytesHist, noteworthyInternalMemoryUsageBytes, execCfg.Settings) p.extendedEvalCtx = internalExtendedEvalCtx( ctx, sd, dataMutator, params.collection, txn, ts, ts, execCfg, plannerMon, ) p.extendedEvalCtx.Planner = p p.extendedEvalCtx.PrivilegedAccessor = p p.extendedEvalCtx.SessionAccessor = p p.extendedEvalCtx.ClientNoticeSender = p p.extendedEvalCtx.Sequence = p p.extendedEvalCtx.Tenant = p p.extendedEvalCtx.JoinTokenCreator = p p.extendedEvalCtx.ClusterID = execCfg.ClusterID() p.extendedEvalCtx.ClusterName = execCfg.RPCContext.ClusterName() p.extendedEvalCtx.NodeID = execCfg.NodeID p.extendedEvalCtx.Locality = execCfg.Locality p.sessionDataMutator = dataMutator p.autoCommit = false p.extendedEvalCtx.MemMetrics = memMetrics p.extendedEvalCtx.ExecCfg = execCfg p.extendedEvalCtx.Placeholders = &p.semaCtx.Placeholders p.extendedEvalCtx.Annotations = &p.semaCtx.Annotations p.extendedEvalCtx.Descs = params.collection p.queryCacheSession.Init() p.optPlanningCtx.init(p) return p, func() { // Note that we capture ctx here. This is only valid as long as we create // the context as explained at the top of the method. // The collection will accumulate descriptors read during planning as well // as type descriptors read during execution on the local node. Many users // of the internal planner do set the `skipCache` flag on the resolver but // this is not respected by type resolution underneath execution. That // subtle details means that the type descriptor used by execution may be // stale, but that must be okay. Correctness concerns aside, we must release // the leases to ensure that we don't leak a descriptor lease. p.Descriptors().ReleaseAll(ctx) // Stop the memory monitor. plannerMon.Stop(ctx) } } // internalExtendedEvalCtx creates an evaluation context for an "internal // planner". Since the eval context is supposed to be tied to a session and // there's no session to speak of here, different fields are filled in here to // keep the tests using the internal planner passing. func internalExtendedEvalCtx( ctx context.Context, sd *sessiondata.SessionData, dataMutator *sessionDataMutator, tables *descs.Collection, txn *kv.Txn, txnTimestamp time.Time, stmtTimestamp time.Time, execCfg *ExecutorConfig, plannerMon *mon.BytesMonitor, ) extendedEvalContext { evalContextTestingKnobs := execCfg.EvalContextTestingKnobs var sqlStatsResetter tree.SQLStatsResetter if execCfg.InternalExecutor != nil { sqlStatsResetter = execCfg.InternalExecutor.s } return extendedEvalContext{ EvalContext: tree.EvalContext{ Txn: txn, SessionData: sd, TxnReadOnly: false, TxnImplicit: true, Settings: execCfg.Settings, Codec: execCfg.Codec, Context: ctx, Mon: plannerMon, TestingKnobs: evalContextTestingKnobs, StmtTimestamp: stmtTimestamp, TxnTimestamp: txnTimestamp, InternalExecutor: execCfg.InternalExecutor, SQLStatsResetter: sqlStatsResetter, }, SessionMutator: dataMutator, VirtualSchemas: execCfg.VirtualSchemas, Tracing: &SessionTracing{}, NodesStatusServer: execCfg.NodesStatusServer, Descs: tables, ExecCfg: execCfg, schemaAccessors: newSchemaInterface(tables, execCfg.VirtualSchemas), DistSQLPlanner: execCfg.DistSQLPlanner, } } // LogicalSchemaAccessor is part of the resolver.SchemaResolver interface. func (p *planner) LogicalSchemaAccessor() catalog.Accessor { return p.extendedEvalCtx.schemaAccessors.logical } // SemaCtx provides access to the planner's SemaCtx. func (p *planner) SemaCtx() *tree.SemaContext { return &p.semaCtx } // Note: if the context will be modified, use ExtendedEvalContextCopy instead. func (p *planner) ExtendedEvalContext() *extendedEvalContext { return &p.extendedEvalCtx } func (p *planner) ExtendedEvalContextCopy() *extendedEvalContext { return p.extendedEvalCtx.copy() } // CurrentDatabase is part of the resolver.SchemaResolver interface. func (p *planner) CurrentDatabase() string { return p.SessionData().Database } // CurrentSearchPath is part of the resolver.SchemaResolver interface. func (p *planner) CurrentSearchPath() sessiondata.SearchPath { return p.SessionData().SearchPath } // EvalContext() provides convenient access to the planner's EvalContext(). func (p *planner)
EvalContext
identifier_name
planner.go
"github.com/cockroachdb/cockroach/pkg/sql/sem/tree" "github.com/cockroachdb/cockroach/pkg/sql/sessiondata" "github.com/cockroachdb/cockroach/pkg/sql/sessiondatapb" "github.com/cockroachdb/cockroach/pkg/sql/types" "github.com/cockroachdb/cockroach/pkg/util/cancelchecker" "github.com/cockroachdb/cockroach/pkg/util/envutil" "github.com/cockroachdb/cockroach/pkg/util/errorutil" "github.com/cockroachdb/cockroach/pkg/util/hlc" "github.com/cockroachdb/cockroach/pkg/util/mon" "github.com/cockroachdb/errors" "github.com/cockroachdb/logtags" ) // extendedEvalContext extends tree.EvalContext with fields that are needed for // distsql planning. type extendedEvalContext struct { tree.EvalContext SessionMutator *sessionDataMutator // SessionID for this connection. SessionID ClusterWideID // VirtualSchemas can be used to access virtual tables. VirtualSchemas VirtualTabler // Tracing provides access to the session's tracing interface. Changes to the // tracing state should be done through the sessionDataMutator. Tracing *SessionTracing // NodesStatusServer gives access to the NodesStatus service. Unavailable to // tenants. NodesStatusServer serverpb.OptionalNodesStatusServer // SQLStatusServer gives access to a subset of the serverpb.Status service // that is available to both system and non-system tenants. SQLStatusServer serverpb.SQLStatusServer // MemMetrics represent the group of metrics to which execution should // contribute. MemMetrics *MemoryMetrics // Tables points to the Session's table collection (& cache). Descs *descs.Collection ExecCfg *ExecutorConfig DistSQLPlanner *DistSQLPlanner TxnModesSetter txnModesSetter // Jobs refers to jobs in extraTxnState. Jobs is a pointer to a jobsCollection // which is a slice because we need calls to resetExtraTxnState to reset the // jobsCollection. Jobs *jobsCollection // SchemaChangeJobCache refers to schemaChangeJobsCache in extraTxnState. SchemaChangeJobCache map[descpb.ID]*jobs.Job schemaAccessors *schemaInterface sqlStatsCollector *sqlStatsCollector SchemaChangerState *SchemaChangerState } // copy returns a deep copy of ctx. func (evalCtx *extendedEvalContext) copy() *extendedEvalContext { cpy := *evalCtx cpy.EvalContext = *evalCtx.EvalContext.Copy() return &cpy } // QueueJob creates a new job from record and queues it for execution after // the transaction commits. func (evalCtx *extendedEvalContext) QueueJob( ctx context.Context, record jobs.Record, ) (*jobs.Job, error) { jobID := evalCtx.ExecCfg.JobRegistry.MakeJobID() job, err := evalCtx.ExecCfg.JobRegistry.CreateJobWithTxn( ctx, record, jobID, evalCtx.Txn, ) if err != nil { return nil, err } *evalCtx.Jobs = append(*evalCtx.Jobs, jobID) return job, nil } // schemaInterface provides access to the database and table descriptors. // See schema_accessors.go. type schemaInterface struct { logical catalog.Accessor } // planner is the centerpiece of SQL statement execution combining session // state and database state with the logic for SQL execution. It is logically // scoped to the execution of a single statement, and should not be used to // execute multiple statements. It is not safe to use the same planner from // multiple goroutines concurrently. // // planners are usually created by using the newPlanner method on a Session. // If one needs to be created outside of a Session, use makeInternalPlanner(). type planner struct { txn *kv.Txn // isInternalPlanner is set to true when this planner is not bound to // a SQL session. isInternalPlanner bool // Corresponding Statement for this query. stmt Statement instrumentation instrumentationHelper // Contexts for different stages of planning and execution. semaCtx tree.SemaContext extendedEvalCtx extendedEvalContext // sessionDataMutator is used to mutate the session variables. Read // access to them is provided through evalCtx. sessionDataMutator *sessionDataMutator // execCfg is used to access the server configuration for the Executor. execCfg *ExecutorConfig preparedStatements preparedStatementsAccessor // avoidCachedDescriptors, when true, instructs all code that // accesses table/view descriptors to force reading the descriptors // within the transaction. This is necessary to read descriptors // from the store for: // 1. Descriptors that are part of a schema change but are not // modified by the schema change. (reading a table in CREATE VIEW) // 2. Disable the use of the table cache in tests. avoidCachedDescriptors bool // If set, the planner should skip checking for the SELECT privilege when // initializing plans to read from a table. This should be used with care. skipSelectPrivilegeChecks bool // autoCommit indicates whether we're planning for an implicit transaction. // If autoCommit is true, the plan is allowed (but not required) to commit the // transaction along with other KV operations. Committing the txn might be // beneficial because it may enable the 1PC optimization. // // NOTE: plan node must be configured appropriately to actually perform an // auto-commit. This is dependent on information from the optimizer. autoCommit bool // cancelChecker is used by planNodes to check for cancellation of the associated // query. cancelChecker *cancelchecker.CancelChecker // isPreparing is true if this planner is currently preparing. isPreparing bool // curPlan collects the properties of the current plan being prepared. This state // is undefined at the beginning of the planning of each new statement, and cannot // be reused for an old prepared statement after a new statement has been prepared. curPlan planTop // Avoid allocations by embedding commonly used objects and visitors. txCtx transform.ExprTransformContext nameResolutionVisitor schemaexpr.NameResolutionVisitor tableName tree.TableName // Use a common datum allocator across all the plan nodes. This separates the // plan lifetime from the lifetime of returned results allowing plan nodes to // be pool allocated. alloc *rowenc.DatumAlloc // optPlanningCtx stores the optimizer planning context, which contains // data structures that can be reused between queries (for efficiency). optPlanningCtx optPlanningCtx // noticeSender allows the sending of notices. // Do not use this object directly; use the BufferClientNotice() method // instead. noticeSender noticeSender queryCacheSession querycache.Session // contextDatabaseID is the ID of a database. It is set during some name // resolution processes to disallow cross database references. In particular, // the type resolution steps will disallow resolution of types that have a // parentID != contextDatabaseID when it is set. contextDatabaseID descpb.ID } func (evalCtx *extendedEvalContext) setSessionID(sessionID ClusterWideID) { evalCtx.SessionID = sessionID } // noteworthyInternalMemoryUsageBytes is the minimum size tracked by each // internal SQL pool before the pool starts explicitly logging overall usage // growth in the log. var noteworthyInternalMemoryUsageBytes = envutil.EnvOrDefaultInt64("COCKROACH_NOTEWORTHY_INTERNAL_MEMORY_USAGE", 1<<20 /* 1 MB */) // internalPlannerParams encapsulates configurable planner fields. The defaults // are set in newInternalPlanner. type internalPlannerParams struct { collection *descs.Collection } // InternalPlannerParamsOption is an option that can be passed to // NewInternalPlanner. type InternalPlannerParamsOption func(*internalPlannerParams) // WithDescCollection configures the planner with the provided collection // instead of the default (creating a new one from scratch). func WithDescCollection(collection *descs.Collection) InternalPlannerParamsOption { return func(params *internalPlannerParams) { params.collection = collection } } // NewInternalPlanner is an exported version of newInternalPlanner. It // returns an interface{} so it can be used outside of the sql package. func NewInternalPlanner( opName string, txn *kv.Txn, user security.SQLUsername, memMetrics *MemoryMetrics, execCfg *ExecutorConfig, sessionData sessiondatapb.SessionData, opts ...InternalPlannerParamsOption, ) (interface{}, func()) { return newInternalPlanner(opName, txn, user, memMetrics, execCfg, sessionData, opts...) } // newInternalPlanner creates a new planner instance for internal usage. This // planner is not associated with a sql session. // // Since it can't be reset, the planner can be used only for planning a single // statement. // // Returns
"github.com/cockroachdb/cockroach/pkg/sql/opt/exec" "github.com/cockroachdb/cockroach/pkg/sql/parser" "github.com/cockroachdb/cockroach/pkg/sql/querycache" "github.com/cockroachdb/cockroach/pkg/sql/rowenc" "github.com/cockroachdb/cockroach/pkg/sql/sem/transform"
random_line_split