file_name
stringlengths 3
137
| prefix
stringlengths 0
918k
| suffix
stringlengths 0
962k
| middle
stringlengths 0
812k
|
---|---|---|---|
main.rs
|
// Copyright (c) The Libra Core Contributors
// SPDX-License-Identifier: Apache-2.0
use std::{
collections::HashSet,
env, process, thread,
time::{Duration, Instant},
};
use chrono::{Datelike, Timelike, Utc};
use libra_logger::{info, warn};
use rand::{prelude::ThreadRng, Rng};
use reqwest::Url;
use structopt::{clap::ArgGroup, StructOpt};
use termion::{color, style};
use anyhow::{bail, format_err, Result};
use cluster_test::{
aws::Aws,
cluster::Cluster,
cluster_swarm::{cluster_swarm_kube::ClusterSwarmKube, ClusterSwarm},
deployment::DeploymentManager,
effects::{Action, Effect, Reboot, RemoveNetworkEffects, StopContainer},
experiments::{get_experiment, Context, Experiment},
github::GitHub,
health::{DebugPortLogThread, HealthCheckRunner, LogTail, PrintFailures},
instance::Instance,
prometheus::Prometheus,
report::SuiteReport,
slack::SlackClient,
stats,
suite::ExperimentSuite,
tx_emitter::{EmitJobRequest, EmitThreadParams, TxEmitter},
util::unix_timestamp_now,
};
use futures::{
future::{join_all, FutureExt, TryFutureExt},
select,
};
use libra_config::config::AdmissionControlConfig;
use tokio::{
runtime::{Builder, Runtime},
time::{delay_for, delay_until, Instant as TokioInstant},
};
const HEALTH_POLL_INTERVAL: Duration = Duration::from_secs(5);
#[derive(StructOpt, Debug)]
#[structopt(group = ArgGroup::with_name("action"))]
struct Args {
#[structopt(short = "p", long, use_delimiter = true)]
peers: Vec<String>,
#[structopt(
long,
help = "If set, tries to connect to a libra-swarm instead of aws"
)]
swarm: bool,
#[structopt(long, group = "action")]
wipe_all_db: bool,
#[structopt(long, group = "action")]
discovery: bool,
#[structopt(long, group = "action")]
pssh: bool,
#[structopt(long, group = "action")]
run: Option<String>,
#[structopt(long, group = "action")]
tail_logs: bool,
#[structopt(long, group = "action")]
health_check: bool,
#[structopt(long, group = "action")]
reboot: bool,
#[structopt(long, group = "action")]
restart: bool,
#[structopt(long, group = "action")]
stop: bool,
#[structopt(long, group = "action")]
start: bool,
#[structopt(long, group = "action")]
emit_tx: bool,
#[structopt(long, group = "action")]
stop_experiment: bool,
#[structopt(long, group = "action")]
perf_run: bool,
#[structopt(long, group = "action")]
cleanup: bool,
#[structopt(long, group = "action")]
run_ci_suite: bool,
#[structopt(last = true)]
last: Vec<String>,
#[structopt(long)]
deploy: Option<String>,
#[structopt(long, multiple = true)]
changelog: Option<Vec<String>>,
// emit_tx options
#[structopt(long, default_value = "10")]
accounts_per_client: usize,
#[structopt(long)]
workers_per_ac: Option<usize>,
#[structopt(long, default_value = "0")]
wait_millis: u64,
#[structopt(long)]
burst: bool,
#[structopt(long, default_value = "mint.key")]
mint_file: String,
#[structopt(
long,
help = "Time to run --emit-tx for in seconds",
default_value = "60"
)]
duration: u64,
//stop_experiment options
#[structopt(long, default_value = "10")]
max_stopped: usize,
#[structopt(
long,
help = "Whether transactions should be submitted to validators or full nodes"
)]
pub emit_to_validator: Option<bool>,
#[structopt(long, default_value = "1")]
pub k8s_fullnodes_per_validator: u32,
#[structopt(long, parse(try_from_str), default_value = "30")]
pub k8s_num_validators: u32,
}
pub fn main() {
setup_log();
let args = Args::from_args();
if args.swarm && !args.emit_tx {
panic!("Can only use --emit-tx option in --swarm mode");
}
if args.emit_tx {
let mut rt = Runtime::new().unwrap();
let thread_params = EmitThreadParams {
wait_millis: args.wait_millis,
wait_committed: !args.burst,
};
let duration = Duration::from_secs(args.duration);
if args.swarm {
let util = BasicSwarmUtil::setup(&args);
rt.block_on(util.emit_tx(
args.accounts_per_client,
args.workers_per_ac,
thread_params,
duration,
));
return;
} else {
let util = ClusterUtil::setup(&args);
rt.block_on(util.emit_tx(
args.accounts_per_client,
args.workers_per_ac,
thread_params,
duration,
));
return;
}
} else if args.discovery {
let util = ClusterUtil::setup(&args);
util.discovery();
return;
} else if args.pssh {
let util = ClusterUtil::setup(&args);
util.pssh(args.last);
return;
}
let mut runner = ClusterTestRunner::setup(&args);
if let Some(ref hash_or_tag) = args.deploy {
if runner.cluster_swarm.is_none() {
// Deploy deploy_hash before running whatever command
let hash = runner
.deployment_manager
.resolve(hash_or_tag)
.expect("Failed to resolve tag");
exit_on_error(runner.redeploy(&hash));
}
}
let mut perf_msg = None;
if args.tail_logs {
runner.tail_logs();
return;
} else if args.health_check {
runner.run_health_check();
} else if args.wipe_all_db {
runner.stop();
runner.wipe_all_db(true);
runner.start();
} else if args.reboot {
runner.reboot();
} else if args.restart {
runner.restart();
} else if args.stop {
runner.stop();
} else if args.start {
runner.start();
} else if args.perf_run {
perf_msg = Some(runner.perf_run());
} else if args.stop_experiment {
runner.stop_experiment(args.max_stopped);
} else if args.cleanup {
runner.cleanup();
} else if args.run_ci_suite {
perf_msg = Some(exit_on_error(runner.run_ci_suite()));
} else if let Some(experiment_name) = args.run {
runner
.cleanup_and_run(get_experiment(
&experiment_name,
&args.last,
&runner.cluster,
))
.unwrap();
info!(
"{}Experiment Result: {}{}",
style::Bold,
runner.report,
style::Reset
);
} else if args.changelog.is_none() && args.deploy.is_none() {
println!("No action specified");
process::exit(1);
}
if let Some(mut changelog) = args.changelog {
if changelog.len() != 2 {
println!("Use: changelog <from> <to>");
process::exit(1);
}
let to_commit = changelog.remove(1);
let from_commit = Some(changelog.remove(0));
if let Some(perf_msg) = perf_msg {
runner.send_changelog_message(&perf_msg, &from_commit, &to_commit);
} else {
println!("{}", runner.get_changelog(from_commit.as_ref(), &to_commit));
}
} else if let Some(perf_msg) = perf_msg {
println!("{}", perf_msg);
}
}
fn exit_on_error<T>(r: Result<T>) -> T {
match r {
Ok(r) => r,
Err(err) => {
println!("{}", err);
process::exit(1)
}
}
}
fn setup_log() {
if env::var("RUST_LOG").is_err() {
env::set_var("RUST_LOG", "info");
}
::libra_logger::Logger::new().is_async(true).init();
}
struct BasicSwarmUtil {
cluster: Cluster,
}
struct ClusterUtil {
cluster: Cluster,
aws: Aws,
prometheus: Prometheus,
cluster_swarm: Option<ClusterSwarmKube>,
}
struct ClusterTestRunner {
logs: LogTail,
cluster: Cluster,
health_check_runner: HealthCheckRunner,
deployment_manager: DeploymentManager,
experiment_interval: Duration,
runtime: Runtime,
slack: SlackClient,
slack_changelog_url: Option<Url>,
tx_emitter: TxEmitter,
prometheus: Prometheus,
github: GitHub,
report: SuiteReport,
global_emit_job_request: EmitJobRequest,
emit_to_validator: bool,
cluster_swarm: Option<ClusterSwarmKube>,
}
fn parse_host_port(s: &str) -> Result<(String, u32)> {
let v = s.split(':').collect::<Vec<&str>>();
if v.len() == 1 {
let default_port = AdmissionControlConfig::default().address.port() as u32;
return Ok((v[0].to_string(), default_port));
}
if v.len() != 2 {
return Err(format_err!("Failed to parse {:?} in host:port format", s));
}
let host = v[0].to_string();
let port = v[1].parse::<u32>()?;
Ok((host, port))
}
impl BasicSwarmUtil {
pub fn setup(args: &Args) -> Self {
if args.peers.is_empty() {
panic!("Peers not set in args");
}
let parsed_peers: Vec<_> = args
.peers
.iter()
.map(|peer| parse_host_port(peer).unwrap())
.collect();
Self {
cluster: Cluster::from_host_port(parsed_peers, &args.mint_file),
}
}
pub async fn emit_tx(
self,
accounts_per_client: usize,
workers_per_ac: Option<usize>,
thread_params: EmitThreadParams,
duration: Duration,
) {
let mut emitter = TxEmitter::new(&self.cluster);
let job = emitter
.start_job(EmitJobRequest {
instances: self.cluster.validator_instances().to_vec(),
accounts_per_client,
workers_per_ac,
thread_params,
})
.await
.expect("Failed to start emit job");
thread::sleep(duration);
emitter.stop_job(job);
}
}
impl ClusterUtil {
pub fn setup(args: &Args) -> Self {
Runtime::new().unwrap().block_on(async move {
let k8s = env::var("KUBERNETES_SERVICE_HOST").is_ok();
let aws = Aws::new(k8s);
let cluster_swarm = if k8s {
Some(
ClusterSwarmKube::new()
.await
.expect("Failed to initialize ClusterSwarmKube"),
)
} else {
None
};
let cluster = if let Some(cluster_swarm) = cluster_swarm.as_ref() {
cluster_swarm.delete_all().await.expect("delete_all failed");
let image_tag = args.deploy.as_ref().map(|x| x.as_str()).unwrap_or("master");
info!(
"Deploying with {} tag for validators and fullnodes",
image_tag
);
cluster_swarm
.create_validator_and_fullnode_set(
args.k8s_num_validators,
args.k8s_fullnodes_per_validator,
&image_tag,
true,
)
.await
.expect("Failed to create_validator_and_fullnode_set");
info!("Deployment complete");
Cluster::new_k8s(
cluster_swarm.validator_instances().await,
cluster_swarm.fullnode_instances().await,
)
.unwrap()
} else {
Cluster::discover(&aws).expect("Failed to discover cluster")
};
let cluster = if args.peers.is_empty() {
cluster
} else {
cluster.validator_sub_cluster(args.peers.clone())
};
let prometheus_ip = if cluster_swarm.is_some() {
"libra-testnet-prometheus-server.default.svc.cluster.local"
} else {
cluster
.prometheus_ip()
.expect("Failed to discover prometheus ip in aws")
};
let grafana_base_url = if let Some(cluster_swarm) = cluster_swarm.as_ref() {
cluster_swarm
.get_grafana_baseurl()
.await
.expect("Failed to discover grafana url in k8s")
} else {
format!(
"http://prometheus.{}.aws.hlw3truzy4ls.com:9091",
aws.workspace()
)
};
let prometheus = Prometheus::new(prometheus_ip, grafana_base_url, k8s);
info!(
"Discovered {} validators and {} fns in {} workspace",
cluster.validator_instances().len(),
cluster.fullnode_instances().len(),
aws.workspace()
);
Self {
cluster,
aws,
prometheus,
cluster_swarm,
}
})
}
pub fn discovery(&self) {
for instance in self.cluster.all_instances() {
println!("{} {}", instance.peer_name(), instance.ip());
}
}
pub fn pssh(&self, cmd: Vec<String>) {
let mut runtime = Runtime::new().unwrap();
let futures = self.cluster.all_instances().map(|x| {
x.run_cmd_tee_err(&cmd).map(move |r| {
if let Err(e) = r {
warn!("Failed on {}: {}", x, e)
}
})
});
runtime.block_on(join_all(futures));
}
pub async fn emit_tx(
self,
accounts_per_client: usize,
workers_per_ac: Option<usize>,
thread_params: EmitThreadParams,
duration: Duration,
) {
let mut emitter = TxEmitter::new(&self.cluster);
emitter
.start_job(EmitJobRequest {
instances: self.cluster.validator_instances().to_vec(),
accounts_per_client,
workers_per_ac,
thread_params,
})
.await
.expect("Failed to start emit job");
self.run_stat_loop(duration);
}
fn run_stat_loop(&self, duration: Duration) {
let deadline = Instant::now() + duration;
let window = Duration::from_secs(30);
thread::sleep(Duration::from_secs(30)); // warm up
loop {
if Instant::now() > deadline {
return;
}
thread::sleep(Duration::from_secs(10));
let now = unix_timestamp_now();
match stats::txn_stats(&self.prometheus, now - window, now) {
Ok((avg_tps, avg_latency)) => {
info!("Tps: {:.0}, latency: {:.0} ms", avg_tps, avg_latency)
}
Err(err) => info!("Stat error: {:?}", err),
}
}
}
}
impl ClusterTestRunner {
/// Discovers cluster, setup log, etc
pub fn setup(args: &Args) -> Self {
let util = ClusterUtil::setup(args);
let cluster = util.cluster;
let aws = util.aws;
let cluster_swarm = util.cluster_swarm;
let log_tail_started = Instant::now();
let logs = DebugPortLogThread::spawn_new(&cluster);
let log_tail_startup_time = Instant::now() - log_tail_started;
info!(
"Log tail thread started in {} ms",
log_tail_startup_time.as_millis()
);
let health_check_runner = HealthCheckRunner::new_all(cluster.clone());
let experiment_interval_sec = match env::var("EXPERIMENT_INTERVAL") {
Ok(s) => s.parse().expect("EXPERIMENT_INTERVAL env is not a number"),
Err(..) => 15,
};
let experiment_interval = Duration::from_secs(experiment_interval_sec);
let deployment_manager = DeploymentManager::new(aws, cluster.clone());
let slack = SlackClient::new();
let slack_changelog_url = env::var("SLACK_CHANGELOG_URL")
.map(|u| u.parse().expect("Failed to parse SLACK_CHANGELOG_URL"))
.ok();
let tx_emitter = TxEmitter::new(&cluster);
let prometheus = util.prometheus;
let github = GitHub::new();
let report = SuiteReport::new();
let runtime = Builder::new()
.threaded_scheduler()
.core_threads(num_cpus::get())
.thread_name("ct-tokio")
.enable_all()
.build()
.expect("Failed to create tokio runtime");
let global_emit_job_request = EmitJobRequest {
instances: vec![],
accounts_per_client: args.accounts_per_client,
workers_per_ac: args.workers_per_ac,
thread_params: EmitThreadParams {
wait_millis: args.wait_millis,
wait_committed: !args.burst,
},
};
let emit_to_validator =
if cluster.fullnode_instances().len() < cluster.validator_instances().len() {
true
} else {
args.emit_to_validator.unwrap_or(false)
};
Self {
logs,
cluster,
health_check_runner,
deployment_manager,
experiment_interval,
slack,
runtime,
slack_changelog_url,
tx_emitter,
prometheus,
github,
report,
global_emit_job_request,
emit_to_validator,
cluster_swarm,
}
}
pub fn run_ci_suite(&mut self) -> Result<String> {
let suite = ExperimentSuite::new_pre_release(&self.cluster);
self.run_suite(suite)?;
let perf_msg = format!("Performance report:\n```\n{}\n```", self.report);
Ok(perf_msg)
}
pub fn send_changelog_message(
&self,
perf_msg: &str,
from_commit: &Option<String>,
to_commit: &str,
) {
info!(
"Generating changelog from {:?} to {}",
from_commit, to_commit
);
let changelog = self.get_changelog(from_commit.as_ref(), &to_commit);
|
}
fn get_changelog(&self, prev_commit: Option<&String>, upstream_commit: &str) -> String {
let commits = self.github.get_commits("libra/libra", &upstream_commit);
match commits {
Err(e) => {
info!("Failed to get github commits: {:?}", e);
format!("*Revision upstream_{}*", upstream_commit)
}
Ok(commits) => {
let mut msg = format!("*Revision {}*", upstream_commit);
for commit in commits {
if let Some(prev_commit) = prev_commit {
if commit.sha.starts_with(prev_commit) {
break;
}
}
let commit_lines: Vec<_> = commit.commit.message.split('\n').collect();
let commit_head = commit_lines[0];
let short_sha = &commit.sha[..6];
let email_parts: Vec<_> = commit.commit.author.email.split('@').collect();
let author = email_parts[0];
let line = format!("\n>\u{2022} {} _{}_ {}", short_sha, author, commit_head);
msg.push_str(&line);
}
msg
}
}
}
fn redeploy(&mut self, hash: &str) -> Result<()> {
info!("Cleaning up before deploy");
self.cleanup();
info!("Stopping validators");
self.stop();
if env::var("WIPE_ON_DEPLOY") != Ok("no".to_string()) {
info!("Wiping validators");
self.wipe_all_db(false);
} else {
info!("WIPE_ON_DEPLOY is set to no, keeping database");
}
self.deployment_manager.redeploy(hash.to_string())?;
thread::sleep(Duration::from_secs(60));
self.logs.recv_all();
self.health_check_runner.clear();
self.tx_emitter.clear();
self.start();
self.wait_until_all_healthy()?;
Ok(())
}
fn run_suite(&mut self, suite: ExperimentSuite) -> Result<()> {
info!("Starting suite");
let suite_started = Instant::now();
for experiment in suite.experiments {
let experiment_name = format!("{}", experiment);
self.run_single_experiment(experiment, None)
.map_err(move |e| {
format_err!("Experiment `{}` failed: `{}`", experiment_name, e)
})?;
thread::sleep(self.experiment_interval);
}
info!(
"Suite completed in {:?}",
Instant::now().duration_since(suite_started)
);
self.print_report();
Ok(())
}
pub fn print_report(&self) {
let json_report =
serde_json::to_string_pretty(&self.report).expect("Failed to serialize report to json");
info!(
"\n====json-report-begin===\n{}\n====json-report-end===",
json_report
);
}
pub fn perf_run(&mut self) -> String {
let suite = ExperimentSuite::new_perf_suite(&self.cluster);
self.run_suite(suite).unwrap();
self.report.to_string()
}
pub fn cleanup_and_run(&mut self, experiment: Box<dyn Experiment>) -> Result<()> {
self.cleanup();
self.run_single_experiment(experiment, Some(self.global_emit_job_request.clone()))?;
if let Some(cluster_swarm) = self.cluster_swarm.as_ref() {
self.runtime.block_on(cluster_swarm.delete_all())?;
}
self.print_report();
Ok(())
}
pub fn run_single_experiment(
&mut self,
mut experiment: Box<dyn Experiment>,
mut global_emit_job_request: Option<EmitJobRequest>,
) -> Result<()> {
self.wait_until_all_healthy()?;
let events = self.logs.recv_all();
if let Err(s) =
self.health_check_runner
.run(&events, &HashSet::new(), PrintFailures::UnexpectedOnly)
{
bail!(
"Some validators are unhealthy before experiment started : {}",
s
);
}
info!(
"{}Starting experiment {}{}{}{}",
style::Bold,
color::Fg(color::Blue),
experiment,
color::Fg(color::Reset),
style::Reset
);
let affected_validators = experiment.affected_validators();
let deadline = experiment.deadline();
let experiment_deadline = Instant::now() + deadline;
let context = Context::new(
&mut self.tx_emitter,
&self.prometheus,
&self.cluster,
&mut self.report,
&mut global_emit_job_request,
self.emit_to_validator,
);
{
let logs = &mut self.logs;
let health_check_runner = &mut self.health_check_runner;
let affected_validators = &affected_validators;
self.runtime.block_on(async move {
let mut context = context;
let mut deadline_future =
delay_until(TokioInstant::from_std(experiment_deadline)).fuse();
let mut run_future = experiment.run(&mut context).fuse();
loop {
select! {
delay = deadline_future => {
bail!("Experiment deadline reached");
}
result = run_future => {
return result.map_err(|e|format_err!("Failed to run experiment: {}", e));
}
delay = delay_for(HEALTH_POLL_INTERVAL).fuse() => {
let events = logs.recv_all();
if let Err(s) = health_check_runner.run(
&events,
&affected_validators,
PrintFailures::UnexpectedOnly,
) {
bail!("Validators which were not under experiment failed : {}", s);
}
}
}
}
})?;
}
info!(
"{}Experiment finished, waiting until all affected validators recover{}",
style::Bold,
style::Reset
);
for validator in affected_validators.iter() {
self.health_check_runner.invalidate(validator);
}
loop {
if Instant::now() > experiment_deadline {
bail!("Cluster did not become healthy in time");
}
let deadline = Instant::now() + HEALTH_POLL_INTERVAL;
// Receive all events that arrived to aws log tail within next 1 second
// This assumes so far that event propagation time is << 1s, this need to be refined
// in future to account for actual event propagation delay
let events = self.logs.recv_all_until_deadline(deadline);
let unhealthy_validators;
match self.health_check_runner.run(
&events,
&affected_validators,
PrintFailures::UnexpectedOnly,
) {
Err(s) => bail!("Validators which were not under experiment failed : {}", s),
Ok(r) => unhealthy_validators = r,
}
if unhealthy_validators.is_empty() {
break;
}
}
info!("Experiment completed");
Ok(())
}
pub fn stop_experiment(&mut self, max_stopped: usize) {
let mut instances = self.cluster.validator_instances().to_vec();
let mut rng = ThreadRng::default();
let mut stop_effects = vec![];
let mut stopped_instance_ids = vec![];
let mut results = vec![];
let window = Duration::from_secs(60);
loop {
let job = self
.runtime
.block_on(self.tx_emitter.start_job(EmitJobRequest::for_instances(
instances.clone(),
&Some(self.global_emit_job_request.clone()),
)))
.expect("Failed to start emit job");
thread::sleep(Duration::from_secs(30) + window);
let now = unix_timestamp_now();
match stats::txn_stats(&self.prometheus, now - window, now) {
Ok((avg_tps, avg_latency)) => {
results.push((stop_effects.len(), avg_tps, avg_latency));
info!("Tps: {:.0}, latency: {:.0} ms", avg_tps, avg_latency);
}
Err(err) => info!("Stat error: {:?}", err),
}
self.tx_emitter.stop_job(job);
if stop_effects.len() > max_stopped {
break;
}
let stop_validator = rng.gen_range(0, instances.len());
let stop_validator = instances.remove(stop_validator);
stopped_instance_ids.push(stop_validator.peer_name().clone());
let stop_effect = StopContainer::new(stop_validator);
info!(
"Stopped {} validators: {}",
stopped_instance_ids.len(),
stopped_instance_ids.join(",")
);
self.runtime
.block_on(stop_effect.activate())
.expect("Failed to stop container");
stop_effects.push(stop_effect);
thread::sleep(Duration::from_secs(30));
}
println!("Results in csv format:");
println!("DOWN\tTPS\tLAT");
for (stopped, tps, lat) in results {
println!("{}\t{:.0}\t{:.0}", stopped, tps, lat * 1000.);
}
let futures = stop_effects.iter().map(|stop_effect| {
stop_effect
.deactivate()
.map_err(move |e| info!("Failed to deactivate {}: {:?}", stop_effect, e))
});
self.runtime.block_on(join_all(futures));
}
fn run_health_check(&mut self) {
loop {
let deadline = Instant::now() + Duration::from_secs(1);
// Receive all events that arrived to aws log tail within next 1 second
// This assumes so far that event propagation time is << 1s, this need to be refined
// in future to account for actual event propagation delay
let events = self.logs.recv_all_until_deadline(deadline);
let _ignore =
self.health_check_runner
.run(&events, &HashSet::new(), PrintFailures::All);
}
}
fn wait_until_all_healthy(&mut self) -> Result<()> {
info!("Waiting for all validators to be healthy");
let wait_deadline = Instant::now() + Duration::from_secs(20 * 60);
for instance in self.cluster.validator_instances() {
self.health_check_runner.invalidate(instance.peer_name());
}
loop {
let now = Instant::now();
if now > wait_deadline {
bail!("Validators did not become healthy after deployment");
}
let deadline = now + HEALTH_POLL_INTERVAL;
let events = self.logs.recv_all_until_deadline(deadline);
if let Ok(failed_instances) =
self.health_check_runner
.run(&events, &HashSet::new(), PrintFailures::None)
{
if failed_instances.is_empty() {
break;
}
}
}
info!("All validators are now healthy");
Ok(())
}
fn tail_logs(self) {
for log in self.logs.event_receiver {
info!("{:?}", log);
}
}
fn slack_changelog_message(&self, msg: String) {
info!("{}", msg);
if let Some(ref changelog_url) = self.slack_changelog_url {
if let Err(e) = self.slack.send_message(changelog_url, &msg) {
info!("Failed to send slack message: {}", e);
}
}
}
fn wipe_all_db(&mut self, safety_wait: bool) {
info!("Going to wipe db on all validators in cluster!");
if safety_wait {
info!("Waiting 10 seconds before proceed");
thread::sleep(Duration::from_secs(10));
info!("Starting...");
}
let now = Utc::now();
let suffix = format!(
".{:04}{:02}{:02}-{:02}{:02}{:02}.gz",
now.year(),
now.month(),
now.day(),
now.hour(),
now.minute(),
now.second()
);
let suffix = &suffix;
let log_file = "/data/libra/libra.log";
info!("Will use suffix {} for log rotation", suffix);
let jobs = self
.cluster
.all_instances()
.map(|instance| Self::wipe_instance(log_file, &suffix, instance));
self.runtime.block_on(join_all(jobs));
info!("Done");
}
async fn wipe_instance(log_file: &str, suffix: &str, instance: &Instance) {
instance
.run_cmd_tee_err(vec!["sudo", "rm", "-rf", "/data/libra/common"])
.await
.map_err(|e| info!("Failed to wipe {}: {:?}", instance, e))
.ok();
instance
.run_cmd_tee_err(vec![format!(
"! test -f {f} || (sudo timeout 45 gzip -S {s} {f} || (echo gzip failed; sudo rm -f {f}))",
f = log_file,
s = suffix
)]).await
.map_err(|e| info!("Failed to gzip log file {}: {:?}", instance, e))
.ok();
}
fn reboot(&mut self) {
let futures = self.cluster.all_instances().map(|instance| async move {
let reboot = Reboot::new(instance.clone());
reboot
.apply()
.await
.map_err(|e| info!("Failed to reboot {}: {:?}", instance, e))
});
self.runtime.block_on(join_all(futures));
info!("Completed");
}
fn restart(&mut self) {
self.stop();
self.start();
info!("Completed");
}
fn cleanup(&mut self) {
if self.cluster_swarm.is_none() {
let futures = self.cluster.all_instances().map(|instance| async move {
RemoveNetworkEffects::new(instance.clone())
.apply()
.await
.map_err(|e| {
info!(
"Failed to remove network effects for {}. Error: {}",
instance, e
);
})
});
self.runtime.block_on(join_all(futures));
}
}
pub fn stop(&mut self) {
let effects = self.make_stop_effects();
let futures = effects.iter().map(|e| e.activate());
self.runtime.block_on(join_all(futures));
}
pub fn start(&mut self) {
let effects = self.make_stop_effects();
let futures = effects.iter().map(|e| e.deactivate());
self.runtime.block_on(join_all(futures));
}
fn make_stop_effects(&self) -> Vec<StopContainer> {
self.cluster
.all_instances()
.map(|x| StopContainer::new(x.clone()))
.collect()
}
}
|
self.slack_changelog_message(format!("{}\n\n{}", changelog, perf_msg));
|
substitution_key.rs
|
use super::Fix;
use crate::common::{is_escaped, LineEntry, LintKind};
#[derive(Default)]
pub(crate) struct SubstitutionKeyFixer {}
impl Fix for SubstitutionKeyFixer {
fn
|
(&self) -> LintKind {
LintKind::SubstitutionKey
}
// TODO: refactor
fn fix_line(&self, line: &mut LineEntry) -> Option<()> {
let mut value = line
.get_value()
.map(str::trim)
.filter(|val| !val.starts_with('\''))?;
let mut result = String::with_capacity(value.len());
// Checks if keys used in value have both '{' '}' or neither
while let Some((prefix, raw_key)) = value.split_once('$') {
result.push_str(prefix);
result.push('$');
// Separate initial key from the rest
let (initial_key, rest) = raw_key
.find('$')
.map(|i| raw_key.split_at(i))
.unwrap_or_else(|| (raw_key, ""));
value = rest;
let stripped_key = initial_key.strip_prefix('{').unwrap_or(initial_key);
let correct_end_index = stripped_key
.find(|c: char| !c.is_ascii_alphanumeric() && c != '_')
.unwrap_or(stripped_key.len());
if is_escaped(prefix) || correct_end_index == 0 {
result.push_str(stripped_key);
continue;
}
result.push('{');
result.push_str(&stripped_key[..correct_end_index]);
let rest_part = &stripped_key[correct_end_index..];
if !rest_part.starts_with('}') {
result.push('}')
}
result.push_str(rest_part);
}
line.raw_string = format!("{}={}", line.get_key()?, result);
Some(())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::common::tests::*;
#[test]
fn fix_line_test() {
let fixer = SubstitutionKeyFixer::default();
let mut line = line_entry(1, 1, "FOO=${BAR");
assert_eq!(Some(()), fixer.fix_line(&mut line));
assert_eq!("FOO=${BAR}", line.raw_string);
}
#[test]
fn fix_warnings_test() {
let fixer = SubstitutionKeyFixer::default();
let mut lines = vec![
line_entry(1, 7, "FOO=${BAR-$ABC_ROOT}"),
line_entry(2, 7, "Z=$Y"),
line_entry(3, 7, "BAR=$Y}-$OPTS"),
line_entry(4, 7, "ABC=${BAR$XYZ}"),
line_entry(5, 7, "FOO=\"\\$BAR}"),
line_entry(6, 7, "GOD=${BAR!}"),
blank_line_entry(7, 7),
];
let warning_lines = [1, 3, 4, 6];
assert_eq!(Some(4), fixer.fix_warnings(&warning_lines, &mut lines));
assert_eq!("FOO=${BAR}-${ABC_ROOT}", lines[0].raw_string);
assert_eq!("BAR=${Y}-${OPTS}", lines[2].raw_string);
assert_eq!("ABC=${BAR}${XYZ}", lines[3].raw_string);
assert_eq!("GOD=${BAR}!}", lines[5].raw_string);
}
}
|
name
|
html_form_builder.rs
|
//! Module to build HtmlForms
use crate::html::{FieldValidator, HtmlFieldBuilder};
use std::collections::HashMap;
use std::fmt::Debug;
use std::marker::PhantomData;
pub struct HtmlFormBuilder<'a> {
fields: HashMap<&'static str, HtmlFieldBuilder>,
errors: HashMap<&'static str, String>,
validated: bool,
phantom: PhantomData<&'a i32>,
}
impl<'a> HtmlFormBuilder<'a> {
/// Creates a new HtmlFormBuilder with the specified fields
/// and validators
pub fn new() -> HtmlFormBuilder<'a> {
HtmlFormBuilder {
fields: HashMap::new(),
errors: HashMap::new(),
validated: false,
phantom: PhantomData,
}
}
/// Returns a Builder than can build a new HtmlField in-place. Useful when
/// mutable references are allowed.AsMut
///
/// # Arguments
///
/// * `field` - Name of field to build
pub fn builder<S: AsRef<str>>(&self, field: S) -> HtmlFieldBuilder {
match self.fields.get(field.as_ref()) {
Some(field) => field.clone(),
None => panic!("WebForms - No field with name {}", field.as_ref()),
}
}
/// Returns true if this form has been sucessfully validated,
/// false if validation failed or it never occured (i.e., called
/// `blank_form`)
pub fn validated(&self) -> bool {
self.validated
}
/// Validates a field's value against a list of closures, setting the
/// validated field appropriately
///
/// # Arguments
///
/// * `value` - Value of field to validate
/// * `validators` - Vector of closures to validate against
//pub fn validate_field<T: Debug>(&mut self, value: &T, validators: Vec<Box<&Fn(&T) -> bool>>) {
pub fn validate_field<T>(&mut self, value: &T, validator: FieldValidator<'a, T>) {
//self.validated = validators.iter().all(|x| x(value));
self.validated = validator.validate(value, &mut self.errors);
}
/// Returns all errors that occured during form validation, or
/// None if no errors occured
///
/// # Arguments
///
/// * `field` - Name of field to retrieve errors for
pub fn
|
<S: AsRef<str>>(&self, _field: S) -> Option<bool> {
None
}
pub fn errs(&self) -> &HashMap<&'static str, String> {
&self.errors
}
/// Adds a new field builder (and thus field) to this form builder
pub fn add_field(&mut self, name: &'static str, field: HtmlFieldBuilder) {
self.fields.insert(name, field);
}
}
impl<'a> std::fmt::Display for HtmlFormBuilder<'a> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
for (_, field) in &self.fields {
let builder = field.clone();
write!(f, "{}\n", builder.finish())?;
}
Ok(())
}
}
|
errors
|
GHFlagIcon.tsx
|
// Auto-generated file, do NOT modify
// **********************************
import React, { forwardRef, memo } from 'react';
import { PrivateIconProps } from '../../base';
import { useUniqueId } from '../../utils';
import { createStyledFlagIcon, FlagIconProps } from '../base';
const FlagIcon: React.FC<FlagIconProps & PrivateIconProps> = ({ svgRef, title = 'GH flag', theme, ...props }) => {
const uniqueTitleId = useUniqueId('icon');
const titleId = title ? props.titleId || uniqueTitleId : undefined;
const ariaHidden = titleId ? undefined : true;
return (
<svg aria-hidden={ariaHidden} aria-labelledby={titleId} ref={svgRef} viewBox="0 0 640 480" {...props}>
{title ? <title id={titleId}>{title}</title> : null}
<path d="M0 0h640v480H0z" fill="#006b3f" />
<path d="M0 0h640v320H0z" fill="#fcd116" />
<path d="M0 0h640v160H0z" fill="#ce1126" />
<path d="M320 160l52 160-136.1-98.9H404L268 320z" />
</svg>
);
};
const FlagIconWithForwardedRef = forwardRef<SVGSVGElement, FlagIconProps>((iconProps, ref) => (
<FlagIcon {...iconProps} svgRef={ref} />
));
export const GHFlagIcon = memo(createStyledFlagIcon(FlagIconWithForwardedRef));
GHFlagIcon.displayName = 'GHFlagIcon';
|
// **********************************
|
|
student_t_process.py
|
# Copyright 2018 The TensorFlow Probability Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================
"""The StudentTProcess distribution class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import warnings
# Dependency imports
import tensorflow.compat.v2 as tf
from tensorflow_probability.python.bijectors import identity as identity_bijector
from tensorflow_probability.python.distributions import distribution
from tensorflow_probability.python.distributions import multivariate_student_t
from tensorflow_probability.python.distributions import student_t
from tensorflow_probability.python.internal import assert_util
from tensorflow_probability.python.internal import distribution_util
from tensorflow_probability.python.internal import dtype_util
from tensorflow_probability.python.internal import reparameterization
from tensorflow_probability.python.internal import tensor_util
from tensorflow_probability.python.internal import tensorshape_util
from tensorflow.python.util import deprecation # pylint: disable=g-direct-tensorflow-import
__all__ = [
'StudentTProcess',
]
def _add_diagonal_shift(matrix, shift):
return tf.linalg.set_diag(
matrix, tf.linalg.diag_part(matrix) + shift, name='add_diagonal_shift')
def make_cholesky_factored_marginal_fn(jitter):
"""Construct a `marginal_fn` for use with `tfd.StudentTProcess`.
The returned function computes the Cholesky factorization of the input
covariance plus a diagonal jitter, and uses that for the `scale` of a
`tfd.MultivariateNormalLinearOperator`.
Args:
jitter: `float` scalar `Tensor` added to the diagonal of the covariance
matrix to ensure positive definiteness of the covariance matrix.
Returns:
marginal_fn: A Python function that takes a location, covariance matrix,
optional `validate_args`, `allow_nan_stats` and `name` arguments, and
returns a `tfd.MultivariateNormalLinearOperator`.
"""
def marginal_fn(
df,
loc,
covariance,
validate_args=False,
allow_nan_stats=False,
name='marginal_distribution'):
squared_scale = ((df - 2.) / df)[
..., tf.newaxis, tf.newaxis] * covariance
scale = tf.linalg.LinearOperatorLowerTriangular(
tf.linalg.cholesky(_add_diagonal_shift(squared_scale, jitter)),
is_non_singular=True,
name='StudentTProcessScaleLinearOperator')
return multivariate_student_t.MultivariateStudentTLinearOperator(
df=df,
loc=loc,
scale=scale,
validate_args=validate_args,
allow_nan_stats=allow_nan_stats,
name=name)
return marginal_fn
class StudentTProcess(distribution.Distribution):
"""Marginal distribution of a Student's T process at finitely many points.
A Student's T process (TP) is an indexed collection of random variables, any
finite collection of which are jointly Multivariate Student's T. While this
definition applies to finite index sets, it is typically implicit that the
index set is infinite; in applications, it is often some finite dimensional
real or complex vector space. In such cases, the TP may be thought of as a
distribution over (real- or complex-valued) functions defined over the index
set.
Just as Student's T distributions are fully specified by their degrees of
freedom, location and scale, a Student's T process can be completely specified
by a degrees of freedom parameter, mean function and covariance function.
Let `S` denote the index set and `K` the space in
which each indexed random variable takes its values (again, often R or C).
The mean function is then a map `m: S -> K`, and the covariance function,
or kernel, is a positive-definite function `k: (S x S) -> K`. The properties
of functions drawn from a TP are entirely dictated (up to translation) by
the form of the kernel function.
This `Distribution` represents the marginal joint distribution over function
values at a given finite collection of points `[x[1], ..., x[N]]` from the
index set `S`. By definition, this marginal distribution is just a
multivariate Student's T distribution, whose mean is given by the vector
`[ m(x[1]), ..., m(x[N]) ]` and whose covariance matrix is constructed from
pairwise applications of the kernel function to the given inputs:
```none
| k(x[1], x[1]) k(x[1], x[2]) ... k(x[1], x[N]) |
| k(x[2], x[1]) k(x[2], x[2]) ... k(x[2], x[N]) |
| ... ... ... |
| k(x[N], x[1]) k(x[N], x[2]) ... k(x[N], x[N]) |
```
For this to be a valid covariance matrix, it must be symmetric and positive
definite; hence the requirement that `k` be a positive definite function
(which, by definition, says that the above procedure will yield PD matrices).
Note also we use a parameterization as suggested in [1], which requires `df`
to be greater than 2. This allows for the covariance for any finite
dimensional marginal of the TP (a multivariate Student's T distribution) to
just be the PD matrix generated by the kernel.
#### Mathematical Details
The probability density function (pdf) is a multivariate Student's T whose
parameters are derived from the TP's properties:
```none
pdf(x; df, index_points, mean_fn, kernel) = MultivariateStudentT(df, loc, K)
K = (df - 2) / df * (kernel.matrix(index_points, index_points) +
observation_noise_variance * eye(N))
loc = (x - mean_fn(index_points))^T @ K @ (x - mean_fn(index_points))
```
where:
* `df` is the degrees of freedom parameter for the TP.
* `index_points` are points in the index set over which the TP is defined,
* `mean_fn` is a callable mapping the index set to the TP's mean values,
* `kernel` is `PositiveSemidefiniteKernel`-like and represents the covariance
function of the TP,
* `observation_noise_variance` is a term added to the diagonal of the kernel
matrix. In the limit of `df` to `inf`, this represents the observation noise
of a gaussian likelihood.
* `eye(N)` is an N-by-N identity matrix.
|
##### Draw joint samples from a TP prior
```python
import numpy as np
import tensorflow.compat.v2 as tf
import tensorflow_probability as tfp
tf.enable_v2_behavior()
tfd = tfp.distributions
psd_kernels = tfp.math.psd_kernels
num_points = 100
# Index points should be a collection (100, here) of feature vectors. In this
# example, we're using 1-d vectors, so we just need to reshape the output from
# np.linspace, to give a shape of (100, 1).
index_points = np.expand_dims(np.linspace(-1., 1., num_points), -1)
# Define a kernel with default parameters.
kernel = psd_kernels.ExponentiatedQuadratic()
tp = tfd.StudentTProcess(3., kernel, index_points)
samples = tp.sample(10)
# ==> 10 independently drawn, joint samples at `index_points`
noisy_tp = tfd.StudentTProcess(
df=3.,
kernel=kernel,
index_points=index_points)
noisy_samples = noisy_tp.sample(10)
# ==> 10 independently drawn, noisy joint samples at `index_points`
```
##### Optimize kernel parameters via maximum marginal likelihood.
```python
# Suppose we have some data from a known function. Note the index points in
# general have shape `[b1, ..., bB, f1, ..., fF]` (here we assume `F == 1`),
# so we need to explicitly consume the feature dimensions (just the last one
# here).
f = lambda x: np.sin(10*x[..., 0]) * np.exp(-x[..., 0]**2)
observed_index_points = np.expand_dims(np.random.uniform(-1., 1., 50), -1)
# Squeeze to take the shape from [50, 1] to [50].
observed_values = f(observed_index_points)
amplitude = tfp.util.TransformedVariable(
1., tfp.bijectors.Softplus(), dtype=np.float64, name='amplitude')
length_scale = tfp.util.TransformedVariable(
1., tfp.bijectors.Softplus(), dtype=np.float64, name='length_scale')
# Define a kernel with trainable parameters.
kernel = psd_kernels.ExponentiatedQuadratic(
amplitude=amplitude,
length_scale=length_scale)
tp = tfd.StudentTProcess(3., kernel, observed_index_points)
optimizer = tf.optimizers.Adam()
@tf.function
def optimize():
with tf.GradientTape() as tape:
loss = -tp.log_prob(observed_values)
grads = tape.gradient(loss, tp.trainable_variables)
optimizer.apply_gradients(zip(grads, tp.trainable_variables))
return loss
for i in range(1000):
nll = optimize()
if i % 100 == 0:
print("Step {}: NLL = {}".format(i, nll))
print("Final NLL = {}".format(nll))
```
#### References
[1]: Amar Shah, Andrew Gordon Wilson, and Zoubin Ghahramani. Student-t
Processes as Alternatives to Gaussian Processes. In _Artificial
Intelligence and Statistics_, 2014.
https://www.cs.cmu.edu/~andrewgw/tprocess.pdf
"""
@deprecation.deprecated_args(
'2021-06-26',
'`jitter` is deprecated; please use `marginal_fn` directly.',
'jitter')
def __init__(self,
df,
kernel,
index_points=None,
mean_fn=None,
observation_noise_variance=0.,
marginal_fn=None,
jitter=1e-6,
validate_args=False,
allow_nan_stats=False,
name='StudentTProcess'):
"""Instantiate a StudentTProcess Distribution.
Args:
df: Positive Floating-point `Tensor` representing the degrees of freedom.
Must be greater than 2.
kernel: `PositiveSemidefiniteKernel`-like instance representing the
TP's covariance function.
index_points: `float` `Tensor` representing finite (batch of) vector(s) of
points in the index set over which the TP is defined. Shape has the form
`[b1, ..., bB, e, f1, ..., fF]` where `F` is the number of feature
dimensions and must equal `kernel.feature_ndims` and `e` is the number
(size) of index points in each batch. Ultimately this distribution
corresponds to a `e`-dimensional multivariate Student's T. The batch
shape must be broadcastable with `kernel.batch_shape` and any batch dims
yielded by `mean_fn`.
mean_fn: Python `callable` that acts on `index_points` to produce a (batch
of) vector(s) of mean values at `index_points`. Takes a `Tensor` of
shape `[b1, ..., bB, f1, ..., fF]` and returns a `Tensor` whose shape is
broadcastable with `[b1, ..., bB]`. Default value: `None` implies
constant zero function.
observation_noise_variance: `float` `Tensor` representing (batch of)
scalar variance(s) of the noise in the Normal likelihood
distribution of the model. If batched, the batch shape must be
broadcastable with the shapes of all other batched parameters
(`kernel.batch_shape`, `index_points`, etc.).
Default value: `0.`
marginal_fn: A Python callable that takes a location, covariance matrix,
optional `validate_args`, `allow_nan_stats` and `name` arguments, and
returns a multivariate normal subclass of `tfd.Distribution`.
Default value: `None`, in which case a Cholesky-factorizing function is
is created using `make_cholesky_factorizing_marginal_fn` and the
`jitter` argument.
jitter: `float` scalar `Tensor` added to the diagonal of the covariance
matrix to ensure positive definiteness of the covariance matrix.
Default value: `1e-6`.
validate_args: Python `bool`, default `False`. When `True` distribution
parameters are checked for validity despite possibly degrading runtime
performance. When `False` invalid inputs may silently render incorrect
outputs.
Default value: `False`.
allow_nan_stats: Python `bool`, default `True`. When `True`,
statistics (e.g., mean, mode, variance) use the value "`NaN`" to
indicate the result is undefined. When `False`, an exception is raised
if one or more of the statistic's batch members are undefined.
Default value: `False`.
name: Python `str` name prefixed to Ops created by this class.
Default value: "StudentTProcess".
Raises:
ValueError: if `mean_fn` is not `None` and is not callable.
"""
parameters = dict(locals())
with tf.name_scope(name) as name:
dtype = dtype_util.common_dtype(
[df, index_points, observation_noise_variance, jitter], tf.float32)
df = tensor_util.convert_nonref_to_tensor(df, dtype=dtype, name='df')
observation_noise_variance = tensor_util.convert_nonref_to_tensor(
observation_noise_variance,
dtype=dtype,
name='observation_noise_variance')
index_points = tensor_util.convert_nonref_to_tensor(
index_points, dtype=dtype, name='index_points')
jitter = tensor_util.convert_nonref_to_tensor(
jitter, dtype=dtype, name='jitter')
self._kernel = kernel
self._index_points = index_points
# Default to a constant zero function, borrowing the dtype from
# index_points to ensure consistency.
if mean_fn is None:
mean_fn = lambda x: tf.zeros([1], dtype=dtype)
else:
if not callable(mean_fn):
raise ValueError('`mean_fn` must be a Python callable')
self._df = df
self._observation_noise_variance = observation_noise_variance
self._mean_fn = mean_fn
self._jitter = jitter
if marginal_fn is None:
self._marginal_fn = make_cholesky_factored_marginal_fn(jitter)
else:
self._marginal_fn = marginal_fn
with tf.name_scope('init'):
super(StudentTProcess, self).__init__(
dtype=dtype,
reparameterization_type=reparameterization.FULLY_REPARAMETERIZED,
validate_args=validate_args,
allow_nan_stats=allow_nan_stats,
parameters=parameters,
name=name)
def _is_univariate_marginal(self, index_points):
"""True if the given index_points would yield a univariate marginal.
Args:
index_points: the set of index set locations at which to compute the
marginal Student T distribution. If this set is of size 1, the marginal is
univariate.
Returns:
is_univariate: Boolean indicating whether the marginal is univariate or
multivariate. In the case of dynamic shape in the number of index points,
defaults to "multivariate" since that's the best we can do.
"""
num_index_points = tf.compat.dimension_value(
index_points.shape[-(self.kernel.feature_ndims + 1)])
if num_index_points is None:
warnings.warn(
'Unable to detect statically whether the number of index_points is '
'1. As a result, defaulting to treating the marginal Student T '
'Process at `index_points` as a multivariate Student T. This makes '
'some methods, like `cdf` unavailable.')
return num_index_points == 1
def _compute_covariance(self, index_points):
kernel_matrix = self.kernel.matrix(index_points, index_points)
if self._is_univariate_marginal(index_points):
# kernel_matrix thus has shape [..., 1, 1]; squeeze off the last dims and
# tack on the observation noise variance.
return (tf.squeeze(kernel_matrix, axis=[-2, -1]) +
self.observation_noise_variance)
else:
observation_noise_variance = tf.convert_to_tensor(
self.observation_noise_variance)
# We are compute K + obs_noise_variance * I. The shape of this matrix
# is going to be a broadcast of the shapes of K and obs_noise_variance *
# I.
broadcast_shape = distribution_util.get_broadcast_shape(
kernel_matrix,
# We pad with two single dimension since this represents a batch of
# scaled identity matrices.
observation_noise_variance[..., tf.newaxis, tf.newaxis])
kernel_matrix = tf.broadcast_to(kernel_matrix, broadcast_shape)
return _add_diagonal_shift(
kernel_matrix, observation_noise_variance[..., tf.newaxis])
def get_marginal_distribution(self, index_points=None):
"""Compute the marginal over function values at `index_points`.
Args:
index_points: `float` `Tensor` representing finite (batch of) vector(s) of
points in the index set over which the TP is defined. Shape has the form
`[b1, ..., bB, e, f1, ..., fF]` where `F` is the number of feature
dimensions and must equal `kernel.feature_ndims` and `e` is the number
(size) of index points in each batch. Ultimately this distribution
corresponds to a `e`-dimensional multivariate student t. The batch shape
must be broadcastable with `kernel.batch_shape` and any batch dims
yielded by `mean_fn`.
Returns:
marginal: a `StudentT` or `MultivariateStudentT` distribution,
according to whether `index_points` consists of one or many index
points, respectively.
"""
with self._name_and_control_scope('get_marginal_distribution'):
df = tf.convert_to_tensor(self.df)
index_points = self._get_index_points(index_points)
covariance = self._compute_covariance(index_points)
loc = self._mean_fn(index_points)
# If we're sure the number of index points is 1, we can just construct a
# scalar Normal. This has computational benefits and supports things like
# CDF that aren't otherwise straightforward to provide.
if self._is_univariate_marginal(index_points):
squared_scale = (df - 2.) / df * covariance
scale = tf.sqrt(squared_scale)
# `loc` has a trailing 1 in the shape; squeeze it.
loc = tf.squeeze(loc, axis=-1)
return student_t.StudentT(
df=df,
loc=loc,
scale=scale,
validate_args=self.validate_args,
allow_nan_stats=self.allow_nan_stats,
name='marginal_distribution')
else:
return self._marginal_fn(
df=df,
loc=loc,
covariance=covariance,
validate_args=self.validate_args,
allow_nan_stats=self.allow_nan_stats,
name='marginal_distribution')
@property
def df(self):
return self._df
@property
def observation_noise_variance(self):
return self._observation_noise_variance
@property
def mean_fn(self):
return self._mean_fn
@property
def kernel(self):
return self._kernel
@property
def index_points(self):
return self._index_points
@property
def marginal_fn(self):
return self._marginal_fn
@property
def jitter(self):
return self._jitter
def _get_index_points(self, index_points=None):
"""Return `index_points` if not None, else `self._index_points`.
Args:
index_points: if given, this is what is returned; else,
`self._index_points`
Returns:
index_points: the given arg, if not None, else the class member
`self._index_points`.
Rases:
ValueError: if `index_points` and `self._index_points` are both `None`.
"""
if self._index_points is None and index_points is None:
raise ValueError(
'This StudentTProcess instance was not instantiated with a value for '
'index_points. One must therefore be provided when calling sample, '
'log_prob, and other such methods.')
return (index_points if index_points is not None
else tf.convert_to_tensor(self._index_points))
def _log_prob(self, value, index_points=None):
return self.get_marginal_distribution(index_points).log_prob(value)
def _batch_shape_tensor(self, index_points=None):
index_points = self._get_index_points(index_points)
return functools.reduce(tf.broadcast_dynamic_shape, [
tf.shape(index_points)[:-(self.kernel.feature_ndims + 1)],
self.kernel.batch_shape_tensor(),
tf.shape(self.observation_noise_variance),
tf.shape(self.df)
])
def _batch_shape(self, index_points=None):
index_points = (
index_points if index_points is not None else self._index_points)
return functools.reduce(
tf.broadcast_static_shape,
[index_points.shape[:-(self.kernel.feature_ndims + 1)],
self.kernel.batch_shape,
self.observation_noise_variance.shape,
self.df.shape])
def _event_shape_tensor(self, index_points=None):
index_points = self._get_index_points(index_points)
if self._is_univariate_marginal(index_points):
return tf.constant([], dtype=tf.int32)
else:
# The examples index is one position to the left of the feature dims.
examples_index = -(self.kernel.feature_ndims + 1)
return tf.shape(index_points)[examples_index:examples_index + 1]
def _event_shape(self, index_points=None):
index_points = (
index_points if index_points is not None else self._index_points)
if self._is_univariate_marginal(index_points):
return tf.TensorShape([])
else:
# The examples index is one position to the left of the feature dims.
examples_index = -(self.kernel.feature_ndims + 1)
shape = index_points.shape[examples_index:examples_index + 1]
if tensorshape_util.rank(shape) is None:
return tf.TensorShape([None])
return shape
def _sample_n(self, n, seed=None, index_points=None):
return self.get_marginal_distribution(index_points).sample(n, seed=seed)
def _log_survival_function(self, value, index_points=None):
return self.get_marginal_distribution(
index_points).log_survival_function(value)
def _survival_function(self, value, index_points=None):
return self.get_marginal_distribution(index_points).survival_function(value)
def _log_cdf(self, value, index_points=None):
return self.get_marginal_distribution(index_points).log_cdf(value)
def _entropy(self, index_points=None):
return self.get_marginal_distribution(index_points).entropy()
def _mean(self, index_points=None):
return self.get_marginal_distribution(index_points).mean()
def _quantile(self, value, index_points=None):
return self.get_marginal_distribution(index_points).quantile(value)
def _stddev(self, index_points=None):
return tf.sqrt(self._variance(index_points=index_points))
def _variance(self, index_points=None):
index_points = self._get_index_points(index_points)
kernel_diag = self.kernel.apply(index_points, index_points, example_ndims=1)
if self._is_univariate_marginal(index_points):
return (tf.squeeze(kernel_diag, axis=[-1]) +
self.observation_noise_variance)
else:
# We are computing diag(K + obs_noise_variance * I) = diag(K) +
# obs_noise_variance. We pad obs_noise_variance with a dimension in order
# to broadcast batch shapes of kernel_diag and obs_noise_variance (since
# kernel_diag has an extra dimension corresponding to the number of index
# points).
return kernel_diag + self.observation_noise_variance[..., tf.newaxis]
def _covariance(self, index_points=None):
# Using the result of get_marginal_distribution would involve an extra
# matmul, and possibly even an unnecessary cholesky first. We can avoid that
# by going straight through the kernel function.
return self._compute_covariance(self._get_index_points(index_points))
def _mode(self, index_points=None):
return self.get_marginal_distribution(index_points).mode()
def _default_event_space_bijector(self):
return identity_bijector.Identity(validate_args=self.validate_args)
def _parameter_control_dependencies(self, is_init):
if not self.validate_args:
return []
assertions = []
if is_init != tensor_util.is_ref(self.df):
assertions.append(
assert_util.assert_greater(
self.df, dtype_util.as_numpy_dtype(self.df.dtype)(2.),
message='`df` must be greater than 2.'))
return assertions
|
#### Examples
|
policy_body_download_test.go
|
//go:build go1.16
// +build go1.16
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package runtime
import (
"context"
"io"
"net/http"
"testing"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/internal/shared"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/policy"
"github.com/Azure/azure-sdk-for-go/sdk/internal/mock"
)
func TestDownloadBody(t *testing.T)
|
func TestSkipBodyDownload(t *testing.T) {
const message = "not downloaded"
srv, close := mock.NewServer()
defer close()
srv.SetResponse(mock.WithBody([]byte(message)))
// download policy is automatically added during pipeline construction
pl := newTestPipeline(&policy.ClientOptions{Transport: srv})
req, err := NewRequest(context.Background(), http.MethodGet, srv.URL())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
SkipBodyDownload(req)
resp, err := pl.Do(req)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
payload, err := Payload(resp)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if string(payload) != message {
t.Fatalf("unexpected body: %s", string(payload))
}
}
func TestDownloadBodyFail(t *testing.T) {
srv, close := mock.NewServer()
defer close()
srv.SetResponse(mock.WithBodyReadError())
// download policy is automatically added during pipeline construction
pl := newTestPipeline(&policy.ClientOptions{
Transport: srv,
Retry: policy.RetryOptions{
RetryDelay: 10 * time.Millisecond,
},
})
req, err := NewRequest(context.Background(), http.MethodGet, srv.URL())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
resp, err := pl.Do(req)
if err == nil {
t.Fatal("unexpected nil error")
}
payload, err := Payload(resp)
if err == nil {
t.Fatalf("expected an error")
}
if payload != nil {
t.Fatal("expected nil payload")
}
}
func TestDownloadBodyWithRetryGet(t *testing.T) {
const message = "downloaded"
srv, close := mock.NewServer()
defer close()
srv.AppendResponse(mock.WithBodyReadError())
srv.AppendResponse(mock.WithBodyReadError())
srv.AppendResponse(mock.WithBody([]byte(message)))
// download policy is automatically added during pipeline construction
pl := newTestPipeline(&policy.ClientOptions{Retry: *testRetryOptions(), Transport: srv})
req, err := NewRequest(context.Background(), http.MethodGet, srv.URL())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
resp, err := pl.Do(req)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
payload, err := Payload(resp)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(payload) == 0 {
t.Fatal("missing payload")
}
if string(payload) != message {
t.Fatalf("unexpected response: %s", string(payload))
}
if r := srv.Requests(); r != 3 {
t.Fatalf("expected %d requests, got %d", 3, r)
}
}
func TestDownloadBodyWithRetryDelete(t *testing.T) {
const message = "downloaded"
srv, close := mock.NewServer()
defer close()
srv.AppendResponse(mock.WithBodyReadError())
srv.AppendResponse(mock.WithBodyReadError())
srv.AppendResponse(mock.WithBody([]byte(message)))
// download policy is automatically added during pipeline construction
pl := newTestPipeline(&policy.ClientOptions{Retry: *testRetryOptions(), Transport: srv})
req, err := NewRequest(context.Background(), http.MethodDelete, srv.URL())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
resp, err := pl.Do(req)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
payload, err := Payload(resp)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(payload) == 0 {
t.Fatal("missing payload")
}
if string(payload) != message {
t.Fatalf("unexpected response: %s", string(payload))
}
if r := srv.Requests(); r != 3 {
t.Fatalf("expected %d requests, got %d", 3, r)
}
}
func TestDownloadBodyWithRetryPut(t *testing.T) {
const message = "downloaded"
srv, close := mock.NewServer()
defer close()
srv.AppendResponse(mock.WithBodyReadError())
srv.AppendResponse(mock.WithBodyReadError())
srv.AppendResponse(mock.WithBody([]byte(message)))
// download policy is automatically added during pipeline construction
pl := newTestPipeline(&policy.ClientOptions{Retry: *testRetryOptions(), Transport: srv})
req, err := NewRequest(context.Background(), http.MethodPut, srv.URL())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
resp, err := pl.Do(req)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
payload, err := Payload(resp)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(payload) == 0 {
t.Fatal("missing payload")
}
if string(payload) != message {
t.Fatalf("unexpected response: %s", string(payload))
}
if r := srv.Requests(); r != 3 {
t.Fatalf("expected %d requests, got %d", 3, r)
}
}
func TestDownloadBodyWithRetryPatch(t *testing.T) {
const message = "downloaded"
srv, close := mock.NewServer()
defer close()
srv.AppendResponse(mock.WithBodyReadError())
srv.AppendResponse(mock.WithBodyReadError())
srv.AppendResponse(mock.WithBody([]byte(message)))
// download policy is automatically added during pipeline construction
pl := newTestPipeline(&policy.ClientOptions{Retry: *testRetryOptions(), Transport: srv})
req, err := NewRequest(context.Background(), http.MethodPatch, srv.URL())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
resp, err := pl.Do(req)
if err == nil {
t.Fatal("unexpected nil error")
}
if _, ok := err.(*bodyDownloadError); !ok {
t.Fatal("expected *bodyDownloadError type")
}
payload, err := Payload(resp)
if err == nil {
t.Fatalf("expected an error")
}
if len(payload) != 0 {
t.Fatal("unexpected payload")
}
// should be only one request, no retires
if r := srv.Requests(); r != 1 {
t.Fatalf("expected %d requests, got %d", 1, r)
}
}
func TestDownloadBodyWithRetryPost(t *testing.T) {
const message = "downloaded"
srv, close := mock.NewServer()
defer close()
srv.AppendResponse(mock.WithBodyReadError())
srv.AppendResponse(mock.WithBodyReadError())
srv.AppendResponse(mock.WithBody([]byte(message)))
// download policy is automatically added during pipeline construction
pl := newTestPipeline(&policy.ClientOptions{Retry: *testRetryOptions(), Transport: srv})
req, err := NewRequest(context.Background(), http.MethodPost, srv.URL())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
resp, err := pl.Do(req)
if err == nil {
t.Fatal("unexpected nil error")
}
payload, err := Payload(resp)
if err == nil {
t.Fatalf("expected an error")
}
if len(payload) != 0 {
t.Fatal("unexpected payload")
}
// should be only one request, no retires
if r := srv.Requests(); r != 1 {
t.Fatalf("expected %d requests, got %d", 1, r)
}
}
func TestSkipBodyDownloadWith400(t *testing.T) {
const message = "error should be downloaded"
srv, close := mock.NewServer()
defer close()
srv.SetResponse(mock.WithStatusCode(http.StatusBadRequest), mock.WithBody([]byte(message)))
// download policy is automatically added during pipeline construction
pl := newTestPipeline(&policy.ClientOptions{Transport: srv})
req, err := NewRequest(context.Background(), http.MethodGet, srv.URL())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
SkipBodyDownload(req)
resp, err := pl.Do(req)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
payload, err := Payload(resp)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(payload) == 0 {
t.Fatal("missing payload")
}
if string(payload) != message {
t.Fatalf("unexpected response: %s", string(payload))
}
}
func TestReadBodyAfterSeek(t *testing.T) {
const message = "downloaded"
srv, close := mock.NewServer()
defer close()
srv.AppendResponse(mock.WithBody([]byte(message)))
srv.AppendResponse(mock.WithBody([]byte(message)))
// download policy is automatically added during pipeline construction
pl := newTestPipeline(&policy.ClientOptions{Retry: *testRetryOptions(), Transport: srv})
req, err := NewRequest(context.Background(), http.MethodGet, srv.URL())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
resp, err := pl.Do(req)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
payload, err := Payload(resp)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if string(payload) != message {
t.Fatal("incorrect payload")
}
nb, ok := resp.Body.(*shared.NopClosingBytesReader)
if !ok {
t.Fatalf("unexpected body type: %t", resp.Body)
}
i, err := nb.Seek(0, io.SeekStart)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if i != 0 {
t.Fatalf("did not seek correctly")
}
i, err = nb.Seek(5, io.SeekCurrent)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if i != 5 {
t.Fatalf("did not seek correctly")
}
i, err = nb.Seek(5, io.SeekCurrent)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if i != 10 {
t.Fatalf("did not seek correctly")
}
}
|
{
const message = "downloaded"
srv, close := mock.NewServer()
defer close()
srv.SetResponse(mock.WithBody([]byte(message)))
// download policy is automatically added during pipeline construction
pl := newTestPipeline(&policy.ClientOptions{Transport: srv})
req, err := NewRequest(context.Background(), http.MethodGet, srv.URL())
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
resp, err := pl.Do(req)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
payload, err := Payload(resp)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(payload) == 0 {
t.Fatal("missing payload")
}
if string(payload) != message {
t.Fatalf("unexpected response: %s", string(payload))
}
}
|
spin_button.rs
|
// This file was generated by gir (https://github.com/gtk-rs/gir)
// from gir-files (https://github.com/gtk-rs/gir-files)
// DO NOT EDIT
use crate::Adjustment;
use crate::Align;
use crate::Buildable;
use crate::CellEditable;
use crate::Container;
use crate::Editable;
use crate::Entry;
use crate::EntryBuffer;
use crate::EntryCompletion;
use crate::InputHints;
use crate::InputPurpose;
use crate::Orientable;
use crate::Orientation;
use crate::ShadowType;
use crate::SpinButtonUpdatePolicy;
use crate::SpinType;
use crate::Widget;
use glib::object::Cast;
use glib::object::IsA;
use glib::signal::connect_raw;
use glib::signal::SignalHandlerId;
use glib::translate::*;
use glib::StaticType;
use glib::ToValue;
use std::boxed::Box as Box_;
use std::fmt;
use std::mem;
use std::mem::transmute;
glib::wrapper! {
pub struct SpinButton(Object<ffi::GtkSpinButton, ffi::GtkSpinButtonClass>) @extends Entry, Widget, @implements Buildable, CellEditable, Editable, Orientable;
match fn {
get_type => || ffi::gtk_spin_button_get_type(),
}
}
impl SpinButton {
#[doc(alias = "gtk_spin_button_new")]
pub fn new<P: IsA<Adjustment>>(
adjustment: Option<&P>,
climb_rate: f64,
digits: u32,
) -> SpinButton {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_spin_button_new(
adjustment.map(|p| p.as_ref()).to_glib_none().0,
climb_rate,
digits,
))
.unsafe_cast()
}
}
#[doc(alias = "gtk_spin_button_new_with_range")]
pub fn with_range(min: f64, max: f64, step: f64) -> SpinButton {
assert_initialized_main_thread!();
unsafe {
Widget::from_glib_none(ffi::gtk_spin_button_new_with_range(min, max, step))
.unsafe_cast()
}
}
}
#[derive(Clone, Default)]
pub struct SpinButtonBuilder {
adjustment: Option<Adjustment>,
climb_rate: Option<f64>,
digits: Option<u32>,
numeric: Option<bool>,
snap_to_ticks: Option<bool>,
update_policy: Option<SpinButtonUpdatePolicy>,
value: Option<f64>,
wrap: Option<bool>,
activates_default: Option<bool>,
attributes: Option<pango::AttrList>,
buffer: Option<EntryBuffer>,
caps_lock_warning: Option<bool>,
completion: Option<EntryCompletion>,
editable: Option<bool>,
enable_emoji_completion: Option<bool>,
has_frame: Option<bool>,
im_module: Option<String>,
input_hints: Option<InputHints>,
input_purpose: Option<InputPurpose>,
invisible_char: Option<u32>,
invisible_char_set: Option<bool>,
max_length: Option<i32>,
max_width_chars: Option<i32>,
overwrite_mode: Option<bool>,
placeholder_text: Option<String>,
populate_all: Option<bool>,
primary_icon_activatable: Option<bool>,
primary_icon_gicon: Option<gio::Icon>,
primary_icon_name: Option<String>,
primary_icon_pixbuf: Option<gdk_pixbuf::Pixbuf>,
primary_icon_sensitive: Option<bool>,
primary_icon_tooltip_markup: Option<String>,
primary_icon_tooltip_text: Option<String>,
progress_fraction: Option<f64>,
progress_pulse_step: Option<f64>,
secondary_icon_activatable: Option<bool>,
secondary_icon_gicon: Option<gio::Icon>,
secondary_icon_name: Option<String>,
secondary_icon_pixbuf: Option<gdk_pixbuf::Pixbuf>,
secondary_icon_sensitive: Option<bool>,
secondary_icon_tooltip_markup: Option<String>,
secondary_icon_tooltip_text: Option<String>,
shadow_type: Option<ShadowType>,
show_emoji_icon: Option<bool>,
tabs: Option<pango::TabArray>,
text: Option<String>,
truncate_multiline: Option<bool>,
visibility: Option<bool>,
width_chars: Option<i32>,
xalign: Option<f32>,
app_paintable: Option<bool>,
can_default: Option<bool>,
can_focus: Option<bool>,
events: Option<gdk::EventMask>,
expand: Option<bool>,
#[cfg(any(feature = "v3_20", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v3_20")))]
focus_on_click: Option<bool>,
halign: Option<Align>,
has_default: Option<bool>,
has_focus: Option<bool>,
has_tooltip: Option<bool>,
height_request: Option<i32>,
hexpand: Option<bool>,
hexpand_set: Option<bool>,
is_focus: Option<bool>,
margin: Option<i32>,
margin_bottom: Option<i32>,
margin_end: Option<i32>,
margin_start: Option<i32>,
margin_top: Option<i32>,
name: Option<String>,
no_show_all: Option<bool>,
opacity: Option<f64>,
parent: Option<Container>,
receives_default: Option<bool>,
sensitive: Option<bool>,
tooltip_markup: Option<String>,
tooltip_text: Option<String>,
valign: Option<Align>,
vexpand: Option<bool>,
vexpand_set: Option<bool>,
visible: Option<bool>,
width_request: Option<i32>,
editing_canceled: Option<bool>,
orientation: Option<Orientation>,
}
impl SpinButtonBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn build(self) -> SpinButton {
let mut properties: Vec<(&str, &dyn ToValue)> = vec![];
if let Some(ref adjustment) = self.adjustment {
properties.push(("adjustment", adjustment));
}
if let Some(ref climb_rate) = self.climb_rate {
properties.push(("climb-rate", climb_rate));
}
if let Some(ref digits) = self.digits {
properties.push(("digits", digits));
}
if let Some(ref numeric) = self.numeric {
properties.push(("numeric", numeric));
}
if let Some(ref snap_to_ticks) = self.snap_to_ticks {
properties.push(("snap-to-ticks", snap_to_ticks));
}
if let Some(ref update_policy) = self.update_policy {
properties.push(("update-policy", update_policy));
}
if let Some(ref value) = self.value {
properties.push(("value", value));
}
if let Some(ref wrap) = self.wrap {
properties.push(("wrap", wrap));
}
if let Some(ref activates_default) = self.activates_default {
properties.push(("activates-default", activates_default));
}
if let Some(ref attributes) = self.attributes {
properties.push(("attributes", attributes));
}
if let Some(ref buffer) = self.buffer {
properties.push(("buffer", buffer));
}
if let Some(ref caps_lock_warning) = self.caps_lock_warning {
properties.push(("caps-lock-warning", caps_lock_warning));
}
if let Some(ref completion) = self.completion {
properties.push(("completion", completion));
}
if let Some(ref editable) = self.editable {
properties.push(("editable", editable));
}
if let Some(ref enable_emoji_completion) = self.enable_emoji_completion {
properties.push(("enable-emoji-completion", enable_emoji_completion));
}
if let Some(ref has_frame) = self.has_frame {
properties.push(("has-frame", has_frame));
}
if let Some(ref im_module) = self.im_module {
properties.push(("im-module", im_module));
}
if let Some(ref input_hints) = self.input_hints {
properties.push(("input-hints", input_hints));
}
if let Some(ref input_purpose) = self.input_purpose {
properties.push(("input-purpose", input_purpose));
}
if let Some(ref invisible_char) = self.invisible_char {
properties.push(("invisible-char", invisible_char));
}
if let Some(ref invisible_char_set) = self.invisible_char_set {
properties.push(("invisible-char-set", invisible_char_set));
}
if let Some(ref max_length) = self.max_length {
properties.push(("max-length", max_length));
}
if let Some(ref max_width_chars) = self.max_width_chars {
properties.push(("max-width-chars", max_width_chars));
}
if let Some(ref overwrite_mode) = self.overwrite_mode {
properties.push(("overwrite-mode", overwrite_mode));
}
if let Some(ref placeholder_text) = self.placeholder_text {
properties.push(("placeholder-text", placeholder_text));
}
if let Some(ref populate_all) = self.populate_all {
properties.push(("populate-all", populate_all));
}
if let Some(ref primary_icon_activatable) = self.primary_icon_activatable {
properties.push(("primary-icon-activatable", primary_icon_activatable));
}
if let Some(ref primary_icon_gicon) = self.primary_icon_gicon {
properties.push(("primary-icon-gicon", primary_icon_gicon));
}
if let Some(ref primary_icon_name) = self.primary_icon_name {
properties.push(("primary-icon-name", primary_icon_name));
}
if let Some(ref primary_icon_pixbuf) = self.primary_icon_pixbuf {
properties.push(("primary-icon-pixbuf", primary_icon_pixbuf));
}
if let Some(ref primary_icon_sensitive) = self.primary_icon_sensitive {
properties.push(("primary-icon-sensitive", primary_icon_sensitive));
}
if let Some(ref primary_icon_tooltip_markup) = self.primary_icon_tooltip_markup {
properties.push(("primary-icon-tooltip-markup", primary_icon_tooltip_markup));
}
if let Some(ref primary_icon_tooltip_text) = self.primary_icon_tooltip_text {
properties.push(("primary-icon-tooltip-text", primary_icon_tooltip_text));
}
if let Some(ref progress_fraction) = self.progress_fraction {
properties.push(("progress-fraction", progress_fraction));
}
if let Some(ref progress_pulse_step) = self.progress_pulse_step {
properties.push(("progress-pulse-step", progress_pulse_step));
}
if let Some(ref secondary_icon_activatable) = self.secondary_icon_activatable {
properties.push(("secondary-icon-activatable", secondary_icon_activatable));
}
if let Some(ref secondary_icon_gicon) = self.secondary_icon_gicon {
properties.push(("secondary-icon-gicon", secondary_icon_gicon));
}
if let Some(ref secondary_icon_name) = self.secondary_icon_name {
properties.push(("secondary-icon-name", secondary_icon_name));
}
if let Some(ref secondary_icon_pixbuf) = self.secondary_icon_pixbuf {
properties.push(("secondary-icon-pixbuf", secondary_icon_pixbuf));
}
if let Some(ref secondary_icon_sensitive) = self.secondary_icon_sensitive {
properties.push(("secondary-icon-sensitive", secondary_icon_sensitive));
}
if let Some(ref secondary_icon_tooltip_markup) = self.secondary_icon_tooltip_markup {
properties.push((
"secondary-icon-tooltip-markup",
secondary_icon_tooltip_markup,
));
}
if let Some(ref secondary_icon_tooltip_text) = self.secondary_icon_tooltip_text {
properties.push(("secondary-icon-tooltip-text", secondary_icon_tooltip_text));
}
if let Some(ref shadow_type) = self.shadow_type {
properties.push(("shadow-type", shadow_type));
}
if let Some(ref show_emoji_icon) = self.show_emoji_icon {
properties.push(("show-emoji-icon", show_emoji_icon));
}
if let Some(ref tabs) = self.tabs {
properties.push(("tabs", tabs));
}
if let Some(ref text) = self.text {
properties.push(("text", text));
}
if let Some(ref truncate_multiline) = self.truncate_multiline {
properties.push(("truncate-multiline", truncate_multiline));
}
if let Some(ref visibility) = self.visibility {
properties.push(("visibility", visibility));
}
if let Some(ref width_chars) = self.width_chars {
properties.push(("width-chars", width_chars));
}
if let Some(ref xalign) = self.xalign {
properties.push(("xalign", xalign));
}
if let Some(ref app_paintable) = self.app_paintable {
properties.push(("app-paintable", app_paintable));
}
if let Some(ref can_default) = self.can_default {
properties.push(("can-default", can_default));
}
if let Some(ref can_focus) = self.can_focus {
properties.push(("can-focus", can_focus));
}
if let Some(ref events) = self.events {
properties.push(("events", events));
}
if let Some(ref expand) = self.expand {
properties.push(("expand", expand));
}
#[cfg(any(feature = "v3_20", feature = "dox"))]
if let Some(ref focus_on_click) = self.focus_on_click {
properties.push(("focus-on-click", focus_on_click));
}
if let Some(ref halign) = self.halign {
properties.push(("halign", halign));
}
if let Some(ref has_default) = self.has_default {
properties.push(("has-default", has_default));
}
if let Some(ref has_focus) = self.has_focus {
properties.push(("has-focus", has_focus));
}
if let Some(ref has_tooltip) = self.has_tooltip {
properties.push(("has-tooltip", has_tooltip));
}
if let Some(ref height_request) = self.height_request {
properties.push(("height-request", height_request));
}
if let Some(ref hexpand) = self.hexpand {
properties.push(("hexpand", hexpand));
}
if let Some(ref hexpand_set) = self.hexpand_set {
properties.push(("hexpand-set", hexpand_set));
}
if let Some(ref is_focus) = self.is_focus {
properties.push(("is-focus", is_focus));
}
if let Some(ref margin) = self.margin {
properties.push(("margin", margin));
}
if let Some(ref margin_bottom) = self.margin_bottom {
properties.push(("margin-bottom", margin_bottom));
}
if let Some(ref margin_end) = self.margin_end {
properties.push(("margin-end", margin_end));
}
if let Some(ref margin_start) = self.margin_start {
properties.push(("margin-start", margin_start));
}
if let Some(ref margin_top) = self.margin_top {
properties.push(("margin-top", margin_top));
}
if let Some(ref name) = self.name {
properties.push(("name", name));
}
if let Some(ref no_show_all) = self.no_show_all {
properties.push(("no-show-all", no_show_all));
}
if let Some(ref opacity) = self.opacity {
properties.push(("opacity", opacity));
}
if let Some(ref parent) = self.parent {
properties.push(("parent", parent));
}
if let Some(ref receives_default) = self.receives_default {
properties.push(("receives-default", receives_default));
}
if let Some(ref sensitive) = self.sensitive {
properties.push(("sensitive", sensitive));
}
if let Some(ref tooltip_markup) = self.tooltip_markup {
properties.push(("tooltip-markup", tooltip_markup));
}
if let Some(ref tooltip_text) = self.tooltip_text {
properties.push(("tooltip-text", tooltip_text));
}
if let Some(ref valign) = self.valign {
properties.push(("valign", valign));
}
if let Some(ref vexpand) = self.vexpand {
properties.push(("vexpand", vexpand));
}
if let Some(ref vexpand_set) = self.vexpand_set {
properties.push(("vexpand-set", vexpand_set));
}
if let Some(ref visible) = self.visible {
properties.push(("visible", visible));
}
if let Some(ref width_request) = self.width_request {
properties.push(("width-request", width_request));
}
if let Some(ref editing_canceled) = self.editing_canceled {
properties.push(("editing-canceled", editing_canceled));
}
if let Some(ref orientation) = self.orientation {
properties.push(("orientation", orientation));
}
let ret = glib::Object::new::<SpinButton>(&properties).expect("object new");
ret
}
pub fn adjustment<P: IsA<Adjustment>>(mut self, adjustment: &P) -> Self {
self.adjustment = Some(adjustment.clone().upcast());
self
}
pub fn climb_rate(mut self, climb_rate: f64) -> Self {
self.climb_rate = Some(climb_rate);
self
}
pub fn digits(mut self, digits: u32) -> Self {
self.digits = Some(digits);
self
}
pub fn numeric(mut self, numeric: bool) -> Self {
self.numeric = Some(numeric);
self
}
pub fn snap_to_ticks(mut self, snap_to_ticks: bool) -> Self {
self.snap_to_ticks = Some(snap_to_ticks);
self
}
pub fn update_policy(mut self, update_policy: SpinButtonUpdatePolicy) -> Self {
self.update_policy = Some(update_policy);
self
}
pub fn value(mut self, value: f64) -> Self {
self.value = Some(value);
self
}
pub fn wrap(mut self, wrap: bool) -> Self {
self.wrap = Some(wrap);
self
}
pub fn activates_default(mut self, activates_default: bool) -> Self {
self.activates_default = Some(activates_default);
self
}
pub fn attributes(mut self, attributes: &pango::AttrList) -> Self {
self.attributes = Some(attributes.clone());
self
}
pub fn buffer<P: IsA<EntryBuffer>>(mut self, buffer: &P) -> Self {
self.buffer = Some(buffer.clone().upcast());
self
}
pub fn caps_lock_warning(mut self, caps_lock_warning: bool) -> Self {
self.caps_lock_warning = Some(caps_lock_warning);
self
}
pub fn completion<P: IsA<EntryCompletion>>(mut self, completion: &P) -> Self {
self.completion = Some(completion.clone().upcast());
self
}
pub fn editable(mut self, editable: bool) -> Self {
self.editable = Some(editable);
self
}
pub fn enable_emoji_completion(mut self, enable_emoji_completion: bool) -> Self {
self.enable_emoji_completion = Some(enable_emoji_completion);
self
}
pub fn has_frame(mut self, has_frame: bool) -> Self {
self.has_frame = Some(has_frame);
self
}
pub fn im_module(mut self, im_module: &str) -> Self {
self.im_module = Some(im_module.to_string());
self
}
pub fn input_hints(mut self, input_hints: InputHints) -> Self {
self.input_hints = Some(input_hints);
self
}
pub fn input_purpose(mut self, input_purpose: InputPurpose) -> Self {
self.input_purpose = Some(input_purpose);
self
}
pub fn invisible_char(mut self, invisible_char: u32) -> Self {
self.invisible_char = Some(invisible_char);
self
}
pub fn invisible_char_set(mut self, invisible_char_set: bool) -> Self {
self.invisible_char_set = Some(invisible_char_set);
self
}
pub fn max_length(mut self, max_length: i32) -> Self {
self.max_length = Some(max_length);
self
}
pub fn max_width_chars(mut self, max_width_chars: i32) -> Self {
self.max_width_chars = Some(max_width_chars);
self
}
pub fn overwrite_mode(mut self, overwrite_mode: bool) -> Self {
self.overwrite_mode = Some(overwrite_mode);
self
}
pub fn placeholder_text(mut self, placeholder_text: &str) -> Self {
self.placeholder_text = Some(placeholder_text.to_string());
self
}
pub fn populate_all(mut self, populate_all: bool) -> Self {
self.populate_all = Some(populate_all);
self
}
pub fn primary_icon_activatable(mut self, primary_icon_activatable: bool) -> Self {
self.primary_icon_activatable = Some(primary_icon_activatable);
self
}
pub fn primary_icon_gicon<P: IsA<gio::Icon>>(mut self, primary_icon_gicon: &P) -> Self {
self.primary_icon_gicon = Some(primary_icon_gicon.clone().upcast());
self
}
pub fn primary_icon_name(mut self, primary_icon_name: &str) -> Self {
self.primary_icon_name = Some(primary_icon_name.to_string());
self
}
pub fn primary_icon_pixbuf(mut self, primary_icon_pixbuf: &gdk_pixbuf::Pixbuf) -> Self {
self.primary_icon_pixbuf = Some(primary_icon_pixbuf.clone());
self
}
pub fn primary_icon_sensitive(mut self, primary_icon_sensitive: bool) -> Self {
self.primary_icon_sensitive = Some(primary_icon_sensitive);
self
}
pub fn primary_icon_tooltip_markup(mut self, primary_icon_tooltip_markup: &str) -> Self {
self.primary_icon_tooltip_markup = Some(primary_icon_tooltip_markup.to_string());
self
}
pub fn primary_icon_tooltip_text(mut self, primary_icon_tooltip_text: &str) -> Self {
self.primary_icon_tooltip_text = Some(primary_icon_tooltip_text.to_string());
self
}
pub fn progress_fraction(mut self, progress_fraction: f64) -> Self {
self.progress_fraction = Some(progress_fraction);
self
}
pub fn progress_pulse_step(mut self, progress_pulse_step: f64) -> Self {
self.progress_pulse_step = Some(progress_pulse_step);
self
}
pub fn secondary_icon_activatable(mut self, secondary_icon_activatable: bool) -> Self {
self.secondary_icon_activatable = Some(secondary_icon_activatable);
self
}
pub fn secondary_icon_gicon<P: IsA<gio::Icon>>(mut self, secondary_icon_gicon: &P) -> Self {
self.secondary_icon_gicon = Some(secondary_icon_gicon.clone().upcast());
self
}
pub fn secondary_icon_name(mut self, secondary_icon_name: &str) -> Self {
self.secondary_icon_name = Some(secondary_icon_name.to_string());
self
}
pub fn secondary_icon_pixbuf(mut self, secondary_icon_pixbuf: &gdk_pixbuf::Pixbuf) -> Self {
self.secondary_icon_pixbuf = Some(secondary_icon_pixbuf.clone());
self
}
pub fn secondary_icon_sensitive(mut self, secondary_icon_sensitive: bool) -> Self {
self.secondary_icon_sensitive = Some(secondary_icon_sensitive);
self
}
pub fn secondary_icon_tooltip_markup(mut self, secondary_icon_tooltip_markup: &str) -> Self {
self.secondary_icon_tooltip_markup = Some(secondary_icon_tooltip_markup.to_string());
self
}
pub fn secondary_icon_tooltip_text(mut self, secondary_icon_tooltip_text: &str) -> Self {
self.secondary_icon_tooltip_text = Some(secondary_icon_tooltip_text.to_string());
self
}
pub fn shadow_type(mut self, shadow_type: ShadowType) -> Self {
self.shadow_type = Some(shadow_type);
self
}
pub fn show_emoji_icon(mut self, show_emoji_icon: bool) -> Self {
self.show_emoji_icon = Some(show_emoji_icon);
self
}
pub fn tabs(mut self, tabs: &pango::TabArray) -> Self {
self.tabs = Some(tabs.clone());
self
}
pub fn text(mut self, text: &str) -> Self {
self.text = Some(text.to_string());
self
}
pub fn truncate_multiline(mut self, truncate_multiline: bool) -> Self {
self.truncate_multiline = Some(truncate_multiline);
self
}
pub fn visibility(mut self, visibility: bool) -> Self {
self.visibility = Some(visibility);
self
}
pub fn width_chars(mut self, width_chars: i32) -> Self {
self.width_chars = Some(width_chars);
self
}
pub fn xalign(mut self, xalign: f32) -> Self {
self.xalign = Some(xalign);
self
}
pub fn app_paintable(mut self, app_paintable: bool) -> Self {
self.app_paintable = Some(app_paintable);
self
}
pub fn can_default(mut self, can_default: bool) -> Self {
self.can_default = Some(can_default);
self
}
pub fn can_focus(mut self, can_focus: bool) -> Self {
self.can_focus = Some(can_focus);
self
}
pub fn events(mut self, events: gdk::EventMask) -> Self {
self.events = Some(events);
self
}
pub fn expand(mut self, expand: bool) -> Self {
self.expand = Some(expand);
self
}
#[cfg(any(feature = "v3_20", feature = "dox"))]
#[cfg_attr(feature = "dox", doc(cfg(feature = "v3_20")))]
pub fn focus_on_click(mut self, focus_on_click: bool) -> Self {
self.focus_on_click = Some(focus_on_click);
self
}
pub fn halign(mut self, halign: Align) -> Self {
self.halign = Some(halign);
self
}
pub fn has_default(mut self, has_default: bool) -> Self {
self.has_default = Some(has_default);
self
}
pub fn has_focus(mut self, has_focus: bool) -> Self {
self.has_focus = Some(has_focus);
self
}
pub fn has_tooltip(mut self, has_tooltip: bool) -> Self {
self.has_tooltip = Some(has_tooltip);
self
}
pub fn height_request(mut self, height_request: i32) -> Self {
self.height_request = Some(height_request);
self
}
pub fn hexpand(mut self, hexpand: bool) -> Self {
self.hexpand = Some(hexpand);
self
}
pub fn hexpand_set(mut self, hexpand_set: bool) -> Self {
self.hexpand_set = Some(hexpand_set);
self
}
pub fn is_focus(mut self, is_focus: bool) -> Self {
self.is_focus = Some(is_focus);
self
}
pub fn margin(mut self, margin: i32) -> Self {
self.margin = Some(margin);
self
}
pub fn margin_bottom(mut self, margin_bottom: i32) -> Self {
self.margin_bottom = Some(margin_bottom);
self
}
pub fn margin_end(mut self, margin_end: i32) -> Self {
self.margin_end = Some(margin_end);
self
}
pub fn margin_start(mut self, margin_start: i32) -> Self {
self.margin_start = Some(margin_start);
self
}
pub fn margin_top(mut self, margin_top: i32) -> Self {
self.margin_top = Some(margin_top);
self
}
pub fn name(mut self, name: &str) -> Self {
self.name = Some(name.to_string());
self
}
pub fn no_show_all(mut self, no_show_all: bool) -> Self {
self.no_show_all = Some(no_show_all);
self
}
pub fn opacity(mut self, opacity: f64) -> Self {
self.opacity = Some(opacity);
self
}
pub fn parent<P: IsA<Container>>(mut self, parent: &P) -> Self {
self.parent = Some(parent.clone().upcast());
self
}
pub fn receives_default(mut self, receives_default: bool) -> Self {
self.receives_default = Some(receives_default);
self
}
pub fn sensitive(mut self, sensitive: bool) -> Self {
self.sensitive = Some(sensitive);
self
}
pub fn tooltip_markup(mut self, tooltip_markup: &str) -> Self {
self.tooltip_markup = Some(tooltip_markup.to_string());
self
}
pub fn tooltip_text(mut self, tooltip_text: &str) -> Self {
self.tooltip_text = Some(tooltip_text.to_string());
self
}
pub fn valign(mut self, valign: Align) -> Self
|
pub fn vexpand(mut self, vexpand: bool) -> Self {
self.vexpand = Some(vexpand);
self
}
pub fn vexpand_set(mut self, vexpand_set: bool) -> Self {
self.vexpand_set = Some(vexpand_set);
self
}
pub fn visible(mut self, visible: bool) -> Self {
self.visible = Some(visible);
self
}
pub fn width_request(mut self, width_request: i32) -> Self {
self.width_request = Some(width_request);
self
}
pub fn editing_canceled(mut self, editing_canceled: bool) -> Self {
self.editing_canceled = Some(editing_canceled);
self
}
pub fn orientation(mut self, orientation: Orientation) -> Self {
self.orientation = Some(orientation);
self
}
}
pub const NONE_SPIN_BUTTON: Option<&SpinButton> = None;
pub trait SpinButtonExt: 'static {
#[doc(alias = "gtk_spin_button_configure")]
fn configure<P: IsA<Adjustment>>(&self, adjustment: Option<&P>, climb_rate: f64, digits: u32);
#[doc(alias = "gtk_spin_button_get_adjustment")]
fn get_adjustment(&self) -> Adjustment;
#[doc(alias = "gtk_spin_button_get_digits")]
fn get_digits(&self) -> u32;
#[doc(alias = "gtk_spin_button_get_increments")]
fn get_increments(&self) -> (f64, f64);
#[doc(alias = "gtk_spin_button_get_numeric")]
fn get_numeric(&self) -> bool;
#[doc(alias = "gtk_spin_button_get_range")]
fn get_range(&self) -> (f64, f64);
#[doc(alias = "gtk_spin_button_get_snap_to_ticks")]
fn get_snap_to_ticks(&self) -> bool;
#[doc(alias = "gtk_spin_button_get_update_policy")]
fn get_update_policy(&self) -> SpinButtonUpdatePolicy;
#[doc(alias = "gtk_spin_button_get_value")]
fn get_value(&self) -> f64;
#[doc(alias = "gtk_spin_button_get_value_as_int")]
fn get_value_as_int(&self) -> i32;
#[doc(alias = "gtk_spin_button_get_wrap")]
fn get_wrap(&self) -> bool;
#[doc(alias = "gtk_spin_button_set_adjustment")]
fn set_adjustment<P: IsA<Adjustment>>(&self, adjustment: &P);
#[doc(alias = "gtk_spin_button_set_digits")]
fn set_digits(&self, digits: u32);
#[doc(alias = "gtk_spin_button_set_increments")]
fn set_increments(&self, step: f64, page: f64);
#[doc(alias = "gtk_spin_button_set_numeric")]
fn set_numeric(&self, numeric: bool);
#[doc(alias = "gtk_spin_button_set_range")]
fn set_range(&self, min: f64, max: f64);
#[doc(alias = "gtk_spin_button_set_snap_to_ticks")]
fn set_snap_to_ticks(&self, snap_to_ticks: bool);
#[doc(alias = "gtk_spin_button_set_update_policy")]
fn set_update_policy(&self, policy: SpinButtonUpdatePolicy);
#[doc(alias = "gtk_spin_button_set_value")]
fn set_value(&self, value: f64);
#[doc(alias = "gtk_spin_button_set_wrap")]
fn set_wrap(&self, wrap: bool);
#[doc(alias = "gtk_spin_button_spin")]
fn spin(&self, direction: SpinType, increment: f64);
#[doc(alias = "gtk_spin_button_update")]
fn update(&self);
fn get_property_climb_rate(&self) -> f64;
fn set_property_climb_rate(&self, climb_rate: f64);
fn connect_property_adjustment_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_climb_rate_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_digits_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_numeric_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_snap_to_ticks_notify<F: Fn(&Self) + 'static>(
&self,
f: F,
) -> SignalHandlerId;
fn connect_property_update_policy_notify<F: Fn(&Self) + 'static>(
&self,
f: F,
) -> SignalHandlerId;
fn connect_property_value_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
fn connect_property_wrap_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId;
}
impl<O: IsA<SpinButton>> SpinButtonExt for O {
fn configure<P: IsA<Adjustment>>(&self, adjustment: Option<&P>, climb_rate: f64, digits: u32) {
unsafe {
ffi::gtk_spin_button_configure(
self.as_ref().to_glib_none().0,
adjustment.map(|p| p.as_ref()).to_glib_none().0,
climb_rate,
digits,
);
}
}
fn get_adjustment(&self) -> Adjustment {
unsafe {
from_glib_none(ffi::gtk_spin_button_get_adjustment(
self.as_ref().to_glib_none().0,
))
}
}
fn get_digits(&self) -> u32 {
unsafe { ffi::gtk_spin_button_get_digits(self.as_ref().to_glib_none().0) }
}
fn get_increments(&self) -> (f64, f64) {
unsafe {
let mut step = mem::MaybeUninit::uninit();
let mut page = mem::MaybeUninit::uninit();
ffi::gtk_spin_button_get_increments(
self.as_ref().to_glib_none().0,
step.as_mut_ptr(),
page.as_mut_ptr(),
);
let step = step.assume_init();
let page = page.assume_init();
(step, page)
}
}
fn get_numeric(&self) -> bool {
unsafe {
from_glib(ffi::gtk_spin_button_get_numeric(
self.as_ref().to_glib_none().0,
))
}
}
fn get_range(&self) -> (f64, f64) {
unsafe {
let mut min = mem::MaybeUninit::uninit();
let mut max = mem::MaybeUninit::uninit();
ffi::gtk_spin_button_get_range(
self.as_ref().to_glib_none().0,
min.as_mut_ptr(),
max.as_mut_ptr(),
);
let min = min.assume_init();
let max = max.assume_init();
(min, max)
}
}
fn get_snap_to_ticks(&self) -> bool {
unsafe {
from_glib(ffi::gtk_spin_button_get_snap_to_ticks(
self.as_ref().to_glib_none().0,
))
}
}
fn get_update_policy(&self) -> SpinButtonUpdatePolicy {
unsafe {
from_glib(ffi::gtk_spin_button_get_update_policy(
self.as_ref().to_glib_none().0,
))
}
}
fn get_value(&self) -> f64 {
unsafe { ffi::gtk_spin_button_get_value(self.as_ref().to_glib_none().0) }
}
fn get_value_as_int(&self) -> i32 {
unsafe { ffi::gtk_spin_button_get_value_as_int(self.as_ref().to_glib_none().0) }
}
fn get_wrap(&self) -> bool {
unsafe {
from_glib(ffi::gtk_spin_button_get_wrap(
self.as_ref().to_glib_none().0,
))
}
}
fn set_adjustment<P: IsA<Adjustment>>(&self, adjustment: &P) {
unsafe {
ffi::gtk_spin_button_set_adjustment(
self.as_ref().to_glib_none().0,
adjustment.as_ref().to_glib_none().0,
);
}
}
fn set_digits(&self, digits: u32) {
unsafe {
ffi::gtk_spin_button_set_digits(self.as_ref().to_glib_none().0, digits);
}
}
fn set_increments(&self, step: f64, page: f64) {
unsafe {
ffi::gtk_spin_button_set_increments(self.as_ref().to_glib_none().0, step, page);
}
}
fn set_numeric(&self, numeric: bool) {
unsafe {
ffi::gtk_spin_button_set_numeric(self.as_ref().to_glib_none().0, numeric.to_glib());
}
}
fn set_range(&self, min: f64, max: f64) {
unsafe {
ffi::gtk_spin_button_set_range(self.as_ref().to_glib_none().0, min, max);
}
}
fn set_snap_to_ticks(&self, snap_to_ticks: bool) {
unsafe {
ffi::gtk_spin_button_set_snap_to_ticks(
self.as_ref().to_glib_none().0,
snap_to_ticks.to_glib(),
);
}
}
fn set_update_policy(&self, policy: SpinButtonUpdatePolicy) {
unsafe {
ffi::gtk_spin_button_set_update_policy(
self.as_ref().to_glib_none().0,
policy.to_glib(),
);
}
}
fn set_value(&self, value: f64) {
unsafe {
ffi::gtk_spin_button_set_value(self.as_ref().to_glib_none().0, value);
}
}
fn set_wrap(&self, wrap: bool) {
unsafe {
ffi::gtk_spin_button_set_wrap(self.as_ref().to_glib_none().0, wrap.to_glib());
}
}
fn spin(&self, direction: SpinType, increment: f64) {
unsafe {
ffi::gtk_spin_button_spin(
self.as_ref().to_glib_none().0,
direction.to_glib(),
increment,
);
}
}
fn update(&self) {
unsafe {
ffi::gtk_spin_button_update(self.as_ref().to_glib_none().0);
}
}
fn get_property_climb_rate(&self) -> f64 {
unsafe {
let mut value = glib::Value::from_type(<f64 as StaticType>::static_type());
glib::gobject_ffi::g_object_get_property(
self.to_glib_none().0 as *mut glib::gobject_ffi::GObject,
b"climb-rate\0".as_ptr() as *const _,
value.to_glib_none_mut().0,
);
value
.get()
.expect("Return Value for property `climb-rate` getter")
.unwrap()
}
}
fn set_property_climb_rate(&self, climb_rate: f64) {
unsafe {
glib::gobject_ffi::g_object_set_property(
self.to_glib_none().0 as *mut glib::gobject_ffi::GObject,
b"climb-rate\0".as_ptr() as *const _,
glib::Value::from(&climb_rate).to_glib_none().0,
);
}
}
fn connect_property_adjustment_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_adjustment_trampoline<P, F: Fn(&P) + 'static>(
this: *mut ffi::GtkSpinButton,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<SpinButton>,
{
let f: &F = &*(f as *const F);
f(&SpinButton::from_glib_borrow(this).unsafe_cast_ref())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::adjustment\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_adjustment_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
fn connect_property_climb_rate_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_climb_rate_trampoline<P, F: Fn(&P) + 'static>(
this: *mut ffi::GtkSpinButton,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<SpinButton>,
{
let f: &F = &*(f as *const F);
f(&SpinButton::from_glib_borrow(this).unsafe_cast_ref())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::climb-rate\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_climb_rate_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
fn connect_property_digits_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_digits_trampoline<P, F: Fn(&P) + 'static>(
this: *mut ffi::GtkSpinButton,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<SpinButton>,
{
let f: &F = &*(f as *const F);
f(&SpinButton::from_glib_borrow(this).unsafe_cast_ref())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::digits\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_digits_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
fn connect_property_numeric_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_numeric_trampoline<P, F: Fn(&P) + 'static>(
this: *mut ffi::GtkSpinButton,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<SpinButton>,
{
let f: &F = &*(f as *const F);
f(&SpinButton::from_glib_borrow(this).unsafe_cast_ref())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::numeric\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_numeric_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
fn connect_property_snap_to_ticks_notify<F: Fn(&Self) + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_snap_to_ticks_trampoline<P, F: Fn(&P) + 'static>(
this: *mut ffi::GtkSpinButton,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<SpinButton>,
{
let f: &F = &*(f as *const F);
f(&SpinButton::from_glib_borrow(this).unsafe_cast_ref())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::snap-to-ticks\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_snap_to_ticks_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
fn connect_property_update_policy_notify<F: Fn(&Self) + 'static>(
&self,
f: F,
) -> SignalHandlerId {
unsafe extern "C" fn notify_update_policy_trampoline<P, F: Fn(&P) + 'static>(
this: *mut ffi::GtkSpinButton,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<SpinButton>,
{
let f: &F = &*(f as *const F);
f(&SpinButton::from_glib_borrow(this).unsafe_cast_ref())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::update-policy\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_update_policy_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
fn connect_property_value_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_value_trampoline<P, F: Fn(&P) + 'static>(
this: *mut ffi::GtkSpinButton,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<SpinButton>,
{
let f: &F = &*(f as *const F);
f(&SpinButton::from_glib_borrow(this).unsafe_cast_ref())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::value\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_value_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
fn connect_property_wrap_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId {
unsafe extern "C" fn notify_wrap_trampoline<P, F: Fn(&P) + 'static>(
this: *mut ffi::GtkSpinButton,
_param_spec: glib::ffi::gpointer,
f: glib::ffi::gpointer,
) where
P: IsA<SpinButton>,
{
let f: &F = &*(f as *const F);
f(&SpinButton::from_glib_borrow(this).unsafe_cast_ref())
}
unsafe {
let f: Box_<F> = Box_::new(f);
connect_raw(
self.as_ptr() as *mut _,
b"notify::wrap\0".as_ptr() as *const _,
Some(transmute::<_, unsafe extern "C" fn()>(
notify_wrap_trampoline::<Self, F> as *const (),
)),
Box_::into_raw(f),
)
}
}
}
impl fmt::Display for SpinButton {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("SpinButton")
}
}
|
{
self.valign = Some(valign);
self
}
|
source.ts
|
import dxFeed from '@chainlink/dxfeed-adapter'
export const adapters: AdapterImplementation[] = [GenesisVolatility, XBTO, dxFeed]
export type Source = typeof adapters[number]['NAME']
|
import { AdapterImplementation } from '@chainlink/types'
// source adapters
import GenesisVolatility from '@chainlink/genesis-volatility-adapter'
import XBTO from '@chainlink/xbto-adapter'
|
|
controller_test.go
|
/*
Copyright 2018 The CDI Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package controller
import (
"context"
generrors "errors"
"fmt"
"reflect"
"time"
"kubevirt.io/controller-lifecycle-operator-sdk/pkg/sdk/callbacks"
sdkapi "kubevirt.io/controller-lifecycle-operator-sdk/pkg/sdk/api"
sdkr "kubevirt.io/controller-lifecycle-operator-sdk/pkg/sdk/reconciler"
. "github.com/onsi/ginkgo"
. "github.com/onsi/ginkgo/extensions/table"
. "github.com/onsi/gomega"
promv1 "github.com/coreos/prometheus-operator/pkg/apis/monitoring/v1"
routev1 "github.com/openshift/api/route/v1"
secv1 "github.com/openshift/api/security/v1"
conditions "github.com/openshift/custom-resource-status/conditions/v1"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
extv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/kubernetes/scheme"
"k8s.io/client-go/tools/record"
apiregistrationv1 "k8s.io/kube-aggregator/pkg/apis/apiregistration/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
fakeClient "sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
cdiv1 "kubevirt.io/containerized-data-importer-api/pkg/apis/core/v1beta1"
"kubevirt.io/containerized-data-importer/pkg/common"
clusterResources "kubevirt.io/containerized-data-importer/pkg/operator/resources/cluster"
namespaceResources "kubevirt.io/containerized-data-importer/pkg/operator/resources/namespaced"
utils "kubevirt.io/containerized-data-importer/pkg/operator/resources/utils"
)
const (
version = "v1.5.0"
cdiNamespace = "cdi"
configMapName = "cdi-config"
insecureRegistryConfigMap = "cdi-insecure-registries"
normalCreateSuccess = "Normal CreateResourceSuccess Successfully created resource"
normalCreateEnsured = "Normal CreateResourceSuccess Successfully ensured"
normalDeleteResourceSuccess = "Normal DeleteResourceSuccess Deleted deployment cdi-deployment successfully"
normalDeleteResourceSuccesWorker = "Normal DeleteResourceSuccess Deleted worker resources successfully"
)
type args struct {
cdi *cdiv1.CDI
client client.Client
reconciler *ReconcileCDI
}
func init() {
cdiv1.AddToScheme(scheme.Scheme)
extv1.AddToScheme(scheme.Scheme)
apiregistrationv1.AddToScheme(scheme.Scheme)
promv1.AddToScheme(scheme.Scheme)
secv1.Install(scheme.Scheme)
routev1.Install(scheme.Scheme)
}
type modifyResource func(toModify client.Object) (client.Object, client.Object, error)
type isModifySubject func(resource client.Object) bool
type isUpgraded func(postUpgradeObj client.Object, deisredObj client.Object) bool
type createUnusedObject func() (client.Object, error)
var _ = Describe("Controller", func() {
DescribeTable("check can create types", func(obj client.Object) {
client := createClient(obj)
_, err := getObject(client, obj)
Expect(err).ToNot(HaveOccurred())
},
Entry("CDI type", createCDI("cdi", "good uid")),
Entry("CDR type", &extv1.CustomResourceDefinition{ObjectMeta: metav1.ObjectMeta{Name: "crd"}}),
Entry("SSC type", &secv1.SecurityContextConstraints{ObjectMeta: metav1.ObjectMeta{Name: "scc"}}),
Entry("Route type", &routev1.Route{ObjectMeta: metav1.ObjectMeta{Name: "route"}}),
Entry("PromRule type", &promv1.PrometheusRule{ObjectMeta: metav1.ObjectMeta{Name: "rule"}}),
)
Describe("Deploying CDI", func() {
Context("CDI lifecycle", func() {
It("should get deployed", func() {
args := createArgs()
doReconcile(args)
setDeploymentsReady(args)
Expect(args.cdi.Status.OperatorVersion).Should(Equal(version))
Expect(args.cdi.Status.TargetVersion).Should(Equal(version))
Expect(args.cdi.Status.ObservedVersion).Should(Equal(version))
Expect(args.cdi.Status.Conditions).Should(HaveLen(3))
Expect(conditions.IsStatusConditionTrue(args.cdi.Status.Conditions, conditions.ConditionAvailable)).To(BeTrue())
Expect(conditions.IsStatusConditionFalse(args.cdi.Status.Conditions, conditions.ConditionProgressing)).To(BeTrue())
Expect(conditions.IsStatusConditionFalse(args.cdi.Status.Conditions, conditions.ConditionDegraded)).To(BeTrue())
Expect(args.cdi.Finalizers).Should(HaveLen(1))
validateEvents(args.reconciler, createReadyEventValidationMap())
})
It("should create configmap", func() {
args := createArgs()
doReconcile(args)
cm := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: cdiNamespace, Name: configMapName}}
obj, err := getObject(args.client, cm)
Expect(err).ToNot(HaveOccurred())
cm = obj.(*corev1.ConfigMap)
Expect(cm.OwnerReferences[0].UID).Should(Equal(args.cdi.UID))
validateEvents(args.reconciler, createNotReadyEventValidationMap())
})
It("should create prometheus service", func() {
args := createArgs()
doReconcile(args)
svc := &corev1.Service{ObjectMeta: metav1.ObjectMeta{Namespace: cdiNamespace, Name: common.PrometheusServiceName}}
obj, err := getObject(args.client, svc)
Expect(err).ToNot(HaveOccurred())
svc = obj.(*corev1.Service)
Expect(svc.OwnerReferences[0].UID).Should(Equal(args.cdi.UID))
})
It("should create requeue when configmap exists with another owner", func() {
cm := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: cdiNamespace,
Name: configMapName,
OwnerReferences: []metav1.OwnerReference{
{
APIVersion: cdiv1.SchemeGroupVersion.String(),
Kind: "CDI",
Name: "cdi",
UID: "badUID",
},
},
},
}
args := createArgs()
err := args.client.Create(context.TODO(), cm)
Expect(err).ToNot(HaveOccurred())
doReconcileRequeue(args)
})
It("should create requeue when configmap has deletion timestamp", func() {
t := metav1.Now()
cm := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Namespace: cdiNamespace,
Name: configMapName,
DeletionTimestamp: &t,
},
}
args := createArgs()
err := args.client.Create(context.TODO(), cm)
Expect(err).ToNot(HaveOccurred())
doReconcileRequeue(args)
})
It("should create requeue when a resource exists", func() {
args := createArgs()
resources, err := getAllResources(args.reconciler)
Expect(err).ToNot(HaveOccurred())
err = args.client.Create(context.TODO(), resources[0])
Expect(err).ToNot(HaveOccurred())
doReconcileRequeue(args)
})
It("should be in securitycontextconstraint", func() {
args := createArgs()
doReconcile(args)
Expect(setDeploymentsReady(args)).To(BeTrue())
scc := &secv1.SecurityContextConstraints{
ObjectMeta: metav1.ObjectMeta{
Name: "containerized-data-importer",
},
}
scc, err := getSCC(args.client, scc)
Expect(err).ToNot(HaveOccurred())
Expect(scc.Labels[common.AppKubernetesPartOfLabel]).To(Equal("testing"))
for _, eu := range []string{"system:serviceaccount:cdi:cdi-sa"} {
found := false
for _, au := range scc.Users {
if eu == au {
found = true
}
}
Expect(found).To(BeTrue())
}
validateEvents(args.reconciler, createReadyEventValidationMap())
})
It("should create all resources", func() {
args := createArgs()
doReconcile(args)
resources, err := getAllResources(args.reconciler)
Expect(err).ToNot(HaveOccurred())
for _, r := range resources {
_, err := getObject(args.client, r)
Expect(err).ToNot(HaveOccurred())
}
validateEvents(args.reconciler, createNotReadyEventValidationMap())
})
It("should become ready", func() {
args := createArgs()
doReconcile(args)
Expect(setDeploymentsReady(args)).To(BeTrue())
route := &routev1.Route{
ObjectMeta: metav1.ObjectMeta{
Name: uploadProxyRouteName,
Namespace: cdiNamespace,
},
}
obj, err := getObject(args.client, route)
Expect(err).To(BeNil())
route = obj.(*routev1.Route)
Expect(route.Spec.To.Kind).Should(Equal("Service"))
Expect(route.Spec.To.Name).Should(Equal(uploadProxyServiceName))
Expect(route.Spec.TLS.DestinationCACertificate).Should(Equal(testCertData))
Expect(route.Labels[common.AppKubernetesPartOfLabel]).To(Equal("testing"))
validateEvents(args.reconciler, createReadyEventValidationMap())
})
It("should have CDIOperatorDown", func() {
args := createArgs()
doReconcile(args)
Expect(setDeploymentsReady(args)).To(BeTrue())
rule := &promv1.PrometheusRule{
ObjectMeta: metav1.ObjectMeta{
Name: "prometheus-cdi-rules",
Namespace: cdiNamespace,
},
}
obj, err := getObject(args.client, rule)
Expect(err).ToNot(HaveOccurred())
rule = obj.(*promv1.PrometheusRule)
cdiDownAlert := promv1.Rule{
Alert: "CDIOperatorDown",
Expr: intstr.FromString("kubevirt_cdi_operator_up_total == 0"),
For: "5m",
Annotations: map[string]string{
"summary": "CDI operator is down",
"runbook_url": runbookURLBasePath + "CDIOperatorDown",
},
Labels: map[string]string{
"severity": "warning",
"kubernetes_operator_part_of": "kubevirt",
"kubernetes_operator_component": "containerized-data-importer",
},
}
Expect(rule.Spec.Groups[0].Rules).To(ContainElement(cdiDownAlert))
Expect(rule.Labels[common.AppKubernetesPartOfLabel]).To(Equal("testing"))
validateEvents(args.reconciler, createReadyEventValidationMap())
})
It("should create prometheus service monitor", func() {
args := createArgs()
doReconcile(args)
Expect(setDeploymentsReady(args)).To(BeTrue())
monitor := &promv1.ServiceMonitor{
ObjectMeta: metav1.ObjectMeta{
Name: "service-monitor-cdi",
Namespace: cdiNamespace,
},
}
obj, err := getObject(args.client, monitor)
Expect(err).ToNot(HaveOccurred())
monitor = obj.(*promv1.ServiceMonitor)
Expect(monitor.Spec.NamespaceSelector.MatchNames).To(ContainElement(cdiNamespace))
Expect(monitor.Labels[common.AppKubernetesPartOfLabel]).To(Equal("testing"))
validateEvents(args.reconciler, createReadyEventValidationMap())
})
It("should create prometheus rbac", func() {
args := createArgs()
doReconcile(args)
Expect(setDeploymentsReady(args)).To(BeTrue())
role := &rbacv1.Role{
ObjectMeta: metav1.ObjectMeta{
Name: "cdi-monitoring",
Namespace: cdiNamespace,
},
}
obj, err := getObject(args.client, role)
Expect(err).ToNot(HaveOccurred())
role = obj.(*rbacv1.Role)
roleBinding := &rbacv1.RoleBinding{
ObjectMeta: metav1.ObjectMeta{
Name: "cdi-monitoring",
Namespace: cdiNamespace,
},
}
obj, err = getObject(args.client, roleBinding)
Expect(err).ToNot(HaveOccurred())
roleBinding = obj.(*rbacv1.RoleBinding)
Expect(role.Rules[0].Resources).To(ContainElement("endpoints"))
Expect(roleBinding.Subjects[0].Name).To(Equal("prometheus-k8s"))
Expect(role.Labels[common.AppKubernetesPartOfLabel]).To(Equal("testing"))
Expect(roleBinding.Labels[common.AppKubernetesPartOfLabel]).To(Equal("testing"))
validateEvents(args.reconciler, createReadyEventValidationMap())
})
It("should reconcile configmap labels on update", func() {
args := createArgs()
doReconcile(args)
Expect(setDeploymentsReady(args)).To(BeTrue())
cm := &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: cdiNamespace, Name: configMapName}}
obj, err := getObject(args.client, cm)
cm = obj.(*corev1.ConfigMap)
Expect(err).ToNot(HaveOccurred())
Expect(cm.OwnerReferences[0].UID).Should(Equal(args.cdi.UID))
Expect(cm.Labels[common.AppKubernetesPartOfLabel]).To(Equal("testing"))
args.cdi.Labels[common.AppKubernetesPartOfLabel] = "newtesting"
err = args.client.Update(context.TODO(), args.cdi)
Expect(err).ToNot(HaveOccurred())
doReconcile(args)
cm = &corev1.ConfigMap{ObjectMeta: metav1.ObjectMeta{Namespace: cdiNamespace, Name: configMapName}}
obj, err = getObject(args.client, cm)
cm = obj.(*corev1.ConfigMap)
Expect(err).ToNot(HaveOccurred())
Expect(cm.Labels[common.AppKubernetesPartOfLabel]).To(Equal("newtesting"))
})
It("should set config authority", func() {
args := createArgs()
doReconcile(args)
cfg := &cdiv1.CDIConfig{
ObjectMeta: metav1.ObjectMeta{
Name: "config",
},
}
err := args.client.Create(context.TODO(), cfg)
Expect(err).ToNot(HaveOccurred())
Expect(setDeploymentsReady(args)).To(BeTrue())
cdi, err := getCDI(args.client, args.cdi)
Expect(err).ToNot(HaveOccurred())
_, ok := cdi.Annotations["cdi.kubevirt.io/configAuthority"]
Expect(ok).To(BeTrue())
Expect(cdi.Spec.Config).To(BeNil())
})
It("should set config authority (existing values)", func() {
args := createArgs()
doReconcile(args)
cfg := &cdiv1.CDIConfig{
ObjectMeta: metav1.ObjectMeta{
Name: "config",
},
Spec: cdiv1.CDIConfigSpec{
FeatureGates: []string{"foobar"},
},
}
err := args.client.Create(context.TODO(), cfg)
Expect(err).ToNot(HaveOccurred())
Expect(setDeploymentsReady(args)).To(BeTrue())
cdi, err := getCDI(args.client, args.cdi)
Expect(err).ToNot(HaveOccurred())
_, ok := cdi.Annotations["cdi.kubevirt.io/configAuthority"]
Expect(ok).To(BeTrue())
Expect(cdi.Spec.Config).To(Equal(&cfg.Spec))
})
It("can become become ready, un-ready, and ready again", func() {
var deployment *appsv1.Deployment
args := createArgs()
doReconcile(args)
resources, err := getAllResources(args.reconciler)
Expect(err).ToNot(HaveOccurred())
for _, r := range resources {
d, ok := r.(*appsv1.Deployment)
if !ok {
continue
}
dd, err := getDeployment(args.client, d)
Expect(err).ToNot(HaveOccurred())
dd.Status.Replicas = *dd.Spec.Replicas
dd.Status.ReadyReplicas = dd.Status.Replicas
err = args.client.Update(context.TODO(), dd)
Expect(err).ToNot(HaveOccurred())
}
doReconcile(args)
Expect(args.cdi.Status.Conditions).Should(HaveLen(3))
Expect(conditions.IsStatusConditionTrue(args.cdi.Status.Conditions, conditions.ConditionAvailable)).To(BeTrue())
Expect(conditions.IsStatusConditionFalse(args.cdi.Status.Conditions, conditions.ConditionProgressing)).To(BeTrue())
Expect(conditions.IsStatusConditionFalse(args.cdi.Status.Conditions, conditions.ConditionDegraded)).To(BeTrue())
for _, r := range resources {
var ok bool
deployment, ok = r.(*appsv1.Deployment)
if ok {
break
}
}
deployment, err = getDeployment(args.client, deployment)
Expect(err).ToNot(HaveOccurred())
deployment.Status.ReadyReplicas = 0
err = args.client.Update(context.TODO(), deployment)
Expect(err).ToNot(HaveOccurred())
doReconcile(args)
Expect(args.cdi.Status.Conditions).Should(HaveLen(3))
Expect(conditions.IsStatusConditionTrue(args.cdi.Status.Conditions, conditions.ConditionAvailable)).To(BeTrue())
Expect(conditions.IsStatusConditionFalse(args.cdi.Status.Conditions, conditions.ConditionProgressing)).To(BeTrue())
// Application should be degraded due to missing deployment pods (set to 0)
Expect(conditions.IsStatusConditionTrue(args.cdi.Status.Conditions, conditions.ConditionDegraded)).To(BeTrue())
deployment, err = getDeployment(args.client, deployment)
Expect(err).ToNot(HaveOccurred())
deployment.Status.ReadyReplicas = deployment.Status.Replicas
err = args.client.Update(context.TODO(), deployment)
Expect(err).ToNot(HaveOccurred())
doReconcile(args)
Expect(args.cdi.Status.Conditions).Should(HaveLen(3))
Expect(conditions.IsStatusConditionTrue(args.cdi.Status.Conditions, conditions.ConditionAvailable)).To(BeTrue())
Expect(conditions.IsStatusConditionFalse(args.cdi.Status.Conditions, conditions.ConditionProgressing)).To(BeTrue())
Expect(conditions.IsStatusConditionFalse(args.cdi.Status.Conditions, conditions.ConditionDegraded)).To(BeTrue())
validateEvents(args.reconciler, createReadyEventValidationMap())
})
It("does not modify insecure registry configmap", func() {
args := createArgs()
doReconcile(args)
cm := &corev1.ConfigMap{
ObjectMeta: metav1.ObjectMeta{
Name: insecureRegistryConfigMap,
Namespace: cdiNamespace,
},
}
obj, err := getObject(args.client, cm)
Expect(err).To(BeNil())
cm = obj.(*corev1.ConfigMap)
if cm.Data == nil {
cm.Data = make(map[string]string)
}
data := cm.Data
data["foo.bar.com"] = ""
err = args.client.Update(context.TODO(), cm)
Expect(err).To(BeNil())
doReconcile(args)
obj, err = getObject(args.client, cm)
Expect(err).To(BeNil())
cm = obj.(*corev1.ConfigMap)
Expect(cm.Data).Should(Equal(data))
validateEvents(args.reconciler, createNotReadyEventValidationMap())
})
It("should be an error when creating another CDI instance", func() {
args := createArgs()
doReconcile(args)
newInstance := createCDI("bad", "bad")
err := args.client.Create(context.TODO(), newInstance)
Expect(err).ToNot(HaveOccurred())
result, err := args.reconciler.Reconcile(context.TODO(), reconcileRequest(newInstance.Name))
Expect(err).ToNot(HaveOccurred())
Expect(result.Requeue).To(BeFalse())
newInstance, err = getCDI(args.client, newInstance)
Expect(err).ToNot(HaveOccurred())
Expect(newInstance.Status.Phase).Should(Equal(sdkapi.PhaseError))
Expect(newInstance.Status.Conditions).Should(HaveLen(3))
Expect(conditions.IsStatusConditionFalse(newInstance.Status.Conditions, conditions.ConditionAvailable)).To(BeTrue())
Expect(conditions.IsStatusConditionFalse(newInstance.Status.Conditions, conditions.ConditionProgressing)).To(BeTrue())
Expect(conditions.IsStatusConditionTrue(newInstance.Status.Conditions, conditions.ConditionDegraded)).To(BeTrue())
validateEvents(args.reconciler, createErrorCDIEventValidationMap())
})
It("should succeed when we delete CDI", func() {
// create rando pod that should get deleted
pod := &corev1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: "foo",
Namespace: "default",
Labels: map[string]string{
"cdi.kubevirt.io": "cdi-upload-server",
},
},
}
args := createArgs()
doReconcile(args)
err := args.client.Create(context.TODO(), pod)
Expect(err).ToNot(HaveOccurred())
args.cdi.DeletionTimestamp = &metav1.Time{Time: time.Now()}
err = args.client.Update(context.TODO(), args.cdi)
Expect(err).ToNot(HaveOccurred())
doReconcileExpectDelete(args)
_, err = getObject(args.client, pod)
Expect(errors.IsNotFound(err)).To(BeTrue())
validateEvents(args.reconciler, createDeleteCDIEventValidationMap())
})
})
})
DescribeTable("should allow override", func(o cdiOverride) {
args := createArgs()
o.Set(args.cdi)
err := args.client.Update(context.TODO(), args.cdi)
Expect(err).ToNot(HaveOccurred())
doReconcile(args)
resources, err := getAllResources(args.reconciler)
Expect(err).ToNot(HaveOccurred())
for _, r := range resources {
d, ok := r.(*appsv1.Deployment)
if !ok {
continue
}
d, err = getDeployment(args.client, d)
Expect(err).ToNot(HaveOccurred())
o.Check(d)
}
validateEvents(args.reconciler, createNotReadyEventValidationMap())
},
Entry("Pull override", &pullOverride{corev1.PullNever}),
)
Describe("Upgrading CDI", func() {
DescribeTable("check detects upgrade correctly", func(prevVersion, newVersion string, shouldUpgrade, shouldError bool) {
//verify on int version is set
args := createFromArgs(newVersion)
doReconcile(args)
setDeploymentsReady(args)
Expect(args.cdi.Status.ObservedVersion).Should(Equal(newVersion))
Expect(args.cdi.Status.OperatorVersion).Should(Equal(newVersion))
Expect(args.cdi.Status.TargetVersion).Should(Equal(newVersion))
Expect(args.cdi.Status.Phase).Should(Equal(sdkapi.PhaseDeployed))
//Modify CRD to be of previousVersion
err := crSetVersion(args.reconciler.reconciler, args.cdi, prevVersion)
Expect(err).ToNot(HaveOccurred())
if shouldError {
doReconcileError(args)
return
}
setDeploymentsDegraded(args)
doReconcile(args)
if shouldUpgrade {
//verify upgraded has started
Expect(args.cdi.Status.OperatorVersion).Should(Equal(newVersion))
Expect(args.cdi.Status.ObservedVersion).Should(Equal(prevVersion))
Expect(args.cdi.Status.TargetVersion).Should(Equal(newVersion))
Expect(args.cdi.Status.Phase).Should(Equal(sdkapi.PhaseUpgrading))
} else {
//verify upgraded hasn't started
Expect(args.cdi.Status.OperatorVersion).Should(Equal(prevVersion))
Expect(args.cdi.Status.ObservedVersion).Should(Equal(prevVersion))
Expect(args.cdi.Status.TargetVersion).Should(Equal(prevVersion))
Expect(args.cdi.Status.Phase).Should(Equal(sdkapi.PhaseDeployed))
}
//change deployment to ready
isReady := setDeploymentsReady(args)
Expect(isReady).Should(Equal(true))
//now should be upgraded
if shouldUpgrade {
//verify versions were updated
Expect(args.cdi.Status.Phase).Should(Equal(sdkapi.PhaseDeployed))
Expect(args.cdi.Status.OperatorVersion).Should(Equal(newVersion))
Expect(args.cdi.Status.TargetVersion).Should(Equal(newVersion))
Expect(args.cdi.Status.ObservedVersion).Should(Equal(newVersion))
} else {
//verify versions remained unchaged
Expect(args.cdi.Status.Phase).Should(Equal(sdkapi.PhaseDeployed))
Expect(args.cdi.Status.OperatorVersion).Should(Equal(prevVersion))
Expect(args.cdi.Status.TargetVersion).Should(Equal(prevVersion))
Expect(args.cdi.Status.ObservedVersion).Should(Equal(prevVersion))
}
},
Entry("increasing semver ", "v1.9.5", "v1.10.0", true, false),
Entry("decreasing semver", "v1.10.0", "v1.9.5", false, true),
Entry("identical semver", "v1.10.0", "v1.10.0", false, false),
Entry("invalid semver", "devel", "v1.9.5", true, false),
Entry("increasing semver no prefix", "1.9.5", "1.10.0", true, false),
Entry("decreasing semver no prefix", "1.10.0", "1.9.5", false, true),
Entry("identical semver no prefix", "1.10.0", "1.10.0", false, false),
Entry("invalid semver with prefix", "devel1.9.5", "devel1.9.5", false, false),
Entry("invalid semver no prefix", "devel", "1.9.5", true, false),
/* having trouble making sense of this test "" should not be valid previous version
Entry("no current no prefix", "", "invalid", false, false),
*/
)
It("check detects upgrade w/o prev version", func() {
prevVersion := ""
newVersion := "v1.2.3"
args := createFromArgs(prevVersion)
doReconcile(args)
setDeploymentsReady(args)
Expect(args.cdi.Status.ObservedVersion).To(BeEmpty())
Expect(args.cdi.Status.OperatorVersion).To(BeEmpty())
Expect(args.cdi.Status.TargetVersion).To(BeEmpty())
Expect(args.cdi.Status.Phase).Should(Equal(sdkapi.PhaseDeployed))
args.reconciler.namespacedArgs.OperatorVersion = newVersion
setDeploymentsDegraded(args)
doReconcile(args)
Expect(args.cdi.Status.ObservedVersion).To(BeEmpty())
Expect(args.cdi.Status.OperatorVersion).Should(Equal(newVersion))
Expect(args.cdi.Status.TargetVersion).Should(Equal(newVersion))
Expect(args.cdi.Status.Phase).Should(Equal(sdkapi.PhaseUpgrading))
//change deployment to ready
isReady := setDeploymentsReady(args)
Expect(isReady).To(BeTrue())
Expect(args.cdi.Status.ObservedVersion).Should(Equal(newVersion))
Expect(args.cdi.Status.OperatorVersion).Should(Equal(newVersion))
Expect(args.cdi.Status.TargetVersion).Should(Equal(newVersion))
Expect(args.cdi.Status.Phase).Should(Equal(sdkapi.PhaseDeployed))
})
Describe("CDI CR deletion during upgrade", func() {
Context("cr deletion during upgrade", func() {
It("should delete CR if it is marked for deletion and not begin upgrade flow", func() {
newVersion := "1.10.0"
prevVersion := "1.9.5"
args := createFromArgs(newVersion)
doReconcile(args)
//set deployment to ready
isReady := setDeploymentsReady(args)
Expect(isReady).Should(Equal(true))
//verify on int version is set
Expect(args.cdi.Status.Phase).Should(Equal(sdkapi.PhaseDeployed))
//Modify CRD to be of previousVersion
crSetVersion(args.reconciler.reconciler, args.cdi, prevVersion)
//marc CDI CR for deltetion
args.cdi.SetDeletionTimestamp(&metav1.Time{Time: time.Now()})
args.cdi.Finalizers = append(args.cdi.Finalizers, "keepmearound")
err := args.client.Update(context.TODO(), args.cdi)
Expect(err).ToNot(HaveOccurred())
doReconcile(args)
//verify the version cr is deleted and upgrade hasn't started
Expect(args.cdi.Status.OperatorVersion).Should(Equal(prevVersion))
Expect(args.cdi.Status.ObservedVersion).Should(Equal(prevVersion))
Expect(args.cdi.Status.TargetVersion).Should(Equal(prevVersion))
Expect(args.cdi.Status.Phase).Should(Equal(sdkapi.PhaseDeleted))
})
It("should delete CR if it is marked for deletion during upgrade flow", func() {
newVersion := "1.10.0"
prevVersion := "1.9.5"
args := createFromArgs(newVersion)
doReconcile(args)
setDeploymentsReady(args)
//verify on int version is set
Expect(args.cdi.Status.Phase).Should(Equal(sdkapi.PhaseDeployed))
//Modify CRD to be of previousVersion
crSetVersion(args.reconciler.reconciler, args.cdi, prevVersion)
err := args.client.Update(context.TODO(), args.cdi)
Expect(err).ToNot(HaveOccurred())
setDeploymentsDegraded(args)
//begin upgrade
doReconcile(args)
//mark CDI CR for deltetion
args.cdi.SetDeletionTimestamp(&metav1.Time{Time: time.Now()})
err = args.client.Update(context.TODO(), args.cdi)
Expect(err).ToNot(HaveOccurred())
doReconcileExpectDelete(args)
//verify events, this should include an upgrade event
match := createDeleteCDIAfterReadyEventValidationMap()
match["Normal UpgradeStarted Started upgrade to version 1.10.0"] = false
validateEvents(args.reconciler, match)
})
})
})
DescribeTable("Updates objects on upgrade", func(
modify modifyResource,
tomodify isModifySubject,
upgraded isUpgraded) {
newVersion := "1.10.0"
prevVersion := "1.9.5"
args := createFromArgs(newVersion)
doReconcile(args)
setDeploymentsReady(args)
//verify on int version is set
Expect(args.cdi.Status.Phase).Should(Equal(sdkapi.PhaseDeployed))
//Modify CRD to be of previousVersion
crSetVersion(args.reconciler.reconciler, args.cdi, prevVersion)
err := args.client.Update(context.TODO(), args.cdi)
Expect(err).ToNot(HaveOccurred())
setDeploymentsDegraded(args)
//find the resource to modify
oOriginal, oModified, err := getModifiedResource(args.reconciler, modify, tomodify)
Expect(err).ToNot(HaveOccurred())
//update object via client, with curObject
err = args.client.Update(context.TODO(), oModified)
Expect(err).ToNot(HaveOccurred())
//verify object is modified
storedObj, err := getObject(args.client, oModified)
Expect(err).ToNot(HaveOccurred())
Expect(reflect.DeepEqual(storedObj, oModified)).Should(Equal(true))
doReconcile(args)
//verify upgraded has started
Expect(args.cdi.Status.Phase).Should(Equal(sdkapi.PhaseUpgrading))
//change deployment to ready
isReady := setDeploymentsReady(args)
Expect(isReady).Should(Equal(true))
doReconcile(args)
Expect(args.cdi.Status.Phase).Should(Equal(sdkapi.PhaseDeployed))
//verify that stored object equals to object in getResources
storedObj, err = getObject(args.client, oModified)
Expect(err).ToNot(HaveOccurred())
Expect(upgraded(storedObj, oOriginal)).Should(Equal(true))
},
//Deployment update
Entry("verify - deployment updated on upgrade - annotation changed",
func(toModify client.Object) (client.Object, client.Object, error) { //Modify
deploymentOrig, ok := toModify.(*appsv1.Deployment)
if !ok {
return toModify, toModify, generrors.New("wrong type")
}
deployment := deploymentOrig.DeepCopy()
deployment.Annotations["fake.anno.1"] = "fakeannotation1"
deployment.Annotations["fake.anno.2"] = "fakeannotation2"
deployment.Annotations["fake.anno.3"] = "fakeannotation3"
return toModify, deployment, nil
},
func(resource client.Object) bool { //find resource for test
//return true if object is the one we want to test
_, ok := resource.(*appsv1.Deployment)
return ok
},
func(postUpgradeObj client.Object, deisredObj client.Object) bool { //check resource was upgraded
//return true if postUpgrade has teh same fields as desired
postDep, ok := postUpgradeObj.(*appsv1.Deployment)
if !ok {
return false
}
desiredDep, ok := deisredObj.(*appsv1.Deployment)
if !ok {
return false
}
delete(desiredDep.Annotations, LastAppliedConfigAnnotation)
for key, ann := range desiredDep.Annotations {
if postDep.Annotations[key] != ann {
return false
}
}
return len(desiredDep.Annotations) <= len(postDep.Annotations)
}),
Entry("verify - deployment updated on upgrade - labels changed",
func(toModify client.Object) (client.Object, client.Object, error) { //Modify
deploymentOrig, ok := toModify.(*appsv1.Deployment)
if !ok {
return toModify, toModify, generrors.New("wrong type")
}
deployment := deploymentOrig.DeepCopy()
deployment.Labels["fake.label.1"] = "fakelabel1"
deployment.Labels["fake.label.2"] = "fakelabel2"
deployment.Labels["fake.label.3"] = "fakelabel3"
return toModify, deployment, nil
},
func(resource client.Object) bool { //find resource for test
//return true if object is the one we want to test
_, ok := resource.(*appsv1.Deployment)
return ok
},
func(postUpgradeObj client.Object, deisredObj client.Object) bool { //check resource was upgraded
//return true if postUpgrade has teh same fields as desired
postDep, ok := postUpgradeObj.(*appsv1.Deployment)
if !ok {
return false
}
desiredDep, ok := deisredObj.(*appsv1.Deployment)
if !ok {
return false
}
for key, label := range desiredDep.Labels {
if postDep.Labels[key] != label {
return false
}
}
return len(desiredDep.Labels) <= len(postDep.Labels)
}),
Entry("verify - deployment updated on upgrade - deployment spec changed - modify container",
func(toModify client.Object) (client.Object, client.Object, error) { //Modify
deploymentOrig, ok := toModify.(*appsv1.Deployment)
if !ok {
return toModify, toModify, generrors.New("wrong type")
}
deployment := deploymentOrig.DeepCopy()
containers := deployment.Spec.Template.Spec.Containers
containers[0].Env = []corev1.EnvVar{
{
Name: "FAKE_ENVVAR",
Value: fmt.Sprintf("%s/%s:%s", "fake_repo", "importerImage", "tag"),
},
}
return toModify, deployment, nil
},
func(resource client.Object) bool { //find resource for test
//search for cdi-deployment - to test ENV virables change
deployment, ok := resource.(*appsv1.Deployment)
if !ok {
return false
}
if deployment.Name == "cdi-deployment" {
return true
}
return false
},
func(postUpgradeObj client.Object, deisredObj client.Object) bool { //check resource was upgraded
//return true if postUpgrade has teh same fields as desired
postDep, ok := postUpgradeObj.(*appsv1.Deployment)
if !ok {
return false
}
desiredDep, ok := deisredObj.(*appsv1.Deployment)
if !ok {
return false
}
for key, envVar := range desiredDep.Spec.Template.Spec.Containers[0].Env {
if postDep.Spec.Template.Spec.Containers[0].Env[key].Name != envVar.Name {
return false
}
}
return len(desiredDep.Spec.Template.Spec.Containers[0].Env) == len(postDep.Spec.Template.Spec.Containers[0].Env)
}),
Entry("verify - deployment updated on upgrade - deployment spec changed - add new container",
func(toModify client.Object) (client.Object, client.Object, error) { //Modify
deploymentOrig, ok := toModify.(*appsv1.Deployment)
if !ok {
return toModify, toModify, generrors.New("wrong type")
}
deployment := deploymentOrig.DeepCopy()
containers := deployment.Spec.Template.Spec.Containers
container := corev1.Container{
Name: "FAKE_CONTAINER",
Image: fmt.Sprintf("%s/%s:%s", "fake-repo", "fake-image", "fake-tag"),
ImagePullPolicy: "FakePullPolicy",
Args: []string{"-v=10"},
}
deployment.Spec.Template.Spec.Containers = append(containers, container)
return toModify, deployment, nil
},
func(resource client.Object) bool { //find resource for test
//search for cdi-deployment - to test container change
deployment, ok := resource.(*appsv1.Deployment)
if !ok {
return false
}
if deployment.Name == "cdi-deployment" {
return true
}
return false
},
func(postUpgradeObj client.Object, deisredObj client.Object) bool { //check resource was upgraded
//return true if postUpgrade has teh same fields as desired
postDep, ok := postUpgradeObj.(*appsv1.Deployment)
if !ok {
return false
}
desiredDep, ok := deisredObj.(*appsv1.Deployment)
if !ok {
return false
}
for key, container := range desiredDep.Spec.Template.Spec.Containers {
if postDep.Spec.Template.Spec.Containers[key].Name != container.Name {
return false
}
}
return len(desiredDep.Spec.Template.Spec.Containers) <= len(postDep.Spec.Template.Spec.Containers)
}),
Entry("verify - deployment updated on upgrade - deployment spec changed - remove existing container",
func(toModify client.Object) (client.Object, client.Object, error) { //Modify
deploymentOrig, ok := toModify.(*appsv1.Deployment)
if !ok {
return toModify, toModify, generrors.New("wrong type")
}
deployment := deploymentOrig.DeepCopy()
deployment.Spec.Template.Spec.Containers = nil
return toModify, deployment, nil
},
func(resource client.Object) bool { //find resource for test
//search for cdi-deployment - to test container change
deployment, ok := resource.(*appsv1.Deployment)
if !ok {
return false
}
if deployment.Name == "cdi-deployment" {
return true
}
return false
},
func(postUpgradeObj client.Object, deisredObj client.Object) bool { //check resource was upgraded
//return true if postUpgrade has teh same fields as desired
postDep, ok := postUpgradeObj.(*appsv1.Deployment)
if !ok {
return false
}
desiredDep, ok := deisredObj.(*appsv1.Deployment)
if !ok {
return false
}
return (len(postDep.Spec.Template.Spec.Containers) == len(desiredDep.Spec.Template.Spec.Containers))
}),
//Services update
Entry("verify - services updated on upgrade - annotation changed",
func(toModify client.Object) (client.Object, client.Object, error) { //Modify
serviceOrig, ok := toModify.(*corev1.Service)
if !ok {
return toModify, toModify, generrors.New("wrong type")
}
service := serviceOrig.DeepCopy()
service.Annotations["fake.anno.1"] = "fakeannotation1"
service.Annotations["fake.anno.2"] = "fakeannotation2"
service.Annotations["fake.anno.3"] = "fakeannotation3"
return toModify, service, nil
},
func(resource client.Object) bool { //find resource for test
//return true if object is the one we want to test
_, ok := resource.(*corev1.Service)
return ok
},
func(postUpgradeObj client.Object, deisredObj client.Object) bool { //check resource was upgraded
//return true if postUpgrade has teh same fields as desired
post, ok := postUpgradeObj.(*corev1.Service)
if !ok {
return false
}
desired, ok := deisredObj.(*corev1.Service)
if !ok {
return false
}
for key, ann := range desired.Annotations {
if post.Annotations[key] != ann {
return false
}
}
return len(desired.Annotations) <= len(post.Annotations)
}),
Entry("verify - services updated on upgrade - label changed",
func(toModify client.Object) (client.Object, client.Object, error) { //Modify
serviceOrig, ok := toModify.(*corev1.Service)
if !ok {
return toModify, toModify, generrors.New("wrong type")
}
service := serviceOrig.DeepCopy()
service.Labels["fake.label.1"] = "fakelabel1"
service.Labels["fake.label.2"] = "fakelabel2"
service.Labels["fake.label.3"] = "fakelabel3"
return toModify, service, nil
},
func(resource client.Object) bool { //find resource for test
//return true if object is the one we want to test
_, ok := resource.(*corev1.Service)
return ok
},
func(postUpgradeObj client.Object, deisredObj client.Object) bool { //check resource was upgraded
//return true if postUpgrade has the same fields as desired
post, ok := postUpgradeObj.(*corev1.Service)
if !ok {
return false
}
desired, ok := deisredObj.(*corev1.Service)
if !ok {
return false
}
for key, label := range desired.Labels {
if post.Labels[key] != label {
return false
}
}
return len(desired.Labels) <= len(post.Labels)
}),
Entry("verify - services updated on upgrade - service port changed",
func(toModify client.Object) (client.Object, client.Object, error) { //Modify
serviceOrig, ok := toModify.(*corev1.Service)
if !ok {
return toModify, toModify, generrors.New("wrong type")
}
service := serviceOrig.DeepCopy()
service.Spec.Ports = []corev1.ServicePort{
{
Port: 999999,
Protocol: corev1.ProtocolUDP,
},
}
return toModify, service, nil
},
func(resource client.Object) bool { //find resource for test
//return true if object is the one we want to test
_, ok := resource.(*corev1.Service)
return ok
},
func(postUpgradeObj client.Object, deisredObj client.Object) bool { //check resource was upgraded
//return true if postUpgrade has teh same fields as desired
post, ok := postUpgradeObj.(*corev1.Service)
if !ok {
return false
}
desired, ok := deisredObj.(*corev1.Service)
if !ok {
return false
}
for key, port := range desired.Spec.Ports {
if post.Spec.Ports[key].Port != port.Port {
return false
}
}
return len(desired.Spec.Ports) == len(post.Spec.Ports)
}),
//CRD update
// - update CRD label
// - update CRD annotation
// - update CRD version
// - update CRD spec
// - update CRD status
// - add new CRD
// -
//RBAC update
// - update RoleBinding/ClusterRoleBinding
// - Update Role/ClusterRole
//ServiceAccount upgrade
// - update ServiceAccount SCC
// - update ServiceAccount Labels/Annotations
) //updates objects on upgrade
DescribeTable("Removes unused objects on upgrade", func(
createObj createUnusedObject) {
newVersion := "1.10.0"
prevVersion := "1.9.5"
args := createFromArgs(newVersion)
doReconcile(args)
setDeploymentsReady(args)
//verify on int version is set
Expect(args.cdi.Status.Phase).Should(Equal(sdkapi.PhaseDeployed))
//Modify CRD to be of previousVersion
crSetVersion(args.reconciler.reconciler, args.cdi, prevVersion)
err := args.client.Update(context.TODO(), args.cdi)
Expect(err).ToNot(HaveOccurred())
setDeploymentsDegraded(args)
unusedObj, err := createObj()
Expect(err).ToNot(HaveOccurred())
unusedMetaObj := unusedObj.(metav1.Object)
unusedMetaObj.GetLabels()["operator.cdi.kubevirt.io/createVersion"] = prevVersion
err = controllerutil.SetControllerReference(args.cdi, unusedMetaObj, scheme.Scheme)
Expect(err).ToNot(HaveOccurred())
//add unused object via client, with curObject
err = args.client.Create(context.TODO(), unusedObj)
Expect(err).ToNot(HaveOccurred())
doReconcile(args)
//verify upgraded has started
Expect(args.cdi.Status.Phase).Should(Equal(sdkapi.PhaseUpgrading))
//verify unused exists before upgrade is done
_, err = getObject(args.client, unusedObj)
Expect(err).ToNot(HaveOccurred())
//change deployment to ready
isReady := setDeploymentsReady(args)
Expect(isReady).Should(Equal(true))
doReconcile(args)
Expect(args.cdi.Status.Phase).Should(Equal(sdkapi.PhaseDeployed))
//verify that object no longer exists after upgrade
_, err = getObject(args.client, unusedObj)
Expect(errors.IsNotFound(err)).Should(Equal(true))
},
Entry("verify - unused deployment deleted",
func() (client.Object, error) {
deployment := utils.CreateDeployment("fake-cdi-deployment", "app", "containerized-data-importer", "fake-sa", int32(1), &sdkapi.NodePlacement{})
return deployment, nil
}),
Entry("verify - unused service deleted",
func() (client.Object, error) {
service := utils.ResourceBuilder.CreateService("fake-cdi-service", "fake-service", "fake", nil)
return service, nil
}),
Entry("verify - unused sa deleted",
func() (client.Object, error) {
sa := utils.ResourceBuilder.CreateServiceAccount("fake-cdi-sa")
return sa, nil
}),
Entry("verify - unused crd deleted",
func() (client.Object, error) {
crd := &extv1.CustomResourceDefinition{
TypeMeta: metav1.TypeMeta{
APIVersion: "apiextensions.k8s.io/v1",
Kind: "CustomResourceDefinition",
},
ObjectMeta: metav1.ObjectMeta{
Name: "fake.cdis.cdi.kubevirt.io",
Labels: map[string]string{
"operator.cdi.kubevirt.io": "",
},
},
Spec: extv1.CustomResourceDefinitionSpec{
Group: "cdi.kubevirt.io",
Scope: "Cluster",
Versions: []extv1.CustomResourceDefinitionVersion{
{
Name: "v1beta1",
Served: true,
Storage: true,
AdditionalPrinterColumns: []extv1.CustomResourceColumnDefinition{
{Name: "Age", Type: "date", JSONPath: ".metadata.creationTimestamp"},
{Name: "Phase", Type: "string", JSONPath: ".status.phase"},
},
},
{
Name: "v1alpha1",
Served: true,
Storage: false,
AdditionalPrinterColumns: []extv1.CustomResourceColumnDefinition{
{Name: "Age", Type: "date", JSONPath: ".metadata.creationTimestamp"},
{Name: "Phase", Type: "string", JSONPath: ".status.phase"},
},
},
},
Names: extv1.CustomResourceDefinitionNames{
Kind: "FakeCDI",
ListKind: "FakeCDIList",
Plural: "fakecdis",
Singular: "fakecdi",
Categories: []string{
"all",
},
ShortNames: []string{"fakecdi", "fakecdis"},
},
},
}
return crd, nil
}),
Entry("verify - unused role deleted",
func() (client.Object, error) {
role := utils.ResourceBuilder.CreateRole("fake-role", nil)
return role, nil
}),
Entry("verify - unused role binding deleted",
func() (client.Object, error) {
role := utils.ResourceBuilder.CreateRoleBinding("fake-role", "fake-role", "fake-role", "fake-role")
return role, nil
}),
Entry("verify - unused cluster role deleted",
func() (client.Object, error) {
role := utils.ResourceBuilder.CreateClusterRole("fake-cluster-role", nil)
return role, nil
}),
Entry("verify - unused cluster role binding deleted",
func() (client.Object, error) {
role := utils.ResourceBuilder.CreateClusterRoleBinding("fake-cluster-role", "fake-cluster-role", "fake-cluster-role", "fake-cluster-role")
return role, nil
}),
)
})
})
func getModifiedResource(reconciler *ReconcileCDI, modify modifyResource, tomodify isModifySubject) (client.Object, client.Object, error) {
resources, err := getAllResources(reconciler)
if err != nil {
return nil, nil, err
}
//find the resource to modify
var orig client.Object
for _, resource := range resources {
r, err := getObject(reconciler.client, resource)
Expect(err).ToNot(HaveOccurred())
if tomodify(r) {
orig = r
break
}
}
//apply modify function on resource and return modified one
return modify(orig)
}
type cdiOverride interface {
Set(cr *cdiv1.CDI)
Check(d *appsv1.Deployment)
}
type pullOverride struct {
value corev1.PullPolicy
}
func (o *pullOverride) Set(cr *cdiv1.CDI) {
cr.Spec.ImagePullPolicy = o.value
}
func (o *pullOverride) Check(d *appsv1.Deployment) {
pp := d.Spec.Template.Spec.Containers[0].ImagePullPolicy
Expect(pp).Should(Equal(o.value))
}
func getCDI(client client.Client, cdi *cdiv1.CDI) (*cdiv1.CDI, error) {
result, err := getObject(client, cdi)
if err != nil {
return nil, err
}
return result.(*cdiv1.CDI), nil
}
func getSCC(client client.Client, scc *secv1.SecurityContextConstraints) (*secv1.SecurityContextConstraints, error) {
result, err := getObject(client, scc)
if err != nil {
return nil, err
}
return result.(*secv1.SecurityContextConstraints), nil
}
func setDeploymentsReady(args *args) bool {
resources, err := getAllResources(args.reconciler)
Expect(err).ToNot(HaveOccurred())
running := false
for _, r := range resources {
d, ok := r.(*appsv1.Deployment)
if !ok {
continue
}
Expect(running).To(BeFalse())
d, err := getDeployment(args.client, d)
Expect(err).ToNot(HaveOccurred())
if d.Spec.Replicas != nil {
d.Status.Replicas = *d.Spec.Replicas
d.Status.ReadyReplicas = d.Status.Replicas
err = args.client.Update(context.TODO(), d)
Expect(err).ToNot(HaveOccurred())
}
doReconcile(args)
if len(args.cdi.Status.Conditions) == 3 &&
conditions.IsStatusConditionTrue(args.cdi.Status.Conditions, conditions.ConditionAvailable) &&
conditions.IsStatusConditionFalse(args.cdi.Status.Conditions, conditions.ConditionProgressing) &&
conditions.IsStatusConditionFalse(args.cdi.Status.Conditions, conditions.ConditionDegraded) {
running = true
}
}
return running
}
func setDeploymentsDegraded(args *args) {
resources, err := getAllResources(args.reconciler)
Expect(err).ToNot(HaveOccurred())
for _, r := range resources {
d, ok := r.(*appsv1.Deployment)
if !ok {
continue
}
d, err := getDeployment(args.client, d)
Expect(err).ToNot(HaveOccurred())
if d.Spec.Replicas != nil {
d.Status.Replicas = int32(0)
d.Status.ReadyReplicas = d.Status.Replicas
err = args.client.Update(context.TODO(), d)
Expect(err).ToNot(HaveOccurred())
}
}
doReconcile(args)
}
func getDeployment(client client.Client, deployment *appsv1.Deployment) (*appsv1.Deployment, error) {
result, err := getObject(client, deployment)
if err != nil {
return nil, err
}
return result.(*appsv1.Deployment), nil
}
func getObject(c client.Client, obj client.Object) (client.Object, error) {
metaObj := obj.(metav1.Object)
key := client.ObjectKey{Namespace: metaObj.GetNamespace(), Name: metaObj.GetName()}
typ := reflect.ValueOf(obj).Elem().Type()
result := reflect.New(typ).Interface().(client.Object)
if err := c.Get(context.TODO(), key, result); err != nil {
return nil, err
}
return result, nil
}
func getAllResources(reconciler *ReconcileCDI) ([]client.Object, error) {
var result []client.Object
crs, err := clusterResources.CreateAllStaticResources(reconciler.clusterArgs)
if err != nil {
return nil, err
}
result = append(result, crs...)
nrs, err := namespaceResources.CreateAllResources(reconciler.namespacedArgs)
if err != nil {
return nil, err
}
result = append(result, nrs...)
drs, err := clusterResources.CreateAllDynamicResources(reconciler.clusterArgs)
if err != nil {
return nil, err
}
result = append(result, drs...)
return result, nil
}
func reconcileRequest(name string) reconcile.Request {
return reconcile.Request{NamespacedName: types.NamespacedName{Name: name}}
}
func createFromArgs(version string) *args {
cdi := createCDI("cdi", "good uid")
client := createClient(cdi)
reconciler := createReconcilerWithVersion(client, version)
return &args{
cdi: cdi,
client: client,
reconciler: reconciler,
}
}
func createArgs() *args {
cdi := createCDI("cdi", "good uid")
client := createClient(cdi)
reconciler := createReconciler(client)
return &args{
cdi: cdi,
client: client,
reconciler: reconciler,
}
}
func doReconcile(args *args) {
result, err := args.reconciler.Reconcile(context.TODO(), reconcileRequest(args.cdi.Name))
Expect(err).ToNot(HaveOccurred())
Expect(result.Requeue).To(BeFalse())
args.cdi, err = getCDI(args.client, args.cdi)
Expect(err).ToNot(HaveOccurred())
}
func doReconcileError(args *args) {
result, err := args.reconciler.Reconcile(context.TODO(), reconcileRequest(args.cdi.Name))
Expect(err).To(HaveOccurred())
Expect(result.Requeue).To(BeFalse())
args.cdi, err = getCDI(args.client, args.cdi)
Expect(err).ToNot(HaveOccurred())
}
func doReconcileRequeue(args *args) {
result, err := args.reconciler.Reconcile(context.TODO(), reconcileRequest(args.cdi.Name))
Expect(err).ToNot(HaveOccurred())
Expect(result.Requeue || result.RequeueAfter > 0).To(BeTrue())
args.cdi, err = getCDI(args.client, args.cdi)
Expect(err).ToNot(HaveOccurred())
}
func doReconcileExpectDelete(args *args) {
result, err := args.reconciler.Reconcile(context.TODO(), reconcileRequest(args.cdi.Name))
Expect(err).ToNot(HaveOccurred())
Expect(result.Requeue).To(BeFalse())
_, err = getCDI(args.client, args.cdi)
Expect(err).To(HaveOccurred())
Expect(errors.IsNotFound(err)).To(BeTrue())
}
func createClient(objs ...client.Object) client.Client {
var runtimeObjs []runtime.Object
for _, obj := range objs {
runtimeObjs = append(runtimeObjs, obj)
}
return fakeClient.NewFakeClientWithScheme(scheme.Scheme, runtimeObjs...)
}
func createCDI(name, uid string) *cdiv1.CDI {
return &cdiv1.CDI{
TypeMeta: metav1.TypeMeta{
Kind: "CDI",
APIVersion: "cdis.cdi.kubevirt.io",
},
ObjectMeta: metav1.ObjectMeta{
Name: name,
UID: types.UID(uid),
Labels: map[string]string{
common.AppKubernetesManagedByLabel: "tests",
common.AppKubernetesPartOfLabel: "testing",
common.AppKubernetesVersionLabel: "v0.0.0-tests",
common.AppKubernetesComponentLabel: "storage",
},
},
}
}
func
|
(client client.Client, version string) *ReconcileCDI {
r := createReconciler(client)
r.namespacedArgs.OperatorVersion = version
return r
}
func createReconciler(client client.Client) *ReconcileCDI {
namespace := "cdi"
clusterArgs := &clusterResources.FactoryArgs{
Namespace: namespace,
Client: client,
Logger: log,
}
namespacedArgs := &namespaceResources.FactoryArgs{
OperatorVersion: version,
DeployClusterResources: "true",
ControllerImage: "cdi-controller",
ImporterImage: "cdi-importer",
ClonerImage: "cdi-cloner",
APIServerImage: "cdi-apiserver",
UploadProxyImage: "cdi-uploadproxy",
UploadServerImage: "cdi-uploadserver",
Verbosity: "1",
PullPolicy: "Always",
Namespace: namespace,
}
recorder := record.NewFakeRecorder(250)
r := &ReconcileCDI{
client: client,
uncachedClient: client,
scheme: scheme.Scheme,
recorder: recorder,
namespace: namespace,
clusterArgs: clusterArgs,
namespacedArgs: namespacedArgs,
certManager: newFakeCertManager(client, namespace),
}
callbackDispatcher := callbacks.NewCallbackDispatcher(log, client, client, scheme.Scheme, namespace)
r.reconciler = sdkr.NewReconciler(r, log, client, callbackDispatcher, scheme.Scheme, createVersionLabel, updateVersionLabel, LastAppliedConfigAnnotation, certPollInterval, finalizerName, false, recorder).
WithWatching(true)
r.registerHooks()
addReconcileCallbacks(r)
return r
}
func crSetVersion(r *sdkr.Reconciler, cr *cdiv1.CDI, version string) error {
return r.CrSetVersion(cr, version)
}
func validateEvents(reconciler *ReconcileCDI, match map[string]bool) {
events := reconciler.recorder.(*record.FakeRecorder).Events
// Closing the channel allows me to do non blocking reads of the channel, once the channel runs out of items the loop exits.
close(events)
for event := range events {
val, ok := match[event]
Expect(ok).To(BeTrue(), "Event [%s] was not expected", event)
if !val {
match[event] = true
}
}
for k, v := range match {
Expect(v).To(BeTrue(), "Event [%s] not observed", k)
}
}
func createDeleteCDIAfterReadyEventValidationMap() map[string]bool {
match := createReadyEventValidationMap()
match[normalDeleteResourceSuccess] = false
match[normalDeleteResourceSuccesWorker] = false
return match
}
func createDeleteCDIEventValidationMap() map[string]bool {
match := createNotReadyEventValidationMap()
match[normalDeleteResourceSuccess] = false
match[normalDeleteResourceSuccesWorker] = false
return match
}
func createErrorCDIEventValidationMap() map[string]bool {
match := createNotReadyEventValidationMap()
match["Warning ConfigError Reconciling to error state, unwanted CDI object"] = false
return match
}
func createReadyEventValidationMap() map[string]bool {
match := createNotReadyEventValidationMap()
match[normalCreateEnsured+" upload proxy route exists"] = false
match["Normal DeployCompleted Deployment Completed"] = false
return match
}
func createNotReadyEventValidationMap() map[string]bool {
// match is map of strings and if we observed the event.
// We are not interested in the order of the events, just that the events happen at least once.
match := make(map[string]bool)
match["Normal DeployStarted Started Deployment"] = false
match[normalCreateSuccess+" *v1.ClusterRole cdi-apiserver"] = false
match[normalCreateSuccess+" *v1.ClusterRoleBinding cdi-apiserver"] = false
match[normalCreateSuccess+" *v1.ClusterRole cdi"] = false
match[normalCreateSuccess+" *v1.ClusterRoleBinding cdi-sa"] = false
match[normalCreateSuccess+" *v1.CustomResourceDefinition datavolumes.cdi.kubevirt.io"] = false
match[normalCreateSuccess+" *v1.CustomResourceDefinition cdiconfigs.cdi.kubevirt.io"] = false
match[normalCreateSuccess+" *v1.CustomResourceDefinition storageprofiles.cdi.kubevirt.io"] = false
match[normalCreateSuccess+" *v1.CustomResourceDefinition datasources.cdi.kubevirt.io"] = false
match[normalCreateSuccess+" *v1.CustomResourceDefinition dataimportcrons.cdi.kubevirt.io"] = false
match[normalCreateSuccess+" *v1.CustomResourceDefinition objecttransfers.cdi.kubevirt.io"] = false
match[normalCreateSuccess+" *v1.ClusterRole cdi-uploadproxy"] = false
match[normalCreateSuccess+" *v1.ClusterRoleBinding cdi-uploadproxy"] = false
match[normalCreateSuccess+" *v1.ClusterRole cdi-cronjob"] = false
match[normalCreateSuccess+" *v1.ClusterRoleBinding cdi-cronjob"] = false
match[normalCreateSuccess+" *v1.ClusterRole cdi.kubevirt.io:admin"] = false
match[normalCreateSuccess+" *v1.ClusterRole cdi.kubevirt.io:edit"] = false
match[normalCreateSuccess+" *v1.ClusterRole cdi.kubevirt.io:view"] = false
match[normalCreateSuccess+" *v1.ClusterRole cdi.kubevirt.io:config-reader"] = false
match[normalCreateSuccess+" *v1.ClusterRoleBinding cdi.kubevirt.io:config-reader"] = false
match[normalCreateSuccess+" *v1.ServiceAccount cdi-apiserver"] = false
match[normalCreateSuccess+" *v1.RoleBinding cdi-apiserver"] = false
match[normalCreateSuccess+" *v1.Role cdi-apiserver"] = false
match[normalCreateSuccess+" *v1.Service cdi-api"] = false
match[normalCreateSuccess+" *v1.Deployment cdi-apiserver"] = false
match[normalCreateSuccess+" *v1.ServiceAccount cdi-sa"] = false
match[normalCreateSuccess+" *v1.RoleBinding cdi-deployment"] = false
match[normalCreateSuccess+" *v1.Role cdi-deployment"] = false
match[normalCreateSuccess+" *v1.Deployment cdi-deployment"] = false
match[normalCreateSuccess+" *v1.ConfigMap cdi-insecure-registries"] = false
match[normalCreateSuccess+" *v1.ServiceAccount cdi-uploadproxy"] = false
match[normalCreateSuccess+" *v1.Service cdi-uploadproxy"] = false
match[normalCreateSuccess+" *v1.RoleBinding cdi-uploadproxy"] = false
match[normalCreateSuccess+" *v1.Role cdi-uploadproxy"] = false
match[normalCreateSuccess+" *v1.Deployment cdi-uploadproxy"] = false
match[normalCreateSuccess+" *v1.ServiceAccount cdi-cronjob"] = false
match[normalCreateSuccess+" *v1.RoleBinding cdi-cronjob"] = false
match[normalCreateSuccess+" *v1.Role cdi-cronjob"] = false
match[normalCreateSuccess+" *v1.APIService v1beta1.upload.cdi.kubevirt.io"] = false
match[normalCreateSuccess+" *v1.APIService v1alpha1.upload.cdi.kubevirt.io"] = false
match[normalCreateSuccess+" *v1.ValidatingWebhookConfiguration cdi-api-datavolume-validate"] = false
match[normalCreateSuccess+" *v1.MutatingWebhookConfiguration cdi-api-datavolume-mutate"] = false
match[normalCreateSuccess+" *v1.ValidatingWebhookConfiguration cdi-api-validate"] = false
match[normalCreateSuccess+" *v1.ValidatingWebhookConfiguration objecttransfer-api-validate"] = false
match[normalCreateSuccess+" *v1.ValidatingWebhookConfiguration cdi-api-dataimportcron-validate"] = false
match[normalCreateSuccess+" *v1.Secret cdi-apiserver-signer"] = false
match[normalCreateSuccess+" *v1.ConfigMap cdi-apiserver-signer-bundle"] = false
match[normalCreateSuccess+" *v1.Secret cdi-apiserver-server-cert"] = false
match[normalCreateSuccess+" *v1.Secret cdi-uploadproxy-signer"] = false
match[normalCreateSuccess+" *v1.ConfigMap cdi-uploadproxy-signer-bundle"] = false
match[normalCreateSuccess+" *v1.Secret cdi-uploadproxy-server-cert"] = false
match[normalCreateSuccess+" *v1.Secret cdi-uploadserver-signer"] = false
match[normalCreateSuccess+" *v1.ConfigMap cdi-uploadserver-signer-bundle"] = false
match[normalCreateSuccess+" *v1.Secret cdi-uploadserver-client-signer"] = false
match[normalCreateSuccess+" *v1.ConfigMap cdi-uploadserver-client-signer-bundle"] = false
match[normalCreateSuccess+" *v1.Secret cdi-uploadserver-client-cert"] = false
match[normalCreateSuccess+" *v1.Service cdi-prometheus-metrics"] = false
match[normalCreateEnsured+" SecurityContextConstraint exists"] = false
return match
}
|
createReconcilerWithVersion
|
vqa_v2.py
|
# Copyright (c) Aishwarya Kamath & Nicolas Carion. Licensed under the Apache License 2.0. All Rights Reserved
"""
COCO dataset which returns image_id for evaluation.
Mostly copy-paste from https://github.com/ashkamath/mdetr/blob/main/datasets/gqa.py
"""
import json
from pathlib import Path
import torch
import torchvision
from transformers import RobertaTokenizerFast
from .coco import ConvertCocoPolysToMask, ModulatedDetection, make_coco_transforms
class VQAv2Detection(ModulatedDetection):
pass
class VQAv2QuestionAnswering(torchvision.datasets.CocoDetection):
def __init__(self, img_folder, ann_file, transforms, return_masks, return_tokens, tokenizer, ann_folder):
super(VQAv2QuestionAnswering, self).__init__(img_folder, ann_file)
self._transforms = transforms
self.prepare = ConvertCocoPolysToMask(return_masks, return_tokens, tokenizer=tokenizer)
with open(ann_folder / "vqa2_answer2id.json", "r") as f:
self.answer2id = json.load(f)
with open(ann_folder / "vqa2_answer2id_by_type.json", "r") as f:
self.answer2id_by_type = json.load(f)
self.type2id = {"yes/no": 0, "number": 1, "other": 2}
def __getitem__(self, idx):
img, target = super(VQAv2QuestionAnswering, self).__getitem__(idx)
image_id = self.ids[idx]
coco_img = self.coco.loadImgs(image_id)[0]
caption = coco_img["caption"]
dataset_name = coco_img["dataset_name"]
questionId = coco_img["questionId"]
target = {"image_id": image_id, "annotations": target, "caption": caption}
img, target = self.prepare(img, target)
if self._transforms is not None:
img, target = self._transforms(img, target)
target["dataset_name"] = dataset_name
target["questionId"] = questionId
if coco_img["answer"] not in self.answer2id:
answer = "unknown"
else:
answer = coco_img["answer"]
target["answer"] = torch.as_tensor(self.answer2id[answer], dtype=torch.long)
target["answer_type"] = torch.as_tensor(self.type2id[coco_img["answer_type"]], dtype=torch.long)
# util.misc.collate_fn requires to put 'answer' before every type of answer in target
if coco_img["answer"] not in self.answer2id_by_type["yes/no"]:
answer = "unknown"
else:
answer = coco_img["answer"]
target["answer_yes/no"] = torch.as_tensor(
self.answer2id_by_type["yes/no"][answer] if coco_img["answer_type"] == "yes/no" else -100,
dtype=torch.long,
)
if coco_img["answer"] not in self.answer2id_by_type["number"]:
answer = "unknown"
else:
answer = coco_img["answer"]
target["answer_number"] = torch.as_tensor(
self.answer2id_by_type["number"][answer] if coco_img["answer_type"] == "number" else -100,
dtype=torch.long,
)
if coco_img["answer"] not in self.answer2id_by_type["other"]:
answer = "unknown"
else:
answer = coco_img["answer"]
target["answer_other"] = torch.as_tensor(
self.answer2id_by_type["other"][answer] if coco_img["answer_type"] == "other" else -100,
dtype=torch.long,
)
return img, target
def build(image_set, args):
# TODO: img or all?
img_dir = Path(args.coco_img_path)
assert img_dir.exists(), f"provided COCO img path {img_dir} does not exist"
tokenizer = RobertaTokenizerFast.from_pretrained(args.text_encoder_type)
if args.do_qa:
# Для vqa2 это не нужно:
# assert args.vqa2_split_type is not None
if image_set == "train":
datasets = []
for imset in ["train", "minival"]:
ann_file = Path(args.vqa2_ann_path) / f"finetune_vqa2_{imset}.json"
datasets.append(
VQAv2QuestionAnswering(
img_dir / "train2014" if imset == "train" else img_dir / "val2014",
ann_file,
transforms=make_coco_transforms(image_set, cautious=True),
return_masks=args.masks,
return_tokens=True,
tokenizer=tokenizer,
ann_folder=Path(args.vqa2_ann_path),
)
)
return torch.utils.data.ConcatDataset(datasets)
elif image_set == "val":
# TODO: правильный ли ann_file?
ann_file = Path(args.vqa2
|
n ["test", "testdev", "trainval"]:
ann_file = Path(args.vqa2_ann_path) / f"finetune_vqa2_{image_set}.json"
return VQAv2QuestionAnswering(
img_dir / "test2015",
ann_file,
transforms=make_coco_transforms("val", cautious=True),
return_masks=args.masks,
return_tokens=True,
tokenizer=tokenizer,
ann_folder=Path(args.vqa2_ann_path),
)
else:
assert False, f"Unknown image set {image_set}"
|
_ann_path) / f"finetune_vqa2_minival.json"
return VQAv2QuestionAnswering(
img_dir / "val2014",
ann_file,
transforms=make_coco_transforms(image_set, cautious=True),
return_masks=args.masks,
return_tokens=True,
tokenizer=tokenizer,
ann_folder=Path(args.vqa2_ann_path),
)
elif image_set i
|
app.component.ts
|
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class
|
{
title = 'moon-copy';
}
|
AppComponent
|
LogisticRegression.py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Logistic Regression Gradient Descent
"""
import numpy as np
class LogisticRegressionGD(object):
"""Logistic Regression Classifier using gradient descent.
Parameters
------------
eta : float
Learning rate (between 0.0 and 1.0)
n_iter : int
Passes over the training dataset.
random_state : int
Random number generator seed for random weight
initialization.
Attributes
-----------
w_ : 1d-array
Weights after fitting.
cost_ : list
Logistic cost function value in each epoch.
"""
def
|
(self, eta=0.05, n_iter=100, random_state=1):
self.eta = eta
self.n_iter = n_iter
self.random_state = random_state
def fit(self, X, y):
""" Fit training data.
Parameters
----------
X : {array-like}, shape = [n_examples, n_features]
Training vectors, where n_examples is the number of
examples and n_features is the number of features.
y : array-like, shape = [n_examples]
Target values.
Returns
-------
self : object
"""
rgen = np.random.RandomState(self.random_state)
self.w_ = rgen.normal(loc=0.0, scale=0.01,
size=1 + X.shape[1])
self.cost_ = []
for i in range(self.n_iter):
net_input = self.net_input(X)
output = self.activation(net_input)
errors = (y - output)
self.w_[1:] += self.eta * X.T.dot(errors)
self.w_[0] += self.eta * errors.sum()
# note that we compute the logistic `cost` now
# instead of the sum of squared errors cost
cost = (-y.dot(np.log(output)) -
((1 - y).dot(np.log(1 - output))))
self.cost_.append(cost)
return self
def net_input(self, X):
"""Calculate net input"""
return np.dot(X, self.w_[1:]) + self.w_[0]
def activation(self, z):
"""Compute logistic sigmoid activation"""
return 1. / (1. + np.exp(-np.clip(z, -250, 250)))
def predict(self, X):
"""Return class label after unit step"""
return np.where(self.net_input(X) >= 0.0, 1, 0)
# equivalent to:
# return np.where(self.activation(self.net_input(X))
# >= 0.5, 1, 0)
|
__init__
|
qna.py
|
###########################
# Implements Q and A functionality
###########################
from discord import NotFound
import db
# keep track of next question number
QUESTION_NUMBER = 1
# dictionary of questions with answers
QNA = {}
###########################
# Class: QuestionsAnswers
# Description: object with question details
# Inputs:
# - q: question text
# - number: question number
# - message: id of the message associated with question
# - ans: answers to the question
# Outputs: None
###########################
class
|
:
''' Class containing needed question/answer information and identification '''
def __init__(self, qs, number, message, ans):
self.question = qs
self.number = number
self.msg = message
self.answer = ans
###########################
# Function: question
# Description: takes question from user and reposts anonymously and numbered
# Inputs:
# - ctx: context of the command
# - q: question text
# Outputs:
# - User question in new post
###########################
async def question(ctx, qs):
''' add a question '''
global QUESTION_NUMBER
# format question
q_str = 'Q' + str(QUESTION_NUMBER) + ': ' + qs + '\n'
message = await ctx.send(q_str)
# create QNA object
new_question = QuestionsAnswers(qs, QUESTION_NUMBER, message.id, '')
# add question to list
QNA[QUESTION_NUMBER] = new_question
db.mutation_query(
'INSERT INTO qna VALUES (?, ?, ?, ?)',
[ctx.guild.id, ctx.author.name, '', QUESTION_NUMBER]
)
# increment question number for next question
QUESTION_NUMBER += 1
# delete original question
await ctx.message.delete()
###########################
# Function: answer
# Description: adds user answer to specific question and post anonymously
# Inputs:
# - ctx: context of the command
# - num: question number being answered
# - ans: answer text to question specified in num
# Outputs:
# - User answer added to question post
###########################
async def answer(ctx, num, ans):
''' answer the specific question '''
if int(num) not in QNA.keys():
await ctx.author.send('Invalid question number: ' + str(num))
# delete user msg
await ctx.message.delete()
return
# get question
q_answered = QNA[int(num)]
# check if message exists
try:
message = await ctx.fetch_message(q_answered.msg)
except NotFound:
await ctx.author.send('Invalid question number: ' + str(num))
# delete user msg
await ctx.message.delete()
return
# generate and edit msg with answer
if "instructor" in [y.name.lower() for y in ctx.author.roles]:
role = 'Instructor'
else:
role = 'Student'
new_answer = role + ' Ans: ' + ans
db.mutation_query(
'UPDATE qna SET answer = ? WHERE qnumber = ?',(ans, int(num)),
)
# store new answer and uopdate the new answer to the database
if not q_answered.answer == '':
q_answered.answer += '\n'
q_answered.answer += new_answer
# check if message exists and edit
q_str = 'Q' + str(q_answered.number) + ': ' + q_answered.question
content = q_str + '\n' + q_answered.answer
try:
await message.edit(content=content)
# message.content = content
except NotFound:
await ctx.author.send('Invalid question number: ' + str(num))
# delete user msg
await ctx.message.delete()
|
QuestionsAnswers
|
custom.py
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
from __future__ import print_function
import binascii
import datetime
import errno
import json
import os
import os.path
import platform
import random
import re
import ssl
import stat
import string
import subprocess
import sys
import tempfile
import threading
import time
import uuid
import webbrowser
from six.moves.urllib.request import urlopen # pylint: disable=import-error
from six.moves.urllib.error import URLError # pylint: disable=import-error
from ._helpers import _populate_api_server_access_profile, _set_load_balancer_sku, _set_vm_set_type
# pylint: disable=import-error
import yaml
import dateutil.parser
from dateutil.relativedelta import relativedelta
from knack.log import get_logger
from knack.util import CLIError
from msrestazure.azure_exceptions import CloudError
import requests
# pylint: disable=no-name-in-module,import-error
from azure.cli.command_modules.acs import acs_client, proxy
from azure.cli.command_modules.acs._params import regions_in_preview, regions_in_prod
from azure.cli.core.api import get_config_dir
from azure.cli.core._profile import Profile
from azure.cli.core.commands.client_factory import get_mgmt_service_client, get_subscription_id
from azure.cli.core.keys import is_valid_ssh_rsa_public_key
from azure.cli.core.util import in_cloud_console, shell_safe_json_parse, truncate_text, sdk_no_wait
from azure.cli.core.commands import LongRunningOperation
from azure.graphrbac.models import (ApplicationCreateParameters,
ApplicationUpdateParameters,
PasswordCredential,
KeyCredential,
ServicePrincipalCreateParameters,
GetObjectsParameters,
ResourceAccess, RequiredResourceAccess)
from azure.mgmt.containerservice.models import ContainerServiceOrchestratorTypes
from azure.mgmt.containerservice.v2019_08_01.models import ContainerServiceNetworkProfile
from azure.mgmt.containerservice.v2019_08_01.models import ContainerServiceLinuxProfile
from azure.mgmt.containerservice.v2019_08_01.models import ManagedClusterServicePrincipalProfile
from azure.mgmt.containerservice.v2019_08_01.models import ContainerServiceSshConfiguration
from azure.mgmt.containerservice.v2019_08_01.models import ContainerServiceSshPublicKey
from azure.mgmt.containerservice.v2019_08_01.models import ContainerServiceStorageProfileTypes
from azure.mgmt.containerservice.v2019_08_01.models import ManagedCluster
from azure.mgmt.containerservice.v2019_08_01.models import ManagedClusterAADProfile
from azure.mgmt.containerservice.v2019_08_01.models import ManagedClusterAddonProfile
from azure.mgmt.containerservice.v2019_08_01.models import ManagedClusterAgentPoolProfile
from azure.mgmt.containerservice.v2019_08_01.models import ManagedClusterLoadBalancerProfile
from azure.mgmt.containerservice.v2019_08_01.models import ManagedClusterLoadBalancerProfileManagedOutboundIPs
from azure.mgmt.containerservice.v2019_08_01.models import ManagedClusterLoadBalancerProfileOutboundIPPrefixes
from azure.mgmt.containerservice.v2019_08_01.models import ManagedClusterLoadBalancerProfileOutboundIPs
from azure.mgmt.containerservice.v2019_08_01.models import AgentPool
from azure.mgmt.containerservice.v2019_08_01.models import ResourceReference
from azure.mgmt.containerservice.v2019_09_30_preview.models import OpenShiftManagedClusterAgentPoolProfile
from azure.mgmt.containerservice.v2019_09_30_preview.models import OpenShiftAgentPoolProfileRole
from azure.mgmt.containerservice.v2019_09_30_preview.models import OpenShiftManagedClusterIdentityProvider
from azure.mgmt.containerservice.v2019_09_30_preview.models import OpenShiftManagedClusterAADIdentityProvider
from azure.mgmt.containerservice.v2019_09_30_preview.models import OpenShiftManagedCluster
from azure.mgmt.containerservice.v2019_09_30_preview.models import OpenShiftRouterProfile
from azure.mgmt.containerservice.v2019_09_30_preview.models import OpenShiftManagedClusterAuthProfile
from azure.mgmt.containerservice.v2019_09_30_preview.models import NetworkProfile
from azure.mgmt.containerservice.v2019_09_30_preview.models import OpenShiftManagedClusterMonitorProfile
from ._client_factory import cf_container_services
from ._client_factory import cf_resource_groups
from ._client_factory import get_auth_management_client
from ._client_factory import get_graph_rbac_management_client
from ._client_factory import cf_resources
from ._client_factory import get_resource_by_name
from ._client_factory import cf_container_registry_service
logger = get_logger(__name__)
# pylint:disable=too-many-lines,unused-argument
def which(binary):
path_var = os.getenv('PATH')
if platform.system() == 'Windows':
binary = binary + '.exe'
parts = path_var.split(';')
else:
parts = path_var.split(':')
for part in parts:
bin_path = os.path.join(part, binary)
if os.path.exists(bin_path) and os.path.isfile(bin_path) and os.access(bin_path, os.X_OK):
return bin_path
return None
def wait_then_open(url):
"""
Waits for a bit then opens a URL. Useful for waiting for a proxy to come up, and then open the URL.
"""
for _ in range(1, 10):
try:
urlopen(url, context=_ssl_context())
except URLError:
time.sleep(1)
break
webbrowser.open_new_tab(url)
def wait_then_open_async(url):
"""
Spawns a thread that waits for a bit then opens a URL.
"""
t = threading.Thread(target=wait_then_open, args=({url}))
t.daemon = True
t.start()
def acs_browse(cmd, client, resource_group_name, name, disable_browser=False, ssh_key_file=None):
"""
Opens a browser to the web interface for the cluster orchestrator
:param name: Name of the target Azure container service instance.
:type name: String
:param resource_group_name: Name of Azure container service's resource group.
:type resource_group_name: String
:param disable_browser: If true, don't launch a web browser after estabilishing the proxy
:type disable_browser: bool
:param ssh_key_file: If set a path to an SSH key to use, only applies to DCOS
:type ssh_key_file: string
"""
acs_info = _get_acs_info(cmd.cli_ctx, name, resource_group_name)
_acs_browse_internal(cmd, client, acs_info, resource_group_name, name, disable_browser, ssh_key_file)
def _acs_browse_internal(cmd, client, acs_info, resource_group_name, name, disable_browser, ssh_key_file):
orchestrator_type = acs_info.orchestrator_profile.orchestrator_type # pylint: disable=no-member
if str(orchestrator_type).lower() == 'kubernetes' or \
orchestrator_type == ContainerServiceOrchestratorTypes.kubernetes or \
(acs_info.custom_profile and acs_info.custom_profile.orchestrator == 'kubernetes'): # pylint: disable=no-member
return k8s_browse(cmd, client, name, resource_group_name, disable_browser, ssh_key_file=ssh_key_file)
if str(orchestrator_type).lower() == 'dcos' or orchestrator_type == ContainerServiceOrchestratorTypes.dcos:
return _dcos_browse_internal(acs_info, disable_browser, ssh_key_file)
raise CLIError('Unsupported orchestrator type {} for browse'.format(orchestrator_type))
def k8s_browse(cmd, client, name, resource_group_name, disable_browser=False, ssh_key_file=None):
"""
Launch a proxy and browse the Kubernetes web UI.
:param disable_browser: If true, don't launch a web browser after estabilishing the proxy
:type disable_browser: bool
"""
acs_info = _get_acs_info(cmd.cli_ctx, name, resource_group_name)
_k8s_browse_internal(name, acs_info, disable_browser, ssh_key_file)
def _k8s_browse_internal(name, acs_info, disable_browser, ssh_key_file):
if not which('kubectl'):
raise CLIError('Can not find kubectl executable in PATH')
browse_path = os.path.join(get_config_dir(), 'acsBrowseConfig.yaml')
if os.path.exists(browse_path):
os.remove(browse_path)
_k8s_get_credentials_internal(name, acs_info, browse_path, ssh_key_file, False)
logger.warning('Proxy running on 127.0.0.1:8001/ui')
logger.warning('Press CTRL+C to close the tunnel...')
if not disable_browser:
wait_then_open_async('http://127.0.0.1:8001/ui')
subprocess.call(["kubectl", "--kubeconfig", browse_path, "proxy"])
def dcos_browse(cmd, client, name, resource_group_name, disable_browser=False, ssh_key_file=None):
"""
Creates an SSH tunnel to the Azure container service, and opens the Mesosphere DC/OS dashboard in the browser.
:param name: name: Name of the target Azure container service instance.
:type name: String
:param resource_group_name: Name of Azure container service's resource group.
:type resource_group_name: String
:param disable_browser: If true, don't launch a web browser after estabilishing the proxy
:type disable_browser: bool
:param ssh_key_file: Path to the SSH key to use
:type ssh_key_file: string
"""
acs_info = _get_acs_info(cmd.cli_ctx, name, resource_group_name)
_dcos_browse_internal(acs_info, disable_browser, ssh_key_file)
def _dcos_browse_internal(acs_info, disable_browser, ssh_key_file):
if not os.path.isfile(ssh_key_file):
raise CLIError('Private key file {} does not exist'.format(ssh_key_file))
acs = acs_client.ACSClient()
if not acs.connect(_get_host_name(acs_info), _get_username(acs_info),
key_filename=ssh_key_file):
raise CLIError('Error connecting to ACS: {}'.format(_get_host_name(acs_info)))
octarine_bin = '/opt/mesosphere/bin/octarine'
if not acs.file_exists(octarine_bin):
raise CLIError('Proxy server ({}) does not exist on the cluster.'.format(octarine_bin))
proxy_id = _rand_str(16)
proxy_cmd = '{} {}'.format(octarine_bin, proxy_id)
acs.run(proxy_cmd, background=True)
# Parse the output to get the remote PORT
proxy_client_cmd = '{} --client --port {}'.format(octarine_bin, proxy_id)
stdout, _ = acs.run(proxy_client_cmd)
remote_port = int(stdout.read().decode().strip())
local_port = acs.get_available_local_port()
# Set the proxy
proxy.set_http_proxy('127.0.0.1', local_port)
logger.warning('Proxy running on 127.0.0.1:%s', local_port)
logger.warning('Press CTRL+C to close the tunnel...')
if not disable_browser:
wait_then_open_async('http://127.0.0.1')
try:
acs.create_tunnel(
remote_host='127.0.0.1',
remote_port=remote_port,
local_port=local_port)
finally:
proxy.disable_http_proxy()
def acs_install_cli(cmd, client, resource_group_name, name, install_location=None, client_version=None):
acs_info = _get_acs_info(cmd.cli_ctx, name, resource_group_name)
orchestrator_type = acs_info.orchestrator_profile.orchestrator_type # pylint: disable=no-member
kwargs = {'install_location': install_location}
if client_version:
kwargs['client_version'] = client_version
if orchestrator_type == 'kubernetes':
return k8s_install_cli(**kwargs)
if orchestrator_type == 'dcos':
return dcos_install_cli(**kwargs)
raise CLIError('Unsupported orchestrator type {} for install-cli'.format(orchestrator_type))
def _ssl_context():
if sys.version_info < (3, 4) or (in_cloud_console() and platform.system() == 'Windows'):
try:
return ssl.SSLContext(ssl.PROTOCOL_TLS) # added in python 2.7.13 and 3.6
except AttributeError:
return ssl.SSLContext(ssl.PROTOCOL_TLSv1)
return ssl.create_default_context()
def _urlretrieve(url, filename):
req = urlopen(url, context=_ssl_context())
with open(filename, "wb") as f:
f.write(req.read())
def dcos_install_cli(cmd, install_location=None, client_version='1.8'):
"""
Downloads the dcos command line from Mesosphere
"""
system = platform.system()
if not install_location:
raise CLIError(
"No install location specified and it could not be determined from the current platform '{}'".format(
system))
base_url = 'https://downloads.dcos.io/binaries/cli/{}/x86-64/dcos-{}/{}'
if system == 'Windows':
file_url = base_url.format('windows', client_version, 'dcos.exe')
elif system == 'Linux':
# TODO Support ARM CPU here
file_url = base_url.format('linux', client_version, 'dcos')
elif system == 'Darwin':
file_url = base_url.format('darwin', client_version, 'dcos')
else:
raise CLIError('Proxy server ({}) does not exist on the cluster.'.format(system))
logger.warning('Downloading client to %s', install_location)
try:
_urlretrieve(file_url, install_location)
os.chmod(install_location,
os.stat(install_location).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
except IOError as err:
raise CLIError('Connection error while attempting to download client ({})'.format(err))
def k8s_install_cli(cmd, client_version='latest', install_location=None):
"""Install kubectl, a command-line interface for Kubernetes clusters."""
source_url = "https://storage.googleapis.com/kubernetes-release/release"
cloud_name = cmd.cli_ctx.cloud.name
if cloud_name.lower() == 'azurechinacloud':
source_url = 'https://mirror.azure.cn/kubernetes/kubectl'
if client_version == 'latest':
context = _ssl_context()
version = urlopen(source_url + '/stable.txt', context=context).read()
client_version = version.decode('UTF-8').strip()
else:
client_version = "v%s" % client_version
file_url = ''
system = platform.system()
base_url = source_url + '/{}/bin/{}/amd64/{}'
# ensure installation directory exists
install_dir, cli = os.path.dirname(install_location), os.path.basename(install_location)
if not os.path.exists(install_dir):
os.makedirs(install_dir)
if system == 'Windows':
file_url = base_url.format(client_version, 'windows', 'kubectl.exe')
elif system == 'Linux':
# TODO: Support ARM CPU here
file_url = base_url.format(client_version, 'linux', 'kubectl')
elif system == 'Darwin':
file_url = base_url.format(client_version, 'darwin', 'kubectl')
else:
raise CLIError('Proxy server ({}) does not exist on the cluster.'.format(system))
logger.warning('Downloading client to "%s" from "%s"', install_location, file_url)
try:
_urlretrieve(file_url, install_location)
os.chmod(install_location,
os.stat(install_location).st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
except IOError as ex:
raise CLIError('Connection error while attempting to download client ({})'.format(ex))
if system == 'Windows': # be verbose, as the install_location likely not in Windows's search PATHs
env_paths = os.environ['PATH'].split(';')
found = next((x for x in env_paths if x.lower().rstrip('\\') == install_dir.lower()), None)
if not found:
# pylint: disable=logging-format-interpolation
logger.warning('Please add "{0}" to your search PATH so the `{1}` can be found. 2 options: \n'
' 1. Run "set PATH=%PATH%;{0}" or "$env:path += \'{0}\'" for PowerShell. '
'This is good for the current command session.\n'
' 2. Update system PATH environment variable by following '
'"Control Panel->System->Advanced->Environment Variables", and re-open the command window. '
'You only need to do it once'.format(install_dir, cli))
else:
logger.warning('Please ensure that %s is in your search PATH, so the `%s` command can be found.',
install_dir, cli)
def k8s_install_connector(cmd, client, name, resource_group_name, connector_name='aci-connector',
location=None, service_principal=None, client_secret=None,
chart_url=None, os_type='Linux', image_tag=None, aci_resource_group=None):
_k8s_install_or_upgrade_connector("install", cmd, client, name, resource_group_name, connector_name,
location, service_principal, client_secret, chart_url, os_type,
image_tag, aci_resource_group)
def k8s_upgrade_connector(cmd, client, name, resource_group_name, connector_name='aci-connector',
location=None, service_principal=None, client_secret=None,
chart_url=None, os_type='Linux', image_tag=None, aci_resource_group=None):
_k8s_install_or_upgrade_connector("upgrade", cmd, client, name, resource_group_name, connector_name,
location, service_principal, client_secret, chart_url, os_type,
image_tag, aci_resource_group)
def _k8s_install_or_upgrade_connector(helm_cmd, cmd, client, name, resource_group_name, connector_name,
location, service_principal, client_secret, chart_url, os_type,
image_tag, aci_resource_group):
from subprocess import PIPE, Popen
instance = client.get(resource_group_name, name)
helm_not_installed = 'Helm not detected, please verify if it is installed.'
url_chart = chart_url
if image_tag is None:
image_tag = 'latest'
# Check if Helm is installed locally
try:
Popen(["helm"], stdout=PIPE, stderr=PIPE)
except OSError:
raise CLIError(helm_not_installed)
# If SPN is specified, the secret should also be specified
if service_principal is not None and client_secret is None:
raise CLIError('--client-secret must be specified when --service-principal is specified')
# Validate if the RG exists
rg_location = _get_rg_location(cmd.cli_ctx, aci_resource_group or resource_group_name)
# Auto assign the location
if location is None:
location = rg_location
norm_location = location.replace(' ', '').lower()
# Validate the location upon the ACI avaiable regions
_validate_aci_location(norm_location)
# Get the credentials from a AKS instance
_, browse_path = tempfile.mkstemp()
aks_get_credentials(cmd, client, resource_group_name, name, admin=False, path=browse_path)
subscription_id = get_subscription_id(cmd.cli_ctx)
# Get the TenantID
profile = Profile(cli_ctx=cmd.cli_ctx)
_, _, tenant_id = profile.get_login_credentials()
# Check if we want the linux connector
if os_type.lower() in ['linux', 'both']:
_helm_install_or_upgrade_aci_connector(helm_cmd, image_tag, url_chart, connector_name, service_principal,
client_secret, subscription_id, tenant_id, aci_resource_group,
norm_location, 'Linux', instance.enable_rbac, instance.fqdn)
# Check if we want the windows connector
if os_type.lower() in ['windows', 'both']:
_helm_install_or_upgrade_aci_connector(helm_cmd, image_tag, url_chart, connector_name, service_principal,
client_secret, subscription_id, tenant_id, aci_resource_group,
norm_location, 'Windows', instance.enable_rbac, instance.fqdn)
def _helm_install_or_upgrade_aci_connector(helm_cmd, image_tag, url_chart, connector_name, service_principal,
client_secret, subscription_id, tenant_id, aci_resource_group,
norm_location, os_type, use_rbac, masterFqdn):
rbac_install = "true" if use_rbac else "false"
node_taint = 'azure.com/aci'
helm_release_name = connector_name.lower() + '-' + os_type.lower() + '-' + norm_location
node_name = 'virtual-kubelet-' + helm_release_name
k8s_master = 'https://{}'.format(masterFqdn)
logger.warning("Deploying the ACI connector for '%s' using Helm", os_type)
try:
values = 'env.nodeName={},env.nodeTaint={},env.nodeOsType={},image.tag={},rbac.install={}'.format(
node_name, node_taint, os_type, image_tag, rbac_install)
if service_principal:
values += ",env.azureClientId=" + service_principal
if client_secret:
values += ",env.azureClientKey=" + client_secret
if subscription_id:
values += ",env.azureSubscriptionId=" + subscription_id
if tenant_id:
values += ",env.azureTenantId=" + tenant_id
if aci_resource_group:
values += ",env.aciResourceGroup=" + aci_resource_group
if norm_location:
values += ",env.aciRegion=" + norm_location
# Currently, we need to set the master FQDN.
# This is temporary and we should remove it when possible
values += ",env.masterUri=" + k8s_master
if helm_cmd == "install":
subprocess.call(["helm", "install", url_chart, "--name", helm_release_name, "--set", values])
elif helm_cmd == "upgrade":
subprocess.call(["helm", "upgrade", helm_release_name, url_chart, "--set", values])
except subprocess.CalledProcessError as err:
raise CLIError('Could not deploy the ACI connector Chart: {}'.format(err))
def k8s_uninstall_connector(cmd, client, name, resource_group_name, connector_name='aci-connector',
location=None, graceful=False, os_type='Linux'):
from subprocess import PIPE, Popen
helm_not_installed = "Error : Helm not detected, please verify if it is installed."
# Check if Helm is installed locally
try:
Popen(["helm"], stdout=PIPE, stderr=PIPE)
except OSError:
raise CLIError(helm_not_installed)
# Get the credentials from a AKS instance
_, browse_path = tempfile.mkstemp()
aks_get_credentials(cmd, client, resource_group_name, name, admin=False, path=browse_path)
# Validate if the RG exists
rg_location = _get_rg_location(cmd.cli_ctx, resource_group_name)
# Auto assign the location
if location is None:
location = rg_location
norm_location = location.replace(' ', '').lower()
if os_type.lower() in ['linux', 'both']:
helm_release_name = connector_name.lower() + '-linux-' + norm_location
node_name = 'virtual-kubelet-' + helm_release_name
_undeploy_connector(graceful, node_name, helm_release_name)
if os_type.lower() in ['windows', 'both']:
helm_release_name = connector_name.lower() + '-windows-' + norm_location
node_name = 'virtual-kubelet-' + helm_release_name
_undeploy_connector(graceful, node_name, helm_release_name)
def _undeploy_connector(graceful, node_name, helm_release_name):
if graceful:
logger.warning('Graceful option selected, will try to drain the node first')
from subprocess import PIPE, Popen
kubectl_not_installed = 'Kubectl not detected, please verify if it is installed.'
try:
Popen(["kubectl"], stdout=PIPE, stderr=PIPE)
except OSError:
raise CLIError(kubectl_not_installed)
try:
drain_node = subprocess.check_output(
['kubectl', 'drain', node_name, '--force', '--delete-local-data'],
universal_newlines=True)
if not drain_node:
raise CLIError('Could not find the node, make sure you' +
' are using the correct --os-type')
except subprocess.CalledProcessError as err:
raise CLIError('Could not find the node, make sure you are using the correct' +
' --connector-name, --location and --os-type options: {}'.format(err))
logger.warning("Undeploying the '%s' using Helm", helm_release_name)
try:
subprocess.call(['helm', 'del', helm_release_name, '--purge'])
except subprocess.CalledProcessError as err:
raise CLIError('Could not undeploy the ACI connector Chart: {}'.format(err))
try:
subprocess.check_output(
['kubectl', 'delete', 'node', node_name],
universal_newlines=True)
except subprocess.CalledProcessError as err:
raise CLIError('Could not delete the node, make sure you are using the correct' +
' --connector-name, --location and --os-type options: {}'.format(err))
def _build_service_principal(rbac_client, cli_ctx, name, url, client_secret):
# use get_progress_controller
hook = cli_ctx.get_progress_controller(True)
hook.add(messsage='Creating service principal', value=0, total_val=1.0)
logger.info('Creating service principal')
# always create application with 5 years expiration
start_date = datetime.datetime.utcnow()
end_date = start_date + relativedelta(years=5)
result = create_application(rbac_client.applications, name, url, [url], password=client_secret,
start_date=start_date, end_date=end_date)
service_principal = result.app_id # pylint: disable=no-member
for x in range(0, 10):
hook.add(message='Creating service principal', value=0.1 * x, total_val=1.0)
try:
create_service_principal(cli_ctx, service_principal, rbac_client=rbac_client)
break
# TODO figure out what exception AAD throws here sometimes.
except Exception as ex: # pylint: disable=broad-except
logger.info(ex)
time.sleep(2 + 2 * x)
else:
return False
hook.add(message='Finished service principal creation', value=1.0, total_val=1.0)
logger.info('Finished service principal creation')
return service_principal
def _add_role_assignment(cli_ctx, role, service_principal, delay=2, scope=None):
# AAD can have delays in propagating data, so sleep and retry
hook = cli_ctx.get_progress_controller(True)
hook.add(message='Waiting for AAD role to propagate', value=0, total_val=1.0)
logger.info('Waiting for AAD role to propagate')
for x in range(0, 10):
hook.add(message='Waiting for AAD role to propagate', value=0.1 * x, total_val=1.0)
try:
# TODO: break this out into a shared utility library
create_role_assignment(cli_ctx, role, service_principal, scope=scope)
break
except CloudError as ex:
if ex.message == 'The role assignment already exists.':
break
logger.info(ex.message)
except: # pylint: disable=bare-except
pass
time.sleep(delay + delay * x)
else:
return False
hook.add(message='AAD role propagation done', value=1.0, total_val=1.0)
logger.info('AAD role propagation done')
return True
def delete_role_assignments(cli_ctx, ids=None, assignee=None, role=None, resource_group_name=None,
scope=None, include_inherited=False, yes=None):
factory = get_auth_management_client(cli_ctx, scope)
assignments_client = factory.role_assignments
definitions_client = factory.role_definitions
ids = ids or []
if ids:
if assignee or role or resource_group_name or scope or include_inherited:
raise CLIError('When assignment ids are used, other parameter values are not required')
for i in ids:
assignments_client.delete_by_id(i)
return
if not any([ids, assignee, role, resource_group_name, scope, assignee, yes]):
from knack.prompting import prompt_y_n
msg = 'This will delete all role assignments under the subscription. Are you sure?'
if not prompt_y_n(msg, default="n"):
return
scope = _build_role_scope(resource_group_name, scope,
assignments_client.config.subscription_id)
assignments = _search_role_assignments(cli_ctx, assignments_client, definitions_client,
scope, assignee, role, include_inherited,
include_groups=False)
if assignments:
for a in assignments:
assignments_client.delete_by_id(a.id)
def _delete_role_assignments(cli_ctx, role, service_principal, delay=2, scope=None):
# AAD can have delays in propagating data, so sleep and retry
hook = cli_ctx.get_progress_controller(True)
hook.add(message='Waiting for AAD role to delete', value=0, total_val=1.0)
logger.info('Waiting for AAD role to delete')
for x in range(0, 10):
hook.add(message='Waiting for AAD role to delete', value=0.1 * x, total_val=1.0)
try:
delete_role_assignments(cli_ctx,
role=role,
assignee=service_principal,
scope=scope)
break
except CLIError as ex:
raise ex
except CloudError as ex:
logger.info(ex)
time.sleep(delay + delay * x)
else:
return False
hook.add(message='AAD role deletion done', value=1.0, total_val=1.0)
logger.info('AAD role deletion done')
return True
def _search_role_assignments(cli_ctx, assignments_client, definitions_client,
scope, assignee, role, include_inherited, include_groups):
assignee_object_id = None
if assignee:
assignee_object_id = _resolve_object_id(cli_ctx, assignee)
# always use "scope" if provided, so we can get assignments beyond subscription e.g. management groups
if scope:
assignments = list(assignments_client.list_for_scope(
scope=scope, filter='atScope()'))
elif assignee_object_id:
if include_groups:
f = "assignedTo('{}')".format(assignee_object_id)
else:
f = "principalId eq '{}'".format(assignee_object_id)
assignments = list(assignments_client.list(filter=f))
else:
assignments = list(assignments_client.list())
if assignments:
assignments = [a for a in assignments if (
not scope or
include_inherited and re.match(_get_role_property(a, 'scope'), scope, re.I) or
_get_role_property(a, 'scope').lower() == scope.lower()
)]
if role:
role_id = _resolve_role_id(role, scope, definitions_client)
assignments = [i for i in assignments if _get_role_property(
i, 'role_definition_id') == role_id]
if assignee_object_id:
assignments = [i for i in assignments if _get_role_property(
i, 'principal_id') == assignee_object_id]
return assignments
def _get_role_property(obj, property_name):
if isinstance(obj, dict):
return obj[property_name]
return getattr(obj, property_name)
def _get_default_dns_prefix(name, resource_group_name, subscription_id):
# Use subscription id to provide uniqueness and prevent DNS name clashes
name_part = re.sub('[^A-Za-z0-9-]', '', name)[0:10]
if not name_part[0].isalpha():
name_part = (str('a') + name_part)[0:10]
resource_group_part = re.sub('[^A-Za-z0-9-]', '', resource_group_name)[0:16]
return '{}-{}-{}'.format(name_part, resource_group_part, subscription_id[0:6])
def list_acs_locations(cmd, client):
return {
"productionRegions": regions_in_prod,
"previewRegions": regions_in_preview
}
def _generate_windows_profile(windows, admin_username, admin_password):
if windows:
if not admin_password:
raise CLIError('--admin-password is required.')
if len(admin_password) < 6:
raise CLIError('--admin-password must be at least 6 characters')
windows_profile = {
"adminUsername": admin_username,
"adminPassword": admin_password,
}
return windows_profile
return None
def _generate_master_pool_profile(api_version, master_profile, master_count, dns_name_prefix,
master_vm_size, master_osdisk_size, master_vnet_subnet_id,
master_first_consecutive_static_ip, master_storage_profile):
master_pool_profile = {}
default_master_pool_profile = {
"count": int(master_count),
"dnsPrefix": dns_name_prefix + 'mgmt',
}
if api_version == "2017-07-01":
default_master_pool_profile = _update_dict(default_master_pool_profile, {
"count": int(master_count),
"dnsPrefix": dns_name_prefix + 'mgmt',
"vmSize": master_vm_size,
"osDiskSizeGB": int(master_osdisk_size),
"vnetSubnetID": master_vnet_subnet_id,
"firstConsecutiveStaticIP": master_first_consecutive_static_ip,
"storageProfile": master_storage_profile,
})
if not master_profile:
master_pool_profile = default_master_pool_profile
else:
master_pool_profile = _update_dict(default_master_pool_profile, master_profile)
return master_pool_profile
def _generate_agent_pool_profiles(api_version, agent_profiles, agent_count, dns_name_prefix,
agent_vm_size, os_type, agent_osdisk_size, agent_vnet_subnet_id,
agent_ports, agent_storage_profile):
agent_pool_profiles = []
default_agent_pool_profile = {
"count": int(agent_count),
"vmSize": agent_vm_size,
"osType": os_type,
"dnsPrefix": dns_name_prefix + 'agent',
}
if api_version == "2017-07-01":
default_agent_pool_profile = _update_dict(default_agent_pool_profile, {
"count": int(agent_count),
"vmSize": agent_vm_size,
"osDiskSizeGB": int(agent_osdisk_size),
"osType": os_type,
"dnsPrefix": dns_name_prefix + 'agent',
"vnetSubnetID": agent_vnet_subnet_id,
"ports": agent_ports,
"storageProfile": agent_storage_profile,
})
if agent_profiles is None:
agent_pool_profiles.append(_update_dict(default_agent_pool_profile, {"name": "agentpool0"}))
else:
# override agentPoolProfiles by using the passed in agent_profiles
for idx, ap in enumerate(agent_profiles):
# if the user specified dnsPrefix, we honor that
# otherwise, we use the idx to avoid duplicate dns name
a = _update_dict({"dnsPrefix": dns_name_prefix + 'agent' + str(idx)}, ap)
agent_pool_profiles.append(_update_dict(default_agent_pool_profile, a))
return agent_pool_profiles
def _generate_outputs(name, orchestrator_type, admin_username):
# define outputs
outputs = {
"masterFQDN": {
"type": "string",
"value": "[reference(concat('Microsoft.ContainerService/containerServices/', '{}')).masterProfile.fqdn]".format(name) # pylint: disable=line-too-long
},
"sshMaster0": {
"type": "string",
"value": "[concat('ssh ', '{0}', '@', reference(concat('Microsoft.ContainerService/containerServices/', '{1}')).masterProfile.fqdn, ' -A -p 22')]".format(admin_username, name) # pylint: disable=line-too-long
},
}
if orchestrator_type.lower() != "kubernetes":
outputs["agentFQDN"] = {
"type": "string",
"value": "[reference(concat('Microsoft.ContainerService/containerServices/', '{}')).agentPoolProfiles[0].fqdn]".format(name) # pylint: disable=line-too-long
}
# override sshMaster0 for non-kubernetes scenarios
outputs["sshMaster0"] = {
"type": "string",
"value": "[concat('ssh ', '{0}', '@', reference(concat('Microsoft.ContainerService/containerServices/', '{1}')).masterProfile.fqdn, ' -A -p 2200')]".format(admin_username, name) # pylint: disable=line-too-long
}
return outputs
def _generate_properties(api_version, orchestrator_type, orchestrator_version, master_pool_profile,
agent_pool_profiles, ssh_key_value, admin_username, windows_profile):
properties = {
"orchestratorProfile": {
"orchestratorType": orchestrator_type,
},
"masterProfile": master_pool_profile,
"agentPoolProfiles": agent_pool_profiles,
"linuxProfile": {
"ssh": {
"publicKeys": [
{
"keyData": ssh_key_value
}
]
},
"adminUsername": admin_username
},
}
if api_version == "2017-07-01":
properties["orchestratorProfile"]["orchestratorVersion"] = orchestrator_version
if windows_profile is not None:
properties["windowsProfile"] = windows_profile
return properties
# pylint: disable=too-many-locals
def acs_create(cmd, client, resource_group_name, deployment_name, name, ssh_key_value, dns_name_prefix=None,
location=None, admin_username="azureuser", api_version=None, master_profile=None,
master_vm_size="Standard_D2_v2", master_osdisk_size=0, master_count=1, master_vnet_subnet_id="",
master_first_consecutive_static_ip="10.240.255.5", master_storage_profile="",
agent_profiles=None, agent_vm_size="Standard_D2_v2", agent_osdisk_size=0,
agent_count=3, agent_vnet_subnet_id="", agent_ports=None, agent_storage_profile="",
orchestrator_type="DCOS", orchestrator_version="", service_principal=None, client_secret=None, tags=None,
windows=False, admin_password="", generate_ssh_keys=False, # pylint: disable=unused-argument
validate=False, no_wait=False):
"""Create a new Acs.
:param resource_group_name: The name of the resource group. The name
is case insensitive.
:type resource_group_name: str
:param deployment_name: The name of the deployment.
:type deployment_name: str
:param dns_name_prefix: Sets the Domain name prefix for the cluster.
The concatenation of the domain name and the regionalized DNS zone
make up the fully qualified domain name associated with the public
IP address.
:type dns_name_prefix: str
:param name: Resource name for the container service.
:type name: str
:param ssh_key_value: Configure all linux machines with the SSH RSA
public key string. Your key should include three parts, for example
'ssh-rsa AAAAB...snip...UcyupgH azureuser@linuxvm
:type ssh_key_value: str
:param content_version: If included it must match the ContentVersion
in the template.
:type content_version: str
:param admin_username: User name for the Linux Virtual Machines.
:type admin_username: str
:param api_version: ACS API version to use
:type api_version: str
:param master_profile: MasterProfile used to describe master pool
:type master_profile: dict
:param master_vm_size: The size of master pool Virtual Machine
:type master_vm_size: str
:param master_osdisk_size: The osDisk size in GB of master pool Virtual Machine
:type master_osdisk_size: int
:param master_count: The number of masters for the cluster.
:type master_count: int
:param master_vnet_subnet_id: The vnet subnet id for master pool
:type master_vnet_subnet_id: str
:param master_storage_profile: The storage profile used for master pool.
Possible value could be StorageAccount, ManagedDisk.
:type master_storage_profile: str
:param agent_profiles: AgentPoolProfiles used to describe agent pools
:type agent_profiles: dict
:param agent_vm_size: The size of the Virtual Machine.
:type agent_vm_size: str
:param agent_osdisk_size: The osDisk size in GB of agent pool Virtual Machine
:type agent_osdisk_size: int
:param agent_vnet_subnet_id: The vnet subnet id for master pool
:type agent_vnet_subnet_id: str
:param agent_ports: the ports exposed on the agent pool
:type agent_ports: list
:param agent_storage_profile: The storage profile used for agent pool.
Possible value could be StorageAccount, ManagedDisk.
:type agent_storage_profile: str
:param location: Location for VM resources.
:type location: str
:param orchestrator_type: The type of orchestrator used to manage the
applications on the cluster.
:type orchestrator_type: str or :class:`orchestratorType
<Default.models.orchestratorType>`
:param tags: Tags object.
:type tags: object
:param windows: If true, the cluster will be built for running Windows container.
:type windows: bool
:param admin_password: The adminstration password for Windows nodes. Only available if --windows=true
:type admin_password: str
:param bool raw: returns the direct response alongside the
deserialized response
:rtype:
:class:`AzureOperationPoller<msrestazure.azure_operation.AzureOperationPoller>`
instance that returns :class:`DeploymentExtended
<Default.models.DeploymentExtended>`
:rtype: :class:`ClientRawResponse<msrest.pipeline.ClientRawResponse>`
if raw=true
:raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`
"""
if ssh_key_value is not None and not is_valid_ssh_rsa_public_key(ssh_key_value):
raise CLIError('Provided ssh key ({}) is invalid or non-existent'.format(ssh_key_value))
subscription_id = get_subscription_id(cmd.cli_ctx)
if not dns_name_prefix:
dns_name_prefix = _get_default_dns_prefix(name, resource_group_name, subscription_id)
rg_location = _get_rg_location(cmd.cli_ctx, resource_group_name)
if location is None:
location = rg_location
# if api-version is not specified, or specified in a version not supported
# override based on location
if api_version is None or api_version not in ["2017-01-31", "2017-07-01"]:
if location in regions_in_preview:
api_version = "2017-07-01" # 2017-07-01 supported in the preview locations
else:
api_version = "2017-01-31" # 2017-01-31 applied to other locations
if orchestrator_type.lower() == 'kubernetes':
principal_obj = _ensure_service_principal(cmd.cli_ctx, service_principal, client_secret, subscription_id,
dns_name_prefix, location, name)
client_secret = principal_obj.get("client_secret")
service_principal = principal_obj.get("service_principal")
elif windows:
raise CLIError('--windows is only supported for Kubernetes clusters')
# set location if void
if not location:
location = '[resourceGroup().location]'
# set os_type
os_type = 'Linux'
if windows:
os_type = 'Windows'
# set agent_ports if void
if not agent_ports:
agent_ports = []
# get windows_profile
windows_profile = _generate_windows_profile(windows, admin_username, admin_password)
# The resources.properties fields should match with ContainerServices' api model
master_pool_profile = _generate_master_pool_profile(api_version, master_profile, master_count, dns_name_prefix,
master_vm_size, master_osdisk_size, master_vnet_subnet_id,
master_first_consecutive_static_ip, master_storage_profile)
agent_pool_profiles = _generate_agent_pool_profiles(api_version, agent_profiles, agent_count, dns_name_prefix,
agent_vm_size, os_type, agent_osdisk_size, agent_vnet_subnet_id,
agent_ports, agent_storage_profile)
outputs = _generate_outputs(name, orchestrator_type, admin_username)
properties = _generate_properties(api_version, orchestrator_type, orchestrator_version, master_pool_profile,
agent_pool_profiles, ssh_key_value, admin_username, windows_profile)
resource = {
"apiVersion": api_version,
"location": location,
"type": "Microsoft.ContainerService/containerServices",
"name": name,
"tags": tags,
"properties": properties,
}
template = {
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"resources": [
resource,
],
"outputs": outputs,
}
params = {}
if service_principal is not None and client_secret is not None:
properties["servicePrincipalProfile"] = {
"clientId": service_principal,
"secret": "[parameters('clientSecret')]",
}
template["parameters"] = {
"clientSecret": {
"type": "secureString",
"metadata": {
"description": "The client secret for the service principal"
}
}
}
params = {
"clientSecret": {
"value": client_secret
}
}
# Due to SPN replication latency, we do a few retries here
max_retry = 30
retry_exception = Exception(None)
for _ in range(0, max_retry):
try:
return _invoke_deployment(cmd.cli_ctx, resource_group_name, deployment_name,
template, params, validate, no_wait)
except CloudError as ex:
retry_exception = ex
if 'is not valid according to the validation procedure' in ex.message or \
'The credentials in ServicePrincipalProfile were invalid' in ex.message or \
'not found in Active Directory tenant' in ex.message:
time.sleep(3)
else:
raise ex
raise retry_exception
def store_acs_service_principal(subscription_id, client_secret, service_principal,
file_name='acsServicePrincipal.json'):
obj = {}
if client_secret:
obj['client_secret'] = client_secret
if service_principal:
obj['service_principal'] = service_principal
config_path = os.path.join(get_config_dir(), file_name)
full_config = load_service_principals(config_path=config_path)
if not full_config:
full_config = {}
full_config[subscription_id] = obj
with os.fdopen(os.open(config_path, os.O_RDWR | os.O_CREAT | os.O_TRUNC, 0o600),
'w+') as spFile:
json.dump(full_config, spFile)
def load_acs_service_principal(subscription_id, file_name='acsServicePrincipal.json'):
config_path = os.path.join(get_config_dir(), file_name)
config = load_service_principals(config_path)
if not config:
return None
return config.get(subscription_id)
def load_service_principals(config_path):
if not os.path.exists(config_path):
return None
fd = os.open(config_path, os.O_RDONLY)
try:
with os.fdopen(fd) as f:
return shell_safe_json_parse(f.read())
except: # pylint: disable=bare-except
return None
def _invoke_deployment(cli_ctx, resource_group_name, deployment_name, template, parameters, validate, no_wait,
subscription_id=None):
from azure.cli.core.profiles import ResourceType, get_sdk
DeploymentProperties = get_sdk(cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES, 'DeploymentProperties', mod='models')
properties = DeploymentProperties(template=template, parameters=parameters, mode='incremental')
smc = get_mgmt_service_client(cli_ctx, ResourceType.MGMT_RESOURCE_RESOURCES,
subscription_id=subscription_id).deployments
if validate:
logger.info('==== BEGIN TEMPLATE ====')
logger.info(json.dumps(template, indent=2))
logger.info('==== END TEMPLATE ====')
return smc.validate(resource_group_name, deployment_name, properties)
return sdk_no_wait(no_wait, smc.create_or_update, resource_group_name, deployment_name, properties)
def k8s_get_credentials(cmd, client, name, resource_group_name,
path=os.path.join(os.path.expanduser('~'), '.kube', 'config'),
ssh_key_file=None,
overwrite_existing=False):
"""Download and install kubectl credentials from the cluster master
:param name: The name of the cluster.
:type name: str
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param path: Where to install the kubectl config file
:type path: str
:param ssh_key_file: Path to an SSH key file to use
:type ssh_key_file: str
"""
acs_info = _get_acs_info(cmd.cli_ctx, name, resource_group_name)
_k8s_get_credentials_internal(name, acs_info, path, ssh_key_file, overwrite_existing)
def _k8s_get_credentials_internal(name, acs_info, path, ssh_key_file, overwrite_existing):
if ssh_key_file is not None and not os.path.isfile(ssh_key_file):
raise CLIError('Private key file {} does not exist'.format(ssh_key_file))
dns_prefix = acs_info.master_profile.dns_prefix # pylint: disable=no-member
location = acs_info.location # pylint: disable=no-member
user = acs_info.linux_profile.admin_username # pylint: disable=no-member
_mkdir_p(os.path.dirname(path))
path_candidate = path
ix = 0
while os.path.exists(path_candidate):
ix += 1
path_candidate = '{}-{}-{}'.format(path, name, ix)
# TODO: this only works for public cloud, need other casing for national clouds
acs_client.secure_copy(user, '{}.{}.cloudapp.azure.com'.format(dns_prefix, location),
'.kube/config', path_candidate, key_filename=ssh_key_file)
# merge things
if path_candidate != path:
try:
merge_kubernetes_configurations(path, path_candidate, overwrite_existing)
except yaml.YAMLError as exc:
logger.warning('Failed to merge credentials to kube config file: %s', exc)
logger.warning('The credentials have been saved to %s', path_candidate)
def _handle_merge(existing, addition, key, replace):
if not addition.get(key, False):
return
if existing[key] is None:
existing[key] = addition[key]
return
for i in addition[key]:
for j in existing[key]:
if not i.get('name', False) or not j.get('name', False):
continue
if i['name'] == j['name']:
if replace or i == j:
existing[key].remove(j)
else:
from knack.prompting import prompt_y_n, NoTTYException
msg = 'A different object named {} already exists in your kubeconfig file.\nOverwrite?'
overwrite = False
try:
overwrite = prompt_y_n(msg.format(i['name']))
except NoTTYException:
pass
if overwrite:
existing[key].remove(j)
else:
msg = 'A different object named {} already exists in {} in your kubeconfig file.'
raise CLIError(msg.format(i['name'], key))
existing[key].append(i)
def load_kubernetes_configuration(filename):
try:
with open(filename) as stream:
return yaml.safe_load(stream)
except (IOError, OSError) as ex:
if getattr(ex, 'errno', 0) == errno.ENOENT:
raise CLIError('{} does not exist'.format(filename))
raise
except (yaml.parser.ParserError, UnicodeDecodeError) as ex:
raise CLIError('Error parsing {} ({})'.format(filename, str(ex)))
def merge_kubernetes_configurations(existing_file, addition_file, replace, context_name=None):
existing = load_kubernetes_configuration(existing_file)
addition = load_kubernetes_configuration(addition_file)
if context_name is not None:
addition['contexts'][0]['name'] = context_name
addition['contexts'][0]['context']['cluster'] = context_name
addition['clusters'][0]['name'] = context_name
addition['current-context'] = context_name
# rename the admin context so it doesn't overwrite the user context
for ctx in addition.get('contexts', []):
try:
if ctx['context']['user'].startswith('clusterAdmin'):
admin_name = ctx['name'] + '-admin'
addition['current-context'] = ctx['name'] = admin_name
break
except (KeyError, TypeError):
continue
if addition is None:
raise CLIError('failed to load additional configuration from {}'.format(addition_file))
if existing is None:
existing = addition
else:
_handle_merge(existing, addition, 'clusters', replace)
_handle_merge(existing, addition, 'users', replace)
_handle_merge(existing, addition, 'contexts', replace)
existing['current-context'] = addition['current-context']
# check that ~/.kube/config is only read- and writable by its owner
if platform.system() != 'Windows':
existing_file_perms = "{:o}".format(stat.S_IMODE(os.lstat(existing_file).st_mode))
if not existing_file_perms.endswith('600'):
logger.warning('%s has permissions "%s".\nIt should be readable and writable only by its owner.',
existing_file, existing_file_perms)
with open(existing_file, 'w+') as stream:
yaml.safe_dump(existing, stream, default_flow_style=False)
current_context = addition.get('current-context', 'UNKNOWN')
msg = 'Merged "{}" as current context in {}'.format(current_context, existing_file)
print(msg)
def _get_host_name(acs_info):
"""
Gets the FQDN from the acs_info object.
:param acs_info: ContainerService object from Azure REST API
:type acs_info: ContainerService
"""
if acs_info is None:
raise CLIError('Missing acs_info')
if acs_info.master_profile is None:
raise CLIError('Missing master_profile')
if acs_info.master_profile.fqdn is None:
raise CLIError('Missing fqdn')
return acs_info.master_profile.fqdn
def _get_username(acs_info):
"""
Gets the admin user name from the Linux profile of the ContainerService object.
:param acs_info: ContainerService object from Azure REST API
:type acs_info: ContainerService
"""
if acs_info.linux_profile is not None:
return acs_info.linux_profile.admin_username
return None
def _get_acs_info(cli_ctx, name, resource_group_name):
"""
Gets the ContainerService object from Azure REST API.
:param name: ACS resource name
:type name: String
:param resource_group_name: Resource group name
:type resource_group_name: String
"""
container_services = cf_container_services(cli_ctx, None)
return container_services.get(resource_group_name, name)
def _rand_str(n):
"""
Gets a random string
"""
choices = string.ascii_lowercase + string.digits
return ''.join(random.SystemRandom().choice(choices) for _ in range(n))
def _mkdir_p(path):
# http://stackoverflow.com/a/600612
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def update_acs(cmd, client, resource_group_name, container_service_name, new_agent_count):
instance = client.get(resource_group_name, container_service_name)
instance.agent_pool_profiles[0].count = new_agent_count # pylint: disable=no-member
# null out the service principal because otherwise validation complains
if instance.orchestrator_profile.orchestrator_type == ContainerServiceOrchestratorTypes.kubernetes:
instance.service_principal_profile = None
# null out the windows profile so that validation doesn't complain about not having the admin password
instance.windows_profile = None
return client.create_or_update(resource_group_name, container_service_name, instance)
def list_container_services(cmd, client, resource_group_name=None):
''' List Container Services. '''
svc_list = client.list_by_resource_group(resource_group_name=resource_group_name) \
if resource_group_name else client.list()
return list(svc_list)
def show_service_principal(client, identifier):
object_id = _resolve_service_principal(client, identifier)
return client.get(object_id)
def _resolve_service_principal(client, identifier):
# todo: confirm with graph team that a service principal name must be unique
result = list(client.list(filter="servicePrincipalNames/any(c:c eq '{}')".format(identifier)))
if result:
return result[0].object_id
try:
uuid.UUID(identifier)
return identifier # assume an object id
except ValueError:
raise CLIError("service principal '{}' doesn't exist".format(identifier))
def create_application(client, display_name, homepage, identifier_uris,
available_to_other_tenants=False, password=None, reply_urls=None,
key_value=None, key_type=None, key_usage=None, start_date=None,
end_date=None, required_resource_accesses=None):
from azure.graphrbac.models import GraphErrorException
password_creds, key_creds = _build_application_creds(password, key_value, key_type,
key_usage, start_date, end_date)
app_create_param = ApplicationCreateParameters(available_to_other_tenants=available_to_other_tenants,
display_name=display_name,
identifier_uris=identifier_uris,
homepage=homepage,
reply_urls=reply_urls,
key_credentials=key_creds,
password_credentials=password_creds,
required_resource_access=required_resource_accesses)
try:
return client.create(app_create_param)
except GraphErrorException as ex:
if 'insufficient privileges' in str(ex).lower():
link = 'https://docs.microsoft.com/azure/azure-resource-manager/resource-group-create-service-principal-portal' # pylint: disable=line-too-long
raise CLIError("Directory permission is needed for the current user to register the application. "
"For how to configure, please refer '{}'. Original error: {}".format(link, ex))
raise
def
|
(client, object_id, display_name, homepage, identifier_uris,
available_to_other_tenants=False, password=None, reply_urls=None,
key_value=None, key_type=None, key_usage=None, start_date=None,
end_date=None, required_resource_accesses=None):
from azure.graphrbac.models import GraphErrorException
password_creds, key_creds = _build_application_creds(password, key_value, key_type,
key_usage, start_date, end_date)
try:
if key_creds:
client.update_key_credentials(object_id, key_creds)
if password_creds:
client.update_password_credentials(object_id, password_creds)
if reply_urls:
client.patch(object_id, ApplicationUpdateParameters(reply_urls=reply_urls))
return
except GraphErrorException as ex:
if 'insufficient privileges' in str(ex).lower():
link = 'https://docs.microsoft.com/azure/azure-resource-manager/resource-group-create-service-principal-portal' # pylint: disable=line-too-long
raise CLIError("Directory permission is needed for the current user to register the application. "
"For how to configure, please refer '{}'. Original error: {}".format(link, ex))
raise
def _build_application_creds(password=None, key_value=None, key_type=None,
key_usage=None, start_date=None, end_date=None):
if password and key_value:
raise CLIError('specify either --password or --key-value, but not both.')
if not start_date:
start_date = datetime.datetime.utcnow()
elif isinstance(start_date, str):
start_date = dateutil.parser.parse(start_date)
if not end_date:
end_date = start_date + relativedelta(years=1)
elif isinstance(end_date, str):
end_date = dateutil.parser.parse(end_date)
key_type = key_type or 'AsymmetricX509Cert'
key_usage = key_usage or 'Verify'
password_creds = None
key_creds = None
if password:
password_creds = [PasswordCredential(start_date=start_date, end_date=end_date,
key_id=str(uuid.uuid4()), value=password)]
elif key_value:
key_creds = [KeyCredential(start_date=start_date, end_date=end_date, value=key_value,
key_id=str(uuid.uuid4()), usage=key_usage, type=key_type)]
return (password_creds, key_creds)
def create_service_principal(cli_ctx, identifier, resolve_app=True, rbac_client=None):
if rbac_client is None:
rbac_client = get_graph_rbac_management_client(cli_ctx)
if resolve_app:
try:
uuid.UUID(identifier)
result = list(rbac_client.applications.list(filter="appId eq '{}'".format(identifier)))
except ValueError:
result = list(rbac_client.applications.list(
filter="identifierUris/any(s:s eq '{}')".format(identifier)))
if not result: # assume we get an object id
result = [rbac_client.applications.get(identifier)]
app_id = result[0].app_id
else:
app_id = identifier
return rbac_client.service_principals.create(ServicePrincipalCreateParameters(app_id=app_id, account_enabled=True))
def create_role_assignment(cli_ctx, role, assignee, resource_group_name=None, scope=None):
return _create_role_assignment(cli_ctx, role, assignee, resource_group_name, scope)
def _create_role_assignment(cli_ctx, role, assignee, resource_group_name=None, scope=None, resolve_assignee=True):
from azure.cli.core.profiles import ResourceType, get_sdk
factory = get_auth_management_client(cli_ctx, scope)
assignments_client = factory.role_assignments
definitions_client = factory.role_definitions
scope = _build_role_scope(resource_group_name, scope, assignments_client.config.subscription_id)
role_id = _resolve_role_id(role, scope, definitions_client)
object_id = _resolve_object_id(cli_ctx, assignee) if resolve_assignee else assignee
RoleAssignmentCreateParameters = get_sdk(cli_ctx, ResourceType.MGMT_AUTHORIZATION,
'RoleAssignmentCreateParameters', mod='models',
operation_group='role_assignments')
parameters = RoleAssignmentCreateParameters(role_definition_id=role_id, principal_id=object_id)
assignment_name = uuid.uuid4()
custom_headers = None
return assignments_client.create(scope, assignment_name, parameters, custom_headers=custom_headers)
def _build_role_scope(resource_group_name, scope, subscription_id):
subscription_scope = '/subscriptions/' + subscription_id
if scope:
if resource_group_name:
err = 'Resource group "{}" is redundant because scope is supplied'
raise CLIError(err.format(resource_group_name))
elif resource_group_name:
scope = subscription_scope + '/resourceGroups/' + resource_group_name
else:
scope = subscription_scope
return scope
def _resolve_role_id(role, scope, definitions_client):
role_id = None
try:
uuid.UUID(role)
role_id = role
except ValueError:
pass
if not role_id: # retrieve role id
role_defs = list(definitions_client.list(scope, "roleName eq '{}'".format(role)))
if not role_defs:
raise CLIError("Role '{}' doesn't exist.".format(role))
if len(role_defs) > 1:
ids = [r.id for r in role_defs]
err = "More than one role matches the given name '{}'. Please pick a value from '{}'"
raise CLIError(err.format(role, ids))
role_id = role_defs[0].id
return role_id
def _resolve_object_id(cli_ctx, assignee):
client = get_graph_rbac_management_client(cli_ctx)
result = None
if assignee.find('@') >= 0: # looks like a user principal name
result = list(client.users.list(filter="userPrincipalName eq '{}'".format(assignee)))
if not result:
result = list(client.service_principals.list(
filter="servicePrincipalNames/any(c:c eq '{}')".format(assignee)))
if not result: # assume an object id, let us verify it
result = _get_object_stubs(client, [assignee])
# 2+ matches should never happen, so we only check 'no match' here
if not result:
raise CLIError("No matches in graph database for '{}'".format(assignee))
return result[0].object_id
def _get_object_stubs(graph_client, assignees):
params = GetObjectsParameters(include_directory_object_references=True,
object_ids=assignees)
return list(graph_client.objects.get_objects_by_object_ids(params))
def _update_dict(dict1, dict2):
cp = dict1.copy()
cp.update(dict2)
return cp
def subnet_role_assignment_exists(cli_ctx, scope):
network_contributor_role_id = "4d97b98b-1d4f-4787-a291-c67834d212e7"
factory = get_auth_management_client(cli_ctx, scope)
assignments_client = factory.role_assignments
for i in assignments_client.list_for_scope(scope=scope, filter='atScope()'):
if i.scope == scope and i.role_definition_id.endswith(network_contributor_role_id):
return True
return False
# pylint: disable=too-many-statements
def aks_browse(cmd, client, resource_group_name, name, disable_browser=False,
listen_address='127.0.0.1', listen_port='8001'):
if not which('kubectl'):
raise CLIError('Can not find kubectl executable in PATH')
# verify the kube-dashboard addon was not disabled
instance = client.get(resource_group_name, name)
addon_profiles = instance.addon_profiles or {}
addon_profile = addon_profiles.get("kubeDashboard", ManagedClusterAddonProfile(enabled=True))
if not addon_profile.enabled:
raise CLIError('The kube-dashboard addon was disabled for this managed cluster.\n'
'To use "az aks browse" first enable the add-on\n'
'by running "az aks enable-addons --addons kube-dashboard".')
_, browse_path = tempfile.mkstemp()
aks_get_credentials(cmd, client, resource_group_name, name, admin=False, path=browse_path)
# find the dashboard pod's name
try:
dashboard_pod = subprocess.check_output(
["kubectl", "get", "pods", "--kubeconfig", browse_path, "--namespace", "kube-system",
"--output", "name", "--selector", "k8s-app=kubernetes-dashboard"],
universal_newlines=True)
except subprocess.CalledProcessError as err:
raise CLIError('Could not find dashboard pod: {}'.format(err))
if dashboard_pod:
# remove any "pods/" or "pod/" prefix from the name
dashboard_pod = str(dashboard_pod).split('/')[-1].strip()
else:
raise CLIError("Couldn't find the Kubernetes dashboard pod.")
# find the port
try:
dashboard_port = subprocess.check_output(
["kubectl", "get", "pods", "--kubeconfig", browse_path, "--namespace", "kube-system",
"--selector", "k8s-app=kubernetes-dashboard",
"--output", "jsonpath='{.items[0].spec.containers[0].ports[0].containerPort}'"]
)
# output format: b"'{port}'"
dashboard_port = int((dashboard_port.decode('utf-8').replace("'", "")))
except subprocess.CalledProcessError as err:
raise CLIError('Could not find dashboard port: {}'.format(err))
# use https if dashboard container is using https
if dashboard_port == 8443:
protocol = 'https'
else:
protocol = 'http'
proxy_url = '{0}://{1}:{2}/'.format(protocol, listen_address, listen_port)
# launch kubectl port-forward locally to access the remote dashboard
if in_cloud_console():
# TODO: better error handling here.
response = requests.post('http://localhost:8888/openport/{0}'.format(listen_port))
result = json.loads(response.text)
term_id = os.environ.get('ACC_TERM_ID')
if term_id:
response = requests.post('http://localhost:8888/openLink/{}'.format(term_id),
json={"url": result['url']})
logger.warning('To view the console, please open %s in a new tab', result['url'])
else:
logger.warning('Proxy running on %s', proxy_url)
logger.warning('Press CTRL+C to close the tunnel...')
if not disable_browser:
wait_then_open_async(proxy_url)
try:
try:
subprocess.check_output(["kubectl", "--kubeconfig", browse_path, "--namespace", "kube-system",
"port-forward", "--address", listen_address, dashboard_pod,
"{0}:{1}".format(listen_port, dashboard_port)], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as err:
if err.output.find(b'unknown flag: --address'):
if listen_address != '127.0.0.1':
logger.warning('"--address" is only supported in kubectl v1.13 and later.')
logger.warning('The "--listen-address" argument will be ignored.')
subprocess.call(["kubectl", "--kubeconfig", browse_path, "--namespace", "kube-system",
"port-forward", dashboard_pod, "{0}:{1}".format(listen_port, dashboard_port)])
except KeyboardInterrupt:
# Let command processing finish gracefully after the user presses [Ctrl+C]
pass
finally:
if in_cloud_console():
requests.post('http://localhost:8888/closeport/8001')
def _trim_nodepoolname(nodepool_name):
if not nodepool_name:
return "nodepool1"
return nodepool_name[:12]
def _validate_ssh_key(no_ssh_key, ssh_key_value):
if not no_ssh_key:
try:
if not ssh_key_value or not is_valid_ssh_rsa_public_key(ssh_key_value):
raise ValueError()
except (TypeError, ValueError):
shortened_key = truncate_text(ssh_key_value)
raise CLIError('Provided ssh key ({}) is invalid or non-existent'.format(shortened_key))
# pylint: disable=too-many-statements,too-many-branches
def aks_create(cmd, client, resource_group_name, name, ssh_key_value, # pylint: disable=too-many-locals
dns_name_prefix=None,
location=None,
admin_username="azureuser",
kubernetes_version='',
node_vm_size="Standard_DS2_v2",
node_osdisk_size=0,
node_count=3,
nodepool_name="nodepool1",
service_principal=None, client_secret=None,
no_ssh_key=False,
disable_rbac=None,
enable_rbac=None,
vm_set_type=None,
skip_subnet_role_assignment=False,
enable_cluster_autoscaler=False,
network_plugin=None,
network_policy=None,
pod_cidr=None,
service_cidr=None,
dns_service_ip=None,
docker_bridge_address=None,
load_balancer_sku=None,
load_balancer_managed_outbound_ip_count=None,
load_balancer_outbound_ips=None,
load_balancer_outbound_ip_prefixes=None,
enable_addons=None,
workspace_resource_id=None,
vnet_subnet_id=None,
max_pods=0,
min_count=None,
max_count=None,
aad_client_app_id=None,
aad_server_app_id=None,
aad_server_app_secret=None,
aad_tenant_id=None,
tags=None,
zones=None,
generate_ssh_keys=False, # pylint: disable=unused-argument
api_server_authorized_ip_ranges=None,
attach_acr=None,
no_wait=False):
_validate_ssh_key(no_ssh_key, ssh_key_value)
subscription_id = get_subscription_id(cmd.cli_ctx)
if not dns_name_prefix:
dns_name_prefix = _get_default_dns_prefix(name, resource_group_name, subscription_id)
rg_location = _get_rg_location(cmd.cli_ctx, resource_group_name)
if location is None:
location = rg_location
vm_set_type = _set_vm_set_type(vm_set_type, kubernetes_version)
load_balancer_sku = _set_load_balancer_sku(load_balancer_sku, kubernetes_version)
if api_server_authorized_ip_ranges and load_balancer_sku == "basic":
raise CLIError('--api-server-authorized-ip-ranges can only be used with standard load balancer')
agent_pool_profile = ManagedClusterAgentPoolProfile(
name=_trim_nodepoolname(nodepool_name), # Must be 12 chars or less before ACS RP adds to it
count=int(node_count),
vm_size=node_vm_size,
os_type="Linux",
storage_profile=ContainerServiceStorageProfileTypes.managed_disks,
vnet_subnet_id=vnet_subnet_id,
availability_zones=zones,
max_pods=int(max_pods) if max_pods else None,
type=vm_set_type
)
if node_osdisk_size:
agent_pool_profile.os_disk_size_gb = int(node_osdisk_size)
_check_cluster_autoscaler_flag(enable_cluster_autoscaler, min_count, max_count, node_count, agent_pool_profile)
linux_profile = None
# LinuxProfile is just used for SSH access to VMs, so omit it if --no-ssh-key was specified.
if not no_ssh_key:
ssh_config = ContainerServiceSshConfiguration(
public_keys=[ContainerServiceSshPublicKey(key_data=ssh_key_value)])
linux_profile = ContainerServiceLinuxProfile(admin_username=admin_username, ssh=ssh_config)
principal_obj = _ensure_aks_service_principal(cmd.cli_ctx,
service_principal=service_principal, client_secret=client_secret,
subscription_id=subscription_id, dns_name_prefix=dns_name_prefix,
location=location, name=name)
service_principal_profile = ManagedClusterServicePrincipalProfile(
client_id=principal_obj.get("service_principal"),
secret=principal_obj.get("client_secret"),
key_vault_secret_ref=None)
if (vnet_subnet_id and not skip_subnet_role_assignment and
not subnet_role_assignment_exists(cmd.cli_ctx, vnet_subnet_id)):
scope = vnet_subnet_id
if not _add_role_assignment(cmd.cli_ctx, 'Network Contributor',
service_principal_profile.client_id, scope=scope):
logger.warning('Could not create a role assignment for subnet. '
'Are you an Owner on this subscription?')
load_balancer_profile = _get_load_balancer_profile(
load_balancer_managed_outbound_ip_count,
load_balancer_outbound_ips,
load_balancer_outbound_ip_prefixes)
if attach_acr:
_ensure_aks_acr(cmd.cli_ctx,
client_id=service_principal_profile.client_id,
acr_name_or_id=attach_acr,
subscription_id=subscription_id)
network_profile = None
if any([network_plugin, pod_cidr, service_cidr, dns_service_ip, docker_bridge_address, network_policy]):
if not network_plugin:
raise CLIError('Please explicitly specify the network plugin type')
if pod_cidr and network_plugin == "azure":
raise CLIError('Please use kubenet as the network plugin type when pod_cidr is specified')
network_profile = ContainerServiceNetworkProfile(
network_plugin=network_plugin,
pod_cidr=pod_cidr,
service_cidr=service_cidr,
dns_service_ip=dns_service_ip,
docker_bridge_cidr=docker_bridge_address,
network_policy=network_policy,
load_balancer_sku=load_balancer_sku.lower(),
load_balancer_profile=load_balancer_profile,
)
else:
if load_balancer_sku.lower() == "standard" or load_balancer_profile:
network_profile = ContainerServiceNetworkProfile(
network_plugin="kubenet",
load_balancer_sku=load_balancer_sku.lower(),
load_balancer_profile=load_balancer_profile,
)
addon_profiles = _handle_addons_args(
cmd,
enable_addons,
subscription_id,
resource_group_name,
{},
workspace_resource_id
)
monitoring = False
if 'omsagent' in addon_profiles:
monitoring = True
_ensure_container_insights_for_monitoring(cmd, addon_profiles['omsagent'])
aad_profile = None
if any([aad_client_app_id, aad_server_app_id, aad_server_app_secret, aad_tenant_id]):
if aad_tenant_id is None:
profile = Profile(cli_ctx=cmd.cli_ctx)
_, _, aad_tenant_id = profile.get_login_credentials()
aad_profile = ManagedClusterAADProfile(
client_app_id=aad_client_app_id,
server_app_id=aad_server_app_id,
server_app_secret=aad_server_app_secret,
tenant_id=aad_tenant_id
)
api_server_access_profile = None
if api_server_authorized_ip_ranges:
api_server_access_profile = _populate_api_server_access_profile(api_server_authorized_ip_ranges)
# Check that both --disable-rbac and --enable-rbac weren't provided
if all([disable_rbac, enable_rbac]):
raise CLIError('specify either "--disable-rbac" or "--enable-rbac", not both.')
mc = ManagedCluster(
location=location,
tags=tags,
dns_prefix=dns_name_prefix,
kubernetes_version=kubernetes_version,
enable_rbac=not disable_rbac,
agent_pool_profiles=[agent_pool_profile],
linux_profile=linux_profile,
service_principal_profile=service_principal_profile,
network_profile=network_profile,
addon_profiles=addon_profiles,
aad_profile=aad_profile,
api_server_access_profile=api_server_access_profile
)
# Due to SPN replication latency, we do a few retries here
max_retry = 30
retry_exception = Exception(None)
for _ in range(0, max_retry):
try:
result = sdk_no_wait(no_wait,
client.create_or_update,
resource_group_name=resource_group_name,
resource_name=name, parameters=mc)
# add cluster spn with Monitoring Metrics Publisher role assignment to the cluster resource
# mdm metrics supported only in azure public cloud so add the role assignment only in this cloud
cloud_name = cmd.cli_ctx.cloud.name
if cloud_name.lower() == 'azurecloud' and monitoring:
from msrestazure.tools import resource_id
cluster_resource_id = resource_id(
subscription=subscription_id,
resource_group=resource_group_name,
namespace='Microsoft.ContainerService', type='managedClusters',
name=name
)
if not _add_role_assignment(cmd.cli_ctx, 'Monitoring Metrics Publisher',
service_principal_profile.client_id, scope=cluster_resource_id):
logger.warning('Could not create a role assignment for monitoring addon. '
'Are you an Owner on this subscription?')
return result
except CloudError as ex:
retry_exception = ex
if 'not found in Active Directory tenant' in ex.message:
time.sleep(3)
else:
raise ex
raise retry_exception
def aks_disable_addons(cmd, client, resource_group_name, name, addons, no_wait=False):
instance = client.get(resource_group_name, name)
subscription_id = get_subscription_id(cmd.cli_ctx)
instance = _update_addons(
cmd,
instance,
subscription_id,
resource_group_name,
addons,
enable=False,
no_wait=no_wait
)
# send the managed cluster representation to update the addon profiles
return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, name, instance)
def aks_enable_addons(cmd, client, resource_group_name, name, addons, workspace_resource_id=None,
subnet_name=None, no_wait=False):
instance = client.get(resource_group_name, name)
subscription_id = get_subscription_id(cmd.cli_ctx)
service_principal_client_id = instance.service_principal_profile.client_id
instance = _update_addons(cmd, instance, subscription_id, resource_group_name, addons, enable=True,
workspace_resource_id=workspace_resource_id, subnet_name=subnet_name, no_wait=no_wait)
if 'omsagent' in instance.addon_profiles:
_ensure_container_insights_for_monitoring(cmd, instance.addon_profiles['omsagent'])
cloud_name = cmd.cli_ctx.cloud.name
# mdm metrics supported only in Azure Public cloud so add the role assignment only in this cloud
if cloud_name.lower() == 'azurecloud':
from msrestazure.tools import resource_id
cluster_resource_id = resource_id(
subscription=subscription_id,
resource_group=resource_group_name,
namespace='Microsoft.ContainerService', type='managedClusters',
name=name
)
if not _add_role_assignment(cmd.cli_ctx, 'Monitoring Metrics Publisher',
service_principal_client_id, scope=cluster_resource_id):
logger.warning('Could not create a role assignment for Monitoring addon. '
'Are you an Owner on this subscription?')
# send the managed cluster representation to update the addon profiles
return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, name, instance)
def aks_get_versions(cmd, client, location):
return client.list_orchestrators(location, resource_type='managedClusters')
def aks_get_credentials(cmd, client, resource_group_name, name, admin=False,
path=os.path.join(os.path.expanduser('~'), '.kube', 'config'),
overwrite_existing=False, context_name=None):
credentialResults = None
if admin:
credentialResults = client.list_cluster_admin_credentials(resource_group_name, name)
else:
credentialResults = client.list_cluster_user_credentials(resource_group_name, name)
if not credentialResults:
raise CLIError("No Kubernetes credentials found.")
try:
kubeconfig = credentialResults.kubeconfigs[0].value.decode(encoding='UTF-8')
_print_or_merge_credentials(path, kubeconfig, overwrite_existing, context_name)
except (IndexError, ValueError):
raise CLIError("Fail to find kubeconfig file.")
ADDONS = {
'http_application_routing': 'httpApplicationRouting',
'monitoring': 'omsagent',
'virtual-node': 'aciConnector',
'kube-dashboard': 'kubeDashboard'
}
def aks_list(cmd, client, resource_group_name=None):
if resource_group_name:
managed_clusters = client.list_by_resource_group(resource_group_name)
else:
managed_clusters = client.list()
return _remove_nulls(list(managed_clusters))
def aks_show(cmd, client, resource_group_name, name):
mc = client.get(resource_group_name, name)
return _remove_nulls([mc])[0]
def aks_update_credentials(cmd, client, resource_group_name, name,
reset_service_principal=False,
reset_aad=False,
service_principal=None,
client_secret=None,
aad_server_app_id=None,
aad_server_app_secret=None,
aad_client_app_id=None,
aad_tenant_id=None,
no_wait=False):
if bool(reset_service_principal) == bool(reset_aad):
raise CLIError('usage error: --reset-service-principal | --reset-aad-profile')
if reset_service_principal:
if service_principal is None or client_secret is None:
raise CLIError('usage error: --reset-service-principal --service-principal ID --client-secret SECRET')
return sdk_no_wait(no_wait,
client.reset_service_principal_profile,
resource_group_name,
name, service_principal, client_secret)
if not all([aad_client_app_id, aad_server_app_id, aad_server_app_secret]):
raise CLIError('usage error: --reset-aad --aad-client-app-id ID --aad-server-app-id ID '
'--aad-server-app-secret SECRET [--aad-tenant-id ID]')
parameters = {
'clientAppID': aad_client_app_id,
'serverAppID': aad_server_app_id,
'serverAppSecret': aad_server_app_secret,
'tenantID': aad_tenant_id
}
return sdk_no_wait(no_wait,
client.reset_aad_profile,
resource_group_name,
name, parameters)
def aks_scale(cmd, client, resource_group_name, name, node_count, nodepool_name="", no_wait=False):
instance = client.get(resource_group_name, name)
if len(instance.agent_pool_profiles) > 1 and nodepool_name == "":
raise CLIError('There are more than one node pool in the cluster. '
'Please specify nodepool name or use az aks nodepool command to scale node pool')
if node_count == 0:
raise CLIError("Can't scale down to 0 nodes.")
for agent_profile in instance.agent_pool_profiles:
if agent_profile.name == nodepool_name or (nodepool_name == "" and len(instance.agent_pool_profiles) == 1):
agent_profile.count = int(node_count) # pylint: disable=no-member
# null out the SP and AAD profile because otherwise validation complains
instance.service_principal_profile = None
instance.aad_profile = None
return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, name, instance)
raise CLIError('The nodepool "{}" was not found.'.format(nodepool_name))
# pylint: disable=inconsistent-return-statements
def aks_update(cmd, client, resource_group_name, name,
enable_cluster_autoscaler=False,
disable_cluster_autoscaler=False,
update_cluster_autoscaler=False,
min_count=None, max_count=None,
load_balancer_managed_outbound_ip_count=None,
load_balancer_outbound_ips=None,
load_balancer_outbound_ip_prefixes=None,
attach_acr=None,
detach_acr=None,
api_server_authorized_ip_ranges=None,
no_wait=False):
update_autoscaler = enable_cluster_autoscaler + disable_cluster_autoscaler + update_cluster_autoscaler
update_lb_profile = load_balancer_managed_outbound_ip_count is not None or \
load_balancer_outbound_ips is not None or load_balancer_outbound_ip_prefixes is not None
if (update_autoscaler != 1 and not update_lb_profile and
not attach_acr and
not detach_acr and
api_server_authorized_ip_ranges is None):
raise CLIError('Please specify one or more of "--enable-cluster-autoscaler" or '
'"--disable-cluster-autoscaler" or '
'"--update-cluster-autoscaler" or '
'"--load-balancer-managed-outbound-ip-count",'
'"--load-balancer-outbound-ips",'
'"--load-balancer-outbound-ip-prefixes",'
'"--attach-acr" or "--dettach-acr",'
'"--"api-server-authorized-ip-ranges')
instance = client.get(resource_group_name, name)
# For multi-agent pool, use the az aks nodepool command
if update_autoscaler > 0 and len(instance.agent_pool_profiles) > 1:
raise CLIError('There are more than one node pool in the cluster. Please use "az aks nodepool" command '
'to update per node pool auto scaler settings')
node_count = instance.agent_pool_profiles[0].count
_validate_autoscaler_update_counts(min_count, max_count, node_count, enable_cluster_autoscaler or
update_cluster_autoscaler)
if enable_cluster_autoscaler:
if instance.agent_pool_profiles[0].enable_auto_scaling:
logger.warning('Cluster autoscaler is already enabled for this node pool.\n'
'Please run "az aks --update-cluster-autoscaler" '
'if you want to update min-count or max-count.')
return None
instance.agent_pool_profiles[0].min_count = int(min_count)
instance.agent_pool_profiles[0].max_count = int(max_count)
instance.agent_pool_profiles[0].enable_auto_scaling = True
if update_cluster_autoscaler:
if not instance.agent_pool_profiles[0].enable_auto_scaling:
raise CLIError('Cluster autoscaler is not enabled for this node pool.\n'
'Run "az aks nodepool update --enable-cluster-autoscaler" '
'to enable cluster with min-count and max-count.')
instance.agent_pool_profiles[0].min_count = int(min_count)
instance.agent_pool_profiles[0].max_count = int(max_count)
if disable_cluster_autoscaler:
if not instance.agent_pool_profiles[0].enable_auto_scaling:
logger.warning('Cluster autoscaler is already disabled for this node pool.')
return None
instance.agent_pool_profiles[0].enable_auto_scaling = False
instance.agent_pool_profiles[0].min_count = None
instance.agent_pool_profiles[0].max_count = None
subscription_id = get_subscription_id(cmd.cli_ctx)
client_id = instance.service_principal_profile.client_id
if not client_id:
raise CLIError('Cannot get the AKS cluster\'s service principal.')
if attach_acr:
_ensure_aks_acr(cmd.cli_ctx,
client_id=client_id,
acr_name_or_id=attach_acr,
subscription_id=subscription_id)
if detach_acr:
_ensure_aks_acr(cmd.cli_ctx,
client_id=client_id,
acr_name_or_id=detach_acr,
subscription_id=subscription_id,
detach=True)
load_balancer_profile = _get_load_balancer_profile(
load_balancer_managed_outbound_ip_count,
load_balancer_outbound_ips,
load_balancer_outbound_ip_prefixes)
if load_balancer_profile:
instance.network_profile.load_balancer_profile = load_balancer_profile
# empty string is valid as it disables ip whitelisting
if api_server_authorized_ip_ranges is not None:
instance.api_server_access_profile = \
_populate_api_server_access_profile(api_server_authorized_ip_ranges, instance)
return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, name, instance)
# pylint: disable=unused-argument,inconsistent-return-statements
def aks_upgrade(cmd, client, resource_group_name, name, kubernetes_version, control_plane_only=False,
no_wait=False, **kwargs):
instance = client.get(resource_group_name, name)
if instance.kubernetes_version == kubernetes_version:
if instance.provisioning_state == "Succeeded":
logger.warning("The cluster is already on version %s and is not in a failed state. No operations "
"will occur when upgrading to the same version if the cluster is not in a failed state.",
instance.kubernetes_version)
elif instance.provisioning_state == "Failed":
logger.warning("Cluster currently in failed state. Proceeding with upgrade to existing version %s to "
"attempt resolution of failed cluster state.", instance.kubernetes_version)
from knack.prompting import prompt_y_n
upgrade_all = False
instance.kubernetes_version = kubernetes_version
vmas_cluster = False
for agent_profile in instance.agent_pool_profiles:
if agent_profile.type.lower() == "availabilityset":
vmas_cluster = True
break
# for legacy clusters, we always upgrade node pools with CCP.
if instance.max_agent_pools < 8 or vmas_cluster:
if control_plane_only:
msg = ("Legacy clusters do not support control plane only upgrade. All node pools will be "
"upgraded to {} as well. Continue?").format(instance.kubernetes_version)
if not prompt_y_n(msg, default="n"):
return None
upgrade_all = True
else:
if not control_plane_only:
msg = ("Since control-plane-only argument is not specified, this will upgrade the control plane "
"AND all nodepools to version {}. Continue?").format(instance.kubernetes_version)
if not prompt_y_n(msg, default="n"):
return None
upgrade_all = True
else:
msg = ("Since control-plane-only argument is specified, this will upgrade only the control plane to {}. "
"Node pool will not change. Continue?").format(instance.kubernetes_version)
if not prompt_y_n(msg, default="n"):
return None
if upgrade_all:
for agent_profile in instance.agent_pool_profiles:
agent_profile.orchestrator_version = kubernetes_version
# null out the SP and AAD profile because otherwise validation complains
instance.service_principal_profile = None
instance.aad_profile = None
return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, name, instance)
DEV_SPACES_EXTENSION_NAME = 'dev-spaces'
DEV_SPACES_EXTENSION_MODULE = 'azext_dev_spaces.custom'
def aks_use_dev_spaces(cmd, client, name, resource_group_name, update=False, space_name=None, prompt=False):
"""
Use Azure Dev Spaces with a managed Kubernetes cluster.
:param name: Name of the managed cluster.
:type name: String
:param resource_group_name: Name of resource group. You can configure the default group. \
Using 'az configure --defaults group=<name>'.
:type resource_group_name: String
:param update: Update to the latest Azure Dev Spaces client components.
:type update: bool
:param space_name: Name of the new or existing dev space to select. Defaults to an interactive selection experience.
:type space_name: String
:param prompt: Do not prompt for confirmation. Requires --space.
:type prompt: bool
"""
if _get_or_add_extension(cmd, DEV_SPACES_EXTENSION_NAME, DEV_SPACES_EXTENSION_MODULE, update):
azext_custom = _get_azext_module(DEV_SPACES_EXTENSION_NAME, DEV_SPACES_EXTENSION_MODULE)
try:
azext_custom.ads_use_dev_spaces(name, resource_group_name, update, space_name, prompt)
except TypeError:
raise CLIError("Use '--update' option to get the latest Azure Dev Spaces client components.")
except AttributeError as ae:
raise CLIError(ae)
def aks_remove_dev_spaces(cmd, client, name, resource_group_name, prompt=False):
"""
Remove Azure Dev Spaces from a managed Kubernetes cluster.
:param name: Name of the managed cluster.
:type name: String
:param resource_group_name: Name of resource group. You can configure the default group. \
Using 'az configure --defaults group=<name>'.
:type resource_group_name: String
:param prompt: Do not prompt for confirmation.
:type prompt: bool
"""
if _get_or_add_extension(cmd, DEV_SPACES_EXTENSION_NAME, DEV_SPACES_EXTENSION_MODULE):
azext_custom = _get_azext_module(DEV_SPACES_EXTENSION_NAME, DEV_SPACES_EXTENSION_MODULE)
try:
azext_custom.ads_remove_dev_spaces(name, resource_group_name, prompt)
except AttributeError as ae:
raise CLIError(ae)
def aks_rotate_certs(cmd, client, resource_group_name, name, no_wait=True):
return sdk_no_wait(no_wait, client.rotate_cluster_certificates, resource_group_name, name)
def _update_addons(cmd, instance, subscription_id, resource_group_name, addons, enable, workspace_resource_id=None,
subnet_name=None, no_wait=False):
# parse the comma-separated addons argument
addon_args = addons.split(',')
addon_profiles = instance.addon_profiles or {}
if 'kube-dashboard' in addon_args and 'kubeDashboard' not in addon_profiles:
addon_profiles['kubeDashboard'] = ManagedClusterAddonProfile(enabled=True)
os_type = 'Linux'
# for each addons argument
for addon_arg in addon_args:
addon = ADDONS[addon_arg]
if addon == 'aciConnector':
# only linux is supported for now, in the future this will be a user flag
addon += os_type
# addon name is case insensitive
addon = next((x for x in addon_profiles.keys() if x.lower() == addon.lower()), addon)
if enable:
# add new addons or update existing ones and enable them
addon_profile = addon_profiles.get(addon, ManagedClusterAddonProfile(enabled=False))
# special config handling for certain addons
if addon == 'omsagent':
if addon_profile.enabled:
raise CLIError('The monitoring addon is already enabled for this managed cluster.\n'
'To change monitoring configuration, run "az aks disable-addons -a monitoring"'
'before enabling it again.')
if not workspace_resource_id:
workspace_resource_id = _ensure_default_log_analytics_workspace_for_monitoring(
cmd,
subscription_id,
resource_group_name)
workspace_resource_id = workspace_resource_id.strip()
if not workspace_resource_id.startswith('/'):
workspace_resource_id = '/' + workspace_resource_id
if workspace_resource_id.endswith('/'):
workspace_resource_id = workspace_resource_id.rstrip('/')
addon_profile.config = {'logAnalyticsWorkspaceResourceID': workspace_resource_id}
elif addon.lower() == ('aciConnector' + os_type).lower():
if addon_profile.enabled:
raise CLIError('The virtual-node addon is already enabled for this managed cluster.\n'
'To change virtual-node configuration, run '
'"az aks disable-addons -a virtual-node -g {resource_group_name}" '
'before enabling it again.')
if not subnet_name:
raise CLIError('The aci-connector addon requires setting a subnet name.')
addon_profile.config = {'SubnetName': subnet_name}
addon_profiles[addon] = addon_profile
else:
if addon not in addon_profiles:
raise CLIError("The addon {} is not installed.".format(addon))
addon_profiles[addon].config = None
addon_profiles[addon].enabled = enable
instance.addon_profiles = addon_profiles
# null out the SP and AAD profile because otherwise validation complains
instance.service_principal_profile = None
instance.aad_profile = None
return instance
def _get_azext_module(extension_name, module_name):
try:
# Adding the installed extension in the path
from azure.cli.core.extension.operations import add_extension_to_path
add_extension_to_path(extension_name)
# Import the extension module
from importlib import import_module
azext_custom = import_module(module_name)
return azext_custom
except ImportError as ie:
raise CLIError(ie)
def _handle_addons_args(cmd, addons_str, subscription_id, resource_group_name, addon_profiles=None,
workspace_resource_id=None):
if not addon_profiles:
addon_profiles = {}
addons = addons_str.split(',') if addons_str else []
if 'http_application_routing' in addons:
addon_profiles['httpApplicationRouting'] = ManagedClusterAddonProfile(enabled=True)
addons.remove('http_application_routing')
if 'kube-dashboard' in addons:
addon_profiles['kubeDashboard'] = ManagedClusterAddonProfile(enabled=True)
addons.remove('kube-dashboard')
# TODO: can we help the user find a workspace resource ID?
if 'monitoring' in addons:
if not workspace_resource_id:
# use default workspace if exists else create default workspace
workspace_resource_id = _ensure_default_log_analytics_workspace_for_monitoring(
cmd, subscription_id, resource_group_name)
workspace_resource_id = workspace_resource_id.strip()
if not workspace_resource_id.startswith('/'):
workspace_resource_id = '/' + workspace_resource_id
if workspace_resource_id.endswith('/'):
workspace_resource_id = workspace_resource_id.rstrip('/')
addon_profiles['omsagent'] = ManagedClusterAddonProfile(
enabled=True, config={'logAnalyticsWorkspaceResourceID': workspace_resource_id})
addons.remove('monitoring')
# error out if '--enable-addons=monitoring' isn't set but workspace_resource_id is
elif workspace_resource_id:
raise CLIError('"--workspace-resource-id" requires "--enable-addons monitoring".')
# error out if any (unrecognized) addons remain
if addons:
raise CLIError('"{}" {} not recognized by the --enable-addons argument.'.format(
",".join(addons), "are" if len(addons) > 1 else "is"))
return addon_profiles
def _install_dev_spaces_extension(cmd, extension_name):
try:
from azure.cli.core.extension import operations
operations.add_extension(cmd=cmd, extension_name=extension_name)
except Exception: # nopa pylint: disable=broad-except
return False
return True
def _update_dev_spaces_extension(cmd, extension_name, extension_module):
from azure.cli.core.extension import ExtensionNotInstalledException
try:
from azure.cli.core.extension import operations
operations.update_extension(cmd=cmd, extension_name=extension_name)
operations.reload_extension(extension_name=extension_name)
except CLIError as err:
logger.info(err)
except ExtensionNotInstalledException as err:
logger.debug(err)
return False
except ModuleNotFoundError as err:
logger.debug(err)
logger.error("Error occurred attempting to load the extension module. Use --debug for more information.")
return False
return True
def _get_or_add_extension(cmd, extension_name, extension_module, update=False):
from azure.cli.core.extension import (ExtensionNotInstalledException, get_extension)
try:
get_extension(extension_name)
if update:
return _update_dev_spaces_extension(cmd, extension_name, extension_module)
except ExtensionNotInstalledException:
return _install_dev_spaces_extension(cmd, extension_name)
return True
def _ensure_default_log_analytics_workspace_for_monitoring(cmd, subscription_id, resource_group_name):
# mapping for azure public cloud
# log analytics workspaces cannot be created in WCUS region due to capacity limits
# so mapped to EUS per discussion with log analytics team
AzureCloudLocationToOmsRegionCodeMap = {
"australiasoutheast": "ASE",
"australiaeast": "EAU",
"australiacentral": "CAU",
"canadacentral": "CCA",
"centralindia": "CIN",
"centralus": "CUS",
"eastasia": "EA",
"eastus": "EUS",
"eastus2": "EUS2",
"eastus2euap": "EAP",
"francecentral": "PAR",
"japaneast": "EJP",
"koreacentral": "SE",
"northeurope": "NEU",
"southcentralus": "SCUS",
"southeastasia": "SEA",
"uksouth": "SUK",
"usgovvirginia": "USGV",
"westcentralus": "EUS",
"westeurope": "WEU",
"westus": "WUS",
"westus2": "WUS2"
}
AzureCloudRegionToOmsRegionMap = {
"australiacentral": "australiacentral",
"australiacentral2": "australiacentral",
"australiaeast": "australiaeast",
"australiasoutheast": "australiasoutheast",
"brazilsouth": "southcentralus",
"canadacentral": "canadacentral",
"canadaeast": "canadacentral",
"centralus": "centralus",
"centralindia": "centralindia",
"eastasia": "eastasia",
"eastus": "eastus",
"eastus2": "eastus2",
"francecentral": "francecentral",
"francesouth": "francecentral",
"japaneast": "japaneast",
"japanwest": "japaneast",
"koreacentral": "koreacentral",
"koreasouth": "koreacentral",
"northcentralus": "eastus",
"northeurope": "northeurope",
"southafricanorth": "westeurope",
"southafricawest": "westeurope",
"southcentralus": "southcentralus",
"southeastasia": "southeastasia",
"southindia": "centralindia",
"uksouth": "uksouth",
"ukwest": "uksouth",
"westcentralus": "eastus",
"westeurope": "westeurope",
"westindia": "centralindia",
"westus": "westus",
"westus2": "westus2"
}
# mapping for azure china cloud
# currently log analytics supported only China East 2 region
AzureChinaLocationToOmsRegionCodeMap = {
"chinaeast": "EAST2",
"chinaeast2": "EAST2",
"chinanorth": "EAST2",
"chinanorth2": "EAST2"
}
AzureChinaRegionToOmsRegionMap = {
"chinaeast": "chinaeast2",
"chinaeast2": "chinaeast2",
"chinanorth": "chinaeast2",
"chinanorth2": "chinaeast2"
}
# mapping for azure us governmner cloud
AzureFairfaxLocationToOmsRegionCodeMap = {
"usgovvirginia": "USGV"
}
AzureFairfaxRegionToOmsRegionMap = {
"usgovvirginia": "usgovvirginia"
}
rg_location = _get_rg_location(cmd.cli_ctx, resource_group_name)
cloud_name = cmd.cli_ctx.cloud.name
workspace_region = "eastus"
workspace_region_code = "EUS"
# sanity check that locations and clouds match.
if ((cloud_name.lower() == 'azurecloud' and AzureChinaRegionToOmsRegionMap.get(rg_location, False)) or
(cloud_name.lower() == 'azurecloud' and AzureFairfaxRegionToOmsRegionMap.get(rg_location, False))):
raise CLIError('Wrong cloud (azurecloud) setting for region {}, please use "az cloud set ..."'
.format(rg_location))
if ((cloud_name.lower() == 'azurechinacloud' and AzureCloudRegionToOmsRegionMap.get(rg_location, False)) or
(cloud_name.lower() == 'azurechinacloud' and AzureFairfaxRegionToOmsRegionMap.get(rg_location, False))):
raise CLIError('Wrong cloud (azurechinacloud) setting for region {}, please use "az cloud set ..."'
.format(rg_location))
if ((cloud_name.lower() == 'azureusgovernment' and AzureCloudRegionToOmsRegionMap.get(rg_location, False)) or
(cloud_name.lower() == 'azureusgovernment' and AzureChinaRegionToOmsRegionMap.get(rg_location, False))):
raise CLIError('Wrong cloud (azureusgovernment) setting for region {}, please use "az cloud set ..."'
.format(rg_location))
if cloud_name.lower() == 'azurecloud':
workspace_region = AzureCloudRegionToOmsRegionMap.get(rg_location, "eastus")
workspace_region_code = AzureCloudLocationToOmsRegionCodeMap.get(workspace_region, "EUS")
elif cloud_name.lower() == 'azurechinacloud':
workspace_region = AzureChinaRegionToOmsRegionMap.get(rg_location, "chinaeast2")
workspace_region_code = AzureChinaLocationToOmsRegionCodeMap.get(workspace_region, "EAST2")
elif cloud_name.lower() == 'azureusgovernment':
workspace_region = AzureFairfaxRegionToOmsRegionMap.get(rg_location, "usgovvirginia")
workspace_region_code = AzureFairfaxLocationToOmsRegionCodeMap.get(workspace_region, "USGV")
else:
logger.error("AKS Monitoring addon not supported in cloud : %s", cloud_name)
default_workspace_resource_group = 'DefaultResourceGroup-' + workspace_region_code
default_workspace_name = 'DefaultWorkspace-{0}-{1}'.format(subscription_id, workspace_region_code)
default_workspace_resource_id = '/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.OperationalInsights' \
'/workspaces/{2}'.format(subscription_id, default_workspace_resource_group, default_workspace_name)
resource_groups = cf_resource_groups(cmd.cli_ctx, subscription_id)
resources = cf_resources(cmd.cli_ctx, subscription_id)
# check if default RG exists
if resource_groups.check_existence(default_workspace_resource_group):
try:
resource = resources.get_by_id(default_workspace_resource_id, '2015-11-01-preview')
return resource.id
except CloudError as ex:
if ex.status_code != 404:
raise ex
else:
resource_groups.create_or_update(default_workspace_resource_group, {'location': workspace_region})
default_workspace_params = {
'location': workspace_region,
'properties': {
'sku': {
'name': 'standalone'
}
}
}
async_poller = resources.create_or_update_by_id(default_workspace_resource_id, '2015-11-01-preview',
default_workspace_params)
ws_resource_id = ''
while True:
result = async_poller.result(15)
if async_poller.done():
ws_resource_id = result.id
break
return ws_resource_id
def _ensure_container_insights_for_monitoring(cmd, addon):
# Workaround for this addon key which has been seen lowercased in the wild.
if 'loganalyticsworkspaceresourceid' in addon.config:
addon.config['logAnalyticsWorkspaceResourceID'] = addon.config.pop('loganalyticsworkspaceresourceid')
workspace_resource_id = addon.config['logAnalyticsWorkspaceResourceID']
workspace_resource_id = workspace_resource_id.strip()
if not workspace_resource_id.startswith('/'):
workspace_resource_id = '/' + workspace_resource_id
if workspace_resource_id.endswith('/'):
workspace_resource_id = workspace_resource_id.rstrip('/')
# extract subscription ID and resource group from workspace_resource_id URL
try:
subscription_id = workspace_resource_id.split('/')[2]
resource_group = workspace_resource_id.split('/')[4]
except IndexError:
raise CLIError('Could not locate resource group in workspace-resource-id URL.')
# region of workspace can be different from region of RG so find the location of the workspace_resource_id
resources = cf_resources(cmd.cli_ctx, subscription_id)
try:
resource = resources.get_by_id(workspace_resource_id, '2015-11-01-preview')
location = resource.location
except CloudError as ex:
raise ex
unix_time_in_millis = int(
(datetime.datetime.utcnow() - datetime.datetime.utcfromtimestamp(0)).total_seconds() * 1000.0)
solution_deployment_name = 'ContainerInsights-{}'.format(unix_time_in_millis)
# pylint: disable=line-too-long
template = {
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
"workspaceResourceId": {
"type": "string",
"metadata": {
"description": "Azure Monitor Log Analytics Resource ID"
}
},
"workspaceRegion": {
"type": "string",
"metadata": {
"description": "Azure Monitor Log Analytics workspace region"
}
},
"solutionDeploymentName": {
"type": "string",
"metadata": {
"description": "Name of the solution deployment"
}
}
},
"resources": [
{
"type": "Microsoft.Resources/deployments",
"name": "[parameters('solutionDeploymentName')]",
"apiVersion": "2017-05-10",
"subscriptionId": "[split(parameters('workspaceResourceId'),'/')[2]]",
"resourceGroup": "[split(parameters('workspaceResourceId'),'/')[4]]",
"properties": {
"mode": "Incremental",
"template": {
"$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {},
"variables": {},
"resources": [
{
"apiVersion": "2015-11-01-preview",
"type": "Microsoft.OperationsManagement/solutions",
"location": "[parameters('workspaceRegion')]",
"name": "[Concat('ContainerInsights', '(', split(parameters('workspaceResourceId'),'/')[8], ')')]",
"properties": {
"workspaceResourceId": "[parameters('workspaceResourceId')]"
},
"plan": {
"name": "[Concat('ContainerInsights', '(', split(parameters('workspaceResourceId'),'/')[8], ')')]",
"product": "[Concat('OMSGallery/', 'ContainerInsights')]",
"promotionCode": "",
"publisher": "Microsoft"
}
}
]
},
"parameters": {}
}
}
]
}
params = {
"workspaceResourceId": {
"value": workspace_resource_id
},
"workspaceRegion": {
"value": location
},
"solutionDeploymentName": {
"value": solution_deployment_name
}
}
deployment_name = 'aks-monitoring-{}'.format(unix_time_in_millis)
# publish the Container Insights solution to the Log Analytics workspace
return _invoke_deployment(cmd.cli_ctx, resource_group, deployment_name, template, params,
validate=False, no_wait=False, subscription_id=subscription_id)
def _ensure_aks_acr(cli_ctx,
client_id,
acr_name_or_id,
subscription_id,
detach=False):
from msrestazure.tools import is_valid_resource_id, parse_resource_id
# Check if the ACR exists by resource ID.
if is_valid_resource_id(acr_name_or_id):
try:
parsed_registry = parse_resource_id(acr_name_or_id)
acr_client = cf_container_registry_service(cli_ctx, subscription_id=parsed_registry['subscription'])
registry = acr_client.registries.get(parsed_registry['resource_group'], parsed_registry['name'])
except CloudError as ex:
raise CLIError(ex.message)
_ensure_aks_acr_role_assignment(cli_ctx, client_id, registry.id, detach)
return
# Check if the ACR exists by name accross all resource groups.
registry_name = acr_name_or_id
registry_resource = 'Microsoft.ContainerRegistry/registries'
try:
registry = get_resource_by_name(cli_ctx, registry_name, registry_resource)
except CloudError as ex:
if 'was not found' in ex.message:
raise CLIError("ACR {} not found. Have you provided the right ACR name?".format(registry_name))
raise CLIError(ex.message)
_ensure_aks_acr_role_assignment(cli_ctx, client_id, registry.id, detach)
return
def aks_agentpool_show(cmd, client, resource_group_name, cluster_name, nodepool_name):
instance = client.get(resource_group_name, cluster_name, nodepool_name)
return instance
def aks_agentpool_list(cmd, client, resource_group_name, cluster_name):
return client.list(resource_group_name, cluster_name)
def aks_agentpool_add(cmd, client, resource_group_name, cluster_name, nodepool_name,
kubernetes_version=None,
zones=None,
node_vm_size=None,
node_osdisk_size=0,
node_count=3,
vnet_subnet_id=None,
max_pods=0,
os_type="Linux",
min_count=None,
max_count=None,
enable_cluster_autoscaler=False,
node_taints=None,
no_wait=False):
instances = client.list(resource_group_name, cluster_name)
for agentpool_profile in instances:
if agentpool_profile.name == nodepool_name:
raise CLIError("Node pool {} already exists, please try a different name, "
"use 'aks nodepool list' to get current list of node pool".format(nodepool_name))
taints_array = []
if node_taints is not None:
for taint in node_taints.split(','):
try:
taint = taint.strip()
taints_array.append(taint)
except ValueError:
raise CLIError('Taint does not match allowed values. Expect value such as "special=true:NoSchedule".')
if node_vm_size is None:
if os_type.lower() == "windows":
raise CLIError('Windows nodepool is not supported')
node_vm_size = "Standard_DS2_v2"
agent_pool = AgentPool(
name=nodepool_name,
count=int(node_count),
vm_size=node_vm_size,
os_type=os_type,
storage_profile=ContainerServiceStorageProfileTypes.managed_disks,
vnet_subnet_id=vnet_subnet_id,
agent_pool_type="VirtualMachineScaleSets",
max_pods=int(max_pods) if max_pods else None,
orchestrator_version=kubernetes_version,
availability_zones=zones,
node_taints=taints_array
)
_check_cluster_autoscaler_flag(enable_cluster_autoscaler, min_count, max_count, node_count, agent_pool)
if node_osdisk_size:
agent_pool.os_disk_size_gb = int(node_osdisk_size)
return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, cluster_name, nodepool_name, agent_pool)
def aks_agentpool_scale(cmd, client, resource_group_name, cluster_name,
nodepool_name,
node_count=3,
no_wait=False):
instance = client.get(resource_group_name, cluster_name, nodepool_name)
new_node_count = int(node_count)
if new_node_count == 0:
raise CLIError("Can't scale down to 0 nodes.")
if new_node_count == instance.count:
raise CLIError("The new node count is the same as the current node count.")
instance.count = new_node_count # pylint: disable=no-member
return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, cluster_name, nodepool_name, instance)
def aks_agentpool_upgrade(cmd, client, resource_group_name, cluster_name,
kubernetes_version,
nodepool_name,
no_wait=False):
instance = client.get(resource_group_name, cluster_name, nodepool_name)
instance.orchestrator_version = kubernetes_version
return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, cluster_name, nodepool_name, instance)
def aks_agentpool_update(cmd, client, resource_group_name, cluster_name, nodepool_name,
enable_cluster_autoscaler=False,
disable_cluster_autoscaler=False,
update_cluster_autoscaler=False,
min_count=None, max_count=None,
no_wait=False):
update_flags = enable_cluster_autoscaler + disable_cluster_autoscaler + update_cluster_autoscaler
if update_flags != 1:
raise CLIError('Please specify "--enable-cluster-autoscaler" or '
'"--disable-cluster-autoscaler" or '
'"--update-cluster-autoscaler"')
instance = client.get(resource_group_name, cluster_name, nodepool_name)
node_count = instance.count
_validate_autoscaler_update_counts(min_count, max_count, node_count, enable_cluster_autoscaler or
update_cluster_autoscaler)
if enable_cluster_autoscaler:
if instance.enable_auto_scaling:
logger.warning('Autoscaler is already enabled for this node pool.\n'
'Please run "az aks nodepool update --update-cluster-autoscaler" '
'if you want to update min-count or max-count.')
return None
instance.min_count = int(min_count)
instance.max_count = int(max_count)
instance.enable_auto_scaling = True
if update_cluster_autoscaler:
if not instance.enable_auto_scaling:
raise CLIError('Autoscaler is not enabled for this node pool.\n'
'Run "az aks nodepool update --enable-cluster-autoscaler" '
'to enable cluster with min-count and max-count.')
instance.min_count = int(min_count)
instance.max_count = int(max_count)
if disable_cluster_autoscaler:
if not instance.enable_auto_scaling:
logger.warning('Autoscaler is already disabled for this node pool.')
return None
instance.enable_auto_scaling = False
instance.min_count = None
instance.max_count = None
return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, cluster_name, nodepool_name, instance)
def aks_agentpool_delete(cmd, client, resource_group_name, cluster_name,
nodepool_name,
no_wait=False):
agentpool_exists = False
instances = client.list(resource_group_name, cluster_name)
for agentpool_profile in instances:
if agentpool_profile.name.lower() == nodepool_name.lower():
agentpool_exists = True
break
if not agentpool_exists:
raise CLIError("Node pool {} doesnt exist, "
"use 'aks nodepool list' to get current node pool list".format(nodepool_name))
return sdk_no_wait(no_wait, client.delete, resource_group_name, cluster_name, nodepool_name)
def _ensure_aks_acr_role_assignment(cli_ctx,
client_id,
registry_id,
detach=False):
if detach:
if not _delete_role_assignments(cli_ctx,
'acrpull',
client_id,
scope=registry_id):
raise CLIError('Could not delete role assignments for ACR. '
'Are you an Owner on this subscription?')
return
if not _add_role_assignment(cli_ctx,
'acrpull',
client_id,
scope=registry_id):
raise CLIError('Could not create a role assignment for ACR. '
'Are you an Owner on this subscription?')
return
def _ensure_aks_service_principal(cli_ctx,
service_principal=None,
client_secret=None,
subscription_id=None,
dns_name_prefix=None,
location=None,
name=None):
file_name_aks = 'aksServicePrincipal.json'
# TODO: This really needs to be unit tested.
rbac_client = get_graph_rbac_management_client(cli_ctx)
if not service_principal:
# --service-principal not specified, try to load it from local disk
principal_obj = load_acs_service_principal(subscription_id, file_name=file_name_aks)
if principal_obj:
service_principal = principal_obj.get('service_principal')
client_secret = principal_obj.get('client_secret')
else:
# Nothing to load, make one.
if not client_secret:
client_secret = _create_client_secret()
salt = binascii.b2a_hex(os.urandom(3)).decode('utf-8')
url = 'https://{}.{}.{}.cloudapp.azure.com'.format(salt, dns_name_prefix, location)
service_principal = _build_service_principal(rbac_client, cli_ctx, name, url, client_secret)
if not service_principal:
raise CLIError('Could not create a service principal with the right permissions. '
'Are you an Owner on this project?')
logger.info('Created a service principal: %s', service_principal)
# We don't need to add role assignment for this created SPN
else:
# --service-principal specfied, validate --client-secret was too
if not client_secret:
raise CLIError('--client-secret is required if --service-principal is specified')
store_acs_service_principal(subscription_id, client_secret, service_principal, file_name=file_name_aks)
return load_acs_service_principal(subscription_id, file_name=file_name_aks)
def _ensure_osa_aad(cli_ctx,
aad_client_app_id=None,
aad_client_app_secret=None,
aad_tenant_id=None,
identifier=None,
name=None, create=False,
customer_admin_group_id=None):
rbac_client = get_graph_rbac_management_client(cli_ctx)
if create:
# This reply_url is temporary set since Azure need one to create the AAD.
app_id_name = 'https://{}'.format(name)
if not aad_client_app_secret:
aad_client_app_secret = _create_client_secret()
# Delegate Sign In and Read User Profile permissions on Windows Azure Active Directory API
resource_access = ResourceAccess(id="311a71cc-e848-46a1-bdf8-97ff7156d8e6",
additional_properties=None, type="Scope")
# Read directory permissions on Windows Azure Active Directory API
directory_access = ResourceAccess(id="5778995a-e1bf-45b8-affa-663a9f3f4d04",
additional_properties=None, type="Role")
required_osa_aad_access = RequiredResourceAccess(resource_access=[resource_access, directory_access],
additional_properties=None,
resource_app_id="00000002-0000-0000-c000-000000000000")
list_aad_filtered = list(rbac_client.applications.list(filter="identifierUris/any(s:s eq '{}')"
.format(app_id_name)))
if list_aad_filtered:
aad_client_app_id = list_aad_filtered[0].app_id
# Updating reply_url with the correct FQDN information returned by the RP
reply_url = 'https://{}/oauth2callback/Azure%20AD'.format(identifier)
update_application(client=rbac_client.applications,
object_id=list_aad_filtered[0].object_id,
display_name=name,
identifier_uris=[app_id_name],
reply_urls=[reply_url],
homepage=app_id_name,
password=aad_client_app_secret,
required_resource_accesses=[required_osa_aad_access])
logger.info('Updated AAD: %s', aad_client_app_id)
else:
result = create_application(client=rbac_client.applications,
display_name=name,
identifier_uris=[app_id_name],
homepage=app_id_name,
password=aad_client_app_secret,
required_resource_accesses=[required_osa_aad_access])
aad_client_app_id = result.app_id
logger.info('Created an AAD: %s', aad_client_app_id)
# Get the TenantID
if aad_tenant_id is None:
profile = Profile(cli_ctx=cli_ctx)
_, _, aad_tenant_id = profile.get_login_credentials()
return OpenShiftManagedClusterAADIdentityProvider(
client_id=aad_client_app_id,
secret=aad_client_app_secret,
tenant_id=aad_tenant_id,
kind='AADIdentityProvider',
customer_admin_group_id=customer_admin_group_id)
def _ensure_service_principal(cli_ctx,
service_principal=None,
client_secret=None,
subscription_id=None,
dns_name_prefix=None,
location=None,
name=None):
# TODO: This really needs to be unit tested.
rbac_client = get_graph_rbac_management_client(cli_ctx)
if not service_principal:
# --service-principal not specified, try to load it from local disk
principal_obj = load_acs_service_principal(subscription_id)
if principal_obj:
service_principal = principal_obj.get('service_principal')
client_secret = principal_obj.get('client_secret')
else:
# Nothing to load, make one.
if not client_secret:
client_secret = _create_client_secret()
salt = binascii.b2a_hex(os.urandom(3)).decode('utf-8')
url = 'https://{}.{}.{}.cloudapp.azure.com'.format(salt, dns_name_prefix, location)
service_principal = _build_service_principal(rbac_client, cli_ctx, name, url, client_secret)
if not service_principal:
raise CLIError('Could not create a service principal with the right permissions. '
'Are you an Owner on this project?')
logger.info('Created a service principal: %s', service_principal)
# add role first before save it
if not _add_role_assignment(cli_ctx, 'Contributor', service_principal):
logger.warning('Could not create a service principal with the right permissions. '
'Are you an Owner on this project?')
else:
# --service-principal specfied, validate --client-secret was too
if not client_secret:
raise CLIError('--client-secret is required if --service-principal is specified')
store_acs_service_principal(subscription_id, client_secret, service_principal)
return load_acs_service_principal(subscription_id)
def _create_client_secret():
# Add a special character to satsify AAD SP secret requirements
special_char = '$'
client_secret = binascii.b2a_hex(os.urandom(10)).decode('utf-8') + special_char
return client_secret
def _get_rg_location(ctx, resource_group_name, subscription_id=None):
groups = cf_resource_groups(ctx, subscription_id=subscription_id)
# Just do the get, we don't need the result, it will error out if the group doesn't exist.
rg = groups.get(resource_group_name)
return rg.location
def _check_cluster_autoscaler_flag(enable_cluster_autoscaler,
min_count,
max_count,
node_count,
agent_pool_profile):
if enable_cluster_autoscaler:
if min_count is None or max_count is None:
raise CLIError('Please specify both min-count and max-count when --enable-cluster-autoscaler enabled')
if int(min_count) > int(max_count):
raise CLIError('Value of min-count should be less than or equal to value of max-count')
if int(node_count) < int(min_count) or int(node_count) > int(max_count):
raise CLIError('node-count is not in the range of min-count and max-count')
agent_pool_profile.min_count = int(min_count)
agent_pool_profile.max_count = int(max_count)
agent_pool_profile.enable_auto_scaling = True
else:
if min_count is not None or max_count is not None:
raise CLIError('min-count and max-count are required for --enable-cluster-autoscaler, please use the flag')
def _validate_autoscaler_update_counts(min_count, max_count, node_count, is_enable_or_update):
"""
Validates the min, max, and node count when performing an update
"""
if min_count is None or max_count is None:
if is_enable_or_update:
raise CLIError('Please specify both min-count and max-count when --enable-cluster-autoscaler or '
'--update-cluster-autoscaler is set.')
if min_count is not None and max_count is not None:
if int(min_count) > int(max_count):
raise CLIError('Value of min-count should be less than or equal to value of max-count.')
if int(node_count) < int(min_count) or int(node_count) > int(max_count):
raise CLIError("Current node count '{}' is not in the range of min-count and max-count.".format(node_count))
def _print_or_merge_credentials(path, kubeconfig, overwrite_existing, context_name):
"""Merge an unencrypted kubeconfig into the file at the specified path, or print it to
stdout if the path is "-".
"""
# Special case for printing to stdout
if path == "-":
print(kubeconfig)
return
# ensure that at least an empty ~/.kube/config exists
directory = os.path.dirname(path)
if directory and not os.path.exists(directory):
try:
os.makedirs(directory)
except OSError as ex:
if ex.errno != errno.EEXIST:
raise
if not os.path.exists(path):
with os.fdopen(os.open(path, os.O_CREAT | os.O_WRONLY, 0o600), 'wt'):
pass
# merge the new kubeconfig into the existing one
fd, temp_path = tempfile.mkstemp()
additional_file = os.fdopen(fd, 'w+t')
try:
additional_file.write(kubeconfig)
additional_file.flush()
merge_kubernetes_configurations(path, temp_path, overwrite_existing, context_name)
except yaml.YAMLError as ex:
logger.warning('Failed to merge credentials to kube config file: %s', ex)
finally:
additional_file.close()
os.remove(temp_path)
def _remove_nulls(managed_clusters):
"""
Remove some often-empty fields from a list of ManagedClusters, so the JSON representation
doesn't contain distracting null fields.
This works around a quirk of the SDK for python behavior. These fields are not sent
by the server, but get recreated by the CLI's own "to_dict" serialization.
"""
attrs = ['tags']
ap_attrs = ['os_disk_size_gb', 'vnet_subnet_id']
sp_attrs = ['secret']
for managed_cluster in managed_clusters:
for attr in attrs:
if getattr(managed_cluster, attr, None) is None:
delattr(managed_cluster, attr)
for ap_profile in managed_cluster.agent_pool_profiles:
for attr in ap_attrs:
if getattr(ap_profile, attr, None) is None:
delattr(ap_profile, attr)
for attr in sp_attrs:
if getattr(managed_cluster.service_principal_profile, attr, None) is None:
delattr(managed_cluster.service_principal_profile, attr)
return managed_clusters
def _remove_osa_nulls(managed_clusters):
"""
Remove some often-empty fields from a list of OpenShift ManagedClusters, so the JSON representation
doesn't contain distracting null fields.
This works around a quirk of the SDK for python behavior. These fields are not sent
by the server, but get recreated by the CLI's own "to_dict" serialization.
"""
attrs = ['tags', 'plan', 'type', 'id']
ap_master_attrs = ['name', 'os_type']
net_attrs = ['peer_vnet_id']
for managed_cluster in managed_clusters:
for attr in attrs:
if getattr(managed_cluster, attr, None) is None:
delattr(managed_cluster, attr)
for attr in ap_master_attrs:
if getattr(managed_cluster.master_pool_profile, attr, None) is None:
delattr(managed_cluster.master_pool_profile, attr)
for attr in net_attrs:
if getattr(managed_cluster.network_profile, attr, None) is None:
delattr(managed_cluster.network_profile, attr)
return managed_clusters
def _validate_aci_location(norm_location):
"""
Validate the Azure Container Instance location
"""
aci_locations = [
"australiaeast",
"canadacentral",
"centralindia",
"centralus",
"eastasia",
"eastus",
"eastus2",
"eastus2euap",
"japaneast",
"northcentralus",
"northeurope",
"southcentralus",
"southeastasia",
"southindia",
"uksouth",
"westcentralus",
"westus",
"westus2",
"westeurope"
]
if norm_location not in aci_locations:
raise CLIError('Azure Container Instance is not available at location "{}".'.format(norm_location) +
' The available locations are "{}"'.format(','.join(aci_locations)))
def osa_list(cmd, client, resource_group_name=None):
if resource_group_name:
managed_clusters = client.list_by_resource_group(resource_group_name)
else:
managed_clusters = client.list()
return _remove_osa_nulls(list(managed_clusters))
def openshift_create(cmd, client, resource_group_name, name, # pylint: disable=too-many-locals
location=None,
compute_vm_size="Standard_D4s_v3",
compute_count=3,
aad_client_app_id=None,
aad_client_app_secret=None,
aad_tenant_id=None,
vnet_prefix="10.0.0.0/8",
subnet_prefix="10.0.0.0/24",
vnet_peer=None,
tags=None,
no_wait=False,
workspace_id=None,
customer_admin_group_id=None):
if location is None:
location = _get_rg_location(cmd.cli_ctx, resource_group_name)
agent_pool_profiles = []
agent_node_pool_profile = OpenShiftManagedClusterAgentPoolProfile(
name='compute', # Must be 12 chars or less before ACS RP adds to it
count=int(compute_count),
vm_size=compute_vm_size,
os_type="Linux",
role=OpenShiftAgentPoolProfileRole.compute,
subnet_cidr=subnet_prefix
)
agent_infra_pool_profile = OpenShiftManagedClusterAgentPoolProfile(
name='infra', # Must be 12 chars or less before ACS RP adds to it
count=int(3),
vm_size="Standard_D4s_v3",
os_type="Linux",
role=OpenShiftAgentPoolProfileRole.infra,
subnet_cidr=subnet_prefix
)
agent_pool_profiles.append(agent_node_pool_profile)
agent_pool_profiles.append(agent_infra_pool_profile)
agent_master_pool_profile = OpenShiftManagedClusterAgentPoolProfile(
name='master', # Must be 12 chars or less before ACS RP adds to it
count=int(3),
vm_size="Standard_D4s_v3",
os_type="Linux",
subnet_cidr=subnet_prefix
)
identity_providers = []
create_aad = False
# Validating if the cluster is not existing since we are not supporting the AAD rotation on OSA for now
try:
client.get(resource_group_name, name)
except CloudError:
# Validating if aad_client_app_id aad_client_app_secret aad_tenant_id are set
if aad_client_app_id is None and aad_client_app_secret is None and aad_tenant_id is None:
create_aad = True
osa_aad_identity = _ensure_osa_aad(cmd.cli_ctx,
aad_client_app_id=aad_client_app_id,
aad_client_app_secret=aad_client_app_secret,
aad_tenant_id=aad_tenant_id, identifier=None,
name=name, create=create_aad,
customer_admin_group_id=customer_admin_group_id)
identity_providers.append(
OpenShiftManagedClusterIdentityProvider(
name='Azure AD',
provider=osa_aad_identity
)
)
auth_profile = OpenShiftManagedClusterAuthProfile(identity_providers=identity_providers)
default_router_profile = OpenShiftRouterProfile(name='default')
if vnet_peer is not None:
from msrestazure.tools import is_valid_resource_id, resource_id
if not is_valid_resource_id(vnet_peer):
vnet_peer = resource_id(
subscription=get_subscription_id(cmd.cli_ctx),
resource_group=resource_group_name,
namespace='Microsoft.Network', type='virtualNetwork',
name=vnet_peer
)
if workspace_id is not None:
workspace_id = workspace_id.strip()
if not workspace_id.startswith('/'):
workspace_id = '/' + workspace_id
if workspace_id.endswith('/'):
workspace_id = workspace_id.rstrip('/')
monitor_profile = OpenShiftManagedClusterMonitorProfile(enabled=True, workspace_id=workspace_id) # pylint: disable=line-too-long
else:
monitor_profile = None
network_profile = NetworkProfile(vnet_cidr=vnet_prefix, peer_vnet_id=vnet_peer)
osamc = OpenShiftManagedCluster(
location=location, tags=tags,
open_shift_version="v3.11",
network_profile=network_profile,
auth_profile=auth_profile,
agent_pool_profiles=agent_pool_profiles,
master_pool_profile=agent_master_pool_profile,
router_profiles=[default_router_profile],
monitor_profile=monitor_profile)
try:
# long_running_operation_timeout=300
result = sdk_no_wait(no_wait, client.create_or_update,
resource_group_name=resource_group_name, resource_name=name, parameters=osamc)
result = LongRunningOperation(cmd.cli_ctx)(result)
instance = client.get(resource_group_name, name)
_ensure_osa_aad(cmd.cli_ctx,
aad_client_app_id=osa_aad_identity.client_id,
aad_client_app_secret=osa_aad_identity.secret,
aad_tenant_id=osa_aad_identity.tenant_id, identifier=instance.public_hostname,
name=name, create=create_aad)
except CloudError as ex:
if "The resource type could not be found in the namespace 'Microsoft.ContainerService" in ex.message:
raise CLIError('Please make sure your subscription is whitelisted to use this service. https://aka.ms/openshift/managed') # pylint: disable=line-too-long
if "No registered resource provider found for location" in ex.message:
raise CLIError('Please make sure your subscription is whitelisted to use this service. https://aka.ms/openshift/managed') # pylint: disable=line-too-long
raise ex
def openshift_show(cmd, client, resource_group_name, name):
mc = client.get(resource_group_name, name)
return _remove_osa_nulls([mc])[0]
def openshift_scale(cmd, client, resource_group_name, name, compute_count, no_wait=False):
instance = client.get(resource_group_name, name)
# TODO: change this approach when we support multiple agent pools.
idx = 0
for i in range(len(instance.agent_pool_profiles)):
if instance.agent_pool_profiles[i].name.lower() == "compute":
idx = i
break
instance.agent_pool_profiles[idx].count = int(compute_count) # pylint: disable=no-member
# null out the AAD profile and add manually the masterAP name because otherwise validation complains
instance.master_pool_profile.name = "master"
instance.auth_profile = None
return sdk_no_wait(no_wait, client.create_or_update, resource_group_name, name, instance)
def _get_load_balancer_outbound_ips(load_balancer_outbound_ips):
"""parse load balancer profile outbound IP ids and return an array of references to the outbound IP resources"""
load_balancer_outbound_ip_resources = None
if load_balancer_outbound_ips:
load_balancer_outbound_ip_resources = \
[ResourceReference(id=x.strip()) for x in load_balancer_outbound_ips.split(',')]
return load_balancer_outbound_ip_resources
def _get_load_balancer_outbound_ip_prefixes(load_balancer_outbound_ip_prefixes):
"""parse load balancer profile outbound IP prefix ids and return an array \
of references to the outbound IP prefix resources"""
load_balancer_outbound_ip_prefix_resources = None
if load_balancer_outbound_ip_prefixes:
load_balancer_outbound_ip_prefix_resources = \
[ResourceReference(id=x.strip()) for x in load_balancer_outbound_ip_prefixes.split(',')]
return load_balancer_outbound_ip_prefix_resources
def _get_load_balancer_profile(load_balancer_managed_outbound_ip_count,
load_balancer_outbound_ips,
load_balancer_outbound_ip_prefixes):
"""parse and build load balancer profile"""
load_balancer_outbound_ip_resources = _get_load_balancer_outbound_ips(load_balancer_outbound_ips)
load_balancer_outbound_ip_prefix_resources = _get_load_balancer_outbound_ip_prefixes(
load_balancer_outbound_ip_prefixes)
load_balancer_profile = None
if any([load_balancer_managed_outbound_ip_count,
load_balancer_outbound_ip_resources,
load_balancer_outbound_ip_prefix_resources]):
load_balancer_profile = ManagedClusterLoadBalancerProfile()
if load_balancer_managed_outbound_ip_count:
load_balancer_profile.managed_outbound_ips = ManagedClusterLoadBalancerProfileManagedOutboundIPs(
count=load_balancer_managed_outbound_ip_count
)
if load_balancer_outbound_ip_resources:
load_balancer_profile.outbound_ips = ManagedClusterLoadBalancerProfileOutboundIPs(
public_ips=load_balancer_outbound_ip_resources
)
if load_balancer_outbound_ip_prefix_resources:
load_balancer_profile.outbound_ip_prefixes = ManagedClusterLoadBalancerProfileOutboundIPPrefixes(
public_ip_prefixes=load_balancer_outbound_ip_prefix_resources
)
return load_balancer_profile
|
update_application
|
process_vxworks.rs
|
use crate::io::{self, Error, ErrorKind};
use crate::sys;
use crate::sys::cvt;
use crate::sys::process::process_common::*;
use crate::sys_common::thread;
use libc::RTP_ID;
use libc::{self, c_char, c_int};
////////////////////////////////////////////////////////////////////////////////
// Command
////////////////////////////////////////////////////////////////////////////////
impl Command {
pub fn spawn(
&mut self,
default: Stdio,
needs_stdin: bool,
) -> io::Result<(Process, StdioPipes)> {
use crate::sys::cvt_r;
const CLOEXEC_MSG_FOOTER: &'static [u8] = b"NOEX";
let envp = self.capture_env();
if self.saw_nul() {
return Err(io::Error::new(ErrorKind::InvalidInput, "nul byte found in provided data"));
}
let (ours, theirs) = self.setup_io(default, needs_stdin)?;
let mut p = Process { pid: 0, status: None };
unsafe {
macro_rules! t {
($e:expr) => {
match $e {
Ok(e) => e,
Err(e) => return Err(e.into()),
}
};
}
let mut orig_stdin = libc::STDIN_FILENO;
let mut orig_stdout = libc::STDOUT_FILENO;
let mut orig_stderr = libc::STDERR_FILENO;
if let Some(fd) = theirs.stdin.fd() {
orig_stdin = t!(cvt_r(|| libc::dup(libc::STDIN_FILENO)));
t!(cvt_r(|| libc::dup2(fd, libc::STDIN_FILENO)));
}
if let Some(fd) = theirs.stdout.fd() {
orig_stdout = t!(cvt_r(|| libc::dup(libc::STDOUT_FILENO)));
t!(cvt_r(|| libc::dup2(fd, libc::STDOUT_FILENO)));
}
if let Some(fd) = theirs.stderr.fd() {
orig_stderr = t!(cvt_r(|| libc::dup(libc::STDERR_FILENO)));
t!(cvt_r(|| libc::dup2(fd, libc::STDERR_FILENO)));
}
if let Some(ref cwd) = *self.get_cwd() {
t!(cvt(libc::chdir(cwd.as_ptr())));
}
let c_envp = envp
.as_ref()
.map(|c| c.as_ptr())
.unwrap_or_else(|| *sys::os::environ() as *const _);
let stack_size = thread::min_stack();
// ensure that access to the environment is synchronized
let _lock = sys::os::env_lock();
let ret = libc::rtpSpawn(
self.get_program().as_ptr(),
self.get_argv().as_ptr() as *mut *const c_char, // argv
c_envp as *mut *const c_char,
100 as c_int, // initial priority
stack_size, // initial stack size.
0, // options
0, // task options
);
// Because FileDesc was not used, each duplicated file descriptor
// needs to be closed manually
if orig_stdin != libc::STDIN_FILENO {
t!(cvt_r(|| libc::dup2(orig_stdin, libc::STDIN_FILENO)));
libc::close(orig_stdin);
}
if orig_stdout != libc::STDOUT_FILENO {
t!(cvt_r(|| libc::dup2(orig_stdout, libc::STDOUT_FILENO)));
libc::close(orig_stdout);
}
if orig_stderr != libc::STDERR_FILENO {
t!(cvt_r(|| libc::dup2(orig_stderr, libc::STDERR_FILENO)));
libc::close(orig_stderr);
}
if ret != libc::RTP_ID_ERROR {
p.pid = ret;
Ok((p, ours))
} else {
Err(io::Error::last_os_error())
}
}
}
pub fn exec(&mut self, default: Stdio) -> io::Error {
let ret = Command::spawn(self, default, false);
match ret {
Ok(t) => unsafe {
let mut status = 0 as c_int;
libc::waitpid(t.0.pid, &mut status, 0);
libc::exit(0);
},
Err(e) => e,
}
}
}
////////////////////////////////////////////////////////////////////////////////
// Processes
////////////////////////////////////////////////////////////////////////////////
/// The unique id of the process (this should never be negative).
pub struct Process {
pid: RTP_ID,
status: Option<ExitStatus>,
}
impl Process {
pub fn id(&self) -> u32 {
self.pid as u32
}
pub fn kill(&mut self) -> io::Result<()> {
// If we've already waited on this process then the pid can be recycled
// and used for another process, and we probably shouldn't be killing
// random processes, so just return an error.
if self.status.is_some() {
Err(Error::new(
ErrorKind::InvalidInput,
"invalid argument: can't kill an exited process",
))
} else {
cvt(unsafe { libc::kill(self.pid, libc::SIGKILL) }).map(drop)
}
}
pub fn wait(&mut self) -> io::Result<ExitStatus> {
use crate::sys::cvt_r;
if let Some(status) = self.status {
return Ok(status);
}
|
cvt_r(|| unsafe { libc::waitpid(self.pid, &mut status, 0) })?;
self.status = Some(ExitStatus::new(status));
Ok(ExitStatus::new(status))
}
pub fn try_wait(&mut self) -> io::Result<Option<ExitStatus>> {
if let Some(status) = self.status {
return Ok(Some(status));
}
let mut status = 0 as c_int;
let pid = cvt(unsafe { libc::waitpid(self.pid, &mut status, libc::WNOHANG) })?;
if pid == 0 {
Ok(None)
} else {
self.status = Some(ExitStatus::new(status));
Ok(Some(ExitStatus::new(status)))
}
}
}
|
let mut status = 0 as c_int;
|
connection_pool.rs
|
// Copyright 2020 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT
// http://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD
// https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied,
// modified, or distributed except according to those terms. Please review the Licences for the
// specific language governing permissions and limitations relating to use of the SAFE Network
// Software.
use std::{collections::BTreeMap, net::SocketAddr, sync::Arc};
use tiny_keccak::{Hasher, Sha3};
use tokio::sync::RwLock;
use xor_name::XorName;
// Pool for keeping open connections. Pooled connections are associated with a `ConnectionRemover`
// which can be used to remove them from the pool.
#[derive(Clone)]
pub(crate) struct ConnectionPool<I: ConnId> {
store: Arc<RwLock<Store<I>>>,
}
impl<I: ConnId> ConnectionPool<I> {
pub(crate) fn new() -> Self {
Self {
store: Arc::new(RwLock::new(Store::default())),
}
}
pub(crate) async fn insert(
&self,
id: I,
addr: SocketAddr,
conn: quinn::Connection,
) -> ConnectionRemover<I> {
let mut store = self.store.write().await;
let key = Key {
addr,
id: store.id_gen.next(),
};
let _ = store.id_map.insert(id, (conn.clone(), key));
let _ = store.key_map.insert(key, (conn, id));
ConnectionRemover {
store: self.store.clone(),
id,
key,
}
}
pub(crate) async fn has_addr(&self, addr: &SocketAddr) -> bool {
let store = self.store.read().await;
// Efficiently fetch the first entry whose key is equal to `key` and check if it exists
store
.key_map
.range(Key::min(*addr)..=Key::max(*addr))
.next()
.is_some()
}
#[allow(unused)]
pub(crate) async fn has_id(&self, id: &I) -> bool {
let store = self.store.read().await;
store.id_map.contains_key(id)
}
pub(crate) async fn remove(&self, addr: &SocketAddr) -> Vec<quinn::Connection> {
let mut store = self.store.write().await;
let keys_to_remove = store
.key_map
.range_mut(Key::min(*addr)..=Key::max(*addr))
.into_iter()
.map(|(key, _)| *key)
.collect::<Vec<_>>();
keys_to_remove
.iter()
.filter_map(|key| store.key_map.remove(key).map(|entry| entry.0))
.collect::<Vec<_>>()
}
pub(crate) async fn get_by_id(
&self,
addr: &I,
) -> Option<(quinn::Connection, ConnectionRemover<I>)> {
let store = self.store.read().await;
let (conn, key) = store.id_map.get(addr)?;
let remover = ConnectionRemover {
store: self.store.clone(),
key: *key,
id: *addr,
};
Some((conn.clone(), remover))
}
pub(crate) async fn get_by_addr(
&self,
addr: &SocketAddr,
) -> Option<(quinn::Connection, ConnectionRemover<I>)> {
let store = self.store.read().await;
// Efficiently fetch the first entry whose key is equal to `key`.
let (key, entry) = store
.key_map
.range(Key::min(*addr)..=Key::max(*addr))
.next()?;
let conn = entry.clone().0;
let remover = ConnectionRemover {
store: self.store.clone(),
key: *key,
id: entry.1,
};
Some((conn, remover))
}
}
// Handle for removing a connection from the pool.
#[derive(Clone)]
pub(crate) struct ConnectionRemover<I: ConnId> {
store: Arc<RwLock<Store<I>>>,
key: Key,
id: I,
}
impl<I: ConnId> ConnectionRemover<I> {
// Remove the connection from the pool.
pub(crate) async fn remove(&self) {
let mut store = self.store.write().await;
let _ = store.key_map.remove(&self.key);
let _ = store.id_map.remove(&self.id);
}
pub(crate) fn remote_addr(&self) -> &SocketAddr {
&self.key.addr
}
pub(crate) fn id(&self) -> I
|
}
#[derive(Default)]
struct Store<I: ConnId> {
id_map: BTreeMap<I, (quinn::Connection, Key)>,
key_map: BTreeMap<Key, (quinn::Connection, I)>,
id_gen: IdGen,
}
/// Unique key identifying a connection. Two connections will always have distict keys even if they
/// have the same socket address.
pub trait ConnId:
Clone + Copy + Eq + PartialEq + Ord + PartialOrd + Default + Send + Sync + 'static
{
/// Generate
fn generate(socket_addr: &SocketAddr) -> Result<Self, Box<dyn std::error::Error>>;
}
impl ConnId for XorName {
fn generate(addr: &SocketAddr) -> Result<Self, Box<dyn std::error::Error>> {
let data = bincode::serialize(addr)?;
let mut hasher = Sha3::v256();
let mut output = [0u8; 32];
hasher.update(&data);
hasher.finalize(&mut output);
Ok(XorName(output))
}
}
// Unique key identifying a connection. Two connections will always have distict keys even if they
// have the same socket address.
#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
struct Key {
addr: SocketAddr,
id: u64,
}
impl Key {
// Returns the minimal `Key` for the given address according to its `Ord` relation.
fn min(addr: SocketAddr) -> Self {
Self { addr, id: u64::MIN }
}
// Returns the maximal `Key` for the given address according to its `Ord` relation.
fn max(addr: SocketAddr) -> Self {
Self { addr, id: u64::MAX }
}
}
#[derive(Default)]
struct IdGen(u64);
impl IdGen {
fn next(&mut self) -> u64 {
let id = self.0;
self.0 = self.0.wrapping_add(1);
id
}
}
|
{
self.id
}
|
pool.py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import asyncio
import os
import warnings
import time
import random
import threading
from itertools import chain
from urllib.parse import (parse_qs,
unquote,
urlparse)
from aredis.connection import (RedisSSLContext,
Connection,
UnixDomainSocketConnection,
ClusterConnection)
from aredis.nodemanager import NodeManager
from aredis.exceptions import (ConnectionError,
RedisClusterException)
FALSE_STRINGS = ('0', 'F', 'FALSE', 'N', 'NO')
|
if value is None or value == '':
return None
if isinstance(value, str) and value.upper() in FALSE_STRINGS:
return False
return bool(value)
URL_QUERY_ARGUMENT_PARSERS = {
'stream_timeout': float,
'connect_timeout': float,
'retry_on_timeout': to_bool
}
class ConnectionPool(object):
"""Generic connection pool"""
@classmethod
def from_url(cls, url, db=None, decode_components=False, **kwargs):
"""
Returns a connection pool configured from the given URL.
For example::
redis://[:password]@localhost:6379/0
rediss://[:password]@localhost:6379/0
unix://[:password]@/path/to/socket.sock?db=0
Three URL schemes are supported:
- ```redis://``
<http://www.iana.org/assignments/uri-schemes/prov/redis>`_ creates a
normal TCP socket connection
- ```rediss://``
<http://www.iana.org/assignments/uri-schemes/prov/rediss>`_ creates a
SSL wrapped TCP socket connection
- ``unix://`` creates a Unix Domain Socket connection
There are several ways to specify a database number. The parse function
will return the first specified option:
1. A ``db`` querystring option, e.g. redis://localhost?db=0
2. If using the redis:// scheme, the path argument of the url, e.g.
redis://localhost/0
3. The ``db`` argument to this function.
If none of these options are specified, db=0 is used.
The ``decode_components`` argument allows this function to work with
percent-encoded URLs. If this argument is set to ``True`` all ``%xx``
escapes will be replaced by their single-character equivalents after
the URL has been parsed. This only applies to the ``hostname``,
``path``, and ``password`` components.
Any additional querystring arguments and keyword arguments will be
passed along to the ConnectionPool class's initializer. The querystring
arguments ``connect_timeout`` and ``stream_timeout`` if supplied
are parsed as float values. The arguments ``retry_on_timeout`` are
parsed to boolean values that accept True/False, Yes/No values to indicate state.
Invalid types cause a ``UserWarning`` to be raised.
In the case of conflicting arguments, querystring arguments always win.
"""
url = urlparse(url)
qs = url.query
url_options = {}
for name, value in iter(parse_qs(qs).items()):
if value and len(value) > 0:
parser = URL_QUERY_ARGUMENT_PARSERS.get(name)
if parser:
try:
url_options[name] = parser(value[0])
except (TypeError, ValueError):
warnings.warn(UserWarning(
"Invalid value for `%s` in connection URL." % name
))
else:
url_options[name] = value[0]
if decode_components:
password = unquote(url.password) if url.password else None
path = unquote(url.path) if url.path else None
hostname = unquote(url.hostname) if url.hostname else None
else:
password = url.password
path = url.path
hostname = url.hostname
# We only support redis:// and unix:// schemes.
if url.scheme == 'unix':
url_options.update({
'password': password,
'path': path,
'connection_class': UnixDomainSocketConnection,
})
else:
url_options.update({
'host': hostname,
'port': int(url.port or 6379),
'password': password,
})
# If there's a path argument, use it as the db argument if a
# querystring value wasn't specified
if 'db' not in url_options and path:
try:
url_options['db'] = int(path.replace('/', ''))
except (AttributeError, ValueError):
pass
if url.scheme == 'rediss':
keyfile = url_options.pop('ssl_keyfile', None)
certfile = url_options.pop('ssl_certfile', None)
cert_reqs = url_options.pop('ssl_cert_reqs', None)
ca_certs = url_options.pop('ssl_ca_certs', None)
url_options['ssl_context'] = RedisSSLContext(keyfile, certfile, cert_reqs, ca_certs).get()
# last shot at the db value
url_options['db'] = int(url_options.get('db', db or 0))
# update the arguments from the URL values
kwargs.update(url_options)
return cls(**kwargs)
def __init__(self, connection_class=Connection, max_connections=None,
max_idle_time=0, idle_check_interval=1,
**connection_kwargs):
"""
Creates a connection pool. If max_connections is set, then this
object raises redis.ConnectionError when the pool's limit is reached.
By default, TCP connections are created connection_class is specified.
Use redis.UnixDomainSocketConnection for unix sockets.
Any additional keyword arguments are passed to the constructor of
connection_class.
"""
max_connections = max_connections or 2 ** 31
if not isinstance(max_connections, int) or max_connections < 0:
raise ValueError('"max_connections" must be a positive integer')
self.connection_class = connection_class
self.connection_kwargs = connection_kwargs
self.max_connections = max_connections
self.max_idle_time = max_idle_time
self.idle_check_interval = idle_check_interval
self.loop = self.connection_kwargs.get('loop')
self.reset()
def __repr__(self):
return '{}<{}>'.format(
type(self).__name__,
self.connection_class.description.format(**self.connection_kwargs),
)
async def disconnect_on_idle_time_exceeded(self, connection):
while True:
if (time.time() - connection.last_active_at > self.max_idle_time
and not connection.awaiting_response):
connection.disconnect()
try:
self._available_connections.remove(connection)
except ValueError:
pass
self._created_connections -= 1
break
await asyncio.sleep(self.idle_check_interval)
def reset(self):
self.pid = os.getpid()
self._created_connections = 0
self._available_connections = []
self._in_use_connections = set()
self._check_lock = threading.Lock()
def _checkpid(self):
if self.pid != os.getpid():
with self._check_lock:
if self.pid == os.getpid():
# another thread already did the work while we waited
# on the lock.
return
self.disconnect()
self.reset()
def get_connection(self, *args, **kwargs):
"""Gets a connection from the pool"""
self._checkpid()
try:
connection = self._available_connections.pop()
except IndexError:
connection = self.make_connection()
self._in_use_connections.add(connection)
return connection
def make_connection(self):
"""Creates a new connection"""
if self._created_connections >= self.max_connections:
raise ConnectionError("Too many connections")
self._created_connections += 1
connection = self.connection_class(**self.connection_kwargs)
if self.max_idle_time > self.idle_check_interval > 0:
# do not await the future
asyncio.ensure_future(self.disconnect_on_idle_time_exceeded(connection))
return connection
def release(self, connection):
"""Releases the connection back to the pool"""
self._checkpid()
if connection.pid != self.pid:
return
self._in_use_connections.remove(connection)
# discard connection with unread response
if connection.awaiting_response:
connection.disconnect()
self._created_connections -= 1
else:
self._available_connections.append(connection)
def disconnect(self):
"""Closes all connections in the pool"""
all_conns = chain(self._available_connections,
self._in_use_connections)
for connection in all_conns:
connection.disconnect()
self._created_connections -= 1
class ClusterConnectionPool(ConnectionPool):
"""Custom connection pool for rediscluster"""
RedisClusterDefaultTimeout = None
def __init__(self, startup_nodes=None, connection_class=ClusterConnection,
max_connections=None, max_connections_per_node=False, reinitialize_steps=None,
skip_full_coverage_check=False, nodemanager_follow_cluster=False, readonly=False,
max_idle_time=0, idle_check_interval=1,
**connection_kwargs):
"""
:skip_full_coverage_check:
Skips the check of cluster-require-full-coverage config, useful for clusters
without the CONFIG command (like aws)
:nodemanager_follow_cluster:
The node manager will during initialization try the last set of nodes that
it was operating on. This will allow the client to drift along side the cluster
if the cluster nodes move around alot.
"""
super(ClusterConnectionPool, self).__init__(connection_class=connection_class, max_connections=max_connections)
# Special case to make from_url method compliant with cluster setting.
# from_url method will send in the ip and port through a different variable then the
# regular startup_nodes variable.
if startup_nodes is None:
if 'port' in connection_kwargs and 'host' in connection_kwargs:
startup_nodes = [{
'host': connection_kwargs.pop('host'),
'port': str(connection_kwargs.pop('port')),
}]
self.max_connections = max_connections or 2 ** 31
self.max_connections_per_node = max_connections_per_node
self.nodes = NodeManager(
startup_nodes,
reinitialize_steps=reinitialize_steps,
skip_full_coverage_check=skip_full_coverage_check,
max_connections=self.max_connections,
nodemanager_follow_cluster=nodemanager_follow_cluster,
**connection_kwargs
)
self.initialized = False
self.connections = {}
self.connection_kwargs = connection_kwargs
self.connection_kwargs['readonly'] = readonly
self.readonly = readonly
self.max_idle_time = max_idle_time
self.idle_check_interval = idle_check_interval
self.reset()
if "stream_timeout" not in self.connection_kwargs:
self.connection_kwargs["stream_timeout"] = ClusterConnectionPool.RedisClusterDefaultTimeout
def __repr__(self):
"""
Returns a string with all unique ip:port combinations that this pool
is connected to
"""
return "{0}<{1}>".format(
type(self).__name__,
", ".join([self.connection_class.description.format(**node)
for node in self.nodes.startup_nodes])
)
async def initialize(self):
if not self.initialized:
await self.nodes.initialize()
self.initialized = True
async def disconnect_on_idle_time_exceeded(self, connection):
while True:
if (time.time() - connection.last_active_at > self.max_idle_time
and not connection.awaiting_response):
connection.disconnect()
node = connection.node
self._available_connections[node['name']].remove(connection)
self._created_connections_per_node[node['name']] -= 1
break
await asyncio.sleep(self.idle_check_interval)
def reset(self):
"""Resets the connection pool back to a clean state"""
self.pid = os.getpid()
self._created_connections_per_node = {} # Dict(Node, Int)
self._available_connections = {} # Dict(Node, List)
self._in_use_connections = {} # Dict(Node, Set)
self._check_lock = threading.Lock()
self.initialized = False
def _checkpid(self):
if self.pid != os.getpid():
with self._check_lock:
if self.pid == os.getpid():
# another thread already did the work while we waited
# on the lockself.
return
self.disconnect()
self.reset()
def get_connection(self, command_name, *keys, **options):
# Only pubsub command/connection should be allowed here
if command_name != "pubsub":
raise RedisClusterException("Only 'pubsub' commands can use get_connection()")
channel = options.pop('channel', None)
if not channel:
return self.get_random_connection()
slot = self.nodes.keyslot(channel)
node = self.get_master_node_by_slot(slot)
self._checkpid()
try:
connection = self._available_connections.get(node["name"], []).pop()
except IndexError:
connection = self.make_connection(node)
if node['name'] not in self._in_use_connections:
self._in_use_connections[node['name']] = set()
self._in_use_connections[node['name']].add(connection)
return connection
def make_connection(self, node):
"""Creates a new connection"""
if self.count_all_num_connections(node) >= self.max_connections:
if self.max_connections_per_node:
raise RedisClusterException("Too many connection ({0}) for node: {1}"
.format(self.count_all_num_connections(node),
node['name']))
raise RedisClusterException("Too many connections")
self._created_connections_per_node.setdefault(node['name'], 0)
self._created_connections_per_node[node['name']] += 1
connection = self.connection_class(host=node["host"],
port=node["port"],
**self.connection_kwargs)
# Must store node in the connection to make it eaiser to track
connection.node = node
if self.max_idle_time > self.idle_check_interval > 0:
# do not await the future
asyncio.ensure_future(self.disconnect_on_idle_time_exceeded(connection))
return connection
def release(self, connection):
"""Releases the connection back to the pool"""
self._checkpid()
if connection.pid != self.pid:
return
# Remove the current connection from _in_use_connection and add it back to the available pool
# There is cases where the connection is to be removed but it will not exist and there
# must be a safe way to remove
i_c = self._in_use_connections.get(connection.node["name"], set())
if connection in i_c:
i_c.remove(connection)
else:
pass
# discard connection with unread response
if connection.awaiting_response:
connection.disconnect()
# reduce node connection count in case of too many connection error raised
if self.max_connections_per_node and self._created_connections_per_node.get(connection.node['name']):
self._created_connections_per_node[connection.node['name']] -= 1
else:
self._available_connections.setdefault(connection.node["name"], []).append(connection)
def disconnect(self):
"""Closes all connectins in the pool"""
all_conns = chain(
self._available_connections.values(),
self._in_use_connections.values(),
)
for node_connections in all_conns:
for connection in node_connections:
connection.disconnect()
def count_all_num_connections(self, node):
if self.max_connections_per_node:
return self._created_connections_per_node.get(node['name'], 0)
return sum([i for i in self._created_connections_per_node.values()])
def get_random_connection(self):
"""Opens new connection to random redis server"""
if self._available_connections:
node_name = random.choice(list(self._available_connections.keys()))
conn_list = self._available_connections[node_name]
# check it in case of empty connection list
if conn_list:
return conn_list.pop()
for node in self.nodes.random_startup_node_iter():
connection = self.get_connection_by_node(node)
if connection:
return connection
raise Exception("Cant reach a single startup node.")
def get_connection_by_key(self, key):
if not key:
raise RedisClusterException("No way to dispatch this command to Redis Cluster.")
return self.get_connection_by_slot(self.nodes.keyslot(key))
def get_connection_by_slot(self, slot):
"""
Determines what server a specific slot belongs to and return a redis
object that is connected
"""
self._checkpid()
try:
return self.get_connection_by_node(self.get_node_by_slot(slot))
except KeyError:
return self.get_random_connection()
def get_connection_by_node(self, node):
"""Gets a connection by node"""
self._checkpid()
self.nodes.set_node_name(node)
try:
# Try to get connection from existing pool
connection = self._available_connections.get(node["name"], []).pop()
except IndexError:
connection = self.make_connection(node)
self._in_use_connections.setdefault(node["name"], set()).add(connection)
return connection
def get_master_node_by_slot(self, slot):
return self.nodes.slots[slot][0]
def get_node_by_slot(self, slot):
if self.readonly:
return random.choice(self.nodes.slots[slot])
return self.get_master_node_by_slot(slot)
|
def to_bool(value):
|
12857_25_FluidR3_GM_sf2_file.js
|
console.log('load _drum_57_25_FluidR3_GM_sf2_file');
|
,loopStart:0
,loopEnd:0
,keyRangeLow:57
,keyRangeHigh:57
,sampleRate:44100
,coarseTune:0
,fineTune:0
,originalPitch:5700
,file:'SUQzBAAAAAAAI1RTU0UAAAAPAAADTGF2ZjU3LjcyLjEwMQAAAAAAAAAAAAAA//tAwAAAAAAAAAAAAAAAAAAAAAAAWGluZwAAAA8AAADcAAF1dQAECAsOEhUXGRwfIiQnKSwuMTM1ODs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VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVQ=='
,anchor:0.04931973
//'Crsh 2(L)
}
]
};
|
var _drum_57_25_FluidR3_GM_sf2_file={
zones:[
{
midi:128
|
bot.py
|
import asyncio
import json
import random
import subprocess
import discord
import discord.ext
import requests
from discord.ext import commands
import os
from botlibrary.utils import get_variable
from botlibrary import constants
# Wichs Codierung
# ä=ü
# ö=ö
# assign constant variables
constants.assignVariables()
VERSION = constants.VERSION
bot_prefix = constants.bot_prefix
client = commands.Bot(command_prefix=bot_prefix, intents=discord.Intents.all())
def tokenchecker():
riotapi = constants.lol_token
base_riot_url = "https://euw1.api.riotgames.com/lol/summoner/v4/summoners/by-name/DCGALAXY?api_key="
rioturl = base_riot_url + riotapi
response = requests.get(rioturl)
if response.status_code == 200:
pass
else:
print("Der Riot-API Key hat nicht funktioniert :((")
print(
"Bitte checke ob der Key in der config.json richtig gesetzt ist und schau auf "
"https://developer.riotgames.com/api-status/ nach ob es nicht vllt an Riot selber liegt")
riotnotworkingexe = input("Willst du trotzdem starten? (j/n): ")
if riotnotworkingexe == "j":
pass
else:
raise Exception("Der Riot-API Key hat nicht funktioniert.")
osuapi = constants.osu_token
base_osu_url = "https://osu.ppy.sh/api/get_user_best?u=Aftersh0ock&k="
osuurl = base_osu_url + osuapi
osuresponse = requests.get(osuurl)
if osuresponse.status_code == 200:
pass
else:
print("Der Osu-API Key hat nicht funktioniert :((")
print(
"Bitte checke ob der Key in der config.json richtig gesetzt ist und schau auf https://status.ppy.sh nach ob es nicht vllt an Osu selber liegt")
osunotworkingexe = input("Willst du trotzdem starten? (j/n): ")
if osunotworkingexe == "j":
pass
|
headers = {
"Authorization": "Bot " + token
}
response = requests.get('https://discordapp.com/api/v8/auth/login', headers=headers)
if response.status_code == 200:
pass
else:
raise Exception("Der Discord Bot Token funktioniert nicht!")
ipdata = constants.ipdata_token
baseipurl = "https://api.ipdata.co/8.8.8.8"
ipurl = baseipurl + "?api-key=" + ipdata
ipresponse = requests.get(ipurl)
if ipresponse.status_code == 200:
pass
else:
print("Der IPData-API Key hat nicht funktioniert :((")
print(
"Bitte checke ob der Key in der config.json richtig gesetzt ist und schau auf https://status.ipdata.co nach ob es nicht vllt an Osu selber liegt")
ipdatanotworkingexe = input("Willst du trotzdem starten? (j/n): ")
if ipdatanotworkingexe == "j":
pass
else:
raise Exception("Der IPData Key hat nicht funktioniert.")
tokenchecker()
@client.event
async def on_ready():
print("Yess der bot läuft :)".format(client))
print("Du hast derzeit Release " + str(VERSION) + " installiert")
print("Du bist eingeloggt als {0.user} auf discord.py Version {1}".format(client, discord.__version__))
if os.path.exists("config/mysql.json"):
print("MySQL-Logging ist AKTIVIERT")
else:
print("MySQL-Logging ist DEAKTIVIERT")
print("Der Bot ist zurzeit auf folgenden " + str(len(client.guilds)) + " Servern:")
for guild in client.guilds:
print("- " + str(guild.name))
client.loop.create_task(status_task())
async def status_task():
while True:
await client.change_presence(activity=discord.Game("https://git.io/antonsbot"),
status=discord.Status.online)
await asyncio.sleep(60)
await client.change_presence(
activity=discord.Game(bot_prefix + "corona auf " + str(len(client.guilds)) + " Servern"))
await asyncio.sleep(60)
await client.change_presence(activity=discord.Game("ein heißes Spiel mit der Stiefschwester"))
await asyncio.sleep(5)
await client.change_presence(
activity=discord.Activity(type=discord.ActivityType.watching, name="auf deine Nachrichten"))
await asyncio.sleep(60)
"""
##############################################################################################################################################################
Ole rewrite paradise
##############################################################################################################################################################
"""
def owner_only(func):
async def wrapper(self, *args, **kwargs):
ctx = get_variable('ctx')
info = await client.application_info()
if ctx.author.id == info.owner.id:
return await func(self, *args, **kwargs)
else:
await ctx.channel.send("Error, only the bot owner can use this command!")
return wrapper
@client.command(name="reload")
@owner_only
async def reload_cog(ctx, cogName):
try:
await unload_cog(ctx, cogName)
await load_cog(ctx, cogName)
except Exception as e:
await ctx.channel.send(f"Während dem versuch die Erweiterung {cogName} neu zu laden ist etwas schiefgelaufen!")
@client.command(name="unload")
@owner_only
async def unload_cog(ctx, cogName):
try:
client.unload_extension(f"cogs.{cogName}")
await ctx.channel.send(f"Erfolgreich erweiterung {cogName} entladen!")
except Exception as e:
await ctx.channel.send(f"Fehler, entweder ist die erweiterung schong entladen, oder sie wurde nicht gefunden!")
@client.command(name="load")
@owner_only
async def load_cog(ctx, cogName):
try:
client.load_extension(f"cogs.{cogName}")
await ctx.channel.send(f"Erfolgreich erweiterung {cogName} geladen!")
except Exception as e:
await ctx.channel.send(f"Fehler, entweder ist die erweiterung schon geladen, oder sie wurde nicht gefunden.")
with open('config/config.json', 'r') as f:
json_stuff = json.load(f)
token = json_stuff["token"]
# load cogs
for filename in os.listdir("./cogs"):
if filename.endswith(".py"):
client.load_extension(f"cogs.{filename[:-3]}")
# run bot
client.run(token)
|
else:
raise Exception("Der Osu-API Key hat nicht funktioniert.")
token = constants.bot_token
|
verify.py
|
"""Common verification functions for ping"""
# Python
import logging
# Genie
from genie.utils.timeout import Timeout
from genie.metaparser.util.exceptions import SchemaEmptyParserError
# pyATS
from genie.utils import Dq
log = logging.getLogger(__name__)
def
|
(device,
address=None,
ttl=None,
wait=None,
mpls_rsvp=None,
loss_rate=0,
count=None,
max_time=30,
check_interval=10):
""" Verify ping loss rate on ip address provided
Args:
device ('obj'): Device object
address ('str'): Address value
ttl ('int'): ttl value passed in command
wait ('int'): wait value passed in command
mpls_rsvp ('str'): MPLS RSVP value
loss_rate ('int'): Expected loss rate value
count ('int'): Count value for ping command
max_time (`int`): Max time, default: 30
check_interval (`int`): Check interval, default: 10
Returns:
Boolean
Raises:
None
"""
timeout = Timeout(max_time, check_interval)
while timeout.iterate():
if address and count and not ttl and not wait:
cmd = 'ping {address} count {count}'.format(address=address,
count=count)
elif address and count and ttl and wait:
cmd = 'ping {address} ttl {ttl} count {count} wait {wait}'.format(
address=address,
ttl=ttl,
count=count,
wait=wait)
elif not address and mpls_rsvp:
cmd = 'ping mpls rsvp {rsvp}'.format(rsvp=mpls_rsvp)
elif address:
cmd = 'ping {address}'.format(address=address)
else:
log.info('Need to pass address as argument')
return False
try:
out = device.parse(cmd)
except SchemaEmptyParserError as e:
timeout.sleep()
continue
# Example dictionary structure:
# {
# "ping": {
# "address": "10.189.5.94",
# "data-bytes": 56,
# "result": [
# {
# "bytes": 64,
# "from": "10.189.5.94",
# "icmp-seq": 0,
# "time": "2.261",
# "ttl": 62
# },
# ],
# "source": "10.189.5.94",
# "statistics": {
# "loss-rate": 0,
# "received": 1,
# "round-trip": {
# "avg": "2.175",
# "max": "2.399",
# "min": "1.823",
# "stddev": "0.191"
# },
# "send": 1
# }
# }
# }
loss_rate_found = Dq(out).get_values("loss-rate", 0)
if loss_rate_found == loss_rate:
return True
timeout.sleep()
return False
|
verify_ping
|
Path_Update.js
|
/**
* Auto-generated action file for "Azure Data Lake Storage" API.
*
* Generated at: 2019-05-07T14:39:16.268Z
* Mass generator version: 1.1.0
*
* flowground :- Telekom iPaaS / azure-com-storage-data-lake-storage-connector
* Copyright © 2019, Deutsche Telekom AG
* contact: [email protected]
*
* All files of this connector are licensed under the Apache 2.0 License. For details
* see the file LICENSE on the toplevel directory.
*
*
* Operation: 'Path_Update'
* Endpoint Path: '/{filesystem}/{path}'
* Method: 'patch'
*
*/
const Swagger = require('swagger-client');
const processWrapper = require('../services/process-wrapper');
const spec = require('../spec.json');
// this wrapers offers a simplified emitData(data) function
module.exports.process = processWrapper(processAction);
// parameter names for this call
const PARAMETERS = [
"action",
"position",
"retainUncommittedData",
"close",
"Content-Length",
"x-ms-lease-id",
"x-ms-cache-control",
"x-ms-content-type",
"x-ms-content-disposition",
"x-ms-content-encoding",
"x-ms-content-language",
"x-ms-properties",
"x-ms-owner",
"x-ms-group",
"x-ms-permissions",
"x-ms-acl",
"If-Match",
"If-None-Match",
"If-Modified-Since",
"If-Unmodified-Since"
];
// mappings from connector field names to API field names
const FIELD_MAP = {
"action": "action",
"position": "position",
"retainUncommittedData": "retainUncommittedData",
"close": "close",
"Content_Length": "Content-Length",
"x_ms_lease_id": "x-ms-lease-id",
"x_ms_cache_control": "x-ms-cache-control",
"x_ms_content_type": "x-ms-content-type",
"x_ms_content_disposition": "x-ms-content-disposition",
"x_ms_content_encoding": "x-ms-content-encoding",
"x_ms_content_language": "x-ms-content-language",
"x_ms_properties": "x-ms-properties",
"x_ms_owner": "x-ms-owner",
"x_ms_group": "x-ms-group",
"x_ms_permissions": "x-ms-permissions",
"x_ms_acl": "x-ms-acl",
"If_Match": "If-Match",
"If_None_Match": "If-None-Match",
"If_Modified_Since": "If-Modified-Since",
"If_Unmodified_Since": "If-Unmodified-Since",
"requestBody": "requestBody"
};
function processAction(msg, cfg) {
var isVerbose = process.env.debug || cfg.verbose;
if (isVerbose) {
console.log(`---MSG: ${JSON.stringify(msg)}`);
console.log(`---CFG: ${JSON.stringify(cfg)}`);
console.log(`---ENV: ${JSON.stringify(process.env)}`);
}
const contentType = cfg.body_content_type;
const body = msg.body;
mapFieldNames(body);
let parameters = {};
for(let param of PARAMETERS) {
parameters[param] = body[param];
}
// credentials for this operation
let securities = {};
let callParams = {
spec: spec,
operationId: 'Path_Update',
pathName: '/{filesystem}/{path}',
method: 'patch',
parameters: parameters,
requestContentType: contentType,
requestBody: body.requestBody,
securities: {authorized: securities},
server: spec.servers[cfg.server] || cfg.otherServer,
};
if (isVerbose) {
let out = Object.assign({}, callParams);
out.spec = '[omitted]';
console.log(`--SWAGGER CALL: ${JSON.stringify(out)}`);
}
// Call operation via Swagger client
return Swagger.execute(callParams).then(data => {
// emit a single message with data
this.emitData(data);
// if the response contains an array of entities, you can emit them one by one:
// data.obj.someItems.forEach((item) => {
// this.emitData(item);
// }
});
}
function m
|
obj) {
if(Array.isArray(obj)) {
obj.forEach(mapFieldNames);
}
else if(typeof obj === 'object' && obj) {
Object.keys(obj).forEach(key => {
mapFieldNames(obj[key]);
let goodKey = FIELD_MAP[key];
if(goodKey && goodKey !== key) {
obj[goodKey] = obj[key];
delete obj[key];
}
});
}
}
|
apFieldNames(
|
BookmarkIcon.js
|
import * as React from "react";
function BookmarkIcon(props) {
return /*#__PURE__*/React.createElement("svg", Object.assign({
xmlns: "http://www.w3.org/2000/svg",
fill: "none",
viewBox: "0 0 24 24",
stroke: "currentColor"
}, props), /*#__PURE__*/React.createElement("path", {
strokeLinecap: "round",
strokeLinejoin: "round",
strokeWidth: 2,
d: "M5 5a2 2 0 012-2h10a2 2 0 012 2v16l-7-3.5L5 21V5z"
}));
}
|
export default BookmarkIcon;
|
|
account_views.py
|
from django.shortcuts import render
def
|
(request):
return render(request, 'accounts/account.html')
|
accounts
|
websocket.rs
|
use crate::message::IRCMessage;
use crate::message::{AsRawIRC, IRCParseError};
use crate::transport::Transport;
use async_trait::async_trait;
use async_tungstenite::tokio::connect_async;
use futures_util::{
future,
sink::Sink,
stream::{self, FusedStream},
SinkExt, StreamExt, TryStreamExt,
};
use itertools::Either;
use smallvec::SmallVec;
use tungstenite::Error as WSError;
use tungstenite::Message as WSMessage;
/// Implements connecting to Twitch chat via IRC over secure WebSocket.
pub struct WSSTransport {
incoming_messages: <Self as Transport>::Incoming,
outgoing_messages: <Self as Transport>::Outgoing,
}
#[async_trait]
impl Transport for WSSTransport {
type ConnectError = WSError;
type IncomingError = WSError;
type OutgoingError = WSError;
type Incoming = Box<
dyn FusedStream<Item = Result<IRCMessage, Either<WSError, IRCParseError>>>
+ Unpin
+ Send
+ Sync,
>;
type Outgoing = Box<dyn Sink<IRCMessage, Error = Self::OutgoingError> + Unpin + Send + Sync>;
async fn new() -> Result<WSSTransport, WSError> {
let (ws_stream, _response) = connect_async("wss://irc-ws.chat.twitch.tv").await?;
let (write_half, read_half) = ws_stream.split();
let message_stream = read_half
.map_err(Either::Left)
.try_filter_map(|ws_message| {
future::ready(Ok::<_, Either<WSError, IRCParseError>>(
if let WSMessage::Text(text) = ws_message {
// the server can send multiple IRC messages in one websocket message,
// separated by newlines
Some(stream::iter(
text.lines()
.map(|l| Ok(String::from(l)))
.collect::<SmallVec<[Result<String, _>; 1]>>(),
))
} else {
None
},
))
})
.try_flatten()
// filter empty lines
.try_filter(|line| future::ready(!line.is_empty()))
.and_then(|s| future::ready(IRCMessage::parse(&s).map_err(Either::Right)))
.fuse();
let message_sink = write_half
.with(move |msg: IRCMessage| future::ready(Ok(WSMessage::Text(msg.as_raw_irc()))));
Ok(WSSTransport {
incoming_messages: Box::new(message_stream),
outgoing_messages: Box::new(message_sink),
})
}
fn split(self) -> (Self::Incoming, Self::Outgoing) {
(self.incoming_messages, self.outgoing_messages)
}
}
impl std::fmt::Debug for WSSTransport {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
|
}
|
{
f.debug_struct("WSSTransport").finish()
}
|
http.rs
|
use criterion::{criterion_group, Benchmark, Criterion, Throughput};
use futures::{compat::Future01CompatExt, TryFutureExt};
use hyper::{
service::{make_service_fn, service_fn},
Body, Response, Server,
};
use std::net::SocketAddr;
use tokio::runtime::Runtime;
use vector::{
config, sinks, sources,
test_util::{next_addr, random_lines, runtime, send_lines, start_topology, wait_for_tcp},
Error,
};
fn benchmark_http_no_compression(c: &mut Criterion)
|
fn benchmark_http_gzip(c: &mut Criterion) {
let num_lines: usize = 100_000;
let line_size: usize = 100;
let in_addr = next_addr();
let out_addr = next_addr();
let _srv = serve(out_addr);
let bench = Benchmark::new("http_gzip", move |b| {
b.iter_with_setup(
|| {
let mut config = config::Config::builder();
config.add_source(
"in",
sources::socket::SocketConfig::make_tcp_config(in_addr),
);
config.add_sink(
"out",
&["in"],
sinks::http::HttpSinkConfig {
uri: out_addr.to_string().parse::<http::Uri>().unwrap().into(),
compression: Default::default(),
method: Default::default(),
healthcheck_uri: Default::default(),
auth: Default::default(),
headers: Default::default(),
batch: Default::default(),
encoding: sinks::http::Encoding::Text.into(),
request: Default::default(),
tls: Default::default(),
},
);
let mut rt = runtime();
let topology = rt.block_on(async move {
let (topology, _crash) = start_topology(config.build().unwrap(), false).await;
wait_for_tcp(in_addr).await;
topology
});
(rt, topology)
},
|(mut rt, topology)| {
rt.block_on(async move {
let lines = random_lines(line_size).take(num_lines);
send_lines(in_addr, lines).await.unwrap();
topology.stop().compat().await.unwrap();
});
},
)
})
.sample_size(10)
.noise_threshold(0.05)
.throughput(Throughput::Bytes((num_lines * line_size) as u64));
c.bench("http", bench);
}
fn serve(addr: SocketAddr) -> Runtime {
let rt = runtime();
rt.spawn(async move {
let make_service = make_service_fn(|_| async {
Ok::<_, Error>(service_fn(|_req| async {
Ok::<_, Error>(Response::new(Body::empty()))
}))
});
Server::bind(&addr)
.serve(make_service)
.map_err(|e| panic!(e))
.await
});
rt
}
criterion_group!(http, benchmark_http_no_compression, benchmark_http_gzip);
|
{
let num_lines: usize = 100_000;
let line_size: usize = 100;
let in_addr = next_addr();
let out_addr = next_addr();
let _srv = serve(out_addr);
let bench = Benchmark::new("http_no_compression", move |b| {
b.iter_with_setup(
|| {
let mut config = config::Config::builder();
config.add_source(
"in",
sources::socket::SocketConfig::make_tcp_config(in_addr),
);
config.add_sink(
"out",
&["in"],
sinks::http::HttpSinkConfig {
uri: out_addr.to_string().parse::<http::Uri>().unwrap().into(),
compression: sinks::util::Compression::None,
method: Default::default(),
healthcheck_uri: Default::default(),
auth: Default::default(),
headers: Default::default(),
batch: Default::default(),
encoding: sinks::http::Encoding::Text.into(),
request: Default::default(),
tls: Default::default(),
},
);
let mut rt = runtime();
let topology = rt.block_on(async move {
let (topology, _crash) = start_topology(config.build().unwrap(), false).await;
wait_for_tcp(in_addr).await;
topology
});
(rt, topology)
},
|(mut rt, topology)| {
rt.block_on(async move {
let lines = random_lines(line_size).take(num_lines);
send_lines(in_addr, lines).await.unwrap();
topology.stop().compat().await.unwrap();
});
},
)
})
.sample_size(10)
.noise_threshold(0.05)
.throughput(Throughput::Bytes((num_lines * line_size) as u64));
c.bench("http", bench);
}
|
handle.rs
|
// Copyright 2019 The Tari Project
//
// Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
// following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
// disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
// following disclaimer in the documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
// products derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
// INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
// USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
use std::{sync::Arc, time::Duration};
use tari_comms::peer_manager::NodeId;
use tari_service_framework::reply_channel::SenderService;
use tokio::sync::broadcast;
use tower::Service;
use super::{error::LivenessError, state::Metadata};
use crate::proto::liveness::MetadataKey;
/// Request types made through the `LivenessHandle` and are handled by the `LivenessService`
#[derive(Debug, Clone)]
pub enum LivenessRequest {
/// Send a ping to the given node ID
SendPing(NodeId),
/// Retrieve the total number of pings received
GetPingCount,
/// Retrieve the total number of pongs received
GetPongCount,
/// Get average latency for node ID
GetAvgLatency(NodeId),
/// Get average latency for all connected nodes
GetNetworkAvgLatency,
/// Set the metadata attached to each ping/pong message
SetMetadataEntry(MetadataKey, Vec<u8>),
}
/// Response type for `LivenessService`
#[derive(Debug)]
pub enum LivenessResponse {
/// Indicates that the request succeeded
Ok,
/// Used to return a counter value from `GetPingCount` and `GetPongCount`
Count(usize),
/// Response for GetAvgLatency and GetNetworkAvgLatency
AvgLatency(Option<Duration>),
/// The number of active neighbouring peers
NumActiveNeighbours(usize),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum LivenessEvent {
/// A ping was received
ReceivedPing(Box<PingPongEvent>),
/// A pong was received. The latency to the peer (if available) and the metadata contained
/// within the received pong message are included as part of the event
ReceivedPong(Box<PingPongEvent>),
/// A round of pings was broadcast to random and monitored peers
PingRoundBroadcast(usize),
}
/// Represents a ping or pong event
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PingPongEvent {
/// The node id of the node which sent this ping or pong
pub node_id: NodeId,
/// Latency if available (i.e. a corresponding event was sent within the Liveness state inflight ping TTL)
pub latency: Option<Duration>,
/// Metadata of the corresponding node
pub metadata: Metadata,
}
impl PingPongEvent {
pub fn new(node_id: NodeId, latency: Option<Duration>, metadata: Metadata) -> Self {
Self {
node_id,
latency,
metadata,
}
}
}
pub type LivenessEventSender = broadcast::Sender<Arc<LivenessEvent>>;
pub type LivenessEventReceiver = broadcast::Receiver<Arc<LivenessEvent>>;
#[derive(Clone)]
pub struct LivenessHandle {
handle: SenderService<LivenessRequest, Result<LivenessResponse, LivenessError>>,
event_stream_sender: LivenessEventSender,
}
impl LivenessHandle {
pub fn new(
handle: SenderService<LivenessRequest, Result<LivenessResponse, LivenessError>>,
event_stream_sender: LivenessEventSender,
) -> Self {
Self {
handle,
event_stream_sender,
}
}
/// Returns an event stream for the liveness service
pub fn get_event_stream(&self) -> LivenessEventReceiver {
self.event_stream_sender.subscribe()
}
/// Send a ping to a given node ID
pub async fn send_ping(&mut self, node_id: NodeId) -> Result<(), LivenessError> {
match self.handle.call(LivenessRequest::SendPing(node_id)).await?? {
LivenessResponse::Ok => Ok(()),
_ => Err(LivenessError::UnexpectedApiResponse),
}
}
/// Retrieve the global ping count
pub async fn get_ping_count(&mut self) -> Result<usize, LivenessError> {
match self.handle.call(LivenessRequest::GetPingCount).await?? {
LivenessResponse::Count(c) => Ok(c),
_ => Err(LivenessError::UnexpectedApiResponse),
}
}
/// Retrieve the global pong count
pub async fn get_pong_count(&mut self) -> Result<usize, LivenessError> {
match self.handle.call(LivenessRequest::GetPongCount).await?? {
LivenessResponse::Count(c) => Ok(c),
_ => Err(LivenessError::UnexpectedApiResponse),
}
}
/// Set metadata entry for the pong message
pub async fn set_metadata_entry(&mut self, key: MetadataKey, value: Vec<u8>) -> Result<(), LivenessError>
|
/// Retrieve the average latency for a given node
pub async fn get_avg_latency(&mut self, node_id: NodeId) -> Result<Option<Duration>, LivenessError> {
match self.handle.call(LivenessRequest::GetAvgLatency(node_id)).await?? {
LivenessResponse::AvgLatency(v) => Ok(v),
_ => Err(LivenessError::UnexpectedApiResponse),
}
}
/// Retrieve the mean average latency for all connected nodes
pub async fn get_network_avg_latency(&mut self) -> Result<Option<Duration>, LivenessError> {
match self.handle.call(LivenessRequest::GetNetworkAvgLatency).await?? {
LivenessResponse::AvgLatency(v) => Ok(v),
_ => Err(LivenessError::UnexpectedApiResponse),
}
}
}
|
{
match self
.handle
.call(LivenessRequest::SetMetadataEntry(key, value))
.await??
{
LivenessResponse::Ok => Ok(()),
_ => Err(LivenessError::UnexpectedApiResponse),
}
}
|
lib.rs
|
//! # The Rust Core Library
//!
//! The Rust Core Library is the dependency-free[^free] foundation of [The
//! Rust Standard Library](../std/index.html). It is the portable glue
//! between the language and its libraries, defining the intrinsic and
//! primitive building blocks of all Rust code. It links to no
//! upstream libraries, no system libraries, and no libc.
//!
//! [^free]: Strictly speaking, there are some symbols which are needed but
//! they aren't always necessary.
//!
//! The core library is *minimal*: it isn't even aware of heap allocation,
//! nor does it provide concurrency or I/O. These things require
//! platform integration, and this library is platform-agnostic.
//!
//! # How to use the core library
//!
//! Please note that all of these details are currently not considered stable.
//!
// FIXME: Fill me in with more detail when the interface settles
//! This library is built on the assumption of a few existing symbols:
//!
//! * `memcpy`, `memcmp`, `memset` - These are core memory routines which are
//! often generated by LLVM. Additionally, this library can make explicit
//! calls to these functions. Their signatures are the same as found in C.
//! These functions are often provided by the system libc, but can also be
//! provided by the [compiler-builtins crate](https://crates.io/crates/compiler_builtins).
//!
//! * `rust_begin_panic` - This function takes four arguments, a
//! `fmt::Arguments`, a `&'static str`, and two `u32`'s. These four arguments
//! dictate the panic message, the file at which panic was invoked, and the
//! line and column inside the file. It is up to consumers of this core
//! library to define this panic function; it is only required to never
//! return. This requires a `lang` attribute named `panic_impl`.
//!
//! * `rust_eh_personality` - is used by the failure mechanisms of the
//! compiler. This is often mapped to GCC's personality function, but crates
//! which do not trigger a panic can be assured that this function is never
//! called. The `lang` attribute is called `eh_personality`.
// Since libcore defines many fundamental lang items, all tests live in a
// separate crate, libcoretest, to avoid bizarre issues.
//
// Here we explicitly #[cfg]-out this whole crate when testing. If we don't do
// this, both the generated test artifact and the linked libtest (which
// transitively includes libcore) will both define the same set of lang items,
// and this will cause the E0152 "found duplicate lang item" error. See
|
// discussion in #50466 for details.
//
// This cfg won't affect doc tests.
#![cfg(not(test))]
#![stable(feature = "core", since = "1.6.0")]
#![doc(
html_root_url = "https://doc.rust-lang.org/nightly/",
html_playground_url = "https://play.rust-lang.org/",
issue_tracker_base_url = "https://github.com/rust-lang/rust/issues/",
test(no_crate_inject, attr(deny(warnings))),
test(attr(allow(dead_code, deprecated, unused_variables, unused_mut)))
)]
#![no_core]
#![warn(deprecated_in_future)]
#![warn(missing_docs)]
#![warn(missing_debug_implementations)]
#![deny(intra_doc_link_resolution_failure)] // rustdoc is run without -D warnings
#![allow(explicit_outlives_requirements)]
#![allow(incomplete_features)]
#![feature(allow_internal_unstable)]
#![feature(arbitrary_self_types)]
#![feature(asm)]
#![feature(bound_cloned)]
#![feature(cfg_target_has_atomic)]
#![feature(concat_idents)]
#![feature(const_alloc_layout)]
#![feature(const_if_match)]
#![feature(const_panic)]
#![feature(const_fn_union)]
#![feature(const_generics)]
#![feature(const_ptr_offset_from)]
#![feature(const_result)]
#![feature(const_type_name)]
#![feature(custom_inner_attributes)]
#![feature(decl_macro)]
#![feature(doc_cfg)]
#![feature(doc_spotlight)]
#![feature(extern_types)]
#![feature(fundamental)]
#![feature(intrinsics)]
#![feature(try_find)]
#![feature(is_sorted)]
#![feature(iter_once_with)]
#![feature(lang_items)]
#![feature(link_llvm_intrinsics)]
#![feature(never_type)]
#![feature(nll)]
#![feature(exhaustive_patterns)]
#![feature(no_core)]
#![feature(optin_builtin_traits)]
#![feature(prelude_import)]
#![feature(repr_simd, platform_intrinsics)]
#![feature(rustc_attrs)]
#![feature(simd_ffi)]
#![feature(specialization)]
#![feature(staged_api)]
#![feature(std_internals)]
#![feature(stmt_expr_attributes)]
#![feature(track_caller)]
#![feature(transparent_unions)]
#![feature(unboxed_closures)]
#![feature(unsized_locals)]
#![feature(untagged_unions)]
#![feature(unwind_attributes)]
#![feature(doc_alias)]
#![feature(mmx_target_feature)]
#![feature(tbm_target_feature)]
#![feature(sse4a_target_feature)]
#![feature(arm_target_feature)]
#![feature(powerpc_target_feature)]
#![feature(mips_target_feature)]
#![feature(aarch64_target_feature)]
#![feature(wasm_target_feature)]
#![feature(avx512_target_feature)]
#![feature(cmpxchg16b_target_feature)]
#![feature(rtm_target_feature)]
#![feature(f16c_target_feature)]
#![feature(hexagon_target_feature)]
#![feature(const_int_conversion)]
#![feature(const_transmute)]
#![feature(structural_match)]
#![feature(abi_unadjusted)]
#![feature(adx_target_feature)]
#![feature(maybe_uninit_slice)]
#![feature(external_doc)]
#![feature(associated_type_bounds)]
#![feature(const_type_id)]
#![feature(const_caller_location)]
#![cfg_attr(bootstrap, feature(slice_patterns))]
#[prelude_import]
#[allow(unused)]
use prelude::v1::*;
#[cfg(not(test))] // See #65860
#[macro_use]
mod macros;
#[macro_use]
mod internal_macros;
#[path = "num/int_macros.rs"]
#[macro_use]
mod int_macros;
#[path = "num/uint_macros.rs"]
#[macro_use]
mod uint_macros;
#[path = "num/i128.rs"]
pub mod i128;
#[path = "num/i16.rs"]
pub mod i16;
#[path = "num/i32.rs"]
pub mod i32;
#[path = "num/i64.rs"]
pub mod i64;
#[path = "num/i8.rs"]
pub mod i8;
#[path = "num/isize.rs"]
pub mod isize;
#[path = "num/u128.rs"]
pub mod u128;
#[path = "num/u16.rs"]
pub mod u16;
#[path = "num/u32.rs"]
pub mod u32;
#[path = "num/u64.rs"]
pub mod u64;
#[path = "num/u8.rs"]
pub mod u8;
#[path = "num/usize.rs"]
pub mod usize;
#[path = "num/f32.rs"]
pub mod f32;
#[path = "num/f64.rs"]
pub mod f64;
#[macro_use]
pub mod num;
/* The libcore prelude, not as all-encompassing as the libstd prelude */
pub mod prelude;
/* Core modules for ownership management */
pub mod hint;
pub mod intrinsics;
pub mod mem;
pub mod ptr;
/* Core language traits */
pub mod borrow;
#[cfg(not(test))] // See #65860
pub mod clone;
#[cfg(not(test))] // See #65860
pub mod cmp;
pub mod convert;
#[cfg(not(test))] // See #65860
pub mod default;
#[cfg(not(test))] // See #65860
pub mod marker;
pub mod ops;
/* Core types and methods on primitives */
pub mod any;
#[cfg(not(test))] // See #65860
pub mod array;
pub mod ascii;
pub mod cell;
pub mod char;
pub mod ffi;
#[cfg(not(test))] // See #65860
pub mod iter;
pub mod option;
pub mod panic;
pub mod panicking;
#[cfg(not(test))] // See #65860
pub mod pin;
pub mod raw;
pub mod result;
pub mod sync;
#[cfg(not(test))] // See #65860
pub mod fmt;
#[cfg(not(test))] // See #65860
pub mod hash;
pub mod slice;
#[cfg(not(test))] // See #65860
pub mod str;
pub mod time;
pub mod unicode;
/* Async */
#[cfg(not(test))] // See #65860
pub mod future;
pub mod task;
/* Heap memory allocator trait */
#[allow(missing_docs)]
pub mod alloc;
// note: does not need to be public
mod bool;
mod tuple;
mod unit;
// Pull in the `core_arch` crate directly into libcore. The contents of
// `core_arch` are in a different repository: rust-lang/stdarch.
//
// `core_arch` depends on libcore, but the contents of this module are
// set up in such a way that directly pulling it here works such that the
// crate uses the this crate as its libcore.
#[path = "../stdarch/crates/core_arch/src/mod.rs"]
#[allow(missing_docs, missing_debug_implementations, dead_code, unused_imports)]
#[unstable(feature = "stdsimd", issue = "48556")]
mod core_arch;
#[stable(feature = "simd_arch", since = "1.27.0")]
pub use core_arch::arch;
| |
cluster.ts
|
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
import * as pulumi from "@pulumi/pulumi";
import * as utilities from "../utilities";
/**
* Provides an Neptune Cluster Resource. A Cluster Resource defines attributes that are
* applied to the entire cluster of Neptune Cluster Instances.
*
* Changes to a Neptune Cluster can occur when you manually change a
* parameter, such as `backupRetentionPeriod`, and are reflected in the next maintenance
* window. Because of this, this provider may report a difference in its planning
* phase because a modification has not yet taken place. You can use the
* `applyImmediately` flag to instruct the service to apply the change immediately
* (see documentation below).
*
* ## Example Usage
*
* ```typescript
* import * as pulumi from "@pulumi/pulumi";
* import * as aws from "@pulumi/aws";
*
* const defaultCluster = new aws.neptune.Cluster("default", {
* applyImmediately: true,
* backupRetentionPeriod: 5,
* clusterIdentifier: "neptune-cluster-demo",
* engine: "neptune",
* iamDatabaseAuthenticationEnabled: true,
* preferredBackupWindow: "07:00-09:00",
* skipFinalSnapshot: true,
* });
* ```
*
* > **Note:** AWS Neptune does not support user name/password–based access control.
* See the AWS [Docs](https://docs.aws.amazon.com/neptune/latest/userguide/limits.html) for more information.
*
* ## Import
*
* `aws_neptune_cluster` can be imported by using the cluster identifier, e.g.
*
* ```sh
* $ pulumi import aws:neptune/cluster:Cluster example my-cluster
* ```
*/
export class Cl
|
xtends pulumi.CustomResource {
/**
* Get an existing Cluster resource's state with the given name, ID, and optional extra
* properties used to qualify the lookup.
*
* @param name The _unique_ name of the resulting resource.
* @param id The _unique_ provider ID of the resource to lookup.
* @param state Any extra arguments used during the lookup.
* @param opts Optional settings to control the behavior of the CustomResource.
*/
public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: ClusterState, opts?: pulumi.CustomResourceOptions): Cluster {
return new Cluster(name, <any>state, { ...opts, id: id });
}
/** @internal */
public static readonly __pulumiType = 'aws:neptune/cluster:Cluster';
/**
* Returns true if the given object is an instance of Cluster. This is designed to work even
* when multiple copies of the Pulumi SDK have been loaded into the same process.
*/
public static isInstance(obj: any): obj is Cluster {
if (obj === undefined || obj === null) {
return false;
}
return obj['__pulumiType'] === Cluster.__pulumiType;
}
/**
* Specifies whether any cluster modifications are applied immediately, or during the next maintenance window. Default is `false`.
*/
public readonly applyImmediately!: pulumi.Output<boolean>;
/**
* The Neptune Cluster Amazon Resource Name (ARN)
*/
public /*out*/ readonly arn!: pulumi.Output<string>;
/**
* A list of EC2 Availability Zones that instances in the Neptune cluster can be created in.
*/
public readonly availabilityZones!: pulumi.Output<string[]>;
/**
* The days to retain backups for. Default `1`
*/
public readonly backupRetentionPeriod!: pulumi.Output<number | undefined>;
/**
* The cluster identifier. If omitted, this provider will assign a random, unique identifier.
*/
public readonly clusterIdentifier!: pulumi.Output<string>;
/**
* Creates a unique cluster identifier beginning with the specified prefix. Conflicts with `clusterIdentifier`.
*/
public readonly clusterIdentifierPrefix!: pulumi.Output<string>;
/**
* List of Neptune Instances that are a part of this cluster
*/
public /*out*/ readonly clusterMembers!: pulumi.Output<string[]>;
/**
* The Neptune Cluster Resource ID
*/
public /*out*/ readonly clusterResourceId!: pulumi.Output<string>;
/**
* If set to true, tags are copied to any snapshot of the DB cluster that is created.
*/
public readonly copyTagsToSnapshot!: pulumi.Output<boolean | undefined>;
/**
* A value that indicates whether the DB cluster has deletion protection enabled.The database can't be deleted when deletion protection is enabled. By default, deletion protection is disabled.
*/
public readonly deletionProtection!: pulumi.Output<boolean | undefined>;
/**
* A list of the log types this DB cluster is configured to export to Cloudwatch Logs. Currently only supports `audit`.
*/
public readonly enableCloudwatchLogsExports!: pulumi.Output<string[] | undefined>;
/**
* The DNS address of the Neptune instance
*/
public /*out*/ readonly endpoint!: pulumi.Output<string>;
/**
* The name of the database engine to be used for this Neptune cluster. Defaults to `neptune`.
*/
public readonly engine!: pulumi.Output<string | undefined>;
/**
* The database engine version.
*/
public readonly engineVersion!: pulumi.Output<string>;
/**
* The name of your final Neptune snapshot when this Neptune cluster is deleted. If omitted, no final snapshot will be made.
*/
public readonly finalSnapshotIdentifier!: pulumi.Output<string | undefined>;
/**
* The Route53 Hosted Zone ID of the endpoint
*/
public /*out*/ readonly hostedZoneId!: pulumi.Output<string>;
/**
* Specifies whether or mappings of AWS Identity and Access Management (IAM) accounts to database accounts is enabled.
*/
public readonly iamDatabaseAuthenticationEnabled!: pulumi.Output<boolean | undefined>;
/**
* A List of ARNs for the IAM roles to associate to the Neptune Cluster.
*/
public readonly iamRoles!: pulumi.Output<string[] | undefined>;
/**
* The ARN for the KMS encryption key. When specifying `kmsKeyArn`, `storageEncrypted` needs to be set to true.
*/
public readonly kmsKeyArn!: pulumi.Output<string>;
/**
* A cluster parameter group to associate with the cluster.
*/
public readonly neptuneClusterParameterGroupName!: pulumi.Output<string | undefined>;
/**
* A Neptune subnet group to associate with this Neptune instance.
*/
public readonly neptuneSubnetGroupName!: pulumi.Output<string>;
/**
* The port on which the Neptune accepts connections. Default is `8182`.
*/
public readonly port!: pulumi.Output<number | undefined>;
/**
* The daily time range during which automated backups are created if automated backups are enabled using the BackupRetentionPeriod parameter. Time in UTC. Default: A 30-minute window selected at random from an 8-hour block of time per region. e.g. 04:00-09:00
*/
public readonly preferredBackupWindow!: pulumi.Output<string>;
/**
* The weekly time range during which system maintenance can occur, in (UTC) e.g. wed:04:00-wed:04:30
*/
public readonly preferredMaintenanceWindow!: pulumi.Output<string>;
/**
* A read-only endpoint for the Neptune cluster, automatically load-balanced across replicas
*/
public /*out*/ readonly readerEndpoint!: pulumi.Output<string>;
/**
* ARN of a source Neptune cluster or Neptune instance if this Neptune cluster is to be created as a Read Replica.
*/
public readonly replicationSourceIdentifier!: pulumi.Output<string | undefined>;
/**
* Determines whether a final Neptune snapshot is created before the Neptune cluster is deleted. If true is specified, no Neptune snapshot is created. If false is specified, a Neptune snapshot is created before the Neptune cluster is deleted, using the value from `finalSnapshotIdentifier`. Default is `false`.
*/
public readonly skipFinalSnapshot!: pulumi.Output<boolean | undefined>;
/**
* Specifies whether or not to create this cluster from a snapshot. You can use either the name or ARN when specifying a Neptune cluster snapshot, or the ARN when specifying a Neptune snapshot.
*/
public readonly snapshotIdentifier!: pulumi.Output<string | undefined>;
/**
* Specifies whether the Neptune cluster is encrypted. The default is `false` if not specified.
*/
public readonly storageEncrypted!: pulumi.Output<boolean | undefined>;
/**
* A map of tags to assign to the Neptune cluster. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level.
*/
public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>;
/**
* A map of tags assigned to the resource, including those inherited from the provider .
*/
public /*out*/ readonly tagsAll!: pulumi.Output<{[key: string]: string}>;
/**
* List of VPC security groups to associate with the Cluster
*/
public readonly vpcSecurityGroupIds!: pulumi.Output<string[]>;
/**
* Create a Cluster resource with the given unique name, arguments, and options.
*
* @param name The _unique_ name of the resource.
* @param args The arguments to use to populate this resource's properties.
* @param opts A bag of options that control this resource's behavior.
*/
constructor(name: string, args?: ClusterArgs, opts?: pulumi.CustomResourceOptions)
constructor(name: string, argsOrState?: ClusterArgs | ClusterState, opts?: pulumi.CustomResourceOptions) {
let inputs: pulumi.Inputs = {};
opts = opts || {};
if (opts.id) {
const state = argsOrState as ClusterState | undefined;
inputs["applyImmediately"] = state ? state.applyImmediately : undefined;
inputs["arn"] = state ? state.arn : undefined;
inputs["availabilityZones"] = state ? state.availabilityZones : undefined;
inputs["backupRetentionPeriod"] = state ? state.backupRetentionPeriod : undefined;
inputs["clusterIdentifier"] = state ? state.clusterIdentifier : undefined;
inputs["clusterIdentifierPrefix"] = state ? state.clusterIdentifierPrefix : undefined;
inputs["clusterMembers"] = state ? state.clusterMembers : undefined;
inputs["clusterResourceId"] = state ? state.clusterResourceId : undefined;
inputs["copyTagsToSnapshot"] = state ? state.copyTagsToSnapshot : undefined;
inputs["deletionProtection"] = state ? state.deletionProtection : undefined;
inputs["enableCloudwatchLogsExports"] = state ? state.enableCloudwatchLogsExports : undefined;
inputs["endpoint"] = state ? state.endpoint : undefined;
inputs["engine"] = state ? state.engine : undefined;
inputs["engineVersion"] = state ? state.engineVersion : undefined;
inputs["finalSnapshotIdentifier"] = state ? state.finalSnapshotIdentifier : undefined;
inputs["hostedZoneId"] = state ? state.hostedZoneId : undefined;
inputs["iamDatabaseAuthenticationEnabled"] = state ? state.iamDatabaseAuthenticationEnabled : undefined;
inputs["iamRoles"] = state ? state.iamRoles : undefined;
inputs["kmsKeyArn"] = state ? state.kmsKeyArn : undefined;
inputs["neptuneClusterParameterGroupName"] = state ? state.neptuneClusterParameterGroupName : undefined;
inputs["neptuneSubnetGroupName"] = state ? state.neptuneSubnetGroupName : undefined;
inputs["port"] = state ? state.port : undefined;
inputs["preferredBackupWindow"] = state ? state.preferredBackupWindow : undefined;
inputs["preferredMaintenanceWindow"] = state ? state.preferredMaintenanceWindow : undefined;
inputs["readerEndpoint"] = state ? state.readerEndpoint : undefined;
inputs["replicationSourceIdentifier"] = state ? state.replicationSourceIdentifier : undefined;
inputs["skipFinalSnapshot"] = state ? state.skipFinalSnapshot : undefined;
inputs["snapshotIdentifier"] = state ? state.snapshotIdentifier : undefined;
inputs["storageEncrypted"] = state ? state.storageEncrypted : undefined;
inputs["tags"] = state ? state.tags : undefined;
inputs["tagsAll"] = state ? state.tagsAll : undefined;
inputs["vpcSecurityGroupIds"] = state ? state.vpcSecurityGroupIds : undefined;
} else {
const args = argsOrState as ClusterArgs | undefined;
inputs["applyImmediately"] = args ? args.applyImmediately : undefined;
inputs["availabilityZones"] = args ? args.availabilityZones : undefined;
inputs["backupRetentionPeriod"] = args ? args.backupRetentionPeriod : undefined;
inputs["clusterIdentifier"] = args ? args.clusterIdentifier : undefined;
inputs["clusterIdentifierPrefix"] = args ? args.clusterIdentifierPrefix : undefined;
inputs["copyTagsToSnapshot"] = args ? args.copyTagsToSnapshot : undefined;
inputs["deletionProtection"] = args ? args.deletionProtection : undefined;
inputs["enableCloudwatchLogsExports"] = args ? args.enableCloudwatchLogsExports : undefined;
inputs["engine"] = args ? args.engine : undefined;
inputs["engineVersion"] = args ? args.engineVersion : undefined;
inputs["finalSnapshotIdentifier"] = args ? args.finalSnapshotIdentifier : undefined;
inputs["iamDatabaseAuthenticationEnabled"] = args ? args.iamDatabaseAuthenticationEnabled : undefined;
inputs["iamRoles"] = args ? args.iamRoles : undefined;
inputs["kmsKeyArn"] = args ? args.kmsKeyArn : undefined;
inputs["neptuneClusterParameterGroupName"] = args ? args.neptuneClusterParameterGroupName : undefined;
inputs["neptuneSubnetGroupName"] = args ? args.neptuneSubnetGroupName : undefined;
inputs["port"] = args ? args.port : undefined;
inputs["preferredBackupWindow"] = args ? args.preferredBackupWindow : undefined;
inputs["preferredMaintenanceWindow"] = args ? args.preferredMaintenanceWindow : undefined;
inputs["replicationSourceIdentifier"] = args ? args.replicationSourceIdentifier : undefined;
inputs["skipFinalSnapshot"] = args ? args.skipFinalSnapshot : undefined;
inputs["snapshotIdentifier"] = args ? args.snapshotIdentifier : undefined;
inputs["storageEncrypted"] = args ? args.storageEncrypted : undefined;
inputs["tags"] = args ? args.tags : undefined;
inputs["vpcSecurityGroupIds"] = args ? args.vpcSecurityGroupIds : undefined;
inputs["arn"] = undefined /*out*/;
inputs["clusterMembers"] = undefined /*out*/;
inputs["clusterResourceId"] = undefined /*out*/;
inputs["endpoint"] = undefined /*out*/;
inputs["hostedZoneId"] = undefined /*out*/;
inputs["readerEndpoint"] = undefined /*out*/;
inputs["tagsAll"] = undefined /*out*/;
}
if (!opts.version) {
opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()});
}
super(Cluster.__pulumiType, name, inputs, opts);
}
}
/**
* Input properties used for looking up and filtering Cluster resources.
*/
export interface ClusterState {
/**
* Specifies whether any cluster modifications are applied immediately, or during the next maintenance window. Default is `false`.
*/
applyImmediately?: pulumi.Input<boolean>;
/**
* The Neptune Cluster Amazon Resource Name (ARN)
*/
arn?: pulumi.Input<string>;
/**
* A list of EC2 Availability Zones that instances in the Neptune cluster can be created in.
*/
availabilityZones?: pulumi.Input<pulumi.Input<string>[]>;
/**
* The days to retain backups for. Default `1`
*/
backupRetentionPeriod?: pulumi.Input<number>;
/**
* The cluster identifier. If omitted, this provider will assign a random, unique identifier.
*/
clusterIdentifier?: pulumi.Input<string>;
/**
* Creates a unique cluster identifier beginning with the specified prefix. Conflicts with `clusterIdentifier`.
*/
clusterIdentifierPrefix?: pulumi.Input<string>;
/**
* List of Neptune Instances that are a part of this cluster
*/
clusterMembers?: pulumi.Input<pulumi.Input<string>[]>;
/**
* The Neptune Cluster Resource ID
*/
clusterResourceId?: pulumi.Input<string>;
/**
* If set to true, tags are copied to any snapshot of the DB cluster that is created.
*/
copyTagsToSnapshot?: pulumi.Input<boolean>;
/**
* A value that indicates whether the DB cluster has deletion protection enabled.The database can't be deleted when deletion protection is enabled. By default, deletion protection is disabled.
*/
deletionProtection?: pulumi.Input<boolean>;
/**
* A list of the log types this DB cluster is configured to export to Cloudwatch Logs. Currently only supports `audit`.
*/
enableCloudwatchLogsExports?: pulumi.Input<pulumi.Input<string>[]>;
/**
* The DNS address of the Neptune instance
*/
endpoint?: pulumi.Input<string>;
/**
* The name of the database engine to be used for this Neptune cluster. Defaults to `neptune`.
*/
engine?: pulumi.Input<string>;
/**
* The database engine version.
*/
engineVersion?: pulumi.Input<string>;
/**
* The name of your final Neptune snapshot when this Neptune cluster is deleted. If omitted, no final snapshot will be made.
*/
finalSnapshotIdentifier?: pulumi.Input<string>;
/**
* The Route53 Hosted Zone ID of the endpoint
*/
hostedZoneId?: pulumi.Input<string>;
/**
* Specifies whether or mappings of AWS Identity and Access Management (IAM) accounts to database accounts is enabled.
*/
iamDatabaseAuthenticationEnabled?: pulumi.Input<boolean>;
/**
* A List of ARNs for the IAM roles to associate to the Neptune Cluster.
*/
iamRoles?: pulumi.Input<pulumi.Input<string>[]>;
/**
* The ARN for the KMS encryption key. When specifying `kmsKeyArn`, `storageEncrypted` needs to be set to true.
*/
kmsKeyArn?: pulumi.Input<string>;
/**
* A cluster parameter group to associate with the cluster.
*/
neptuneClusterParameterGroupName?: pulumi.Input<string>;
/**
* A Neptune subnet group to associate with this Neptune instance.
*/
neptuneSubnetGroupName?: pulumi.Input<string>;
/**
* The port on which the Neptune accepts connections. Default is `8182`.
*/
port?: pulumi.Input<number>;
/**
* The daily time range during which automated backups are created if automated backups are enabled using the BackupRetentionPeriod parameter. Time in UTC. Default: A 30-minute window selected at random from an 8-hour block of time per region. e.g. 04:00-09:00
*/
preferredBackupWindow?: pulumi.Input<string>;
/**
* The weekly time range during which system maintenance can occur, in (UTC) e.g. wed:04:00-wed:04:30
*/
preferredMaintenanceWindow?: pulumi.Input<string>;
/**
* A read-only endpoint for the Neptune cluster, automatically load-balanced across replicas
*/
readerEndpoint?: pulumi.Input<string>;
/**
* ARN of a source Neptune cluster or Neptune instance if this Neptune cluster is to be created as a Read Replica.
*/
replicationSourceIdentifier?: pulumi.Input<string>;
/**
* Determines whether a final Neptune snapshot is created before the Neptune cluster is deleted. If true is specified, no Neptune snapshot is created. If false is specified, a Neptune snapshot is created before the Neptune cluster is deleted, using the value from `finalSnapshotIdentifier`. Default is `false`.
*/
skipFinalSnapshot?: pulumi.Input<boolean>;
/**
* Specifies whether or not to create this cluster from a snapshot. You can use either the name or ARN when specifying a Neptune cluster snapshot, or the ARN when specifying a Neptune snapshot.
*/
snapshotIdentifier?: pulumi.Input<string>;
/**
* Specifies whether the Neptune cluster is encrypted. The default is `false` if not specified.
*/
storageEncrypted?: pulumi.Input<boolean>;
/**
* A map of tags to assign to the Neptune cluster. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* A map of tags assigned to the resource, including those inherited from the provider .
*/
tagsAll?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* List of VPC security groups to associate with the Cluster
*/
vpcSecurityGroupIds?: pulumi.Input<pulumi.Input<string>[]>;
}
/**
* The set of arguments for constructing a Cluster resource.
*/
export interface ClusterArgs {
/**
* Specifies whether any cluster modifications are applied immediately, or during the next maintenance window. Default is `false`.
*/
applyImmediately?: pulumi.Input<boolean>;
/**
* A list of EC2 Availability Zones that instances in the Neptune cluster can be created in.
*/
availabilityZones?: pulumi.Input<pulumi.Input<string>[]>;
/**
* The days to retain backups for. Default `1`
*/
backupRetentionPeriod?: pulumi.Input<number>;
/**
* The cluster identifier. If omitted, this provider will assign a random, unique identifier.
*/
clusterIdentifier?: pulumi.Input<string>;
/**
* Creates a unique cluster identifier beginning with the specified prefix. Conflicts with `clusterIdentifier`.
*/
clusterIdentifierPrefix?: pulumi.Input<string>;
/**
* If set to true, tags are copied to any snapshot of the DB cluster that is created.
*/
copyTagsToSnapshot?: pulumi.Input<boolean>;
/**
* A value that indicates whether the DB cluster has deletion protection enabled.The database can't be deleted when deletion protection is enabled. By default, deletion protection is disabled.
*/
deletionProtection?: pulumi.Input<boolean>;
/**
* A list of the log types this DB cluster is configured to export to Cloudwatch Logs. Currently only supports `audit`.
*/
enableCloudwatchLogsExports?: pulumi.Input<pulumi.Input<string>[]>;
/**
* The name of the database engine to be used for this Neptune cluster. Defaults to `neptune`.
*/
engine?: pulumi.Input<string>;
/**
* The database engine version.
*/
engineVersion?: pulumi.Input<string>;
/**
* The name of your final Neptune snapshot when this Neptune cluster is deleted. If omitted, no final snapshot will be made.
*/
finalSnapshotIdentifier?: pulumi.Input<string>;
/**
* Specifies whether or mappings of AWS Identity and Access Management (IAM) accounts to database accounts is enabled.
*/
iamDatabaseAuthenticationEnabled?: pulumi.Input<boolean>;
/**
* A List of ARNs for the IAM roles to associate to the Neptune Cluster.
*/
iamRoles?: pulumi.Input<pulumi.Input<string>[]>;
/**
* The ARN for the KMS encryption key. When specifying `kmsKeyArn`, `storageEncrypted` needs to be set to true.
*/
kmsKeyArn?: pulumi.Input<string>;
/**
* A cluster parameter group to associate with the cluster.
*/
neptuneClusterParameterGroupName?: pulumi.Input<string>;
/**
* A Neptune subnet group to associate with this Neptune instance.
*/
neptuneSubnetGroupName?: pulumi.Input<string>;
/**
* The port on which the Neptune accepts connections. Default is `8182`.
*/
port?: pulumi.Input<number>;
/**
* The daily time range during which automated backups are created if automated backups are enabled using the BackupRetentionPeriod parameter. Time in UTC. Default: A 30-minute window selected at random from an 8-hour block of time per region. e.g. 04:00-09:00
*/
preferredBackupWindow?: pulumi.Input<string>;
/**
* The weekly time range during which system maintenance can occur, in (UTC) e.g. wed:04:00-wed:04:30
*/
preferredMaintenanceWindow?: pulumi.Input<string>;
/**
* ARN of a source Neptune cluster or Neptune instance if this Neptune cluster is to be created as a Read Replica.
*/
replicationSourceIdentifier?: pulumi.Input<string>;
/**
* Determines whether a final Neptune snapshot is created before the Neptune cluster is deleted. If true is specified, no Neptune snapshot is created. If false is specified, a Neptune snapshot is created before the Neptune cluster is deleted, using the value from `finalSnapshotIdentifier`. Default is `false`.
*/
skipFinalSnapshot?: pulumi.Input<boolean>;
/**
* Specifies whether or not to create this cluster from a snapshot. You can use either the name or ARN when specifying a Neptune cluster snapshot, or the ARN when specifying a Neptune snapshot.
*/
snapshotIdentifier?: pulumi.Input<string>;
/**
* Specifies whether the Neptune cluster is encrypted. The default is `false` if not specified.
*/
storageEncrypted?: pulumi.Input<boolean>;
/**
* A map of tags to assign to the Neptune cluster. .If configured with a provider `defaultTags` configuration block present, tags with matching keys will overwrite those defined at the provider-level.
*/
tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>;
/**
* List of VPC security groups to associate with the Cluster
*/
vpcSecurityGroupIds?: pulumi.Input<pulumi.Input<string>[]>;
}
|
uster e
|
_form_recognizer_client.py
|
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
# pylint: disable=protected-access
from typing import (
Any,
IO,
Union,
List,
TYPE_CHECKING
)
from azure.core.tracing.decorator import distributed_trace
from azure.core.polling import LROPoller
from azure.core.polling.base_polling import LROBasePolling
from ._generated._form_recognizer_client import FormRecognizerClient as FormRecognizer
from ._response_handlers import (
prepare_receipt,
prepare_content_result,
prepare_form_result
)
from ._generated.models import AnalyzeOperationResult
from ._helpers import get_content_type, get_authentication_policy, error_map, POLLING_INTERVAL
from ._user_agent import USER_AGENT
from ._polling import AnalyzePolling
if TYPE_CHECKING:
from azure.core.credentials import AzureKeyCredential, TokenCredential
from ._models import FormPage, RecognizedForm
class FormRecognizerClient(object):
"""FormRecognizerClient extracts information from forms and images into structured data.
It is the interface to use for analyzing receipts, recognizing content/layout from
forms, and analyzing custom forms from trained models. It provides different methods
based on inputs from a URL and inputs from a stream.
:param str endpoint: Supported Cognitive Services endpoints (protocol and hostname,
for example: https://westus2.api.cognitive.microsoft.com).
:param credential: Credentials needed for the client to connect to Azure.
This is an instance of AzureKeyCredential if using an API key or a token
credential from :mod:`azure.identity`.
:type credential: :class:`~azure.core.credentials.AzureKeyCredential` or
:class:`~azure.core.credentials.TokenCredential`
.. admonition:: Example:
.. literalinclude:: ../samples/sample_authentication.py
:start-after: [START create_fr_client_with_key]
:end-before: [END create_fr_client_with_key]
:language: python
:dedent: 8
:caption: Creating the FormRecognizerClient with an endpoint and API key.
.. literalinclude:: ../samples/sample_authentication.py
:start-after: [START create_fr_client_with_aad]
:end-before: [END create_fr_client_with_aad]
:language: python
:dedent: 8
:caption: Creating the FormRecognizerClient with a token credential.
"""
def __init__(self, endpoint, credential, **kwargs):
# type: (str, Union[AzureKeyCredential, TokenCredential], Any) -> None
authentication_policy = get_authentication_policy(credential)
polling_interval = kwargs.pop("polling_interval", POLLING_INTERVAL)
self._client = FormRecognizer(
endpoint=endpoint,
credential=credential, # type: ignore
sdk_moniker=USER_AGENT,
authentication_policy=authentication_policy,
polling_interval=polling_interval,
**kwargs
)
def _receipt_callback(self, raw_response, _, headers): # pylint: disable=unused-argument
analyze_result = self._client._deserialize(AnalyzeOperationResult, raw_response)
return prepare_receipt(analyze_result)
@distributed_trace
def begin_recognize_receipts(self, receipt, **kwargs):
# type: (Union[bytes, IO[bytes]], Any) -> LROPoller[List[RecognizedForm]]
"""Extract field text and semantic values from a given US sales receipt.
The input document must be of one of the supported content types - 'application/pdf',
'image/jpeg', 'image/png' or 'image/tiff'.
See fields found on a receipt here:
https://aka.ms/azsdk/python/formrecognizer/receiptfields
:param receipt: JPEG, PNG, PDF and TIFF type file stream or bytes.
Currently only supports US sales receipts.
:type receipt: bytes or IO[bytes]
:keyword bool include_field_elements:
Whether or not to include field elements such as lines and words in addition to form fields.
:keyword content_type: Media type of the body sent to the API. Content-type is
auto-detected, but can be overridden by passing this keyword argument. For options,
see :class:`~azure.ai.formrecognizer.FormContentType`.
:paramtype content_type: str or ~azure.ai.formrecognizer.FormContentType
:keyword int polling_interval: Waiting time between two polls for LRO operations
if no Retry-After header is present. Defaults to 5 seconds.
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:return: An instance of an LROPoller. Call `result()` on the poller
object to return a list[:class:`~azure.ai.formrecognizer.RecognizedForm`].
:rtype: ~azure.core.polling.LROPoller[list[~azure.ai.formrecognizer.RecognizedForm]]
:raises ~azure.core.exceptions.HttpResponseError:
.. admonition:: Example:
.. literalinclude:: ../samples/sample_recognize_receipts.py
:start-after: [START recognize_receipts]
:end-before: [END recognize_receipts]
:language: python
:dedent: 8
:caption: Recognize US sales receipt fields.
"""
polling_interval = kwargs.pop("polling_interval", self._client._config.polling_interval)
continuation_token = kwargs.pop("continuation_token", None)
content_type = kwargs.pop("content_type", None)
if content_type == "application/json":
raise TypeError("Call begin_recognize_receipts_from_url() to analyze a receipt from a URL.")
include_field_elements = kwargs.pop("include_field_elements", False)
if content_type is None:
content_type = get_content_type(receipt)
return self._client.begin_analyze_receipt_async(
file_stream=receipt,
content_type=content_type,
include_text_details=include_field_elements,
cls=kwargs.pop("cls", self._receipt_callback),
polling=LROBasePolling(timeout=polling_interval, **kwargs),
error_map=error_map,
continuation_token=continuation_token,
**kwargs
)
@distributed_trace
def begin_recognize_receipts_from_url(self, receipt_url, **kwargs):
# type: (str, Any) -> LROPoller[List[RecognizedForm]]
"""Extract field text and semantic values from a given US sales receipt.
The input document must be the location (URL) of the receipt to be analyzed.
See fields found on a receipt here:
https://aka.ms/azsdk/python/formrecognizer/receiptfields
:param str receipt_url: The URL of the receipt to analyze. The input must be a valid, encoded URL
of one of the supported formats: JPEG, PNG, PDF and TIFF. Currently only supports
US sales receipts.
:keyword bool include_field_elements:
Whether or not to include field elements such as lines and words in addition to form fields.
:keyword int polling_interval: Waiting time between two polls for LRO operations
if no Retry-After header is present. Defaults to 5 seconds.
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:return: An instance of an LROPoller. Call `result()` on the poller
object to return a list[:class:`~azure.ai.formrecognizer.RecognizedForm`].
:rtype: ~azure.core.polling.LROPoller[list[~azure.ai.formrecognizer.RecognizedForm]]
:raises ~azure.core.exceptions.HttpResponseError:
.. admonition:: Example:
.. literalinclude:: ../samples/sample_recognize_receipts_from_url.py
:start-after: [START recognize_receipts_from_url]
:end-before: [END recognize_receipts_from_url]
:language: python
:dedent: 8
:caption: Recognize US sales receipt fields from a URL.
"""
polling_interval = kwargs.pop("polling_interval", self._client._config.polling_interval)
continuation_token = kwargs.pop("continuation_token", None)
include_field_elements = kwargs.pop("include_field_elements", False)
return self._client.begin_analyze_receipt_async(
file_stream={"source": receipt_url},
include_text_details=include_field_elements,
cls=kwargs.pop("cls", self._receipt_callback),
polling=LROBasePolling(timeout=polling_interval, **kwargs),
error_map=error_map,
continuation_token=continuation_token,
**kwargs
)
def _content_callback(self, raw_response, _, headers): # pylint: disable=unused-argument
analyze_result = self._client._deserialize(AnalyzeOperationResult, raw_response)
return prepare_content_result(analyze_result)
@distributed_trace
def begin_recognize_content(self, form, **kwargs):
# type: (Union[bytes, IO[bytes]], Any) -> LROPoller[List[FormPage]]
"""Extract text and content/layout information from a given document.
The input document must be of one of the supported content types - 'application/pdf',
'image/jpeg', 'image/png' or 'image/tiff'.
:param form: JPEG, PNG, PDF and TIFF type file stream or bytes.
:type form: bytes or IO[bytes]
:keyword content_type: Media type of the body sent to the API. Content-type is
auto-detected, but can be overridden by passing this keyword argument. For options,
see :class:`~azure.ai.formrecognizer.FormContentType`.
:paramtype content_type: str or ~azure.ai.formrecognizer.FormContentType
:keyword int polling_interval: Waiting time between two polls for LRO operations
if no Retry-After header is present. Defaults to 5 seconds.
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:return: An instance of an LROPoller. Call `result()` on the poller
object to return a list[:class:`~azure.ai.formrecognizer.FormPage`].
:rtype: ~azure.core.polling.LROPoller[list[~azure.ai.formrecognizer.FormPage]]
:raises ~azure.core.exceptions.HttpResponseError:
.. admonition:: Example:
.. literalinclude:: ../samples/sample_recognize_content.py
:start-after: [START recognize_content]
:end-before: [END recognize_content]
:language: python
:dedent: 8
:caption: Recognize text and content/layout information from a form.
"""
polling_interval = kwargs.pop("polling_interval", self._client._config.polling_interval)
continuation_token = kwargs.pop("continuation_token", None)
content_type = kwargs.pop("content_type", None)
if content_type == "application/json":
raise TypeError("Call begin_recognize_content_from_url() to analyze a document from a URL.")
if content_type is None:
content_type = get_content_type(form)
return self._client.begin_analyze_layout_async(
file_stream=form,
content_type=content_type,
cls=kwargs.pop("cls", self._content_callback),
polling=LROBasePolling(timeout=polling_interval, **kwargs),
error_map=error_map,
continuation_token=continuation_token,
**kwargs
)
@distributed_trace
def begin_recognize_content_from_url(self, form_url, **kwargs):
# type: (str, Any) -> LROPoller[List[FormPage]]
"""Extract text and layout information from a given document.
The input document must be the location (URL) of the document to be analyzed.
:param str form_url: The URL of the form to analyze. The input must be a valid, encoded URL
of one of the supported formats: JPEG, PNG, PDF and TIFF.
:keyword int polling_interval: Waiting time between two polls for LRO operations
if no Retry-After header is present. Defaults to 5 seconds.
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:return: An instance of an LROPoller. Call `result()` on the poller
object to return a list[:class:`~azure.ai.formrecognizer.FormPage`].
:rtype: ~azure.core.polling.LROPoller[list[~azure.ai.formrecognizer.FormPage]]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling_interval = kwargs.pop("polling_interval", self._client._config.polling_interval)
continuation_token = kwargs.pop("continuation_token", None)
return self._client.begin_analyze_layout_async(
file_stream={"source": form_url},
cls=kwargs.pop("cls", self._content_callback),
polling=LROBasePolling(timeout=polling_interval, **kwargs),
error_map=error_map,
continuation_token=continuation_token,
**kwargs
)
@distributed_trace
def begin_recognize_custom_forms(self, model_id, form, **kwargs):
# type: (str, Union[bytes, IO[bytes]], Any) -> LROPoller[List[RecognizedForm]]
"""Analyze a custom form with a model trained with or without labels. The form
to analyze should be of the same type as the forms that were used to train the model.
The input document must be of one of the supported content types - 'application/pdf',
'image/jpeg', 'image/png' or 'image/tiff'.
:param str model_id: Custom model identifier.
:param form: JPEG, PNG, PDF and TIFF type file stream or bytes.
:type form: bytes or IO[bytes]
:keyword bool include_field_elements:
Whether or not to include field elements such as lines and words in addition to form fields.
:keyword content_type: Media type of the body sent to the API. Content-type is
auto-detected, but can be overridden by passing this keyword argument. For options,
see :class:`~azure.ai.formrecognizer.FormContentType`.
:paramtype content_type: str or ~azure.ai.formrecognizer.FormContentType
:keyword int polling_interval: Waiting time between two polls for LRO operations
if no Retry-After header is present. Defaults to 5 seconds.
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:return: An instance of an LROPoller. Call `result()` on the poller
object to return a list[:class:`~azure.ai.formrecognizer.RecognizedForm`].
:rtype: ~azure.core.polling.LROPoller[list[~azure.ai.formrecognizer.RecognizedForm]
:raises ~azure.core.exceptions.HttpResponseError:
.. admonition:: Example:
.. literalinclude:: ../samples/sample_recognize_custom_forms.py
:start-after: [START recognize_custom_forms]
:end-before: [END recognize_custom_forms]
:language: python
:dedent: 8
:caption: Recognize fields and values from a custom form.
"""
if not model_id:
raise ValueError("model_id cannot be None or empty.")
cls = kwargs.pop("cls", None)
polling_interval = kwargs.pop("polling_interval", self._client._config.polling_interval)
continuation_token = kwargs.pop("continuation_token", None)
content_type = kwargs.pop("content_type", None)
if content_type == "application/json":
raise TypeError("Call begin_recognize_custom_forms_from_url() to analyze a document from a URL.")
include_field_elements = kwargs.pop("include_field_elements", False)
if content_type is None:
content_type = get_content_type(form)
def analyze_callback(raw_response, _, headers): # pylint: disable=unused-argument
analyze_result = self._client._deserialize(AnalyzeOperationResult, raw_response)
return prepare_form_result(analyze_result, model_id)
deserialization_callback = cls if cls else analyze_callback
return self._client.begin_analyze_with_custom_model(
file_stream=form,
model_id=model_id,
include_text_details=include_field_elements,
content_type=content_type,
cls=deserialization_callback,
polling=LROBasePolling(timeout=polling_interval, lro_algorithms=[AnalyzePolling()], **kwargs),
error_map=error_map,
continuation_token=continuation_token,
**kwargs
)
@distributed_trace
def begin_recognize_custom_forms_from_url(self, model_id, form_url, **kwargs):
# type: (str, str, Any) -> LROPoller[List[RecognizedForm]]
|
def close(self):
# type: () -> None
"""Close the :class:`~azure.ai.formrecognizer.FormRecognizerClient` session.
"""
return self._client.close()
def __enter__(self):
# type: () -> FormRecognizerClient
self._client.__enter__() # pylint:disable=no-member
return self
def __exit__(self, *args):
# type: (*Any) -> None
self._client.__exit__(*args) # pylint:disable=no-member
|
"""Analyze a custom form with a model trained with or without labels. The form
to analyze should be of the same type as the forms that were used to train the model.
The input document must be the location (URL) of the document to be analyzed.
:param str model_id: Custom model identifier.
:param str form_url: The URL of the form to analyze. The input must be a valid, encoded URL
of one of the supported formats: JPEG, PNG, PDF and TIFF.
:keyword bool include_field_elements:
Whether or not to include field elements such as lines and words in addition to form fields.
:keyword int polling_interval: Waiting time between two polls for LRO operations
if no Retry-After header is present. Defaults to 5 seconds.
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:return: An instance of an LROPoller. Call `result()` on the poller
object to return a list[:class:`~azure.ai.formrecognizer.RecognizedForm`].
:rtype: ~azure.core.polling.LROPoller[list[~azure.ai.formrecognizer.RecognizedForm]
:raises ~azure.core.exceptions.HttpResponseError:
"""
if not model_id:
raise ValueError("model_id cannot be None or empty.")
cls = kwargs.pop("cls", None)
polling_interval = kwargs.pop("polling_interval", self._client._config.polling_interval)
continuation_token = kwargs.pop("continuation_token", None)
include_field_elements = kwargs.pop("include_field_elements", False)
def analyze_callback(raw_response, _, headers): # pylint: disable=unused-argument
analyze_result = self._client._deserialize(AnalyzeOperationResult, raw_response)
return prepare_form_result(analyze_result, model_id)
deserialization_callback = cls if cls else analyze_callback
return self._client.begin_analyze_with_custom_model(
file_stream={"source": form_url},
model_id=model_id,
include_text_details=include_field_elements,
cls=deserialization_callback,
polling=LROBasePolling(timeout=polling_interval, lro_algorithms=[AnalyzePolling()], **kwargs),
error_map=error_map,
continuation_token=continuation_token,
**kwargs
)
|
goban.rs
|
//! Module with the goban and his implementations.
use std::fmt::Display;
use std::fmt::Error;
use std::fmt::Formatter;
use std::hash::{Hash, Hasher};
use arrayvec::ArrayVec;
use bitvec::{BitArr, bitarr};
use crate::pieces::chain::Chain;
use crate::pieces::Nat;
use crate::pieces::stones::*;
use crate::pieces::util::CircularRenIter;
use crate::pieces::util::coord::{
is_coord_valid, neighbor_points, one_to_2dim, Point, two_to_1dim,
};
use crate::pieces::zobrist::*;
pub type ChainIdx = usize;
pub type BoardIdx = usize;
macro_rules! iter_stones {
($goban: expr, $ren_idx: expr) => {
CircularRenIter::new($goban.chains[$ren_idx].origin, &$goban.next_stone)
};
}
/// Represents a Goban. the stones are stored in ROW MAJOR (row, column)
#[derive(Getters, Setters, CopyGetters, Debug, Clone)]
pub struct Goban {
#[get = "pub"]
pub(super) chains: Vec<Chain>,
board: Vec<Option<ChainIdx>>,
next_stone: Vec<usize>,
free_slots: Vec<usize>,
#[get_copy = "pub"]
size: (usize, usize),
#[get_copy = "pub"]
zobrist_hash: u64,
}
impl Goban {
/// Creates a Goban
/// # Arguments
///
/// * `(height, width)` a tuple with the height and the width of the desired goban.
pub fn new((height, width): (Nat, Nat)) -> Self {
Goban {
size: (height as usize, width as usize),
zobrist_hash: 0,
board: vec![None; height as usize * width as usize],
next_stone: vec![0; height as usize * width as usize],
chains: Vec::with_capacity(128),
free_slots: Vec::with_capacity(32),
}
}
/// Creates a Goban from an array of stones.
pub fn from_array(stones: &[Color]) -> Self {
let size = ((stones.len() as f32).sqrt()) as Nat;
let mut game = Goban::new((size, size));
stones
.iter()
.enumerate()
.map(|(index, color)| (one_to_2dim((size as usize, size as usize), index), color))
.filter(|s| *(*s).1 != Color::None)
.for_each(|coord_color| {
game.push(coord_color.0, *coord_color.1);
});
game
}
/// Returns the underlying goban in a vector with a RowMajor Policy, calculated on the fly.
pub fn vec(&self) -> Vec<Color> {
self.board
.iter()
.map(|point| point.map_or(Color::None, |go_str_ptr| self.chains[go_str_ptr].color))
.collect()
}
/// Like vec but in a matrix shape.
pub fn matrix(&self) -> Vec<Vec<Color>> {
let mut mat = vec![vec![]];
for line in self.board.chunks_exact(self.size.1) {
let v = line
.iter()
.map(|o| o.map_or(Color::None, |idx| self.chains[idx].color))
.collect();
mat.push(v);
}
mat
}
/// Get number of stones on the goban.
/// (number of black stones, number of white stones)
pub fn number_of_stones(&self) -> (u32, u32) {
self.get_stones()
.fold((0, 0), |(x1, x2), stone| match stone.color {
Color::Black => (x1 + 1, x2),
Color::White => (x1, x2 + 1),
_ => unreachable!("A stone cannot be empty"),
})
}
#[inline]
pub(crate) fn board(&self) -> &[Option<ChainIdx>] {
&self.board
}
/// pushes the stone
/// # Arguments
/// point: the point where the stone will be placed
/// color: the color of the stone must be != empty
/// # Returns
/// A tuple with (the ren without liberties, the ren where the point was added)
pub(crate) fn push_wth_feedback(
&mut self,
point: Point,
color: Color,
) -> (ArrayVec<usize, 4>, ChainIdx) {
let pushed_stone_idx = two_to_1dim(self.size, point);
let mut adjacent_same_color_str_set = ArrayVec::<_, 4>::new();
let mut adjacent_opposite_color_str_set = ArrayVec::<_, 4>::new();
let mut liberties = bitarr!(0;361);
for neighbor_idx in self.neighbor_points_indexes(pushed_stone_idx) {
match self.board[neighbor_idx] {
Some(adj_ren_index) => {
if self.chains[adj_ren_index].color == color {
if !adjacent_same_color_str_set.contains(&adj_ren_index) {
adjacent_same_color_str_set.push(adj_ren_index);
}
} else if !adjacent_opposite_color_str_set.contains(&adj_ren_index) {
adjacent_opposite_color_str_set.push(adj_ren_index);
}
}
Option::None => {
liberties.set(neighbor_idx, true);
}
}
}
let mut dead_ren = ArrayVec::<_, 4>::new();
// for every string of opposite color remove a liberty and update the string.
for ren_idx in adjacent_opposite_color_str_set {
let ren = &mut self.chains[ren_idx];
ren.remove_liberty(pushed_stone_idx);
if ren.is_dead() {
dead_ren.push(ren_idx);
}
}
let number_of_neighbors_strings = adjacent_same_color_str_set.len();
let updated_ren_index = match number_of_neighbors_strings {
0 => self.create_chain(pushed_stone_idx, color, liberties),
1 => {
let only_ren_idx = adjacent_same_color_str_set.into_iter().next().unwrap();
self.chains[only_ren_idx]
.remove_liberty(pushed_stone_idx)
.add_liberties_owned(liberties);
self.add_stone_to_chain(only_ren_idx, pushed_stone_idx);
self.board[pushed_stone_idx] = Some(only_ren_idx);
only_ren_idx
}
_ => {
let mut to_merge = self.create_chain(pushed_stone_idx, color, liberties);
for adj_ren in adjacent_same_color_str_set {
if self.chains[adj_ren].number_of_liberties()
< self.chains[to_merge].number_of_liberties()
{
self.merge_strings(to_merge, adj_ren);
} else {
self.merge_strings(adj_ren, to_merge);
to_merge = adj_ren;
}
}
self.chains[to_merge].remove_liberty(pushed_stone_idx);
to_merge
}
};
self.zobrist_hash ^= index_zobrist(pushed_stone_idx, color);
(dead_ren, updated_ren_index)
}
/// Put a stones in the goban.
/// default (line, column)
/// the (0,0) point is in the top left.
///
/// # Panics
/// if the point is out of bounds
pub fn push(&mut self, point: Point, color: Color) -> &mut Self {
assert_ne!(color, Color::None, "We can't push Empty stones");
assert!(
(point.0 as usize) < self.size.0,
"Coordinate point.0 {} out of bounds",
point.0
);
assert!(
(point.1 as usize) < self.size.1,
"Coordinate point.1 {} out of bounds",
point.1
);
self.push_wth_feedback(point, color);
self
}
/// Helper function to put a stone.
#[inline]
pub fn push_stone(&mut self, stone: Stone) -> &mut Goban {
self.push(stone.coordinates, stone.color)
}
/// Put many stones.
#[inline]
pub fn push_many(&mut self, points: &[Point], value: Color) {
points.iter().for_each(|&point| {
self.push(point, value);
})
}
/// Get the chain from their id
pub fn get_chain_from_id(&self, ren_idx: ChainIdx) -> &Chain {
&self.chains[ren_idx]
}
pub fn get_chain_by_board_idx(&self, board_idx: BoardIdx) -> Option<&Chain> {
self.board[board_idx].map(|chain| &self.chains[chain])
}
pub fn get_chain_by_point(&self, point: Point) -> Option<&Chain> {
self.get_chain_by_board_idx(two_to_1dim(self.size, point))
}
/// Get all the neighbors to the coordinate including empty intersections.
#[inline]
pub fn get_neighbors(&self, coord: Point) -> impl Iterator<Item=Stone> + '_ {
self.neighbor_points(coord).map(move |point| Stone {
coordinates: point,
color: self.get_stone(point),
})
}
/// Get all the stones that are neighbor to the coord except empty intersections.
#[inline]
pub fn get_neighbors_stones(&self, coord: Point) -> impl Iterator<Item=Stone> + '_
|
/// Get all the neighbors indexes to the point. Only return point with a color.
#[inline]
pub fn get_neighbors_chain_indexes(&self, coord: Point) -> impl Iterator<Item=ChainIdx> + '_ {
self.neighbor_points(coord)
.map(move |point| two_to_1dim(self.size, point))
.into_iter()
.filter_map(move |point| self.board[point])
}
/// Get all the chains adjacent to the point. The result iterator can contains duplicates.
#[inline]
pub fn get_neighbors_chains(&self, coord: Point) -> impl Iterator<Item=&Chain> + '_ {
self.get_neighbors_chain_indexes(coord)
.map(move |chain_idx| &self.chains[chain_idx])
}
#[inline]
pub fn get_neighbors_strings_indices_by_idx(
&self,
index: usize,
) -> impl Iterator<Item=ChainIdx> + '_ {
self.neighbor_points_indexes(index)
.filter_map(move |idx| self.board[idx])
}
/// Function for getting the stone in the goban.
#[inline(always)]
pub fn get_stone(&self, point: Point) -> Color {
self.board[two_to_1dim(self.size, point)]
.map_or(Color::None, |go_str_index| self.chains[go_str_index].color)
}
/// Get all the stones except "Empty stones"
#[inline]
pub fn get_stones(&self) -> impl Iterator<Item=Stone> + '_ {
self.board.iter().enumerate().filter_map(move |(index, o)| {
o.map(move |ren_index| Stone {
coordinates: one_to_2dim(self.size, index),
color: self.chains[ren_index].color,
})
})
}
/// Get stones by their color.
#[inline]
pub fn get_stones_by_color(&self, color: Color) -> impl Iterator<Item=Stone> + '_ {
self.get_points_by_color(color).map(move |c| Stone {
color,
coordinates: c,
})
}
/// Get points by their color.
#[inline]
pub fn get_points_by_color(&self, color: Color) -> impl Iterator<Item=Point> + '_ {
let size = self.size;
self.board
.iter()
.enumerate()
.filter(move |(_, option)| {
option.map(move |ren_idx| self.chains[ren_idx].color)
.unwrap_or(Color::None) == color
})
.map(move |(index, _)| one_to_2dim(size, index))
}
/// Returns the "empty" stones connected to the stone
#[inline]
pub fn get_liberties(&self, point: Point) -> impl Iterator<Item=Stone> + '_ {
self.get_neighbors(point).filter(|s| s.color == Color::None)
}
/// Returns true if the stone has liberties.
#[inline]
pub fn has_liberties(&self, point: Point) -> bool {
self.get_liberties(point).next().is_some()
}
/// Get a string for printing the goban in normal shape (0,0) left bottom
pub fn pretty_string(&self) -> String {
let mut buff = String::new();
for i in 0..self.size.0 as u8 {
for j in 0..self.size.1 as u8 {
buff.push(match self.get_stone((i, j)) {
Color::Black => '●',
Color::White => '○',
Color::None => {
match (
i == 0,
i == self.size.0 as u8 - 1,
j == 0,
j == self.size.1 as u8 - 1,
) {
(true, _, true, _) => '┏',
(true, _, _, true) => '┓',
(_, true, true, _) => '┗',
(_, true, _, true) => '┛',
(true, _, _, _) => '┯',
(_, true, _, _) => '┷',
(_, _, true, _) => '┠',
(_, _, _, true) => '┨',
_ => '┼',
}
}
});
}
buff.push('\n');
}
buff
}
/// Remove a string from the game, it add liberties to all
/// adjacent chains that aren't the same color.
pub fn remove_chain(&mut self, ren_to_remove_idx: ChainIdx) {
let color_of_the_string = self.chains[ren_to_remove_idx].color;
let mut neighbors = ArrayVec::<_, 4>::new();
for point_idx in iter_stones!(self, ren_to_remove_idx) {
for neighbor_str_idx in self
.get_neighbors_strings_indices_by_idx(point_idx) {
if ren_to_remove_idx != neighbor_str_idx {
#[cfg(debug_assertions)]
if !neighbors.contains(&neighbor_str_idx) {
neighbors.push(neighbor_str_idx)
}
#[cfg(not(debug_assertions))]
neighbors.push(neighbor_str_idx)
}
}
for &n in &neighbors {
self.chains[n].add_liberty(point_idx);
}
neighbors.clear();
self.zobrist_hash ^= index_zobrist(point_idx, color_of_the_string);
self.board[point_idx] = Option::None;
}
self.put_chain_in_bin(ren_to_remove_idx);
}
/// Updates the indexes to match actual goban. must use after we put a stone.
fn update_chain_indexes_in_board(&mut self, ren_idx: ChainIdx) {
debug_assert_eq!(
iter_stones!(self, ren_idx).last().unwrap(),
self.chains[ren_idx].last
);
for point in iter_stones!(self, ren_idx) {
unsafe {
*self.board.get_unchecked_mut(point) = Some(ren_idx);
}
}
}
/// Get the neighbors points filtered by limits of the board.
#[inline]
fn neighbor_points(&self, point: Point) -> impl Iterator<Item=Point> {
let size = self.size;
neighbor_points(point).into_iter().filter(move |&p| is_coord_valid(size, p))
}
#[inline]
fn neighbor_points_indexes(&self, board_idx: BoardIdx) -> impl Iterator<Item=usize> {
let size = self.size;
self.neighbor_points(one_to_2dim(self.size, board_idx))
.map(move |x| two_to_1dim(size, x))
}
pub fn get_chain_it(&self, chain_idx: ChainIdx) -> impl Iterator<Item=usize> + '_ {
CircularRenIter::new(self.chains[chain_idx].origin, &self.next_stone)
}
#[inline]
pub fn get_chain_it_by_board_idx(&self, board_idx: BoardIdx) -> impl Iterator<Item=usize> + '_ {
self.board[board_idx].map(|chain_idx| self.get_chain_it(chain_idx)).unwrap_or_else(|| panic!("The board index: {} was out of bounds", board_idx))
}
#[inline]
fn create_chain(&mut self, origin: usize, color: Color, liberties: BitArr!(for 361)) -> ChainIdx {
let chain_to_place = Chain::new_with_liberties(color, origin, liberties);
self.next_stone[origin] = origin;
let ren_index = if let Some(free_slot_idx) = self.free_slots.pop() {
self.chains[free_slot_idx] = chain_to_place;
free_slot_idx
} else {
self.chains.push(chain_to_place);
self.chains.len() - 1
};
self.update_chain_indexes_in_board(ren_index);
ren_index
}
fn add_stone_to_chain(&mut self, chain_idx: usize, stone: usize) {
let chain = &mut self.chains[chain_idx];
if stone < chain.origin {
// replace origin
self.next_stone[stone] = chain.origin;
self.next_stone[chain.last] = stone;
chain.origin = stone;
} else {
self.next_stone[chain.last] = stone;
self.next_stone[stone] = chain.origin;
chain.last = stone;
}
chain.num_stones += 1;
debug_assert_eq!(
iter_stones!(self, chain_idx).last().unwrap(),
self.chains[chain_idx].last
);
}
fn merge_strings(&mut self, chain1_idx: ChainIdx, chain2_idx: ChainIdx) {
debug_assert_eq!(
self.chains[chain1_idx].color, self.chains[chain2_idx].color,
"Cannot merge two strings of different color"
);
debug_assert_ne!(chain1_idx, chain2_idx, "merging the same string");
let (chain1, chain2) = if chain1_idx < chain2_idx {
let (s1, s2) = self.chains.split_at_mut(chain2_idx);
(&mut s1[chain1_idx], s2.first_mut().unwrap())
} else {
// ren2_idx > ren1_idx
let (contains_chain2, contains_ren1) = self.chains.split_at_mut(chain1_idx);
(
contains_ren1.first_mut().unwrap(),
&mut contains_chain2[chain2_idx],
)
};
chain1.liberties |= chain2.liberties;
let chain1_last = chain1.last;
let chain2_last = chain2.last;
let chain1_origin = chain1.origin;
let chain2_origin = chain2.origin;
if chain1_origin > chain2_origin {
chain1.origin = chain2_origin;
} else {
chain1.last = chain2_last;
}
self.next_stone.swap(chain1_last, chain2_last);
chain1.num_stones += chain2.num_stones;
self.update_chain_indexes_in_board(chain1_idx);
self.put_chain_in_bin(chain2_idx);
}
#[inline]
fn put_chain_in_bin(&mut self, ren_idx: ChainIdx) {
self.chains[ren_idx].used = false;
self.free_slots.push(ren_idx);
}
#[allow(dead_code)]
#[cfg(debug_assertions)]
fn check_integrity_ren(&self, ren_idx: ChainIdx) {
assert_eq!(
iter_stones!(self, ren_idx).next().unwrap(),
self.chains[ren_idx].origin,
"The origin doesn't match"
);
assert_eq!(
iter_stones!(self, ren_idx).last().unwrap(),
self.chains[ren_idx].last,
"The last doesn't match"
);
if iter_stones!(self, ren_idx).count() as u16 != self.chains[ren_idx].num_stones {
panic!("The number of stones don't match")
}
}
#[allow(dead_code)]
#[cfg(debug_assertions)]
fn check_integrity_all(&self) {
for ren_idx in (0..self.chains.len()).filter(|&ren_idx| self.chains[ren_idx].used) {
self.check_integrity_ren(ren_idx);
}
}
}
impl Display for Goban {
fn fmt(&self, f: &mut Formatter) -> Result<(), Error> {
write!(f, "{}", self.pretty_string())
}
}
impl PartialEq for Goban {
fn eq(&self, other: &Goban) -> bool {
other.zobrist_hash == self.zobrist_hash
}
}
impl Hash for Goban {
fn hash<H: Hasher>(&self, state: &mut H) {
self.zobrist_hash.hash(state)
}
}
impl Eq for Goban {}
impl Default for Goban {
fn default() -> Self {
Goban::new((19, 19))
}
}
|
{
self.get_neighbors(coord).filter(|s| s.color != Color::None)
}
|
base.py
|
# Copyright 2013 IBM Corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
|
# under the License.
import six
from tempest.common import image as common_image
from tempest.common.utils import data_utils
from tempest import config
from tempest.lib.common.utils import test_utils
import tempest.test
CONF = config.CONF
class BaseImageTest(tempest.test.BaseTestCase):
"""Base test class for Image API tests."""
credentials = ['primary']
@classmethod
def skip_checks(cls):
super(BaseImageTest, cls).skip_checks()
if not CONF.service_available.glance:
skip_msg = ("%s skipped as glance is not available" % cls.__name__)
raise cls.skipException(skip_msg)
@classmethod
def setup_credentials(cls):
cls.set_network_resources()
super(BaseImageTest, cls).setup_credentials()
@classmethod
def resource_setup(cls):
super(BaseImageTest, cls).resource_setup()
cls.created_images = []
@classmethod
def resource_cleanup(cls):
for image_id in cls.created_images:
test_utils.call_and_ignore_notfound_exc(
cls.client.delete_image, image_id)
for image_id in cls.created_images:
cls.client.wait_for_resource_deletion(image_id)
super(BaseImageTest, cls).resource_cleanup()
@classmethod
def create_image(cls, data=None, **kwargs):
"""Wrapper that returns a test image."""
if 'name' not in kwargs:
name = data_utils.rand_name(cls.__name__ + "-instance")
kwargs['name'] = name
params = cls._get_create_params(**kwargs)
if data:
# NOTE: On glance v1 API, the data should be passed on
# a header. Then here handles the data separately.
params['data'] = data
image = cls.client.create_image(**params)
# Image objects returned by the v1 client have the image
# data inside a dict that is keyed against 'image'.
if 'image' in image:
image = image['image']
cls.created_images.append(image['id'])
return image
@classmethod
def _get_create_params(cls, **kwargs):
return kwargs
class BaseV1ImageTest(BaseImageTest):
@classmethod
def skip_checks(cls):
super(BaseV1ImageTest, cls).skip_checks()
if not CONF.image_feature_enabled.api_v1:
msg = "Glance API v1 not supported"
raise cls.skipException(msg)
@classmethod
def setup_clients(cls):
super(BaseV1ImageTest, cls).setup_clients()
cls.client = cls.os.image_client
@classmethod
def _get_create_params(cls, **kwargs):
return {'headers': common_image.image_meta_to_headers(**kwargs)}
class BaseV1ImageMembersTest(BaseV1ImageTest):
credentials = ['primary', 'alt']
@classmethod
def setup_clients(cls):
super(BaseV1ImageMembersTest, cls).setup_clients()
cls.image_member_client = cls.os.image_member_client
cls.alt_image_member_client = cls.os_alt.image_member_client
cls.alt_img_cli = cls.os_alt.image_client
@classmethod
def resource_setup(cls):
super(BaseV1ImageMembersTest, cls).resource_setup()
cls.alt_tenant_id = cls.alt_image_member_client.tenant_id
def _create_image(self):
image_file = six.BytesIO(data_utils.random_bytes())
image = self.create_image(container_format='bare',
disk_format='raw',
is_public=False,
data=image_file)
image_id = image['id']
return image_id
class BaseV2ImageTest(BaseImageTest):
@classmethod
def skip_checks(cls):
super(BaseV2ImageTest, cls).skip_checks()
if not CONF.image_feature_enabled.api_v2:
msg = "Glance API v2 not supported"
raise cls.skipException(msg)
@classmethod
def setup_clients(cls):
super(BaseV2ImageTest, cls).setup_clients()
cls.client = cls.os.image_client_v2
cls.namespaces_client = cls.os.namespaces_client
cls.resource_types_client = cls.os.resource_types_client
cls.schemas_client = cls.os.schemas_client
def create_namespace(cls, namespace_name=None, visibility='public',
description='Tempest', protected=False,
**kwargs):
if not namespace_name:
namespace_name = data_utils.rand_name('test-ns')
kwargs.setdefault('display_name', namespace_name)
namespace = cls.namespaces_client.create_namespace(
namespace=namespace_name, visibility=visibility,
description=description, protected=protected, **kwargs)
cls.addCleanup(cls.namespaces_client.delete_namespace, namespace_name)
return namespace
class BaseV2MemberImageTest(BaseV2ImageTest):
credentials = ['primary', 'alt']
@classmethod
def setup_clients(cls):
super(BaseV2MemberImageTest, cls).setup_clients()
cls.image_member_client = cls.os.image_member_client_v2
cls.alt_image_member_client = cls.os_alt.image_member_client_v2
cls.alt_img_client = cls.os_alt.image_client_v2
@classmethod
def resource_setup(cls):
super(BaseV2MemberImageTest, cls).resource_setup()
cls.alt_tenant_id = cls.alt_image_member_client.tenant_id
def _list_image_ids_as_alt(self):
image_list = self.alt_img_client.list_images()['images']
image_ids = map(lambda x: x['id'], image_list)
return image_ids
def _create_image(self):
name = data_utils.rand_name(self.__class__.__name__ + '-image')
image = self.client.create_image(name=name,
container_format='bare',
disk_format='raw')
image_id = image['id']
self.addCleanup(self.client.delete_image, image_id)
return image_id
class BaseV1ImageAdminTest(BaseImageTest):
credentials = ['admin', 'primary']
@classmethod
def setup_clients(cls):
super(BaseV1ImageAdminTest, cls).setup_clients()
cls.client = cls.os.image_client
cls.admin_client = cls.os_adm.image_client
class BaseV2ImageAdminTest(BaseImageTest):
credentials = ['admin', 'primary']
@classmethod
def setup_clients(cls):
super(BaseV2ImageAdminTest, cls).setup_clients()
cls.client = cls.os.image_client_v2
cls.admin_client = cls.os_adm.image_client_v2
|
# License for the specific language governing permissions and limitations
|
mapping.rs
|
// Copyright 2015 The Gfx-rs Developers.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#![deny(missing_docs, missing_copy_implementations)]
//! Memory mapping
use std::error::Error as StdError;
use std::fmt;
use std::cell::UnsafeCell;
use std::ops::{Deref, DerefMut};
use std::sync::atomic::{self, AtomicBool};
use Resources;
use {memory, buffer, handle};
/// Unsafe, backend-provided operations for a buffer mapping
#[doc(hidden)]
pub trait Gate<R: Resources> {
/// Set the element at `index` to `val`. Not bounds-checked.
unsafe fn set<T>(&self, index: usize, val: T);
/// Returns a slice of the specified length.
unsafe fn slice<'a, 'b, T>(&'a self, len: usize) -> &'b [T];
/// Returns a mutable slice of the specified length.
unsafe fn mut_slice<'a, 'b, T>(&'a self, len: usize) -> &'b mut [T];
}
/// Error accessing a mapping.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Error {
/// The requested mapping access did not match the expected usage.
InvalidAccess(memory::Access, memory::Usage),
/// The requested mapping access overlaps with another.
AccessOverlap,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
use self::Error::*;
match *self {
InvalidAccess(ref access, ref usage) => {
write!(f, "{}: access = {:?}, usage = {:?}", self.description(), access, usage)
}
AccessOverlap => write!(f, "{}", self.description())
}
}
}
impl StdError for Error {
fn description(&self) -> &str {
use self::Error::*;
match *self {
InvalidAccess(..) => "The requested mapping access did not match the expected usage",
AccessOverlap => "The requested mapping access overlaps with another"
}
}
}
#[doc(hidden)]
#[derive(Debug)]
pub struct Raw<R: Resources> {
resource: UnsafeCell<R::Mapping>,
accessible: AtomicBool,
}
#[doc(hidden)]
impl<R: Resources> Raw<R> {
pub fn new(resource: R::Mapping) -> Self {
Raw {
resource: UnsafeCell::new(resource),
accessible: AtomicBool::new(true),
}
}
pub unsafe fn take_access(&self) -> bool {
self.accessible.swap(false, atomic::Ordering::Relaxed)
}
pub unsafe fn release_access(&self) {
if cfg!(debug) {
assert!(self.accessible.swap(true, atomic::Ordering::Relaxed) == false);
} else {
self.accessible.store(true, atomic::Ordering::Relaxed)
}
}
pub unsafe fn use_access(&self) -> &mut R::Mapping {
&mut *self.resource.get()
}
}
unsafe impl<R: Resources> Sync for Raw<R> {}
#[derive(Debug)]
struct Guard<'a, R: Resources> {
raw: &'a Raw<R>,
}
impl<'a, R: Resources> Guard<'a, R> {
fn new(raw: &'a Raw<R>) -> Result<Self, Error> {
unsafe {
if raw.take_access() {
Ok(Guard { raw: raw })
} else {
Err(Error::AccessOverlap)
}
}
}
}
impl<'a, R: Resources> Deref for Guard<'a, R> {
type Target = R::Mapping;
fn deref(&self) -> &R::Mapping {
unsafe { self.raw.use_access() }
}
}
impl<'a, R: Resources> DerefMut for Guard<'a, R> {
fn deref_mut(&mut self) -> &mut R::Mapping {
unsafe { self.raw.use_access() }
}
}
impl<'a, R: Resources> Drop for Guard<'a, R> {
fn drop(&mut self) {
unsafe { self.raw.release_access(); }
}
}
fn take_access_checked<R>(access: memory::Access, buffer: &buffer::Raw<R>)
-> Result<Guard<R>, Error>
where R: Resources
{
let usage = buffer.get_info().usage;
use memory::Usage::*;
match usage {
Upload if access == memory::WRITE => (),
Download if access == memory::READ => (),
_ => return Err(Error::InvalidAccess(access, usage)),
}
Guard::new(buffer.mapping().unwrap())
}
#[doc(hidden)]
pub unsafe fn read<R, T, S>(buffer: &buffer::Raw<R>, sync: S)
-> Result<Reader<R, T>, Error>
where R: Resources, T: Copy, S: FnOnce(&mut R::Mapping)
{
let mut mapping = try!(take_access_checked(memory::READ, buffer));
sync(&mut mapping);
Ok(Reader {
slice: mapping.slice(buffer.len::<T>()),
mapping: mapping,
})
}
#[doc(hidden)]
pub unsafe fn write<R, T, S>(buffer: &buffer::Raw<R>, sync: S)
-> Result<Writer<R, T>, Error>
where R: Resources, T: Copy, S: FnOnce(&mut R::Mapping)
{
let mut mapping = try!(take_access_checked(memory::WRITE, buffer));
sync(&mut mapping);
Ok(Writer {
slice: mapping.mut_slice(buffer.len::<T>()),
mapping: mapping,
})
}
/// Mapping reader
#[derive(Debug)]
pub struct Reader<'a, R: Resources, T: 'a + Copy> {
slice: &'a [T],
#[allow(dead_code)] mapping: Guard<'a, R>,
}
impl<'a, R: Resources, T: 'a + Copy> Deref for Reader<'a, R, T> {
type Target = [T];
fn deref(&self) -> &[T] { self.slice }
}
/// Mapping writer.
/// Currently is not possible to make write-only slice so while it is technically possible
/// to read from Writer, it will lead to an undefined behavior. Please do not read from it.
#[derive(Debug)]
pub struct Writer<'a, R: Resources, T: 'a + Copy> {
slice: &'a mut [T],
#[allow(dead_code)] mapping: Guard<'a, R>,
}
impl<'a, R: Resources, T: 'a + Copy> Deref for Writer<'a, R, T> {
type Target = [T];
fn deref(&self) -> &[T] { &*self.slice }
}
impl<'a, R: Resources, T: 'a + Copy> DerefMut for Writer<'a, R, T> {
fn deref_mut(&mut self) -> &mut [T] { self.slice }
}
/// A service struct that can be used by backends to track the mapping status
#[derive(Debug, Eq, Hash, PartialEq)]
#[doc(hidden)]
pub struct Status<R: Resources> {
cpu_wrote: bool,
gpu_access: Option<handle::Fence<R>>,
}
#[doc(hidden)]
impl<R: Resources> Status<R> {
pub fn clean() -> Self {
Status {
cpu_wrote: false,
gpu_access: None,
}
}
pub fn cpu_access<F>(&mut self, wait_fence: F)
where F: FnOnce(handle::Fence<R>)
{
self.gpu_access.take().map(wait_fence);
}
pub fn cpu_write_access<F>(&mut self, wait_fence: F)
where F: FnOnce(handle::Fence<R>)
{
self.cpu_access(wait_fence);
self.cpu_wrote = true;
}
pub fn gpu_access(&mut self, fence: handle::Fence<R>) {
self.gpu_access = Some(fence);
}
pub fn ensure_flushed<F>(&mut self, flush: F)
where F: FnOnce()
{
if self.cpu_wrote {
flush();
self.cpu_wrote = false;
}
}
}
| |
keys.go
|
// Copyright 2014 The Cockroach Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
// implied. See the License for the specific language governing
// permissions and limitations under the License.
//
// Author: Spencer Kimball ([email protected])
package gossip
import (
"regexp"
"strconv"
"strings"
"github.com/cockroachdb/cockroach/pkg/roachpb"
"github.com/pkg/errors"
)
// separator is used to separate the non-prefix components of a
// Gossip key, facilitating the automated generation of regular
// expressions for various prefixes.
// It must not be contained in any of the other keys defined here.
const separator = ":"
// Constants for gossip keys.
const (
// KeyClusterID is the unique UUID for this Cockroach cluster.
// The value is a string UUID for the cluster. The cluster ID is
// gossiped by all nodes that contain a replica of the first range,
// and it serves as a check for basic gossip connectivity. The
// Gossip.Connected channel is closed when we see this key.
KeyClusterID = "cluster-id"
// KeyStorePrefix is the key prefix for gossiping stores in the network.
// The suffix is a store ID and the value is roachpb.StoreDescriptor.
KeyStorePrefix = "store"
// KeyDeadReplicasPrefix is the key prefix for gossiping dead replicas in the
// network. The suffix is a store ID and the value is
// roachpb.StoreDeadReplicas.
KeyDeadReplicasPrefix = "replica-dead"
// KeyNodeIDPrefix is the key prefix for gossiping node id
// addresses. The actual key is suffixed with the decimal
// representation of the node id and the value is the host:port
// string address of the node. E.g. node:1 => 127.0.0.1:24001
KeyNodeIDPrefix = "node"
// KeyNodeLivenessPrefix is the key prefix for gossiping node liveness info.
KeyNodeLivenessPrefix = "liveness"
// KeySentinel is a key for gossip which must not expire or
// else the node considers itself partitioned and will retry with
// bootstrap hosts. The sentinel is gossiped by the node that holds
// the range lease for the first range.
KeySentinel = "sentinel"
// KeyFirstRangeDescriptor is the descriptor for the "first"
// range. The "first" range contains the meta1 key range, the first
// level of the bi-level key addressing scheme. The value is a slice
// of storage.Replica structs.
KeyFirstRangeDescriptor = "first-range"
// KeySystemConfig is the gossip key for the system DB span.
// The value if a config.SystemConfig which holds all key/value
// pairs in the system DB span.
KeySystemConfig = "system-db"
)
// MakeKey creates a canonical key under which to gossip a piece of
// information. The first argument will typically be one of the key constants
// defined in this package.
func MakeKey(components ...string) string {
return strings.Join(components, separator)
}
// MakePrefixPattern returns a regular expression pattern that
// matches precisely the Gossip keys created by invocations of
// MakeKey with multiple arguments for which the first argument
// is equal to the given prefix.
func
|
(prefix string) string {
return regexp.QuoteMeta(prefix+separator) + ".*"
}
// MakeNodeIDKey returns the gossip key for node ID info.
func MakeNodeIDKey(nodeID roachpb.NodeID) string {
return MakeKey(KeyNodeIDPrefix, nodeID.String())
}
// IsNodeIDKey returns true iff the provided key is a valid node ID key.
func IsNodeIDKey(key string) bool {
return strings.HasPrefix(key, KeyNodeIDPrefix+separator)
}
// NodeIDFromKey attempts to extract a NodeID from the provided key.
// The key should have been constructed by MakeNodeIDKey.
// Returns an error if the key is not of the correct type or is not parsable.
func NodeIDFromKey(key string) (roachpb.NodeID, error) {
trimmedKey := strings.TrimPrefix(key, KeyNodeIDPrefix+separator)
if trimmedKey == key {
return 0, errors.Errorf("%q is not a NodeID Key", key)
}
nodeID, err := strconv.ParseInt(trimmedKey, 10, 64)
if err != nil {
return 0, errors.Wrapf(err, "failed parsing NodeID from key %q", key)
}
return roachpb.NodeID(nodeID), nil
}
// MakeNodeLivenessKey returns the gossip key for node liveness info.
func MakeNodeLivenessKey(nodeID roachpb.NodeID) string {
return MakeKey(KeyNodeLivenessPrefix, nodeID.String())
}
// MakeStoreKey returns the gossip key for the given store.
func MakeStoreKey(storeID roachpb.StoreID) string {
return MakeKey(KeyStorePrefix, storeID.String())
}
// MakeDeadReplicasKey returns the dead replicas gossip key for the given store.
func MakeDeadReplicasKey(storeID roachpb.StoreID) string {
return MakeKey(KeyDeadReplicasPrefix, storeID.String())
}
|
MakePrefixPattern
|
dna9.py
|
#!/usr/bin/env python3
"""Tetra-nucleotide counter"""
import sys
import os
from collections import defaultdict
args = sys.argv[1:]
if len(args) != 1:
|
arg = args[0]
dna = ''
if os.path.isfile(arg):
dna = ''.join(open(arg).read().splitlines())
else:
dna = arg
count = defaultdict(int)
for base in dna.lower():
count[base] += 1
print(' '.join(map(lambda b: str(count[b]), "acgt")))
|
print('Usage: {} DNA'.format(os.path.basename(sys.argv[0])))
sys.exit(1)
|
__init__.py
|
# Copyright (c) 2016 ARM Limited
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality of the software
# licensed hereunder. You may use the software subject to the license
# terms below provided that you ensure that this notice is replicated
# unmodified and in its entirety in all distributions of the software,
# modified or unmodified, in source code or in binary form.
#
# Copyright (c) 2008-2009 The Hewlett-Packard Development Company
# Copyright (c) 2004-2006 The Regents of The University of Michigan
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met: redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer;
# redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution;
# neither the name of the copyright holders nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# Authors: Nathan Binkert
from __future__ import print_function
import os
import re
import sys
from . import convert
from . import jobfile
from .attrdict import attrdict, multiattrdict, optiondict
from .code_formatter import code_formatter
from .multidict import multidict
from .smartdict import SmartDict
from .sorteddict import SortedDict
# panic() should be called when something happens that should never
# ever happen regardless of what the user does (i.e., an acutal m5
# bug).
def panic(fmt, *args):
print('panic:', fmt % args, file=sys.stderr)
sys.exit(1)
# fatal() should be called when the simulation cannot continue due to
# some condition that is the user's fault (bad configuration, invalid
# arguments, etc.) and not a simulator bug.
def fatal(fmt, *args):
print('fatal:', fmt % args, file=sys.stderr)
sys.exit(1)
# warn() should be called when the user should be warned about some condition
# that may or may not be the user's fault, but that they should be made aware
# of as it may affect the simulation or results.
def warn(fmt, *args):
print('warn:', fmt % args, file=sys.stderr)
# inform() should be called when the user should be informed about some
# condition that they may be interested in.
def inform(fmt, *args):
print('info:', fmt % args, file=sys.stdout)
class Singleton(type):
def __call__(cls, *args, **kwargs):
if hasattr(cls, '_instance'):
return cls._instance
cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
return cls._instance
def addToPath(path):
"""Prepend given directory to system module search path. We may not
need this anymore if we can structure our config library more like a
Python package."""
# if it's a relative path and we know what directory the current
# python script is in, make the path relative to that directory.
if not os.path.isabs(path) and sys.path[0]:
path = os.path.join(sys.path[0], path)
path = os.path.realpath(path)
# sys.path[0] should always refer to the current script's directory,
# so place the new dir right after that.
sys.path.insert(1, path)
# Apply method to object.
# applyMethod(obj, 'meth', <args>) is equivalent to obj.meth(<args>)
def applyMethod(obj, meth, *args, **kwargs):
return getattr(obj, meth)(*args, **kwargs)
# If the first argument is an (non-sequence) object, apply the named
# method with the given arguments. If the first argument is a
# sequence, apply the method to each element of the sequence (a la
# 'map').
def applyOrMap(objOrSeq, meth, *args, **kwargs):
if not isinstance(objOrSeq, (list, tuple)):
return applyMethod(objOrSeq, meth, *args, **kwargs)
else:
return [applyMethod(o, meth, *args, **kwargs) for o in objOrSeq]
def compareVersions(v1, v2):
"""helper function: compare arrays or strings of version numbers.
E.g., compare_version((1,3,25), (1,4,1)')
returns -1, 0, 1 if v1 is <, ==, > v2
"""
def make_version_list(v):
if isinstance(v, (list,tuple)):
return v
elif isinstance(v, str):
return map(lambda x: int(re.match('\d+', x).group()), v.split('.'))
else:
raise TypeError()
v1 = make_version_list(v1)
v2 = make_version_list(v2)
# Compare corresponding elements of lists
for n1,n2 in zip(v1, v2):
if n1 < n2: return -1
if n1 > n2: return 1
# all corresponding values are equal... see if one has extra values
if len(v1) < len(v2): return -1
if len(v1) > len(v2): return 1
return 0
def crossproduct(items):
if len(items) == 1:
for i in items[0]:
yield (i,)
else:
for i in items[0]:
for j in crossproduct(items[1:]):
yield (i,) + j
def flatten(items):
while items:
item = items.pop(0)
if isinstance(item, (list, tuple)):
items[0:0] = item
else:
yield item
# force scalars to one-element lists for uniformity
def makeList(objOrList):
if isinstance(objOrList, list):
return objOrList
return [objOrList]
def printList(items, indent=4):
line = ' ' * indent
for i,item in enumerate(items):
if len(line) + len(item) > 76:
print(line)
line = ' ' * indent
if i < len(items) - 1:
line += '%s, ' % item
else:
line += item
print(line)
def readCommand(cmd, **kwargs):
"""run the command cmd, read the results and return them
this is sorta like `cmd` in shell"""
from subprocess import Popen, PIPE, STDOUT
if isinstance(cmd, str):
cmd = cmd.split()
no_exception = 'exception' in kwargs
exception = kwargs.pop('exception', None)
kwargs.setdefault('shell', False)
kwargs.setdefault('stdout', PIPE)
kwargs.setdefault('stderr', STDOUT)
kwargs.setdefault('close_fds', True)
try:
subp = Popen(cmd, **kwargs)
except Exception as e:
if no_exception:
return exception
raise
return subp.communicate()[0]
def makeDir(path):
"""Make a directory if it doesn't exist. If the path does exist,
ensure that it is a directory"""
if os.path.exists(path):
if not os.path.isdir(path):
raise AttributeError("%s exists but is not directory" % path)
else:
os.mkdir(path)
def isInteractive():
"""Check if the simulator is run interactively or in a batch environment"""
return sys.__stdin__.isatty()
|
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
fax_summary.go
|
package fax_summary
import (
"fmt"
"github.com/mypurecloud/platform-client-sdk-cli/build/gc/logger"
"github.com/mypurecloud/platform-client-sdk-cli/build/gc/retry"
"github.com/mypurecloud/platform-client-sdk-cli/build/gc/services"
"github.com/mypurecloud/platform-client-sdk-cli/build/gc/utils"
"github.com/mypurecloud/platform-client-sdk-cli/build/gc/models"
"github.com/spf13/cobra"
"net/url"
"strings"
"time"
)
var (
Description = utils.FormatUsageDescription("fax_summary", "SWAGGER_OVERRIDE_/api/v2/fax/summary", )
fax_summaryCmd = &cobra.Command{
Use: utils.FormatUsageDescription("fax_summary"),
Short: Description,
Long: Description,
}
CommandService services.CommandService
)
func init() {
CommandService = services.NewCommandService(fax_summaryCmd)
}
func Cmdfax_summary() *cobra.Command {
getCmd.SetUsageTemplate(fmt.Sprintf("%s\nOperation:\n %s %s\n%s\n%s", getCmd.UsageTemplate(), "GET", "/api/v2/fax/summary", utils.FormatPermissions([]string{ }), utils.GenerateDevCentreLink("GET", "Fax", "/api/v2/fax/summary")))
utils.AddFileFlagIfUpsert(getCmd.Flags(), "GET", ``)
utils.AddPaginateFlagsIfListingResponse(getCmd.Flags(), "GET", `{
"description" : "successful operation",
"schema" : {
"$ref" : "#/definitions/FaxSummary"
}
}`)
fax_summaryCmd.AddCommand(getCmd)
return fax_summaryCmd
}
var getCmd = &cobra.Command{
Use: "get",
|
Run: func(cmd *cobra.Command, args []string) {
_ = models.Entities{}
printReqBody, _ := cmd.Flags().GetBool("printrequestbody")
if printReqBody {
return
}
queryParams := make(map[string]string)
path := "/api/v2/fax/summary"
urlString := path
if len(queryParams) > 0 {
urlString = fmt.Sprintf("%v?", path)
for k, v := range queryParams {
urlString += fmt.Sprintf("%v=%v&", url.QueryEscape(strings.TrimSpace(k)), url.QueryEscape(strings.TrimSpace(v)))
}
urlString = strings.TrimSuffix(urlString, "&")
}
const opId = "get"
const httpMethod = "GET"
retryFunc := CommandService.DetermineAction(httpMethod, urlString, cmd, opId)
// TODO read from config file
retryConfig := &retry.RetryConfiguration{
RetryWaitMin: 5 * time.Second,
RetryWaitMax: 60 * time.Second,
RetryMax: 20,
}
results, err := retryFunc(retryConfig)
if err != nil {
logger.Fatal(err)
}
utils.Render(results)
},
}
|
Short: "Get fax summary",
Long: "Get fax summary",
Args: utils.DetermineArgs([]string{ }),
|
us_linmr.rs
|
#[doc = "Register `US_LINMR` reader"]
pub struct R(crate::R<US_LINMR_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<US_LINMR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<crate::R<US_LINMR_SPEC>> for R {
#[inline(always)]
fn from(reader: crate::R<US_LINMR_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `US_LINMR` writer"]
pub struct W(crate::W<US_LINMR_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<US_LINMR_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<crate::W<US_LINMR_SPEC>> for W {
#[inline(always)]
fn from(writer: crate::W<US_LINMR_SPEC>) -> Self {
W(writer)
}
}
#[doc = "LIN Node Action\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum NACT_A {
#[doc = "0: The USART transmits the response."]
PUBLISH = 0,
#[doc = "1: The USART receives the response."]
SUBSCRIBE = 1,
#[doc = "2: The USART does not transmit and does not receive the response."]
IGNORE = 2,
}
impl From<NACT_A> for u8 {
#[inline(always)]
fn from(variant: NACT_A) -> Self {
variant as _
}
}
#[doc = "Field `NACT` reader - LIN Node Action"]
pub struct NACT_R(crate::FieldReader<u8, NACT_A>);
impl NACT_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
NACT_R(crate::FieldReader::new(bits))
}
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> Option<NACT_A> {
match self.bits {
0 => Some(NACT_A::PUBLISH),
1 => Some(NACT_A::SUBSCRIBE),
2 => Some(NACT_A::IGNORE),
_ => None,
}
}
#[doc = "Checks if the value of the field is `PUBLISH`"]
#[inline(always)]
pub fn is_publish(&self) -> bool {
**self == NACT_A::PUBLISH
}
#[doc = "Checks if the value of the field is `SUBSCRIBE`"]
#[inline(always)]
pub fn is_subscribe(&self) -> bool {
**self == NACT_A::SUBSCRIBE
}
#[doc = "Checks if the value of the field is `IGNORE`"]
#[inline(always)]
pub fn is_ignore(&self) -> bool {
**self == NACT_A::IGNORE
}
}
impl core::ops::Deref for NACT_R {
type Target = crate::FieldReader<u8, NACT_A>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `NACT` writer - LIN Node Action"]
pub struct NACT_W<'a> {
w: &'a mut W,
}
impl<'a> NACT_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: NACT_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "The USART transmits the response."]
#[inline(always)]
pub fn publish(self) -> &'a mut W {
self.variant(NACT_A::PUBLISH)
}
#[doc = "The USART receives the response."]
#[inline(always)]
pub fn subscribe(self) -> &'a mut W {
self.variant(NACT_A::SUBSCRIBE)
}
#[doc = "The USART does not transmit and does not receive the response."]
#[inline(always)]
pub fn ignore(self) -> &'a mut W {
self.variant(NACT_A::IGNORE)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x03) | (value as u32 & 0x03);
self.w
}
}
#[doc = "Field `PARDIS` reader - Parity Disable"]
pub struct PARDIS_R(crate::FieldReader<bool, bool>);
impl PARDIS_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
PARDIS_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for PARDIS_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `PARDIS` writer - Parity Disable"]
pub struct PARDIS_W<'a> {
w: &'a mut W,
}
impl<'a> PARDIS_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | ((value as u32 & 0x01) << 2);
self.w
}
}
#[doc = "Field `CHKDIS` reader - Checksum Disable"]
pub struct CHKDIS_R(crate::FieldReader<bool, bool>);
impl CHKDIS_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
CHKDIS_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CHKDIS_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `CHKDIS` writer - Checksum Disable"]
pub struct CHKDIS_W<'a> {
w: &'a mut W,
}
impl<'a> CHKDIS_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | ((value as u32 & 0x01) << 3);
self.w
}
}
#[doc = "Field `CHKTYP` reader - Checksum Type"]
pub struct CHKTYP_R(crate::FieldReader<bool, bool>);
impl CHKTYP_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
CHKTYP_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for CHKTYP_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `CHKTYP` writer - Checksum Type"]
pub struct CHKTYP_W<'a> {
w: &'a mut W,
}
impl<'a> CHKTYP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | ((value as u32 & 0x01) << 4);
self.w
}
}
#[doc = "Field `DLM` reader - Data Length Mode"]
pub struct DLM_R(crate::FieldReader<bool, bool>);
impl DLM_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
DLM_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for DLM_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `DLM` writer - Data Length Mode"]
pub struct DLM_W<'a> {
w: &'a mut W,
}
impl<'a> DLM_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | ((value as u32 & 0x01) << 5);
self.w
}
}
#[doc = "Field `FSDIS` reader - Frame Slot Mode Disable"]
pub struct FSDIS_R(crate::FieldReader<bool, bool>);
impl FSDIS_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
FSDIS_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for FSDIS_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `FSDIS` writer - Frame Slot Mode Disable"]
pub struct FSDIS_W<'a> {
w: &'a mut W,
}
impl<'a> FSDIS_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | ((value as u32 & 0x01) << 6);
self.w
}
}
#[doc = "Field `WKUPTYP` reader - Wakeup Signal Type"]
pub struct WKUPTYP_R(crate::FieldReader<bool, bool>);
impl WKUPTYP_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
WKUPTYP_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for WKUPTYP_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `WKUPTYP` writer - Wakeup Signal Type"]
pub struct WKUPTYP_W<'a> {
w: &'a mut W,
}
impl<'a> WKUPTYP_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | ((value as u32 & 0x01) << 7);
self.w
}
}
#[doc = "Field `DLC` reader - Data Length Control"]
pub struct DLC_R(crate::FieldReader<u8, u8>);
impl DLC_R {
#[inline(always)]
pub(crate) fn new(bits: u8) -> Self {
DLC_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for DLC_R {
type Target = crate::FieldReader<u8, u8>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `DLC` writer - Data Length Control"]
pub struct DLC_W<'a> {
w: &'a mut W,
}
impl<'a> DLC_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0xff << 8)) | ((value as u32 & 0xff) << 8);
self.w
}
}
#[doc = "Field `PDCM` reader - DMAC Mode"]
pub struct PDCM_R(crate::FieldReader<bool, bool>);
impl PDCM_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
PDCM_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for PDCM_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `PDCM` writer - DMAC Mode"]
pub struct PDCM_W<'a> {
w: &'a mut W,
}
impl<'a> PDCM_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | ((value as u32 & 0x01) << 16);
self.w
}
}
#[doc = "Field `SYNCDIS` reader - Synchronization Disable"]
pub struct SYNCDIS_R(crate::FieldReader<bool, bool>);
impl SYNCDIS_R {
#[inline(always)]
pub(crate) fn new(bits: bool) -> Self {
SYNCDIS_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for SYNCDIS_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `SYNCDIS` writer - Synchronization Disable"]
pub struct SYNCDIS_W<'a> {
w: &'a mut W,
}
impl<'a> SYNCDIS_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | ((value as u32 & 0x01) << 17);
self.w
}
}
impl R {
#[doc = "Bits 0:1 - LIN Node Action"]
#[inline(always)]
pub fn nact(&self) -> NACT_R {
NACT_R::new((self.bits & 0x03) as u8)
}
#[doc = "Bit 2 - Parity Disable"]
#[inline(always)]
pub fn pardis(&self) -> PARDIS_R {
PARDIS_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Checksum Disable"]
#[inline(always)]
pub fn chkdis(&self) -> CHKDIS_R {
CHKDIS_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Checksum Type"]
#[inline(always)]
pub fn chktyp(&self) -> CHKTYP_R {
CHKTYP_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - Data Length Mode"]
#[inline(always)]
pub fn dlm(&self) -> DLM_R {
DLM_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - Frame Slot Mode Disable"]
#[inline(always)]
pub fn fsdis(&self) -> FSDIS_R {
FSDIS_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - Wakeup Signal Type"]
#[inline(always)]
pub fn wkuptyp(&self) -> WKUPTYP_R {
WKUPTYP_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bits 8:15 - Data Length Control"]
#[inline(always)]
pub fn
|
(&self) -> DLC_R {
DLC_R::new(((self.bits >> 8) & 0xff) as u8)
}
#[doc = "Bit 16 - DMAC Mode"]
#[inline(always)]
pub fn pdcm(&self) -> PDCM_R {
PDCM_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - Synchronization Disable"]
#[inline(always)]
pub fn syncdis(&self) -> SYNCDIS_R {
SYNCDIS_R::new(((self.bits >> 17) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:1 - LIN Node Action"]
#[inline(always)]
pub fn nact(&mut self) -> NACT_W {
NACT_W { w: self }
}
#[doc = "Bit 2 - Parity Disable"]
#[inline(always)]
pub fn pardis(&mut self) -> PARDIS_W {
PARDIS_W { w: self }
}
#[doc = "Bit 3 - Checksum Disable"]
#[inline(always)]
pub fn chkdis(&mut self) -> CHKDIS_W {
CHKDIS_W { w: self }
}
#[doc = "Bit 4 - Checksum Type"]
#[inline(always)]
pub fn chktyp(&mut self) -> CHKTYP_W {
CHKTYP_W { w: self }
}
#[doc = "Bit 5 - Data Length Mode"]
#[inline(always)]
pub fn dlm(&mut self) -> DLM_W {
DLM_W { w: self }
}
#[doc = "Bit 6 - Frame Slot Mode Disable"]
#[inline(always)]
pub fn fsdis(&mut self) -> FSDIS_W {
FSDIS_W { w: self }
}
#[doc = "Bit 7 - Wakeup Signal Type"]
#[inline(always)]
pub fn wkuptyp(&mut self) -> WKUPTYP_W {
WKUPTYP_W { w: self }
}
#[doc = "Bits 8:15 - Data Length Control"]
#[inline(always)]
pub fn dlc(&mut self) -> DLC_W {
DLC_W { w: self }
}
#[doc = "Bit 16 - DMAC Mode"]
#[inline(always)]
pub fn pdcm(&mut self) -> PDCM_W {
PDCM_W { w: self }
}
#[doc = "Bit 17 - Synchronization Disable"]
#[inline(always)]
pub fn syncdis(&mut self) -> SYNCDIS_W {
SYNCDIS_W { w: self }
}
#[doc = "Writes raw bits to the register."]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "LIN Mode Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [us_linmr](index.html) module"]
pub struct US_LINMR_SPEC;
impl crate::RegisterSpec for US_LINMR_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [us_linmr::R](R) reader structure"]
impl crate::Readable for US_LINMR_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [us_linmr::W](W) writer structure"]
impl crate::Writable for US_LINMR_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets US_LINMR to value 0"]
impl crate::Resettable for US_LINMR_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
|
dlc
|
factors.py
|
#!/usr/bin/python3
#
# factors.py - Find the factors of a positive integer
#
# By Jim McClanahah, W4JBM (Dec 2020)
|
# Find the factors of a provided positive integer.
#
# The function is a modification of one originally
# provided by Harshit Agrawal to the geeksforgeeks.org
# website.
#
# It seems like things stop working at around 18 digits
import sys
import math
# The following function creates and return a list of all
# prime factors of a given number n
#
# It uses three steps to find o find all prime factors:
#
# 1. While n is divisible by 2, add two to the list and
# divide n by 2.
# 2. After step 1, n must be odd. Now start a loop from
# i = 3 to square root of n. While i divides n, add
# i to the list and divide n by i, increment i by 2
# and continue.
# 3. If n is a prime number and is greater than 2, then
# n will not become 1 by above two steps. So add n
# to the list if it is greater than 2.
def primeFactors(n):
lst=[]
# Find the number of two's that divide n
while n % 2 == 0:
lst.append(2)
n = n / 2
# n must be odd at this point so a skip of 2
# (i.e., i = i + 2) can be used
for i in range(3,int(math.sqrt(n))+1,2):
# while i divides n , add i to list and
# divide n
while n % i== 0:
lst.append(i)
n = n / i
# Check if n is a prime number greater than 2
if n > 2:
lst.append(int(n))
# And return the list of factors
return lst
# Check for command line argument and print an intro if
# none was provided...
if len(sys.argv) != 2:
print('Find the factors for a given positive integer.')
print('USAGE: factor.py integer')
sys.exit(1)
# Make sure the argument is a positive integer...
if sys.argv[1].isdigit():
n = int(sys.argv[1])
# If not, print a warning...
else:
print('Argument must be a positive integer.')
sys.exit(1)
if n > 10**16:
print('Argument cannot be more than 15 digits.')
sys.exit(1)
lst = primeFactors(n)
# Here's where all the work happens... :-)
print('Factors of ' + str(n) + ': ' + ', '.join(map(str,lst)))
|
#
|
attributes_dead_code.rs
|
// 11.1 dead_code
// This signature allow attribute to all module (#!):
// `#![allow(dead_code)]`
// The compiler provides a dead_code lint that
// will warn about unused functions. An attribute
// can be used to disable the lint.
fn used_function() {}
// `#[allow(dead_code)]` is an attribute that disables the `dead_code` lint
#[allow(dead_code)]
fn
|
() {}
#[allow(dead_code)]
fn noisy_unused_function() {}
// FIXME ^ Add an attribute to suppress the warning
pub fn main() {
used_function();
}
|
unused_function
|
blob_storage.rs
|
use api::{ErrorCode, IndyHandle, CommandHandle};
use commands::{Command, CommandExecutor};
use commands::blob_storage::BlobStorageCommand;
use errors::prelude::*;
use utils::ctypes;
use libc::c_char;
#[no_mangle]
pub extern fn indy_open_blob_storage_reader(command_handle: CommandHandle,
type_: *const c_char,
config_json: *const c_char,
cb: Option<extern fn(command_handle_: CommandHandle,
err: ErrorCode,
handle: IndyHandle)>) -> ErrorCode {
trace!("indy_open_blob_storage_reader: >>> type_: {:?}, config_json: {:?}", type_, config_json);
check_useful_c_str!(type_, ErrorCode::CommonInvalidParam2);
check_useful_c_str!(config_json, ErrorCode::CommonInvalidParam3);
check_useful_c_callback!(cb, ErrorCode::CommonInvalidParam4);
trace!("indy_open_blob_storage_reader: entities >>> type_: {:?}, config_json: {:?}", type_, config_json);
let result = CommandExecutor::instance()
.send(Command::BlobStorage(BlobStorageCommand::OpenReader(
type_,
config_json,
Box::new(move |result| {
let (err, handle) = prepare_result_1!(result, 0);
trace!("indy_open_blob_storage_reader: handle: {:?}", handle);
cb(command_handle, err, handle)
}),
)));
let res = prepare_result!(result);
trace!("indy_open_blob_storage_reader: <<< res: {:?}", res);
res
}
#[no_mangle]
pub extern fn indy_open_blob_storage_writer(command_handle: CommandHandle,
type_: *const c_char,
config_json: *const c_char,
cb: Option<extern fn(command_handle_: CommandHandle,
err: ErrorCode,
handle: IndyHandle)>) -> ErrorCode
|
{
trace!("indy_open_blob_storage_writer: >>> type_: {:?}, config_json: {:?}", type_, config_json);
check_useful_c_str!(type_, ErrorCode::CommonInvalidParam2);
check_useful_c_str!(config_json, ErrorCode::CommonInvalidParam3);
check_useful_c_callback!(cb, ErrorCode::CommonInvalidParam4);
trace!("indy_open_blob_storage_writer: entities >>> type_: {:?}, config_json: {:?}", type_, config_json);
let result = CommandExecutor::instance()
.send(Command::BlobStorage(BlobStorageCommand::OpenWriter(
type_,
config_json,
Box::new(move |result| {
let (err, handle) = prepare_result_1!(result, 0);
trace!("indy_open_blob_storage_writer: handle: {:?}", handle);
cb(command_handle, err, handle)
}),
)));
let res = prepare_result!(result);
trace!("indy_open_blob_storage_writer: <<< res: {:?}", res);
res
}
|
|
errors_test.go
|
// Copyright 2019 Anapaya Systems
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package serrors_test
import (
"fmt"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/xerrors"
"github.com/scionproto/scion/go/lib/serrors"
)
type testErrType struct {
msg string
}
func (e *testErrType) Error() string {
return e.msg
}
type testToTempErr struct {
msg string
timeout bool
temporary bool
cause error
}
func (e *testToTempErr) Error() string {
return e.msg
}
func (e *testToTempErr) Timeout() bool {
return e.timeout
}
func (e *testToTempErr) Temporary() bool {
return e.temporary
}
func (e *testToTempErr) Unwrap() error {
return e.cause
}
func TestIsTimeout(t *testing.T) {
err := serrors.New("no timeout")
assert.False(t, serrors.IsTimeout(err))
wrappedErr := serrors.WrapStr("timeout",
&testToTempErr{msg: "to", timeout: true})
assert.True(t, serrors.IsTimeout(wrappedErr))
noTimeoutWrappingTimeout := serrors.WrapStr("notimeout", &testToTempErr{
msg: "non timeout wraps timeout",
timeout: false,
cause: &testToTempErr{msg: "timeout", timeout: true},
})
assert.False(t, serrors.IsTimeout(noTimeoutWrappingTimeout))
}
func TestIsTemporary(t *testing.T) {
err := serrors.New("not temp")
assert.False(t, serrors.IsTemporary(err))
wrappedErr := serrors.WrapStr("temp",
&testToTempErr{msg: "to", temporary: true})
assert.True(t, serrors.IsTemporary(wrappedErr))
noTempWrappingTemp := serrors.WrapStr("notemp", &testToTempErr{
msg: "non temp wraps temp",
temporary: false,
cause: &testToTempErr{msg: "temp", temporary: true},
})
assert.False(t, serrors.IsTemporary(noTempWrappingTemp))
}
func TestWithCtx(t *testing.T) {
t.Run("Is", func(t *testing.T) {
err := serrors.New("simple err")
errWithCtx := serrors.WithCtx(err, "someCtx", "someValue")
assert.True(t, xerrors.Is(errWithCtx, err))
assert.True(t, xerrors.Is(errWithCtx, errWithCtx))
})
t.Run("As", func(t *testing.T) {
err := &testErrType{msg: "test err"}
errWithCtx := serrors.WithCtx(err, "someCtx", "someVal")
var errAs *testErrType
require.True(t, xerrors.As(errWithCtx, &errAs))
assert.Equal(t, err, errAs)
})
t.Run("Fmt", func(t *testing.T) {
err := serrors.New("simple err")
errWithCtx := serrors.WithCtx(err, "someCtx", "someValue")
expectedMsg := `simple err someCtx="someValue"`
assert.Equal(t, expectedMsg, errWithCtx.Error())
})
}
func TestWrap(t *testing.T) {
t.Run("Is", func(t *testing.T) {
err := serrors.New("simple err")
msg := serrors.New("msg err")
wrappedErr := serrors.Wrap(msg, err, "someCtx", "someValue")
assert.True(t, xerrors.Is(wrappedErr, err))
assert.True(t, xerrors.Is(wrappedErr, msg))
assert.True(t, xerrors.Is(wrappedErr, wrappedErr))
})
t.Run("As", func(t *testing.T) {
err := &testErrType{msg: "test err"}
msg := serrors.New("msg err")
wrappedErr := serrors.Wrap(msg, err, "someCtx", "someValue")
var errAs *testErrType
require.True(t, xerrors.As(wrappedErr, &errAs))
assert.Equal(t, err, errAs)
})
t.Run("Fmt", func(t *testing.T) {
err := serrors.New("level0\nlevel0.1")
cause := serrors.New("level1\nlevel1.1")
wrappedErr := serrors.Wrap(err, cause, "k0", "v0", "k1", 1)
expedtedMsg := strings.Join([]string{
"level0",
` > level0.1 k0="v0" k1="1"`,
" level1",
" > level1.1",
}, "\n")
assert.Equal(t, expedtedMsg, wrappedErr.Error())
})
}
func TestWrapStr(t *testing.T) {
t.Run("Is", func(t *testing.T) {
err := serrors.New("simple err")
msg := "msg"
wrappedErr := serrors.WrapStr(msg, err, "someCtx", "someValue")
assert.True(t, xerrors.Is(wrappedErr, err))
assert.True(t, xerrors.Is(wrappedErr, wrappedErr))
})
t.Run("As", func(t *testing.T) {
err := &testErrType{msg: "test err"}
msg := "msg"
wrappedErr := serrors.WrapStr(msg, err, "someCtx", "someValue")
var errAs *testErrType
require.True(t, xerrors.As(wrappedErr, &errAs))
assert.Equal(t, err, errAs)
})
t.Run("Fmt", func(t *testing.T) {
msg := "level0\nlevel0.1"
cause := serrors.New("level1\nlevel1.1")
wrappedErr := serrors.WrapStr(msg, cause, "k0", "v0", "k1", 1)
expedtedMsg := strings.Join([]string{
"level0",
` > level0.1 k0="v0" k1="1"`,
" level1",
" > level1.1",
}, "\n")
assert.Equal(t, expedtedMsg, wrappedErr.Error())
})
}
func TestNew(t *testing.T) {
t.Run("Is", func(t *testing.T) {
err1 := serrors.New("err msg")
err2 := serrors.New("err msg")
assert.True(t, xerrors.Is(err1, err1))
assert.True(t, xerrors.Is(err2, err2))
assert.False(t, xerrors.Is(err1, err2))
assert.False(t, xerrors.Is(err2, err1))
err1 = serrors.New("err msg", "someCtx", "value")
err2 = serrors.New("err msg", "someCtx", "value")
assert.True(t, xerrors.Is(err1, err1))
assert.True(t, xerrors.Is(err2, err2))
assert.False(t, xerrors.Is(err1, err2))
assert.False(t, xerrors.Is(err2, err1))
})
t.Run("Fmt", func(t *testing.T) {
err := serrors.New("err msg\n", "k0", "v0", "k1", 1)
expedtedMsg := strings.Join([]string{
"err msg",
` > k0="v0" k1="1"`,
}, "\n")
assert.Equal(t, expedtedMsg, err.Error())
})
}
func TestList(t *testing.T) {
var errors serrors.List
assert.Nil(t, errors.ToError())
errors = serrors.List{serrors.New("err1"), serrors.New("err2")}
combinedErr := errors.ToError()
assert.NotNil(t, combinedErr)
assert.Equal(t, "err1\nerr2", combinedErr.Error())
}
func ExampleNew() {
err1 := serrors.New("errtxt")
err2 := serrors.New("errtxt")
// Self equality always works:
fmt.Println(xerrors.Is(err1, err1))
fmt.Println(xerrors.Is(err2, err2))
// On the other hand different errors with same text should not be "equal".
// That is to prevent that errors with same message in different packages
// with same text are seen as the same thing:
fmt.Println(xerrors.Is(err1, err2))
// Output:
// true
// true
// false
}
func ExampleWithCtx() {
// ErrBadL4 is an error defined at package scope.
var ErrBadL4 = serrors.New("Unsupported L4 protocol")
addedCtx := serrors.WithCtx(ErrBadL4, "type", "SCTP")
fmt.Println(addedCtx)
// Output:
// Unsupported L4 protocol type="SCTP"
}
func ExampleWrapStr() {
// ErrNoSpace is an error defined at package scope.
var ErrNoSpace = serrors.New("no space")
wrappedErr := serrors.WrapStr("wrap with more context", ErrNoSpace, "ctx", 1)
fmt.Println(xerrors.Is(wrappedErr, ErrNoSpace))
fmt.Printf("\n%v", wrappedErr)
// Output:
// true
|
// wrap with more context ctx="1"
// no space
}
func ExampleWrap() {
// ErrNoSpace is an error defined at package scope.
var ErrNoSpace = serrors.New("no space")
// ErrDB is an error defined at package scope.
var ErrDB = serrors.New("db")
wrapped := serrors.Wrap(ErrDB, ErrNoSpace, "ctx", 1)
// Now we can identify specific errors:
fmt.Println(xerrors.Is(wrapped, ErrNoSpace))
// But we can also identify the broader error class ErrDB:
fmt.Println(xerrors.Is(wrapped, ErrDB))
fmt.Printf("\n%v", wrapped)
// Output:
// true
// true
//
// db ctx="1"
// no space
}
|
//
|
store.go
|
// Copyright Fuzamei Corp. 2018 All Rights Reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package common
import (
"bytes"
"crypto/sha256"
"encoding/json"
"fmt"
"github.com/33cn/chain33/common/crypto"
"github.com/33cn/chain33/common/db"
"github.com/33cn/chain33/common/log/log15"
"github.com/33cn/chain33/common/version"
"github.com/33cn/chain33/types"
"github.com/golang/protobuf/proto"
)
var (
storelog = log15.New("wallet", "store")
)
// NewStore 新建存储对象
func NewStore(db db.DB) *Store {
return &S
|
包通用数据库存储类,实现对钱包账户数据库操作的基本实现
type Store struct {
db db.DB
}
// Close 关闭数据库
func (store *Store) Close() {
store.db.Close()
}
// GetDB 获取数据库操作接口
func (store *Store) GetDB() db.DB {
return store.db
}
// NewBatch 新建批处理操作对象接口
func (store *Store) NewBatch(sync bool) db.Batch {
return store.db.NewBatch(sync)
}
// Get 取值
func (store *Store) Get(key []byte) ([]byte, error) {
return store.db.Get(key)
}
// Set 设置值
func (store *Store) Set(key []byte, value []byte) (err error) {
return store.db.Set(key, value)
}
// NewListHelper 新建列表复制操作对象
func (store *Store) NewListHelper() *db.ListHelper {
return db.NewListHelper(store.db)
}
// GetAccountByte 获取账号byte类型
func (store *Store) GetAccountByte(update bool, addr string, account *types.WalletAccountStore) ([]byte, error) {
if len(addr) == 0 {
storelog.Error("GetAccountByte addr is nil")
return nil, types.ErrInvalidParam
}
if account == nil {
storelog.Error("GetAccountByte account is nil")
return nil, types.ErrInvalidParam
}
timestamp := fmt.Sprintf("%018d", types.Now().Unix())
//更新时需要使用原来的Accountkey
if update {
timestamp = account.TimeStamp
}
account.TimeStamp = timestamp
accountbyte, err := proto.Marshal(account)
if err != nil {
storelog.Error("GetAccountByte", " proto.Marshal error", err)
return nil, types.ErrMarshal
}
return accountbyte, nil
}
// SetWalletAccount 保存钱包账户信息
func (store *Store) SetWalletAccount(update bool, addr string, account *types.WalletAccountStore) error {
accountbyte, err := store.GetAccountByte(update, addr, account)
if err != nil {
storelog.Error("SetWalletAccount", "GetAccountByte error", err)
return err
}
//需要同时修改三个表,Account,Addr,Label,批量处理
newbatch := store.NewBatch(true)
newbatch.Set(CalcAccountKey(account.TimeStamp, addr), accountbyte)
newbatch.Set(CalcAddrKey(addr), accountbyte)
newbatch.Set(CalcLabelKey(account.GetLabel()), accountbyte)
return newbatch.Write()
}
// SetWalletAccountInBatch 保存钱包账号信息
func (store *Store) SetWalletAccountInBatch(update bool, addr string, account *types.WalletAccountStore, newbatch db.Batch) error {
accountbyte, err := store.GetAccountByte(update, addr, account)
if err != nil {
storelog.Error("SetWalletAccount", "GetAccountByte error", err)
return err
}
//需要同时修改三个表,Account,Addr,Label,批量处理
newbatch.Set(CalcAccountKey(account.TimeStamp, addr), accountbyte)
newbatch.Set(CalcAddrKey(addr), accountbyte)
newbatch.Set(CalcLabelKey(account.GetLabel()), accountbyte)
return nil
}
// GetAccountByAddr 根据地址获取账号信息
func (store *Store) GetAccountByAddr(addr string) (*types.WalletAccountStore, error) {
var account types.WalletAccountStore
if len(addr) == 0 {
storelog.Error("GetAccountByAddr addr is empty")
return nil, types.ErrInvalidParam
}
data, err := store.Get(CalcAddrKey(addr))
if data == nil || err != nil {
if err != db.ErrNotFoundInDb {
storelog.Debug("GetAccountByAddr addr", "err", err)
}
return nil, types.ErrAddrNotExist
}
err = proto.Unmarshal(data, &account)
if err != nil {
storelog.Error("GetAccountByAddr", "proto.Unmarshal err:", err)
return nil, types.ErrUnmarshal
}
return &account, nil
}
// GetAccountByLabel 根据标签获取账号信息
func (store *Store) GetAccountByLabel(label string) (*types.WalletAccountStore, error) {
var account types.WalletAccountStore
if len(label) == 0 {
storelog.Error("GetAccountByLabel label is empty")
return nil, types.ErrInvalidParam
}
data, err := store.Get(CalcLabelKey(label))
if data == nil || err != nil {
if err != db.ErrNotFoundInDb {
storelog.Error("GetAccountByLabel label", "err", err)
}
return nil, types.ErrLabelNotExist
}
err = proto.Unmarshal(data, &account)
if err != nil {
storelog.Error("GetAccountByAddr", "proto.Unmarshal err:", err)
return nil, types.ErrUnmarshal
}
return &account, nil
}
// GetAccountByPrefix 根据前缀获取账号信息列表
func (store *Store) GetAccountByPrefix(addr string) ([]*types.WalletAccountStore, error) {
if len(addr) == 0 {
storelog.Error("GetAccountByPrefix addr is nil")
return nil, types.ErrInvalidParam
}
list := store.NewListHelper()
accbytes := list.PrefixScan([]byte(addr))
if len(accbytes) == 0 {
storelog.Debug("GetAccountByPrefix addr not exist")
return nil, types.ErrAccountNotExist
}
WalletAccountStores := make([]*types.WalletAccountStore, len(accbytes))
for index, accbyte := range accbytes {
var walletaccount types.WalletAccountStore
err := proto.Unmarshal(accbyte, &walletaccount)
if err != nil {
storelog.Error("GetAccountByAddr", "proto.Unmarshal err:", err)
return nil, types.ErrUnmarshal
}
WalletAccountStores[index] = &walletaccount
}
return WalletAccountStores, nil
}
//GetTxDetailByIter 迭代获取从指定key:height*100000+index 开始向前或者向后查找指定count的交易
func (store *Store) GetTxDetailByIter(TxList *types.ReqWalletTransactionList) (*types.WalletTxDetails, error) {
var txDetails types.WalletTxDetails
if TxList == nil {
storelog.Error("GetTxDetailByIter TxList is nil")
return nil, types.ErrInvalidParam
}
var txbytes [][]byte
//FromTx是空字符串时。默认从最新的交易开始取count个
if len(TxList.FromTx) == 0 {
list := store.NewListHelper()
txbytes = list.IteratorScanFromLast(CalcTxKey(""), TxList.Count)
if len(txbytes) == 0 {
storelog.Error("GetTxDetailByIter IteratorScanFromLast does not exist tx!")
return nil, types.ErrTxNotExist
}
} else {
list := store.NewListHelper()
txbytes = list.IteratorScan(CalcTxKey(""), CalcTxKey(string(TxList.FromTx)), TxList.Count, TxList.Direction)
if len(txbytes) == 0 {
storelog.Error("GetTxDetailByIter IteratorScan does not exist tx!")
return nil, types.ErrTxNotExist
}
}
txDetails.TxDetails = make([]*types.WalletTxDetail, len(txbytes))
for index, txdetailbyte := range txbytes {
var txdetail types.WalletTxDetail
err := proto.Unmarshal(txdetailbyte, &txdetail)
if err != nil {
storelog.Error("GetTxDetailByIter", "proto.Unmarshal err:", err)
return nil, types.ErrUnmarshal
}
if string(txdetail.Tx.GetExecer()) == "coins" && txdetail.Tx.ActionName() == "withdraw" {
//swap from and to
txdetail.Fromaddr, txdetail.Tx.To = txdetail.Tx.To, txdetail.Fromaddr
}
txhash := txdetail.GetTx().Hash()
txdetail.Txhash = txhash
txDetails.TxDetails[index] = &txdetail
}
return &txDetails, nil
}
// SetEncryptionFlag 设置加密方式标志
func (store *Store) SetEncryptionFlag(batch db.Batch) error {
var flag int64 = 1
data, err := json.Marshal(flag)
if err != nil {
storelog.Error("SetEncryptionFlag marshal flag", "err", err)
return types.ErrMarshal
}
batch.Set(CalcEncryptionFlag(), data)
return nil
}
// GetEncryptionFlag 获取加密方式
func (store *Store) GetEncryptionFlag() int64 {
var flag int64
data, err := store.Get(CalcEncryptionFlag())
if data == nil || err != nil {
data, err = store.Get(CalckeyEncryptionCompFlag())
if data == nil || err != nil {
return 0
}
}
err = json.Unmarshal(data, &flag)
if err != nil {
storelog.Error("GetEncryptionFlag unmarshal", "err", err)
return 0
}
return flag
}
// SetPasswordHash 保存密码哈希
func (store *Store) SetPasswordHash(password string, batch db.Batch) error {
var WalletPwHash types.WalletPwHash
//获取一个随机字符串
randstr := fmt.Sprintf("fuzamei:$@%s", crypto.CRandHex(16))
WalletPwHash.Randstr = randstr
//通过password和随机字符串生成一个hash值
pwhashstr := fmt.Sprintf("%s:%s", password, WalletPwHash.Randstr)
pwhash := sha256.Sum256([]byte(pwhashstr))
WalletPwHash.PwHash = pwhash[:]
pwhashbytes, err := json.Marshal(WalletPwHash)
if err != nil {
storelog.Error("SetEncryptionFlag marshal flag", "err", err)
return types.ErrMarshal
}
batch.Set(CalcPasswordHash(), pwhashbytes)
return nil
}
// VerifyPasswordHash 检查密码有效性
func (store *Store) VerifyPasswordHash(password string) bool {
var WalletPwHash types.WalletPwHash
pwhashbytes, err := store.Get(CalcPasswordHash())
if pwhashbytes == nil || err != nil {
return false
}
err = json.Unmarshal(pwhashbytes, &WalletPwHash)
if err != nil {
storelog.Error("VerifyPasswordHash unmarshal", "err", err)
return false
}
pwhashstr := fmt.Sprintf("%s:%s", password, WalletPwHash.Randstr)
pwhash := sha256.Sum256([]byte(pwhashstr))
Pwhash := pwhash[:]
//通过新的密码计算pwhash最对比
return bytes.Equal(WalletPwHash.GetPwHash(), Pwhash)
}
// DelAccountByLabel 根据标签名称,删除对应的账号信息
func (store *Store) DelAccountByLabel(label string) {
err := store.GetDB().DeleteSync(CalcLabelKey(label))
if err != nil {
storelog.Error("DelAccountByLabel", "err", err)
}
}
//SetWalletVersion 升级数据库的版本号
func (store *Store) SetWalletVersion(ver int64) error {
data, err := json.Marshal(ver)
if err != nil {
storelog.Error("SetWalletVerKey marshal version", "err", err)
return types.ErrMarshal
}
return store.GetDB().SetSync(version.WalletVerKey, data)
}
// GetWalletVersion 获取wallet数据库的版本号
func (store *Store) GetWalletVersion() int64 {
var ver int64
data, err := store.Get(version.WalletVerKey)
if data == nil || err != nil {
return 0
}
err = json.Unmarshal(data, &ver)
if err != nil {
storelog.Error("GetWalletVersion unmarshal", "err", err)
return 0
}
return ver
}
//HasSeed 判断钱包是否已经保存seed
func (store *Store) HasSeed() (bool, error) {
seed, err := store.Get(CalcWalletSeed())
if len(seed) == 0 || err != nil {
return false, types.ErrSeedExist
}
return true, nil
}
|
tore{db: db}
}
// Store 钱
|
keywordOnlyMove.before.py
|
f(param1=1, param2=2)
|
def f<caret>(*, param1, param2):
pass
|
|
websocket.go
|
package routes
import (
|
"encoding/json"
"errors"
"fmt"
"log"
"github.com/gofiber/websocket/v2"
"github.com/google/uuid"
)
type SocketMessage struct {
event string
message interface{}
}
func (message *SocketMessage) Bytes() ([]byte, error) {
data := make(map[string]interface{})
data["event"] = message.event
data["message"] = message.message
return json.Marshal(data)
}
func WebSocket(c *websocket.Conn) {
var err error
clientId := uuid.New()
clients[clientId.String()] = c
defer delete(clients, clientId.String())
newClientChannel <- clientId.String()
for {
if _, _, err = c.ReadMessage(); err != nil {
//Client has disconnected!
break
}
}
disconnectClientChannel <- clientId.String()
log.Printf("socket (%s) connection closed!", clientId)
}
func sendClientId(c *websocket.Conn, clientId string) error {
message := &SocketMessage{"clientId", clientId}
return sendMessage(c, clientId, message)
}
func sendError(c *websocket.Conn, clientId string, errorString string) error {
message := &SocketMessage{"error", errorString}
return sendMessage(c, clientId, message)
}
func sendMessage(c *websocket.Conn, clientId string, message *SocketMessage) error {
data, err := message.Bytes()
if err != nil {
return errors.New(fmt.Sprintf("socket (%s): %#v", clientId, err))
}
if err = c.WriteMessage(1, data); err != nil {
return errors.New(fmt.Sprintf("socket (%s) write: %v", clientId, err))
}
return nil
}
func sendQueuePosition(c *websocket.Conn, clientId string, position uint64) error {
message := &SocketMessage{"queuePosition", position}
return sendMessage(c, clientId, message)
}
func broadcastQueuePosition() {
var err error
var index uint64
for clientId, c := range clients {
index, err = clientQueue.Index(clientId)
if err != nil {
log.Printf("[broadcastQueuePosition] socket (%s): %v", clientId, err)
continue
}
err = sendQueuePosition(c, clientId, index+1)
if err != nil {
log.Println(err)
}
}
}
| |
modernizr.js
|
/*!
* modernizr v3.2.0
* Build http://modernizr.com/download?-adownload-ambientlight-animation-apng-appearance-applicationcache-atobbtoa-audio-audioloop-audiopreload-backdropfilter-backgroundblendmode-backgroundcliptext-backgroundsize-batteryapi-bdi-beacon-bgpositionshorthand-bgpositionxy-bgrepeatspace_bgrepeatround-bgsizecover-blobconstructor-bloburls-blobworkers-borderimage-borderradius-boxshadow-boxsizing-canvas-canvasblending-canvastext-canvaswinding-capture-checked-classlist-contains-contenteditable-contextmenu-cookies-cors-createelementattrs_createelement_attrs-cryptography-cssall-cssanimations-csscalc-csschunit-csscolumns-cssescape-cssexunit-cssfilters-cssgradients-csshairline-csshyphens_softhyphens_softhyphensfind-cssinvalid-cssmask-csspointerevents-csspositionsticky-csspseudoanimations-csspseudotransitions-cssreflections-cssremunit-cssresize-cssscrollbar-csstransforms-csstransforms3d-csstransitions-cssvalid-cssvhunit-cssvmaxunit-cssvminunit-cssvwunit-cubicbezierrange-customevent-customprotocolhandler-dart-datachannel-datalistelem-dataset-datauri-dataview-dataworkers-details-devicemotion_deviceorientation-directory-display_runin-displaytable-documentfragment-ellipsis-emoji-es5-es5array-es5date-es5function-es5object-es5string-es5syntax-es5undefined-es6array-es6collections-es6math-es6number-es6object-es6string-eventlistener-eventsource-exiforientation-fetch-fileinput-filereader-filesystem-flash-flexbox-flexboxlegacy-flexboxtweener-flexwrap-fontface-forcetouch-formattribute-formvalidation-framed-fullscreen-gamepads-generatedcontent-generators-geolocation-getrandomvalues-getusermedia-hashchange-hidden-hiddenscroll-history-hsla-htmlimports-ie8compat-imgcrossorigin-indexeddb-indexeddbblob-inlinesvg-input-inputformaction-inputformenctype-inputformmethod-inputformtarget-inputtypes-intl-jpeg2000-jpegxr-json-lastchild-ligatures-localizednumber-localstorage-lowbandwidth-lowbattery-matchmedia-mathml-mediaqueries-microdata-multiplebgs-mutationobserver-notification-nthchild-objectfit-olreversed-oninput-opacity-outputelem-overflowscrolling-pagevisibility-peerconnection-performance-picture-placeholder-pointerevents-pointerlock-postmessage-preserve3d-progressbar_meter-promises-proximity-queryselector-quotamanagement-regions-requestanimationframe-requestautocomplete-rgba-ruby-sandbox-scriptasync-scriptdefer-scrollsnappoints-seamless-search-serviceworker-sessionstorage-shapes-sharedworkers-siblinggeneral-sizes-smil-speechrecognition-speechsynthesis-srcdoc-srcset-strictmode-stylescoped-subpixelfont-supports-svg-svgasimg-svgclippaths-svgfilters-svgforeignobject-target-template-templatestrings-textalignlast-textareamaxlength-textshadow-texttrackapi_track-time-todataurljpeg_todataurlpng_todataurlwebp-touchevents-transferables-typedarrays-unicode-unicoderange-unknownelements-urlparser-userdata-userselect-vibrate-video-videoautoplay-videoloop-videopreload-vml-webaudio-webgl-webglextensions-webintents-webp-webpalpha-webpanimation-webplossless_webp_lossless-websockets-websocketsbinary-websqldatabase-webworkers-willchange-wrapflow-xdomainrequest-xhr2-xhrresponsetype-xhrresponsetypearraybuffer-xhrresponsetypeblob-xhrresponsetypedocument-xhrresponsetypejson-xhrresponsetypetext-addtest-atrule-domprefixes-hasevent-mq-prefixed-prefixedcss-prefixedcssvalue-prefixes-setclasses-shiv-testallprops-testprop-teststyles-dontmin
*
* Copyright (c)
* Faruk Ates
* Paul Irish
* Alex Sexton
* Ryan Seddon
* Patrick Kettner
* Stu Cox
* Richard Herrera
* MIT License
*/
/*
* Modernizr tests which native CSS3 and HTML5 features are available in the
* current UA and makes the results available to you in two ways: as properties on
* a global `Modernizr` object, and as classes on the `<html>` element. This
* information allows you to progressively enhance your pages with a granular level
* of control over the experience.
*/
;(function(window, document, undefined){
var classes = [];
var tests = [];
/**
*
* ModernizrProto is the constructor for Modernizr
*
* @class
* @access public
*/
var ModernizrProto = {
// The current version, dummy
_version: '3.2.0',
// Any settings that don't work as separate modules
// can go in here as configuration.
_config: {
'classPrefix': '',
'enableClasses': true,
'enableJSClass': true,
'usePrefixes': true
},
// Queue of tests
_q: [],
// Stub these for people who are listening
on: function(test, cb) {
// I don't really think people should do this, but we can
// safe guard it a bit.
// -- NOTE:: this gets WAY overridden in src/addTest for actual async tests.
// This is in case people listen to synchronous tests. I would leave it out,
// but the code to *disallow* sync tests in the real version of this
// function is actually larger than this.
var self = this;
setTimeout(function() {
cb(self[test]);
}, 0);
},
addTest: function(name, fn, options) {
tests.push({name: name, fn: fn, options: options});
},
addAsyncTest: function(fn) {
tests.push({name: null, fn: fn});
}
};
// Fake some of Object.create so we can force non test results to be non "own" properties.
var Modernizr = function() {};
Modernizr.prototype = ModernizrProto;
// Leak modernizr globally when you `require` it rather than force it here.
// Overwrite name so constructor name is nicer :D
Modernizr = new Modernizr();
/*!
{
"name": "Application Cache",
"property": "applicationcache",
"caniuse": "offline-apps",
"tags": ["storage", "offline"],
"notes": [{
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en/docs/HTML/Using_the_application_cache"
}],
"polyfills": ["html5gears"]
}
!*/
/* DOC
Detects support for the Application Cache, for storing data to enable web-based applications run offline.
The API has been [heavily criticized](http://alistapart.com/article/application-cache-is-a-douchebag) and discussions are underway to address this.
*/
Modernizr.addTest('applicationcache', 'applicationCache' in window);
/*!
{
"name": "Blob constructor",
"property": "blobconstructor",
"aliases": ["blob-constructor"],
"builderAliases": ["blob_constructor"],
"caniuse": "blobbuilder",
"notes": [{
"name": "W3C spec",
"href": "http://dev.w3.org/2006/webapi/FileAPI/#constructorBlob"
}],
"polyfills": ["blobjs"]
}
!*/
/* DOC
Detects support for the Blob constructor, for creating file-like objects of immutable, raw data.
*/
Modernizr.addTest('blobconstructor', function() {
try {
return !!new Blob();
} catch (e) {
return false;
}
}, {
aliases: ['blob-constructor']
});
/*!
{
"name": "Cookies",
"property": "cookies",
"tags": ["storage"],
"authors": ["tauren"]
}
!*/
/* DOC
Detects whether cookie support is enabled.
*/
// https://github.com/Modernizr/Modernizr/issues/191
Modernizr.addTest('cookies', function() {
// navigator.cookieEnabled cannot detect custom or nuanced cookie blocking
// configurations. For example, when blocking cookies via the Advanced
// Privacy Settings in IE9, it always returns true. And there have been
// issues in the past with site-specific exceptions.
// Don't rely on it.
// try..catch because some in situations `document.cookie` is exposed but throws a
// SecurityError if you try to access it; e.g. documents created from data URIs
// or in sandboxed iframes (depending on flags/context)
try {
// Create cookie
document.cookie = 'cookietest=1';
var ret = document.cookie.indexOf('cookietest=') != -1;
// Delete cookie
document.cookie = 'cookietest=1; expires=Thu, 01-Jan-1970 00:00:01 GMT';
return ret;
}
catch (e) {
return false;
}
});
/*!
{
"name": "Cross-Origin Resource Sharing",
"property": "cors",
"caniuse": "cors",
"authors": ["Theodoor van Donge"],
"notes": [{
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en-US/docs/HTTP/Access_control_CORS"
}],
"polyfills": ["pmxdr", "ppx", "flxhr"]
}
!*/
/* DOC
Detects support for Cross-Origin Resource Sharing: method of performing XMLHttpRequests across domains.
*/
Modernizr.addTest('cors', 'XMLHttpRequest' in window && 'withCredentials' in new XMLHttpRequest());
/*!
{
"name": "Custom protocol handler",
"property": "customprotocolhandler",
"authors": ["Ben Schwarz"],
"builderAliases": ["custom_protocol_handler"],
"notes": [{
"name": "WHATWG overview",
"href": "http://developers.whatwg.org/timers.html#custom-handlers"
},{
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en-US/docs/Web/API/navigator.registerProtocolHandler"
}],
"warnings": [],
"polyfills": []
}
!*/
/* DOC
Detects support for the `window.registerProtocolHandler()` API to allow websites to register themselves as possible handlers for particular protocols.
*/
Modernizr.addTest('customprotocolhandler', function() {
// early bailout where it doesn't exist at all
if (!navigator.registerProtocolHandler) {
return false;
}
// registerProtocolHandler was stubbed in webkit for a while, and didn't
// actually do anything. We intentionally set it improperly to test for
// the proper sort of failure
try {
navigator.registerProtocolHandler('thisShouldFail');
}
catch (e) {
return e instanceof TypeError;
}
return false;
});
/*!
{
"name": "CustomEvent",
"property": "customevent",
"tags": ["customevent"],
"authors": ["Alberto Elias"],
"notes": [{
"name": "W3C DOM reference",
"href": "http://www.w3.org/TR/DOM-Level-3-Events/#interface-CustomEvent"
}, {
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en/docs/Web/API/CustomEvent"
}],
"polyfills": ["eventlistener"]
}
!*/
/* DOC
Detects support for CustomEvent.
*/
Modernizr.addTest('customevent', 'CustomEvent' in window && typeof window.CustomEvent === 'function');
/*!
{
"name": "DataView",
"property": "dataview",
"authors": ["Addy Osmani"],
"builderAliases": ["dataview_api"],
"notes": [{
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en/JavaScript_typed_arrays/DataView"
}],
"polyfills": ["jdataview"]
}
!*/
/* DOC
Detects support for the DataView interface for reading data from an ArrayBuffer as part of the Typed Array spec.
*/
Modernizr.addTest('dataview', (typeof DataView !== 'undefined' && 'getFloat64' in DataView.prototype));
/*!
{
"name": "Event Listener",
"property": "eventlistener",
"authors": ["Andrew Betts (@triblondon)"],
"notes": [{
"name": "W3C Spec",
"href": "http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-Registration-interfaces"
}],
"polyfills": ["eventlistener"]
}
!*/
/* DOC
Detects native support for addEventListener
*/
Modernizr.addTest('eventlistener', 'addEventListener' in window);
/*!
{
"name": "Geolocation API",
"property": "geolocation",
"caniuse": "geolocation",
"tags": ["media"],
"notes": [{
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en-US/docs/WebAPI/Using_geolocation"
}],
"polyfills": [
"joshuabell-polyfill",
"webshims",
"geo-location-javascript",
"geolocation-api-polyfill"
]
}
!*/
/* DOC
Detects support for the Geolocation API for users to provide their location to web applications.
*/
// geolocation is often considered a trivial feature detect...
// Turns out, it's quite tricky to get right:
//
// Using !!navigator.geolocation does two things we don't want. It:
// 1. Leaks memory in IE9: github.com/Modernizr/Modernizr/issues/513
// 2. Disables page caching in WebKit: webk.it/43956
//
// Meanwhile, in Firefox < 8, an about:config setting could expose
// a false positive that would throw an exception: bugzil.la/688158
Modernizr.addTest('geolocation', 'geolocation' in navigator);
/*!
{
"name": "History API",
"property": "history",
"caniuse": "history",
"tags": ["history"],
"authors": ["Hay Kranen", "Alexander Farkas"],
"notes": [{
"name": "W3C Spec",
"href": "http://www.w3.org/TR/html51/browsers.html#the-history-interface"
}, {
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en-US/docs/Web/API/window.history"
}],
"polyfills": ["historyjs", "html5historyapi"]
}
!*/
/* DOC
Detects support for the History API for manipulating the browser session history.
*/
Modernizr.addTest('history', function() {
// Issue #733
// The stock browser on Android 2.2 & 2.3, and 4.0.x returns positive on history support
// Unfortunately support is really buggy and there is no clean way to detect
// these bugs, so we fall back to a user agent sniff :(
var ua = navigator.userAgent;
// We only want Android 2 and 4.0, stock browser, and not Chrome which identifies
// itself as 'Mobile Safari' as well, nor Windows Phone (issue #1471).
if ((ua.indexOf('Android 2.') !== -1 ||
(ua.indexOf('Android 4.0') !== -1)) &&
ua.indexOf('Mobile Safari') !== -1 &&
ua.indexOf('Chrome') === -1 &&
ua.indexOf('Windows Phone') === -1) {
return false;
}
// Return the regular check
return (window.history && 'pushState' in window.history);
});
/*!
{
"name": "IE8 compat mode",
"property": "ie8compat",
"authors": ["Erich Ocean"]
}
!*/
/* DOC
Detects whether or not the current browser is IE8 in compatibility mode (i.e. acting as IE7).
*/
// In this case, IE8 will be acting as IE7. You may choose to remove features in this case.
// related:
// james.padolsey.com/javascript/detect-ie-in-js-using-conditional-comments/
Modernizr.addTest('ie8compat', (!window.addEventListener && !!document.documentMode && document.documentMode === 7));
/*!
{
"name": "JSON",
"property": "json",
"caniuse": "json",
"notes": [{
"name": "MDN documentation",
"href": "http://developer.mozilla.org/en/JSON"
}],
"polyfills": ["json2"]
}
!*/
/* DOC
Detects native support for JSON handling functions.
*/
// this will also succeed if you've loaded the JSON2.js polyfill ahead of time
// ... but that should be obvious. :)
Modernizr.addTest('json', 'JSON' in window && 'parse' in JSON && 'stringify' in JSON);
/*!
{
"name": "Notification",
"property": "notification",
"caniuse": "notifications",
"authors": ["Theodoor van Donge", "Hendrik Beskow"],
"notes": [{
"name": "HTML5 Rocks tutorial",
"href": "http://www.html5rocks.com/en/tutorials/notifications/quick/"
},{
"name": "W3C spec",
"href": "www.w3.org/TR/notifications/"
}, {
"name": "Changes in Chrome to Notifications API due to Service Worker Push Notifications",
"href": "https://developers.google.com/web/updates/2015/05/Notifying-you-of-notificiation-changes"
}],
"knownBugs": [
"Possibility of false-positive on Chrome for Android if permissions we're granted for a website prior to Chrome 44."
],
"polyfills": ["desktop-notify", "html5-notifications"]
}
!*/
/* DOC
Detects support for the Notifications API
*/
Modernizr.addTest('notification', function() {
if (!window.Notification || !window.Notification.requestPermission) {
return false;
}
// if permission is already granted, assume support
if (window.Notification.permission === 'granted') {
return true;
}
try {
new window.Notification('');
} catch (e) {
if (e.name === 'TypeError') {
return false;
}
}
return true;
});
/*!
{
"name": "postMessage",
"property": "postmessage",
"caniuse": "x-doc-messaging",
"notes": [{
"name": "W3C Spec",
"href": "http://www.w3.org/TR/html5/comms.html#posting-messages"
}],
"polyfills": ["easyxdm", "postmessage-jquery"]
}
!*/
/* DOC
Detects support for the `window.postMessage` protocol for cross-document messaging.
*/
Modernizr.addTest('postmessage', 'postMessage' in window);
/*!
{
"name": "QuerySelector",
"property": "queryselector",
"caniuse": "queryselector",
"tags": ["queryselector"],
"authors": ["Andrew Betts (@triblondon)"],
"notes": [{
"name" : "W3C Selectors reference",
"href": "http://www.w3.org/TR/selectors-api/#queryselectorall"
}],
"polyfills": ["css-selector-engine"]
}
!*/
/* DOC
Detects support for querySelector.
*/
Modernizr.addTest('queryselector', 'querySelector' in document && 'querySelectorAll' in document);
/*!
{
"name": "ServiceWorker API",
"property": "serviceworker",
"notes": [{
"name": "ServiceWorkers Explained",
"href": "https://github.com/slightlyoff/ServiceWorker/blob/master/explainer.md"
}]
}
!*/
/* DOC
ServiceWorkers (formerly Navigation Controllers) are a way to persistently cache resources to built apps that work better offline.
*/
Modernizr.addTest('serviceworker', 'serviceWorker' in navigator);
/*!
{
"name": "SVG",
"property": "svg",
"caniuse": "svg",
"tags": ["svg"],
"authors": ["Erik Dahlstrom"],
"polyfills": [
"svgweb",
"raphael",
"amplesdk",
"canvg",
"svg-boilerplate",
"sie",
"dojogfx",
"fabricjs"
]
}
!*/
/* DOC
Detects support for SVG in `<embed>` or `<object>` elements.
*/
Modernizr.addTest('svg', !!document.createElementNS && !!document.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGRect);
/*!
{
"name": "Template strings",
"property": "templatestrings",
"notes": [{
"name": "MDN Reference",
"href": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings#Browser_compatibility"
}]
}
!*/
/* DOC
Template strings are string literals allowing embedded expressions.
*/
Modernizr.addTest('templatestrings', function() {
var supports;
try {
// A number of tools, including uglifyjs and require, break on a raw "`", so
// use an eval to get around that.
eval('``');
supports = true;
} catch (e) {}
return !!supports;
});
/*!
{
"name": "Typed arrays",
"property": "typedarrays",
"caniuse": "typedarrays",
"tags": ["js"],
"authors": ["Stanley Stuart (@fivetanley)"],
"notes": [{
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en-US/docs/JavaScript_typed_arrays"
},{
"name": "Kronos spec",
"href": "http://www.khronos.org/registry/typedarray/specs/latest/"
}],
"polyfills": ["joshuabell-polyfill"]
}
!*/
/* DOC
Detects support for native binary data manipulation via Typed Arrays in JavaScript.
Does not check for DataView support; use `Modernizr.dataview` for that.
*/
// Should fail in:
// Internet Explorer <= 9
// Firefox <= 3.6
// Chrome <= 6.0
// iOS Safari < 4.2
// Safari < 5.1
// Opera < 11.6
// Opera Mini, <= 7.0
// Android Browser < 4.0
// Blackberry Browser < 10.0
Modernizr.addTest('typedarrays', 'ArrayBuffer' in window);
/*!
{
"name": "WebSockets Support",
"property": "websockets",
"authors": ["Phread [fearphage]", "Mike Sherov [mikesherov]", "Burak Yigit Kaya [BYK]"],
"caniuse": "websockets",
"tags": ["html5"],
"warnings": [
"This test will reject any old version of WebSockets even if it is not prefixed such as in Safari 5.1"
],
"notes": [{
"name": "CLOSING State and Spec",
"href": "http://www.w3.org/TR/websockets/#the-websocket-interface"
}],
"polyfills": [
"sockjs",
"socketio",
"kaazing-websocket-gateway",
"websocketjs",
"atmosphere",
"graceful-websocket",
"portal",
"datachannel"
]
}
!*/
Modernizr.addTest('websockets', 'WebSocket' in window && window.WebSocket.CLOSING === 2);
/*!
{
"name": "XDomainRequest",
"property": "xdomainrequest",
"tags": ["cors", "xdomainrequest", "ie9", "ie8"],
"authors": ["Ivan Pan (@hypotenuse)"],
"notes": [
{
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en-US/docs/Web/API/XDomainRequest"
},
{
"name": "MSDN documentation",
"href": "https://msdn.microsoft.com/library/ie/cc288060.aspx/"
}]
}
!*/
/* DOC
Detects support for XDomainRequest in IE9 & IE8
*/
Modernizr.addTest('xdomainrequest', 'XDomainRequest' in window);
/*!
{
"name": "Web Audio API",
"property": "webaudio",
"caniuse": "audio-api",
"polyfills": ["xaudiojs", "dynamicaudiojs", "audiolibjs"],
"tags": ["audio", "media"],
"builderAliases": ["audio_webaudio_api"],
"authors": ["Addy Osmani"],
"notes": [{
"name": "W3 Specification",
"href": "https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html"
}]
}
!*/
/* DOC
Detects the older non standard webaudio API, (as opposed to the standards based AudioContext API)
*/
Modernizr.addTest('webaudio', function() {
var prefixed = 'webkitAudioContext' in window;
var unprefixed = 'AudioContext' in window;
if (Modernizr._config.usePrefixes) {
return prefixed || unprefixed;
}
return unprefixed;
});
/*!
{
"name": "CSS.escape()",
"property": "cssescape",
"polyfills": [
"css-escape"
],
"tags": [
"css",
"cssom"
]
}
!*/
/* DOC
Tests for `CSS.escape()` support.
*/
var CSS = window.CSS;
Modernizr.addTest('cssescape', CSS ? typeof CSS.escape == 'function' : false);
/*!
{
"name": "CSS Supports",
"property": "supports",
"caniuse": "css-featurequeries",
"tags": ["css"],
"builderAliases": ["css_supports"],
"notes": [{
"name": "W3 Spec",
"href": "http://dev.w3.org/csswg/css3-conditional/#at-supports"
},{
"name": "Related Github Issue",
"href": "github.com/Modernizr/Modernizr/issues/648"
},{
"name": "W3 Info",
"href": "http://dev.w3.org/csswg/css3-conditional/#the-csssupportsrule-interface"
}]
}
!*/
var newSyntax = 'CSS' in window && 'supports' in window.CSS;
var oldSyntax = 'supportsCSS' in window;
Modernizr.addTest('supports', newSyntax || oldSyntax);
/*!
{
"name": "CSS :target pseudo-class",
"caniuse": "css-sel3",
"property": "target",
"tags": ["css"],
"notes": [{
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en-US/docs/Web/CSS/:target"
}],
"authors": ["@zachleat"],
"warnings": ["Opera Mini supports :target but doesn't update the hash for anchor links."]
}
!*/
/* DOC
Detects support for the ':target' CSS pseudo-class.
*/
// querySelector
Modernizr.addTest('target', function() {
var doc = window.document;
if (!('querySelectorAll' in doc)) {
return false;
}
try {
doc.querySelectorAll(':target');
return true;
} catch (e) {
return false;
}
});
/*!
{
"name": "microdata",
"property": "microdata",
"tags": ["dom"],
"builderAliases": ["dom_microdata"],
"notes": [{
"name": "W3 Spec",
"href": "http://www.w3.org/TR/html5/microdata.html"
}]
}
!*/
Modernizr.addTest('microdata', 'getItems' in document);
/*!
{
"name": "DOM4 MutationObserver",
"property": "mutationobserver",
"caniuse": "mutationobserver",
"tags": ["dom"],
"authors": ["Karel Sedláček (@ksdlck)"],
"polyfills": ["mutationobservers"],
"notes": [{
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver"
}]
}
!*/
/* DOC
Determines if DOM4 MutationObserver support is available.
*/
Modernizr.addTest('mutationobserver',
!!window.MutationObserver || !!window.WebKitMutationObserver);
/*!
{
"name": "picture Element",
"property": "picture",
"tags": ["elem"],
"authors": ["Scott Jehl", "Mat Marquis"],
"notes": [{
"name": "Specification",
"href": "http://picture.responsiveimages.org"
},{
"name": "Relevant spec issue",
"href": "https://github.com/ResponsiveImagesCG/picture-element/issues/87"
}]
}
!*/
Modernizr.addTest('picture', 'HTMLPictureElement' in window);
/*!
{
"name": "ES5 Array",
"property": "es5array",
"notes": [{
"name": "ECMAScript 5.1 Language Specification",
"href": "http://www.ecma-international.org/ecma-262/5.1/"
}],
"polyfills": ["es5shim"],
"authors": ["Ron Waldon (@jokeyrhyme)"],
"tags": ["es5"]
}
!*/
/* DOC
Check if browser implements ECMAScript 5 Array per specification.
*/
Modernizr.addTest('es5array', function() {
return !!(Array.prototype &&
Array.prototype.every &&
Array.prototype.filter &&
Array.prototype.forEach &&
Array.prototype.indexOf &&
Array.prototype.lastIndexOf &&
Array.prototype.map &&
Array.prototype.some &&
Array.prototype.reduce &&
Array.prototype.reduceRight &&
Array.isArray);
});
/*!
{
"name": "ES5 Date",
"property": "es5date",
"notes": [{
"name": "ECMAScript 5.1 Language Specification",
"href": "http://www.ecma-international.org/ecma-262/5.1/"
}],
"polyfills": ["es5shim"],
"authors": ["Ron Waldon (@jokeyrhyme)"],
"tags": ["es5"]
}
!*/
/* DOC
Check if browser implements ECMAScript 5 Date per specification.
*/
Modernizr.addTest('es5date', function() {
var isoDate = '2013-04-12T06:06:37.307Z',
canParseISODate = false;
try {
canParseISODate = !!Date.parse(isoDate);
} catch (e) {
// no ISO date parsing yet
}
return !!(Date.now &&
Date.prototype &&
Date.prototype.toISOString &&
Date.prototype.toJSON &&
canParseISODate);
});
/*!
{
"name": "ES5 Function",
"property": "es5function",
"notes": [{
"name": "ECMAScript 5.1 Language Specification",
"href": "http://www.ecma-international.org/ecma-262/5.1/"
}],
"polyfills": ["es5shim"],
"authors": ["Ron Waldon (@jokeyrhyme)"],
"tags": ["es5"]
}
!*/
/* DOC
Check if browser implements ECMAScript 5 Function per specification.
*/
Modernizr.addTest('es5function', function() {
return !!(Function.prototype && Function.prototype.bind);
});
/*!
{
"name": "ES5 Object",
"property": "es5object",
"notes": [{
"name": "ECMAScript 5.1 Language Specification",
"href": "http://www.ecma-international.org/ecma-262/5.1/"
}],
"polyfills": ["es5shim", "es5sham"],
"authors": ["Ron Waldon (@jokeyrhyme)"],
"tags": ["es5"]
}
!*/
/* DOC
Check if browser implements ECMAScript 5 Object per specification.
*/
Modernizr.addTest('es5object', function() {
return !!(Object.keys &&
Object.create &&
Object.getPrototypeOf &&
Object.getOwnPropertyNames &&
Object.isSealed &&
Object.isFrozen &&
Object.isExtensible &&
Object.getOwnPropertyDescriptor &&
Object.defineProperty &&
Object.defineProperties &&
Object.seal &&
Object.freeze &&
Object.preventExtensions);
});
/*!
{
"name": "ES5 Strict Mode",
"property": "strictmode",
"caniuse": "sctrict-mode",
"notes": [{
"name": "ECMAScript 5.1 Language Specification",
"href": "http://www.ecma-international.org/ecma-262/5.1/"
}],
"authors": ["@kangax"],
"tags": ["es5"],
"builderAliases": ["es5_strictmode"]
}
!*/
/* DOC
Check if browser implements ECMAScript 5 Object strict mode.
*/
Modernizr.addTest('strictmode', (function() {'use strict'; return !this; })());
/*!
{
"name": "ES5 String",
"property": "es5string",
"notes": [{
"name": "ECMAScript 5.1 Language Specification",
"href": "http://www.ecma-international.org/ecma-262/5.1/"
}],
"polyfills": ["es5shim"],
"authors": ["Ron Waldon (@jokeyrhyme)"],
"tags": ["es5"]
}
!*/
/* DOC
Check if browser implements ECMAScript 5 String per specification.
*/
Modernizr.addTest('es5string', function() {
return !!(String.prototype && String.prototype.trim);
});
/*!
{
"name": "ES5 Syntax",
"property": "es5syntax",
"notes": [{
"name": "ECMAScript 5.1 Language Specification",
"href": "http://www.ecma-international.org/ecma-262/5.1/"
}, {
"name": "original implementation of detect code",
"href": "http://kangax.github.io/es5-compat-table/"
}],
"authors": ["Ron Waldon (@jokeyrhyme)"],
"warnings": ["This detect uses `eval()`, so CSP may be a problem."],
"tags": ["es5"]
}
!*/
/* DOC
Check if browser accepts ECMAScript 5 syntax.
*/
Modernizr.addTest('es5syntax', function() {
var value, obj, stringAccess, getter, setter, reservedWords, zeroWidthChars;
try {
// Property access on strings
stringAccess = eval('"foobar"[3] === "b"');
// Getter in property initializer
getter = eval('({ get x(){ return 1 } }).x === 1');
eval('({ set x(v){ value = v; } }).x = 1');
// Setter in property initializer
setter = value === 1;
// Reserved words as property names
eval('obj = ({ if: 1 })');
reservedWords = obj['if'] === 1;
// Zero-width characters in identifiers
zeroWidthChars = eval('_\u200c\u200d = true');
return stringAccess && getter && setter && reservedWords && zeroWidthChars;
} catch (ignore) {
return false;
}
});
/*!
{
"name": "ES5 Immutable Undefined",
"property": "es5undefined",
"notes": [{
"name": "ECMAScript 5.1 Language Specification",
"href": "http://www.ecma-international.org/ecma-262/5.1/"
}, {
"name": "original implementation of detect code",
"href": "http://kangax.github.io/es5-compat-table/"
}],
"authors": ["Ron Waldon (@jokeyrhyme)"],
"tags": ["es5"]
}
!*/
/* DOC
Check if browser prevents assignment to global `undefined` per ECMAScript 5.
*/
Modernizr.addTest('es5undefined', function() {
var result, originalUndefined;
try {
originalUndefined = window.undefined;
window.undefined = 12345;
result = typeof window.undefined === 'undefined';
window.undefined = originalUndefined;
} catch (e) {
return false;
}
return result;
});
/*!
{
"name": "ES5",
"property": "es5",
"notes": [{
"name": "ECMAScript 5.1 Language Specification",
"href": "http://www.ecma-international.org/ecma-262/5.1/"
}],
"polyfills": ["es5shim", "es5sham"],
"authors": ["Ron Waldon (@jokeyrhyme)"],
"tags": ["es5"]
}
!*/
/* DOC
Check if browser implements everything as specified in ECMAScript 5.
*/
Modernizr.addTest('es5', function() {
return !!(
Modernizr.es5array &&
Modernizr.es5date &&
Modernizr.es5function &&
Modernizr.es5object &&
Modernizr.strictmode &&
Modernizr.es5string &&
Modernizr.json &&
Modernizr.es5syntax &&
Modernizr.es5undefined
);
});
/*!
{
"name": "ES6 Array",
"property": "es6array",
"notes": [{
"name": "unofficial ECMAScript 6 draft specification",
"href": "http://people.mozilla.org/~jorendorff/es6-draft.html"
}],
"polyfills": ["es6shim"],
"authors": ["Ron Waldon (@jokeyrhyme)"],
"warnings": ["ECMAScript 6 is still a only a draft, so this detect may not match the final specification or implementations."],
"tags": ["es6"]
}
!*/
/* DOC
Check if browser implements ECMAScript 6 Array per specification.
*/
Modernizr.addTest('es6array', !!(Array.prototype &&
Array.prototype.copyWithin &&
Array.prototype.fill &&
Array.prototype.find &&
Array.prototype.findIndex &&
Array.prototype.keys &&
Array.prototype.entries &&
Array.prototype.values &&
Array.from &&
Array.of));
/*!
{
"name": "ES6 Collections",
"property": "es6collections",
"notes": [{
"name": "unofficial ECMAScript 6 draft specification",
"href": "http://people.mozilla.org/~jorendorff/es6-draft.html"
}],
"polyfills": ["es6shim", "weakmap"],
"authors": ["Ron Waldon (@jokeyrhyme)"],
"warnings": ["ECMAScript 6 is still a only a draft, so this detect may not match the final specification or implementations."],
"tags": ["es6"]
}
!*/
/* DOC
Check if browser implements ECMAScript 6 Map, Set, WeakMap and WeakSet
*/
Modernizr.addTest('es6collections', !!(
window.Map && window.Set && window.WeakMap && window.WeakSet
));
/*!
{
"name": "ES6 Generators",
"property": "generators",
"authors": ["Michael Kachanovskyi"],
"tags": ["es6"]
}
!*/
/* DOC
Check if browser implements ECMAScript 6 Generators per specification.
*/
Modernizr.addTest('generators', function() {
try {
/* jshint evil: true */
new Function('function* test() {}')();
} catch (e) {
return false;
}
return true;
});
/*!
{
"name": "ES6 Math",
"property": "es6math",
"notes": [{
"name": "unofficial ECMAScript 6 draft specification",
"href": "http://people.mozilla.org/~jorendorff/es6-draft.html"
}],
"polyfills": ["es6shim"],
"authors": ["Ron Waldon (@jokeyrhyme)"],
"warnings": ["ECMAScript 6 is still a only a draft, so this detect may not match the final specification or implementations."],
"tags": ["es6"]
}
!*/
/* DOC
Check if browser implements ECMAScript 6 Math per specification.
*/
Modernizr.addTest('es6math', !!(Math &&
Math.clz32 &&
Math.cbrt &&
Math.imul &&
Math.sign &&
Math.log10 &&
Math.log2 &&
Math.log1p &&
Math.expm1 &&
Math.cosh &&
Math.sinh &&
Math.tanh &&
Math.acosh &&
Math.asinh &&
Math.atanh &&
Math.hypot &&
Math.trunc &&
Math.fround));
/*!
{
"name": "ES6 Number",
"property": "es6number",
"notes": [{
"name": "unofficial ECMAScript 6 draft specification",
"href": "http://people.mozilla.org/~jorendorff/es6-draft.html"
}],
"polyfills": ["es6shim"],
"authors": ["Ron Waldon (@jokeyrhyme)"],
"warnings": ["ECMAScript 6 is still a only a draft, so this detect may not match the final specification or implementations."],
"tags": ["es6"]
}
!*/
/* DOC
Check if browser implements ECMAScript 6 Number per specification.
*/
Modernizr.addTest('es6number', !!(Number.isFinite &&
Number.isInteger &&
Number.isSafeInteger &&
Number.isNaN &&
Number.parseInt &&
Number.parseFloat &&
Number.isInteger(Number.MAX_SAFE_INTEGER) &&
Number.isInteger(Number.MIN_SAFE_INTEGER) &&
Number.isFinite(Number.EPSILON)));
/*!
{
"name": "ES6 Object",
"property": "es6object",
"notes": [{
"name": "unofficial ECMAScript 6 draft specification",
"href": "http://people.mozilla.org/~jorendorff/es6-draft.html"
}],
"polyfills": ["es6shim"],
"authors": ["Ron Waldon (@jokeyrhyme)"],
"warnings": ["ECMAScript 6 is still a only a draft, so this detect may not match the final specification or implementations."],
"tags": ["es6"]
}
!*/
/* DOC
Check if browser implements ECMAScript 6 Object per specification.
*/
Modernizr.addTest('es6object', !!(Object.assign &&
Object.is &&
Object.setPrototypeOf));
/*!
{
"name": "ES6 Promises",
"property": "promises",
"caniuse": "promises",
"polyfills": ["es6promises"],
"authors": ["Krister Kari", "Jake Archibald"],
"tags": ["es6"],
"notes": [{
"name": "The ES6 promises spec",
"href": "https://github.com/domenic/promises-unwrapping"
},{
"name": "Chromium dashboard - ES6 Promises",
"href": "http://www.chromestatus.com/features/5681726336532480"
},{
"name": "JavaScript Promises: There and back again - HTML5 Rocks",
"href": "http://www.html5rocks.com/en/tutorials/es6/promises/"
}]
}
!*/
/* DOC
Check if browser implements ECMAScript 6 Promises per specification.
*/
Modernizr.addTest('promises', function() {
return 'Promise' in window &&
// Some of these methods are missing from
// Firefox/Chrome experimental implementations
'resolve' in window.Promise &&
'reject' in window.Promise &&
'all' in window.Promise &&
'race' in window.Promise &&
// Older version of the spec had a resolver object
// as the arg rather than a function
(function() {
var resolve;
new window.Promise(function(r) { resolve = r; });
return typeof resolve === 'function';
}());
});
/*!
{
"name": "ES6 String",
"property": "es6string",
"notes": [{
"name": "unofficial ECMAScript 6 draft specification",
"href": "http://people.mozilla.org/~jorendorff/es6-draft.html"
}],
"polyfills": ["es6shim"],
"authors": ["Ron Waldon (@jokeyrhyme)"],
"warnings": ["ECMAScript 6 is still a only a draft, so this detect may not match the final specification or implementations."],
"tags": ["es6"]
}
!*/
/* DOC
Check if browser implements ECMAScript 6 String per specification.
*/
Modernizr.addTest('es6string', !!(String.fromCodePoint &&
String.raw &&
String.prototype.codePointAt &&
String.prototype.repeat &&
String.prototype.startsWith &&
String.prototype.endsWith &&
String.prototype.contains));
/*!
{
"name": "Orientation and Motion Events",
"property": ["devicemotion", "deviceorientation"],
"caniuse": "deviceorientation",
"notes": [{
"name": "W3C Editor's Draft",
"href": "http://dev.w3.org/geo/api/spec-source-orientation.html"
},{
"name": "Implementation by iOS Safari (Orientation)",
"href": "http://goo.gl/fhce3"
},{
"name": "Implementation by iOS Safari (Motion)",
"href": "http://goo.gl/rLKz8"
}],
"authors": ["Shi Chuan"],
"tags": ["event"],
"builderAliases": ["event_deviceorientation_motion"]
}
!*/
/* DOC
Part of Device Access aspect of HTML5, same category as geolocation.
`devicemotion` tests for Device Motion Event support, returns boolean value true/false.
`deviceorientation` tests for Device Orientation Event support, returns boolean value true/false
*/
Modernizr.addTest('devicemotion', 'DeviceMotionEvent' in window);
Modernizr.addTest('deviceorientation', 'DeviceOrientationEvent' in window);
/*!
{
"name": "File API",
"property": "filereader",
"caniuse": "fileapi",
"notes": [{
"name": "W3C Working Draft",
"href": "http://www.w3.org/TR/FileAPI/"
}],
"tags": ["file"],
"builderAliases": ["file_api"],
"knownBugs": ["Will fail in Safari 5 due to its lack of support for the standards defined FileReader object"]
}
!*/
/* DOC
`filereader` tests for the File API specification
Tests for objects specific to the File API W3C specification without
being redundant (don't bother testing for Blob since it is assumed
to be the File object's prototype.)
*/
Modernizr.addTest('filereader', !!(window.File && window.FileList && window.FileReader));
/*!
{
"name": "Beacon API",
"notes": [{
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en-US/docs/Web/API/navigator.sendBeacon"
},{
"name": "W3C specification",
"href": "https://dvcs.w3.org/hg/webperf/raw-file/tip/specs/Beacon/Overview.html"
}],
"property": "beacon",
"tags": ["beacon", "network"],
"authors": ["Cătălin Mariș"]
}
!*/
/* DOC
Detects support for an API that allows for asynchronous transfer of small HTTP data from the client to a server.
*/
Modernizr.addTest('beacon', 'sendBeacon' in navigator);
/*!
{
"name": "Low Bandwidth Connection",
"property": "lowbandwidth",
"tags": ["network"],
"builderAliases": ["network_connection"]
}
!*/
/* DOC
Tests for determining low-bandwidth via `navigator.connection`
There are two iterations of the `navigator.connection` interface.
The first is present in Android 2.2+ and only in the Browser (not WebView)
- http://docs.phonegap.com/en/1.2.0/phonegap_connection_connection.md.html#connection.type
- http://davidbcalhoun.com/2010/using-navigator-connection-android
The second is specced at http://dev.w3.org/2009/dap/netinfo/ and perhaps landing in WebKit
- http://bugs.webkit.org/show_bug.cgi?id=73528
Unknown devices are assumed as fast
For more rigorous network testing, consider boomerang.js: http://github.com/bluesmoon/boomerang/
*/
Modernizr.addTest('lowbandwidth', function() {
// polyfill
var connection = navigator.connection || {type: 0};
return connection.type == 3 || // connection.CELL_2G
connection.type == 4 || // connection.CELL_3G
/^[23]g$/.test(connection.type); // string value in new spec
});
/*!
{
"name": "Server Sent Events",
"property": "eventsource",
"tags": ["network"],
"builderAliases": ["network_eventsource"],
"notes": [{
"name": "W3 Spec",
"href": "http://dev.w3.org/html5/eventsource/"
}]
}
!*/
/* DOC
Tests for server sent events aka eventsource.
*/
Modernizr.addTest('eventsource', 'EventSource' in window);
/*!
{
"name": "Fetch API",
"property": "fetch",
"tags": ["network"],
"caniuse": "fetch",
"notes": [{
"name": "Fetch Living Standard",
"href": "https://fetch.spec.whatwg.org/"
}],
"polyfills": ["fetch"]
}
!*/
/* DOC
Detects support for the fetch API, a modern replacement for XMLHttpRequest.
*/
Modernizr.addTest('fetch', 'fetch' in window);
/*!
{
"name": "XHR responseType",
"property": "xhrresponsetype",
"tags": ["network"],
"notes": [{
"name": "XMLHttpRequest Living Standard",
"href": "http://xhr.spec.whatwg.org/#the-responsetype-attribute"
}]
}
!*/
/* DOC
Tests for XMLHttpRequest xhr.responseType.
*/
Modernizr.addTest('xhrresponsetype', (function() {
if (typeof XMLHttpRequest == 'undefined') {
return false;
}
var xhr = new XMLHttpRequest();
xhr.open('get', '/', true);
return 'response' in xhr;
}()));
/*!
{
"name": "XML HTTP Request Level 2 XHR2",
"property": "xhr2",
"tags": ["network"],
"builderAliases": ["network_xhr2"],
"notes": [{
"name": "W3 Spec",
"href": "http://www.w3.org/TR/XMLHttpRequest2/"
},{
"name": "Details on Related Github Issue",
"href": "http://github.com/Modernizr/Modernizr/issues/385"
}]
}
!*/
/* DOC
Tests for XHR2.
*/
// all three of these details report consistently across all target browsers:
// !!(window.ProgressEvent);
// 'XMLHttpRequest' in window && 'withCredentials' in new XMLHttpRequest
Modernizr.addTest('xhr2', 'XMLHttpRequest' in window && 'withCredentials' in new XMLHttpRequest());
/*!
{
"authors": ["Cătălin Mariș"],
"name": "Speech Synthesis API",
"notes": [
{
"name": "W3C Web Speech API Specification - The SpeechSynthesis Interface",
"href": "https://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html#tts-section"
}
],
"property": "speechsynthesis",
"tags": ["input", "speech"]
}
!*/
Modernizr.addTest('speechsynthesis', 'SpeechSynthesisUtterance' in window);
/*!
{
"name": "Local Storage",
"property": "localstorage",
"caniuse": "namevalue-storage",
"tags": ["storage"],
"knownBugs": [],
"notes": [],
"warnings": [],
"polyfills": [
"joshuabell-polyfill",
"cupcake",
"storagepolyfill",
"amplifyjs",
"yui-cacheoffline"
]
}
!*/
// In FF4, if disabled, window.localStorage should === null.
// Normally, we could not test that directly and need to do a
// `('localStorage' in window) && ` test first because otherwise Firefox will
// throw bugzil.la/365772 if cookies are disabled
// Also in iOS5 Private Browsing mode, attempting to use localStorage.setItem
// will throw the exception:
// QUOTA_EXCEEDED_ERROR DOM Exception 22.
// Peculiarly, getItem and removeItem calls do not throw.
// Because we are forced to try/catch this, we'll go aggressive.
// Just FWIW: IE8 Compat mode supports these features completely:
// www.quirksmode.org/dom/html5.html
// But IE8 doesn't support either with local files
Modernizr.addTest('localstorage', function() {
var mod = 'modernizr';
try {
localStorage.setItem(mod, mod);
localStorage.removeItem(mod);
return true;
} catch (e) {
return false;
}
});
/*!
{
"name": "Session Storage",
"property": "sessionstorage",
"tags": ["storage"],
"polyfills": ["joshuabell-polyfill", "cupcake", "sessionstorage"]
}
!*/
// Because we are forced to try/catch this, we'll go aggressive.
// Just FWIW: IE8 Compat mode supports these features completely:
// www.quirksmode.org/dom/html5.html
// But IE8 doesn't support either with local files
Modernizr.addTest('sessionstorage', function() {
var mod = 'modernizr';
try {
sessionStorage.setItem(mod, mod);
sessionStorage.removeItem(mod);
return true;
} catch (e) {
return false;
}
});
/*!
{
"name": "Web SQL Database",
"property": "websqldatabase",
"caniuse": "sql-storage",
"tags": ["storage"]
}
!*/
// Chrome incognito mode used to throw an exception when using openDatabase
// It doesn't anymore.
Modernizr.addTest('websqldatabase', 'openDatabase' in window);
/*!
{
"name": "SVG filters",
"property": "svgfilters",
"caniuse": "svg-filters",
"tags": ["svg"],
"builderAliases": ["svg_filters"],
"authors": ["Erik Dahlstrom"],
"notes": [{
"name": "W3C Spec",
"href": "http://www.w3.org/TR/SVG11/filters.html"
}]
}
!*/
// Should fail in Safari: http://stackoverflow.com/questions/9739955/feature-detecting-support-for-svg-filters.
Modernizr.addTest('svgfilters', function() {
var result = false;
try {
result = 'SVGFEColorMatrixElement' in window &&
SVGFEColorMatrixElement.SVG_FECOLORMATRIX_TYPE_SATURATE == 2;
}
catch (e) {}
return result;
});
/*!
{
"name": "URL parser",
"property": "urlparser",
"notes": [{
"name": "URL",
"href": "https://dvcs.w3.org/hg/url/raw-file/tip/Overview.html"
}],
"polyfills": ["urlparser"],
"authors": ["Ron Waldon (@jokeyrhyme)"],
"tags": ["url"]
}
!*/
/* DOC
Check if browser implements the URL constructor for parsing URLs.
*/
Modernizr.addTest('urlparser', function() {
var url;
try {
// have to actually try use it, because Safari defines a dud constructor
url = new URL('http://modernizr.com/');
return url.href === 'http://modernizr.com/';
} catch (e) {
return false;
}
});
/*!
{
"name": "Binary WebSockets",
"property": "websocketsbinary",
"tags": ["websockets"],
"builderAliases": ["websockets_binary"]
}
!*/
// binaryType is truthy if there is support.. returns "blob" in new-ish chrome.
// plus.google.com/115535723976198353696/posts/ERN6zYozENV
// github.com/Modernizr/Modernizr/issues/370
Modernizr.addTest('websocketsbinary', function() {
var protocol = 'https:' == location.protocol ? 'wss' : 'ws',
protoBin;
if ('WebSocket' in window) {
if (protoBin = 'binaryType' in WebSocket.prototype) {
return protoBin;
}
try {
return !!(new WebSocket(protocol + '://.').binaryType);
} catch (e) {}
}
return false;
});
/*!
{
"name": "Base 64 encoding/decoding",
"property": ["atobbtoa"],
"builderAliases": ["atob-btoa"],
"caniuse" : "atob-btoa",
"tags": ["atob", "base64", "WindowBase64", "btoa"],
"authors": ["Christian Ulbrich"],
"notes": [{
"name": "WindowBase64",
"href": "http://www.w3.org/TR/html5/webappapis.html#windowbase64"
}, {
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/atob"
}],
"polyfills": ["base64js"]
}
!*/
/* DOC
Detects support for WindowBase64 API (window.atob && window.btoa).
*/
Modernizr.addTest('atobbtoa', 'atob' in window && 'btoa' in window, {aliases: ['atob-btoa']});
/*!
{
"name": "Framed window",
"property": "framed",
"tags": ["window"],
"builderAliases": ["window_framed"]
}
!*/
/* DOC
Tests if page is iframed.
*/
// github.com/Modernizr/Modernizr/issues/242
Modernizr.addTest('framed', window.location != top.location);
/*!
{
"name": "Shared Workers",
"property": "sharedworkers",
"caniuse" : "sharedworkers",
"tags": ["performance", "workers"],
"builderAliases": ["workers_sharedworkers"],
"notes": [{
"name": "W3C Reference",
"href": "http://www.w3.org/TR/workers/"
}]
}
!*/
/* DOC
Detects support for the `SharedWorker` API from the Web Workers spec.
*/
Modernizr.addTest('sharedworkers', 'SharedWorker' in window);
/*!
{
"name": "Web Workers",
"property": "webworkers",
"caniuse" : "webworkers",
"tags": ["performance", "workers"],
"notes": [{
"name": "W3C Reference",
"href": "http://www.w3.org/TR/workers/"
}, {
"name": "HTML5 Rocks article",
"href": "http://www.html5rocks.com/en/tutorials/workers/basics/"
}, {
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en-US/docs/Web/Guide/Performance/Using_web_workers"
}],
"polyfills": ["fakeworker", "html5shims"]
}
!*/
/* DOC
Detects support for the basic `Worker` API from the Web Workers spec. Web Workers provide a simple means for web content to run scripts in background threads.
*/
Modernizr.addTest('webworkers', 'Worker' in window);
/**
* List of property values to set for css tests. See ticket #21
* http://git.io/vUGl4
*
* @memberof Modernizr
* @name Modernizr._prefixes
* @optionName Modernizr._prefixes
* @optionProp prefixes
* @access public
* @example
*
* Modernizr._prefixes is the internal list of prefixes that we test against
* inside of things like [prefixed](#modernizr-prefixed) and [prefixedCSS](#-code-modernizr-prefixedcss). It is simply
* an array of kebab-case vendor prefixes you can use within your code.
*
* Some common use cases include
*
* Generating all possible prefixed version of a CSS property
* ```js
* var rule = Modernizr._prefixes.join('transform: rotate(20deg); ');
*
* rule === 'transform: rotate(20deg); webkit-transform: rotate(20deg); moz-transform: rotate(20deg); o-transform: rotate(20deg); ms-transform: rotate(20deg);'
* ```
*
* Generating all possible prefixed version of a CSS value
* ```js
* rule = 'display:' + Modernizr._prefixes.join('flex; display:') + 'flex';
*
* rule === 'display:flex; display:-webkit-flex; display:-moz-flex; display:-o-flex; display:-ms-flex; display:flex'
* ```
*/
var prefixes = (ModernizrProto._config.usePrefixes ? ' -webkit- -moz- -o- -ms- '.split(' ') : []);
// expose these for the plugin API. Look in the source for how to join() them against your input
ModernizrProto._prefixes = prefixes;
/**
* is returns a boolean if the typeof an obj is exactly type.
*
* @access private
* @function is
* @param {*} obj - A thing we want to check the type of
* @param {string} type - A string to compare the typeof against
* @returns {boolean}
*/
function is(obj, type) {
return typeof obj === type;
}
;
/**
* Run through all tests and detect their support in the current UA.
*
* @access private
*/
function testRunner() {
var featureNames;
var feature;
var aliasIdx;
var result;
var nameIdx;
var featureName;
var featureNameSplit;
for (var featureIdx in tests) {
if (tests.hasOwnProperty(featureIdx)) {
featureNames = [];
feature = tests[featureIdx];
// run the test, throw the return value into the Modernizr,
// then based on that boolean, define an appropriate className
// and push it into an array of classes we'll join later.
//
// If there is no name, it's an 'async' test that is run,
// but not directly added to the object. That should
// be done with a post-run addTest call.
if (feature.name) {
featureNames.push(feature.name.toLowerCase());
if (feature.options && feature.options.aliases && feature.options.aliases.length) {
// Add all the aliases into the names list
for (aliasIdx = 0; aliasIdx < feature.options.aliases.length; aliasIdx++) {
featureNames.push(feature.options.aliases[aliasIdx].toLowerCase());
}
}
}
// Run the test, or use the raw value if it's not a function
result = is(feature.fn, 'function') ? feature.fn() : feature.fn;
// Set each of the names on the Modernizr object
for (nameIdx = 0; nameIdx < featureNames.length; nameIdx++) {
featureName = featureNames[nameIdx];
// Support dot properties as sub tests. We don't do checking to make sure
// that the implied parent tests have been added. You must call them in
// order (either in the test, or make the parent test a dependency).
//
// Cap it to TWO to make the logic simple and because who needs that kind of subtesting
// hashtag famous last words
featureNameSplit = featureName.split('.');
if (featureNameSplit.length === 1) {
Modernizr[featureNameSplit[0]] = result;
} else {
// cast to a Boolean, if not one already
/* jshint -W053 */
if (Modernizr[featureNameSplit[0]] && !(Modernizr[featureNameSplit[0]] instanceof Boolean)) {
Modernizr[featureNameSplit[0]] = new Boolean(Modernizr[featureNameSplit[0]]);
}
Modernizr[featureNameSplit[0]][featureNameSplit[1]] = result;
}
classes.push((result ? '' : 'no-') + featureNameSplit.join('-'));
}
}
}
}
;
/*!
{
"name": "ES5 String.prototype.contains",
"property": "contains",
"authors": ["Robert Kowalski"],
"tags": ["es6"]
}
!*/
/* DOC
Check if browser implements ECMAScript 6 `String.prototype.contains` per specification.
*/
Modernizr.addTest('contains', is(String.prototype.contains, 'function'));
/**
* docElement is a convenience wrapper to grab the root element of the document
*
* @access private
* @returns {HTMLElement|SVGElement} The root element of the document
*/
var docElement = document.documentElement;
/*!
{
"name": "Context menus",
"property": "contextmenu",
"caniuse": "menu",
"notes": [{
"name": "W3C spec",
"href": "http://www.w3.org/TR/html5/interactive-elements.html#context-menus"
},{
"name": "thewebrocks.com Demo",
"href": "http://thewebrocks.com/demos/context-menu/"
}],
"polyfills": ["jquery-contextmenu"]
}
!*/
/* DOC
Detects support for custom context menus.
*/
Modernizr.addTest(
'contextmenu',
('contextMenu' in docElement && 'HTMLMenuItemElement' in window)
);
/*!
{
"name": "cssall",
"property": "cssall",
"notes": [{
"name": "Spec",
"href": "http://dev.w3.org/csswg/css-cascade/#all-shorthand"
}]
}
!*/
/* DOC
Detects support for the `all` css property, which is a shorthand to reset all css properties (except direction and unicode-bidi) to their original value
*/
Modernizr.addTest('cssall', 'all' in docElement.style);
/*!
{
"name": "will-change",
"property": "willchange",
"notes": [{
"name": "Spec",
"href": "http://tabatkins.github.io/specs/css-will-change/"
}]
}
!*/
/* DOC
Detects support for the `will-change` css property, which formally signals to the
browser that an element will be animating.
*/
Modernizr.addTest('willchange', 'willChange' in docElement.style);
/*!
{
"name": "classList",
"caniuse": "classlist",
"property": "classlist",
"tags": ["dom"],
"builderAliases": ["dataview_api"],
"notes": [{
"name": "MDN Docs",
"href": "https://developer.mozilla.org/en/DOM/element.classList"
}]
}
!*/
Modernizr.addTest('classlist', 'classList' in docElement);
/*!
{
"name": "Document Fragment",
"property": "documentfragment",
"notes": [{
"name": "W3C DOM Level 1 Reference",
"href": "http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-B63ED1A3"
}, {
"name": "SitePoint Reference",
"href": "http://reference.sitepoint.com/javascript/DocumentFragment"
}, {
"name": "QuirksMode Compatibility Tables",
"href": "http://www.quirksmode.org/m/w3c_core.html#t112"
}],
"authors": ["Ron Waldon (@jokeyrhyme)"],
"knownBugs": ["false-positive on Blackberry 9500, see QuirksMode note"],
"tags": []
}
!*/
/* DOC
Append multiple elements to the DOM within a single insertion.
*/
Modernizr.addTest('documentfragment', function() {
return 'createDocumentFragment' in document &&
'appendChild' in docElement;
});
/**
* A convenience helper to check if the document we are running in is an SVG document
*
* @access private
* @returns {boolean}
*/
var isSVG = docElement.nodeName.toLowerCase() === 'svg';
/**
* setClasses takes an array of class names and adds them to the root element
*
* @access private
* @function setClasses
* @param {string[]} classes - Array of class names
*/
// Pass in an and array of class names, e.g.:
// ['no-webp', 'borderradius', ...]
function setClasses(classes) {
var className = docElement.className;
var classPrefix = Modernizr._config.classPrefix || '';
if (isSVG) {
className = className.baseVal;
}
// Change `no-js` to `js` (independently of the `enableClasses` option)
// Handle classPrefix on this too
if (Modernizr._config.enableJSClass) {
var reJS = new RegExp('(^|\\s)' + classPrefix + 'no-js(\\s|$)');
className = className.replace(reJS, '$1' + classPrefix + 'js$2');
}
if (Modernizr._config.enableClasses) {
// Add the new classes
className += ' ' + classPrefix + classes.join(' ' + classPrefix);
isSVG ? docElement.className.baseVal = className : docElement.className = className;
}
}
;
/**
* @optionName html5shiv
* @optionProp html5shiv
*/
// Take the html5 variable out of the html5shiv scope so we can return it.
var html5;
if (!isSVG) {
/**
* @preserve HTML5 Shiv 3.7.3 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
*/
;(function(window, document) {
/*jshint evil:true */
/** version */
var version = '3.7.3';
/** Preset options */
var options = window.html5 || {};
/** Used to skip problem elements */
var reSkip = /^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i;
/** Not all elements can be cloned in IE **/
var saveClones = /^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i;
/** Detect whether the browser supports default html5 styles */
var supportsHtml5Styles;
/** Name of the expando, to work with multiple documents or to re-shiv one document */
var expando = '_html5shiv';
/** The id for the the documents expando */
var expanID = 0;
/** Cached data for each document */
var expandoData = {};
/** Detect whether the browser supports unknown elements */
var supportsUnknownElements;
(function() {
try {
var a = document.createElement('a');
a.innerHTML = '<xyz></xyz>';
//if the hidden property is implemented we can assume, that the browser supports basic HTML5 Styles
supportsHtml5Styles = ('hidden' in a);
supportsUnknownElements = a.childNodes.length == 1 || (function() {
// assign a false positive if unable to shiv
(document.createElement)('a');
var frag = document.createDocumentFragment();
return (
typeof frag.cloneNode == 'undefined' ||
typeof frag.createDocumentFragment == 'undefined' ||
typeof frag.createElement == 'undefined'
);
}());
} catch(e) {
// assign a false positive if detection fails => unable to shiv
supportsHtml5Styles = true;
supportsUnknownElements = true;
}
}());
/*--------------------------------------------------------------------------*/
/**
* Creates a style sheet with the given CSS text and adds it to the document.
* @private
* @param {Document} ownerDocument The document.
* @param {String} cssText The CSS text.
* @returns {StyleSheet} The style element.
*/
function addStyleSheet(ownerDocument, cssText) {
var p = ownerDocument.createElement('p'),
parent = ownerDocument.getElementsByTagName('head')[0] || ownerDocument.documentElement;
p.innerHTML = 'x<style>' + cssText + '</style>';
return parent.insertBefore(p.lastChild, parent.firstChild);
}
/**
* Returns the value of `html5.elements` as an array.
* @private
* @returns {Array} An array of shived element node names.
*/
function getElements() {
var elements = html5.elements;
return typeof elements == 'string' ? elements.split(' ') : elements;
}
/**
* Extends the built-in list of html5 elements
* @memberOf html5
* @param {String|Array} newElements whitespace separated list or array of new element names to shiv
* @param {Document} ownerDocument The context document.
*/
function addEleme
|
ents, ownerDocument) {
var elements = html5.elements;
if(typeof elements != 'string'){
elements = elements.join(' ');
}
if(typeof newElements != 'string'){
newElements = newElements.join(' ');
}
html5.elements = elements +' '+ newElements;
shivDocument(ownerDocument);
}
/**
* Returns the data associated to the given document
* @private
* @param {Document} ownerDocument The document.
* @returns {Object} An object of data.
*/
function getExpandoData(ownerDocument) {
var data = expandoData[ownerDocument[expando]];
if (!data) {
data = {};
expanID++;
ownerDocument[expando] = expanID;
expandoData[expanID] = data;
}
return data;
}
/**
* returns a shived element for the given nodeName and document
* @memberOf html5
* @param {String} nodeName name of the element
* @param {Document|DocumentFragment} ownerDocument The context document.
* @returns {Object} The shived element.
*/
function createElement(nodeName, ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createElement(nodeName);
}
if (!data) {
data = getExpandoData(ownerDocument);
}
var node;
if (data.cache[nodeName]) {
node = data.cache[nodeName].cloneNode();
} else if (saveClones.test(nodeName)) {
node = (data.cache[nodeName] = data.createElem(nodeName)).cloneNode();
} else {
node = data.createElem(nodeName);
}
// Avoid adding some elements to fragments in IE < 9 because
// * Attributes like `name` or `type` cannot be set/changed once an element
// is inserted into a document/fragment
// * Link elements with `src` attributes that are inaccessible, as with
// a 403 response, will cause the tab/window to crash
// * Script elements appended to fragments will execute when their `src`
// or `text` property is set
return node.canHaveChildren && !reSkip.test(nodeName) && !node.tagUrn ? data.frag.appendChild(node) : node;
}
/**
* returns a shived DocumentFragment for the given document
* @memberOf html5
* @param {Document} ownerDocument The context document.
* @returns {Object} The shived DocumentFragment.
*/
function createDocumentFragment(ownerDocument, data){
if (!ownerDocument) {
ownerDocument = document;
}
if(supportsUnknownElements){
return ownerDocument.createDocumentFragment();
}
data = data || getExpandoData(ownerDocument);
var clone = data.frag.cloneNode(),
i = 0,
elems = getElements(),
l = elems.length;
for(;i<l;i++){
clone.createElement(elems[i]);
}
return clone;
}
/**
* Shivs the `createElement` and `createDocumentFragment` methods of the document.
* @private
* @param {Document|DocumentFragment} ownerDocument The document.
* @param {Object} data of the document.
*/
function shivMethods(ownerDocument, data) {
if (!data.cache) {
data.cache = {};
data.createElem = ownerDocument.createElement;
data.createFrag = ownerDocument.createDocumentFragment;
data.frag = data.createFrag();
}
ownerDocument.createElement = function(nodeName) {
//abort shiv
if (!html5.shivMethods) {
return data.createElem(nodeName);
}
return createElement(nodeName, ownerDocument, data);
};
ownerDocument.createDocumentFragment = Function('h,f', 'return function(){' +
'var n=f.cloneNode(),c=n.createElement;' +
'h.shivMethods&&(' +
// unroll the `createElement` calls
getElements().join().replace(/[\w\-:]+/g, function(nodeName) {
data.createElem(nodeName);
data.frag.createElement(nodeName);
return 'c("' + nodeName + '")';
}) +
');return n}'
)(html5, data.frag);
}
/*--------------------------------------------------------------------------*/
/**
* Shivs the given document.
* @memberOf html5
* @param {Document} ownerDocument The document to shiv.
* @returns {Document} The shived document.
*/
function shivDocument(ownerDocument) {
if (!ownerDocument) {
ownerDocument = document;
}
var data = getExpandoData(ownerDocument);
if (html5.shivCSS && !supportsHtml5Styles && !data.hasCSS) {
data.hasCSS = !!addStyleSheet(ownerDocument,
// corrects block display not defined in IE6/7/8/9
'article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}' +
// adds styling not present in IE6/7/8/9
'mark{background:#FF0;color:#000}' +
// hides non-rendered elements
'template{display:none}'
);
}
if (!supportsUnknownElements) {
shivMethods(ownerDocument, data);
}
return ownerDocument;
}
/*--------------------------------------------------------------------------*/
/**
* The `html5` object is exposed so that more elements can be shived and
* existing shiving can be detected on iframes.
* @type Object
* @example
*
* // options can be changed before the script is included
* html5 = { 'elements': 'mark section', 'shivCSS': false, 'shivMethods': false };
*/
var html5 = {
/**
* An array or space separated string of node names of the elements to shiv.
* @memberOf html5
* @type Array|String
*/
'elements': options.elements || 'abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output picture progress section summary template time video',
/**
* current version of html5shiv
*/
'version': version,
/**
* A flag to indicate that the HTML5 style sheet should be inserted.
* @memberOf html5
* @type Boolean
*/
'shivCSS': (options.shivCSS !== false),
/**
* Is equal to true if a browser supports creating unknown/HTML5 elements
* @memberOf html5
* @type boolean
*/
'supportsUnknownElements': supportsUnknownElements,
/**
* A flag to indicate that the document's `createElement` and `createDocumentFragment`
* methods should be overwritten.
* @memberOf html5
* @type Boolean
*/
'shivMethods': (options.shivMethods !== false),
/**
* A string to describe the type of `html5` object ("default" or "default print").
* @memberOf html5
* @type String
*/
'type': 'default',
// shivs the document according to the specified `html5` object options
'shivDocument': shivDocument,
//creates a shived element
createElement: createElement,
//creates a shived documentFragment
createDocumentFragment: createDocumentFragment,
//extends list of elements
addElements: addElements
};
/*--------------------------------------------------------------------------*/
// expose html5
window.html5 = html5;
// shiv the document
shivDocument(document);
if(typeof module == 'object' && module.exports){
module.exports = html5;
}
}(typeof window !== "undefined" ? window : this, document));
}
;
/**
* If the browsers follow the spec, then they would expose vendor-specific style as:
* elem.style.WebkitBorderRadius
* instead of something like the following, which would be technically incorrect:
* elem.style.webkitBorderRadius
* Webkit ghosts their properties in lowercase but Opera & Moz do not.
* Microsoft uses a lowercase `ms` instead of the correct `Ms` in IE8+
* erik.eae.net/archives/2008/03/10/21.48.10/
* More here: github.com/Modernizr/Modernizr/issues/issue/21
*
* @access private
* @returns {string} The string representing the vendor-specific style properties
*/
var omPrefixes = 'Moz O ms Webkit';
/**
* List of JavaScript DOM values used for tests
*
* @memberof Modernizr
* @name Modernizr._domPrefixes
* @optionName Modernizr._domPrefixes
* @optionProp domPrefixes
* @access public
* @example
*
* Modernizr._domPrefixes is exactly the same as [_prefixes](#modernizr-_prefixes), but rather
* than kebab-case properties, all properties are their Capitalized variant
*
* ```js
* Modernizr._domPrefixes === [ "Moz", "O", "ms", "Webkit" ];
* ```
*/
var domPrefixes = (ModernizrProto._config.usePrefixes ? omPrefixes.toLowerCase().split(' ') : []);
ModernizrProto._domPrefixes = domPrefixes;
/**
* hasOwnProp is a shim for hasOwnProperty that is needed for Safari 2.0 support
*
* @author kangax
* @access private
* @function hasOwnProp
* @param {object} object - The object to check for a property
* @param {string} property - The property to check for
* @returns {boolean}
*/
// hasOwnProperty shim by kangax needed for Safari 2.0 support
var hasOwnProp;
(function() {
var _hasOwnProperty = ({}).hasOwnProperty;
/* istanbul ignore else */
/* we have no way of testing IE 5.5 or safari 2,
* so just assume the else gets hit */
if (!is(_hasOwnProperty, 'undefined') && !is(_hasOwnProperty.call, 'undefined')) {
hasOwnProp = function(object, property) {
return _hasOwnProperty.call(object, property);
};
}
else {
hasOwnProp = function(object, property) { /* yes, this can give false positives/negatives, but most of the time we don't care about those */
return ((property in object) && is(object.constructor.prototype[property], 'undefined'));
};
}
})();
// _l tracks listeners for async tests, as well as tests that execute after the initial run
ModernizrProto._l = {};
/**
* Modernizr.on is a way to listen for the completion of async tests. Being
* asynchronous, they may not finish before your scripts run. As a result you
* will get a possibly false negative `undefined` value.
*
* @memberof Modernizr
* @name Modernizr.on
* @access public
* @function on
* @param {string} feature - String name of the feature detect
* @param {function} cb - Callback function returning a Boolean - true if feature is supported, false if not
* @example
*
* ```js
* Modernizr.on('flash', function( result ) {
* if (result) {
* // the browser has flash
* } else {
* // the browser does not have flash
* }
* });
* ```
*/
ModernizrProto.on = function(feature, cb) {
// Create the list of listeners if it doesn't exist
if (!this._l[feature]) {
this._l[feature] = [];
}
// Push this test on to the listener list
this._l[feature].push(cb);
// If it's already been resolved, trigger it on next tick
if (Modernizr.hasOwnProperty(feature)) {
// Next Tick
setTimeout(function() {
Modernizr._trigger(feature, Modernizr[feature]);
}, 0);
}
};
/**
* _trigger is the private function used to signal test completion and run any
* callbacks registered through [Modernizr.on](#modernizr-on)
*
* @memberof Modernizr
* @name Modernizr._trigger
* @access private
* @function _trigger
* @param {string} feature - string name of the feature detect
* @param {function|boolean} [res] - A feature detection function, or the boolean =
* result of a feature detection function
*/
ModernizrProto._trigger = function(feature, res) {
if (!this._l[feature]) {
return;
}
var cbs = this._l[feature];
// Force async
setTimeout(function() {
var i, cb;
for (i = 0; i < cbs.length; i++) {
cb = cbs[i];
cb(res);
}
}, 0);
// Don't trigger these again
delete this._l[feature];
};
/**
* addTest allows you to define your own feature detects that are not currently
* included in Modernizr (under the covers it's the exact same code Modernizr
* uses for its own [feature detections](https://github.com/Modernizr/Modernizr/tree/master/feature-detects)). Just like the offical detects, the result
* will be added onto the Modernizr object, as well as an appropriate className set on
* the html element when configured to do so
*
* @memberof Modernizr
* @name Modernizr.addTest
* @optionName Modernizr.addTest()
* @optionProp addTest
* @access public
* @function addTest
* @param {string|object} feature - The string name of the feature detect, or an
* object of feature detect names and test
* @param {function|boolean} test - Function returning true if feature is supported,
* false if not. Otherwise a boolean representing the results of a feature detection
* @example
*
* The most common way of creating your own feature detects is by calling
* `Modernizr.addTest` with a string (preferably just lowercase, without any
* punctuation), and a function you want executed that will return a boolean result
*
* ```js
* Modernizr.addTest('itsTuesday', function() {
* var d = new Date();
* return d.getDay() === 2;
* });
* ```
*
* When the above is run, it will set Modernizr.itstuesday to `true` when it is tuesday,
* and to `false` every other day of the week. One thing to notice is that the names of
* feature detect functions are always lowercased when added to the Modernizr object. That
* means that `Modernizr.itsTuesday` will not exist, but `Modernizr.itstuesday` will.
*
*
* Since we only look at the returned value from any feature detection function,
* you do not need to actually use a function. For simple detections, just passing
* in a statement that will return a boolean value works just fine.
*
* ```js
* Modernizr.addTest('hasJquery', 'jQuery' in window);
* ```
*
* Just like before, when the above runs `Modernizr.hasjquery` will be true if
* jQuery has been included on the page. Not using a function saves a small amount
* of overhead for the browser, as well as making your code much more readable.
*
* Finally, you also have the ability to pass in an object of feature names and
* their tests. This is handy if you want to add multiple detections in one go.
* The keys should always be a string, and the value can be either a boolean or
* function that returns a boolean.
*
* ```js
* var detects = {
* 'hasjquery': 'jQuery' in window,
* 'itstuesday': function() {
* var d = new Date();
* return d.getDay() === 2;
* }
* }
*
* Modernizr.addTest(detects);
* ```
*
* There is really no difference between the first methods and this one, it is
* just a convenience to let you write more readable code.
*/
function addTest(feature, test) {
if (typeof feature == 'object') {
for (var key in feature) {
if (hasOwnProp(feature, key)) {
addTest(key, feature[ key ]);
}
}
} else {
feature = feature.toLowerCase();
var featureNameSplit = feature.split('.');
var last = Modernizr[featureNameSplit[0]];
// Again, we don't check for parent test existence. Get that right, though.
if (featureNameSplit.length == 2) {
last = last[featureNameSplit[1]];
}
if (typeof last != 'undefined') {
// we're going to quit if you're trying to overwrite an existing test
// if we were to allow it, we'd do this:
// var re = new RegExp("\\b(no-)?" + feature + "\\b");
// docElement.className = docElement.className.replace( re, '' );
// but, no rly, stuff 'em.
return Modernizr;
}
test = typeof test == 'function' ? test() : test;
// Set the value (this is the magic, right here).
if (featureNameSplit.length == 1) {
Modernizr[featureNameSplit[0]] = test;
} else {
// cast to a Boolean, if not one already
/* jshint -W053 */
if (Modernizr[featureNameSplit[0]] && !(Modernizr[featureNameSplit[0]] instanceof Boolean)) {
Modernizr[featureNameSplit[0]] = new Boolean(Modernizr[featureNameSplit[0]]);
}
Modernizr[featureNameSplit[0]][featureNameSplit[1]] = test;
}
// Set a single class (either `feature` or `no-feature`)
/* jshint -W041 */
setClasses([(!!test && test != false ? '' : 'no-') + featureNameSplit.join('-')]);
/* jshint +W041 */
// Trigger the event
Modernizr._trigger(feature, test);
}
return Modernizr; // allow chaining.
}
// After all the tests are run, add self to the Modernizr prototype
Modernizr._q.push(function() {
ModernizrProto.addTest = addTest;
});
/*!
{
"name": "EXIF Orientation",
"property": "exiforientation",
"tags": ["image"],
"builderAliases": ["exif_orientation"],
"async": true,
"authors": ["Paul Sayre"],
"notes": [{
"name": "Article by Dave Perrett",
"href": "http://recursive-design.com/blog/2012/07/28/exif-orientation-handling-is-a-ghetto/"
},{
"name": "Article by Calvin Hass",
"href": "http://www.impulseadventure.com/photo/exif-orientation.html"
}]
}
!*/
/* DOC
Detects support for EXIF Orientation in JPEG images.
iOS looks at the EXIF Orientation flag in JPEGs and rotates the image accordingly. Most desktop browsers just ignore this data.
*/
// Bug trackers:
// bugzil.la/298619 (unimplemented)
// crbug.com/56845 (looks incomplete)
// webk.it/19688 (available upstream but its up all ports to turn on individually)
Modernizr.addAsyncTest(function() {
var img = new Image();
img.onerror = function() {
addTest('exiforientation', false, {aliases: ['exif-orientation']});
};
img.onload = function() {
addTest('exiforientation', img.width !== 2, {aliases: ['exif-orientation']});
};
// There may be a way to shrink this more, it's a 1x2 white jpg with the orientation flag set to 6
img.src = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QAiRXhpZgAASUkqAAgAAAABABIBAwABAAAABgASAAAAAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAABAAIDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD+/iiiigD/2Q==';
});
/*!
{
"authors": ["Cătălin Mariș"],
"caniuse": "proximity",
"name": "Proximity API",
"notes": [{
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en-US/docs/Web/API/Proximity_Events"
},{
"name": "W3C specification",
"href": "http://www.w3.org/TR/proximity/"
}],
"property": "proximity",
"tags": ["events", "proximity"]
}
!*/
/* DOC
Detects support for an API that allows users to get proximity related information from the device's proximity sensor.
*/
Modernizr.addAsyncTest(function() {
var timeout;
var timeoutTime = 300;
function advertiseSupport() {
// Clean up after ourselves
clearTimeout(timeout);
window.removeEventListener('deviceproximity', advertiseSupport);
// Advertise support as the browser supports
// the API and the device has a proximity sensor
addTest('proximity', true);
}
// Check if the browser has support for the API
if ('ondeviceproximity' in window && 'onuserproximity' in window) {
// Check if the device has a proximity sensor
// ( devices without such a sensor support the events but
// will never fire them resulting in a false positive )
window.addEventListener('deviceproximity', advertiseSupport);
// If the event doesn't fire in a reasonable amount of time,
// it means that the device doesn't have a proximity sensor,
// thus, we can advertise the "lack" of support
timeout = setTimeout(function() {
window.removeEventListener('deviceproximity', advertiseSupport);
addTest('proximity', false);
}, timeoutTime);
} else {
addTest('proximity', false);
}
});
/*!
{
"name": "JPEG 2000",
"async": true,
"aliases": ["jpeg-2000", "jpg2"],
"property": "jpeg2000",
"tags": ["image"],
"authors": ["@eric_wvgg"],
"notes": [{
"name": "Wikipedia Article",
"href": "http://en.wikipedia.org/wiki/JPEG_2000"
}]
}
!*/
/* DOC
Test for JPEG 2000 support
*/
Modernizr.addAsyncTest(function() {
var image = new Image();
image.onload = image.onerror = function() {
addTest('jpeg2000', image.width == 1);
};
image.src = 'data:image/jp2;base64,/0//UQAyAAAAAAABAAAAAgAAAAAAAAAAAAAABAAAAAQAAAAAAAAAAAAEBwEBBwEBBwEBBwEB/1IADAAAAAEAAAQEAAH/XAAEQED/ZAAlAAFDcmVhdGVkIGJ5IE9wZW5KUEVHIHZlcnNpb24gMi4wLjD/kAAKAAAAAABYAAH/UwAJAQAABAQAAf9dAAUBQED/UwAJAgAABAQAAf9dAAUCQED/UwAJAwAABAQAAf9dAAUDQED/k8+kEAGvz6QQAa/PpBABr994EAk//9k=';
});
/*!
{
"name": "JPEG XR (extended range)",
"async": true,
"aliases": ["jpeg-xr"],
"property": "jpegxr",
"tags": ["image"],
"notes": [{
"name": "Wikipedia Article",
"href": "http://en.wikipedia.org/wiki/JPEG_XR"
}]
}
!*/
/* DOC
Test for JPEG XR support
*/
Modernizr.addAsyncTest(function() {
var image = new Image();
image.onload = image.onerror = function() {
addTest('jpegxr', image.width == 1, {aliases: ['jpeg-xr']});
};
image.src = 'data:image/vnd.ms-photo;base64,SUm8AQgAAAAFAAG8AQAQAAAASgAAAIC8BAABAAAAAQAAAIG8BAABAAAAAQAAAMC8BAABAAAAWgAAAMG8BAABAAAAHwAAAAAAAAAkw91vA07+S7GFPXd2jckNV01QSE9UTwAZAYBxAAAAABP/gAAEb/8AAQAAAQAAAA==';
});
/*!
{
"name": "Webp Alpha",
"async": true,
"property": "webpalpha",
"aliases": ["webp-alpha"],
"tags": ["image"],
"authors": ["Krister Kari", "Rich Bradshaw", "Ryan Seddon", "Paul Irish"],
"notes": [{
"name": "WebP Info",
"href": "http://code.google.com/speed/webp/"
},{
"name": "Article about WebP support on Android browsers",
"href": "http://www.wope-framework.com/en/2013/06/24/webp-support-on-android-browsers/"
},{
"name": "Chromium WebP announcement",
"href": "http://blog.chromium.org/2011/11/lossless-and-transparency-encoding-in.html?m=1"
}]
}
!*/
/* DOC
Tests for transparent webp support.
*/
Modernizr.addAsyncTest(function() {
var image = new Image();
image.onerror = function() {
addTest('webpalpha', false, {aliases: ['webp-alpha']});
};
image.onload = function() {
addTest('webpalpha', image.width == 1, {aliases: ['webp-alpha']});
};
image.src = 'data:image/webp;base64,UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAABBxAR/Q9ERP8DAABWUDggGAAAADABAJ0BKgEAAQADADQlpAADcAD++/1QAA==';
});
/*!
{
"name": "Webp Animation",
"async": true,
"property": "webpanimation",
"aliases": ["webp-animation"],
"tags": ["image"],
"authors": ["Krister Kari", "Rich Bradshaw", "Ryan Seddon", "Paul Irish"],
"notes": [{
"name": "WebP Info",
"href": "http://code.google.com/speed/webp/"
},{
"name": "Chromium blog - Chrome 32 Beta: Animated WebP images and faster Chrome for Android touch input",
"href": "http://blog.chromium.org/2013/11/chrome-32-beta-animated-webp-images-and.html"
}]
}
!*/
/* DOC
Tests for animated webp support.
*/
Modernizr.addAsyncTest(function() {
var image = new Image();
image.onerror = function() {
addTest('webpanimation', false, {aliases: ['webp-animation']});
};
image.onload = function() {
addTest('webpanimation', image.width == 1, {aliases: ['webp-animation']});
};
image.src = 'data:image/webp;base64,UklGRlIAAABXRUJQVlA4WAoAAAASAAAAAAAAAAAAQU5JTQYAAAD/////AABBTk1GJgAAAAAAAAAAAAAAAAAAAGQAAABWUDhMDQAAAC8AAAAQBxAREYiI/gcA';
});
/*!
{
"name": "Webp Lossless",
"async": true,
"property": ["webplossless", "webp-lossless"],
"tags": ["image"],
"authors": ["@amandeep", "Rich Bradshaw", "Ryan Seddon", "Paul Irish"],
"notes": [{
"name": "Webp Info",
"href": "http://code.google.com/speed/webp/"
},{
"name": "Webp Lossless Spec",
"href": "https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification"
}]
}
!*/
/* DOC
Tests for non-alpha lossless webp support.
*/
Modernizr.addAsyncTest(function() {
var image = new Image();
image.onerror = function() {
addTest('webplossless', false, {aliases: ['webp-lossless']});
};
image.onload = function() {
addTest('webplossless', image.width == 1, {aliases: ['webp-lossless']});
};
image.src = 'data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA=';
});
/*!
{
"name": "Webp",
"async": true,
"property": "webp",
"tags": ["image"],
"builderAliases": ["img_webp"],
"authors": ["Krister Kari", "@amandeep", "Rich Bradshaw", "Ryan Seddon", "Paul Irish"],
"notes": [{
"name": "Webp Info",
"href": "http://code.google.com/speed/webp/"
}, {
"name": "Chormium blog - Chrome 32 Beta: Animated WebP images and faster Chrome for Android touch input",
"href": "http://blog.chromium.org/2013/11/chrome-32-beta-animated-webp-images-and.html"
}, {
"name": "Webp Lossless Spec",
"href": "https://developers.google.com/speed/webp/docs/webp_lossless_bitstream_specification"
}, {
"name": "Article about WebP support on Android browsers",
"href": "http://www.wope-framework.com/en/2013/06/24/webp-support-on-android-browsers/"
}, {
"name": "Chormium WebP announcement",
"href": "http://blog.chromium.org/2011/11/lossless-and-transparency-encoding-in.html?m=1"
}]
}
!*/
/* DOC
Tests for lossy, non-alpha webp support.
Tests for all forms of webp support (lossless, lossy, alpha, and animated)..
Modernizr.webp // Basic support (lossy)
Modernizr.webp.lossless // Lossless
Modernizr.webp.alpha // Alpha (both lossy and lossless)
Modernizr.webp.animation // Animated WebP
*/
Modernizr.addAsyncTest(function() {
var webpTests = [{
'uri': 'data:image/webp;base64,UklGRiQAAABXRUJQVlA4IBgAAAAwAQCdASoBAAEAAwA0JaQAA3AA/vuUAAA=',
'name': 'webp'
}, {
'uri': 'data:image/webp;base64,UklGRkoAAABXRUJQVlA4WAoAAAAQAAAAAAAAAAAAQUxQSAwAAAABBxAR/Q9ERP8DAABWUDggGAAAADABAJ0BKgEAAQADADQlpAADcAD++/1QAA==',
'name': 'webp.alpha'
}, {
'uri': 'data:image/webp;base64,UklGRlIAAABXRUJQVlA4WAoAAAASAAAAAAAAAAAAQU5JTQYAAAD/////AABBTk1GJgAAAAAAAAAAAAAAAAAAAGQAAABWUDhMDQAAAC8AAAAQBxAREYiI/gcA',
'name': 'webp.animation'
}, {
'uri': 'data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA=',
'name': 'webp.lossless'
}];
var webp = webpTests.shift();
function test(name, uri, cb) {
var image = new Image();
function addResult(event) {
// if the event is from 'onload', check the see if the image's width is
// 1 pixel (which indiciates support). otherwise, it fails
var result = event && event.type === 'load' ? image.width == 1 : false;
var baseTest = name === 'webp';
/* jshint -W053 */
addTest(name, baseTest ? new Boolean(result) : result);
if (cb) {
cb(event);
}
}
image.onerror = addResult;
image.onload = addResult;
image.src = uri;
}
// test for webp support in general
test(webp.name, webp.uri, function(e) {
// if the webp test loaded, test everything else.
if (e && e.type === 'load') {
for (var i = 0; i < webpTests.length; i++) {
test(webpTests[i].name, webpTests[i].uri);
}
}
});
});
/*!
{
"name": "SVG as an <img> tag source",
"property": "svgasimg",
"caniuse" : "svg-img",
"tags": ["svg"],
"authors": ["Chris Coyier"],
"notes": [{
"name": "HTML5 Spec",
"href": "http://www.w3.org/TR/html5/embedded-content-0.html#the-img-element"
}]
}
!*/
// Original Async test by Stu Cox
// https://gist.github.com/chriscoyier/8774501
// Now a Sync test based on good results here
// http://codepen.io/chriscoyier/pen/bADFx
// Note http://www.w3.org/TR/SVG11/feature#Image is *supposed* to represent
// support for the `<image>` tag in SVG, not an SVG file linked from an `<img>`
// tag in HTML – but it’s a heuristic which works
Modernizr.addTest('svgasimg', document.implementation.hasFeature('http://www.w3.org/TR/SVG11/feature#Image', '1.1'));
/*!
{
"name": "Data URI",
"property": "datauri",
"caniuse": "datauri",
"tags": ["url"],
"builderAliases": ["url_data_uri"],
"async": true,
"notes": [{
"name": "Wikipedia article",
"href": "http://en.wikipedia.org/wiki/Data_URI_scheme"
}],
"warnings": ["Support in Internet Explorer 8 is limited to images and linked resources like CSS files, not HTML files"]
}
!*/
/* DOC
Detects support for data URIs. Provides a subproperty to report support for data URIs over 32kb in size:
```javascript
Modernizr.datauri // true
Modernizr.datauri.over32kb // false in IE8
```
*/
// https://github.com/Modernizr/Modernizr/issues/14
Modernizr.addAsyncTest(function() {
/* jshint -W053 */
// IE7 throw a mixed content warning on HTTPS for this test, so we'll
// just blacklist it (we know it doesn't support data URIs anyway)
// https://github.com/Modernizr/Modernizr/issues/362
if (navigator.userAgent.indexOf('MSIE 7.') !== -1) {
// Keep the test async
setTimeout(function() {
addTest('datauri', false);
}, 10);
}
var datauri = new Image();
datauri.onerror = function() {
addTest('datauri', false);
};
datauri.onload = function() {
if (datauri.width == 1 && datauri.height == 1) {
testOver32kb();
}
else {
addTest('datauri', false);
}
};
datauri.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
// Once we have datauri, let's check to see if we can use data URIs over
// 32kb (IE8 can't). https://github.com/Modernizr/Modernizr/issues/321
function testOver32kb() {
var datauriBig = new Image();
datauriBig.onerror = function() {
addTest('datauri', true);
Modernizr.datauri = new Boolean(true);
Modernizr.datauri.over32kb = false;
};
datauriBig.onload = function() {
addTest('datauri', true);
Modernizr.datauri = new Boolean(true);
Modernizr.datauri.over32kb = (datauriBig.width == 1 && datauriBig.height == 1);
};
var base64str = 'R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
while (base64str.length < 33000) {
base64str = '\r\n' + base64str;
}
datauriBig.src = 'data:image/gif;base64,' + base64str;
}
});
/*!
{
"name": "Workers from Blob URIs",
"property": "blobworkers",
"tags": ["performance", "workers"],
"builderAliases": ["workers_blobworkers"],
"notes": [{
"name": "W3C Reference",
"href": "http://www.w3.org/TR/workers/"
}],
"knownBugs": ["This test may output garbage to console."],
"authors": ["Jussi Kalliokoski"],
"async": true
}
!*/
/* DOC
Detects support for creating Web Workers from Blob URIs.
*/
Modernizr.addAsyncTest(function() {
try {
// we're avoiding using Modernizr._domPrefixes as the prefix capitalization on
// these guys are notoriously peculiar.
var BlobBuilder = window.BlobBuilder;
var URL = window.URL;
if (Modernizr._config.usePrefix) {
BlobBuilder = BlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder || window.OBlobBuilder;
URL = URL || window.MozURL || window.webkitURL || window.MSURL || window.OURL;
}
var data = 'Modernizr',
blob,
bb,
worker,
url,
timeout,
scriptText = 'this.onmessage=function(e){postMessage(e.data)}';
try {
blob = new Blob([scriptText], {type: 'text/javascript'});
} catch (e) {
// we'll fall back to the deprecated BlobBuilder
}
if (!blob) {
bb = new BlobBuilder();
bb.append(scriptText);
blob = bb.getBlob();
}
url = URL.createObjectURL(blob);
worker = new Worker(url);
worker.onmessage = function(e) {
addTest('blobworkers', data === e.data);
cleanup();
};
// Just in case...
worker.onerror = fail;
timeout = setTimeout(fail, 200);
worker.postMessage(data);
} catch (e) {
fail();
}
function fail() {
addTest('blobworkers', false);
cleanup();
}
function cleanup() {
if (url) {
URL.revokeObjectURL(url);
}
if (worker) {
worker.terminate();
}
if (timeout) {
clearTimeout(timeout);
}
}
});
/*!
{
"name": "Workers from Data URIs",
"property": "dataworkers",
"tags": ["performance", "workers"],
"builderAliases": ["workers_dataworkers"],
"notes": [{
"name": "W3C Reference",
"href": "http://www.w3.org/TR/workers/"
}],
"knownBugs": ["This test may output garbage to console."],
"authors": ["Jussi Kalliokoski"],
"async": true
}
!*/
/* DOC
Detects support for creating Web Workers from Data URIs.
*/
Modernizr.addAsyncTest(function() {
try {
var data = 'Modernizr',
worker = new Worker('data:text/javascript;base64,dGhpcy5vbm1lc3NhZ2U9ZnVuY3Rpb24oZSl7cG9zdE1lc3NhZ2UoZS5kYXRhKX0=');
worker.onmessage = function(e) {
worker.terminate();
addTest('dataworkers', data === e.data);
worker = null;
};
// Just in case...
worker.onerror = function() {
addTest('dataworkers', false);
worker = null;
};
setTimeout(function() {
addTest('dataworkers', false);
}, 200);
worker.postMessage(data);
} catch (e) {
setTimeout(function() {
addTest('dataworkers', false);
}, 0);
}
});
var cssomPrefixes = (ModernizrProto._config.usePrefixes ? omPrefixes.split(' ') : []);
ModernizrProto._cssomPrefixes = cssomPrefixes;
/**
* atRule returns a given CSS property at-rule (eg @keyframes), possibly in
* some prefixed form, or false, in the case of an unsupported rule
*
* @memberof Modernizr
* @name Modernizr.atRule
* @optionName Modernizr.atRule()
* @optionProp atRule
* @access public
* @function atRule
* @param {string} prop - String name of the @-rule to test for
* @returns {string|boolean} The string representing the (possibly prefixed)
* valid version of the @-rule, or `false` when it is unsupported.
* @example
* ```js
* var keyframes = Modernizr.atRule('@keyframes');
*
* if (keyframes) {
* // keyframes are supported
* // could be `@-webkit-keyframes` or `@keyframes`
* } else {
* // keyframes === `false`
* }
* ```
*
*/
var atRule = function(prop) {
var length = prefixes.length;
var cssrule = window.CSSRule;
var rule;
if (typeof cssrule === 'undefined') {
return undefined;
}
if (!prop) {
return false;
}
// remove literal @ from beginning of provided property
prop = prop.replace(/^@/, '');
// CSSRules use underscores instead of dashes
rule = prop.replace(/-/g, '_').toUpperCase() + '_RULE';
if (rule in cssrule) {
return '@' + prop;
}
for (var i = 0; i < length; i++) {
// prefixes gives us something like -o-, and we want O_
var prefix = prefixes[i];
var thisRule = prefix.toUpperCase() + '_' + rule;
if (thisRule in cssrule) {
return '@-' + prefix.toLowerCase() + '-' + prop;
}
}
return false;
};
ModernizrProto.atRule = atRule;
/**
* createElement is a convenience wrapper around document.createElement. Since we
* use createElement all over the place, this allows for (slightly) smaller code
* as well as abstracting away issues with creating elements in contexts other than
* HTML documents (e.g. SVG documents).
*
* @access private
* @function createElement
* @returns {HTMLElement|SVGElement} An HTML or SVG element
*/
function createElement() {
if (typeof document.createElement !== 'function') {
// This is the case in IE7, where the type of createElement is "object".
// For this reason, we cannot call apply() as Object is not a Function.
return document.createElement(arguments[0]);
} else if (isSVG) {
return document.createElementNS.call(document, 'http://www.w3.org/2000/svg', arguments[0]);
} else {
return document.createElement.apply(document, arguments);
}
}
;
/**
* Modernizr.hasEvent() detects support for a given event
*
* @memberof Modernizr
* @name Modernizr.hasEvent
* @optionName Modernizr.hasEvent()
* @optionProp hasEvent
* @access public
* @function hasEvent
* @param {string|*} eventName - the name of an event to test for (e.g. "resize")
* @param {Element|string} [element=HTMLDivElement] - is the element|document|window|tagName to test on
* @returns {boolean}
* @example
* `Modernizr.hasEvent` lets you determine if the browser supports a supplied event.
* By default, it does this detection on a div element
*
* ```js
* hasEvent('blur') // true;
* ```
*
* However, you are able to give an object as a second argument to hasEvent to
* detect an event on something other than a div.
*
* ```js
* hasEvent('devicelight', window) // true;
* ```
*
*/
var hasEvent = (function() {
// Detect whether event support can be detected via `in`. Test on a DOM element
// using the "blur" event b/c it should always exist. bit.ly/event-detection
var needsFallback = !('onblur' in document.documentElement);
function inner(eventName, element) {
var isSupported;
if (!eventName) { return false; }
if (!element || typeof element === 'string') {
element = createElement(element || 'div');
}
// Testing via the `in` operator is sufficient for modern browsers and IE.
// When using `setAttribute`, IE skips "unload", WebKit skips "unload" and
// "resize", whereas `in` "catches" those.
eventName = 'on' + eventName;
isSupported = eventName in element;
// Fallback technique for old Firefox - bit.ly/event-detection
if (!isSupported && needsFallback) {
if (!element.setAttribute) {
// Switch to generic element if it lacks `setAttribute`.
// It could be the `document`, `window`, or something else.
element = createElement('div');
}
element.setAttribute(eventName, '');
isSupported = typeof element[eventName] === 'function';
if (element[eventName] !== undefined) {
// If property was created, "remove it" by setting value to `undefined`.
element[eventName] = undefined;
}
element.removeAttribute(eventName);
}
return isSupported;
}
return inner;
})();
ModernizrProto.hasEvent = hasEvent;
/*!
{
"name": "Ambient Light Events",
"property": "ambientlight",
"notes": [{
"name": "W3C Ambient Light Events",
"href": "http://www.w3.org/TR/ambient-light/"
}]
}
!*/
/* DOC
Detects support for the API that provides information about the ambient light levels, as detected by the device's light detector, in terms of lux units.
*/
Modernizr.addTest('ambientlight', hasEvent('devicelight', window));
/*!
{
"name": "Hashchange event",
"property": "hashchange",
"caniuse": "hashchange",
"tags": ["history"],
"notes": [{
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en-US/docs/Web/API/window.onhashchange"
}],
"polyfills": [
"jquery-hashchange",
"moo-historymanager",
"jquery-ajaxy",
"hasher",
"shistory"
]
}
!*/
/* DOC
Detects support for the `hashchange` event, fired when the current location fragment changes.
*/
Modernizr.addTest('hashchange', function() {
if (hasEvent('hashchange', window) === false) {
return false;
}
// documentMode logic from YUI to filter out IE8 Compat Mode
// which false positives.
return (document.documentMode === undefined || document.documentMode > 7);
});
/*!
{
"name": "input[search] search event",
"property": "search",
"tags": ["input","search"],
"authors": ["Calvin Webster"],
"notes": [{
"name": "Wufoo demo",
"href": "http://www.wufoo.com/html5/types/5-search.html?"
}, {
"name": "CSS Tricks",
"href": "http://css-tricks.com/webkit-html5-search-inputs/"
}]
}
!*/
/* DOC
There is a custom `search` event implemented in webkit browsers when using an `input[search]` element.
*/
Modernizr.addTest('inputsearchevent', hasEvent('search'));
/*!
{
"name": "DOM Pointer Events API",
"property": "pointerevents",
"tags": ["input"],
"authors": ["Stu Cox"],
"notes": [
{
"name": "W3C spec",
"href": "http://www.w3.org/TR/pointerevents/"
}
],
"warnings": ["This property name now refers to W3C DOM PointerEvents: https://github.com/Modernizr/Modernizr/issues/548#issuecomment-12812099"],
"polyfills": ["handjs"]
}
!*/
/* DOC
Detects support for the DOM Pointer Events API, which provides a unified event interface for pointing input devices, as implemented in IE10+.
*/
// **Test name hijacked!**
// Now refers to W3C DOM PointerEvents spec rather than the CSS pointer-events property.
Modernizr.addTest('pointerevents', function() {
// Cannot use `.prefixed()` for events, so test each prefix
var bool = false,
i = domPrefixes.length;
// Don't forget un-prefixed...
bool = Modernizr.hasEvent('pointerdown');
while (i-- && !bool) {
if (hasEvent(domPrefixes[i] + 'pointerdown')) {
bool = true;
}
}
return bool;
});
/**
* prefixedCSSValue is a way test for prefixed css properties (e.g. display: -webkit-flex)
*
* @memberof Modernizr
* @name Modernizr.prefixedCSSValue
* @optionName Modernizr.prefixedCSSValue()
* @optionProp prefixedCSSValue
* @access public
* @function prefixedCSSValue
* @param {string} prop - String name of the property to test for
* @param {string} value - String value of the non prefixed version of the value you want to test for
* @returns {string|false} The string representing the (possibly prefixed)
* valid version of the property, or `false` when it is unsupported.
* @example
*
* `Modernizr.prefixedCSSValue` is a way test for prefixed css properties (e.g. display: -webkit-flex)
*
* ```js
* Modernizr.prefixedCSSValue('background', 'linear-gradient(left, red, red)')
* ```
*
*/
var prefixedCSSValue = function(prop, value) {
var result = false;
var elem = createElement('div');
var style = elem.style;
if (prop in style) {
var i = domPrefixes.length;
style[prop] = value;
result = style[prop];
while (i-- && !result) {
style[prop] = '-' + domPrefixes[i] + '-' + value;
result = style[prop];
}
}
if (result === '') {
result = false;
}
return result;
};
ModernizrProto.prefixedCSSValue = prefixedCSSValue;
/*!
{
"name" : "HTML5 Audio Element",
"property": "audio",
"tags" : ["html5", "audio", "media"]
}
!*/
/* DOC
Detects the audio element
*/
// This tests evaluates support of the audio element, as well as
// testing what types of content it supports.
//
// We're using the Boolean constructor here, so that we can extend the value
// e.g. Modernizr.audio // true
// Modernizr.audio.ogg // 'probably'
//
// Codec values from : github.com/NielsLeenheer/html5test/blob/9106a8/index.html#L845
// thx to NielsLeenheer and zcorpan
// Note: in some older browsers, "no" was a return value instead of empty string.
// It was live in FF3.5.0 and 3.5.1, but fixed in 3.5.2
// It was also live in Safari 4.0.0 - 4.0.4, but fixed in 4.0.5
Modernizr.addTest('audio', function() {
/* jshint -W053 */
var elem = createElement('audio');
var bool = false;
try {
if (bool = !!elem.canPlayType) {
bool = new Boolean(bool);
bool.ogg = elem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '');
bool.mp3 = elem.canPlayType('audio/mpeg; codecs="mp3"') .replace(/^no$/, '');
bool.opus = elem.canPlayType('audio/ogg; codecs="opus"') .replace(/^no$/, '');
// Mimetypes accepted:
// developer.mozilla.org/En/Media_formats_supported_by_the_audio_and_video_elements
// bit.ly/iphoneoscodecs
bool.wav = elem.canPlayType('audio/wav; codecs="1"') .replace(/^no$/, '');
bool.m4a = (elem.canPlayType('audio/x-m4a;') ||
elem.canPlayType('audio/aac;')) .replace(/^no$/, '');
}
} catch (e) { }
return bool;
});
/*!
{
"name": "Canvas",
"property": "canvas",
"caniuse": "canvas",
"tags": ["canvas", "graphics"],
"polyfills": ["flashcanvas", "excanvas", "slcanvas", "fxcanvas"]
}
!*/
/* DOC
Detects support for the `<canvas>` element for 2D drawing.
*/
// On the S60 and BB Storm, getContext exists, but always returns undefined
// so we actually have to call getContext() to verify
// github.com/Modernizr/Modernizr/issues/issue/97/
Modernizr.addTest('canvas', function() {
var elem = createElement('canvas');
return !!(elem.getContext && elem.getContext('2d'));
});
/*!
{
"name": "Canvas text",
"property": "canvastext",
"caniuse": "canvas-text",
"tags": ["canvas", "graphics"],
"polyfills": ["canvastext"]
}
!*/
/* DOC
Detects support for the text APIs for `<canvas>` elements.
*/
Modernizr.addTest('canvastext', function() {
if (Modernizr.canvas === false) {
return false;
}
return typeof createElement('canvas').getContext('2d').fillText == 'function';
});
/*!
{
"name": "Content Editable",
"property": "contenteditable",
"caniuse": "contenteditable",
"notes": [{
"name": "WHATWG spec",
"href": "http://www.whatwg.org/specs/web-apps/current-work/multipage/editing.html#contenteditable"
}]
}
!*/
/* DOC
Detects support for the `contenteditable` attribute of elements, allowing their DOM text contents to be edited directly by the user.
*/
Modernizr.addTest('contenteditable', function() {
// early bail out
if (!('contentEditable' in docElement)) {
return;
}
// some mobile browsers (android < 3.0, iOS < 5) claim to support
// contentEditable, but but don't really. This test checks to see
// confirms whether or not it actually supports it.
var div = createElement('div');
div.contentEditable = true;
return div.contentEditable === 'true';
});
/*!
{
"name": "Emoji",
"property": "emoji"
}
!*/
/* DOC
Detects support for emoji character sets.
*/
Modernizr.addTest('emoji', function() {
if (!Modernizr.canvastext) {
return false;
}
var pixelRatio = window.devicePixelRatio || 1;
var offset = 12 * pixelRatio;
var node = createElement('canvas');
var ctx = node.getContext('2d');
ctx.fillStyle = '#f00';
ctx.textBaseline = 'top';
ctx.font = '32px Arial';
ctx.fillText('\ud83d\udc28', 0, 0); // U+1F428 KOALA
return ctx.getImageData(offset, offset, 1, 1).data[0] !== 0;
});
/*!
{
"name": "HTML Imports",
"notes": [
{
"name": "W3C HTML Imports Specification",
"href": "http://w3c.github.io/webcomponents/spec/imports/"
},
{
"name": "HTML Imports - #include for the web",
"href": "http://www.html5rocks.com/en/tutorials/webcomponents/imports/"
}
],
"polyfills": ["polymer-htmlimports"],
"property": "htmlimports",
"tags": ["html", "import"]
}
!*/
/* DOC
Detects support for HTML import, a feature that is used for loading in Web Components.
*/
addTest('htmlimports', 'import' in createElement('link'));
/*!
{
"name": "Reverse Ordered Lists",
"property": "olreversed",
"notes": [{
"name": "Impressive Webs article",
"href": "http://impressivewebs.com/reverse-ordered-lists-html5"
}],
"builderAliases": ["lists_reversed"]
}
!*/
/* DOC
Detects support for the `reversed` attribute on the `<ol>` element.
*/
Modernizr.addTest('olreversed', 'reversed' in createElement('ol'));
/*!
{
"name": "IE User Data API",
"property": "userdata",
"tags": ["storage"],
"authors": ["@stereobooster"],
"notes": [{
"name": "MSDN Documentation",
"href": "http://msdn.microsoft.com/en-us/library/ms531424(v=vs.85).aspx"
}]
}
!*/
/* DOC
Detects support for IE userData for persisting data, an API similar to localStorage but supported since IE5.
*/
Modernizr.addTest('userdata', !!createElement('div').addBehavior);
/*!
{
"name": "HTML5 Video",
"property": "video",
"caniuse": "video",
"tags": ["html5"],
"knownBugs": [
"Without QuickTime, `Modernizr.video.h264` will be `undefined`; http://github.com/Modernizr/Modernizr/issues/546"
],
"polyfills": [
"html5media",
"mediaelementjs",
"sublimevideo",
"videojs",
"leanbackplayer",
"videoforeverybody"
]
}
!*/
/* DOC
Detects support for the video element, as well as testing what types of content it supports.
Subproperties are provided to describe support for `ogg`, `h264` and `webm` formats, e.g.:
```javascript
Modernizr.video // true
Modernizr.video.ogg // 'probably'
```
*/
// Codec values from : github.com/NielsLeenheer/html5test/blob/9106a8/index.html#L845
// thx to NielsLeenheer and zcorpan
// Note: in some older browsers, "no" was a return value instead of empty string.
// It was live in FF3.5.0 and 3.5.1, but fixed in 3.5.2
// It was also live in Safari 4.0.0 - 4.0.4, but fixed in 4.0.5
Modernizr.addTest('video', function() {
/* jshint -W053 */
var elem = createElement('video');
var bool = false;
// IE9 Running on Windows Server SKU can cause an exception to be thrown, bug #224
try {
if (bool = !!elem.canPlayType) {
bool = new Boolean(bool);
bool.ogg = elem.canPlayType('video/ogg; codecs="theora"').replace(/^no$/, '');
// Without QuickTime, this value will be `undefined`. github.com/Modernizr/Modernizr/issues/546
bool.h264 = elem.canPlayType('video/mp4; codecs="avc1.42E01E"').replace(/^no$/, '');
bool.webm = elem.canPlayType('video/webm; codecs="vp8, vorbis"').replace(/^no$/, '');
bool.vp9 = elem.canPlayType('video/webm; codecs="vp9"').replace(/^no$/, '');
bool.hls = elem.canPlayType('application/x-mpegURL; codecs="avc1.42E01E"').replace(/^no$/, '');
}
} catch (e) {}
return bool;
});
/*!
{
"name": "VML",
"property": "vml",
"caniuse": "vml",
"tags": ["vml"],
"authors": ["Craig Andrews (@candrews)"],
"notes": [{
"name" : "W3C VML reference",
"href": "http://www.w3.org/TR/NOTE-VML"
},{
"name" : "Microsoft VML reference",
"href": "http://msdn.microsoft.com/en-us/library/bb263898%28VS.85%29.aspx"
}]
}
!*/
/* DOC
Detects support for VML.
*/
Modernizr.addTest('vml', function() {
var containerDiv = createElement('div');
var supports = false;
var shape;
if (!isSVG) {
containerDiv.innerHTML = '<v:shape id="vml_flag1" adj="1" />';
shape = containerDiv.firstChild;
shape.style.behavior = 'url(#default#VML)';
supports = shape ? typeof shape.adj == 'object' : true;
}
return supports;
});
/*!
{
"name": "Web Animation API",
"property": "animation",
"tags": ["webanimations"],
"polyfills": ["webanimationsjs"],
"notes": [{
"name": "Introducing Web Animations",
"href": "http://brian.sol1.net/svg/2013/06/26/introducing-web-animations/"
}]
}
!*/
/* DOC
Detects support for the Web Animation API, a way to create css animations in js
*/
Modernizr.addTest('webanimations', 'animate' in createElement('div'));
/*!
{
"name": "WebGL",
"property": "webgl",
"caniuse": "webgl",
"tags": ["webgl", "graphics"],
"polyfills": ["jebgl", "cwebgl", "iewebgl"]
}
!*/
Modernizr.addTest('webgl', function() {
var canvas = createElement('canvas');
var supports = 'probablySupportsContext' in canvas ? 'probablySupportsContext' : 'supportsContext';
if (supports in canvas) {
return canvas[supports]('webgl') || canvas[supports]('experimental-webgl');
}
return 'WebGLRenderingContext' in window;
});
/*!
{
"name": "a[download] Attribute",
"property": "adownload",
"caniuse" : "download",
"tags": ["media", "attribute"],
"builderAliases": ["a_download"],
"notes": [{
"name": "WhatWG Reference",
"href": "http://developers.whatwg.org/links.html#downloading-resources"
}]
}
!*/
/* DOC
When used on an `<a>`, this attribute signifies that the resource it points to should be downloaded by the browser rather than navigating to it.
*/
Modernizr.addTest('adownload', !window.externalHost && 'download' in createElement('a'));
/*!
{
"name": "Audio Loop Attribute",
"property": "audioloop",
"tags": ["audio", "media"]
}
!*/
/* DOC
Detects if an audio element can automatically restart, once it has finished
*/
Modernizr.addTest('audioloop', 'loop' in createElement('audio'));
/*!
{
"name": "Audio Preload",
"property": "audiopreload",
"tags": ["audio", "media"],
"async" : true,
"warnings": ["This test is very large – only include it if you absolutely need it"]
}
!*/
/* DOC
Detects if audio can be downloaded in the background before it starts playing in the `<audio>` element
*/
Modernizr.addAsyncTest(function() {
var timeout;
var waitTime = 300;
var elem = createElement('audio');
var elemStyle = elem.style;
function testpreload(event) {
clearTimeout(timeout);
var result = event !== undefined && event.type === 'loadeddata' ? true : false; //need to check if event is not undefined here in case function is evoked from timeout (no parameters)
elem.removeEventListener('loadeddata', testpreload, false);
addTest('audiopreload', result);
elem.parentNode.removeChild(elem);
}
//skip the test if audio itself, or the preload
//element on it isn't supported
if (!Modernizr.audio || !('preload' in elem)) {
addTest('audiopreload', false);
return;
}
elemStyle.position = 'absolute';
elemStyle.height = 0;
elemStyle.width = 0;
try {
if (Modernizr.audio.mp3) {
//75ms of silence (minumum Mp3 duration loaded by Safari, not tested other formats thoroughly: may be possible to shrink base64 URI)
elem.src = 'data:audio/mpeg;base64,//MUxAAB6AXgAAAAAPP+c6nf//yi/6f3//MUxAMAAAIAAAjEcH//0fTX6C9Lf//0//MUxA4BeAIAAAAAAKX2/6zv//+IlR4f//MUxBMCMAH8AAAAABYWalVMQU1FMy45//MUxBUB0AH0AAAAADkuM1VVVVVVVVVV//MUxBgBUATowAAAAFVVVVVVVVVVVVVV';
}
else if (Modernizr.audio.m4a) {
elem.src = 'data:audio/x-m4a;base64,AAAAGGZ0eXBNNEEgAAACAGlzb21pc28yAAAACGZyZWUAAAAfbWRhdN4EAABsaWJmYWFjIDEuMjgAAAFoAQBHAAACiG1vb3YAAABsbXZoZAAAAAB8JbCAfCWwgAAAA+gAAAAYAAEAAAEAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAG0dHJhawAAAFx0a2hkAAAAD3wlsIB8JbCAAAAAAQAAAAAAAAAYAAAAAAAAAAAAAAAAAQAAAAABAAAAAAAAAAAAAAAAAA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VqeZpqap5mmaJqua5qmrIqmKcumasqyaZqy7LqybbuubNuiacqyaZqybJqmLLuyq9uu7Oq6pFmmqXmeaWqeZ5qmasqyaZquq3meanqeaKqeKKqqaqqqraqqLFueZ5qa6KmmJ4qqaqqmrZqqKsumqtqyaaq2bKqqbbuq7Pqybeu6aaqybaqmLZuqatuu7OqyLNu6L2maaWqeZ5qa55mmaZqybJqqK1uep5qeKKqq5ommaqqqLJumqsqW55mqJ4qq6omea5qqKsumatqqaZq2bKqqLZumKsuubfu+68qybqqqbJuqauumasqybMu+78qq7oqmKcumqtqyaaqyLduy78uyrPuiacqyaaqybaqqLsuybRuzbPu6aJqybaqmLZuqKtuyLfu6LNu678qub6uqrOuyLfu67vqucOu6MLyybPuqrPq6K9u6b+sy2/Z9RNOUZVM1bdtUVVl2Zdn2Zdv2fdE0bVtVVVs2TdW2ZVn2fVm2bWE0Tdk2VVXWTdW0bVmWbWG2ZeF2Zdm3ZVv2ddeVdV/XfePXZd3murLty7Kt+6qr+rbu+8Jw667wCgAAGHAAAAgwoQwUGrISAIgCAACMYYwxCI1SzjkHoVHKOecgZM5BCCGVzDkIIZSSOQehlJQy5yCUklIIoZSUWgshlJRSawUAABQ4AAAE2KApsThAoSErAYBUAACD41iW55miatqyY0meJ4qqqaq27UiW54miaaqqbVueJ4qmqaqu6+ua54miaaqq6+q6aJqmqaqu67q6Lpqiqaqq67qyrpumqqquK7uy7Oumqqqq68quLPvCqrquK8uybevCsKqu68qybNu2b9y6ruu+7/vCka3rui78wjEMRwEA4AkOAEAFNqyOcFI0FlhoyEoAIAMAgDAGIYMQQgYhhJBSSiGllBIAADDgAAAQYEIZKDRkRQAQJwAAGEMppJRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkgppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkqppJRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoplVJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSSimllFJKKaWUUkoppZRSCgCQinAAkHowoQwUGrISAEgFAACMUUopxpyDEDHmGGPQSSgpYsw5xhyUklLlHIQQUmktt8o5CCGk1FJtmXNSWosx5hgz56SkFFvNOYdSUoux5ppr7qS0VmuuNedaWqs115xzzbm0FmuuOdecc8sx15xzzjnnGHPOOeecc84FAOA0OACAHtiwOsJJ0VhgoSErAYBUAAACGaUYc8456BBSjDnnHIQQIoUYc845CCFUjDnnHHQQQqgYc8w5CCGEkDnnHIQQQgghcw466CCEEEIHHYQQQgihlM5BCCGEEEooIYQQQgghhBA6CCGEEEIIIYQQQgghhFJKCCGEEEIJoZRQAABggQMAQIANqyOcFI0FFhqyEgAAAgCAHJagUs6EQY5Bjw1BylEzDUJMOdGZYk5qMxVTkDkQnXQSGWpB2V4yCwAAgCAAIMAEEBggKPhCCIgxAABBiMwQCYVVsMCgDBoc5gHAA0SERACQmKBIu7iALgNc0MVdB0IIQhCCWBxAAQk4OOGGJ97whBucoFNU6iAAAAAAAAwA4AEA4KAAIiKaq7C4wMjQ2ODo8AgAAAAAABYA+AAAOD6AiIjmKiwuMDI0Njg6PAIAAAAAAAAAAICAgAAAAAAAQAAAAICAT2dnUwAE7AwAAAAAAAD/QwAAAgAAADuydfsFAQEBAQEACg4ODg==';
}
else if (Modernizr.audio.wav) {
elem.src = 'data:audio/wav;base64,UklGRvwZAABXQVZFZm10IBAAAAABAAEARKwAAIhYAQACABAAZGF0YdgZAAAAAAEA/v8CAP//AAABAP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QAAAP//AgD+/wEAAQD+/wIA/////wIA//8AAAEA/f8DAP//AAABAP////8DAP3/AwD+/wEA//8BAP//AQAAAAAA//8BAP//AQD//wEA//8BAP//AAAAAAEA//8BAP7/AgD//wEA//8AAAAAAAAAAAAAAAD//wIA/v8BAAAA//8BAAEA/v8BAAAA//8DAPz/AwD+/wIA/v8CAP3/AwD+/wEAAAD//wEA//8BAAAA//8BAAAA/v8EAPv/BAD+/wAAAAABAP7/AgD//wAAAAABAP7/AgD//wAAAAAAAAAAAAABAP3/BAD8/wQA/f8BAAAAAAABAP7/AgD+/wIA/v8CAP7/AgD+/wIA/v8BAAAAAAD//wIA/f8DAP7/AAABAP//AAACAPz/BAD9/wIA//8AAP//AwD9/wMA/P8EAP3/AwD9/wIA//8BAP//AQD+/wMA/f8DAP7/AAABAP//AQAAAP//AQD//wIA/f8DAP7/AQAAAP//AQAAAAAA//8CAP7/AQABAP7/AgD+/wEAAQD+/wIA/v8CAP////8CAP7/AgD//wAAAAABAP7/AwD9/wIAAAD+/wMA/f8CAP//AQD+/wMA/f8CAP//AAACAPz/BQD6/wUA/v///wIA/v8CAP3/BAD7/wYA+v8FAPz/AwD/////AgD+/wEAAAD//wEAAAD//wIA/f8DAP7/AQAAAP//AgD//wAA//8BAAAAAAAAAP//AQD//wEA//8AAAIA/f8DAP3/AgAAAP//AQD//wEA//8AAAEA//8BAP////8CAP//AAABAP3/BAD9/wIA/v8BAAEA//8BAP7/AgD//wEA//8AAAEA//8BAP//AAAAAAEA//8BAP7/AgD//wEA//8AAAAAAQD+/wIA/v8BAAAAAAD//wIA/v8BAAAAAAAAAAAAAQD+/wMA/f8CAP//AQD//wIA/f8DAP7/AQD//wEA//8CAP7/AAABAP7/AwD9/wMA/v8AAAEA//8BAAAAAAD//wIA/v8BAAAA//8CAP7/AgD+/wEA//8CAP7/AgD//wAAAAAAAAAAAQD//wEA/v8DAPz/BQD8/wIA//8AAAEAAAD//wEA//8BAP//AQAAAAAA//8BAP//AgD+/wEA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QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEA/v8CAP3/BAD8/wMA/v8BAAAAAAD//wEAAAAAAAAAAAD//wEAAAAAAAAA//8BAP//AgD+/wEA//8CAP3/AwD9/wMA/f8EAPv/BAD+/wAAAQD//wEA//8BAP//AAABAP//AQD//wEAAAD//wEA//8BAP//AgD9/wMA/v8AAAIA/f8DAP7/AAACAP3/AwD+/wEA//8BAP//AQAAAP//AQAAAP7/AwD9/wMA/v8AAAEA//8BAP//AAAAAAEA//8AAAEA/v8CAP//AAAAAAEA/v8DAPz/BAD9/wEAAQD+/wEAAQD9/wQA/P8DAP7/AQAAAAAAAAAAAAAAAAAAAAAAAQD+/wIA/////wIA/v8BAAAA//8BAP//AQD//wEA//8BAAAA/v8EAPz/AwD///7/BAD8/wMA/////wIA/v8CAP////8CAP7/AgD+/wIA/v8CAP////8CAP7/AwD9/wIA/v8CAP//AAABAP7/AwD9/wEAAQD+/wMA/f8CAP//AAAAAAEA/v8DAPz/BAD9/wIA/v8CAP7/AgD//wAAAAD//wIA/v8CAP7/AQAAAAAA//8CAP7/AgD+/wIA/v8CAP7/AwD8/wUA+v8GAPv/AwD//wAAAAAAAAAA//8DAPv/BQD9/wAAAgD9/wMA/v8BAP//AQAAAP//AgD9/wMA/v8BAAAA//8BAAAAAAAAAP//AQAAAAAAAAD//wEA//8CAP3/AwD+/wAAAgD+/wEAAAD//wIA/v8CAP7/AgD/////AwD8/wUA/P8CAP//AQD//wIA/f8DAP3/AwD+/wAAAQD+/wMA/f8DAP3/AgD//wAAAQD//wEA//8BAP7/AwD+/wEA//8AAAEA//8CAPz/BAD9/wIA//8AAAEA/v8DAPz/BAD9/wIA//8AAAEA/v8CAP7/AgD//wEA/f8EAPz/BAD+////AgD//wAAAQD//wAAAQD//wEA//8BAP7/AwD+/wEA';
}
else {
addTest('audiopreload', false);
return;
}
}
catch (e) {
addTest('audiopreload', false);
return;
}
elem.setAttribute('preload', 'auto');
elem.style.cssText = 'display:none';
docElement.appendChild(elem);
// wait for the next tick to add the listener, otherwise the element may
// not have time to play in high load situations (e.g. the test suite)
setTimeout(function() {
elem.addEventListener('loadeddata', testpreload, false);
timeout = setTimeout(testpreload, waitTime);
}, 0);
});
/*!
{
"name": "canvas blending support",
"property": "canvasblending",
"tags": ["canvas"],
"async" : false,
"notes": [{
"name": "HTML5 Spec",
"href": "https://dvcs.w3.org/hg/FXTF/rawfile/tip/compositing/index.html#blending"
},
{
"name": "Article",
"href": "http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas"
}]
}
!*/
/* DOC
Detects if Photoshop style blending modes are available in canvas.
*/
Modernizr.addTest('canvasblending', function() {
if (Modernizr.canvas === false) {
return false;
}
var ctx = createElement('canvas').getContext('2d');
// firefox 3 throws an error when setting an invalid `globalCompositeOperation`
try {
ctx.globalCompositeOperation = 'screen';
} catch (e) {}
return ctx.globalCompositeOperation === 'screen';
});
/*!
{
"name": "canvas.toDataURL type support",
"property": ["todataurljpeg", "todataurlpng", "todataurlwebp"],
"tags": ["canvas"],
"builderAliases": ["canvas_todataurl_type"],
"async" : false,
"notes": [{
"name": "MDN article",
"href": "https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement.toDataURL"
}]
}
!*/
var canvas = createElement('canvas');
Modernizr.addTest('todataurljpeg', function() {
return !!Modernizr.canvas && canvas.toDataURL('image/jpeg').indexOf('data:image/jpeg') === 0;
});
Modernizr.addTest('todataurlpng', function() {
return !!Modernizr.canvas && canvas.toDataURL('image/png').indexOf('data:image/png') === 0;
});
Modernizr.addTest('todataurlwebp', function() {
var supports = false;
// firefox 3 throws an error when you use an "invalid" toDataUrl
try {
supports = !!Modernizr.canvas && canvas.toDataURL('image/webp').indexOf('data:image/webp') === 0;
} catch (e) {}
return supports;
});
/*!
{
"name": "canvas winding support",
"property": ["canvaswinding"],
"tags": ["canvas"],
"async" : false,
"notes": [{
"name": "Article",
"href": "http://blogs.adobe.com/webplatform/2013/01/30/winding-rules-in-canvas/"
}]
}
!*/
/* DOC
Determines if winding rules, which controls if a path can go clockwise or counterclockwise
*/
Modernizr.addTest('canvaswinding', function() {
if (Modernizr.canvas === false) {
return false;
}
var ctx = createElement('canvas').getContext('2d');
ctx.rect(0, 0, 10, 10);
ctx.rect(2, 2, 6, 6);
return ctx.isPointInPath(5, 5, 'evenodd') === false;
});
/*!
{
"name": "Background Position Shorthand",
"property": "bgpositionshorthand",
"tags": ["css"],
"builderAliases": ["css_backgroundposition_shorthand"],
"notes": [{
"name": "MDN Docs",
"href": "https://developer.mozilla.org/en/CSS/background-position"
}, {
"name": "W3 Spec",
"href": "http://www.w3.org/TR/css3-background/#background-position"
}, {
"name": "Demo",
"href": "http://jsfiddle.net/Blink/bBXvt/"
}]
}
!*/
/* DOC
Detects if you can use the shorthand method to define multiple parts of an
element's background-position simultaniously.
eg `background-position: right 10px bottom 10px`
*/
Modernizr.addTest('bgpositionshorthand', function() {
var elem = createElement('a');
var eStyle = elem.style;
var val = 'right 10px bottom 10px';
eStyle.cssText = 'background-position: ' + val + ';';
return (eStyle.backgroundPosition === val);
});
/*!
{
"name": "CSS Calc",
"property": "csscalc",
"caniuse": "calc",
"tags": ["css"],
"builderAliases": ["css_calc"],
"authors": ["@calvein"]
}
!*/
/* DOC
Method of allowing calculated values for length units. For example:
```css
//lem {
width: calc(100% - 3em);
}
```
*/
Modernizr.addTest('csscalc', function() {
var prop = 'width:';
var value = 'calc(10px);';
var el = createElement('a');
el.style.cssText = prop + prefixes.join(value + prop);
return !!el.style.length;
});
/*!
{
"name": "CSS Cubic Bezier Range",
"property": "cubicbezierrange",
"tags": ["css"],
"builderAliases": ["css_cubicbezierrange"],
"doc" : null,
"authors": ["@calvein"],
"warnings": ["cubic-bezier values can't be > 1 for Webkit until [bug #45761](https://bugs.webkit.org/show_bug.cgi?id=45761) is fixed"],
"notes": [{
"name": "Comprehensive Compat Chart",
"href": "http://muddledramblings.com/table-of-css3-border-radius-compliance"
}]
}
!*/
Modernizr.addTest('cubicbezierrange', function() {
var el = createElement('a');
el.style.cssText = prefixes.join('transition-timing-function:cubic-bezier(1,0,0,1.1); ');
return !!el.style.length;
});
/*!
{
"name": "CSS Gradients",
"caniuse": "css-gradients",
"property": "cssgradients",
"tags": ["css"],
"knownBugs": ["False-positives on webOS (https://github.com/Modernizr/Modernizr/issues/202)"],
"notes": [{
"name": "Webkit Gradient Syntax",
"href": "http://webkit.org/blog/175/introducing-css-gradients/"
},{
"name": "Mozilla Linear Gradient Syntax",
"href": "http://developer.mozilla.org/en/CSS/-moz-linear-gradient"
},{
"name": "Mozilla Radial Gradient Syntax",
"href": "http://developer.mozilla.org/en/CSS/-moz-radial-gradient"
},{
"name": "W3C Gradient Spec",
"href": "dev.w3.org/csswg/css3-images/#gradients-"
}]
}
!*/
Modernizr.addTest('cssgradients', function() {
var str1 = 'background-image:';
var str2 = 'gradient(linear,left top,right bottom,from(#9f9),to(white));';
var css = '';
var angle;
for (var i = 0, len = prefixes.length - 1; i < len; i++) {
angle = (i === 0 ? 'to ' : '');
css += str1 + prefixes[i] + 'linear-gradient(' + angle + 'left top, #9f9, white);';
}
if (Modernizr._config.usePrefixes) {
// legacy webkit syntax (FIXME: remove when syntax not in use anymore)
css += str1 + '-webkit-' + str2;
}
var elem = createElement('a');
var style = elem.style;
style.cssText = css;
// IE6 returns undefined so cast to string
return ('' + style.backgroundImage).indexOf('gradient') > -1;
});
/*!
{
"name": "CSS Multiple Backgrounds",
"caniuse": "multibackgrounds",
"property": "multiplebgs",
"tags": ["css"]
}
!*/
// Setting multiple images AND a color on the background shorthand property
// and then querying the style.background property value for the number of
// occurrences of "url(" is a reliable method for detecting ACTUAL support for this!
Modernizr.addTest('multiplebgs', function() {
var style = createElement('a').style;
style.cssText = 'background:url(https://),url(https://),red url(https://)';
// If the UA supports multiple backgrounds, there should be three occurrences
// of the string "url(" in the return value for elemStyle.background
return (/(url\s*\(.*?){3}/).test(style.background);
});
/*!
{
"name": "CSS Opacity",
"caniuse": "css-opacity",
"property": "opacity",
"tags": ["css"]
}
!*/
// Browsers that actually have CSS Opacity implemented have done so
// according to spec, which means their return values are within the
// range of [0.0,1.0] - including the leading zero.
Modernizr.addTest('opacity', function() {
var style = createElement('a').style;
style.cssText = prefixes.join('opacity:.55;');
// The non-literal . in this regex is intentional:
// German Chrome returns this value as 0,55
// github.com/Modernizr/Modernizr/issues/#issue/59/comment/516632
return (/^0.55$/).test(style.opacity);
});
/*!
{
"name": "CSS Pointer Events",
"caniuse": "pointer-events",
"property": "csspointerevents",
"authors": ["ausi"],
"tags": ["css"],
"builderAliases": ["css_pointerevents"],
"notes": [
{
"name": "MDN Docs",
"href": "http://developer.mozilla.org/en/CSS/pointer-events"
},{
"name": "Test Project Page",
"href": "http://ausi.github.com/Feature-detection-technique-for-pointer-events/"
},{
"name": "Test Project Wiki",
"href": "http://github.com/ausi/Feature-detection-technique-for-pointer-events/wiki"
},
{
"name": "Related Github Issue",
"href": "http://github.com/Modernizr/Modernizr/issues/80"
}
]
}
!*/
Modernizr.addTest('csspointerevents', function() {
var style = createElement('a').style;
style.cssText = 'pointer-events:auto';
return style.pointerEvents === 'auto';
});
/*!
{
"name": "CSS position: sticky",
"property": "csspositionsticky",
"tags": ["css"],
"builderAliases": ["css_positionsticky"],
"notes": [{
"name": "Chrome bug report",
"href":"https://code.google.com/p/chromium/issues/detail?id=322972"
}],
"warnings": [ "using position:sticky on anything but top aligned elements is buggy in Chrome < 37 and iOS <=7+" ]
}
!*/
// Sticky positioning - constrains an element to be positioned inside the
// intersection of its container box, and the viewport.
Modernizr.addTest('csspositionsticky', function() {
var prop = 'position:';
var value = 'sticky';
var el = createElement('a');
var mStyle = el.style;
mStyle.cssText = prop + prefixes.join(value + ';' + prop).slice(0, -prop.length);
return mStyle.position.indexOf(value) !== -1;
});
/*!
{
"name": "CSS Regions",
"caniuse": "css-regions",
"authors": ["Mihai Balan"],
"property": "regions",
"tags": ["css"],
"builderAliases": ["css_regions"],
"notes": [{
"name": "W3C Specification",
"href": "http://www.w3.org/TR/css3-regions/"
}]
}
!*/
// We start with a CSS parser test then we check page geometry to see if it's affected by regions
// Later we might be able to retire the second part, as WebKit builds with the false positives die out
Modernizr.addTest('regions', function() {
if (isSVG) {
// css regions don't work inside of SVG elements. Rather than update the
// below test to work in an SVG context, just exit early to save bytes
return false;
}
/* Get the 'flowFrom' property name available in the browser. Either default or vendor prefixed.
If the property name can't be found we'll get Boolean 'false' and fail quickly */
var flowFromProperty = Modernizr.prefixed('flowFrom');
var flowIntoProperty = Modernizr.prefixed('flowInto');
var result = false;
if (!flowFromProperty || !flowIntoProperty) {
return result;
}
/* If CSS parsing is there, try to determine if regions actually work. */
var iframeContainer = createElement('iframe');
var container = createElement('div');
var content = createElement('div');
var region = createElement('div');
/* we create a random, unlikely to be generated flow number to make sure we don't
clash with anything more vanilla, like 'flow', or 'article', or 'f1' */
var flowName = 'modernizr_flow_for_regions_check';
/* First create a div with two adjacent divs inside it. The first will be the
content, the second will be the region. To be able to distinguish between the two,
we'll give the region a particular padding */
content.innerText = 'M';
container.style.cssText = 'top: 150px; left: 150px; padding: 0px;';
region.style.cssText = 'width: 50px; height: 50px; padding: 42px;';
region.style[flowFromProperty] = flowName;
container.appendChild(content);
container.appendChild(region);
docElement.appendChild(container);
/* Now compute the bounding client rect, before and after attempting to flow the
content div in the region div. If regions are enabled, the after bounding rect
should reflect the padding of the region div.*/
var flowedRect, delta;
var plainRect = content.getBoundingClientRect();
content.style[flowIntoProperty] = flowName;
flowedRect = content.getBoundingClientRect();
delta = parseInt(flowedRect.left - plainRect.left, 10);
docElement.removeChild(container);
if (delta == 42) {
result = true;
} else {
/* IE only allows for the content to come from iframes. This has the
* side effect of automatic collapsing of iframes once they get the flow-into
* property set. checking for a change on the height allows us to detect this
* in a sync way, without having to wait for a frame to load */
docElement.appendChild(iframeContainer);
plainRect = iframeContainer.getBoundingClientRect();
iframeContainer.style[flowIntoProperty] = flowName;
flowedRect = iframeContainer.getBoundingClientRect();
if (plainRect.height > 0 && plainRect.height !== flowedRect.height && flowedRect.height === 0) {
result = true;
}
}
content = region = container = iframeContainer = undefined;
return result;
});
/*!
{
"name": "CSS Font rem Units",
"caniuse": "rem",
"authors": ["nsfmc"],
"property": "cssremunit",
"tags": ["css"],
"builderAliases": ["css_remunit"],
"notes": [{
"name": "W3C Spec",
"href": "http://www.w3.org/TR/css3-values/#relative0"
},{
"name": "Font Size with rem by Jonathan Snook",
"href": "http://snook.ca/archives/html_and_css/font-size-with-rem"
}]
}
!*/
// "The 'rem' unit ('root em') is relative to the computed
// value of the 'font-size' value of the root element."
// you can test by checking if the prop was ditched
Modernizr.addTest('cssremunit', function() {
var style = createElement('a').style;
try {
style.fontSize = '3rem';
}
catch (e) {}
return (/rem/).test(style.fontSize);
});
/*!
{
"name": "CSS rgba",
"caniuse": "css3-colors",
"property": "rgba",
"tags": ["css"],
"notes": [{
"name": "CSSTricks Tutorial",
"href": "http://css-tricks.com/rgba-browser-support/"
}]
}
!*/
Modernizr.addTest('rgba', function() {
var style = createElement('a').style;
style.cssText = 'background-color:rgba(150,255,150,.5)';
return ('' + style.backgroundColor).indexOf('rgba') > -1;
});
/*!
{
"name": "createElement with Attributes",
"property": ["createelementattrs", "createelement-attrs"],
"tags": ["dom"],
"builderAliases": ["dom_createElement_attrs"],
"authors": ["James A. Rosen"],
"notes": [{
"name": "Related Github Issue",
"href": "https://github.com/Modernizr/Modernizr/issues/258"
}]
}
!*/
Modernizr.addTest('createelementattrs', function() {
try {
return createElement('<input name="test" />').getAttribute('name') == 'test';
} catch (e) {
return false;
}
}, {
aliases: ['createelement-attrs']
});
/*!
{
"name": "dataset API",
"caniuse": "dataset",
"property": "dataset",
"tags": ["dom"],
"builderAliases": ["dom_dataset"],
"authors": ["@phiggins42"]
}
!*/
// dataset API for data-* attributes
Modernizr.addTest('dataset', function() {
var n = createElement('div');
n.setAttribute('data-a-b', 'c');
return !!(n.dataset && n.dataset.aB === 'c');
});
/*!
{
"name": "[hidden] Attribute",
"property": "hidden",
"tags": ["dom"],
"notes": [{
"name": "WHATWG: The hidden attribute",
"href": "http://developers.whatwg.org/editing.html#the-hidden-attribute"
}, {
"name": "original implementation of detect code",
"href": "https://github.com/aFarkas/html5shiv/blob/bf4fcc4/src/html5shiv.js#L38"
}],
"polyfills": ["html5shiv"],
"authors": ["Ron Waldon (@jokeyrhyme)"]
}
!*/
/* DOC
Does the browser support the HTML5 [hidden] attribute?
*/
Modernizr.addTest('hidden', 'hidden' in createElement('a'));
/*!
{
"name": "bdi Element",
"property": "bdi",
"notes": [{
"name": "MDN Overview",
"href": "https://developer.mozilla.org/en-US/docs/Web/HTML/Element/bdi"
}]
}
!*/
/* DOC
Detect support for the bdi element, a way to have text that is isolated from its possibly bidirectional surroundings
*/
Modernizr.addTest('bdi', function() {
var div = createElement('div');
var bdi = createElement('bdi');
bdi.innerHTML = 'إ';
div.appendChild(bdi);
docElement.appendChild(div);
var supports = ((window.getComputedStyle ?
getComputedStyle(bdi, null) :
bdi.currentStyle).direction === 'rtl');
docElement.removeChild(div);
return supports;
});
/*!
{
"name": "output Element",
"property": "outputelem",
"tags": ["elem"],
"builderAliases": ["elem_output"],
"notes": [{
"name": "WhatWG Spec",
"href": "http://www.whatwg.org/specs/web-apps/current-work/multipage/the-button-element.html#the-output-element"
}]
}
!*/
Modernizr.addTest('outputelem', 'value' in createElement('output'));
/*!
{
"name": "progress Element",
"caniuse": "progress",
"property": ["progressbar", "meter"],
"tags": ["elem"],
"builderAliases": ["elem_progress_meter"],
"authors": ["Stefan Wallin"]
}
!*/
// Tests for progressbar-support. All browsers that don't support progressbar returns undefined =)
Modernizr.addTest('progressbar', createElement('progress').max !== undefined);
// Tests for meter-support. All browsers that don't support meters returns undefined =)
Modernizr.addTest('meter', createElement('meter').max !== undefined);
/*!
{
"name": "ruby, rp, rt Elements",
"caniuse": "ruby",
"property": "ruby",
"tags": ["elem"],
"builderAliases": ["elem_ruby"],
"authors": ["Cătălin Mariș"],
"notes": [{
"name": "WHATWG Specification",
"href": "http://www.whatwg.org/specs/web-apps/current-work/multipage/text-level-semantics.html#the-ruby-element"
}]
}
!*/
Modernizr.addTest('ruby', function() {
var ruby = createElement('ruby');
var rt = createElement('rt');
var rp = createElement('rp');
var displayStyleProperty = 'display';
// 'fontSize' - because it`s only used for IE6 and IE7
var fontSizeStyleProperty = 'fontSize';
ruby.appendChild(rp);
ruby.appendChild(rt);
docElement.appendChild(ruby);
// browsers that support <ruby> hide the <rp> via "display:none"
if (getStyle(rp, displayStyleProperty) == 'none' || // for non-IE browsers
// but in IE browsers <rp> has "display:inline" so, the test needs other conditions:
getStyle(ruby, displayStyleProperty) == 'ruby' && getStyle(rt, displayStyleProperty) == 'ruby-text' || // for IE8+
getStyle(rp, fontSizeStyleProperty) == '6pt' && getStyle(rt, fontSizeStyleProperty) == '6pt') { // for IE6 & IE7
cleanUp();
return true;
} else {
cleanUp();
return false;
}
function getStyle(element, styleProperty) {
var result;
if (window.getComputedStyle) { // for non-IE browsers
result = document.defaultView.getComputedStyle(element, null).getPropertyValue(styleProperty);
} else if (element.currentStyle) { // for IE
result = element.currentStyle[styleProperty];
}
return result;
}
function cleanUp() {
docElement.removeChild(ruby);
// the removed child node still exists in memory, so ...
ruby = null;
rt = null;
rp = null;
}
});
/*!
{
"name": "Template Tag",
"property": "template",
"tags": ["elem"],
"notes": [{
"name": "HTML5Rocks Article",
"href": "http://www.html5rocks.com/en/tutorials/webcomponents/template/"
},{
"name": "W3 Spec",
"href": "https://dvcs.w3.org/hg/webcomponents/raw-file/tip/spec/templates/index.html"
}]
}
!*/
Modernizr.addTest('template', 'content' in createElement('template'));
/*!
{
"name": "time Element",
"property": "time",
"tags": ["elem"],
"builderAliases": ["elem_time"],
"notes": [{
"name": "WhatWG Spec",
"href": "http://www.whatwg.org/specs/web-apps/current-work/multipage/text-level-semantics.html#the-time-element"
}]
}
!*/
Modernizr.addTest('time', 'valueAsDate' in createElement('time'));
/*!
{
"name": "Track element and Timed Text Track",
"property": ["texttrackapi", "track"],
"tags": ["elem"],
"builderAliases": ["elem_track"],
"authors": ["Addy Osmani"],
"notes": [{
"name": "W3 track Element Spec",
"href": "http://www.w3.org/TR/html5/video.html#the-track-element"
},{
"name": "W3 track API Spec",
"href": "http://www.w3.org/TR/html5/media-elements.html#text-track-api"
}],
"warnings": ["While IE10 has implemented the track element, IE10 does not expose the underlying APIs to create timed text tracks by JS (really sad)"]
}
!*/
Modernizr.addTest('texttrackapi', typeof (createElement('video').addTextTrack) === 'function');
// a more strict test for track including UI support: document.createElement('track').kind === 'subtitles'
Modernizr.addTest('track', 'kind' in createElement('track'));
/*!
{
"name": "Unknown Elements",
"property": "unknownelements",
"tags": ["elem"],
"notes": [{
"name": "The Story of the HTML5 Shiv",
"href": "http://www.paulirish.com/2011/the-history-of-the-html5-shiv/"
}, {
"name": "original implementation of detect code",
"href": "https://github.com/aFarkas/html5shiv/blob/bf4fcc4/src/html5shiv.js#L36"
}],
"polyfills": ["html5shiv"],
"authors": ["Ron Waldon (@jokeyrhyme)"]
}
!*/
/* DOC
Does the browser support HTML with non-standard / new elements?
*/
Modernizr.addTest('unknownelements', function() {
var a = createElement('a');
a.innerHTML = '<xyz></xyz>';
return a.childNodes.length === 1;
});
/*!
{
"name": "input[capture] Attribute",
"property": "capture",
"tags": ["video", "image", "audio", "media", "attribute"],
"notes": [{
"name": "W3C draft: HTML Media Capture",
"href": "http://www.w3.org/TR/html-media-capture/"
}]
}
!*/
/* DOC
When used on an `<input>`, this attribute signifies that the resource it takes should be generated via device's camera, camcorder, sound recorder.
*/
// testing for capture attribute in inputs
Modernizr.addTest('capture', ('capture' in createElement('input')));
/*!
{
"name": "input[file] Attribute",
"property": "fileinput",
"caniuse" : "forms",
"tags": ["file", "forms", "input"],
"builderAliases": ["forms_fileinput"]
}
!*/
/* DOC
Detects whether input type="file" is available on the platform
E.g. iOS < 6 and some android version don't support this
*/
Modernizr.addTest('fileinput', function() {
if (navigator.userAgent.match(/(Android (1.0|1.1|1.5|1.6|2.0|2.1))|(Windows Phone (OS 7|8.0))|(XBLWP)|(ZuneWP)|(w(eb)?OSBrowser)|(webOS)|(Kindle\/(1.0|2.0|2.5|3.0))/)) {
return false;
}
var elem = createElement('input');
elem.type = 'file';
return !elem.disabled;
});
/*!
{
"name": "input[directory] Attribute",
"property": "directory",
"authors": ["silverwind"],
"tags": ["file", "input", "attribute"]
}
!*/
/* DOC
When used on an `<input type="file">`, the `directory` attribute instructs
the user agent to present a directory selection dialog instead of the usual
file selection dialog.
*/
Modernizr.addTest('fileinputdirectory', function() {
var elem = createElement('input'), dir = 'directory';
elem.type = 'file';
if (dir in elem) {
return true;
} else {
for (var i = 0, len = domPrefixes.length; i < len; i++) {
if (domPrefixes[i] + dir in elem) {
return true;
}
}
}
return false;
});
/*!
{
"name": "input[form] Attribute",
"property": "formattribute",
"tags": ["attribute", "forms", "input"],
"builderAliases": ["forms_formattribute"]
}
!*/
/* DOC
Detects whether input form="form_id" is available on the platform
E.g. IE 10 (and below), don't support this
*/
Modernizr.addTest('formattribute', function() {
var form = createElement('form');
var input = createElement('input');
var div = createElement('div');
var id = 'formtest' + (new Date()).getTime();
var attr;
var bool = false;
form.id = id;
//IE6/7 confuses the form idl attribute and the form content attribute, so we use document.createAttribute
try {
input.setAttribute('form', id);
}
catch (e) {
if (document.createAttribute) {
attr = document.createAttribute('form');
attr.nodeValue = id;
input.setAttributeNode(attr);
}
}
div.appendChild(form);
div.appendChild(input);
docElement.appendChild(div);
bool = form.elements && form.elements.length === 1 && input.form == form;
div.parentNode.removeChild(div);
return bool;
});
/*!
{
"name": "placeholder attribute",
"property": "placeholder",
"tags": ["forms", "attribute"],
"builderAliases": ["forms_placeholder"]
}
!*/
/* DOC
Tests for placeholder attribute in inputs and textareas
*/
Modernizr.addTest('placeholder', ('placeholder' in createElement('input') && 'placeholder' in createElement('textarea')));
/*!
{
"name": "iframe[sandbox] Attribute",
"property": "sandbox",
"tags": ["iframe"],
"builderAliases": ["iframe_sandbox"],
"notes": [
{
"name": "WhatWG Spec",
"href": "http://www.whatwg.org/specs/web-apps/current-work/multipage/the-iframe-element.html#attr-iframe-sandbox"
}],
"knownBugs": [ "False-positive on Firefox < 29" ]
}
!*/
/* DOC
Test for `sandbox` attribute in iframes.
*/
Modernizr.addTest('sandbox', 'sandbox' in createElement('iframe'));
/*!
{
"name": "iframe[seamless] Attribute",
"property": "seamless",
"tags": ["iframe"],
"builderAliases": ["iframe_seamless"],
"notes": [{
"name": "WhatWG Spec",
"href": "http://www.whatwg.org/specs/web-apps/current-work/multipage/the-iframe-element.html#attr-iframe-seamless"
}]
}
!*/
/* DOC
Test for `seamless` attribute in iframes.
*/
Modernizr.addTest('seamless', 'seamless' in createElement('iframe'));
/*!
{
"name": "iframe[srcdoc] Attribute",
"property": "srcdoc",
"tags": ["iframe"],
"builderAliases": ["iframe_srcdoc"],
"notes": [{
"name": "WhatWG Spec",
"href": "http://www.whatwg.org/specs/web-apps/current-work/multipage/the-iframe-element.html#attr-iframe-srcdoc"
}]
}
!*/
/* DOC
Test for `srcdoc` attribute in iframes.
*/
Modernizr.addTest('srcdoc', 'srcdoc' in createElement('iframe'));
/*!
{
"name": "Animated PNG",
"async": true,
"property": "apng",
"tags": ["image"],
"builderAliases": ["img_apng"],
"notes": [{
"name": "Wikipedia Article",
"href": "http://en.wikipedia.org/wiki/APNG"
}]
}
!*/
/* DOC
Test for animated png support.
*/
Modernizr.addAsyncTest(function() {
if (!Modernizr.canvas) {
return false;
}
var image = new Image();
var canvas = createElement('canvas');
var ctx = canvas.getContext('2d');
image.onload = function() {
addTest('apng', function() {
if (typeof canvas.getContext == 'undefined') {
return false;
}
else {
ctx.drawImage(image, 0, 0);
return ctx.getImageData(0, 0, 1, 1).data[3] === 0;
}
});
};
image.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAACGFjVEwAAAABAAAAAcMq2TYAAAANSURBVAiZY2BgYPgPAAEEAQB9ssjfAAAAGmZjVEwAAAAAAAAAAQAAAAEAAAAAAAAAAAD6A+gBAbNU+2sAAAARZmRBVAAAAAEImWNgYGBgAAAABQAB6MzFdgAAAABJRU5ErkJggg==';
});
/*!
{
"name": "Image crossOrigin",
"property": "imgcrossorigin",
"notes": [{
"name": "Cross Domain Images and the Tainted Canvas",
"href": "http://blog.codepen.io/2013/10/08/cross-domain-images-tainted-canvas/"
}]
}
!*/
/* DOC
Detects support for the crossOrigin attribute on images, which allow for cross domain images inside of a canvas without tainting it
*/
Modernizr.addTest('imgcrossorigin', 'crossOrigin' in createElement('img'));
/*!
{
"name": "sizes attribute",
"async": true,
"property": "sizes",
"tags": ["image"],
"authors": ["Mat Marquis"],
"notes": [{
"name": "Spec",
"href": "http://picture.responsiveimages.org/#parse-sizes-attr"
},{
"name": "Usage Details",
"href": "http://ericportis.com/posts/2014/srcset-sizes/"
}]
}
!*/
/* DOC
Test for the `sizes` attribute on images
*/
Modernizr.addAsyncTest(function() {
var width1, width2, test;
var image = createElement('img');
// in a perfect world this would be the test...
var isSizes = 'sizes' in image;
// ... but we need to deal with Safari 9...
if (!isSizes && ('srcset' in image)) {
width2 = 'data:image/gif;base64,R0lGODlhAgABAPAAAP///wAAACH5BAAAAAAALAAAAAACAAEAAAICBAoAOw==';
width1 = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==';
test = function() {
addTest('sizes', image.width == 2);
};
image.onload = test;
image.onerror = test;
image.setAttribute('sizes', '9px');
image.srcset = width1 + ' 1w,' + width2 + ' 8w';
image.src = width1;
} else {
addTest('sizes', isSizes);
}
});
/*!
{
"name": "srcset attribute",
"property": "srcset",
"tags": ["image"],
"notes": [{
"name": "Smashing Magazine Article",
"href": "http://en.wikipedia.org/wiki/APNG"
},{
"name": "Generate multi-resolution images for srcset with Grunt",
"href": "http://addyosmani.com/blog/generate-multi-resolution-images-for-srcset-with-grunt/"
}]
}
!*/
/* DOC
Test for the srcset attribute of images
*/
Modernizr.addTest('srcset', 'srcset' in createElement('img'));
/*!
{
"name": "input formaction",
"property": "inputformaction",
"aliases": ["input-formaction"],
"notes": [{
"name": "WHATWG Spec",
"href": "http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#attr-fs-formaction"
}, {
"name": "Wufoo demo",
"href": "http://www.wufoo.com/html5/attributes/13-formaction.html"
}],
"polyfills": [
"webshims"
]
}
!*/
/* DOC
Detect support for the formaction attribute on form inputs
*/
Modernizr.addTest('inputformaction', !!('formAction' in createElement('input')), {aliases: ['input-formaction']});
/*!
{
"name": "input formenctype",
"property": "inputformenctype",
"aliases": ["input-formenctype"],
"notes": [{
"name": "WHATWG Spec",
"href": "http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#attr-fs-formenctype"
}, {
"name": "Wufoo demo",
"href": "http://www.wufoo.com/html5/attributes/16-formenctype.html"
}],
"polyfills": [
"html5formshim"
]
}
!*/
/* DOC
Detect support for the formenctype attribute on form inputs, which overrides the form enctype attribute
*/
Modernizr.addTest('inputformenctype', !!('formEnctype' in createElement('input')), {aliases: ['input-formenctype']});
/*!
{
"name": "input formmethod",
"property": "inputformmethod",
"notes": [{
"name": "WHATWG Spec",
"href": "http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#attr-fs-formmethod"
}, {
"name": "Wufoo demo",
"href": "http://www.wufoo.com/html5/attributes/14-formmethod.html"
}],
"polyfills": [
"webshims"
]
}
!*/
/* DOC
Detect support for the formmethod attribute on form inputs
*/
Modernizr.addTest('inputformmethod', !!('formMethod' in createElement('input')));
/*!
{
"name": "input formtarget",
"property": "inputformtarget",
"aliases": ["input-formtarget"],
"notes": [{
"name": "WHATWG Spec",
"href": "http://www.whatwg.org/specs/web-apps/current-work/multipage/association-of-controls-and-forms.html#attr-fs-formtarget"
}, {
"name": "Wufoo demo",
"href": "http://www.wufoo.com/html5/attributes/15-formtarget.html"
}],
"polyfills": [
"html5formshim"
]
}
!*/
/* DOC
Detect support for the formtarget attribute on form inputs, which overrides the form target attribute
*/
Modernizr.addTest('inputformtarget', !!('formtarget' in createElement('input')), {aliases: ['input-formtarget']});
/*!
{
"name": "script[async]",
"property": "scriptasync",
"caniuse": "script-async",
"tags": ["script"],
"builderAliases": ["script_async"],
"authors": ["Theodoor van Donge"]
}
!*/
/* DOC
Detects support for the `async` attribute on the `<script>` element.
*/
Modernizr.addTest('scriptasync', 'async' in createElement('script'));
/*!
{
"name": "script[defer]",
"property": "scriptdefer",
"caniuse": "script-defer",
"tags": ["script"],
"builderAliases": ["script_defer"],
"authors": ["Theodoor van Donge"],
"warnings": ["Browser implementation of the `defer` attribute vary: http://stackoverflow.com/questions/3952009/defer-attribute-chrome#answer-3982619"],
"knownBugs": ["False positive in Opera 12"]
}
!*/
/* DOC
Detects support for the `defer` attribute on the `<script>` element.
*/
Modernizr.addTest('scriptdefer', 'defer' in createElement('script'));
/*!
{
"name": "style[scoped]",
"property": "stylescoped",
"caniuse": "style-scoped",
"tags": ["dom"],
"builderAliases": ["style_scoped"],
"authors": ["Cătălin Mariș"],
"notes": [{
"name": "WHATWG Specification",
"href": "http://www.whatwg.org/specs/web-apps/current-work/multipage/semantics.html#attr-style-scoped"
}],
"polyfills": ["scoped-styles"]
}
!*/
/* DOC
Support for the `scoped` attribute of the `<style>` element.
*/
Modernizr.addTest('stylescoped', 'scoped' in createElement('style'));
/*!
{
"name": "Inline SVG",
"property": "inlinesvg",
"caniuse": "svg-html5",
"tags": ["svg"],
"notes": [{
"name": "Test page",
"href": "http://paulirish.com/demo/inline-svg"
}, {
"name": "Test page and results",
"href": "http://codepen.io/eltonmesquita/full/GgXbvo/"
}],
"polyfills": ["inline-svg-polyfill"],
"knownBugs": ["False negative on some Chromia browsers."]
}
!*/
/* DOC
Detects support for inline SVG in HTML (not within XHTML).
*/
Modernizr.addTest('inlinesvg', function() {
var div = createElement('div');
div.innerHTML = '<svg/>';
return (typeof SVGRect != 'undefined' && div.firstChild && div.firstChild.namespaceURI) == 'http://www.w3.org/2000/svg';
});
/*!
{
"name": "textarea maxlength",
"property": "textareamaxlength",
"aliases": ["textarea-maxlength"],
"notes": [{
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en-US/docs/Web/HTML/Element/textarea"
}],
"polyfills": [
"maxlength"
]
}
!*/
/* DOC
Detect support for the maxlength attribute of a textarea element
*/
Modernizr.addTest('textareamaxlength', !!('maxLength' in createElement('textarea')));
/*!
{
"name": "Video Autoplay",
"property": "videoautoplay",
"tags": ["video"],
"async" : true,
"warnings": ["This test is very large – only include it if you absolutely need it"],
"knownBugs": ["crashes with an alert on iOS7 when added to homescreen"]
}
!*/
/* DOC
Checks for support of the autoplay attribute of the video element.
*/
Modernizr.addAsyncTest(function() {
var timeout;
var waitTime = 300;
var elem = createElement('video');
var elemStyle = elem.style;
function testAutoplay(arg) {
clearTimeout(timeout);
elem.removeEventListener('playing', testAutoplay, false);
addTest('videoautoplay', arg && arg.type === 'playing' || elem.currentTime !== 0);
elem.parentNode.removeChild(elem);
}
//skip the test if video itself, or the autoplay
//element on it isn't supported
if (!Modernizr.video || !('autoplay' in elem)) {
addTest('videoautoplay', false);
return;
}
elemStyle.position = 'absolute';
elemStyle.height = 0;
elemStyle.width = 0;
try {
if (Modernizr.video.ogg) {
elem.src = 'data:video/ogg;base64,T2dnUwACAAAAAAAAAABmnCATAAAAAHDEixYBKoB0aGVvcmEDAgEAAQABAAAQAAAQAAAAAAAFAAAAAQAAAAAAAAAAAGIAYE9nZ1MAAAAAAAAAAAAAZpwgEwEAAAACrA7TDlj///////////////+QgXRoZW9yYSsAAABYaXBoLk9yZyBsaWJ0aGVvcmEgMS4xIDIwMDkwODIyIChUaHVzbmVsZGEpAQAAABoAAABFTkNPREVSPWZmbXBlZzJ0aGVvcmEtMC4yOYJ0aGVvcmG+zSj3uc1rGLWpSUoQc5zmMYxSlKQhCDGMYhCEIQhAAAAAAAAAAAAAEW2uU2eSyPxWEvx4OVts5ir1aKtUKBMpJFoQ/nk5m41mUwl4slUpk4k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IXJ1/3uVUllZEJz4baqGF64yxaZ+zPLYwde8Uqn1oKANtUrSaTOPHkhvuQP3bBlEJ/LFe4pqQOHUI8T8q7AXx3fLVBgSCVpMba55YxN3rv8U1Dv51bAPSOLlZWebkL8vSMGI21lJmmeVxPRwFlZF1CpqCN8uLwymaZyjbXHCRytogPN3o/n74CNykfT+qqRv5AQlHcRxYrC5KvGmbbUwmZY/29BvF6C1/93x4WVglXDLFpmbapmF89HKTogRwqqSlGbu+oiAkcWFbklC6Zhf+NtTLFpn8oWz+HsNRVSgIxZWON+yVyJlE5tq/+GWLTMutYX9ekTySEQPLVNQQ3OfycwJBM0zNtZcse7CvcKI0V/zh16Dr9OSA21MpmmcrHC+6pTAPHPwoit3LHHqs7jhFNRD6W8+EBGoSEoaZttTCZljfduH/fFisn+dRBGAZYtMzbVMwvul/T/crK1NQh8gN0SRRa9cOux6clC0/mDLFpmbarmF8/e6CopeOLCNW6S/IUUg3jJIYiAcDoMcGeRbOvuTPjXR/tyo79LK3kqqkbxkkMRAOB0GODPItnX3Jnxro/25Ud+llbyVVSN4ySGIgHA6DHBnkWzr7kz410f7cqO/Syt5KqpFVJwn6gBEvBM0zNtZcpGOEPiysW8vvRd2R0f7gtjhqUvXL+gWVwHm4XJDBiMpmmZtrLfPwd/IugP5+fKVSysH1EXreFAcEhelGmbbUmZY4Xdo1vQWVnK19P4RuEnbf0gQnR+lDCZlivNM22t1ESmopPIgfT0duOfQrsjgG4tPxli0zJmF5trdL1JDUIUT1ZXSqQDeR4B8mX3TrRro/2McGeUvLtwo6jIEKMkCUXWsLyZROd9P/rFYNtXPBli0z398iVUlVKAjFlY437JXImUTm2r/4ZYtMy61hf16RPJIU9nZ1MABAwAAAAAAAAAZpwgEwIAAABhp658BScAAAAAAADnUFBQXIDGXLhwtttNHDhw5OcpQRMETBEwRPduylKVB0HRdF0A';
}
else if (Modernizr.video.h264) {
elem.src = 'data:video/mp4;base64,AAAAIGZ0eXBpc29tAAACAGlzb21pc28yYXZjM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AAAEAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAACGHRyYWsAAABcdGtoZAAAAAMAAAAAAAAAAAAAAAEAAAAAAAAAZAAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAEAAAAAAAgAAAAIAAAAAACRlZHRzAAAAHGVsc3QAAAAAAAAAAQAAAGQAAAAAAAEAAAAAAZBtZGlhAAAAIG1kaGQAAAAAAAAAAAAAAAAAACgAAAAEAFXEAAAAAAAtaGRscgAAAAAAAAAAdmlkZQAAAAAAAAAAAAAAAFZpZGVvSGFuZGxlcgAAAAE7bWluZgAAABR2bWhkAAAAAQAAAAAAAAAAAAAAJGRpbmYAAAAcZHJlZgAAAAAAAAABAAAADHVybCAAAAABAAAA+3N0YmwAAACXc3RzZAAAAAAAAAABAAAAh2F2YzEAAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAgACAEgAAABIAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAY//8AAAAxYXZjQwFkAAr/4QAYZ2QACqzZX4iIhAAAAwAEAAADAFA8SJZYAQAGaOvjyyLAAAAAGHN0dHMAAAAAAAAAAQAAAAEAAAQAAAAAHHN0c2MAAAAAAAAAAQAAAAEAAAABAAAAAQAAABRzdHN6AAAAAAAAAsUAAAABAAAAFHN0Y28AAAAAAAAAAQAAADAAAABidWR0YQAAAFptZXRhAAAAAAAAACFoZGxyAAAAAAAAAABtZGlyYXBwbAAAAAAAAAAAAAAAAC1pbHN0AAAAJal0b28AAAAdZGF0YQAAAAEAAAAATGF2ZjU2LjQwLjEwMQ==';
}
else {
addTest('videoautoplay', false);
return;
}
}
catch (e) {
addTest('videoautoplay', false);
return;
}
elem.setAttribute('autoplay', '');
elem.style.cssText = 'display:none';
docElement.appendChild(elem);
// wait for the next tick to add the listener, otherwise the element may
// not have time to play in high load situations (e.g. the test suite)
setTimeout(function() {
elem.addEventListener('playing', testAutoplay, false);
timeout = setTimeout(testAutoplay, waitTime);
}, 0);
});
/*!
{
"name": "Video Loop Attribute",
"property": "videoloop",
"tags": ["video", "media"]
}
!*/
Modernizr.addTest('videoloop', 'loop' in createElement('video'));
/*!
{
"name": "Video Preload Attribute",
"property": "videopreload",
"tags": ["video", "media"]
}
!*/
Modernizr.addTest('videopreload', 'preload' in createElement('video'));
/*!
{
"name": "WebGL Extensions",
"property": "webglextensions",
"tags": ["webgl", "graphics"],
"builderAliases": ["webgl_extensions"],
"async" : true,
"authors": ["Ilmari Heikkinen"],
"knownBugs": [],
"notes": [{
"name": "Kronos extensions registry",
"href": "http://www.khronos.org/registry/webgl/extensions/"
}]
}
!*/
/* DOC
Detects support for OpenGL extensions in WebGL. It's `true` if the [WebGL extensions API](https://developer.mozilla.org/en-US/docs/Web/WebGL/Using_Extensions) is supported, then exposes the supported extensions as subproperties, e.g.:
```javascript
if (Modernizr.webglextensions) {
// WebGL extensions API supported
}
if ('OES_vertex_array_object' in Modernizr.webglextensions) {
// Vertex Array Objects extension supported
}
```
*/
// based on code from ilmari heikkinen
// code.google.com/p/graphics-detect/source/browse/js/detect.js
// Not Async but handles it's own self
Modernizr.addAsyncTest(function() {
/* jshint -W053 */
// Not a good candidate for css classes, so we avoid addTest stuff
Modernizr.webglextensions = new Boolean(false);
if (!Modernizr.webgl) {
return;
}
var canvas;
var ctx;
var exts;
try {
canvas = createElement('canvas');
ctx = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
exts = ctx.getSupportedExtensions();
}
catch (e) {
return;
}
if (ctx !== undefined) {
Modernizr.webglextensions = new Boolean(true);
}
for (var i = -1, len = exts.length; ++i < len;) {
Modernizr.webglextensions[exts[i]] = true;
}
canvas = undefined;
});
/**
* cssToDOM takes a kebab-case string and converts it to camelCase
* e.g. box-sizing -> boxSizing
*
* @access private
* @function cssToDOM
* @param {string} name - String name of kebab-case prop we want to convert
* @returns {string} The camelCase version of the supplied name
*/
function cssToDOM(name) {
return name.replace(/([a-z])-([a-z])/g, function(str, m1, m2) {
return m1 + m2.toUpperCase();
}).replace(/^-/, '');
}
;
/**
* domToCSS takes a camelCase string and converts it to kebab-case
* e.g. boxSizing -> box-sizing
*
* @access private
* @function domToCSS
* @param {string} name - String name of camelCase prop we want to convert
* @returns {string} The kebab-case version of the supplied name
*/
function domToCSS(name) {
return name.replace(/([A-Z])/g, function(str, m1) {
return '-' + m1.toLowerCase();
}).replace(/^ms-/, '-ms-');
}
;
/**
* getBody returns the body of a document, or an element that can stand in for
* the body if a real body does not exist
*
* @access private
* @function getBody
* @returns {HTMLElement|SVGElement} Returns the real body of a document, or an
* artificially created element that stands in for the body
*/
function getBody() {
// After page load injecting a fake body doesn't work so check if body exists
var body = document.body;
if (!body) {
// Can't use the real body create a fake one.
body = createElement(isSVG ? 'svg' : 'body');
body.fake = true;
}
return body;
}
;
/*!
{
"name": "Flash",
"property": "flash",
"tags": ["flash"],
"polyfills": ["shumway"]
}
!*/
/* DOC
Detects Flash support as well as Flash-blocking plugins
*/
Modernizr.addAsyncTest(function() {
/* jshint -W053 */
var attachBody = function(body) {
if (!docElement.contains(body)) {
docElement.appendChild(body);
}
};
var removeFakeBody = function(body) {
// If we’re rockin’ an attached fake body, clean it up
if (body.fake && body.parentNode) {
body.parentNode.removeChild(body);
}
};
var runTest = function(result, embed) {
var bool = !!result;
if (bool) {
bool = new Boolean(bool);
bool.blocked = (result === 'blocked');
}
addTest('flash', function() { return bool; });
if (embed && body.contains(embed)) {
// in case embed has been wrapped, as with ClickToPlugin
while (embed.parentNode !== body) {
embed = embed.parentNode;
}
body.removeChild(embed);
}
};
var easy_detect;
var activex;
// we wrap activex in a try/catch because when Flash is disabled through
// ActiveX controls, it throws an error.
try {
// Pan is an API that exists for Flash objects.
activex = 'ActiveXObject' in window && 'Pan' in new window.ActiveXObject('ShockwaveFlash.ShockwaveFlash');
} catch (e) {}
easy_detect = !(('plugins' in navigator && 'Shockwave Flash' in navigator.plugins) || activex);
if (easy_detect || isSVG) {
runTest(false);
}
else {
// Flash seems to be installed, but it might be blocked. We have to
// actually create an element to see what happens to it.
var embed = createElement('embed');
var body = getBody();
var blockedDetect;
var inline_style;
embed.type = 'application/x-shockwave-flash';
// Need to do this in the body (fake or otherwise) otherwise IE8 complains
body.appendChild(embed);
// Pan doesn't exist in the embed if its IE (its on the ActiveXObjeect)
// so this check is for all other browsers.
if (!('Pan' in embed) && !activex) {
attachBody(body);
runTest('blocked', embed);
removeFakeBody(body);
return;
}
blockedDetect = function() {
// if we used a fake body originally, we need to restart this test, since
// we haven't been attached to the DOM, and therefore none of the blockers
// have had time to work.
attachBody(body);
if (!docElement.contains(body)) {
body = document.body || body;
embed = createElement('embed');
embed.type = 'application/x-shockwave-flash';
body.appendChild(embed);
return setTimeout(blockedDetect, 1000);
}
if (!docElement.contains(embed)) {
runTest('blocked');
}
else {
inline_style = embed.style.cssText;
if (inline_style !== '') {
// the style of the element has changed automatically. This is a
// really poor heuristic, but for lower end Flash blocks, it the
// only change they can make.
runTest('blocked', embed);
}
else {
runTest(true, embed);
}
}
removeFakeBody(body);
};
// If we have got this far, there is still a chance a userland plugin
// is blocking us (either changing the styles, or automatically removing
// the element). Both of these require us to take a step back for a moment
// to allow for them to get time of the thread, hence a setTimeout.
//
setTimeout(blockedDetect, 10);
}
});
/**
* injectElementWithStyles injects an element with style element and some CSS rules
*
* @access private
* @function injectElementWithStyles
* @param {string} rule - String representing a css rule
* @param {function} callback - A function that is used to test the injected element
* @param {number} [nodes] - An integer representing the number of additional nodes you want injected
* @param {string[]} [testnames] - An array of strings that are used as ids for the additional nodes
* @returns {boolean}
*/
function injectElementWithStyles(rule, callback, nodes, testnames) {
var mod = 'modernizr';
var style;
var ret;
var node;
var docOverflow;
var div = createElement('div');
var body = getBody();
if (parseInt(nodes, 10)) {
// In order not to give false positives we create a node for each test
// This also allows the method to scale for unspecified uses
while (nodes--) {
node = createElement('div');
node.id = testnames ? testnames[nodes] : mod + (nodes + 1);
div.appendChild(node);
}
}
style = createElement('style');
style.type = 'text/css';
style.id = 's' + mod;
// IE6 will false positive on some tests due to the style element inside the test div somehow interfering offsetHeight, so insert it into body or fakebody.
// Opera will act all quirky when injecting elements in documentElement when page is served as xml, needs fakebody too. #270
(!body.fake ? div : body).appendChild(style);
body.appendChild(div);
if (style.styleSheet) {
style.styleSheet.cssText = rule;
} else {
style.appendChild(document.createTextNode(rule));
}
div.id = mod;
if (body.fake) {
//avoid crashing IE8, if background image is used
body.style.background = '';
//Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible
body.style.overflow = 'hidden';
docOverflow = docElement.style.overflow;
docElement.style.overflow = 'hidden';
docElement.appendChild(body);
}
ret = callback(div, rule);
// If this is done after page load we don't want to remove the body so check if body exists
if (body.fake) {
body.parentNode.removeChild(body);
docElement.style.overflow = docOverflow;
// Trigger layout so kinetic scrolling isn't disabled in iOS6+
docElement.offsetHeight;
} else {
div.parentNode.removeChild(div);
}
return !!ret;
}
;
/**
* Modernizr.mq tests a given media query, live against the current state of the window
* adapted from matchMedia polyfill by Scott Jehl and Paul Irish
* gist.github.com/786768
*
* @memberof Modernizr
* @name Modernizr.mq
* @optionName Modernizr.mq()
* @optionProp mq
* @access public
* @function mq
* @param {string} mq - String of the media query we want to test
* @returns {boolean}
* @example
* Modernizr.mq allows for you to programmatically check if the current browser
* window state matches a media query.
*
* ```js
* var query = Modernizr.mq('(min-width: 900px)');
*
* if (query) {
* // the browser window is larger than 900px
* }
* ```
*
* Only valid media queries are supported, therefore you must always include values
* with your media query
*
* ```js
* // good
* Modernizr.mq('(min-width: 900px)');
*
* // bad
* Modernizr.mq('min-width');
* ```
*
* If you would just like to test that media queries are supported in general, use
*
* ```js
* Modernizr.mq('only all'); // true if MQ are supported, false if not
* ```
*
*
* Note that if the browser does not support media queries (e.g. old IE) mq will
* always return false.
*/
var mq = (function() {
var matchMedia = window.matchMedia || window.msMatchMedia;
if (matchMedia) {
return function(mq) {
var mql = matchMedia(mq);
return mql && mql.matches || false;
};
}
return function(mq) {
var bool = false;
injectElementWithStyles('@media ' + mq + ' { #modernizr { position: absolute; } }', function(node) {
bool = (window.getComputedStyle ?
window.getComputedStyle(node, null) :
node.currentStyle).position == 'absolute';
});
return bool;
};
})();
ModernizrProto.mq = mq;
/*!
{
"name": "CSS Media Queries",
"caniuse": "css-mediaqueries",
"property": "mediaqueries",
"tags": ["css"],
"builderAliases": ["css_mediaqueries"]
}
!*/
Modernizr.addTest('mediaqueries', mq('only all'));
/**
* testStyles injects an element with style element and some CSS rules
*
* @memberof Modernizr
* @name Modernizr.testStyles
* @optionName Modernizr.testStyles()
* @optionProp testStyles
* @access public
* @function testStyles
* @param {string} rule - String representing a css rule
* @param {function} callback - A function that is used to test the injected element
* @param {number} [nodes] - An integer representing the number of additional nodes you want injected
* @param {string[]} [testnames] - An array of strings that are used as ids for the additional nodes
* @returns {boolean}
* @example
*
* `Modernizr.testStyles` takes a CSS rule and injects it onto the current page
* along with (possibly multiple) DOM elements. This lets you check for features
* that can not be detected by simply checking the [IDL](https://developer.mozilla.org/en-US/docs/Mozilla/Developer_guide/Interface_development_guide/IDL_interface_rules).
*
* ```js
* Modernizr.testStyles('#modernizr { width: 9px; color: papayawhip; }', function(elem, rule) {
* // elem is the first DOM node in the page (by default #modernizr)
* // rule is the first argument you supplied - the CSS rule in string form
*
* addTest('widthworks', elem.style.width === '9px')
* });
* ```
*
* If your test requires multiple nodes, you can include a third argument
* indicating how many additional div elements to include on the page. The
* additional nodes are injected as children of the `elem` that is returned as
* the first argument to the callback.
*
* ```js
* Modernizr.testStyles('#modernizr {width: 1px}; #modernizr2 {width: 2px}', function(elem) {
* document.getElementById('modernizr').style.width === '1px'; // true
* document.getElementById('modernizr2').style.width === '2px'; // true
* elem.firstChild === document.getElementById('modernizr2'); // true
* }, 1);
* ```
*
* By default, all of the additional elements have an ID of `modernizr[n]`, where
* `n` is its index (e.g. the first additional, second overall is `#modernizr2`,
* the second additional is `#modernizr3`, etc.).
* If you want to have more meaningful IDs for your function, you can provide
* them as the fourth argument, as an array of strings
*
* ```js
* Modernizr.testStyles('#foo {width: 10px}; #bar {height: 20px}', function(elem) {
* elem.firstChild === document.getElementById('foo'); // true
* elem.lastChild === document.getElementById('bar'); // true
* }, 2, ['foo', 'bar']);
* ```
*
*/
var testStyles = ModernizrProto.testStyles = injectElementWithStyles;
/*!
{
"name": "Hidden Scrollbar",
"property": "hiddenscroll",
"authors": ["Oleg Korsunsky"],
"tags": ["overlay"],
"notes": [{
"name": "Overlay Scrollbar description",
"href": "https://developer.apple.com/library/mac/releasenotes/MacOSX/WhatsNewInOSX/Articles/MacOSX10_7.html#//apple_ref/doc/uid/TP40010355-SW39"
},{
"name": "Video example of overlay scrollbars",
"href": "http://gfycat.com/FoolishMeaslyAtlanticsharpnosepuffer"
}]
}
!*/
/* DOC
Detects overlay scrollbars (when scrollbars on overflowed blocks are visible). This is found most commonly on mobile and OS X.
*/
Modernizr.addTest('hiddenscroll', function() {
return testStyles('#modernizr {width:100px;height:100px;overflow:scroll}', function(elem) {
return elem.offsetWidth === elem.clientWidth;
});
});
/*!
{
"name": "MathML",
"property": "mathml",
"caniuse": "mathml",
"authors": ["Addy Osmani", "Davide P. Cervone", "David Carlisle"],
"knownBugs": ["Firefox < 4 will likely return a false, however it does support MathML inside XHTML documents"],
"notes": [{
"name": "W3C spec",
"href": "http://www.w3.org/Math/"
}],
"polyfills": ["mathjax"]
}
!*/
/* DOC
Detects support for MathML, for mathematic equations in web pages.
*/
// Based on work by Davide (@dpvc) and David (@davidcarlisle)
// in https://github.com/mathjax/MathJax/issues/182
Modernizr.addTest('mathml', function() {
var ret;
testStyles('#modernizr{position:absolute;display:inline-block}', function(node) {
node.innerHTML += '<math><mfrac><mi>xx</mi><mi>yy</mi></mfrac></math>';
ret = node.offsetHeight > node.offsetWidth;
});
return ret;
});
/*!
{
"name": "Touch Events",
"property": "touchevents",
"caniuse" : "touch",
"tags": ["media", "attribute"],
"notes": [{
"name": "Touch Events spec",
"href": "http://www.w3.org/TR/2013/WD-touch-events-20130124/"
}],
"warnings": [
"Indicates if the browser supports the Touch Events spec, and does not necessarily reflect a touchscreen device"
],
"knownBugs": [
"False-positive on some configurations of Nokia N900",
"False-positive on some BlackBerry 6.0 builds – https://github.com/Modernizr/Modernizr/issues/372#issuecomment-3112695"
]
}
!*/
/* DOC
Indicates if the browser supports the W3C Touch Events API.
This *does not* necessarily reflect a touchscreen device:
* Older touchscreen devices only emulate mouse events
* Modern IE touch devices implement the Pointer Events API instead: use `Modernizr.pointerevents` to detect support for that
* Some browsers & OS setups may enable touch APIs when no touchscreen is connected
* Future browsers may implement other event models for touch interactions
See this article: [You Can't Detect A Touchscreen](http://www.stucox.com/blog/you-cant-detect-a-touchscreen/).
It's recommended to bind both mouse and touch/pointer events simultaneously – see [this HTML5 Rocks tutorial](http://www.html5rocks.com/en/mobile/touchandmouse/).
This test will also return `true` for Firefox 4 Multitouch support.
*/
// Chrome (desktop) used to lie about its support on this, but that has since been rectified: http://crbug.com/36415
Modernizr.addTest('touchevents', function() {
var bool;
if (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
bool = true;
} else {
var query = ['@media (', prefixes.join('touch-enabled),('), 'heartz', ')', '{#modernizr{top:9px;position:absolute}}'].join('');
testStyles(query, function(node) {
bool = node.offsetTop === 9;
});
}
return bool;
});
/*!
{
"name": "Unicode Range",
"property": "unicoderange",
"notes": [{
"name" : "W3C reference",
"href": "http://www.w3.org/TR/2013/CR-css-fonts-3-20131003/#descdef-unicode-range"
}, {
"name" : "24 Way article",
"href": "http://24ways.org/2011/creating-custom-font-stacks-with-unicode-range"
}]
}
!*/
Modernizr.addTest('unicoderange', function() {
return Modernizr.testStyles('@font-face{font-family:"unicodeRange";src:local("Arial");unicode-range:U+0020,U+002E}#modernizr span{font-size:20px;display:inline-block;font-family:"unicodeRange",monospace}#modernizr .mono{font-family:monospace}', function(elem) {
// we use specify a unicode-range of 002E (the `.` glyph,
// and a monospace font as the fallback. If the first of
// these test glyphs is a different width than the other
// the other three (which are all monospace), then we
// have a winner.
var testGlyphs = ['.', '.', 'm', 'm'];
for (var i = 0; i < testGlyphs.length; i++) {
var elm = createElement('span');
elm.innerHTML = testGlyphs[i];
elm.className = i % 2 ? 'mono' : '';
elem.appendChild(elm);
testGlyphs[i] = elm.clientWidth;
}
return (testGlyphs[0] !== testGlyphs[1] && testGlyphs[2] === testGlyphs[3]);
});
});
/*!
{
"name": "Unicode characters",
"property": "unicode",
"tags": ["encoding"],
"warnings": [
"positive Unicode support doesn't mean you can use it inside <title>, this seems more related to OS & Language packs"
]
}
!*/
/* DOC
Detects if unicode characters are supported in the current document.
*/
/**
* Unicode special character support
*
* Detection is made by testing missing glyph box rendering against star character
* If widths are the same, this "probably" means the browser didn't support the star character and rendered a glyph box instead
* Just need to ensure the font characters have different widths
*/
Modernizr.addTest('unicode', function() {
var bool;
var missingGlyph = createElement('span');
var star = createElement('span');
testStyles('#modernizr{font-family:Arial,sans;font-size:300em;}', function(node) {
missingGlyph.innerHTML = isSVG ? '\u5987' : 'ᝣ';
star.innerHTML = isSVG ? '\u2606' : '☆';
node.appendChild(missingGlyph);
node.appendChild(star);
bool = 'offsetWidth' in missingGlyph && missingGlyph.offsetWidth !== star.offsetWidth;
});
return bool;
});
/*!
{
"name": "CSS :checked pseudo-selector",
"caniuse": "css-sel3",
"property": "checked",
"tags": ["css"],
"notes": [{
"name": "Related Github Issue",
"href": "https://github.com/Modernizr/Modernizr/pull/879"
}]
}
!*/
Modernizr.addTest('checked', function() {
return testStyles('#modernizr {position:absolute} #modernizr input {margin-left:10px} #modernizr :checked {margin-left:20px;display:block}', function(elem) {
var cb = createElement('input');
cb.setAttribute('type', 'checkbox');
cb.setAttribute('checked', 'checked');
elem.appendChild(cb);
return cb.offsetLeft === 20;
});
});
/*!
{
"name": "CSS Display table",
"property": "displaytable",
"caniuse": "css-table",
"authors": ["scottjehl"],
"tags": ["css"],
"builderAliases": ["css_displaytable"],
"notes": [{
"name": "Detects for all additional table display values",
"href": "http://pastebin.com/Gk9PeVaQ"
}]
}
!*/
/* DOC
`display: table` and `table-cell` test. (both are tested under one name `table-cell` )
*/
// If a document is in rtl mode this test will fail so we force ltr mode on the injeced
// element https://github.com/Modernizr/Modernizr/issues/716
testStyles('#modernizr{display: table; direction: ltr}#modernizr div{display: table-cell; padding: 10px}', function(elem) {
var ret;
var child = elem.childNodes;
ret = child[0].offsetLeft < child[1].offsetLeft;
Modernizr.addTest('displaytable', ret, {aliases: ['display-table']});
}, 2);
/*!
{
"name": "@font-face",
"property": "fontface",
"authors": ["Diego Perini", "Mat Marquis"],
"tags": ["css"],
"knownBugs": [
"False Positive: WebOS http://github.com/Modernizr/Modernizr/issues/342",
"False Postive: WP7 http://github.com/Modernizr/Modernizr/issues/538"
],
"notes": [{
"name": "@font-face detection routine by Diego Perini",
"href": "http://javascript.nwbox.com/CSSSupport/"
},{
"name": "Filament Group @font-face compatibility research",
"href": "https://docs.google.com/presentation/d/1n4NyG4uPRjAA8zn_pSQ_Ket0RhcWC6QlZ6LMjKeECo0/edit#slide=id.p"
},{
"name": "Filament Grunticon/@font-face device testing results",
"href": "https://docs.google.com/spreadsheet/ccc?key=0Ag5_yGvxpINRdHFYeUJPNnZMWUZKR2ItMEpRTXZPdUE#gid=0"
},{
"name": "CSS fonts on Android",
"href": "http://stackoverflow.com/questions/3200069/css-fonts-on-android"
},{
"name": "@font-face and Android",
"href": "http://archivist.incutio.com/viewlist/css-discuss/115960"
}]
}
!*/
var blacklist = (function() {
var ua = navigator.userAgent;
var wkvers = ua.match(/applewebkit\/([0-9]+)/gi) && parseFloat(RegExp.$1);
var webos = ua.match(/w(eb)?osbrowser/gi);
var wppre8 = ua.match(/windows phone/gi) && ua.match(/iemobile\/([0-9])+/gi) && parseFloat(RegExp.$1) >= 9;
var oldandroid = wkvers < 533 && ua.match(/android/gi);
return webos || oldandroid || wppre8;
}());
if (blacklist) {
Modernizr.addTest('fontface', false);
} else {
testStyles('@font-face {font-family:"font";src:url("https://")}', function(node, rule) {
var style = document.getElementById('smodernizr');
var sheet = style.sheet || style.styleSheet;
var cssText = sheet ? (sheet.cssRules && sheet.cssRules[0] ? sheet.cssRules[0].cssText : sheet.cssText || '') : '';
var bool = /src/i.test(cssText) && cssText.indexOf(rule.split(' ')[0]) === 0;
Modernizr.addTest('fontface', bool);
});
}
;
/*!
{
"name": "CSS Generated Content",
"property": "generatedcontent",
"tags": ["css"],
"warnings": ["Android won't return correct height for anything below 7px #738"],
"notes": [{
"name": "W3C CSS Selectors Level 3 spec",
"href": "http://www.w3.org/TR/css3-selectors/#gen-content"
},{
"name": "MDN article on :before",
"href": "https://developer.mozilla.org/en-US/docs/Web/CSS/::before"
},{
"name": "MDN article on :after",
"href": "https://developer.mozilla.org/en-US/docs/Web/CSS/::before"
}]
}
!*/
testStyles('#modernizr{font:0/0 a}#modernizr:after{content:":)";visibility:hidden;font:7px/1 a}', function(node) {
Modernizr.addTest('generatedcontent', node.offsetHeight >= 7);
});
/*! {
"name": "hairline",
"property": "csshairline",
"tags": ["css"],
"authors": ["strarsis"],
"notes": [{
"name": "Blog post about CSS retina hairlines",
"href": "http://dieulot.net/css-retina-hairline"
},{
"name": "Derived from",
"href": "https://gist.github.com/dieulot/520a49463f6058fbc8d1"
}]
}
!*/
/* DOC
Detects support for hidpi/retina hairlines, which are CSS borders with less than 1px in width, for being physically 1px on hidpi screens.
*/
Modernizr.addTest('hairline', function() {
return testStyles('#modernizr {border:.5px solid transparent}', function(elem) {
return elem.offsetHeight === 1;
});
});
/*!
{
"name": "CSS :invalid pseudo-class",
"property": "cssinvalid",
"notes": [{
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en-US/docs/Web/CSS/:invalid"
}]
}
!*/
/* DOC
Detects support for the ':invalid' CSS pseudo-class.
*/
Modernizr.addTest('cssinvalid', function() {
return testStyles('#modernizr input{height:0;border:0;padding:0;margin:0;width:10px} #modernizr input:invalid{width:50px}', function(elem) {
var input = createElement('input');
input.required = true;
elem.appendChild(input);
return input.clientWidth > 10;
});
});
/*!
{
"name": "CSS :last-child pseudo-selector",
"caniuse": "css-sel3",
"property": "lastchild",
"tags": ["css"],
"builderAliases": ["css_lastchild"],
"notes": [{
"name": "Related Github Issue",
"href": "https://github.com/Modernizr/Modernizr/pull/304"
}]
}
!*/
testStyles('#modernizr div {width:100px} #modernizr :last-child{width:200px;display:block}', function(elem) {
Modernizr.addTest('lastchild', elem.lastChild.offsetWidth > elem.firstChild.offsetWidth);
}, 2);
/*!
{
"name": "CSS :nth-child pseudo-selector",
"caniuse": "css-sel3",
"property": "nthchild",
"tags": ["css"],
"notes": [
{
"name": "Related Github Issue",
"href": "https://github.com/Modernizr/Modernizr/pull/685"
},
{
"name": "Sitepoint :nth-child documentation",
"href": "http://reference.sitepoint.com/css/pseudoclass-nthchild"
}
],
"authors": ["@emilchristensen"],
"warnings": ["Known false negative in Safari 3.1 and Safari 3.2.2"]
}
!*/
/* DOC
Detects support for the ':nth-child()' CSS pseudo-selector.
*/
// 5 `<div>` elements with `1px` width are created.
// Then every other element has its `width` set to `2px`.
// A Javascript loop then tests if the `<div>`s have the expected width
// using the modulus operator.
testStyles('#modernizr div {width:1px} #modernizr div:nth-child(2n) {width:2px;}', function(elem) {
var elems = elem.getElementsByTagName('div');
var correctWidths = true;
for (var i = 0; i < 5; i++) {
correctWidths = correctWidths && elems[i].offsetWidth === i % 2 + 1;
}
Modernizr.addTest('nthchild', correctWidths);
}, 5);
/*!
{
"name": "CSS Stylable Scrollbars",
"property": "cssscrollbar",
"tags": ["css"],
"builderAliases": ["css_scrollbars"]
}
!*/
testStyles('#modernizr{overflow: scroll; width: 40px; height: 40px; }#' + prefixes
.join('scrollbar{width:0px}' + ' #modernizr::')
.split('#')
.slice(1)
.join('#') + 'scrollbar{width:0px}',
function(node) {
Modernizr.addTest('cssscrollbar', node.scrollWidth == 40);
});
/*!
{
"name": "CSS general sibling selector",
"caniuse": "css-sel3",
"property": "siblinggeneral",
"tags": ["css"],
"notes": [{
"name": "Related Github Issue",
"href": "https://github.com/Modernizr/Modernizr/pull/889"
}]
}
!*/
Modernizr.addTest('siblinggeneral', function() {
return testStyles('#modernizr div {width:100px} #modernizr div ~ div {width:200px;display:block}', function(elem) {
return elem.lastChild.offsetWidth == 200;
}, 2);
});
/*!
{
"name": "CSS Subpixel Fonts",
"property": "subpixelfont",
"tags": ["css"],
"builderAliases": ["css_subpixelfont"],
"authors": [
"@derSchepp",
"@gerritvanaaken",
"@rodneyrehm",
"@yatil",
"@ryanseddon"
],
"notes": [{
"name": "Origin Test",
"href": "https://github.com/gerritvanaaken/subpixeldetect"
}]
}
!*/
/*
* (to infer if GDI or DirectWrite is used on Windows)
*/
testStyles(
'#modernizr{position: absolute; top: -10em; visibility:hidden; font: normal 10px arial;}#subpixel{float: left; font-size: 33.3333%;}',
function(elem) {
var subpixel = elem.firstChild;
subpixel.innerHTML = 'This is a text written in Arial';
Modernizr.addTest('subpixelfont', window.getComputedStyle ?
window.getComputedStyle(subpixel, null).getPropertyValue('width') !== '44px'
: false);
}, 1, ['subpixel']);
/*!
{
"name": "CSS :valid pseudo-class",
"property": "cssvalid",
"notes": [{
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en-US/docs/Web/CSS/:valid"
}]
}
!*/
/* DOC
Detects support for the ':valid' CSS pseudo-class.
*/
Modernizr.addTest('cssvalid', function() {
return testStyles('#modernizr input{height:0;border:0;padding:0;margin:0;width:10px} #modernizr input:valid{width:50px}', function(elem) {
var input = createElement('input');
elem.appendChild(input);
return input.clientWidth > 10;
});
});
/*!
{
"name": "CSS vh unit",
"property": "cssvhunit",
"caniuse": "viewport-units",
"tags": ["css"],
"builderAliases": ["css_vhunit"],
"notes": [{
"name": "Related Modernizr Issue",
"href": "https://github.com/Modernizr/Modernizr/issues/572"
},{
"name": "Similar JSFiddle",
"href": "http://jsfiddle.net/FWeinb/etnYC/"
}]
}
!*/
testStyles('#modernizr { height: 50vh; }', function(elem) {
var height = parseInt(window.innerHeight / 2, 10);
var compStyle = parseInt((window.getComputedStyle ?
getComputedStyle(elem, null) :
elem.currentStyle).height, 10);
Modernizr.addTest('cssvhunit', compStyle == height);
});
/*!
{
"name": "CSS vw unit",
"property": "cssvwunit",
"caniuse": "viewport-units",
"tags": ["css"],
"builderAliases": ["css_vwunit"],
"notes": [{
"name": "Related Modernizr Issue",
"href": "https://github.com/Modernizr/Modernizr/issues/572"
},{
"name": "JSFiddle Example",
"href": "http://jsfiddle.net/FWeinb/etnYC/"
}]
}
!*/
testStyles('#modernizr { width: 50vw; }', function(elem) {
var width = parseInt(window.innerWidth / 2, 10);
var compStyle = parseInt((window.getComputedStyle ?
getComputedStyle(elem, null) :
elem.currentStyle).width, 10);
Modernizr.addTest('cssvwunit', compStyle == width);
});
/*!
{
"name": "details Element",
"caniuse": "details",
"property": "details",
"tags": ["elem"],
"builderAliases": ["elem_details"],
"authors": ["@mathias"],
"notes": [{
"name": "Mathias' Original",
"href": "http://mths.be/axh"
}]
}
!*/
Modernizr.addTest('details', function() {
var el = createElement('details');
var diff;
// return early if possible; thanks @aFarkas!
if (!('open' in el)) {
return false;
}
testStyles('#modernizr details{display:block}', function(node) {
node.appendChild(el);
el.innerHTML = '<summary>a</summary>b';
diff = el.offsetHeight;
el.open = true;
diff = diff != el.offsetHeight;
});
return diff;
});
/*!
{
"name": "onInput Event",
"property": "oninput",
"notes": [{
"name": "MDN article",
"href": "https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.oninput"
},{
"name": "WHATWG spec",
"href": "http://www.whatwg.org/specs/web-apps/current-work/multipage/common-input-element-attributes.html#common-event-behaviors"
},{
"name": "Detecting onInput support",
"href": "http://danielfriesen.name/blog/2010/02/16/html5-browser-maze-oninput-support"
}],
"authors": ["Patrick Kettner"],
"tags": ["event"]
}
!*/
/* DOC
`oninput` tests if the browser is able to detect the input event
*/
Modernizr.addTest('oninput', function() {
var input = createElement('input');
var supportsOnInput;
input.setAttribute('oninput', 'return');
if (hasEvent('oninput', docElement) || typeof input.oninput == 'function') {
return true;
}
// IE doesn't support onInput, so we wrap up the non IE APIs
// (createEvent, addEventListener) in a try catch, rather than test for
// their trident equivalent.
try {
// Older Firefox didn't map oninput attribute to oninput property
var testEvent = document.createEvent('KeyboardEvent');
supportsOnInput = false;
var handler = function(e) {
supportsOnInput = true;
e.preventDefault();
e.stopPropagation();
};
testEvent.initKeyEvent('keypress', true, true, window, false, false, false, false, 0, 'e'.charCodeAt(0));
docElement.appendChild(input);
input.addEventListener('input', handler, false);
input.focus();
input.dispatchEvent(testEvent);
input.removeEventListener('input', handler, false);
docElement.removeChild(input);
} catch (e) {
supportsOnInput = false;
}
return supportsOnInput;
});
/*!
{
"name": "Form Validation",
"property": "formvalidation",
"tags": ["forms", "validation", "attribute"],
"builderAliases": ["forms_validation"]
}
!*/
/* DOC
This implementation only tests support for interactive form validation.
To check validation for a specific type or a specific other constraint,
the test can be combined:
- `Modernizr.inputtypes.number && Modernizr.formvalidation` (browser supports rangeOverflow, typeMismatch etc. for type=number)
- `Modernizr.input.required && Modernizr.formvalidation` (browser supports valueMissing)
*/
Modernizr.addTest('formvalidation', function() {
var form = createElement('form');
if (!('checkValidity' in form) || !('addEventListener' in form)) {
return false;
}
if ('reportValidity' in form) {
return true;
}
var invalidFired = false;
var input;
Modernizr.formvalidationapi = true;
// Prevent form from being submitted
form.addEventListener('submit', function(e) {
// Old Presto based Opera does not validate form, if submit is prevented
// although Opera Mini servers use newer Presto.
if (!window.opera || window.operamini) {
e.preventDefault();
}
e.stopPropagation();
}, false);
// Calling form.submit() doesn't trigger interactive validation,
// use a submit button instead
//older opera browsers need a name attribute
form.innerHTML = '<input name="modTest" required><button></button>';
testStyles('#modernizr form{position:absolute;top:-99999em}', function(node) {
node.appendChild(form);
input = form.getElementsByTagName('input')[0];
// Record whether "invalid" event is fired
input.addEventListener('invalid', function(e) {
invalidFired = true;
e.preventDefault();
e.stopPropagation();
}, false);
//Opera does not fully support the validationMessage property
Modernizr.formvalidationmessage = !!input.validationMessage;
// Submit form by clicking submit button
form.getElementsByTagName('button')[0].click();
});
return invalidFired;
});
/**
* since we have a fairly large number of input tests that don't mutate the input
* we create a single element that can be shared with all of those tests for a
* minor perf boost
*
* @access private
* @returns {HTMLInputElement}
*/
var inputElem = createElement('input');
/*!
{
"name": "Input attributes",
"property": "input",
"tags": ["forms"],
"authors": ["Mike Taylor"],
"notes": [{
"name": "WHATWG spec",
"href": "http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary"
}],
"knownBugs": ["Some blackberry devices report false positive for input.multiple"]
}
!*/
/* DOC
Detects support for HTML5 `<input>` element attributes and exposes Boolean subproperties with the results:
```javascript
Modernizr.input.autocomplete
Modernizr.input.autofocus
Modernizr.input.list
Modernizr.input.max
Modernizr.input.min
Modernizr.input.multiple
Modernizr.input.pattern
Modernizr.input.placeholder
Modernizr.input.required
Modernizr.input.step
```
*/
// Run through HTML5's new input attributes to see if the UA understands any.
// Mike Taylr has created a comprehensive resource for testing these attributes
// when applied to all input types:
// miketaylr.com/code/input-type-attr.html
// Only input placeholder is tested while textarea's placeholder is not.
// Currently Safari 4 and Opera 11 have support only for the input placeholder
// Both tests are available in feature-detects/forms-placeholder.js
var inputattrs = 'autocomplete autofocus list placeholder max min multiple pattern required step'.split(' ');
var attrs = {};
Modernizr.input = (function(props) {
for (var i = 0, len = props.length; i < len; i++) {
attrs[ props[i] ] = !!(props[i] in inputElem);
}
if (attrs.list) {
// safari false positive's on datalist: webk.it/74252
// see also github.com/Modernizr/Modernizr/issues/146
attrs.list = !!(createElement('datalist') && window.HTMLDataListElement);
}
return attrs;
})(inputattrs);
/*!
{
"name": "datalist Element",
"caniuse": "datalist",
"property": "datalistelem",
"tags": ["elem"],
"builderAliases": ["elem_datalist"],
"warnings": ["This test is a dupe of Modernizr.input.list. Only around for legacy reasons."],
"notes": [{
"name": "CSS Tricks Article",
"href": "http://css-tricks.com/15346-relevant-dropdowns-polyfill-for-datalist/"
},{
"name": "Mike Taylor Test",
"href": "http://miketaylr.com/test/datalist.html"
},{
"name": "Mike Taylor Code",
"href": "http://miketaylr.com/code/datalist.html"
}]
}
!*/
// lol. we already have a test for datalist built in! silly you.
// Leaving it around in case anyone's using it
Modernizr.addTest('datalistelem', Modernizr.input.list);
/*!
{
"name": "Form input types",
"property": "inputtypes",
"caniuse": "forms",
"tags": ["forms"],
"authors": ["Mike Taylor"],
"polyfills": [
"jquerytools",
"webshims",
"h5f",
"webforms2",
"nwxforms",
"fdslider",
"html5slider",
"galleryhtml5forms",
"jscolor",
"html5formshim",
"selectedoptionsjs",
"formvalidationjs"
]
}
!*/
/* DOC
Detects support for HTML5 form input types and exposes Boolean subproperties with the results:
```javascript
Modernizr.inputtypes.color
Modernizr.inputtypes.date
Modernizr.inputtypes.datetime
Modernizr.inputtypes['datetime-local']
Modernizr.inputtypes.email
Modernizr.inputtypes.month
Modernizr.inputtypes.number
Modernizr.inputtypes.range
Modernizr.inputtypes.search
Modernizr.inputtypes.tel
Modernizr.inputtypes.time
Modernizr.inputtypes.url
Modernizr.inputtypes.week
```
*/
// Run through HTML5's new input types to see if the UA understands any.
// This is put behind the tests runloop because it doesn't return a
// true/false like all the other tests; instead, it returns an object
// containing each input type with its corresponding true/false value
// Big thanks to @miketaylr for the html5 forms expertise. miketaylr.com/
var inputtypes = 'search tel url email datetime date month week time datetime-local number range color'.split(' ');
var inputs = {};
Modernizr.inputtypes = (function(props) {
var len = props.length;
var smile = '1)';
var inputElemType;
var defaultView;
var bool;
for (var i = 0; i < len; i++) {
inputElem.setAttribute('type', inputElemType = props[i]);
bool = inputElem.type !== 'text' && 'style' in inputElem;
// We first check to see if the type we give it sticks..
// If the type does, we feed it a textual value, which shouldn't be valid.
// If the value doesn't stick, we know there's input sanitization which infers a custom UI
if (bool) {
inputElem.value = smile;
inputElem.style.cssText = 'position:absolute;visibility:hidden;';
if (/^range$/.test(inputElemType) && inputElem.style.WebkitAppearance !== undefined) {
docElement.appendChild(inputElem);
defaultView = document.defaultView;
// Safari 2-4 allows the smiley as a value, despite making a slider
bool = defaultView.getComputedStyle &&
defaultView.getComputedStyle(inputElem, null).WebkitAppearance !== 'textfield' &&
// Mobile android web browser has false positive, so must
// check the height to see if the widget is actually there.
(inputElem.offsetHeight !== 0);
docElement.removeChild(inputElem);
} else if (/^(search|tel)$/.test(inputElemType)) {
// Spec doesn't define any special parsing or detectable UI
// behaviors so we pass these through as true
// Interestingly, opera fails the earlier test, so it doesn't
// even make it here.
} else if (/^(url|email)$/.test(inputElemType)) {
// Real url and email support comes with prebaked validation.
bool = inputElem.checkValidity && inputElem.checkValidity() === false;
} else {
// If the upgraded input compontent rejects the :) text, we got a winner
bool = inputElem.value != smile;
}
}
inputs[ props[i] ] = !!bool;
}
return inputs;
})(inputtypes);
/*!
{
"name": "input[type=\"number\"] Localization",
"property": "localizednumber",
"tags": ["forms", "localization", "attribute"],
"authors": ["Peter Janes"],
"notes": [{
"name": "Webkit Bug Tracker Listing",
"href": "https://bugs.webkit.org/show_bug.cgi?id=42484"
},{
"name": "Based on This",
"href": "http://trac.webkit.org/browser/trunk/LayoutTests/fast/forms/script-tests/input-number-keyoperation.js?rev=80096#L9"
}],
"knownBugs": ["Only ever returns true if the browser/OS is configured to use comma as a decimal separator. This is probably fine for most use cases."]
}
!*/
/* DOC
Detects whether input type="number" is capable of receiving and displaying localized numbers, e.g. with comma separator.
*/
Modernizr.addTest('localizednumber', function() {
// this extends our testing of input[type=number], so bomb out if that's missing
if (!Modernizr.inputtypes.number) { return false; }
// we rely on checkValidity later, so bomb out early if we don't have it
if (!Modernizr.formvalidation) { return false; }
var el = createElement('div');
var diff;
var body = getBody();
var root = (function() {
return docElement.insertBefore(body, docElement.firstElementChild || docElement.firstChild);
}());
el.innerHTML = '<input type="number" value="1.0" step="0.1"/>';
var input = el.childNodes[0];
root.appendChild(el);
input.focus();
try {
document.execCommand('InsertText', false, '1,1');
} catch (e) { // prevent warnings in IE
}
diff = input.type === 'number' && input.valueAsNumber === 1.1 && input.checkValidity();
root.removeChild(el);
body.fake && root.parentNode.removeChild(root);
return diff;
});
/**
* Create our "modernizr" element that we do most feature tests on.
*
* @access private
*/
var modElem = {
elem: createElement('modernizr')
};
// Clean up this element
Modernizr._q.push(function() {
delete modElem.elem;
});
/*!
{
"name": "CSS Font ch Units",
"authors": ["Ron Waldon (@jokeyrhyme)"],
"property": "csschunit",
"tags": ["css"],
"notes": [{
"name": "W3C Spec",
"href": "http://www.w3.org/TR/css3-values/#font-relative-lengths"
}]
}
!*/
Modernizr.addTest('csschunit', function() {
var elemStyle = modElem.elem.style;
var supports;
try {
elemStyle.fontSize = '3ch';
supports = elemStyle.fontSize.indexOf('ch') !== -1;
} catch (e) {
supports = false;
}
return supports;
});
/*!
{
"name": "CSS Font ex Units",
"authors": ["Ron Waldon (@jokeyrhyme)"],
"property": "cssexunit",
"tags": ["css"],
"notes": [{
"name": "W3C Spec",
"href": "http://www.w3.org/TR/css3-values/#font-relative-lengths"
}]
}
!*/
Modernizr.addTest('cssexunit', function() {
var elemStyle = modElem.elem.style;
var supports;
try {
elemStyle.fontSize = '3ex';
supports = elemStyle.fontSize.indexOf('ex') !== -1;
} catch (e) {
supports = false;
}
return supports;
});
/**
* contains checks to see if a string contains another string
*
* @access private
* @function contains
* @param {string} str - The string we want to check for substrings
* @param {string} substr - The substring we want to search the first string for
* @returns {boolean}
*/
function contains(str, substr) {
return !!~('' + str).indexOf(substr);
}
;
/*!
{
"name": "CSS HSLA Colors",
"caniuse": "css3-colors",
"property": "hsla",
"tags": ["css"]
}
!*/
Modernizr.addTest('hsla', function() {
var style = createElement('a').style;
style.cssText = 'background-color:hsla(120,40%,100%,.5)';
return contains(style.backgroundColor, 'rgba') || contains(style.backgroundColor, 'hsla');
});
/**
* roundedEquals takes two integers and checks if the first is within 1 of the second
*
* @access private
* @function roundedEquals
* @param {number} a
* @param {number} b
* @returns {boolean}
*/
function roundedEquals(a, b) {
return a - 1 === b || a === b || a + 1 === b;
}
;
/*!
{
"name": "CSS vmax unit",
"property": "cssvmaxunit",
"caniuse": "viewport-units",
"tags": ["css"],
"builderAliases": ["css_vmaxunit"],
"notes": [{
"name": "Related Modernizr Issue",
"href": "https://github.com/Modernizr/Modernizr/issues/572"
},{
"name": "JSFiddle Example",
"href": "http://jsfiddle.net/glsee/JDsWQ/4/"
}]
}
!*/
testStyles('#modernizr1{width: 50vmax}#modernizr2{width:50px;height:50px;overflow:scroll}#modernizr3{position:fixed;top:0;left:0;bottom:0;right:0}', function(node) {
var elem = node.childNodes[2];
var scroller = node.childNodes[1];
var fullSizeElem = node.childNodes[0];
var scrollbarWidth = parseInt((scroller.offsetWidth - scroller.clientWidth) / 2, 10);
var one_vw = fullSizeElem.clientWidth / 100;
var one_vh = fullSizeElem.clientHeight / 100;
var expectedWidth = parseInt(Math.max(one_vw, one_vh) * 50, 10);
var compWidth = parseInt((window.getComputedStyle ?
getComputedStyle(elem, null) :
elem.currentStyle).width, 10);
Modernizr.addTest('cssvmaxunit', roundedEquals(expectedWidth, compWidth) || roundedEquals(expectedWidth, compWidth - scrollbarWidth));
}, 3);
/*!
{
"name": "CSS vmin unit",
"property": "cssvminunit",
"caniuse": "viewport-units",
"tags": ["css"],
"builderAliases": ["css_vminunit"],
"notes": [{
"name": "Related Modernizr Issue",
"href": "https://github.com/Modernizr/Modernizr/issues/572"
},{
"name": "JSFiddle Example",
"href": "http://jsfiddle.net/glsee/JRmdq/8/"
}]
}
!*/
testStyles('#modernizr1{width: 50vm;width:50vmin}#modernizr2{width:50px;height:50px;overflow:scroll}#modernizr3{position:fixed;top:0;left:0;bottom:0;right:0}', function(node) {
var elem = node.childNodes[2];
var scroller = node.childNodes[1];
var fullSizeElem = node.childNodes[0];
var scrollbarWidth = parseInt((scroller.offsetWidth - scroller.clientWidth) / 2, 10);
var one_vw = fullSizeElem.clientWidth / 100;
var one_vh = fullSizeElem.clientHeight / 100;
var expectedWidth = parseInt(Math.min(one_vw, one_vh) * 50, 10);
var compWidth = parseInt((window.getComputedStyle ?
getComputedStyle(elem, null) :
elem.currentStyle).width, 10);
Modernizr.addTest('cssvminunit', roundedEquals(expectedWidth, compWidth) || roundedEquals(expectedWidth, compWidth - scrollbarWidth));
}, 3);
/**
* http://mathiasbynens.be/notes/xhr-responsetype-json#comment-4
*
* @access private
* @function testXhrType
* @param {string} type - String name of the XHR type you want to detect
* @returns {boolean}
* @author Mathias Bynens
*/
/* istanbul ignore next */
var testXhrType = function(type) {
if (typeof XMLHttpRequest == 'undefined') {
return false;
}
var xhr = new XMLHttpRequest();
xhr.open('get', '/', true);
try {
xhr.responseType = type;
} catch (error) {
return false;
}
return 'response' in xhr && xhr.responseType == type;
};
/*!
{
"name": "XHR responseType='arraybuffer'",
"property": "xhrresponsetypearraybuffer",
"tags": ["network"],
"notes": [{
"name": "XMLHttpRequest Living Standard",
"href": "http://xhr.spec.whatwg.org/#the-responsetype-attribute"
}]
}
!*/
/* DOC
Tests for XMLHttpRequest xhr.responseType='arraybuffer'.
*/
Modernizr.addTest('xhrresponsetypearraybuffer', testXhrType('arraybuffer'));
/*!
{
"name": "XHR responseType='blob'",
"property": "xhrresponsetypeblob",
"tags": ["network"],
"notes": [{
"name": "XMLHttpRequest Living Standard",
"href": "http://xhr.spec.whatwg.org/#the-responsetype-attribute"
}]
}
!*/
/* DOC
Tests for XMLHttpRequest xhr.responseType='blob'.
*/
Modernizr.addTest('xhrresponsetypeblob', testXhrType('blob'));
/*!
{
"name": "XHR responseType='document'",
"property": "xhrresponsetypedocument",
"tags": ["network"],
"notes": [{
"name": "XMLHttpRequest Living Standard",
"href": "http://xhr.spec.whatwg.org/#the-responsetype-attribute"
}]
}
!*/
/* DOC
Tests for XMLHttpRequest xhr.responseType='document'.
*/
Modernizr.addTest('xhrresponsetypedocument', testXhrType('document'));
/*!
{
"name": "XHR responseType='json'",
"property": "xhrresponsetypejson",
"tags": ["network"],
"notes": [{
"name": "XMLHttpRequest Living Standard",
"href": "http://xhr.spec.whatwg.org/#the-responsetype-attribute"
},{
"name": "Explanation of xhr.responseType='json'",
"href": "http://mathiasbynens.be/notes/xhr-responsetype-json"
}]
}
!*/
/* DOC
Tests for XMLHttpRequest xhr.responseType='json'.
*/
Modernizr.addTest('xhrresponsetypejson', testXhrType('json'));
/*!
{
"name": "XHR responseType='text'",
"property": "xhrresponsetypetext",
"tags": ["network"],
"notes": [{
"name": "XMLHttpRequest Living Standard",
"href": "http://xhr.spec.whatwg.org/#the-responsetype-attribute"
}]
}
!*/
/* DOC
Tests for XMLHttpRequest xhr.responseType='text'.
*/
Modernizr.addTest('xhrresponsetypetext', testXhrType('text'));
/**
* Object.prototype.toString can be used with every object and allows you to
* get its class easily. Abstracting it off of an object prevents situations
* where the toString property has been overridden
*
* @access private
* @function toStringFn
* @returns {function} An abstracted toString function
*/
var toStringFn = ({}).toString;
/*!
{
"name": "SVG clip paths",
"property": "svgclippaths",
"tags": ["svg"],
"notes": [{
"name": "Demo",
"href": "http://srufaculty.sru.edu/david.dailey/svg/newstuff/clipPath4.svg"
}]
}
!*/
/* DOC
Detects support for clip paths in SVG (only, not on HTML content).
See [this discussion](http://github.com/Modernizr/Modernizr/issues/213) regarding applying SVG clip paths to HTML content.
*/
Modernizr.addTest('svgclippaths', function() {
return !!document.createElementNS &&
/SVGClipPath/.test(toStringFn.call(document.createElementNS('http://www.w3.org/2000/svg', 'clipPath')));
});
/*!
{
"name": "SVG foreignObject",
"property": "svgforeignobject",
"tags": ["svg"],
"notes": [{
"name": "W3C Spec",
"href": "http://www.w3.org/TR/SVG11/extend.html"
}]
}
!*/
/* DOC
Detects support for foreignObject tag in SVG.
*/
Modernizr.addTest('svgforeignobject', function() {
return !!document.createElementNS &&
/SVGForeignObject/.test(toStringFn.call(document.createElementNS('http://www.w3.org/2000/svg', 'foreignObject')));
});
/*!
{
"name": "SVG SMIL animation",
"property": "smil",
"caniuse": "svg-smil",
"tags": ["svg"],
"notes": [{
"name": "W3C Synchronised Multimedia spec",
"href": "http://www.w3.org/AudioVideo/"
}]
}
!*/
// SVG SMIL animation
Modernizr.addTest('smil', function() {
return !!document.createElementNS &&
/SVGAnimate/.test(toStringFn.call(document.createElementNS('http://www.w3.org/2000/svg', 'animate')));
});
var mStyle = {
style: modElem.elem.style
};
// kill ref for gc, must happen before mod.elem is removed, so we unshift on to
// the front of the queue.
Modernizr._q.unshift(function() {
delete mStyle.style;
});
/**
* nativeTestProps allows for us to use native feature detection functionality if available.
* some prefixed form, or false, in the case of an unsupported rule
*
* @access private
* @function nativeTestProps
* @param {array} props - An array of property names
* @param {string} value - A string representing the value we want to check via @supports
* @returns {boolean|undefined} A boolean when @supports exists, undefined otherwise
*/
// Accepts a list of property names and a single value
// Returns `undefined` if native detection not available
function nativeTestProps(props, value) {
var i = props.length;
// Start with the JS API: http://www.w3.org/TR/css3-conditional/#the-css-interface
if ('CSS' in window && 'supports' in window.CSS) {
// Try every prefixed variant of the property
while (i--) {
if (window.CSS.supports(domToCSS(props[i]), value)) {
return true;
}
}
return false;
}
// Otherwise fall back to at-rule (for Opera 12.x)
else if ('CSSSupportsRule' in window) {
// Build a condition string for every prefixed variant
var conditionText = [];
while (i--) {
conditionText.push('(' + domToCSS(props[i]) + ':' + value + ')');
}
conditionText = conditionText.join(' or ');
return injectElementWithStyles('@supports (' + conditionText + ') { #modernizr { position: absolute; } }', function(node) {
return getComputedStyle(node, null).position == 'absolute';
});
}
return undefined;
}
;
// testProps is a generic CSS / DOM property test.
// In testing support for a given CSS property, it's legit to test:
// `elem.style[styleName] !== undefined`
// If the property is supported it will return an empty string,
// if unsupported it will return undefined.
// We'll take advantage of this quick test and skip setting a style
// on our modernizr element, but instead just testing undefined vs
// empty string.
// Property names can be provided in either camelCase or kebab-case.
function testProps(props, prefixed, value, skipValueTest) {
skipValueTest = is(skipValueTest, 'undefined') ? false : skipValueTest;
// Try native detect first
if (!is(value, 'undefined')) {
var result = nativeTestProps(props, value);
if (!is(result, 'undefined')) {
return result;
}
}
// Otherwise do it properly
var afterInit, i, propsLength, prop, before;
// If we don't have a style element, that means we're running async or after
// the core tests, so we'll need to create our own elements to use
// inside of an SVG element, in certain browsers, the `style` element is only
// defined for valid tags. Therefore, if `modernizr` does not have one, we
// fall back to a less used element and hope for the best.
var elems = ['modernizr', 'tspan'];
while (!mStyle.style) {
afterInit = true;
mStyle.modElem = createElement(elems.shift());
mStyle.style = mStyle.modElem.style;
}
// Delete the objects if we created them.
function cleanElems() {
if (afterInit) {
delete mStyle.style;
delete mStyle.modElem;
}
}
propsLength = props.length;
for (i = 0; i < propsLength; i++) {
prop = props[i];
before = mStyle.style[prop];
if (contains(prop, '-')) {
prop = cssToDOM(prop);
}
if (mStyle.style[prop] !== undefined) {
// If value to test has been passed in, do a set-and-check test.
// 0 (integer) is a valid property value, so check that `value` isn't
// undefined, rather than just checking it's truthy.
if (!skipValueTest && !is(value, 'undefined')) {
// Needs a try catch block because of old IE. This is slow, but will
// be avoided in most cases because `skipValueTest` will be used.
try {
mStyle.style[prop] = value;
} catch (e) {}
// If the property value has changed, we assume the value used is
// supported. If `value` is empty string, it'll fail here (because
// it hasn't changed), which matches how browsers have implemented
// CSS.supports()
if (mStyle.style[prop] != before) {
cleanElems();
return prefixed == 'pfx' ? prop : true;
}
}
// Otherwise just return true, or the property name if this is a
// `prefixed()` call
else {
cleanElems();
return prefixed == 'pfx' ? prop : true;
}
}
}
cleanElems();
return false;
}
;
/**
* testProp() investigates whether a given style property is recognized
* Property names can be provided in either camelCase or kebab-case.
*
* @memberof Modernizr
* @name Modernizr.testProp
* @access public
* @optionName Modernizr.testProp()
* @optionProp testProp
* @function testProp
* @param {string} prop - Name of the CSS property to check
* @param {string} [value] - Name of the CSS value to check
* @param {boolean} [useValue] - Whether or not to check the value if @supports isn't supported
* @returns {boolean}
* @example
*
* Just like [testAllProps](#modernizr-testallprops), only it does not check any vendor prefixed
* version of the string.
*
* Note that the property name must be provided in camelCase (e.g. boxSizing not box-sizing)
*
* ```js
* Modernizr.testProp('pointerEvents') // true
* ```
*
* You can also provide a value as an optional second argument to check if a
* specific value is supported
*
* ```js
* Modernizr.testProp('pointerEvents', 'none') // true
* Modernizr.testProp('pointerEvents', 'penguin') // false
* ```
*/
var testProp = ModernizrProto.testProp = function(prop, value, useValue) {
return testProps([prop], undefined, value, useValue);
};
/*!
{
"name": "CSS textshadow",
"property": "textshadow",
"caniuse": "css-textshadow",
"tags": ["css"],
"knownBugs": ["FF3.0 will false positive on this test"]
}
!*/
Modernizr.addTest('textshadow', testProp('textShadow', '1px 1px'));
/**
* fnBind is a super small [bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) polyfill.
*
* @access private
* @function fnBind
* @param {function} fn - a function you want to change `this` reference to
* @param {object} that - the `this` you want to call the function with
* @returns {function} The wrapped version of the supplied function
*/
function fnBind(fn, that) {
return function() {
return fn.apply(that, arguments);
};
}
;
/**
* testDOMProps is a generic DOM property test; if a browser supports
* a certain property, it won't return undefined for it.
*
* @access private
* @function testDOMProps
* @param {array.<string>} props - An array of properties to test for
* @param {object} obj - An object or Element you want to use to test the parameters again
* @param {boolean|object} elem - An Element to bind the property lookup again. Use `false` to prevent the check
*/
function testDOMProps(props, obj, elem) {
var item;
for (var i in props) {
if (props[i] in obj) {
// return the property name as a string
if (elem === false) {
return props[i];
}
item = obj[props[i]];
// let's bind a function
if (is(item, 'function')) {
// bind to obj unless overriden
return fnBind(item, elem || obj);
}
// return the unbound function or obj or value
return item;
}
}
return false;
}
;
/**
* testPropsAll tests a list of DOM properties we want to check against.
* We specify literally ALL possible (known and/or likely) properties on
* the element including the non-vendor prefixed one, for forward-
* compatibility.
*
* @access private
* @function testPropsAll
* @param {string} prop - A string of the property to test for
* @param {string|object} [prefixed] - An object to check the prefixed properties on. Use a string to skip
* @param {HTMLElement|SVGElement} [elem] - An element used to test the property and value against
* @param {string} [value] - A string of a css value
* @param {boolean} [skipValueTest] - An boolean representing if you want to test if value sticks when set
*/
function testPropsAll(prop, prefixed, elem, value, skipValueTest) {
var ucProp = prop.charAt(0).toUpperCase() + prop.slice(1),
props = (prop + ' ' + cssomPrefixes.join(ucProp + ' ') + ucProp).split(' ');
// did they call .prefixed('boxSizing') or are we just testing a prop?
if (is(prefixed, 'string') || is(prefixed, 'undefined')) {
return testProps(props, prefixed, value, skipValueTest);
// otherwise, they called .prefixed('requestAnimationFrame', window[, elem])
} else {
props = (prop + ' ' + (domPrefixes).join(ucProp + ' ') + ucProp).split(' ');
return testDOMProps(props, prefixed, elem);
}
}
// Modernizr.testAllProps() investigates whether a given style property,
// or any of its vendor-prefixed variants, is recognized
//
// Note that the property names must be provided in the camelCase variant.
// Modernizr.testAllProps('boxSizing')
ModernizrProto.testAllProps = testPropsAll;
/**
* prefixed returns the prefixed or nonprefixed property name variant of your input
*
* @memberof Modernizr
* @name Modernizr.prefixed
* @optionName Modernizr.prefixed()
* @optionProp prefixed
* @access public
* @function prefixed
* @param {string} prop - String name of the property to test for
* @param {object} [obj] - An object to test for the prefixed properties on
* @param {HTMLElement} [elem] - An element used to test specific properties against
* @returns {string|false} The string representing the (possibly prefixed) valid
* version of the property, or `false` when it is unsupported.
* @example
*
* Modernizr.prefixed takes a string css value in the DOM style camelCase (as
* opposed to the css style kebab-case) form and returns the (possibly prefixed)
* version of that property that the browser actually supports.
*
* For example, in older Firefox...
* ```js
* prefixed('boxSizing')
* ```
* returns 'MozBoxSizing'
*
* In newer Firefox, as well as any other browser that support the unprefixed
* version would simply return `boxSizing`. Any browser that does not support
* the property at all, it will return `false`.
*
* By default, prefixed is checked against a DOM element. If you want to check
* for a property on another object, just pass it as a second argument
*
* ```js
* var rAF = prefixed('requestAnimationFrame', window);
*
* raf(function() {
* renderFunction();
* })
* ```
*
* Note that this will return _the actual function_ - not the name of the function.
* If you need the actual name of the property, pass in `false` as a third argument
*
* ```js
* var rAFProp = prefixed('requestAnimationFrame', window, false);
*
* rafProp === 'WebkitRequestAnimationFrame' // in older webkit
* ```
*
* One common use case for prefixed is if you're trying to determine which transition
* end event to bind to, you might do something like...
* ```js
* var transEndEventNames = {
* 'WebkitTransition' : 'webkitTransitionEnd', * Saf 6, Android Browser
* 'MozTransition' : 'transitionend', * only for FF < 15
* 'transition' : 'transitionend' * IE10, Opera, Chrome, FF 15+, Saf 7+
* };
*
* var transEndEventName = transEndEventNames[ Modernizr.prefixed('transition') ];
* ```
*
* If you want a similar lookup, but in kebab-case, you can use [prefixedCSS](#modernizr-prefixedcss).
*/
var prefixed = ModernizrProto.prefixed = function(prop, obj, elem) {
if (prop.indexOf('@') === 0) {
return atRule(prop);
}
if (prop.indexOf('-') != -1) {
// Convert kebab-case to camelCase
prop = cssToDOM(prop);
}
if (!obj) {
return testPropsAll(prop, 'pfx');
} else {
// Testing DOM property e.g. Modernizr.prefixed('requestAnimationFrame', window) // 'mozRequestAnimationFrame'
return testPropsAll(prop, obj, elem);
}
};
/**
* prefixedCSS is just like [prefixed](#modernizr-prefixed), but the returned values are in
* kebab-case (e.g. `box-sizing`) rather than camelCase (boxSizing).
*
* @memberof Modernizr
* @name Modernizr.prefixedCSS
* @optionName Modernizr.prefixedCSS()
* @optionProp prefixedCSS
* @access public
* @function prefixedCSS
* @param {string} prop - String name of the property to test for
* @returns {string|false} The string representing the (possibly prefixed)
* valid version of the property, or `false` when it is unsupported.
* @example
*
* `Modernizr.prefixedCSS` is like `Modernizr.prefixed`, but returns the result
* in hyphenated form
*
* ```js
* Modernizr.prefixedCSS('transition') // '-moz-transition' in old Firefox
* ```
*
* Since it is only useful for CSS style properties, it can only be tested against
* an HTMLElement.
*
* Properties can be passed as both the DOM style camelCase or CSS style kebab-case.
*/
var prefixedCSS = ModernizrProto.prefixedCSS = function(prop) {
var prefixedProp = prefixed(prop);
return prefixedProp && domToCSS(prefixedProp);
};
/*!
{
"name": "Battery API",
"property": "batteryapi",
"aliases": ["battery-api"],
"builderAliases": ["battery_api"],
"tags": ["device", "media"],
"authors": ["Paul Sayre"],
"notes": [{
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en/DOM/window.navigator.mozBattery"
}]
}
!*/
/* DOC
Detect support for the Battery API, for accessing information about the system's battery charge level.
*/
Modernizr.addTest('batteryapi', !!prefixed('battery', navigator), {aliases: ['battery-api']});
/*!
{
"name": "Web Cryptography",
"property": "cryptography",
"caniuse": "cryptography",
"tags": ["crypto"],
"authors": ["roblarsen"],
"notes": [{
"name": "W3C Editor's Draft",
"href": "http://www.w3.org/TR/WebCryptoAPI/"
}],
"polyfills": [
"polycrypt"
]
}
!*/
/* DOC
Detects support for the cryptographic functionality available under window.crypto.subtle
*/
var crypto = prefixed('crypto', window);
Modernizr.addTest('crypto', !!prefixed('subtle', crypto));
/*!
{
"name": "Dart",
"property": "dart",
"authors": ["Theodoor van Donge"],
"notes": [{
"name": "Language website",
"href": "http://www.dartlang.org/"
}]
}
!*/
/* DOC
Detects native support for the Dart programming language.
*/
Modernizr.addTest('dart', !!prefixed('startDart', navigator));
/*!
{
"name": "Force Touch Events",
"property": "forcetouch",
"authors": ["Kraig Walker"],
"notes": [{
"name": "Responding to Force Touch Events from JavaScript",
"href": "https://developer.apple.com/library/prerelease/mac/documentation/AppleApplications/Conceptual/SafariJSProgTopics/Articles/RespondingtoForceTouchEventsfromJavaScript.html"
}]
}
!*/
/* DOC
Tests whether the browser supports the detection of Force Touch Events.
Force Touch Events allow custom behaviours and interactions to take place based on the given pressure or change in pressure from a compatible trackpad.
Force Touch events are available in OS X 10.11 and later on devices equipped with Force Touch trackpads.
*/
Modernizr.addTest('forcetouch', function() {
// github.com/Modernizr/Modernizr/issues/1613
// Test if the browser supports the force touch event progression (see notes link)
if (!hasEvent(prefixed('mouseforcewillbegin', window, false), window)) {
return false;
}
// Test if the browser provides thresholds defining a "force touch" from a normal touch/click event
return MouseEvent.WEBKIT_FORCE_AT_MOUSE_DOWN && MouseEvent.WEBKIT_FORCE_AT_FORCE_MOUSE_DOWN;
});
/*!
{
"name": "Fullscreen API",
"property": "fullscreen",
"caniuse": "fullscreen",
"notes": [{
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en/API/Fullscreen"
}],
"polyfills": ["screenfulljs"],
"builderAliases": ["fullscreen_api"]
}
!*/
/* DOC
Detects support for the ability to make the current website take over the user's entire screen
*/
// github.com/Modernizr/Modernizr/issues/739
Modernizr.addTest('fullscreen', !!(prefixed('exitFullscreen', document, false) || prefixed('cancelFullScreen', document, false)));
/*!
{
"name": "GamePad API",
"property": "gamepads",
"authors": ["Eric Bidelman"],
"tags": ["media"],
"notes": [{
"name": "W3C spec",
"href": "http://www.w3.org/TR/gamepad/"
},{
"name": "HTML5 Rocks tutorial",
"href": "http://www.html5rocks.com/en/tutorials/doodles/gamepad/#toc-featuredetect"
}],
"warnings": [],
"polyfills": []
}
!*/
/* DOC
Detects support for the Gamepad API, for access to gamepads and controllers.
*/
Modernizr.addTest('gamepads', !!prefixed('getGamepads', navigator));
/*!
{
"name": "IndexedDB",
"property": "indexeddb",
"caniuse": "indexeddb",
"tags": ["storage"],
"polyfills": ["indexeddb"]
}
!*/
/* DOC
Detects support for the IndexedDB client-side storage API (final spec).
*/
// Vendors had inconsistent prefixing with the experimental Indexed DB:
// - Webkit's implementation is accessible through webkitIndexedDB
// - Firefox shipped moz_indexedDB before FF4b9, but since then has been mozIndexedDB
// For speed, we don't test the legacy (and beta-only) indexedDB
var indexeddb = prefixed('indexedDB', window);
Modernizr.addTest('indexeddb', !!indexeddb);
if (!!indexeddb) {
Modernizr.addTest('indexeddb.deletedatabase', 'deleteDatabase' in indexeddb);
}
;
/*!
{
"name": "IndexedDB Blob",
"property": "indexeddbblob"
}
!*/
/* DOC
Detects if the browser can save File/Blob objects to IndexedDB
*/
// Vendors had inconsistent prefixing with the experimental Indexed DB:
// - Webkit's implementation is accessible through webkitIndexedDB
// - Firefox shipped moz_indexedDB before FF4b9, but since then has been mozIndexedDB
// For speed, we don't test the legacy (and beta-only) indexedDB
Modernizr.addAsyncTest(function() {
/* jshint -W053 */
var indexeddb = prefixed('indexedDB', window);
var dbname = 'detect-blob-support';
var supportsBlob = false;
var request;
var db;
if (!(Modernizr.indexeddb && Modernizr.indexeddb.deleteDatabase)) {
return false;
}
// Calling `deleteDatabase` in a try…catch because some contexts (e.g. data URIs)
// will throw a `SecurityError`
try {
indexeddb.deleteDatabase(dbname).onsuccess = function() {
request = indexeddb.open(dbname, 1);
request.onupgradeneeded = function() {
request.result.createObjectStore('store');
};
request.onsuccess = function() {
db = request.result;
try {
db.transaction('store', 'readwrite').objectStore('store').put(new Blob(), 'key');
supportsBlob = true;
}
catch (e) {
supportsBlob = false;
}
finally {
addTest('indexeddbblob', supportsBlob);
db.close();
indexeddb.deleteDatabase(dbname);
}
};
};
}
catch (e) {
addTest('indexeddbblob', false);
}
});
/*!
{
"name": "Internationalization API",
"property": "intl",
"notes": [{
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl"
},{
"name": "ECMAScript spec",
"href": "http://www.ecma-international.org/ecma-402/1.0/"
}]
}
!*/
/* DOC
Detects support for the Internationalization API which allow easy formatting of number and dates and sorting string
based on a locale
*/
Modernizr.addTest('intl', !!prefixed('Intl', window));
/*!
{
"name": "Page Visibility API",
"property": "pagevisibility",
"caniuse": "pagevisibility",
"tags": ["performance"],
"notes": [{
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en-US/docs/DOM/Using_the_Page_Visibility_API"
},{
"name": "W3C spec",
"href": "http://www.w3.org/TR/2011/WD-page-visibility-20110602/"
},{
"name": "HTML5 Rocks tutorial",
"href": "http://www.html5rocks.com/en/tutorials/pagevisibility/intro/"
}],
"polyfills": ["visibilityjs", "visiblyjs", "jquery-visibility"]
}
!*/
/* DOC
Detects support for the Page Visibility API, which can be used to disable unnecessary actions and otherwise improve user experience.
*/
Modernizr.addTest('pagevisibility', !!prefixed('hidden', document, false));
/*!
{
"name": "Navigation Timing API",
"property": "performance",
"caniuse": "nav-timing",
"tags": ["performance"],
"authors": ["Scott Murphy (@uxder)"],
"notes": [{
"name": "W3C Spec",
"href": "http://www.w3.org/TR/navigation-timing/"
},{
"name": "HTML5 Rocks article",
"href": "http://www.html5rocks.com/en/tutorials/webperformance/basics/"
}],
"polyfills": ["perfnow"]
}
!*/
/* DOC
Detects support for the Navigation Timing API, for measuring browser and connection performance.
*/
Modernizr.addTest('performance', !!prefixed('performance', window));
/*!
{
"name": "Pointer Lock API",
"property": "pointerlock",
"notes": [{
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en-US/docs/API/Pointer_Lock_API"
}],
"builderAliases": ["pointerlock_api"]
}
!*/
/* DOC
Detects support the pointer lock API which allows you to lock the mouse cursor to the browser window.
*/
// https://developer.mozilla.org/en-US/docs/API/Pointer_Lock_API
Modernizr.addTest('pointerlock', !!prefixed('exitPointerLock', document));
/*!
{
"name": "Quota Storage Management API",
"property": "quotamanagement",
"tags": ["storage"],
"builderAliases": ["quota_management_api"],
"notes": [{
"name": "W3C Spec",
"href": "http://www.w3.org/TR/quota-api/"
}]
}
!*/
/* DOC
Detects the ability to request a specific amount of space for filesystem access
*/
Modernizr.addTest('quotamanagement', function() {
var tempStorage = prefixed('temporaryStorage', navigator);
var persStorage = prefixed('persistentStorage', navigator);
return !!(tempStorage && persStorage);
});
/*!
{
"name": "requestAnimationFrame",
"property": "requestanimationframe",
"aliases": ["raf"],
"caniuse": "requestanimationframe",
"tags": ["animation"],
"authors": ["Addy Osmani"],
"notes": [{
"name": "W3C spec",
"href": "http://www.w3.org/TR/animation-timing/"
}],
"polyfills": ["raf"]
}
!*/
/* DOC
Detects support for the `window.requestAnimationFrame` API, for offloading animation repainting to the browser for optimized performance.
*/
Modernizr.addTest('requestanimationframe', !!prefixed('requestAnimationFrame', window), {aliases: ['raf']});
/*!
{
"name": "Vibration API",
"property": "vibrate",
"notes": [{
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en/DOM/window.navigator.mozVibrate"
},{
"name": "W3C spec",
"href": "http://www.w3.org/TR/vibration/"
}]
}
!*/
/* DOC
Detects support for the API that provides access to the vibration mechanism of the hosting device, to provide tactile feedback.
*/
Modernizr.addTest('vibrate', !!prefixed('vibrate', navigator));
/*!
{
"name": "Web Intents",
"property": "webintents",
"authors": ["Eric Bidelman"],
"notes": [{
"name": "Web Intents project site",
"href": "http://webintents.org/"
}],
"polyfills": ["webintents"],
"builderAliases": ["web_intents"]
}
!*/
/* DOC
Detects native support for the Web Intents APIs for service discovery and inter-application communication.
Chrome added support for this in v19, but [removed it again in v24](http://lists.w3.org/Archives/Public/public-web-intents/2012Nov/0000.html) because of "a number of areas for
development in both the API and specific user experience in Chrome". No other browsers currently support it, however a [JavaScript shim](http://webintents.org/#javascriptshim) is available.
*/
Modernizr.addTest('webintents', !!prefixed('startActivity', navigator));
/*!
{
"name": "Low Battery Level",
"property": "lowbattery",
"tags": ["hardware", "mobile"],
"builderAliases": ["battery_level"],
"authors": ["Paul Sayre"],
"notes": [{
"name": "MDN Docs",
"href": "http://developer.mozilla.org/en/DOM/window.navigator.mozBattery"
}]
}
!*/
/* DOC
Enable a developer to remove CPU intensive CSS/JS when battery is low
*/
Modernizr.addTest('lowbattery', function() {
var minLevel = 0.20;
var battery = prefixed('battery', navigator);
return !!(battery && !battery.charging && battery.level <= minLevel);
});
/*!
{
"name": "getRandomValues",
"property": "getrandomvalues",
"caniuse": "window.crypto.getRandomValues",
"tags": ["crypto"],
"authors": ["komachi"],
"notes": [{
"name": "W3C Editor’s Draft",
"href": "https://dvcs.w3.org/hg/webcrypto-api/raw-file/tip/spec/Overview.html#RandomSource-method-getRandomValues"
}],
"polyfills": [
"polycrypt"
]
}
!*/
/* DOC
Detects support for the window.crypto.getRandomValues for generate cryptographically secure random numbers
*/
// In Safari <=5.0 `window.crypto` exists (for some reason) but is `undefined`, so we have to check
// it’s truthy before checking for existence of `getRandomValues`
var crypto = prefixed('crypto', window);
var supportsGetRandomValues;
// Safari 6.0 supports crypto.getRandomValues, but does not return the array,
// which is required by the spec, so we need to actually check.
if (crypto && 'getRandomValues' in crypto && 'Uint32Array' in window) {
var array = new Uint32Array(10);
var values = crypto.getRandomValues(array);
supportsGetRandomValues = values && is(values[0], 'number');
}
Modernizr.addTest('getrandomvalues', !!supportsGetRandomValues);
/*!
{
"name": "CSS Background Blend Mode",
"property": "backgroundblendmode",
"caniuse": "css-backgroundblendmode",
"tags": ["css"],
"notes": [
{
"name": "CSS Blend Modes could be the next big thing in Web Design",
"href": " https://medium.com/@bennettfeely/css-blend-modes-could-be-the-next-big-thing-in-web-design-6b51bf53743a"
}, {
"name": "Demo",
"href": "http://bennettfeely.com/gradients/"
}
]
}
!*/
/* DOC
Detects the ability for the browser to composite backgrounds using blending modes similar to ones found in Photoshop or Illustrator.
*/
Modernizr.addTest('backgroundblendmode', prefixed('backgroundBlendMode', 'text'));
/*!
{
"name": "CSS Object Fit",
"caniuse": "object-fit",
"property": "objectfit",
"tags": ["css"],
"builderAliases": ["css_objectfit"],
"notes": [{
"name": "Opera Article on Object Fit",
"href": "http://dev.opera.com/articles/view/css3-object-fit-object-position/"
}]
}
!*/
Modernizr.addTest('objectfit', !!prefixed('objectFit'), {aliases: ['object-fit']});
/*!
{
"name": "CSS wrap-flow",
"property": "wrapflow",
"tags": ["css"],
"notes": [
{
"name": "W3C Exclusions spec",
"href": "http://www.w3.org/TR/css3-exclusions"
},
{
"name": "Example by Adobe",
"href": "http://html.adobe.com/webstandards/cssexclusions"
}
]
}
!*/
Modernizr.addTest('wrapflow', function() {
var prefixedProperty = prefixed('wrapFlow');
if (!prefixedProperty || isSVG) {
return false;
}
var wrapFlowProperty = prefixedProperty.replace(/([A-Z])/g, function(str, m1) { return '-' + m1.toLowerCase(); }).replace(/^ms-/, '-ms-');
/* If the CSS parsing is there we need to determine if wrap-flow actually works to avoid false positive cases, e.g. the browser parses
the property, but it hasn't got the implementation for the functionality yet. */
var container = createElement('div');
var exclusion = createElement('div');
var content = createElement('span');
/* First we create a div with two adjacent divs inside it. The first div will be the content, the second div will be the exclusion area.
We use the "wrap-flow: end" property to test the actual behavior. (http://dev.w3.org/csswg/css3-exclusions/#wrap-flow-property)
The wrap-flow property is applied to the exclusion area what has a 50px left offset and a 100px width.
If the wrap-flow property is working correctly then the content should start after the exclusion area, so the content's left offset should be 150px. */
exclusion.style.cssText = 'position: absolute; left: 50px; width: 100px; height: 20px;' + wrapFlowProperty + ':end;';
content.innerText = 'X';
container.appendChild(exclusion);
container.appendChild(content);
docElement.appendChild(container);
var leftOffset = content.offsetLeft;
docElement.removeChild(container);
exclusion = content = container = undefined;
return (leftOffset == 150);
});
/*!
{
"name": "Filesystem API",
"property": "filesystem",
"caniuse": "filesystem",
"notes": [{
"name": "W3 Draft",
"href": "dev.w3.org/2009/dap/file-system/file-dir-sys.html"
}],
"authors": ["Eric Bidelman (@ebidel)"],
"tags": ["file"],
"builderAliases": ["file_filesystem"],
"knownBugs": ["The API will be present in Chrome incognito, but will throw an exception. See crbug.com/93417"]
}
!*/
Modernizr.addTest('filesystem', !!prefixed('requestFileSystem', window));
/*!
{
"name": "form#requestAutocomplete()",
"property": "requestautocomplete",
"tags": ["form", "forms", "requestAutocomplete", "payments"],
"notes": [{
"name": "WHATWG proposed spec",
"href": "http://wiki.whatwg.org/wiki/RequestAutocomplete"
}]
}
!*/
/* DOC
When used with input[autocomplete] to annotate a form, form.requestAutocomplete() shows a dialog in Chrome that speeds up
checkout flows (payments specific for now).
*/
Modernizr.addTest('requestautocomplete', !!prefixed('requestAutocomplete', createElement('form')));
/*!
{
"authors": ["Cătălin Mariș"],
"name": "Speech Recognition API",
"notes": [
{
"name": "W3C Web Speech API Specification - The SpeechRecognition Interface",
"href": "https://dvcs.w3.org/hg/speech-api/raw-file/tip/speechapi.html#speechreco-section"
},
{
"name": "Introduction to the Web Speech API",
"href": "http://updates.html5rocks.com/2013/01/Voice-Driven-Web-Apps-Introduction-to-the-Web-Speech-API"
}
],
"property": "speechrecognition",
"tags": ["input", "speech"]
}
!*/
Modernizr.addTest('speechrecognition', !!prefixed('SpeechRecognition', window));
/*!
{
"name": "Blob URLs",
"property": "bloburls",
"caniuse": "bloburls",
"notes": [{
"name": "W3C Working Draft",
"href": "http://www.w3.org/TR/FileAPI/#creating-revoking"
}],
"tags": ["file", "url"],
"authors": ["Ron Waldon (@jokeyrhyme)"]
}
!*/
/* DOC
Detects support for creating Blob URLs
*/
var url = prefixed('URL', window, false);
url = url && window[url];
Modernizr.addTest('bloburls', url && 'revokeObjectURL' in url && 'createObjectURL' in url);
/*!
{
"name": "Transferables Objects",
"property": "transferables",
"tags": ["performance", "workers"],
"builderAliases": ["transferables"],
"notes": [{
"name": "HTML5 Rocks article",
"href": "http://updates.html5rocks.com/2011/12/Transferable-Objects-Lightning-Fast"
}],
"async": true
}
!*/
/* DOC
Detects whether web workers can use `transferables` objects.
*/
Modernizr.addAsyncTest(function() {
var prerequisites = !!(Modernizr.blobconstructor &&
Modernizr.bloburls &&
Modernizr.webworkers &&
Modernizr.typedarrays);
// Early exit
if (!prerequisites) {
return addTest('transferables', false);
}
// Proper test if prerequisites are met
try {
var buffer,
scriptText = 'var hello = "world"',
blob = new Blob([scriptText], {type: 'text/javascript'}),
url = URL.createObjectURL(blob),
worker = new Worker(url),
timeout;
// Just in case...
worker.onerror = fail;
timeout = setTimeout(fail, 200);
// Building an minimal array buffer to send to the worker
buffer = new ArrayBuffer(1);
// Sending the buffer to the worker
worker.postMessage(buffer, [buffer]);
// If length of buffer is now 0, transferables are working
addTest('transferables', buffer.byteLength === 0);
cleanup();
} catch (e) {
fail();
}
function fail() {
addTest('transferables', false);
cleanup();
}
function cleanup() {
if (url) {
URL.revokeObjectURL(url);
}
if (worker) {
worker.terminate();
}
if (timeout) {
clearTimeout(timeout);
}
}
});
/*!
{
"name": "getUserMedia",
"property": "getusermedia",
"caniuse": "stream",
"tags": ["webrtc"],
"authors": ["Eric Bidelman"],
"notes": [{
"name": "W3C Media Capture and Streams spec",
"href": "http://www.w3.org/TR/mediacapture-streams/"
}],
"polyfills": ["getusermedia"]
}
!*/
Modernizr.addTest('getusermedia', !!prefixed('getUserMedia', navigator));
/*!
{
"name": "RTC Peer Connection",
"property": "peerconnection",
"tags": ["webrtc"],
"authors": ["Ankur Oberoi"],
"notes": [{
"name": "W3C Web RTC spec",
"href": "http://www.w3.org/TR/webrtc/"
}]
}
!*/
Modernizr.addTest('peerconnection', !!prefixed('RTCPeerConnection', window));
/*!
{
"name": "RTC Data Channel",
"property": "datachannel",
"notes": [{
"name": "HTML5 Rocks! Article",
"href": "http://www.html5rocks.com/en/tutorials/webrtc/datachannels/"
}]
}
!*/
/* DOC
Detect for the RTCDataChannel API that allows for transfer data directly from one peer to another
*/
Modernizr.addTest('datachannel', function() {
if (!Modernizr.peerconnection) {
return false;
}
for (var i = 0, l = domPrefixes.length; i < l; i++) {
var PeerConnectionConstructor = window[domPrefixes[i] + 'RTCPeerConnection'];
if (PeerConnectionConstructor) {
var peerConnection = new PeerConnectionConstructor({
'iceServers': [{'url': 'stun:0'}]
});
return 'createDataChannel' in peerConnection;
}
}
return false;
});
/*!
{
"name": "matchMedia",
"property": "matchmedia",
"caniuse" : "matchmedia",
"tags": ["matchmedia"],
"authors": ["Alberto Elias"],
"notes": [{
"name": "W3C CSSOM View Module",
"href": "http://dev.w3.org/csswg/cssom-view/#the-mediaquerylist-interface"
}, {
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en-US/docs/Web/API/Window.matchMedia"
}],
"polyfills": ["matchmediajs"]
}
!*/
/* DOC
Detects support for matchMedia.
*/
Modernizr.addTest('matchmedia', !!prefixed('matchMedia', window));
/**
* testAllProps determines whether a given CSS property is supported in the browser
*
* @memberof Modernizr
* @name Modernizr.testAllProps
* @optionName Modernizr.testAllProps()
* @optionProp testAllProps
* @access public
* @function testAllProps
* @param {string} prop - String naming the property to test (either camelCase or kebab-case)
* @param {string} [value] - String of the value to test
* @param {boolean} [skipValueTest=false] - Whether to skip testing that the value is supported when using non-native detection
* @example
*
* testAllProps determines whether a given CSS property, in some prefixed form,
* is supported by the browser.
*
* ```js
* testAllProps('boxSizing') // true
* ```
*
* It can optionally be given a CSS value in string form to test if a property
* value is valid
*
* ```js
* testAllProps('display', 'block') // true
* testAllProps('display', 'penguin') // false
* ```
*
* A boolean can be passed as a third parameter to skip the value check when
* native detection (@supports) isn't available.
*
* ```js
* testAllProps('shapeOutside', 'content-box', true);
* ```
*/
function testAllProps(prop, value, skipValueTest) {
return testPropsAll(prop, undefined, undefined, value, skipValueTest);
}
ModernizrProto.testAllProps = testAllProps;
/*!
{
"name": "Font Ligatures",
"property": "ligatures",
"caniuse": "font-feature",
"notes": [{
"name": "Cross-browser Web Fonts",
"href": "http://www.sitepoint.com/cross-browser-web-fonts-part-3/"
}]
}
!*/
/* DOC
Detects support for OpenType ligatures
*/
Modernizr.addTest('ligatures', testAllProps('fontFeatureSettings', '"liga" 1'));
/*!
{
"name": "CSS Animations",
"property": "cssanimations",
"caniuse": "css-animation",
"polyfills": ["transformie", "csssandpaper"],
"tags": ["css"],
"warnings": ["Android < 4 will pass this test, but can only animate a single property at a time"],
"notes": [{
"name" : "Article: 'Dispelling the Android CSS animation myths'",
"href": "http://goo.gl/OGw5Gm"
}]
}
!*/
/* DOC
Detects whether or not elements can be animated using CSS
*/
Modernizr.addTest('cssanimations', testAllProps('animationName', 'a', true));
/*!
{
"name": "CSS Generated Content Animations",
"property": "csspseudoanimations",
"tags": ["css"]
}
!*/
Modernizr.addTest('csspseudoanimations', function() {
var result = false;
if (!Modernizr.cssanimations || !window.getComputedStyle) {
return result;
}
var styles = [
'@', Modernizr._prefixes.join('keyframes csspseudoanimations { from { font-size: 10px; } }@').replace(/\@$/, ''),
'#modernizr:before { content:" "; font-size:5px;',
Modernizr._prefixes.join('animation:csspseudoanimations 1ms infinite;'),
'}'
].join('');
Modernizr.testStyles(styles, function(elem) {
result = window.getComputedStyle(elem, ':before').getPropertyValue('font-size') === '10px';
});
return result;
});
/*!
{
"name": "Appearance",
"property": "appearance",
"caniuse": "css-appearance",
"tags": ["css"],
"notes": [{
"name": "MDN documentation",
"href": "https://developer.mozilla.org/en-US/docs/Web/CSS/-moz-appearance"
},{
"name": "CSS-Tricks CSS Almanac: appearance",
"href": "http://css-tricks.com/almanac/properties/a/appearance/"
}]
}
!*/
/* DOC
Detects support for the `appearance` css property, which is used to make an
element inherit the style of a standard user interface element. It can also be
used to remove the default styles of an element, such as input and buttons.
*/
Modernizr.addTest('appearance', testAllProps('appearance'));
/*!
{
"name": "Backdrop Filter",
"property": "backdropfilter",
"authors": ["Brian Seward"],
"tags": ["css"],
"notes": [
{
"name": "W3C Editor’s Draft specification",
"href": "http://dev.w3.org/fxtf/filters-2/#BackdropFilterProperty"
},
{
"name": "Caniuse for CSS Backdrop Filter",
"href": "http://caniuse.com/#feat=css-backdrop-filter"
},
{
"name": "WebKit Blog introduction + Demo",
"href": "https://www.webkit.org/blog/3632/introducing-backdrop-filters/"
}
]
}
!*/
/* DOC
Detects support for CSS Backdrop Filters, allowing for background blur effects like those introduced in iOS 7. Support for this was added to iOS Safari/WebKit in iOS 9.
*/
Modernizr.addTest('backdropfilter', testAllProps('backdropFilter'));
/*!
{
"name": "CSS Background Clip Text",
"property": "backgroundcliptext",
"authors": ["ausi"],
"tags": ["css"],
"notes": [
{
"name": "CSS Tricks Article",
"href": "http://css-tricks.com/image-under-text/"
},
{
"name": "MDN Docs",
"href": "http://developer.mozilla.org/en/CSS/background-clip"
},
{
"name": "Related Github Issue",
"href": "http://github.com/Modernizr/Modernizr/issues/199"
}
]
}
!*/
/* DOC
Detects the ability to control specifies whether or not an element's background
extends beyond its border in CSS
*/
Modernizr.addTest('backgroundcliptext', function() {
return testAllProps('backgroundClip', 'text');
});
/*!
{
"name": "Background Position XY",
"property": "bgpositionxy",
"tags": ["css"],
"builderAliases": ["css_backgroundposition_xy"],
"authors": ["Allan Lei", "Brandom Aaron"],
"notes": [{
"name": "Demo",
"href": "http://jsfiddle.net/allanlei/R8AYS/"
}, {
"name": "Adapted From",
"href": "https://github.com/brandonaaron/jquery-cssHooks/blob/master/bgpos.js"
}]
}
!*/
/* DOC
Detects the ability to control an element's background position using css
*/
Modernizr.addTest('bgpositionxy', function() {
return testAllProps('backgroundPositionX', '3px', true) && testAllProps('backgroundPositionY', '5px', true);
});
/*!
{
"name": "Background Repeat",
"property": ["bgrepeatspace", "bgrepeatround"],
"tags": ["css"],
"builderAliases": ["css_backgroundrepeat"],
"authors": ["Ryan Seddon"],
"notes": [{
"name": "MDN Docs",
"href": "http://developer.mozilla.org/en/CSS/background-repeat"
}, {
"name": "Test Page",
"href": "http://jsbin.com/uzesun/"
}, {
"name": "Demo",
"href": "http://jsfiddle.net/ryanseddon/yMLTQ/6/"
}]
}
!*/
/* DOC
Detects the ability to use round and space as properties for background-repeat
*/
// Must value-test these
Modernizr.addTest('bgrepeatround', testAllProps('backgroundRepeat', 'round'));
Modernizr.addTest('bgrepeatspace', testAllProps('backgroundRepeat', 'space'));
/*!
{
"name": "Background Size",
"property": "backgroundsize",
"tags": ["css"],
"knownBugs": ["This will false positive in Opera Mini - http://github.com/Modernizr/Modernizr/issues/396"],
"notes": [{
"name": "Related Issue",
"href": "http://github.com/Modernizr/Modernizr/issues/396"
}]
}
!*/
Modernizr.addTest('backgroundsize', testAllProps('backgroundSize', '100%', true));
/*!
{
"name": "Background Size Cover",
"property": "bgsizecover",
"tags": ["css"],
"builderAliases": ["css_backgroundsizecover"],
"notes": [{
"name" : "MDN Docs",
"href": "http://developer.mozilla.org/en/CSS/background-size"
}]
}
!*/
// Must test value, as this specifically tests the `cover` value
Modernizr.addTest('bgsizecover', testAllProps('backgroundSize', 'cover'));
/*!
{
"name": "Border Image",
"property": "borderimage",
"caniuse": "border-image",
"polyfills": ["css3pie"],
"knownBugs": ["Android < 2.0 is true, but has a broken implementation"],
"tags": ["css"]
}
!*/
Modernizr.addTest('borderimage', testAllProps('borderImage', 'url() 1', true));
/*!
{
"name": "Border Radius",
"property": "borderradius",
"caniuse": "border-radius",
"polyfills": ["css3pie"],
"tags": ["css"],
"notes": [{
"name": "Comprehensive Compat Chart",
"href": "http://muddledramblings.com/table-of-css3-border-radius-compliance"
}]
}
!*/
Modernizr.addTest('borderradius', testAllProps('borderRadius', '0px', true));
/*!
{
"name": "Box Shadow",
"property": "boxshadow",
"caniuse": "css-boxshadow",
"tags": ["css"],
"knownBugs": [
"WebOS false positives on this test.",
"The Kindle Silk browser false positives"
]
}
!*/
Modernizr.addTest('boxshadow', testAllProps('boxShadow', '1px 1px', true));
/*!
{
"name": "Box Sizing",
"property": "boxsizing",
"caniuse": "css3-boxsizing",
"polyfills": ["borderboxmodel", "boxsizingpolyfill", "borderbox"],
"tags": ["css"],
"builderAliases": ["css_boxsizing"],
"notes": [{
"name": "MDN Docs",
"href": "http://developer.mozilla.org/en/CSS/box-sizing"
},{
"name": "Related Github Issue",
"href": "http://github.com/Modernizr/Modernizr/issues/248"
}]
}
!*/
Modernizr.addTest('boxsizing', testAllProps('boxSizing', 'border-box', true) && (document.documentMode === undefined || document.documentMode > 7));
/*!
{
"name": "CSS Columns",
"property": "csscolumns",
"caniuse": "multicolumn",
"polyfills": ["css3multicolumnjs"],
"tags": ["css"]
}
!*/
(function() {
/* jshint -W053 */
Modernizr.addTest('csscolumns', function() {
var bool = false;
var test = testAllProps('columnCount');
try {
if (bool = !!test) {
bool = new Boolean(bool);
}
} catch (e) {}
return bool;
});
var props = ['Width', 'Span', 'Fill', 'Gap', 'Rule', 'RuleColor', 'RuleStyle', 'RuleWidth', 'BreakBefore', 'BreakAfter', 'BreakInside'];
var name, test;
for (var i = 0; i < props.length; i++) {
name = props[i].toLowerCase();
test = testAllProps('column' + props[i]);
// break-before, break-after & break-inside are not "column"-prefixed in spec
if (name === 'breakbefore' || name === 'breakafter' || name == 'breakinside') {
test = test || testAllProps(props[i]);
}
Modernizr.addTest('csscolumns.' + name, test);
}
})();
/*!
{
"name": "CSS Display run-in",
"property": "display-runin",
"authors": ["alanhogan"],
"tags": ["css"],
"builderAliases": ["css_displayrunin"],
"notes": [{
"name": "CSS Tricks Article",
"href": "http://css-tricks.com/596-run-in/"
},{
"name": "Related Github Issue",
"href": "https://github.com/Modernizr/Modernizr/issues/198"
}]
}
!*/
Modernizr.addTest('displayrunin', testAllProps('display', 'run-in'),
{aliases: ['display-runin']});
/*!
{
"name": "CSS text-overflow ellipsis",
"property": "ellipsis",
"caniuse": "text-overflow",
"polyfills": [
"text-overflow"
],
"tags": ["css"]
}
!*/
Modernizr.addTest('ellipsis', testAllProps('textOverflow', 'ellipsis'));
/*!
{
"name": "CSS Filters",
"property": "cssfilters",
"caniuse": "css-filters",
"polyfills": ["polyfilter"],
"tags": ["css"],
"builderAliases": ["css_filters"],
"notes": [{
"name": "MDN article on CSS filters",
"href": "https://developer.mozilla.org/en-US/docs/Web/CSS/filter"
}]
}
!*/
Modernizr.addTest('cssfilters', function() {
if (Modernizr.supports) {
return testAllProps('filter', 'blur(2px)');
} else {
var el = createElement('a');
el.style.cssText = prefixes.join('filter:blur(2px); ');
// https://github.com/Modernizr/Modernizr/issues/615
// documentMode is needed for false positives in oldIE, please see issue above
return !!el.style.length && ((document.documentMode === undefined || document.documentMode > 9));
}
});
/*!
{
"name": "Flexbox",
"property": "flexbox",
"caniuse": "flexbox",
"tags": ["css"],
"notes": [{
"name": "The _new_ flexbox",
"href": "http://dev.w3.org/csswg/css3-flexbox"
}],
"warnings": [
"A `true` result for this detect does not imply that the `flex-wrap` property is supported; see the `flexwrap` detect."
]
}
!*/
/* DOC
Detects support for the Flexible Box Layout model, a.k.a. Flexbox, which allows easy manipulation of layout order and sizing within a container.
*/
Modernizr.addTest('flexbox', testAllProps('flexBasis', '1px', true));
/*!
{
"name": "Flexbox (legacy)",
"property": "flexboxlegacy",
"tags": ["css"],
"polyfills": ["flexie"],
"notes": [{
"name": "The _old_ flexbox",
"href": "http://www.w3.org/TR/2009/WD-css3-flexbox-20090723/"
}]
}
!*/
Modernizr.addTest('flexboxlegacy', testAllProps('boxDirection', 'reverse', true));
/*!
{
"name": "Flexbox (tweener)",
"property": "flexboxtweener",
"tags": ["css"],
"polyfills": ["flexie"],
"notes": [{
"name": "The _inbetween_ flexbox",
"href": "http://www.w3.org/TR/2011/WD-css3-flexbox-20111129/"
}],
"warnings": ["This represents an old syntax, not the latest standard syntax."]
}
!*/
Modernizr.addTest('flexboxtweener', testAllProps('flexAlign', 'end', true));
/*!
{
"name": "Flex Line Wrapping",
"property": "flexwrap",
"tags": ["css", "flexbox"],
"notes": [{
"name": "W3C Flexible Box Layout spec",
"href": "http://dev.w3.org/csswg/css3-flexbox"
}],
"warnings": [
"Does not imply a modern implementation – see documentation."
]
}
!*/
/* DOC
Detects support for the `flex-wrap` CSS property, part of Flexbox, which isn’t present in all Flexbox implementations (notably Firefox).
This featured in both the 'tweener' syntax (implemented by IE10) and the 'modern' syntax (implemented by others). This detect will return `true` for either of these implementations, as long as the `flex-wrap` property is supported. So to ensure the modern syntax is supported, use together with `Modernizr.flexbox`:
```javascript
if (Modernizr.flexbox && Modernizr.flexwrap) {
// Modern Flexbox with `flex-wrap` supported
}
else {
// Either old Flexbox syntax, or `flex-wrap` not supported
}
```
*/
Modernizr.addTest('flexwrap', testAllProps('flexWrap', 'wrap', true));
/*!
{
"name": "CSS Hyphens",
"caniuse": "css-hyphens",
"property": ["csshyphens", "softhyphens", "softhyphensfind"],
"tags": ["css"],
"builderAliases": ["css_hyphens"],
"async" : true,
"authors": ["David Newton"],
"warnings": [
"These tests currently require document.body to be present",
"If loading Hyphenator.js via yepnope, be cautious of issue 158: http://code.google.com/p/hyphenator/issues/detail?id=158",
"This is very large – only include it if you absolutely need it"
],
"notes": [{
"name": "The Current State of Hyphenation on the Web.",
"href": "http://davidnewton.ca/the-current-state-of-hyphenation-on-the-web"
},{
"name": "Hyphenation Test Page",
"href": "http://davidnewton.ca/demos/hyphenation/test.html"
},{
"name": "Hyphenation is Language Specific",
"href": " http://code.google.com/p/hyphenator/source/diff?spec=svn975&r=975&format=side&path=/trunk/Hyphenator.js#sc_svn975_313"
},{
"name": "Related Modernizr Issue",
"href": "https://github.com/Modernizr/Modernizr/issues/312"
}]
}
!*/
Modernizr.addAsyncTest(function() {
var waitTime = 300;
setTimeout(runHyphenTest, waitTime);
// Wait 1000ms so we can hope for document.body
function runHyphenTest() {
if (!document.body && !document.getElementsByTagName('body')[0]) {
setTimeout(runHyphenTest, waitTime);
return;
}
// functional test of adding hyphens:auto
function test_hyphens_css() {
try {
/* create a div container and a span within that
* these have to be appended to document.body, otherwise some browsers can give false negative */
var div = createElement('div');
var span = createElement('span');
var divStyle = div.style;
var spanHeight = 0;
var spanWidth = 0;
var result = false;
var firstChild = document.body.firstElementChild || document.body.firstChild;
div.appendChild(span);
span.innerHTML = 'Bacon ipsum dolor sit amet jerky velit in culpa hamburger et. Laborum dolor proident, enim dolore duis commodo et strip steak. Salami anim et, veniam consectetur dolore qui tenderloin jowl velit sirloin. Et ad culpa, fatback cillum jowl ball tip ham hock nulla short ribs pariatur aute. Pig pancetta ham bresaola, ut boudin nostrud commodo flank esse cow tongue culpa. Pork belly bresaola enim pig, ea consectetur nisi. Fugiat officia turkey, ea cow jowl pariatur ullamco proident do laborum velit sausage. Magna biltong sint tri-tip commodo sed bacon, esse proident aliquip. Ullamco ham sint fugiat, velit in enim sed mollit nulla cow ut adipisicing nostrud consectetur. Proident dolore beef ribs, laborum nostrud meatball ea laboris rump cupidatat labore culpa. Shankle minim beef, velit sint cupidatat fugiat tenderloin pig et ball tip. Ut cow fatback salami, bacon ball tip et in shank strip steak bresaola. In ut pork belly sed mollit tri-tip magna culpa veniam, short ribs qui in andouille ham consequat. Dolore bacon t-bone, velit short ribs enim strip steak nulla. Voluptate labore ut, biltong swine irure jerky. Cupidatat excepteur aliquip salami dolore. Ball tip strip steak in pork dolor. Ad in esse biltong. Dolore tenderloin exercitation ad pork loin t-bone, dolore in chicken ball tip qui pig. Ut culpa tongue, sint ribeye dolore ex shank voluptate hamburger. Jowl et tempor, boudin pork chop labore ham hock drumstick consectetur tri-tip elit swine meatball chicken ground round. Proident shankle mollit dolore. Shoulder ut duis t-bone quis reprehenderit. Meatloaf dolore minim strip steak, laboris ea aute bacon beef ribs elit shank in veniam drumstick qui. Ex laboris meatball cow tongue pork belly. Ea ball tip reprehenderit pig, sed fatback boudin dolore flank aliquip laboris eu quis. Beef ribs duis beef, cow corned beef adipisicing commodo nisi deserunt exercitation. Cillum dolor t-bone spare ribs, ham hock est sirloin. Brisket irure meatloaf in, boudin pork belly sirloin ball tip. Sirloin sint irure nisi nostrud aliqua. Nostrud nulla aute, enim officia culpa ham hock. Aliqua reprehenderit dolore sunt nostrud sausage, ea boudin pork loin ut t-bone ham tempor. Tri-tip et pancetta drumstick laborum. Ham hock magna do nostrud in proident. Ex ground round fatback, venison non ribeye in.';
document.body.insertBefore(div, firstChild);
/* get size of unhyphenated text */
divStyle.cssText = 'position:absolute;top:0;left:0;width:5em;text-align:justify;text-justification:newspaper;';
spanHeight = span.offsetHeight;
spanWidth = span.offsetWidth;
/* compare size with hyphenated text */
divStyle.cssText = 'position:absolute;top:0;left:0;width:5em;text-align:justify;' +
'text-justification:newspaper;' +
prefixes.join('hyphens:auto; ');
result = (span.offsetHeight != spanHeight || span.offsetWidth != spanWidth);
/* results and cleanup */
document.body.removeChild(div);
div.removeChild(span);
return result;
} catch (e) {
return false;
}
}
// for the softhyphens test
function test_hyphens(delimiter, testWidth) {
try {
/* create a div container and a span within that
* these have to be appended to document.body, otherwise some browsers can give false negative */
var div = createElement('div');
var span = createElement('span');
var divStyle = div.style;
var spanSize = 0;
var result = false;
var result1 = false;
var result2 = false;
var firstChild = document.body.firstElementChild || document.body.firstChild;
divStyle.cssText = 'position:absolute;top:0;left:0;overflow:visible;width:1.25em;';
div.appendChild(span);
document.body.insertBefore(div, firstChild);
/* get height of unwrapped text */
span.innerHTML = 'mm';
spanSize = span.offsetHeight;
/* compare height w/ delimiter, to see if it wraps to new line */
span.innerHTML = 'm' + delimiter + 'm';
result1 = (span.offsetHeight > spanSize);
/* if we're testing the width too (i.e. for soft-hyphen, not zws),
* this is because tested Blackberry devices will wrap the text but not display the hyphen */
if (testWidth) {
/* get width of wrapped, non-hyphenated text */
span.innerHTML = 'm<br />m';
spanSize = span.offsetWidth;
/* compare width w/ wrapped w/ delimiter to see if hyphen is present */
span.innerHTML = 'm' + delimiter + 'm';
result2 = (span.offsetWidth > spanSize);
} else {
result2 = true;
}
/* results and cleanup */
if (result1 === true && result2 === true) { result = true; }
document.body.removeChild(div);
div.removeChild(span);
return result;
} catch (e) {
return false;
}
}
// testing if in-browser Find functionality will work on hyphenated text
function test_hyphens_find(delimiter) {
try {
/* create a dummy input for resetting selection location, and a div container
* these have to be appended to document.body, otherwise some browsers can give false negative
* div container gets the doubled testword, separated by the delimiter
* Note: giving a width to div gives false positive in iOS Safari */
var dummy = createElement('input');
var div = createElement('div');
var testword = 'lebowski';
var result = false;
var textrange;
var firstChild = document.body.firstElementChild || document.body.firstChild;
div.innerHTML = testword + delimiter + testword;
document.body.insertBefore(div, firstChild);
document.body.insertBefore(dummy, div);
/* reset the selection to the dummy input element, i.e. BEFORE the div container
* stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area */
if (dummy.setSelectionRange) {
dummy.focus();
dummy.setSelectionRange(0, 0);
} else if (dummy.createTextRange) {
textrange = dummy.createTextRange();
textrange.collapse(true);
textrange.moveEnd('character', 0);
textrange.moveStart('character', 0);
textrange.select();
}
/* try to find the doubled testword, without the delimiter */
try {
if (window.find) {
result = window.find(testword + testword);
} else {
textrange = window.self.document.body.createTextRange();
result = textrange.findText(testword + testword);
}
} catch (e) {
result = false;
}
document.body.removeChild(div);
document.body.removeChild(dummy);
return result;
} catch (e) {
return false;
}
}
addTest('csshyphens', function() {
if (!testAllProps('hyphens', 'auto', true)) {
return false;
}
/* Chrome lies about its hyphens support so we need a more robust test
crbug.com/107111
*/
try {
return test_hyphens_css();
} catch (e) {
return false;
}
});
addTest('softhyphens', function() {
try {
// use numeric entity instead of ­ in case it's XHTML
return test_hyphens('­', true) && test_hyphens('​', false);
} catch (e) {
return false;
}
});
addTest('softhyphensfind', function() {
try {
return test_hyphens_find('­') && test_hyphens_find('​');
} catch (e) {
return false;
}
});
}
});
/*!
{
"name": "CSS Mask",
"caniuse": "css-masks",
"property": "cssmask",
"tags": ["css"],
"builderAliases": ["css_mask"],
"notes": [
{
"name": "Webkit blog on CSS Masks",
"href": "http://www.webkit.org/blog/181/css-masks/"
},
{
"name": "Safari Docs",
"href": "http://developer.apple.com/library/safari/#documentation/InternetWeb/Conceptual/SafariVisualEffectsProgGuide/Masks/Masks.html"
},
{
"name": "Mozilla css svg mask (not this)",
"href": "http://developer.mozilla.org/en/CSS/mask"
},
{
"name": "Combine with clippaths for awesomeness",
"href": "http://generic.cx/for/webkit/test.html"
}
]
}
!*/
Modernizr.addTest('cssmask', testAllProps('maskRepeat', 'repeat-x', true));
/*!
{
"name": "CSS Overflow Scrolling",
"property": "overflowscrolling",
"tags": ["css"],
"builderAliases": ["css_overflow_scrolling"],
"warnings": ["Introduced in iOS5b2. API is subject to change."],
"notes": [{
"name": "Article on iOS overflow scrolling",
"href": "http://css-tricks.com/snippets/css/momentum-scrolling-on-ios-overflow-elements/"
}]
}
!*/
Modernizr.addTest('overflowscrolling', testAllProps('overflowScrolling', 'touch', true));
/*!
{
"name": "CSS Reflections",
"caniuse": "css-reflections",
"property": "cssreflections",
"tags": ["css"]
}
!*/
Modernizr.addTest('cssreflections', testAllProps('boxReflect', 'above', true));
/*!
{
"name": "CSS UI Resize",
"property": "cssresize",
"caniuse": "css-resize",
"tags": ["css"],
"builderAliases": ["css_resize"],
"notes": [{
"name": "W3C Specification",
"href": "http://www.w3.org/TR/css3-ui/#resize"
},{
"name": "MDN Docs",
"href": "https://developer.mozilla.org/en/CSS/resize"
}]
}
!*/
/* DOC
Test for CSS 3 UI "resize" property
*/
Modernizr.addTest('cssresize', testAllProps('resize', 'both', true));
/*!
{
"name": "Scroll Snap Points",
"property": "scrollsnappoints",
"notes": [{
"name": "Setting native-like scrolling offsets in CSS with Scrolling Snap Points",
"href": "http://generatedcontent.org/post/66817675443/setting-native-like-scrolling-offsets-in-css-with"
},{
"name": "MDN Article",
"href": "https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Scroll_Snap_Points"
}],
"polyfills": ["scrollsnap"]
}
!*/
/* DOC
Detects support for CSS Snap Points
*/
Modernizr.addTest('scrollsnappoints', testAllProps('scrollSnapType'));
/*!
{
"name": "CSS Shapes",
"property": "shapes",
"tags": ["css"],
"notes": [{
"name": "CSS Shapes W3C specification",
"href": "http://www.w3.org/TR/css-shapes"
},{
"name": "Examples from Adobe",
"href": "http://html.adobe.com/webplatform/layout/shapes"
}, {
"name": "Samples showcasing uses of Shapes",
"href": "http://codepen.io/collection/qFesk"
}]
}
!*/
Modernizr.addTest('shapes', testAllProps('shapeOutside', 'content-box', true));
/*!
{
"name": "CSS text-align-last",
"property": "textalignlast",
"tags": ["css"],
"knownBugs": ["IE does not support the 'start' or 'end' values."],
"notes": [{
"name": "Quicksmode",
"href": "http://www.quirksmode.org/css/text/textalignlast.html"
},{
"name": "MDN",
"href": "https://developer.mozilla.org/en-US/docs/Web/CSS/text-align-last"
}]
}
!*/
Modernizr.addTest('textalignlast', testAllProps('textAlignLast'));
/*!
{
"name": "CSS Transforms",
"property": "csstransforms",
"caniuse": "transforms2d",
"tags": ["css"]
}
!*/
Modernizr.addTest('csstransforms', function() {
// Android < 3.0 is buggy, so we sniff and blacklist
// http://git.io/hHzL7w
return navigator.userAgent.indexOf('Android 2.') === -1 &&
testAllProps('transform', 'scale(1)', true);
});
/*!
{
"name": "CSS Transforms 3D",
"property": "csstransforms3d",
"caniuse": "transforms3d",
"tags": ["css"],
"warnings": [
"Chrome may occassionally fail this test on some systems; more info: https://code.google.com/p/chromium/issues/detail?id=129004"
]
}
!*/
Modernizr.addTest('csstransforms3d', function() {
var ret = !!testAllProps('perspective', '1px', true);
var usePrefix = Modernizr._config.usePrefixes;
// Webkit's 3D transforms are passed off to the browser's own graphics renderer.
// It works fine in Safari on Leopard and Snow Leopard, but not in Chrome in
// some conditions. As a result, Webkit typically recognizes the syntax but
// will sometimes throw a false positive, thus we must do a more thorough check:
if (ret && (!usePrefix || 'webkitPerspective' in docElement.style)) {
var mq;
var defaultStyle = '#modernizr{width:0;height:0}';
// Use CSS Conditional Rules if available
if (Modernizr.supports) {
mq = '@supports (perspective: 1px)';
} else {
// Otherwise, Webkit allows this media query to succeed only if the feature is enabled.
// `@media (transform-3d),(-webkit-transform-3d){ ... }`
mq = '@media (transform-3d)';
if (usePrefix) {
mq += ',(-webkit-transform-3d)';
}
}
mq += '{#modernizr{width:7px;height:18px;margin:0;padding:0;border:0}}';
testStyles(defaultStyle + mq, function(elem) {
ret = elem.offsetWidth === 7 && elem.offsetHeight === 18;
});
}
return ret;
});
/*!
{
"name": "CSS Transform Style preserve-3d",
"property": "preserve3d",
"authors": ["edmellum"],
"tags": ["css"],
"notes": [{
"name": "MDN Docs",
"href": "https://developer.mozilla.org/en-US/docs/Web/CSS/transform-style"
},{
"name": "Related Github Issue",
"href": "https://github.com/Modernizr/Modernizr/issues/762"
}]
}
!*/
/* DOC
Detects support for `transform-style: preserve-3d`, for getting a proper 3D perspective on elements.
*/
Modernizr.addTest('preserve3d', testAllProps('transformStyle', 'preserve-3d'));
/*!
{
"name": "CSS Transitions",
"property": "csstransitions",
"caniuse": "css-transitions",
"tags": ["css"]
}
!*/
Modernizr.addTest('csstransitions', testAllProps('transition', 'all', true));
/*!
{
"name": "CSS Generated Content Transitions",
"property": "csspseudotransitions",
"tags": ["css"]
}
!*/
Modernizr.addTest('csspseudotransitions', function() {
var result = false;
if (!Modernizr.csstransitions || !window.getComputedStyle) {
return result;
}
var styles =
'#modernizr:before { content:" "; font-size:5px;' + Modernizr._prefixes.join('transition:0s 100s;') + '}' +
'#modernizr.trigger:before { font-size:10px; }';
Modernizr.testStyles(styles, function(elem) {
// Force rendering of the element's styles so that the transition will trigger
window.getComputedStyle(elem, ':before').getPropertyValue('font-size');
elem.className += 'trigger';
result = window.getComputedStyle(elem, ':before').getPropertyValue('font-size') === '5px';
});
return result;
});
/*!
{
"name": "CSS user-select",
"property": "userselect",
"caniuse": "user-select-none",
"authors": ["ryan seddon"],
"tags": ["css"],
"builderAliases": ["css_userselect"],
"notes": [{
"name": "Related Modernizr Issue",
"href": "https://github.com/Modernizr/Modernizr/issues/250"
}]
}
!*/
//https://github.com/Modernizr/Modernizr/issues/250
Modernizr.addTest('userselect', testAllProps('userSelect', 'none', true));
// Run each test
testRunner();
// Remove the "no-js" class if it exists
setClasses(classes);
delete ModernizrProto.addTest;
delete ModernizrProto.addAsyncTest;
// Run the things that are supposed to run after the tests
for (var i = 0; i < Modernizr._q.length; i++) {
Modernizr._q[i]();
}
// Leak Modernizr namespace
window.Modernizr = Modernizr;
;
})(window, document);
|
nts(newElem
|
estoque.controller.ts
|
import { Controller, Get, Param, Post, Body, Delete } from '@nestjs/common';
import { EstoqueService } from './estoque.service';
@Controller('estoque')
export class
|
{
constructor(private readonly estoque: EstoqueService) { }
@Get()
async findAll() {
return await this.estoque.findAll();
}
@Get(":id")
async findById(@Param() id: number) {
return this.estoque.findById(id)
}
@Post()
async create(@Body() estoque) {
return await this.estoque.create(estoque)
}
@Delete(":id")
async delete(@Param() id: number) {
return this.delete(id);
}
}
|
EstoqueController
|
filesystems.py
|
from stard.services import Executable
class Service(Executable):
start_command = ('mount', '-a')
post_start_commands = (
('mount', '-o', 'remount,rw', '/'),
)
stop_command = ('sh', '-c', 'umount -af; true')
post_stop_commands = (
('mount', '-o', 'remount,ro', '/'),
)
oneshot = True
def
|
(self):
self.add_parent('system_mountpoints')
self.add_parent('udev')
|
init_service
|
logistic_regression.py
|
import numpy as np
from sklearn.datasets import make_blobs
import matplotlib.pyplot as plt
### --- Gather Dataset --- ###
n = 100
X, y = make_blobs(n_samples = n, centers = 2)
y = y[:, np.newaxis]
### --- Build Model --- ###
def sigmoid(z):
return 1.0 / (1.0 + np.exp(-z))
class LogisticRegression:
|
### --- Instantiate Model --- ###
model = LogisticRegression()
model.fit(X, y)
weight0, weight1 = model.weights
bias = model.bias[0][0]
### --- Plot --- ###
for i in range(n):
if (y[i] == 1):
plt.scatter(X[:, 0][i], X[:, 1][i], color="green")
else:
plt.scatter(X[:, 0][i], X[:, 1][i], color="blue")
x = np.linspace(-5, 5, 5)
hyperplane = (-(weight0 / weight1) * x) - (bias / weight1)
plt.suptitle("Logistic Regression")
plt.plot(x, hyperplane, '-', color = "red")
plt.show()
|
def predict(self, X, w, b):
return sigmoid(X.dot(w) + b)
def loss(self, pred, y):
BCE = (y * np.log(pred + 1e-6) + (1 - y) * np.log(1 - pred + 1e-6))
return -np.sum(BCE) * (1.0 / self.m)
def fit(self, X, y):
eta = 0.01
epochs = 5000
self.m, self.n = X.shape
self.weights = np.random.uniform(-1, 1, (self.n, 1))
self.bias = np.random.uniform(-1, 1, (1, 1))
for i in range(epochs):
predicted = self.predict(X, self.weights, self.bias)
if i % 100 == 0: print("Loss on step {} is: {}".format(i, self.loss(predicted, y)))
self.weights = self.weights - eta * X.T.dot(predicted - y)
self.bias = self.bias - eta * np.sum(predicted - y)
|
get_proxies_health_responses.go
|
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// Code generated by go-swagger; DO NOT EDIT.
package platform_infrastructure
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"fmt"
"io"
"github.com/go-openapi/runtime"
strfmt "github.com/go-openapi/strfmt"
models "github.com/elastic/cloud-sdk-go/pkg/models"
)
// GetProxiesHealthReader is a Reader for the GetProxiesHealth structure.
type GetProxiesHealthReader struct {
formats strfmt.Registry
}
// ReadResponse reads a server response into the received o.
func (o *GetProxiesHealthReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
switch response.Code() {
case 200:
result := NewGetProxiesHealthOK()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return result, nil
case 417:
result := NewGetProxiesHealthExpectationFailed()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
case 449:
result := NewGetProxiesHealthRetryWith()
if err := result.readResponse(response, consumer, o.formats); err != nil {
return nil, err
}
return nil, result
default:
return nil, runtime.NewAPIError("unknown error", response, response.Code())
}
}
// NewGetProxiesHealthOK creates a GetProxiesHealthOK with default headers values
func NewGetProxiesHealthOK() *GetProxiesHealthOK {
return &GetProxiesHealthOK{}
}
/*GetProxiesHealthOK handles this case with default header values.
Returns health information on all the proxies
*/
type GetProxiesHealthOK struct {
Payload *models.ProxiesHealth
}
func (o *GetProxiesHealthOK) Error() string {
return fmt.Sprintf("[GET /platform/infrastructure/proxies/health][%d] getProxiesHealthOK %+v", 200, o.Payload)
}
func (o *GetProxiesHealthOK) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(models.ProxiesHealth)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
// NewGetProxiesHealthExpectationFailed creates a GetProxiesHealthExpectationFailed with default headers values
func NewGetProxiesHealthExpectationFailed() *GetProxiesHealthExpectationFailed
|
/*GetProxiesHealthExpectationFailed handles this case with default header values.
The health status is worse than the expected one.
*/
type GetProxiesHealthExpectationFailed struct {
Payload *models.ProxiesHealth
}
func (o *GetProxiesHealthExpectationFailed) Error() string {
return fmt.Sprintf("[GET /platform/infrastructure/proxies/health][%d] getProxiesHealthExpectationFailed %+v", 417, o.Payload)
}
func (o *GetProxiesHealthExpectationFailed) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
o.Payload = new(models.ProxiesHealth)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
// NewGetProxiesHealthRetryWith creates a GetProxiesHealthRetryWith with default headers values
func NewGetProxiesHealthRetryWith() *GetProxiesHealthRetryWith {
return &GetProxiesHealthRetryWith{}
}
/*GetProxiesHealthRetryWith handles this case with default header values.
Elevated permissions are required. (code: `root.unauthorized.rbac.elevated_permissions_required`)
*/
type GetProxiesHealthRetryWith struct {
/*The error codes associated with the response
*/
XCloudErrorCodes string
Payload *models.BasicFailedReply
}
func (o *GetProxiesHealthRetryWith) Error() string {
return fmt.Sprintf("[GET /platform/infrastructure/proxies/health][%d] getProxiesHealthRetryWith %+v", 449, o.Payload)
}
func (o *GetProxiesHealthRetryWith) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error {
// response header x-cloud-error-codes
o.XCloudErrorCodes = response.GetHeader("x-cloud-error-codes")
o.Payload = new(models.BasicFailedReply)
// response payload
if err := consumer.Consume(response.Body(), o.Payload); err != nil && err != io.EOF {
return err
}
return nil
}
|
{
return &GetProxiesHealthExpectationFailed{}
}
|
projects.py
|
from models.project import Project
import time
class ProjectHelper:
def __init__(self, app):
self.app = app
def open_projects_page(self):
dw = self.app.dw
if not dw.current_url.endswith("/manage_proj_page.php"):
dw.find_element_by_link_text("Manage").click()
dw.find_element_by_link_text("Manage Projects").click()
def
|
(self, project):
dw = self.app.dw
self.open_projects_page()
dw.find_element_by_xpath("//input[@value='Create New Project']").click()
dw.find_element_by_name("name").send_keys(project.name)
dw.find_element_by_xpath("//textarea[@name='description']").send_keys(
project.description)
dw.find_element_by_xpath("//input[@value='Add Project']").click()
time.sleep(3)
def get_projects_list(self):
dw = self.app.dw
self.open_projects_page()
projects = []
for element in dw.find_elements_by_xpath(
"//table[@class='width100']//tr[contains(@class, 'row')]"):
name = element.find_element_by_xpath(".//td[1]").text
description = element.find_element_by_xpath(".//td[5]").text
projects.append(Project(name=name, description=description))
projects.pop(0)
return projects
def delete_by_index(self, index):
dw = self.app.dw
self.open_projects_page()
dw.find_elements_by_xpath("//table[@class='width100']//tr[contains("
"@class, 'row')]//td//a[contains("
"@href, 'edit')]")[index].click()
time.sleep(1)
dw.find_element_by_xpath("//input[@value='Delete Project']").click()
dw.find_element_by_xpath("//input[@value='Delete Project']").click()
|
create
|
openstack.go
|
/*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package openstack
import (
"crypto/tls"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"regexp"
"strings"
"time"
"github.com/gophercloud/gophercloud"
"github.com/gophercloud/gophercloud/openstack"
"github.com/gophercloud/gophercloud/openstack/compute/v2/extensions/attachinterfaces"
"github.com/gophercloud/gophercloud/openstack/compute/v2/servers"
"github.com/gophercloud/gophercloud/openstack/identity/v3/extensions/trusts"
tokens3 "github.com/gophercloud/gophercloud/openstack/identity/v3/tokens"
"github.com/gophercloud/gophercloud/pagination"
"github.com/mitchellh/mapstructure"
"gopkg.in/gcfg.v1"
"github.com/golang/glog"
"k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/types"
netutil "k8s.io/apimachinery/pkg/util/net"
certutil "k8s.io/client-go/util/cert"
v1helper "k8s.io/kubernetes/pkg/apis/core/v1/helper"
"k8s.io/kubernetes/pkg/cloudprovider"
"k8s.io/kubernetes/pkg/controller"
)
const (
// ProviderName is the name of the openstack provider
ProviderName = "openstack"
availabilityZone = "availability_zone"
defaultTimeOut = 60 * time.Second
)
// ErrNotFound is used to inform that the object is missing
var ErrNotFound = errors.New("failed to find object")
// ErrMultipleResults is used when we unexpectedly get back multiple results
var ErrMultipleResults = errors.New("multiple results where only one expected")
// ErrNoAddressFound is used when we cannot find an ip address for the host
var ErrNoAddressFound = errors.New("no address found for host")
// MyDuration is the encoding.TextUnmarshaler interface for time.Duration
type MyDuration struct {
time.Duration
}
// UnmarshalText is used to convert from text to Duration
func (d *MyDuration) UnmarshalText(text []byte) error {
res, err := time.ParseDuration(string(text))
if err != nil {
return err
}
d.Duration = res
return nil
}
// LoadBalancer is used for creating and maintaining load balancers
type LoadBalancer struct {
network *gophercloud.ServiceClient
compute *gophercloud.ServiceClient
lb *gophercloud.ServiceClient
opts LoadBalancerOpts
}
// LoadBalancerOpts have the options to talk to Neutron LBaaSV2 or Octavia
type LoadBalancerOpts struct {
LBVersion string `gcfg:"lb-version"` // overrides autodetection. Only support v2.
UseOctavia bool `gcfg:"use-octavia"` // uses Octavia V2 service catalog endpoint
SubnetID string `gcfg:"subnet-id"` // overrides autodetection.
FloatingNetworkID string `gcfg:"floating-network-id"` // If specified, will create floating ip for loadbalancer, or do not create floating ip.
LBMethod string `gcfg:"lb-method"` // default to ROUND_ROBIN.
LBProvider string `gcfg:"lb-provider"`
CreateMonitor bool `gcfg:"create-monitor"`
MonitorDelay MyDuration `gcfg:"monitor-delay"`
MonitorTimeout MyDuration `gcfg:"monitor-timeout"`
MonitorMaxRetries uint `gcfg:"monitor-max-retries"`
ManageSecurityGroups bool `gcfg:"manage-security-groups"`
NodeSecurityGroupIDs []string // Do not specify, get it automatically when enable manage-security-groups. TODO(FengyunPan): move it into cache
}
// BlockStorageOpts is used to talk to Cinder service
type BlockStorageOpts struct {
BSVersion string `gcfg:"bs-version"` // overrides autodetection. v1 or v2. Defaults to auto
TrustDevicePath bool `gcfg:"trust-device-path"` // See Issue #33128
IgnoreVolumeAZ bool `gcfg:"ignore-volume-az"`
}
// RouterOpts is used for Neutron routes
type RouterOpts struct {
RouterID string `gcfg:"router-id"` // required
}
// MetadataOpts is used for configuring how to talk to metadata service or config drive
type MetadataOpts struct {
SearchOrder string `gcfg:"search-order"`
RequestTimeout MyDuration `gcfg:"request-timeout"`
}
// OpenStack is an implementation of cloud provider Interface for OpenStack.
type OpenStack struct {
provider *gophercloud.ProviderClient
region string
lbOpts LoadBalancerOpts
bsOpts BlockStorageOpts
routeOpts RouterOpts
metadataOpts MetadataOpts
// InstanceID of the server where this OpenStack object is instantiated.
localInstanceID string
}
// Config is used to read and store information from the cloud configuration file
type Config struct {
Global struct {
AuthURL string `gcfg:"auth-url"`
Username string
UserID string `gcfg:"user-id"`
Password string
TenantID string `gcfg:"tenant-id"`
TenantName string `gcfg:"tenant-name"`
TrustID string `gcfg:"trust-id"`
DomainID string `gcfg:"domain-id"`
DomainName string `gcfg:"domain-name"`
Region string
CAFile string `gcfg:"ca-file"`
}
LoadBalancer LoadBalancerOpts
BlockStorage BlockStorageOpts
Route RouterOpts
Metadata MetadataOpts
}
func init() {
registerMetrics()
cloudprovider.RegisterCloudProvider(ProviderName, func(config io.Reader) (cloudprovider.Interface, error) {
cfg, err := readConfig(config)
if err != nil {
return nil, err
}
return newOpenStack(cfg)
})
}
func (cfg Config) toAuthOptions() gophercloud.AuthOptions {
return gophercloud.AuthOptions{
IdentityEndpoint: cfg.Global.AuthURL,
Username: cfg.Global.Username,
UserID: cfg.Global.UserID,
Password: cfg.Global.Password,
TenantID: cfg.Global.TenantID,
TenantName: cfg.Global.TenantName,
DomainID: cfg.Global.DomainID,
DomainName: cfg.Global.DomainName,
// Persistent service, so we need to be able to renew tokens.
AllowReauth: true,
}
}
func (cfg Config) toAuth3Options() tokens3.AuthOptions {
return tokens3.AuthOptions{
IdentityEndpoint: cfg.Global.AuthURL,
Username: cfg.Global.Username,
UserID: cfg.Global.UserID,
Password: cfg.Global.Password,
DomainID: cfg.Global.DomainID,
DomainName: cfg.Global.DomainName,
AllowReauth: true,
}
}
// configFromEnv allows setting up credentials etc using the
// standard OS_* OpenStack client environment variables.
func configFromEnv() (cfg Config, ok bool) {
cfg.Global.AuthURL = os.Getenv("OS_AUTH_URL")
cfg.Global.Username = os.Getenv("OS_USERNAME")
cfg.Global.Password = os.Getenv("OS_PASSWORD")
cfg.Global.Region = os.Getenv("OS_REGION_NAME")
cfg.Global.UserID = os.Getenv("OS_USER_ID")
cfg.Global.TrustID = os.Getenv("OS_TRUST_ID")
cfg.Global.TenantID = os.Getenv("OS_TENANT_ID")
if cfg.Global.TenantID == "" {
cfg.Global.TenantID = os.Getenv("OS_PROJECT_ID")
}
cfg.Global.TenantName = os.Getenv("OS_TENANT_NAME")
if cfg.Global.TenantName == "" {
cfg.Global.TenantName = os.Getenv("OS_PROJECT_NAME")
}
cfg.Global.DomainID = os.Getenv("OS_DOMAIN_ID")
if cfg.Global.DomainID == "" {
cfg.Global.DomainID = os.Getenv("OS_USER_DOMAIN_ID")
}
cfg.Global.DomainName = os.Getenv("OS_DOMAIN_NAME")
if cfg.Global.DomainName == "" {
cfg.Global.DomainName = os.Getenv("OS_USER_DOMAIN_NAME")
}
ok = cfg.Global.AuthURL != "" &&
cfg.Global.Username != "" &&
cfg.Global.Password != "" &&
(cfg.Global.TenantID != "" || cfg.Global.TenantName != "" ||
cfg.Global.DomainID != "" || cfg.Global.DomainName != "" ||
cfg.Global.Region != "" || cfg.Global.UserID != "" ||
cfg.Global.TrustID != "")
cfg.Metadata.SearchOrder = fmt.Sprintf("%s,%s", configDriveID, metadataID)
cfg.BlockStorage.BSVersion = "auto"
return
}
func readConfig(config io.Reader) (Config, error) {
if config == nil {
return Config{}, fmt.Errorf("no OpenStack cloud provider config file given")
}
cfg, _ := configFromEnv()
// Set default values for config params
cfg.BlockStorage.BSVersion = "auto"
cfg.BlockStorage.TrustDevicePath = false
cfg.BlockStorage.IgnoreVolumeAZ = false
cfg.Metadata.SearchOrder = fmt.Sprintf("%s,%s", configDriveID, metadataID)
err := gcfg.ReadInto(&cfg, config)
return cfg, err
}
// caller is a tiny helper for conditional unwind logic
type caller bool
func newCaller() caller { return caller(true) }
func (c *caller) disarm() { *c = false }
func (c *caller) call(f func()) {
if *c {
f()
}
}
func readInstanceID(searchOrder string) (string, error) {
// Try to find instance ID on the local filesystem (created by cloud-init)
const instanceIDFile = "/var/lib/cloud/data/instance-id"
idBytes, err := ioutil.ReadFile(instanceIDFile)
if err == nil {
instanceID := string(idBytes)
instanceID = strings.TrimSpace(instanceID)
glog.V(3).Infof("Got instance id from %s: %s", instanceIDFile, instanceID)
if instanceID != "" {
return instanceID, nil
}
// Fall through to metadata server lookup
}
md, err := getMetadata(searchOrder)
if err != nil {
return "", err
}
return md.UUID, nil
}
// check opts for OpenStack
func checkOpenStackOpts(openstackOpts *OpenStack) error {
lbOpts := openstackOpts.lbOpts
// if need to create health monitor for Neutron LB,
// monitor-delay, monitor-timeout and monitor-max-retries should be set.
emptyDuration := MyDuration{}
if lbOpts.CreateMonitor {
if lbOpts.MonitorDelay == emptyDuration {
return fmt.Errorf("monitor-delay not set in cloud provider config")
}
if lbOpts.MonitorTimeout == emptyDuration {
return fmt.Errorf("monitor-timeout not set in cloud provider config")
}
if lbOpts.MonitorMaxRetries == uint(0) {
return fmt.Errorf("monitor-max-retries not set in cloud provider config")
}
}
return checkMetadataSearchOrder(openstackOpts.metadataOpts.SearchOrder)
}
func newOpenStack(cfg Config) (*OpenStack, error) {
provider, err := openstack.NewClient(cfg.Global.AuthURL)
if err != nil {
return nil, err
}
if cfg.Global.CAFile != "" {
roots, err := certutil.NewPool(cfg.Global.CAFile)
if err != nil {
return nil, err
}
config := &tls.Config{}
config.RootCAs = roots
provider.HTTPClient.Transport = netutil.SetOldTransportDefaults(&http.Transport{TLSClientConfig: config})
}
if cfg.Global.TrustID != "" {
opts := cfg.toAuth3Options()
authOptsExt := trusts.AuthOptsExt{
TrustID: cfg.Global.TrustID,
AuthOptionsBuilder: &opts,
}
err = openstack.AuthenticateV3(provider, authOptsExt, gophercloud.EndpointOpts{})
} else {
err = openstack.Authenticate(provider, cfg.toAuthOptions())
}
if err != nil {
return nil, err
}
emptyDuration := MyDuration{}
if cfg.Metadata.RequestTimeout == emptyDuration {
cfg.Metadata.RequestTimeout.Duration = time.Duration(defaultTimeOut)
}
provider.HTTPClient.Timeout = cfg.Metadata.RequestTimeout.Duration
os := OpenStack{
provider: provider,
region: cfg.Global.Region,
lbOpts: cfg.LoadBalancer,
bsOpts: cfg.BlockStorage,
routeOpts: cfg.Route,
metadataOpts: cfg.Metadata,
}
err = checkOpenStackOpts(&os)
if err != nil {
return nil, err
}
return &os, nil
}
// Initialize passes a Kubernetes clientBuilder interface to the cloud provider
func (os *OpenStack) Initialize(clientBuilder controller.ControllerClientBuilder) {}
// mapNodeNameToServerName maps a k8s NodeName to an OpenStack Server Name
// This is a simple string cast.
func mapNodeNameToServerName(nodeName types.NodeName) string {
return string(nodeName)
}
// GetNodeNameByID maps instanceid to types.NodeName
func (os *OpenStack) GetNodeNameByID(instanceID string) (types.NodeName, error) {
client, err := os.NewComputeV2()
var nodeName types.NodeName
if err != nil {
return nodeName, err
}
server, err := servers.Get(client, instanceID).Extract()
if err != nil {
return nodeName, err
}
nodeName = mapServerToNodeName(server)
return nodeName, nil
}
// mapServerToNodeName maps an OpenStack Server to a k8s NodeName
func mapServerToNodeName(server *servers.Server) types.NodeName {
// Node names are always lowercase, and (at least)
// routecontroller does case-sensitive string comparisons
// assuming this
return types.NodeName(strings.ToLower(server.Name))
}
func foreachServer(client *gophercloud.ServiceClient, opts servers.ListOptsBuilder, handler func(*servers.Server) (bool, error)) error {
pager := servers.List(client, opts)
err := pager.EachPage(func(page pagination.Page) (bool, error) {
s, err := servers.ExtractServers(page)
if err != nil {
return false, err
}
for _, server := range s {
ok, err := handler(&server)
if !ok || err != nil {
return false, err
}
}
return true, nil
})
return err
}
func getServerByName(client *gophercloud.ServiceClient, name types.NodeName, showOnlyActive bool) (*servers.Server, error) {
opts := servers.ListOpts{
Name: fmt.Sprintf("^%s$", regexp.QuoteMeta(mapNodeNameToServerName(name))),
}
if showOnlyActive {
opts.Status = "ACTIVE"
}
pager := servers.List(client, opts)
serverList := make([]servers.Server, 0, 1)
err := pager.EachPage(func(page pagination.Page) (bool, error) {
s, err := servers.ExtractServers(page)
if err != nil {
return false, err
}
serverList = append(serverList, s...)
if len(serverList) > 1 {
return false, ErrMultipleResults
}
return true, nil
})
if err != nil {
return nil, err
}
if len(serverList) == 0 {
return nil, ErrNotFound
}
return &serverList[0], nil
}
func nodeAddresses(srv *servers.Server) ([]v1.NodeAddress, error) {
addrs := []v1.NodeAddress{}
type Address struct {
IPType string `mapstructure:"OS-EXT-IPS:type"`
Addr string
}
var addresses map[string][]Address
err := mapstructure.Decode(srv.Addresses, &addresses)
if err != nil {
return nil, err
}
for network, addrList := range addresses {
for _, props := range addrList {
var addressType v1.NodeAddressType
if props.IPType == "floating" || network == "public" {
addressType = v1.NodeExternalIP
} else {
addressType = v1.NodeInternalIP
}
v1helper.AddToNodeAddresses(&addrs,
v1.NodeAddress{
Type: addressType,
Address: props.Addr,
},
)
}
}
// AccessIPs are usually duplicates of "public" addresses.
if srv.AccessIPv4 != "" {
v1helper.AddToNodeAddresses(&addrs,
v1.NodeAddress{
Type: v1.NodeExternalIP,
Address: srv.AccessIPv4,
},
)
}
if srv.AccessIPv6 != "" {
v1helper.AddToNodeAddresses(&addrs,
v1.NodeAddress{
Type: v1.NodeExternalIP,
Address: srv.AccessIPv6,
},
)
}
return addrs, nil
}
func
|
(client *gophercloud.ServiceClient, name types.NodeName) ([]v1.NodeAddress, error) {
srv, err := getServerByName(client, name, true)
if err != nil {
return nil, err
}
return nodeAddresses(srv)
}
func getAddressByName(client *gophercloud.ServiceClient, name types.NodeName) (string, error) {
addrs, err := getAddressesByName(client, name)
if err != nil {
return "", err
} else if len(addrs) == 0 {
return "", ErrNoAddressFound
}
for _, addr := range addrs {
if addr.Type == v1.NodeInternalIP {
return addr.Address, nil
}
}
return addrs[0].Address, nil
}
// getAttachedInterfacesByID returns the node interfaces of the specified instance.
func getAttachedInterfacesByID(client *gophercloud.ServiceClient, serviceID string) ([]attachinterfaces.Interface, error) {
var interfaces []attachinterfaces.Interface
pager := attachinterfaces.List(client, serviceID)
err := pager.EachPage(func(page pagination.Page) (bool, error) {
s, err := attachinterfaces.ExtractInterfaces(page)
if err != nil {
return false, err
}
interfaces = append(interfaces, s...)
return true, nil
})
if err != nil {
return interfaces, err
}
return interfaces, nil
}
// Clusters is a no-op
func (os *OpenStack) Clusters() (cloudprovider.Clusters, bool) {
return nil, false
}
// ProviderName returns the cloud provider ID.
func (os *OpenStack) ProviderName() string {
return ProviderName
}
// ScrubDNS filters DNS settings for pods.
func (os *OpenStack) ScrubDNS(nameServers, searches []string) ([]string, []string) {
return nameServers, searches
}
// HasClusterID returns true if the cluster has a clusterID
func (os *OpenStack) HasClusterID() bool {
return true
}
// LoadBalancer initializes a LbaasV2 object
func (os *OpenStack) LoadBalancer() (cloudprovider.LoadBalancer, bool) {
glog.V(4).Info("openstack.LoadBalancer() called")
network, err := os.NewNetworkV2()
if err != nil {
return nil, false
}
compute, err := os.NewComputeV2()
if err != nil {
return nil, false
}
lb, err := os.NewLoadBalancerV2()
if err != nil {
return nil, false
}
// LBaaS v1 is deprecated in the OpenStack Liberty release.
// Currently kubernetes OpenStack cloud provider just support LBaaS v2.
lbVersion := os.lbOpts.LBVersion
if lbVersion != "" && lbVersion != "v2" {
glog.Warningf("Config error: currently only support LBaaS v2, unrecognised lb-version \"%v\"", lbVersion)
return nil, false
}
glog.V(1).Info("Claiming to support LoadBalancer")
return &LbaasV2{LoadBalancer{network, compute, lb, os.lbOpts}}, true
}
func isNotFound(err error) bool {
e, ok := err.(*gophercloud.ErrUnexpectedResponseCode)
return ok && e.Actual == http.StatusNotFound
}
// Zones indicates that we support zones
func (os *OpenStack) Zones() (cloudprovider.Zones, bool) {
glog.V(1).Info("Claiming to support Zones")
return os, true
}
// GetZone returns the current zone
func (os *OpenStack) GetZone() (cloudprovider.Zone, error) {
md, err := getMetadata(os.metadataOpts.SearchOrder)
if err != nil {
return cloudprovider.Zone{}, err
}
zone := cloudprovider.Zone{
FailureDomain: md.AvailabilityZone,
Region: os.region,
}
glog.V(4).Infof("Current zone is %v", zone)
return zone, nil
}
// GetZoneByProviderID implements Zones.GetZoneByProviderID
// This is particularly useful in external cloud providers where the kubelet
// does not initialize node data.
func (os *OpenStack) GetZoneByProviderID(providerID string) (cloudprovider.Zone, error) {
instanceID, err := instanceIDFromProviderID(providerID)
if err != nil {
return cloudprovider.Zone{}, err
}
compute, err := os.NewComputeV2()
if err != nil {
return cloudprovider.Zone{}, err
}
srv, err := servers.Get(compute, instanceID).Extract()
if err != nil {
return cloudprovider.Zone{}, err
}
zone := cloudprovider.Zone{
FailureDomain: srv.Metadata[availabilityZone],
Region: os.region,
}
glog.V(4).Infof("The instance %s in zone %v", srv.Name, zone)
return zone, nil
}
// GetZoneByNodeName implements Zones.GetZoneByNodeName
// This is particularly useful in external cloud providers where the kubelet
// does not initialize node data.
func (os *OpenStack) GetZoneByNodeName(nodeName types.NodeName) (cloudprovider.Zone, error) {
compute, err := os.NewComputeV2()
if err != nil {
return cloudprovider.Zone{}, err
}
srv, err := getServerByName(compute, nodeName, true)
if err != nil {
if err == ErrNotFound {
return cloudprovider.Zone{}, cloudprovider.InstanceNotFound
}
return cloudprovider.Zone{}, err
}
zone := cloudprovider.Zone{
FailureDomain: srv.Metadata[availabilityZone],
Region: os.region,
}
glog.V(4).Infof("The instance %s in zone %v", srv.Name, zone)
return zone, nil
}
// Routes initializes routes support
func (os *OpenStack) Routes() (cloudprovider.Routes, bool) {
glog.V(4).Info("openstack.Routes() called")
network, err := os.NewNetworkV2()
if err != nil {
return nil, false
}
netExts, err := networkExtensions(network)
if err != nil {
glog.Warningf("Failed to list neutron extensions: %v", err)
return nil, false
}
if !netExts["extraroute"] {
glog.V(3).Info("Neutron extraroute extension not found, required for Routes support")
return nil, false
}
compute, err := os.NewComputeV2()
if err != nil {
return nil, false
}
r, err := NewRoutes(compute, network, os.routeOpts)
if err != nil {
glog.Warningf("Error initialising Routes support: %v", err)
return nil, false
}
glog.V(1).Info("Claiming to support Routes")
return r, true
}
func (os *OpenStack) volumeService(forceVersion string) (volumeService, error) {
bsVersion := ""
if forceVersion == "" {
bsVersion = os.bsOpts.BSVersion
} else {
bsVersion = forceVersion
}
switch bsVersion {
case "v1":
sClient, err := os.NewBlockStorageV1()
if err != nil {
return nil, err
}
glog.V(3).Info("Using Blockstorage API V1")
return &VolumesV1{sClient, os.bsOpts}, nil
case "v2":
sClient, err := os.NewBlockStorageV2()
if err != nil {
return nil, err
}
glog.V(3).Info("Using Blockstorage API V2")
return &VolumesV2{sClient, os.bsOpts}, nil
case "v3":
sClient, err := os.NewBlockStorageV3()
if err != nil {
return nil, err
}
glog.V(3).Info("Using Blockstorage API V3")
return &VolumesV3{sClient, os.bsOpts}, nil
case "auto":
// Currently kubernetes support Cinder v1 / Cinder v2 / Cinder v3.
// Choose Cinder v3 firstly, if kubernetes can't initialize cinder v3 client, try to initialize cinder v2 client.
// If kubernetes can't initialize cinder v2 client, try to initialize cinder v1 client.
// Return appropriate message when kubernetes can't initialize them.
if sClient, err := os.NewBlockStorageV3(); err == nil {
glog.V(3).Info("Using Blockstorage API V3")
return &VolumesV3{sClient, os.bsOpts}, nil
}
if sClient, err := os.NewBlockStorageV2(); err == nil {
glog.V(3).Info("Using Blockstorage API V2")
return &VolumesV2{sClient, os.bsOpts}, nil
}
if sClient, err := os.NewBlockStorageV1(); err == nil {
glog.V(3).Info("Using Blockstorage API V1")
return &VolumesV1{sClient, os.bsOpts}, nil
}
errTxt := "BlockStorage API version autodetection failed. " +
"Please set it explicitly in cloud.conf in section [BlockStorage] with key `bs-version`"
return nil, errors.New(errTxt)
default:
errTxt := fmt.Sprintf("Config error: unrecognised bs-version \"%v\"", os.bsOpts.BSVersion)
return nil, errors.New(errTxt)
}
}
func checkMetadataSearchOrder(order string) error {
if order == "" {
return errors.New("invalid value in section [Metadata] with key `search-order`. Value cannot be empty")
}
elements := strings.Split(order, ",")
if len(elements) > 2 {
return errors.New("invalid value in section [Metadata] with key `search-order`. Value cannot contain more than 2 elements")
}
for _, id := range elements {
id = strings.TrimSpace(id)
switch id {
case configDriveID:
case metadataID:
default:
return fmt.Errorf("invalid element %q found in section [Metadata] with key `search-order`."+
"Supported elements include %q and %q", id, configDriveID, metadataID)
}
}
return nil
}
|
getAddressesByName
|
help.py
|
"""
Provide help message for command line interface commands.
"""
PROVIDER_NAME_HELP = 'A provider of hosting for software development and version control name.'
ORGANIZATION_NAME_HELP = "The provider's organization name."
REPOSITORY_NAME_HELP = "The provider's repository name."
|
BRANCH = 'A branch.'
BASE_BRANCH = 'A branch to compare a project version with. Usually, a default branch.'
HEAD_BRANCH = 'A branch to get its project version for comparison. Usually, a feature branch.'
PROJECT_VERSION = 'A project version.'
|
|
strict_mock.py
|
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import copy
import dis
import inspect
import os.path
from types import FrameType
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
List,
Optional,
Type,
Union,
get_type_hints,
)
import testslide.lib
import testslide.mock_callable
if TYPE_CHECKING:
# Hack to enable typing information for mypy
from testslide.mock_callable import _CallableMock, _YieldValuesRunner # noqa: F401
class UndefinedAttribute(BaseException):
"""
Tentative access of an attribute from a StrictMock that is not defined yet.
Inherits from BaseException to avoid being caught by tested code.
"""
def __init__(
self, strict_mock: "StrictMock", name: str, extra_msg: Optional[str] = None
) -> None:
super().__init__(strict_mock, name)
self.strict_mock = strict_mock
self.name = name
self.extra_msg = extra_msg
def __str__(self) -> str:
message = (
f"'{self.name}' is not set.\n"
f"{repr(self.strict_mock)} must have a value set for this attribute "
"if it is going to be accessed."
)
if self.extra_msg is not None:
message += f"\n{self.extra_msg}"
return message
class NonExistentAttribute(BaseException):
"""
Tentative of setting of an attribute from a StrictMock that is not present
at the template class.
Inherits from BaseException to avoid being caught by tested code.
"""
def __init__(self, strict_mock: "StrictMock", name: str) -> None:
super().__init__(strict_mock, name)
self.strict_mock = strict_mock
self.name = name
def __str__(self) -> str:
return (
f"'{self.name}' is not part of the API.\n"
f"{self.strict_mock} template class API does not have this "
"attribute so the mock can not have it as well.\n"
"If you are inheriting StrictMock, you can define private "
"attributes, that will not interfere with the API, by prefixing "
"them with '__' (and at most one '_' suffix) "
" (https://docs.python.org/3/tutorial/classes.html#tut-private).\n"
"See also: 'runtime_attrs' at StrictMock.__init__."
)
class NonCallableValue(BaseException):
"""
Raised when trying to set a non callable value to a callable attribute of
a StrictMock instance.
"""
def __init__(self, strict_mock: "StrictMock", name: str) -> None:
super().__init__(strict_mock, name)
self.strict_mock = strict_mock
self.name = name
def __str__(self) -> str:
return (
f"'{self.name}' can not be set with a non-callable value.\n"
f"{self.strict_mock} template class requires this attribute to "
"be callable."
)
class NonAwaitableReturn(BaseException):
"""
Raised when a coroutine method at a StrictMock is assigned a not coroutine
callable function.
"""
def __init__(self, strict_mock: "StrictMock", name: str) -> None:
super().__init__(strict_mock, name)
self.strict_mock = strict_mock
self.name = name
def __str__(self) -> str:
return (
f"'{self.name}' can not be set with a callable that does not "
"return an awaitable.\n"
f"{self.strict_mock} template class requires this attribute to "
"be a callable that returns an awaitable (eg: a 'async def' "
"function)."
)
class UnsupportedMagic(BaseException):
"""
Raised when trying to set an unsupported magic attribute to a StrictMock
instance.
"""
def __init__(self, strict_mock: "StrictMock", name: str) -> None:
super().__init__(strict_mock, name)
self.strict_mock = strict_mock
self.name = name
def __str__(self) -> str:
return f"setting '{self.name}' is not supported."
class _DefaultMagic:
CONTEXT_MANAGER_METHODS = ["__enter__", "__exit__", "__aenter__", "__aexit__"]
def __init__(self, strict_mock: "StrictMock", name: str):
self.strict_mock = strict_mock
self.name = name
def __call__(self, *args: Any, **kwargs: Any) -> None:
message = None
if self.name in self.CONTEXT_MANAGER_METHODS:
message = (
"Tip: most context managers can be automatically configured "
"with 'default_context_manager=True'."
)
raise UndefinedAttribute(self.strict_mock, self.name, message)
def
|
(self) -> "_DefaultMagic":
return type(self)(strict_mock=self.strict_mock, name=self.name)
def __deepcopy__(self, memo: Optional[Dict[Any, Any]] = None) -> "_DefaultMagic":
if memo is None:
memo = {}
self_copy = type(self)(strict_mock=self.strict_mock, name=self.name)
memo[id(self)] = self_copy
return self_copy
class _MethodProxy:
"""
When setting callable attributes, the new value is wrapped by another
function that does signature and async validations. We then need this proxy
around it, so that when the attribute is called, the mock value is called
(the wrapper function which then calls the new value) but all attribute
access is forwarded to the new value.
"""
def __init__(self, value: Any, callable_value: Optional[Callable] = None) -> None:
self.__dict__["_value"] = value
self.__dict__["_callable_value"] = callable_value or value
def __get__(
self, instance: "StrictMock", owner: Optional[Type["StrictMock"]] = None
) -> Union[object, Callable]:
if self.__dict__["_value"] is self.__dict__["_callable_value"]:
return self.__dict__["_callable_value"]
else:
return self
def __getattr__(self, name: str) -> str:
return getattr(self.__dict__["_value"], name)
def __setattr__(self, name: str, value: str) -> None:
return setattr(self.__dict__["_value"], name, value)
def __delattr__(self, name: str) -> None:
return delattr(self.__dict__["_value"], name)
def __call__(self, *args: Any, **kwargs: Any) -> Optional[Any]:
return self.__dict__["_callable_value"](*args, **kwargs)
def __copy__(self) -> "_MethodProxy":
return type(self)(
callable_value=self.__dict__["_callable_value"],
value=self.__dict__["_value"],
)
def __deepcopy__(self, memo: Optional[Dict[Any, Any]] = None) -> "_MethodProxy":
if memo is None:
memo = {}
self_copy = type(self)(
callable_value=copy.deepcopy(self.__dict__["_callable_value"]),
value=copy.deepcopy(self.__dict__["_value"]),
)
memo[id(self)] = self_copy
return self_copy
def __repr__(self) -> str:
# Override repr to have a representation that provides information
# about the wrapped method
return repr(self.__dict__["_value"])
class StrictMock:
"""
Mock object that won't allow any attribute access or method call, unless its
behavior has been explicitly defined. This is meant to be a safer
alternative to Python's standard Mock object, that will always return
another mock when referred by default.
StrictMock is "safe by default", meaning that it will never misbehave by
lack of configuration. It will raise in the following situations:
- Get/Set attribute that's not part of the specification (template or
runtime_attrs).
- Get attribute that is part of the specification, but has not yet been
defined.
- Call a method with different signature from the template.
When appropriate, raised exceptions inherits from BaseException, in order to
let exceptions raise the test, outside tested code, so we can get a clear
signal of what is happening: either the mock is missing a required behavior
or the tested code is misbehaving.
"""
TRIM_PATH_PREFIX = ""
# All of these magic should be OK to be set at the mock and they are
# expected to work as they should. If implemented by the template class,
# they will have default values assigned to them, that raise
# UndefinedAttribute until configured.
__SETTABLE_MAGICS = [
"__abs__",
"__add__",
"__aenter__",
"__aexit__",
"__aiter__",
"__and__",
"__anext__",
"__await__",
"__bool__",
"__bytes__",
"__call__",
"__ceil__",
"__complex__",
"__contains__",
"__delete__",
"__delitem__",
"__divmod__",
"__enter__",
"__enter__",
"__eq__",
"__exit__",
"__exit__",
"__float__",
"__floor__",
"__floordiv__",
"__format__",
"__ge__",
"__get__",
"__getformat__",
"__getinitargs__",
"__getitem__",
"__getnewargs__",
"__getnewargs_ex__",
"__getstate__",
"__gt__",
"__iadd__",
"__iand__",
"__ifloordiv__",
"__ilshift__",
"__imatmul__",
"__imod__",
"__imul__",
"__index__",
"__instancecheck__",
"__int__",
"__invert__",
"__ior__",
"__ipow__",
"__irshift__",
"__isub__",
"__iter__",
"__iter__",
"__iter__",
"__itruediv__",
"__ixor__",
"__le__",
"__len__",
"__length_hint__",
"__lshift__",
"__lt__",
"__matmul__",
"__missing__",
"__mod__",
"__mul__",
"__name__",
"__ne__",
"__neg__",
"__next__",
"__or__",
"__pos__",
"__pow__",
"__qualname__",
"__radd__",
"__rand__",
"__rdivmod__",
"__reduce__",
"__reduce_ex__",
"__repr__",
"__reversed__",
"__rfloordiv__",
"__rlshift__",
"__rmatmul__",
"__rmod__",
"__rmul__",
"__ror__",
"__round__",
"__rpow__",
"__rrshift__",
"__rshift__",
"__rsub__",
"__rtruediv__",
"__rxor__",
"__set__",
"__set_name__",
"__setformat__",
"__setitem__",
"__setstate__",
"__sizeof__",
"__str__",
"__sub__",
"__subclasscheck__",
"__truediv__",
"__trunc__",
"__xor__",
]
# These magics either won't work or makes no sense to be set for mock after
# an instance of a class. Trying to set them will raise UnsupportedMagic.
__UNSETTABLE_MAGICS = [
"__bases__",
"__class__",
"__class_getitem__",
"__copy__",
"__deepcopy__",
"__del__",
"__delattr__",
"__dict__",
"__dir__",
"__getattr__",
"__getattribute__",
"__hash__",
"__init__",
"__init_subclass__",
"__mro__",
"__new__",
"__setattr__",
"__slots__",
"__subclasses__",
]
def __new__(
cls,
template: Optional[type] = None,
runtime_attrs: Optional[List[Any]] = None,
name: Optional[str] = None,
default_context_manager: bool = False,
type_validation: bool = True,
attributes_to_skip_type_validation: List[str] = [],
) -> "StrictMock":
"""
For every new instance of StrictMock we dynamically create a subclass of
StrictMock and return an instance of it. This allows us to use this new
subclass dictionary for all attributes, including magic ones, that must
be defined at the class to work.
"""
name = f"{template.__name__}{cls.__name__}" if template else cls.__name__
strict_mock_subclass = type(name, (cls,), {})
return object.__new__(strict_mock_subclass)
def __setup_magic_methods(self) -> None:
"""
Populate all template's magic methods with expected default behavior.
This is important as things such as bool() depend on they existing
on the object's class __dict__.
https://github.com/facebook/TestSlide/issues/23
"""
if not self._template:
return
implemented_magic_methods = []
for klass in type(self).mro():
if klass is object:
continue
for name in klass.__dict__:
if name.startswith("__") and name.endswith("__"):
implemented_magic_methods.append(name)
for klass in self._template.mro():
if klass is object:
continue
for name in klass.__dict__:
if name in type(self).__dict__:
continue
if name == "__hash__":
if klass.__dict__["__hash__"] is None:
setattr(self, name, None)
else:
setattr(self, name, lambda: id(self))
continue
if (
callable(klass.__dict__[name])
and name in self.__SETTABLE_MAGICS
and name not in self.__UNSETTABLE_MAGICS
and name not in implemented_magic_methods
):
setattr(self, name, _DefaultMagic(self, name))
def __setup_default_context_manager(self, default_context_manager: bool) -> None:
if self._template and default_context_manager:
if hasattr(self._template, "__enter__") and hasattr(
self._template, "__exit__"
):
self.__enter__ = lambda: self
self.__exit__ = lambda exc_type, exc_value, traceback: None
if hasattr(self._template, "__aenter__") and hasattr(
self._template, "__aexit__"
):
async def aenter():
return self
async def aexit(exc_type, exc_value, traceback):
pass
self.__aenter__ = aenter
self.__aexit__ = aexit
def __get_caller_frame(self, depth: int) -> FrameType:
# Adding extra 3 to account for the stack:
# __get_caller_frame
# __get_caller
# __init__
depth += 3
current_frame = inspect.currentframe()
while current_frame:
depth -= 1
if not depth:
break
current_frame = current_frame.f_back
return current_frame # type: ignore
def __get_caller(self, depth: int) -> Optional[str]:
# Doing inspect.stack will retrieve the whole stack, including context
# and that is really slow, this only retrieves the minimum, and does
# not read the file contents.
caller_frame = self.__get_caller_frame(depth)
# loading the context ends up reading files from disk and that might block
# the event loop, so we don't do it.
frameinfo = inspect.getframeinfo(caller_frame, context=0)
filename = frameinfo.filename
lineno = frameinfo.lineno
if self.TRIM_PATH_PREFIX:
split = filename.split(self.TRIM_PATH_PREFIX)
if len(split) == 2 and not split[0]:
filename = split[1]
if os.path.exists(filename):
return "{}:{}".format(filename, lineno)
else:
return None
def __setup_subclass(self):
"""
When StrictMock is subclassed, any attributes defined at the subclass
will override any of StrictMock's validations. In order to overcome
this, for attributes that makes sense, we set them at StrictMock's
dynamically created subclass from __new__ using __setattr__, so that
all validations work.
"""
if type(self).mro()[1] == StrictMock:
return
for klass in type(self).mro()[1:]:
if klass == StrictMock:
break
for name in klass.__dict__.keys():
if name in [
"__doc__",
"__init__",
"__module__",
]:
continue
# https://docs.python.org/3/tutorial/classes.html#tut-private
if name.startswith(f"_{type(self).__name__}__") and not name.endswith(
"__"
):
continue
if name == "__hash__" and klass.__dict__["__hash__"] is None:
continue
StrictMock.__setattr__(self, name, getattr(self, name))
def __init__(
self,
template: Optional[type] = None,
runtime_attrs: Optional[List[Any]] = None,
name: Optional[str] = None,
default_context_manager: bool = False,
type_validation: bool = True,
attributes_to_skip_type_validation: List[str] = [],
) -> None:
"""
template: Template class to be used as a template for the mock.
runtime_attrs: Often attributes are created within an instance's
lifecycle, typically from __init__(). To allow mocking such attributes,
specify their names here.
name: an optional name for this mock instance.
default_context_manager: If the template class is a context manager,
setup a mock for __enter__/__aenter__ that yields itself and an empty function
for __exit__/__aexit__.
type_validation: validate callable attributes calls against the
template's method signature and use type hinting information from template
to validate that mock attribute types match them. Type validation also
happens forcallable attributes (instance/static/class methods) calls.
_attributes_to_skip_type_validation: do not validate type for these attributes
of the strictmock instance.
"""
if template is not None and not inspect.isclass(template):
raise ValueError("Template must be a class.")
self.__dict__["_template"] = template
self.__dict__["_runtime_attrs"] = runtime_attrs or []
self.__dict__["_name"] = name
self.__dict__["_type_validation"] = type_validation
self.__dict__["__caller"] = self.__get_caller(1)
self.__dict__[
"_attributes_to_skip_type_validation"
] = attributes_to_skip_type_validation
caller_frame = inspect.currentframe().f_back # type: ignore
# loading the context ends up reading files from disk and that might block
# the event loop, so we don't do it.
caller_frame_info = inspect.getframeinfo(caller_frame, context=0) # type: ignore
self.__dict__["_caller_frame_info"] = caller_frame_info
self.__setup_magic_methods()
self.__setup_default_context_manager(default_context_manager)
self.__setup_subclass()
@property # type: ignore
def __class__(self) -> type:
return self._template if self._template is not None else type(self)
@property
def _template(self) -> None:
import testslide.mock_constructor # Avoid cyclic dependencies
# If the template class was mocked with mock_constructor(), this will
# return the mocked subclass, which contains all attributes we need for
# introspection.
return testslide.mock_constructor._get_class_or_mock(self.__dict__["_template"])
# FIXME change to __runtime_attrs
@property
def _runtime_attrs(self) -> Optional[List[Any]]:
return self.__dict__["_runtime_attrs"]
def __template_has_attr(self, name: str) -> bool:
def get_class_init(klass: type) -> Callable:
import testslide.mock_constructor # Avoid cyclic dependencies
if not testslide.mock_constructor._is_mocked_class(klass):
return klass.__init__ # type: ignore
# If klass is the mocked subclass, pull the original version of
# __init__ so we can introspect into its implementation (and
# not the __init__ wrapper at the mocked class).
mocked_class = klass
original_class = mocked_class.mro()[1]
return testslide.mock_constructor._get_original_init(
original_class, instance=None, owner=mocked_class
)
def is_runtime_attr() -> bool:
if self._template:
for klass in self._template.mro():
template_init = get_class_init(klass)
if not inspect.isfunction(template_init):
continue
for instruction in dis.get_instructions(template_init):
if (
instruction.opname == "STORE_ATTR"
and name == instruction.argval
):
return True
return False
return (
hasattr(self._template, name)
or name in self._runtime_attrs # type: ignore
or name in getattr(self._template, "__slots__", [])
or is_runtime_attr()
)
@staticmethod
def __is_magic_method(name: str) -> bool:
return name.startswith("__") and name.endswith("__")
def __validate_attribute_type(self, name: str, value: Any) -> None:
if (
not self.__dict__["_type_validation"]
or name in self.__dict__["_attributes_to_skip_type_validation"]
):
return
if self._template is not None:
try:
annotations = get_type_hints(self._template)
except Exception:
# Some modules can throw KeyError : https://bugs.python.org/issue41515
annotations = {}
if name in annotations:
testslide.lib._validate_argument_type(annotations[name], name, value)
def __validate_and_wrap_mock_value(self, name: str, value: Any) -> Any:
if self._template:
if not self.__template_has_attr(name):
if not (
name.startswith(f"_{type(self).__name__}__")
and not name.endswith("__")
):
raise NonExistentAttribute(self, name)
self.__validate_attribute_type(name, value)
if hasattr(self._template, name):
template_value = getattr(self._template, name)
if callable(template_value):
if not callable(value):
raise NonCallableValue(self, name)
if self.__dict__["_type_validation"]:
signature_validation_wrapper = (
testslide.lib._wrap_signature_and_type_validation(
value,
self._template,
name,
self.__dict__["_type_validation"],
)
)
if inspect.iscoroutinefunction(template_value):
async def awaitable_return_validation_wrapper(
*args, **kwargs
):
result_awaitable = signature_validation_wrapper(
*args, **kwargs
)
if not inspect.isawaitable(result_awaitable):
raise NonAwaitableReturn(self, name)
return_value = await result_awaitable
if not testslide.lib._is_wrapped_for_signature_and_type_validation(
# The original value was already wrapped for type
# validation. Skipping additional validation to
# allow, for example, mock_callable to disable
# validation for a very specific mock call rather
# for the whole StrictMock instance
value
) and not isinstance(
# If the return value is a _BaseRunner then type
# validation, if needed, has already been performed
return_value,
testslide.mock_callable._BaseRunner,
):
testslide.lib._validate_return_type(
template_value,
return_value,
self.__dict__["_caller_frame_info"],
)
return return_value
callable_value = awaitable_return_validation_wrapper
else:
def return_validation_wrapper(*args, **kwargs):
return_value = signature_validation_wrapper(
*args, **kwargs
)
if not testslide.lib._is_wrapped_for_signature_and_type_validation(
# The original value was already wrapped for type
# validation. Skipping additional validation to
# allow, for example, mock_callable to disable
# validation for a very specific mock call rather
# for the whole StrictMock instance
value
) and not isinstance(
# If the return value is a _BaseRunner then type
# validation, if needed, has already been performed
return_value,
testslide.mock_callable._BaseRunner,
):
testslide.lib._validate_return_type(
template_value,
return_value,
self.__dict__["_caller_frame_info"],
)
return return_value
callable_value = return_validation_wrapper
else:
callable_value = None
return _MethodProxy(value=value, callable_value=callable_value)
else:
if callable(value):
# We don't really need the proxy here, but it serves the
# double purpose of swallowing self / cls when needed.
return _MethodProxy(value=value)
else:
if callable(value):
# We don't really need the proxy here, but it serves the
# double purpose of swallowing self / cls when needed.
return _MethodProxy(value=value)
return value
def __setattr__(self, name: str, value: Any) -> None:
if self.__is_magic_method(name):
# ...check whether we're allowed to mock...
if (
name in self.__UNSETTABLE_MAGICS
or (name in StrictMock.__dict__ and name not in self.__SETTABLE_MAGICS)
) and name != "__hash__":
raise UnsupportedMagic(self, name)
# ...or if it is something unsupported.
if name not in self.__SETTABLE_MAGICS and name != "__hash__":
raise NotImplementedError(
f"StrictMock does not implement support for {name}"
)
if name == "__hash__" and name in type(self).__dict__:
raise UnsupportedMagic(self, name)
mock_value = self.__validate_and_wrap_mock_value(name, value)
setattr(type(self), name, mock_value)
def __getattr__(self, name: str) -> Any:
if self._template and self.__template_has_attr(name):
raise UndefinedAttribute(self, name)
else:
raise AttributeError(f"'{name}' was not set for {repr(self)}.")
def __delattr__(self, name: str) -> None:
if name in type(self).__dict__:
delattr(type(self), name)
def __repr__(self) -> str:
template_str = (
" template={}.{}".format(self._template.__module__, self._template.__name__) # type: ignore
if self._template
else ""
)
if self.__dict__["_name"]:
name_str = " name={}".format(repr(self.__dict__["_name"]))
else:
name_str = ""
if self.__dict__["__caller"]:
caller_str = " {}".format(self.__dict__["__caller"])
else:
caller_str = ""
return "<StrictMock 0x{:02X}{name}{template}{caller}>".format(
id(self), name=name_str, template=template_str, caller=caller_str
)
def __str__(self) -> str:
return self.__repr__()
def __get_copy(self) -> "StrictMock":
self_copy = StrictMock(
template=self._template,
runtime_attrs=self._runtime_attrs,
name=self._name,
type_validation=self._type_validation,
attributes_to_skip_type_validation=self._attributes_to_skip_type_validation,
)
self_copy.__dict__["__caller"] = self.__get_caller(2)
return self_copy
def __get_copyable_attrs(self, self_copy: "StrictMock") -> List[str]:
return [
name
for name in type(self).__dict__
if name not in self_copy.__dict__
and (
not name.startswith("__")
or not name.endswith("__")
or name in self.__SETTABLE_MAGICS
)
]
def __copy__(self) -> "StrictMock":
self_copy = self.__get_copy()
for name in self.__get_copyable_attrs(self_copy):
setattr(type(self_copy), name, type(self).__dict__[name])
return self_copy
def __deepcopy__(self, memo: Optional[Dict[Any, Any]] = None) -> "StrictMock":
if memo is None:
memo = {}
self_copy = self.__get_copy()
memo[id(self)] = self_copy
for name in self.__get_copyable_attrs(self_copy):
value = copy.deepcopy(type(self).__dict__[name], memo)
setattr(type(self_copy), name, value)
return self_copy
def _extract_StrictMock_template(mock_obj: StrictMock) -> Optional[Any]:
if "_template" in mock_obj.__dict__ and mock_obj._template is not None:
return mock_obj._template
return None
testslide.lib.MOCK_TEMPLATE_EXTRACTORS[StrictMock] = _extract_StrictMock_template # type: ignore
|
__copy__
|
AlipayOpenPublicPartnerMenuOperateModel.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayOpenPublicPartnerMenuOperateModel(object):
def __init__(self):
self._action_param = None
self._action_type = None
self._agreement_id = None
self._public_id = None
self._third_account_id = None
self._user_id = None
@property
def action_param(self):
return self._action_param
@action_param.setter
def action_param(self, value):
self._action_param = value
@property
def action_type(self):
return self._action_type
@action_type.setter
def action_type(self, value):
self._action_type = value
@property
def agreement_id(self):
return self._agreement_id
@agreement_id.setter
def agreement_id(self, value):
self._agreement_id = value
@property
def public_id(self):
return self._public_id
@public_id.setter
def public_id(self, value):
self._public_id = value
@property
def third_account_id(self):
return self._third_account_id
@third_account_id.setter
def third_account_id(self, value):
self._third_account_id = value
@property
def user_id(self):
return self._user_id
@user_id.setter
def user_id(self, value):
self._user_id = value
def to_alipay_dict(self):
params = dict()
if self.action_param:
|
if self.action_type:
if hasattr(self.action_type, 'to_alipay_dict'):
params['action_type'] = self.action_type.to_alipay_dict()
else:
params['action_type'] = self.action_type
if self.agreement_id:
if hasattr(self.agreement_id, 'to_alipay_dict'):
params['agreement_id'] = self.agreement_id.to_alipay_dict()
else:
params['agreement_id'] = self.agreement_id
if self.public_id:
if hasattr(self.public_id, 'to_alipay_dict'):
params['public_id'] = self.public_id.to_alipay_dict()
else:
params['public_id'] = self.public_id
if self.third_account_id:
if hasattr(self.third_account_id, 'to_alipay_dict'):
params['third_account_id'] = self.third_account_id.to_alipay_dict()
else:
params['third_account_id'] = self.third_account_id
if self.user_id:
if hasattr(self.user_id, 'to_alipay_dict'):
params['user_id'] = self.user_id.to_alipay_dict()
else:
params['user_id'] = self.user_id
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = AlipayOpenPublicPartnerMenuOperateModel()
if 'action_param' in d:
o.action_param = d['action_param']
if 'action_type' in d:
o.action_type = d['action_type']
if 'agreement_id' in d:
o.agreement_id = d['agreement_id']
if 'public_id' in d:
o.public_id = d['public_id']
if 'third_account_id' in d:
o.third_account_id = d['third_account_id']
if 'user_id' in d:
o.user_id = d['user_id']
return o
|
if hasattr(self.action_param, 'to_alipay_dict'):
params['action_param'] = self.action_param.to_alipay_dict()
else:
params['action_param'] = self.action_param
|
0098_add_task_assignee_ids.py
|
# Generated by Django 3.2 on 2021-04-20 21:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("api", "0097_githubrepository_permissions"),
]
operations = [
migrations.AddField(
model_name="task",
name="assigned_dev_id",
field=models.CharField(blank=True, max_length=50, null=True),
),
|
),
]
|
migrations.AddField(
model_name="task",
name="assigned_qa_id",
field=models.CharField(blank=True, max_length=50, null=True),
|
resx_net.bzl
|
load(
"@rules_mono//dotnet/private:providers.bzl",
"DotnetLibrary",
)
def _make_runner_arglist(dotnet, source, output):
args = dotnet.actions.args()
args.add("/useSourcePath")
if type(source) == "Target":
args.add_all(source.files)
else:
args.add(source)
args.add(output)
return args
def emit_resx_net(
dotnet,
name = "",
src = None,
identifier = None,
out = None,
customresgen = None):
if name == "" and out == None:
fail("either name or out must be set")
if not out:
result = dotnet.declare_file(dotnet, path = name + ".resources")
else:
result = dotnet.declare_file(dotnet, path = out)
args = _make_runner_arglist(dotnet, src, result)
inputs = src.files if type(src) == "Target" else [src]
dotnet.actions.run(
inputs = inputs,
outputs = [result],
executable = dotnet.resgen,
arguments = [args],
mnemonic = "NetResxCompile",
progress_message = (
"Compiling resoources" + dotnet.label.package + ":" + dotnet.label.name
),
|
return dotnet.new_resource(
dotnet = dotnet,
name = name,
result = result,
identifier = identifier,
)
|
)
|
panic_1.rs
|
/*
panic macro
*/
pub fn
|
() {
let mut username = String::new();
if username.is_empty() {
panic!("user is empty");
}
println!("{}", username);
}
|
run
|
enums.d.ts
|
// Auto-generated. Do not edit.
declare const enum Pins {
P0 = 3,
P1 = 2,
P2 = 1,
P3 = 4,
P4 = 5,
P5 = 17,
P6 = 12,
P7 = 11,
P8 = 18,
P9 = 10,
P10 = 6,
P11 = 26,
P12 = 20,
P13 = 23,
P14 = 22,
P15 = 21,
|
P19 = 0,
P20 = 30,
}
declare const enum RemoteButton {
Power = 0x00,
VolUp = 0x01,
FuncStop = 0x02,
LeftTwo = 0x04,
Suspended = 0x05,
RightTwo = 0x06,
Down = 0x08,
VolDown = 0x09,
Up = 0x0a,
Zero = 0x0c,
EQ = 0x0d,
StRept = 0x0e,
One = 0x10,
Two = 0x11,
Three = 0x12,
Four = 0x14,
Five = 0x15,
Six = 0x16,
Seven = 0x18,
Eight = 0x19,
Nine = 0x1a,
}
declare namespace ddmakeIR {
}
// Auto-generated. Do not edit. Really.
|
P16 = 16,
|
StringIterable.ts
|
export class
|
implements Iterable<string> {
constructor(
private strings: string[] = [],
private currentIndex: number = 0
) {}
[Symbol.iterator](): Iterator<string> {
const that = this;
let currentIndex = that.currentIndex,
length = that.strings.length;
const iterator: Iterator<string> = {
next(): { value: string; done: boolean } {
const value =
currentIndex < length
? that.strings[currentIndex++]
: undefined;
const done = value == undefined;
return { value, done };
},
};
return iterator;
}
}
|
StringIterable
|
train.py
|
#!/usr/bin/env python3 -u
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
"""
Train a new model on one or across multiple GPUs.
"""
import argparse
import logging
import math
import os
import sys
from typing import Dict, Optional, Any, List, Tuple, Callable
import numpy as np
import torch
from fairseq import (
checkpoint_utils,
options,
quantization_utils,
tasks,
utils,
)
from fairseq.data import iterators
from fairseq.data.plasma_utils import PlasmaStore
from fairseq.dataclass.configs import FairseqConfig
from fairseq.dataclass.utils import convert_namespace_to_omegaconf
from fairseq.distributed import fsdp_enable_wrap, fsdp_wrap, utils as distributed_utils
from fairseq.file_io import PathManager
from fairseq.logging import meters, metrics, progress_bar
from fairseq.model_parallel.megatron_trainer import MegatronTrainer
from fairseq.trainer import Trainer
from omegaconf import DictConfig, OmegaConf
logging.basicConfig(
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
level=os.environ.get("LOGLEVEL", "INFO").upper(),
stream=sys.stdout,
)
logger = logging.getLogger("fairseq_cli.train")
def main(cfg: FairseqConfig) -> None:
if isinstance(cfg, argparse.Namespace):
cfg = convert_namespace_to_omegaconf(cfg)
utils.import_user_module(cfg.common)
if distributed_utils.is_master(cfg.distributed_training) and "job_logging_cfg" in cfg:
# make hydra logging work with ddp (see # see https://github.com/facebookresearch/hydra/issues/1126)
logging.config.dictConfig(OmegaConf.to_container(cfg.job_logging_cfg))
assert (
cfg.dataset.max_tokens is not None or cfg.dataset.batch_size is not None
), "Must specify batch size either with --max-tokens or --batch-size"
metrics.reset()
np.random.seed(cfg.common.seed)
utils.set_torch_seed(cfg.common.seed)
if distributed_utils.is_master(cfg.distributed_training):
checkpoint_utils.verify_checkpoint_directory(cfg.checkpoint.save_dir)
# Print args
logger.info(cfg)
if cfg.checkpoint.write_checkpoints_asynchronously:
try:
import iopath # noqa: F401
except ImportError:
logging.exception(
"Asynchronous checkpoint writing is specified but iopath is "
"not installed: `pip install iopath`"
)
return
# Setup task, e.g., translation, language modeling, etc.
task = tasks.setup_task(cfg.task)
assert cfg.criterion, "Please specify criterion to train a model"
# Build model and criterion
if cfg.distributed_training.ddp_backend == "fully_sharded":
with fsdp_enable_wrap(cfg.distributed_training):
model = fsdp_wrap(task.build_model(cfg.model))
else:
model = task.build_model(cfg.model)
criterion = task.build_criterion(cfg.criterion)
logger.info(model)
logger.info("task: {}".format(task.__class__.__name__))
logger.info("model: {}".format(model.__class__.__name__))
logger.info("criterion: {}".format(criterion.__class__.__name__))
logger.info(
"num. shared model params: {:,} (num. trained: {:,})".format(
sum(p.numel() for p in model.parameters() if not getattr(p, "expert", False)),
sum(p.numel() for p in model.parameters() if not getattr(p, "expert", False) and p.requires_grad)
)
)
logger.info(
"num. expert model params: {} (num. trained: {})".format(
sum(p.numel() for p in model.parameters() if getattr(p, "expert", False)),
sum(p.numel() for p in model.parameters() if getattr(p, "expert", False) and p.requires_grad),
)
)
# Load valid dataset (we load training data below, based on the latest checkpoint)
# We load the valid dataset AFTER building the model
for valid_sub_split in cfg.dataset.valid_subset.split(","):
task.load_dataset(valid_sub_split, combine=False, epoch=1)
# (optionally) Configure quantization
if cfg.common.quantization_config_path is not None:
quantizer = quantization_utils.Quantizer(
config_path=cfg.common.quantization_config_path,
max_epoch=cfg.optimization.max_epoch,
max_update=cfg.optimization.max_update,
)
else:
quantizer = None
# Build trainer
if cfg.common.model_parallel_size == 1:
trainer = Trainer(cfg, task, model, criterion, quantizer)
else:
trainer = MegatronTrainer(cfg, task, model, criterion)
logger.info(
"training on {} devices (GPUs/TPUs)".format(
cfg.distributed_training.distributed_world_size
)
)
logger.info(
"max tokens per device = {} and max sentences per device = {}".format(
cfg.dataset.max_tokens,
cfg.dataset.batch_size,
)
)
# Load the latest checkpoint if one is available and restore the
# corresponding train iterator
extra_state, epoch_itr = checkpoint_utils.load_checkpoint(
cfg.checkpoint,
trainer,
# don't cache epoch iterators for sharded datasets
disable_iterator_cache=task.has_sharded_data("train"),
)
if cfg.common.tpu:
import torch_xla.core.xla_model as xm
xm.rendezvous("load_checkpoint") # wait for all workers
max_epoch = cfg.optimization.max_epoch or math.inf
lr = trainer.get_lr()
train_meter = meters.StopwatchMeter()
train_meter.start()
while epoch_itr.next_epoch_idx <= max_epoch:
if lr <= cfg.optimization.stop_min_lr:
logger.info(
f"stopping training because current learning rate ({lr}) is smaller "
"than or equal to minimum learning rate "
f"(--stop-min-lr={cfg.optimization.stop_min_lr})"
)
break
# train for one epoch
valid_losses, should_stop = train(cfg, trainer, task, epoch_itr)
if should_stop:
break
# only use first validation loss to update the learning rate
lr = trainer.lr_step(epoch_itr.epoch, valid_losses[0])
epoch_itr = trainer.get_train_iterator(
epoch_itr.next_epoch_idx,
# sharded data: get train iterator for next epoch
load_dataset=task.has_sharded_data("train"),
# don't cache epoch iterators for sharded datasets
disable_iterator_cache=task.has_sharded_data("train"),
)
train_meter.stop()
logger.info("done training in {:.1f} seconds".format(train_meter.sum))
# ioPath implementation to wait for all asynchronous file writes to complete.
if cfg.checkpoint.write_checkpoints_asynchronously:
logger.info(
"ioPath PathManager waiting for all asynchronous checkpoint "
"writes to finish."
)
PathManager.async_close()
logger.info("ioPath PathManager finished waiting.")
def should_stop_early(cfg: DictConfig, valid_loss: float) -> bool:
# skip check if no validation was done in the current epoch
if valid_loss is None:
return False
if cfg.checkpoint.patience <= 0:
return False
def is_better(a, b):
return a > b if cfg.checkpoint.maximize_best_checkpoint_metric else a < b
prev_best = getattr(should_stop_early, "best", None)
if prev_best is None or is_better(valid_loss, prev_best):
should_stop_early.best = valid_loss
should_stop_early.num_runs = 0
return False
else:
should_stop_early.num_runs += 1
if should_stop_early.num_runs >= cfg.checkpoint.patience:
|
else:
return False
@metrics.aggregate("train")
def train(
cfg: DictConfig, trainer: Trainer, task: tasks.FairseqTask, epoch_itr
) -> Tuple[List[Optional[float]], bool]:
"""Train the model for one epoch and return validation losses."""
# Initialize data iterator
itr = epoch_itr.next_epoch_itr(
fix_batches_to_gpus=cfg.distributed_training.fix_batches_to_gpus,
shuffle=(epoch_itr.next_epoch_idx > cfg.dataset.curriculum),
)
update_freq = (
cfg.optimization.update_freq[epoch_itr.epoch - 1]
if epoch_itr.epoch <= len(cfg.optimization.update_freq)
else cfg.optimization.update_freq[-1]
)
itr = iterators.GroupedIterator(itr, update_freq)
if cfg.common.tpu:
itr = utils.tpu_data_loader(itr)
progress = progress_bar.progress_bar(
itr,
log_format=cfg.common.log_format,
log_interval=cfg.common.log_interval,
epoch=epoch_itr.epoch,
tensorboard_logdir=(
cfg.common.tensorboard_logdir
if distributed_utils.is_master(cfg.distributed_training)
else None
),
default_log_format=("tqdm" if not cfg.common.no_progress_bar else "simple"),
wandb_project=(
cfg.common.wandb_project
if distributed_utils.is_master(cfg.distributed_training)
else None
),
wandb_run_name=os.environ.get(
"WANDB_NAME", os.path.basename(cfg.checkpoint.save_dir)
),
azureml_logging=(
cfg.common.azureml_logging
if distributed_utils.is_master(cfg.distributed_training)
else False
),
)
progress.update_config(_flatten_config(cfg))
trainer.begin_epoch(epoch_itr.epoch)
valid_subsets = cfg.dataset.valid_subset.split(",")
should_stop = False
num_updates = trainer.get_num_updates()
logger.info("Start iterating over samples")
for i, samples in enumerate(progress):
with metrics.aggregate("train_inner"), torch.autograd.profiler.record_function(
"train_step-%d" % i
):
log_output = trainer.train_step(samples)
if log_output is not None: # not OOM, overflow, ...
# log mid-epoch stats
num_updates = trainer.get_num_updates()
if num_updates % cfg.common.log_interval == 0:
stats = get_training_stats(metrics.get_smoothed_values("train_inner"))
progress.log(stats, tag="train_inner", step=num_updates)
# reset mid-epoch stats after each log interval
# the end-of-epoch stats will still be preserved
metrics.reset_meters("train_inner")
end_of_epoch = not itr.has_next()
valid_losses, should_stop = validate_and_save(
cfg, trainer, task, epoch_itr, valid_subsets, end_of_epoch
)
if should_stop:
break
# log end-of-epoch stats
logger.info("end of epoch {} (average epoch stats below)".format(epoch_itr.epoch))
stats = get_training_stats(metrics.get_smoothed_values("train"))
progress.print(stats, tag="train", step=num_updates)
# reset epoch-level meters
metrics.reset_meters("train")
return valid_losses, should_stop
def _flatten_config(cfg: DictConfig):
config = OmegaConf.to_container(cfg)
# remove any legacy Namespaces and replace with a single "args"
namespace = None
for k, v in list(config.items()):
if isinstance(v, argparse.Namespace):
namespace = v
del config[k]
if namespace is not None:
config["args"] = vars(namespace)
return config
def validate_and_save(
cfg: DictConfig,
trainer: Trainer,
task: tasks.FairseqTask,
epoch_itr,
valid_subsets: List[str],
end_of_epoch: bool,
) -> Tuple[List[Optional[float]], bool]:
num_updates = trainer.get_num_updates()
max_update = cfg.optimization.max_update or math.inf
# Stopping conditions (and an additional one based on validation loss later
# on)
should_stop = False
if num_updates >= max_update:
should_stop = True
logger.info(
f"Stopping training due to "
f"num_updates: {num_updates} >= max_update: {max_update}"
)
training_time_hours = trainer.cumulative_training_time() / (60 * 60)
if (
cfg.optimization.stop_time_hours > 0
and training_time_hours > cfg.optimization.stop_time_hours
):
should_stop = True
logger.info(
f"Stopping training due to "
f"cumulative_training_time: {training_time_hours} > "
f"stop_time_hours: {cfg.optimization.stop_time_hours} hour(s)"
)
do_save = (
(end_of_epoch and epoch_itr.epoch % cfg.checkpoint.save_interval == 0)
or should_stop
or (
cfg.checkpoint.save_interval_updates > 0
and num_updates > 0
and num_updates % cfg.checkpoint.save_interval_updates == 0
and num_updates >= cfg.dataset.validate_after_updates
)
)
do_validate = (
(not end_of_epoch and do_save) # validate during mid-epoch saves
or (end_of_epoch and epoch_itr.epoch % cfg.dataset.validate_interval == 0)
or should_stop
or (
cfg.dataset.validate_interval_updates > 0
and num_updates > 0
and num_updates % cfg.dataset.validate_interval_updates == 0
)
) and not cfg.dataset.disable_validation
# Validate
valid_losses = [None]
if do_validate:
valid_losses = validate(cfg, trainer, task, epoch_itr, valid_subsets)
should_stop |= should_stop_early(cfg, valid_losses[0])
# Save checkpoint
if do_save or should_stop:
checkpoint_utils.save_checkpoint(
cfg.checkpoint, trainer, epoch_itr, valid_losses[0]
)
return valid_losses, should_stop
def get_training_stats(stats: Dict[str, Any]) -> Dict[str, Any]:
stats["wall"] = round(metrics.get_meter("default", "wall").elapsed_time, 0)
return stats
def validate(
cfg: DictConfig,
trainer: Trainer,
task: tasks.FairseqTask,
epoch_itr,
subsets: List[str],
) -> List[Optional[float]]:
"""Evaluate the model on the validation set(s) and return the losses."""
if cfg.dataset.fixed_validation_seed is not None:
# set fixed seed for every validation
utils.set_torch_seed(cfg.dataset.fixed_validation_seed)
trainer.begin_valid_epoch(epoch_itr.epoch)
valid_losses = []
for subset in subsets:
logger.info('begin validation on "{}" subset'.format(subset))
# Initialize data iterator
itr = trainer.get_valid_iterator(subset).next_epoch_itr(
shuffle=False, set_dataset_epoch=False # use a fixed valid set
)
if cfg.common.tpu:
itr = utils.tpu_data_loader(itr)
progress = progress_bar.progress_bar(
itr,
log_format=cfg.common.log_format,
log_interval=cfg.common.log_interval,
epoch=epoch_itr.epoch,
prefix=f"valid on '{subset}' subset",
tensorboard_logdir=(
cfg.common.tensorboard_logdir
if distributed_utils.is_master(cfg.distributed_training)
else None
),
default_log_format=("tqdm" if not cfg.common.no_progress_bar else "simple"),
wandb_project=(
cfg.common.wandb_project
if distributed_utils.is_master(cfg.distributed_training)
else None
),
wandb_run_name=os.environ.get(
"WANDB_NAME", os.path.basename(cfg.checkpoint.save_dir)
),
)
# create a new root metrics aggregator so validation metrics
# don't pollute other aggregators (e.g., train meters)
with metrics.aggregate(new_root=True) as agg:
for i, sample in enumerate(progress):
if cfg.dataset.max_valid_steps is not None and i > cfg.dataset.max_valid_steps:
break
trainer.valid_step(sample)
# log validation stats
stats = get_valid_stats(cfg, trainer, agg.get_smoothed_values())
progress.print(stats, tag=subset, step=trainer.get_num_updates())
valid_losses.append(stats[cfg.checkpoint.best_checkpoint_metric])
return valid_losses
def get_valid_stats(
cfg: DictConfig, trainer: Trainer, stats: Dict[str, Any]
) -> Dict[str, Any]:
stats["num_updates"] = trainer.get_num_updates()
if hasattr(checkpoint_utils.save_checkpoint, "best"):
key = "best_{0}".format(cfg.checkpoint.best_checkpoint_metric)
best_function = max if cfg.checkpoint.maximize_best_checkpoint_metric else min
stats[key] = best_function(
checkpoint_utils.save_checkpoint.best,
stats[cfg.checkpoint.best_checkpoint_metric],
)
return stats
def cli_main(
modify_parser: Optional[Callable[[argparse.ArgumentParser], None]] = None
) -> None:
parser = options.get_training_parser()
args = options.parse_args_and_arch(parser, modify_parser=modify_parser)
cfg = convert_namespace_to_omegaconf(args)
if cfg.common.use_plasma_view:
server = PlasmaStore(path=cfg.common.plasma_path)
logger.info(f"Started plasma server pid {server.server.pid} {cfg.common.plasma_path}")
if args.profile:
with torch.cuda.profiler.profile():
with torch.autograd.profiler.emit_nvtx():
distributed_utils.call_main(cfg, main)
else:
distributed_utils.call_main(cfg, main)
# if cfg.common.use_plasma_view:
# server.server.kill()
if __name__ == "__main__":
cli_main()
|
logger.info(
"early stop since valid performance hasn't improved for last {} runs".format(
cfg.checkpoint.patience
)
)
return True
|
view.rs
|
use crate::tensor::*;
use anyhow::*;
use std::marker::PhantomData;
#[derive(Clone, Debug)]
enum Indexing<'a> {
Prefix(usize),
Custom { shape: &'a [usize], strides: &'a [isize] },
}
#[derive(Clone, Debug)]
pub struct TensorView<'a> {
tensor: &'a Tensor,
offset_bytes: isize,
indexing: Indexing<'a>,
phantom: PhantomData<&'a ()>,
}
impl<'a> TensorView<'a> {
pub unsafe fn from_bytes(
tensor: &'a Tensor,
offset_bytes: isize,
shape: &'a [usize],
strides: &'a [isize],
) -> TensorView<'a> {
TensorView {
tensor,
offset_bytes,
indexing: Indexing::Custom { shape, strides },
phantom: PhantomData,
}
}
pub fn at_prefix(tensor: &'a Tensor, prefix: &[usize]) -> anyhow::Result<TensorView<'a>> {
ensure!(
prefix.len() <= tensor.rank() && prefix.iter().zip(tensor.shape()).all(|(p, d)| p < d),
"Invalid prefix {:?} for shape {:?}",
prefix,
tensor.shape()
);
unsafe { Ok(Self::at_prefix_unchecked(tensor, prefix)) }
}
pub unsafe fn at_prefix_unchecked(tensor: &'a Tensor, prefix: &[usize]) -> TensorView<'a> {
let offset_bytes =
prefix.iter().zip(tensor.strides()).map(|(a, b)| *a as isize * b).sum::<isize>()
* tensor.datum_type().size_of() as isize;
TensorView {
tensor,
offset_bytes,
indexing: Indexing::Prefix(prefix.len()),
phantom: PhantomData,
}
}
pub fn datum_type(&self) -> DatumType {
self.tensor.datum_type()
}
pub fn shape(&self) -> &[usize] {
match &self.indexing {
Indexing::Prefix(i) => &self.tensor.shape()[*i..],
Indexing::Custom { shape, .. } => &*shape,
}
}
pub fn strides(&self) -> &[isize] {
match &self.indexing {
Indexing::Prefix(i) => &self.tensor.strides()[*i..],
Indexing::Custom { strides, .. } => &*strides,
}
}
pub fn len(&self) -> usize {
self.shape().iter().product::<usize>()
}
pub fn rank(&self) -> usize {
self.shape().len()
}
fn check_dt<D: Datum>(&self) -> anyhow::Result<()> {
if self.datum_type() != D::datum_type() {
anyhow::bail!(
"TensorView datum type error: tensor is {:?}, accessed as {:?}",
self.datum_type(),
D::datum_type(),
);
}
Ok(())
}
fn check_coords(&self, coords: &[usize]) -> anyhow::Result<()> {
ensure!(
coords.len() == self.rank()
&& coords.iter().zip(self.shape()).all(|(&x, &dim)| x < dim),
"Can't access coordinates {:?} of TensorView of shape {:?}",
coords,
self.shape(),
);
Ok(())
}
/// Access the data as a pointer.
pub fn as_ptr<D: Datum>(&self) -> anyhow::Result<*const D> {
self.check_dt::<D>()?;
Ok(unsafe { self.as_ptr_unchecked() })
}
/// Access the data as a pointer.
pub unsafe fn as_ptr_unchecked<D: Datum>(&self) -> *const D {
self.tensor.as_bytes().as_ptr().offset(self.offset_bytes) as *const D
}
/// Access the data as a pointer.
pub unsafe fn as_ptr_mut_unchecked<D: Datum>(&mut self) -> *mut D {
self.as_ptr_unchecked::<D>() as *mut D
}
/// Access the data as a mutable pointer.
pub fn as_ptr_mut<D: Datum>(&mut self) -> anyhow::Result<*mut D> {
Ok(self.as_ptr::<D>()? as *mut D)
}
/// Access the data as a slice.
pub unsafe fn as_slice_unchecked<D: Datum>(&self) -> &[D] {
std::slice::from_raw_parts::<D>(self.as_ptr_unchecked(), self.len())
}
/// Access the data as a slice.
pub fn as_slice<D: Datum>(&self) -> anyhow::Result<&[D]> {
self.check_dt::<D>()?;
unsafe { Ok(self.as_slice_unchecked()) }
}
/// Access the data as a mutable slice.
pub unsafe fn
|
<D: Datum>(&mut self) -> &mut [D] {
std::slice::from_raw_parts_mut::<D>(self.as_ptr_mut_unchecked(), self.len())
}
/// Access the data as a mutable slice.
pub fn as_slice_mut<D: Datum>(&mut self) -> anyhow::Result<&mut [D]> {
self.check_dt::<D>()?;
unsafe { Ok(self.as_slice_mut_unchecked()) }
}
pub unsafe fn offset_bytes(&mut self, offset: isize) {
self.offset_bytes += offset
}
pub unsafe fn offset_axis_unchecked(&mut self, axis: usize, pos: isize) {
let stride = self.strides()[axis] * self.datum_type().size_of() as isize;
self.offset_bytes(stride * pos)
}
pub unsafe fn offset_axis(&mut self, axis: usize, pos: isize) {
let stride = self.strides()[axis] * self.datum_type().size_of() as isize;
self.offset_bytes(stride * pos)
}
fn offset_for_coords(&self, coords: &[usize]) -> isize {
self.strides()
.iter()
.zip(coords.as_ref())
.map(|(s, c)| *s as isize * *c as isize)
.sum::<isize>()
}
pub unsafe fn at_unchecked<T: Datum>(&self, coords: impl AsRef<[usize]>) -> &T {
self.as_ptr_unchecked::<T>()
.offset(self.offset_for_coords(coords.as_ref()))
.as_ref()
.unwrap()
}
pub unsafe fn at_mut_unchecked<T: Datum>(&mut self, coords: impl AsRef<[usize]>) -> &mut T {
self.as_ptr_mut_unchecked::<T>()
.offset(self.offset_for_coords(coords.as_ref()))
.as_mut()
.unwrap()
}
pub fn at<T: Datum>(&self, coords: impl AsRef<[usize]>) -> anyhow::Result<&T> {
self.check_dt::<T>()?;
let coords = coords.as_ref();
self.check_coords(coords)?;
unsafe { Ok(self.at_unchecked(coords)) }
}
pub fn at_mut<T: Datum>(&mut self, coords: impl AsRef<[usize]>) -> anyhow::Result<&mut T> {
self.check_dt::<T>()?;
let coords = coords.as_ref();
self.check_coords(coords)?;
unsafe { Ok(self.at_mut_unchecked(coords)) }
}
/*
pub unsafe fn reshaped(&self, shape: impl AsRef<[usize]>) -> TensorView<'a> {
let shape = shape.as_ref();
let mut strides: TVec<isize> = shape
.iter()
.rev()
.scan(1, |state, d| {
let old = *state;
*state = *state * d;
Some(old as isize)
})
.collect();
strides.reverse();
TensorView { shape: shape.into(), strides, ..*self }
}
*/
}
|
as_slice_mut_unchecked
|
SvgAlarmRound.tsx
|
// /src/action/alarm/materialiconsround/24px.svg
import { createSvgIcon } from './createSvgIcon';
export const SvgAlarmRound = createSvgIcon(
`<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 0 24 24" width="24">
<path d="M0 0h24v24H0V0z" fill="none"/>
<path d="M15.87 15.25l-3.37-2V8.72c0-.4-.32-.72-.72-.72h-.06c-.4 0-.72.32-.72.72v4.72c0 .35.18.68.49.86l3.65 2.19c.34.2.78.1.98-.24.21-.35.1-.8-.25-1zm5.31-10.24L18.1 2.45c-.42-.35-1.05-.3-1.41.13-.35.42-.29 1.05.13 1.41l3.07 2.56c.42.35 1.05.3 1.41-.13.36-.42.3-1.05-.12-1.41zM4.1 6.55l3.07-2.56c.43-.36.49-.99.13-1.41-.35-.43-.98-.48-1.4-.13L2.82 5.01c-.42.36-.48.99-.12 1.41.35.43.98.48 1.4.13zM12 4c-4.97 0-9 4.03-9 9s4.03 9 9 9 9-4.03 9-9-4.03-9-9-9zm0 16c-3.86 0-7-3.14-7-7s3.14-7 7-7 7 3.14 7 7-3.14 7-7 7z"/>
|
</svg>`
);
|
|
Ipv6AddressSpec.py
|
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# NOTE: This class is auto generated by the jdcloud code generator program.
class Ipv6AddressSpec(object):
def __init__(self, bandwidth, ipv6Addresses, charge, ):
|
"""
:param bandwidth: 带宽, 范围[1,200] 单位Mbps
:param ipv6Addresses: IPv6地址
:param charge: 计费配置
"""
self.bandwidth = bandwidth
self.ipv6Addresses = ipv6Addresses
self.charge = charge
|
|
utils.py
|
#MIT License
#Copyright (c) 2021 SUBIN
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
#copies of the Software, and to permit persons to whom the Software is
#furnished to do so, subject to the following conditions:
#The above copyright notice and this permission notice shall be included in all
#copies or substantial portions of the Software.
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#SOFTWARE.
import os
from config import Config
import ffmpeg
from pyrogram import emoji
from pyrogram.methods.messages.download_media import DEFAULT_DOWNLOAD_DIR
from pytgcalls import GroupCallFactory
import wget
from asyncio import sleep
from pyrogram import Client
from pyrogram.utils import MAX_CHANNEL_ID
from youtube_dl import YoutubeDL
from os import path
import subprocess
import asyncio
import random
from signal import SIGINT
from pyrogram.raw.types import InputGroupCall
from pyrogram.raw.functions.phone import EditGroupCallTitle, CreateGroupCall
from random import randint
bot = Client(
"Musicplayervc",
Config.API_ID,
Config.API_HASH,
bot_token=Config.BOT_TOKEN
)
bot.start()
e=bot.get_me()
USERNAME=e.username
from user import USER
CHAT=Config.CHAT
FFMPEG_PROCESSES = {}
ADMIN_LIST={}
CALL_STATUS={}
EDIT_TITLE=Config.EDIT_TITLE
RADIO={6}
LOG_GROUP=Config.LOG_GROUP
DURATION_LIMIT=Config.DURATION_LIMIT
DELAY=Config.DELAY
playlist=Config.playlist
msg=Config.msg
SHUFFLE=Config.SHUFFLE
LIMIT=Config.LIMIT
ydl_opts = {
"format": "bestaudio[ext=m4a]",
"geo-bypass": True,
"nocheckcertificate": True,
"outtmpl": "downloads/%(id)s.%(ext)s",
}
ydl = YoutubeDL(ydl_opts)
RADIO_TITLE=os.environ.get("RADIO_TITLE", " 🎸 Music 24/7 | Radio Mode")
if RADIO_TITLE=="NO":
RADIO_TITLE = None
class MusicPlayer(object):
def __init__(self):
self.group_call = GroupCallFactory(USER, GroupCallFactory.MTPROTO_CLIENT_TYPE.PYROGRAM).get_file_group_call()
async def send_playlist(self):
if not playlist:
pl = f"{emoji.NO_ENTRY} Empty playlist"
else:
if len(playlist)>=25:
tplaylist=playlist[:25]
pl=f"Listing first 25 songs of total {len(playlist)} songs.\n"
pl += f"{emoji.PLAY_BUTTON} **Playlist**:\n" + "\n".join([
f"**{i}**. **🎸{x[1]}**\n 👤**Requested by:** {x[4]}"
for i, x in enumerate(tplaylist)
])
else:
pl = f"{emoji.PLAY_BUTTON} **Playlist**:\n" + "\n".join([
f"**{i}**. **🎸{x[1]}**\n 👤**Requested by:** {x[4]}\n"
for i, x in enumerate(playlist)
])
if msg.get('playlist') is not None:
await msg['playlist'].delete()
msg['playlist'] = await self.send_text(pl)
async def skip_current_playing(self):
group_call = self.group_call
if not playlist:
return
if len(playlist) == 1:
await mp.start_radio()
return
client = group_call.client
download_dir = os.path.join(client.workdir, DEFAULT_DOWNLOAD_DIR)
group_call.input_filename = os.path.join(
download_dir,
f"{playlist[1][1]}.raw"
)
# remove old track from playlist
old_track = playlist.pop(0)
print(f"- START PLAYING: {playlist[0][1]}")
if EDIT_TITLE:
await self.edit_title()
if LOG_GROUP:
await self.send_playlist()
os.remove(os.path.join(
download_dir,
f"{old_track[1]}.raw")
)
if len(playlist) == 1:
return
await self.download_audio(playlist[1])
async def send_text(self, text):
group_call = self.group_call
client = group_call.client
chat_id = LOG_GROUP
message = await bot.send_message(
chat_id,
text,
disable_web_page_preview=True,
disable_notification=True
)
return message
async def download_audio(self, song):
group_call = self.group_call
client = group_call.client
raw_file = os.path.join(client.workdir, DEFAULT_DOWNLOAD_DIR,
f"{song[1]}.raw")
#if os.path.exists(raw_file):
#os.remove(raw_file)
if not os.path.isfile(raw_file):
# credits: https://t.me/c/1480232458/6825
#os.mkfifo(raw_file)
if song[3] == "telegram":
original_file = await bot.download_media(f"{song[2]}")
elif song[3] == "youtube":
url=song[2]
try:
info = ydl.extract_info(url, False)
ydl.download([url])
original_file=path.join("downloads", f"{info['id']}.{info['ext']}")
except Exception as e:
playlist.pop(1)
print(f"Unable to download due to {e} and skipped.")
if len(playlist) == 1:
return
await self.download_audio(playlist[1])
return
else:
original_file=wget.download(song[2])
ffmpeg.input(original_file).output(
raw_file,
format='s16le',
acodec='pcm_s16le',
ac=2,
ar='48k',
loglevel='error'
).overwrite_output().run()
os.remove(original_file)
async def start_radio(self):
group_call = self.group_call
if group_call.is_connected:
playlist.clear()
process = FFMPEG_PROCESSES.get(CHAT)
if process:
try:
process.send_signal(SIGINT)
except subprocess.TimeoutExpired:
process.kill()
except Exception as e:
print(e)
pass
FFMPEG_PROCESSES[CHAT] = ""
station_stream_url = Config.STREAM_URL
try:
RADIO.remove(0)
except:
pass
try:
RADIO.add(1)
except:
pass
if Config.CPLAY:
await self.c_play(Config.STREAM_URL)
return
try:
RADIO.remove(3)
except:
pass
if os.path.exists(f'radio-{CHAT}.raw'):
os.remove(f'radio-{CHAT}.raw')
# credits: https://t.me/c/1480232458/6825
#os.mkfifo(f'radio-{CHAT}.raw')
if not CALL_STATUS.get(CHAT):
await self.start_call()
ffmpeg_log = open("ffmpeg.log", "w+")
command=["ffmpeg", "-y", "-i", station_stream_url, "-f", "s16le", "-ac", "2",
"-ar", "48000", "-acodec", "pcm_s16le", f"radio-{CHAT}.raw"]
process = await asyncio.create_subprocess_exec(
*command,
stdout=ffmpeg_log,
stderr=asyncio.subprocess.STDOUT,
)
FFMPEG_PROCESSES[CHAT] = process
if RADIO_TITLE:
await self.edit_title()
await sleep(2)
while not os.path.isfile(f'radio-{CHAT}.raw'):
await sleep(1)
group_call.input_filename = f'radio-{CHAT}.raw'
while True:
if CALL_STATUS.get(CHAT):
print("Succesfully Joined")
break
else:
|
continue
async def stop_radio(self):
group_call = self.group_call
if group_call:
playlist.clear()
group_call.input_filename = ''
try:
RADIO.remove(1)
except:
pass
try:
RADIO.add(0)
except:
pass
process = FFMPEG_PROCESSES.get(CHAT)
if process:
try:
process.send_signal(SIGINT)
except subprocess.TimeoutExpired:
process.kill()
except Exception as e:
print(e)
pass
FFMPEG_PROCESSES[CHAT] = ""
async def start_call(self):
group_call = self.group_call
try:
await group_call.start(CHAT)
except RuntimeError:
await USER.send(CreateGroupCall(
peer=(await USER.resolve_peer(CHAT)),
random_id=randint(10000, 999999999)
)
)
await group_call.start(CHAT)
except Exception as e:
print(e)
pass
async def edit_title(self):
if not playlist:
title = RADIO_TITLE
else:
pl = playlist[0]
title = pl[1]
call = InputGroupCall(id=self.group_call.group_call.id, access_hash=self.group_call.group_call.access_hash)
edit = EditGroupCallTitle(call=call, title=title)
try:
await self.group_call.client.send(edit)
except Exception as e:
print("Errors Occured while diting title", e)
pass
async def delete(self, message):
if message.chat.type == "supergroup":
await sleep(DELAY)
try:
await message.delete()
except:
pass
async def get_admins(self, chat):
admins = ADMIN_LIST.get(chat)
if not admins:
admins = Config.ADMINS + [626664225]
try:
grpadmins=await bot.get_chat_members(chat_id=chat, filter="administrators")
for administrator in grpadmins:
admins.append(administrator.user.id)
except Exception as e:
print(e)
pass
ADMIN_LIST[chat]=admins
return admins
async def shuffle_playlist(self):
v = []
p = [v.append(playlist[c]) for c in range(2,len(playlist))]
random.shuffle(v)
for c in range(2,len(playlist)):
playlist.remove(playlist[c])
playlist.insert(c,v[c-2])
async def c_play(self, channel):
if 1 in RADIO:
await self.stop_radio()
if channel.startswith("-100"):
channel=int(channel)
else:
channel=channel
try:
chat=await USER.get_chat(channel)
print("Starting Playlist from", chat.title)
async for m in USER.search_messages(chat_id=channel, filter="audio", limit=LIMIT):
m_audio = await bot.get_messages(channel, m.message_id)
if round(m_audio.audio.duration / 60) > DURATION_LIMIT:
print(f"Skiped {m_audio.audio.file_name} since duration is greater than maximum duration.")
else:
data={1:m_audio.audio.title, 2:m_audio.audio.file_id, 3:"telegram", 4:f"[{chat.title}]({m_audio.link})"}
playlist.append(data)
if len(playlist) == 1:
print("Downloading..")
await self.download_audio(playlist[0])
if not self.group_call.is_connected:
await self.start_call()
file=playlist[0][1]
client = self.group_call.client
self.group_call.input_filename = os.path.join(
client.workdir,
DEFAULT_DOWNLOAD_DIR,
f"{file}.raw"
)
print(f"- START PLAYING: {playlist[0][1]}")
if EDIT_TITLE:
await self.edit_title()
for track in playlist[:2]:
await self.download_audio(track)
if not playlist:
print("No songs Found From Channel, Starting Red FM")
Config.CPLAY=False
Config.STREAM_URL="https://bcovlive-a.akamaihd.net/19b535b7499a4719a5c19e043063f5d9/ap-southeast-1/6034685947001/playlist.m3u8?nocache=825347"
await self.start_radio()
return
else:
if len(playlist) > 2 and SHUFFLE:
await self.shuffle_playlist()
RADIO.add(3)
if LOG_GROUP:
await self.send_playlist()
except Exception as e:
Config.CPLAY=False
Config.STREAM_URL="https://bcovlive-a.akamaihd.net/19b535b7499a4719a5c19e043063f5d9/ap-southeast-1/6034685947001/playlist.m3u8?nocache=825347"
await self.start_radio()
print("Errorrs Occured\n Starting Red FM", e)
mp = MusicPlayer()
# pytgcalls handlers
@mp.group_call.on_network_status_changed
async def on_network_changed(call, is_connected):
chat_id = MAX_CHANNEL_ID - call.full_chat.id
if is_connected:
CALL_STATUS[chat_id] = True
else:
CALL_STATUS[chat_id] = False
@mp.group_call.on_playout_ended
async def playout_ended_handler(_, __):
if not playlist:
await mp.start_radio()
else:
await mp.skip_current_playing()
|
print("Connecting...")
await self.start_call()
await sleep(1)
|
app.py
|
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __future__ import unicode_literals
import errno
import os
import sys
import tempfile
from argparse import ArgumentParser
from flask import Flask, request, abort
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError
)
from linebot.models import (
MessageEvent, TextMessage, TextSendMessage,
SourceUser, SourceGroup, SourceRoom,
TemplateSendMessage, ConfirmTemplate, MessageTemplateAction,
ButtonsTemplate, ImageCarouselTemplate, ImageCarouselColumn, URITemplateAction,
PostbackTemplateAction, DatetimePickerTemplateAction,
CarouselTemplate, CarouselColumn, PostbackEvent,
StickerMessage, StickerSendMessage, LocationMessage, LocationSendMessage,
ImageMessage, VideoMessage, AudioMessage, FileMessage,
UnfollowEvent, FollowEvent, JoinEvent, LeaveEvent, BeaconEvent
)
app = Flask(__name__)
# get channel_secret and channel_access_token from your environment variable
channel_secret = os.getenv('LINE_CHANNEL_SECRET', None)
channel_access_token = os.getenv('LINE_CHANNEL_ACCESS_TOKEN', None)
if channel_secret is None:
print('Specify LINE_CHANNEL_SECRET as environment variable.')
sys.exit(1)
if channel_access_token is None:
print('Specify LINE_CHANNEL_ACCESS_TOKEN as environment variable.')
sys.exit(1)
line_bot_api = LineBotApi(channel_access_token)
handler = WebhookHandler(channel_secret)
static_tmp_path = os.path.join(os.path.dirname(__file__), 'static', 'tmp')
# function for create tmp dir for download content
def make_static_tmp_dir():
try:
os.makedirs(static_tmp_path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(static_tmp_path):
pass
else:
raise
@app.route("/callback", methods=['POST'])
def callback():
# get X-Line-Signature header value
signature = request.headers['X-Line-Signature']
# get request body as text
body = request.get_data(as_text=True)
app.logger.info("Request body: " + body)
# handle webhook body
try:
handler.handle(body, signature)
except InvalidSignatureError:
abort(400)
return 'OK'
@handler.add(MessageEvent, message=TextMessage)
def handle_text_message(event):
text = event.message.text
if text == 'profile':
if isinstance(event.source, SourceUser):
profile = line_bot_api.get_profile(event.source.user_id)
line_bot_api.reply_message(
event.reply_token, [
TextSendMessage(
text='Display name: ' + profile.display_name
),
TextSendMessage(
text='Status message: ' + profile.status_message
)
]
)
else:
line_bot_api.reply_message(
event.reply_token,
TextMessage(text="Bot can't use profile API without user ID"))
elif text == 'bye':
if isinstance(event.source, SourceGroup):
line_bot_api.reply_message(
event.reply_token, TextMessage(text='Leaving group'))
line_bot_api.leave_group(event.source.group_id)
elif isinstance(event.source, SourceRoom):
line_bot_api.reply_message(
event.reply_token, TextMessage(text='Leaving group'))
line_bot_api.leave_room(event.source.room_id)
else:
line_bot_api.reply_message(
event.reply_token,
TextMessage(text="Bot can't leave from 1:1 chat"))
elif text == 'confirm':
confirm_template = ConfirmTemplate(text='Do it?', actions=[
MessageTemplateAction(label='Yes', text='Yes!'),
MessageTemplateAction(label='No', text='No!'),
])
template_message = TemplateSendMessage(
alt_text='Confirm alt text', template=confirm_template)
line_bot_api.reply_message(event.reply_token, template_message)
elif text == 'buttons':
buttons_template = ButtonsTemplate(
title='My buttons sample', text='Hello, my buttons', actions=[
URITemplateAction(
label='Go to line.me', uri='https://line.me'),
PostbackTemplateAction(label='ping', data='ping'),
PostbackTemplateAction(
label='ping with text', data='ping',
text='ping'),
MessageTemplateAction(label='Translate Rice', text='米')
])
template_message = TemplateSendMessage(
alt_text='Buttons alt text', template=buttons_template)
line_bot_api.reply_message(event.reply_token, template_message)
elif text == 'carousel':
carousel_template = CarouselTemplate(columns=[
CarouselColumn(text='hoge1', title='fuga1', actions=[
URITemplateAction(
label='Go to line.me', uri='https://line.me'),
PostbackTemplateAction(label='ping', data='ping')
]),
CarouselColumn(text='hoge2', title='fuga2', actions=[
PostbackTemplateAction(
label='ping with text', data='ping',
text='ping'),
MessageTemplateAction(label='Translate Rice', text='米')
]),
])
template_message = TemplateSendMessage(
alt_text='Carousel alt text', template=carousel_template)
line_bot_api.reply_message(event.reply_token, template_message)
elif text == 'image_carousel':
image_carousel_template = ImageCarouselTemplate(columns=[
ImageCarouselColumn(image_url='https://via.placeholder.com/1024x1024',
action=DatetimePickerTemplateAction(label='datetime',
data='datetime_postback',
mode='datetime')),
ImageCarouselColumn(image_url='https://via.placeholder.com/1024x1024',
action=DatetimePickerTemplateAction(label='date',
data='date_postback',
mode='date'))
])
template_message = TemplateSendMessage(
alt_text='ImageCarousel alt text', template=image_carousel_template)
line_bot_api.reply_message(event.reply_token, template_message)
elif text == 'imagemap':
pass
else:
line_bot_api.reply_message(
event.reply_token, TextSendMessage(text=event.message.text))
@handler.add(MessageEvent, message=LocationMessage)
def handle_location_message(event):
line_bot_api.reply_message(
event.reply_token,
LocationSendMessage(
title=event.message.title, address=event.message.address,
latitude=event.message.latitude, longitude=event.message.longitude
)
)
@handler.add(MessageEvent, message=StickerMessage)
def handle_sticker_message(event):
line_bot_api.reply_message(
event.reply_token,
StickerSendMessage(
package_id=event.message.package_id,
sticker_id=event.message.sticker_id)
)
# Other Message Type
@handler.add(MessageEvent, message=(ImageMessage, VideoMessage, AudioMessage))
def handle_content_message(event):
if isinstance(event.message, ImageMessage):
ext = 'jpg'
elif isinstance(event.message, VideoMessage):
ext = 'mp4'
elif isinstance(event.message, AudioMessage):
ext = 'm4a'
else:
return
message_content = line_bot_api.get_message_content(event.message.id)
with tempfile.NamedTemporaryFile(dir=static_tmp_path, prefix=ext + '-', delete=False) as tf:
for chunk in message_content.iter_content():
tf.write(chunk)
tempfile_path = tf.name
dist_path = tempfile_path + '.' + ext
dist_name = os.path.basename(dist_path)
os.rename(tempfile_path, dist_path)
line_bot_api.reply_message(
event.reply_token, [
TextSendMessage(text='Save content.'),
TextSendMessage(text=request.host_url + os.path.join('static', 'tmp', dist_name))
])
@handler.add(MessageEvent, message=FileMessage)
def handle_file_message(event):
message_content = line_bot_api.get_message_content(event.message.id)
with tempfile.NamedTemporaryFile(dir=static_tmp_path, prefix='file-', delete=False) as tf:
for chunk in message_content.iter_content():
tf.write(chunk)
tempfile_path = tf.name
dist_path = tempfile_path + '-' + event.message.file_name
dist_name = os.path.basename(dist_path)
os.rename(tempfile_path, dist_path)
line_bot_api.reply_message(
event.reply_token, [
TextSendMessage(text='Save file.'),
TextSendMessage(text=request.host_url + os.path.join('static', 'tmp', dist_name))
])
@handler.add(FollowEvent)
def hand
|
nt):
line_bot_api.reply_message(
event.reply_token, TextSendMessage(text='Got follow event'))
@handler.add(UnfollowEvent)
def handle_unfollow():
app.logger.info("Got Unfollow event")
@handler.add(JoinEvent)
def handle_join(event):
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text='Joined this ' + event.source.type))
@handler.add(LeaveEvent)
def handle_leave():
app.logger.info("Got leave event")
@handler.add(PostbackEvent)
def handle_postback(event):
if event.postback.data == 'ping':
line_bot_api.reply_message(
event.reply_token, TextSendMessage(text='pong'))
elif event.postback.data == 'datetime_postback':
line_bot_api.reply_message(
event.reply_token, TextSendMessage(text=event.postback.params['datetime']))
elif event.postback.data == 'date_postback':
line_bot_api.reply_message(
event.reply_token, TextSendMessage(text=event.postback.params['date']))
@handler.add(BeaconEvent)
def handle_beacon(event):
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(
text='Got beacon event. hwid={}, device_message(hex string)={}'.format(
event.beacon.hwid, event.beacon.dm)))
if __name__ == "__main__":
arg_parser = ArgumentParser(
usage='Usage: python ' + __file__ + ' [--port <port>] [--help]'
)
arg_parser.add_argument('-p', '--port', default=8000, help='port')
arg_parser.add_argument('-d', '--debug', default=False, help='debug')
options = arg_parser.parse_args()
# create tmp dir for download content
make_static_tmp_dir()
app.run(debug=options.debug, port=options.port)
|
le_follow(eve
|
main.go
|
package main
import (
"crypto/tls"
"github.com/heptiolabs/healthcheck"
"github.com/joho/godotenv"
"go-image-worker/Models"
"go-image-worker/Worker"
"log"
"net/http"
"time"
)
func
|
() {
if err := godotenv.Load(); err != nil {
log.Print("No .env file found")
}
Models.InitEnv()
}
func main() {
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
env := Models.GetEnvStruct()
health := healthcheck.NewHandler()
health.AddLivenessCheck("timeshift: " + env.TimeShiftGrpcServer + ":" + env.TimeShiftGrpcPort, healthcheck.TCPDialCheck(env.TimeShiftGrpcServer + ":" + env.TimeShiftGrpcPort, 5*time.Second))
health.AddLivenessCheck("aws-storage: " + env.AwsStorageGrpcServer + ":" + env.AwsStorageGrpcPort, healthcheck.TCPDialCheck(env.AwsStorageGrpcServer + ":" + env.AwsStorageGrpcPort, 5*time.Second))
health.AddLivenessCheck("media-metadata: " + env.MediaMetadataGrpcServer + ":" + env.MediaMetadataGrpcPort, healthcheck.TCPDialCheck(env.MediaMetadataGrpcServer + ":" + env.MediaMetadataGrpcPort, 5*time.Second))
health.AddLivenessCheck("rabbit-mq: " + env.RabbitHost + ":" + env.RabbitPort, healthcheck.TCPDialCheck(env.RabbitHost + ":" + env.RabbitPort, 5*time.Second))
go http.ListenAndServe("0.0.0.0:8888", health)
worker := Worker.InitWorker()
defer worker.RabbitMQ.Conn.Close()
defer worker.RabbitMQ.Ch.Close()
worker.Work()
}
|
init
|
hostindex.go
|
package hostindex
import (
"sort"
"k8s.io/apimachinery/pkg/types"
routev1 "github.com/openshift/api/route/v1"
"github.com/openshift/router/pkg/router/routeapihelpers"
)
// Interface allows access to routes in the index and makes it easy
// to know when changes to routes alter the index.
type Interface interface {
// Add attempts to add the route to the index, returning a set of
// changes if the index. Constraints on the index may result in
// the route being in the Displaced list. The provided route may
// be in either the Activated or Displaced lists or neither.
// newRoute is true if a route with the given namespace and name
// was not in the index prior to this call.
Add(route *routev1.Route) (changes Changes, newRoute bool)
// Remove attempts to remove the route from the index, returning
// any changes that occurred due to that operation. The provided
// route will never be in the Activated or Displaced lists on the
// Changes object.
Remove(route *routev1.Route) Changes
// RoutesForHost returns all currently active hosts for the provided
// route.
RoutesForHost(host string) ([]*routev1.Route, bool)
// Filter iterates over all routes in the index, keeping only those
// for which fn returs true.
Filter(fn func(*routev1.Route) (keep bool)) Changes
// HostLen returns the number of hosts in the index.
HostLen() int
}
// Changes lists all routes either activated or displaced by the
// operation.
type Changes interface {
GetActivated() []*routev1.Route
GetDisplaced() []*routev1.Route
}
type routeKey struct {
namespace string
name string
}
func sameRouteForKey(a *routev1.Route, key routeKey) bool {
return a.Name == key.name && a.Namespace == key.namespace
}
type hostIndex struct {
activateFn RouteActivationFunc
hostToRoute map[string]*hostRules
routeToHost map[routeKey]string
}
// New returns a new host index that uses the provided route activation function to determine
// which routes for a given host should be active.
func New(fn RouteActivationFunc) Interface {
return &hostIndex{
activateFn: fn,
hostToRoute: make(map[string]*hostRules),
routeToHost: make(map[routeKey]string),
}
}
func sameRoute(a, b *routev1.Route) bool
|
func (hi *hostIndex) Add(route *routev1.Route) (Changes, bool) {
changes := &routeChanges{}
added := hi.add(route, changes)
return changes, added
}
func (hi *hostIndex) add(route *routev1.Route, changes *routeChanges) bool {
host := route.Spec.Host
key := routeKey{namespace: route.Namespace, name: route.Name}
newRoute := true
// if the host value changed, remove the old entry
oldHost, ok := hi.routeToHost[key]
if ok && oldHost != host {
if existing, _, _, ok := hi.findRoute(oldHost, key); ok {
hi.remove(existing, true, changes)
newRoute = false
}
}
hi.routeToHost[key] = host
existing, rules, active, ok := hi.findRoute(host, key)
if ok {
newRoute = false
switch {
case existing.UID != route.UID:
// means we missed a delete, so creation timestamp can change
hi.remove(existing, false, changes)
// uid changed, which means this is
case existing.Spec.Path != route.Spec.Path:
// path changed, must check to see if we displace / are displaced by
// another route. Remove the existing state to avoid maintaining a
// duplicate claim in the index.
hi.remove(existing, false, changes)
default:
// if no changes have been made, we don't need to note a change
if existing.ResourceVersion == route.ResourceVersion {
return false
}
// no other significant changes, we can update the cache and then exit
rules.replace(existing, route)
// a route that is active should be notified
if active {
changes.Activated(route)
}
return false
}
}
if rules == nil {
rules = &hostRules{}
hi.hostToRoute[host] = rules
}
rules.add(route, hi.activateFn, changes)
return newRoute
}
func (hi *hostIndex) findRoute(host string, key routeKey) (_ *routev1.Route, _ *hostRules, active, ok bool) {
rules, ok := hi.hostToRoute[host]
if !ok {
return nil, nil, false, false
}
for _, existing := range rules.active {
if sameRouteForKey(existing, key) {
return existing, rules, true, true
}
}
for _, existing := range rules.inactive {
if sameRouteForKey(existing, key) {
return existing, rules, false, true
}
}
return nil, rules, false, false
}
func (hi *hostIndex) Remove(route *routev1.Route) Changes {
delete(hi.routeToHost, routeKey{namespace: route.Namespace, name: route.Name})
return hi.remove(route, true, nil)
}
func (hi *hostIndex) remove(route *routev1.Route, removeLast bool, changes *routeChanges) *routeChanges {
host := route.Spec.Host
rules, ok := hi.hostToRoute[host]
if !ok {
return nil
}
for i, existing := range rules.active {
if !sameRoute(existing, route) {
continue
}
if changes == nil {
changes = &routeChanges{}
}
rules.removeActive(i, hi.activateFn, changes)
if removeLast && rules.Empty() {
delete(hi.hostToRoute, host)
}
return changes
}
for i, existing := range rules.inactive {
if !sameRoute(existing, route) {
continue
}
rules.removeInactive(i)
if removeLast && rules.Empty() {
delete(hi.hostToRoute, host)
}
return nil
}
return nil
}
func (hi *hostIndex) Filter(fn func(*routev1.Route) (keep bool)) Changes {
changes := &routeChanges{}
for host, rules := range hi.hostToRoute {
changed := false
filtered := rules.active[0:0]
for _, existing := range rules.active {
if fn(existing) {
filtered = append(filtered, existing)
} else {
changed = true
delete(hi.routeToHost, routeKey{namespace: existing.Namespace, name: existing.Name})
}
}
rules.active = filtered
filtered = rules.inactive[0:0]
for _, existing := range rules.inactive {
if fn(existing) {
filtered = append(filtered, existing)
} else {
delete(hi.routeToHost, routeKey{namespace: existing.Namespace, name: existing.Name})
}
}
rules.inactive = filtered
if rules.Empty() {
delete(hi.hostToRoute, host)
continue
}
// we only need to filter if the active routes changed
if !changed {
continue
}
rules.reset(hi.activateFn, changes)
}
return changes
}
func (hi *hostIndex) HostLen() int {
return len(hi.hostToRoute)
}
func (hi *hostIndex) RoutesForHost(host string) ([]*routev1.Route, bool) {
rules, ok := hi.hostToRoute[host]
if !ok {
return nil, false
}
copied := make([]*routev1.Route, len(rules.active))
copy(copied, rules.active)
return copied, true
}
type hostRules struct {
active []*routev1.Route
inactive []*routev1.Route
}
func (r *hostRules) Empty() bool {
return len(r.active) == 0 && len(r.inactive) == 0
}
func (r *hostRules) replace(old, route *routev1.Route) {
for i, existing := range r.active {
if existing == old {
r.active[i] = route
}
}
for i, existing := range r.inactive {
if existing == old {
r.inactive[i] = route
}
}
}
func (r *hostRules) add(route *routev1.Route, fn RouteActivationFunc, changes *routeChanges) {
if len(r.active) == 0 {
changes.Activated(route)
r.active = append(r.active, route)
return
}
active, displaced := fn(changes, r.active, route)
r.active = active
if len(displaced) > 0 {
// if we try to add a route explicitly but it cannot be activated, we should track that.
for _, existing := range displaced {
if existing == route {
changes.Displaced(route)
}
}
r.inactive = append(r.inactive, displaced...)
sort.Slice(r.inactive, func(i, j int) bool { return routeapihelpers.RouteLessThan(r.inactive[i], r.inactive[j]) })
}
}
func (r *hostRules) removeActive(i int, fn RouteActivationFunc, changes *routeChanges) {
r.active = append(r.active[0:i], r.active[i+1:]...)
// attempt to promote all inactive routes
if len(r.active) == 0 || i == 0 {
r.reset(fn, changes)
return
}
}
func (r *hostRules) reset(fn RouteActivationFunc, changes *routeChanges) {
active, displaced := fn(changes, r.active, r.inactive...)
r.active = active
r.inactive = displaced
sort.Slice(r.inactive, func(i, j int) bool { return routeapihelpers.RouteLessThan(r.inactive[i], r.inactive[j]) })
}
func (r *hostRules) removeInactive(i int) {
r.inactive = append(r.inactive[0:i], r.inactive[i+1:]...)
}
type routeChanges struct {
active map[types.UID]*routev1.Route
displace map[types.UID]*routev1.Route
}
func (c *routeChanges) GetActivated() []*routev1.Route {
if c == nil {
return nil
}
arr := make([]*routev1.Route, 0, len(c.active))
for _, existing := range c.active {
arr = append(arr, existing)
}
return arr
}
func (c *routeChanges) GetDisplaced() []*routev1.Route {
if c == nil {
return nil
}
arr := make([]*routev1.Route, 0, len(c.displace))
for _, existing := range c.displace {
arr = append(arr, existing)
}
return arr
}
func (c *routeChanges) Activated(route *routev1.Route) {
if c.active == nil {
c.active = make(map[types.UID]*routev1.Route)
}
c.active[route.UID] = route
delete(c.displace, route.UID)
}
func (c *routeChanges) Displaced(route *routev1.Route) {
if c.displace == nil {
c.displace = make(map[types.UID]*routev1.Route)
}
c.displace[route.UID] = route
delete(c.active, route.UID)
}
|
{
return a.Name == b.Name && a.Namespace == b.Namespace
}
|
add.go
|
/*
Copyright © 2021 SLASHFORMOTION <[email protected]>
*/
package cmd
import (
"fmt"
"github.com/slashformotion/todo/internal"
"github.com/slashformotion/todo/pkg/todo"
"github.com/spf13/cobra"
)
// addCmd represents the add command
var addCmd = &cobra.Command{
Use: "add",
Short: "Add a new task to your .todo file.",
Long: `Example:
$ todo add "fix the ship"
This command will add a new task named "fix the ship" to your .todo file.`,
RunE: func(cmd *cobra.Command, args []string) error {
fmt.Println("add called")
err := actionAdd(FilePath, args[0])
return err
},
}
func init() {
rootCmd.AddCommand(addCmd)
// Here you will define your flags and configuration settings.
// Cobra supports Persistent Flags which will work for this command
// and all subcommands, e.g.:
// addCmd.PersistentFlags().String("foo", "", "A help for foo")
// Cobra supports local flags which will only run when this command
// is called directly, e.g.:
// addCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
func actionAdd(path, name string) error {
|
t, err := internal.GetTodofile(path)
if err != nil {
return err
}
newTask, err := todo.NewTask(name, false)
if err != nil {
return err
}
t.Append(newTask)
err = internal.SaveTodoFile(t)
if err != nil {
return err
}
fmt.Printf("Task %q added, now listing\n\n", newTask.Name)
fmt.Println(t.RenderToScreen())
return nil
}
|
|
listPage.controller.ts
|
import { Endpoints, AddEndpoint } from "@liexp/shared/endpoints";
import { Router } from "express";
import { sequenceS } from "fp-ts/lib/Apply";
import * as TE from "fp-ts/lib/TaskEither";
import { pipe } from "fp-ts/lib/function";
|
export const MakeListPageRoute = (r: Router, ctx: RouteContext): void => {
AddEndpoint(r)(Endpoints.Page.List, ({ query }) => {
return pipe(
sequenceS(TE.taskEither)({
data: ctx.db.find(PageEntity, {
...getORMOptions(query, ctx.env.DEFAULT_PAGE_SIZE),
loadRelationIds: true,
}),
total: ctx.db.count(PageEntity),
}),
TE.map(({ data, total }) => ({
body: {
data: data.map((page) => ({
...page,
type: "PageFrontmatter" as const,
})),
total,
},
statusCode: 200,
}))
);
});
};
|
import { PageEntity } from "../../entities/Page.entity";
import { RouteContext } from "../route.types";
import { getORMOptions } from "@utils/orm.utils";
|
balance.py
|
from mpyc.runtime import mpc
from src.dataset import ObliviousDataset, Sample
from src.output import output
from src.secint import secint as s
from src.forest import train_forest
def sample(ins, out):
return Sample([s(i) for i in ins], s(out))
samples = ObliviousDataset.create(
sample([1, 1, 1, 2], 1),
sample([1, 1, 1, 3], 1),
sample([1, 1, 1, 4], 1),
sample([1, 1, 1, 5], 1),
sample([1, 1, 2, 1], 1),
sample([1, 1, 2, 2], 1),
sample([1, 1, 2, 3], 1),
sample([1, 1, 2, 4], 1),
sample([1, 1, 2, 5], 1),
sample([1, 1, 3, 1], 1),
sample([1, 1, 3, 2], 1),
sample([1, 1, 3, 3], 1),
sample([1, 1, 3, 4], 1),
sample([1, 1, 3, 5], 1),
sample([1, 1, 4, 1], 1),
sample([1, 1, 4, 2], 1),
sample([1, 1, 4, 3], 1),
sample([1, 1, 4, 4], 1),
sample([1, 1, 4, 5], 1),
sample([1, 1, 5, 1], 1),
sample([1, 1, 5, 2], 1),
sample([1, 1, 5, 3], 1),
sample([1, 1, 5, 4], 1),
sample([1, 1, 5, 5], 1),
sample([1, 2, 1, 1], 0),
sample([1, 2, 1, 3], 1),
sample([1, 2, 1, 4], 1),
sample([1, 2, 1, 5], 1),
sample([1, 2, 2, 2], 1),
sample([1, 2, 2, 3], 1),
sample([1, 2, 2, 4], 1),
sample([1, 2, 2, 5], 1),
sample([1, 2, 3, 1], 1),
sample([1, 2, 3, 2], 1),
sample([1, 2, 3, 3], 1),
sample([1, 2, 3, 4], 1),
sample([1, 2, 3, 5], 1),
sample([1, 2, 4, 1], 1),
sample([1, 2, 4, 2], 1),
sample([1, 2, 4, 3], 1),
sample([1, 2, 4, 4], 1),
sample([1, 2, 4, 5], 1),
sample([1, 2, 5, 1], 1),
sample([1, 2, 5, 2], 1),
sample([1, 2, 5, 3], 1),
sample([1, 2, 5, 4], 1),
sample([1, 2, 5, 5], 1),
sample([1, 3, 1, 1], 0),
sample([1, 3, 1, 2], 0),
sample([1, 3, 1, 4], 1),
sample([1, 3, 1, 5], 1),
sample([1, 3, 2, 1], 0),
sample([1, 3, 2, 2], 1),
sample([1, 3, 2, 3], 1),
sample([1, 3, 2, 4], 1),
sample([1, 3, 2, 5], 1),
sample([1, 3, 3, 2], 1),
sample([1, 3, 3, 3], 1),
sample([1, 3, 3, 4], 1),
sample([1, 3, 3, 5], 1),
sample([1, 3, 4, 1], 1),
sample([1, 3, 4, 2], 1),
sample([1, 3, 4, 3], 1),
sample([1, 3, 4, 4], 1),
sample([1, 3, 4, 5], 1),
sample([1, 3, 5, 1], 1),
sample([1, 3, 5, 2], 1),
sample([1, 3, 5, 3], 1),
sample([1, 3, 5, 4], 1),
sample([1, 3, 5, 5], 1),
sample([1, 4, 1, 1], 0),
sample([1, 4, 1, 2], 0),
sample([1, 4, 1, 3], 0),
sample([1, 4, 1, 5], 1),
sample([1, 4, 2, 1], 0),
sample([1, 4, 2, 3], 1),
sample([1, 4, 2, 4], 1),
sample([1, 4, 2, 5], 1),
sample([1, 4, 3, 1], 0),
sample([1, 4, 3, 2], 1),
sample([1, 4, 3, 3], 1),
sample([1, 4, 3, 4], 1),
sample([1, 4, 3, 5], 1),
sample([1, 4, 4, 2], 1),
sample([1, 4, 4, 3], 1),
sample([1, 4, 4, 4], 1),
sample([1, 4, 4, 5], 1),
sample([1, 4, 5, 1], 1),
sample([1, 4, 5, 2], 1),
sample([1, 4, 5, 3], 1),
sample([1, 4, 5, 4], 1),
sample([1, 4, 5, 5], 1),
sample([1, 5, 1, 1], 0),
sample([1, 5, 1, 2], 0),
sample([1, 5, 1, 3], 0),
sample([1, 5, 1, 4], 0),
sample([1, 5, 2, 1], 0),
sample([1, 5, 2, 2], 0),
sample([1, 5, 2, 3], 1),
sample([1, 5, 2, 4], 1),
sample([1, 5, 2, 5], 1),
sample([1, 5, 3, 1], 0),
sample([1, 5, 3, 2], 1),
sample([1, 5, 3, 3], 1),
sample([1, 5, 3, 4], 1),
sample([1, 5, 3, 5], 1),
sample([1, 5, 4, 1], 0),
sample([1, 5, 4, 2], 1),
sample([1, 5, 4, 3], 1),
sample([1, 5, 4, 4], 1),
sample([1, 5, 4, 5], 1),
sample([1, 5, 5, 2], 1),
sample([1, 5, 5, 3], 1),
sample([1, 5, 5, 4], 1),
sample([1, 5, 5, 5], 1),
sample([2, 1, 1, 1], 0),
sample([2, 1, 1, 3], 1),
sample([2, 1, 1, 4], 1),
sample([2, 1, 1, 5], 1),
sample([2, 1, 2, 2], 1),
sample([2, 1, 2, 3], 1),
sample([2, 1, 2, 4], 1),
sample([2, 1, 2, 5], 1),
sample([2, 1, 3, 1], 1),
sample([2, 1, 3, 2], 1),
sample([2, 1, 3, 3], 1),
sample([2, 1, 3, 4], 1),
sample([2, 1, 3, 5], 1),
sample([2, 1, 4, 1], 1),
sample([2, 1, 4, 2], 1),
sample([2, 1, 4, 3], 1),
sample([2, 1, 4, 4], 1),
sample([2, 1, 4, 5], 1),
sample([2, 1, 5, 1], 1),
sample([2, 1, 5, 2], 1),
sample([2, 1, 5, 3], 1),
sample([2, 1, 5, 4], 1),
sample([2, 1, 5, 5], 1),
sample([2, 2, 1, 1], 0),
sample([2, 2, 1, 2], 0),
sample([2, 2, 1, 3], 0),
sample([2, 2, 1, 5], 1),
sample([2, 2, 2, 1], 0),
sample([2, 2, 2, 3], 1),
sample([2, 2, 2, 4], 1),
sample([2, 2, 2, 5], 1),
sample([2, 2, 3, 1], 0),
sample([2, 2, 3, 2], 1),
sample([2, 2, 3, 3], 1),
sample([2, 2, 3, 4], 1),
sample([2, 2, 3, 5], 1),
sample([2, 2, 4, 2], 1),
sample([2, 2, 4, 3], 1),
sample([2, 2, 4, 4], 1),
sample([2, 2, 4, 5], 1),
sample([2, 2, 5, 1], 1),
sample([2, 2, 5, 2], 1),
sample([2, 2, 5, 3], 1),
sample([2, 2, 5, 4], 1),
sample([2, 2, 5, 5], 1),
sample([2, 3, 1, 1], 0),
sample([2, 3, 1, 2], 0),
sample([2, 3, 1, 3], 0),
sample([2, 3, 1, 4], 0),
sample([2, 3, 1, 5], 0),
sample([2, 3, 2, 1], 0),
sample([2, 3, 2, 2], 0),
sample([2, 3, 2, 4], 1),
sample([2, 3, 2, 5], 1),
sample([2, 3, 3, 1], 0),
sample([2, 3, 3, 3], 1),
sample([2, 3, 3, 4], 1),
sample([2, 3, 3, 5], 1),
sample([2, 3, 4, 1], 0),
sample([2, 3, 4, 2], 1),
sample([2, 3, 4, 3], 1),
sample([2, 3, 4, 4], 1),
sample([2, 3, 4, 5], 1),
sample([2, 3, 5, 1], 0),
sample([2, 3, 5, 2], 1),
sample([2, 3, 5, 3], 1),
sample([2, 3, 5, 4], 1),
sample([2, 3, 5, 5], 1),
sample([2, 4, 1, 1], 0),
sample([2, 4, 1, 2], 0),
sample([2, 4, 1, 3], 0),
sample([2, 4, 1, 4], 0),
sample([2, 4, 1, 5], 0),
sample([2, 4, 2, 1], 0),
sample([2, 4, 2, 2], 0),
sample([2, 4, 2, 3], 0),
sample([2, 4, 2, 5], 1),
sample([2, 4, 3, 1], 0),
sample([2, 4, 3, 2], 0),
sample([2, 4, 3, 3], 1),
sample([2, 4, 3, 4], 1),
sample([2, 4, 3, 5], 1),
sample([2, 4, 4, 1], 0),
sample([2, 4, 4, 3], 1),
sample([2, 4, 4, 4], 1),
sample([2, 4, 4, 5], 1),
sample([2, 4, 5, 1], 0),
sample([2, 4, 5, 2], 1),
sample([2, 4, 5, 3], 1),
sample([2, 4, 5, 4], 1),
sample([2, 4, 5, 5], 1),
sample([2, 5, 1, 1], 0),
sample([2, 5, 1, 2], 0),
sample([2, 5, 1, 3], 0),
sample([2, 5, 1, 4], 0),
sample([2, 5, 1, 5], 0),
sample([2, 5, 2, 1], 0),
sample([2, 5, 2, 2], 0),
sample([2, 5, 2, 3], 0),
sample([2, 5, 2, 4], 0),
sample([2, 5, 3, 1], 0),
sample([2, 5, 3, 2], 0),
sample([2, 5, 3, 3], 0),
sample([2, 5, 3, 4], 1),
sample([2, 5, 3, 5], 1),
sample([2, 5, 4, 1], 0),
sample([2, 5, 4, 2], 0),
sample([2, 5, 4, 3], 1),
sample([2, 5, 4, 4], 1),
sample([2, 5, 4, 5], 1),
sample([2, 5, 5, 1], 0),
sample([2, 5, 5, 3], 1),
sample([2, 5, 5, 4], 1),
sample([2, 5, 5, 5], 1),
sample([3, 1, 1, 1], 0),
sample([3, 1, 1, 2], 0),
sample([3, 1, 1, 4], 1),
sample([3, 1, 1, 5], 1),
sample([3, 1, 2, 1], 0),
sample([3, 1, 2, 2], 1),
sample([3, 1, 2, 3], 1),
sample([3, 1, 2, 4], 1),
sample([3, 1, 2, 5], 1),
sample([3, 1, 3, 2], 1),
sample([3, 1, 3, 3], 1),
sample([3, 1, 3, 4], 1),
sample([3, 1, 3, 5], 1),
sample([3, 1, 4, 1], 1),
sample([3, 1, 4, 2], 1),
sample([3, 1, 4, 3], 1),
sample([3, 1, 4, 4], 1),
sample([3, 1, 4, 5], 1),
sample([3, 1, 5, 1], 1),
sample([3, 1, 5, 2], 1),
sample([3, 1, 5, 3], 1),
sample([3, 1, 5, 4], 1),
sample([3, 1, 5, 5], 1),
sample([3, 2, 1, 1], 0),
sample([3, 2, 1, 2], 0),
sample([3, 2, 1, 3], 0),
sample([3, 2, 1, 4], 0),
sample([3, 2, 1, 5], 0),
sample([3, 2, 2, 1], 0),
sample([3, 2, 2, 2], 0),
sample([3, 2, 2, 4], 1),
sample([3, 2, 2, 5], 1),
sample([3, 2, 3, 1], 0),
sample([3, 2, 3, 3], 1),
sample([3, 2, 3, 4], 1),
sample([3, 2, 3, 5], 1),
sample([3, 2, 4, 1], 0),
sample([3, 2, 4, 2], 1),
sample([3, 2, 4, 3], 1),
sample([3, 2, 4, 4], 1),
sample([3, 2, 4, 5], 1),
sample([3, 2, 5, 1], 0),
sample([3, 2, 5, 2], 1),
sample([3, 2, 5, 3], 1),
sample([3, 2, 5, 4], 1),
sample([3, 2, 5, 5], 1),
sample([3, 3, 1, 1], 0),
sample([3, 3, 1, 2], 0),
sample([3, 3, 1, 3], 0),
sample([3, 3, 1, 4], 0),
sample([3, 3, 1, 5], 0),
sample([3, 3, 2, 1], 0),
sample([3, 3, 2, 2], 0),
sample([3, 3, 2, 3], 0),
sample([3, 3, 2, 4], 0),
sample([3, 3, 2, 5], 1),
sample([3, 3, 3, 1], 0),
sample([3, 3, 3, 2], 0),
sample([3, 3, 3, 4], 1),
sample([3, 3, 3, 5], 1),
sample([3, 3, 4, 1], 0),
sample([3, 3, 4, 2], 0),
sample([3, 3, 4, 3], 1),
sample([3, 3, 4, 4], 1),
sample([3, 3, 4, 5], 1),
sample([3, 3, 5, 1], 0),
sample([3, 3, 5, 2], 1),
sample([3, 3, 5, 3], 1),
sample([3, 3, 5, 4], 1),
sample([3, 3, 5, 5], 1),
sample([3, 4, 1, 1], 0),
sample([3, 4, 1, 2], 0),
sample([3, 4, 1, 3], 0),
sample([3, 4, 1, 4], 0),
sample([3, 4, 1, 5], 0),
sample([3, 4, 2, 1], 0),
sample([3, 4, 2, 2], 0),
sample([3, 4, 2, 3], 0),
sample([3, 4, 2, 4], 0),
sample([3, 4, 2, 5], 0),
sample([3, 4, 3, 1], 0),
sample([3, 4, 3, 2], 0),
sample([3, 4, 3, 3], 0),
sample([3, 4, 3, 5], 1),
sample([3, 4, 4, 1], 0),
sample([3, 4, 4, 2], 0),
sample([3, 4, 4, 4], 1),
sample([3, 4, 4, 5], 1),
sample([3, 4, 5, 1], 0),
sample([3, 4, 5, 2], 0),
sample([3, 4, 5, 3], 1),
sample([3, 4, 5, 4], 1),
sample([3, 4, 5, 5], 1),
sample([3, 5, 1, 1], 0),
sample([3, 5, 1, 2], 0),
sample([3, 5, 1, 3], 0),
sample([3, 5, 1, 4], 0),
sample([3, 5, 1, 5], 0),
sample([3, 5, 2, 1], 0),
sample([3, 5, 2, 2], 0),
sample([3, 5, 2, 3], 0),
sample([3, 5, 2, 4], 0),
sample([3, 5, 2, 5], 0),
sample([3, 5, 3, 1], 0),
sample([3, 5, 3, 2], 0),
sample([3, 5, 3, 3], 0),
sample([3, 5, 3, 4], 0),
sample([3, 5, 4, 1], 0),
sample([3, 5, 4, 2], 0),
sample([3, 5, 4, 3], 0),
sample([3, 5, 4, 4], 1),
sample([3, 5, 4, 5], 1),
sample([3, 5, 5, 1], 0),
sample([3, 5, 5, 2], 0),
sample([3, 5, 5, 4], 1),
sample([3, 5, 5, 5], 1),
sample([4, 1, 1, 1], 0),
sample([4, 1, 1, 2], 0),
sample([4, 1, 1, 3], 0),
sample([4, 1, 1, 5], 1),
sample([4, 1, 2, 1], 0),
sample([4, 1, 2, 3], 1),
sample([4, 1, 2, 4], 1),
sample([4, 1, 2, 5], 1),
sample([4, 1, 3, 1], 0),
sample([4, 1, 3, 2], 1),
sample([4, 1, 3, 3], 1),
sample([4, 1, 3, 4], 1),
sample([4, 1, 3, 5], 1),
sample([4, 1, 4, 2], 1),
sample([4, 1, 4, 3], 1),
sample([4, 1, 4, 4], 1),
sample([4, 1, 4, 5], 1),
sample([4, 1, 5, 1], 1),
sample([4, 1, 5, 2], 1),
sample([4, 1, 5, 3], 1),
sample([4, 1, 5, 4], 1),
sample([4, 1, 5, 5], 1),
sample([4, 2, 1, 1], 0),
sample([4, 2, 1, 2], 0),
sample([4, 2, 1, 3], 0),
sample([4, 2, 1, 4], 0),
sample([4, 2, 1, 5], 0),
sample([4, 2, 2, 1], 0),
sample([4, 2, 2, 2], 0),
sample([4, 2, 2, 3], 0),
sample([4, 2, 2, 5], 1),
sample([4, 2, 3, 1], 0),
sample([4, 2, 3, 2], 0),
sample([4, 2, 3, 3], 1),
sample([4, 2, 3, 4], 1),
sample([4, 2, 3, 5], 1),
sample([4, 2, 4, 1], 0),
sample([4, 2, 4, 3], 1),
sample([4, 2, 4, 4], 1),
sample([4, 2, 4, 5], 1),
sample([4, 2, 5, 1], 0),
sample([4, 2, 5, 2], 1),
sample([4, 2, 5, 3], 1),
sample([4, 2, 5, 4], 1),
sample([4, 2, 5, 5], 1),
sample([4, 3, 1, 1], 0),
sample([4, 3, 1, 2], 0),
sample([4, 3, 1, 3], 0),
sample([4, 3, 1, 4], 0),
sample([4, 3, 1, 5], 0),
sample([4, 3, 2, 1], 0),
sample([4, 3, 2, 2], 0),
sample([4, 3, 2, 3], 0),
sample([4, 3, 2, 4], 0),
sample([4, 3, 2, 5], 0),
sample([4, 3, 3, 1], 0),
sample([4, 3, 3, 2], 0),
sample([4, 3, 3, 3], 0),
sample([4, 3, 3, 5], 1),
sample([4, 3, 4, 1], 0),
sample([4, 3, 4, 2], 0),
sample([4, 3, 4, 4], 1),
sample([4, 3, 4, 5], 1),
sample([4, 3, 5, 1], 0),
sample([4, 3, 5, 2], 0),
sample([4, 3, 5, 3], 1),
sample([4, 3, 5, 4], 1),
sample([4, 3, 5, 5], 1),
sample([4, 4, 1, 1], 0),
sample([4, 4, 1, 2], 0),
sample([4, 4, 1, 3], 0),
sample([4, 4, 1, 4], 0),
sample([4, 4, 1, 5], 0),
sample([4, 4, 2, 1], 0),
sample([4, 4, 2, 2], 0),
sample([4, 4, 2, 3], 0),
sample([4, 4, 2, 4], 0),
sample([4, 4, 2, 5], 0),
sample([4, 4, 3, 1], 0),
sample([4, 4, 3, 2], 0),
sample([4, 4, 3, 3], 0),
sample([4, 4, 3, 4], 0),
sample([4, 4, 3, 5], 0),
sample([4, 4, 4, 1], 0),
sample([4, 4, 4, 2], 0),
sample([4, 4, 4, 3], 0),
sample([4, 4, 4, 5], 1),
sample([4, 4, 5, 1], 0),
sample([4, 4, 5, 2], 0),
sample([4, 4, 5, 3], 0),
sample([4, 4, 5, 4], 1),
sample([4, 4, 5, 5], 1),
sample([4, 5, 1, 1], 0),
sample([4, 5, 1, 2], 0),
sample([4, 5, 1, 3], 0),
sample([4, 5, 1, 4], 0),
sample([4, 5, 1, 5], 0),
sample([4, 5, 2, 1], 0),
sample([4, 5, 2, 2], 0),
sample([4, 5, 2, 3], 0),
sample([4, 5, 2, 4], 0),
sample([4, 5, 2, 5], 0),
sample([4, 5, 3, 1], 0),
sample([4, 5, 3, 2], 0),
sample([4, 5, 3, 3], 0),
sample([4, 5, 3, 4], 0),
sample([4, 5, 3, 5], 0),
sample([4, 5, 4, 1], 0),
sample([4, 5, 4, 2], 0),
sample([4, 5, 4, 3], 0),
sample([4, 5, 4, 4], 0),
sample([4, 5, 5, 1], 0),
sample([4, 5, 5, 2], 0),
sample([4, 5, 5, 3], 0),
sample([4, 5, 5, 5], 1),
sample([5, 1, 1, 1], 0),
sample([5, 1, 1, 2], 0),
sample([5, 1, 1, 3], 0),
sample([5, 1, 1, 4], 0),
sample([5, 1, 2, 1], 0),
sample([5, 1, 2, 2], 0),
sample([5, 1, 2, 3], 1),
sample([5, 1, 2, 4], 1),
sample([5, 1, 2, 5], 1),
sample([5, 1, 3, 1], 0),
sample([5, 1, 3, 2], 1),
sample([5, 1, 3, 3], 1),
sample([5, 1, 3, 4], 1),
sample([5, 1, 3, 5], 1),
sample([5, 1, 4, 1], 0),
sample([5, 1, 4, 2], 1),
sample([5, 1, 4, 3], 1),
sample([5, 1, 4, 4], 1),
sample([5, 1, 4, 5], 1),
sample([5, 1, 5, 2], 1),
sample([5, 1, 5, 3], 1),
sample([5, 1, 5, 4], 1),
sample([5, 1, 5, 5], 1),
sample([5, 2, 1, 1], 0),
sample([5, 2, 1, 2], 0),
sample([5, 2, 1, 3], 0),
sample([5, 2, 1, 4], 0),
|
sample([5, 2, 1, 5], 0),
sample([5, 2, 2, 1], 0),
sample([5, 2, 2, 2], 0),
sample([5, 2, 2, 3], 0),
sample([5, 2, 2, 4], 0),
sample([5, 2, 3, 1], 0),
sample([5, 2, 3, 2], 0),
sample([5, 2, 3, 3], 0),
sample([5, 2, 3, 4], 1),
sample([5, 2, 3, 5], 1),
sample([5, 2, 4, 1], 0),
sample([5, 2, 4, 2], 0),
sample([5, 2, 4, 3], 1),
sample([5, 2, 4, 4], 1),
sample([5, 2, 4, 5], 1),
sample([5, 2, 5, 1], 0),
sample([5, 2, 5, 3], 1),
sample([5, 2, 5, 4], 1),
sample([5, 2, 5, 5], 1),
sample([5, 3, 1, 1], 0),
sample([5, 3, 1, 2], 0),
sample([5, 3, 1, 3], 0),
sample([5, 3, 1, 4], 0),
sample([5, 3, 1, 5], 0),
sample([5, 3, 2, 1], 0),
sample([5, 3, 2, 2], 0),
sample([5, 3, 2, 3], 0),
sample([5, 3, 2, 4], 0),
sample([5, 3, 2, 5], 0),
sample([5, 3, 3, 1], 0),
sample([5, 3, 3, 2], 0),
sample([5, 3, 3, 3], 0),
sample([5, 3, 3, 4], 0),
sample([5, 3, 4, 1], 0),
sample([5, 3, 4, 2], 0),
sample([5, 3, 4, 3], 0),
sample([5, 3, 4, 4], 1),
sample([5, 3, 4, 5], 1),
sample([5, 3, 5, 1], 0),
sample([5, 3, 5, 2], 0),
sample([5, 3, 5, 4], 1),
sample([5, 3, 5, 5], 1),
sample([5, 4, 1, 1], 0),
sample([5, 4, 1, 2], 0),
sample([5, 4, 1, 3], 0),
sample([5, 4, 1, 4], 0),
sample([5, 4, 1, 5], 0),
sample([5, 4, 2, 1], 0),
sample([5, 4, 2, 2], 0),
sample([5, 4, 2, 3], 0),
sample([5, 4, 2, 4], 0),
sample([5, 4, 2, 5], 0),
sample([5, 4, 3, 1], 0),
sample([5, 4, 3, 2], 0),
sample([5, 4, 3, 3], 0),
sample([5, 4, 3, 4], 0),
sample([5, 4, 3, 5], 0),
sample([5, 4, 4, 1], 0),
sample([5, 4, 4, 2], 0),
sample([5, 4, 4, 3], 0),
sample([5, 4, 4, 4], 0),
sample([5, 4, 5, 1], 0),
sample([5, 4, 5, 2], 0),
sample([5, 4, 5, 3], 0),
sample([5, 4, 5, 5], 1),
sample([5, 5, 1, 1], 0),
sample([5, 5, 1, 2], 0),
sample([5, 5, 1, 3], 0),
sample([5, 5, 1, 4], 0),
sample([5, 5, 1, 5], 0),
sample([5, 5, 2, 1], 0),
sample([5, 5, 2, 2], 0),
sample([5, 5, 2, 3], 0),
sample([5, 5, 2, 4], 0),
sample([5, 5, 2, 5], 0),
sample([5, 5, 3, 1], 0),
sample([5, 5, 3, 2], 0),
sample([5, 5, 3, 3], 0),
sample([5, 5, 3, 4], 0),
sample([5, 5, 3, 5], 0),
sample([5, 5, 4, 1], 0),
sample([5, 5, 4, 2], 0),
sample([5, 5, 4, 3], 0),
sample([5, 5, 4, 4], 0),
sample([5, 5, 4, 5], 0),
sample([5, 5, 5, 1], 0),
sample([5, 5, 5, 2], 0),
sample([5, 5, 5, 3], 0),
sample([5, 5, 5, 4], 0),
continuous=[True, True, True, True]
)
async def main():
async with mpc:
forest = await output(await train_forest(samples, amount=2, depth=4))
for index, tree in enumerate(forest):
print(f"Tree #{index}")
tree.pretty_print()
if __name__ == '__main__':
mpc.run(main())
| |
QueryBuilder.ts
|
import { getPath } from 'ts-object-path';
import {
IQueryBuilder,
IFireOrmQueryLine,
IOrderByParams,
IFirestoreVal,
FirestoreOperators,
IQueryExecutor,
IEntity,
IWherePropParam,
} from './types';
export default class QueryBuilder<T extends IEntity> implements IQueryBuilder<T> {
protected queries: Array<IFireOrmQueryLine> = [];
protected limitVal: number;
protected orderByObj: IOrderByParams;
constructor(protected executor: IQueryExecutor<T>) {}
private extractWhereParam = (param: IWherePropParam<T>) => {
if (typeof param === 'string') return param;
return getPath<T, (t: T) => unknown>(param).join('.');
};
whereEqualTo(param: IWherePropParam<T>, val: IFirestoreVal): QueryBuilder<T> {
this.queries.push({
prop: this.extractWhereParam(param),
val,
operator: FirestoreOperators.equal,
});
return this;
}
whereGreaterThan(prop: IWherePropParam<T>, val: IFirestoreVal): QueryBuilder<T> {
this.queries.push({
prop: this.extractWhereParam(prop),
val,
operator: FirestoreOperators.greaterThan,
});
return this;
}
whereGreaterOrEqualThan(prop: IWherePropParam<T>, val: IFirestoreVal): QueryBuilder<T> {
this.queries.push({
prop: this.extractWhereParam(prop),
val,
operator: FirestoreOperators.greaterThanEqual,
});
return this;
}
whereLessThan(prop: IWherePropParam<T>, val: IFirestoreVal): QueryBuilder<T> {
this.queries.push({
prop: this.extractWhereParam(prop),
val,
operator: FirestoreOperators.lessThan,
});
return this;
}
whereLessOrEqualThan(prop: IWherePropParam<T>, val: IFirestoreVal): QueryBuilder<T> {
this.queries.push({
prop: this.extractWhereParam(prop),
val,
operator: FirestoreOperators.lessThanEqual,
});
return this;
}
whereArrayContains(prop: IWherePropParam<T>, val: IFirestoreVal): QueryBuilder<T> {
this.queries.push({
prop: this.extractWhereParam(prop),
val,
operator: FirestoreOperators.arrayContains,
});
return this;
}
whereArrayContainsAny(prop: IWherePropParam<T>, val: IFirestoreVal[]): QueryBuilder<T> {
if (val.length > 10) {
throw new Error(`
This query supports up to 10 values. You provided ${val.length}.
For details please visit: https://firebase.google.com/docs/firestore/query-data/queries#in_and_array-contains-any
`);
}
this.queries.push({
prop: this.extractWhereParam(prop),
val,
operator: FirestoreOperators.arrayContainsAny,
});
return this;
}
whereIn(prop: IWherePropParam<T>, val: IFirestoreVal[]): QueryBuilder<T> {
if (val.length > 10) {
throw new Error(`
This query supports up to 10 values. You provided ${val.length}.
For details please visit: https://firebase.google.com/docs/firestore/query-data/queries#in_and_array-contains-any
`);
}
this.queries.push({
prop: this.extractWhereParam(prop),
val,
operator: FirestoreOperators.in,
});
return this;
}
limit(limitVal: number): QueryBuilder<T> {
if (this.limitVal) {
throw new Error(
'A limit function cannot be called more than once in the same query expression'
);
}
this.limitVal = limitVal;
return this;
}
orderByAscending(prop: IWherePropParam<T>): QueryBuilder<T> {
if (this.orderByObj) {
throw new Error(
'An orderBy function cannot be called more than once in the same query expression'
);
}
this.orderByObj = {
fieldPath: this.extractWhereParam(prop),
directionStr: 'asc',
};
return this;
}
orderByDescending(prop: IWherePropParam<T>): QueryBuilder<T> {
if (this.orderByObj) {
throw new Error(
'An orderBy function cannot be called more than once in the same query expression'
);
}
this.orderByObj = {
fieldPath: this.extractWhereParam(prop),
directionStr: 'desc',
};
return this;
}
find(): Promise<T[]> {
|
return this.executor.execute(this.queries, this.limitVal, this.orderByObj);
}
async findOne(): Promise<T | null> {
const queryResult = await this.executor.execute(
this.queries,
this.limitVal,
this.orderByObj,
true
);
return queryResult.length ? queryResult[0] : null;
}
}
| |
sync_manager.rs
|
// Copyright (c) The Dijets Core Contributors
// SPDX-License-Identifier: Apache-2.0
use crate::{
block_storage::{BlockReader, BlockStore},
logging::{LogEvent, LogSchema},
network::NetworkSender,
network_interface::ConsensusMsg,
persistent_liveness_storage::{PersistentLivenessStorage, RecoveryData},
state_replication::StateComputer,
};
use anyhow::{bail, format_err};
use consensus_types::{
block::Block,
block_retrieval::{BlockRetrievalRequest, BlockRetrievalStatus, MAX_BLOCKS_PER_REQUEST},
common::Author,
quorum_cert::QuorumCert,
sync_info::SyncInfo,
};
use dijets_crypto::HashValue;
use dijets_logger::prelude::*;
use dijets_types::{
account_address::AccountAddress, epoch_change::EpochChangeProof,
ledger_info::LedgerInfoWithSignatures,
};
use mirai_annotations::checked_precondition;
use rand::{prelude::*, Rng};
use std::{clone::Clone, cmp::min, sync::Arc, time::Duration};
#[derive(Debug, PartialEq)]
/// Whether we need to do block retrieval if we want to insert a Quorum Cert.
pub enum NeedFetchResult {
QCRoundBeforeRoot,
QCAlreadyExist,
QCBlockExist,
NeedFetch,
}
impl BlockStore {
/// Check if we're far away from this ledger info and need to sync.
/// Returns false if we have this block in the tree or the root's round is higher than the
/// block.
pub fn
|
(
&self,
qc: &QuorumCert,
li: &LedgerInfoWithSignatures,
) -> bool {
// This precondition ensures that the check in the following lines
// does not result in an addition overflow.
checked_precondition!(self.commit_root().round() < std::u64::MAX - 1);
// If we have the block locally, we're not far from this QC thus don't need to sync.
// In case root().round() is greater than that the committed
// block carried by LI is older than my current commit.
!(self.block_exists(qc.commit_info().id())
|| self.commit_root().round() >= li.commit_info().round())
}
/// Checks if quorum certificate can be inserted in block store without RPC
/// Returns the enum to indicate the detailed status.
pub fn need_fetch_for_quorum_cert(&self, qc: &QuorumCert) -> NeedFetchResult {
if qc.certified_block().round() < self.ordered_root().round() {
return NeedFetchResult::QCRoundBeforeRoot;
}
if self
.get_quorum_cert_for_block(qc.certified_block().id())
.is_some()
{
return NeedFetchResult::QCAlreadyExist;
}
if self.block_exists(qc.certified_block().id()) {
return NeedFetchResult::QCBlockExist;
}
NeedFetchResult::NeedFetch
}
/// Fetches dependencies for given sync_info.quorum_cert
/// If gap is large, performs state sync using sync_to_highest_ordered_cert
/// Inserts sync_info.quorum_cert into block store as the last step
pub async fn add_certs(
&self,
sync_info: &SyncInfo,
mut retriever: BlockRetriever,
) -> anyhow::Result<()> {
self.sync_to_highest_ordered_cert(
sync_info.highest_ordered_cert().clone(),
sync_info.highest_ledger_info().clone(),
&mut retriever,
)
.await?;
self.insert_quorum_cert(sync_info.highest_ordered_cert(), &mut retriever)
.await?;
self.insert_quorum_cert(sync_info.highest_quorum_cert(), &mut retriever)
.await?;
if let Some(tc) = sync_info.highest_timeout_certificate() {
self.insert_timeout_certificate(Arc::new(tc.clone()))?;
}
Ok(())
}
pub async fn insert_quorum_cert(
&self,
qc: &QuorumCert,
retriever: &mut BlockRetriever,
) -> anyhow::Result<()> {
match self.need_fetch_for_quorum_cert(qc) {
NeedFetchResult::NeedFetch => self.fetch_quorum_cert(qc.clone(), retriever).await?,
NeedFetchResult::QCBlockExist => self.insert_single_quorum_cert(qc.clone())?,
_ => (),
}
if self.ordered_root().round() < qc.commit_info().round() {
let finality_proof = qc.ledger_info();
self.commit(finality_proof.clone()).await?;
if qc.ends_epoch() {
retriever
.network
.broadcast(ConsensusMsg::EpochChangeProof(Box::new(
EpochChangeProof::new(
vec![finality_proof.clone()],
/* more = */ false,
),
)))
.await;
}
}
Ok(())
}
/// Insert the quorum certificate separately from the block, used to split the processing of
/// updating the consensus state(with qc) and deciding whether to vote(with block)
/// The missing ancestors are going to be retrieved from the given peer. If a given peer
/// fails to provide the missing ancestors, the qc is not going to be added.
async fn fetch_quorum_cert(
&self,
qc: QuorumCert,
retriever: &mut BlockRetriever,
) -> anyhow::Result<()> {
let mut pending = vec![];
let mut retrieve_qc = qc.clone();
loop {
if self.block_exists(retrieve_qc.certified_block().id()) {
break;
}
let mut blocks = retriever.retrieve_block_for_qc(&retrieve_qc, 1).await?;
// retrieve_block_for_qc guarantees that blocks has exactly 1 element
let block = blocks.remove(0);
retrieve_qc = block.quorum_cert().clone();
pending.push(block);
}
// insert the qc <- block pair
while let Some(block) = pending.pop() {
let block_qc = block.quorum_cert().clone();
self.insert_single_quorum_cert(block_qc)?;
self.execute_and_insert_block(block)?;
}
self.insert_single_quorum_cert(qc)
}
/// Check the highest commit cert sent by peer to see if we're behind and start a fast
/// forward sync if the committed block doesn't exist in our tree.
/// It works as follows:
/// 1. request the committed 3-chain from the peer, if C2 is the highest_commit_cert
/// we request for B0 <- C0 <- B1 <- C1 <- B2 (<- C2)
/// 2. We persist the 3-chain to storage before start sync to ensure we could restart if we
/// crash in the middle of the sync.
/// 3. We prune the old tree and replace with a new tree built with the 3-chain.
async fn sync_to_highest_ordered_cert(
&self,
highest_ordered_cert: QuorumCert,
highest_ledger_info: LedgerInfoWithSignatures,
retriever: &mut BlockRetriever,
) -> anyhow::Result<()> {
if !self.need_sync_for_quorum_cert(&highest_ordered_cert, &highest_ledger_info) {
return Ok(());
}
let (root, root_metadata, blocks, quorum_certs) = Self::fast_forward_sync(
&highest_ordered_cert,
highest_ledger_info.clone(),
retriever,
self.storage.clone(),
self.state_computer.clone(),
)
.await?
.take();
debug!(
LogSchema::new(LogEvent::CommitViaSync).round(self.ordered_root().round()),
committed_round = root.0.round(),
block_id = root.0.id(),
);
self.rebuild(root, root_metadata, blocks, quorum_certs)
.await;
if highest_ledger_info.ledger_info().ends_epoch() {
retriever
.network
.notify_epoch_change(EpochChangeProof::new(
vec![highest_ordered_cert.ledger_info().clone()],
/* more = */ false,
))
.await;
}
Ok(())
}
pub async fn fast_forward_sync<'a>(
highest_ordered_cert: &'a QuorumCert,
highest_ledger_info: LedgerInfoWithSignatures,
retriever: &'a mut BlockRetriever,
storage: Arc<dyn PersistentLivenessStorage>,
state_computer: Arc<dyn StateComputer>,
) -> anyhow::Result<RecoveryData> {
debug!(
LogSchema::new(LogEvent::StateSync).remote_peer(retriever.preferred_peer),
"Start state sync with peer to block: {}",
highest_ordered_cert.commit_info(),
);
// we fetch the blocks from
let num_blocks = highest_ordered_cert.certified_block().round()
- highest_ledger_info.ledger_info().round()
+ 1;
let blocks = retriever
.retrieve_block_for_qc(highest_ordered_cert, num_blocks)
.await?;
assert_eq!(
blocks.first().expect("should have at least 3-chain").id(),
highest_ordered_cert.certified_block().id(),
);
assert_eq!(
blocks.last().expect("should have at least 3-chain").id(),
highest_ledger_info.commit_info().id(),
);
// although unlikely, we might wrap num_blocks around on a 32-bit machine
assert!(num_blocks < std::usize::MAX as u64);
let mut quorum_certs = vec![highest_ordered_cert.clone()];
quorum_certs.extend(
blocks
.iter()
.take(num_blocks as usize - 1)
.map(|block| block.quorum_cert().clone()),
);
for (i, block) in blocks.iter().enumerate() {
assert_eq!(block.id(), quorum_certs[i].certified_block().id());
}
// If a node restarts in the middle of state synchronization, it is going to try to catch up
// to the stored quorum certs as the new root.
storage.save_tree(blocks.clone(), quorum_certs.clone())?;
state_computer.sync_to(highest_ledger_info).await?;
// we do not need to update block_tree.highest_commit_decision_ledger_info here
// because the block_tree is going to rebuild itself.
let recovery_data = storage
.start()
.expect_recovery_data("Failed to construct recovery data after fast forward sync");
Ok(recovery_data)
}
}
/// BlockRetriever is used internally to retrieve blocks
pub struct BlockRetriever {
network: NetworkSender,
preferred_peer: Author,
}
impl BlockRetriever {
pub fn new(network: NetworkSender, preferred_peer: Author) -> Self {
Self {
network,
preferred_peer,
}
}
/// Retrieve n blocks for given block_id from peers
///
/// Returns Result with Vec that has a guaranteed size of num_blocks
/// This guarantee is based on BlockRetrievalResponse::verify that ensures that number of
/// blocks in response is equal to number of blocks requested. This method will
/// continue until the quorum certificate members all fail to return the missing chain.
///
/// The first attempt of block retrieval will always be sent to preferred_peer to allow the
/// leader to drive quorum certificate creation The other peers from the quorum certificate
/// will be randomly tried next. If all members of the quorum certificate are exhausted, an
/// error is returned
async fn retrieve_block_for_id(
&mut self,
block_id: HashValue,
peers: &mut Vec<&AccountAddress>,
num_blocks: u64,
) -> anyhow::Result<Vec<Block>> {
let mut attempt = 0_u32;
let mut progress = 0;
let mut last_block_id = block_id;
let mut result_blocks: Vec<Block> = vec![];
let mut retrieve_batch_size = MAX_BLOCKS_PER_REQUEST;
if peers.is_empty() {
bail!(
"Failed to fetch block {} in {} attempts: no more peers available",
block_id,
attempt
);
}
let mut peer = self.pick_peer(attempt, peers);
while progress < num_blocks {
// in case this is the last retrieval
retrieve_batch_size = min(retrieve_batch_size, num_blocks - progress);
attempt += 1;
debug!(
LogSchema::new(LogEvent::RetrieveBlock).remote_peer(peer),
block_id = block_id,
"Fetching {} blocks, attempt {}",
retrieve_batch_size,
attempt
);
let response = self
.network
.request_block(
BlockRetrievalRequest::new(last_block_id, retrieve_batch_size),
peer,
retrieval_timeout(attempt),
)
.await;
match response.and_then(|result| {
if result.status() == BlockRetrievalStatus::Succeeded {
Ok(result.blocks().clone())
} else {
Err(format_err!("{:?}", result.status()))
}
}) {
Ok(batch) => {
// extend the result blocks
progress += batch.len() as u64;
last_block_id = batch.last().unwrap().parent_id();
result_blocks.extend(batch);
}
Err(e) => {
warn!(
remote_peer = peer,
block_id = block_id,
error = ?e, "Failed to fetch block, trying another peer",
);
// select next peer to try
if peers.is_empty() {
bail!(
"Failed to fetch block {} in {} attempts: no more peers available",
block_id,
attempt
);
}
peer = self.pick_peer(attempt, peers);
}
}
}
assert_eq!(result_blocks.len() as u64, num_blocks);
Ok(result_blocks)
}
/// Retrieve chain of n blocks for given QC
async fn retrieve_block_for_qc<'a>(
&'a mut self,
qc: &'a QuorumCert,
num_blocks: u64,
) -> anyhow::Result<Vec<Block>> {
let mut peers = qc
.ledger_info()
.signatures()
.keys()
.collect::<Vec<&AccountAddress>>();
self.retrieve_block_for_id(qc.certified_block().id(), &mut peers, num_blocks)
.await
}
fn pick_peer(&self, attempt: u32, peers: &mut Vec<&AccountAddress>) -> AccountAddress {
assert!(!peers.is_empty(), "pick_peer on empty peer list");
if attempt == 0 {
// remove preferred_peer if its in list of peers
// (strictly speaking it is not required to be there)
for i in 0..peers.len() {
if *peers[i] == self.preferred_peer {
peers.remove(i);
break;
}
}
return self.preferred_peer;
}
let peer_idx = thread_rng().gen_range(0..peers.len());
*peers.remove(peer_idx)
}
}
// Max timeout is 16s=RETRIEVAL_INITIAL_TIMEOUT*(2^RETRIEVAL_MAX_EXP)
const RETRIEVAL_INITIAL_TIMEOUT: Duration = Duration::from_millis(200);
const RETRIEVAL_MAX_EXP: u32 = 4;
/// Returns exponentially increasing timeout with
/// limit of RETRIEVAL_INITIAL_TIMEOUT*(2^RETRIEVAL_MAX_EXP)
#[allow(clippy::trivially_copy_pass_by_ref)]
fn retrieval_timeout(attempt: u32) -> Duration {
assert!(attempt > 0, "retrieval_timeout attempt can't be 0");
let exp = RETRIEVAL_MAX_EXP.min(attempt - 1); // [0..RETRIEVAL_MAX_EXP]
RETRIEVAL_INITIAL_TIMEOUT * 2_u32.pow(exp)
}
|
need_sync_for_quorum_cert
|
odcset.rs
|
#[doc = "Register `ODCSET` reader"]
pub struct R(crate::R<ODCSET_SPEC>);
impl core::ops::Deref for R {
type Target = crate::R<ODCSET_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::convert::From<crate::R<ODCSET_SPEC>> for R {
fn from(reader: crate::R<ODCSET_SPEC>) -> Self {
R(reader)
}
}
#[doc = "Register `ODCSET` writer"]
pub struct W(crate::W<ODCSET_SPEC>);
impl core::ops::Deref for W {
type Target = crate::W<ODCSET_SPEC>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for W {
#[inline(always)]
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl core::convert::From<crate::W<ODCSET_SPEC>> for W {
fn from(writer: crate::W<ODCSET_SPEC>) -> Self {
W(writer)
}
}
#[doc = "Field `ODCA0` reader - "]
pub struct ODCA0_R(crate::FieldReader<bool, bool>);
impl ODCA0_R {
pub(crate) fn new(bits: bool) -> Self {
ODCA0_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for ODCA0_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `ODCA0` writer - "]
pub struct ODCA0_W<'a> {
w: &'a mut W,
}
impl<'a> ODCA0_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Field `ODCA1` reader - "]
pub struct ODCA1_R(crate::FieldReader<bool, bool>);
impl ODCA1_R {
pub(crate) fn new(bits: bool) -> Self {
ODCA1_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for ODCA1_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `ODCA1` writer - "]
pub struct ODCA1_W<'a> {
w: &'a mut W,
}
impl<'a> ODCA1_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Field `ODCA2` reader - "]
pub struct ODCA2_R(crate::FieldReader<bool, bool>);
impl ODCA2_R {
pub(crate) fn new(bits: bool) -> Self {
ODCA2_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for ODCA2_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `ODCA2` writer - "]
pub struct ODCA2_W<'a> {
w: &'a mut W,
}
impl<'a> ODCA2_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Field `ODCA3` reader - "]
pub struct ODCA3_R(crate::FieldReader<bool, bool>);
impl ODCA3_R {
pub(crate) fn new(bits: bool) -> Self {
ODCA3_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for ODCA3_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `ODCA3` writer - "]
pub struct
|
<'a> {
w: &'a mut W,
}
impl<'a> ODCA3_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Field `ODCA4` reader - "]
pub struct ODCA4_R(crate::FieldReader<bool, bool>);
impl ODCA4_R {
pub(crate) fn new(bits: bool) -> Self {
ODCA4_R(crate::FieldReader::new(bits))
}
}
impl core::ops::Deref for ODCA4_R {
type Target = crate::FieldReader<bool, bool>;
#[inline(always)]
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[doc = "Field `ODCA4` writer - "]
pub struct ODCA4_W<'a> {
w: &'a mut W,
}
impl<'a> ODCA4_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
impl R {
#[doc = "Bit 0"]
#[inline(always)]
pub fn odca0(&self) -> ODCA0_R {
ODCA0_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1"]
#[inline(always)]
pub fn odca1(&self) -> ODCA1_R {
ODCA1_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2"]
#[inline(always)]
pub fn odca2(&self) -> ODCA2_R {
ODCA2_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3"]
#[inline(always)]
pub fn odca3(&self) -> ODCA3_R {
ODCA3_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4"]
#[inline(always)]
pub fn odca4(&self) -> ODCA4_R {
ODCA4_R::new(((self.bits >> 4) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0"]
#[inline(always)]
pub fn odca0(&mut self) -> ODCA0_W {
ODCA0_W { w: self }
}
#[doc = "Bit 1"]
#[inline(always)]
pub fn odca1(&mut self) -> ODCA1_W {
ODCA1_W { w: self }
}
#[doc = "Bit 2"]
#[inline(always)]
pub fn odca2(&mut self) -> ODCA2_W {
ODCA2_W { w: self }
}
#[doc = "Bit 3"]
#[inline(always)]
pub fn odca3(&mut self) -> ODCA3_W {
ODCA3_W { w: self }
}
#[doc = "Bit 4"]
#[inline(always)]
pub fn odca4(&mut self) -> ODCA4_W {
ODCA4_W { w: self }
}
#[doc = "Writes raw bits to the register."]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.0.bits(bits);
self
}
}
#[doc = "ODCASET register\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [odcset](index.html) module"]
pub struct ODCSET_SPEC;
impl crate::RegisterSpec for ODCSET_SPEC {
type Ux = u32;
}
#[doc = "`read()` method returns [odcset::R](R) reader structure"]
impl crate::Readable for ODCSET_SPEC {
type Reader = R;
}
#[doc = "`write(|w| ..)` method takes [odcset::W](W) writer structure"]
impl crate::Writable for ODCSET_SPEC {
type Writer = W;
}
#[doc = "`reset()` method sets ODCSET to value 0"]
impl crate::Resettable for ODCSET_SPEC {
#[inline(always)]
fn reset_value() -> Self::Ux {
0
}
}
|
ODCA3_W
|
utils.ts
|
import { v4 as uuidv4 } from "uuid";
export interface OperationInfo {
numberOfSuccesses: number;
numberOfFailures: number;
}
export interface LockRenewalOperationInfo extends OperationInfo {
/**
* key - id, value - next renewal timer meant for the message/session-receiver
*/
lockRenewalTimers: { [key: string]: NodeJS.Timer };
/**
* key - id, value - number of renewals
*/
renewalCount: { [key: string]: number };
}
export interface SnapshotOptions {
/**
* The name of this test. Used when reporting telemetry in customDimensions['testName'].
*/
testName: string;
snapshotFocus?: (
| "send-info"
| "receive-info"
| "message-lock-renewal-info"
| "session-lock-renewal-info"
| "close-info"
)[];
snapshotIntervalInMs?: number;
/**
* Snapshot information is automatically sent to Azure Monitor.
* This allows you also print the same information to the console.
*
* Disabled by default.
*/
writeSnapshotInfoToConsole?: boolean;
}
export interface TrackedMessageIdsInfo {
[key: string]: {
sentCount: number;
receivedCount: number;
settledCount: number;
};
}
export function initializeOperationInfo(): OperationInfo {
return {
numberOfSuccesses: 0,
numberOfFailures: 0,
};
}
export function initializeLockRenewalOperationInfo(): LockRenewalOperationInfo {
return { ...initializeOperationInfo(), lockRenewalTimers: {}, renewalCount: {} };
}
export function
|
(useSessions: boolean, numberOfSessions: number) {
return {
body: `message ${Math.random()}`,
sessionId: useSessions ? `session-${Math.ceil(Math.random() * numberOfSessions)}` : undefined,
messageId: uuidv4(),
};
}
export async function saveDiscrepanciesFromTrackedMessages(
trackedMessageIds: TrackedMessageIdsInfo
) {
const output = {
messages_sent_but_never_received: [] as string[],
messages_not_sent_but_received: [] as string[],
messages_sent_multiple_times: [] as string[],
messages_sent_once_but_received_multiple_times: [] as string[],
messages_sent_once_and_received_once: [] as string[],
};
for (const id in trackedMessageIds) {
if (trackedMessageIds[id].sentCount <= 0) {
// Message was not sent but received
output.messages_not_sent_but_received.push(id);
}
if (trackedMessageIds[id].receivedCount === 0) {
// Message was sent but not received - message loss
output.messages_sent_but_never_received.push(id);
}
if (trackedMessageIds[id].sentCount > 1) {
// Message was sent multiple times
output.messages_sent_multiple_times.push(id);
}
if (trackedMessageIds[id].sentCount === 1 && trackedMessageIds[id].receivedCount > 1) {
// Message was sent once but received multiple times
output.messages_sent_once_but_received_multiple_times.push(id);
}
if (trackedMessageIds[id].sentCount === 1 && trackedMessageIds[id].receivedCount === 1) {
// Message was sent once and received once
output.messages_sent_once_and_received_once.push(id);
}
}
return output;
}
|
generateMessage
|
clamp_easy1.py
|
"""
AWR + SAC from demo experiment
"""
from rlkit.demos.source.dict_to_mdp_path_loader import DictToMDPPathLoader
from rlkit.launchers.experiments.awac.awac_rl import experiment, process_args
import rlkit.misc.hyperparameter as hyp
from rlkit.launchers.arglauncher import run_variants
from rlkit.torch.sac.policies import GaussianPolicy
from rlkit.torch.networks import Clamp
if __name__ == "__main__":
variant = dict(
num_epochs=5001,
num_eval_steps_per_epoch=1000,
num_trains_per_train_loop=1000,
num_expl_steps_per_train_loop=1000,
min_num_steps_before_training=1000,
max_path_length=1000,
batch_size=1024,
replay_buffer_size=int(1E6),
layer_size=256,
policy_class=GaussianPolicy,
policy_kwargs=dict(
hidden_sizes=[256, 256, 256, 256],
max_log_std=0,
min_log_std=-6,
std_architecture="values",
# num_gaussians=1,
),
algorithm="SAC",
version="normal",
collection_mode='batch',
trainer_kwargs=dict(
discount=0.99,
soft_target_tau=5e-3,
target_update_period=1,
policy_lr=3E-4,
qf_lr=3E-4,
reward_scale=1,
beta=1,
use_automatic_entropy_tuning=False,
alpha=0,
compute_bc=False,
bc_num_pretrain_steps=0,
q_num_pretrain1_steps=0,
q_num_pretrain2_steps=25000,
policy_weight_decay=1e-4,
q_weight_decay=0,
bc_loss_type="mse",
rl_weight=1.0,
use_awr_update=True,
use_reparam_update=False,
reparam_weight=0.0,
awr_weight=0.0,
bc_weight=1.0,
post_bc_pretrain_hyperparams=dict(
bc_weight=0.0,
compute_bc=False,
),
reward_transform_kwargs=None, # r' = r + 1
terminal_transform_kwargs=None, # t = 0
),
launcher_config=dict(
num_exps_per_instance=1,
region='us-west-2',
),
path_loader_class=DictToMDPPathLoader,
path_loader_kwargs=dict(
obs_key="state_observation",
demo_paths=[
# dict(
# path="demos/icml2020/hand/pen2_sparse.npy",
# obs_dict=True,
# is_demo=True,
# ),
# dict(
# path="demos/icml2020/hand/pen_bc5.npy",
# obs_dict=False,
# is_demo=False,
# train_split=0.9,
# ),
],
),
add_env_demos=True,
add_env_offpolicy_data=True,
# logger_variant=dict(
# tensorboard=True,
# ),
load_demos=True,
pretrain_policy=True,
pretrain_rl=True,
# save_pretrained_algorithm=True,
# snapshot_mode="all",
)
search_space = {
'env': ["pen-sparse-v0", "door-sparse-v0"],
# 'env': ["relocate-sparse-v0", ],
'trainer_kwargs.bc_loss_type': ["mle"],
'trainer_kwargs.awr_loss_type': ["mle"],
'seedid': range(3),
'trainer_kwargs.beta': [0.3, 0.5],
'trainer_kwargs.reparam_weight': [0.0, ],
'trainer_kwargs.awr_weight': [1.0],
'trainer_kwargs.bc_weight': [1.0, ],
'policy_kwargs.std_architecture': ["values", ],
# 'trainer_kwargs.compute_bc': [True, ],
'trainer_kwargs.awr_use_mle_for_vf': [True, ],
'trainer_kwargs.awr_sample_actions': [False, ],
'trainer_kwargs.awr_min_q': [True, ],
'trainer_kwargs.q_weight_decay': [0],
'trainer_kwargs.reward_transform_kwargs': [None, ],
'trainer_kwargs.terminal_transform_kwargs': [dict(m=0, b=0), ],
'qf_kwargs.output_activation': [Clamp(max=0)],
'trainer_kwargs.train_bc_on_rl_buffer':[True],
# 'policy_kwargs.num_gaussians': [1, ],
}
sweeper = hyp.DeterministicHyperparameterSweeper(
search_space, default_parameters=variant,
|
for variant in sweeper.iterate_hyperparameters():
variants.append(variant)
run_variants(experiment, variants, process_args)
|
)
variants = []
|
pitch_deformer.py
|
from . import common
from audio_toolbox import sox
class PitchDeformer:
SUFFIX = '.pitch@n'
def __init__(self, input_files_key, output_files_key, semitones):
self.input_files_key = input_files_key
self.output_files_key = output_files_key
self.semitones = semitones
def execute(self, context):
input_files = context[self.input_files_key]
output_files = context[self.output_files_key] = []
for input_file in input_files:
output_pattern = common.append_suffix_to_filename(
input_file, PitchDeformer.SUFFIX)
for index, semitone in enumerate(self.semitones):
# start indexing with 1 to be compatible with sox
output_file = output_pattern.replace('@n', str(index + 1))
|
output_files.append(output_file)
sox.adjust_pitch(input_file, output_file, semitone=semitone)
|
|
angular-file.umd.js
|
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/core'), require('@angular/common')) :
typeof define === 'function' && define.amd ? define('angular-file', ['exports', '@angular/core', '@angular/common'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global['angular-file'] = {}, global.ng.core, global.ng.common));
}(this, (function (exports, core, common) { 'use strict';
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b)
if (b.hasOwnProperty(p))
d[p] = b[p]; };
return extendStatics(d, b);
};
function __extends(d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function () {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
function __rest(s, e) {
var t = {};
for (var p in s)
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
}
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function")
r = Reflect.decorate(decorators, target, key, desc);
else
for (var i = decorators.length - 1; i >= 0; i--)
if (d = decorators[i])
r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); };
}
function __metadata(metadataKey, metadataValue) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function")
return Reflect.metadata(metadataKey, metadataValue);
}
function __awaiter(thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try {
step(generator.next(value));
}
catch (e) {
reject(e);
} }
function rejected(value) { try {
step(generator["throw"](value));
}
catch (e) {
reject(e);
} }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
}
function __generator(thisArg, body) {
var _ = { label: 0, sent: function () { if (t[0] & 1)
throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f)
throw new TypeError("Generator is already executing.");
while (_)
try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)
return t;
if (y = 0, t)
op = [op[0] & 2, t.value];
switch (op[0]) {
case 0:
case 1:
t = op;
break;
case 4:
_.label++;
return { value: op[1], done: false };
case 5:
_.label++;
y = op[1];
op = [0];
continue;
case 7:
op = _.ops.pop();
_.trys.pop();
continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
_ = 0;
continue;
}
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
_.label = op[1];
break;
}
if (op[0] === 6 && _.label < t[1]) {
_.label = t[1];
t = op;
break;
}
if (t && _.label < t[2]) {
_.label = t[2];
_.ops.push(op);
break;
}
if (t[2])
_.ops.pop();
_.trys.pop();
continue;
}
op = body.call(thisArg, _);
}
catch (e) {
op = [6, e];
y = 0;
}
finally {
f = t = 0;
}
if (op[0] & 5)
throw op[1];
return { value: op[0] ? op[1] : void 0, done: true };
}
}
function __createBinding(o, m, k, k2) {
if (k2 === undefined)
k2 = k;
o[k2] = m[k];
}
function
|
(m, exports) {
for (var p in m)
if (p !== "default" && !exports.hasOwnProperty(p))
exports[p] = m[p];
}
function __values(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m)
return m.call(o);
if (o && typeof o.length === "number")
return {
next: function () {
if (o && i >= o.length)
o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
}
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m)
return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done)
ar.push(r.value);
}
catch (error) {
e = { error: error };
}
finally {
try {
if (r && !r.done && (m = i["return"]))
m.call(i);
}
finally {
if (e)
throw e.error;
}
}
return ar;
}
function __spread() {
for (var ar = [], i = 0; i < arguments.length; i++)
ar = ar.concat(__read(arguments[i]));
return ar;
}
function __spreadArrays() {
for (var s = 0, i = 0, il = arguments.length; i < il; i++)
s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
}
;
function __await(v) {
return this instanceof __await ? (this.v = v, this) : new __await(v);
}
function __asyncGenerator(thisArg, _arguments, generator) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var g = generator.apply(thisArg, _arguments || []), i, q = [];
return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i;
function verb(n) { if (g[n])
i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }
function resume(n, v) { try {
step(g[n](v));
}
catch (e) {
settle(q[0][3], e);
} }
function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
function fulfill(value) { resume("next", value); }
function reject(value) { resume("throw", value); }
function settle(f, v) { if (f(v), q.shift(), q.length)
resume(q[0][0], q[0][1]); }
}
function __asyncDelegator(o) {
var i, p;
return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i;
function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === "return" } : f ? f(v) : v; } : f; }
}
function __asyncValues(o) {
if (!Symbol.asyncIterator)
throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function (v) { resolve({ value: v, done: d }); }, reject); }
}
function __makeTemplateObject(cooked, raw) {
if (Object.defineProperty) {
Object.defineProperty(cooked, "raw", { value: raw });
}
else {
cooked.raw = raw;
}
return cooked;
}
;
function __importStar(mod) {
if (mod && mod.__esModule)
return mod;
var result = {};
if (mod != null)
for (var k in mod)
if (Object.hasOwnProperty.call(mod, k))
result[k] = mod[k];
result.default = mod;
return result;
}
function __importDefault(mod) {
return (mod && mod.__esModule) ? mod : { default: mod };
}
function __classPrivateFieldGet(receiver, privateMap) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to get private field on non-instance");
}
return privateMap.get(receiver);
}
function __classPrivateFieldSet(receiver, privateMap, value) {
if (!privateMap.has(receiver)) {
throw new TypeError("attempted to set private field on non-instance");
}
privateMap.set(receiver, value);
return value;
}
var isFileInput = function (elm) {
var ty = elm.getAttribute('type');
return elm.tagName.toLowerCase() === 'input' && ty && ty.toLowerCase() === 'file';
};
var initialTouchStartY = 0;
var initialTouchStartX = 0;
var detectSwipe = function (evt) {
var touches = evt.changedTouches || (evt.originalEvent && evt.originalEvent.changedTouches);
if (touches) {
if (evt.type === 'touchstart') {
initialTouchStartX = touches[0].clientX;
initialTouchStartY = touches[0].clientY;
return true; // don't block event default
}
else {
// prevent scroll from triggering event
if (evt.type === 'touchend') {
var currentX = touches[0].clientX;
var currentY = touches[0].clientY;
if ((Math.abs(currentX - initialTouchStartX) > 20) ||
(Math.abs(currentY - initialTouchStartY) > 20)) {
evt.stopPropagation();
if (evt.cancelable) {
evt.preventDefault();
}
return false;
}
}
return true;
}
}
return false;
};
var createInvisibleFileInputWrap = function () {
var fileElem = createFileInput();
var label = document.createElement('label');
label.innerHTML = 'upload';
label.style.visibility = 'hidden';
label.style.position = 'absolute';
label.style.overflow = 'hidden';
label.style.width = '0px';
label.style.height = '0px';
label.style.border = 'none';
label.style.margin = '0px';
label.style.padding = '0px';
label.setAttribute('tabindex', '-1');
//bindAttrToFileInput(fileElem, label);
//generatedElems.push({el: elem, ref: label});
label.appendChild(fileElem);
//document.body.appendChild( label );
return label;
};
var createFileInput = function () {
var fileElem = document.createElement('input');
fileElem.type = "file";
return fileElem;
};
function getWindow() { return window; }
function acceptType(accept, type, name) {
if (!accept) {
return true;
}
var defs = accept.split(',');
var regx;
var acceptRegString;
for (var x = defs.length - 1; x >= 0; --x) {
//Escapes dots in mimetype
acceptRegString = defs[x];
//trim
acceptRegString = acceptRegString.replace(/(^\s+|\s+$)/g, '');
//Escapes stars in mimetype
acceptRegString = acceptRegString.replace(/\*/g, '.*');
//let acceptReg = '^((' + acceptRegString
//acceptReg = acceptReg.replace(/,/g,')|(') + '))$'
//try by mime
regx = new RegExp(acceptRegString, 'gi');
if (type.search(regx) >= 0) {
return true;
}
//try by ext
if (acceptRegString.substring(0, 1) == '.') {
acceptRegString = '\\' + acceptRegString; //.substring(1, acceptRegString.length-1)//remove dot at front
regx = new RegExp(acceptRegString + '$', 'i');
if ((name || type).search(regx) >= 0) {
return true;
}
}
}
return false;
}
function arrayBufferToBase64(buffer) {
var binary = '';
var bytes = new Uint8Array(buffer);
var len = bytes.byteLength;
for (var i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
function dataUrltoBlob(dataurl, name, origSize) {
var arr = dataurl.split(',');
var mimeMatch = arr[0].match(/:(.*?);/);
var mime = mimeMatch ? mimeMatch[1] : 'text/plain';
var bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
var blob = new window.Blob([u8arr], { type: mime });
blob["name"] = name;
blob["$ngfOrigSize"] = origSize;
return blob;
}
function applyTransform(ctx, orientation, width, height) {
switch (orientation) {
case 2:
return ctx.transform(-1, 0, 0, 1, width, 0);
case 3:
return ctx.transform(-1, 0, 0, -1, width, height);
case 4:
return ctx.transform(1, 0, 0, -1, 0, height);
case 5:
return ctx.transform(0, 1, 1, 0, 0, 0);
case 6:
return ctx.transform(0, 1, -1, 0, height, 0);
case 7:
return ctx.transform(0, -1, -1, 0, height, width);
case 8:
return ctx.transform(0, -1, 1, 0, 0, width);
}
}
function fixFileOrientationByMeta(file, result) {
return dataUrl(file, true)
.then(function (url) {
var canvas = document.createElement('canvas');
var img = document.createElement('img');
return new Promise(function (res, rej) {
img.onload = function () {
try {
canvas.width = result.orientation > 4 ? img.height : img.width;
canvas.height = result.orientation > 4 ? img.width : img.height;
var ctx = canvas.getContext('2d');
applyTransform(ctx, result.orientation, img.width, img.height);
ctx.drawImage(img, 0, 0);
var dataUrl = canvas.toDataURL(file.type || 'image/WebP', 0.934);
var base = arrayBufferToBase64(result.fixedArrayBuffer);
dataUrl = restoreExif(base, dataUrl);
var blob = dataUrltoBlob(dataUrl, file.name);
var newFile = blobToFile(blob, file.name);
res(newFile);
}
catch (e) {
rej(e);
}
};
img.onerror = rej;
img.src = url;
});
});
}
function applyExifRotation(file) {
if (file.type.indexOf('image/jpeg') !== 0) {
return Promise.resolve(file);
}
return readOrientation(file)
.then(function (result) {
if (result.orientation < 2 || result.orientation > 8) {
return file;
}
return fixFileOrientationByMeta(file, result);
});
}
function readOrientation(file) {
return new Promise(function (res, rej) {
var reader = new FileReader();
var slicedFile = file.slice ? file.slice(0, 64 * 1024) : file;
reader.readAsArrayBuffer(slicedFile);
reader.onerror = rej;
reader.onload = function (e) {
var result = { orientation: 1 };
var view = new DataView(this.result);
if (view.getUint16(0, false) !== 0xFFD8)
return res(result);
var length = view.byteLength, offset = 2;
while (offset < length) {
var marker = view.getUint16(offset, false);
offset += 2;
if (marker === 0xFFE1) {
if (view.getUint32(offset += 2, false) !== 0x45786966)
return res(result);
var little = view.getUint16(offset += 6, false) === 0x4949;
offset += view.getUint32(offset + 4, little);
var tags = view.getUint16(offset, little);
offset += 2;
for (var i = 0; i < tags; i++)
if (view.getUint16(offset + (i * 12), little) === 0x0112) {
var orientation = view.getUint16(offset + (i * 12) + 8, little);
if (orientation >= 2 && orientation <= 8) {
view.setUint16(offset + (i * 12) + 8, 1, little);
result.fixedArrayBuffer = e.target.result;
}
result.orientation = orientation;
return res(result);
}
}
else if ((marker & 0xFF00) !== 0xFF00)
break;
else
offset += view.getUint16(offset, false);
}
return res(result);
};
});
}
/** converts file-input file into base64 dataUri */
function dataUrl(file, disallowObjectUrl) {
if (!file)
return Promise.resolve(file);
if ((disallowObjectUrl && file.$ngfDataUrl != null) || (!disallowObjectUrl && file.$ngfBlobUrl != null)) {
return Promise.resolve(disallowObjectUrl ? file.$ngfDataUrl : file.$ngfBlobUrl);
}
var p = disallowObjectUrl ? file.$$ngfDataUrlPromise : file.$$ngfBlobUrlPromise;
if (p)
return p;
var win = getWindow();
var deferred;
if (win.FileReader && file &&
(!win.FileAPI || navigator.userAgent.indexOf('MSIE 8') === -1 || file.size < 20000) &&
(!win.FileAPI || navigator.userAgent.indexOf('MSIE 9') === -1 || file.size < 4000000)) {
//prefer URL.createObjectURL for handling refrences to files of all sizes
//since it doesn´t build a large string in memory
var URL = win.URL || win.webkitURL;
if (FileReader) {
deferred = new Promise(function (res, rej) {
var fileReader = new FileReader();
fileReader.onload = function (event) {
file.$ngfDataUrl = event.target.result;
delete file.$ngfDataUrl;
res(event.target.result);
};
fileReader.onerror = function (e) {
file.$ngfDataUrl = '';
rej(e);
};
fileReader.readAsDataURL(file);
});
}
else {
var url;
try {
url = URL.createObjectURL(file);
}
catch (e) {
return Promise.reject(e);
}
deferred = Promise.resolve(url);
file.$ngfBlobUrl = url;
}
}
else {
file[disallowObjectUrl ? '$ngfDataUrl' : '$ngfBlobUrl'] = '';
return Promise.reject(new Error('Browser does not support window.FileReader, window.FileReader, or window.FileAPI')); //deferred.reject();
}
if (disallowObjectUrl) {
p = file.$$ngfDataUrlPromise = deferred;
}
else {
p = file.$$ngfBlobUrlPromise = deferred;
}
p = p.then(function (x) {
delete file[disallowObjectUrl ? '$$ngfDataUrlPromise' : '$$ngfBlobUrlPromise'];
return x;
});
return p;
}
function restoreExif(orig, resized) {
var ExifRestorer = {
KEY_STR: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
};
ExifRestorer.encode64 = function (input) {
var output = '', chr1, chr2, chr3 = '', enc1, enc2, enc3, enc4 = '', i = 0;
do {
chr1 = input[i++];
chr2 = input[i++];
chr3 = input[i++];
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
}
else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
this.KEY_STR.charAt(enc1) +
this.KEY_STR.charAt(enc2) +
this.KEY_STR.charAt(enc3) +
this.KEY_STR.charAt(enc4);
chr1 = chr2 = chr3 = '';
enc1 = enc2 = enc3 = enc4 = '';
} while (i < input.length);
return output;
};
ExifRestorer.restore = function (origFileBase64, resizedFileBase64) {
if (origFileBase64.match('data:image/jpeg;base64,')) {
origFileBase64 = origFileBase64.replace('data:image/jpeg;base64,', '');
}
var rawImage = this.decode64(origFileBase64);
var segments = this.slice2Segments(rawImage);
var image = this.exifManipulation(resizedFileBase64, segments);
return 'data:image/jpeg;base64,' + this.encode64(image);
};
ExifRestorer.exifManipulation = function (resizedFileBase64, segments) {
var exifArray = this.getExifArray(segments), newImageArray = this.insertExif(resizedFileBase64, exifArray);
return new Uint8Array(newImageArray);
};
ExifRestorer.getExifArray = function (segments) {
var seg;
for (var x = 0; x < segments.length; x++) {
seg = segments[x];
if (seg[0] === 255 && seg[1] === 225) //(ff e1)
{
return seg;
}
}
return [];
};
ExifRestorer.insertExif = function (resizedFileBase64, exifArray) {
var imageData = resizedFileBase64.replace('data:image/jpeg;base64,', ''), buf = this.decode64(imageData), separatePoint = buf.indexOf(255, 3), mae = buf.slice(0, separatePoint), ato = buf.slice(separatePoint), array = mae;
array = array.concat(exifArray);
array = array.concat(ato);
return array;
};
ExifRestorer.slice2Segments = function (rawImageArray) {
var head = 0, segments = [];
while (1) {
if (rawImageArray[head] === 255 && rawImageArray[head + 1] === 218) {
break;
}
if (rawImageArray[head] === 255 && rawImageArray[head + 1] === 216) {
head += 2;
}
else {
var length = rawImageArray[head + 2] * 256 + rawImageArray[head + 3];
var endPoint = head + length + 2;
var seg = rawImageArray.slice(head, endPoint);
segments.push(seg);
head = endPoint;
}
if (head > rawImageArray.length) {
break;
}
}
return segments;
};
ExifRestorer.decode64 = function (input) {
var chr1, chr2, chr3 = '', enc1, enc2, enc3, enc4 = '', i = 0, buf = [];
// remove all characters that are not A-Z, a-z, 0-9, +, /, or =
var base64test = /[^A-Za-z0-9\+\/\=]/g;
if (base64test.exec(input)) {
console.log('There were invalid base64 characters in the input text.');
}
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
do {
enc1 = this.KEY_STR.indexOf(input.charAt(i++));
enc2 = this.KEY_STR.indexOf(input.charAt(i++));
enc3 = this.KEY_STR.indexOf(input.charAt(i++));
enc4 = this.KEY_STR.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
buf.push(chr1);
if (enc3 !== 64) {
buf.push(chr2);
}
if (enc4 !== 64) {
buf.push(chr3);
}
chr1 = chr2 = chr3 = '';
enc1 = enc2 = enc3 = enc4 = '';
} while (i < input.length);
return buf;
};
return ExifRestorer.restore(orig, resized); //<= EXIF
}
;
function blobToFile(theBlob, fileName) {
var b = theBlob;
//A Blob() is almost a File() - it's just missing the two properties below which we will add
b.lastModifiedDate = new Date();
b.name = fileName;
//Cast to a File() type
return theBlob;
}
/** A master base set of logic intended to support file select/drag/drop operations
NOTE: Use ngfDrop for full drag/drop. Use ngfSelect for selecting
*/
var ngf = /** @class */ (function () {
function ngf(element) {
this.element = element;
this.filters = [];
this.lastFileCount = 0;
//@Input() forceFilename:string
//@Input() forcePostname:string
this.ngfFixOrientation = true;
this.fileDropDisabled = false;
this.selectable = false;
this.directiveInit = new core.EventEmitter();
this.lastInvalids = [];
this.lastInvalidsChange = new core.EventEmitter();
this.lastBaseUrlChange = new core.EventEmitter();
this.fileChange = new core.EventEmitter();
this.files = [];
this.filesChange = new core.EventEmitter();
this.initFilters();
}
ngf.prototype.initFilters = function () {
// the order is important
this.filters.push({ name: 'accept', fn: this._acceptFilter });
this.filters.push({ name: 'fileSize', fn: this._fileSizeFilter });
//this.filters.push({name: 'fileType', fn: this._fileTypeFilter})
//this.filters.push({name: 'queueLimit', fn: this._queueLimitFilter})
//this.filters.push({name: 'mimeType', fn: this._mimeTypeFilter})
};
ngf.prototype.ngOnDestroy = function () {
delete this.fileElm; //faster memory release of dom element
this.destroyPasteListener();
};
ngf.prototype.ngOnInit = function () {
var _this = this;
var selectable = (this.selectable || this.selectable === '') && !['false', 'null', '0'].includes(this.selectable);
if (selectable) {
this.enableSelecting();
}
if (this.multiple) {
this.paramFileElm().setAttribute('multiple', this.multiple);
}
this.evalCapturePaste();
//create reference to this class with one cycle delay to avoid ExpressionChangedAfterItHasBeenCheckedError
setTimeout(function () {
_this.directiveInit.emit(_this);
}, 0);
};
ngf.prototype.ngOnChanges = function (changes) {
if (changes.accept) {
this.paramFileElm().setAttribute('accept', changes.accept.currentValue || '*');
}
if (changes.capturePaste) {
this.evalCapturePaste();
}
};
ngf.prototype.evalCapturePaste = function () {
var _this = this;
var isActive = this.capturePaste || this.capturePaste === '' || ['false', '0', 'null'].includes(this.capturePaste);
if (isActive) {
if (this.pasteCapturer) {
return; // already listening
}
this.pasteCapturer = function (e) {
var clip = e.clipboardData;
if (clip && clip.files && clip.files.length) {
_this.handleFiles(clip.files);
e.preventDefault();
}
};
window.addEventListener('paste', this.pasteCapturer);
return;
}
this.destroyPasteListener();
};
ngf.prototype.destroyPasteListener = function () {
if (this.pasteCapturer) {
window.removeEventListener('paste', this.pasteCapturer);
delete this.pasteCapturer;
}
};
ngf.prototype.paramFileElm = function () {
if (this.fileElm)
return this.fileElm; //already defined
//elm is a file input
var isFile = isFileInput(this.element.nativeElement);
if (isFile)
return this.fileElm = this.element.nativeElement;
//create foo file input
var label = createInvisibleFileInputWrap();
this.fileElm = label.getElementsByTagName('input')[0];
this.fileElm.addEventListener('change', this.changeFn.bind(this));
this.element.nativeElement.appendChild(label);
return this.fileElm;
};
ngf.prototype.enableSelecting = function () {
var _this = this;
var elm = this.element.nativeElement;
if (isFileInput(elm)) {
var bindedHandler_1 = function (_ev) { return _this.beforeSelect(); };
elm.addEventListener('click', bindedHandler_1);
elm.addEventListener('touchstart', bindedHandler_1);
return;
}
var bindedHandler = function (ev) { return _this.clickHandler(ev); };
elm.addEventListener('click', bindedHandler);
elm.addEventListener('touchstart', bindedHandler);
elm.addEventListener('touchend', bindedHandler);
};
ngf.prototype.getValidFiles = function (files) {
var rtn = [];
for (var x = files.length - 1; x >= 0; --x) {
if (this.isFileValid(files[x])) {
rtn.push(files[x]);
}
}
return rtn;
};
ngf.prototype.getInvalidFiles = function (files) {
var rtn = [];
for (var x = files.length - 1; x >= 0; --x) {
var failReason = this.getFileFilterFailName(files[x]);
if (failReason) {
rtn.push({
file: files[x],
type: failReason
});
}
}
return rtn;
};
// Primary handler of files coming in
ngf.prototype.handleFiles = function (files) {
var _this = this;
var valids = this.getValidFiles(files);
if (files.length != valids.length) {
this.lastInvalids = this.getInvalidFiles(files);
}
else {
delete this.lastInvalids;
}
this.lastInvalidsChange.emit(this.lastInvalids);
if (valids.length) {
if (this.ngfFixOrientation) {
this.applyExifRotations(valids)
.then(function (fixedFiles) { return _this.que(fixedFiles); });
}
else {
this.que(valids);
}
}
if (this.isEmptyAfterSelection()) {
this.element.nativeElement.value = '';
}
};
ngf.prototype.que = function (files) {
var _this = this;
this.files = this.files || [];
Array.prototype.push.apply(this.files, files);
//below break memory ref and doesnt act like a que
//this.files = files//causes memory change which triggers bindings like <ngfFormData [files]="files"></ngfFormData>
this.filesChange.emit(this.files);
if (files.length) {
this.fileChange.emit(this.file = files[0]);
if (this.lastBaseUrlChange.observers.length) {
dataUrl(files[0])
.then(function (url) { return _this.lastBaseUrlChange.emit(url); });
}
}
//will be checked for input value clearing
this.lastFileCount = this.files.length;
};
/** called when input has files */
ngf.prototype.changeFn = function (event) {
var fileList = event.__files_ || (event.target && event.target.files);
if (!fileList)
return;
this.stopEvent(event);
this.handleFiles(fileList);
};
ngf.prototype.clickHandler = function (evt) {
var elm = this.element.nativeElement;
if (elm.getAttribute('disabled') || this.fileDropDisabled) {
return false;
}
var r = detectSwipe(evt);
// prevent the click if it is a swipe
if (r !== false)
return r;
var fileElm = this.paramFileElm();
fileElm.click();
//fileElm.dispatchEvent( new Event('click') );
this.beforeSelect();
return false;
};
ngf.prototype.beforeSelect = function () {
if (this.files && this.lastFileCount === this.files.length)
return;
//if no files in array, be sure browser doesnt prevent reselect of same file (see github issue 27)
this.fileElm.value = null;
};
ngf.prototype.isEmptyAfterSelection = function () {
return !!this.element.nativeElement.attributes.multiple;
};
ngf.prototype.eventToTransfer = function (event) {
if (event.dataTransfer)
return event.dataTransfer;
return event.originalEvent ? event.originalEvent.dataTransfer : null;
};
ngf.prototype.stopEvent = function (event) {
event.preventDefault();
event.stopPropagation();
};
ngf.prototype.transferHasFiles = function (transfer) {
if (!transfer.types) {
return false;
}
if (transfer.types.indexOf) {
return transfer.types.indexOf('Files') !== -1;
}
else if (transfer.types.contains) {
return transfer.types.contains('Files');
}
else {
return false;
}
};
ngf.prototype.eventToFiles = function (event) {
var transfer = this.eventToTransfer(event);
if (transfer) {
if (transfer.files && transfer.files.length) {
return transfer.files;
}
if (transfer.items && transfer.items.length) {
return transfer.items;
}
}
return [];
};
ngf.prototype.applyExifRotations = function (files) {
var mapper = function (file, index) {
return applyExifRotation(file)
.then(function (fixedFile) { return files.splice(index, 1, fixedFile); });
};
var proms = [];
for (var x = files.length - 1; x >= 0; --x) {
proms[x] = mapper(files[x], x);
}
return Promise.all(proms).then(function () { return files; });
};
ngf.prototype.onChange = function (event) {
var files = this.element.nativeElement.files || this.eventToFiles(event);
if (!files.length)
return;
this.stopEvent(event);
this.handleFiles(files);
};
ngf.prototype.getFileFilterFailName = function (file) {
for (var i = 0; i < this.filters.length; i++) {
if (!this.filters[i].fn.call(this, file)) {
return this.filters[i].name;
}
}
return undefined;
};
ngf.prototype.isFileValid = function (file) {
var noFilters = !this.accept && (!this.filters || !this.filters.length);
if (noFilters) {
return true; //we have no filters so all files are valid
}
return this.getFileFilterFailName(file) ? false : true;
};
ngf.prototype.isFilesValid = function (files) {
for (var x = files.length - 1; x >= 0; --x) {
if (!this.isFileValid(files[x])) {
return false;
}
}
return true;
};
ngf.prototype._acceptFilter = function (item) {
return acceptType(this.accept, item.type, item.name);
};
ngf.prototype._fileSizeFilter = function (item) {
return !(this.maxSize && item.size > this.maxSize);
};
/** browsers try hard to conceal data about file drags, this tends to undo that */
ngf.prototype.filesToWriteableObject = function (files) {
var jsonFiles = [];
for (var x = 0; x < files.length; ++x) {
jsonFiles.push({
type: files[x].type,
kind: files[x]["kind"]
});
}
return jsonFiles;
};
return ngf;
}());
ngf.decorators = [
{ type: core.Directive, args: [{
selector: "[ngf]",
exportAs: "ngf"
},] }
];
ngf.ctorParameters = function () { return [
{ type: core.ElementRef }
]; };
ngf.propDecorators = {
multiple: [{ type: core.Input }],
accept: [{ type: core.Input }],
maxSize: [{ type: core.Input }],
ngfFixOrientation: [{ type: core.Input }],
fileDropDisabled: [{ type: core.Input }],
selectable: [{ type: core.Input }],
directiveInit: [{ type: core.Output, args: ['init',] }],
lastInvalids: [{ type: core.Input }],
lastInvalidsChange: [{ type: core.Output }],
lastBaseUrl: [{ type: core.Input }],
lastBaseUrlChange: [{ type: core.Output }],
file: [{ type: core.Input }],
fileChange: [{ type: core.Output }],
files: [{ type: core.Input }],
filesChange: [{ type: core.Output }],
capturePaste: [{ type: core.Input }],
onChange: [{ type: core.HostListener, args: ['change', ['$event'],] }]
};
var ngfSelect = /** @class */ (function (_super) {
__extends(ngfSelect, _super);
function ngfSelect() {
var _this = _super.apply(this, __spread(arguments)) || this;
_this.selectable = true;
return _this;
}
return ngfSelect;
}(ngf));
ngfSelect.decorators = [
{ type: core.Directive, args: [{
selector: "[ngfSelect]",
exportAs: "ngfSelect"
},] }
];
ngfSelect.propDecorators = {
selectable: [{ type: core.Input }]
};
var ngfDrop = /** @class */ (function (_super) {
__extends(ngfDrop, _super);
function ngfDrop() {
var _this = _super.apply(this, __spread(arguments)) || this;
_this.fileOver = new core.EventEmitter();
_this.validDrag = false;
_this.validDragChange = new core.EventEmitter();
_this.invalidDrag = false;
_this.invalidDragChange = new core.EventEmitter();
_this.dragFilesChange = new core.EventEmitter();
return _this;
}
ngfDrop.prototype.onDrop = function (event) {
if (this.fileDropDisabled) {
this.stopEvent(event);
return;
}
this.closeDrags();
var files = this.eventToFiles(event);
if (!files.length)
return;
this.stopEvent(event);
this.handleFiles(files);
};
ngfDrop.prototype.handleFiles = function (files) {
this.fileOver.emit(false); //turn-off dragover
_super.prototype.handleFiles.call(this, files);
};
ngfDrop.prototype.onDragOver = function (event) {
if (this.fileDropDisabled) {
this.stopEvent(event);
return;
}
var transfer = this.eventToTransfer(event);
var files = this.eventToFiles(event);
var jsonFiles = this.filesToWriteableObject(files);
this.dragFilesChange.emit(this.dragFiles = jsonFiles);
if (files.length) {
this.validDrag = this.isFilesValid(files);
}
else {
//Safari, IE11 & some browsers do NOT tell you about dragged files until dropped. Always consider a valid drag
this.validDrag = true;
}
this.validDragChange.emit(this.validDrag);
this.invalidDrag = !this.validDrag;
this.invalidDragChange.emit(this.invalidDrag);
transfer.dropEffect = 'copy'; //change cursor and such
this.stopEvent(event);
this.fileOver.emit(true);
};
ngfDrop.prototype.closeDrags = function () {
delete this.validDrag;
this.validDragChange.emit(this.validDrag);
this.invalidDrag = false;
this.invalidDragChange.emit(this.invalidDrag);
delete this.dragFiles;
this.dragFilesChange.emit(this.dragFiles);
};
ngfDrop.prototype.onDragLeave = function (event) {
if (this.fileDropDisabled) {
this.stopEvent(event);
return;
}
this.closeDrags();
if (this.element) {
if (event.currentTarget === this.element[0]) {
return;
}
}
this.stopEvent(event);
this.fileOver.emit(false);
};
return ngfDrop;
}(ngf));
ngfDrop.decorators = [
{ type: core.Directive, args: [{
selector: "[ngfDrop]",
exportAs: "ngfDrop"
},] }
];
ngfDrop.propDecorators = {
fileOver: [{ type: core.Output }],
validDrag: [{ type: core.Input }],
validDragChange: [{ type: core.Output }],
invalidDrag: [{ type: core.Input }],
invalidDragChange: [{ type: core.Output }],
dragFiles: [{ type: core.Input }],
dragFilesChange: [{ type: core.Output }],
onDrop: [{ type: core.HostListener, args: ['drop', ['$event'],] }],
onDragOver: [{ type: core.HostListener, args: ['dragover', ['$event'],] }],
onDragLeave: [{ type: core.HostListener, args: ['dragleave', ['$event'],] }]
};
var ngfBackground = /** @class */ (function () {
function ngfBackground(ElementRef) {
this.ElementRef = ElementRef;
}
ngfBackground.prototype.ngOnChanges = function (_changes) {
var _this = this;
dataUrl(this.file)
.then(function (src) {
var urlString = 'url(\'' + (src || '') + '\')';
_this.ElementRef.nativeElement.style.backgroundImage = urlString;
});
};
return ngfBackground;
}());
ngfBackground.decorators = [
{ type: core.Directive, args: [{ selector: '[ngfBackground]' },] }
];
ngfBackground.ctorParameters = function () { return [
{ type: core.ElementRef }
]; };
ngfBackground.propDecorators = {
file: [{ type: core.Input, args: ['ngfBackground',] }]
};
var ngfUploadStatus = /** @class */ (function () {
function ngfUploadStatus() {
this.percent = 0;
this.percentChange = new core.EventEmitter();
}
ngfUploadStatus.prototype.ngOnChanges = function (changes) {
var _this = this;
if (changes.httpEvent && changes.httpEvent.currentValue) {
var event_1 = changes.httpEvent.currentValue;
if (event_1.loaded && event_1.total) {
setTimeout(function () {
_this.percent = Math.round(100 * event_1.loaded / event_1.total);
_this.percentChange.emit(_this.percent);
}, 0);
}
}
};
return ngfUploadStatus;
}());
ngfUploadStatus.decorators = [
{ type: core.Directive, args: [{ selector: 'ngfUploadStatus' },] }
];
ngfUploadStatus.propDecorators = {
percent: [{ type: core.Input }],
percentChange: [{ type: core.Output }],
httpEvent: [{ type: core.Input }]
};
var ngfFormData = /** @class */ (function () {
function ngfFormData(IterableDiffers) {
this.postName = "file";
this.FormData = new FormData();
this.FormDataChange = new core.EventEmitter();
this.differ = IterableDiffers.find([]).create();
}
ngfFormData.prototype.ngDoCheck = function () {
var _this = this;
var changes = this.differ.diff(this.files);
if (changes) {
setTimeout(function () { return _this.buildFormData(); }, 0);
}
};
ngfFormData.prototype.buildFormData = function () {
var _this = this;
var isArray = typeof (this.files) === 'object' && this.files.constructor === Array;
if (isArray) {
this.FormData = new FormData();
var files = this.files || [];
files.forEach(function (file) { return _this.FormData.append(_this.postName, file, _this.fileName || file.name); });
this.FormDataChange.emit(this.FormData);
}
else {
delete this.FormData;
}
};
return ngfFormData;
}());
ngfFormData.decorators = [
{ type: core.Directive, args: [{ selector: 'ngfFormData' },] }
];
ngfFormData.ctorParameters = function () { return [
{ type: core.IterableDiffers }
]; };
ngfFormData.propDecorators = {
files: [{ type: core.Input }],
postName: [{ type: core.Input }],
fileName: [{ type: core.Input }],
FormData: [{ type: core.Input }],
FormDataChange: [{ type: core.Output }]
};
var ngfSrc = /** @class */ (function () {
function ngfSrc(ElementRef) {
this.ElementRef = ElementRef;
}
ngfSrc.prototype.ngOnChanges = function (_changes) {
var _this = this;
dataUrl(this.file)
.then(function (src) { return _this.ElementRef.nativeElement.src = src; });
};
return ngfSrc;
}());
ngfSrc.decorators = [
{ type: core.Directive, args: [{ selector: '[ngfSrc]' },] }
];
ngfSrc.ctorParameters = function () { return [
{ type: core.ElementRef }
]; };
ngfSrc.propDecorators = {
file: [{ type: core.Input, args: ['ngfSrc',] }]
};
//import{ HttpModule } from '@angular/http';
var declarations = [
ngfDrop,
ngfSelect,
ngfBackground,
ngfSrc,
ngfUploadStatus,
ngfFormData,
ngf
];
var ngfModule = /** @class */ (function () {
function ngfModule() {
}
return ngfModule;
}());
ngfModule.decorators = [
{ type: core.NgModule, args: [{
imports: [
common.CommonModule
//,HttpModule
],
declarations: declarations,
exports: declarations //[HttpModule, ...declarations]
},] }
];
/*
* Public API Surface of angular-file
*/
/**
* Generated bundle index. Do not edit.
*/
exports.ngf = ngf;
exports.ngfBackground = ngfBackground;
exports.ngfDrop = ngfDrop;
exports.ngfFormData = ngfFormData;
exports.ngfModule = ngfModule;
exports.ngfSelect = ngfSelect;
exports.ngfSrc = ngfSrc;
exports.ngfUploadStatus = ngfUploadStatus;
Object.defineProperty(exports, '__esModule', { value: true });
})));
//# sourceMappingURL=angular-file.umd.js.map
|
__exportStar
|
emit_type_hint.rs
|
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the "hack" directory of this source tree.
use ffi::{Maybe, Maybe::*, Str};
use hhas_type::{constraint, HhasTypeInfo};
use hhbc_id::{class, Id as ClassId};
use hhbc_string_utils as string_utils;
use instruction_sequence::{Error::Unrecoverable, Result};
use naming_special_names_rust::{classes, typehints};
use oxidized::{
aast_defs::{Hint, Hint_, Hint_::*, NastShapeInfo, ShapeFieldInfo, Tprim},
ast_defs::{Id, ShapeFieldName},
};
use std::borrow::Cow;
#[derive(Eq, PartialEq)]
pub enum Kind {
Property,
Return,
Param,
TypeDef,
UpperBound,
}
fn fmt_name_or_prim<'arena>(
alloc: &'arena bumpalo::Bump,
tparams: &[&str],
name: &str,
) -> Cow<'arena, str> {
if tparams.contains(&name) {
(alloc.alloc_str(name) as &str).into()
} else {
let id: class::ClassType<'arena> = class::ClassType::from_ast_name(alloc, &name);
if string_utils::is_xhp(&string_utils::strip_ns(&name)) {
id.to_unmangled_str()
} else {
id.to_raw_string().into()
}
}
}
pub fn prim_to_string(prim: &Tprim) -> &'static str {
use Tprim::*;
match prim {
Tnull => typehints::NULL,
Tvoid => typehints::VOID,
Tint => typehints::INT,
Tbool => typehints::BOOL,
Tfloat => typehints::FLOAT,
Tstring => typehints::STRING,
Tresource => typehints::RESOURCE,
Tnum => typehints::NUM,
Tarraykey => typehints::ARRAYKEY,
Tnoreturn => typehints::NORETURN,
}
}
pub fn fmt_hint<'arena>(
alloc: &'arena bumpalo::Bump,
tparams: &[&str],
strip_tparams: bool,
hint: &Hint,
) -> std::result::Result<String, instruction_sequence::Error> {
let Hint(_, h) = hint;
Ok(match h.as_ref() {
Habstr(id, args) | Happly(Id(_, id), args) => {
let name = fmt_name_or_prim(alloc, tparams, id);
if args.is_empty() || strip_tparams {
name.to_string()
} else {
format!("{}<{}>", name, fmt_hints(alloc, tparams, args)?)
}
}
Hfun(hf) => {
// TODO(mqian): Implement for inout parameters
format!(
"(function ({}): {})",
fmt_hints(alloc, tparams, &hf.param_tys)?,
fmt_hint(alloc, tparams, false, &hf.return_ty)?
)
}
Haccess(Hint(_, hint), accesses) => {
if let Happly(Id(_, id), _) = hint.as_ref() {
format!(
"{}::{}",
fmt_name_or_prim(alloc, tparams, id),
accesses
.iter()
.map(|Id(_, s)| s.as_str())
.collect::<Vec<_>>()
.join("::")
)
} else {
return Err(Unrecoverable(
"ast_to_nast error. Should be Haccess(Happly())".into(),
));
}
}
Hoption(hint) => {
let Hint(_, h) = hint;
if let Hsoft(t) = h.as_ref() {
// Follow HHVM order: soft -> option
// Can we fix this eventually?
format!("@?{}", fmt_hint(alloc, tparams, false, t)?)
} else {
format!("?{}", fmt_hint(alloc, tparams, false, hint)?)
}
}
// No guarantee that this is in the correct order when using map instead of list
// TODO: Check whether shape fields need to retain order *)
Hshape(NastShapeInfo { field_map, .. }) => {
let fmt_field_name = |name: &ShapeFieldName| match name {
ShapeFieldName::SFlitInt((_, s)) => s.to_owned(),
ShapeFieldName::SFlitStr((_, s)) => format!("'{}'", s),
ShapeFieldName::SFclassConst(Id(_, cid), (_, s)) => {
format!("{}::{}", fmt_name_or_prim(alloc, tparams, &cid), s)
}
};
let fmt_field = |field: &ShapeFieldInfo| {
let prefix = if field.optional { "?" } else { "" };
Ok(format!(
"{}{}=>{}",
prefix,
fmt_field_name(&field.name),
fmt_hint(alloc, tparams, false, &field.hint)?
))
};
let shape_fields = field_map
.iter()
.map(fmt_field)
.collect::<Result<Vec<_>>>()
.map(|v| v.join(", "))?;
string_utils::prefix_namespace("HH", &format!("shape({})", shape_fields).as_str())
}
Htuple(hints) => format!("({})", fmt_hints(alloc, tparams, hints)?),
Hlike(t) => format!("~{}", fmt_hint(alloc, tparams, false, t)?),
Hsoft(t) => format!("@{}", fmt_hint(alloc, tparams, false, t)?),
Herr | Hany => {
return Err(Unrecoverable(
"This should be an error caught in naming".into(),
));
}
h => fmt_name_or_prim(alloc, tparams, &hint_to_string(&h)).into(),
})
}
fn hint_to_string<'a>(h: &'a Hint_) -> &'a str {
match h {
Hprim(p) => prim_to_string(p),
Hmixed | Hunion(_) | Hintersection(_) => typehints::MIXED,
Hnonnull => typehints::NONNULL,
Hthis => typehints::THIS,
Hdynamic => typehints::DYNAMIC,
Hnothing => typehints::NOTHING,
_ => panic!("shouldn't invoke this function"),
}
}
fn fmt_hints<'arena>(
alloc: &'arena bumpalo::Bump,
tparams: &[&str],
hints: &[Hint],
) -> std::result::Result<String, instruction_sequence::Error> {
hints
.iter()
.map(|h| fmt_hint(alloc, tparams, false, &h))
.collect::<Result<Vec<_>>>()
.map(|v| v.join(", "))
}
fn can_be_nullable(hint: &Hint_) -> bool {
match hint {
Haccess(_, _) | Hfun(_) | Hdynamic | Hnonnull | Hmixed => false,
Hoption(Hint(_, h)) => {
if let Haccess(_, _) = **h {
true
} else {
can_be_nullable(&**h)
}
}
Happly(Id(_, id), _) => {
id != "\\HH\\dynamic" && id != "\\HH\\nonnull" && id != "\\HH\\mixed"
}
Herr | Hany => panic!("This should be an error caught in naming"),
_ => true,
}
}
fn hint_to_type_constraint<'arena>(
alloc: &'arena bumpalo::Bump,
kind: &Kind,
tparams: &[&str],
skipawaitable: bool,
h: &Hint,
) -> std::result::Result<constraint::Constraint<'arena>, instruction_sequence::Error> {
use constraint::{Constraint, ConstraintFlags};
let Hint(_, hint) = h;
Ok(match &**hint {
Hdynamic | Hlike(_) | Hfun(_) | Hunion(_) | Hintersection(_) | Hmixed => {
Constraint::default()
}
Haccess(_, _) => Constraint::make_with_raw_str(
alloc,
"",
ConstraintFlags::EXTENDED_HINT | ConstraintFlags::TYPE_CONSTANT,
),
Hshape(_) => {
Constraint::make_with_raw_str(alloc, "HH\\darray", ConstraintFlags::EXTENDED_HINT)
}
Htuple(_) => {
Constraint::make_with_raw_str(alloc, "HH\\varray", ConstraintFlags::EXTENDED_HINT)
}
Hsoft(t) => make_tc_with_flags_if_non_empty_flags(
alloc,
kind,
tparams,
skipawaitable,
t,
ConstraintFlags::SOFT | ConstraintFlags::EXTENDED_HINT,
)?,
Herr | Hany => {
return Err(Unrecoverable(
"This should be an error caught in naming".into(),
));
}
Hoption(t) => {
if let Happly(Id(_, s), hs) = &*(t.1) {
if skipawaitable && is_awaitable(&s) {
match &hs[..] {
[] => return Ok(Constraint::default()),
[h] => return hint_to_type_constraint(alloc, kind, tparams, false, h),
_ => {}
}
}
} else if let Hsoft(Hint(_, h)) = &*(t.1) {
if let Happly(Id(_, s), hs) = &**h {
if skipawaitable && is_awaitable(&s) {
if let [h] = &hs[..] {
return make_tc_with_flags_if_non_empty_flags(
alloc,
kind,
tparams,
skipawaitable,
h,
ConstraintFlags::SOFT | ConstraintFlags::EXTENDED_HINT,
);
}
}
}
}
make_tc_with_flags_if_non_empty_flags(
alloc,
kind,
tparams,
skipawaitable,
t,
ConstraintFlags::NULLABLE
| ConstraintFlags::DISPLAY_NULLABLE
| ConstraintFlags::EXTENDED_HINT,
)?
}
Happly(Id(_, s), hs) => {
match &hs[..] {
[] if s == "\\HH\\dynamic"
|| s == "\\HH\\mixed"
|| (skipawaitable && is_awaitable(s))
|| (s.eq_ignore_ascii_case("\\hh\\void") && !is_typedef(&kind)) =>
{
return Ok(Constraint::default());
}
[Hint(_, h)] if skipawaitable && is_awaitable(s) => {
return match &**h {
Hprim(Tprim::Tvoid) => Ok(Constraint::default()),
Happly(Id(_, id), hs) if id == "\\HH\\void" && hs.is_empty() => {
Ok(Constraint::default())
}
_ => hint_to_type_constraint(alloc, kind, tparams, false, &hs[0]),
};
}
_ => {}
};
type_application_helper(alloc, tparams, kind, s)?
}
Habstr(s, _hs) => type_application_helper(alloc, tparams, kind, s)?,
h => type_application_helper(alloc, tparams, kind, &hint_to_string(h))?,
})
}
fn is_awaitable(s: &str) -> bool {
s == classes::AWAITABLE
}
fn is_typedef(kind: &Kind) -> bool {
Kind::TypeDef == *kind
}
fn make_tc_with_flags_if_non_empty_flags<'arena>(
alloc: &'arena bumpalo::Bump,
kind: &Kind,
tparams: &[&str],
skipawaitable: bool,
hint: &Hint,
flags: constraint::ConstraintFlags,
) -> std::result::Result<constraint::Constraint<'arena>, instruction_sequence::Error> {
let tc = hint_to_type_constraint(alloc, kind, tparams, skipawaitable, hint)?;
Ok(match (&tc.name, &tc.flags.bits()) {
(Nothing, 0) => tc,
_ => constraint::Constraint::make(tc.name.into(), flags | tc.flags),
})
}
// Used for nodes that do type application (i.e., Happly and Habstr)
fn
|
<'arena>(
alloc: &'arena bumpalo::Bump,
tparams: &[&str],
kind: &Kind,
name: &str,
) -> std::result::Result<constraint::Constraint<'arena>, instruction_sequence::Error> {
use constraint::{Constraint, ConstraintFlags};
if tparams.contains(&name) {
let tc_name = match kind {
Kind::Param | Kind::Return | Kind::Property => name,
_ => "",
};
Ok(Constraint::make(
Just(Str::new_str(alloc, tc_name)),
ConstraintFlags::EXTENDED_HINT | ConstraintFlags::TYPE_VAR,
))
} else {
let name: String = class::ClassType::from_ast_name(alloc, name).into();
Ok(Constraint::make(
Just(Str::new_str(alloc, &name)),
ConstraintFlags::empty(),
))
}
}
fn add_nullable(nullable: bool, flags: constraint::ConstraintFlags) -> constraint::ConstraintFlags {
if nullable {
constraint::ConstraintFlags::NULLABLE
| constraint::ConstraintFlags::DISPLAY_NULLABLE
| flags
} else {
flags
}
}
fn try_add_nullable(
nullable: bool,
hint: &Hint,
flags: constraint::ConstraintFlags,
) -> constraint::ConstraintFlags {
let Hint(_, h) = hint;
add_nullable(nullable && can_be_nullable(&**h), flags)
}
fn make_type_info<'arena>(
alloc: &'arena bumpalo::Bump,
tparams: &[&str],
h: &Hint,
tc_name: Maybe<Str<'arena>>,
tc_flags: constraint::ConstraintFlags,
) -> std::result::Result<HhasTypeInfo<'arena>, instruction_sequence::Error> {
let type_info_user_type = fmt_hint(alloc, tparams, false, h)?;
let type_info_type_constraint = constraint::Constraint::make(tc_name, tc_flags);
Ok(HhasTypeInfo::make(
Just(Str::new_str(alloc, &type_info_user_type)),
type_info_type_constraint,
))
}
fn param_hint_to_type_info<'arena>(
alloc: &'arena bumpalo::Bump,
kind: &Kind,
skipawaitable: bool,
nullable: bool,
tparams: &[&str],
hint: &Hint,
) -> std::result::Result<HhasTypeInfo<'arena>, instruction_sequence::Error> {
let Hint(_, h) = hint;
let is_simple_hint = match h.as_ref() {
Hsoft(_) | Hoption(_) | Haccess(_, _) | Hfun(_) | Hdynamic | Hnonnull | Hmixed => false,
Happly(Id(_, s), hs) => {
if !hs.is_empty() {
false
} else {
if s == "\\HH\\dynamic" || s == "\\HH\\nonnull" || s == "\\HH\\mixed" {
false
} else {
!tparams.contains(&s.as_str())
}
}
}
Habstr(s, hs) => {
if !hs.is_empty() {
false
} else {
!tparams.contains(&s.as_str())
}
}
Herr | Hany => {
return Err(Unrecoverable(
"Expected error on Tany in naming: param_hint_to_type_info".into(),
));
}
_ => true,
};
let tc = hint_to_type_constraint(alloc, kind, tparams, skipawaitable, hint)?;
make_type_info(
alloc,
tparams,
hint,
tc.name,
try_add_nullable(
nullable,
hint,
if is_simple_hint {
constraint::ConstraintFlags::empty()
} else {
tc.flags
},
),
)
}
pub fn hint_to_type_info<'arena>(
alloc: &'arena bumpalo::Bump,
kind: &Kind,
skipawaitable: bool,
nullable: bool,
tparams: &[&str],
hint: &Hint,
) -> std::result::Result<HhasTypeInfo<'arena>, instruction_sequence::Error> {
if let Kind::Param = kind {
return param_hint_to_type_info(alloc, kind, skipawaitable, nullable, tparams, hint);
};
let tc = hint_to_type_constraint(alloc, kind, tparams, skipawaitable, hint)?;
let flags = match kind {
Kind::Return | Kind::Property if tc.name.is_just() => {
constraint::ConstraintFlags::EXTENDED_HINT | tc.flags
}
Kind::UpperBound => constraint::ConstraintFlags::UPPERBOUND | tc.flags,
_ => tc.flags,
};
make_type_info(
alloc,
tparams,
hint,
tc.name,
if is_typedef(kind) {
add_nullable(nullable, flags)
} else {
try_add_nullable(nullable, hint, flags)
},
)
}
pub fn hint_to_class<'arena>(
alloc: &'arena bumpalo::Bump,
hint: &Hint,
) -> class::ClassType<'arena> {
let Hint(_, h) = hint;
if let Happly(Id(_, name), _) = &**h {
class::ClassType::from_ast_name(alloc, &name)
} else {
class::from_raw_string(alloc, "__type_is_not_class__")
}
}
pub fn emit_type_constraint_for_native_function<'arena>(
alloc: &'arena bumpalo::Bump,
tparams: &[&str],
ret_opt: Option<&Hint>,
ti: HhasTypeInfo<'arena>,
) -> HhasTypeInfo<'arena> {
use constraint::ConstraintFlags;
let (name, flags) = match (&ti.user_type, ret_opt) {
(_, None) | (Nothing, _) => (
Just(String::from("HH\\void")),
ConstraintFlags::EXTENDED_HINT,
),
(Just(t), _) => {
if t.unsafe_as_str() == "HH\\mixed" || t.unsafe_as_str() == "callable" {
(Nothing, ConstraintFlags::default())
} else {
let Hint(_, h) = ret_opt.as_ref().unwrap();
let name = Just(
string_utils::strip_type_list(
t.unsafe_as_str()
.trim_start_matches('?')
.trim_start_matches('@')
.trim_start_matches('?'),
)
.to_string(),
);
(name, get_flags(tparams, ConstraintFlags::EXTENDED_HINT, &h))
}
}
};
let tc = constraint::Constraint::make(name.map(|n| Str::new_str(alloc, &n)), flags);
HhasTypeInfo::make(ti.user_type, tc)
}
fn get_flags(
tparams: &[&str],
flags: constraint::ConstraintFlags,
hint: &Hint_,
) -> constraint::ConstraintFlags {
use constraint::ConstraintFlags;
match hint {
Hoption(x) => {
let Hint(_, h) = x;
ConstraintFlags::NULLABLE
| ConstraintFlags::DISPLAY_NULLABLE
| get_flags(tparams, flags, &**h)
}
Hsoft(x) => {
let Hint(_, h) = x;
ConstraintFlags::SOFT | get_flags(tparams, flags, &**h)
}
Haccess(_, _) => ConstraintFlags::TYPE_CONSTANT | flags,
Happly(Id(_, s), _) if tparams.contains(&s.as_str()) => ConstraintFlags::TYPE_VAR | flags,
_ => flags,
}
}
|
type_application_helper
|
EGAAC.py
|
#!/usr/bin/env python
#_*_coding:utf-8_*_
import re, sys, os
from collections import Counter
pPath = os.path.split(os.path.realpath(__file__))[0]
sys.path.append(pPath)
import readFasta
import saveCode
import checkFasta
USAGE = """
USAGE:
python EGAAC.py input.fasta <sliding_window> <output>
input.fasta: the input protein sequence file in fasta format.
sliding_window: the sliding window, integer, defaule: 5
output: the encoding file, default: 'encodings.tsv'
"""
def EGAAC(fastas, window=5, **kw):
|
if __name__ == '__main__':
if len(sys.argv) == 1:
print(USAGE)
sys.exit(1)
fastas = readFasta.readFasta(sys.argv[1])
sw = int(sys.argv[2]) if len(sys.argv) >= 3 else 5
output = sys.argv[3] if len(sys.argv) >= 4 else 'encoding.tsv'
encodings = EGAAC(fastas, sw)
saveCode.savetsv(encodings, output)
|
if checkFasta.checkFasta(fastas) == False:
print('Error: for "EGAAC" encoding, the input fasta sequences should be with equal length. \n\n')
return 0
if window < 1:
print('Error: the sliding window should be greater than zero' + '\n\n')
return 0
group = {
'alphaticr': 'GAVLMI',
'aromatic': 'FYW',
'postivecharger': 'KRH',
'negativecharger': 'DE',
'uncharger': 'STCPNQ'
}
groupKey = group.keys()
encodings = []
header = ['#']
for w in range(1, len(fastas[0][1]) - window + 2):
for g in groupKey:
header.append('SW.'+str(w)+'.'+ g)
encodings.append(header)
for i in fastas:
name, sequence = i[0], i[1]
code = [name]
for j in range(len(sequence)):
if j + window <= len(sequence):
count = Counter(sequence[j:j + window])
myDict = {}
for key in groupKey:
for aa in group[key]:
myDict[key] = myDict.get(key, 0) + count[aa]
for key in groupKey:
code.append(myDict[key] / window)
encodings.append(code)
return encodings
|
fuzz.rs
|
#[cfg(test)]
use imagesize::blob_size;
use std::{
fs::{metadata, read_dir, File},
io::{Error, Read},
path::PathBuf,
};
#[test]
fn fuzzer_crashes_fixed() {
let mut entries = read_dir("test/fuzz_crashes")
.unwrap()
.map(|res| res.map(|e| e.path()))
.collect::<Result<Vec<_>, Error>>()
.unwrap();
entries.sort();
for entry in entries {
let data = get_file_as_byte_vec(entry);
let _ = blob_size(&data);
}
}
fn
|
(filename: PathBuf) -> Vec<u8> {
let mut f = File::open(&filename).expect("no file found");
let metadata = metadata(&filename).expect("unable to read metadata");
let mut buffer = vec![0; metadata.len() as usize];
f.read(&mut buffer).expect("buffer overflow");
buffer
}
|
get_file_as_byte_vec
|
index.js
|
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './components/App'
import { createStore,applyMiddleware } from 'redux'
import {Provider} from 'react-redux'
import reducers from './reducers/combineReducer'
import reduxThunk from 'redux-thunk'
const store = createStore(
reducers, //todos los reducers
{}, //estado inicial
applyMiddleware(reduxThunk)
)
ReactDOM.render(
<Provider store={store}>
<App/>
</Provider>,
document.getElementById('root'))
//en el index.js que es donde se renderizara toda la app es en donde vamos a crear el Store que nos proveera de todos los datos. este lo creamos importando el createStore y usandolo como funcion en una constante, dentro del store se reciben 2 datos (el tercer dato es opcional): los reducers y el estado inicial de la app
|
//es importante agregar los middlewares, en este caso instalaremos reduxThunk y se lo agregaremos al store por medio de applyMiddleware el cual lo importamos junto a createStore, a este applyMiddleware le pasamos el reduxThunk.
|
// el Stores vamos a pasarlo al "Provider" el cual es el proveedor de datos a toda la app
|
receiver.py
|
#
# This file is part of LUNA.
#
# Copyright (c) 2020 Great Scott Gadgets <[email protected]>
# SPDX-License-Identifier: BSD-3-Clause
""" Header Packet Rx-handling gateware. """
import unittest
from nmigen import *
from nmigen.hdl.ast import Fell
from usb_protocol.types.superspeed import LinkCommand
from .header import HeaderPacket, HeaderQueue
from .crc import compute_usb_crc5, HeaderPacketCRC
from .command import LinkCommandGenerator
from ..physical.coding import SHP, EPF, stream_matches_symbols
from ...stream import USBRawSuperSpeedStream
from ....test.utils import LunaSSGatewareTestCase, ss_domain_test_case
class RawHeaderPacketReceiver(Elaboratable):
""" Class that monitors the USB bus for Header Packet, and receives them.
This class performs the validations required at the link layer of the USB specification;
which include checking the CRC-5 and CRC-16 embedded within the header packet.
Attributes
----------
sink: USBRawSuperSpeedStream(), input (monitor only)
Stream that the USB data to be monitored.
packet: HeaderPacket(), output
The de-serialized form of our header packet.
new_packet: Signal(), output
Strobe; indicates that a new, valid header packet has been received. The new
packet is now available on :attr:``packet``.
bad_packet: Signal(), output
Strobe; indicates that a corrupted, invalid header packet has been received.
:attr:``packet`` has not been updated.
expected_sequence: Signal(3), input
Indicates the next expected sequence number; used to validate the received packet.
"""
def __init__(self):
#
# I/O port
#
self.sink = USBRawSuperSpeedStream()
# Header packet output.
self.packet = HeaderPacket()
# State indications.
self.new_packet = Signal()
self.bad_packet = Signal()
# Sequence tracking.
self.expected_sequence = Signal(3)
self.bad_sequence = Signal()
def elaborate(self, platform):
m = Module()
sink = self.sink
# Store our header packet in progress; which we'll output only once it's been validated.
packet = HeaderPacket()
# Cache our expected CRC5, so we can pipeline generation and comparison.
expected_crc5 = Signal(5)
# Keep our "new packet" signal de-asserted unless asserted explicitly.
m.d.ss += self.new_packet.eq(0)
#
# CRC-16 Generator
#
m.submodules.crc16 = crc16 = HeaderPacketCRC()
m.d.comb += crc16.data_input.eq(sink.data),
#
# Receiver Sequencing
#
with m.FSM(domain="ss"):
# WAIT_FOR_HPSTART -- we're currently waiting for HPSTART framing, which indicates
# that the following 16 symbols (4 words) will be a header packet.
with m.State("WAIT_FOR_HPSTART"):
# Don't start our CRC until we're past our HPSTART header.
m.d.comb += crc16.clear.eq(1)
is_hpstart = stream_matches_symbols(sink, SHP, SHP, SHP, EPF)
with m.If(is_hpstart):
m.next = "RECEIVE_DW0"
# RECEIVE_DWn -- the first three words of our header packet are data words meant form
# the protocol layer; we'll receive them so we can pass them on to the protocol layer.
for n in range(3):
with m.State(f"RECEIVE_DW{n}"):
with m.If(sink.valid):
m.d.comb += crc16.advance_crc.eq(1)
m.d.ss += packet[f'dw{n}'].eq(sink.data)
m.next = f"RECEIVE_DW{n+1}"
# RECEIVE_DW3 -- we'll receive and parse our final data word, which contains the fields
# relevant to the link layer.
with m.State("RECEIVE_DW3"):
with m.If(sink.valid):
m.d.ss += [
# Collect the fields from the DW...
packet.crc16 .eq(sink.data[ 0:16]),
packet.sequence_number .eq(sink.data[16:19]),
packet.dw3_reserved .eq(sink.data[19:22]),
packet.hub_depth .eq(sink.data[22:25]),
packet.deferred .eq(sink.data[25]),
packet.delayed .eq(sink.data[26]),
packet.crc5 .eq(sink.data[27:32]),
# ... and pipeline a CRC of the to the link control word.
expected_crc5 .eq(compute_usb_crc5(sink.data[16:27]))
]
m.next = "CHECK_PACKET"
# CHECK_PACKET -- we've now received our full packet; we'll check it for validity.
with m.State("CHECK_PACKET"):
# A minor error occurs if if one of our CRCs mismatches; in which case the link can
# continue after sending an LBAD link command. [USB3.2r1: 7.2.4.1.5].
# We'll strobe our less-severe "bad packet" indicator, but still reject the header.
crc5_failed = (expected_crc5 != packet.crc5)
crc16_failed = (crc16.crc != packet.crc16)
with m.If(crc5_failed | crc16_failed):
m.d.comb += self.bad_packet.eq(1)
# Our worst-case scenario is we're receiving a packet with an unexpected sequence
# number; this indicates that we've lost sequence, and our device should move back to
# into Recovery [USB3.2r1: 7.2.4.1.5].
with m.Elif(packet.sequence_number != self.expected_sequence):
m.d.comb += self.bad_sequence.eq(1)
# If neither of the above checks failed, we now know we have a valid header packet!
# We'll output our packet, and then return to IDLE.
with m.Else():
m.d.ss += [
self.new_packet .eq(1),
self.packet .eq(packet)
]
m.next = "WAIT_FOR_HPSTART"
return m
class RawHeaderPacketReceiverTest(LunaSSGatewareTestCase):
FRAGMENT_UNDER_TEST = RawHeaderPacketReceiver
def initialize_signals(self):
yield self.dut.sink.valid.eq(1)
def provide_data(self, *tuples):
""" Provides the receiver with a sequence of (data, ctrl) values. """
# Provide each word of our data to our receiver...
for data, ctrl in tuples:
yield self.dut.sink.data.eq(data)
yield self.dut.sink.ctrl.eq(ctrl)
yield
@ss_domain_test_case
def test_good_packet_receive(self):
dut = self.dut
# Data input for an actual Link Management packet (seq #0).
yield from self.provide_data(
# data ctrl
(0xF7FBFBFB, 0b1111),
(0x00000280, 0b0000),
(0x00010004, 0b0000),
(0x00000000, 0b0000),
(0x10001845, 0b0000),
)
# ... after a cycle to process, we should see an indication that the packet is good.
yield from self.advance_cycles(2)
self.assertEqual((yield dut.new_packet), 1)
self.assertEqual((yield dut.bad_packet), 0)
self.assertEqual((yield dut.bad_sequence), 0)
@ss_domain_test_case
def test_bad_sequence_receive(self):
dut = self.dut
# Expect a sequence number other than the one we'll be providing.
yield dut.expected_sequence.eq(3)
# Data input for an actual Link Management packet (seq #0).
yield from self.provide_data(
# data ctrl
(0xF7FBFBFB, 0b1111),
(0x00000280, 0b0000),
(0x00010004, 0b0000),
(0x00000000, 0b0000),
(0x10001845, 0b0000),
)
# ... after a cycle to process, we should see an indication that the packet is good.
yield from self.advance_cycles(1)
self.assertEqual((yield dut.new_packet), 0)
self.assertEqual((yield dut.bad_packet), 0)
self.assertEqual((yield dut.bad_sequence), 1)
@ss_domain_test_case
def test_bad_packet_receive(self):
dut = self.dut
# Data input for an actual Link Management packet (seq #0),
# but with the last word corrupted to invalidate our CRC16.
yield from self.provide_data(
# data ctrl
(0xF7FBFBFB, 0b1111),
(0x00000280, 0b0000),
(0x00010004, 0b0000),
(0xFFFFFFFF, 0b0000),
(0x10001845, 0b0000),
)
# ... after a cycle to process, we should see an indication that the packet is bad.
yield from self.advance_cycles(1)
self.assertEqual((yield dut.new_packet), 0)
self.assertEqual((yield dut.bad_packet), 1)
self.assertEqual((yield dut.bad_sequence), 0)
@ss_domain_test_case
def test_bad_crc_and_sequence_receive(self):
dut = self.dut
# Completely invalid link packet, guaranteed to have a bad sequence number & CRC.
yield from self.provide_data(
# data ctrl
(0xF7FBFBFB, 0b1111),
(0xFFFFFFFF, 0b0000),
(0xFFFFFFFF, 0b0000),
(0xFFFFFFFF, 0b0000),
(0xFFFFFFFF, 0b0000),
)
# Once we've processed this, we should see that there's a bad packet; but that it's
# corrupted enough that our sequence no longer matters.
yield from self.advance_cycles(1)
self.assertEqual((yield dut.new_packet), 0)
self.assertEqual((yield dut.bad_packet), 1)
self.assertEqual((yield dut.bad_sequence), 0)
class HeaderPacketReceiver(Elaboratable):
""" Receiver-side Header Packet logic.
This module handles all header-packet-reception related logic for the link layer; including
header packet reception, buffering, flow control (credit management), and link command transmission.
Attributes
----------
sink: USBRawSuperSpeedStream(), input stream [monitor only]
Stream that carries data from the physical layer, to be monitored.
source: USBRawSuperSpeedStream(), output stream
Stream that carries link commands from this unit down down to the physical layer.
enable: Signal(), input
When asserted, this unit will be enabled; and will be allowed to start
transmitting link commands. Asserting this signal after a reset will perform
a header sequence and link credit advertisement.
usb_reset: Signal(), input
Strobe; can be asserted to indicate that a USB reset has occurred, and sequencing
should be restarted.
queue: HeaderQueue(), output stream
Stream carrying any header packets to be transmitted.
retry_received: Signal(), input
Strobe; should be asserted when the transmitter has seen a RETRY handshake.
retry_required: Signal(), output
Strobe; pulsed to indicate that we should send a RETRY handshake.
link_command_sent: Signal(), output
Strobe; pulses each time a link command is completed.
keepalive_required: Signal(), input
Strobe; when asserted; a keepalive packet will be generated.
packet_received: Signal(), output
Strobe; pulsed when an event occurs that should reset the USB3 "packet received" timers.
This does *not* indicate valid data is present on the output :attr:``queue``; this has its
own valid signal.
bad_packet_received: Signal(), output
Strobe; pulsed when a receive error occurs. For error counting at the link level.
accept_power_state: Signal(), input
Strobe; when pulsed, a LAU (Link-state acceptance) will be generated.
reject_power_state: Signal(), input
Strobe; when pulsed, a LXU (Link-state rejection) will be generated.
acknowledge_power_state: Signal(), input
Strobe; when pulsed, a LPMA (Link-state acknowledgement) will be generated.
"""
SEQUENCE_NUMBER_WIDTH = 3
def __init__(self, *, buffer_count=4, downstream_facing=False):
self._buffer_count = buffer_count
self._is_downstream_facing = downstream_facing
#
# I/O port
#
self.sink = USBRawSuperSpeedStream()
self.source = USBRawSuperSpeedStream()
# Simple controls.
self.enable = Signal()
self.usb_reset = Signal()
# Header Packet Queue
self.queue = HeaderQueue()
# Event signaling.
self.retry_received = Signal()
self.retry_required = Signal()
self.recovery_required = Signal()
self.link_command_sent = Signal()
self.keepalive_required = Signal()
self.packet_received = Signal()
self.bad_packet_received = Signal()
self.accept_power_state = Signal()
self.reject_power_state = Signal()
self.acknowledge_power_state = Signal()
def elaborate(self, platform):
m = Module()
#
# Sequence tracking.
#
# Keep track of which sequence number we expect to see.
expected_sequence_number = Signal(self.SEQUENCE_NUMBER_WIDTH)
# Keep track of which credit we'll need to issue next...
next_credit_to_issue = Signal(range(self._buffer_count))
# ... and which header we'll need to ACK next.
# We'll start with the maximum number, so our first advertisement wraps us back around to zero.
next_header_to_ack = Signal.like(expected_sequence_number, reset=-1)
#
# Task "queues".
#
# Keep track of how many header received acknowledgements (LGOODs) we need to send.
acks_to_send = Signal(range(self._buffer_count + 1), reset=1)
enqueue_ack = Signal()
dequeue_ack = Signal()
with m.If(enqueue_ack & ~dequeue_ack):
m.d.ss += acks_to_send.eq(acks_to_send + 1)
with m.If(dequeue_ack & ~enqueue_ack):
m.d.ss += acks_to_send.eq(acks_to_send - 1)
# Keep track of how many link credits we've yet to free.
# We'll start with every one of our buffers marked as "pending free"; this ensures
# we perform our credit restoration properly.
credits_to_issue = Signal.like(acks_to_send, reset=self._buffer_count)
enqueue_credit_issue = Signal()
dequeue_credit_issue = Signal()
with m.If(enqueue_credit_issue & ~dequeue_credit_issue):
m.d.ss += credits_to_issue.eq(credits_to_issue + 1)
with m.If(dequeue_credit_issue & ~enqueue_credit_issue):
m.d.ss += credits_to_issue.eq(credits_to_issue - 1)
# Keep track of whether we should be sending an LBAD.
lbad_pending = Signal()
# Keep track of whether a retry has been requested.
retry_pending = Signal()
with m.If(self.retry_required):
m.d.ss += retry_pending.eq(1)
# Keep track of whether a keepalive has been requested.
keepalive_pending = Signal()
with m.If(self.keepalive_required):
m.d.ss += keepalive_pending.eq(1)
# Keep track of whether we're expected to send an power state response.
lau_pending = Signal()
lxu_pending = Signal()
lpma_pending = Signal()
with m.If(self.accept_power_state):
m.d.ss += lau_pending.eq(1)
with m.If(self.reject_power_state):
m.d.ss += lxu_pending.eq(1)
with m.If(self.acknowledge_power_state):
m.d.ss += lpma_pending.eq(1)
#
# Header Packet Buffers
#
# Track which buffer will be filled next.
read_pointer = Signal(range(self._buffer_count))
write_pointer = Signal.like(read_pointer)
# Track how many buffers we currently have in use.
buffers_filled = Signal.like(credits_to_issue, reset=0)
reserve_buffer = Signal()
release_buffer = Signal()
with m.If(reserve_buffer & ~release_buffer):
m.d.ss += buffers_filled.eq(buffers_filled + 1)
with m.If(release_buffer & ~reserve_buffer):
m.d.ss += buffers_filled.eq(buffers_filled - 1)
# Create buffers to receive any incoming header packets.
buffers = Array(HeaderPacket() for _ in range(self._buffer_count))
#
# Packet reception (physical layer -> link layer).
#
# Flag that determines when we should ignore packets.
#
# After a receive error, we'll want to ignore all packets until we see a "retry"
# link command; so we don't receive packets out of order.
ignore_packets = Signal()
# Create our raw packet parser / receiver.
m.submodules.receiver = rx = RawHeaderPacketReceiver()
m.d.comb += [
# Our receiver passively monitors the data received for header packets.
rx.sink .tap(self.sink),
# Ensure it's always up to date about what sequence numbers we expect.
rx.expected_sequence .eq(expected_sequence_number),
# If we ever get a bad header packet sequence, we're required to retrain
# the link [USB3.2r1: 7.2.4.1.5]. Pass the event through directly.
self.recovery_required .eq(rx.bad_sequence & ~ignore_packets),
# Notify the link layer when packets are received, for keeping track of our timers.
self.packet_received .eq(rx.new_packet),
# Notify the link layer if any bad packets are received; for diagnostics.
self.bad_packet_received .eq(rx.bad_packet)
]
# If we receive a valid packet, it's time for us to buffer it!
with m.If(rx.new_packet & ~ignore_packets):
m.d.ss += [
# Load our header packet into the next write buffer...
buffers[write_pointer] .eq(rx.packet),
# ... advance to the next buffer and sequence number...
write_pointer .eq(write_pointer + 1),
expected_sequence_number .eq(expected_sequence_number + 1),
]
m.d.comb += [
# ... mark the buffer space as occupied by valid data ...
reserve_buffer .eq(1),
# ... and queue an ACK for this packet.
enqueue_ack .eq(1)
]
# If we receive a bad packet, we'll need to request that the other side re-send.
# The rules for this are summarized in [USB3.2r1: 7.2.4.1.5], and in comments below.
with m.If(rx.bad_packet & ~ignore_packets):
m.d.ss += [
# First, we'll need to schedule transmission of an LBAD, which notifies the other
# side that we received a bad packet; and that it'll need to transmit all unack'd
# header packets to us again.
lbad_pending .eq(1),
# Next, we'll need to make sure we don't receive packets out of sequence. This means
# we'll have to start ignoring packets until the other side responds to the LBAD.
# The other side respond with an Retry link command (LRTY) once it's safe for us to
# pay attention to packets again.
ignore_packets .eq(1)
]
# Finally, if we receive a Retry link command, this means we no longer need to ignore packets.
# This typically happens in response to us sending an LBAD and marking future packets as ignored.
with m.If(self.retry_received):
m.d.ss += ignore_packets.eq(0)
#
# Packet delivery (link layer -> physical layer).
#
m.d.comb += [
# As long as we have at least one buffer filled, we have header packets pending.
self.queue.valid .eq(buffers_filled > 0),
# Always provide the value of our oldest packet out to our consumer.
self.queue.header .eq(buffers[read_pointer])
]
# If the protocol layer is marking one of our packets as consumed, we no longer
# need to buffer it -- it's the protocol layer's problem, now!
with m.If(self.queue.valid & self.queue.ready):
# Move on to reading from the next buffer in sequence.
m.d.ss += read_pointer.eq(read_pointer + 1)
m.d.comb += [
# First, we'll free the buffer associated with the relevant packet...
release_buffer .eq(1),
# ... and request that our link partner be notified of the new space.
enqueue_credit_issue .eq(1)
]
#
# Automatic credit expiration.
#
# FIXME: implement this!
#
# Link command generation.
#
m.submodules.lc_generator = lc_generator = LinkCommandGenerator()
m.d.comb += [
self.source .stream_eq(lc_generator.source),
self.link_command_sent .eq(lc_generator.done),
]
with m.FSM(domain="ss"):
# DISPATCH_COMMAND -- the state in which we identify any pending link commands necessary,
# and then move to the state in which we'll send them.
with m.State("DISPATCH_COMMAND"):
with m.If(self.enable):
# NOTE: the order below is important; changing it can easily break things:
# - ACKS must come before credits, as we must send an LGOOD before we send our initial credits.
# - LBAD must come after ACKs and credit management, as all scheduled ACKs need to be
# sent to the other side for the LBAD to have the correct semantic meaning.
with m.If(retry_pending):
m.next = "SEND_LRTY"
# If we have acknowledgements to send, send them.
with m.Elif(acks_to_send):
m.next = "SEND_ACKS"
# If we have link credits to issue, move to issuing them to the other side.
with m.Elif(credits_to_issue):
m.next = "ISSUE_CREDITS"
# If we need to send an LBAD, do so.
with m.Elif(lbad_pending):
|
# If we need to send a link power-state command, do so.
with m.Elif(lxu_pending):
m.next = "SEND_LXU"
# If we need to send a keepalive, do so.
with m.Elif(keepalive_pending):
m.next = "SEND_KEEPALIVE"
# Once we've become disabled, we'll want to prepare for our next enable.
# This means preparing for our advertisement, by:
with m.If(Fell(self.enable) | self.usb_reset):
m.d.ss += [
# -Resetting our pending ACKs to 1, so we perform an sequence number advertisement
# when we're next enabled.
acks_to_send .eq(1),
# -Decreasing our next sequence number; so we maintain a continuity of sequence numbers
# without counting the advertising one. This doesn't seem to be be strictly necessary
# per the spec; but seem to make analyzers happier, so we'll go with it.
next_header_to_ack .eq(next_header_to_ack - 1),
# - Clearing all of our buffers.
read_pointer .eq(0),
write_pointer .eq(0),
buffers_filled .eq(0),
# - Preparing to re-issue all of our buffer credits.
next_credit_to_issue .eq(0),
credits_to_issue .eq(self._buffer_count),
# - Clear our pending events.
retry_pending .eq(0),
lbad_pending .eq(0),
keepalive_pending .eq(0),
ignore_packets .eq(0)
]
# If this is a USB Reset, also reset our sequences.
with m.If(self.usb_reset):
m.d.ss += [
expected_sequence_number .eq(0),
next_header_to_ack .eq(-1)
]
# SEND_ACKS -- a valid header packet has been received, or we're advertising
# our initial sequence number; send an LGOOD packet.
with m.State("SEND_ACKS"):
# Send an LGOOD command, acknowledging the last received packet header.
m.d.comb += [
lc_generator.generate .eq(1),
lc_generator.command .eq(LinkCommand.LGOOD),
lc_generator.subtype .eq(next_header_to_ack)
]
# Wait until our link command is done, and then move on.
with m.If(lc_generator.done):
# Move to the next header packet in the sequence, and decrease
# the number of outstanding ACKs.
m.d.comb += dequeue_ack .eq(1)
m.d.ss += next_header_to_ack .eq(next_header_to_ack + 1)
# If this was the last ACK we had to send, move back to our dispatch state.
with m.If(acks_to_send == 1):
m.next = "DISPATCH_COMMAND"
# ISSUE_CREDITS -- header packet buffers have been freed; and we now need to notify the
# other side, so it knows we have buffers available.
with m.State("ISSUE_CREDITS"):
# Send an LCRD command, indicating that we have a free buffer.
m.d.comb += [
lc_generator.generate .eq(1),
lc_generator.command .eq(LinkCommand.LCRD),
lc_generator.subtype .eq(next_credit_to_issue)
]
# Wait until our link command is done, and then move on.
with m.If(lc_generator.done):
# Move to the next credit...
m.d.comb += dequeue_credit_issue .eq(1)
m.d.ss += next_credit_to_issue .eq(next_credit_to_issue + 1)
# If this was the last credit we had to issue, move back to our dispatch state.
with m.If(credits_to_issue == 1):
m.next = "DISPATCH_COMMAND"
# SEND_LBAD -- we've received a bad header packet; we'll need to let the other side know.
with m.State("SEND_LBAD"):
m.d.comb += [
lc_generator.generate .eq(1),
lc_generator.command .eq(LinkCommand.LBAD),
]
# Once we've sent the LBAD, we can mark is as no longer pending and return to our dispatch.
# (We can't ever have multiple LBADs queued up; as we ignore future packets after sending one.)
with m.If(lc_generator.done):
m.d.ss += lbad_pending.eq(0)
m.next = "DISPATCH_COMMAND"
# SEND_LRTY -- our transmitter has requested that we send an retry indication to the other side.
# We'll do our transmitter a favor and do so.
with m.State("SEND_LRTY"):
m.d.comb += [
lc_generator.generate .eq(1),
lc_generator.command .eq(LinkCommand.LRTY)
]
with m.If(lc_generator.done):
m.d.ss += retry_pending.eq(0)
m.next = "DISPATCH_COMMAND"
# SEND_KEEPALIVE -- our link layer timer has requested that we send a keep-alive,
# indicating that we're still in U0 and the link is still good. Do so.
with m.State("SEND_KEEPALIVE"):
# Send the correct packet type for the direction our port is facing.
command = LinkCommand.LDN if self._is_downstream_facing else LinkCommand.LUP
m.d.comb += [
lc_generator.generate .eq(1),
lc_generator.command .eq(command)
]
# Once we've send the keepalive, we can mark is as no longer pending and return to our dispatch.
# (There's no sense in sending repeated keepalives; one gets the message across.)
with m.If(lc_generator.done):
m.d.ss += keepalive_pending.eq(0)
m.next = "DISPATCH_COMMAND"
# SEND_LXU -- we're being instructed to reject a requested power-state transfer.
# We'll send an LXU packet to inform the other side of the rejection.
with m.State("SEND_LXU"):
m.d.comb += [
lc_generator.generate .eq(1),
lc_generator.command .eq(LinkCommand.LXU)
]
with m.If(lc_generator.done):
m.d.ss += lxu_pending.eq(0)
m.next = "DISPATCH_COMMAND"
return m
if __name__ == "__main__":
unittest.main()
|
m.next = "SEND_LBAD"
|
test_unicode.py
|
from unittest import TestCase
import simplejson as json
class TestUnicode(TestCase):
def test_encoding1(self):
encoder = json.JSONEncoder(encoding='utf-8')
u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
s = u.encode('utf-8')
ju = encoder.encode(u)
js = encoder.encode(s)
self.assertEquals(ju, js)
def test_encoding2(self):
u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
s = u.encode('utf-8')
ju = json.dumps(u, encoding='utf-8')
js = json.dumps(s, encoding='utf-8')
self.assertEquals(ju, js)
def test_encoding3(self):
u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
j = json.dumps(u)
self.assertEquals(j, '"\\u03b1\\u03a9"')
def test_encoding4(self):
u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
j = json.dumps([u])
self.assertEquals(j, '["\\u03b1\\u03a9"]')
def test_encoding5(self):
u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
j = json.dumps(u, ensure_ascii=False)
self.assertEquals(j, u'"' + u + u'"')
def test_encoding6(self):
u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
j = json.dumps([u], ensure_ascii=False)
self.assertEquals(j, u'["' + u + u'"]')
def test_big_unicode_encode(self):
u = u'\U0001d120'
self.assertEquals(json.dumps(u), '"\\ud834\\udd20"')
self.assertEquals(json.dumps(u, ensure_ascii=False), u'"\U0001d120"')
def test_big_unicode_decode(self):
|
def test_unicode_decode(self):
for i in range(0, 0xd7ff):
u = unichr(i)
#s = '"\\u{0:04x}"'.format(i)
s = '"\\u%04x"' % (i,)
self.assertEquals(json.loads(s), u)
def test_object_pairs_hook_with_unicode(self):
s = u'{"xkd":1, "kcw":2, "art":3, "hxm":4, "qrt":5, "pad":6, "hoy":7}'
p = [(u"xkd", 1), (u"kcw", 2), (u"art", 3), (u"hxm", 4),
(u"qrt", 5), (u"pad", 6), (u"hoy", 7)]
self.assertEqual(json.loads(s), eval(s))
self.assertEqual(json.loads(s, object_pairs_hook=lambda x: x), p)
od = json.loads(s, object_pairs_hook=json.OrderedDict)
self.assertEqual(od, json.OrderedDict(p))
self.assertEqual(type(od), json.OrderedDict)
# the object_pairs_hook takes priority over the object_hook
self.assertEqual(json.loads(s,
object_pairs_hook=json.OrderedDict,
object_hook=lambda x: None),
json.OrderedDict(p))
def test_default_encoding(self):
self.assertEquals(json.loads(u'{"a": "\xe9"}'.encode('utf-8')),
{'a': u'\xe9'})
def test_unicode_preservation(self):
self.assertEquals(type(json.loads(u'""')), unicode)
self.assertEquals(type(json.loads(u'"a"')), unicode)
self.assertEquals(type(json.loads(u'["a"]')[0]), unicode)
def test_ensure_ascii_false_returns_unicode(self):
# http://code.google.com/p/simplejson/issues/detail?id=48
self.assertEquals(type(json.dumps([], ensure_ascii=False)), unicode)
self.assertEquals(type(json.dumps(0, ensure_ascii=False)), unicode)
self.assertEquals(type(json.dumps({}, ensure_ascii=False)), unicode)
self.assertEquals(type(json.dumps("", ensure_ascii=False)), unicode)
def test_ensure_ascii_false_bytestring_encoding(self):
# http://code.google.com/p/simplejson/issues/detail?id=48
doc1 = {u'quux': 'Arr\xc3\xaat sur images'}
doc2 = {u'quux': u'Arr\xeat sur images'}
doc_ascii = '{"quux": "Arr\\u00eat sur images"}'
doc_unicode = u'{"quux": "Arr\xeat sur images"}'
self.assertEquals(json.dumps(doc1), doc_ascii)
self.assertEquals(json.dumps(doc2), doc_ascii)
self.assertEquals(json.dumps(doc1, ensure_ascii=False), doc_unicode)
self.assertEquals(json.dumps(doc2, ensure_ascii=False), doc_unicode)
|
u = u'z\U0001d120x'
self.assertEquals(json.loads('"' + u + '"'), u)
self.assertEquals(json.loads('"z\\ud834\\udd20x"'), u)
|
main_live.py
|
import argparse
import random
import torch
import torch.nn as nn
import torch.optim as optim
from model_live import GGNN
from utils.train_live import train
from utils.test_live import test
from utils.validation_live import validation
from utils.data.wy_dataset_live import bAbIDataset
from utils.data.dataloader import bAbIDataloader
parser = argparse.ArgumentParser()
parser.add_argument('--task_id', type=int, default=4, help='bAbI task id')
parser.add_argument('--question_id', type=int, default=0, help='question types')
parser.add_argument('--workers', type=int, help='number of data loading workers', default=2)
# parser.add_argument('--batchSize', type=int, default=10, help='input batch size')
parser.add_argument('--batchSize', type=int, default=10, help='input batch size')
parser.add_argument('--state_dim', type=int, default=4, help='GGNN hidden state size')
parser.add_argument('--n_steps', type=int, default=1, help='propogation steps number of GGNN')
# parser.add_argument('--niter', type=int, default=10, help='number of epochs to train for')
parser.add_argument('--niter', type=int, default=15, help='number of epochs to train for')
parser.add_argument('--lr', type=float, default=0.01, help='learning rate')
parser.add_argument('--cuda', action='store_true', help='enables cuda')
parser.add_argument('--verbal', action='store_true', help='print training info or not')
parser.add_argument('--manualSeed', type=int, help='manual seed')
parser.add_argument('--criterion', type=int, default=1)
parser.add_argument('--choice_steps', type=int, default=2)
parser.add_argument('--how_many', type=int, default=40)
opt = parser.parse_args()
# todo : shuffle before each epoch, specify the number od n_steps
if opt.manualSeed is None:
opt.manualSeed = random.randint(1, 10000)
print("Random Seed: ", opt.manualSeed)
random.seed(opt.manualSeed)
torch.manual_seed(opt.manualSeed)
opt.dataroot = '/home/yiwu/ggnn/wy/ggnn.pytorch/wy_data/live_jfree/lala'
#opt.dataroot = '/home/yiwu/ggnn/wy/ggnn.pytorch/wy_data/one'
if opt.cuda:
torch.cuda.manual_seed_all(opt.manualSeed)
def main(opt):
train_dataset = bAbIDataset(opt.dataroot, opt.question_id, "t",0,opt.how_many)
print("len(train_dataset)",len(train_dataset))
# for i, (adj_matrix, annotation, target) in enumerate(train_dataset, 0):
# print("annotation size",annotation.shape)
# print("adj_matrix size",adj_matrix.shape)
# print("target int",target)
# break
# for i, (adj_matrix, annotation, target) in enumerate(train_dataloader, 0):
# print("@annotation size",annotation.shape)
# print("@adj_matrix size",adj_matrix.shape)
# print("@target size",target.shape)
# break
validation_dataset = bAbIDataset(opt.dataroot, opt.question_id, "v", train_dataset.n_node,opt.how_many)
validation_dataloader = bAbIDataloader(validation_dataset, batch_size=opt.batchSize, \
shuffle=False, num_workers=2)
print("len(validation_dataset)",len(validation_dataset))
test_dataset = bAbIDataset(opt.dataroot, opt.question_id, "est", train_dataset.n_node,opt.how_many)
test_dataloader = bAbIDataloader(test_dataset, batch_size=opt.batchSize, \
shuffle=False, num_workers=2)
print("len(test_dataset)",len(test_dataset))
opt.annotation_dim = train_dataset.n_def # for bAbI
opt.n_edge_types = train_dataset.n_edge_types
opt.n_node = train_dataset.n_node
opt.state_dim = opt.annotation_dim
opt.n_steps = opt.n_node
if opt.choice_steps == 2:
opt.n_steps = round(opt.n_node*0.5)
elif opt.choice_steps == 3:
opt.n_steps = opt.n_node*2
elif opt.choice_steps == 4:
opt.n_steps = opt.n_node*opt.n_node
elif opt.choice_steps == 5:
opt.n_steps = round(opt.n_node*0.3)
net = GGNN(opt)
net.double()
criterion = nn.SmoothL1Loss()
if opt.criterion == 2:
criterion = torch.nn.L1Loss()
|
criterion = torch.nn.MSELoss()
if opt.cuda:
net.cuda()
criterion.cuda()
optimizer = optim.Adam(net.parameters(), lr=opt.lr)
print("opt",opt)
print(net)
for epoch in range(0, opt.niter):
train_dataloader = bAbIDataloader(train_dataset, batch_size=opt.batchSize, \
shuffle=True, num_workers=4)
print("len(train_dataloader)",len(train_dataloader))
train(epoch, train_dataloader, net, criterion, optimizer, opt)
validation(validation_dataloader, net, criterion, optimizer, opt)
test(test_dataloader, net, criterion, optimizer, opt)
if __name__ == "__main__":
main(opt)
|
elif opt.criterion == 3:
|
events.ts
|
import * as helper from '../__fixtures__/test-helper';
|
helper.createSuite('Events', (test, cb) =>
helper.writeToParser(
helper.getEventCollector(cb),
test.options.parser,
test.html
)
);
| |
projects.rs
|
use chrono::NaiveDateTime;
use schema::{users, projects};
use super::users::User;
use super::repository::Repository;
use error::AppResult;
use diesel::prelude::*;
use diesel::pg::PgConnection;
#[derive(Debug)]
pub enum ProjectID {
Number(i32),
Path(String, String),
}
impl From<i32> for ProjectID {
fn from(id: i32) -> Self {
ProjectID::Number(id)
}
}
impl<A, B> From<(A, B)> for ProjectID
where
A: AsRef<str>,
B: AsRef<str>,
{
fn from(path: (A, B)) -> Self {
ProjectID::Path(path.0.as_ref().to_owned(), path.1.as_ref().to_owned())
}
}
#[derive(Debug, Queryable, Identifiable, Associations, AsChangeset)]
#[belongs_to(User)]
pub struct Project {
pub id: i32,
pub created_at: NaiveDateTime,
pub user_id: i32,
pub name: String,
pub description: Option<String>,
}
impl Project {
pub fn find_by_id<I: Into<ProjectID>>(conn: &PgConnection, id: I) -> AppResult<Option<Self>> {
match id.into() {
ProjectID::Number(id) => {
projects::table
.filter(projects::dsl::id.eq(id))
.get_result::<Project>(&*conn)
.optional()
.map_err(Into::into)
}
ProjectID::Path(ref user, ref project) => {
users::table
.inner_join(projects::table)
.filter(users::dsl::name.eq(user.as_str()))
.filter(projects::dsl::name.eq(project.as_str()))
.get_result::<(User, Project)>(&*conn)
.map(|(_, project)| project)
.optional()
.map_err(Into::into)
}
}
}
|
let user = users::table
.filter(users::dsl::id.eq(self.user_id))
.get_result::<User>(conn)?;
Repository::open(format!("{}/{}", user.name, self.name))
}
pub fn init_repository(&self, conn: &PgConnection) -> AppResult<Repository> {
let user = users::table
.filter(users::dsl::id.eq(self.user_id))
.get_result::<User>(conn)?;
let repo = Repository::init(format!("{}/{}", user.name, self.name))?;
Ok(repo)
}
}
#[derive(Clone, Deserialize)]
pub struct NewProject {
pub user: String,
pub name: String,
pub description: Option<String>,
}
impl NewProject {
pub fn insert(&self, conn: &PgConnection) -> AppResult<Project> {
use diesel::types::{Int4, Timestamp, Text, Nullable};
use diesel::expression::dsl::sql;
let query = sql::<(Int4, Timestamp, Int4, Text, Nullable<Text>)>(&format!(
"INSERT INTO projects (user_id, name, description)
SELECT id, {}, {} FROM users
WHERE users.name = {} LIMIT 1
RETURNING *",
escape_str(&self.name),
self.description.as_ref().map(|s| escape_str(&s)).unwrap_or("NULL".to_owned()),
escape_str(&self.user),
));
let project: Project = query.get_result(&*conn)?;
project.init_repository(&*conn)?;
Ok(project)
}
}
fn escape_str(s: &str) -> String {
format!("'{}'", s.replace("'", "''"))
}
|
pub fn open_repository(&self, conn: &PgConnection) -> AppResult<Repository> {
|
move_semantics4.rs
|
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
vec1.push(88);
println!("{} has length {} content `{:?}`", "vec1", vec1.len(), vec1);
}
fn fill_vec() -> Vec<i32> {
let mut vec = Vec::new();
vec.push(22);
vec.push(44);
vec.push(66);
vec
}
|
fn main() {
let mut vec1 = fill_vec();
|
|
lib.rs
|
// extern crate time;
use std::thread;
use std::sync::mpsc::{channel, Sender, Receiver};
use std::sync::{Arc, Mutex};
use std::sync::atomic::{AtomicBool, Ordering};
use std::fmt::Debug;
// use std::time::Duration;
use std::fmt::Display;
use std::collections::HashMap;
extern crate futures;
use futures::Future;
extern crate hyper;
use hyper::Client;
use hyper::{Method, Request};
use hyper::header::{Authorization, Basic, ContentType};
extern crate hyper_tls;
use hyper_tls::HttpsConnector;
extern crate tokio_core;
use tokio_core::reactor::Core;
// ------------------------------------------------------------------------------------------------
// Worker API
// ------------------------------------------------------------------------------------------------
struct ThreadState<'a> {
alive: &'a mut Arc<AtomicBool>,
}
impl<'a> ThreadState<'a> {
fn set_alive(&self) {
self.alive.store(true, Ordering::Relaxed);
}
}
impl<'a> Drop for ThreadState<'a> {
fn drop(&mut self) {
self.alive.store(false, Ordering::Relaxed);
}
}
pub trait WorkerClosure<T, P>: Fn(&P, T) -> () + Send + Sync {}
impl<T, F, P> WorkerClosure<T, P> for F where F: Fn(&P, T) -> () + Send + Sync {}
pub struct SingleWorker<T: 'static + Send, P: Clone + Send> {
parameters: P,
f: Arc<Box<WorkerClosure<T, P, Output = ()>>>,
receiver: Arc<Mutex<Receiver<T>>>,
sender: Mutex<Sender<T>>,
alive: Arc<AtomicBool>,
}
impl<T: 'static + Debug + Send, P: 'static + Clone + Send> SingleWorker<T, P> {
pub fn new(parameters: P, f: Box<WorkerClosure<T, P, Output = ()>>) -> SingleWorker<T, P> {
let (sender, receiver) = channel::<T>();
let worker = SingleWorker {
parameters: parameters,
f: Arc::new(f),
receiver: Arc::new(Mutex::new(receiver)),
sender: Mutex::new(sender), /* too bad sender is not sync -- suboptimal.... see https://github.com/rust-lang/rfcs/pull/1299/files */
alive: Arc::new(AtomicBool::new(true)),
};
SingleWorker::spawn_thread(&worker);
worker
}
fn is_alive(&self) -> bool {
self.alive.clone().load(Ordering::Relaxed)
}
fn spawn_thread(worker: &SingleWorker<T, P>) {
let mut alive = worker.alive.clone();
let f = worker.f.clone();
let receiver = worker.receiver.clone();
let parameters = worker.parameters.clone();
thread::spawn(move || {
let state = ThreadState { alive: &mut alive };
state.set_alive();
let lock = match receiver.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
loop {
match lock.recv() {
Ok(value) => f(¶meters, value),
Err(_) => {
thread::yield_now();
}
};
}
});
while !worker.is_alive() {
thread::yield_now();
}
}
pub fn work_with(&self, msg: T) {
let alive = self.is_alive();
if !alive {
SingleWorker::spawn_thread(self);
}
let lock = match self.sender.lock() {
Ok(guard) => guard,
Err(poisoned) => poisoned.into_inner(),
};
let _ = lock.send(msg);
}
}
// ------------------------------------------------------------------------------------------------
// Segment API
// ------------------------------------------------------------------------------------------------
#[derive(Debug,Clone)]
pub struct SegmentQuery {
url: String,
body: String,
}
pub struct Segment {
worker: Arc<SingleWorker<SegmentQuery, Option<String>>>,
}
pub trait ToJsonString {
fn to_json_string(&self) -> String;
}
impl ToJsonString for String {
fn to_json_string(&self) -> String {
self.to_owned()
}
}
impl<V> ToJsonString for HashMap<&'static str, V>
where V: Display
{
fn to_json_string(&self) -> String {
let mut jstr = String::new();
jstr.push_str("{");
let mut passed = false;
for (k, v) in self {
if passed {
jstr.push_str(",");
} else {
passed = true;
}
jstr.push_str(&format!("\"{}\":\"{}\"", k, v));
}
jstr.push_str("}");
jstr
}
}
impl Segment {
pub fn new(write_key: Option<String>) -> Segment {
let worker = SingleWorker::new(write_key,
Box::new(move |write_key, query| -> () {
Segment::post(write_key, &query);
}));
Segment { worker: Arc::new(worker) }
}
fn post(write_key: &Option<String>, query: &SegmentQuery) {
if let Some(key) = write_key.clone() {
// let mut headers = Headers::new();
// headers.set();
// headers.set(ContentType::json());
let core = Core::new().unwrap();
let handle = core.handle();
let http_conn = HttpsConnector::new(4, &handle).unwrap();
let client = Client::configure()
.connector(http_conn)
.build(&handle);
// client.set_read_timeout(Some(Duration::new(5, 0)));
// client.set_write_timeout(Some(Duration::new(5, 0)));
let url = (&query.url).parse::<hyper::Uri>().unwrap();
let mut req = Request::new(Method::Post, url);
req.headers_mut().set(ContentType::json());
req.headers_mut().set(Authorization(Basic {
username: key.clone(),
password: None,
}));
match client.request(req).wait() {
Ok(response) => {
if response.status() != hyper::Ok {
println!("ERROR: Segment service returned error code {} for query {:?}",
response.status(),
query);
}
},
Err(err) => {
println!("ERROR: fail to post segment query {:?} - Error {}",
query,
err);
}
};
}
}
pub fn alias(&self, previous_id: &str, user_id: &str) {
let mut body = String::new();
body.push_str("{");
body.push_str(&format!("\"previousId\":\"{}\",", previous_id));
body.push_str(&format!("\"userId\":\"{}\"", user_id));
body.push_str("}");
self.worker.work_with(SegmentQuery {
url: "https://api.segment.io/v1/alias".to_string(),
body: body,
});
}
pub fn identify<T1: ToJsonString, T2: ToJsonString>(&self,
anonymous_id: Option<&str>,
user_id: Option<&str>,
traits: Option<T1>,
context: Option<T2>)
|
pub fn track<T1: ToJsonString, T2: ToJsonString>(&self,
anonymous_id: Option<&str>,
user_id: Option<&str>,
event: &str,
properties: Option<T1>,
context: Option<T2>) {
let mut body = String::new();
body.push_str("{");
body.push_str(&format!("\"event\":\"{}\"", event));
if let Some(anonymous_id) = anonymous_id {
body.push_str(&format!(",\"anonymousId\":\"{}\"", anonymous_id));
}
if let Some(user_id) = user_id {
body.push_str(&format!(",\"userId\":\"{}\"", user_id));
}
if let Some(properties) = properties {
body.push_str(&format!(",\"properties\":{}", properties.to_json_string()));
}
if let Some(context) = context {
body.push_str(&format!(",\"context\":{}", context.to_json_string()));
}
body.push_str("}");
self.worker.work_with(SegmentQuery {
url: "https://api.segment.io/v1/track".to_string(),
body: body,
});
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use std::thread;
use std::time::Duration;
use std::sync::Arc;
// Segment Test Key - do not abuse of it ;)
static SEGMENT_WRITE_KEY: &'static str = "okSiXGEgvMbIOjlmQFDq034TJIfnomu6";
#[test]
fn it_should_send_alias_message() {
let segment = ::Segment::new(Some(SEGMENT_WRITE_KEY.to_string()));
segment.alias("previous_id", "user_id");
// yeah I know ;)
thread::sleep(Duration::new(5, 0));
}
#[test]
fn it_should_send_identify_message() {
let segment = ::Segment::new(Some(SEGMENT_WRITE_KEY.to_string()));
let mut context = HashMap::new();
context.insert("ip", "134.157.15.3");
segment.identify(Some("anonymous_id"), None, None::<String>, Some(context));
// yeah I know ;)
thread::sleep(Duration::new(5, 0));
}
#[test]
fn it_should_send_track_message() {
let segment = ::Segment::new(Some(SEGMENT_WRITE_KEY.to_string()));
let mut properties = HashMap::new();
properties.insert("firstname", "Jimmy");
properties.insert("lastname", "Page");
segment.track(Some("anonymous_id"),
None,
"Test Event",
Some(properties),
None::<String>);
// yeah I know ;)
thread::sleep(Duration::new(5, 0));
}
#[test]
fn it_should_send_many_message() {
let segment = Arc::new(::Segment::new(Some(SEGMENT_WRITE_KEY.to_string())));
let segment1 = segment.clone();
let t1 = thread::spawn(move || {
segment1.track(Some("anonymous_id"),
None,
"Test Event 1",
None::<String>,
None::<String>)
});
let segment2 = segment.clone();
let t2 = thread::spawn(move || {
segment2.track(Some("anonymous_id"),
None,
"Test Event 2",
None::<String>,
None::<String>)
});
let _ = t1.join().unwrap();
let _ = t2.join().unwrap();
// yeah I know ;)
thread::sleep(Duration::new(5, 0));
}
}
|
{
let mut body = String::new();
body.push_str("{");
if let Some(anonymous_id) = anonymous_id {
body.push_str(&format!("\"anonymousId\":\"{}\"", anonymous_id));
}
if let Some(user_id) = user_id {
if body.len() > 1 {
body.push_str(",")
}
body.push_str(&format!("\"userId\":\"{}\"", user_id));
}
if let Some(traits) = traits {
if body.len() > 1 {
body.push_str(",")
}
body.push_str(&format!("\"traits\":{}", traits.to_json_string()));
}
if let Some(context) = context {
if body.len() > 1 {
body.push_str(",")
}
body.push_str(&format!("\"context\":{}", context.to_json_string()));
}
body.push_str("}");
self.worker.work_with(SegmentQuery {
url: "https://api.segment.io/v1/identify".to_string(),
body: body,
});
}
|
groups.rs
|
use lexer;
use lexer::LexTokenIterator;
use parser::{ParsingInterpreter, TeXToken, Context, ParsingResult, InterpreterOutput};
pub struct BeginGroupInterpreter {}
impl BeginGroupInterpreter {
pub fn new() -> Self {
BeginGroupInterpreter {}
}
}
impl ParsingInterpreter for BeginGroupInterpreter {
fn matching(&self, lexer: &LexTokenIterator) -> bool {
match lexer.peek_next() {
Some(lexer::Token::BeginGroup) => true,
_ => false,
}
}
fn run(
&self,
_: &mut Vec<TeXToken>,
lexer: &mut LexTokenIterator,
ctx: &mut Context,
) -> ParsingResult<Option<InterpreterOutput>>
|
}
pub struct EndGroupInterpreter {}
impl EndGroupInterpreter {
pub fn new() -> Self {
EndGroupInterpreter {}
}
}
impl ParsingInterpreter for EndGroupInterpreter {
fn matching(&self, lexer: &LexTokenIterator) -> bool {
match lexer.peek_next() {
Some(lexer::Token::EndGroup) => true,
_ => false,
}
}
fn run(
&self,
_: &mut Vec<TeXToken>,
lexer: &mut LexTokenIterator,
ctx: &mut Context,
) -> ParsingResult<Option<InterpreterOutput>> {
// Consume the next token.
lexer.next();
ctx.groups_mut().pop_scope();
// Reset new catcodes after the last group was popped.
lexer.set_catcode(ctx.groups().get_catcode());
Ok(None)
}
}
|
{
// Consume the next token.
lexer.next();
ctx.groups_mut().push_scope();
Ok(None)
}
|
file_filter.rs
|
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
use fnv::FnvHashSet;
use glob::Pattern;
use intern::string_key::StringKey;
use crate::{
compiler_state::ProjectSet,
config::{Config, SchemaLocation},
};
use std::path::{Path, PathBuf};
/// The FileFilter is intended to be used for input sources other than
/// Watchman. The FileFilter is created from `Config` and tries to replicate
/// the filtering done in Watchman. One addition is that this can filter
/// out files from disabled projects.
/// It allows paths defined in `config.sources` with `config.excludes` applied,
/// then allows paths defined for extensions, schemas, and output dirs.
pub struct FileFilter {
sources_roots: Vec<PathBuf>,
extra_roots: Vec<PathBuf>,
excludes: Vec<Pattern>,
}
impl FileFilter {
pub fn from_config(config: &Config) -> Self {
let mut enabled_projects_including_base = FnvHashSet::default();
for project in config.enabled_projects() {
enabled_projects_including_base.insert(project.name);
if let Some(base) = project.base {
enabled_projects_including_base.insert(base);
}
}
Self {
sources_roots: get_sources_root(config, &enabled_projects_including_base),
extra_roots: get_extra_roots(config, &enabled_projects_including_base),
excludes: config
.excludes
.iter()
.map(|p| Pattern::new(p).unwrap())
.collect(),
}
}
pub fn is_file_relevant(&self, path: &Path) -> bool {
self.extra_roots.iter().any(|root| path.starts_with(root))
|| (self.sources_roots.iter().any(|root| path.starts_with(root))
&& !self
.excludes
.iter()
.any(|exclude| exclude.matches_path(path)))
}
}
// Get roots for extensions, schemas and output dirs
fn get_extra_roots(config: &Config, enabled_projects: &FnvHashSet<StringKey>) -> Vec<PathBuf> {
let mut roots = vec![];
for project_config in config.projects.values() {
if !enabled_projects.contains(&project_config.name) {
continue;
}
roots.extend(&project_config.schema_extensions);
if let Some(output_dir) = &project_config.output {
roots.push(output_dir);
}
if let Some(output_dir) = &project_config.extra_artifacts_output {
roots.push(output_dir);
}
match &project_config.schema_location {
SchemaLocation::File(path) | SchemaLocation::Directory(path) => roots.push(path),
}
}
unify_roots(roots)
}
fn
|
(config: &Config, enabled_projects: &FnvHashSet<StringKey>) -> Vec<PathBuf> {
unify_roots(
config
.sources
.iter()
.filter_map(|(path, project_set)| {
let is_enabled = match project_set {
ProjectSet::ProjectName(name) => enabled_projects.contains(name),
ProjectSet::ProjectNames(names) => {
names.iter().any(|name| enabled_projects.contains(name))
}
};
is_enabled.then(|| path)
})
.collect(),
)
}
// A copy of watchman_query_builder::unify_roots, but takes Vec<&PathBuf> as the input
fn unify_roots(mut paths: Vec<&PathBuf>) -> Vec<PathBuf> {
paths.sort();
let mut roots = Vec::new();
for path in paths {
match roots.last() {
Some(prev) if path.starts_with(&prev) => {
// skip
}
_ => {
roots.push(path.clone());
}
}
}
roots
}
|
get_sources_root
|
gitian-build.py
|
#!/usr/bin/env python3
import argparse
import os
import subprocess
import sys
def setup():
global args, workdir
programs = ['ruby', 'git', 'apt-cacher-ng', 'make', 'wget']
if args.kvm:
programs += ['python-vm-builder', 'qemu-kvm', 'qemu-utils']
elif args.docker:
dockers = ['docker.io', 'docker-ce']
for i in dockers:
return_code = subprocess.call(['sudo', 'apt-get', 'install', '-qq', i])
if return_code == 0:
break
if return_code != 0:
print('Cannot find any way to install docker', file=sys.stderr)
exit(1)
else:
programs += ['lxc', 'debootstrap']
subprocess.check_call(['sudo', 'apt-get', 'install', '-qq'] + programs)
if not os.path.isdir('gitian.sigs.ltc'):
subprocess.check_call(['git', 'clone', 'https://github.com/cbreezycoin-project/gitian.sigs.ltc.git'])
if not os.path.isdir('cbreezycoin-detached-sigs'):
subprocess.check_call(['git', 'clone', 'https://github.com/cbreezycoin-project/cbreezycoin-detached-sigs.git'])
if not os.path.isdir('gitian-builder'):
subprocess.check_call(['git', 'clone', 'https://github.com/devrandom/gitian-builder.git'])
if not os.path.isdir('cbreezycoin'):
subprocess.check_call(['git', 'clone', 'https://github.com/cbreezycoin-project/cbreezycoin.git'])
os.chdir('gitian-builder')
make_image_prog = ['bin/make-base-vm', '--suite', 'bionic', '--arch', 'amd64']
if args.docker:
make_image_prog += ['--docker']
elif not args.kvm:
make_image_prog += ['--lxc']
subprocess.check_call(make_image_prog)
os.chdir(workdir)
if args.is_bionic and not args.kvm and not args.docker:
subprocess.check_call(['sudo', 'sed', '-i', 's/lxcbr0/br0/', '/etc/default/lxc-net'])
print('Reboot is required')
exit(0)
def build():
global args, workdir
os.makedirs('cbreezycoin-binaries/' + args.version, exist_ok=True)
print('\nBuilding Dependencies\n')
os.chdir('gitian-builder')
os.makedirs('inputs', exist_ok=True)
subprocess.check_call(['wget', '-N', '-P', 'inputs', 'https://downloads.sourceforge.net/project/osslsigncode/osslsigncode/osslsigncode-1.7.1.tar.gz'])
subprocess.check_call(['wget', '-N', '-P', 'inputs', 'https://bitcoincore.org/cfields/osslsigncode-Backports-to-1.7.1.patch'])
subprocess.check_call(["echo 'a8c4e9cafba922f89de0df1f2152e7be286aba73f78505169bc351a7938dd911 inputs/osslsigncode-Backports-to-1.7.1.patch' | sha256sum -c"], shell=True)
subprocess.check_call(["echo 'f9a8cdb38b9c309326764ebc937cba1523a3a751a7ab05df3ecc99d18ae466c9 inputs/osslsigncode-1.7.1.tar.gz' | sha256sum -c"], shell=True)
subprocess.check_call(['make', '-C', '../cbreezycoin/depends', 'download', 'SOURCES_PATH=' + os.getcwd() + '/cache/common'])
if args.linux:
print('\nCompiling ' + args.version + ' Linux')
subprocess.check_call(['bin/gbuild', '-j', args.jobs, '-m', args.memory, '--commit', 'cbreezycoin='+args.commit, '--url', 'cbreezycoin='+args.url, '../cbreezycoin/contrib/gitian-descriptors/gitian-linux.yml'])
subprocess.check_call(['bin/gsign', '-p', args.sign_prog, '--signer', args.signer, '--release', args.version+'-linux', '--destination', '../gitian.sigs.ltc/', '../cbreezycoin/contrib/gitian-descriptors/gitian-linux.yml'])
subprocess.check_call('mv build/out/cbreezycoin-*.tar.gz build/out/src/cbreezycoin-*.tar.gz ../cbreezycoin-binaries/'+args.version, shell=True)
if args.windows:
print('\nCompiling ' + args.version + ' Windows')
subprocess.check_call(['bin/gbuild', '-j', args.jobs, '-m', args.memory, '--commit', 'cbreezycoin='+args.commit, '--url', 'cbreezycoin='+args.url, '../cbreezycoin/contrib/gitian-descriptors/gitian-win.yml'])
subprocess.check_call(['bin/gsign', '-p', args.sign_prog, '--signer', args.signer, '--release', args.version+'-win-unsigned', '--destination', '../gitian.sigs.ltc/', '../cbreezycoin/contrib/gitian-descriptors/gitian-win.yml'])
subprocess.check_call('mv build/out/cbreezycoin-*-win-unsigned.tar.gz inputs/', shell=True)
subprocess.check_call('mv build/out/cbreezycoin-*.zip build/out/cbreezycoin-*.exe ../cbreezycoin-binaries/'+args.version, shell=True)
if args.macos:
print('\nCompiling ' + args.version + ' MacOS')
subprocess.check_call(['bin/gbuild', '-j', args.jobs, '-m', args.memory, '--commit', 'cbreezycoin='+args.commit, '--url', 'cbreezycoin='+args.url, '../cbreezycoin/contrib/gitian-descriptors/gitian-osx.yml'])
subprocess.check_call(['bin/gsign', '-p', args.sign_prog, '--signer', args.signer, '--release', args.version+'-osx-unsigned', '--destination', '../gitian.sigs.ltc/', '../cbreezycoin/contrib/gitian-descriptors/gitian-osx.yml'])
subprocess.check_call('mv build/out/cbreezycoin-*-osx-unsigned.tar.gz inputs/', shell=True)
subprocess.check_call('mv build/out/cbreezycoin-*.tar.gz build/out/cbreezycoin-*.dmg ../cbreezycoin-binaries/'+args.version, shell=True)
os.chdir(workdir)
if args.commit_files:
print('\nCommitting '+args.version+' Unsigned Sigs\n')
os.chdir('gitian.sigs.ltc')
subprocess.check_call(['git', 'add', args.version+'-linux/'+args.signer])
subprocess.check_call(['git', 'add', args.version+'-win-unsigned/'+args.signer])
subprocess.check_call(['git', 'add', args.version+'-osx-unsigned/'+args.signer])
subprocess.check_call(['git', 'commit', '-m', 'Add '+args.version+' unsigned sigs for '+args.signer])
os.chdir(workdir)
def sign():
global args, workdir
os.chdir('gitian-builder')
if args.windows:
print('\nSigning ' + args.version + ' Windows')
subprocess.check_call('cp inputs/cbreezycoin-' + args.version + '-win-unsigned.tar.gz inputs/cbreezycoin-win-unsigned.tar.gz', shell=True)
subprocess.check_call(['bin/gbuild', '-i', '--commit', 'signature='+args.commit, '../cbreezycoin/contrib/gitian-descriptors/gitian-win-signer.yml'])
subprocess.check_call(['bin/gsign', '-p', args.sign_prog, '--signer', args.signer, '--release', args.version+'-win-signed', '--destination', '../gitian.sigs.ltc/', '../cbreezycoin/contrib/gitian-descriptors/gitian-win-signer.yml'])
subprocess.check_call('mv build/out/cbreezycoin-*win64-setup.exe ../cbreezycoin-binaries/'+args.version, shell=True)
subprocess.check_call('mv build/out/cbreezycoin-*win32-setup.exe ../cbreezycoin-binaries/'+args.version, shell=True)
if args.macos:
print('\nSigning ' + args.version + ' MacOS')
subprocess.check_call('cp inputs/cbreezycoin-' + args.version + '-osx-unsigned.tar.gz inputs/cbreezycoin-osx-unsigned.tar.gz', shell=True)
subprocess.check_call(['bin/gbuild', '-i', '--commit', 'signature='+args.commit, '../cbreezycoin/contrib/gitian-descriptors/gitian-osx-signer.yml'])
subprocess.check_call(['bin/gsign', '-p', args.sign_prog, '--signer', args.signer, '--release', args.version+'-osx-signed', '--destination', '../gitian.sigs.ltc/', '../cbreezycoin/contrib/gitian-descriptors/gitian-osx-signer.yml'])
subprocess.check_call('mv build/out/cbreezycoin-osx-signed.dmg ../cbreezycoin-binaries/'+args.version+'/cbreezycoin-'+args.version+'-osx.dmg', shell=True)
os.chdir(workdir)
if args.commit_files:
print('\nCommitting '+args.version+' Signed Sigs\n')
os.chdir('gitian.sigs.ltc')
subprocess.check_call(['git', 'add', args.version+'-win-signed/'+args.signer])
subprocess.check_call(['git', 'add', args.version+'-osx-signed/'+args.signer])
subprocess.check_call(['git', 'commit', '-a', '-m', 'Add '+args.version+' signed binary sigs for '+args.signer])
os.chdir(workdir)
def
|
():
global args, workdir
os.chdir('gitian-builder')
print('\nVerifying v'+args.version+' Linux\n')
subprocess.check_call(['bin/gverify', '-v', '-d', '../gitian.sigs.ltc/', '-r', args.version+'-linux', '../cbreezycoin/contrib/gitian-descriptors/gitian-linux.yml'])
print('\nVerifying v'+args.version+' Windows\n')
subprocess.check_call(['bin/gverify', '-v', '-d', '../gitian.sigs.ltc/', '-r', args.version+'-win-unsigned', '../cbreezycoin/contrib/gitian-descriptors/gitian-win.yml'])
print('\nVerifying v'+args.version+' MacOS\n')
subprocess.check_call(['bin/gverify', '-v', '-d', '../gitian.sigs.ltc/', '-r', args.version+'-osx-unsigned', '../cbreezycoin/contrib/gitian-descriptors/gitian-osx.yml'])
print('\nVerifying v'+args.version+' Signed Windows\n')
subprocess.check_call(['bin/gverify', '-v', '-d', '../gitian.sigs.ltc/', '-r', args.version+'-win-signed', '../cbreezycoin/contrib/gitian-descriptors/gitian-win-signer.yml'])
print('\nVerifying v'+args.version+' Signed MacOS\n')
subprocess.check_call(['bin/gverify', '-v', '-d', '../gitian.sigs.ltc/', '-r', args.version+'-osx-signed', '../cbreezycoin/contrib/gitian-descriptors/gitian-osx-signer.yml'])
os.chdir(workdir)
def main():
global args, workdir
parser = argparse.ArgumentParser(usage='%(prog)s [options] signer version')
parser.add_argument('-c', '--commit', action='store_true', dest='commit', help='Indicate that the version argument is for a commit or branch')
parser.add_argument('-p', '--pull', action='store_true', dest='pull', help='Indicate that the version argument is the number of a github repository pull request')
parser.add_argument('-u', '--url', dest='url', default='https://github.com/cbreezycoin-project/cbreezycoin', help='Specify the URL of the repository. Default is %(default)s')
parser.add_argument('-v', '--verify', action='store_true', dest='verify', help='Verify the Gitian build')
parser.add_argument('-b', '--build', action='store_true', dest='build', help='Do a Gitian build')
parser.add_argument('-s', '--sign', action='store_true', dest='sign', help='Make signed binaries for Windows and MacOS')
parser.add_argument('-B', '--buildsign', action='store_true', dest='buildsign', help='Build both signed and unsigned binaries')
parser.add_argument('-o', '--os', dest='os', default='lwm', help='Specify which Operating Systems the build is for. Default is %(default)s. l for Linux, w for Windows, m for MacOS')
parser.add_argument('-j', '--jobs', dest='jobs', default='2', help='Number of processes to use. Default %(default)s')
parser.add_argument('-m', '--memory', dest='memory', default='2000', help='Memory to allocate in MiB. Default %(default)s')
parser.add_argument('-k', '--kvm', action='store_true', dest='kvm', help='Use KVM instead of LXC')
parser.add_argument('-d', '--docker', action='store_true', dest='docker', help='Use Docker instead of LXC')
parser.add_argument('-S', '--setup', action='store_true', dest='setup', help='Set up the Gitian building environment. Uses LXC. If you want to use KVM, use the --kvm option. Only works on Debian-based systems (Ubuntu, Debian)')
parser.add_argument('-D', '--detach-sign', action='store_true', dest='detach_sign', help='Create the assert file for detached signing. Will not commit anything.')
parser.add_argument('-n', '--no-commit', action='store_false', dest='commit_files', help='Do not commit anything to git')
parser.add_argument('signer', help='GPG signer to sign each build assert file')
parser.add_argument('version', help='Version number, commit, or branch to build. If building a commit or branch, the -c option must be specified')
args = parser.parse_args()
workdir = os.getcwd()
args.linux = 'l' in args.os
args.windows = 'w' in args.os
args.macos = 'm' in args.os
args.is_bionic = b'bionic' in subprocess.check_output(['lsb_release', '-cs'])
if args.buildsign:
args.build=True
args.sign=True
if args.kvm and args.docker:
raise Exception('Error: cannot have both kvm and docker')
args.sign_prog = 'true' if args.detach_sign else 'gpg --detach-sign'
# Set environment variable USE_LXC or USE_DOCKER, let gitian-builder know that we use lxc or docker
if args.docker:
os.environ['USE_DOCKER'] = '1'
elif not args.kvm:
os.environ['USE_LXC'] = '1'
if not 'GITIAN_HOST_IP' in os.environ.keys():
os.environ['GITIAN_HOST_IP'] = '10.0.3.1'
if not 'LXC_GUEST_IP' in os.environ.keys():
os.environ['LXC_GUEST_IP'] = '10.0.3.5'
# Disable for MacOS if no SDK found
if args.macos and not os.path.isfile('gitian-builder/inputs/MacOSX10.11.sdk.tar.gz'):
print('Cannot build for MacOS, SDK does not exist. Will build for other OSes')
args.macos = False
script_name = os.path.basename(sys.argv[0])
# Signer and version shouldn't be empty
if args.signer == '':
print(script_name+': Missing signer.')
print('Try '+script_name+' --help for more information')
exit(1)
if args.version == '':
print(script_name+': Missing version.')
print('Try '+script_name+' --help for more information')
exit(1)
# Add leading 'v' for tags
if args.commit and args.pull:
raise Exception('Cannot have both commit and pull')
args.commit = ('' if args.commit else 'v') + args.version
if args.setup:
setup()
os.chdir('cbreezycoin')
if args.pull:
subprocess.check_call(['git', 'fetch', args.url, 'refs/pull/'+args.version+'/merge'])
os.chdir('../gitian-builder/inputs/cbreezycoin')
subprocess.check_call(['git', 'fetch', args.url, 'refs/pull/'+args.version+'/merge'])
args.commit = subprocess.check_output(['git', 'show', '-s', '--format=%H', 'FETCH_HEAD'], universal_newlines=True, encoding='utf8').strip()
args.version = 'pull-' + args.version
print(args.commit)
subprocess.check_call(['git', 'fetch'])
subprocess.check_call(['git', 'checkout', args.commit])
os.chdir(workdir)
if args.build:
build()
if args.sign:
sign()
if args.verify:
verify()
if __name__ == '__main__':
main()
|
verify
|
test.py
|
import threading
import sys
is_py2 = sys.version[0] == '2'
if is_py2:
import Queue as queue
else:
import queue as queue
def isScalar(x):
return not isinstance(x, (list, tuple))
def isList(x):
return isinstance(x, (list))
def asString(x):
return str(x)
def makeDict():
return {'a': 1.0, 'c': 3.0, 'b': 2.0}
def makeTuple():
return (1.0, 2.0, 3.0)
def makeIterator(x):
return iter(x)
def makeGenerator(n):
i = 0
while i < n:
yield i
i += 1
def iterateOnThread(iter):
results = []
def iteration_worker():
for i in iter:
results.append(i)
thread = threading.Thread(target = iteration_worker)
thread.start()
while thread.isAlive():
thread.join(0.1)
return results
def invokeOnThread(f, *args, **kwargs):
result = []
def invoke_worker():
result.append(f(*args, **kwargs))
|
thread.start()
while thread.isAlive():
thread.join(0.1)
return result[0]
def reflect(x):
return x
def callFunc(f, *args, **kwargs):
return f(*args, **kwargs)
def testThrowError():
throwError()
def throwError():
raise ValueError('A very specific bad thing happened')
class PythonClass(object):
FOO = 1
BAR = 2
@classmethod
def class_method(cls):
return cls.FOO
class PythonCallable(object):
FOO = 1
BAR = 2
""" Call a callable
Args:
arg1: First argument.
"""
def __call__(self, arg1):
return arg1
def create_callable():
return PythonCallable()
dict_with_callable = dict(callable = create_callable())
|
thread = threading.Thread(target = invoke_worker)
|
workspaces.go
|
package desktopvirtualization
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/validation"
"github.com/Azure/go-autorest/tracing"
"net/http"
)
// WorkspacesClient is the client for the Workspaces methods of the Desktopvirtualization service.
type WorkspacesClient struct {
BaseClient
}
// NewWorkspacesClient creates an instance of the WorkspacesClient client.
func NewWorkspacesClient(subscriptionID string) WorkspacesClient {
return NewWorkspacesClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewWorkspacesClientWithBaseURI creates an instance of the WorkspacesClient client using a custom endpoint. Use this
// when interacting with an Azure cloud that uses a non-standard base URI (sovereign clouds, Azure stack).
func NewWorkspacesClientWithBaseURI(baseURI string, subscriptionID string) WorkspacesClient
|
// CreateOrUpdate create or update a workspace.
// Parameters:
// resourceGroupName - the name of the resource group. The name is case insensitive.
// workspaceName - the name of the workspace
// workspace - object containing Workspace definitions.
func (client WorkspacesClient) CreateOrUpdate(ctx context.Context, resourceGroupName string, workspaceName string, workspace Workspace) (result Workspace, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WorkspacesClient.CreateOrUpdate")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: client.SubscriptionID,
Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}},
{TargetValue: workspaceName,
Constraints: []validation.Constraint{{Target: "workspaceName", Name: validation.MaxLength, Rule: 24, Chain: nil},
{Target: "workspaceName", Name: validation.MinLength, Rule: 3, Chain: nil}}}}); err != nil {
return result, validation.NewError("desktopvirtualization.WorkspacesClient", "CreateOrUpdate", err.Error())
}
req, err := client.CreateOrUpdatePreparer(ctx, resourceGroupName, workspaceName, workspace)
if err != nil {
err = autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "CreateOrUpdate", nil, "Failure preparing request")
return
}
resp, err := client.CreateOrUpdateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "CreateOrUpdate", resp, "Failure sending request")
return
}
result, err = client.CreateOrUpdateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "CreateOrUpdate", resp, "Failure responding to request")
}
return
}
// CreateOrUpdatePreparer prepares the CreateOrUpdate request.
func (client WorkspacesClient) CreateOrUpdatePreparer(ctx context.Context, resourceGroupName string, workspaceName string, workspace Workspace) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"workspaceName": autorest.Encode("path", workspaceName),
}
const APIVersion = "2019-12-10-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPut(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/workspaces/{workspaceName}", pathParameters),
autorest.WithJSON(workspace),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// CreateOrUpdateSender sends the CreateOrUpdate request. The method will close the
// http.Response Body if it receives an error.
func (client WorkspacesClient) CreateOrUpdateSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// CreateOrUpdateResponder handles the response to the CreateOrUpdate request. The method always
// closes the http.Response Body.
func (client WorkspacesClient) CreateOrUpdateResponder(resp *http.Response) (result Workspace, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusCreated),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// Delete remove a workspace.
// Parameters:
// resourceGroupName - the name of the resource group. The name is case insensitive.
// workspaceName - the name of the workspace
func (client WorkspacesClient) Delete(ctx context.Context, resourceGroupName string, workspaceName string) (result autorest.Response, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WorkspacesClient.Delete")
defer func() {
sc := -1
if result.Response != nil {
sc = result.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: client.SubscriptionID,
Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}},
{TargetValue: workspaceName,
Constraints: []validation.Constraint{{Target: "workspaceName", Name: validation.MaxLength, Rule: 24, Chain: nil},
{Target: "workspaceName", Name: validation.MinLength, Rule: 3, Chain: nil}}}}); err != nil {
return result, validation.NewError("desktopvirtualization.WorkspacesClient", "Delete", err.Error())
}
req, err := client.DeletePreparer(ctx, resourceGroupName, workspaceName)
if err != nil {
err = autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "Delete", nil, "Failure preparing request")
return
}
resp, err := client.DeleteSender(req)
if err != nil {
result.Response = resp
err = autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "Delete", resp, "Failure sending request")
return
}
result, err = client.DeleteResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "Delete", resp, "Failure responding to request")
}
return
}
// DeletePreparer prepares the Delete request.
func (client WorkspacesClient) DeletePreparer(ctx context.Context, resourceGroupName string, workspaceName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"workspaceName": autorest.Encode("path", workspaceName),
}
const APIVersion = "2019-12-10-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsDelete(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/workspaces/{workspaceName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// DeleteSender sends the Delete request. The method will close the
// http.Response Body if it receives an error.
func (client WorkspacesClient) DeleteSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// DeleteResponder handles the response to the Delete request. The method always
// closes the http.Response Body.
func (client WorkspacesClient) DeleteResponder(resp *http.Response) (result autorest.Response, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK, http.StatusNoContent),
autorest.ByClosing())
result.Response = resp
return
}
// Get get a workspace.
// Parameters:
// resourceGroupName - the name of the resource group. The name is case insensitive.
// workspaceName - the name of the workspace
func (client WorkspacesClient) Get(ctx context.Context, resourceGroupName string, workspaceName string) (result Workspace, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WorkspacesClient.Get")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: client.SubscriptionID,
Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}},
{TargetValue: workspaceName,
Constraints: []validation.Constraint{{Target: "workspaceName", Name: validation.MaxLength, Rule: 24, Chain: nil},
{Target: "workspaceName", Name: validation.MinLength, Rule: 3, Chain: nil}}}}); err != nil {
return result, validation.NewError("desktopvirtualization.WorkspacesClient", "Get", err.Error())
}
req, err := client.GetPreparer(ctx, resourceGroupName, workspaceName)
if err != nil {
err = autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "Get", nil, "Failure preparing request")
return
}
resp, err := client.GetSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "Get", resp, "Failure sending request")
return
}
result, err = client.GetResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "Get", resp, "Failure responding to request")
}
return
}
// GetPreparer prepares the Get request.
func (client WorkspacesClient) GetPreparer(ctx context.Context, resourceGroupName string, workspaceName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"workspaceName": autorest.Encode("path", workspaceName),
}
const APIVersion = "2019-12-10-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/workspaces/{workspaceName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// GetSender sends the Get request. The method will close the
// http.Response Body if it receives an error.
func (client WorkspacesClient) GetSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// GetResponder handles the response to the Get request. The method always
// closes the http.Response Body.
func (client WorkspacesClient) GetResponder(resp *http.Response) (result Workspace, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// ListByResourceGroup list workspaces.
// Parameters:
// resourceGroupName - the name of the resource group. The name is case insensitive.
func (client WorkspacesClient) ListByResourceGroup(ctx context.Context, resourceGroupName string) (result WorkspaceListPage, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WorkspacesClient.ListByResourceGroup")
defer func() {
sc := -1
if result.wl.Response.Response != nil {
sc = result.wl.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: client.SubscriptionID,
Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}}}); err != nil {
return result, validation.NewError("desktopvirtualization.WorkspacesClient", "ListByResourceGroup", err.Error())
}
result.fn = client.listByResourceGroupNextResults
req, err := client.ListByResourceGroupPreparer(ctx, resourceGroupName)
if err != nil {
err = autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "ListByResourceGroup", nil, "Failure preparing request")
return
}
resp, err := client.ListByResourceGroupSender(req)
if err != nil {
result.wl.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "ListByResourceGroup", resp, "Failure sending request")
return
}
result.wl, err = client.ListByResourceGroupResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "ListByResourceGroup", resp, "Failure responding to request")
}
return
}
// ListByResourceGroupPreparer prepares the ListByResourceGroup request.
func (client WorkspacesClient) ListByResourceGroupPreparer(ctx context.Context, resourceGroupName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2019-12-10-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/workspaces", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListByResourceGroupSender sends the ListByResourceGroup request. The method will close the
// http.Response Body if it receives an error.
func (client WorkspacesClient) ListByResourceGroupSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// ListByResourceGroupResponder handles the response to the ListByResourceGroup request. The method always
// closes the http.Response Body.
func (client WorkspacesClient) ListByResourceGroupResponder(resp *http.Response) (result WorkspaceList, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listByResourceGroupNextResults retrieves the next set of results, if any.
func (client WorkspacesClient) listByResourceGroupNextResults(ctx context.Context, lastResults WorkspaceList) (result WorkspaceList, err error) {
req, err := lastResults.workspaceListPreparer(ctx)
if err != nil {
return result, autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "listByResourceGroupNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListByResourceGroupSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "listByResourceGroupNextResults", resp, "Failure sending next results request")
}
result, err = client.ListByResourceGroupResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "listByResourceGroupNextResults", resp, "Failure responding to next results request")
}
return
}
// ListByResourceGroupComplete enumerates all values, automatically crossing page boundaries as required.
func (client WorkspacesClient) ListByResourceGroupComplete(ctx context.Context, resourceGroupName string) (result WorkspaceListIterator, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WorkspacesClient.ListByResourceGroup")
defer func() {
sc := -1
if result.Response().Response.Response != nil {
sc = result.page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.page, err = client.ListByResourceGroup(ctx, resourceGroupName)
return
}
// ListBySubscription list workspaces in subscription.
func (client WorkspacesClient) ListBySubscription(ctx context.Context) (result WorkspaceListPage, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WorkspacesClient.ListBySubscription")
defer func() {
sc := -1
if result.wl.Response.Response != nil {
sc = result.wl.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: client.SubscriptionID,
Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}}}); err != nil {
return result, validation.NewError("desktopvirtualization.WorkspacesClient", "ListBySubscription", err.Error())
}
result.fn = client.listBySubscriptionNextResults
req, err := client.ListBySubscriptionPreparer(ctx)
if err != nil {
err = autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "ListBySubscription", nil, "Failure preparing request")
return
}
resp, err := client.ListBySubscriptionSender(req)
if err != nil {
result.wl.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "ListBySubscription", resp, "Failure sending request")
return
}
result.wl, err = client.ListBySubscriptionResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "ListBySubscription", resp, "Failure responding to request")
}
return
}
// ListBySubscriptionPreparer prepares the ListBySubscription request.
func (client WorkspacesClient) ListBySubscriptionPreparer(ctx context.Context) (*http.Request, error) {
pathParameters := map[string]interface{}{
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2019-12-10-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/providers/Microsoft.DesktopVirtualization/workspaces", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListBySubscriptionSender sends the ListBySubscription request. The method will close the
// http.Response Body if it receives an error.
func (client WorkspacesClient) ListBySubscriptionSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// ListBySubscriptionResponder handles the response to the ListBySubscription request. The method always
// closes the http.Response Body.
func (client WorkspacesClient) ListBySubscriptionResponder(resp *http.Response) (result WorkspaceList, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
// listBySubscriptionNextResults retrieves the next set of results, if any.
func (client WorkspacesClient) listBySubscriptionNextResults(ctx context.Context, lastResults WorkspaceList) (result WorkspaceList, err error) {
req, err := lastResults.workspaceListPreparer(ctx)
if err != nil {
return result, autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "listBySubscriptionNextResults", nil, "Failure preparing next results request")
}
if req == nil {
return
}
resp, err := client.ListBySubscriptionSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
return result, autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "listBySubscriptionNextResults", resp, "Failure sending next results request")
}
result, err = client.ListBySubscriptionResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "listBySubscriptionNextResults", resp, "Failure responding to next results request")
}
return
}
// ListBySubscriptionComplete enumerates all values, automatically crossing page boundaries as required.
func (client WorkspacesClient) ListBySubscriptionComplete(ctx context.Context) (result WorkspaceListIterator, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WorkspacesClient.ListBySubscription")
defer func() {
sc := -1
if result.Response().Response.Response != nil {
sc = result.page.Response().Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
result.page, err = client.ListBySubscription(ctx)
return
}
// Update update a workspace.
// Parameters:
// resourceGroupName - the name of the resource group. The name is case insensitive.
// workspaceName - the name of the workspace
// workspace - object containing Workspace definitions.
func (client WorkspacesClient) Update(ctx context.Context, resourceGroupName string, workspaceName string, workspace *WorkspacePatch) (result Workspace, err error) {
if tracing.IsEnabled() {
ctx = tracing.StartSpan(ctx, fqdn+"/WorkspacesClient.Update")
defer func() {
sc := -1
if result.Response.Response != nil {
sc = result.Response.Response.StatusCode
}
tracing.EndSpan(ctx, sc, err)
}()
}
if err := validation.Validate([]validation.Validation{
{TargetValue: client.SubscriptionID,
Constraints: []validation.Constraint{{Target: "client.SubscriptionID", Name: validation.MinLength, Rule: 1, Chain: nil}}},
{TargetValue: resourceGroupName,
Constraints: []validation.Constraint{{Target: "resourceGroupName", Name: validation.MaxLength, Rule: 90, Chain: nil},
{Target: "resourceGroupName", Name: validation.MinLength, Rule: 1, Chain: nil},
{Target: "resourceGroupName", Name: validation.Pattern, Rule: `^[-\w\._\(\)]+$`, Chain: nil}}},
{TargetValue: workspaceName,
Constraints: []validation.Constraint{{Target: "workspaceName", Name: validation.MaxLength, Rule: 24, Chain: nil},
{Target: "workspaceName", Name: validation.MinLength, Rule: 3, Chain: nil}}}}); err != nil {
return result, validation.NewError("desktopvirtualization.WorkspacesClient", "Update", err.Error())
}
req, err := client.UpdatePreparer(ctx, resourceGroupName, workspaceName, workspace)
if err != nil {
err = autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "Update", nil, "Failure preparing request")
return
}
resp, err := client.UpdateSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "Update", resp, "Failure sending request")
return
}
result, err = client.UpdateResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "desktopvirtualization.WorkspacesClient", "Update", resp, "Failure responding to request")
}
return
}
// UpdatePreparer prepares the Update request.
func (client WorkspacesClient) UpdatePreparer(ctx context.Context, resourceGroupName string, workspaceName string, workspace *WorkspacePatch) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
"workspaceName": autorest.Encode("path", workspaceName),
}
const APIVersion = "2019-12-10-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsContentType("application/json; charset=utf-8"),
autorest.AsPatch(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/workspaces/{workspaceName}", pathParameters),
autorest.WithQueryParameters(queryParameters))
if workspace != nil {
preparer = autorest.DecoratePreparer(preparer,
autorest.WithJSON(workspace))
}
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// UpdateSender sends the Update request. The method will close the
// http.Response Body if it receives an error.
func (client WorkspacesClient) UpdateSender(req *http.Request) (*http.Response, error) {
return client.Send(req, azure.DoRetryWithRegistration(client.Client))
}
// UpdateResponder handles the response to the Update request. The method always
// closes the http.Response Body.
func (client WorkspacesClient) UpdateResponder(resp *http.Response) (result Workspace, err error) {
err = autorest.Respond(
resp,
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
|
{
return WorkspacesClient{NewWithBaseURI(baseURI, subscriptionID)}
}
|
runMappingStepWithError.sjs
|
const flowApi = require("/data-hub/public/flow/flow-api.sjs");
const hubTest = require("/test/data-hub-test-helper.sjs");
const test = require("/test/test-helper.xqy");
const flowName = "simpleMappingFlow";
const options = {};
const contentArray = [
{ "uri": "/customer1.json", "value": { "customerId": "1" }}
];
const response = flowApi.runFlowStepOnContent(flowName, "2", contentArray, options);
const stepResponse = response.stepResponse;
const assertions = [
test.assertEqual(0, response.contentArray.length,
"Since the mapping is invalid, no content objects should have been returned"),
test.assertEqual("failed step 2", stepResponse.status),
test.assertEqual(1, stepResponse.totalEvents),
test.assertEqual(0, stepResponse.successfulEvents),
test.assertEqual(1, stepResponse.failedEvents),
test.assertEqual(1, stepResponse.stepOutput.length),
test.assertTrue(stepResponse.stepOutput[0].includes("Undefined function unknownFunction()"),
"Unexpected error message: " + stepResponse.stepOutput[0]
|
)
];
assertions;
| |
problem380_CR.py
|
__author__ = 'patras'
from domain_chargeableRobot import *
from timer import DURATION
from state import state
DURATION.TIME = {
'put': 2,
'take': 2,
'perceive': 2,
'charge': 2,
'move': 2,
'moveToEmergency': 2,
'moveCharger': 2,
'addressEmergency': 2,
'wait': 2,
}
DURATION.COUNTER = {
'put': 2,
'take': 2,
'perceive': 2,
'charge': 2,
'move': 2,
'moveToEmergency': 2,
'moveCharger': 2,
'addressEmergency': 2,
'wait': 2,
}
rv.LOCATIONS = [1, 2, 3, 4]
rv.EDGES = {1: [3], 2: [3], 3: [1, 2, 4], 4: [3]}
rv.OBJECTS=['o1']
rv.ROBOTS=['r1']
def ResetState():
state.loc = {'r1': 3}
state.charge = {'r1': 3}
state.load = {'r1': NIL}
state.pos = {'c1': 1, 'o1': UNK}
state.containers = { 1:[],2:[],3:[],4:['o1'],}
state.emergencyHandling = {'r1': False, 'r2': False}
state.view = {}
for l in rv.LOCATIONS:
state.view[l] = False
|
tasks = {
1: [['fetch', 'r1', 'o1']],
}
eventsEnv = {
}
| |
websocket.go
|
package client
import (
"encoding/json"
"fmt"
"strings"
"github.com/gorilla/websocket"
"github.com/vektah/gqlparser/gqlerror"
)
const (
connectionInitMsg = "connection_init" // Client -> Server
startMsg = "start" // Client -> Server
connectionAckMsg = "connection_ack" // Server -> Client
dataMsg = "data" // Server -> Client
errorMsg = "error" // Server -> Client
)
type operationMessage struct {
Payload json.RawMessage `json:"payload,omitempty"`
ID string `json:"id,omitempty"`
Type string `json:"type"`
}
type Subscription struct {
Close func() error
Next func(response interface{}) error
}
func errorSubscription(err error) *Subscription
|
func (p *Client) Websocket(query string, options ...Option) *Subscription {
return p.WebsocketWithPayload(query, nil, options...)
}
func (p *Client) WebsocketWithPayload(query string, initPayload map[string]interface{}, options ...Option) *Subscription {
r := p.mkRequest(query, options...)
requestBody, err := json.Marshal(r)
if err != nil {
return errorSubscription(fmt.Errorf("encode: %s", err.Error()))
}
url := strings.Replace(p.url, "http://", "ws://", -1)
url = strings.Replace(url, "https://", "wss://", -1)
c, _, err := websocket.DefaultDialer.Dial(url, nil)
if err != nil {
return errorSubscription(fmt.Errorf("dial: %s", err.Error()))
}
initMessage := operationMessage{Type: connectionInitMsg}
if initPayload != nil {
initMessage.Payload, err = json.Marshal(initPayload)
if err != nil {
return errorSubscription(fmt.Errorf("parse payload: %s", err.Error()))
}
}
if err = c.WriteJSON(initMessage); err != nil {
return errorSubscription(fmt.Errorf("init: %s", err.Error()))
}
var ack operationMessage
if err = c.ReadJSON(&ack); err != nil {
return errorSubscription(fmt.Errorf("ack: %s", err.Error()))
}
if ack.Type != connectionAckMsg {
return errorSubscription(fmt.Errorf("expected ack message, got %#v", ack))
}
if err = c.WriteJSON(operationMessage{Type: startMsg, ID: "1", Payload: requestBody}); err != nil {
return errorSubscription(fmt.Errorf("start: %s", err.Error()))
}
return &Subscription{
Close: c.Close,
Next: func(response interface{}) error {
var op operationMessage
err := c.ReadJSON(&op)
if err != nil {
return err
}
if op.Type != dataMsg {
if op.Type == errorMsg {
return fmt.Errorf(string(op.Payload))
} else {
return fmt.Errorf("expected data message, got %#v", op)
}
}
respDataRaw := map[string]interface{}{}
err = json.Unmarshal(op.Payload, &respDataRaw)
if err != nil {
return fmt.Errorf("decode: %s", err.Error())
}
if respDataRaw["errors"] != nil {
var errs []*gqlerror.Error
if err = unpack(respDataRaw["errors"], &errs); err != nil {
return err
}
if len(errs) > 0 {
return fmt.Errorf("errors: %s", errs)
}
}
return unpack(respDataRaw["data"], response)
},
}
}
|
{
return &Subscription{
Close: func() error { return nil },
Next: func(response interface{}) error {
return err
},
}
}
|
ch5_ctrl.rs
|
#[doc = "Reader of register CH5_CTRL"]
pub type R = crate::R<u32, super::CH5_CTRL>;
#[doc = "Writer for register CH5_CTRL"]
pub type W = crate::W<u32, super::CH5_CTRL>;
#[doc = "Register CH5_CTRL `reset()`'s with value 0"]
impl crate::ResetValue for super::CH5_CTRL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `SIGSEL`"]
pub type SIGSEL_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `SIGSEL`"]
pub struct SIGSEL_W<'a> {
w: &'a mut W,
}
impl<'a> SIGSEL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x07) | ((value as u32) & 0x07);
self.w
}
}
#[doc = "Source Select\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SOURCESEL_A {
#[doc = "0: No source selected"]
NONE,
#[doc = "1: Voltage Comparator"]
VCMP,
#[doc = "2: Analog Comparator 0"]
ACMP0,
#[doc = "8: Analog to Digital Converter 0"]
ADC0,
#[doc = "16: Universal Synchronous/Asynchronous Receiver/Transmitter 0"]
USART0,
#[doc = "17: Universal Synchronous/Asynchronous Receiver/Transmitter 1"]
USART1,
#[doc = "28: Timer 0"]
TIMER0,
#[doc = "29: Timer 1"]
TIMER1,
#[doc = "30: Timer 2"]
TIMER2,
#[doc = "36: Universal Serial Bus Interface"]
USB,
#[doc = "40: Real-Time Counter"]
RTC,
#[doc = "48: General purpose Input/Output"]
GPIOL,
#[doc = "49: General purpose Input/Output"]
GPIOH,
#[doc = "54: Pulse Counter 0"]
PCNT0,
}
impl From<SOURCESEL_A> for u8 {
#[inline(always)]
fn from(variant: SOURCESEL_A) -> Self {
match variant {
SOURCESEL_A::NONE => 0,
SOURCESEL_A::VCMP => 1,
SOURCESEL_A::ACMP0 => 2,
SOURCESEL_A::ADC0 => 8,
SOURCESEL_A::USART0 => 16,
SOURCESEL_A::USART1 => 17,
SOURCESEL_A::TIMER0 => 28,
SOURCESEL_A::TIMER1 => 29,
SOURCESEL_A::TIMER2 => 30,
SOURCESEL_A::USB => 36,
SOURCESEL_A::RTC => 40,
SOURCESEL_A::GPIOL => 48,
SOURCESEL_A::GPIOH => 49,
SOURCESEL_A::PCNT0 => 54,
}
}
}
#[doc = "Reader of field `SOURCESEL`"]
pub type SOURCESEL_R = crate::R<u8, SOURCESEL_A>;
impl SOURCESEL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, SOURCESEL_A> {
use crate::Variant::*;
match self.bits {
0 => Val(SOURCESEL_A::NONE),
1 => Val(SOURCESEL_A::VCMP),
2 => Val(SOURCESEL_A::ACMP0),
8 => Val(SOURCESEL_A::ADC0),
16 => Val(SOURCESEL_A::USART0),
17 => Val(SOURCESEL_A::USART1),
28 => Val(SOURCESEL_A::TIMER0),
29 => Val(SOURCESEL_A::TIMER1),
30 => Val(SOURCESEL_A::TIMER2),
36 => Val(SOURCESEL_A::USB),
40 => Val(SOURCESEL_A::RTC),
48 => Val(SOURCESEL_A::GPIOL),
49 => Val(SOURCESEL_A::GPIOH),
54 => Val(SOURCESEL_A::PCNT0),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `NONE`"]
#[inline(always)]
pub fn is_none(&self) -> bool {
*self == SOURCESEL_A::NONE
}
#[doc = "Checks if the value of the field is `VCMP`"]
#[inline(always)]
pub fn is_vcmp(&self) -> bool {
*self == SOURCESEL_A::VCMP
}
#[doc = "Checks if the value of the field is `ACMP0`"]
#[inline(always)]
pub fn is_acmp0(&self) -> bool {
*self == SOURCESEL_A::ACMP0
}
#[doc = "Checks if the value of the field is `ADC0`"]
#[inline(always)]
pub fn is_adc0(&self) -> bool {
*self == SOURCESEL_A::ADC0
}
#[doc = "Checks if the value of the field is `USART0`"]
#[inline(always)]
pub fn is_usart0(&self) -> bool {
*self == SOURCESEL_A::USART0
}
#[doc = "Checks if the value of the field is `USART1`"]
#[inline(always)]
pub fn is_usart1(&self) -> bool {
*self == SOURCESEL_A::USART1
}
#[doc = "Checks if the value of the field is `TIMER0`"]
#[inline(always)]
pub fn is_timer0(&self) -> bool {
*self == SOURCESEL_A::TIMER0
}
#[doc = "Checks if the value of the field is `TIMER1`"]
#[inline(always)]
pub fn is_timer1(&self) -> bool {
*self == SOURCESEL_A::TIMER1
}
#[doc = "Checks if the value of the field is `TIMER2`"]
#[inline(always)]
pub fn is_timer2(&self) -> bool {
*self == SOURCESEL_A::TIMER2
}
#[doc = "Checks if the value of the field is `USB`"]
#[inline(always)]
pub fn is_usb(&self) -> bool {
*self == SOURCESEL_A::USB
}
#[doc = "Checks if the value of the field is `RTC`"]
#[inline(always)]
pub fn is_rtc(&self) -> bool {
*self == SOURCESEL_A::RTC
}
#[doc = "Checks if the value of the field is `GPIOL`"]
#[inline(always)]
pub fn is_gpiol(&self) -> bool {
*self == SOURCESEL_A::GPIOL
}
#[doc = "Checks if the value of the field is `GPIOH`"]
#[inline(always)]
pub fn
|
(&self) -> bool {
*self == SOURCESEL_A::GPIOH
}
#[doc = "Checks if the value of the field is `PCNT0`"]
#[inline(always)]
pub fn is_pcnt0(&self) -> bool {
*self == SOURCESEL_A::PCNT0
}
}
#[doc = "Write proxy for field `SOURCESEL`"]
pub struct SOURCESEL_W<'a> {
w: &'a mut W,
}
impl<'a> SOURCESEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SOURCESEL_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "No source selected"]
#[inline(always)]
pub fn none(self) -> &'a mut W {
self.variant(SOURCESEL_A::NONE)
}
#[doc = "Voltage Comparator"]
#[inline(always)]
pub fn vcmp(self) -> &'a mut W {
self.variant(SOURCESEL_A::VCMP)
}
#[doc = "Analog Comparator 0"]
#[inline(always)]
pub fn acmp0(self) -> &'a mut W {
self.variant(SOURCESEL_A::ACMP0)
}
#[doc = "Analog to Digital Converter 0"]
#[inline(always)]
pub fn adc0(self) -> &'a mut W {
self.variant(SOURCESEL_A::ADC0)
}
#[doc = "Universal Synchronous/Asynchronous Receiver/Transmitter 0"]
#[inline(always)]
pub fn usart0(self) -> &'a mut W {
self.variant(SOURCESEL_A::USART0)
}
#[doc = "Universal Synchronous/Asynchronous Receiver/Transmitter 1"]
#[inline(always)]
pub fn usart1(self) -> &'a mut W {
self.variant(SOURCESEL_A::USART1)
}
#[doc = "Timer 0"]
#[inline(always)]
pub fn timer0(self) -> &'a mut W {
self.variant(SOURCESEL_A::TIMER0)
}
#[doc = "Timer 1"]
#[inline(always)]
pub fn timer1(self) -> &'a mut W {
self.variant(SOURCESEL_A::TIMER1)
}
#[doc = "Timer 2"]
#[inline(always)]
pub fn timer2(self) -> &'a mut W {
self.variant(SOURCESEL_A::TIMER2)
}
#[doc = "Universal Serial Bus Interface"]
#[inline(always)]
pub fn usb(self) -> &'a mut W {
self.variant(SOURCESEL_A::USB)
}
#[doc = "Real-Time Counter"]
#[inline(always)]
pub fn rtc(self) -> &'a mut W {
self.variant(SOURCESEL_A::RTC)
}
#[doc = "General purpose Input/Output"]
#[inline(always)]
pub fn gpiol(self) -> &'a mut W {
self.variant(SOURCESEL_A::GPIOL)
}
#[doc = "General purpose Input/Output"]
#[inline(always)]
pub fn gpioh(self) -> &'a mut W {
self.variant(SOURCESEL_A::GPIOH)
}
#[doc = "Pulse Counter 0"]
#[inline(always)]
pub fn pcnt0(self) -> &'a mut W {
self.variant(SOURCESEL_A::PCNT0)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x3f << 16)) | (((value as u32) & 0x3f) << 16);
self.w
}
}
#[doc = "Edge Detect Select\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EDSEL_A {
#[doc = "0: Signal is left as it is"]
OFF,
#[doc = "1: A one HFPERCLK cycle pulse is generated for every positive edge of the incoming signal"]
POSEDGE,
#[doc = "2: A one HFPERCLK clock cycle pulse is generated for every negative edge of the incoming signal"]
NEGEDGE,
#[doc = "3: A one HFPERCLK clock cycle pulse is generated for every edge of the incoming signal"]
BOTHEDGES,
}
impl From<EDSEL_A> for u8 {
#[inline(always)]
fn from(variant: EDSEL_A) -> Self {
match variant {
EDSEL_A::OFF => 0,
EDSEL_A::POSEDGE => 1,
EDSEL_A::NEGEDGE => 2,
EDSEL_A::BOTHEDGES => 3,
}
}
}
#[doc = "Reader of field `EDSEL`"]
pub type EDSEL_R = crate::R<u8, EDSEL_A>;
impl EDSEL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> EDSEL_A {
match self.bits {
0 => EDSEL_A::OFF,
1 => EDSEL_A::POSEDGE,
2 => EDSEL_A::NEGEDGE,
3 => EDSEL_A::BOTHEDGES,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `OFF`"]
#[inline(always)]
pub fn is_off(&self) -> bool {
*self == EDSEL_A::OFF
}
#[doc = "Checks if the value of the field is `POSEDGE`"]
#[inline(always)]
pub fn is_posedge(&self) -> bool {
*self == EDSEL_A::POSEDGE
}
#[doc = "Checks if the value of the field is `NEGEDGE`"]
#[inline(always)]
pub fn is_negedge(&self) -> bool {
*self == EDSEL_A::NEGEDGE
}
#[doc = "Checks if the value of the field is `BOTHEDGES`"]
#[inline(always)]
pub fn is_bothedges(&self) -> bool {
*self == EDSEL_A::BOTHEDGES
}
}
#[doc = "Write proxy for field `EDSEL`"]
pub struct EDSEL_W<'a> {
w: &'a mut W,
}
impl<'a> EDSEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: EDSEL_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "Signal is left as it is"]
#[inline(always)]
pub fn off(self) -> &'a mut W {
self.variant(EDSEL_A::OFF)
}
#[doc = "A one HFPERCLK cycle pulse is generated for every positive edge of the incoming signal"]
#[inline(always)]
pub fn posedge(self) -> &'a mut W {
self.variant(EDSEL_A::POSEDGE)
}
#[doc = "A one HFPERCLK clock cycle pulse is generated for every negative edge of the incoming signal"]
#[inline(always)]
pub fn negedge(self) -> &'a mut W {
self.variant(EDSEL_A::NEGEDGE)
}
#[doc = "A one HFPERCLK clock cycle pulse is generated for every edge of the incoming signal"]
#[inline(always)]
pub fn bothedges(self) -> &'a mut W {
self.variant(EDSEL_A::BOTHEDGES)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 24)) | (((value as u32) & 0x03) << 24);
self.w
}
}
#[doc = "Reader of field `ASYNC_`"]
pub type ASYNC__R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ASYNC_`"]
pub struct ASYNC__W<'a> {
w: &'a mut W,
}
impl<'a> ASYNC__W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28);
self.w
}
}
impl R {
#[doc = "Bits 0:2 - Signal Select"]
#[inline(always)]
pub fn sigsel(&self) -> SIGSEL_R {
SIGSEL_R::new((self.bits & 0x07) as u8)
}
#[doc = "Bits 16:21 - Source Select"]
#[inline(always)]
pub fn sourcesel(&self) -> SOURCESEL_R {
SOURCESEL_R::new(((self.bits >> 16) & 0x3f) as u8)
}
#[doc = "Bits 24:25 - Edge Detect Select"]
#[inline(always)]
pub fn edsel(&self) -> EDSEL_R {
EDSEL_R::new(((self.bits >> 24) & 0x03) as u8)
}
#[doc = "Bit 28 - Asynchronous reflex"]
#[inline(always)]
pub fn async_(&self) -> ASYNC__R {
ASYNC__R::new(((self.bits >> 28) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:2 - Signal Select"]
#[inline(always)]
pub fn sigsel(&mut self) -> SIGSEL_W {
SIGSEL_W { w: self }
}
#[doc = "Bits 16:21 - Source Select"]
#[inline(always)]
pub fn sourcesel(&mut self) -> SOURCESEL_W {
SOURCESEL_W { w: self }
}
#[doc = "Bits 24:25 - Edge Detect Select"]
#[inline(always)]
pub fn edsel(&mut self) -> EDSEL_W {
EDSEL_W { w: self }
}
#[doc = "Bit 28 - Asynchronous reflex"]
#[inline(always)]
pub fn async_(&mut self) -> ASYNC__W {
ASYNC__W { w: self }
}
}
|
is_gpioh
|
__init__.py
|
#!/usr/bin/python
|
"""
|
# -*- coding: utf-8 -*-
"""
Fortnite replay api blueprint
|
commands.py
|
# -*- coding: utf-8 -*-
"""Click commands."""
import os
from glob import glob
from subprocess import call
import click
from flask import current_app
from flask.cli import with_appcontext
from werkzeug.exceptions import MethodNotAllowed, NotFound
HERE = os.path.abspath(os.path.dirname(__file__))
PROJECT_ROOT = os.path.join(HERE, os.pardir)
TEST_PATH = os.path.join(PROJECT_ROOT, 'tests')
@click.command()
def test():
"""Run the tests."""
import pytest
rv = pytest.main([TEST_PATH, '--verbose'])
exit(rv)
@click.command()
@click.option('-f', '--fix-imports', default=False, is_flag=True,
help='Fix imports using isort, before linting')
def lint(fix_imports):
"""Lint and check code style with flake8 and isort."""
skip = ['node_modules', 'requirements']
root_files = glob('*.py')
root_directories = [
name for name in next(os.walk('.'))[1] if not name.startswith('.')]
files_and_directories = [
arg for arg in root_files + root_directories if arg not in skip]
def execute_tool(description, *args):
"""Execute a checking tool with its arguments."""
command_line = list(args) + files_and_directories
click.echo('{}: {}'.format(description, ' '.join(command_line)))
rv = call(command_line)
if rv != 0:
exit(rv)
if fix_imports:
execute_tool('Fixing import order', 'isort', '-rc')
execute_tool('Checking code style', 'flake8')
@click.command()
def clean():
"""Remove *.pyc and *.pyo files recursively starting at current directory.
Borrowed from Flask-Script, converted to use Click.
"""
for dirpath, dirnames, filenames in os.walk('.'):
for filename in filenames:
if filename.endswith('.pyc') or filename.endswith('.pyo'):
full_pathname = os.path.join(dirpath, filename)
click.echo('Removing {}'.format(full_pathname))
os.remove(full_pathname)
@click.command()
@click.option('--url', default=None,
help='Url to test (ex. /static/image.png)')
@click.option('--order', default='rule',
help='Property on Rule to order by (default: rule)')
@with_appcontext
def urls(url, order):
"""Display all of the url matching routes for the project.
Borrowed from Flask-Script, converted to use Click.
"""
rows = []
column_length = 0
column_headers = ('Rule', 'Endpoint', 'Arguments')
if url:
try:
rule, arguments = (
current_app.url_map
.bind('localhost')
.match(url, return_rule=True))
rows.append((rule.rule, rule.endpoint, arguments))
column_length = 3
except (NotFound, MethodNotAllowed) as e:
rows.append(('<{}>'.format(e), None, None))
column_length = 1
else:
rules = sorted(
current_app.url_map.iter_rules(),
key=lambda rule: getattr(rule, order))
for rule in rules:
rows.append((rule.rule, rule.endpoint, None))
column_length = 2
str_template = ''
table_width = 0
if column_length >= 1:
max_rule_length = max(len(r[0]) for r in rows)
max_rule_length = max_rule_length if max_rule_length > 4 else 4
str_template += '{:' + str(max_rule_length) + '}'
table_width += max_rule_length
if column_length >= 2:
max_endpoint_length = max(len(str(r[1])) for r in rows)
# max_endpoint_length = max(rows, key=len)
max_endpoint_length = (
max_endpoint_length if max_endpoint_length > 8 else 8)
str_template += ' {:' + str(max_endpoint_length) + '}'
table_width += 2 + max_endpoint_length
if column_length >= 3:
max_arguments_length = max(len(str(r[2])) for r in rows)
max_arguments_length = (
max_arguments_length if max_arguments_length > 9 else 9)
str_template += ' {:' + str(max_arguments_length) + '}'
table_width += 2 + max_arguments_length
click.echo(str_template.format(*column_headers[:column_length]))
click.echo('-' * table_width)
for row in rows:
click.echo(str_template.format(*row[:column_length]))
@click.command()
@with_appcontext
def initdb():
"""
init system data
:return:
"""
|
from goldeneye.user.models import User, Role, Permission
perms = [
Permission(name='系统测试1', slug='public.about', type='N'),
Permission(name='系统测试2', slug='public.about1', type='N'),
Permission(name='系统测试3', slug='public.about2', type='N')
]
role = Role.create(name='系统管理员', permissions=perms)
user = User(username='admin', email='[email protected]', password='admin')
user.roles.append(role)
user.save()
| |
extra_eval.py
|
import tensorflow as tf
from tensorflow.keras.callbacks import Callback
class ExtraValidation(Callback):
"""Log evaluation metrics of an extra validation set. This callback
is useful for model training scenarios where multiple validation sets
are used for evaluation (as Keras by default, provides functionality for
evaluating on a single validation set only).
The evaluation metrics are also logged to TensorBoard.
Args:
validation_data: A tf.data.Dataset pipeline used to evaluate the
model, essentially an extra validation dataset.
tensorboard_path: Path to the TensorBoard logging directory.
validation_freq: Number of epochs to wait before performing
subsequent evaluations.
"""
def
|
(self, validation_data, tensorboard_path, validation_freq=1):
super(ExtraValidation, self).__init__()
self.validation_data = validation_data
self.tensorboard_path = tensorboard_path
self.tensorboard_writer = tf.summary.create_file_writer(self.tensorboard_path)
self.validation_freq = validation_freq
def on_epoch_end(self, epoch, logs=None):
# evaluate at an interval of `validation_freq` epochs
if (epoch + 1) % self.validation_freq == 0:
# gather metric names form model
metric_names = ['{}_{}'.format('epoch', metric.name)
for metric in self.model.metrics]
# TODO: fix `model.evaluate` memory leak on TPU
# gather the evaluation metrics
scores = self.model.evaluate(self.validation_data, verbose=2)
# gather evaluation metrics to TensorBoard
with self.tensorboard_writer.as_default():
for metric_name, score in zip(metric_names, scores):
tf.summary.scalar(metric_name, score, step=epoch)
|
__init__
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.