prompt
large_stringlengths
70
991k
completion
large_stringlengths
0
1.02k
<|file_name|>setup.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python """ setup.py file for augeas """ import os prefix = os.environ.get("prefix", "/usr") from distutils.core import setup setup (name = 'python-augeas', version = '0.3.0', author = "Harald Hoyer",<|fim▁hole|> description = """Python bindings for Augeas""", py_modules = [ "augeas" ], url = "http://augeas.net/", )<|fim▁end|>
author_email = "augeas-devel@redhat.com",
<|file_name|>adaptation.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python ## \file adjoint.py # \brief python package for running adjoint problems # \author T. Lukaczyk, F. Palacios # \version 5.0.0 "Raven" # # SU2 Original Developers: Dr. Francisco D. Palacios. # Dr. Thomas D. Economon. # # SU2 Developers: Prof. Juan J. Alonso's group at Stanford University. # Prof. Piero Colonna's group at Delft University of Technology. # Prof. Nicolas R. Gauger's group at Kaiserslautern University of Technology. # Prof. Alberto Guardone's group at Polytechnic University of Milan. # Prof. Rafael Palacios' group at Imperial College London. # Prof. Edwin van der Weide's group at the University of Twente. # Prof. Vincent Terrapon's group at the University of Liege. # # Copyright (C) 2012-2017 SU2, the open-source CFD code. # # SU2 is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # SU2 is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details.<|fim▁hole|># You should have received a copy of the GNU Lesser General Public # License along with SU2. If not, see <http://www.gnu.org/licenses/>. import os, sys, shutil, copy from .. import io as su2io from .. import mesh as su2mesh def adaptation ( config , kind='' ): # local copy konfig = copy.deepcopy(config) # check kind if kind: konfig['KIND_ADAPT'] = kind kind = konfig.get('KIND_ADAPT','NONE') if kind == 'NONE': return {} # check adapted? # get adaptation function adapt_function = su2mesh.adapt.name_map[kind] # setup problem suffix = 'adapt' meshname_orig = konfig['MESH_FILENAME'] meshname_new = su2io.add_suffix( konfig['MESH_FILENAME'], suffix ) konfig['MESH_OUT_FILENAME'] = meshname_new # Run Adaptation info = adapt_function(konfig) # update super config config['MESH_FILENAME'] = meshname_new config['KIND_ADAPT'] = kind # files out files = { 'MESH' : meshname_new } # info out append_nestdict( info, { 'FILES' : files } ) return info<|fim▁end|>
#
<|file_name|>mod.rs<|end_file_name|><|fim▁begin|>// Copyright 2020 The Exonum Team // // 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. pub use self::schema::{remove_local_migration_result, Schema}; use exonum_merkledb::{ migration::{ flush_migration, rollback_migration, AbortHandle, MigrationError as DbMigrationError, MigrationHelper, }, Database, Fork, Patch, Snapshot, }; use semver::Version; use std::{ collections::{BTreeMap, HashMap}, fmt, panic, sync::{mpsc, Arc}, thread, }; use crate::{ blockchain::{Blockchain, CallInBlock, Schema as CoreSchema}, crypto::Hash, helpers::ValidateInput, messages::{AnyTx, Verified}, runtime::{ ArtifactStatus, CoreError, InstanceDescriptor, InstanceQuery, InstanceStatus, RuntimeInstance, }, }; use self::schema::{ArtifactAction, MigrationTransition, ModifiedInstanceInfo}; use super::{ error::{CallSite, CallType, CommonError, ErrorKind, ExecutionError, ExecutionFail}, execution_context::TopLevelContext, migrations::{ InstanceMigration, MigrationContext, MigrationError, MigrationScript, MigrationStatus, MigrationType, }, ArtifactId, InstanceId, InstanceSpec, InstanceState, Runtime, RuntimeFeature, RuntimeIdentifier, }; #[cfg(test)] mod migration_tests; mod schema; #[cfg(test)] mod tests; // Warning shared among several log messages. const NOT_FINAL_WARNING: &str = "NB: This operation may be rolled back if the fork with it is discarded, \ but this probability is reasonably low in most cases."; #[derive(Debug)] struct ServiceInfo { runtime_id: u32, name: String, status: InstanceStatus, } /// Lookup table for the committed service instances. #[derive(Debug, Default)] struct CommittedServices { instances: BTreeMap<InstanceId, ServiceInfo>, instance_names: HashMap<String, InstanceId>, } impl CommittedServices { fn insert(&mut self, id: InstanceId, info: ServiceInfo) { let name = info.name.clone();<|fim▁hole|> fn get_runtime_id_for_active_instance(&self, id: InstanceId) -> Option<u32> { self.instances.get(&id).and_then(|info| { if info.status.is_active() { Some(info.runtime_id) } else { None } }) } fn get_instance<'q>( &self, id: impl Into<InstanceQuery<'q>>, ) -> Option<(InstanceDescriptor, &InstanceStatus)> { let (id, info) = match id.into() { InstanceQuery::Id(id) => (id, self.instances.get(&id)?), InstanceQuery::Name(name) => { let resolved_id = *self.instance_names.get(name)?; (resolved_id, self.instances.get(&resolved_id)?) } }; Some((InstanceDescriptor::new(id, &info.name), &info.status)) } fn active_instances<'a>(&'a self) -> impl Iterator<Item = (InstanceDescriptor, u32)> + 'a { self.instances.iter().filter_map(|(&id, info)| { if info.status.is_active() { let descriptor = InstanceDescriptor::new(id, &info.name); Some((descriptor, info.runtime_id)) } else { None } }) } } #[derive(Debug)] struct MigrationThread { handle: thread::JoinHandle<Result<Hash, MigrationError>>, abort_handle: AbortHandle, } impl MigrationThread { fn join(self) -> MigrationStatus { let result = match self.handle.join() { Ok(Ok(hash)) => Ok(hash), Ok(Err(MigrationError::Custom(description))) => Err(description), Ok(Err(MigrationError::Helper(e))) => { panic!("Migration terminated with database error: {}", e); } Err(e) => Err(ExecutionError::description_from_panic(e)), }; MigrationStatus(result) } } #[derive(Debug)] struct Migrations { db: Arc<dyn Database>, threads: HashMap<String, MigrationThread>, } impl Migrations { fn new(blockchain: &Blockchain) -> Self { Self { db: blockchain.database().to_owned(), threads: HashMap::new(), } } fn report_result( res: &Result<Hash, MigrationError>, script_name: &str, instance_spec: &InstanceSpec, ) { match res { Ok(migration_hash) => { log::info!( "Successfully finished migration script \"{}\" for service {} with hash {:?}", script_name, instance_spec, migration_hash ); } Err(MigrationError::Custom(msg)) => { log::error!( "Migration script \"{}\" for {} has failed: {}", script_name, instance_spec, msg ); } Err(MigrationError::Helper(DbMigrationError::Merge(db_err))) => { log::error!( "DB error during running migration script \"{}\" for {:?}: {}", script_name, instance_spec, db_err ); } Err(MigrationError::Helper(DbMigrationError::Aborted)) => { log::info!( "Migration script \"{}\" for {:?} was aborted", script_name, instance_spec ); } } } fn add_migration( &mut self, instance_spec: InstanceSpec, data_version: Version, script: MigrationScript, ) { let db = Arc::clone(&self.db); let instance_spec_ = instance_spec.clone(); let instance_name = instance_spec.name.clone(); let script_name = script.name().to_owned(); let script_name_ = script_name.clone(); let (handle_tx, handle_rx) = mpsc::channel(); let thread_fn = move || -> Result<Hash, MigrationError> { let script_name = script.name().to_owned(); log::info!( "Starting migration script \"{}\" for service {}", script_name, instance_spec ); let (helper, abort_handle) = MigrationHelper::with_handle(Arc::clone(&db), &instance_spec.name); handle_tx.send(abort_handle).unwrap(); let mut context = MigrationContext::new(helper, instance_spec, data_version); script.execute(&mut context)?; let migration_hash = context.helper.finish()?; Ok(migration_hash) }; let handle = thread::Builder::new() .name(script_name) .spawn(move || { let res = thread_fn(); Self::report_result(&res, &script_name_, &instance_spec_); res }) .expect("Cannot spawn thread for migration script"); let prev_thread = self.threads.insert( instance_name.clone(), MigrationThread { handle, abort_handle: handle_rx.recv().unwrap(), }, ); debug_assert!( prev_thread.is_none(), "Attempt to run concurrent migrations for service `{}`", instance_name ); } fn take_completed(&mut self) -> Vec<(String, MigrationStatus)> { let completed_names: Vec<_> = self .threads .iter() .filter_map(|(name, thread)| { if thread.abort_handle.is_finished() { Some(name.to_owned()) } else { None } }) .collect(); completed_names .into_iter() .map(|name| { let thread = self.threads.remove(&name).unwrap(); (name, thread.join()) }) .collect() } } /// Opaque cache used for transaction checking. /// /// A single cache object is only valid for a single blockchain height, which **MUST** be ensured /// by the caller. Using the cache with multiple heights may lead to unpredictable results. /// /// # Examples /// /// ``` /// # use exonum::{blockchain::{Blockchain, TxCheckCache}, messages::{AnyTx, Verified}}; /// # use exonum::merkledb::{Database, TemporaryDB}; /// let mut check_cache = TxCheckCache::new(); /// let snapshot = // (blockchain snapshot) /// # TemporaryDB::new().snapshot(); /// let transactions: Vec<Verified<AnyTx>> = // ... /// # vec![]; /// /// // Check that all `transactions` are correct. /// assert!(transactions /// .iter() /// .all(|transaction| { /// Blockchain::check_tx_with_cache( /// &snapshot, /// transaction, /// &mut check_cache, /// ) /// .is_ok() /// })); /// ``` #[derive(Debug, Default)] pub struct TxCheckCache { service_states: HashMap<InstanceId, Option<InstanceStatus>>, } impl TxCheckCache { fn missing_error(service_id: InstanceId) -> ExecutionError { let msg = format!( "Cannot dispatch transaction to unknown service with ID {}", service_id ); CoreError::IncorrectInstanceId.with_description(msg) } fn non_active_error(service_id: InstanceId, status: &InstanceStatus) -> ExecutionError { let msg = format!( "Cannot dispatch transaction to non-active service `{}` (status: {})", service_id, status ); CoreError::ServiceNotActive.with_description(msg) } /// Creates a new empty cache for checking transaction validity. pub fn new() -> Self { Self::default() } fn set_missing_service(&mut self, service_id: InstanceId) { self.service_states.insert(service_id, None); } fn set_service_status(&mut self, service_id: InstanceId, status: InstanceStatus) { self.service_states.insert(service_id, Some(status)); } fn check_service_status(&self, service_id: InstanceId) -> Option<Result<(), ExecutionError>> { let status = self.service_states.get(&service_id)?.as_ref(); Some(match status { None => Err(Self::missing_error(service_id)), Some(InstanceStatus::Active) => Ok(()), Some(other_status) => Err(Self::non_active_error(service_id, other_status)), }) } } /// A collection of `Runtime`s capable of modifying the blockchain state. #[derive(Debug)] pub struct Dispatcher { runtimes: BTreeMap<u32, Box<dyn Runtime>>, service_infos: CommittedServices, migrations: Migrations, } impl Dispatcher { /// Creates a new dispatcher with the specified runtimes. pub(crate) fn new( blockchain: &Blockchain, runtimes: impl IntoIterator<Item = RuntimeInstance>, ) -> Self { let mut this = Self { runtimes: runtimes .into_iter() .map(|runtime| (runtime.id, runtime.instance)) .collect(), service_infos: CommittedServices::default(), migrations: Migrations::new(blockchain), }; for runtime in this.runtimes.values_mut() { runtime.initialize(blockchain); } this } /// Restore the dispatcher from the state which was saved in the specified snapshot. /// /// # Panics /// /// This method panics if the stored state cannot be restored. pub(crate) fn restore_state(&mut self, snapshot: &dyn Snapshot) { let schema = Schema::new(snapshot); // Restore information about the deployed services. for (artifact, state) in schema.artifacts().iter() { debug_assert_eq!( state.status, ArtifactStatus::Active, "BUG: Artifact should not be in pending state." ); self.deploy_artifact(artifact.clone(), state.deploy_spec) .unwrap_or_else(|err| { panic!( "BUG: Cannot restore blockchain state; artifact `{}` failed to deploy \ after successful previous deployment. Reported error: {}", artifact, err ); }); } // Restart active service instances. for state in schema.instances().values() { let data_version = state.data_version().to_owned(); self.update_service_status(snapshot, &state); // Restart a migration script if it is not finished locally. let status = state .status .expect("BUG: Stored service instance should have a determined status."); if let Some(target) = status.ongoing_migration_target() { if schema.local_migration_result(&state.spec.name).is_none() { self.start_migration_script(target, state.spec, data_version); } } } // Notify runtimes about the end of initialization process. for runtime in self.runtimes.values_mut() { runtime.on_resume(); } } /// Adds a built-in artifact to the dispatcher. Unlike artifacts added via `commit_artifact` + /// `deploy_artifact`, this method skips artifact commitment; the artifact /// is synchronously deployed and marked as `Active`. /// /// # Panics /// /// This method treats errors during artifact deployment as fatal and panics on them. pub(crate) fn add_builtin_artifact( &mut self, fork: &Fork, artifact: ArtifactId, payload: Vec<u8>, ) { Schema::new(fork) .add_active_artifact(&artifact, payload.clone()) .unwrap_or_else(|err| { panic!("Cannot deploy a built-in artifact: {}", err); }); self.deploy_artifact(artifact, payload) .unwrap_or_else(|err| panic!("Cannot deploy a built-in artifact: {}", err)); } /// Add a built-in service with the predefined identifier. /// /// This method must be followed by the `start_builtin_instances()` call in order /// to persist information about deployed artifacts / services. /// Multiple `add_builtin_service()` calls can be covered by a single `start_builtin_instances()`. /// /// # Panics /// /// * If instance spec contains invalid service name or artifact id. pub(crate) fn add_builtin_service( &mut self, fork: &mut Fork, spec: InstanceSpec, constructor: Vec<u8>, ) -> Result<(), ExecutionError> { // Start the built-in service instance. let name = spec.name.clone(); let context = TopLevelContext::for_block_call(self, fork, InstanceDescriptor::new(spec.id, &name)); context.call(|mut ctx| ctx.initiate_adding_service(spec, constructor)) } /// Starts all the built-in instances, creating a `Patch` with persisted changes. pub(crate) fn start_builtin_instances(&mut self, fork: Fork) -> Patch { // Mark services as active. Self::activate_pending(&fork); // Start pending services. let mut schema = Schema::new(&fork); let pending_instances = schema.take_modified_instances(); let patch = fork.into_patch(); for (state, _) in pending_instances { debug_assert_eq!( state.status, Some(InstanceStatus::Active), "BUG: The built-in service instance must have an active status at startup" ); self.update_service_status(&patch, &state); } patch } /// Initiate artifact deploy procedure in the corresponding runtime. If the deploy /// is successful, the artifact spec will be written into `artifact_sources`. /// /// # Panics /// /// * If artifact identifier is invalid. pub(crate) fn deploy_artifact( &mut self, artifact: ArtifactId, payload: Vec<u8>, ) -> Result<(), ExecutionError> { // TODO: revise dispatcher integrity checks [ECR-3743] debug_assert!(artifact.validate().is_ok()); log::info!( "Deploying artifact `{}` with payload {:?}", artifact, payload ); if let Some(runtime) = self.runtimes.get_mut(&artifact.runtime_id) { let runtime_id = artifact.runtime_id; runtime .deploy_artifact(artifact, payload) .wait() .map_err(move |mut err| { err.set_runtime_id(runtime_id); err }) } else { let msg = format!( "Cannot deploy an artifact `{}` depending on the unknown runtime with ID {}", artifact, artifact.runtime_id ); Err(CoreError::IncorrectRuntime.with_description(msg)) } } /// Commits to the artifact deployment. This means that the node will cease working /// if the block with built on top of `fork` is committed until the artifact is deployed. /// /// Until the block built on top of `fork` is committed (or if `fork` is discarded in /// favor of another block proposal), no blocking is performed. /// /// # Panics /// /// This method assumes that `deploy_artifact` was previously called for the corresponding /// `ArtifactId` and deployment was completed successfully. /// If any error happens within `commit_artifact`, it is considered either a bug in the /// `Supervisor` service or `Dispatcher` itself, and as a result, this method will panic. pub(crate) fn commit_artifact(fork: &Fork, artifact: &ArtifactId, deploy_spec: Vec<u8>) { debug_assert!(artifact.validate().is_ok(), "{:?}", artifact.validate()); Schema::new(fork) .add_pending_artifact(artifact, deploy_spec) .unwrap_or_else(|err| panic!("BUG: Can't commit the artifact, error: {}", err)); } pub(crate) fn unload_artifact( fork: &Fork, artifact: &ArtifactId, ) -> Result<(), ExecutionError> { Schema::new(fork).unload_artifact(artifact) } /// Initiates migration of an existing stopped service to a newer artifact. /// The migration script is started once the block corresponding to `fork` /// is committed. pub(crate) fn initiate_migration( &self, fork: &Fork, new_artifact: ArtifactId, service_name: &str, ) -> Result<MigrationType, ExecutionError> { let mut schema = Schema::new(fork); let instance_state = schema.check_migration_initiation(&new_artifact, service_name)?; let maybe_script = self.get_migration_script(&new_artifact, instance_state.data_version())?; let migration_type = if let Some(script) = maybe_script { let migration = InstanceMigration::new(new_artifact, script.end_version().to_owned()); schema.add_pending_migration(instance_state, migration); MigrationType::Async } else { log::info!( "Reassigning artifact for service {} to `{}`. {}", instance_state.spec, new_artifact, NOT_FINAL_WARNING ); // No migration script means that the service instance may be immediately updated to // the new artifact version. schema.fast_forward_migration(instance_state, new_artifact); MigrationType::FastForward }; Ok(migration_type) } /// Initiates migration rollback. The rollback will actually be performed once /// the block corresponding to `fork` is committed. pub(crate) fn rollback_migration( fork: &Fork, service_name: &str, ) -> Result<(), ExecutionError> { Schema::new(fork) .add_migration_rollback(service_name) .map_err(From::from) } /// Makes the node block on the specified migration after the block corresponding /// to `fork` is committed. After the block is committed, all nodes in the network /// are guaranteed to have migration data prepared for flushing. pub(crate) fn commit_migration( fork: &Fork, service_name: &str, migration_hash: Hash, ) -> Result<(), ExecutionError> { log::info!( "Committing migration for service `{}` (migration hash = {:?}). {}", service_name, migration_hash, NOT_FINAL_WARNING ); Schema::new(fork) .add_migration_commit(service_name, migration_hash) .map_err(From::from) } pub(crate) fn flush_migration( fork: &mut Fork, service_name: &str, ) -> Result<(), ExecutionError> { log::info!( "Flushing migration for service `{}`. {}", service_name, NOT_FINAL_WARNING ); Schema::new(&*fork).complete_migration(service_name)?; flush_migration(fork, service_name); Ok(()) } /// Initiates stopping an existing service instance in the blockchain. The stopping /// service is active (i.e., processes transactions and the `after_transactions` hook) /// until the block built on top of the provided `fork` is committed. pub(crate) fn initiate_stopping_service( fork: &Fork, instance_id: InstanceId, ) -> Result<(), ExecutionError> { Schema::new(fork) .initiate_simple_service_transition(instance_id, InstanceStatus::Stopped) .map_err(From::from) } pub(crate) fn initiate_freezing_service( &self, fork: &Fork, instance_id: InstanceId, ) -> Result<(), ExecutionError> { let mut schema = Schema::new(fork); let instance_state = schema.get_instance(instance_id).ok_or_else(|| { let msg = format!("Cannot freeze unknown service {}", instance_id); CoreError::IncorrectInstanceId.with_description(msg) })?; let runtime_id = instance_state.spec.artifact.runtime_id; let runtime = self.runtime_by_id(runtime_id).unwrap_or_else(|| { panic!( "BUG: runtime absent for an artifact `{}` associated with service `{}`", instance_state.spec.artifact, instance_state.spec.as_descriptor() ); }); if !runtime.is_supported(&RuntimeFeature::FreezingServices) { let runtime_description = RuntimeIdentifier::transform(runtime_id).ok().map_or_else( || format!("Runtime with ID {}", runtime_id), |id| id.to_string(), ); let msg = format!("{} does not support freezing services", runtime_description); return Err(CommonError::FeatureNotSupported.with_description(msg)); } schema .initiate_simple_service_transition(instance_id, InstanceStatus::Frozen) .map_err(From::from) } fn block_until_deployed(&mut self, artifact: ArtifactId, payload: Vec<u8>) { if !self.is_artifact_deployed(&artifact) { log::info!("Blocking until artifact `{}` is deployed", artifact); self.deploy_artifact(artifact, payload).unwrap_or_else(|e| { // In this case artifact deployment error is fatal because the deploy // was committed on the network level. panic!("Unable to deploy registered artifact. {}", e); }); } } /// Performs several shallow checks that transaction is correct. /// /// Returned `Ok(())` value doesn't necessarily mean that transaction is correct and will be /// executed successfully, but returned `Err(..)` value means that this transaction is /// **obviously** incorrect and should be declined as early as possible. pub(crate) fn check_tx( snapshot: &dyn Snapshot, tx: &Verified<AnyTx>, mut cache: Option<&mut TxCheckCache>, ) -> Result<(), ExecutionError> { let service_id = tx.as_ref().call_info.instance_id; if let Some(cache) = cache.as_deref_mut() { if let Some(res) = cache.check_service_status(service_id) { return res; } } // Currently the only check is that destination service exists, but later // functionality of this method can be extended. let instance = Schema::new(snapshot) .get_instance(service_id) .ok_or_else(|| { if let Some(cache) = cache.as_deref_mut() { cache.set_missing_service(service_id); } TxCheckCache::missing_error(service_id) })?; match instance.status { Some(InstanceStatus::Active) => { if let Some(cache) = cache.as_deref_mut() { cache.set_service_status(service_id, InstanceStatus::Active); } Ok(()) } Some(status) => { let err = TxCheckCache::non_active_error(service_id, &status); if let Some(cache) = cache.as_deref_mut() { cache.set_service_status(service_id, status); } Err(err) } None => { if let Some(cache) = cache.as_deref_mut() { cache.set_missing_service(service_id); } Err(TxCheckCache::missing_error(service_id)) } } } fn report_error(err: &ExecutionError, fork: &Fork, call: CallInBlock) { let height = CoreSchema::new(fork).next_height(); if err.kind() == ErrorKind::Unexpected { log::error!( "{} at {:?} resulted in unexpected error: {:?}", call, height, err ); } else { log::info!("{} at {:?} failed: {:?}", call, height, err); } } /// Executes transaction with the specified ID with fork isolation. pub(crate) fn execute( &self, fork: &mut Fork, tx_id: Hash, tx_index: u32, tx: &Verified<AnyTx>, ) -> Result<(), ExecutionError> { let call_info = &tx.as_ref().call_info; let (runtime_id, runtime) = self.runtime_for_service(call_info.instance_id) .ok_or_else(|| { let msg = format!( "Cannot dispatch transaction to unknown service with ID {}", call_info.instance_id ); CoreError::IncorrectInstanceId.with_description(msg) })?; let instance = self.get_service(call_info.instance_id).ok_or_else(|| { let msg = format!( "Cannot dispatch transaction to inactive service with ID {}", call_info.instance_id ); CoreError::IncorrectInstanceId.with_description(msg) })?; let context = TopLevelContext::for_transaction(self, fork, instance, tx.author(), tx_id); let mut res = context.call(|ctx| runtime.execute(ctx, call_info.method_id, &tx.as_ref().arguments)); if let Err(ref mut err) = res { fork.rollback(); err.set_runtime_id(runtime_id) .set_call_site(CallSite::from_call_info(call_info, "")); Self::report_error(err, fork, CallInBlock::transaction(tx_index)); } else { fork.flush(); } res } /// Calls service hooks of the specified type for all active services. fn call_service_hooks( &self, fork: &mut Fork, call_type: &CallType, ) -> Vec<(CallInBlock, ExecutionError)> { self.service_infos .active_instances() .filter_map(|(instance, runtime_id)| { let context = TopLevelContext::for_block_call(self, fork, instance.clone()); let call_fn = match &call_type { CallType::BeforeTransactions => Runtime::before_transactions, CallType::AfterTransactions => Runtime::after_transactions, _ => unreachable!(), }; let res = context.call(|ctx| call_fn(self.runtimes[&runtime_id].as_ref(), ctx)); if let Err(mut err) = res { fork.rollback(); err.set_runtime_id(runtime_id) .set_call_site(CallSite::new(instance.id, call_type.clone())); let call = match &call_type { CallType::BeforeTransactions => { CallInBlock::before_transactions(instance.id) } CallType::AfterTransactions => CallInBlock::after_transactions(instance.id), _ => unreachable!(), }; Self::report_error(&err, fork, call); Some((call, err)) } else { fork.flush(); None } }) .collect() } /// Calls `before_transactions` for all currently active services, isolating each call. pub(crate) fn before_transactions( &self, fork: &mut Fork, ) -> Vec<(CallInBlock, ExecutionError)> { self.call_service_hooks(fork, &CallType::BeforeTransactions) } /// Calls `after_transactions` for all currently active services, isolating each call. /// /// Changes the status of pending artifacts and services to active in the merkelized /// indexes of the dispatcher information scheme. Thus, these statuses will be equally /// calculated for precommit and actually committed block. pub(crate) fn after_transactions(&self, fork: &mut Fork) -> Vec<(CallInBlock, ExecutionError)> { let errors = self.call_service_hooks(fork, &CallType::AfterTransactions); Self::activate_pending(fork); errors } /// Commits to service instances and artifacts marked as pending in the provided `fork`. pub(crate) fn commit_block(&mut self, mut fork: Fork) -> Patch { let mut schema = Schema::new(&fork); let pending_artifacts = schema.take_pending_artifacts(); let modified_instances = schema.take_modified_instances(); // Process migration commits and rollbacks. self.block_on_migrations(&modified_instances, &mut schema); self.rollback_migrations(&modified_instances, &mut fork); // Check if any migration scripts have completed locally. Record migration results in the DB. let results = self.migrations.take_completed(); let mut schema = Schema::new(&fork); for (instance_name, result) in results { schema.add_local_migration_result(&instance_name, result); } let patch = fork.into_patch(); // Process changed artifacts, blocking on futures with pending deployments. for (artifact, action) in pending_artifacts { match action { ArtifactAction::Deploy(deploy_spec) => { self.block_until_deployed(artifact, deploy_spec); } ArtifactAction::Unload => { log::info!("Unloading artifact `{}`", artifact); let runtime = self .runtimes .get_mut(&artifact.runtime_id) .expect("BUG: Cannot obtain runtime for an unloaded artifact"); runtime.unload_artifact(&artifact); } } } // Notify runtime about changes in service instances. for (state, modified_info) in modified_instances { let data_version = state.data_version().to_owned(); let status = state .status .as_ref() .expect("BUG: Service status cannot be changed to `None`"); self.update_service_status(&patch, &state); if modified_info.migration_transition == Some(MigrationTransition::Start) { let target = status .ongoing_migration_target() .expect("BUG: Migration target is not specified for ongoing migration"); self.start_migration_script(target, state.spec, data_version); } } patch } fn get_migration_script( &self, new_artifact: &ArtifactId, data_version: &Version, ) -> Result<Option<MigrationScript>, ExecutionError> { let runtime = self.runtime_by_id(new_artifact.runtime_id).ok_or_else(|| { let msg = format!( "Cannot extract a migration script from artifact `{}` which corresponds to \ unknown runtime with ID {}", new_artifact, new_artifact.runtime_id, ); CoreError::IncorrectRuntime.with_description(msg) })?; runtime .migrate(new_artifact, data_version) .map_err(From::from) } fn start_migration_script( &mut self, new_artifact: &ArtifactId, old_service: InstanceSpec, data_version: Version, ) { let maybe_script = self .get_migration_script(new_artifact, &data_version) .unwrap_or_else(|err| { panic!( "BUG: Cannot obtain migration script for migrating {:?} to new artifact {:?}, {}", old_service, new_artifact, err ); }); let script = maybe_script.unwrap_or_else(|| { panic!( "BUG: Runtime returned no script for migrating {:?} to new artifact {:?}, \ although it earlier returned a script for the same migration", old_service, new_artifact ); }); self.migrations .add_migration(old_service, data_version, script); } /// Blocks until all committed migrations are completed with the expected outcome. /// The node will panic if the local outcome of a migration is unexpected. fn block_on_migrations( &mut self, modified_instances: &[(InstanceState, ModifiedInstanceInfo)], schema: &mut Schema<&Fork>, ) { let committed_migrations = modified_instances.iter().filter(|(_, modified_info)| { modified_info.migration_transition == Some(MigrationTransition::Commit) }); for (state, _) in committed_migrations { let migration_hash = state .status .as_ref() .and_then(InstanceStatus::completed_migration_hash) .expect("BUG: No migration hash saved for committed migration"); let instance_name = &state.spec.name; let local_result = schema.local_migration_result(instance_name); let local_result = self.block_on_migration(instance_name, migration_hash, local_result); schema.add_local_migration_result(instance_name, local_result); } } fn block_on_migration( &mut self, namespace: &str, global_hash: Hash, local_result: Option<MigrationStatus>, ) -> MigrationStatus { let local_result = if let Some(thread) = self.migrations.threads.remove(namespace) { log::info!("Blocking on migration script for service `{}`", namespace); // If the migration script hasn't finished locally, wait until it's finished. thread.join() } else { // If the local script has finished, the result should be recorded in the database. local_result.unwrap_or_else(|| { panic!( "BUG: migration is marked as completed for service `{}`, but its result \ is missing from the database", namespace ); }) }; // Check if the local result agrees with the global one. Any deviation is considered // a consensus failure. let res = local_result.0.as_ref(); let local_hash = *res.unwrap_or_else(|err| { panic!( "Migration for service `{}` is committed with migration hash {:?}, \ but locally it has finished with an error: {}. You can remove local \ migration result with CLI maintenance command `restart-migration`.", namespace, global_hash, err ); }); assert!( local_hash == global_hash, "Migration for service `{}` is committed with migration hash {:?}, \ but locally it has finished with another hash {:?}. You can remove local \ migration result with CLI maintenance command `restart-migration`.", namespace, global_hash, local_hash ); local_result } fn rollback_migrations( &mut self, modified_instances: &[(InstanceState, ModifiedInstanceInfo)], fork: &mut Fork, ) { let migration_rollbacks = modified_instances.iter().filter(|(_, modified_info)| { modified_info.migration_transition == Some(MigrationTransition::Rollback) }); for (state, _) in migration_rollbacks { log::info!("Rolling back migration for service {}", state.spec); // Remove the thread corresponding to the migration (if any). This will abort // the migration script since its `AbortHandle` is dropped. let namespace = &state.spec.name; self.migrations.threads.remove(namespace); rollback_migration(fork, namespace); } } /// Make pending artifacts and instances active. pub(crate) fn activate_pending(fork: &Fork) { Schema::new(fork).activate_pending() } /// Notifies runtimes about a committed block. pub(crate) fn notify_runtimes_about_commit(&mut self, snapshot: &dyn Snapshot) { let mut mailbox = Mailbox::default(); for runtime in self.runtimes.values_mut() { runtime.after_commit(snapshot, &mut mailbox); } for action in mailbox.actions { action.execute(self); } } /// Performs the complete set of operations after committing a block. Returns a patch /// corresponding to the fork. /// /// This method should be called for all blocks except for the genesis block. For reasons /// described in `BlockchainMut::create_genesis_block()`, the processing of the genesis /// block is split into 2 parts. pub(crate) fn commit_block_and_notify_runtimes(&mut self, fork: Fork) -> Patch { let patch = self.commit_block(fork); self.notify_runtimes_about_commit(&patch); patch } /// Return true if the artifact with the given identifier is deployed. pub(crate) fn is_artifact_deployed(&self, id: &ArtifactId) -> bool { if let Some(runtime) = self.runtimes.get(&id.runtime_id) { runtime.is_artifact_deployed(id) } else { false } } /// Looks up a runtime by its identifier. pub(crate) fn runtime_by_id(&self, id: u32) -> Option<&dyn Runtime> { self.runtimes.get(&id).map(AsRef::as_ref) } /// Looks up the runtime for the specified service instance. Returns a reference to /// the runtime, or `None` if the service with the specified instance ID does not exist. pub(crate) fn runtime_for_service( &self, instance_id: InstanceId, ) -> Option<(u32, &dyn Runtime)> { let runtime_id = self .service_infos .get_runtime_id_for_active_instance(instance_id)?; let runtime = self.runtimes[&runtime_id].as_ref(); Some((runtime_id, runtime)) } /// Returns the service matching the specified query. pub(crate) fn get_service<'q>( &self, id: impl Into<InstanceQuery<'q>>, ) -> Option<InstanceDescriptor> { let (descriptor, status) = self.service_infos.get_instance(id)?; if status.is_active() { Some(descriptor) } else { None } } /// Commits service instance status to the corresponding runtime. /// /// # Panics /// /// This method assumes that it was previously checked if runtime can change the state /// of the service, and will panic if it cannot be done. fn update_service_status(&mut self, snapshot: &dyn Snapshot, instance: &InstanceState) { let runtime_id = instance.spec.artifact.runtime_id; // Notify the runtime that the service has been committed. let runtime = self.runtimes.get_mut(&runtime_id).expect( "BUG: `update_service_status` was invoked for incorrect runtime, \ this should never happen because of preemptive checks.", ); runtime.update_service_status(snapshot, instance); let status = instance .status .clone() .expect("BUG: instance status cannot change to `None`"); log::info!( "Assigning status \"{}\" to service {}", status, instance.spec ); self.service_infos.insert( instance.spec.id, ServiceInfo { runtime_id, name: instance.spec.name.clone(), status, }, ); } } /// Mailbox accumulating `Action`s to be performed by the dispatcher. #[derive(Debug, Default)] pub struct Mailbox { actions: Vec<Action>, } impl Mailbox { /// Appends a new action to be performed by the dispatcher. pub fn push(&mut self, action: Action) { self.actions.push(action); } } /// The actions that will be performed after the deployment is finished. pub type ThenFn = Box<dyn FnOnce(Result<(), ExecutionError>) -> Result<(), ExecutionError> + Send>; /// Action to be performed by the dispatcher. #[non_exhaustive] pub enum Action { /// Start artifact deployment. StartDeploy { /// Information uniquely identifying the artifact. artifact: ArtifactId, /// Runtime-specific artifact payload. spec: Vec<u8>, /// The actions that will be performed after the deployment is finished. /// For example, this closure may create a transaction with the deployment confirmation. then: ThenFn, }, } impl fmt::Debug for Action { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::StartDeploy { artifact, spec, .. } => formatter .debug_struct("StartDeploy") .field("artifact", artifact) .field("spec", spec) .finish(), } } } impl Action { fn execute(self, dispatcher: &mut Dispatcher) { match self { Self::StartDeploy { artifact, spec, then, } => { then(dispatcher.deploy_artifact(artifact.clone(), spec)).unwrap_or_else(|e| { log::error!("Deploying artifact {:?} failed: {}", artifact, e); }); } } } }<|fim▁end|>
self.instances.insert(id, info); self.instance_names.insert(name, id); }
<|file_name|>weighted_random_bools.rs<|end_file_name|><|fim▁begin|>use itertools::Itertools; use malachite_base::bools::random::weighted_random_bools; use malachite_base::random::EXAMPLE_SEED; use malachite_base_test_util::stats::common_values_map::common_values_map; use malachite_base_test_util::stats::median; fn weighted_random_bools_helper( p_numerator: u64, p_denominator: u64, expected_values: &[bool],<|fim▁hole|> let xs = weighted_random_bools(EXAMPLE_SEED, p_numerator, p_denominator); let values = xs.clone().take(20).collect_vec(); let common_values = common_values_map(1000000, 10, xs.clone()); let median = median(xs.take(1000000)); assert_eq!( (values.as_slice(), common_values.as_slice(), median), (expected_values, expected_common_values, expected_median) ); } #[test] fn test_weighted_random_bools() { // p = 0 weighted_random_bools_helper(0, 1, &[false; 20], &[(false, 1000000)], (false, None)); // p = 1 weighted_random_bools_helper(1, 1, &[true; 20], &[(true, 1000000)], (true, None)); // p = 1/2 weighted_random_bools_helper( 1, 2, &[ false, true, true, true, false, false, false, true, false, false, false, false, true, false, false, false, false, true, false, true, ], &[(false, 500473), (true, 499527)], (false, None), ); // p = 1/51 weighted_random_bools_helper( 1, 51, &[ false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, ], &[(false, 980406), (true, 19594)], (false, None), ); // w = 50/51 weighted_random_bools_helper( 50, 51, &[ true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, false, true, true, true, ], &[(true, 980602), (false, 19398)], (true, None), ); } #[test] #[should_panic] fn weighted_random_bools_fail_1() { weighted_random_bools(EXAMPLE_SEED, 1, 0); } #[test] #[should_panic] fn weighted_random_bools_fail_2() { weighted_random_bools(EXAMPLE_SEED, 2, 1); }<|fim▁end|>
expected_common_values: &[(bool, usize)], expected_median: (bool, Option<bool>), ) {
<|file_name|>index.js<|end_file_name|><|fim▁begin|>/** * Created by dmitry on 21.11.16. */ import React, { Component } from 'react'; import { Container, Content, Spinner } from 'native-base'; // TODO: Рядом лежат спиннеры, поди можно прикрячить<|fim▁hole|> <Container> <Content contentContainerStyle={{ flex: 1, flexDirection: 'row', justifyContent: 'center' }}> <Spinner color="blue"/> </Content> </Container> ); } }<|fim▁end|>
export default class Loading extends Component { render() { return (
<|file_name|>getopt.py<|end_file_name|><|fim▁begin|><|fim▁hole|><|fim▁end|>
raise NotImplementedError("getopt is not yet implemented in Skulpt")
<|file_name|>sensor.py<|end_file_name|><|fim▁begin|>"""Support for monitoring OctoPrint sensors.""" from __future__ import annotations from datetime import datetime, timedelta import logging from pyoctoprintapi import OctoprintJobInfo, OctoprintPrinterInfo from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorStateClass, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import PERCENTAGE, TEMP_CELSIUS from homeassistant.core import HomeAssistant from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.helpers.update_coordinator import CoordinatorEntity from . import OctoprintDataUpdateCoordinator from .const import DOMAIN _LOGGER = logging.getLogger(__name__) JOB_PRINTING_STATES = ["Printing from SD", "Printing"] def _is_printer_printing(printer: OctoprintPrinterInfo) -> bool: return ( printer and printer.state and printer.state.flags and printer.state.flags.printing ) async def async_setup_entry( hass: HomeAssistant, config_entry: ConfigEntry, async_add_entities: AddEntitiesCallback, ) -> None: """Set up the available OctoPrint binary sensors.""" coordinator: OctoprintDataUpdateCoordinator = hass.data[DOMAIN][ config_entry.entry_id ]["coordinator"] device_id = config_entry.unique_id assert device_id is not None entities: list[SensorEntity] = [] if coordinator.data["printer"]: printer_info = coordinator.data["printer"] types = ["actual", "target"] for tool in printer_info.temperatures: for temp_type in types: entities.append( OctoPrintTemperatureSensor( coordinator, tool.name, temp_type, device_id, ) ) else: _LOGGER.error("Printer appears to be offline, skipping temperature sensors") entities.append(OctoPrintStatusSensor(coordinator, device_id)) entities.append(OctoPrintJobPercentageSensor(coordinator, device_id)) entities.append(OctoPrintEstimatedFinishTimeSensor(coordinator, device_id)) entities.append(OctoPrintStartTimeSensor(coordinator, device_id)) async_add_entities(entities) class OctoPrintSensorBase(CoordinatorEntity, SensorEntity): """Representation of an OctoPrint sensor.""" coordinator: OctoprintDataUpdateCoordinator def __init__(<|fim▁hole|> ) -> None: """Initialize a new OctoPrint sensor.""" super().__init__(coordinator) self._device_id = device_id self._attr_name = f"OctoPrint {sensor_type}" self._attr_unique_id = f"{sensor_type}-{device_id}" @property def device_info(self): """Device info.""" return self.coordinator.device_info class OctoPrintStatusSensor(OctoPrintSensorBase): """Representation of an OctoPrint sensor.""" _attr_icon = "mdi:printer-3d" def __init__( self, coordinator: OctoprintDataUpdateCoordinator, device_id: str ) -> None: """Initialize a new OctoPrint sensor.""" super().__init__(coordinator, "Current State", device_id) @property def native_value(self): """Return sensor state.""" printer: OctoprintPrinterInfo = self.coordinator.data["printer"] if not printer: return None return printer.state.text @property def available(self) -> bool: """Return if entity is available.""" return self.coordinator.last_update_success and self.coordinator.data["printer"] class OctoPrintJobPercentageSensor(OctoPrintSensorBase): """Representation of an OctoPrint sensor.""" _attr_native_unit_of_measurement = PERCENTAGE _attr_icon = "mdi:file-percent" def __init__( self, coordinator: OctoprintDataUpdateCoordinator, device_id: str ) -> None: """Initialize a new OctoPrint sensor.""" super().__init__(coordinator, "Job Percentage", device_id) @property def native_value(self): """Return sensor state.""" job: OctoprintJobInfo = self.coordinator.data["job"] if not job: return None if not (state := job.progress.completion): return 0 return round(state, 2) class OctoPrintEstimatedFinishTimeSensor(OctoPrintSensorBase): """Representation of an OctoPrint sensor.""" _attr_device_class = SensorDeviceClass.TIMESTAMP def __init__( self, coordinator: OctoprintDataUpdateCoordinator, device_id: str ) -> None: """Initialize a new OctoPrint sensor.""" super().__init__(coordinator, "Estimated Finish Time", device_id) @property def native_value(self) -> datetime | None: """Return sensor state.""" job: OctoprintJobInfo = self.coordinator.data["job"] if ( not job or not job.progress.print_time_left or not _is_printer_printing(self.coordinator.data["printer"]) ): return None read_time = self.coordinator.data["last_read_time"] return read_time + timedelta(seconds=job.progress.print_time_left) class OctoPrintStartTimeSensor(OctoPrintSensorBase): """Representation of an OctoPrint sensor.""" _attr_device_class = SensorDeviceClass.TIMESTAMP def __init__( self, coordinator: OctoprintDataUpdateCoordinator, device_id: str ) -> None: """Initialize a new OctoPrint sensor.""" super().__init__(coordinator, "Start Time", device_id) @property def native_value(self) -> datetime | None: """Return sensor state.""" job: OctoprintJobInfo = self.coordinator.data["job"] if ( not job or not job.progress.print_time or not _is_printer_printing(self.coordinator.data["printer"]) ): return None read_time = self.coordinator.data["last_read_time"] return read_time - timedelta(seconds=job.progress.print_time) class OctoPrintTemperatureSensor(OctoPrintSensorBase): """Representation of an OctoPrint sensor.""" _attr_native_unit_of_measurement = TEMP_CELSIUS _attr_device_class = SensorDeviceClass.TEMPERATURE _attr_state_class = SensorStateClass.MEASUREMENT def __init__( self, coordinator: OctoprintDataUpdateCoordinator, tool: str, temp_type: str, device_id: str, ) -> None: """Initialize a new OctoPrint sensor.""" super().__init__(coordinator, f"{temp_type} {tool} temp", device_id) self._temp_type = temp_type self._api_tool = tool @property def native_value(self): """Return sensor state.""" printer: OctoprintPrinterInfo = self.coordinator.data["printer"] if not printer: return None for temp in printer.temperatures: if temp.name == self._api_tool: val = ( temp.actual_temp if self._temp_type == "actual" else temp.target_temp ) if val is None: return None return round(val, 2) return None @property def available(self) -> bool: """Return if entity is available.""" return self.coordinator.last_update_success and self.coordinator.data["printer"]<|fim▁end|>
self, coordinator: OctoprintDataUpdateCoordinator, sensor_type: str, device_id: str,
<|file_name|>updateView.py<|end_file_name|><|fim▁begin|>import os import shutil import addSubproject import option import utility import grapeGit as git import grapeConfig import grapeMenu import checkout # update your custom sparse checkout view class UpdateView(option.Option): """ grape uv - Updates your active submodules and ensures you are on a consistent branch throughout your project. Usage: grape-uv [-f ] [--checkSubprojects] [-b] [--skipSubmodules] [--allSubmodules] [--skipNestedSubprojects] [--allNestedSubprojects] [--sync=<bool>] [--add=<addedSubmoduleOrSubproject>...] [--rm=<removedSubmoduleOrSubproject>...] Options: -f Force removal of subprojects currently in your view that are taken out of the view as a result to this call to uv. --checkSubprojects Checks for branch model consistency across your submodules and subprojects, but does not go through the 'which submodules do you want' script. -b Automatically creates subproject branches that should be there according to your branching model. --allSubmodules Automatically add all submodules to your workspace. --allNestedSubprojects Automatically add all nested subprojects to your workspace. --sync=<bool> Take extra steps to ensure the branch you're on is up to date with origin, either by pushing or pulling the remote tracking branch. This will also checkout the public branch in a headless state prior to offering to create a new branch (in repositories where the current branch does not exist). [default: .grapeconfig.post-checkout.syncWithOrigin] --add=<project> Submodule or subproject to add to the workspace. Can be defined multiple times. --remove=<project> Submodule or subproject to remove from the workspace. Can be defined multiple times. """ def __init__(self): super(UpdateView, self).__init__() self._key = "uv" self._section = "Workspace" self._pushBranch = False self._skipPush = False def description(self): return "Update the view of your current working tree" @staticmethod def defineActiveSubmodules(projectType="submodule"): """ Queries the user for the submodules (projectType == "submodule") or nested subprojects (projectType == "nested subproject") they would like to activate. """ if projectType == "submodule": allSubprojects = git.getAllSubmodules() activeSubprojects = git.getActiveSubmodules() if projectType == "nested subproject": config = grapeConfig.grapeConfig() allSubprojectNames = config.getAllNestedSubprojects() allSubprojects = [] for project in allSubprojectNames: allSubprojects.append(config.get("nested-%s" % project, "prefix")) activeSubprojects = grapeConfig.GrapeConfigParser.getAllActiveNestedSubprojectPrefixes() toplevelDirs = {} toplevelActiveDirs = {} toplevelSubs = [] for sub in allSubprojects: # we are taking advantage of the fact that branchPrefixes are the same as directory prefixes for local # top-level dirs. prefix = git.branchPrefix(sub) if sub != prefix: toplevelDirs[prefix] = [] toplevelActiveDirs[prefix] = [] for sub in allSubprojects: prefix = git.branchPrefix(sub) if sub != prefix: toplevelDirs[prefix].append(sub) else: toplevelSubs.append(sub) for sub in activeSubprojects: prefix = git.branchPrefix(sub) if sub != prefix: toplevelActiveDirs[prefix].append(sub) included = {} for directory, subprojects in toplevelDirs.items(): activeDir = toplevelActiveDirs[directory] if len(activeDir) == 0: defaultValue = "none" elif set(activeDir) == set(subprojects): defaultValue = "all" else: defaultValue = "some" opt = utility.userInput("Would you like all, some, or none of the %ss in %s?" % (projectType,directory), default=defaultValue) if opt.lower()[0] == "a": for subproject in subprojects: included[subproject] = True if opt.lower()[0] == "n": for subproject in subprojects: included[subproject] = False if opt.lower()[0] == "s": for subproject in subprojects: included[subproject] = utility.userInput("Would you like %s %s? [y/n]" % (projectType, subproject), 'y' if (subproject in activeSubprojects) else 'n') for subproject in toplevelSubs: included[subproject] = utility.userInput("Would you like %s %s? [y/n]" % (projectType, subproject), 'y' if (subproject in activeSubprojects) else 'n') return included @staticmethod def defineActiveNestedSubprojects(): """ Queries the user for the nested subprojects they would like to activate. """ return UpdateView.defineActiveSubmodules(projectType="nested subproject") def execute(self, args): sync = args["--sync"].lower().strip() sync = sync == "true" or sync == "yes" args["--sync"] = sync config = grapeConfig.grapeConfig() origwd = os.getcwd() wsDir = utility.workspaceDir() os.chdir(wsDir) base = git.baseDir() if base == "": return False hasSubmodules = len(git.getAllSubmodules()) > 0 and not args["--skipSubmodules"] includedSubmodules = {} includedNestedSubprojectPrefixes = {} allSubmodules = git.getAllSubmodules() allNestedSubprojects = config.getAllNestedSubprojects() addedSubmodules = [] addedNestedSubprojects = [] addedProjects = args["--add"] notFound = [] for proj in addedProjects: if proj in allSubmodules: addedSubmodules.append(proj) elif proj in allNestedSubprojects: addedNestedSubprojects.append(proj) else: notFound.append(proj) rmSubmodules = [] rmNestedSubprojects = [] rmProjects = args["--rm"] for proj in rmProjects: if proj in allSubmodules: rmSubmodules.append(proj) elif proj in allNestedSubprojects: rmNestedSubprojects.append(proj) else: notFound.append(proj) if notFound: utility.printMsg("\"%s\" not found in submodules %s \nor\n nested subprojects %s" % (",".join(notFound),",".join(allSubmodules),",".join(allNestedSubprojects))) return False if not args["--checkSubprojects"]: # get submodules to update if hasSubmodules: if args["--allSubmodules"]: includedSubmodules = {sub:True for sub in allSubmodules} elif args["--add"] or args["--rm"]: includedSubmodules = {sub:True for sub in git.getActiveSubmodules()} includedSubmodules.update({sub:True for sub in addedSubmodules}) includedSubmodules.update({sub:False for sub in rmSubmodules}) else: includedSubmodules = self.defineActiveSubmodules() # get subprojects to update if not args["--skipNestedSubprojects"]: nestedPrefixLookup = lambda x : config.get("nested-%s" % x, "prefix") if args["--allNestedSubprojects"]: includedNestedSubprojectPrefixes = {nestedPrefixLookup(sub):True for sub in allNestedSubprojects} elif args["--add"] or args["--rm"]: includedNestedSubprojectPrefixes = {sub:True for sub in grapeConfig.GrapeConfigParser.getAllActiveNestedSubprojectPrefixes()} includedNestedSubprojectPrefixes.update({nestedPrefixLookup(sub):True for sub in addedNestedSubprojects}) includedNestedSubprojectPrefixes.update({nestedPrefixLookup(sub):False for sub in rmNestedSubprojects}) else: includedNestedSubprojectPrefixes = self.defineActiveNestedSubprojects() if hasSubmodules: initStr = "" deinitStr = "" rmCachedStr = "" resetStr = "" for submodule, nowActive in includedSubmodules.items(): if nowActive: initStr += ' %s' % submodule else: deinitStr += ' %s' % submodule rmCachedStr += ' %s' % submodule resetStr += ' %s' % submodule if args["-f"] and deinitStr: deinitStr = "-f"+deinitStr utility.printMsg("Configuring submodules...") utility.printMsg("Initializing submodules...") git.submodule("init %s" % initStr.strip()) if deinitStr: utility.printMsg("Deiniting submodules that were not requested... (%s)" % deinitStr) done = False while not done: try: git.submodule("deinit %s" % deinitStr.strip()) done = True except git.GrapeGitError as e: if "the following file has local modifications" in e.gitOutput: print e.gitOutput utility.printMsg("A submodule that you wanted to remove has local modifications. " "Use grape uv -f to force removal.") return False elif "use 'rm -rf' if you really want to remove it including all of its history" in e.gitOutput: if not args["-f"]: raise e # it is safe to move the .git of the submodule to the .git/modules area of the workspace... module = None for l in e.gitOutput.split('\n'): if "Submodule work tree" in l and "contains a .git directory" in l: module = l.split("'")[1] break if module: src = os.path.join(module, ".git") dest = os.path.join(wsDir, ".git", "modules", module) utility.printMsg("Moving %s to %s"%(src, dest)) shutil.move(src, dest ) else: raise e else: raise e git.rm("--cached %s" % rmCachedStr) git.reset(" %s" % resetStr) if initStr: utility.printMsg("Updating active submodules...(%s)" % initStr) git.submodule("update") # handle nested subprojects if not args["--skipNestedSubprojects"]: reverseLookupByPrefix = {nestedPrefixLookup(sub) : sub for sub in allNestedSubprojects} userConfig = grapeConfig.grapeUserConfig() updatedActiveList = [] for subproject, nowActive in includedNestedSubprojectPrefixes.items(): subprojectName = reverseLookupByPrefix[subproject] section = "nested-%s" % reverseLookupByPrefix[subproject] userConfig.ensureSection(section) previouslyActive = userConfig.getboolean(section, "active") previouslyActive = previouslyActive and os.path.exists(os.path.join(base, subproject, ".git")) userConfig.set(section, "active", "True" if previouslyActive else "False") if nowActive and previouslyActive: updatedActiveList.append(subprojectName) if nowActive and not previouslyActive: utility.printMsg("Activating Nested Subproject %s" % subproject) if not addSubproject.AddSubproject.activateNestedSubproject(subprojectName, userConfig): utility.printMsg("Can't activate %s. Exiting..." % subprojectName) return False updatedActiveList.append(subprojectName) if not nowActive and not previouslyActive: pass if not nowActive and previouslyActive: #remove the subproject subprojectdir = os.path.join(base, utility.makePathPortable(subproject)) proceed = args["-f"] or \ utility.userInput("About to delete all contents in %s. Any uncommitted changes, committed changes " "that have not been pushed, or ignored files will be lost. Proceed?" % subproject, 'n') if proceed: shutil.rmtree(subprojectdir) userConfig.setActiveNestedSubprojects(updatedActiveList) grapeConfig.writeConfig(userConfig, os.path.join(utility.workspaceDir(), ".git", ".grapeuserconfig")) checkoutArgs = "-b" if args["-b"] else "" safeSwitchWorkspaceToBranch( git.currentBranch(), checkoutArgs, sync) os.chdir(origwd) return True @staticmethod def getDesiredSubmoduleBranch(config): publicBranches = config.getPublicBranchList() currentBranch = git.currentBranch() if currentBranch in publicBranches: desiredSubmoduleBranch = config.getMapping("workspace", "submodulepublicmappings")[currentBranch] else: desiredSubmoduleBranch = currentBranch return desiredSubmoduleBranch def setDefaultConfig(self, config): config.ensureSection("workspace") config.set("workspace", "submodulepublicmappings", "?:master") def ensureLocalUpToDateWithRemote(repo = '', branch = 'master'): utility.printMsg( "Ensuring local branch %s in %s is up to date with origin" % (branch, repo)) with utility.cd(repo): # attempt to fetch the requested branch try: git.fetch("origin", "%s:%s" % (branch, branch)) except: # the branch may not exist, but this is ok pass if git.currentBranch() == branch: return if not git.hasBranch(branch): # switch to corresponding public branch if the branch does not exist public = grapeConfig.workspaceConfig().getPublicBranchFor(branch) # figure out if this is a submodule relpath = os.path.relpath(repo, utility.workspaceDir()) relpath = relpath.replace('\\',"/") with utility.cd(utility.workspaceDir()): # if this is a submodule, get the appropriate public mapping if relpath in git.getAllSubmoduleURLMap().keys(): public = grapeConfig.workspaceConfig().getMapping("workspace", "submodulepublicmappings")[public] utility.printMsg("Branch %s does not exist in %s, switching to %s and detaching" % (branch, repo, public)) git.checkout(public) git.pull("origin %s" % (public)) git.checkout("--detach HEAD") def cleanupPush(repo='', branch='', args='none'): with utility.cd(repo): utility.printMsg("Attempting push of local %s in %s" % (branch, repo)) git.push("origin %s" % branch) def handleCleanupPushMRE(mre): for e, repo, branch in zip(mre.exceptions(), mre.repos(), mre.branches()): try: raise e except git.GrapeGitError as e2: utility.printMsg("Local and remote versions of %s may have diverged in %s" % (branch, repo)) utility.printMsg("%s" % e2.gitOutput) utility.printMsg("Use grape pull to merge the remote version into the local version.") def handleEnsureLocalUpToDateMRE(mre): _pushBranch = False _skipPush = False cleanupPushArgs = [] for e1, repo, branch in zip(mre.exceptions(), mre.repos(), mre.branches()): try: raise e1 except git.GrapeGitError as e: if ("[rejected]" in e.gitOutput and "(non-fast-forward)" in e.gitOutput) or "Couldn't find remote ref" in e.gitOutput: if "Couldn't find remote ref" in e.gitOutput: if not _pushBranch: utility.printMsg("No remote reference to %s in %s's origin. You may want to push this branch." % (branch, repo))<|fim▁hole|> utility.printMsg("Fetch of %s rejected as non-fast-forward in repo %s" % (branch, repo)) pushBranch = _pushBranch if _skipPush: pushBranch = False elif not pushBranch: pushBranch = utility.userInput("Would you like to push your local branch? \n" "(select 'a' to say yes for (a)ll subprojects, 's' to (s)kip push for all subprojects)" "\n(y,n,a,s)", 'y') if str(pushBranch).lower()[0] == 'a': _pushBranch = True pushBranch = True if str(pushBranch).lower()[0] == 's': _skipPush = True pushBranch = False if pushBranch: cleanupPushArgs.append((repo, branch, None)) else: utility.printMsg("Skipping push of local %s in %s" % (branch, repo)) elif e.commError: utility.printMsg("Could not update %s from origin due to a connectivity issue. Checking out most recent\n" "local version. " % branch) else: raise(e) # do another MRC launch to do any follow up pushes that were requested. utility.MultiRepoCommandLauncher(cleanupPush, listOfRepoBranchArgTuples=cleanupPushArgs).launchFromWorkspaceDir(handleMRE=handleCleanupPushMRE) return def safeSwitchWorkspaceToBranch(branch, checkoutArgs, sync): # Ensure local branches that you are about to check out are up to date with the remote if sync: launcher = utility.MultiRepoCommandLauncher(ensureLocalUpToDateWithRemote, branch = branch, globalArgs=[checkoutArgs]) launcher.launchFromWorkspaceDir(handleMRE=handleEnsureLocalUpToDateMRE) # Do a checkout # Pass False instead of sync since if sync is True ensureLocalUpToDateWithRemote will have already performed the fetch launcher = utility.MultiRepoCommandLauncher(checkout.handledCheckout, branch = branch, globalArgs = [checkoutArgs, False]) launcher.launchFromWorkspaceDir(handleMRE=checkout.handleCheckoutMRE) return<|fim▁end|>
else:
<|file_name|>main.rs<|end_file_name|><|fim▁begin|>//! Initium is a modern bootloader with no legacy components. #![no_std]<|fim▁hole|>#![no_main] #![feature(asm)] #![feature(try_trait)] #![feature(abi_efiapi)] #![feature(global_asm)] #![feature(const_mut_refs)] #![feature(num_as_ne_bytes)] #![feature(in_band_lifetimes)] #![feature(panic_info_message)] #![feature(alloc_error_handler)] use alloc::{boxed::Box, string::String, vec::Vec}; use console::get_console_out; use ui::{ChoiceEntry, ListWindow}; use common::{command_manager::get_command_manager, BuiltinCommand}; extern crate alloc; #[macro_use] extern crate log; extern crate common; // HAL(Hardware Abstraction Layer) #[macro_use] mod platform; mod config; mod console; mod device; mod disk; mod line_editor; mod shell; mod ui; #[no_mangle] pub fn loader_main() { use crate::alloc::string::ToString; // init console get_console_out().init(); device::init(); register_commands(); // TODO: this is a simple test is to be removed on the future let mut window = ListWindow::new("Boot Menu".to_string(), false); // create a list of entries window.add_list( Box::new(ChoiceEntry { label: "Example OS Choice".to_string(), }), false, ); window.add_list( Box::new(ChoiceEntry { label: "Example OS Choice 2".to_string(), }), false, ); window.add_list( Box::new(ChoiceEntry { label: "Example OS Choice 3".to_string(), }), false, ); { let console = get_console_out(); window.render(console, 0); } // TODO: remove this as soon as we have the environment loader implemented loop {} } /// Register about command fn register_commands() { let command_manager = get_command_manager(); command_manager.add_command(BuiltinCommand { name: "about", description: "Shows the bootloader version", func: about_command, }); // we can't implement the 'help' command on the common crate since the println! macro isn't available there command_manager.add_command(BuiltinCommand { name: "help", description: "List all available commands", func: help_command, }); command_manager.add_command(BuiltinCommand { name: "reboot", description: "Reboot the system", func: reboot_command, }); } /// Reboot platform fn reboot_command(_: Vec<String>) -> bool { self::platform::target_reboot(); } /// Show current Initium version fn about_command(_: Vec<String>) -> bool { println!("Initium version {}", env!("CARGO_PKG_VERSION")); true } /// Show all available commands fn help_command(_: Vec<String>) -> bool { let manager = get_command_manager(); println!("Command Description"); println!("------- -----------"); manager.get_commands().iter().for_each(|c| { println!("{:<16} {}", &c.name, &c.description); }); true } #[panic_handler] fn panic_handler(info: &core::panic::PanicInfo) -> ! { if let Some(location) = info.location() { error!( "Panic in {} at ({}, {}):", location.file(), location.line(), location.column() ); if let Some(message) = info.message() { error!("{}", message); } } // TODO: halt in a way that makes sense for the platform loop {} }<|fim▁end|>
<|file_name|>gulpfile.js<|end_file_name|><|fim▁begin|>var gulp = require('gulp'), concat = require('gulp-concat'), compass = require('gulp-compass'), notify = require('gulp-notify'); function swallowError(error) { this.emit('end'); } function reportError(error) { notify.onError().apply(this, arguments); this.emit('end'); } // combine js into single file //=========================================== gulp.task('scripts', function() { gulp.src([ './src/js/lib/jquery.min.js', './src/js/lib/cssbeautify.js', './src/js/lib/specificity.js', './src/js/lib/tablesorter.js', './src/js/local/helpers.js', // './src/js/local/syntax-highlight.js', './src/js/local/build-html.js', // './src/js/local/build-specificity.js', './src/js/local/button-control.js', // './src/js/local/css-highlight.js', './src/js/local/tabs.js' ]) .pipe(concat('smprof.js')) .pipe(gulp.dest('./ext/js/')) }); // compass: compile sass to css //=========================================== gulp.task('compass', function() { gulp.src('./assets/sass/*.scss') .pipe(compass({ config_file: './config.rb', css: './ext/css/', sass: './assets/sass' })) .on('error', reportError); }); // watch: monitor html and static assets updates //=========================================== gulp.task('watch', function() { // watch task for sass gulp.watch('./assets/sass/**/*.scss', ['compass']); gulp.watch('./src/js/**/*.js', ['scripts']); }); <|fim▁hole|>//=========================================== gulp.task('default', ['compass', 'scripts', 'watch']);<|fim▁end|>
// Default Gulp Task
<|file_name|>point_tests.js<|end_file_name|><|fim▁begin|>import assert from "assert"; import {Point2D, Vector2D, Matrix2D} from "../index.js"; describe("Point2D", () => { it("new point", () => { const p = new Point2D(10, 20); assert.strictEqual(p.x, 10); assert.strictEqual(p.y, 20); }); it("clone", () => { const p = new Point2D(10, 20); const c = p.clone(); assert.strictEqual(p.x, c.x); assert.strictEqual(p.y, c.y); assert.strictEqual(c.x, 10); assert.strictEqual(c.y, 20); }); it("add", () => { const p1 = new Point2D(10, 20); const p2 = new Point2D(20, 30); const p3 = p1.add(p2); assert.strictEqual(p3.x, 30); assert.strictEqual(p3.y, 50); }); it("subtract", () => { const p1 = new Point2D(10, 20); const p2 = new Point2D(20, 40); const p3 = p1.subtract(p2); assert.strictEqual(p3.x, -10); assert.strictEqual(p3.y, -20); }); <|fim▁hole|> assert.strictEqual(p2.x, 5); assert.strictEqual(p2.y, 10); }); it("divide", () => { const p1 = new Point2D(10, 20); const p2 = p1.divide(2); assert.strictEqual(p2.x, 5); assert.strictEqual(p2.y, 10); }); it("equal", () => { const p1 = new Point2D(10, 20); const p2 = new Point2D(10, 20); assert.strictEqual(p1.equals(p2), true); }); it("not equal", () => { const p1 = new Point2D(10, 20); const p2 = new Point2D(10, 21); assert.strictEqual(p1.equals(p2), false); }); it("interpolate between two points", () => { const p1 = new Point2D(10, 20); const p2 = new Point2D(30, 40); const p3 = p1.lerp(p2, 0.25); assert.strictEqual(p3.x, 15); assert.strictEqual(p3.y, 25); }); it("distance between two points", () => { const p1 = new Point2D(10, 20); const p2 = new Point2D(13, 24); const dist = p1.distanceFrom(p2); assert.strictEqual(dist, 5); }); it("min", () => { const p1 = new Point2D(30, 5); const p2 = new Point2D(10, 50); const p3 = p1.min(p2); assert.strictEqual(p3.x, 10); assert.strictEqual(p3.y, 5); }); it("max", () => { const p1 = new Point2D(30, 5); const p2 = new Point2D(10, 50); const p3 = p1.max(p2); assert.strictEqual(p3.x, 30); assert.strictEqual(p3.y, 50); }); it("translate", () => { const p1 = new Point2D(10, 20); const m = new Matrix2D().translate(20, 30); const p2 = p1.transform(m); assert.strictEqual(p2.x, 30); assert.strictEqual(p2.y, 50); }); it("scale", () => { const p1 = new Point2D(10, 20); const m = new Matrix2D().scale(2); const p2 = p1.transform(m); assert.strictEqual(p2.x, 20); assert.strictEqual(p2.y, 40); }); it("scale non-uniform", () => { const p1 = new Point2D(10, 20); const m = new Matrix2D().scaleNonUniform(2, 3); const p2 = p1.transform(m); assert.strictEqual(p2.x, 20); assert.strictEqual(p2.y, 60); }); it("rotate", () => { const p1 = new Point2D(10, 0); const m = new Matrix2D().rotate(Math.PI / 4.0); const p2 = p1.transform(m); assert.strictEqual(p2.x, 7.0710678118654755); assert.strictEqual(p2.y, 7.071067811865475); }); it("rotate from vector", () => { const p1 = new Point2D(10, 0); const v = new Vector2D(Math.PI / 4.0, Math.PI / 4.0); const m = new Matrix2D().rotateFromVector(v); const p2 = p1.transform(m); assert.strictEqual(p2.x, 7.0710678118654755); assert.strictEqual(p2.y, 7.0710678118654755); }); it("flip x", () => { const p1 = new Point2D(10, 20); const m = new Matrix2D().flipX(); const p2 = p1.transform(m); assert.strictEqual(p2.x, -10); assert.strictEqual(p2.y, 20); }); it("flip y", () => { const p1 = new Point2D(10, 20); const m = new Matrix2D().flipY(); const p2 = p1.transform(m); assert.strictEqual(p2.x, 10); assert.strictEqual(p2.y, -20); }); it("inverse transform", () => { const p1 = new Point2D(10, 20); const m = new Matrix2D().translate(30, 50).inverse(); const p2 = p1.transform(m); assert.strictEqual(p2.x, -20); assert.strictEqual(p2.y, -30); }); it("to string", () => { const p = new Point2D(10, 20); assert.strictEqual("point(10,20)", p.toString()); }); });<|fim▁end|>
it("multiply", () => { const p1 = new Point2D(10, 20); const p2 = p1.multiply(0.5);
<|file_name|>bitcoin_ca@valencia.ts<|end_file_name|><|fim▁begin|><?xml version="1.0" ?><!DOCTYPE TS><TS language="ca@valencia" version="2.1"> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About NexxusCoin</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>&lt;b&gt;NexxusCoin&lt;/b&gt; version</source> <translation type="unfinished"/> </message> <message> <location line="+41"/> <source>Copyright © 2009-2014 The Bitcoin developers Copyright © 2012-2014 The NovaCoin developers Copyright © 2014 The NexxusCoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or &lt;a href=&quot;http://www.opensource.org/licenses/mit-license.php&quot;&gt;http://www.opensource.org/licenses/mit-license.php&lt;/a&gt;. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (&lt;a href=&quot;https://www.openssl.org/&quot;&gt;https://www.openssl.org/&lt;/a&gt;) and cryptographic software written by Eric Young (&lt;a href=&quot;mailto:eay@cryptsoft.com&quot;&gt;eay@cryptsoft.com&lt;/a&gt;) and UPnP software written by Thomas Bernard.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Double-click to edit address or label</source> <translation>Doble click per editar la direccio o la etiqueta</translation> </message> <message> <location line="+24"/> <source>Create a new address</source> <translation>Crear nova direccio</translation> </message> <message> <location line="+10"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Copieu l&apos;adreça seleccionada al porta-retalls del sistema</translation> </message> <message> <location line="-7"/> <source>&amp;New Address</source> <translation type="unfinished"/> </message> <message> <location line="-43"/> <source>These are your NexxusCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation type="unfinished"/> </message> <message> <location line="+53"/> <source>&amp;Copy Address</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show &amp;QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign a message to prove you own a NexxusCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Verify a message to ensure it was signed with a specified NexxusCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Delete</source> <translation>Eliminar</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+66"/> <source>Copy &amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation type="unfinished"/> </message> <message> <location line="+248"/> <source>Export Address Book Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+145"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>(no label)</source> <translation type="unfinished"/> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <source>Serves to disable the trivial sendmoney when OS account compromised. Provides no real security.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>For staking only</source> <translation type="unfinished"/> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+38"/> <source>Encrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Confirm wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR COINS&lt;/b&gt;!</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+103"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-133"/> <location line="+60"/> <source>Wallet encrypted</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;ten or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>NexxusCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your coins from being stolen by malware infecting your computer.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+44"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation type="unfinished"/> </message> <message> <location line="-56"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <location line="+50"/> <source>The supplied passphrases do not match.</source> <translation type="unfinished"/> </message> <message> <location line="-38"/> <source>Wallet unlock failed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+12"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation type="unfinished"/> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+297"/> <source>Sign &amp;message...</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Show general overview of wallet</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>&amp;Transactions</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>&amp;Address Book</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit the list of stored addresses and labels</source> <translation type="unfinished"/> </message> <message> <location line="-18"/> <source>Show the list of addresses for receiving payments</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>E&amp;xit</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Quit application</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Show information about NexxusCoin</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>&amp;Encrypt Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Backup Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Export...</source> <translation type="unfinished"/> </message> <message> <location line="-55"/> <source>Send coins to a NexxusCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+39"/> <source>Modify configuration options for NexxusCoin</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="-13"/> <source>Encrypt or decrypt wallet</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Backup wallet to another location</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>&amp;Verify message...</source> <translation type="unfinished"/> </message> <message> <location line="-214"/> <location line="+555"/> <source>NexxusCoin</source> <translation type="unfinished"/> </message> <message> <location line="-555"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+193"/> <source>&amp;About NexxusCoin</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Unlock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&amp;Lock Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Lock wallet</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>&amp;File</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>&amp;Settings</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>&amp;Help</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Tabs toolbar</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <location line="+9"/> <source>[testnet]</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+58"/> <source>NexxusCoin client</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+70"/> <source>%n active connection(s) to NexxusCoin network</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+488"/> <source>Staking.&lt;br&gt;Your weight is %1&lt;br&gt;Network weight is %2&lt;br&gt;Expected time to earn reward is %3</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Not staking because wallet is locked</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because wallet is syncing</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Not staking because you don&apos;t have mature coins</source> <translation type="unfinished"/> </message> <message> <location line="-812"/> <source>&amp;Dashboard</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>&amp;Unlock Wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+277"/> <source>Up to date</source> <translation type="unfinished"/> </message> <message> <location line="+43"/> <source>Catching up...</source> <translation type="unfinished"/> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Sent transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Incoming transaction</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+15"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <location line="+15"/> <source>URI can not be parsed! This can be caused by an invalid NexxusCoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Wallet is &lt;b&gt;not encrypted&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+91"/> <source>%n second(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n minute(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="-429"/> <location line="+433"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="-456"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+27"/> <location line="+433"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="-429"/> <location line="+6"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+0"/> <source>%1 and %2</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+0"/> <source>%n year(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="+324"/> <source>Not staking</source> <translation type="unfinished"/> </message> <message> <location filename="../bitcoin.cpp" line="+104"/> <source>A fatal error occurred. NexxusCoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+110"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>CoinControlDialog</name> <message> <location filename="../forms/coincontroldialog.ui" line="+14"/> <source>Coin Control</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message> <location line="+48"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="+537"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location filename="../forms/coincontroldialog.ui" line="+51"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change:</source> <translation type="unfinished"/> </message> <message> <location line="+69"/> <source>(un)select all</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Tree mode</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>List mode</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Priority</source> <translation type="unfinished"/> </message> <message> <location filename="../coincontroldialog.cpp" line="-500"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+26"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+317"/> <source>highest</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium-high</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>low-medium</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>low</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>lowest</source> <translation type="unfinished"/> </message> <message> <location line="+140"/> <source>DUST</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>yes</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>This label turns red, if the transaction size is bigger than 10000 bytes. This means a fee of at least %1 per kb is required. Can vary +/- 1 Byte per input.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transactions with higher priority get more likely into a block. This label turns red, if the priority is smaller than &quot;medium&quot;. This means a fee of at least %1 per kb is required.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if any recipient receives an amount smaller than %1. This means a fee of at least %2 is required. Amounts below 0.546 times the minimum relay fee are shown as DUST.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This label turns red, if the change is smaller than %1. This means a fee of at least %2 is required.</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <location line="+66"/> <source>(no label)</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <source>change from %1 (%2)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>(change)</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation type="unfinished"/> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>New sending address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation type="unfinished"/> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid NexxusCoin address.</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation type="unfinished"/> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+426"/> <location line="+12"/> <source>NexxusCoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>UI options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB. Fee 0.01 recommended.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Reserved amount does not participate in staking and is therefore spendable at any time.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Reserve</source> <translation type="unfinished"/> </message> <message> <location line="+31"/> <source>Automatically start NexxusCoin after logging in to the system.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Start NexxusCoin on system login</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the NexxusCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation type="unfinished"/> </message> <message> <location line="-57"/> <source>Connect to the NexxusCoin network through a SOCKS5 proxy (e.g. when connecting through Tor).</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS5 proxy:</source> <translation type="unfinished"/> </message> <message> <location line="+90"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting NexxusCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+9"/> <source>Whether to show coin control features or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Display coin &amp;control features (experts only!)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Whether to select the coin outputs randomly or with minimal coin age.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Minimize weight consumption (experimental)</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use black visual theme (requires restart)</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation type="unfinished"/> </message> <message> <location filename="../optionsdialog.cpp" line="+47"/> <source>default</source> <translation type="unfinished"/> </message> <message> <location line="+148"/> <location line="+9"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting NexxusCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <location line="+247"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the NexxusCoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-173"/> <source>Stake:</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Unconfirmed:</source> <translation type="unfinished"/> </message> <message> <location line="-113"/> <source>Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Spendable:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current spendable balance</source> <translation type="unfinished"/> </message> <message> <location line="+80"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Total:</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Your current total balance</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-118"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location line="-32"/> <source>Total of coins that was staked, and do not yet count toward the current balance</source> <translation type="unfinished"/> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start nexxuscoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation type="unfinished"/> </message> <message> <location line="+56"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Label:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Message:</source> <translation type="unfinished"/> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation type="unfinished"/> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation type="unfinished"/> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <source>N/A</source> <translation type="unfinished"/> </message> <message> <location line="-194"/> <source>Client version</source> <translation type="unfinished"/> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation type="unfinished"/> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>Network</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>On testnet</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Block chain</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation type="unfinished"/> </message> <message> <location line="+197"/> <source>&amp;Network Traffic</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Clear</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Totals</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>In:</source> <translation type="unfinished"/> </message> <message> <location line="+80"/> <source>Out:</source> <translation type="unfinished"/> </message> <message> <location line="-383"/> <source>Last block time</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the NexxusCoin-Qt help message to get a list with possible NexxusCoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation type="unfinished"/> </message> <message> <location line="-237"/> <source>Build date</source> <translation type="unfinished"/> </message> <message> <location line="-104"/> <source>NexxusCoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>NexxusCoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+256"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the NexxusCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation type="unfinished"/> </message> <message> <location filename="../rpcconsole.cpp" line="+325"/> <source>Welcome to the NexxusCoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> <message> <location line="+127"/> <source>%1 B</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 KB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 MB</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 GB</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>%1 m</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>%1 h</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 h %2 m</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+182"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation type="unfinished"/> </message> <message> <location line="+76"/> <source>Coin Control Features</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Inputs...</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>automatically selected</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Insufficient funds!</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Quantity:</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <location line="+35"/> <source>0</source> <translation type="unfinished"/> </message> <message> <location line="-19"/> <source>Bytes:</source> <translation type="unfinished"/> </message> <message> <location line="+51"/> <source>Amount:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Priority:</source> <translation type="unfinished"/> </message> <message><|fim▁hole|> <location line="+19"/> <source>medium</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Low Output:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>no</source> <translation type="unfinished"/> </message> <message> <location line="+32"/> <source>After Fee:</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Change</source> <translation type="unfinished"/> </message> <message> <location line="+50"/> <source>custom change address</source> <translation type="unfinished"/> </message> <message> <location line="+106"/> <source>Send to multiple recipients at once</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Remove all transaction fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Balance:</source> <translation type="unfinished"/> </message> <message> <location line="+47"/> <source>Confirm the send action</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-174"/> <source>Enter a NexxusCoin address (e.g. SjBj1QvJvsAkU5EBKggdZ8gWc4oK2F5AMY)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Copy quantity</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy after fee</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy bytes</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy priority</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy low output</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy change</source> <translation type="unfinished"/> </message> <message> <location line="+87"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source> and </source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The recipient address is not valid, please recheck.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+247"/> <source>WARNING: Invalid NexxusCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>(no label)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>WARNING: unknown change address</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. SjBj1QvJvsAkU5EBKggdZ8gWc4oK2F5AMY)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation type="unfinished"/> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation type="unfinished"/> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a NexxusCoin address (e.g. SjBj1QvJvsAkU5EBKggdZ8gWc4oK2F5AMY)</source> <translation type="unfinished"/> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <location line="+124"/> <source>&amp;Sign Message</source> <translation type="unfinished"/> </message> <message> <location line="-118"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. SjBj1QvJvsAkU5EBKggdZ8gWc4oK2F5AMY)</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <location line="+203"/> <source>Choose an address from the address book</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <location line="+203"/> <source>Alt+A</source> <translation type="unfinished"/> </message> <message> <location line="-193"/> <source>Paste address from clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this NexxusCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation type="unfinished"/> </message> <message> <location line="-87"/> <location line="+70"/> <source>&amp;Verify Message</source> <translation type="unfinished"/> </message> <message> <location line="-64"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. SjBj1QvJvsAkU5EBKggdZ8gWc4oK2F5AMY)</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified NexxusCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a NexxusCoin address (e.g. SjBj1QvJvsAkU5EBKggdZ8gWc4oK2F5AMY)</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter NexxusCoin signature</source> <translation type="unfinished"/> </message> <message> <location line="+85"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation type="unfinished"/> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>TrafficGraphWidget</name> <message> <location filename="../trafficgraphwidget.cpp" line="+75"/> <source>KB/s</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+25"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Status</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <location line="+13"/> <source>From</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <location line="+19"/> <location line="+58"/> <source>To</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation type="unfinished"/> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Net amount</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Message</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Comment</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-202"/> <source>, has not been successfully broadcast yet</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-36"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+67"/> <source>unknown</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+231"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+52"/> <source>Open until %1</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Confirmed (%1 confirmations)</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="-15"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+6"/> <source>Offline</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Unconfirmed</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Confirming (%1 of %2 recommended confirmations)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Conflicted</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Immature (%1 confirmations, will be available after %2)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Received from</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation type="unfinished"/> </message> <message> <location line="+194"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation type="unfinished"/> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+54"/> <location line="+17"/> <source>All</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Today</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This week</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Last month</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This year</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Range...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Received with</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Sent to</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>To yourself</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Mined</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Other</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Min amount</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Copy address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation type="unfinished"/> </message> <message> <location line="+138"/> <source>Export Transaction Data</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Date</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Label</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>ID</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <source>Range:</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>to</source> <translation type="unfinished"/> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+212"/> <source>Sending...</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+171"/> <source>NexxusCoin version</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Usage:</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send command to -server or nexxuscoind</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>List commands</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Get help for a command</source> <translation type="unfinished"/> </message> <message> <location line="-145"/> <source>Options:</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify configuration file (default: nexxuscoin.conf)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify pid file (default: nexxuscoind.pid)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify wallet file (within data directory)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=nexxuscoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;NexxusCoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set database disk log size in megabytes (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Listen for connections on &lt;port&gt; (default: 16178 or testnet: 25714)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Bind to given address. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Query for peer addresses via DNS lookup, if low on addresses (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Always query for peer addresses via DNS lookup (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation type="unfinished"/> </message> <message> <location line="-35"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+62"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 16174 or testnet: 25715)</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Accept command line and JSON-RPC commands</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Run in the background as a daemon and accept commands</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use the test network</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-28"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+93"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation type="unfinished"/> </message> <message> <location line="-103"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong NexxusCoin will not work properly.</source> <translation type="unfinished"/> </message> <message> <location line="+130"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="-34"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="-67"/> <source>Connect only to the specified node(s)</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+101"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Invalid amount for -reservebalance=&lt;amount&gt;</source> <translation type="unfinished"/> </message> <message> <location line="-89"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="-16"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+30"/> <source>Prepend debug output with timestamp</source> <translation type="unfinished"/> </message> <message> <location line="+40"/> <source>SSL options: (see the Bitcoin Wiki for SSL setup instructions)</source> <translation type="unfinished"/> </message> <message> <location line="-38"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation type="unfinished"/> </message> <message> <location line="+34"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="-34"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="-41"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation type="unfinished"/> </message> <message> <location line="-25"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+45"/> <source>Username for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+54"/> <source>Verifying database integrity...</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="-52"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-59"/> <source>Password for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="-47"/> <source>Connect through SOCKS5 proxy</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Sync time with other nodes. Disable if time on your system is precise e.g. syncing with NTP (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>When creating transactions, ignore inputs with value less than this (default: 0.01)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Output debugging information (default: 0, supplying &lt;category&gt; is optional)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>If &lt;category&gt; is not supplied, output all debugging information.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>&lt;category&gt; can be:</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wait for RPC server to start</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Require a confirmations for change (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Upgrade wallet to latest format</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rescan the block chain for missing wallet transactions</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>How thorough the block verification is (0-6, default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Imports blocks from external blk000?.dat file</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Keep at most &lt;n&gt; MiB of unconnectable blocks in memory (default: %u)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server certificate file (default: server.cert)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: Unsupported argument -socks found. Setting SOCKS version isn&apos;t possible anymore, only SOCKS5 proxies are supported.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Initialization sanity check failed. NexxusCoin is shutting down.</source> <translation type="unfinished"/> </message> <message> <location line="+20"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>Error: Wallet unlocked for staking only, unable to create transaction.</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="-168"/> <source>This help message</source> <translation type="unfinished"/> </message> <message> <location line="+104"/> <source>Wallet %s resides outside data directory %s.</source> <translation type="unfinished"/> </message> <message> <location line="+35"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation type="unfinished"/> </message> <message> <location line="-129"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation type="unfinished"/> </message> <message> <location line="+125"/> <source>Loading addresses...</source> <translation type="unfinished"/> </message> <message> <location line="-10"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error loading wallet.dat: Wallet requires newer version of NexxusCoin</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Wallet needed to be rewritten: restart NexxusCoin to complete</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="-15"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-22"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+58"/> <source>Sending...</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Invalid amount</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Insufficient funds</source> <translation type="unfinished"/> </message> <message> <location line="-40"/> <source>Loading block index...</source> <translation type="unfinished"/> </message> <message> <location line="-109"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation type="unfinished"/> </message> <message> <location line="+124"/> <source>Unable to bind to %s on this computer. NexxusCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="-101"/> <source>Fee per KB to add to transactions you send</source> <translation type="unfinished"/> </message> <message> <location line="+33"/> <source>Minimize weight consumption (experimental) (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>How many blocks to check at startup (default: 500, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Deprecated argument -debugnet ignored, use -debug=net</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Invalid amount for -mininput=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. NexxusCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Loading wallet...</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Rescanning...</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Done loading</source> <translation type="unfinished"/> </message> <message> <location line="-159"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="+186"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="-18"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS><|fim▁end|>
<|file_name|>sshplus.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python3 # -*- coding: utf-8 -*- # # SSHplus # A remote connect utlity, sshmenu compatible clone, and application starter. # # (C) 2011 Anil Gulecha # Based on sshlist, incorporating changes by Benjamin Heil's simplestarter # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # # Instructions # # 1. Copy file sshplus.py (this file) to /usr/local/bin # 2. Edit file .sshplus in your home directory to add menu entries, each # line in the format NAME|COMMAND|ARGS # 3. Launch sshplus.py # 4. Or better yet, add it to gnome startup programs list so it's run on login. import shlex import sys import notify2 import os import gi gi.require_version("AppIndicator3", "0.1") from gi.repository import AppIndicator3 gi.require_version("Gtk", "3.0") from gi.repository import Gtk _VERSION = "1.0" _SETTINGS_FILE = os.getenv("HOME") + "/.sshplus" _ABOUT_TXT = """A simple application starter as appindicator. To add items to the menu, edit the file <i>.sshplus</i> in your home directory. Each entry must be on a new line in this format: <tt>NAME|COMMAND|ARGS</tt> If the item is clicked in the menu, COMMAND with arguments ARGS will be executed. ARGS can be empty. To insert a separator, add a line which only contains "sep". Lines starting with "#" will be ignored. You can set an unclickable label with the prefix "label:". To insert a nested menu, use the prefix "folder:menu name". Subsequent items will be inserted in this menu, until a line containing an empty folder name is found: "folder:". After that, subsequent items get inserted in the parent menu. That means that more than one level of nested menus can be created. Example file: <tt><small> Show top|gnome-terminal|-x top sep # this is a comment label:SSH connections # create a folder named "Home" folder:Home SSH Ex|gnome-terminal|-x ssh user@1.2.3.4 # to mark the end of items inside "Home", specify and empty folder: folder: # this item appears in the main menu SSH Ex|gnome-terminal|-x ssh user@1.2.3.4 label:RDP connections RDP Ex|rdesktop|-T "RDP-Server" -r sound:local 1.2.3.4 </small></tt> Copyright 2011 Anil Gulecha Incorporating changes from simplestarter, Benjamin Heil, http://www.bheil.net Released under GPL3, http://www.gnu.org/licenses/gpl-3.0.html""" _EDIT_CONFIG = """To add items to the menu, edit the file <i>.sshplus</i> in your home directory. Each entry must be on a new line in this format: <tt>NAME|COMMAND|ARGS</tt> If the item is clicked in the menu, COMMAND with arguments ARGS will be executed. ARGS can be empty. To insert a separator, add a line which only contains "sep". Lines starting with "#" will be ignored. You can set an unclickable label with the prefix "label:". To insert a nested menu, use the prefix "folder:menu name". Subsequent items will be inserted in this menu, until a line containing an empty folder name is found: "folder:". After that, subsequent items get inserted in the parent menu. That means that more than one level of nested menus can be created. Example file: <tt><small> Show top|gnome-terminal|-x top sep # this is a comment label:SSH connections # create a folder named "Home" folder:Home SSH Ex|gnome-terminal|-x ssh user@1.2.3.4 # to mark the end of items inside "Home", specify and empty folder: folder: # this item appears in the main menu SSH Ex|gnome-terminal|-x ssh user@1.2.3.4 label:RDP connections RDP Ex|rdesktop|-T "RDP-Server" -r sound:local 1.2.3.4 </small></tt>""" def menuitem_response(w, item): if item == "_about": show_help_dlg(_ABOUT_TXT) elif item == "_edit": edit_config_file() elif item == "_refresh": newmenu = build_menu() ind.set_menu(newmenu) notify2.init("sshplus") notify2.Notification( "SSHplus refreshed", '"%s" has been read! Menu list was refreshed!' % _SETTINGS_FILE ).show() elif item == "_quit": sys.exit(0) elif item == "folder": pass else: print(item) os.spawnvp(os.P_NOWAIT, item["cmd"], [item["cmd"]] + item["args"]) os.wait3(os.WNOHANG) def show_help_dlg(msg, error=False): if error: dlg_icon = Gtk.MessageType.ERROR md = Gtk.MessageDialog( None, 0, dlg_icon, Gtk.ButtonsType.OK, "This is an INFO MessageDialog" ) edit_config_file() else: dlg_icon = Gtk.MessageType.INFO md = Gtk.MessageDialog( None, 0, dlg_icon, Gtk.ButtonsType.OK, "This is an INFO MessageDialog" ) try: md.set_markup("<b>SSHplus %s</b>" % _VERSION) md.format_secondary_markup(msg) md.run() finally: md.destroy() def edit_config_file(): if os.path.isfile(_SETTINGS_FILE) is not True: os.mknod(_SETTINGS_FILE) show_help_dlg( "<b>No <i>.sshplus</i> config file found, we created one for you!\n\nPlease edit the" " file and reload the config.</b>\n\n%s" % _EDIT_CONFIG, error=True, ) os.spawnvp(os.P_NOWAIT, "xdg-open", ["xdg-open", _SETTINGS_FILE]) os.wait3(os.WNOHANG) def add_separator(menu): separator = Gtk.SeparatorMenuItem() separator.show() menu.append(separator) def add_menu_item(menu, caption, item=None): menu_item = Gtk.MenuItem.new_with_label(caption) if item: menu_item.connect("activate", menuitem_response, item) else: menu_item.set_sensitive(False)<|fim▁hole|> menu.append(menu_item) return menu_item def get_sshplusconfig(): if not os.path.exists(_SETTINGS_FILE): return [] app_list = [] f = open(_SETTINGS_FILE, "r") try: for line in f.readlines(): line = line.rstrip() if not line or line.startswith("#"): continue elif line == "sep": app_list.append("sep") elif line.startswith("label:"): app_list.append({"name": "LABEL", "cmd": line[6:], "args": ""}) elif line.startswith("folder:"): app_list.append({"name": "FOLDER", "cmd": line[7:], "args": ""}) else: try: name, cmd, args = line.split("|", 2) app_list.append( { "name": name, "cmd": cmd, "args": [n.replace("\n", "") for n in shlex.split(args)], } ) except ValueError: print("The following line has errors and will be ignored:\n%s" % line) finally: f.close() return app_list def build_menu(): if not os.path.exists(_SETTINGS_FILE): show_help_dlg( "<b>ERROR: No .sshmenu file found in home directory</b>\n\n%s" % _ABOUT_TXT, error=True ) sys.exit(1) app_list = get_sshplusconfig() menu = Gtk.Menu() menus = [menu] for app in app_list: if app == "sep": add_separator(menus[-1]) elif app["name"] == "FOLDER" and not app["cmd"]: if len(menus) > 1: menus.pop() elif app["name"] == "FOLDER": menu_item = add_menu_item(menus[-1], app["cmd"], "folder") menus.append(Gtk.Menu()) menu_item.set_submenu(menus[-1]) elif app["name"] == "LABEL": add_menu_item(menus[-1], app["cmd"], None) else: add_menu_item(menus[-1], app["name"], app) # Add SSHplus options folder to the end of the Menu add_separator(menu) menu_item = add_menu_item(menus[-1], "SSHplus Options", "folder") menus.append(Gtk.Menu()) menu_item.set_submenu(menus[-1]) add_menu_item(menus[-1], "Options", None) add_menu_item(menus[-1], "Edit", "_edit") add_menu_item(menus[-1], "Refresh", "_refresh") add_menu_item(menus[-1], "About", "_about") add_separator(menus[-1]) add_menu_item(menus[-1], "Quit", "_quit") menus.pop() return menu if __name__ == "__main__": ind = AppIndicator3.Indicator.new( "SSHplus", "utilities-terminal", AppIndicator3.IndicatorCategory.APPLICATION_STATUS ) ind.set_label("Launch", "none") ind.set_status(AppIndicator3.IndicatorStatus.ACTIVE) if not os.path.exists(_SETTINGS_FILE): edit_config_file() appmenu = build_menu() ind.set_menu(appmenu) Gtk.main()<|fim▁end|>
menu_item.show()
<|file_name|>garden_real.py<|end_file_name|><|fim▁begin|>#!/usr/bin/python # -*- coding: utf-8 -*- import pythymio import random from gardenworld import * init('info2_1') with pythymio.thymio(["acc"],[]) as Thym:<|fim▁hole|> state["delay"] = 10 def dispatch(evtid, evt_name, evt_args): # https://www.thymio.org/en:thymioapi prox freq is 16Hz if evt_name == "fwd.acc": # every 0.0625 sec state["time"] += 0.0625 state["delay"] -= 1 if state["delay"] < 0: if 7 < evt_args[1] < 14: if evt_args[0] > 10: state["delay"] = 20 tg() elif evt_args[0] < -10: state["delay"] = 20 td() elif evt_args[1] > 20 and abs(evt_args[0]) < 8: state["delay"] = 10 av() elif evt_args[1] < 5: if evt_args[0] > 10: state["delay"] = 20 dp() elif evt_args[0] < -10: state["delay"] = 20 ra() else: # Wat? print evt_name # Now lets start the loopy thing Thym.loop(dispatch) print "state is %s" % state print "Sayonara"<|fim▁end|>
state = dict([]) state["time"] = 0
<|file_name|>VerifyPP.js<|end_file_name|><|fim▁begin|>/** * @author Kai Salmen / www.kaisalmen.de */ 'use strict'; if ( KSX.test.projectionspace === undefined ) KSX.test.projectionspace = {}; KSX.test.projectionspace.VerifyPP = (function () { PPCheck.prototype = Object.create(KSX.core.ThreeJsApp.prototype, { constructor: { configurable: true, enumerable: true, value: PPCheck, writable: true } }); function PPCheck(elementToBindTo, loader) { KSX.core.ThreeJsApp.call(this); <|fim▁hole|> loader: loader }); this.controls = null; this.projectionSpace = new KSX.instancing.ProjectionSpace({ low: { index: 0, name: 'Low', x: 240, y: 100, defaultHeightFactor: 9, mesh: null }, medium: { index: 1, name: 'Medium', x: 720, y: 302, defaultHeightFactor: 18, mesh: null } }, 0); this.cameraDefaults = { posCamera: new THREE.Vector3( 300, 300, 300 ), far: 100000 }; } PPCheck.prototype.initPreGL = function() { var scope = this; var callbackOnSuccess = function () { scope.preloadDone = true; }; scope.projectionSpace.loadAsyncResources( callbackOnSuccess ); }; PPCheck.prototype.initGL = function () { this.projectionSpace.initGL(); this.projectionSpace.flipTexture( 'linkPixelProtest' ); this.scenePerspective.scene.add( this.projectionSpace.dimensions[this.projectionSpace.index].mesh ); this.scenePerspective.setCameraDefaults( this.cameraDefaults ); this.controls = new THREE.TrackballControls( this.scenePerspective.camera ); }; PPCheck.prototype.resizeDisplayGL = function () { this.controls.handleResize(); }; PPCheck.prototype.renderPre = function () { this.controls.update(); }; return PPCheck; })();<|fim▁end|>
this.configure({ name: 'PPCheck', htmlCanvas: elementToBindTo, useScenePerspective: true,
<|file_name|>sync_replicas_optimizer.py<|end_file_name|><|fim▁begin|># Copyright 2016 The TensorFlow Authors. 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. # ============================================================================== """Synchronize replicas for training.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.core.framework import types_pb2 from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import data_flow_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import state_ops from tensorflow.python.ops import variables from tensorflow.python.platform import tf_logging as logging from tensorflow.python.training import optimizer from tensorflow.python.training import queue_runner # Please note that the gradients from replicas are averaged instead of summed # (as in the old sync_replicas_optimizer) so you need to increase the learning # rate according to the number of replicas. This change is introduced to be # consistent with how gradients are aggregated (averaged) within a batch in a # replica. class SyncReplicasOptimizerV2(optimizer.Optimizer): """Class to synchronize, aggregate gradients and pass them to the optimizer. In a typical asynchronous training environment, it's common to have some stale gradients. For example, with a N-replica asynchronous training, gradients will be applied to the variables N times independently. Depending on each replica's training speed, some gradients might be calculated from copies of the variable from several steps back (N-1 steps on average). This optimizer avoids stale gradients by collecting gradients from all replicas, averaging them, then applying them to the variables in one shot, after which replicas can fetch the new variables and continue. The following accumulators/queue are created: <empty line> * N `gradient accumulators`, one per variable to train. Gradients are pushed to them and the chief worker will wait until enough gradients are collected and then average them before applying to variables. The accumulator will drop all stale gradients (more details in the accumulator op). * 1 `token` queue where the optimizer pushes the new global_step value after all variables are updated. The following local variable is created: * `sync_rep_local_step`, one per replica. Compared against the global_step in each accumulator to check for staleness of the gradients. The optimizer adds nodes to the graph to collect gradients and pause the trainers until variables are updated. For the Parameter Server job: <empty line> 1. An accumulator is created for each variable, and each replica pushes the gradients into the accumulators instead of directly applying them to the variables. 2. Each accumulator averages once enough gradients (replicas_to_aggregate) have been accumulated. 3. Apply the averaged gradients to the variables. 4. Only after all variables have been updated, increment the global step. 5. Only after step 4, pushes `global_step` in the `token_queue`, once for each worker replica. The workers can now fetch the global step, use it to update its local_step variable and start the next batch. For the replicas: <empty line> 1. Start a step: fetch variables and compute gradients. 2. Once the gradients have been computed, push them into gradient accumulators. Each accumulator will check the staleness and drop the stale. 3. After pushing all the gradients, dequeue an updated value of global_step from the token queue and record that step to its local_step variable. Note that this is effectively a barrier. 4. Start the next batch. ### Usage ```python # Create any optimizer to update the variables, say a simple SGD: opt = GradientDescentOptimizer(learning_rate=0.1) # Wrap the optimizer with sync_replicas_optimizer with 50 replicas: at each # step the optimizer collects 50 gradients before applying to variables. # Note that if you want to have 2 backup replicas, you can change # total_num_replicas=52 and make sure this number matches how many physical # replicas you started in your job. opt = tf.SyncReplicasOptimizerV2(opt, replicas_to_aggregate=50, total_num_replicas=50) # Some models have startup_delays to help stabilize the model but when using # sync_replicas training, set it to 0. # Now you can call `minimize()` or `compute_gradients()` and # `apply_gradients()` normally grads = opt.minimize(total_loss, global_step=self.global_step) # You can now call get_init_tokens_op() and get_chief_queue_runner(). # Note that get_init_tokens_op() must be called before creating session # because it modifies the graph by adding new nodes. init_token_op = opt.get_init_tokens_op() chief_queue_runner = opt.get_chief_queue_runner() ``` In the training program, every worker will run the train_op as if not synchronized. But one worker (usually the chief) will need to execute the chief_queue_runner and get_init_tokens_op from this optimizer. ```python # When you create the supervisor, you need to add the local_init_op and # ready_for_local_init_op to make sure the local_step is initialized to the # global_step. Here is an example: sv = tf.Supervisor(graph=g, is_chief=is_chief, # This initialize local step. local_init_op=local_init_op, # This makes sure global step is initialized before using. ready_for_local_init_op=ready_for_local_init_op, saver=model.saver) # After the session is created by the Supervisor and before the main while # loop: if is_chief and FLAGS.sync_replicas: sv.start_queue_runners(sess, [chief_queue_runner]) # Insert initial tokens to the queue. sess.run(init_token_op) ``` @@__init__ @@compute_gradients @@apply_gradients @@get_chief_queue_runner @@get_init_tokens_op """ def __init__(self, opt, replicas_to_aggregate, total_num_replicas=None, variable_averages=None, variables_to_average=None, use_locking=False, name="sync_replicas"): """Construct a sync_replicas optimizer. Args: opt: The actual optimizer that will be used to compute and apply the gradients. Must be one of the Optimizer classes. replicas_to_aggregate: number of replicas to aggregate for each variable update. total_num_replicas: Total number of tasks/workers/replicas, could be different from replicas_to_aggregate. If total_num_replicas > replicas_to_aggregate: it is backup_replicas + replicas_to_aggregate. If total_num_replicas < replicas_to_aggregate: Replicas compute multiple batches per update to variables. variable_averages: Optional `ExponentialMovingAverage` object, used to maintain moving averages for the variables passed in `variables_to_average`. variables_to_average: a list of variables that need to be averaged. Only needed if variable_averages is passed in. use_locking: If True use locks for update operation. name: string. Optional name of the returned operation. """ if total_num_replicas is None: total_num_replicas = replicas_to_aggregate super(SyncReplicasOptimizerV2, self).__init__(use_locking, name) logging.info( "SyncReplicasV2: replicas_to_aggregate=%s; total_num_replicas=%s", replicas_to_aggregate, total_num_replicas) self._opt = opt self._replicas_to_aggregate = replicas_to_aggregate self._gradients_applied = False self._variable_averages = variable_averages self._variables_to_average = variables_to_average self._total_num_replicas = total_num_replicas self._tokens_per_step = max(total_num_replicas, replicas_to_aggregate) self._global_step = None self._sync_token_queue = None # The synchronization op will be executed in a queue runner which should # only be executed by one of the replicas (usually the chief). self._chief_queue_runner = None # Remember which accumulator is on which device to set the initial step in # the accumulator to be global step. This list contains list of the # following format: (accumulator, device). self._accumulator_list = [] def compute_gradients(self, *args, **kwargs): """Compute gradients of "loss" for the variables in "var_list". This simply wraps the compute_gradients() from the real optimizer. The gradients will be aggregated in the apply_gradients() so that user can modify the gradients like clipping with per replica global norm if needed. The global norm with aggregated gradients can be bad as one replica's huge gradients can hurt the gradients from other replicas. Args: *args: Arguments for compute_gradients(). **kwargs: Keyword arguments for compute_gradients(). Returns: A list of (gradient, variable) pairs. """ return self._opt.compute_gradients(*args, **kwargs) def apply_gradients(self, grads_and_vars, global_step=None, name=None): """Apply gradients to variables. This contains most of the synchronization implementation and also wraps the apply_gradients() from the real optimizer. Args: grads_and_vars: List of (gradient, variable) pairs as returned by compute_gradients(). global_step: Optional Variable to increment by one after the variables have been updated. name: Optional name for the returned operation. Default to the name passed to the Optimizer constructor. Returns: train_op: The op to dequeue a token so the replicas can exit this batch and start the next one. This is executed by each replica. Raises: ValueError: If the grads_and_vars is empty. ValueError: If global step is not provided, the staleness cannot be checked. """ if not grads_and_vars: raise ValueError("Must supply at least one variable") if global_step is None: raise ValueError("Global step is required to check staleness") self._global_step = global_step train_ops = [] aggregated_grad = [] var_list = [] self._local_step = variables.Variable( initial_value=0, trainable=False, collections=[ops.GraphKeys.LOCAL_VARIABLES], name="sync_rep_local_step") self.local_step_init_op = state_ops.assign(self._local_step, global_step) chief_init_ops = [self.local_step_init_op] self.ready_for_local_init_op = variables.report_uninitialized_variables( variables.all_variables()) with ops.name_scope(None, self._name): for grad, var in grads_and_vars: var_list.append(var) with ops.device(var.device): # Dense gradients. if grad is None: aggregated_grad.append(None) # pass-through. continue elif isinstance(grad, ops.Tensor): grad_accum = data_flow_ops.ConditionalAccumulator( grad.dtype, shape=var.get_shape(), shared_name=var.name + "/grad_accum") train_ops.append(grad_accum.apply_grad( grad, local_step=self._local_step)) aggregated_grad.append(grad_accum.take_grad( self._replicas_to_aggregate)) else: if not isinstance(grad, ops.IndexedSlices): raise ValueError("Unknown grad type!") grad_accum = data_flow_ops.SparseConditionalAccumulator( grad.dtype, shape=(), shared_name=var.name + "/grad_accum") train_ops.append(grad_accum.apply_indexed_slices_grad( grad, local_step=self._local_step)) aggregated_grad.append(grad_accum.take_indexed_slices_grad( self._replicas_to_aggregate)) self._accumulator_list.append((grad_accum, var.device)) aggregated_grads_and_vars = zip(aggregated_grad, var_list) # sync_op will be assigned to the same device as the global step. with ops.device(global_step.device), ops.name_scope(""): update_op = self._opt.apply_gradients(aggregated_grads_and_vars, global_step) # Create token queue. with ops.device(global_step.device), ops.name_scope(""): sync_token_queue = ( data_flow_ops.FIFOQueue(-1, global_step.dtype.base_dtype, shapes=(), shared_name="sync_token_q")) self._sync_token_queue = sync_token_queue # dummy_queue is passed to the queue runner. Don't use the real queues # because the queue runner doesn't automatically reopen it once it # closed queues in PS devices. dummy_queue = ( data_flow_ops.FIFOQueue(1, types_pb2.DT_INT32, shapes=(), shared_name="dummy_queue")) with ops.device(global_step.device), ops.name_scope(""): # Replicas have to wait until they can get a token from the token queue. with ops.control_dependencies(train_ops): token = sync_token_queue.dequeue() train_op = state_ops.assign(self._local_step, token) with ops.control_dependencies([update_op]): # Sync_op needs to insert tokens to the token queue at the end of the # step so the replicas can fetch them to start the next step. tokens = array_ops.fill([self._tokens_per_step], global_step.ref()) sync_op = sync_token_queue.enqueue_many((tokens,)) if self._variable_averages is not None: with ops.control_dependencies([sync_op]), ops.name_scope(""): sync_op = self._variable_averages.apply( self._variables_to_average) self._chief_queue_runner = queue_runner.QueueRunner(dummy_queue, [sync_op]) for accum, dev in self._accumulator_list: with ops.device(dev): chief_init_ops.append( accum.set_global_step( global_step, name="SetGlobalStep")) self.chief_init_op = control_flow_ops.group(*(chief_init_ops)) self._gradients_applied = True return train_op def get_chief_queue_runner(self): """Returns the QueueRunner for the chief to execute. This includes the operations to synchronize replicas: aggregate gradients, apply to variables, increment global step, insert tokens to token queue. Note that this can only be called after calling apply_gradients() which actually generates this queuerunner. Returns: A `QueueRunner` for chief to execute. Raises: ValueError: If this is called before apply_gradients(). """ if self._gradients_applied is False: raise ValueError("Should be called after apply_gradients().") return self._chief_queue_runner def get_slot(self, *args, **kwargs): """Return a slot named "name" created for "var" by the Optimizer. This simply wraps the get_slot() from the actual optimizer. Args: *args: Arguments for get_slot(). **kwargs: Keyword arguments for get_slot(). Returns: The `Variable` for the slot if it was created, `None` otherwise. """ return self._opt.get_slot(*args, **kwargs) def get_slot_names(self, *args, **kwargs): """Return a list of the names of slots created by the `Optimizer`. This simply wraps the get_slot_names() from the actual optimizer. Args: *args: Arguments for get_slot(). **kwargs: Keyword arguments for get_slot(). Returns: A list of strings. """ return self._opt.get_slot_names(*args, **kwargs) def get_init_tokens_op(self, num_tokens=-1): """Returns the op to fill the sync_token_queue with the tokens. This is supposed to be executed in the beginning of the chief/sync thread so that even if the total_num_replicas is less than replicas_to_aggregate, the model can still proceed as the replicas can compute multiple steps per variable update. Make sure: `num_tokens >= replicas_to_aggregate - total_num_replicas`. Args: num_tokens: Number of tokens to add to the queue. Returns: An op for the chief/sync replica to fill the token queue. Raises: ValueError: If this is called before apply_gradients(). ValueError: If num_tokens are smaller than replicas_to_aggregate - total_num_replicas. """ if self._gradients_applied is False: raise ValueError( "get_init_tokens_op() should be called after apply_gradients().") tokens_needed = self._replicas_to_aggregate - self._total_num_replicas if num_tokens == -1: num_tokens = self._replicas_to_aggregate elif num_tokens < tokens_needed: raise ValueError( "Too few tokens to finish the first step: %d (given) vs %d (needed)" % (num_tokens, tokens_needed)) if num_tokens > 0: with ops.device(self._global_step.device), ops.name_scope(""): tokens = array_ops.fill([num_tokens], self._global_step.ref()) init_tokens = self._sync_token_queue.enqueue_many((tokens,)) else: init_tokens = control_flow_ops.no_op(name="no_init_tokens") return init_tokens # Please switch to v2 if you are still using the old sync optimizer. V2 # is much more efficient and stable. It also removed 100% of the stale # gradients which is not possible in this implementation without significant # overhead. This is kept here just for backward compatibility and will be # DEPRECATED later. class SyncReplicasOptimizer(optimizer.Optimizer): """Class to synchronize, aggregate gradients and pass them to the optimizer. In a typical asynchronous training environment, it's common to have some stale gradients. For example, with a N-replica asynchronous training, gradients will be applied to the variables N times independently. Depending on each replica's training speed, some gradients might be calculated from copies of the variable from several steps back (N-1 steps on average). This optimizer avoids stale gradients by collecting gradients from all replicas, summing them, then applying them to the variables in one shot, after which replicas can fetch the new variables and continue. The following queues are created: <empty line> * N `gradient` queues, one per variable to train. Gradients are pushed to these queues and the chief worker will dequeue_many and then sum them before applying to variables. * 1 `token` queue where the optimizer pushes the new global_step value after all gradients have been applied. The following variables are created: * N `local_step`, one per replica. Compared against global step to check for staleness of the gradients. This adds nodes to the graph to collect gradients and pause the trainers until variables are updated. For the PS: <empty line> 1. A queue is created for each variable, and each replica now pushes the gradients into the queue instead of directly applying them to the variables. 2. For each gradient_queue, pop and sum the gradients once enough replicas (replicas_to_aggregate) have pushed gradients to the queue. 3. Apply the aggregated gradients to the variables. 4. Only after all variables have been updated, increment the global step. 5. Only after step 4, clear all the gradients in the queues as they are stale now (could happen when replicas are restarted and push to the queues multiple times, or from the backup replicas). 6. Only after step 5, pushes `global_step` in the `token_queue`, once for each worker replica. The workers can now fetch it to its local_step variable and start the next batch. For the replicas: <empty line> 1. Start a step: fetch variables and compute gradients. 2. Once the gradients have been computed, push them into `gradient_queue` only if local_step equals global_step, otherwise the gradients are just dropped. This avoids stale gradients. 3. After pushing all the gradients, dequeue an updated value of global_step from the token queue and record that step to its local_step variable. Note that this is effectively a barrier. 4. Start the next batch. ### Usage ```python # Create any optimizer to update the variables, say a simple SGD: opt = GradientDescentOptimizer(learning_rate=0.1) # Wrap the optimizer with sync_replicas_optimizer with 50 replicas: at each # step the optimizer collects 50 gradients before applying to variables. opt = tf.SyncReplicasOptimizer(opt, replicas_to_aggregate=50, replica_id=task_id, total_num_replicas=50) # Note that if you want to have 2 backup replicas, you can change # total_num_replicas=52 and make sure this number matches how many physical # replicas you started in your job. # Some models have startup_delays to help stabilize the model but when using # sync_replicas training, set it to 0. # Now you can call `minimize()` or `compute_gradients()` and # `apply_gradients()` normally grads = opt.minimize(total_loss, global_step=self.global_step) # You can now call get_init_tokens_op() and get_chief_queue_runner(). # Note that get_init_tokens_op() must be called before creating session # because it modifies the graph. init_token_op = opt.get_init_tokens_op() chief_queue_runner = opt.get_chief_queue_runner() ``` In the training program, every worker will run the train_op as if not synchronized. But one worker (usually the chief) will need to execute the chief_queue_runner and get_init_tokens_op generated from this optimizer. ```python # After the session is created by the Supervisor and before the main while # loop: if is_chief and FLAGS.sync_replicas: sv.start_queue_runners(sess, [chief_queue_runner]) # Insert initial tokens to the queue. sess.run(init_token_op) ``` @@__init__ @@compute_gradients @@apply_gradients @@get_chief_queue_runner @@get_init_tokens_op """ def __init__(self, opt, replicas_to_aggregate, variable_averages=None, variables_to_average=None, replica_id=None, total_num_replicas=0, use_locking=False, name="sync_replicas"): """Construct a sync_replicas optimizer. Args: opt: The actual optimizer that will be used to compute and apply the gradients. Must be one of the Optimizer classes. replicas_to_aggregate: number of replicas to aggregate for each variable update. variable_averages: Optional `ExponentialMovingAverage` object, used to maintain moving averages for the variables passed in `variables_to_average`. variables_to_average: a list of variables that need to be averaged. Only needed if variable_averages is passed in. replica_id: This is the task/worker/replica ID. Needed as index to access local_steps to check staleness. Must be in the interval: [0, total_num_replicas) total_num_replicas: Total number of tasks/workers/replicas, could be different from replicas_to_aggregate. If total_num_replicas > replicas_to_aggregate: it is backup_replicas + replicas_to_aggregate. If total_num_replicas < replicas_to_aggregate: Replicas compute multiple batches per update to variables. use_locking: If True use locks for update operation. name: string. Optional name of the returned operation. """ if total_num_replicas == 0: total_num_replicas = replicas_to_aggregate super(SyncReplicasOptimizer, self).__init__(use_locking, name) logging.info("""TO BE DEPRECATED!!! This version will be deprecated. Please switch to V2 at your earliest convenience.""") logging.info( "SyncReplicas enabled: replicas_to_aggregate=%s; total_num_replicas=%s", replicas_to_aggregate, total_num_replicas) self._opt = opt self._replicas_to_aggregate = replicas_to_aggregate self._gradients_applied = False self._variable_averages = variable_averages self._variables_to_average = variables_to_average self._replica_id = replica_id self._total_num_replicas = total_num_replicas self._tokens_per_step = max(total_num_replicas, replicas_to_aggregate) self._global_step = None self._sync_token_queue = None # This will be executed in a queue runner and includes the synchronization # operations done by the chief. self._chief_queue_runner = None # Remember which queue is on which device for the "clear" operation. # This list contains list of the following format: (grad_queue, device). self._one_element_queue_list = [] # Sparse gradients queue has both value and index self._sparse_grad_queues_and_devs = [] # clean_up_op will be executed when the chief is about to restart. # If chief restarts, it is possible that some variables have already been # updated before and when chief comes back, these variables will not be # updated again as the workers have already computed the gradients for # them. # But chief still waits for all variables to be updated, which will hang # the training. # To avoid such hang, every time the chief is about to die, it will call # abort_op to kill the PS with the token_queue so all replicas will also # restart. # TODO(jmchen): When training restarts, the variables are restored from the # previous checkpoint. As such all the gradients in all the queues should be # removed as they are computed from potentially different variables. # Currently this is not done. self._clean_up_op = None def compute_gradients(self, *args, **kwargs): """Compute gradients of "loss" for the variables in "var_list". This simply wraps the compute_gradients() from the real optimizer. The gradients will be aggregated in the apply_gradients() so that user can modify the gradients like clipping with per replica global norm if needed. The global norm with aggregated gradients can be bad as one replica's huge gradients can hurt the gradients from other replicas. Args: *args: Arguments for compute_gradients(). **kwargs: Keyword arguments for compute_gradients(). Returns: A list of (gradient, variable) pairs. """ return self._opt.compute_gradients(*args, **kwargs) def _aggregate_sparse_grad(self, grad, var, train_ops): """Aggregate sparse gradients. Args: grad: The sparse gradient to aggregate. var: The variable to apply this gradient to. train_ops: The train_ops for the worker to run. Returns: aggregated_grad: Aggregated grad. """ # Sparse gradients have to be inserted as one pair of (value, # indice) as an element instead of the whole "indexedslice" because # their shapes are not deterministic. sparse_grad_queue = (data_flow_ops.FIFOQueue( -1, (grad.values.dtype, grad.indices.dtype), shapes=(var.get_shape().as_list()[1:], ()), shared_name="sparse_grad_q_%s" % var.name)) self._sparse_grad_queues_and_devs.append((sparse_grad_queue, var.device)) # Sparse token is inserted after the "enqueue_many" finishes. This # is needed to make sure enough sparse gradients have been enqueued # before applying them to the variables. sparse_token_queue = (data_flow_ops.FIFOQueue( self._replicas_to_aggregate * 2, types_pb2.DT_INT32, shapes=(), shared_name="sparse_token_q_%s" % var.name)) self._one_element_queue_list.append((sparse_token_queue, var.device)) enqueue_spares_op = sparse_grad_queue.enqueue_many([grad.values, grad.indices]) with ops.control_dependencies([enqueue_spares_op]): train_ops.append(sparse_token_queue.enqueue((1,))) with ops.control_dependencies([sparse_token_queue.dequeue_many( self._replicas_to_aggregate)]): values, indices = sparse_grad_queue.dequeue_many(sparse_grad_queue.size()) concat_grad = ops.IndexedSlices(values, indices, grad.dense_shape) # Sum the gradients of the same variables in the sparse layers so # that each variable is only updated once. Note that with 2 # gradients g1 and g2 from 2 replicas for the same variable, # apply(g1+g2) is different from apply(g1) and then apply(g2) when # the optimizer is complex like Momentum or Adagrad. values = concat_grad.values indices = concat_grad.indices new_indices, indx = array_ops.unique(indices) num_indices = array_ops.shape(new_indices)[0] sum_values = math_ops.unsorted_segment_sum(values, indx, num_indices) return ops.IndexedSlices(sum_values, new_indices, concat_grad.dense_shape)<|fim▁hole|> def apply_gradients(self, grads_and_vars, global_step=None, name=None): """Apply gradients to variables. This contains most of the synchronization implementation and also wraps the apply_gradients() from the real optimizer. Args: grads_and_vars: List of (gradient, variable) pairs as returned by compute_gradients(). global_step: Optional Variable to increment by one after the variables have been updated. name: Optional name for the returned operation. Default to the name passed to the Optimizer constructor. Returns: train_op: The op to dequeue a token so the replicas can exit this batch and start the next one. This is executed by each replica. Raises: ValueError: If the grads_and_vars is empty. ValueError: If global step is not provided, the staleness cannot be checked. """ if not grads_and_vars: raise ValueError("Must supply at least one variable") if global_step is None: raise ValueError("Global step is required to check staleness") self._global_step = global_step train_ops = [] aggregated_grad = [] inputs = [] var_list = [] for x in grads_and_vars: inputs.extend(list(x)) with ops.device(global_step.device): self._local_steps = variables.Variable( array_ops.zeros( [self._total_num_replicas], dtype=global_step.dtype), trainable=False, name="local_steps") # Check staleness. Note that this has to be ref(), otherwise identity will # be accessed and it will be old values. local_step = array_ops.slice(self._local_steps.ref(), array_ops.reshape(self._replica_id, (1,)), [1], name="get_local_step") local_step = array_ops.reshape(local_step, ()) is_stale = math_ops.less(local_step, global_step) with ops.name_scope(name, self._name, inputs) as name: for grad, var in grads_and_vars: var_list.append(var) with ops.device(var.device): if isinstance(grad, ops.Tensor): gradient_queue = (data_flow_ops.FIFOQueue(self._tokens_per_step * 2, grad.dtype, shapes=var.get_shape(), shared_name=var.name)) self._one_element_queue_list.append((gradient_queue, var.device)) train_ops.append(gradient_queue.enqueue([grad])) # Aggregate all gradients gradients = gradient_queue.dequeue_many( self._replicas_to_aggregate) aggregated_grad.append(math_ops.reduce_sum(gradients, [0])) elif grad is None: aggregated_grad.append(None) # pass-through. else: if not isinstance(grad, ops.IndexedSlices): raise ValueError("Unknown grad type!") aggregated_grad.append(self._aggregate_sparse_grad(grad, var, train_ops)) aggregated_grads_and_vars = zip(aggregated_grad, var_list) # sync_op will be assigned to the same device as the global step. with ops.device(global_step.device), ops.name_scope(""): update_op = self._opt.apply_gradients(aggregated_grads_and_vars, global_step) # Create token queue. with ops.device(global_step.device), ops.name_scope(""): sync_token_queue = ( data_flow_ops.FIFOQueue(-1, global_step.dtype.base_dtype, shapes=(), shared_name="sync_token_q")) self._sync_token_queue = sync_token_queue # dummy_queue is passed to the queue runner. Don't use the real queues # because the queue runner doesn't automatically reopen it once it # closed queues in PS devices. dummy_queue = ( data_flow_ops.FIFOQueue(1, types_pb2.DT_INT32, shapes=(), shared_name="dummy_queue")) # Clear all the gradients queues in case there are stale gradients. clear_queue_ops = [] with ops.control_dependencies([update_op]): for queue, dev in self._one_element_queue_list: with ops.device(dev): stale_grads = queue.dequeue_many(queue.size()) clear_queue_ops.append(stale_grads) for queue, dev in self._sparse_grad_queues_and_devs: with ops.device(dev): _, stale_indices = queue.dequeue_many(queue.size()) clear_queue_ops.append(stale_indices) with ops.device(global_step.device): self._clean_up_op = control_flow_ops.abort( error_msg="From sync_replicas") # According to the staleness, select between the enqueue op (real_grad) # or no-op (no_op_grad). Effectively dropping all the stale gradients. no_op_grad = lambda: [control_flow_ops.no_op(name="no_grad_enqueue")] real_grad = lambda: [control_flow_ops.group(*train_ops)] final_train_ops = control_flow_ops.cond(is_stale, no_op_grad, real_grad) with ops.device(global_step.device), ops.name_scope(""): # Replicas have to wait until they can get a token from the token queue. with ops.control_dependencies([final_train_ops]): token = sync_token_queue.dequeue() train_op = state_ops.scatter_update(self._local_steps, self._replica_id, token, name=name) with ops.control_dependencies(clear_queue_ops): # Sync_op needs to insert tokens to the token queue at the end of the # step so the replicas can fetch them to start the next step. # Note that ref() is used to avoid reading from the identity with old # the step. tokens = array_ops.fill([self._tokens_per_step], global_step.ref()) sync_op = sync_token_queue.enqueue_many((tokens,)) if self._variable_averages is not None: with ops.control_dependencies([sync_op]), ops.name_scope(""): sync_op = self._variable_averages.apply( self._variables_to_average) self._chief_queue_runner = queue_runner.QueueRunner(dummy_queue, [sync_op]) self._gradients_applied = True return train_op def get_chief_queue_runner(self): """Returns the QueueRunner for the chief to execute. This includes the operations to synchronize replicas: aggregate gradients, apply to variables, increment global step, insert tokens to token queue. Note that this can only be called after calling apply_gradients() which actually generates this queuerunner. Returns: A `QueueRunner` for chief to execute. Raises: ValueError: If this is called before apply_gradients(). """ if self._gradients_applied is False: raise ValueError("Should be called after apply_gradients().") return self._chief_queue_runner def get_slot(self, *args, **kwargs): """Return a slot named "name" created for "var" by the Optimizer. This simply wraps the get_slot() from the actual optimizer. Args: *args: Arguments for get_slot(). **kwargs: Keyword arguments for get_slot(). Returns: The `Variable` for the slot if it was created, `None` otherwise. """ return self._opt.get_slot(*args, **kwargs) def get_slot_names(self, *args, **kwargs): """Return a list of the names of slots created by the `Optimizer`. This simply wraps the get_slot_names() from the actual optimizer. Args: *args: Arguments for get_slot(). **kwargs: Keyword arguments for get_slot(). Returns: A list of strings. """ return self._opt.get_slot_names(*args, **kwargs) def get_clean_up_op(self): """Returns the clean up op for the chief to execute before exit. This includes the operation to abort the device with the token queue so all other replicas can also restart. This can avoid potential hang when chief restarts. Note that this can only be called after calling apply_gradients(). Returns: A clean_up_op for chief to execute before exits. Raises: ValueError: If this is called before apply_gradients(). """ if self._gradients_applied is False: raise ValueError( "get_clean_up_op() should be called after apply_gradients().") return self._clean_up_op def get_init_tokens_op(self, num_tokens=-1): """Returns the op to fill the sync_token_queue with the tokens. This is supposed to be executed in the beginning of the chief/sync thread so that even if the total_num_replicas is less than replicas_to_aggregate, the model can still proceed as the replicas can compute multiple steps per variable update. Make sure: `num_tokens >= replicas_to_aggregate - total_num_replicas`. Args: num_tokens: Number of tokens to add to the queue. Returns: An op for the chief/sync replica to fill the token queue. Raises: ValueError: If this is called before apply_gradients(). ValueError: If num_tokens are smaller than replicas_to_aggregate - total_num_replicas. """ if self._gradients_applied is False: raise ValueError( "get_init_tokens_op() should be called after apply_gradients().") tokens_needed = self._replicas_to_aggregate - self._total_num_replicas if num_tokens == -1: num_tokens = self._replicas_to_aggregate elif num_tokens < tokens_needed: raise ValueError( "Too few tokens to finish the first step: %d (given) vs %d (needed)" % (num_tokens, tokens_needed)) if num_tokens > 0: with ops.device(self._global_step.device), ops.name_scope(""): tokens = array_ops.fill([num_tokens], self._global_step.ref()) init_tokens = self._sync_token_queue.enqueue_many((tokens,)) else: init_tokens = control_flow_ops.no_op(name="no_init_tokens") return init_tokens<|fim▁end|>
<|file_name|>create.js<|end_file_name|><|fim▁begin|>/* -------------------------------------------------------------------------- */ /* Copyright 2002-2016, OpenNebula Project, OpenNebula 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. */ /* -------------------------------------------------------------------------- */ define(function(require) { /* DEPENDENCIES */ // require('foundation.tab'); var BaseFormPanel = require('utils/form-panels/form-panel'); var Sunstone = require('sunstone'); var Locale = require('utils/locale'); //var Tips = require('utils/tips'); var TemplateUtils = require('utils/template-utils'); var WizardFields = require('utils/wizard-fields'); var RoleTab = require('tabs/vmgroup-tab/utils/role-tab'); var AffinityRoleTab = require('tabs/vmgroup-tab/utils/affinity-role-tab'); var Notifier = require('utils/notifier'); var Utils = require('../utils/common'); /* TEMPLATES */ var TemplateWizardHTML = require('hbs!./create/wizard'); var TemplateAdvancedHTML = require('hbs!./create/advanced'); /* CONSTANTS */ var FORM_PANEL_ID = require('./create/formPanelId'); var TAB_ID = require('../tabId'); /* CONSTRUCTOR */ function FormPanel() { this.formPanelId = FORM_PANEL_ID; this.tabId = TAB_ID; this.affinity_role_tab = new AffinityRoleTab([]); this.actions = { 'create': { 'title': Locale.tr("Create Virtual Machine Group"), 'buttonText': Locale.tr("Create"), 'resetButton': true }, 'update': { 'title': Locale.tr("Update Virtual Machine Group"), 'buttonText': Locale.tr("Update"), 'resetButton': false } }; BaseFormPanel.call(this); } FormPanel.FORM_PANEL_ID = FORM_PANEL_ID; FormPanel.prototype = Object.create(BaseFormPanel.prototype); FormPanel.prototype.constructor = FormPanel; FormPanel.prototype.htmlWizard = _htmlWizard; FormPanel.prototype.htmlAdvanced = _htmlAdvanced; FormPanel.prototype.submitWizard = _submitWizard; FormPanel.prototype.submitAdvanced = _submitAdvanced; FormPanel.prototype.onShow = _onShow; FormPanel.prototype.fill = _fill; FormPanel.prototype.setup = _setup; FormPanel.prototype.addRoleTab = _add_role_tab; return FormPanel; /* FUNCTION DEFINITIONS */ function _htmlWizard() { var opts = { info: false, select: true }; return TemplateWizardHTML({ 'affinity-role-tab': this.affinity_role_tab.html(), 'formPanelId': this.formPanelId }); } function _htmlAdvanced() { return TemplateAdvancedHTML({formPanelId: this.formPanelId}); } function _setup(context) { this.roleTabObjects = {}; var that = this; var roles_index = 0; this.affinity_role_tab.setup(context); // Fill parents table // Each time a tab is clicked the table is filled with existing tabs (roles) // Selected roles are kept // TODO If the name of a role is changed and is selected, selection will be lost $("#roles_tabs", context).on("click", "a", function() { var tab_id = "#"+this.id+"Tab"; var str = ""; $(tab_id+" .parent_roles").hide(); var parent_role_available = false; $("#roles_tabs_content #role_name", context).each(function(){ if ($(this).val() != "" && ($(this).val() != $(tab_id+" #role_name", context).val())) { parent_role_available = true; str += "<tr>\ <td style='width:10%'>\ <input class='check_item' type='checkbox' value='"+$(this).val()+"' id='"+$(this).val()+"'/>\ </td>\ <td>"+$(this).val()+"</td>\ </tr>"; } }); if (parent_role_available) { $(tab_id+" .parent_roles", context).show(); } var selected_parents = []; $(tab_id+" .parent_roles_body input:checked", context).each(function(){ selected_parents.push($(this).val()); }); $(tab_id+" .parent_roles_body", context).html(str); $.each(selected_parents, function(){ $(tab_id+" .parent_roles_body #"+this, context).attr('checked', true); }); }); $("#tf_btn_roles", context).bind("click", function(){ that.addRoleTab(roles_index, context);<|fim▁hole|> return false; }); /*$("#btn_refresh_roles", context).bind("click", function(){ $("#btn_refresh_roles", context).html("<i class='fa fa-angle-double-down'></i> "+Locale.tr("Refresh roles")); that.affinity_role_tab.refresh(context, that.roleTabObjects); });*/ //---------btn_group_vm_roles Foundation.reflow(context, 'tabs'); // Add first role $("#tf_btn_roles", context).trigger("click"); //Tips.setup(); return false; } function _submitWizard(context) { that = this; var name = WizardFields.retrieveInput($('#vm_group_name', context)); var description = WizardFields.retrieveInput($('#vm_group_description', context)); var role = []; $('.role_content', context).each(function() { var role_id = $(this).attr("role_id"); role.push(that.roleTabObjects[role_id].retrieve($(this))); }); //call to role-tab.js for retrieve data var roles_affinity = this.affinity_role_tab.retrieve(context); var vm_group_json = { "NAME" : name, "DESCRIPTION": description, "ROLE" : role, }; vm_group_json = $.extend(vm_group_json, roles_affinity); if (this.action == "create") { vm_group_json = { "vm_group" : vm_group_json }; Sunstone.runAction("VMGroup.create",JSON.parse(JSON.stringify(vm_group_json))); return false; } else if (this.action == "update") { delete vm_group_json["NAME"]; Sunstone.runAction( "VMGroup.update", this.resourceId, TemplateUtils.templateToString(vm_group_json)); return false; } } function _submitAdvanced(context) { if (this.action == "create") { var template = $('textarea#template', context).val(); var vm_group_json = {vm_group: {vm_group_raw: template}}; Sunstone.runAction("VMGroup.create",vm_group_json); return false; } else if (this.action == "update") { var template_raw = $('textarea#template', context).val(); Sunstone.runAction("VMGroup.update_template", this.resourceId, template_raw); return false; } } function _onShow(context) { var that = this; $('.role_content', context).each(function() { var role_id = $(this).attr("role_id"); that.roleTabObjects[role_id].onShow(); }); } function _fill(context, element) { $("#new_role", context)[0].parentElement.remove(); var that = this; this.setHeader(element); this.resourceId = element.ID; $('#template', context).val(TemplateUtils.templateToString(element.TEMPLATE)); WizardFields.fillInput($('#vm_group_name',context), element.NAME); $('#vm_group_name',context).prop("disabled", true); WizardFields.fillInput($('#vm_group_description', context), element.TEMPLATE.DESCRIPTION ); //Remove row of roles----------------------------------------------------------------- $.each(element.ROLES.ROLE, function(index, value){ var name = value.NAME; if(name){ var html = "<option id='" + name + "' class='roles' value=" + name + "> " + name + "</option>"; $("#list_roles_select").append(html); $("select #" + name).mousedown(function(e) { e.preventDefault(); $(this).prop('selected', !$(this).prop('selected')); return false; }); } }); this.affinity_role_tab.fill(context, element); $("#btn_refresh_roles", context).remove(); $("#affinity",context).show(); //Remove row of roles------------------------------------------------------------------ /*var role_context_first = $('.role_content', context).first(); var role_id_first = $(role_context_first).attr("role_id"); delete that.roleTabObjects[role_id_first]; // Populates the Avanced mode Tab var roles_names = []; var data = []; if(Array.isArray(element.ROLES.ROLE)) data = element.ROLES.ROLE; else data.push(element.ROLES.ROLE); $.each(data, function(index, value){ roles_names.push(value.NAME); $("#tf_btn_roles", context).click(); var role_context = $('.role_content', context).last(); var role_id = $(role_context).attr("role_id"); that.roleTabObjects[role_id].fill(role_context, value,element); }); $.each(data, function(index, value){ var role_context = $('.role_content', context)[index]; var str = ""; $.each(roles_names, function(){ if (this != value.NAME) { str += "<tr>\ <td style='width:10%'>\ <input class='check_item' type='checkbox' value='"+this+"' id='"+this+"'/>\ </td>\ <td>"+this+"</td>\ </tr>"; } }); $(".parent_roles_body", role_context).html(str); if (value.parents) { $.each(value.parents, function(index, value){ $(".parent_roles_body #"+this, role_context).attr('checked', true); }); } });*/ //Remove first tab role, is empty. //$('i.remove-tab', context).first().click(); //$("#tf_btn_roles", context).click(); } function _add_role_tab(role_id, dialog) { var that = this; var html_role_id = 'role' + role_id; var role_tab = new RoleTab(html_role_id); that.roleTabObjects[role_id] = role_tab; // Append the new div containing the tab and add the tab to the list var role_section = $('<div id="'+html_role_id+'Tab" class="tabs-panel role_content wizard_internal_tab" role_id="'+role_id+'">'+ role_tab.html() + '</div>').appendTo($("#roles_tabs_content", dialog)); _redo_service_vmgroup_selector_role(dialog, role_section); role_section.on("change", "#role_name", function(){ var val = true; var chars = ['/','*','&','|',':', String.fromCharCode(92),'"', ';', '/',String.fromCharCode(39),'#','{','}','$','<','>','*']; var newName = $(this).val(); $.each(chars, function(index, value){ if(newName.indexOf(value) != -1 && val){ val = false; } }); if(val){ that.affinity_role_tab.refresh($(this).val(), role_tab.oldName()); role_tab.changeNameTab(newName); } else { Notifier.notifyError(Locale.tr("The new role name contains invalid characters.")); } }); //Tips.setup(role_section); var a = $("<li class='tabs-title'>\ <a class='text-center' id='"+html_role_id+"' href='#"+html_role_id+"Tab'>\ <span>\ <i class='off-color fa fa-cube fa-3x'/>\ <br>\ <span id='role_name_text'>"+Locale.tr("Role ")+role_id+"</span>\ </span>\ <i class='fa fa-times-circle remove-tab'></i>\ </a>\ </li>").appendTo($("ul#roles_tabs", dialog)); Foundation.reInit($("ul#roles_tabs", dialog)); $("a", a).trigger("click"); // close icon: removing the tab on click a.on("click", "i.remove-tab", function() { var target = $(this).parent().attr("href"); var li = $(this).closest('li'); var ul = $(this).closest('ul'); var content = $(target); var role_id = content.attr("role_id"); li.remove(); content.remove(); if (li.hasClass('is-active')) { $('a', ul.children('li').last()).click(); } that.affinity_role_tab.removeRole(role_tab.oldName()); delete that.roleTabObjects[role_id]; return false; }); role_tab.setup(role_section); role_tab.onShow(); } function _redo_service_vmgroup_selector_role(dialog, role_section){ $('#roles_tabs_content .role_content', dialog).each(function(){ var role_section = this; var role_tab_id = $(role_section).attr('id'); }); } });<|fim▁end|>
roles_index++;
<|file_name|>test_availability_zone.py<|end_file_name|><|fim▁begin|># 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 # License for the specific language governing permissions and limitations # under the License. import nova.conf from nova.tests.functional.api_sample_tests import test_servers CONF = nova.conf.CONF class AvailabilityZoneJsonTest(test_servers.ServersSampleBase): ADMIN_API = True extension_name = "os-availability-zone" def _get_flags(self): f = super(AvailabilityZoneJsonTest, self)._get_flags() f['osapi_compute_extension'] = CONF.osapi_compute_extension[:] f['osapi_compute_extension'].append( 'nova.api.openstack.compute.contrib.availability_zone.' 'Availability_zone') return f <|fim▁hole|> self._verify_response('availability-zone-list-resp', {}, response, 200) def test_availability_zone_detail(self): response = self._do_get('os-availability-zone/detail') self._verify_response('availability-zone-detail-resp', {}, response, 200) def test_availability_zone_post(self): self._post_server()<|fim▁end|>
def test_availability_zone_list(self): response = self._do_get('os-availability-zone')
<|file_name|>__init__.py<|end_file_name|><|fim▁begin|>""" General functions for HTML manipulation, backported from Py3.<|fim▁hole|>module names and locations. """ from __future__ import unicode_literals _escape_map = {ord('&'): '&amp;', ord('<'): '&lt;', ord('>'): '&gt;'} _escape_map_full = {ord('&'): '&amp;', ord('<'): '&lt;', ord('>'): '&gt;', ord('"'): '&quot;', ord('\''): '&#x27;'} # NB: this is a candidate for a bytes/string polymorphic interface def escape(s, quote=True): """ Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true (the default), the quotation mark characters, both double quote (") and single quote (') characters are also translated. """ assert not isinstance(s, bytes), 'Pass a unicode string' if quote: return s.translate(_escape_map_full) return s.translate(_escape_map)<|fim▁end|>
Note that this uses Python 2.7 code with the corresponding Python 3
<|file_name|>GlobalForParameter.py<|end_file_name|><|fim▁begin|># Copyright 2021, Kay Hayen, mailto:kay.hayen@gmail.com # # Python tests originally created or extracted from other peoples work. The # parts were too small to be protected. # # 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<|fim▁hole|> global a<|fim▁end|>
# limitations under the License. # def f(a):
<|file_name|>test_content.py<|end_file_name|><|fim▁begin|># -*- coding: UTF-8 -*- # # Copyright (c) 2009 Ars Aperta, Itaapy, Pierlis, Talend. # # Authors: Romain Gauthier <romain@itaapy.com> # Hervé Cauwelier <herve@itaapy.com> # David Versmisse <david.versmisse@itaapy.com> # # This file is part of Lpod (see: http://lpod-project.org). # Lpod is free software; you can redistribute it and/or modify it under # the terms of either: # # a) the GNU General Public License as published by the Free Software # Foundation, either version 3 of the License, or (at your option) # any later version. # Lpod is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with Lpod. If not, see <http://www.gnu.org/licenses/>. # # b) 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 # # Import from the Standard Library from unittest import TestCase, main # Import from lpod from lpod.document import odf_get_document class ContentTestCase(TestCase): def setUp(self): self.document = document = odf_get_document('samples/base_text.odt') def tearDown(self): del self.document def test_get_body(self): body = self.document.get_body() expected = ('<office:text>\n' ' <text:sequence-decls>\n'<|fim▁hole|> ' <text:sequence-decl text:display-outline-level="0" ' 'text:name="Table"/>\n' ' <text:sequence-decl text:display-outline-level="0" ' 'text:name="Text"/>\n' ' <text:sequence-decl text:display-outline-level="0" ' 'text:name="Drawing"/>\n' ' </text:sequence-decls>\n' ' <text:section text:style-name="Sect1" ' 'text:name="Section1">\n' ' <text:h text:style-name="Heading_20_1" ' 'text:outline-level="1">LpOD Test Case Document</text:h>\n' ' <text:p text:style-name="Text_20_body">This is the ' 'first paragraph.</text:p>\n' ' <text:p text:style-name="Text_20_body">This is the ' 'second paragraph.</text:p>\n' ' <text:p text:style-name="Hanging_20_indent">This is ' 'a paragraph with a named style.</text:p>\n' ' <text:h text:style-name="Heading_20_2" ' 'text:outline-level="2">Level 2 Title</text:h>\n' ' <text:p text:style-name="Text_20_body">This is the ' 'first paragraph of the second title.</text:p>\n' ' <text:p text:style-name="Text_20_body">This is the ' 'last paragraph with diacritical signs: ' '&#233;&#232;</text:p>\n' ' </text:section>\n' ' <text:section text:style-name="Sect1" ' 'text:name="Section2">\n' ' <text:h text:style-name="Heading_20_1" ' 'text:outline-level="1" text:restart-numbering="true" ' 'text:start-value="-1">First Title of the ' 'Second Section</text:h>\n' ' <text:p text:style-name="Text_20_body">First ' 'paragraph of the second section.</text:p>\n' ' <text:p text:style-name="Text_20_body">This is ' 'the second paragraph with <text:a xlink:type="simple" ' 'xlink:href="http://lpod-project.org/" office:name="Link ' 'to the lpod project">an external link</text:a> inside.' '</text:p>\n' ' </text:section>\n' ' </office:text>\n') self.assertEqual(body.serialize(pretty=True), expected) if __name__ == '__main__': main()<|fim▁end|>
' <text:sequence-decl text:display-outline-level="0" ' 'text:name="Illustration"/>\n'
<|file_name|>test_blog_settings.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- # Copyright (c) 2020, Frappe Technologies and Contributors # See license.txt from __future__ import unicode_literals # import frappe import unittest<|fim▁hole|><|fim▁end|>
class TestBlogSettings(unittest.TestCase): pass
<|file_name|>test_del_contact.py<|end_file_name|><|fim▁begin|>from model.contact import Contact import random def test_delete_some_contact(app, db, check_ui): if len(db.get_contact_list()) == 0: app.contact.add(Contact(firstname="test")) old_contacts = db.get_contact_list() contact = random.choice(old_contacts) app.contact.delete_contact_by_id(contact.id) assert len(old_contacts) - 1 == app.contact.count() new_contacts = db.get_contact_list() old_contacts.remove(contact)<|fim▁hole|> assert sorted(new_contacts, key=Contact.id_or_max) == sorted(app.contact.get_contact_list(), key=Contact.id_or_max)<|fim▁end|>
assert old_contacts == new_contacts if check_ui:
<|file_name|>GrandStaffApp.java<|end_file_name|><|fim▁begin|>package com.rockhoppertech.music.fx.cmn; /* * #%L * rockymusic-fx * %% * Copyright (C) 1996 - 2013 Rockhopper Technologies * %% * 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. * #L% */ import java.io.IOException; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Scene; import javafx.scene.SceneBuilder; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.Pane; import javafx.scene.paint.Color; import javafx.stage.Screen; import javafx.stage.Stage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author <a href="http://genedelisa.com/">Gene De Lisa</a> * */ public class GrandStaffApp extends Application { private static final Logger logger = LoggerFactory .getLogger(GrandStaffApp.class); private Stage stage; private Scene scene; private Pane root; private GrandStaffAppController controller; public static void main(String[] args) throws Exception { launch(args); } void loadRootFxml() { String fxmlFile = "/fxml/GrandStaffPanel.fxml"; logger.debug("Loading FXML for main view from: {}", fxmlFile); try { FXMLLoader loader = new FXMLLoader( GrandStaffApp.class.getResource(fxmlFile)); root = (AnchorPane) loader.load(); controller = loader.getController(); } catch (IOException e) { logger.error(e.getLocalizedMessage(),e); } } @Override public void start(Stage stage) throws Exception { this.stage = stage; // this.staffModel = new StaffModel(); // MIDITrack track = MIDITrackBuilder // .create() // .noteString( // "E5 F G Ab G# A B C C6 D Eb F# G A B C7 B4 Bf4 A4 Af4") // .durations(5, 4, 3, 2, 1, 1.5, .5, .75, .25, .25) // .sequential() // .build(); // this.staffModel.setTrack(track); <|fim▁hole|> .root(root) .fill(Color.web("#1030F0")) .stylesheets("/styles/grandStaffApp.css") .build(); this.configureStage(); logger.debug("started"); } private void configureStage() { stage.setTitle("Music Notation"); // fullScreen(); stage.setScene(this.scene); stage.show(); } private void fullScreen() { // make it full screen stage.setX(0); stage.setY(0); stage.setWidth(Screen.getPrimary().getVisualBounds().getWidth()); stage.setHeight(Screen.getPrimary().getVisualBounds().getHeight()); } }<|fim▁end|>
loadRootFxml(); this.scene = SceneBuilder.create()
<|file_name|>apps.py<|end_file_name|><|fim▁begin|>from django.apps import AppConfig<|fim▁hole|><|fim▁end|>
class FinancesConfig(AppConfig): name = "finances"
<|file_name|>client.rs<|end_file_name|><|fim▁begin|>/* * Copyright 2015-2016 Torrie Fischer <tdfischer@hackerbots.net> * * 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. */ use std::collections::BTreeMap; use std::collections::HashMap; use hyper; use rustc_serialize::json::Json; use rustc_serialize::json; use std::fmt; use std::result; use matrix::json as mjson; use matrix::events; use matrix::model; enum ApiVersion { R0, V1, V2Alpha } #[derive(Debug)] pub enum ClientError { Http(hyper::Error), UrlNotFound(hyper::Url), BadStatus(hyper::status::StatusCode), Json(json::ParserError) } pub type Result<T = ()> = result::Result<T, ClientError>; mod http { use rustc_serialize::json::Json; use hyper; use std::io::Read; use matrix::client::{Result,ClientError}; pub fn json(http: hyper::client::RequestBuilder) -> Result<Json> { let mut response = String::new(); http.send().map_err(|err|{ ClientError::Http(err) }).and_then(|mut res|{ match res.status { hyper::status::StatusCode::Ok => { res.read_to_string(&mut response).expect("Could not read response"); Json::from_str(&response).map_err(|err|{ ClientError::Json(err) }) }, hyper::status::StatusCode::NotFound => Err(ClientError::UrlNotFound(res.url.clone())), s => Err(ClientError::BadStatus(s)) } }) } } pub struct AsyncPoll { http: hyper::client::Client, url: hyper::Url } impl AsyncPoll { fn do_room_events(events: &mut Vec<events::Event>, json: &Vec<Json>, id: &String) { for ref evt in json { if cfg!(raw_logs) { trace!("<<< {}", evt); } let mut e = evt.as_object().unwrap().clone(); e.insert("room_id".to_string(), Json::String(id.clone())); // FIXME: It'd be nice to return to the previous // callback-based mechanism to avoid memory bloat events.push(events::Event::from_json(&Json::Object(e))); }; } pub fn send(self) -> Result<Vec<events::Event>> { http::json(self.http.get(self.url)).and_then(|json| { if cfg!(raw_logs) { trace!("Got JSON! {}", json.pretty()); } let mut ret: Vec<events::Event> = vec![]; let presence = mjson::path(&json, "presence.events").as_array().unwrap(); for ref p in presence { ret.push(events::Event::from_json(&Json::Object(p.as_object().unwrap().clone()))); }; let joined_rooms = mjson::path(&json, "rooms.join").as_object().unwrap(); for (id, r) in joined_rooms { AsyncPoll::do_room_events(&mut ret, mjson::array(r, "state.events"), id); AsyncPoll::do_room_events(&mut ret, mjson::array(r, "timeline.events"), id); AsyncPoll::do_room_events(&mut ret, mjson::array(r, "account_data.events"), id); AsyncPoll::do_room_events(&mut ret, mjson::array(r, "ephemeral.events"), id); }; let next_token = mjson::string(&json, "next_batch").to_string(); ret.push(events::Event { age: 0, data: events::EventData::EndOfSync(next_token), id: None }); Ok(ret) }) } } #[derive(Clone)] pub struct AccessToken { access: String, refresh: String } pub struct Client { http: hyper::Client, token: Option<AccessToken>, next_id: u32, baseurl: hyper::Url, pub uid: Option<model::UserID> } impl fmt::Debug for Client { fn fmt(&self, _: &mut fmt::Formatter) -> fmt::Result { Ok(()) } } impl Client { pub fn new(baseurl: hyper::Url) -> Self { if !baseurl.scheme.starts_with("https") { warn!("YOU ARE CONNECTING TO A MATRIX SERVER WITHOUT SSL"); } let mut http = hyper::Client::new(); http.set_redirect_policy(hyper::client::RedirectPolicy::FollowAll); Client { http: http, token: None, next_id: 0, baseurl: baseurl, uid: None } } pub fn anon_login(&mut self) -> Result { let mut query_args = HashMap::new(); query_args.insert("kind", "guest"); debug!("Logging in to matrix"); http::json(self.http.post(self.url(ApiVersion::R0, "register", &query_args))) .and_then(|js| { let obj = js.as_object().unwrap(); self.token = Some(AccessToken { access: obj.get("access_token").unwrap().as_string().unwrap().to_string(), refresh: String::new() }); self.uid = Some(model::UserID::from_str(obj.get("user_id").unwrap().as_string().unwrap())); Ok(()) }) } pub fn login(&mut self, username: &str, password: &str) -> Result { let mut d = BTreeMap::new(); d.insert("user".to_string(), Json::String(username.to_string())); d.insert("password".to_string(), Json::String(password.to_string())); d.insert("type".to_string(), Json::String("m.login.password".to_string())); debug!("Logging in to matrix"); http::json(self.http.post(self.url(ApiVersion::V1, "login", &HashMap::new())) .body(&Json::Object(d).to_string())) .and_then(|js| { let obj = js.as_object().unwrap(); self.token = Some(AccessToken { access: obj.get("access_token").unwrap().as_string().unwrap().to_string(), refresh: obj.get("refresh_token").unwrap().as_string().unwrap().to_string() }); let domain = self.baseurl.host().unwrap().serialize(); self.uid = Some(model::UserID::from_str(&format!("@{}:{}", username, domain))); Ok(()) }) } fn url(&self, version: ApiVersion, endpoint: &str, args: &HashMap<&str, &str>) -> hyper::Url { let mut ret = self.baseurl.clone(); ret.path_mut().unwrap().append(&mut vec!["client".to_string()]); ret.path_mut().unwrap().append(&mut match version { ApiVersion::R0 => vec!["r0".to_string()], ApiVersion::V1 => vec!["api".to_string(), "v1".to_string()], ApiVersion::V2Alpha => vec!["v2_alpha".to_string()] }); ret.path_mut().unwrap().push(endpoint.to_string()); let args_with_auth = match self.token { None => args.clone(), Some(ref token) => { let mut a = args.clone(); a.insert("access_token", &*token.access); a } }; ret.set_query_from_pairs(args_with_auth); ret } pub fn sync(&mut self, token: Option<&str>) -> AsyncPoll { let mut args = HashMap::new();<|fim▁hole|> args.insert("full_state", "true"); } let url = self.url(ApiVersion::V2Alpha, "sync", &args); let mut http = hyper::client::Client::new(); http.set_redirect_policy(hyper::client::RedirectPolicy::FollowAll); AsyncPoll { http: http, url: url } } pub fn send(&mut self, evt: events::EventData) -> Result<model::EventID> { self.next_id += 1; match evt { events::EventData::Room(ref id, _) => { let url = self.url(ApiVersion::V1, &format!("rooms/{}/send/{}/{}", id, evt.type_str(), self.next_id), &HashMap::new()); trace!("Sending events to {:?}", url); // FIXME: This seems needed since hyper will pool HTTP client // connections for pipelining. Sometimes the server will close // the pooled connection and everything will catch on fire here. let mut http = hyper::client::Client::new(); http.set_redirect_policy(hyper::client::RedirectPolicy::FollowAll); http::json(http.put(url).body(&format!("{}", evt.to_json()))) }, _ => panic!("Don't know where to send {}", evt.to_json()) }.and_then(|response| { if cfg!(raw_logs) { trace!(">>> {} {:?}", evt.to_json(), response); } Ok(model::EventID::from_str(mjson::string(&response, "event_id"))) }) } }<|fim▁end|>
if let Some(next) = token { args.insert("since", next); args.insert("timeout", "5000"); } else {
<|file_name|>index.js<|end_file_name|><|fim▁begin|>"use strict"; var ArrayCollection_1 = require('./ArrayCollection'); exports.ArrayCollection = ArrayCollection_1.ArrayCollection; var ArrayList_1 = require('./ArrayList'); exports.ArrayList = ArrayList_1.ArrayList; var SequenceBase_1 = require('./SequenceBase'); exports.SequenceBase = SequenceBase_1.SequenceBase; var Buckets_1 = require('./Buckets'); exports.Buckets = Buckets_1.Buckets; var Collection_1 = require('./Collection'); exports.Collection = Collection_1.Collection; var Dictionary_1 = require('./Dictionary'); exports.Dictionary = Dictionary_1.Dictionary; exports.Pair = Dictionary_1.Pair; var Hash_1 = require('./Hash'); exports.HashFunc = Hash_1.HashFunc; exports.DefaultHashFunc = Hash_1.DefaultHashFunc; var HashSet_1 = require('./HashSet'); exports.HashSet = HashSet_1.HashSet; var Iterable_1 = require('./Iterable'); exports.Iterable = Iterable_1.Iterable; var LinkedList_1 = require('./LinkedList'); exports.LinkedList = LinkedList_1.LinkedList; var Native_1 = require('./Native'); exports.NativeIndex = Native_1.NativeIndex; exports.NativeMap = Native_1.NativeMap; var Sequence_1 = require('./Sequence'); exports.Sequence = Sequence_1.Sequence;<|fim▁hole|>//# sourceMappingURL=index.js.map<|fim▁end|>
var Stack_1 = require('./Stack'); exports.Stack = Stack_1.Stack; var Util_1 = require('./Util'); exports.Util = Util_1.Util;
<|file_name|>DBLogger.py<|end_file_name|><|fim▁begin|>import datetime import MySQLdb from os import sys<|fim▁hole|> self.pwd = '<password>' self.dbase = '<database>' self.location = loc self.conn = MySQLdb.connect(host="localhost", user=self.usr, passwd=self.pwd, db=self.dbase) self.cursor = self.conn.cursor() def cleanUp(self): self.conn.close() self.cursor.close()<|fim▁end|>
class DBLogger: def __init__(self, loc='default-location'): self.usr = '<user>'
<|file_name|>config.ts<|end_file_name|><|fim▁begin|>/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ <|fim▁hole|>import {Type} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import {PRIMARY_OUTLET, Params} from './shared'; import {UrlSegment, UrlSegmentGroup} from './url_tree'; /** * @whatItDoes Represents router configuration. * * @description * `Routes` is an array of route configurations. Each one has the following properties: * * - `path` is a string that uses the route matcher DSL. * - `pathMatch` is a string that specifies the matching strategy. * - `component` is a component type. * - `redirectTo` is the url fragment which will replace the current matched segment. * - `outlet` is the name of the outlet the component should be placed into. * - `canActivate` is an array of DI tokens used to look up CanActivate handlers. See {@link * CanActivate} for more info. * - `canActivateChild` is an array of DI tokens used to look up CanActivateChild handlers. See * {@link * CanActivateChild} for more info. * - `canDeactivate` is an array of DI tokens used to look up CanDeactivate handlers. See {@link * CanDeactivate} for more info. * - `data` is additional data provided to the component via `ActivatedRoute`. * - `resolve` is a map of DI tokens used to look up data resolvers. See {@link Resolve} for more * info. * - `children` is an array of child route definitions. * * ### Simple Configuration * * ``` * [{ * path: 'team/:id', * component: Team, * children: [ * { * path: 'user/:name', * component: User * } * ] * }] * ``` * * When navigating to `/team/11/user/bob`, the router will create the team component with the user * component in it. * * ### Multiple Outlets * * ``` * [{ * path: 'team/:id', * component: Team * }, * { * path: 'chat/:user', * component: Chat * outlet: 'aux' * }] * ``` * * When navigating to `/team/11(aux:chat/jim)`, the router will create the team component next to * the chat component. The chat component will be placed into the aux outlet. * * ### Wild Cards * * ``` * [{ * path: '**', * component: Sink * }] * ``` * * Regardless of where you navigate to, the router will instantiate the sink component. * * ### Redirects * * ``` * [{ * path: 'team/:id', * component: Team, * children: [ * { * path: 'legacy/user/:name', * redirectTo: 'user/:name' * }, * { * path: 'user/:name', * component: User * } * ] * }] * ``` * * When navigating to '/team/11/legacy/user/jim', the router will change the url to * '/team/11/user/jim', and then will instantiate the team component with the user component * in it. * * If the `redirectTo` value starts with a '/', then it is an absolute redirect. E.g., if in the * example above we change the `redirectTo` to `/user/:name`, the result url will be '/user/jim'. * * ### Empty Path * * Empty-path route configurations can be used to instantiate components that do not 'consume' * any url segments. Let's look at the following configuration: * * ``` * [{ * path: 'team/:id', * component: Team, * children: [ * { * path: '', * component: AllUsers * }, * { * path: 'user/:name', * component: User * } * ] * }] * ``` * * When navigating to `/team/11`, the router will instantiate the AllUsers component. * * Empty-path routes can have children. * * ``` * [{ * path: 'team/:id', * component: Team, * children: [ * { * path: '', * component: WrapperCmp, * children: [ * { * path: 'user/:name', * component: User * } * ] * } * ] * }] * ``` * * When navigating to `/team/11/user/jim`, the router will instantiate the wrapper component with * the user component in it. * * An empty path route inherits its parent's params and data. This is because it cannot have its * own params, and, as a result, it often uses its parent's params and data as its own. * * ### Matching Strategy * * By default the router will look at what is left in the url, and check if it starts with * the specified path (e.g., `/team/11/user` starts with `team/:id`). * * We can change the matching strategy to make sure that the path covers the whole unconsumed url, * which is akin to `unconsumedUrl === path` or `$` regular expressions. * * This is particularly important when redirecting empty-path routes. * * ``` * [{ * path: '', * pathMatch: 'prefix', //default * redirectTo: 'main' * }, * { * path: 'main', * component: Main * }] * ``` * * Since an empty path is a prefix of any url, even when navigating to '/main', the router will * still apply the redirect. * * If `pathMatch: full` is provided, the router will apply the redirect if and only if navigating to * '/'. * * ``` * [{ * path: '', * pathMatch: 'full', * redirectTo: 'main' * }, * { * path: 'main', * component: Main * }] * ``` * * ### Componentless Routes * * It is useful at times to have the ability to share parameters between sibling components. * * Say we have two components--ChildCmp and AuxCmp--that we want to put next to each other and both * of them require some id parameter. * * One way to do that would be to have a bogus parent component, so both the siblings can get the id * parameter from it. This is not ideal. Instead, you can use a componentless route. * * ``` * [{ * path: 'parent/:id', * children: [ * { path: 'a', component: MainChild }, * { path: 'b', component: AuxChild, outlet: 'aux' } * ] * }] * ``` * * So when navigating to `parent/10/(a//aux:b)`, the route will instantiate the main child and aux * child components next to each other. In this example, the application component * has to have the primary and aux outlets defined. * * The router will also merge the `params`, `data`, and `resolve` of the componentless parent into * the `params`, `data`, and `resolve` of the children. This is done because there is no component * that can inject the activated route of the componentless parent. * * This is especially useful when child components are defined as follows: * * ``` * [{ * path: 'parent/:id', * children: [ * { path: '', component: MainChild }, * { path: '', component: AuxChild, outlet: 'aux' } * ] * }] * ``` * * With this configuration in place, navigating to '/parent/10' will create the main child and aux * components. * * ### Lazy Loading * * Lazy loading speeds up our application load time by splitting it into multiple bundles, and * loading them on demand. The router is designed to make lazy loading simple and easy. Instead of * providing the children property, you can provide * the loadChildren property, as follows: * * ``` * [{ * path: 'team/:id', * component: Team, * loadChildren: 'team' * }] * ``` * * The router will use registered NgModuleFactoryLoader to fetch an NgModule associated with 'team'. * Then it will * extract the set of routes defined in that NgModule, and will transparently add those routes to * the main configuration. * * @stable use Routes */ export type Routes = Route[]; /** * @whatItDoes Represents the results of the URL matching. * * * `consumed` is an array of the consumed URL segments. * * `posParams` is a map of positional parameters. * * @experimental */ export type UrlMatchResult = { consumed: UrlSegment[]; posParams?: {[name: string]: UrlSegment}; }; /** * @whatItDoes A function matching URLs * * @description * * A custom URL matcher can be provided when a combination of `path` and `pathMatch` isn't * expressive enough. * * For instance, the following matcher matches html files. * * ``` * function htmlFiles(url: UrlSegment[]) { * return url.length === 1 && url[0].path.endsWith('.html') ? ({consumed: url}) : null; * } * * const routes = [{ matcher: htmlFiles, component: HtmlCmp }]; * ``` * * @experimental */ export type UrlMatcher = (segments: UrlSegment[], group: UrlSegmentGroup, route: Route) => UrlMatchResult; /** * @whatItDoes Represents the static data associated with a particular route. * See {@link Routes} for more details. * @stable */ export type Data = { [name: string]: any }; /** * @whatItDoes Represents the resolved data associated with a particular route. * See {@link Routes} for more details. * @stable */ export type ResolveData = { [name: string]: any }; /** * @whatItDoes The type of `loadChildren`. * See {@link Routes} for more details. * @stable */ export type LoadChildrenCallback = () => Type<any>| Promise<Type<any>>| Observable<Type<any>>; /** * @whatItDoes The type of `loadChildren`. * * See {@link Routes} for more details. * @stable */ export type LoadChildren = string | LoadChildrenCallback; /** * See {@link Routes} for more details. * @stable */ export interface Route { path?: string; pathMatch?: string; matcher?: UrlMatcher; component?: Type<any>; redirectTo?: string; outlet?: string; canActivate?: any[]; canActivateChild?: any[]; canDeactivate?: any[]; canLoad?: any[]; data?: Data; resolve?: ResolveData; children?: Route[]; loadChildren?: LoadChildren; } export function validateConfig(config: Routes): void { // forEach doesn't iterate undefined values for (let i = 0; i < config.length; i++) { validateNode(config[i]); } } function validateNode(route: Route): void { if (!route) { throw new Error(` Invalid route configuration: Encountered undefined route. The reason might be an extra comma. Example: const routes: Routes = [ { path: '', redirectTo: '/dashboard', pathMatch: 'full' }, { path: 'dashboard', component: DashboardComponent },, << two commas { path: 'detail/:id', component: HeroDetailComponent } ]; `); } if (Array.isArray(route)) { throw new Error(`Invalid route configuration: Array cannot be specified`); } if (route.component === undefined && (route.outlet && route.outlet !== PRIMARY_OUTLET)) { throw new Error( `Invalid route configuration of route '${route.path}': a componentless route cannot have a named outlet set`); } if (!!route.redirectTo && !!route.children) { throw new Error( `Invalid configuration of route '${route.path}': redirectTo and children cannot be used together`); } if (!!route.redirectTo && !!route.loadChildren) { throw new Error( `Invalid configuration of route '${route.path}': redirectTo and loadChildren cannot be used together`); } if (!!route.children && !!route.loadChildren) { throw new Error( `Invalid configuration of route '${route.path}': children and loadChildren cannot be used together`); } if (!!route.redirectTo && !!route.component) { throw new Error( `Invalid configuration of route '${route.path}': redirectTo and component cannot be used together`); } if (!!route.path && !!route.matcher) { throw new Error( `Invalid configuration of route '${route.path}': path and matcher cannot be used together`); } if (route.redirectTo === undefined && !route.component && !route.children && !route.loadChildren) { throw new Error( `Invalid configuration of route '${route.path}': one of the following must be provided (component or redirectTo or children or loadChildren)`); } if (route.path === undefined) { throw new Error(`Invalid route configuration: routes must have path specified`); } if (route.path.startsWith('/')) { throw new Error( `Invalid route configuration of route '${route.path}': path cannot start with a slash`); } if (route.path === '' && route.redirectTo !== undefined && route.pathMatch === undefined) { const exp = `The default value of 'pathMatch' is 'prefix', but often the intent is to use 'full'.`; throw new Error( `Invalid route configuration of route '{path: "${route.path}", redirectTo: "${route.redirectTo}"}': please provide 'pathMatch'. ${exp}`); } if (route.pathMatch !== undefined && route.pathMatch !== 'full' && route.pathMatch !== 'prefix') { throw new Error( `Invalid configuration of route '${route.path}': pathMatch can only be set to 'prefix' or 'full'`); } }<|fim▁end|>
<|file_name|>functionCallOnConstrainedTypeVariable.ts<|end_file_name|><|fim▁begin|>// @strict: true // Repro from #20196 type A = { a: (x: number) => string }; type B = { a: (x: boolean) => string }; function call0(p: A | B) { p.a("s"); // Error } function callN<T extends A | B>(p: T) { <|fim▁hole|> a("", "", "", ""); // Error }<|fim▁end|>
p.a("s"); // Error var a: T["a"] = p.a; a(""); // Error
<|file_name|>redis.py<|end_file_name|><|fim▁begin|>from feedly.feed_managers.base import Feedly from feedly.feeds.base import UserBaseFeed from feedly.feeds.redis import RedisFeed from feedly.tests.managers.base import BaseFeedlyTest import pytest class RedisUserBaseFeed(UserBaseFeed, RedisFeed): pass class RedisFeedly(Feedly):<|fim▁hole|> feed_classes = { 'feed': RedisFeed } user_feed_class = RedisUserBaseFeed @pytest.mark.usefixtures("redis_reset") class RedisFeedlyTest(BaseFeedlyTest): manager_class = RedisFeedly<|fim▁end|>
<|file_name|>generate.js<|end_file_name|><|fim▁begin|><|fim▁hole|> var pages = [ 'index', 'contact', 'faq', 'registration', 'sponsors', 'travel', 'visit', 'volunteers' ]; pages.forEach(function(page) { cons.dust('views/'+page+'.dust', { views: __dirname+'/views'}, function(err, html) { if(err) return console.log('error: ', err); fs.writeFile(__dirname+'/dist/'+page+'.html', html, function(err) { if(err) return console.log('error saving file: ', page, err); console.log('create page: ', page); }); }); });<|fim▁end|>
var fs = require('fs'), cons = require('consolidate'), dust = require('dustjs-linkedin');
<|file_name|>TanteadorTopilejo.java<|end_file_name|><|fim▁begin|>package Calibradores; import java.io.File; import Metricas.MultiescalaConBorde; import Modelo.UrbanizandoFrenos; public class TanteadorTopilejo extends Tanteador { UrbanizandoFrenos CA; public TanteadorTopilejo() { // int[] unConjuntoDeParametros = {1, 1, 1, 333, 333, 333, 1, 1, 444, 400, 400, 555}; // puntoDeTanteo = new PuntoDeBusqueda(unConjuntoDeParametros); // puntoDelRecuerdo = new PuntoDeBusqueda(unConjuntoDeParametros); <|fim▁hole|> CA.setDistVias(new File ("Topilejo/distancia1.txt")); CA.setPendiente(new File ("Topilejo/pendiente.txt")); CA.setGoalGrid(new File ("Topilejo/topi1999.txt")); infoADN = CA.infoADN; MultiescalaConBorde metrica = new MultiescalaConBorde(CA.gridMeta, CA.numeroDeCeldasX, CA.numeroDeCeldasY ); metrica.normalizateConEste(new File ("Topilejo/topi1995.txt")); CA.setMetric(metrica); CA.setIteraciones(4); puntoDeTanteo = new PuntoDeBusqueda(infoADN.size); puntoDelRecuerdo = new PuntoDeBusqueda(infoADN.size); vuelo = new PuntoDeBusqueda(infoADN.size); bajando = new Ventana("Guardar Acercamiento", "Caminante Siego Estocastico"); bajando.setVisible(true); bajando.graf.setLocation(850, 715); bajando.setQueTantoLocation(865, 650); //solo para correr los 3 calibradores al mismo tiempo // ventana = new Ventana("Guardar Todo", "Todos"); // ventana.setVisible(true); pintaGrid1 = new PintaGrid(new File("Topilejo/topi1999.txt"), "Grrid Meta", 4); pintaGrid2 = new PintaGrid(new File("Topilejo/topi1995.txt"), "Mejor Aproximacion", 5); pintaGrid3 = new PintaGrid(new File("Topilejo/topi1995.txt"), "Grid de Salida", 4); pintaGrid2.setLocation(865, 370); } public double mide(int[] parametros) { return CA.mide(parametros, 100); } public static void main(String[] args) { TanteadorTopilejo topo = new TanteadorTopilejo(); topo.busca(); } @Override public int[][] unOutputPara(int[] parametros) { // TODO Auto-generated method stub return CA.unOutputPara(parametros); } }<|fim▁end|>
CA = new UrbanizandoFrenos(72, 56, 11, 4); CA.setInitialGrid(new File ("Topilejo/topi1995.txt")); CA.setBosque(new File ("Topilejo/bosqueb.txt"));
<|file_name|>copy_tree.py<|end_file_name|><|fim▁begin|>''' Created on Dec 12, 2011 @author: sean ''' from . import Visitor import ast #FIXME: add tests class CopyVisitor(Visitor): ''' Copy only ast nodes and lists ''' def visitDefault(self, node): Node = type(node) new_node = Node() for _field in Node._fields: if hasattr(node, _field): field = getattr(node, _field) if isinstance(field, (list, tuple)):<|fim▁hole|> for item in field: if isinstance(item, ast.AST): new_item = self.visit(item) else: new_item = item new_list.append(new_item) setattr(new_node, _field, new_list) elif isinstance(field, ast.AST): setattr(new_node, _field, self.visit(field)) else: setattr(new_node, _field, field) for _attr in node._attributes: if hasattr(node, _attr): setattr(new_node, _attr, getattr(node, _attr)) return new_node def copy_node(node): return CopyVisitor().visit(node)<|fim▁end|>
new_list = []
<|file_name|>ModalManager.jest.tsx<|end_file_name|><|fim▁begin|>import { LoginForm } from "v2/Components/Authentication/Desktop/LoginForm" import { ModalType } from "v2/Components/Authentication/Types" import { mount, ReactWrapper } from "enzyme" import React from "react" import { Intent, ContextModule } from "@artsy/cohesion" import { ModalManager, ModalManagerProps, } from "v2/Components/Authentication/Desktop/ModalManager" const getWrapper = ( props?: ModalManagerProps ): ReactWrapper<ModalManagerProps> => { const wrapper = mount( <ModalManager submitUrls={{ apple: "/users/auth/apple", facebook: "/users/auth/facebook", login: "/login", signup: "/signup", forgot: "/forgot", }} csrf="CSRF_TOKEN" {...props} /> ) return wrapper } describe("ModalManager", () => { it("renders the right form when a type is passed in", () => { const wrapper = getWrapper() expect(wrapper.find(LoginForm).exists).toBeTruthy() }) it("sets the currentType if openModal is called", () => { const wrapper = getWrapper() const manager = wrapper.instance() as ModalManager manager.openModal({ mode: ModalType.login, intent: Intent.login, contextModule: ContextModule.header, }) expect(manager.state.currentType).toEqual("login") }) it("sets the currentType to null if closeModal is called", () => { const wrapper = getWrapper() const manager = wrapper.instance() as ModalManager manager.closeModal() expect(manager.state.currentType).toEqual(null) }) it("prevents scrolling when opened", () => { const wrapper = getWrapper() const manager = wrapper.instance() as ModalManager expect(document.body.style.overflowY).toEqual("visible") manager.openModal({ mode: ModalType.login, intent: Intent.login, contextModule: ContextModule.header, }) expect(document.body.style.overflowY).toEqual("hidden") }) it("handles type changes", () => { const wrapper = getWrapper() const manager = wrapper.instance() as ModalManager manager.openModal({ mode: ModalType.login, intent: Intent.login, contextModule: ContextModule.header, }) manager.handleTypeChange("signup") expect(manager.state.currentType).toEqual("signup") expect(manager.state.switchedForms).toEqual(true) expect(manager.state.options.mode).toEqual("signup") }) it("returns the right subtitle", () => { const wrapper = getWrapper() const manager = wrapper.instance() as ModalManager manager.openModal({ mode: ModalType.login, intent: Intent.signup, copy: "Foobar",<|fim▁hole|> contextModule: ContextModule.header, }) expect(manager.getSubtitle()).toEqual("Foobar") manager.handleTypeChange("signup") expect(manager.getSubtitle()).toEqual("Sign up") manager.handleTypeChange("forgot") expect(manager.getSubtitle()).toEqual("Reset your password") }) })<|fim▁end|>
<|file_name|>lib.rs<|end_file_name|><|fim▁begin|>extern crate regex; macro_rules! regex( ($s:expr) => (regex::Regex::new($s).unwrap()); ); pub fn is_valid(kennitala : &str) -> bool { let constants = [3, 2, 7, 6, 5, 4, 3, 2]; let re = regex!(r"^\d{6}-?\d{4}$");<|fim▁hole|> if re.is_match(kennitala) { let sanitized = kennitala.replace("-",""); let check_digit = (sanitized.as_bytes()[8] as char).to_digit(10).unwrap(); let c = constants .iter() .zip(sanitized.bytes()) .fold(0, |sum : u32, (x, y) : (&u32, u8)| sum + x * (y as char).to_digit(10).unwrap() ); println!("check digit: {0}", check_digit); if 11 - (c % 11) == check_digit { return true } } false }<|fim▁end|>
<|file_name|>vk_parser.py<|end_file_name|><|fim▁begin|>import vk import json from sentiment_classifiers import SentimentClassifier, binary_dict, files class VkFeatureProvider(object): def __init__(self): self._vk_api = vk.API(vk.Session()) self._vk_delay = 0.3 self._clf = SentimentClassifier(files['binary_goods'], binary_dict) def _vk_grace(self): import time time.sleep(self._vk_delay) def get_news(self, sources, amount=10): # entry for Alex Anlysis tool result = [] for source in sources: try: data = self._vk_api.wall.get(domain=source, count=amount, extended=1, fields='name') self._vk_grace() except: return {} news = [] for node in data['wall'][1:]: try: if node['post_type'] != 'post': continue text = node['text'] #print('{}'.format(text.encode('utf-8'))) rate = self._clf.predict_text(text)[0] news.append({'text' : '{}'.format(text.encode('utf-8')), 'rate' : rate}) except Exception as e: print('Exception: {}'.format(e))<|fim▁hole|> #return json.dumps(result) return result # NOTE: the completely other feature, very usefull personally for me def friends_intersect(self, uid_list): result = None try: result = set(self._vk_api.friends.get(user_id=uid_list[0])) self._vk_grace() except: pass for i, uid in enumerate(uid_list[1:]): try: tmp = set(self._vk_api.friends.get(user_id=uid)) self._vk_grace() except: continue if result is not None: result = result.intersection(tmp) else: result = tmp return result def get_user_info(self, entry_uid, fname=None, lname=None): try: friend_list = self._vk_api.friends.get(user_id=entry_uid, fields='personal', name_case='nom') self._vk_grace() except: return [] return [x for x in friend_list if (not fname or fname in x['first_name']) and (not lname or lname in x['last_name'])] def get_uid_set_info(self, uid_set): result = [] for friend_uid in uid_set: try: friend = self._vk_api.users.get(user_id=friend_uid, fields='sex,personal', name_case='nom') self._vk_grace() except: continue result.append(friend) return result if __name__ == '__main__': provider = VkFeatureProvider() res = provider.get_news(['scientific.american'], 5) print(res)<|fim▁end|>
result.append({'source': data['groups'][0]['name'], 'news': news})
<|file_name|>GridList.d.ts<|end_file_name|><|fim▁begin|>import * as React from 'react'; import { StandardProps } from '..'; export interface GridListProps extends StandardProps< React.HTMLAttributes<HTMLUListElement>, GridListClassKey > { cellHeight?: number | 'auto'; cols?: number; component?: string | React.ComponentType<GridListProps>; spacing?: number;<|fim▁hole|> export type GridListClassKey = | 'root' ; declare const GridList: React.ComponentType<GridListProps>; export default GridList;<|fim▁end|>
}
<|file_name|>simrun.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- """Simulation launch services. Simulation launch services provide the following functionality: - generating simulation id based on local date and time; - generating simulation directory name;<|fim▁hole|>- loading names of simulation directories from a text file; - creating directory structure for simulation; - normalizing the format of executable; - launching simulation. """ import os import shlex import subprocess import time from simtools.argparse import all_options as options from simtools.base import is_iterable, is_string TMP_DIR_PREFIX = "_" def generate_sim_id(): """Generate simulation id based on local date and time.""" t = time.localtime() sim_id = "{0:04}{1:02}{2:02}_{3:02}{4:02}{5:02}".format( t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec) return sim_id def generate_sim_dirname(tmp=False, sim_id=None): """Generate simulation directory name.""" if not sim_id: sim_id = generate_sim_id() return sim_id if not tmp else TMP_DIR_PREFIX + sim_id def make_dirs(sim_dirname, sim_master_dirname=None, data_dirname=None): """Create directory structure for simulation.""" if sim_master_dirname is not None: sim_path = os.path.join(sim_master_dirname, sim_dirname) else: sim_path = sim_dirname os.makedirs(sim_path) # raises an error if simulation directory already # exists if data_dirname is not None: os.makedirs(os.path.join(sim_path, data_dirname)) return sim_path def run_sim(model_filename, params_filename=None, sim_id=None, data_dirname=None, executable=None, model_args=None): """Launch simulation.""" cmd = [] if executable: if is_string(executable): cmd.append(executable) else: if not is_iterable(executable): raise TypeError( "'executable' is neither a string nor iterable.") cmd += executable cmd.append(model_filename) if params_filename: cmd += [options['params_filename']['arg'][1], params_filename] if sim_id: cmd += [options['sim_id']['arg'][1], sim_id] if data_dirname: cmd += [options['data_dirname']['arg'][1], data_dirname] cmd.append(options['save_data']['arg'][1]) if model_args: cmd += model_args return subprocess.call(cmd) def norm_executable(executable): """Normalize the format of executable.""" # Split executable name and arguments executable = shlex.split(executable) # If necessary, determine the absolute path to the executable if not os.path.isabs(executable[0]) and os.path.isfile(executable[0]): executable[0] = os.path.abspath(executable[0]) return executable def load_sim_dirnames(filename): """Load names of simulation directories from a file.""" COMMENT_START_TOKEN = "#" sim_dirnames = [] with open(filename) as sim_dirnames_file: for line in sim_dirnames_file: # Strip leading and trailing whitespace from the line stripped_line = line.strip() # If the stripped line is empty or contains only a comment, skip it if (not stripped_line or stripped_line.startswith(COMMENT_START_TOKEN)): continue # Assume that the stripped line contains a directory path and # normalize it according to the platform sim_dirname = os.path.normpath(stripped_line.replace("\\", os.sep)) sim_dirnames.append(sim_dirname) return sim_dirnames<|fim▁end|>
<|file_name|>until_any_or_whitespace.rs<|end_file_name|><|fim▁begin|>use read_token::ReadToken; use range::Range; use std::sync::Arc; use super::{ ParseResult, }; use { DebugId, MetaData, ParseError, }; use tokenizer::{ read_data, TokenizerState }; /// Stores information about reading until whitespace or any of some character. #[derive(Clone, Debug, PartialEq)] pub struct UntilAnyOrWhitespace { /// The characters to stop at. pub any_characters: Arc<String>, /// Whether empty data is accepted or not. pub optional: bool, /// The property to store read text. pub property: Option<Arc<String>>, /// A debug id to track down the rule generating an error. pub debug_id: DebugId, } impl UntilAnyOrWhitespace { /// Parses until whitespace or any specified characters. pub fn parse( &self, tokens: &mut Vec<Range<MetaData>>, state: &TokenizerState, read_token: &ReadToken ) -> ParseResult<TokenizerState> { let (range, _) = read_token.until_any_or_whitespace( &self.any_characters); if range.length == 0 && !self.optional { Err(range.wrap(ParseError::ExpectedSomething(self.debug_id))) } else { if let Some(ref property) = self.property { let text = read_token.raw_string(range.length); Ok((range, read_data( tokens, range.wrap( MetaData::String(property.clone(), Arc::new(text))),<|fim▁hole|> Ok((range, state.clone(), None)) } } } } #[cfg(test)] mod tests { use all::*; use all::tokenizer::*; use meta_rules::UntilAnyOrWhitespace; use range::Range; use read_token::ReadToken; use std::sync::Arc; #[test] fn required() { let text = "fn ()"; let mut tokenizer = vec![]; let s = TokenizerState::new(); let name = UntilAnyOrWhitespace { debug_id: 0, any_characters: Arc::new("(".into()), optional: false, property: None }; let res = name.parse(&mut tokenizer, &s, &ReadToken::new(&text[3..], 3)); assert_eq!(res, Err(Range::new(3, 0).wrap( ParseError::ExpectedSomething(0)))); } #[test] fn successful() { let text = "fn foo()"; let mut tokens = vec![]; let s = TokenizerState::new(); let function_name: Arc<String> = Arc::new("function_name".into()); let name = UntilAnyOrWhitespace { debug_id: 0, any_characters: Arc::new("(".into()), optional: false, property: Some(function_name.clone()) }; let res = name.parse(&mut tokens, &s, &ReadToken::new(&text[3..], 3)); assert_eq!(res, Ok((Range::new(3, 3), TokenizerState(1), None))); assert_eq!(tokens.len(), 1); assert_eq!(&tokens[0].data, &MetaData::String(function_name.clone(), Arc::new("foo".into()))); } }<|fim▁end|>
state ), None)) } else {
<|file_name|>error.py<|end_file_name|><|fim▁begin|># box # Copyright 2013-2014 Dipen Patel # See LICENSE for details. STATUSCODES = { 200 : "success", 201 : "created", 202 : "accepted", 204 : "no_content", 302 : "redirect", 304 : "not_modified", 400 : "bad_request", 401 : "unauthorized", 403 : "forbidden", 404 : "not_found", 405 : "method_not_allowed", 409 : "conflict", 412 : "precondition_failed", 429 : "too_many_requests", 500 : "internal_server_error", 507 : "insufficient_storage" } ERRORCODES = (204,400,401,403,404,405,409,412,429,500,507) class BoxError(Exception): """Box exception"""<|fim▁hole|> Exception.__init__(self, reason) def __str__(self): return self.reason<|fim▁end|>
def __init__(self, reason, response=None): self.reason = unicode(reason) self.response = response
<|file_name|>biopore_detect.py<|end_file_name|><|fim▁begin|># coding: utf-8 import numpy as np import matplotlib.pyplot as plt import scipy.ndimage as snd import seaborn as sns from skimage import img_as_float, morphology, measure from skimage.color import rgb2hsv from skimage.morphology import reconstruction from skimage.exposure import rescale_intensity from skimage.measure import label from astropy.table import Table from scipy import spatial from skimage.filters import sobel from skimage.feature import peak_local_max def biop_det(fi, mp_threshold, patch_threshold, perc,px, plot=True, morph=False,testing=True): """ Function for detecting biopores to analyse their spatial arrangement & matrix interaction Line 105:134 are adapted from the preprocessor of the echoRD-model by C. Jackisch. For further informations see: https://github.com/cojacoo/echoRD_model/tree/master/echoRD file "macropore_ini.py" Parameters ---------- fi : input image ('.png'-format, either as rgb or rgba image) mp_threshold : lower limit for removing small macropores patch_threshold : min [0] and max [1] of the desired patch size limits (usually min=100,max=10000) perc : value up to which percentile gray values among to biopores (0.125 shows good results for brighter soil matrix) px : actual length of one pixel in input image [mm] plot : True/False: whether results should be plotted (default:True) morph : if True the morphology of detected biopores will be plotted, otherwise pores are displayed as scatterplot and distinguished whether stained or not (default) testing : if True no distances are calculated and only the detected macropores are plotted to reduce computing time during threshold adjustment (default), otherwise all distances are computed Output ------ Dictionary with following keys: 'biopores' : labeled biopores 'biopores_centroidxy' : x/y-coordinates of detected biopores 'biopores_stained_centroidxy' : x/y-coordinates of detected stained biopores 'biopores_area' : area of detected biopores (number of pixels) 'biopores_diameter' : diameter of detected biopores (diameter of circle with same area [mm]) 'distance_matrix_biopore' : distance of each image pixel to nearest biopore [mm] 'distance_matrix_stained_biopore' : distance of each image to nearest stained biopore [mm] 'biopore_matrix_interaction' : distance of pixels from stained patches including at least one biopore to nearest stained biopore [mm] (estimation of biopore-matrix interaction) 'stained_patches' : labeled blue-stained patches 'patches_with_biopores' : detected blue-stained patches including at least one biopore 'table' : summary table with number and main propertiesd of detected biopores 'stained_index' : index of stained biopores 'unstained_index' : index of unstained biopores """ im_raw = snd.imread(fi) # load image sim = np.shape(im_raw) if sim[2]==4: imrgb=im_raw[:,:,:3] else: imrgb=im_raw imhsv = rgb2hsv(imrgb) # convert RGB image to HSV color-space img = imhsv[:,:,2] # extract value channel im = img_as_float(imrgb) # load image as float for detection of stained patches sim = np.shape(im) # extract dimensions of input image # morphological reconstruction for detecting holes inside the picture (according to general example # "filling holes and detecting peaks" from scikit-image http://scikit-image.org/docs/dev/auto_examples/features_detection/plot_holes_and_peaks.html#sphx-glr-auto-examples-features-detection-plot-holes-and-peaks-py) seed = np.copy(img) seed[1:-1, 1:-1] = img.max() mask = img filled = reconstruction(seed, mask, method='erosion') holes=img-filled # rescale and extract macropores holes_resc=rescale_intensity(holes,out_range=(0.0,1)) thresh=np.percentile(holes_resc,perc) holes_resc[holes_resc>thresh]=1 holes_resc[holes_resc<thresh]=0 bp_label=label(holes_resc,neighbors=8, background=1) bp_label[bp_label==-1]=0 # remove objects smaller than threshold bp_label_clean = morphology.remove_small_objects(bp_label, min_size=mp_threshold) # detect and label blue stained patches # calculate difference of channels to extract blue stained patches dim=abs(im[:,:,1]-im[:,:,0]) # discard low contrasts dim[dim<0.2]=0.0 # filter to local maxima for further segmentation # process segmentation according to sobel function of skimage image_max = snd.maximum_filter(dim, size=5, mode='constant') elevation_map = sobel(dim) markers = np.zeros_like(dim) markers[image_max < 0.1] = 2 markers[image_max > 0.2] = 1 segmentation = morphology.watershed(elevation_map, markers) segmentation = snd.binary_fill_holes(1-(segmentation-1)) # clean patches below theshold patches_cleaned = morphology.remove_small_objects(segmentation, patch_threshold[0])<|fim▁hole|> # reanalyse for large patches and break them by means of watershed segmentation idx=np.where(sizes>patch_threshold[1])[0]+1 labeled_patches_large=labeled_patches*0 idy=np.in1d(labeled_patches,idx).reshape(np.shape(labeled_patches)) labeled_patches_large[idy]=labeled_patches[idy] distance = snd.distance_transform_edt(labeled_patches_large) footp=int(np.round(np.sqrt(patch_threshold[1])/100)*100) local_maxi = peak_local_max(distance, indices=False, footprint=np.ones((footp, footp)),labels=labeled_patches_large) markers = snd.label(local_maxi)[0] labels_broken_large = morphology.watershed(-distance, markers, mask=labeled_patches_large) labeled_patches[idy]=labels_broken_large[idy]+np.max(labeled_patches) # measure regionproperties of biopores meas_bp=measure.regionprops(bp_label_clean, intensity_image=None) bp_labels = np.unique(bp_label_clean)[1:] bp_centroidx = bp_labels.astype(np.float64) bp_centroidy = bp_labels.astype(np.float64) bp_area = bp_labels.astype(np.float64) bp_diameter = bp_labels.astype(np.float64) # extract regionprops for each labeled biopore for i in np.arange(len(bp_labels)): bp_centroidx[i], bp_centroidy[i]=meas_bp[i]['centroid'] bp_area[i]=(meas_bp[i]['area']) bp_diameter[i]=(meas_bp[i]['equivalent_diameter'])*px bp_centroidxy = np.stack((bp_centroidx,bp_centroidy), axis=-1) # extract biopores inside stained areas = "stained biopores" stain_info=np.zeros(len(bp_centroidxy)) rbp_centroidxy=np.around(bp_centroidxy).astype(int) for i in np.arange(len(bp_centroidxy)): if labeled_patches[rbp_centroidxy[i,0],rbp_centroidxy[i,1]]>0: stain_info[i]=1 else: stain_info[i]=2 stained=np.where(stain_info==1) unstained=np.where(stain_info==2) # select value of stained patches including an biopore bp_stained=np.around(bp_centroidxy[stained]).astype(int) label_value=np.zeros(len(bp_stained)).astype(int) for i in np.arange(len(bp_stained)): label_value[i]=labeled_patches[bp_stained[i,0], bp_stained[i,1]] # remove labeled patches without any biopore label_withbp=np.copy(labeled_patches) for i in np.arange(len(label_value)): label_withbp[label_withbp==label_value[i]]=-1 label_withbp[label_withbp!=-1]=0 label_withbp[label_withbp==-1]=1 # distance calculations if testing==False: # Compute Euclidian distance for each pixel to nearest biopore m_bp_dist = np.zeros((sim[0],sim[1])) for i in np.arange(sim[0]): for j in np.arange(sim[1]): matrixp1=[i,j] m_bp_dist[i,j]=spatial.KDTree(bp_centroidxy).query(matrixp1,p=2)[0] # compute Euclidian distance for each pixel to nearest stained biopore m_stbp_dist=np.zeros((sim[0],sim[1])) for i in np.arange(sim[0]): for j in np.arange(sim[1]): matrixp1=[i,j] m_stbp_dist[i,j]=spatial.KDTree(bp_centroidxy[stained]).query(matrixp1,p=2)[0] # compute Euclidian distance to nearest stained biopore for each pixel of stained areas including a biopore ~ biopore-matrix interaction stp_stbp_dist = np.zeros((sim[0],sim[1])) for i in np.arange(sim[0]): for j in np.arange(sim[1]): if label_withbp[i,j]!=0: matrixp3=[i,j] stp_stbp_dist[i,j,]=spatial.KDTree(bp_centroidxy[stained]).query(matrixp3,p=2)[0] else: stp_stbp_dist[i,j]=np.nan # table for comparison sbp_diameter=bp_diameter[stained] t1='All','Stained' t2=len(bp_diameter),len(sbp_diameter) t3 = len(bp_diameter[bp_diameter<2]),len(sbp_diameter[sbp_diameter<2]) t4 = len(bp_diameter[bp_diameter>=6]),len(sbp_diameter[sbp_diameter>=6]) t5 =len(bp_diameter[bp_diameter>=2]),len(sbp_diameter[sbp_diameter>=2]) attr=[t1,t2,t3,np.subtract(t5,t4),t4] bp_t=Table(attr,names=('Properties','Sum','<2mm','2-6mm','>6mm'),meta=None) # plot results if plot==True: #colors for plot from matplotlib.colors import ListedColormap ghostwhite=(248/255,248/255,255/255) blue=(31/255,119/255,180/255) cmap=ListedColormap([ghostwhite, blue]) if testing==False: # flatten arrays for kernel density estimate plot m_bp_distall=np.ravel(m_bp_dist*px) m_stbp_distall=np.ravel(m_stbp_dist*px) stp_stbp_distall=np.ravel(stp_stbp_dist*px) #plot sns.set_style("white") plt.figure(figsize=(15,4)) ax1=plt.subplot(131) plt.imshow(imrgb) plt.axis('off') plt.title('Input image') plt.subplot(132,sharex=ax1, sharey=ax1) plt.imshow(labeled_patches, vmin=0, vmax=1, cmap=cmap) plt.imshow(imrgb, alpha=0.5) if morph==True: plt.imshow(bp_label_clean, vmin=0, vmax=1,cmap='binary', alpha=0.5) else: plt.scatter(bp_centroidxy[unstained][:,1],bp_centroidxy[unstained][:,0] ,color='black', s=10,label='unstained') plt.scatter(bp_centroidxy[stained][:,1], bp_centroidxy[stained][:,0] ,color='red', s=15, label='stained') plt.legend(bbox_to_anchor=[0.8,0], ncol=2) plt.axis('off') plt.title('Labeled patches & Biopores') plt.subplot(133) sns.kdeplot(m_bp_distall, cut=0, label='All pores') if len(stained[0])>0: sns.kdeplot(m_stbp_distall, cut=0, label='Stained pores' ,alpha=0.5) sns.kdeplot(stp_stbp_distall[~np.isnan(stp_stbp_distall)], cut=0, label='Biopore-matrix interaction' ,alpha=0.5) plt.title('Frequency distribution of calculated distances') plt.show() print(bp_t) else: #plot sns.set_style("white") plt.figure(figsize=(12,5)) ax1=plt.subplot(121) plt.imshow(imrgb) plt.axis('off') plt.title('Input image') plt.subplot(122, sharex=ax1, sharey=ax1) plt.imshow(labeled_patches, vmin=0, vmax=1, cmap=cmap) plt.imshow(imrgb, alpha=0.5) if morph==True: plt.imshow(bp_label_clean, vmin=0, vmax=1,cmap='binary', alpha=0.5) else: plt.scatter(bp_centroidxy[unstained][:,1],bp_centroidxy[unstained][:,0] ,color='black', s=10,label='unstained') plt.scatter(bp_centroidxy[stained][:,1], bp_centroidxy[stained][:,0] ,color='red', s=15, label='stained') plt.legend(bbox_to_anchor=[0.8,0], ncol=2) plt.axis('off') plt.title('Labeled patches & Biopores') plt.show() print(bp_t) # results for output bp_res={} bp_res['biopores'], bp_res['stained_patches'],bp_res['patches_with_biopores']=bp_label_clean, labeled_patches, label_withbp bp_res['biopores_centroidxy']=bp_centroidxy bp_res['biopores_stained_centroidxy']=bp_centroidxy[stained] bp_res['biopores_area'], bp_res['biopores_diameter']=bp_area, bp_diameter if testing==False: bp_res['distance_matrix_biopore'], bp_res['distance_matrix_stained_biopore'], bp_res['biopore_matrix_interaction']=m_bp_dist*px, m_stbp_dist*px, stp_stbp_dist*px bp_res['table']=bp_t bp_res['stained_index'], bp_res['unstained_index']=stained, unstained return bp_res<|fim▁end|>
labeled_patches = label(patches_cleaned) sizes = np.bincount(labeled_patches.ravel())[1:] #first entry (background) discarded
<|file_name|>project.py<|end_file_name|><|fim▁begin|>from corecat.constants import OBJECT_CODES, MODEL_VERSION from ._sqlalchemy import Base, CoreCatBaseMixin from ._sqlalchemy import Column, \ Integer, \ String, Text class Project(CoreCatBaseMixin, Base): """Project Model class represent for the 'projects' table which is used to store project's basic information.""" # Add the real table name here. # TODO: Add the database prefix here __tablename__ = 'project' # Column definition project_id = Column('id', Integer, primary_key=True, autoincrement=True )<|fim▁hole|> ) project_description = Column('description', Text, nullable=True ) # Relationship # TODO: Building relationship def __init__(self, project_name, created_by_user_id, **kwargs): """ Constructor of Project Model Class. :param project_name: Name of the project. :param created_by_user_id: Project is created under this user ID. :param project_description: Description of the project. """ self.set_up_basic_information( MODEL_VERSION[OBJECT_CODES['Project']], created_by_user_id ) self.project_name = project_name self.project_description = kwargs.get('project_description', None)<|fim▁end|>
project_name = Column('name', String(100), nullable=False
<|file_name|>includer.js<|end_file_name|><|fim▁begin|>const log = require('app/lib/core/log') module.exports = config => props => { const [ pluginName, pluginPath, pluginExports ] = props log.trace(`Initialzing includer: ${log.ul(pluginPath)}.`) const exports = {} exports.name = pluginExports.name || pluginName exports.options = pluginExports.options exports.setOptions = newOpts => { log.trace(`Setting options for modifier: ${log.ul(pluginPath)} ${log.hl(pluginName)}.`)<|fim▁hole|> } exports.configure = conf => new Promise(resolve => { log.trace(`Configuring includer ${log.hl(pluginName)}.`) config = conf exports.htmlCommentIncluder = pluginExports.plugin(pluginExports, config) if (!exports.htmlCommentIncluder) { const msg = `Could not configure includer: ${pluginName}.` log.error(msg) // return reject(msg) resolve(exports) } resolve(exports) }) return exports }<|fim▁end|>
exports.options = newOpts
<|file_name|>kitchen_sink.rs<|end_file_name|><|fim▁begin|>#![feature(plugin)] #![plugin(json_macros)] #[cfg(feature="with-rustc-serialize")] extern crate rustc_serialize; #[cfg(feature="with-serde")] extern crate serde_json; #[cfg(feature="with-rustc-serialize")] fn make_pretty_json(x: i32) -> String { json!({ // object literal "foo": "foooooo", // string literal keys and values "bar": [true, null, 123, 123.4], // array, boolean, null, numeric literals "quux": { // nest as deeply as you like "a": [1, 2, 3, 4], "b": { "a": null }, "c": false }, "waldo": (192 - x) // wrap in parens to splice ToJson expressions directly }).pretty().to_string() } #[cfg(feature="with-serde")] fn make_pretty_json(x: i32) -> String { serde_json::to_string_pretty(&json!({ // object literal "foo": "foooooo", // string literal keys and values "bar": [true, null, 123, 123.4], // array, boolean, null, numeric literals "quux": { // nest as deeply as you like "a": [1, 2, 3, 4], "b": { "a": null }, "c": false },<|fim▁hole|> "waldo": (192 - x) // wrap in parens to splice ToJson expressions directly })).unwrap() } pub fn main() { // See implementation for serde/rustc-serialize features above. println!("{}", make_pretty_json(1)); }<|fim▁end|>
<|file_name|>compression.go<|end_file_name|><|fim▁begin|>package compression import ( c "gopkg.in/h2non/gentleman.v2/context" p "gopkg.in/h2non/gentleman.v2/plugin" "net/http" ) // Disable disables the authorization basic header in the outgoing request func Disable() p.Plugin { return p.NewRequestPlugin(func(ctx *c.Context, h c.Handler) { // Assert http.Transport to work with the instance transport, ok := ctx.Client.Transport.(*http.Transport) if !ok { h.Next(ctx) return<|fim▁hole|> // Override the http.Client transport transport.DisableCompression = true ctx.Client.Transport = transport h.Next(ctx) }) }<|fim▁end|>
}
<|file_name|>handle.go<|end_file_name|><|fim▁begin|>package dmserver import ( "auth" "colorlog" "conf" "encoding/json" "errors" "fmt" "io/ioutil" "net" "net/http" "os" "strconv" "time" "utils" "regexp" "os/exec" ) var config conf.Cnf var serverSaved = make(map[int]*ServerLocal, 0) var servers = make(map[int]*ServerRun, 0) var requestHandlers = make(map[string]*[]func([]byte) []byte,0) func connErrorToExit(errorInfo string, c net.Conn) { res, _ := json.Marshal(Response{-1, errorInfo}) c.Write(res) c.Close() } // 保存服务器信息 func saveServerInfo() error { b, err := json.Marshal(serverSaved) if err != nil { return err } ioutil.WriteFile(config.ServerManager.Servers, b, 0664) return nil } // 处理本地命令 func handleConnection(c net.Conn) { buf := make([]byte, config.DaemonServer.DefaultBufLength) length, _ := c.Read(buf) request := InterfaceRequest{} err := json.Unmarshal(buf[:length], &request) if err != nil { connErrorToExit(err.Error(), c) } if request.Auth == config.DaemonServer.VerifyCode { res, _ := json.Marshal(handleRequest(request.Req)) c.Write(res) c.Close() } else { connErrorToExit("No command or Auth error.", c) } } // 命令处理器 func handleRequest(request Request) Response { // Received ? Who cares? colorlog.PointPrint("Received " + colorlog.ColorSprint(request.Method, colorlog.FR_GREEN) + " Command!") if functions,ok := requestHandlers[request.Method];ok { colorlog.LogPrint("Calling plugin functions") for _,function := range *functions{ resp := Response{} b,_ := json.Marshal(request) err := json.Unmarshal(function(b),&resp) if err != nil { colorlog.ErrorPrint("dmserver.handle during unmarshall json : ",err) return Response{-1,"Plugin override error."} } return resp } } switch request.Method { case "List": return outputListOfServers() case "Create": if _, ok := serverSaved[request.OperateID]; ok { return Response{-1, "Server id: " + strconv.Itoa(request.OperateID) + "has been token"} } serverSaved[request.OperateID] = &ServerLocal{ ID: request.OperateID, Name: request.Message, Executable: "", Status: 0, MaxCpuUtilizatioRate: 1, MaxMem: 1024, MaxHardDiskCapacity: 0, MaxHardDiskReadSpeed: 50, MaxHardDiskWriteSpeed: 50, MaxUnusedUpBandwidth: 100, MaxUsingUpBandwidth: 100, Expire: time.Now().Unix() + 3600, } // 序列化b来储存。 b, err := json.MarshalIndent(serverSaved, "", "\t") // 新创建的服务器写入data文件 err2 := ioutil.WriteFile(config.ServerManager.Servers, b, 0666) if err2 != nil { return Response{ -1, err2.Error(), } } if err != nil { return Response{ -1, err.Error(), } } return Response{ 0, "OK", } serverSaved[0].MaxMem = 1 case "Delete": if _, ok := serverSaved[request.OperateID]; ok { serverSaved[request.OperateID].Delete() } else { return Response{-1, "Invalid server id."} } return Response{0, "OK"} case "Start": // 运行这个服务器 if server, ok := serverSaved[request.OperateID]; ok { if server.Status != SERVER_STATUS_CLOSED { return Response{-1, "Server Running or staring"} } if server.MaxHardDiskCapacity == 0 { return Response{-1, "Please set MaxHardDiskCapacity!"} } err := server.Start() if err == nil { return Response{ 0, "OK", } } else { return Response{-1, err.Error()} } } else { return Response{-1, "Invalid server id."} } case "Stop": colorlog.LogPrint("Stop command sent.") if server, ok := servers[request.OperateID]; ok { server.Close() } else { return Response{-1, "Invalid server id"} } return Response{0, "OK"} case "ExecInstall": colorlog.LogPrint("Try to auto install " + request.Message) conn, err := http.Get( "http://vae.fg.mcpe.cc/exec?name=" + request.Message + "&arch=" + getArch()) if err != nil { return Response{-1, err.Error()} } defer conn.Body.Close() respData, err := ioutil.ReadAll(conn.Body) if err != nil { fmt.Println("Read body error") return Response{-1, err.Error()} } var resp Response err = json.Unmarshal(respData, &config) if err != nil { fmt.Println("Json Unmarshal error!") return Response{-1, err.Error()} } if resp.Status != 0 { return Response{-1, "return error:" + resp.Message} } var config ExecInstallConfig err = json.Unmarshal([]byte(resp.Message),&config) // 解析成功且没有错误 go install(config) return Response{0, "OK,installing"} case "SetServerConfig": var elements []ServerAttrElement err := json.Unmarshal([]byte(request.Message), &elements) if err != nil { return Response{-1, "Json decoding error:" + err.Error()} } nums, err2 := setServerConfigAll(elements, request.OperateID) if err2 != nil { return Response{-1, err2.Error()} } return Response{0, fmt.Sprintf("OK,Setted %d element(s)", nums)} case "InputLineToServer": // 此方法将一行指令输入至服务端 if server, ok := servers[request.OperateID]; ok { err := server.inputLine(request.Message) if err != nil { return Response{-1, err.Error()} } else { return Response{0, "Send OK"} } } else { return Response{-1, "Invalid Server id"} } case "GetServerPlayers": if server, ok := servers[request.OperateID]; ok { b, _ := json.Marshal(server.Players) return Response{-1, fmt.Sprintf("%s", b)} } else { return Response{-1, "Invalid server id"} } case "KeyRegister": auth.KeyRegister(request.Message, request.OperateID) return Response{0, "OK"} case "GetServerDir": if server, ok := serverSaved[request.OperateID]; ok { if validateOperateDir("../servers/server"+strconv.Itoa(server.ID)+"/serverData/", request.Message) { infos, err := ioutil.ReadDir("../servers/server" + strconv.Itoa(server.ID) + "/serverData/" + request.Message) if err != nil { colorlog.ErrorPrint("Server Reading dir: ID:" + strconv.Itoa(server.ID) ,err) return Response{-1, "Reading Dir :" + err.Error()} } b, _ := json.Marshal(buildServerInfos(infos)) return Response{0, string(b)} } else { return Response{-1, "Permission denied."} } } return Response{-1, "Invalid server id"} case "DeleteServerFile": if server, ok := serverSaved[request.OperateID]; ok { if validateOperateDir("../servers/server"+strconv.Itoa(server.ID)+"/serverData/", request.Message) { err := os.RemoveAll("../servers/server" + strconv.Itoa(server.ID) + "/serverData/" + request.Message) if err != nil { colorlog.ErrorPrint("Server Reading dir error: ID:" + strconv.Itoa(server.ID) ,err) return Response{-1, "Reading Dir :" + err.Error()} } return Response{0, "Deleted dir."} } else { return Response{-1, "Permission denied."} } } case "GetExecList": info,err := ioutil.ReadDir("../exec") if err != nil { colorlog.ErrorPrint("read exec path",err) return Response{-1,"Reading dir :" + err.Error()} } result := make([]string,0) for _,v := range info { s := v.Name() cstr := utils.CString(s) if !v.IsDir() && cstr.Contains(".json"){ result = append(result,regexp.MustCompile("\\.json$").ReplaceAllString(v.Name(),"")) } } lang, err := json.Marshal(result) if err == nil { return Response{0, string(lang)} }else{ fmt.Println("Json Unmarshal error!") return Response{-1, err.Error()} } } return Response{ -1, "Unexpected err", } } func setServerConfigAll(attrs []ServerAttrElement, index int) (int, error) { res := 0 // 设置该设置的Attrs if server, ok := serverSaved[index]; ok { // 判断被设置那个服务器是否存在于映射 for i := 0; i < len(attrs); i++ { colorlog.LogPrint("Attempt to set " + colorlog.ColorSprint(attrs[i].AttrName, colorlog.FR_CYAN) + "=" + colorlog.ColorSprint(attrs[i].AttrValue, colorlog.FR_GREEN) + " to server" + strconv.Itoa(index)) switch attrs[i].AttrName { case "MaxCpuRate": rate, err := strconv.Atoi(attrs[i].AttrValue) if err != nil { return -1, err } server.MaxCpuUtilizatioRate = rate case "MaxMem": mem, err := strconv.Atoi(attrs[i].AttrValue) if err != nil { return -1, err } server.MaxMem = mem case "Executable": server.Executable = attrs[i].AttrValue case "MaxHardDiskCapacity": disk, err := strconv.Atoi(attrs[i].AttrValue) if err != nil { return -1, err } server.MaxHardDiskCapacity = disk case "Name": server.Name = attrs[i].AttrValue case "Expire": expire, err := strconv.Atoi(attrs[i].AttrValue) if err != nil { return -1, err } server.Expire = server.Expire + int64(expire) - 3600 case "MaxHardDiskWriteSpeed": speed, err := strconv.Atoi(attrs[i].AttrValue) if err != nil { return -1, err } server.MaxHardDiskWriteSpeed = speed case "MaxHardDiskReadSpeed": speed, err := strconv.Atoi(attrs[i].AttrValue) if err != nil { return -1, err } server.MaxHardDiskReadSpeed = speed case "MaxUnusedUpBandwidth": width, err := strconv.Atoi(attrs[i].AttrValue) if err != nil { return -1, err } server.MaxUnusedUpBandwidth = width case "MaxUsingUpBandwidth": width, err := strconv.Atoi(attrs[i].AttrValue) if err != nil { return -1, err } server.MaxUsingUpBandwidth = width default: colorlog.WarningPrint("Attr " + colorlog.ColorSprint(attrs[i].AttrName, colorlog.FR_RED) + " not found or cannot be set.") } res++ } server.networkFlush() server.performanceFlush() return res, nil } return -1, errors.New("Err with invalid server id.") } func outputListOfServers() Response { b, _ := json.Marshal(serverSaved) return Response{0, string(b)} } func getArch() string { cmd := exec.Command("uname","-a") out,err := cmd.CombinedOutput() if err != nil { colorlog.ErrorPrint("run [uname -a]",err) utils.OutputErrReason(out) } cstr := utils.CString(string(out)) if cstr.Contains("86_64"){ return "64" } else { return "32"<|fim▁hole|><|fim▁end|>
} }
<|file_name|>monorail.py<|end_file_name|><|fim▁begin|># Copyright 2021 Google LLC # # 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. """Monorail client.""" import json from google.oauth2 import service_account from google.auth.transport import requests as google_requests import requests _API_BASE = 'https://api-dot-monorail-prod.appspot.com/prpc' _TARGET_AUDIENCE = 'https://monorail-prod.appspot.com' _XSSI_PREFIX = ')]}\'\n' class Client: """Monorail client.""" def __init__(self, project, service_account_info): self.project = project self._service_account_info = service_account_info def get_issue(self, issue_id): """Get issue data.""" credentials = service_account.IDTokenCredentials.from_service_account_info( self._service_account_info, target_audience=_TARGET_AUDIENCE) credentials.refresh(google_requests.Request()) headers = { 'Content-Type': 'application/json', 'Accept': 'application/json', } credentials.apply(headers)<|fim▁hole|> url = f'{_API_BASE}/monorail.v3.Issues/GetIssue' body = {'name': f'projects/{self.project}/issues/{issue_id}'} resp = requests.post(url, json=body, headers=headers) resp.raise_for_status() result = resp.text if result.startswith(_XSSI_PREFIX): result = result[len(_XSSI_PREFIX):] return json.loads(result)<|fim▁end|>
<|file_name|>test_decorators.py<|end_file_name|><|fim▁begin|># Copyright 2013 IBM Corp # Copyright 2015 Hewlett-Packard Development Company, L.P. # # 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. import uuid import testtools from tempest.lib import base as test from tempest.lib import decorators from tempest.tests.lib import base class TestSkipBecauseDecorator(base.TestCase): def _test_skip_because_helper(self, expected_to_skip=True, **decorator_args): class TestFoo(test.BaseTestCase): _interface = 'json' @decorators.skip_because(**decorator_args) def test_bar(self): return 0 t = TestFoo('test_bar') if expected_to_skip: self.assertRaises(testtools.TestCase.skipException, t.test_bar) else: # assert that test_bar returned 0 self.assertEqual(TestFoo('test_bar').test_bar(), 0) def test_skip_because_bug(self): self._test_skip_because_helper(bug='12345') def test_skip_because_bug_and_condition_true(self):<|fim▁hole|> bug='12349', condition=False) def test_skip_because_bug_without_bug_never_skips(self): """Never skip without a bug parameter.""" self._test_skip_because_helper(expected_to_skip=False, condition=True) self._test_skip_because_helper(expected_to_skip=False) def test_skip_because_invalid_bug_number(self): """Raise ValueError if with an invalid bug number""" self.assertRaises(ValueError, self._test_skip_because_helper, bug='critical_bug') class TestIdempotentIdDecorator(base.TestCase): def _test_helper(self, _id, **decorator_args): @decorators.idempotent_id(_id) def foo(): """Docstring""" pass return foo def _test_helper_without_doc(self, _id, **decorator_args): @decorators.idempotent_id(_id) def foo(): pass return foo def test_positive(self): _id = str(uuid.uuid4()) foo = self._test_helper(_id) self.assertIn('id-%s' % _id, getattr(foo, '__testtools_attrs')) self.assertTrue(foo.__doc__.startswith('Test idempotent id: %s' % _id)) def test_positive_without_doc(self): _id = str(uuid.uuid4()) foo = self._test_helper_without_doc(_id) self.assertTrue(foo.__doc__.startswith('Test idempotent id: %s' % _id)) def test_idempotent_id_not_str(self): _id = 42 self.assertRaises(TypeError, self._test_helper, _id) def test_idempotent_id_not_valid_uuid(self): _id = '42' self.assertRaises(ValueError, self._test_helper, _id) class TestSkipUnlessAttrDecorator(base.TestCase): def _test_skip_unless_attr(self, attr, expected_to_skip=True): class TestFoo(test.BaseTestCase): expected_attr = not expected_to_skip @decorators.skip_unless_attr(attr) def test_foo(self): pass t = TestFoo('test_foo') if expected_to_skip: self.assertRaises(testtools.TestCase.skipException, t.test_foo()) else: try: t.test_foo() except Exception: raise testtools.TestCase.failureException() def test_skip_attr_does_not_exist(self): self._test_skip_unless_attr('unexpected_attr') def test_skip_attr_false(self): self._test_skip_unless_attr('expected_attr') def test_no_skip_for_attr_exist_and_true(self): self._test_skip_unless_attr('expected_attr', expected_to_skip=False)<|fim▁end|>
self._test_skip_because_helper(bug='12348', condition=True) def test_skip_because_bug_and_condition_false(self): self._test_skip_because_helper(expected_to_skip=False,
<|file_name|>scheduler.py<|end_file_name|><|fim▁begin|># Author: Nic Wolfe <nic@wolfeden.ca> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Sick Beard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Sick Beard. If not, see <http://www.gnu.org/licenses/>. import datetime import time import threading import traceback from sickbeard import logger from sickbeard.exceptions import ex class Scheduler: def __init__(self, action, cycleTime=datetime.timedelta(minutes=10), runImmediately=True, threadName="ScheduledThread", silent=False): if runImmediately: self.lastRun = datetime.datetime.fromordinal(1) else: self.lastRun = datetime.datetime.now() self.action = action self.cycleTime = cycleTime self.thread = None self.threadName = threadName self.silent = silent self.initThread() self.abort = False def initThread(self): if self.thread == None or not self.thread.isAlive(): self.thread = threading.Thread(None, self.runAction, self.threadName)<|fim▁hole|> return self.cycleTime - (datetime.datetime.now() - self.lastRun) def forceRun(self): if not self.action.amActive: self.lastRun = datetime.datetime.fromordinal(1) return True return False def runAction(self): while True: currentTime = datetime.datetime.now() if currentTime - self.lastRun > self.cycleTime: self.lastRun = currentTime try: if not self.silent: logger.log(u"Starting new thread: "+self.threadName, logger.DEBUG) self.action.run() except Exception, e: logger.log(u"Exception generated in thread "+self.threadName+": " + ex(e), logger.ERROR) logger.log(traceback.format_exc(), logger.DEBUG) if self.abort: self.abort = False self.thread = None return time.sleep(1)<|fim▁end|>
def timeLeft(self):
<|file_name|>typescript.ts<|end_file_name|><|fim▁begin|>import * as path from 'path'; import { stripIndent } from 'common-tags'; import { AotPlugin, AotPluginOptions, AngularCompilerPlugin, AngularCompilerPluginOptions, PLATFORM } from '@ngtools/webpack'; import { WebpackConfigOptions } from '../webpack-config'; const SilentError = require('silent-error'); const g: any = global; const webpackLoader: string = g['angularCliIsLocal'] ? g.angularCliPackages['@ngtools/webpack'].main : '@ngtools/webpack'; function _createAotPlugin(wco: WebpackConfigOptions, options: any) { const { appConfig, projectRoot, buildOptions } = wco; options.compilerOptions = options.compilerOptions || {}; if (wco.buildOptions.preserveSymlinks) { options.compilerOptions.preserveSymlinks = true; } // Forcing commonjs seems to drastically improve rebuild speeds on webpack. // Dev builds on watch mode will set this option to true. if (wco.buildOptions.forceTsCommonjs) { options.compilerOptions.module = 'commonjs'; } // Read the environment, and set it in the compiler host. let hostReplacementPaths: any = {}; // process environment file replacement if (appConfig.environments) { if (!appConfig.environmentSource) { let migrationMessage = ''; if ('source' in appConfig.environments) { migrationMessage = '\n\n' + stripIndent` A new environmentSource entry replaces the previous source entry inside environments. To migrate angular-cli.json follow the example below: Before: "environments": { "source": "environments/environment.ts", "dev": "environments/environment.ts", "prod": "environments/environment.prod.ts" } After: "environmentSource": "environments/environment.ts", "environments": { "dev": "environments/environment.ts", "prod": "environments/environment.prod.ts" } `; } throw new SilentError( `Environment configuration does not contain "environmentSource" entry.${migrationMessage}` ); } if (!(buildOptions.environment in appConfig.environments)) { throw new SilentError(`Environment "${buildOptions.environment}" does not exist.`); } const appRoot = path.resolve(projectRoot, appConfig.root); const sourcePath = appConfig.environmentSource; const envFile = appConfig.environments[buildOptions.environment]; <|fim▁hole|> if (AngularCompilerPlugin.isSupported()) { const pluginOptions: AngularCompilerPluginOptions = Object.assign({}, { mainPath: path.join(projectRoot, appConfig.root, appConfig.main), i18nInFile: buildOptions.i18nFile, i18nInFormat: buildOptions.i18nFormat, i18nOutFile: buildOptions.i18nOutFile, i18nOutFormat: buildOptions.i18nOutFormat, locale: buildOptions.locale, platform: appConfig.platform === 'server' ? PLATFORM.Server : PLATFORM.Browser, missingTranslation: buildOptions.missingTranslation, hostReplacementPaths, sourceMap: buildOptions.sourcemaps, // If we don't explicitely list excludes, it will default to `['**/*.spec.ts']`. exclude: [], include: options.include, }, options); return new AngularCompilerPlugin(pluginOptions); } else { const pluginOptions: AotPluginOptions = Object.assign({}, { mainPath: path.join(projectRoot, appConfig.root, appConfig.main), i18nFile: buildOptions.i18nFile, i18nFormat: buildOptions.i18nFormat, locale: buildOptions.locale, replaceExport: appConfig.platform === 'server', missingTranslation: buildOptions.missingTranslation, hostReplacementPaths, sourceMap: buildOptions.sourcemaps, // If we don't explicitely list excludes, it will default to `['**/*.spec.ts']`. exclude: [] }, options); return new AotPlugin(pluginOptions); } } export function getNonAotConfig(wco: WebpackConfigOptions) { const { appConfig, projectRoot } = wco; const tsConfigPath = path.resolve(projectRoot, appConfig.root, appConfig.tsconfig); return { module: { rules: [{ test: /\.ts$/, loader: webpackLoader }] }, plugins: [ _createAotPlugin(wco, { tsConfigPath, skipCodeGeneration: true }) ] }; } export function getAotConfig(wco: WebpackConfigOptions) { const { projectRoot, buildOptions, appConfig } = wco; const tsConfigPath = path.resolve(projectRoot, appConfig.root, appConfig.tsconfig); const testTsConfigPath = path.resolve(projectRoot, appConfig.root, appConfig.testTsconfig); let pluginOptions: any = { tsConfigPath }; // Fallback to exclude spec files from AoT compilation on projects using a shared tsconfig. if (testTsConfigPath === tsConfigPath) { let exclude = [ '**/*.spec.ts' ]; if (appConfig.test) { exclude.push(path.join(projectRoot, appConfig.root, appConfig.test)); } pluginOptions.exclude = exclude; } let boLoader: any = []; if (buildOptions.buildOptimizer) { boLoader = [{ loader: '@angular-devkit/build-optimizer/webpack-loader', options: { sourceMap: buildOptions.sourcemaps } }]; } const test = AngularCompilerPlugin.isSupported() ? /(?:\.ngfactory\.js|\.ngstyle\.js|\.ts)$/ : /\.ts$/; return { module: { rules: [{ test, use: [...boLoader, webpackLoader] }] }, plugins: [ _createAotPlugin(wco, pluginOptions) ] }; } export function getNonAotTestConfig(wco: WebpackConfigOptions) { const { projectRoot, appConfig } = wco; const tsConfigPath = path.resolve(projectRoot, appConfig.root, appConfig.testTsconfig); const appTsConfigPath = path.resolve(projectRoot, appConfig.root, appConfig.tsconfig); // Force include main and polyfills. // This is needed for AngularCompilerPlugin compatibility with existing projects, // since TS compilation there is stricter and tsconfig.spec.ts doesn't include them. const include = [appConfig.main, appConfig.polyfills, '**/*.spec.ts']; if (appConfig.test) { include.push(appConfig.test); } let pluginOptions: any = { tsConfigPath, skipCodeGeneration: true, include }; // Fallback to correct module format on projects using a shared tsconfig. if (tsConfigPath === appTsConfigPath) { pluginOptions.compilerOptions = { module: 'commonjs' }; } return { module: { rules: [{ test: /\.ts$/, loader: webpackLoader }] }, plugins: [ _createAotPlugin(wco, pluginOptions) ] }; }<|fim▁end|>
hostReplacementPaths = { [path.resolve(appRoot, sourcePath)]: path.resolve(appRoot, envFile) }; }
<|file_name|>test_buddyns.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF 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. import sys import unittest from libcloud.test import MockHttp from libcloud.test.file_fixtures import DNSFileFixtures from libcloud.test.secrets import DNS_PARAMS_BUDDYNS from libcloud.dns.drivers.buddyns import BuddyNSDNSDriver from libcloud.utils.py3 import httplib from libcloud.dns.types import ZoneDoesNotExistError, ZoneAlreadyExistsError from libcloud.dns.base import Zone class BuddyNSDNSTests(unittest.TestCase): def setUp(self): BuddyNSMockHttp.type = None BuddyNSDNSDriver.connectionCls.conn_class = BuddyNSMockHttp self.driver = BuddyNSDNSDriver(*DNS_PARAMS_BUDDYNS) self.test_zone = Zone( id="test.com", type="master", ttl=None, domain="test.com", extra={}, driver=self, ) def test_list_zones_empty(self): BuddyNSMockHttp.type = "EMPTY_ZONES_LIST" zones = self.driver.list_zones() self.assertEqual(zones, []) def test_list_zones_success(self): BuddyNSMockHttp.type = "LIST_ZONES" zones = self.driver.list_zones() self.assertEqual(len(zones), 2) <|fim▁hole|> self.assertEqual(zone.id, "microsoft.com") self.assertIsNone(zone.type) self.assertEqual(zone.domain, "microsoft.com") self.assertIsNone(zone.ttl) zone = zones[1] self.assertEqual(zone.id, "google.de") self.assertIsNone(zone.type) self.assertEqual(zone.domain, "google.de") self.assertIsNone(zone.ttl) def test_delete_zone_zone_does_not_exist(self): BuddyNSMockHttp.type = "DELETE_ZONE_ZONE_DOES_NOT_EXIST" try: self.driver.delete_zone(zone=self.test_zone) except ZoneDoesNotExistError as e: self.assertEqual(e.zone_id, self.test_zone.id) else: self.fail("Exception was not thrown") def test_delete_zone_success(self): BuddyNSMockHttp.type = "DELETE_ZONE_SUCCESS" status = self.driver.delete_zone(zone=self.test_zone) self.assertTrue(status) def test_get_zone_zone_does_not_exist(self): BuddyNSMockHttp.type = "GET_ZONE_ZONE_DOES_NOT_EXIST" try: self.driver.get_zone(zone_id="zonedoesnotexist.com") except ZoneDoesNotExistError as e: self.assertEqual(e.zone_id, "zonedoesnotexist.com") else: self.fail("Exception was not thrown") def test_get_zone_success(self): BuddyNSMockHttp.type = "GET_ZONE_SUCCESS" zone = self.driver.get_zone(zone_id="myexample.com") self.assertEqual(zone.id, "myexample.com") self.assertEqual(zone.domain, "myexample.com") self.assertIsNone(zone.type) self.assertIsNone(zone.ttl) self.assertEqual(zone.driver, self.driver) def test_create_zone_success(self): BuddyNSMockHttp.type = "CREATE_ZONE_SUCCESS" zone = self.driver.create_zone(domain="microsoft.com") self.assertEqual(zone.id, "microsoft.com") self.assertEqual(zone.domain, "microsoft.com") self.assertIsNone(zone.type), self.assertIsNone(zone.ttl) def test_create_zone_zone_already_exists(self): BuddyNSMockHttp.type = "CREATE_ZONE_ZONE_ALREADY_EXISTS" try: self.driver.create_zone(domain="newzone.com", extra={"master": "13.0.0.1"}) except ZoneAlreadyExistsError as e: self.assertEqual(e.zone_id, "newzone.com") else: self.fail("Exception was not thrown") class BuddyNSMockHttp(MockHttp): fixtures = DNSFileFixtures("buddyns") def _api_v2_zone_EMPTY_ZONES_LIST(self, method, url, body, headers): body = self.fixtures.load("empty_zones_list.json") return httplib.OK, body, {}, httplib.responses[httplib.OK] def _api_v2_zone_LIST_ZONES(self, method, url, body, headers): body = self.fixtures.load("list_zones.json") return httplib.OK, body, {}, httplib.responses[httplib.OK] def _api_v2_zone_zonedoesnotexist_com_GET_ZONE_ZONE_DOES_NOT_EXIST( self, method, url, body, headers ): body = self.fixtures.load("zone_does_not_exist.json") return 404, body, {}, httplib.responses[httplib.OK] def _api_v2_zone_myexample_com_GET_ZONE_SUCCESS(self, method, url, body, headers): body = self.fixtures.load("get_zone_success.json") return httplib.OK, body, {}, httplib.responses[httplib.OK] def _api_v2_zone_test_com_DELETE_ZONE_SUCCESS(self, method, url, body, headers): body = self.fixtures.load("delete_zone_success.json") return httplib.OK, body, {}, httplib.responses[httplib.OK] def _api_v2_zone_test_com_DELETE_ZONE_ZONE_DOES_NOT_EXIST( self, method, url, body, headers ): body = self.fixtures.load("zone_does_not_exist.json") return httplib.OK, body, {}, httplib.responses[httplib.OK] def _api_v2_zone_CREATE_ZONE_SUCCESS(self, method, url, body, headers): body = self.fixtures.load("create_zone_success.json") return httplib.OK, body, {}, httplib.responses[httplib.OK] def _api_v2_zone_CREATE_ZONE_ZONE_ALREADY_EXISTS(self, method, url, body, headers): body = self.fixtures.load("zone_already_exists.json") return httplib.OK, body, {}, httplib.responses[httplib.OK] if __name__ == "__main__": sys.exit(unittest.main())<|fim▁end|>
zone = zones[0]
<|file_name|>upgrade_test.go<|end_file_name|><|fim▁begin|>/* Copyright 2019 The Skaffold 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 v1alpha4 import ( "testing" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/v1alpha5" "github.com/GoogleContainerTools/skaffold/pkg/skaffold/yaml" "github.com/GoogleContainerTools/skaffold/testutil" ) func TestUpgrade(t *testing.T) { yaml := `apiVersion: skaffold/v1alpha4 kind: Config build: artifacts: - image: gcr.io/k8s-skaffold/skaffold-example test: - image: gcr.io/k8s-skaffold/skaffold-example structureTests: - ./test/* deploy: kubectl: manifests: - k8s-* profiles: - name: test profile build: artifacts: - image: gcr.io/k8s-skaffold/skaffold-example test: - image: gcr.io/k8s-skaffold/skaffold-example structureTests: - ./test/* deploy: kubectl: manifests: - k8s-* ` expected := `apiVersion: skaffold/v1alpha5 kind: Config build: artifacts: - image: gcr.io/k8s-skaffold/skaffold-example test: - image: gcr.io/k8s-skaffold/skaffold-example structureTests: - ./test/* deploy: kubectl: manifests: - k8s-* profiles: - name: test profile build: artifacts: - image: gcr.io/k8s-skaffold/skaffold-example test: - image: gcr.io/k8s-skaffold/skaffold-example structureTests: - ./test/* deploy: kubectl: manifests: - k8s-* ` verifyUpgrade(t, yaml, expected) } func verifyUpgrade(t *testing.T, input, output string) { config := NewSkaffoldConfig() err := yaml.UnmarshalStrict([]byte(input), config) testutil.CheckErrorAndDeepEqual(t, false, err, Version, config.GetVersion()) upgraded, err := config.Upgrade() testutil.CheckError(t, false, err) <|fim▁hole|> expected := v1alpha5.NewSkaffoldConfig() err = yaml.UnmarshalStrict([]byte(output), expected) testutil.CheckErrorAndDeepEqual(t, false, err, expected, upgraded) }<|fim▁end|>
<|file_name|>BbCodeAwareSizeValidator.java<|end_file_name|><|fim▁begin|>/** * Copyright (C) 2011 JTalks.org Team * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jtalks.jcommune.plugin.api.web.validation.validators; import org.jtalks.jcommune.plugin.api.service.PluginBbCodeService; import org.jtalks.jcommune.plugin.api.web.validation.annotations.BbCodeAwareSize; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; /** * Extends default @Size annotation to ignore BB codes in string. * As for now, applicable to string values only. * * @author Evgeniy Naumenko */ public class BbCodeAwareSizeValidator implements ConstraintValidator<BbCodeAwareSize, String>, ApplicationContextAware { public static final String NEW_LINE_HTML = "<br/>"; public static final String QUOTE_HTML = "&quot"; public static final String EMPTY_LIST_BB_REGEXP = "\\[list\\][\n\r\\s]*(\\[\\*\\][\n\r\\s]*)*\\[\\/list\\]"; private int min; private int max; private ApplicationContext context; private PluginBbCodeService bbCodeService; @Autowired public BbCodeAwareSizeValidator(PluginBbCodeService bbCodeService) { this.bbCodeService = bbCodeService; } /** * {@inheritDoc} */ @Override public void initialize(BbCodeAwareSize constraintAnnotation) { this.min = constraintAnnotation.min(); this.max = constraintAnnotation.max(); } /** * The database stores both bb codes and symbols visible for users. * Post length with bb codes can't be greater than max value. * {@inheritDoc} */ @Override public boolean isValid(String value, ConstraintValidatorContext context) { if (value != null) { String emptyListRemoved = removeEmptyListBb(value); String trimed = removeBBCodes(emptyListRemoved).trim(); int plainTextLength = getDisplayedLength(trimed); return plainTextLength >= min && value.length() <= max; } return false; } <|fim▁hole|> * @param source text to cleanup * @return plain text without BB tags */ private String removeBBCodes(String source) { return getBBCodeService().stripBBCodes(source); } @Override public void setApplicationContext(ApplicationContext ac) throws BeansException { this.context = ac; } private PluginBbCodeService getBBCodeService() { if (bbCodeService == null) { bbCodeService = this.context.getBean(PluginBbCodeService.class); } return bbCodeService; } /** * Calculate length of string which be displayed. * Needed because method <b>removeBBCodes</b> leaves "&quot" and "<br/>" symbols. * @param s String to calculate length. * @return Length of string which be displayed. */ private int getDisplayedLength(String s) { return s.replaceAll(QUOTE_HTML, "\"").replaceAll(NEW_LINE_HTML, "\n\r").length(); } /** * Removes all empty lists from text. Needed because <b>removeBBCodes</b> deletes * bb codes for list but not deletes bb codes for list elements. * @param text Text to remove empty lists. * @return Text without empty lists. */ private String removeEmptyListBb(String text) { return text.replaceAll(EMPTY_LIST_BB_REGEXP, ""); } }<|fim▁end|>
/** * Removes all BB codes from the text given, simply cutting * out all [...]-style tags found *
<|file_name|>CALC.H<|end_file_name|><|fim▁begin|>///////////////////////////////////////////////////////////////////// // Quantum Calculator example (C++ version) // Copyright (c) 2002 Miro Samek, Palo Alto, CA. // All Rights Reserved. ///////////////////////////////////////////////////////////////////// #ifndef calc_h <|fim▁hole|> #include <windows.h> #include "qf_win32.h" struct CalcEvt : public QEvent { int keyId; // ID of the key depressed }; class Calc : public QHsm { // calculator state machine public: Calc() : QHsm((QPseudoState)initial) {} static Calc *instance(); // Singleton accessor method private: void initial(QEvent const *e); QSTATE calc(QEvent const *e); QSTATE ready(QEvent const *e); QSTATE result(QEvent const *e); QSTATE begin(QEvent const *e); QSTATE negated1(QEvent const *e); QSTATE operand1(QEvent const *e); QSTATE zero1(QEvent const *e); QSTATE int1(QEvent const *e); QSTATE frac1(QEvent const *e); QSTATE opEntered(QEvent const *e); QSTATE negated2(QEvent const *e); QSTATE operand2(QEvent const *e); QSTATE zero2(QEvent const *e); QSTATE int2(QEvent const *e); QSTATE frac2(QEvent const *e); QSTATE final(QEvent const *e); // helper methods... void clear(); void insert(int keyId); void negate(); void eval(); void dispState(char const *s); private: HWND myHwnd; // the calculator window handle BOOL isHandled; char myDisplay[40]; char *myIns; double myOperand1; double myOperand2; int myOperator; friend BOOL CALLBACK calcDlg(HWND hwnd, UINT iEvt, WPARAM wParam, LPARAM lParam); }; #endif // calc_h<|fim▁end|>
#define calc_h
<|file_name|>inst_float.rs<|end_file_name|><|fim▁begin|>// run-pass<|fim▁hole|><|fim▁end|>
pub type T = float;
<|file_name|>behaviors.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python from __future__ import print_function import sys import re from utils import CDNEngine from utils import request if sys.version_info >= (3, 0): import subprocess as commands import urllib.parse as urlparse else: import commands import urlparse def detect(hostname): """ Performs CDN detection thanks to information disclosure from server error. Parameters ---------- hostname : str Hostname to assess """ print('[+] Error server detection\n') hostname = urlparse.urlparse(hostname).netloc regexp = re.compile('\\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\\b') out = commands.getoutput("host " + hostname) addresses = regexp.finditer(out) <|fim▁hole|><|fim▁end|>
for addr in addresses: res = request.do('http://' + addr.group()) if res is not None and res.status_code == 500: CDNEngine.find(res.text.lower())
<|file_name|>CylinderShape.hpp<|end_file_name|><|fim▁begin|>/* * Copyright (c) 2011-2022, The DART development contributors * All rights reserved. * * The list of contributors can be found at: * https://github.com/dartsim/dart/blob/master/LICENSE * * This file is provided under the following "BSD-style" License: * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met:<|fim▁hole|> * * 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. * 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. */ #ifndef DART_DYNAMICS_CYLINDERSHAPE_HPP_ #define DART_DYNAMICS_CYLINDERSHAPE_HPP_ #include "dart/dynamics/Shape.hpp" namespace dart { namespace dynamics { class CylinderShape : public Shape { public: /// \brief Constructor. CylinderShape(double _radius, double _height); // Documentation inherited. const std::string& getType() const override; /// Returns shape type for this class static const std::string& getStaticType(); /// \brief double getRadius() const; /// \brief void setRadius(double _radius); /// \brief double getHeight() const; /// \brief void setHeight(double _height); /// \brief Compute volume from given properties static double computeVolume(double radius, double height); /// \brief Compute moments of inertia of a cylinder static Eigen::Matrix3d computeInertia( double radius, double height, double mass); // Documentation inherited. Eigen::Matrix3d computeInertia(double mass) const override; // Documentation inherited. ShapePtr clone() const override; protected: // Documentation inherited. void updateBoundingBox() const override; // Documentation inherited. void updateVolume() const override; private: /// \brief double mRadius; /// \brief Height along z-axis. double mHeight; }; } // namespace dynamics } // namespace dart #endif // DART_DYNAMICS_CYLINDERSHAPE_HPP_<|fim▁end|>
* * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer.
<|file_name|>party.component.ts<|end_file_name|><|fim▁begin|>import { Component } from '@angular/core'; import { ColyseusGameService } from '../colyseus.game.service'; import { startCase } from 'lodash'; import { LocalStorage } from 'ngx-webstorage'; @Component({ selector: 'app-party',<|fim▁hole|>}) export class PartyComponent { @LocalStorage() public partyName: string; public partyPass: string; get party() { if(!this.colyseusGame.character) return null; return (<any>this.colyseusGame.character)._party; } get partyExp() { if(!this.colyseusGame.character) return null; return (<any>this.colyseusGame.character).partyExp; } get partyPointProgressPercent() { if(!this.partyExp) return 0; return (this.partyExp.__current / this.partyExp.maximum * 100).toFixed(2); } get partyExpString() { if(!this.partyExp) return '0 / 0'; return `${this.partyExp.__current} / ${this.partyExp.maximum}`; } constructor( public colyseusGame: ColyseusGameService ) { } locationFor(character) { if(character.username === this.colyseusGame.character.username) return '✧'; if(character.map !== this.colyseusGame.character.map) { return startCase(character.map).split('Dungeon').join('(Dungeon)'); } if(character.z > this.colyseusGame.character.z) return 'Above'; if(character.z < this.colyseusGame.character.z) return 'Below'; const dir = this.colyseusGame.directionTo(character); const distance = this.colyseusGame.distanceTo(character); if(distance === 0) return '✧'; return `${distance} ${dir}`; } create() { this.colyseusGame.sendCommandString(`party create ${this.partyName}`); } join() { this.colyseusGame.sendCommandString(`party join ${this.partyName}`); } leave() { this.colyseusGame.sendCommandString('party leave'); this.partyPass = ''; } kick() { this.colyseusGame.sendCommandString(`party kick ${this.partyPass}`); this.partyPass = ''; } passLeader() { this.colyseusGame.sendCommandString(`party give ${this.partyPass}`); this.partyPass = ''; } }<|fim▁end|>
templateUrl: './party.component.html', styleUrls: ['./party.component.scss']
<|file_name|>refresh.py<|end_file_name|><|fim▁begin|># coding=utf-8 from ..packet import Packet from ..proto import Proto from ..flags import Flags <|fim▁hole|>class Refresh(Packet): __slots__ = ('flags', ) + Packet.__slots__ def __init__(self): super(Refresh, self).__init__() self.flags = 0x00 def getPayload(self): payload = bytearray() payload.extend(Proto.build_byte(Flags.COM_REFRESH)) payload.extend(Proto.build_fixed_int(1, self.flags)) return payload @staticmethod def loadFromPacket(packet): obj = Refresh() proto = Proto(packet, 3) obj.sequenceId = proto.get_fixed_int(1) proto.get_filler(1) obj.flags = proto.get_fixed_int(1) return obj<|fim▁end|>
<|file_name|>ActiveDictionarySelector.js<|end_file_name|><|fim▁begin|>import React, { Component } from 'react' import { Button, Dropdown, Icon, Image, Form, Modal, Segment } from 'semantic-ui-react' import tr from '../app/utils/Translation'; const verticallyCenteredTextStyle = { display: 'inline-flex', alignItems: 'center' } const verticallyCenteredContainerStyle = { display: 'flex', justifyContent: 'space-between' } class ActiveDictionarySelector extends Component { static propTypes = { dictionaries: React.PropTypes.array.isRequired, activeDictionaryIds: React.PropTypes.array.isRequired,<|fim▁hole|> render() { if (!this.props.dictionaries.length) { return ( // <main className="ui container"> <Segment> <Segment basic style={verticallyCenteredContainerStyle}> <span style={verticallyCenteredTextStyle}>{tr('You have no dictionaries')}</span> <Button content={tr('Add a dictionary')} icon='plus' floated='right' /> </Segment> </Segment> // </main> ); } return ( // <main className="ui container"> <Segment> <Form> <Form.Select label={tr('Active Dictionaries')} name='activeDictionaries' options={this.props.dictionaries} fluid multiple search selection /> <Button content={tr('Clear All')} icon='trash'/> <Button content={tr('Select All')} icon='checkmark'/> </Form> </Segment> // </main> ) } } export default ActiveDictionarySelector;<|fim▁end|>
onActiveDictionariesChanged: React.PropTypes.func };
<|file_name|>Singleton.java<|end_file_name|><|fim▁begin|>package com.javarush.test.level14.lesson08.bonus03; /** * Created by Алексей on 12.04.2014. */ public class Singleton { private static Singleton instance; private Singleton() {<|fim▁hole|> if ( instance == null ) { instance = new Singleton(); } return instance; } }<|fim▁end|>
} public static Singleton getInstance() {
<|file_name|>climate.py<|end_file_name|><|fim▁begin|>"""Plugwise Climate component for Home Assistant.""" import logging from Plugwise_Smile.Smile import Smile from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( CURRENT_HVAC_COOL, CURRENT_HVAC_HEAT, CURRENT_HVAC_IDLE, HVAC_MODE_AUTO, HVAC_MODE_HEAT, HVAC_MODE_HEAT_COOL, SUPPORT_PRESET_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ATTR_TEMPERATURE, TEMP_CELSIUS from homeassistant.core import callback from . import SmileGateway from .const import DEFAULT_MAX_TEMP, DEFAULT_MIN_TEMP, DOMAIN, SCHEDULE_OFF, SCHEDULE_ON HVAC_MODES_HEAT_ONLY = [HVAC_MODE_HEAT, HVAC_MODE_AUTO] HVAC_MODES_HEAT_COOL = [HVAC_MODE_HEAT_COOL, HVAC_MODE_AUTO] SUPPORT_FLAGS = SUPPORT_TARGET_TEMPERATURE | SUPPORT_PRESET_MODE _LOGGER = logging.getLogger(__name__) async def async_setup_entry(hass, config_entry, async_add_entities): """Set up the Smile Thermostats from a config entry.""" api = hass.data[DOMAIN][config_entry.entry_id]["api"] coordinator = hass.data[DOMAIN][config_entry.entry_id]["coordinator"] entities = [] thermostat_classes = [ "thermostat", "zone_thermostat", "thermostatic_radiator_valve", ] all_devices = api.get_all_devices() for dev_id, device_properties in all_devices.items(): if device_properties["class"] not in thermostat_classes: continue thermostat = PwThermostat( api, coordinator, device_properties["name"], dev_id, device_properties["location"], device_properties["class"], DEFAULT_MIN_TEMP, DEFAULT_MAX_TEMP, ) entities.append(thermostat) async_add_entities(entities, True) class PwThermostat(SmileGateway, ClimateEntity): """Representation of an Plugwise thermostat.""" def __init__( self, api, coordinator, name, dev_id, loc_id, model, min_temp, max_temp ): """Set up the Plugwise API.""" super().__init__(api, coordinator, name, dev_id) self._api = api self._loc_id = loc_id self._model = model self._min_temp = min_temp self._max_temp = max_temp self._selected_schema = None self._last_active_schema = None self._preset_mode = None self._presets = None self._presets_list = None self._heating_state = None self._cooling_state = None self._compressor_state = None self._dhw_state = None self._hvac_mode = None self._schema_names = None self._schema_status = None self._temperature = None self._setpoint = None self._water_pressure = None self._schedule_temp = None self._hvac_mode = None self._single_thermostat = self._api.single_master_thermostat() self._unique_id = f"{dev_id}-climate" @property def hvac_action(self): """Return the current action.""" if self._single_thermostat: if self._heating_state: return CURRENT_HVAC_HEAT if self._cooling_state: return CURRENT_HVAC_COOL return CURRENT_HVAC_IDLE if self._heating_state is not None: if self._setpoint > self._temperature: return CURRENT_HVAC_HEAT return CURRENT_HVAC_IDLE @property def supported_features(self): """Return the list of supported features.""" return SUPPORT_FLAGS @property def device_state_attributes(self): """Return the device specific state attributes.""" attributes = {} if self._schema_names: attributes["available_schemas"] = self._schema_names if self._selected_schema: attributes["selected_schema"] = self._selected_schema return attributes @property def preset_modes(self): """Return the available preset modes list.""" return self._presets_list @property def hvac_modes(self): """Return the available hvac modes list.""" if self._heating_state is not None: if self._compressor_state is not None: return HVAC_MODES_HEAT_COOL return HVAC_MODES_HEAT_ONLY @property def hvac_mode(self): """Return current active hvac state.""" return self._hvac_mode @property def target_temperature(self): """Return the target_temperature.""" return self._setpoint @property def preset_mode(self): """Return the active preset.""" if self._presets: return self._preset_mode return None @property def current_temperature(self): """Return the current room temperature.""" return self._temperature @property def min_temp(self): """Return the minimal temperature possible to set.""" return self._min_temp @property def max_temp(self): """Return the maximum temperature possible to set.""" return self._max_temp @property def temperature_unit(self): """Return the unit of measured temperature.""" return TEMP_CELSIUS async def async_set_temperature(self, **kwargs): """Set new target temperature.""" temperature = kwargs.get(ATTR_TEMPERATURE) if (temperature is not None) and ( self._min_temp < temperature < self._max_temp ): try: await self._api.set_temperature(self._loc_id, temperature) self._setpoint = temperature self.async_write_ha_state() except Smile.PlugwiseError: _LOGGER.error("Error while communicating to device") else: _LOGGER.error("Invalid temperature requested") async def async_set_hvac_mode(self, hvac_mode): """Set the hvac mode.""" state = SCHEDULE_OFF if hvac_mode == HVAC_MODE_AUTO: state = SCHEDULE_ON try: await self._api.set_temperature(self._loc_id, self._schedule_temp) self._setpoint = self._schedule_temp except Smile.PlugwiseError: _LOGGER.error("Error while communicating to device") try: await self._api.set_schedule_state( self._loc_id, self._last_active_schema, state ) self._hvac_mode = hvac_mode self.async_write_ha_state() except Smile.PlugwiseError:<|fim▁hole|> async def async_set_preset_mode(self, preset_mode): """Set the preset mode.""" try: await self._api.set_preset(self._loc_id, preset_mode) self._preset_mode = preset_mode self._setpoint = self._presets.get(self._preset_mode, "none")[0] self.async_write_ha_state() except Smile.PlugwiseError: _LOGGER.error("Error while communicating to device") @callback def _async_process_data(self): """Update the data for this climate device.""" climate_data = self._api.get_device_data(self._dev_id) heater_central_data = self._api.get_device_data(self._api.heater_id) if "setpoint" in climate_data: self._setpoint = climate_data["setpoint"] if "temperature" in climate_data: self._temperature = climate_data["temperature"] if "schedule_temperature" in climate_data: self._schedule_temp = climate_data["schedule_temperature"] if "available_schedules" in climate_data: self._schema_names = climate_data["available_schedules"] if "selected_schedule" in climate_data: self._selected_schema = climate_data["selected_schedule"] self._schema_status = False if self._selected_schema is not None: self._schema_status = True if "last_used" in climate_data: self._last_active_schema = climate_data["last_used"] if "presets" in climate_data: self._presets = climate_data["presets"] if self._presets: self._presets_list = list(self._presets) if "active_preset" in climate_data: self._preset_mode = climate_data["active_preset"] if heater_central_data.get("heating_state") is not None: self._heating_state = heater_central_data["heating_state"] if heater_central_data.get("cooling_state") is not None: self._cooling_state = heater_central_data["cooling_state"] if heater_central_data.get("compressor_state") is not None: self._compressor_state = heater_central_data["compressor_state"] if self._schema_status: self._hvac_mode = HVAC_MODE_AUTO elif self._heating_state is not None: self._hvac_mode = HVAC_MODE_HEAT if self._compressor_state is not None: self._hvac_mode = HVAC_MODE_HEAT_COOL self.async_write_ha_state()<|fim▁end|>
_LOGGER.error("Error while communicating to device")
<|file_name|>issue-4252.rs<|end_file_name|><|fim▁begin|>// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. trait X { fn call<T: std::fmt::Debug>(&self, x: &T); fn default_method<T: std::fmt::Debug>(&self, x: &T) { println!("X::default_method {:?}", x);<|fim▁hole|> #[derive(Debug)] struct Y(isize); #[derive(Debug)] struct Z<T: X+std::fmt::Debug> { x: T } impl X for Y { fn call<T: std::fmt::Debug>(&self, x: &T) { println!("X::call {:?} {:?}", self, x); } } impl<T: X + std::fmt::Debug> Drop for Z<T> { fn drop(&mut self) { // These statements used to cause an ICE. self.x.call(self); self.x.default_method(self); } } pub fn main() { let _z = Z {x: Y(42)}; }<|fim▁end|>
} }
<|file_name|>application.js<|end_file_name|><|fim▁begin|>console.log('Hello!'); <|fim▁hole|> $('#temperature_display').css('color', thermostat.colour); }; $(document).ready(function() { updateTemperature(); $('#increase-button').on('click', function() { thermostat.increaseTemp(); updateTemperature(); }); $('#decrease-button').on('click', function() { thermostat.decreaseTemp(); updateTemperature(); }); $('#reset-button').on('click', function() { thermostat.reset(); updateTemperature(); }); $('#power-saving-mode').on('change', function() { if (this.checked) { thermostat.powerSavingOn(); } else { thermostat.powerSavingOff(); } updateTemperature(); }); $('#weather-status-form').submit(function(event){ event.preventDefault(); captureCity = $('#weather-city').val(); console.log(captureCity); processForm(); updateTemperature(); }); }); function processForm() { $.ajax({ url: 'http://api.openweathermap.org/data/2.5/weather?q=' + captureCity, jsonp: 'callback', dataType: 'jsonp', cache: false, data: { q: $('#weather-city').val(), }, success: function (response) { $('#current-city').text(response.name); $('#weather-description').text(response.weather[0].description); $('#weather-temp').text((response.main.temp -273.15).toFixed(1)); $('#weather-wind').text(response.wind.speed); }, }); }<|fim▁end|>
var thermostat = new Thermostat(); var updateTemperature = function() { $('#temperature_display').text(thermostat.temperature);
<|file_name|>DummyAnimInstance.cpp<|end_file_name|><|fim▁begin|><|fim▁hole|>//----------------------------------------------------------------------------- // Class: DummyAnimInstance // Authors: Li, Xizhi // Emails: LiXizhi@yeah.net // Company: ParaEngine // Date: 2014.9.21 //----------------------------------------------------------------------------- #include "ParaEngine.h" #include "ParaXModel/AnimTable.h" #include "DummyAnimInstance.h" /** @def default walking speed when no model is found. */ #define DEFAULT_WALK_SPEED 4.f using namespace ParaEngine; ParaEngine::CDummyAnimInstance::CDummyAnimInstance() { // since it is a singleton, we will never reference count it. addref(); } CDummyAnimInstance* ParaEngine::CDummyAnimInstance::GetInstance() { static CDummyAnimInstance s_instance; return &s_instance; } void ParaEngine::CDummyAnimInstance::LoadAnimation(int nAnimID, float * fSpeed, bool bAppend /*= false*/) { if (fSpeed) { if (nAnimID == ANIM_STAND) *fSpeed = 0.f; else if (nAnimID == ANIM_WALK) *fSpeed = DEFAULT_WALK_SPEED; else if (nAnimID == ANIM_RUN) *fSpeed = DEFAULT_WALK_SPEED*1.5f; else if (nAnimID == ANIM_FLY) *fSpeed = DEFAULT_WALK_SPEED*2.f; else *fSpeed = 0.f; } } bool ParaEngine::CDummyAnimInstance::HasAnimId(int nAnimID) { return (nAnimID == ANIM_STAND || nAnimID == ANIM_WALK || nAnimID == ANIM_RUN || nAnimID == ANIM_FLY); } void ParaEngine::CDummyAnimInstance::GetSpeedOf(const char * sName, float * fSpeed) { int nAnimID = CAnimTable::GetAnimIDByName(sName); if (fSpeed) { if (nAnimID == ANIM_STAND) *fSpeed = 0.f; else if (nAnimID == ANIM_WALK) *fSpeed = DEFAULT_WALK_SPEED; else if (nAnimID == ANIM_RUN) *fSpeed = DEFAULT_WALK_SPEED*1.5f; else if (nAnimID == ANIM_FLY) *fSpeed = DEFAULT_WALK_SPEED*2.f; else *fSpeed = 0.f; } }<|fim▁end|>
<|file_name|>after.ts<|end_file_name|><|fim▁begin|>import { Rowan, Next, Processor } from "./rowan"; /** <|fim▁hole|> */ export class After<Ctx = any> extends Rowan<Ctx>{ process(ctx: Ctx, next: Next) { return next().then(_ => super.process(ctx, function () { return Promise.resolve() })) } }<|fim▁end|>
* executes its middleware after next has returned.
<|file_name|>adobetv.py<|end_file_name|><|fim▁begin|>from __future__ import unicode_literals from .common import InfoExtractor from ..utils import ( parse_duration, unified_strdate, str_to_int, float_or_none, ISO639Utils, ) class AdobeTVIE(InfoExtractor): _VALID_URL = r'https?://tv\.adobe\.com/watch/[^/]+/(?P<id>[^/]+)' _TEST = { 'url': 'http://tv.adobe.com/watch/the-complete-picture-with-julieanne-kost/quick-tip-how-to-draw-a-circle-around-an-object-in-photoshop/', 'md5': '9bc5727bcdd55251f35ad311ca74fa1e', 'info_dict': { 'id': 'quick-tip-how-to-draw-a-circle-around-an-object-in-photoshop', 'ext': 'mp4', 'title': 'Quick Tip - How to Draw a Circle Around an Object in Photoshop', 'description': 'md5:99ec318dc909d7ba2a1f2b038f7d2311', 'thumbnail': 're:https?://.*\.jpg$', 'upload_date': '20110914', 'duration': 60, 'view_count': int, }, } def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage(url, video_id) player = self._parse_json( self._search_regex(r'html5player:\s*({.+?})\s*\n', webpage, 'player'), video_id) title = player.get('title') or self._search_regex( r'data-title="([^"]+)"', webpage, 'title') description = self._og_search_description(webpage) thumbnail = self._og_search_thumbnail(webpage) upload_date = unified_strdate( self._html_search_meta('datepublished', webpage, 'upload date')) duration = parse_duration( self._html_search_meta('duration', webpage, 'duration') or self._search_regex( r'Runtime:\s*(\d{2}:\d{2}:\d{2})', webpage, 'duration', fatal=False)) view_count = str_to_int(self._search_regex( r'<div class="views">\s*Views?:\s*([\d,.]+)\s*</div>', webpage, 'view count')) formats = [{ 'url': source['src'], 'format_id': source.get('quality') or source['src'].split('-')[-1].split('.')[0] or None, 'tbr': source.get('bitrate'), } for source in player['sources']] self._sort_formats(formats) return { 'id': video_id, 'title': title, 'description': description, 'thumbnail': thumbnail, 'upload_date': upload_date, 'duration': duration, 'view_count': view_count, 'formats': formats, } class AdobeTVVideoIE(InfoExtractor): _VALID_URL = r'https?://video\.tv\.adobe\.com/v/(?P<id>\d+)' _TEST = { # From https://helpx.adobe.com/acrobat/how-to/new-experience-acrobat-dc.html?set=acrobat--get-started--essential-beginners 'url': 'https://video.tv.adobe.com/v/2456/', 'md5': '43662b577c018ad707a63766462b1e87', 'info_dict': { 'id': '2456', 'ext': 'mp4', 'title': 'New experience with Acrobat DC', 'description': 'New experience with Acrobat DC', 'duration': 248.667, }, } def _real_extract(self, url): video_id = self._match_id(url) webpage = self._download_webpage(url, video_id) player_params = self._parse_json(self._search_regex( r'var\s+bridge\s*=\s*([^;]+);', webpage, 'player parameters'), video_id) formats = [{ 'url': source['src'], 'width': source.get('width'), 'height': source.get('height'), 'tbr': source.get('bitrate'), } for source in player_params['sources']] # For both metadata and downloaded files the duration varies among # formats. I just pick the max one duration = max(filter(None, [ float_or_none(source.get('duration'), scale=1000) for source in player_params['sources']])) subtitles = {} for translation in player_params.get('translations', []): lang_id = translation.get('language_w3c') or ISO639Utils.long2short(translation['language_medium']) if lang_id not in subtitles: subtitles[lang_id] = [] subtitles[lang_id].append({ 'url': translation['vttPath'], 'ext': 'vtt', }) return {<|fim▁hole|> 'description': self._og_search_description(webpage), 'duration': duration, 'subtitles': subtitles, }<|fim▁end|>
'id': video_id, 'formats': formats, 'title': player_params['title'],
<|file_name|>Coordinate.java<|end_file_name|><|fim▁begin|><|fim▁hole|> * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Apache License v2.0 which accompanies this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * * The Apache License v2.0 is available at * http://www.opensource.org/licenses/apache2.0.php * * You may elect to redistribute this code under either of these licenses. */ package io.vertx.ext.consul; import io.vertx.codegen.annotations.DataObject; import io.vertx.core.json.JsonObject; import java.util.List; /** * Holds network coordinates of node * * @author <a href="mailto:ruslan.sennov@gmail.com">Ruslan Sennov</a> * @see <a href="https://www.consul.io/docs/internals/coordinates.html">Network coordinates</a> */ @DataObject(generateConverter = true) public class Coordinate { private String node; private float adj; private float err; private float height; private List<Float> vec; /** * Default constructor */ public Coordinate() {} /** * Copy constructor * * @param coordinate the one to copy */ public Coordinate(Coordinate coordinate) { this.node = coordinate.node; this.adj = coordinate.adj; this.err = coordinate.err; this.height = coordinate.height; this.vec = coordinate.vec; } /** * Constructor from JSON * * @param coordinate the JSON */ public Coordinate(JsonObject coordinate) { CoordinateConverter.fromJson(coordinate, this); } /** * Convert to JSON * * @return the JSON */ public JsonObject toJson() { JsonObject jsonObject = new JsonObject(); CoordinateConverter.toJson(this, jsonObject); return jsonObject; } /** * Get name of node * * @return name of node */ public String getNode() { return node; } /** * Get adjustment * * @return adjustment */ public float getAdj() { return adj; } /** * Get error * * @return error */ public float getErr() { return err; } /** * Get height * * @return height */ public float getHeight() { return height; } /** * Get vector * * @return vector */ public List<Float> getVec() { return vec; } /** * Set name of node * * @param node name of node * @return reference to this, for fluency */ public Coordinate setNode(String node) { this.node = node; return this; } /** * Set adjustment * * @param adj adjustment * @return reference to this, for fluency */ public Coordinate setAdj(float adj) { this.adj = adj; return this; } /** * Set error * * @param err error * @return reference to this, for fluency */ public Coordinate setErr(float err) { this.err = err; return this; } /** * Set height * * @param height height * @return reference to this, for fluency */ public Coordinate setHeight(float height) { this.height = height; return this; } /** * Set vector * * @param vec vector * @return reference to this, for fluency */ public Coordinate setVec(List<Float> vec) { this.vec = vec; return this; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Coordinate that = (Coordinate) o; if (Float.compare(that.adj, adj) != 0) return false; if (Float.compare(that.err, err) != 0) return false; if (Float.compare(that.height, height) != 0) return false; if (node != null ? !node.equals(that.node) : that.node != null) return false; return vec != null ? vec.equals(that.vec) : that.vec == null; } @Override public int hashCode() { int result = node != null ? node.hashCode() : 0; result = 31 * result + (adj != +0.0f ? Float.floatToIntBits(adj) : 0); result = 31 * result + (err != +0.0f ? Float.floatToIntBits(err) : 0); result = 31 * result + (height != +0.0f ? Float.floatToIntBits(height) : 0); result = 31 * result + (vec != null ? vec.hashCode() : 0); return result; } }<|fim▁end|>
/* * Copyright (c) 2016 The original author or authors *
<|file_name|>event.js<|end_file_name|><|fim▁begin|>/** * helper functions for event entities */ (function () { /** * show self contained popup for listing Course Event entities */ radio('Event-CourseEvent').subscribe(function(modelId){ var id = new Date().getTime(); $.get(document.endpoints.event.getCourseEvent + "/" + modelId , function (html) { var id = new Date().getTime(); var selected = [] ; radio("show-modal").broadcast({ id: id, title: "<i class='icon-event'></i> Event Entities <small>Course Event for Course " + modelId + "</small>", content: html}) }) }) /** * show self contained popup for listing Delegate Event (event) entities */ radio('Event-DelegateEvent').subscribe(function (modelId) { $.get(document.endpoints.delegate.getDelegateEvent + "/" + modelId + "?selected=true", function (html) { var id = new Date().getTime(); var selected = [] ; radio("show-modal").broadcast({ id: id, title: "<i class='icon-delegate'></i> Delegate Entities <small>Delegate Event for Event " + modelId + "</small><hr/><button class='btn btn-success btn-sm disableOnAjax' onclick='radio(\"Delegate-Pick-DelegateEvent\").broadcast(" + modelId + ")' ><i class='icon-delegate'></i> Add Delegate</button>", content: html, pickText: "Update", onPick: function (e) { if (e.state == 0) { if (selected.indexOf(e.id) == -1) { selected.push(e.id); } } if (e.state == 1) { selected = _.reject(selected, function (x) { return x == e.id }); } if (e.state == -1) { $.ajax({ type: 'POST', url: "/event/UnLinkDelegateEvent", data: { modelId: modelId, items: selected }, dataType: "json", cache: false }).done(function (e) { if (e.Success) { radio("close-modal-" + id).broadcast(); radio("notify-success").broadcast({ title: "Event (" + modelId + ") updated", message: "<span onclick=\"radio('app-event-view').broadcast(" + modelId + ")\"><i class='icon-event'></i> View Event</span>" }) radio("app-isDirty").broadcast(true); } else { radio("showError-modal-" + id).broadcast(e.Errors); } }); } } }) }) }) /** * show self contained popup for adding new event Delegate Event */ radio('Event-Add-DelegateEvent').subscribe(function (modelId) { $.get(document.endpoints.event.addDelegateEvent , function (html) { var id = new Date().getTime(); radio("show-modal").broadcast({ id: id, title: "<i class='icon-event'></i> Add New Event <small>Delegate Event for Delegate " + modelId + "</small>", content: html, saveText : "Save", onSave: function (data) { data.modelId = modelId; radio("clear-modal-" + id).broadcast(); $.ajax({ type: 'POST', url: document.endpoints.event.saveDelegateEvent, data: data, dataType: "json", cache: false }).done(function (e) { if (e.Success) { radio("close-modal-" + id).broadcast(); radio("notify-success").broadcast({ title: "Event (" + e.Model.Id + ") updated", message: "<span onclick=\"radio('app-event-view').broadcast(" + e.Model.Id + ")\"><i class='icon-event'></i> View Event</span>" }) radio("app-isDirty").broadcast(true); } else { radio("showError-modal-" + id).broadcast(e.Errors); } }); } }) }) }) /** * show self contained popup for adding new event Delegate Event */ radio('Event-Pick-DelegateEvent').subscribe(function (modelId) { var selected = [] ; // register a refresh function radio("app-refresh-register").broadcast(function () { radio("app-refresh-unregister").broadcast(); // unsubscribe us radio("close-modal-" + id).broadcast(); // close this modal radio('Event-DelegateEvent').broadcast(modelId); // re open it }) $.get(document.endpoints.event.list, function (html) { var id = new Date().getTime(); radio("show-modal").broadcast({ id: id, title: "<i class='icon-event'></i> Pick Existing Event <small>Delegate Event for Delegate " + modelId + "</small>", content: html, pickText: "Pick", onPick: function (e) { if (e.state == 1) { if (selected.indexOf(e.id) == -1) { selected.push(e.id); } } if (e.state == 0) { selected = _.reject(selected, function (x) { return x == e.id }); } if (e.state == -1) { $.ajax({ type: 'POST', url: "/event/LinkDelegateEvent", data: { modelId: modelId, items: selected }, dataType: "json", cache: false }).done(function (e) { if (e.Success) { radio("close-modal-" + id).broadcast(); // close this modal radio("notify-success").broadcast({ title: "Event (" + modelId + ") updated", message: "<span onclick=\"radio('app-event-view').broadcast(" + modelId + ")\"><i class='icon-event'></i> View Event</span>" }) radio("app-isDirty").broadcast(true); } else { radio("showError-modal-" + id).broadcast(e.Errors); } }); } } }) }) }) /** * show self contained popup for listing Event Location (event) entities */ radio('Event-EventLocation').subscribe(function (modelId) { var selected = [] ; $.get(document.endpoints.location.getEventLocation + "/" + modelId , function (html) { var id = new Date().getTime(); // register a refresh function radio("app-refresh-register").broadcast(function () { radio("app-refresh-unregister").broadcast(); // unsubscribe us radio("close-modal-" + id).broadcast(); // close this modal radio('Event-EventLocation').broadcast(modelId); // re open it }) radio("show-modal").broadcast({ id: id, title: "<i class='icon-location'></i> Location Entities <small>Event Location for Event " + modelId + "</small><hr/><button class='btn btn-success btn-sm disableOnAjax' onclick='radio(\"Location-Pick-EventLocation\").broadcast(" + modelId + ")' ><i class='icon-location'></i> Add Location</button>", content: html , pickText: "Update", onPick: function (e) { if (e.state == 0) { if (selected.indexOf(e.id) == -1) { selected.push(e.id); } } if (e.state == 1) { selected = _.reject(selected, function (x) { return x == e.id }); } if (e.state == -1) { $.ajax({ type: 'POST', url: "/location/UnLinkEventLocation", data: { modelId: modelId, items: selected }, dataType: "json", cache: false }).done(function (e) { if (e.Success) { radio("close-modal-" + id).broadcast(); radio("app-refresh-unregister").broadcast(); // unsubscribe us radio("notify-success").broadcast({ title: "Location (" + modelId + ") updated", message: "<span onclick=\"radio('app-location-view').broadcast(" + modelId + ")\"><i class='icon-location'></i> View Location</span>" }) radio("app-isDirty").broadcast(true); } else { radio("showError-modal-" + id).broadcast(e.Errors); } }); } } }) }) }) /** * show self contained popup for adding new event Event Location */ radio('Event-Add-EventLocation').subscribe(function (modelId) { $.get(document.endpoints.event.addEventLocation + "/" + modelId, function (html) { var id = new Date().getTime(); radio("show-modal").broadcast({ id: id, title: "<i class='icon-event'></i> Add New Event <small>Event Location for Location " + modelId + "</small>", content: html, saveText: "Save", onSave: function (data) { radio("clear-modal-" + id).broadcast(); data.modelId = modelId $.ajax({ type: 'Post', data: data, url: document.endpoints.event.saveEventLocation, dataType: "json", cache: false }).done(function (e) { if (e.Success) { radio("close-modal-" + id).broadcast(); radio("notify-success").broadcast({ title: "Event updated", message: "" }) radio("app-isDirty").broadcast(true); } else { radio("showError-modal-" + id).broadcast(e.Errors); } }); }, }) }) }) /** * show self contained popup for picking existing event Event Location */ radio('Event-Pick-EventLocation').subscribe(function (modelId) { var selected = []; $.get(document.endpoints.event.list, function (html) { var id = new Date().getTime(); radio("show-modal").broadcast({ id: id, title: "<i class='icon-event'></i> Pick Existing Event <small>Event Location for Location " + modelId + "</small>", content: html, pickText: "Pick", onPick: function (e) { if (e.state == 1) { if (selected.indexOf(e.id) == -1) { selected.push(e.id); } } if (e.state == 0) { selected = _.reject(selected, function (x) { return x == e.id }); } if (e.state == -1) { $.ajax({ type: 'POST', url: "/location/LinkEventLocation", data: { modelId: modelId, items: selected }, dataType: "json", cache: false }).done(function (e) { if (e.Success) { radio("close-modal-" + id).broadcast(); radio("notify-success").broadcast({ title: "Location (" + modelId + ") updated", message: "<span onclick=\"radio('app-location-view').broadcast(" + modelId + ")\"><i class='icon-location'></i> View Location</span>" }) radio("app-isDirty").broadcast(true); } else { radio("showError-modal-" + id).broadcast(e.Errors); } }); } } }) }) }) /** * show self contained popup for listing Event Delegate (event) entities */ radio('Event-EventDelegate').subscribe(function (modelId) { var selected = [] ; $.get(document.endpoints.delegate.getEventDelegate + "/" + modelId , function (html) { var id = new Date().getTime(); // register a refresh function radio("app-refresh-register").broadcast(function () { radio("app-refresh-unregister").broadcast(); // unsubscribe us radio("close-modal-" + id).broadcast(); // close this modal radio('Event-EventDelegate').broadcast(modelId); // re open it }) radio("show-modal").broadcast({ id: id, title: "<i class='icon-delegate'></i> Delegate Entities <small>Event Delegate for Event " + modelId + "</small><hr/><button class='btn btn-success btn-sm disableOnAjax' onclick='radio(\"Delegate-Pick-EventDelegate\").broadcast(" + modelId + ")' ><i class='icon-delegate'></i> Add Delegate</button>", content: html , pickText: "Update", onPick: function (e) { if (e.state == 0) { if (selected.indexOf(e.id) == -1) { selected.push(e.id); } } if (e.state == 1) { selected = _.reject(selected, function (x) { return x == e.id }); } if (e.state == -1) { $.ajax({ type: 'POST', url: "/delegate/UnLinkEventDelegate", data: { modelId: modelId, items: selected }, dataType: "json", cache: false }).done(function (e) { if (e.Success) { radio("close-modal-" + id).broadcast(); radio("app-refresh-unregister").broadcast(); // unsubscribe us radio("notify-success").broadcast({ title: "Delegate (" + modelId + ") updated", message: "<span onclick=\"radio('app-delegate-view').broadcast(" + modelId + ")\"><i class='icon-delegate'></i> View Delegate</span>" }) radio("app-isDirty").broadcast(true); } else { radio("showError-modal-" + id).broadcast(e.Errors); } }); } } }) }) }) /** * show self contained popup for adding new event Event Delegate */ radio('Event-Add-EventDelegate').subscribe(function (modelId) { $.get(document.endpoints.event.addEventDelegate + "/" + modelId, function (html) { var id = new Date().getTime(); radio("show-modal").broadcast({ id: id, title: "<i class='icon-event'></i> Add New Event <small>Event Delegate for Delegate " + modelId + "</small>", content: html, saveText: "Save", onSave: function (data) { radio("clear-modal-" + id).broadcast(); data.modelId = modelId $.ajax({ type: 'Post', data: data, url: document.endpoints.event.saveEventDelegate, dataType: "json", cache: false }).done(function (e) { if (e.Success) { radio("close-modal-" + id).broadcast(); radio("notify-success").broadcast({ title: "Event updated", message: "" }) radio("app-isDirty").broadcast(true); } else { radio("showError-modal-" + id).broadcast(e.Errors); } }); }, }) }) }) /** * show self contained popup for picking existing event Event Delegate */ radio('Event-Pick-EventDelegate').subscribe(function (modelId) { var selected = []; $.get(document.endpoints.event.list, function (html) { var id = new Date().getTime(); radio("show-modal").broadcast({ id: id, title: "<i class='icon-event'></i> Pick Existing Event <small>Event Delegate for Delegate " + modelId + "</small>", content: html, pickText: "Pick", onPick: function (e) { if (e.state == 1) { if (selected.indexOf(e.id) == -1) { selected.push(e.id); } } if (e.state == 0) { selected = _.reject(selected, function (x) { return x == e.id }); } if (e.state == -1) { $.ajax({ type: 'POST', url: "/delegate/LinkEventDelegate", data: { modelId: modelId, items: selected }, dataType: "json", cache: false }).done(function (e) { if (e.Success) {<|fim▁hole|> radio("close-modal-" + id).broadcast(); radio("notify-success").broadcast({ title: "Delegate (" + modelId + ") updated", message: "<span onclick=\"radio('app-delegate-view').broadcast(" + modelId + ")\"><i class='icon-delegate'></i> View Delegate</span>" }) radio("app-isDirty").broadcast(true); } else { radio("showError-modal-" + id).broadcast(e.Errors); } }); } } }) }) }) })();<|fim▁end|>
<|file_name|>oLanguage.sProcessing.js<|end_file_name|><|fim▁begin|>// DATA_TEMPLATE: empty_table oTest.fnStart( "oLanguage.sProcessing" ); $(document).ready( function () { /* Check the default */ var oTable = $('#example').dataTable( { "sAjaxSource": "../../../examples/ajax/sources/arrays.txt", "bDeferRender": true, "bProcessing": true } ); var oSettings = oTable.fnSettings(); oTest.fnWaitTest( "Processing language is 'Processing...' by default", null, function () { return oSettings.oLanguage.sProcessing == "Processing..."; } ); oTest.fnTest( "Processing language default is in the DOM", null, function () { return document.getElementById('example_processing').innerHTML = "Processing..."; } ); oTest.fnWaitTest( "Processing language can be defined", function () { oSession.fnRestore(); oTable = $('#example').dataTable( { "sAjaxSource": "../../../examples/ajax/sources/arrays.txt", "bDeferRender": true, "bProcessing": true, "oLanguage": { "sProcessing": "unit test" }<|fim▁hole|> function () { return oSettings.oLanguage.sProcessing == "unit test"; } ); oTest.fnTest( "Processing language definition is in the DOM", null, function () { return document.getElementById('example_processing').innerHTML = "unit test"; } ); oTest.fnComplete(); } );<|fim▁end|>
} ); oSettings = oTable.fnSettings(); },
<|file_name|>PPCPredicates.cpp<|end_file_name|><|fim▁begin|>//===-- PPCPredicates.cpp - PPC Branch Predicate Information --------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements the PowerPC branch predicates. // //===----------------------------------------------------------------------===// #include "PPCPredicates.h" #include "llvm/Support/ErrorHandling.h" #include <cassert> using namespace llvm; PPC::Predicate PPC::InvertPredicate(PPC::Predicate Opcode) { switch (Opcode) { case PPC::PRED_EQ: return PPC::PRED_NE; case PPC::PRED_NE: return PPC::PRED_EQ; case PPC::PRED_LT: return PPC::PRED_GE; case PPC::PRED_GE: return PPC::PRED_LT; case PPC::PRED_GT: return PPC::PRED_LE; case PPC::PRED_LE: return PPC::PRED_GT; case PPC::PRED_NU: return PPC::PRED_UN; case PPC::PRED_UN: return PPC::PRED_NU; case PPC::PRED_EQ_MINUS: return PPC::PRED_NE_PLUS; case PPC::PRED_NE_MINUS: return PPC::PRED_EQ_PLUS; case PPC::PRED_LT_MINUS: return PPC::PRED_GE_PLUS; case PPC::PRED_GE_MINUS: return PPC::PRED_LT_PLUS; case PPC::PRED_GT_MINUS: return PPC::PRED_LE_PLUS; case PPC::PRED_LE_MINUS: return PPC::PRED_GT_PLUS; case PPC::PRED_NU_MINUS: return PPC::PRED_UN_PLUS; case PPC::PRED_UN_MINUS: return PPC::PRED_NU_PLUS; case PPC::PRED_EQ_PLUS: return PPC::PRED_NE_MINUS; case PPC::PRED_NE_PLUS: return PPC::PRED_EQ_MINUS; case PPC::PRED_LT_PLUS: return PPC::PRED_GE_MINUS; case PPC::PRED_GE_PLUS: return PPC::PRED_LT_MINUS; case PPC::PRED_GT_PLUS: return PPC::PRED_LE_MINUS; case PPC::PRED_LE_PLUS: return PPC::PRED_GT_MINUS; case PPC::PRED_NU_PLUS: return PPC::PRED_UN_MINUS; case PPC::PRED_UN_PLUS: return PPC::PRED_NU_MINUS; // Simple predicates for single condition-register bits. case PPC::PRED_BIT_SET: return PPC::PRED_BIT_UNSET; case PPC::PRED_BIT_UNSET: return PPC::PRED_BIT_SET; } llvm_unreachable("Unknown PPC branch opcode!"); } PPC::Predicate PPC::getSwappedPredicate(PPC::Predicate Opcode) { switch (Opcode) {<|fim▁hole|> case PPC::PRED_EQ: return PPC::PRED_EQ; case PPC::PRED_NE: return PPC::PRED_NE; case PPC::PRED_LT: return PPC::PRED_GT; case PPC::PRED_GE: return PPC::PRED_LE; case PPC::PRED_GT: return PPC::PRED_LT; case PPC::PRED_LE: return PPC::PRED_GE; case PPC::PRED_NU: return PPC::PRED_NU; case PPC::PRED_UN: return PPC::PRED_UN; case PPC::PRED_EQ_MINUS: return PPC::PRED_EQ_MINUS; case PPC::PRED_NE_MINUS: return PPC::PRED_NE_MINUS; case PPC::PRED_LT_MINUS: return PPC::PRED_GT_MINUS; case PPC::PRED_GE_MINUS: return PPC::PRED_LE_MINUS; case PPC::PRED_GT_MINUS: return PPC::PRED_LT_MINUS; case PPC::PRED_LE_MINUS: return PPC::PRED_GE_MINUS; case PPC::PRED_NU_MINUS: return PPC::PRED_NU_MINUS; case PPC::PRED_UN_MINUS: return PPC::PRED_UN_MINUS; case PPC::PRED_EQ_PLUS: return PPC::PRED_EQ_PLUS; case PPC::PRED_NE_PLUS: return PPC::PRED_NE_PLUS; case PPC::PRED_LT_PLUS: return PPC::PRED_GT_PLUS; case PPC::PRED_GE_PLUS: return PPC::PRED_LE_PLUS; case PPC::PRED_GT_PLUS: return PPC::PRED_LT_PLUS; case PPC::PRED_LE_PLUS: return PPC::PRED_GE_PLUS; case PPC::PRED_NU_PLUS: return PPC::PRED_NU_PLUS; case PPC::PRED_UN_PLUS: return PPC::PRED_UN_PLUS; case PPC::PRED_BIT_SET: case PPC::PRED_BIT_UNSET: llvm_unreachable("Invalid use of bit predicate code"); } llvm_unreachable("Unknown PPC branch opcode!"); }<|fim▁end|>
<|file_name|>test_multiple_nic_support.py<|end_file_name|><|fim▁begin|># Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF 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. """ tests for supporting multiple NIC's in advanced zone with security groups in cloudstack 4.14.0.0 """ # Import Local Modules from nose.plugins.attrib import attr from marvin.cloudstackTestCase import cloudstackTestCase, unittest from marvin.sshClient import SshClient from marvin.lib.utils import (validateList, cleanup_resources, get_host_credentials, get_process_status, execute_command_in_host, random_gen) from marvin.lib.base import (PhysicalNetwork, Account, Host, TrafficType, Domain, Network, NetworkOffering, VirtualMachine, ServiceOffering, Zone, NIC, SecurityGroup) from marvin.lib.common import (get_domain, get_zone, get_template, list_virtual_machines, list_routers, list_hosts, get_free_vlan) from marvin.codes import (PASS, FAILED) import logging import random import time class TestMulipleNicSupport(cloudstackTestCase): @classmethod def setUpClass(cls): cls.testClient = super( TestMulipleNicSupport, cls).getClsTestClient() cls.apiclient = cls.testClient.getApiClient() cls.testdata = cls.testClient.getParsedTestDataConfig() cls.services = cls.testClient.getParsedTestDataConfig() zone = get_zone(cls.apiclient, cls.testClient.getZoneForTests()) cls.zone = Zone(zone.__dict__) cls._cleanup = [] cls.skip = False if str(cls.zone.securitygroupsenabled) != "True": cls.skip = True return cls.logger = logging.getLogger("TestMulipleNicSupport") cls.stream_handler = logging.StreamHandler() cls.logger.setLevel(logging.DEBUG) cls.logger.addHandler(cls.stream_handler) # Get Domain and templates cls.domain = get_domain(cls.apiclient) cls.services['mode'] = cls.zone.networktype cls.template = get_template(cls.apiclient, cls.zone.id, hypervisor="KVM") if cls.template == FAILED: cls.skip = True return # Create new domain, account, network and VM cls.user_domain = Domain.create( cls.apiclient, services=cls.testdata["acl"]["domain2"], parentdomainid=cls.domain.id) # Create account cls.account1 = Account.create( cls.apiclient, cls.testdata["acl"]["accountD2"], admin=True, domainid=cls.user_domain.id ) # Create small service offering cls.service_offering = ServiceOffering.create( cls.apiclient, cls.testdata["service_offerings"]["small"] ) cls._cleanup.append(cls.service_offering) cls.services["network"]["zoneid"] = cls.zone.id cls.network_offering = NetworkOffering.create( cls.apiclient, cls.services["network_offering"], ) # Enable Network offering cls.network_offering.update(cls.apiclient, state='Enabled') cls._cleanup.append(cls.network_offering) cls.testdata["virtual_machine"]["zoneid"] = cls.zone.id cls.testdata["virtual_machine"]["template"] = cls.template.id if cls.zone.securitygroupsenabled: # Enable networking for reaching to VM thorugh SSH security_group = SecurityGroup.create( cls.apiclient, cls.testdata["security_group"], account=cls.account1.name, domainid=cls.account1.domainid ) # Authorize Security group to SSH to VM ingress_rule = security_group.authorize( cls.apiclient, cls.testdata["ingress_rule"], account=cls.account1.name, domainid=cls.account1.domainid ) # Authorize Security group to SSH to VM ingress_rule2 = security_group.authorize( cls.apiclient, cls.testdata["ingress_rule_ICMP"], account=cls.account1.name, domainid=cls.account1.domainid ) cls.testdata["shared_network_offering_sg"]["specifyVlan"] = 'True' cls.testdata["shared_network_offering_sg"]["specifyIpRanges"] = 'True' cls.shared_network_offering = NetworkOffering.create( cls.apiclient, cls.testdata["shared_network_offering_sg"], conservemode=False ) NetworkOffering.update( cls.shared_network_offering, cls.apiclient, id=cls.shared_network_offering.id, state="enabled" ) physical_network, vlan = get_free_vlan(cls.apiclient, cls.zone.id) cls.testdata["shared_network_sg"]["physicalnetworkid"] = physical_network.id random_subnet_number = random.randrange(90, 99) cls.testdata["shared_network_sg"]["name"] = "Shared-Network-SG-Test-vlan" + str(random_subnet_number) cls.testdata["shared_network_sg"]["displaytext"] = "Shared-Network-SG-Test-vlan" + str(random_subnet_number) cls.testdata["shared_network_sg"]["vlan"] = "vlan://" + str(random_subnet_number) cls.testdata["shared_network_sg"]["startip"] = "192.168." + str(random_subnet_number) + ".240" cls.testdata["shared_network_sg"]["endip"] = "192.168." + str(random_subnet_number) + ".250" cls.testdata["shared_network_sg"]["gateway"] = "192.168." + str(random_subnet_number) + ".254" cls.network1 = Network.create( cls.apiclient, cls.testdata["shared_network_sg"], networkofferingid=cls.shared_network_offering.id, zoneid=cls.zone.id, accountid=cls.account1.name, domainid=cls.account1.domainid ) random_subnet_number = random.randrange(100, 110) cls.testdata["shared_network_sg"]["name"] = "Shared-Network-SG-Test-vlan" + str(random_subnet_number) cls.testdata["shared_network_sg"]["displaytext"] = "Shared-Network-SG-Test-vlan" + str(random_subnet_number) cls.testdata["shared_network_sg"]["vlan"] = "vlan://" + str(random_subnet_number) cls.testdata["shared_network_sg"]["startip"] = "192.168." + str(random_subnet_number) + ".240" cls.testdata["shared_network_sg"]["endip"] = "192.168." + str(random_subnet_number) + ".250" cls.testdata["shared_network_sg"]["gateway"] = "192.168." + str(random_subnet_number) + ".254" cls.network2 = Network.create( cls.apiclient, cls.testdata["shared_network_sg"], networkofferingid=cls.shared_network_offering.id, zoneid=cls.zone.id, accountid=cls.account1.name, domainid=cls.account1.domainid ) random_subnet_number = random.randrange(111, 120) cls.testdata["shared_network_sg"]["name"] = "Shared-Network-SG-Test-vlan" + str(random_subnet_number)<|fim▁hole|> cls.testdata["shared_network_sg"]["startip"] = "192.168." + str(random_subnet_number) + ".240" cls.testdata["shared_network_sg"]["endip"] = "192.168." + str(random_subnet_number) + ".250" cls.testdata["shared_network_sg"]["gateway"] = "192.168." + str(random_subnet_number) + ".254" cls.network3 = Network.create( cls.apiclient, cls.testdata["shared_network_sg"], networkofferingid=cls.shared_network_offering.id, zoneid=cls.zone.id, accountid=cls.account1.name, domainid=cls.account1.domainid ) try: cls.virtual_machine1 = VirtualMachine.create( cls.apiclient, cls.testdata["virtual_machine"], accountid=cls.account1.name, domainid=cls.account1.domainid, serviceofferingid=cls.service_offering.id, templateid=cls.template.id, securitygroupids=[security_group.id], networkids=cls.network1.id ) for nic in cls.virtual_machine1.nic: if nic.isdefault: cls.virtual_machine1.ssh_ip = nic.ipaddress cls.virtual_machine1.default_network_id = nic.networkid break except Exception as e: cls.fail("Exception while deploying virtual machine: %s" % e) try: cls.virtual_machine2 = VirtualMachine.create( cls.apiclient, cls.testdata["virtual_machine"], accountid=cls.account1.name, domainid=cls.account1.domainid, serviceofferingid=cls.service_offering.id, templateid=cls.template.id, securitygroupids=[security_group.id], networkids=[str(cls.network1.id), str(cls.network2.id)] ) for nic in cls.virtual_machine2.nic: if nic.isdefault: cls.virtual_machine2.ssh_ip = nic.ipaddress cls.virtual_machine2.default_network_id = nic.networkid break except Exception as e: cls.fail("Exception while deploying virtual machine: %s" % e) cls._cleanup.append(cls.virtual_machine1) cls._cleanup.append(cls.virtual_machine2) cls._cleanup.append(cls.network1) cls._cleanup.append(cls.network2) cls._cleanup.append(cls.network3) cls._cleanup.append(cls.shared_network_offering) if cls.zone.securitygroupsenabled: cls._cleanup.append(security_group) cls._cleanup.append(cls.account1) cls._cleanup.append(cls.user_domain) @classmethod def tearDownClass(self): try: cleanup_resources(self.apiclient, self._cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return def setUp(self): if self.skip: self.skipTest("Test can be run only on advanced zone and KVM hypervisor") self.apiclient = self.testClient.getApiClient() self.cleanup = [] return def tearDown(self): try: cleanup_resources(self.apiclient, self.cleanup) except Exception as e: raise Exception("Warning: Exception during cleanup : %s" % e) return def verify_network_rules(self, vm_id): virtual_machine = VirtualMachine.list( self.apiclient, id=vm_id ) vm = virtual_machine[0] hosts = list_hosts( self.apiclient, id=vm.hostid ) host = hosts[0] if host.hypervisor.lower() not in "kvm": return host.user, host.password = get_host_credentials(self.config, host.ipaddress) for nic in vm.nic: secips = "" if len(nic.secondaryip) > 0: for secip in nic.secondaryip: secips += secip.ipaddress + ";" command="/usr/share/cloudstack-common/scripts/vm/network/security_group.py verify_network_rules --vmname %s --vmip %s --vmmac %s --nicsecips '%s'" % (vm.instancename, nic.ipaddress, nic.macaddress, secips) self.logger.debug("Executing command '%s' in host %s" % (command, host.ipaddress)) result=execute_command_in_host(host.ipaddress, 22, host.user, host.password, command) if len(result) > 0: self.fail("The iptables/ebtables rules for nic %s on vm %s on host %s are not correct" %(nic.ipaddress, vm.instancename, host.name)) @attr(tags=["adeancedsg"], required_hardware="false") def test_01_create_vm_with_multiple_nics(self): """Create Vm with multiple NIC's Steps: # 1. Create more than 1 isolated or shared network # 2. Create a vm and select more than 1 network while deploying # 3. Vm is deployed successfully with 1 nic from each network # 4. All the vm's should be pingable :return: """ virtual_machine = VirtualMachine.list( self.apiclient, id=self.virtual_machine2.id ) self.assertEqual( len(virtual_machine), 1, "Virtual Machine create with 2 NIC's failed") nicIdInVm = virtual_machine[0].nic[0] self.assertIsNotNone(nicIdInVm, "NIC 1 not found in Virtual Machine") nicIdInVm = virtual_machine[0].nic[1] self.assertIsNotNone(nicIdInVm, "NIC 2 not found in Virtual Machine") self.verify_network_rules(self.virtual_machine2.id) @attr(tags=["advancedsg"], required_hardware="false") def test_02_add_nic_to_vm(self): """Create VM with single NIC and then add additional NIC Steps: # 1. Create a VM by selecting one default NIC # 2. Create few more isolated or shared networks # 3. Add extra NIC's to the vm from the newly created networks # 4. The deployed VM should have extra nic's added in the above # step without any fail # 5. The IP's of the extra NIC's should be pingable :return: """ self.virtual_machine1.add_nic(self.apiclient, self.network2.id) virtual_machine = VirtualMachine.list( self.apiclient, id=self.virtual_machine1.id ) nicIdInVm = virtual_machine[0].nic[1] self.assertIsNotNone(nicIdInVm, "Second NIC not found") self.verify_network_rules(self.virtual_machine1.id) @attr(tags=["advancedsg"], required_hardware="false") def test_03_add_ip_to_default_nic(self): """ Add secondary IP's to the VM Steps: # 1. Create a VM with more than 1 NIC # 2) Navigate to Instances->NIC->Edit Secondary IP's # ->Aquire new Secondary IP" # 3) Add as many secondary Ip as possible to the VM # 4) Configure the secondary IP's by referring to "Configure # the secondary IP's" in the "Action Item" section :return: """ ipaddress = NIC.addIp( self.apiclient, id=self.virtual_machine2.nic[0].id ) self.assertIsNotNone( ipaddress, "Unable to add secondary IP to the default NIC") self.verify_network_rules(self.virtual_machine2.id) @attr(tags=["advancedsg"], required_hardware="false") def test_04_add_ip_to_remaining_nics(self): """ Add secondary IP's to remaining NIC's Steps: # 1) Create a VM with more than 1 NIC # 2)Navigate to Instances-NIC's->Edit Secondary IP's # ->Acquire new Secondary IP # 3) Add secondary IP to all the NIC's of the VM # 4) Confiugre the secondary IP's by referring to "Configure the # secondary IP's" in the "Action Item" section :return: """ self.virtual_machine1.add_nic(self.apiclient, self.network3.id) vms = VirtualMachine.list( self.apiclient, id=self.virtual_machine1.id ) self.assertIsNotNone( vms[0].nic[2], "Third NIC is not added successfully to the VM") vms1_nic1_id = vms[0].nic[1]['id'] vms1_nic2_id = vms[0].nic[2]['id'] ipaddress21 = NIC.addIp( self.apiclient, id=vms1_nic1_id ) ipaddress22 = NIC.addIp( self.apiclient, id=vms1_nic1_id ) self.assertIsNotNone( ipaddress21, "Unable to add first secondary IP to the second nic") self.assertIsNotNone( ipaddress22, "Unable to add second secondary IP to second NIC") ipaddress31 = NIC.addIp( self.apiclient, id=vms1_nic2_id ) ipaddress32 = NIC.addIp( self.apiclient, id=vms1_nic2_id ) self.assertIsNotNone( ipaddress31, "Unable to add first secondary IP to third NIC") self.assertIsNotNone( ipaddress32, "Unable to add second secondary IP to third NIC") self.verify_network_rules(self.virtual_machine1.id) @attr(tags=["advancedsg"], required_hardware="false") def test_05_stop_start_vm_with_multiple_nic(self): """ Stop and Start a VM with Multple NIC Steps: # 1) Create a Vm with multiple NIC's # 2) Configure secondary IP's on the VM # 3) Try to stop/start the VM # 4) Ping the IP's of the vm # 5) Remove Secondary IP from one of the NIC :return: """ ipaddress1 = NIC.addIp( self.apiclient, id=self.virtual_machine2.nic[0].id ) ipaddress2 = NIC.addIp( self.apiclient, id=self.virtual_machine2.nic[1].id ) # Stop the VM with multiple NIC's self.virtual_machine2.stop(self.apiclient) virtual_machine = VirtualMachine.list( self.apiclient, id=self.virtual_machine2.id ) self.assertEqual( virtual_machine[0]['state'], 'Stopped', "Could not stop the VM with multiple NIC's") if virtual_machine[0]['state'] == 'Stopped': # If stopped then try to start the VM self.virtual_machine2.start(self.apiclient) virtual_machine = VirtualMachine.list( self.apiclient, id=self.virtual_machine2.id ) self.assertEqual( virtual_machine[0]['state'], 'Running', "Could not start the VM with multiple NIC's") self.verify_network_rules(self.virtual_machine2.id) @attr(tags=["advancedsg"], required_hardware="false") def test_06_migrate_vm_with_multiple_nic(self): """ Migrate a VM with Multple NIC Steps: # 1) Create a Vm with multiple NIC's # 2) Configure secondary IP's on the VM # 3) Try to stop/start the VM # 4) Ping the IP's of the vm :return: """ # Skipping adding Secondary IP to NIC since its already # done in the previous test cases virtual_machine = VirtualMachine.list( self.apiclient, id=self.virtual_machine1.id ) old_host_id = virtual_machine[0]['hostid'] try: hosts = Host.list( self.apiclient, virtualmachineid=self.virtual_machine1.id, listall=True) self.assertEqual( validateList(hosts)[0], PASS, "hosts list validation failed") # Get a host which is not already assigned to VM for host in hosts: if host.id == old_host_id: continue else: host_id = host.id break self.virtual_machine1.migrate(self.apiclient, host_id) except Exception as e: self.fail("Exception occured: %s" % e) # List the vm again virtual_machine = VirtualMachine.list( self.apiclient, id=self.virtual_machine1.id) new_host_id = virtual_machine[0]['hostid'] self.assertNotEqual( old_host_id, new_host_id, "Migration of VM to new host failed" ) self.verify_network_rules(self.virtual_machine1.id) @attr(tags=["advancedsg"], required_hardware="false") def test_07_remove_secondary_ip_from_nic(self): """ Remove secondary IP from any NIC Steps: # 1) Navigate to Instances # 2) Select any vm # 3) NIC's ->Edit secondary IP's->Release IP # 4) The secondary IP should be successfully removed """ virtual_machine = VirtualMachine.list( self.apiclient, id=self.virtual_machine2.id) # Check which NIC is having secondary IP secondary_ips = virtual_machine[0].nic[1].secondaryip for secondary_ip in secondary_ips: NIC.removeIp(self.apiclient, ipaddressid=secondary_ip['id']) virtual_machine = VirtualMachine.list( self.apiclient, id=self.virtual_machine2.id ) self.assertFalse( virtual_machine[0].nic[1].secondaryip, 'Failed to remove secondary IP') self.verify_network_rules(self.virtual_machine2.id) @attr(tags=["advancedsg"], required_hardware="false") def test_08_remove_nic_from_vm(self): """ Remove NIC from VM Steps: # 1) Navigate to Instances->select any vm->NIC's->NIC 2 # ->Click on "X" button to remove the second NIC # 2) Remove other NIC's as well from the VM # 3) All the NIC's should be successfully removed from the VM :return: """ virtual_machine = VirtualMachine.list( self.apiclient, id=self.virtual_machine2.id) for nic in virtual_machine[0].nic: if nic.isdefault: continue self.virtual_machine2.remove_nic(self.apiclient, nic.id) virtual_machine = VirtualMachine.list( self.apiclient, id=self.virtual_machine2.id) self.assertEqual( len(virtual_machine[0].nic), 1, "Failed to remove all the nics from the virtual machine") self.verify_network_rules(self.virtual_machine2.id) @attr(tags=["advancedsg"], required_hardware="false") def test_09_reboot_vm_with_multiple_nic(self): """ Reboot a VM with Multple NIC Steps: # 1) Create a Vm with multiple NIC's # 2) Configure secondary IP's on the VM # 3) Try to reboot the VM # 4) Ping the IP's of the vm :return: """ # Skipping adding Secondary IP to NIC since its already # done in the previous test cases virtual_machine = VirtualMachine.list( self.apiclient, id=self.virtual_machine1.id ) try: self.virtual_machine1.reboot(self.apiclient) except Exception as e: self.fail("Exception occured: %s" % e) self.verify_network_rules(self.virtual_machine1.id)<|fim▁end|>
cls.testdata["shared_network_sg"]["displaytext"] = "Shared-Network-SG-Test-vlan" + str(random_subnet_number) cls.testdata["shared_network_sg"]["vlan"] = "vlan://" + str(random_subnet_number)
<|file_name|>item.py<|end_file_name|><|fim▁begin|>#!/usr/bin/env python3 # Copyright (c) 2008-9 Qtrac Ltd. All rights reserved. # This program or module is free software: you can redistribute it and/or # modify it under the terms of the GNU General Public License as published # by the Free Software Foundation, either version 2 of the License, or # version 3 of the License, or (at your option) any later version. It is # provided for educational purposes and is distributed in the hope that # it will be useful, but WITHOUT ANY WARRANTY; without even the implied # warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See # the GNU General Public License for more details. """Provides the Item example classes. """ class Item(object): def __init__(self, artist, title, year=None): self.__artist = artist self.__title = title self.__year = year def artist(self): return self.__artist def setArtist(self, artist): self.__artist = artist def title(self): return self.__title def setTitle(self, title): self.__title = title def year(self): return self.__year def setYear(self, year): self.__year = year def __str__(self): year = "" if self.__year is not None: year = " in {0}".format(self.__year) return "{0} by {1}{2}".format(self.__title, self.__artist, year) class Painting(Item): def __init__(self, artist, title, year=None): super(Painting, self).__init__(artist, title, year) class Sculpture(Item): def __init__(self, artist, title, year=None, material=None): super(Sculpture, self).__init__(artist, title, year) self.__material = material def material(self): return self.__material def setMaterial(self, material): self.__material = material def __str__(self): materialString = "" if self.__material is not None: materialString = " ({0})".format(self.__material) return "{0}{1}".format(super(Sculpture, self).__str__(), materialString) class Dimension(object): def __init__(self, width, height, depth=None): self.__width = width self.__height = height self.__depth = depth def width(self): return self.__width def setWidth(self, width): self.__width = width def height(self): return self.__height def setHeight(self, height): self.__height = height def depth(self): return self.__depth def setDepth(self, depth): self.__depth = depth def area(self): raise NotImplemented def volume(self):<|fim▁hole|> if __name__ == "__main__": items = [] items.append(Painting("Cecil Collins", "The Poet", 1941)) items.append(Painting("Cecil Collins", "The Sleeping Fool", 1943)) items.append(Painting("Edvard Munch", "The Scream", 1893)) items.append(Painting("Edvard Munch", "The Sick Child", 1896)) items.append(Painting("Edvard Munch", "The Dance of Life", 1900)) items.append(Sculpture("Auguste Rodin", "Eternal Springtime", 1917, "plaster")) items.append(Sculpture("Auguste Rodin", "Naked Balzac", 1917, "plaster")) items.append(Sculpture("Auguste Rodin", "The Secret", 1925, "bronze")) uniquematerials = set() for item in items: print(item) if hasattr(item, "material"): uniquematerials.add(item.material()) print("Sculptures use {0} unique materials".format( len(uniquematerials)))<|fim▁end|>
raise NotImplemented
<|file_name|>unittest_utils.py<|end_file_name|><|fim▁begin|># copyright 2003-2013 LOGILAB S.A. (Paris, FRANCE), all rights reserved. # contact http://www.logilab.fr/ -- mailto:contact@logilab.fr # # This file is part of astroid. # # astroid is free software: you can redistribute it and/or modify it # under the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 2.1 of the License, or (at your # option) any later version. # # astroid is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or # FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License # for more details. # # You should have received a copy of the GNU Lesser General Public License along # with astroid. If not, see <http://www.gnu.org/licenses/>. import unittest from astroid import builder, nodes from astroid.node_classes import are_exclusive builder = builder.AstroidBuilder() class AreExclusiveTC(unittest.TestCase): def test_not_exclusive(self): astroid = builder.string_build(""" x = 10 for x in range(5): print (x) if x > 0: print ('#' * x) """, __name__, __file__) xass1 = astroid.locals['x'][0] assert xass1.lineno == 2 xnames = [n for n in astroid.nodes_of_class(nodes.Name) if n.name == 'x'] assert len(xnames) == 3 assert xnames[1].lineno == 6 self.assertEqual(are_exclusive(xass1, xnames[1]), False) self.assertEqual(are_exclusive(xass1, xnames[2]), False) def test_if(self): astroid = builder.string_build(''' if 1: a = 1 a = 2 elif 2: a = 12 a = 13 else: a = 3 a = 4 ''') a1 = astroid.locals['a'][0] a2 = astroid.locals['a'][1] a3 = astroid.locals['a'][2] a4 = astroid.locals['a'][3] a5 = astroid.locals['a'][4] a6 = astroid.locals['a'][5] self.assertEqual(are_exclusive(a1, a2), False) self.assertEqual(are_exclusive(a1, a3), True) self.assertEqual(are_exclusive(a1, a5), True) self.assertEqual(are_exclusive(a3, a5), True) self.assertEqual(are_exclusive(a3, a4), False) self.assertEqual(are_exclusive(a5, a6), False) def test_try_except(self): astroid = builder.string_build(''' try: def exclusive_func2(): "docstring" except TypeError: def exclusive_func2(): "docstring" except: def exclusive_func2(): "docstring" else: def exclusive_func2():<|fim▁hole|> f1 = astroid.locals['exclusive_func2'][0] f2 = astroid.locals['exclusive_func2'][1] f3 = astroid.locals['exclusive_func2'][2] f4 = astroid.locals['exclusive_func2'][3] self.assertEqual(are_exclusive(f1, f2), True) self.assertEqual(are_exclusive(f1, f3), True) self.assertEqual(are_exclusive(f1, f4), False) self.assertEqual(are_exclusive(f2, f4), True) self.assertEqual(are_exclusive(f3, f4), True) self.assertEqual(are_exclusive(f3, f2), True) self.assertEqual(are_exclusive(f2, f1), True) self.assertEqual(are_exclusive(f4, f1), False) self.assertEqual(are_exclusive(f4, f2), True) if __name__ == '__main__': unittest.main()<|fim▁end|>
"this one redefine the one defined line 42" ''')
<|file_name|>build.rs<|end_file_name|><|fim▁begin|>// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. #[cfg(not(feature = "serde_macros"))] mod inner { extern crate serde_codegen; use std::env; use std::path::Path; pub fn main() {<|fim▁hole|> let dst = Path::new(&out_dir).join("lib.rs"); serde_codegen::expand(&src, &dst).unwrap(); } } #[cfg(feature = "serde_macros")] mod inner { pub fn main() {} } fn main() { inner::main(); }<|fim▁end|>
let out_dir = env::var_os("OUT_DIR").unwrap(); let src = Path::new("src/lib.rs.in");
<|file_name|>t_tube.cc<|end_file_name|><|fim▁begin|>/** * This file is part of the CernVM File System. */ #include "gtest/gtest.h" #include "ingestion/tube.h" using namespace std; // NOLINT namespace { class DummyItem { public: DummyItem() : tag_(-1) { } int64_t tag() { return tag_; } int64_t tag_; }; } class T_Tube : public ::testing::Test { protected: virtual void SetUp() { } virtual void TearDown() { } Tube<DummyItem> tube_; }; TEST_F(T_Tube, Fifo) { DummyItem a, b, c; EXPECT_EQ(0U, tube_.size()); EXPECT_TRUE(tube_.IsEmpty()); Tube<DummyItem>::Link *l1 = tube_.EnqueueBack(&a); EXPECT_EQ(&a, l1->item()); EXPECT_EQ(1U, tube_.size()); EXPECT_FALSE(tube_.IsEmpty()); Tube<DummyItem>::Link *l2 = tube_.EnqueueBack(&b); EXPECT_NE(l1, l2); tube_.EnqueueBack(&c); EXPECT_EQ(3U, tube_.size()); DummyItem *x = tube_.Slice(l2); EXPECT_EQ(2U, tube_.size()); EXPECT_EQ(&b, x); x = tube_.PopFront(); EXPECT_EQ(1U, tube_.size()); EXPECT_EQ(&a, x); x = tube_.PopFront(); EXPECT_EQ(&c, x); EXPECT_TRUE(tube_.IsEmpty()); } TEST_F(T_Tube, Group) { DummyItem a1, a2, b, c; a1.tag_ = a2.tag_ = 0; b.tag_ = 1; c.tag_ = 2; TubeGroup<DummyItem> grp1;<|fim▁hole|> grp1.Dispatch(&a1); grp1.Dispatch(&b); EXPECT_EQ(2U, t1->size()); DummyItem *x = t1->PopFront(); EXPECT_EQ(&a1, x); x = t1->PopFront(); EXPECT_EQ(&b, x); TubeGroup<DummyItem> grp2; Tube<DummyItem> *t2 = new Tube<DummyItem>(); Tube<DummyItem> *t3 = new Tube<DummyItem>(); grp2.TakeTube(t2); grp2.TakeTube(t3); grp2.Activate(); grp2.Dispatch(&a1); grp2.Dispatch(&b); grp2.Dispatch(&a2); grp2.Dispatch(&c); EXPECT_EQ(3U, t2->size()); EXPECT_EQ(1U, t3->size()); x = t2->PopFront(); EXPECT_EQ(&a1, x); x = t2->PopFront(); EXPECT_EQ(&a2, x); x = t2->PopFront(); EXPECT_EQ(&c, x); x = t3->PopFront(); EXPECT_EQ(&b, x); }<|fim▁end|>
Tube<DummyItem> *t1 = new Tube<DummyItem>(); grp1.TakeTube(t1); grp1.Activate();
<|file_name|>test_parentHook2to3.py<|end_file_name|><|fim▁begin|>""" Test upgrading L{_SubSchedulerParentHook} from version 2 to 3. """ from axiom.test.historic.stubloader import StubbedTest from axiom.scheduler import _SubSchedulerParentHook from axiom.substore import SubStore from axiom.dependency import _DependencyConnector class SubSchedulerParentHookUpgradeTests(StubbedTest): """ Test upgrading L{_SubSchedulerParentHook} from version 2 to 3. """ def setUp(self): d = StubbedTest.setUp(self) def cbSetUp(ignored): self.hook = self.store.findUnique(_SubSchedulerParentHook)<|fim▁hole|> def test_attributesCopied(self): """ The only attribute of L{_SubSchedulerParentHook} which still exists at the current version, version 4, C{subStore}, ought to have been copied over. """ self.assertIdentical( self.hook.subStore, self.store.findUnique(SubStore)) def test_uninstalled(self): """ The record of the installation of L{_SubSchedulerParentHook} on the store is deleted in the upgrade to schema version 4. """ self.assertEquals( list(self.store.query( _DependencyConnector, _DependencyConnector.installee == self.hook)), [])<|fim▁end|>
d.addCallback(cbSetUp) return d
<|file_name|>unsized7.rs<|end_file_name|><|fim▁begin|>// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // Test sized-ness checking in substitution in impls. trait T {} // I would like these to fail eventually. // impl - bounded trait T1<Z: T> { } struct S3<Y: ?Sized>; impl<X: ?Sized + T> T1<X> for S3<X> {<|fim▁hole|> fn main() { }<|fim▁end|>
//~^ ERROR `core::marker::Sized` is not implemented for the type `X` }
<|file_name|>test_monitor_log_analytics_cluster.py<|end_file_name|><|fim▁begin|># -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- <|fim▁hole|> class TestClusterScenarios(ScenarioTest): @record_only() @ResourceGroupPreparer(name_prefix='cli_test_monitor_log_analytics_cluster_c', parameter_name='rg1', key='rg1', location='centralus') def test_monitor_log_analytics_cluster_default(self, rg1): new_cluster_name = self.create_random_name('clitest-cluster-', 20) sku_capacity = 1000 self.kwargs.update({ 'new_cluster_name': new_cluster_name, 'sku_capacity': sku_capacity }) self.cmd("monitor log-analytics cluster create -g {rg1} -n {new_cluster_name} --sku-capacity {sku_capacity}", checks=[]) self.cmd("monitor log-analytics cluster show -g {rg1} -n {new_cluster_name}", checks=[ self.check('provisioningState', 'Succeeded'), self.check('name', new_cluster_name), self.check('sku.capacity', sku_capacity) ]) new_sku_capacity = 2000 self.kwargs.update({ 'sku_capacity': new_sku_capacity }) self.cmd("monitor log-analytics cluster update -g {rg1} -n {new_cluster_name} " "--sku-capacity {sku_capacity}", checks=[ self.check('sku.capacity', new_sku_capacity) ]) self.cmd("monitor log-analytics cluster show -g {rg1} -n {new_cluster_name}", checks=[ self.check('provisioningState', 'Succeeded'), self.check('sku.capacity', new_sku_capacity) ]) self.cmd("monitor log-analytics cluster list -g {rg1}", checks=[ self.check('length(@)', 1) ]) self.cmd("monitor log-analytics cluster delete -g {rg1} -n {new_cluster_name} -y", checks=[]) with self.assertRaisesRegex(SystemExit, '3'): self.cmd('monitor log-analytics cluster show -g {rg1} -n {new_cluster_name}') @record_only() def test_monitor_log_analytics_cluster_update_key(self): new_key_name = 'key2' new_key_version = 'dc814576e6b34de69a10b186a4723035' self.kwargs.update({ 'rg': 'azure-cli-test-scus', 'key_name': new_key_name, 'key_version': new_key_version, 'key_vault_uri': 'https://yu-vault-1.vault.azure.net/', 'cluster_name': 'yu-test-cluster2' }) self.cmd("monitor log-analytics cluster update -g {rg} -n {cluster_name} --key-name {key_name} " "--key-vault-uri {key_vault_uri} --key-version {key_version}", checks=[]) self.cmd("monitor log-analytics cluster wait -g {rg} -n {cluster_name} --updated", checks=[]) self.cmd("monitor log-analytics cluster show -g {rg} -n {cluster_name}", checks=[ self.check('provisioningState', 'Succeeded'), self.check('keyVaultProperties.keyName', new_key_name), self.check('keyVaultProperties.keyVersion', new_key_version) ])<|fim▁end|>
from azure.cli.testsdk import ScenarioTest, record_only, ResourceGroupPreparer
<|file_name|>2357b6b3d76_.py<|end_file_name|><|fim▁begin|>"""empty message Revision ID: 2357b6b3d76 Revises: fecca96b9d Create Date: 2015-10-27 10:26:52.074526 """<|fim▁hole|>down_revision = 'fecca96b9d' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic - please adjust! ### op.add_column('citizen_complaints', sa.Column('service_type', sa.String(length=255), nullable=True)) op.add_column('citizen_complaints', sa.Column('source', sa.String(length=255), nullable=True)) ### end Alembic commands ### def downgrade(): ### commands auto generated by Alembic - please adjust! ### op.drop_column('citizen_complaints', 'source') op.drop_column('citizen_complaints', 'service_type') ### end Alembic commands ###<|fim▁end|>
# revision identifiers, used by Alembic. revision = '2357b6b3d76'
<|file_name|>MRSATreatmentVoBean.java<|end_file_name|><|fim▁begin|>//############################################################################# //# #<|fim▁hole|>//# published by the Free Software Foundation, either version 3 of the # //# License, or (at your option) any later version. # //# # //# This program is distributed in the hope that it will be useful, # //# but WITHOUT ANY WARRANTY; without even the implied warranty of # //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # //# GNU Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.nursing.vo.beans; public class MRSATreatmentVoBean extends ims.vo.ValueObjectBean { public MRSATreatmentVoBean() { } public MRSATreatmentVoBean(ims.nursing.vo.MRSATreatmentVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.startdate = vo.getStartDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getStartDate().getBean(); this.rescreendate = vo.getRescreenDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getRescreenDate().getBean(); this.treatmentnumber = vo.getTreatmentNumber(); this.treatmentdetails = vo.getTreatmentDetails() == null ? null : vo.getTreatmentDetails().getBeanCollection(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.nursing.vo.MRSATreatmentVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.startdate = vo.getStartDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getStartDate().getBean(); this.rescreendate = vo.getRescreenDate() == null ? null : (ims.framework.utils.beans.DateBean)vo.getRescreenDate().getBean(); this.treatmentnumber = vo.getTreatmentNumber(); this.treatmentdetails = vo.getTreatmentDetails() == null ? null : vo.getTreatmentDetails().getBeanCollection(); } public ims.nursing.vo.MRSATreatmentVo buildVo() { return this.buildVo(new ims.vo.ValueObjectBeanMap()); } public ims.nursing.vo.MRSATreatmentVo buildVo(ims.vo.ValueObjectBeanMap map) { ims.nursing.vo.MRSATreatmentVo vo = null; if(map != null) vo = (ims.nursing.vo.MRSATreatmentVo)map.getValueObject(this); if(vo == null) { vo = new ims.nursing.vo.MRSATreatmentVo(); map.addValueObject(this, vo); vo.populate(map, this); } return vo; } public Integer getId() { return this.id; } public void setId(Integer value) { this.id = value; } public int getVersion() { return this.version; } public void setVersion(int value) { this.version = value; } public ims.framework.utils.beans.DateBean getStartDate() { return this.startdate; } public void setStartDate(ims.framework.utils.beans.DateBean value) { this.startdate = value; } public ims.framework.utils.beans.DateBean getRescreenDate() { return this.rescreendate; } public void setRescreenDate(ims.framework.utils.beans.DateBean value) { this.rescreendate = value; } public Integer getTreatmentNumber() { return this.treatmentnumber; } public void setTreatmentNumber(Integer value) { this.treatmentnumber = value; } public ims.nursing.vo.beans.MRSATreatmentDetailsVoBean[] getTreatmentDetails() { return this.treatmentdetails; } public void setTreatmentDetails(ims.nursing.vo.beans.MRSATreatmentDetailsVoBean[] value) { this.treatmentdetails = value; } private Integer id; private int version; private ims.framework.utils.beans.DateBean startdate; private ims.framework.utils.beans.DateBean rescreendate; private Integer treatmentnumber; private ims.nursing.vo.beans.MRSATreatmentDetailsVoBean[] treatmentdetails; }<|fim▁end|>
//# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program is free software: you can redistribute it and/or modify # //# it under the terms of the GNU Affero General Public License as #
<|file_name|>0001_initial.py<|end_file_name|><|fim▁begin|># -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Bien', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('descripcion', models.CharField(max_length=255, blank=True)), ('direccion', models.CharField(max_length=255, blank=True)), ('barrio', models.CharField(max_length=255, blank=True)), ('localidad', models.CharField(max_length=255, blank=True)), ('provincia', models.CharField(max_length=255, blank=True)), ('pais', models.CharField(max_length=255, blank=True)), ('modelo', models.IntegerField(null=True, blank=True)), ('entidad', models.CharField(max_length=255, blank=True)), ('ramo', models.CharField(max_length=255, blank=True)), ('cant_acciones', models.CharField(max_length=255, blank=True)), ('fecha_desde', models.DateField(null=True, blank=True)), ('destino', models.CharField(max_length=255, blank=True)), ('origen', models.CharField(max_length=255, blank=True)), ('superficie', models.DecimalField(help_text='Superficie de la propiedad', null=True, max_digits=10, decimal_places=2, blank=True)), ('unidad_medida_id', models.IntegerField(blank=True, help_text='Unidad de medida usada para la superficie', null=True, choices=[(0, 'm2'), (1, 'ha')])), ('m_mejoras_id', models.IntegerField(blank=True, null=True, choices=[(0, '$'), (1, 'us$'), (2, 'E'), (3, '$ Uruguayos'), (4, '\xa3'), (5, 'A'), (6, 'A$'), (7, '$L')])), ('mejoras', models.DecimalField(null=True, max_digits=10, decimal_places=2, blank=True)), ('m_valor_fiscal_id', models.IntegerField(blank=True, null=True, choices=[(0, '$'), (1, 'us$'), (2, 'E'), (3, '$ Uruguayos'), (4, '\xa3'), (5, 'A'), (6, 'A$'), (7, '$L')])), ('valor_fiscal', models.DecimalField(null=True, max_digits=10, decimal_places=2, blank=True)), ('m_valor_adq_id', models.IntegerField(blank=True, null=True, choices=[(0, '$'), (1, 'us$'), (2, 'E'), (3, '$ Uruguayos'), (4, '\xa3'), (5, 'A'), (6, 'A$'), (7, '$L')])), ('valor_adq', models.DecimalField(null=True, max_digits=10, decimal_places=2, blank=True)), ('fecha_hasta', models.DateField(null=True, blank=True)), ('titular_dominio', models.CharField(max_length=255, blank=True)), ('porcentaje', models.DecimalField(help_text="<strong>NO</strong> incluir el signo '%'.<br> Si ingresa un n\xfamero decimal use '.' (punto) como delimitador", null=True, max_digits=10, decimal_places=2, blank=True)), ('vinculo', models.CharField(default='Titular', help_text='Indica la relacion con el titular de la DDJJ', max_length=255, blank=True, choices=[('Conviviente', 'Conviviente'), ('C\xf3nyuge', 'C\xf3nyuge'), ('Hijo/a', 'Hijo/a'), ('Titular', 'Titular')])), ('periodo', models.CharField(max_length=255, blank=True)), ('obs', models.CharField(max_length=255, blank=True)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ('tipo_bien_s', models.CharField(max_length=255, blank=True)), ('nombre_bien_s', models.CharField(max_length=255, blank=True)), ], options={ 'ordering': ['tipo_bien', 'nombre_bien'], 'db_table': 'biens', 'verbose_name_plural': 'bienes', }, bases=(models.Model,), ), migrations.CreateModel( name='Cargo', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('jurisdiccion', models.CharField(max_length=255, blank=True)), ('cargo', models.CharField(help_text='Nombre del cargo', max_length=255)), ('poder_id', models.IntegerField(blank=True, null=True, choices=[(0, 'Ejecutivo'), (1, 'Legislativo'), (2, 'Judicial')])), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], options={ 'ordering': ['cargo'], 'db_table': 'cargos', }, bases=(models.Model,), ), migrations.CreateModel( name='ContenidoDdjjs', fields=[ ('id', models.IntegerField(serialize=False, primary_key=True)), ('ddjj_id', models.IntegerField(null=True, blank=True)), ('ddjj_ano', models.CharField(max_length=255, blank=True)), ('ddjj_tipo', models.CharField(max_length=255, blank=True)), ('poder_id', models.IntegerField(null=True, blank=True)), ('persona_str', models.CharField(max_length=255, blank=True)), ('persona_id', models.IntegerField(null=True, blank=True)), ('cargo_str', models.CharField(max_length=255, blank=True)), ('cargo_id', models.IntegerField(null=True, blank=True)), ('contenido', models.TextField(blank=True)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], options={ 'db_table': 'contenido_ddjjs', }, bases=(models.Model,), ), migrations.CreateModel( name='Ddjj', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('ano', models.IntegerField()), ('tipo_ddjj_id', models.IntegerField(choices=[(0, 'alta'), (1, 'baja'), (2, 'inicial'), (3, 'anual')])), ('funcionario', models.CharField(help_text='Este campo lo completa el sistema.', max_length=255, blank=True)), ('url', models.CharField(help_text='Url DocumentCloud', max_length=255, blank=True)), ('key', models.IntegerField(help_text='Este campo lo completa el sistema.', null=True, blank=True)), ('clave', models.CharField(help_text='Este campo lo completa el sistema.', max_length=255, blank=True)), ('flag_presenta', models.IntegerField(default=1, choices=[(0, 'Si'), (1, 'No')], blank=True, help_text="<strong style='color:blue'>'Solo el PDF'</strong> si solo se muestra el pdf, ej: cartas donde declaran que la ddjj es igual a la del a\xf1o anterior", null=True, verbose_name='Carta de DDJJ')), ('obs', models.TextField(blank=True)), ('flag_search', models.CharField(help_text='Este campo lo completa el sistema.', max_length=255, blank=True)), ('visitas', models.DecimalField(null=True, max_digits=10, decimal_places=0, blank=True)), ('status', models.IntegerField(default=0, help_text='Indica si puede ser publicada', choices=[(0, 'Deshabilitado'), (1, 'Habilitado')])), ('poder_id', models.IntegerField(choices=[(0, 'Ejecutivo'), (1, 'Legislativo'), (2, 'Judicial')])), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], options={ 'ordering': ['persona'], 'db_table': 'ddjjs', 'verbose_name': 'Declaraci\xf3n Jurada', 'verbose_name_plural': 'Declaraciones Juradas', }, bases=(models.Model,), ), migrations.CreateModel( name='Jurisdiccion', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('nombre', models.CharField(max_length=255)), ('poder_id', models.IntegerField(blank=True, null=True, choices=[(0, 'Ejecutivo'), (1, 'Legislativo'), (2, 'Judicial')])), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], options={ 'ordering': ['nombre'], 'db_table': 'jurisdiccions', }, bases=(models.Model,), ), migrations.CreateModel( name='NombreBien', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('nombre', models.CharField(max_length=255, blank=True)), ('tipo_bien_id', models.IntegerField(null=True, blank=True)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], options={ 'ordering': ['nombre'], 'db_table': 'nombre_biens', 'verbose_name_plural': 'Nombre Bienes', }, bases=(models.Model,), ), migrations.CreateModel( name='Persona', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('apellido', models.CharField(max_length=255)), ('nombre', models.CharField(max_length=255)), ('legajo', models.CharField(max_length=255, blank=True)), ('tipo_documento_id', models.IntegerField(blank=True, null=True, choices=[(0, 'dni'), (1, 'le'), (2, 'lc'), (3, 'pasaporte')])), ('documento', models.IntegerField(null=True, blank=True)), ('cuit_cuil', models.CharField(max_length=255, blank=True)), ('nacimento', models.DateField(null=True, blank=True)), ('sexo_id', models.IntegerField(blank=True, null=True, choices=[(0, 'M'), (1, 'F')])), ('estado_civil_id', models.IntegerField(blank=True, null=True, choices=[(0, 'Casado/a'), (1, 'C\xf3nyugue'), (2, 'Divorciado/a'), (3, 'Separado'), (4, 'Soltero/a'), (5, 'U. Hecho'), (6, 'Viudo/a')])), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ('tag_id', models.CharField(help_text='ID del tag en el diario La Naci\xf3n', max_length=255, blank=True)), ('tag_img_id', models.CharField(help_text='ID de la img del tag', max_length=255, blank=True)), ('tag_descripcion', models.CharField(help_text='Descripcion del tag Nacion', max_length=255, blank=True)), ('ficha_d_l', models.CharField(help_text='Url ficha de Directorio Legislativo', max_length=255, blank=True)), ], options={ 'ordering': ['apellido', 'nombre'], 'db_table': 'personas', }, bases=(models.Model,), ), migrations.CreateModel( name='PersonaCargo', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('flag_ingreso', models.IntegerField(null=True, blank=True)), ('ingreso', models.DateField(null=True, blank=True)), ('egreso', models.DateField(null=True, blank=True)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ('cargo', models.ForeignKey(to='admin_ddjj_app.Cargo')), ('jurisdiccion', models.ForeignKey(blank=True, to='admin_ddjj_app.Jurisdiccion', null=True)), ('persona', models.ForeignKey(to='admin_ddjj_app.Persona')), ], options={ 'ordering': ['cargo'], 'db_table': 'persona_cargos', 'verbose_name_plural': 'Persona Cargos', }, bases=(models.Model,),<|fim▁hole|> migrations.CreateModel( name='TiempoControls', fields=[ ('id', models.IntegerField(serialize=False, primary_key=True)), ('dias', models.CharField(max_length=255, blank=True)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], options={ 'db_table': 'tiempo_controls', }, bases=(models.Model,), ), migrations.CreateModel( name='TipoBien', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('nombre', models.CharField(max_length=255, blank=True)), ('created_at', models.DateTimeField(auto_now_add=True)), ('updated_at', models.DateTimeField(auto_now=True)), ], options={ 'ordering': ['nombre'], 'db_table': 'tipo_biens', 'verbose_name_plural': 'Tipo Bienes', }, bases=(models.Model,), ), migrations.AddField( model_name='ddjj', name='persona', field=models.ForeignKey(related_name='ddjjs', to='admin_ddjj_app.Persona'), preserve_default=True, ), migrations.AddField( model_name='ddjj', name='persona_cargo', field=models.ForeignKey(related_name='ddjjs', to='admin_ddjj_app.PersonaCargo', help_text='Indique el cargo que ocupa para esta DDJJ'), preserve_default=True, ), migrations.AddField( model_name='cargo', name='personas', field=models.ManyToManyField(to='admin_ddjj_app.Persona', through='admin_ddjj_app.PersonaCargo'), preserve_default=True, ), migrations.AddField( model_name='bien', name='ddjj', field=models.ForeignKey(related_name='bienes', to='admin_ddjj_app.Ddjj', help_text='Indica la DDJJ a la cual pertenece este bien'), preserve_default=True, ), migrations.AddField( model_name='bien', name='nombre_bien', field=models.ForeignKey(related_name='bienes', to='admin_ddjj_app.NombreBien'), preserve_default=True, ), migrations.AddField( model_name='bien', name='persona', field=models.ForeignKey(help_text='Es el titular del bien, este puede ser distinto al titular de la DDJJ', to='admin_ddjj_app.Persona'), preserve_default=True, ), migrations.AddField( model_name='bien', name='tipo_bien', field=models.ForeignKey(related_name='bienes', to='admin_ddjj_app.TipoBien'), preserve_default=True, ), ]<|fim▁end|>
),
<|file_name|>wine.py<|end_file_name|><|fim▁begin|>from selenium import webdriver from selenium.webdriver.common.keys import Keys import json import time def keys(filename): with open(filename) as f: secret_keys = json.load(f) return secret_keys def access_listpage(secret_keys, driver): driver.get("https://wine.wul.waseda.ac.jp/patroninfo*jpn") time.sleep(5) elem = driver.find_element_by_name("extpatid") elem.send_keys(secret_keys["user"]) elem2 = driver.find_element_by_name("extpatpw") elem2.send_keys(secret_keys["pw"]) submit = driver.find_element_by_link_text("送信") submit.click() time.sleep(5) list_all = driver.find_element_by_partial_link_text("貸出中です") list_all.click() time.sleep(5) def send_extension(driver): """ 前提:借りている書籍のリストにいること<|fim▁hole|> driver.find_element_by_name("requestRenewAll").click() time.sleep(5) driver.find_element_by_name("renewall").click() time.sleep(5)<|fim▁end|>
"""
<|file_name|>D3DSurfaceData.cpp<|end_file_name|><|fim▁begin|>/* * Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #include <jni.h> #include <jni_util.h> #include <jlong.h> #include "D3DSurfaceData.h" #include "D3DPipelineManager.h" #include "Trace.h" #include "awt_Toolkit.h" #include "awt_Window.h" #include "awt_BitmapUtil.h" #include "D3DRenderQueue.h" // REMIND: move to awt_Component.h extern "C" HWND AwtComponent_GetHWnd(JNIEnv *env, jlong pData); /** * Initializes nativeWidth/Height fields of the SurfaceData object with * dimensions on the native surface. */ void D3DSD_SetNativeDimensions(JNIEnv *env, D3DSDOps *d3dsdo) { jobject sdObject; jint width, height; RETURN_IF_NULL(sdObject = env->NewLocalRef(d3dsdo->sdOps.sdObject)); if (d3dsdo->pResource != NULL) { width = d3dsdo->pResource->GetDesc()->Width; height = d3dsdo->pResource->GetDesc()->Height; } else { width = d3dsdo->width; height = d3dsdo->height; } JNU_SetFieldByName(env, NULL, sdObject, "nativeWidth", "I", width); JNU_SetFieldByName(env, NULL, sdObject, "nativeHeight", "I", height); env->DeleteLocalRef(sdObject); } void D3DSD_Flush(void *pData) { J2dTraceLn(J2D_TRACE_INFO, "D3DSD_Flush"); RETURN_IF_NULL(pData); D3DSDOps *d3dsdo = (D3DSDOps*)pData; if (d3dsdo->pResource != NULL) { D3DContext *pCtx; D3DPipelineManager *pMgr; d3dsdo->pResource->SetSDOps(NULL); if ((pMgr = D3DPipelineManager::GetInstance()) != NULL && SUCCEEDED(pMgr->GetD3DContext(d3dsdo->adapter, &pCtx))) { if (pCtx->GetResourceManager()) { pCtx->GetResourceManager()->ReleaseResource(d3dsdo->pResource); } } d3dsdo->pResource = NULL; } } void D3DSD_MarkLost(void *pData) { D3DSDOps *d3dsdo; jobject sdObject; JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2); J2dTraceLn(J2D_TRACE_INFO, "D3DSD_MarkLost"); RETURN_IF_NULL(pData); d3dsdo = (D3DSDOps*)pData; RETURN_IF_NULL(sdObject = env->NewLocalRef(d3dsdo->sdOps.sdObject)); JNU_CallMethodByName(env, NULL, sdObject, "setSurfaceLost", "(Z)V", JNI_TRUE); env->DeleteLocalRef(sdObject); } // ------------ generic SurfaceData.h functions ---------------- void D3DSD_Dispose(JNIEnv *env, SurfaceDataOps *ops) { D3DSDOps *d3dsdo = (D3DSDOps *)ops; RETURN_IF_NULL(d3dsdo); JNU_CallStaticMethodByName(env, NULL, "sun/java2d/d3d/D3DSurfaceData", "dispose", "(J)V", ptr_to_jlong(ops)); } /** * This is the implementation of the general surface LockFunc defined in * SurfaceData.h. */ jint D3DSD_Lock(JNIEnv *env, SurfaceDataOps *ops, SurfaceDataRasInfo *pRasInfo, jint lockflags) { JNU_ThrowInternalError(env, "D3DSD_Lock not implemented!"); return SD_FAILURE; } /** * This is the implementation of the general GetRasInfoFunc defined in * SurfaceData.h. */ void D3DSD_GetRasInfo(JNIEnv *env, SurfaceDataOps *ops, SurfaceDataRasInfo *pRasInfo) { JNU_ThrowInternalError(env, "D3DSD_GetRasInfo not implemented!"); } /** * This is the implementation of the general surface UnlockFunc defined in * SurfaceData.h. */ void D3DSD_Unlock(JNIEnv *env, SurfaceDataOps *ops, SurfaceDataRasInfo *pRasInfo) { JNU_ThrowInternalError(env, "D3DSD_Unlock not implemented!"); } // ------------ D3DSurfaceData's JNI methods ---------------- extern "C" { /* * Class: sun_java2d_d3d_D3DSurfaceData * Method: initOps * Signature: (III)V */ JNIEXPORT void JNICALL Java_sun_java2d_d3d_D3DSurfaceData_initOps (JNIEnv *env, jobject d3dsd, jint gdiScreen, jint width, jint height) { D3DPipelineManager *pMgr; D3DSDOps *d3dsdo = (D3DSDOps *)SurfaceData_InitOps(env, d3dsd, sizeof(D3DSDOps)); J2dTraceLn(J2D_TRACE_INFO, "D3DSurfaceData_initOps"); if (d3dsdo == NULL) { JNU_ThrowOutOfMemoryError(env, "creating native d3d ops"); return; } d3dsdo->sdOps.Lock = D3DSD_Lock; d3dsdo->sdOps.GetRasInfo = D3DSD_GetRasInfo; d3dsdo->sdOps.Unlock = D3DSD_Unlock; d3dsdo->sdOps.Dispose = D3DSD_Dispose; d3dsdo->xoff = 0; d3dsdo->yoff = 0; d3dsdo->width = width; d3dsdo->height = height; d3dsdo->pResource = NULL; d3dsdo->adapter = (pMgr = D3DPipelineManager::GetInstance()) == NULL ? D3DADAPTER_DEFAULT : pMgr->GetAdapterOrdinalForScreen(gdiScreen); } /* * Class: sun_java2d_d3d_D3DSurfaceData * Method: initTexture * Signature: (JZZ)Z */ JNIEXPORT jboolean JNICALL Java_sun_java2d_d3d_D3DSurfaceData_initTexture (JNIEnv *env, jobject d3dsd, jlong pData, jboolean isRTT, jboolean isOpaque) { HRESULT res; D3DSDOps *d3dsdo; D3DContext *pCtx; D3DPipelineManager *pMgr; D3DFORMAT format; J2dTraceLn(J2D_TRACE_INFO, "D3DSurfaceData_initTexture"); RETURN_STATUS_IF_NULL(d3dsdo = (D3DSDOps *)jlong_to_ptr(pData), JNI_FALSE); RETURN_STATUS_IF_NULL(pMgr = D3DPipelineManager::GetInstance(), JNI_FALSE); if (FAILED(res = pMgr->GetD3DContext(d3dsdo->adapter, &pCtx))) { D3DRQ_MarkLostIfNeeded(res, d3dsdo); return JNI_FALSE; } RETURN_STATUS_IF_NULL(pCtx->GetResourceManager(), JNI_FALSE); pCtx->GetResourceManager()->ReleaseResource(d3dsdo->pResource); d3dsdo->pResource = NULL; if (isRTT && isOpaque) { format = pCtx->GetPresentationParams()->BackBufferFormat; } else { format = D3DFMT_UNKNOWN; } res = pCtx->GetResourceManager()-> CreateTexture(d3dsdo->width, d3dsdo->height, isRTT, isOpaque, &format, 0/*usage*/, &d3dsdo->pResource); if (SUCCEEDED(res)) { J2dTraceLn1(J2D_TRACE_VERBOSE, " created texture pResource=%x", d3dsdo->pResource); d3dsdo->pResource->SetSDOps(d3dsdo); } else { D3DRQ_MarkLostIfNeeded(res, d3dsdo); } D3DSD_SetNativeDimensions(env, d3dsdo); return SUCCEEDED(res); } /* * Class: sun_java2d_d3d_D3DSurfaceData * Method: initPlain * Signature: (JZ)Z */ JNIEXPORT jboolean JNICALL Java_sun_java2d_d3d_D3DSurfaceData_initRTSurface (JNIEnv *env, jobject d3dsd, jlong pData, jboolean isOpaque) { HRESULT res; D3DSDOps *d3dsdo; D3DContext *pCtx; D3DPipelineManager *pMgr; D3DFORMAT format = D3DFMT_UNKNOWN; J2dTraceLn(J2D_TRACE_INFO, "D3DSurfaceData_initRTSurface"); RETURN_STATUS_IF_NULL(d3dsdo = (D3DSDOps *)jlong_to_ptr(pData), JNI_FALSE); RETURN_STATUS_IF_NULL(pMgr = D3DPipelineManager::GetInstance(), JNI_FALSE); if (FAILED(res = pMgr->GetD3DContext(d3dsdo->adapter, &pCtx))) { D3DRQ_MarkLostIfNeeded(res, d3dsdo); return JNI_FALSE; } RETURN_STATUS_IF_NULL(pCtx->GetResourceManager(), JNI_FALSE); pCtx->GetResourceManager()->ReleaseResource(d3dsdo->pResource); d3dsdo->pResource = NULL; res = pCtx->GetResourceManager()-> CreateRTSurface(d3dsdo->width, d3dsdo->height, isOpaque, FALSE /*lockable*/, &format, &d3dsdo->pResource); if (SUCCEEDED(res)) { J2dTraceLn1(J2D_TRACE_VERBOSE, " created RT surface pResource=0x%x", d3dsdo->pResource); d3dsdo->pResource->SetSDOps(d3dsdo); } else { D3DRQ_MarkLostIfNeeded(res, d3dsdo); } D3DSD_SetNativeDimensions(env, d3dsdo); return SUCCEEDED(res); } /* * Class: sun_java2d_d3d_D3DSurfaceData * Method: initFlipBackbuffer * Signature: (JJIZ)Z */ JNIEXPORT jboolean JNICALL Java_sun_java2d_d3d_D3DSurfaceData_initFlipBackbuffer (JNIEnv *env, jobject d3dsd, jlong pData, jlong pPeerData, jint numBuffers, jint swapEffect, jint vSyncType) { HRESULT res; D3DSDOps *d3dsdo; D3DContext *pCtx; D3DPipelineManager *pMgr; HWND hWnd; UINT presentationInterval; AwtComponent *pPeer; RECT r = { 0, 0, 0, 0 }; J2dTraceLn(J2D_TRACE_INFO, "D3DSurfaceData_initFlipBackbuffer"); RETURN_STATUS_IF_NULL(d3dsdo = (D3DSDOps *)jlong_to_ptr(pData), JNI_FALSE); RETURN_STATUS_IF_NULL(pMgr = D3DPipelineManager::GetInstance(), JNI_FALSE); RETURN_STATUS_IF_NULL(pPeer = (AwtComponent *)jlong_to_ptr(pPeerData), JNI_FALSE); hWnd = pPeer->GetHWnd(); if (!IsWindow(hWnd)) { J2dTraceLn(J2D_TRACE_WARNING, "D3DSurfaceData_initFlipBackbuffer: disposed component"); return JNI_FALSE; } pPeer->GetInsets(&r); d3dsdo->xoff = -r.left; d3dsdo->yoff = -r.top; if (FAILED(res = pMgr->GetD3DContext(d3dsdo->adapter, &pCtx))) { D3DRQ_MarkLostIfNeeded(res, d3dsdo); return JNI_FALSE; } RETURN_STATUS_IF_NULL(pCtx->GetResourceManager(), JNI_FALSE); pCtx->GetResourceManager()->ReleaseResource(d3dsdo->pResource); d3dsdo->pResource = NULL; d3dsdo->swapEffect = (D3DSWAPEFFECT)swapEffect; // in full-screen mode we should v-sync if (pCtx->GetPresentationParams()->Windowed) { if (vSyncType == VSYNC_ON) { presentationInterval = D3DPRESENT_INTERVAL_ONE; J2dTraceLn(J2D_TRACE_VERBOSE, " windowed, forced interval: ONE"); } else { presentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; J2dTraceLn(J2D_TRACE_VERBOSE, " windowed, default interval: IMMEDIATE"); } // REMIND: this is a workaround for the current issue // we have with non-copy flip chains: since we can not specify // the dest rectangle for Present for these modes, the result of // Present(NULL, NULL) is scaled to the client area. if (d3dsdo->xoff != 0 || d3dsdo->yoff != 0) { d3dsdo->swapEffect = D3DSWAPEFFECT_COPY; } } else { if (vSyncType == VSYNC_OFF) { presentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; J2dTraceLn(J2D_TRACE_VERBOSE, " full-screen, forced interval: IMMEDIATE"); } else { presentationInterval = D3DPRESENT_INTERVAL_ONE; J2dTraceLn(J2D_TRACE_VERBOSE, " full-screen, default interval: ONE"); } } res = pCtx->GetResourceManager()-> CreateSwapChain(hWnd, numBuffers, d3dsdo->width, d3dsdo->height, d3dsdo->swapEffect, presentationInterval, &d3dsdo->pResource); if (SUCCEEDED(res)) { J2dTraceLn1(J2D_TRACE_VERBOSE, " created swap chain pResource=0x%x", d3dsdo->pResource); d3dsdo->pResource->SetSDOps(d3dsdo); } else { D3DRQ_MarkLostIfNeeded(res, d3dsdo); } D3DSD_SetNativeDimensions(env, d3dsdo); return SUCCEEDED(res); } /* * Class: sun_java2d_d3d_D3DSurfaceData * Method: dbGetPixelNative * Signature: (JII)I */ JNIEXPORT jint JNICALL Java_sun_java2d_d3d_D3DSurfaceData_dbGetPixelNative (JNIEnv *env, jclass clazz, jlong pData, jint x, jint y) { HRESULT res; D3DSDOps *d3dsdo; D3DContext *pCtx; D3DPipelineManager *pMgr; D3DResource *pLockableRes; jint pixel = 0; J2dTraceLn(J2D_TRACE_INFO, "D3DSurfaceData_dbGetPixelNative"); RETURN_STATUS_IF_NULL(d3dsdo = (D3DSDOps *)jlong_to_ptr(pData), pixel); RETURN_STATUS_IF_NULL(d3dsdo->pResource, pixel); RETURN_STATUS_IF_NULL(pMgr = D3DPipelineManager::GetInstance(), pixel); if (FAILED(res = pMgr->GetD3DContext(d3dsdo->adapter, &pCtx))) { D3DRQ_MarkLostIfNeeded(res, d3dsdo); return pixel; } RETURN_STATUS_IF_NULL(pCtx->GetResourceManager(), 0); IDirect3DDevice9 *pd3dDevice = pCtx->Get3DDevice(); IDirect3DSurface9 *pSrc = d3dsdo->pResource->GetSurface(); D3DFORMAT srcFmt = d3dsdo->pResource->GetDesc()->Format; pCtx->UpdateState(STATE_OTHEROP); res = pCtx->GetResourceManager()-> GetLockableRTSurface(1, 1, srcFmt, &pLockableRes); if (SUCCEEDED(res)) { IDirect3DSurface9 *pTmpSurface; RECT srcRect = { x, y, x+1, y+1}; RECT dstRect = { 0l, 0l, 1, 1 }; pTmpSurface = pLockableRes->GetSurface(); res = pd3dDevice->StretchRect(pSrc, &srcRect, pTmpSurface, &dstRect, D3DTEXF_NONE); if (SUCCEEDED(res)) { D3DLOCKED_RECT lRect; res = pTmpSurface->LockRect(&lRect, &dstRect, D3DLOCK_NOSYSLOCK); if (SUCCEEDED(res)) { if (srcFmt == D3DFMT_X8R8G8B8) { pixel = *(jint*)lRect.pBits; } else { pixel = *(unsigned short*)lRect.pBits; } pTmpSurface->UnlockRect(); } } } D3DRQ_MarkLostIfNeeded(res, d3dsdo); return pixel; } /* * Class: sun_java2d_d3d_D3DSurfaceData * Method: dbSetPixelNative * Signature: (JIII)V */ JNIEXPORT void JNICALL Java_sun_java2d_d3d_D3DSurfaceData_dbSetPixelNative (JNIEnv *env, jclass clazz, jlong pData, jint x, jint y, jint pixel) { HRESULT res; D3DSDOps *d3dsdo; D3DResource *pLockableRes; D3DContext *pCtx; D3DPipelineManager *pMgr; J2dTraceLn(J2D_TRACE_INFO, "D3DSurfaceData_dbSetPixelNative"); RETURN_IF_NULL(d3dsdo = (D3DSDOps *)jlong_to_ptr(pData)); RETURN_IF_NULL(d3dsdo->pResource); RETURN_IF_NULL(pMgr = D3DPipelineManager::GetInstance()); if (FAILED(res = pMgr->GetD3DContext(d3dsdo->adapter, &pCtx))) { D3DRQ_MarkLostIfNeeded(res, d3dsdo); return; } RETURN_IF_NULL(pCtx->GetResourceManager()); IDirect3DDevice9 *pd3dDevice = pCtx->Get3DDevice(); IDirect3DSurface9 *pSrc = d3dsdo->pResource->GetSurface(); D3DFORMAT srcFmt = d3dsdo->pResource->GetDesc()->Format; pCtx->UpdateState(STATE_OTHEROP); res = pCtx->GetResourceManager()-> GetLockableRTSurface(1, 1, srcFmt, &pLockableRes); if (SUCCEEDED(res)) { IDirect3DSurface9 *pTmpSurface; D3DLOCKED_RECT lRect; RECT srcRect = { 0l, 0l, 1, 1 }; RECT dstRect = { x, y, x+1, y+1}; pTmpSurface = pLockableRes->GetSurface(); res = pTmpSurface->LockRect(&lRect, &srcRect, D3DLOCK_NOSYSLOCK); if (SUCCEEDED(res)) { if (srcFmt == D3DFMT_X8R8G8B8) { *(jint*)lRect.pBits = pixel; } else { *(unsigned short*)lRect.pBits = (unsigned short)pixel; } pTmpSurface->UnlockRect(); res = pd3dDevice->StretchRect(pTmpSurface, &srcRect, pSrc, &dstRect, D3DTEXF_NONE); } } D3DRQ_MarkLostIfNeeded(res, d3dsdo); } /* * Class: sun_java2d_d3d_D3DSurfaceData * Method: getNativeResourceNative * Signature: (JI)J */ JNIEXPORT jlong JNICALL Java_sun_java2d_d3d_D3DSurfaceData_getNativeResourceNative (JNIEnv *env, jclass d3sdc, jlong pData, jint resType) { D3DSDOps *d3dsdo; J2dTraceLn(J2D_TRACE_INFO, "D3DSurfaceData_getNativeResourceNative") RETURN_STATUS_IF_NULL(d3dsdo = (D3DSDOps *)jlong_to_ptr(pData), 0L); if (resType == D3D_DEVICE_RESOURCE) { HRESULT res; D3DPipelineManager *pMgr; D3DContext *pCtx; RETURN_STATUS_IF_NULL(pMgr = D3DPipelineManager::GetInstance(), 0L); if (FAILED(res = pMgr->GetD3DContext(d3dsdo->adapter, &pCtx))) { D3DRQ_MarkLostIfNeeded(res, d3dsdo);<|fim▁hole|> } return ptr_to_jlong(pCtx->Get3DDevice()); } RETURN_STATUS_IF_NULL(d3dsdo->pResource, 0L); if (resType == RT_PLAIN || resType == RT_TEXTURE) { return ptr_to_jlong(d3dsdo->pResource->GetSurface()); } if (resType == TEXTURE) { return ptr_to_jlong(d3dsdo->pResource->GetTexture()); } if (resType == FLIP_BACKBUFFER) { return ptr_to_jlong(d3dsdo->pResource->GetSwapChain()); } return 0L; } /* * Class: sun_java2d_d3d_D3DSurfaceData * Method: updateWindowAccelImpl * Signature: (JJII)Z */ JNIEXPORT jboolean JNICALL Java_sun_java2d_d3d_D3DSurfaceData_updateWindowAccelImpl (JNIEnv *env, jclass clazz, jlong pd3dsd, jlong pData, jint w, jint h) { HRESULT res; AwtWindow *window; HBITMAP hBitmap = NULL; D3DSDOps *d3dsdo; D3DResource *pSrcRes; D3DContext *pCtx; D3DPipelineManager *pMgr; D3DResource *pLockableRes = NULL; IDirect3DSurface9 *pTmpSurface = NULL; IDirect3DDevice9 *pd3dDevice = NULL; D3DLOCKED_RECT lockedRect; J2dTraceLn(J2D_TRACE_ERROR, "D3DSurfaceData_updateWindowAccelImpl"); if (w <= 0 || h <= 0) { return JNI_TRUE; } RETURN_STATUS_IF_NULL(window = (AwtWindow *)jlong_to_ptr(pData), JNI_FALSE); RETURN_STATUS_IF_NULL(d3dsdo = (D3DSDOps *)jlong_to_ptr(pd3dsd), JNI_FALSE); RETURN_STATUS_IF_NULL(pMgr = D3DPipelineManager::GetInstance(), JNI_FALSE); RETURN_STATUS_IF_NULL(pSrcRes = d3dsdo->pResource, JNI_FALSE); if (FAILED(res = pMgr->GetD3DContext(d3dsdo->adapter, &pCtx))) { D3DRQ_MarkLostIfNeeded(res, d3dsdo); return JNI_FALSE; } RETURN_STATUS_IF_NULL(pd3dDevice = pCtx->Get3DDevice(), JNI_FALSE); pCtx->UpdateState(STATE_OTHEROP); res = pCtx->GetResourceManager()-> GetBlitOSPSurface(pSrcRes->GetDesc()->Width, pSrcRes->GetDesc()->Height, pSrcRes->GetDesc()->Format, &pLockableRes); if (FAILED(res)) { D3DRQ_MarkLostIfNeeded(res, d3dsdo); return JNI_FALSE; } pTmpSurface = pLockableRes->GetSurface(); res = pd3dDevice->GetRenderTargetData(pSrcRes->GetSurface(), pTmpSurface); if (FAILED(res)) { D3DRQ_MarkLostIfNeeded(res, d3dsdo); return JNI_FALSE; } res = pTmpSurface->LockRect(&lockedRect, NULL, D3DLOCK_NOSYSLOCK); if (SUCCEEDED(res)) { // REMIND: commented until translucent window support is integrated // hBitmap = // BitmapUtil::CreateBitmapFromARGBPre(w, h, // lockedRect.Pitch, // (int*)lockedRect.pBits); pTmpSurface->UnlockRect(); } RETURN_STATUS_IF_NULL(hBitmap, JNI_FALSE); // REMIND: commented until translucent window support is integrated // window->UpdateWindow(env, NULL, w, h, hBitmap); // hBitmap is released in UpdateWindow return JNI_TRUE; } }<|fim▁end|>
return 0L;
<|file_name|>isEmpty.js<|end_file_name|><|fim▁begin|>// @flow import getKeys from "./getKeys"; import type {Composite} from "./types"; /** * Returns true if composite has no own enumerable keys (is empty) or false * otherwise */ const isEmpty = (composite: Composite): boolean =><|fim▁hole|>export default isEmpty;<|fim▁end|>
getKeys(composite).length === 0;
<|file_name|>tmp-04.cpp<|end_file_name|><|fim▁begin|>#include <cstdlib> #include <iostream> #include <vector> #include <sys/time.h> #include <omp.h> #include <hbwmalloc.h><|fim▁hole|> double drand() { return double(rand()) / double(RAND_MAX); } double wctime() { struct timeval tv; gettimeofday(&tv,NULL); return (double)tv.tv_sec + (double)tv.tv_usec*1e-6; } const int n_task =2048; const int n_time = 8192; typedef double *double_ptr; typedef double task_ar[n_task]; void compute (task_ar aar, task_ar bar, int n_time, int n_task) { const int t_unroll=4; for (int t = 0; t < n_time; t+=t_unroll) { for(int t2=0;t2<t_unroll; ++t2) { for (int i = 1; i < n_task-1; ++i) { double l = aar[i-1]; double c = aar[i]; double r = aar[i+1]; c = 0.2*l+0.4*c+0.3*r+0.1; l = 0.4*l+0.3*c+0.2*r+0.1; r = 0.3*l+0.2*c+0.4*r+0.1; c = 0.2*l+0.4*c+0.3*r+0.1; l = 0.4*l+0.3*c+0.2*r+0.1; r = 0.3*l+0.2*c+0.4*r+0.1; c = 0.2*l+0.4*c+0.3*r+0.1; l = 0.4*l+0.3*c+0.2*r+0.1; r = 0.3*l+0.2*c+0.4*r+0.1; bar[i] = c; } for (int i = 1; i < n_task-1; ++i) { double l = bar[i-1]; double c = bar[i]; double r = bar[i+1]; c = 0.2*l+0.4*c+0.3*r+0.1; l = 0.4*l+0.3*c+0.2*r+0.1; r = 0.3*l+0.2*c+0.4*r+0.1; c = 0.2*l+0.4*c+0.3*r+0.1; l = 0.4*l+0.3*c+0.2*r+0.1; r = 0.3*l+0.2*c+0.4*r+0.1; c = 0.2*l+0.4*c+0.3*r+0.1; l = 0.4*l+0.3*c+0.2*r+0.1; r = 0.3*l+0.2*c+0.4*r+0.1; aar[i] = c; } } #pragma omp barrier } } int main () { const int n_thre = omp_get_max_threads(); cout << "n_thre " << n_thre << " " <<flush; vector<double_ptr> ptra; vector<double_ptr> ptrb; for (int i=0;i<n_thre;++i) { ptra.push_back((double*)hbw_malloc(sizeof(double) * n_task)); ptrb.push_back((double*)hbw_malloc(sizeof(double) * n_task)); for (int x=0;x<n_task;++x) { ptra[i][x] = drand(); ptrb[i][x] = drand(); } } double time_begin = wctime(); #pragma omp parallel { int tid=omp_get_thread_num(); compute(ptra[tid], ptrb[tid], n_time, n_task); } double time_end = wctime(); double gflop = double(108)/1e9 * n_time * n_task * n_thre; double sum = 0; for (int i=0;i<n_thre;++i) { for (int x=0;x<n_task;++x) { sum += ptra[i][x]; } } cout << sum << "\tGflop " << gflop << "\ttime " << (time_end - time_begin) << "\tGflops " << gflop/(time_end - time_begin) << " n_barrier " << n_time << endl; }<|fim▁end|>
using namespace std;
<|file_name|>scope_table_builder.rs<|end_file_name|><|fim▁begin|>//! Build the scope table and make sure all variables/symbols can be resolved use driver::interner::Ident; use driver::session; use driver::symbol_table::SymbolTable; use front::ast::*; use front::ast::visit::*; struct ScopeTableBuilder<'a> { current_scope: Option<NodeId>, current_symbol: Option<Ident>, sytbl: &'a SymbolTable } impl<'a> ScopeTableBuilder<'a> { fn new(sytbl: &'a SymbolTable) -> ScopeTableBuilder<'a> { ScopeTableBuilder { current_scope: None, current_symbol: None, sytbl: sytbl } } fn init_function_scope(&mut self, scope: NodeId) { let current_symbol = self.current_symbol .expect("current symbol is None"); let bindings; { // Get the function's arguments let symbol = self.sytbl.lookup_symbol(&current_symbol) .expect("current symbol is not registered"); bindings = if let Symbol::Function { ref bindings, .. } = symbol { bindings.clone() } else { panic!("current symbol is not a function"); // shouldn't happen }; } // Register arguments in scope table for binding in bindings { self.sytbl.register_variable(scope, &binding).unwrap_or_else(|_| { fatal_at!("multiple parameters with name: `{}`", binding.name; &binding.name); }); } } fn resolve_call(&self, expr: &Node<Expression>) { // Get function name let name = if let Expression::Variable { ref name } = **expr { name } else { fatal_at!("cannot call non-function"; expr); return }; // Look up the symbol in the symbol table let symbol = if let Some(symbol) = self.sytbl.lookup_symbol(name) { symbol } else { fatal_at!("no such function: `{}`", &name; expr); return }; // Verify the symbol is a function if let Symbol::Function { .. } = symbol { return // Everything's okay } else { fatal_at!("cannot call non-function"; expr) } } fn resolve_variable(&self, name: &Node<Ident>) { let current_scope = self.current_scope .expect("resolving a variable without a containing scope"); match self.sytbl.resolve_variable(current_scope, name) { Some(..) => {}, None => fatal_at!("variable `{}` not declared", &name; name) }; } fn resolve_declaration(&mut self, binding: &Node<Binding>) { let scope = self.current_scope .expect("resolving a declaration without a containing scope"); match self.sytbl.register_variable(scope, binding) { Ok(..) => {}, Err(..) => fatal_at!("cannot redeclare `{}`", binding.name; binding) }; } } impl<'v> Visitor<'v> for ScopeTableBuilder<'v> { fn visit_symbol(&mut self, symbol: &'v Node<Symbol>) { // Set the current symbol (needed in visit_block) self.current_symbol = Some(symbol.get_ident()); walk_symbol(self, symbol) } fn visit_block(&mut self, block: &'v Node<Block>) { // Register the new block self.sytbl.register_scope(block.id).unwrap(); // Set the parent if present if let Some(parent) = self.current_scope { self.sytbl.set_parent_scope(block.id, parent); } else { // Top-level block of a function -> insert args into symbol table self.init_function_scope(block.id); } // Set the current scope (needed in visit_statement/expression) let prev_scope = self.current_scope; self.current_scope = Some(block.id); // Process all statements & the optional expression walk_block(self, block); // Reset the current scope to its old value self.current_scope = prev_scope; } fn visit_statement(&mut self, stmt: &'v Node<Statement>) { if let Statement::Declaration { ref binding, .. } = **stmt { self.resolve_declaration(binding); } walk_statement(self, stmt) } fn visit_expression(&mut self, expr: &'v Node<Expression>) { match **expr { Expression::Call { ref func, .. } => { self.resolve_call(func); return // Don't visit sub-expressions }, Expression::Variable { ref name } => { self.resolve_variable(name); }, _ => {}<|fim▁hole|> // Continue walking the expression walk_expression(self, expr) } } pub fn run(program: &[Node<Symbol>]) { let symbol_table = &session().symbol_table; let mut visitor = ScopeTableBuilder::new(symbol_table); walk_program(&mut visitor, program); session().abort_if_errors(); }<|fim▁end|>
}
<|file_name|>AgendaWizardDialogResources.py<|end_file_name|><|fim▁begin|># # This file is part of the LibreOffice project. # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. #<|fim▁hole|># with this work for additional information regarding copyright # ownership. The ASF 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 . # class AgendaWizardDialogResources(object): RID_AGENDAWIZARDDIALOG_START = 5000 RID_AGENDAWIZARDROADMAP_START = 5049 RID_COMMON_START = 500 SECTION_ITEMS = "AGENDA_ITEMS" SECTION_TOPICS = "AGENDA_TOPICS" SECTION_MINUTES_ALL = "MINUTES_ALL" SECTION_MINUTES = "MINUTES" def __init__(self, oWizardResource): self.resAgendaWizardDialog_title = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 1) self.resoptMakeChanges_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 2) self.reslblTemplateName_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 3) self.reslblTemplatePath_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 4) self.reslblProceed_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 5) self.reslblTitle1_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 6) self.reslblTitle3_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 7) self.reslblTitle2_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 8) self.reslblTitle4_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 9) self.reslblTitle5_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 10) self.reslblTitle6_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 11) self.reschkMinutes_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 12) self.reslblHelp1_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 13) self.reslblTime_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 14) self.reslblTitle_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 15) self.reslblLocation_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 16) self.reslblHelp2_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 17) self.resbtnTemplatePath_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 18) self.resoptCreateAgenda_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 19) self.reslblHelp6_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 20) self.reslblTopic_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 21) self.reslblResponsible_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 22) self.reslblDuration_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 23) self.reschkConvenedBy_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 24) self.reschkPresiding_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 25) self.reschkNoteTaker_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 26) self.reschkTimekeeper_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 27) self.reschkAttendees_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 28) self.reschkObservers_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 29) self.reschkResourcePersons_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 30) self.reslblHelp4_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 31) self.reschkMeetingTitle_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 32) self.reschkRead_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 33) self.reschkBring_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 34) self.reschkNotes_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 35) self.reslblHelp3_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 36) self.reslblDate_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 38) self.reslblHelpPg6_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 39) self.reslblPageDesign_value = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 40) self.resDefaultFilename = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 41) self.resDefaultFilename = self.resDefaultFilename[:-4] + ".ott" self.resDefaultTitle = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 42) self.resErrSaveTemplate = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 43) self.resPlaceHolderTitle = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 44) self.resPlaceHolderDate = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 45) self.resPlaceHolderTime = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 46) self.resPlaceHolderLocation = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 47) self.resPlaceHolderHint = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 48) self.resErrOpenTemplate = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 56) self.itemMeetingType = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 57) self.itemBring = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 58) self.itemRead = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 59) self.itemNote = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 60) self.itemCalledBy = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 61) self.itemFacilitator = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 62) self.itemAttendees = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 63) self.itemNotetaker = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 64) self.itemTimekeeper = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 65) self.itemObservers = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 66) self.itemResource = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 67) self.resButtonInsert = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 68) self.resButtonRemove = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 69) self.resButtonUp = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 70) self.resButtonDown = oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 71) #Create a dictionary for localised string in the template self.dictConstants = { "#datetitle#" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 72), "#timetitle#" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 73), "#locationtitle#" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 74), "#topics#" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 75), "#num.#" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 76), "#topicheader#" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 77), "#responsibleheader#" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 78), "#timeheader#" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 79), "#additional-information#" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 80), "#minutes-for#" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 81), "#discussion#" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 82), "#conclusion#" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 83), "#to-do#" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 84), "#responsible-party#" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 85), "#deadline#" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 86)} #Create a dictionary for localising the page design self.dictPageDesign = { "Blue" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 87), "Classic" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 88), "Colorful" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 89), "Elegant" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 90), "Green" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 91), "Grey" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 92), "Modern" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 93), "Orange" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 94), "Red" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 95), "Simple" : oWizardResource.getResText( AgendaWizardDialogResources.RID_AGENDAWIZARDDIALOG_START + 96)} #Common Resources self.resOverwriteWarning = oWizardResource.getResText( AgendaWizardDialogResources.RID_COMMON_START + 19) self.resTemplateDescription = oWizardResource.getResText( AgendaWizardDialogResources.RID_COMMON_START + 20) self.RoadmapLabels = [] self.RoadmapLabels.append(oWizardResource.getResText(AgendaWizardDialogResources.RID_AGENDAWIZARDROADMAP_START + 1)) self.RoadmapLabels.append(oWizardResource.getResText(AgendaWizardDialogResources.RID_AGENDAWIZARDROADMAP_START + 2)) self.RoadmapLabels.append(oWizardResource.getResText(AgendaWizardDialogResources.RID_AGENDAWIZARDROADMAP_START + 3)) self.RoadmapLabels.append(oWizardResource.getResText(AgendaWizardDialogResources.RID_AGENDAWIZARDROADMAP_START + 4)) self.RoadmapLabels.append(oWizardResource.getResText(AgendaWizardDialogResources.RID_AGENDAWIZARDROADMAP_START + 5)) self.RoadmapLabels.append(oWizardResource.getResText(AgendaWizardDialogResources.RID_AGENDAWIZARDROADMAP_START + 6))<|fim▁end|>
# This file incorporates work covered by the following license notice: # # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed
<|file_name|>hook_utils.py<|end_file_name|><|fim▁begin|>import re # flag that caches the information whether Windows firewall is running or not fireWallState = None # this function modifies all necessary run settings to make it possible to hook into # the application compiled by Creator def modifyRunSettingsForHookInto(projectName, port): prepareBuildSettings(1, 0)<|fim▁hole|> switchToBuildOrRunSettingsFor(1, 0, ProjectSettings.BUILD) qtVersion, mkspec, qtBinPath, qtLibPath = getQtInformationForBuildSettings(True) if None in (qtVersion, mkspec, qtBinPath, qtLibPath): test.fatal("At least one of the Qt information returned None - leaving...", "Qt version: %s, mkspec: %s, Qt BinPath: %s, Qt LibPath: %s" % (qtVersion, mkspec, qtBinPath, qtLibPath)) return False qtVersion = ".".join(qtVersion.split(".")[:2]) switchToBuildOrRunSettingsFor(1, 0, ProjectSettings.RUN) result = __configureCustomExecutable__(projectName, port, mkspec, qtVersion) if result: clickButton(waitForObject("{window=':Qt Creator_Core::Internal::MainWindow' text='Details' " "type='Utils::DetailsButton' unnamed='1' visible='1' " "leftWidget={type='QLabel' text~='Us(e|ing) <b>Build Environment</b>' unnamed='1' visible='1'}}")) envVarsTableView = waitForObject("{type='QTableView' visible='1' unnamed='1'}") model = envVarsTableView.model() changingVars = [] for index in dumpIndices(model): # get var name envVarsTableView.scrollTo(index) varName = str(model.data(index).toString()) # if its a special SQUISH var simply unset it, SQUISH_LIBQTDIR and PATH will be replaced with Qt paths if varName == "PATH": test.log("Replacing PATH with '%s'" % qtBinPath) changingVars.append("PATH=%s" % qtBinPath) elif varName.find("SQUISH") == 0: if varName == "SQUISH_LIBQTDIR": if platform.system() in ('Microsoft', 'Windows'): replacement = qtBinPath else: replacement = qtLibPath test.log("Replacing SQUISH_LIBQTDIR with '%s'" % replacement) changingVars.append("SQUISH_LIBQTDIR=%s" % replacement) else: changingVars.append(varName) #test.log("Unsetting %s for run" % varName) clickButton(waitForObject("{text='Batch Edit...' type='QPushButton' unnamed='1' visible='1' " "window=':Qt Creator_Core::Internal::MainWindow'}")) editor = waitForObject("{type='TextEditor::SnippetEditorWidget' unnamed='1' visible='1' " "window=':Edit Environment_ProjectExplorer::EnvironmentItemsDialog'}") typeLines(editor, changingVars) clickButton(waitForObject("{text='OK' type='QPushButton' unnamed='1' visible='1' " "window=':Edit Environment_ProjectExplorer::EnvironmentItemsDialog'}")) switchViewTo(ViewConstants.EDIT) return result def modifyRunSettingsForHookIntoQtQuickUI(workingDir, projectName, port): switchViewTo(ViewConstants.PROJECTS) switchToBuildOrRunSettingsFor(1, 0, ProjectSettings.RUN, True) qtVersion, mkspec, qtLibPath, qmake = getQtInformationForQmlProject() if None in (qtVersion, mkspec, qtLibPath, qmake): test.fatal("At least one of the Qt information returned None - leaving...", "Qt version: %s, mkspec: %s, Qt LibPath: %s, qmake: '%s'" % (qtVersion, mkspec, qtLibPath, qmake)) return None squishPath = getSquishPath(mkspec, qtVersion) if squishPath == None: test.warning("Could not determine the Squish path for %s/%s" % (qtVersion, mkspec), "Using fallback of pushing STOP inside Creator.") return None test.log("Using (QtVersion/mkspec) %s/%s with SquishPath %s" % (qtVersion, mkspec, squishPath)) if platform.system() == "Darwin": qmlViewer = os.path.abspath(os.path.dirname(qmake) + "/QMLViewer.app") else: qmlViewer = os.path.abspath(os.path.dirname(qmake) + "/qmlviewer") if platform.system() in ('Microsoft', 'Windows'): qmlViewer = qmlViewer + ".exe" addRunConfig = waitForObject("{container={window=':Qt Creator_Core::Internal::MainWindow' " "type='ProjectExplorer::Internal::RunSettingsWidget' unnamed='1' " "visible='1'} occurrence='2' text='Add' type='QPushButton' " "unnamed='1' visible='1'}") clickButton(addRunConfig) activateItem(waitForObject("{type='QMenu' visible='1' unnamed='1'}"), "Custom Executable") exePathChooser = waitForObject("{buddy={window=':Qt Creator_Core::Internal::MainWindow' " "text='Command:' type='QLabel' unnamed='1' visible='1'} " "type='Utils::PathChooser' unnamed='1' visible='1'}") exeLineEd = getChildByClass(exePathChooser, "Utils::BaseValidatingLineEdit") argLineEd = waitForObject("{buddy={window=':Qt Creator_Core::Internal::MainWindow' " "type='QLabel' text='Arguments:' visible='1'} type='QLineEdit' " "unnamed='1' visible='1'}") wdPathChooser = waitForObject("{buddy={window=':Qt Creator_Core::Internal::MainWindow' " "text='Working directory:' type='QLabel'} " "type='Utils::PathChooser' unnamed='1' visible='1'}") wdLineEd = getChildByClass(wdPathChooser, "Utils::BaseValidatingLineEdit") startAUT = os.path.abspath(squishPath + "/bin/startaut") if platform.system() in ('Microsoft', 'Windows'): startAUT = startAUT + ".exe" projectPath = os.path.abspath("%s/%s" % (workingDir, projectName)) replaceEditorContent(exeLineEd, startAUT) replaceEditorContent(argLineEd, "--verbose --port=%d %s %s.qml" % (port, qmlViewer, projectName)) replaceEditorContent(wdLineEd, projectPath) clickButton(waitForObject("{text='Details' type='Utils::DetailsButton' unnamed='1' visible='1' " "window=':Qt Creator_Core::Internal::MainWindow' " "leftWidget={type='QLabel' text~='Us(e|ing) <b>Build Environment</b>'" " unnamed='1' visible='1'}}")) row = 0 for varName in ("PATH", "SQUISH_LIBQTDIR"): __addVariableToRunEnvironment__(varName, qtLibPath, row) row = row + 1 if not platform.system() in ('Microsoft', 'Windows', 'Darwin'): __addVariableToRunEnvironment__("LD_LIBRARY_PATH", qtLibPath, 0) if platform.system() == "Darwin": __addVariableToRunEnvironment__("DYLD_FRAMEWORK_PATH", qtLibPath, 0) if not platform.system() in ('Microsoft', 'Windows'): __addVariableToRunEnvironment__("DISPLAY", ":0.0", 0) result = qmlViewer switchViewTo(ViewConstants.EDIT) return result # this helper method must be called on the run settings page of a Qt Quick UI with DetailsWidget # for the run settings already opened - it won't work on other views because of a different layout def __addVariableToRunEnvironment__(name, value, row): clickButton(waitForObject("{text='Add' type='QPushButton' unnamed='1' visible='1' " "container={window=':Qt Creator_Core::Internal::MainWindow' " "type='Utils::DetailsWidget' unnamed='1' visible='1' occurrence='2'}}")) varNameLineEd = waitForObject("{type='QExpandingLineEdit' visible='1' unnamed='1'}") replaceEditorContent(varNameLineEd, name) valueLineEd = __doubleClickQTableView__(":Qt Creator_QTableView", row, 1) replaceEditorContent(valueLineEd, value) type(valueLineEd, "<Return>") def __getMkspecFromQMakeConf__(qmakeConf): if qmakeConf==None or not os.path.exists(qmakeConf): return None if not platform.system() in ('Microsoft', 'Windows'): return os.path.basename(os.path.realpath(os.path.dirname(qmakeConf))) mkspec = None file = codecs.open(qmakeConf, "r", "utf-8") for line in file: if "QMAKESPEC_ORIGINAL" in line: mkspec = line.split("=")[1] break file.close() if mkspec == None: test.warning("Could not determine mkspec from '%s'" % qmakeConf) return None return os.path.basename(mkspec) def __getMkspecFromQmake__(qmakeCall): QmakeConfPath = getOutputFromCmdline("%s -query QMAKE_MKSPECS" % qmakeCall).strip() for tmpPath in QmakeConfPath.split(os.pathsep): tmpPath = tmpPath + os.sep + "default" + os.sep +"qmake.conf" result = __getMkspecFromQMakeConf__(tmpPath) if result != None: return result.strip() test.warning("Could not find qmake.conf inside provided QMAKE_MKSPECS path", "QMAKE_MKSPECS returned: '%s'" % QmakeConfPath) return None # helper that double clicks the table view at specified row and column # returns the QExpandingLineEdit (the editable table cell) def __doubleClickQTableView__(qtableView, row, column): doubleClick(waitForObject("{container='%s' " "type='QModelIndex' row='%d' column='%d'}" % (qtableView, row, column)), 5, 5, 0, Qt.LeftButton) return waitForObject("{type='QExpandingLineEdit' visible='1' unnamed='1'}") # this function configures the custom executable onto the run settings page (using startaut from Squish) def __configureCustomExecutable__(projectName, port, mkspec, qmakeVersion): startAUT = getSquishPath(mkspec, qmakeVersion) if startAUT == None: test.warning("Something went wrong determining the right Squish for %s / %s combination - " "using fallback without hooking into subprocess." % (qmakeVersion, mkspec)) return False else: startAUT = os.path.abspath(startAUT + "/bin/startaut") if platform.system() in ('Microsoft', 'Windows'): startAUT += ".exe" if not os.path.exists(startAUT): test.warning("Configured Squish directory seems to be missing - using fallback without hooking into subprocess.", "Failed to find '%s'" % startAUT) return False addButton = waitForObject("{container={window=':Qt Creator_Core::Internal::MainWindow' " "type='ProjectExplorer::Internal::RunSettingsWidget' unnamed='1' " "visible='1'} occurrence='2' text='Add' type='QPushButton' " "unnamed='1' visible='1'}") clickButton(addButton) addMenu = addButton.menu() activateItem(waitForObjectItem(objectMap.realName(addMenu), 'Custom Executable')) exePathChooser = waitForObject("{buddy={window=':Qt Creator_Core::Internal::MainWindow' text='Command:' type='QLabel' unnamed='1' visible='1'} " "type='Utils::PathChooser' unnamed='1' visible='1'}", 2000) exeLineEd = getChildByClass(exePathChooser, "Utils::BaseValidatingLineEdit") argLineEd = waitForObject("{buddy={window=':Qt Creator_Core::Internal::MainWindow' " "type='QLabel' text='Arguments:' visible='1'} type='QLineEdit' " "unnamed='1' visible='1'}") wdPathChooser = waitForObject("{buddy={window=':Qt Creator_Core::Internal::MainWindow' text='Working directory:' type='QLabel'} " "type='Utils::PathChooser' unnamed='1' visible='1'}") replaceEditorContent(exeLineEd, startAUT) # the following is currently only configured for release builds (will be enhanced later) if platform.system() in ('Microsoft', 'Windows'): debOrRel = "release" + os.sep else: debOrRel = "" replaceEditorContent(argLineEd, "--verbose --port=%d %s%s" % (port, debOrRel, projectName)) return True # function that retrieves a specific child object by its class # this is sometimes the best way to avoid using waitForObject() on objects that # occur more than once - but could easily be found by using a compound object # (e.g. search for Utils::PathChooser instead of Utils::BaseValidatingLineEdit and get the child) def getChildByClass(parent, classToSearchFor, occurence=1): children = [child for child in object.children(parent) if className(child) == classToSearchFor] if len(children) < occurence: return None else: return children[occurence - 1] # get the Squish path that is needed to successfully hook into the compiled app def getSquishPath(mkspec, qmakev): qmakev = ".".join(qmakev.split(".")[0:2]) path = None mapfile = os.environ.get("QT_SQUISH_MAPFILE") if mapfile and os.path.isfile(mapfile): file = codecs.open(mapfile, "r", "utf-8") pattern = re.compile("\s+") for line in file: if line[0] == "#": continue tmp = pattern.split(line, 2) if tmp[0].strip("'\"") == qmakev and tmp[1].strip("'\"") == mkspec: path = os.path.expanduser(tmp[2].strip().strip("'\"")) break file.close() else: if not mapfile: test.warning("Environment variable QT_SQUISH_MAPFILE isn't set. Using fallback test data.", "See the README file how to use it.") else: test.warning("Environment variable QT_SQUISH_MAPFILE isn't set correctly or map file does not exist. Using fallback test data.", "See the README file how to use it.") # try the test data fallback mapData = testData.dataset(os.getcwd() + "/../../shared_data/qt_squish_mapping.tsv") for row, record in enumerate(mapData): if testData.field(record, "qtversion") == qmakev and testData.field(record, "mkspec") == mkspec: path = os.path.expanduser(testData.field(record, "path")) break if path == None or not os.path.exists(path): test.warning("Path '%s' from fallback test data file does not exist!" % path, "See the README file how to set up your environment.") return None return path # function to add a program to allow communication through the win firewall # param workingDir this directory is the parent of the project folder # param projectName this is the name of the project (the folder inside workingDir as well as the name for the executable) # param isReleaseBuild should currently always be set to True (will later add debug build testing) def allowAppThroughWinFW(workingDir, projectName, isReleaseBuild=True): if not __isWinFirewallRunning__(): return # WinFirewall seems to run - hopefully no other result = __configureFW__(workingDir, projectName, isReleaseBuild) if result == 0: test.log("Added %s to firewall" % projectName) else: test.fatal("Could not add %s as allowed program to win firewall" % projectName) # function to delete a (former added) program from the win firewall # param workingDir this directory is the parent of the project folder # param projectName this is the name of the project (the folder inside workingDir as well as the name for the executable) # param isReleaseBuild should currently always be set to True (will later add debug build testing) def deleteAppFromWinFW(workingDir, projectName, isReleaseBuild=True): if not __isWinFirewallRunning__(): return # WinFirewall seems to run - hopefully no other result = __configureFW__(workingDir, projectName, isReleaseBuild, False) if result == 0: test.log("Deleted %s from firewall" % projectName) else: test.fatal("Could not delete %s as allowed program from win firewall" % (mode, projectName)) # helper that can modify the win firewall to allow a program to communicate through it or delete it # param addToFW defines whether to add (True) or delete (False) this programm to/from the firewall def __configureFW__(workingDir, projectName, isReleaseBuild, addToFW=True): if isReleaseBuild == None: if projectName[-4:] == ".exe": projectName = projectName[:-4] path = "%s%s%s" % (workingDir, os.sep, projectName) elif isReleaseBuild: path = "%s%s%s%srelease%s%s" % (workingDir, os.sep, projectName, os.sep, os.sep, projectName) else: path = "%s%s%s%sdebug%s%s" % (workingDir, os.sep, projectName, os.sep, os.sep, projectName) if addToFW: mode = "add" enable = "ENABLE" else: mode = "delete" enable = "" return subprocess.call('netsh firewall %s allowedprogram "%s.exe" %s %s' % (mode, path, projectName, enable)) # helper to check whether win firewall is running or not # this doesn't check for other firewalls! def __isWinFirewallRunning__(): global fireWallState if fireWallState != None: return fireWallState if not platform.system() in ('Microsoft' 'Windows'): fireWallState = False return False result = getOutputFromCmdline("netsh firewall show state") for line in result.splitlines(): if "Operational mode" in line: fireWallState = not "Disable" in line return fireWallState return None # this function adds the given executable as an attachable AUT # Bad: executable/port could be empty strings - you should be aware of this def addExecutableAsAttachableAUT(executable, port, host=None): if not __checkParamsForAttachableAUT__(executable, port): return False if host == None: host = "localhost" squishSrv = __getSquishServer__() if (squishSrv == None): return False result = subprocess.call('%s --config addAttachableAUT "%s" %s:%s' % (squishSrv, executable, host, port), shell=True) if result == 0: test.passes("Added %s as attachable AUT" % executable) else: test.fail("Failed to add %s as attachable AUT" % executable) return result == 0 # this function removes the given executable as an attachable AUT # Bad: executable/port could be empty strings - you should be aware of this def removeExecutableAsAttachableAUT(executable, port, host=None): if not __checkParamsForAttachableAUT__(executable, port): return False if host == None: host = "localhost" squishSrv = __getSquishServer__() if (squishSrv == None): return False result = subprocess.call('%s --config removeAttachableAUT "%s" %s:%s' % (squishSrv, executable, host, port), shell=True) if result == 0: test.passes("Removed %s as attachable AUT" % executable) else: test.fail("Failed to remove %s as attachable AUT" % executable) return result == 0 def __checkParamsForAttachableAUT__(executable, port): return port != None and executable != None def __getSquishServer__(): squishSrv = currentApplicationContext().environmentVariable("SQUISH_PREFIX") if (squishSrv == ""): test.fatal("SQUISH_PREFIX isn't set - leaving test") return None return os.path.abspath(squishSrv + "/bin/squishserver")<|fim▁end|>
# this uses the defaultQtVersion currently switchViewTo(ViewConstants.PROJECTS)
<|file_name|>issue-36744-without-calls.rs<|end_file_name|><|fim▁begin|>// build-pass // Tests for an LLVM abort when storing a lifetime-parametric fn into // context that is expecting one that is not lifetime-parametric // (i.e., has no `for <'_>`).<|fim▁hole|> pub struct A<'a>(&'a ()); pub struct S<T>(T); pub fn bad<'s>(v: &mut S<fn(A<'s>)>, y: S<for<'b> fn(A<'b>)>) { *v = y; } fn main() {}<|fim▁end|>
<|file_name|>ecs.rs<|end_file_name|><|fim▁begin|>use std::collections::HashMap; use std::iter; use world; use entity::{Entity}; use components; use component_ref::{ComponentRef, ComponentRefMut}; use stats; use world::{WorldState}; /// Entity component system. #[derive(RustcDecodable, RustcEncodable)] pub struct Ecs { next_idx: usize, reusable_idxs: Vec<usize>, // Could use Bitv for active, but I can't bother to write the serializer... active: Vec<bool>, parent: HashMap<usize, usize>, } impl Ecs { pub fn new() -> Ecs { Ecs { next_idx: 0, reusable_idxs: vec![], active: vec![], parent: HashMap::new(), } } pub fn new_entity(&mut self, parent: Option<Entity>) -> Entity { // Get the entity idx, reuse old ones to keep the indexing compact. let idx = match self.reusable_idxs.pop() { None => { let ret = self.next_idx; self.next_idx += 1; ret } Some(idx) => idx }; if let Some(Entity(p_idx)) = parent { assert!(self.active[p_idx]); self.parent.insert(idx, p_idx); } if self.active.len() <= idx { let padding = idx + 1 - self.active.len(); self.active.extend(iter::repeat(false).take(padding)); assert!(self.active.len() == idx + 1); } assert!(!self.active[idx]); self.active[idx] = true; Entity(idx) } /// Delete an entity from the entity component system. /// /// XXX: The user is currently responsible for never using an entity /// handle again after delete_entity has been called on it. Using an /// entity handle after deletion may return another entity's contents. pub fn delete(&mut self, Entity(idx): Entity) { assert!(self.active[idx]); self.parent.remove(&idx); self.reusable_idxs.push(idx); self.active[idx] = false; } /// Return an iterator for the entities. The iterator will not be /// invalidated if entities are added or removed during iteration. The /// iterator also won't maintain a lock on the world singleton outside /// calling next. /// /// XXX: It is currently unspecified whether entities added during /// iteration will show up in the iteration or not. pub fn iter(&self) -> EntityIter { EntityIter(0) } /// Return the optional parent entity of an entity. pub fn parent(&self, Entity(idx): Entity) -> Option<Entity> { self.parent.get(&idx).map(|&idx| Entity(idx)) } /// Change the parent of a live entity pub fn reparent(&mut self, Entity(idx): Entity, Entity(new_parent_idx): Entity) { self.parent.insert(idx, new_parent_idx); } } pub struct EntityIter(usize); impl Iterator for EntityIter { type Item = Entity; fn next(&mut self) -> Option<Entity> { world::with(|w| { let &mut EntityIter(ref mut idx) = self; loop { if *idx >= w.ecs.active.len() { return None; } let ret = Entity(*idx); *idx += 1; if !w.ecs.active[*idx - 1] { continue; } return Some(ret); } }) } } //////////////////////////////////////////////////////////////////////// // The one big macro for defining the full set of available entity components // in one place. macro_rules! components { { // Declare the list of types which are included as components in the // game's entity component system. Also declare the non-mutable and // mutable accessor names for them. Example // // ```notrust // [Mesh, meshes, meshes_mut], // ``` $([$comp:ty, $access:ident, $access_mut:ident],)+ } => { // The master container for all the components. #[derive(RustcEncodable, RustcDecodable)] pub struct Comps { $($access: HashMap<usize, Option<$comp>>,)+ } /// Container for all regular entity components. impl Comps { pub fn new() -> Comps { Comps { $($access: HashMap::new(),)+ } } /// Remove the given entity from all the contained components. pub fn remove(&mut self, Entity(idx): Entity) { $(self.$access.remove(&idx);)+ }<|fim▁hole|> // syntax for adding component values to entities used by the entity // factory. $( impl Component for $comp { // XXX: Figure out how to move self into the closure to // get rid of the .clone. fn add_to(self, e: Entity) { world::with_mut(|w| w.$access_mut().insert(e, self.clone())) } } )+ // Implement the trait for accessing all the components that // WorldState will implement pub trait ComponentAccess<'a> { $( fn $access(&'a self) -> ComponentRef<'a, $comp>; fn $access_mut(&'a mut self) -> ComponentRefMut<'a, $comp>; )+ } impl<'a> ComponentAccess<'a> for WorldState { $( fn $access(&'a self) -> ComponentRef<'a, $comp> { ComponentRef::new(&self.ecs, &self.comps.$access) } fn $access_mut(&'a mut self) -> ComponentRefMut<'a, $comp> { ComponentRefMut::new(&mut self.ecs, &mut self.comps.$access) } )+ } } } pub trait Component { /// Create an uniform syntax for attaching components to entities to allow /// a fluent API for constructing prototypes. fn add_to(self, e: Entity); } // Component loadout for the game. components! { [components::IsPrototype, prototypes, prototypes_mut], [components::Desc, descs, descs_mut], [components::MapMemory, map_memories, map_memories_mut], [stats::Stats, stats, stats_mut], [components::Spawn, spawns, spawns_mut], [components::Health, healths, healths_mut], [components::Brain, brains, brains_mut], [components::Item, items, items_mut], [components::StatsCache, stats_caches, stats_caches_mut], [components::Colonist, colonists, colonists_mut], }<|fim▁end|>
} // Implement the Componet trait for the type, this provides an uniform
<|file_name|>ExpandedResourceRepositoryApplicationContext.java<|end_file_name|><|fim▁begin|>/******************************************************************************* * Copyright (c) 1998, 2015 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Oracle - initial API and implementation from Oracle TopLink ******************************************************************************/<|fim▁hole|>import org.eclipse.persistence.tools.workbench.framework.resources.ResourceRepositoryWrapper; /** * Wrap another context and expand its resource * repository with a resource repository wrapper. */ public class ExpandedResourceRepositoryApplicationContext extends ApplicationContextWrapper { private ResourceRepository expandedResourceRepository; // ********** constructor/initialization ********** /** * Construct a context with an expanded resource repository * that adds the resources in the specified resource bundle and icon map * to the original resource repository. */ public ExpandedResourceRepositoryApplicationContext(ApplicationContext delegate, Class resourceBundleClass, IconResourceFileNameMap iconResourceFileNameMap) { super(delegate); this.expandedResourceRepository = new ResourceRepositoryWrapper(this.delegateResourceRepository(), resourceBundleClass, iconResourceFileNameMap); } // ********** non-delegated behavior ********** /** * @see ApplicationContextWrapper#getResourceRepository() */ public ResourceRepository getResourceRepository() { return this.expandedResourceRepository; } // ********** additional behavior ********** /** * Return the original, unwrapped resource repository. */ public ResourceRepository delegateResourceRepository() { return this.getDelegate().getResourceRepository(); } }<|fim▁end|>
package org.eclipse.persistence.tools.workbench.framework.context; import org.eclipse.persistence.tools.workbench.framework.resources.IconResourceFileNameMap; import org.eclipse.persistence.tools.workbench.framework.resources.ResourceRepository;
<|file_name|>pipeline.py<|end_file_name|><|fim▁begin|>"""Auth pipeline definitions. Auth pipelines handle the process of authenticating a user. They involve a consumer system and a provider service. The general pattern is: 1. The consumer system exposes a URL endpoint that starts the process. 2. When a user visits that URL, the client system redirects the user to a page served by the provider. The user authenticates with the provider. The provider handles authentication failure however it wants. 3. On success, the provider POSTs to a URL endpoint on the consumer to invoke the pipeline. It sends back an arbitrary payload of data about the user. 4. The pipeline begins, executing each function in its stack. The stack is defined on django's settings object's SOCIAL_AUTH_PIPELINE. This is done in settings._set_global_settings. 5. Each pipeline function is variadic. Most pipeline functions are part of the pythons-social-auth library; our extensions are defined below. The pipeline is the same no matter what provider is used. 6. Pipeline functions can return a dict to add arguments to the function invoked next. They can return None if this is not necessary. 7. Pipeline functions may be decorated with @partial.partial. This pauses the pipeline and serializes its state onto the request's session. When this is done they may redirect to other edX handlers to execute edX account registration/sign in code. 8. In that code, redirecting to get_complete_url() resumes the pipeline. This happens by hitting a handler exposed by the consumer system. 9. In this way, execution moves between the provider, the pipeline, and arbitrary consumer system code. Gotcha alert!: Bear in mind that when pausing and resuming a pipeline function decorated with @partial.partial, execution resumes by re-invoking the decorated function instead of invoking the next function in the pipeline stack. For example, if you have a pipeline of A B C with an implementation of @partial.partial def B(*args, **kwargs): [...] B will be invoked twice: once when initially proceeding through the pipeline before it is paused, and once when other code finishes and the pipeline resumes. Consequently, many decorated functions will first invoke a predicate to determine if they are in their first or second execution (usually by checking side-effects from the first run). This is surprising but important behavior, since it allows a single function in the pipeline to consolidate all the operations needed to establish invariants rather than spreading them across two functions in the pipeline. See http://python-social-auth.readthedocs.io/en/latest/pipeline.html for more docs. """ import base64 import hashlib import hmac import json import urllib from collections import OrderedDict from logging import getLogger from smtplib import SMTPException import analytics from django.conf import settings from django.contrib.auth.models import User from django.core.mail.message import EmailMessage from django.urls import reverse from django.http import HttpResponseBadRequest from django.shortcuts import redirect import social_django from social_core.exceptions import AuthException from social_core.pipeline import partial from social_core.pipeline.social_auth import associate_by_email import student from edxmako.shortcuts import render_to_string from eventtracking import tracker from openedx.core.djangoapps.site_configuration import helpers as configuration_helpers from third_party_auth.utils import user_exists from lms.djangoapps.verify_student.models import SSOVerification from lms.djangoapps.verify_student.utils import earliest_allowed_verification_date from . import provider # These are the query string params you can pass # to the URL that starts the authentication process. # # `AUTH_ENTRY_KEY` is required and indicates how the user # enters the authentication process. # # `AUTH_REDIRECT_KEY` provides an optional URL to redirect # to upon successful authentication # (if not provided, defaults to `_SOCIAL_AUTH_LOGIN_REDIRECT_URL`) AUTH_ENTRY_KEY = 'auth_entry' AUTH_REDIRECT_KEY = 'next' # The following are various possible values for the AUTH_ENTRY_KEY. AUTH_ENTRY_LOGIN = 'login' AUTH_ENTRY_REGISTER = 'register' AUTH_ENTRY_ACCOUNT_SETTINGS = 'account_settings' # Entry modes into the authentication process by a remote API call (as opposed to a browser session). AUTH_ENTRY_LOGIN_API = 'login_api' AUTH_ENTRY_REGISTER_API = 'register_api' # AUTH_ENTRY_CUSTOM: Custom auth entry point for post-auth integrations. # This should be a dict where the key is a word passed via ?auth_entry=, and the # value is a dict with an arbitrary 'secret_key' and a 'url'. # This can be used as an extension point to inject custom behavior into the auth # process, replacing the registration/login form that would normally be seen # immediately after the user has authenticated with the third party provider. # If a custom 'auth_entry' query parameter is used, then once the user has # authenticated with a specific backend/provider, they will be redirected to the # URL specified with this setting, rather than to the built-in # registration/login form/logic. AUTH_ENTRY_CUSTOM = getattr(settings, 'THIRD_PARTY_AUTH_CUSTOM_AUTH_FORMS', {}) def is_api(auth_entry): """Returns whether the auth entry point is via an API call.""" return (auth_entry == AUTH_ENTRY_LOGIN_API) or (auth_entry == AUTH_ENTRY_REGISTER_API) # URLs associated with auth entry points # These are used to request additional user information # (for example, account credentials when logging in), # and when the user cancels the auth process # (e.g., refusing to grant permission on the provider's login page). # We don't use "reverse" here because doing so may cause modules # to load that depend on this module. AUTH_DISPATCH_URLS = { AUTH_ENTRY_LOGIN: '/login', AUTH_ENTRY_REGISTER: '/register', AUTH_ENTRY_ACCOUNT_SETTINGS: '/account/settings', } _AUTH_ENTRY_CHOICES = frozenset([ AUTH_ENTRY_LOGIN, AUTH_ENTRY_REGISTER, AUTH_ENTRY_ACCOUNT_SETTINGS, AUTH_ENTRY_LOGIN_API, AUTH_ENTRY_REGISTER_API, ] + AUTH_ENTRY_CUSTOM.keys()) logger = getLogger(__name__) class AuthEntryError(AuthException): """Raised when auth_entry is invalid on URLs. auth_entry tells us whether the auth flow was initiated to register a new user (in which case it has the value of AUTH_ENTRY_REGISTER) or log in an existing user (in which case it has the value of AUTH_ENTRY_LOGIN). This is necessary because the edX code we hook into the pipeline to redirect to the existing auth flows needs to know what case we are in in order to format its output correctly (for example, the register code is invoked earlier than the login code, and it needs to know if the login flow was requested to dispatch correctly). """ class ProviderUserState(object): """Object representing the provider state (attached or not) for a user. This is intended only for use when rendering templates. See for example lms/templates/dashboard.html. """ def __init__(self, enabled_provider, user, association): # Boolean. Whether the user has an account associated with the provider self.has_account = association is not None if self.has_account: # UserSocialAuth row ID self.association_id = association.id # Identifier of this user according to the remote provider: self.remote_id = enabled_provider.get_remote_id_from_social_auth(association) else: self.association_id = None self.remote_id = None # provider.BaseProvider child. Callers must verify that the provider is # enabled. self.provider = enabled_provider # django.contrib.auth.models.User. self.user = user def get_unlink_form_name(self): """Gets the name used in HTML forms that unlink a provider account.""" return self.provider.provider_id + '_unlink_form' def get(request): """Gets the running pipeline's data from the passed request.""" strategy = social_django.utils.load_strategy(request) token = strategy.session_get('partial_pipeline_token') partial_object = strategy.partial_load(token) pipeline_data = None if partial_object: pipeline_data = {'kwargs': partial_object.kwargs, 'backend': partial_object.backend} return pipeline_data def get_real_social_auth_object(request): """ At times, the pipeline will have a "social" kwarg that contains a dictionary rather than an actual DB-backed UserSocialAuth object. We need the real thing, so this method allows us to get that by passing in the relevant request. """ running_pipeline = get(request) if running_pipeline and 'social' in running_pipeline['kwargs']: social = running_pipeline['kwargs']['social'] if isinstance(social, dict): social = social_django.models.UserSocialAuth.objects.get(**social) return social def quarantine_session(request, locations): """ Set a session variable indicating that the session is restricted to being used in views contained in the modules listed by string in the `locations` argument. Example: ``quarantine_session(request, ('enterprise.views',))`` """ request.session['third_party_auth_quarantined_modules'] = locations def lift_quarantine(request): """ Remove the session quarantine variable. """ request.session.pop('third_party_auth_quarantined_modules', None) def get_authenticated_user(auth_provider, username, uid): """Gets a saved user authenticated by a particular backend. Between pipeline steps User objects are not saved. We need to reconstitute the user and set its .backend, which is ordinarily monkey-patched on by Django during authenticate(), so it will function like a user returned by authenticate(). Args: auth_provider: the third_party_auth provider in use for the current pipeline. username: string. Username of user to get. uid: string. The user ID according to the third party. Returns: User if user is found and has a social auth from the passed provider. Raises: User.DoesNotExist: if no user matching user is found, or the matching user has no social auth associated with the given backend. AssertionError: if the user is not authenticated. """ match = social_django.models.DjangoStorage.user.get_social_auth(provider=auth_provider.backend_name, uid=uid) if not match or match.user.username != username: raise User.DoesNotExist user = match.user user.backend = auth_provider.get_authentication_backend() return user def _get_enabled_provider(provider_id): """Gets an enabled provider by its provider_id member or throws.""" enabled_provider = provider.Registry.get(provider_id) if not enabled_provider: raise ValueError('Provider %s not enabled' % provider_id) return enabled_provider def _get_url(view_name, backend_name, auth_entry=None, redirect_url=None, extra_params=None, url_params=None): """Creates a URL to hook into social auth endpoints.""" url_params = url_params or {} url_params['backend'] = backend_name url = reverse(view_name, kwargs=url_params) query_params = OrderedDict() if auth_entry: query_params[AUTH_ENTRY_KEY] = auth_entry if redirect_url: query_params[AUTH_REDIRECT_KEY] = redirect_url if extra_params: query_params.update(extra_params) return u"{url}?{params}".format( url=url, params=urllib.urlencode(query_params) ) def get_complete_url(backend_name): """Gets URL for the endpoint that returns control to the auth pipeline. Args: backend_name: string. Name of the python-social-auth backend from the currently-running pipeline. Returns: String. URL that finishes the auth pipeline for a provider. Raises: ValueError: if no provider is enabled with the given backend_name. """ if not any(provider.Registry.get_enabled_by_backend_name(backend_name)): raise ValueError('Provider with backend %s not enabled' % backend_name) return _get_url('social:complete', backend_name) def get_disconnect_url(provider_id, association_id): """Gets URL for the endpoint that starts the disconnect pipeline. Args: provider_id: string identifier of the social_django.models.ProviderConfig child you want to disconnect from. association_id: int. Optional ID of a specific row in the UserSocialAuth table to disconnect (useful if multiple providers use a common backend) Returns: String. URL that starts the disconnection pipeline. Raises: ValueError: if no provider is enabled with the given ID. """ backend_name = _get_enabled_provider(provider_id).backend_name if association_id: return _get_url('social:disconnect_individual', backend_name, url_params={'association_id': association_id}) else: return _get_url('social:disconnect', backend_name) def get_login_url(provider_id, auth_entry, redirect_url=None): """Gets the login URL for the endpoint that kicks off auth with a provider. Args: provider_id: string identifier of the social_django.models.ProviderConfig child you want to disconnect from. auth_entry: string. Query argument specifying the desired entry point for the auth pipeline. Used by the pipeline for later branching. Must be one of _AUTH_ENTRY_CHOICES. Keyword Args: redirect_url (string): If provided, redirect to this URL at the end of the authentication process. Returns: String. URL that starts the auth pipeline for a provider. Raises: ValueError: if no provider is enabled with the given provider_id. """ assert auth_entry in _AUTH_ENTRY_CHOICES enabled_provider = _get_enabled_provider(provider_id) return _get_url( 'social:begin', enabled_provider.backend_name, auth_entry=auth_entry, redirect_url=redirect_url, extra_params=enabled_provider.get_url_params(), ) def get_duplicate_provider(messages): """Gets provider from message about social account already in use. python-social-auth's exception middleware uses the messages module to record details about duplicate account associations. It records exactly one message there is a request to associate a social account S with an edX account E if S is already associated with an edX account E'. This messaging approach is stringly-typed and the particular string is unfortunately not in a reusable constant. Returns: string name of the python-social-auth backend that has the duplicate account, or None if there is no duplicate (and hence no error). """ social_auth_messages = [m for m in messages if m.message.endswith('is already in use.')] if not social_auth_messages: return assert len(social_auth_messages) == 1 backend_name = social_auth_messages[0].extra_tags.split()[1] return backend_name def get_provider_user_states(user): """Gets list of states of provider-user combinations. Args: django.contrib.auth.User. The user to get states for. Returns: List of ProviderUserState. The list of states of a user's account with each enabled provider. """ states = [] found_user_auths = list(social_django.models.DjangoStorage.user.get_social_auth_for_user(user)) for enabled_provider in provider.Registry.enabled(): association = None for auth in found_user_auths: if enabled_provider.match_social_auth(auth): association = auth break if enabled_provider.accepts_logins or association: states.append( ProviderUserState(enabled_provider, user, association) ) return states def running(request): """Returns True iff request is running a third-party auth pipeline.""" return get(request) is not None # Avoid False for {}. # Pipeline functions. # Signatures are set by python-social-auth; prepending 'unused_' causes # TypeError on dispatch to the auth backend's authenticate(). # pylint: disable=unused-argument def parse_query_params(strategy, response, *args, **kwargs): """Reads whitelisted query params, transforms them into pipeline args.""" # If auth_entry is not in the session, we got here by a non-standard workflow. # We simply assume 'login' in that case. auth_entry = strategy.request.session.get(AUTH_ENTRY_KEY, AUTH_ENTRY_LOGIN)<|fim▁hole|> raise AuthEntryError(strategy.request.backend, 'auth_entry invalid') return {'auth_entry': auth_entry} def set_pipeline_timeout(strategy, user, *args, **kwargs): """ Set a short session timeout while the pipeline runs, to improve security. Consider the following attack: 1. Attacker on a public computer visits edX and initiates the third-party login flow 2. Attacker logs into their own third-party account 3. Attacker closes the window and does not complete the login flow 4. Victim on the same computer logs into edX with username/password 5. edX links attacker's third-party account with victim's edX account 6. Attacker logs into victim's edX account using attacker's own third-party account We have two features of the pipeline designed to prevent this attack: * This method shortens the Django session timeout during the pipeline. This should mean that if there is a reasonable delay between steps 3 and 4, the session and pipeline will be reset, and the attack foiled. Configure the timeout with the SOCIAL_AUTH_PIPELINE_TIMEOUT setting (Default: 600 seconds) * On step 4, the login page displays an obvious message to the user, saying "You've successfully signed into (Google), but your (Google) account isn't linked with an edX account. To link your accounts, login now using your edX password.". """ if strategy.request and not user: # If user is set, we're currently logged in (and/or linked) so it doesn't matter. strategy.request.session.set_expiry(strategy.setting('PIPELINE_TIMEOUT', 600)) # We don't need to reset this timeout later. Because the user is not logged in and this # account is not yet linked to an edX account, either the normal 'login' or 'register' # code must occur during the subsequent ensure_user_information step, and those methods # will change the session timeout to the "normal" value according to the "Remember Me" # choice of the user. def redirect_to_custom_form(request, auth_entry, details, kwargs): """ If auth_entry is found in AUTH_ENTRY_CUSTOM, this is used to send provider data to an external server's registration/login page. The data is sent as a base64-encoded values in a POST request and includes a cryptographic checksum in case the integrity of the data is important. """ backend_name = request.backend.name provider_id = provider.Registry.get_from_pipeline({'backend': backend_name, 'kwargs': kwargs}).provider_id form_info = AUTH_ENTRY_CUSTOM[auth_entry] secret_key = form_info['secret_key'] if isinstance(secret_key, unicode): secret_key = secret_key.encode('utf-8') custom_form_url = form_info['url'] data_str = json.dumps({ "auth_entry": auth_entry, "backend_name": backend_name, "provider_id": provider_id, "user_details": details, }) digest = hmac.new(secret_key, msg=data_str, digestmod=hashlib.sha256).digest() # Store the data in the session temporarily, then redirect to a page that will POST it to # the custom login/register page. request.session['tpa_custom_auth_entry_data'] = { 'data': base64.b64encode(data_str), 'hmac': base64.b64encode(digest), 'post_url': custom_form_url, } return redirect(reverse('tpa_post_to_custom_auth_form')) @partial.partial def ensure_user_information(strategy, auth_entry, backend=None, user=None, social=None, current_partial=None, allow_inactive_user=False, details=None, *args, **kwargs): """ Ensure that we have the necessary information about a user (either an existing account or registration data) to proceed with the pipeline. """ # We're deliberately verbose here to make it clear what the intended # dispatch behavior is for the various pipeline entry points, given the # current state of the pipeline. Keep in mind the pipeline is re-entrant # and values will change on repeated invocations (for example, the first # time through the login flow the user will be None so we dispatch to the # login form; the second time it will have a value so we continue to the # next pipeline step directly). # # It is important that we always execute the entire pipeline. Even if # behavior appears correct without executing a step, it means important # invariants have been violated and future misbehavior is likely. def dispatch_to_login(): """Redirects to the login page.""" return redirect(AUTH_DISPATCH_URLS[AUTH_ENTRY_LOGIN]) def dispatch_to_register(): """Redirects to the registration page.""" return redirect(AUTH_DISPATCH_URLS[AUTH_ENTRY_REGISTER]) def should_force_account_creation(): """ For some third party providers, we auto-create user accounts """ current_provider = provider.Registry.get_from_pipeline({'backend': current_partial.backend, 'kwargs': kwargs}) return (current_provider and (current_provider.skip_email_verification or current_provider.send_to_registration_first)) if not user: if user_exists(details or {}): # User has not already authenticated and the details sent over from # identity provider belong to an existing user. return dispatch_to_login() if is_api(auth_entry): return HttpResponseBadRequest() elif auth_entry == AUTH_ENTRY_LOGIN: # User has authenticated with the third party provider but we don't know which edX # account corresponds to them yet, if any. if should_force_account_creation(): return dispatch_to_register() return dispatch_to_login() elif auth_entry == AUTH_ENTRY_REGISTER: # User has authenticated with the third party provider and now wants to finish # creating their edX account. return dispatch_to_register() elif auth_entry == AUTH_ENTRY_ACCOUNT_SETTINGS: raise AuthEntryError(backend, 'auth_entry is wrong. Settings requires a user.') elif auth_entry in AUTH_ENTRY_CUSTOM: # Pass the username, email, etc. via query params to the custom entry page: return redirect_to_custom_form(strategy.request, auth_entry, details or {}, kwargs) else: raise AuthEntryError(backend, 'auth_entry invalid') if not user.is_active: # The user account has not been verified yet. if allow_inactive_user: # This parameter is used by the auth_exchange app, which always allows users to # login, whether or not their account is validated. pass elif social is None: # The user has just registered a new account as part of this pipeline. Their account # is inactive but we allow the login to continue, because if we pause again to force # the user to activate their account via email, the pipeline may get lost (e.g. # email takes too long to arrive, user opens the activation email on a different # device, etc.). This is consistent with first party auth and ensures that the # pipeline completes fully, which is critical. pass else: # This is an existing account, linked to a third party provider but not activated. # Double-check these criteria: assert user is not None assert social is not None # We now also allow them to login again, because if they had entered their email # incorrectly then there would be no way for them to recover the account, nor # register anew via SSO. See SOL-1324 in JIRA. # However, we will log a warning for this case: logger.warning( 'User "%s" is using third_party_auth to login but has not yet activated their account. ', user.username ) @partial.partial def set_logged_in_cookies(backend=None, user=None, strategy=None, auth_entry=None, current_partial=None, *args, **kwargs): """This pipeline step sets the "logged in" cookie for authenticated users. Some installations have a marketing site front-end separate from edx-platform. Those installations sometimes display different information for logged in versus anonymous users (e.g. a link to the student dashboard instead of the login page.) Since social auth uses Django's native `login()` method, it bypasses our usual login view that sets this cookie. For this reason, we need to set the cookie ourselves within the pipeline. The procedure for doing this is a little strange. On the one hand, we need to send a response to the user in order to set the cookie. On the other hand, we don't want to drop the user out of the pipeline. For this reason, we send a redirect back to the "complete" URL, so users immediately re-enter the pipeline. The redirect response contains a header that sets the logged in cookie. If the user is not logged in, or the logged in cookie is already set, the function returns `None`, indicating that control should pass to the next pipeline step. """ if not is_api(auth_entry) and user is not None and user.is_authenticated: request = strategy.request if strategy else None # n.b. for new users, user.is_active may be False at this point; set the cookie anyways. if request is not None: # Check that the cookie isn't already set. # This ensures that we allow the user to continue to the next # pipeline step once he/she has the cookie set by this step. has_cookie = student.cookies.is_logged_in_cookie_set(request) if not has_cookie: try: redirect_url = get_complete_url(current_partial.backend) except ValueError: # If for some reason we can't get the URL, just skip this step # This may be overly paranoid, but it's far more important that # the user log in successfully than that the cookie is set. pass else: response = redirect(redirect_url) return student.cookies.set_logged_in_cookies(request, response, user) @partial.partial def login_analytics(strategy, auth_entry, current_partial=None, *args, **kwargs): """ Sends login info to Segment """ event_name = None if auth_entry == AUTH_ENTRY_LOGIN: event_name = 'edx.bi.user.account.authenticated' elif auth_entry in [AUTH_ENTRY_ACCOUNT_SETTINGS]: event_name = 'edx.bi.user.account.linked' if event_name is not None and hasattr(settings, 'LMS_SEGMENT_KEY') and settings.LMS_SEGMENT_KEY: tracking_context = tracker.get_tracker().resolve_context() analytics.track( kwargs['user'].id, event_name, { 'category': "conversion", 'label': None, 'provider': kwargs['backend'].name }, context={ 'ip': tracking_context.get('ip'), 'Google Analytics': { 'clientId': tracking_context.get('client_id') } } ) @partial.partial def associate_by_email_if_login_api(auth_entry, backend, details, user, current_partial=None, *args, **kwargs): """ This pipeline step associates the current social auth with the user with the same email address in the database. It defers to the social library's associate_by_email implementation, which verifies that only a single database user is associated with the email. This association is done ONLY if the user entered the pipeline through a LOGIN API. """ association_response = associate_by_email(backend, details, user, *args, **kwargs) if ( association_response and association_response.get('user') and association_response['user'].is_active ): # Only return the user matched by email if their email has been activated. # Otherwise, an illegitimate user can create an account with another user's # email address and the legitimate user would now login to the illegitimate # account. return association_response def user_details_force_sync(auth_entry, strategy, details, user=None, *args, **kwargs): """ Update normally protected user details using data from provider. This step in the pipeline is akin to `social_core.pipeline.user.user_details`, which updates the user details but has an unconfigurable protection over updating the username & email, and is unable to update information such as the user's full name which isn't on the user model, but rather on the user profile model. Additionally, because the email field is normally used to log in, if the email is changed by this forced synchronization, we send an email to both the old and new emails, letting the user know. This step is controlled by the `sync_learner_profile_data` flag on the provider's configuration. """ current_provider = provider.Registry.get_from_pipeline({'backend': strategy.request.backend.name, 'kwargs': kwargs}) if user and current_provider.sync_learner_profile_data: # Keep track of which incoming values get applied. changed = {} # Map each incoming field from the provider to the name on the user model (by default, they always match). field_mapping = {field: (user, field) for field in details.keys() if hasattr(user, field)} # This is a special case where the field mapping should go to the user profile object and not the user object, # in some cases with differing field names (i.e. 'fullname' vs. 'name'). field_mapping.update({ 'fullname': (user.profile, 'name'), 'country': (user.profile, 'country'), }) # Remove username from list of fields for update field_mapping.pop('username', None) # Track any fields that would raise an integrity error if there was a conflict. integrity_conflict_fields = {'email': user.email, 'username': user.username} for provider_field, (model, field) in field_mapping.items(): provider_value = details.get(provider_field) current_value = getattr(model, field) if provider_value is not None and current_value != provider_value: if field in integrity_conflict_fields and User.objects.filter(**{field: provider_value}).exists(): logger.warning('User with ID [%s] tried to synchronize profile data through [%s] ' 'but there was a conflict with an existing [%s]: [%s].', user.id, current_provider.name, field, provider_value) continue changed[provider_field] = current_value setattr(model, field, provider_value) if changed: logger.info( "User [%s] performed SSO through [%s] who synchronizes profile data, and the " "following fields were changed: %s", user.username, current_provider.name, changed.keys(), ) # Save changes to user and user.profile models. strategy.storage.user.changed(user) user.profile.save() # Send an email to the old and new email to alert the user that their login email changed. if changed.get('email'): old_email = changed['email'] new_email = user.email email_context = {'old_email': old_email, 'new_email': new_email} # Subjects shouldn't have new lines. subject = ''.join(render_to_string( 'emails/sync_learner_profile_data_email_change_subject.txt', email_context ).splitlines()) body = render_to_string('emails/sync_learner_profile_data_email_change_body.txt', email_context) from_email = configuration_helpers.get_value('email_from_address', settings.DEFAULT_FROM_EMAIL) email = EmailMessage(subject=subject, body=body, from_email=from_email, to=[old_email, new_email]) email.content_subtype = "html" try: email.send() except SMTPException: logger.exception('Error sending IdP learner data sync-initiated email change ' 'notification email for user [%s].', user.username) def set_id_verification_status(auth_entry, strategy, details, user=None, *args, **kwargs): """ Use the user's authentication with the provider, if configured, as evidence of their identity being verified. """ current_provider = provider.Registry.get_from_pipeline({'backend': strategy.request.backend.name, 'kwargs': kwargs}) if user and current_provider.enable_sso_id_verification: # Get previous valid, non expired verification attempts for this SSO Provider and user verifications = SSOVerification.objects.filter( user=user, status="approved", created_at__gte=earliest_allowed_verification_date(), identity_provider_type=current_provider.full_class_name, identity_provider_slug=current_provider.slug, ) # If there is none, create a new approved verification for the user. if not verifications: SSOVerification.objects.create( user=user, status="approved", name=user.profile.name, identity_provider_type=current_provider.full_class_name, identity_provider_slug=current_provider.slug, )<|fim▁end|>
if auth_entry not in _AUTH_ENTRY_CHOICES:
<|file_name|>engine.rs<|end_file_name|><|fim▁begin|>use std::thread; use std::collections::HashMap; use std::intrinsics::type_name; use std::mem; use std::ptr::{self, Unique}; use std::sync::{Arc, Barrier, Mutex}; use std::time::Duration; use bootstrap::input::ScanCode; use bootstrap::window::Window; use bootstrap::window::Message::*; use bootstrap::time::Timer; use bs_audio; use polygon::{Renderer, RendererBuilder}; use singleton::Singleton; use stopwatch::{Collector, Stopwatch}; use scene::*; use resource::ResourceManager; use ecs::*; use component::*; use debug_draw::DebugDraw; pub const TARGET_FRAME_TIME_SECONDS: f32 = 1.0 / 60.0; pub const TARGET_FRAME_TIME_MS: f32 = TARGET_FRAME_TIME_SECONDS * 1000.0; static mut INSTANCE: *mut Engine = ptr::null_mut(); pub struct Engine { renderer: Mutex<Box<Renderer>>, window: Window, resource_manager: Box<ResourceManager>, systems: HashMap<SystemId, Box<System>>, debug_systems: HashMap<SystemId, Box<System>>, // TODO: Replace explicit update ordering with something more automatic (e.g. dependency hierarchy). audio_update: Box<System>, alarm_update: Box<System>, collision_update: Box<System>, scene: Scene, debug_draw: DebugDraw, close: bool, debug_pause: bool, } impl Engine { /// Starts the engine's main loop, blocking until the game shuts down. /// /// This function starts the engine's internal update loop which handles the details of /// processing input from the OS, invoking game code, and rendering each frame. This function /// blocks until the engine recieves a message to being the shutdown process, at which point it /// will end the update loop and perform any necessary shutdown and cleanup procedures. Once /// those have completed this function will return. /// /// Panics if the engine hasn't been created yet. pub fn start() { let instance = unsafe { debug_assert!(!INSTANCE.is_null(), "Cannot retrieve Engine instance because none exists"); &mut *INSTANCE }; // Run main loop. instance.main_loop(); // Perform cleanup. unsafe { Engine::destroy_instance(); } } <|fim▁hole|> let instance = Engine::instance(); &instance.scene } /// Retrieves a reference to the resource manager. /// /// TODO: The resource manager should probably be a singleton too since it's already setup to /// be used through shared references. pub fn resource_manager<'a>() -> &'a ResourceManager { let instance = Engine::instance(); &*instance.resource_manager } pub fn renderer<F, T>(func: F) -> T where F: FnOnce(&mut Renderer) -> T, { let instance = Engine::instance(); let mut renderer = instance.renderer.lock().expect("Could not acquire lock on renderer mutex"); func(&mut **renderer) } pub fn window() -> &'static Window { &Engine::instance().window } fn main_loop(&mut self) { let timer = Timer::new(); let mut collector = Collector::new().unwrap(); loop { let _stopwatch = Stopwatch::new("loop"); let start_time = timer.now(); self.update(); self.draw(); if self.close { println!("shutting down engine"); break; } if !cfg!(feature="timing") && timer.elapsed_ms(start_time) > TARGET_FRAME_TIME_MS { println!( "WARNING: Missed frame time. Frame time: {}ms, target frame time: {}ms", timer.elapsed_ms(start_time), TARGET_FRAME_TIME_MS); } // Wait for target frame time. let mut remaining_time_ms = TARGET_FRAME_TIME_MS - timer.elapsed_ms(start_time); while remaining_time_ms > 1.0 { thread::sleep(Duration::from_millis(remaining_time_ms as u64)); remaining_time_ms = TARGET_FRAME_TIME_MS - timer.elapsed_ms(start_time); } while remaining_time_ms > 0.0 { remaining_time_ms = TARGET_FRAME_TIME_MS - timer.elapsed_ms(start_time); } // TODO: Don't flip buffers until end of frame time? }; collector.flush_to_file("stopwatch.csv"); } fn update(&mut self) { let _stopwatch = Stopwatch::new("update"); let scene = &mut self.scene; scene.input.clear(); // TODO: Make this an iterator to simplify this loop. while let Some(message) = self.window.next_message() { match message { Activate => (), Close => self.close = true, Destroy => (), Paint => (), // Handle inputs. KeyDown(_) | KeyUp(_) | MouseMove(_, _) | MousePos(_, _) | MouseButtonPressed(_) | MouseButtonReleased(_) | MouseWheel(_) => scene.input.push_input(message), } } // TODO: More efficient handling of debug pause (i.e. something that doesn't have any // overhead when doing a release build). if !self.debug_pause || scene.input.key_pressed(ScanCode::F11) { self.debug_draw.clear_buffer(); self.alarm_update.update(scene, TARGET_FRAME_TIME_SECONDS); // Update systems. for (_, system) in self.systems.iter_mut() { system.update(scene, TARGET_FRAME_TIME_SECONDS); } // Update component managers. scene.update_managers(); } // Update debug systems always forever. for (_, system) in self.debug_systems.iter_mut() { system.update(scene, TARGET_FRAME_TIME_SECONDS); } // NOTE: Transform update used to go here. if !self.debug_pause || scene.input.key_pressed(ScanCode::F11) { self.collision_update.update(scene, TARGET_FRAME_TIME_SECONDS); self.audio_update.update(scene, TARGET_FRAME_TIME_SECONDS); } if scene.input.key_pressed(ScanCode::F9) { self.debug_pause = !self.debug_pause; } if scene.input.key_pressed(ScanCode::F11) { self.debug_pause = true; } } #[cfg(not(feature="no-draw"))] fn draw(&mut self) { let _stopwatch = Stopwatch::new("draw"); self.renderer .lock() .expect("Unable to acquire lock on renderer mutex for drawing") .draw(); } #[cfg(feature="no-draw")] fn draw(&mut self) {} } unsafe impl Singleton for Engine { /// Creates the instance of the singleton. fn set_instance(engine: Engine) { assert!(unsafe { INSTANCE.is_null() }, "Cannot create more than one Engine instance"); let boxed_engine = Box::new(engine); unsafe { INSTANCE = Box::into_raw(boxed_engine); } } /// Retrieves an immutable reference to the singleton instance. /// /// This function is unsafe because there is no way of know fn instance() -> &'static Self { unsafe { debug_assert!(!INSTANCE.is_null(), "Cannot retrieve Engine instance because none exists"); &*INSTANCE } } /// Destroys the instance of the singleton. unsafe fn destroy_instance() { let ptr = mem::replace(&mut INSTANCE, ptr::null_mut()); Box::from_raw(ptr); } } pub struct EngineBuilder { systems: HashMap<SystemId, Box<System>>, debug_systems: HashMap<SystemId, Box<System>>, managers: ManagerMap, max_workers: usize, } /// A builder for configuring the components and systems registered with the game engine. /// /// Component managers and systems cannot be changed once the engine has been instantiated so they /// must be provided all together when the instance is created. `EngineBuilder` provides an /// interface for gathering all managers and systems to be provided to the engine. impl EngineBuilder { /// Creates a new `EngineBuilder` object. pub fn new() -> EngineBuilder { let mut builder = EngineBuilder { systems: HashMap::new(), debug_systems: HashMap::new(), managers: ManagerMap::new(), max_workers: 1, }; // Register internal component managers. builder.register_component::<Transform>(); builder.register_component::<Camera>(); builder.register_component::<Light>(); builder.register_component::<Mesh>(); builder.register_component::<AudioSource>(); builder.register_component::<AlarmId>(); builder.register_component::<Collider>(); builder } /// Consumes the builder and creates the `Engine` instance. /// /// No `Engine` object is returned because this method instantiates the engine singleton. pub fn build(self) { let engine = { let window = { let mut window = unsafe { mem::uninitialized() }; let mut out = unsafe { Unique::new(&mut window as *mut _) }; let barrier = Arc::new(Barrier::new(2)); let barrier_clone = barrier.clone(); thread::spawn(move || { let mut window = Window::new("gunship game").unwrap(); let mut message_pump = window.message_pump(); // write data out to `window` without dropping the old (uninitialized) value. unsafe { ptr::write(out.get_mut(), window); } // Sync with barrier_clone.wait(); message_pump.run(); }); // Wait until window thread finishe creating the window. barrier.wait(); window }; let mut renderer = RendererBuilder::new(&window).build(); let debug_draw = DebugDraw::new(&mut *renderer); let resource_manager = Box::new(ResourceManager::new()); let audio_source = match bs_audio::init() { Ok(audio_source) => audio_source, Err(error) => { // TODO: Rather than panicking, create a null audio system and keep running. panic!("Error while initialzing audio subsystem: {}", error) }, }; Engine { window: window, renderer: Mutex::new(renderer), resource_manager: resource_manager, systems: self.systems, debug_systems: self.debug_systems, audio_update: Box::new(AudioSystem), alarm_update: Box::new(alarm_update), collision_update: Box::new(CollisionSystem::new()), scene: Scene::new(audio_source, self.managers), debug_draw: debug_draw, close: false, debug_pause: false, } }; // Init aysnc subsystem. ::async::init(); ::async::start_workers(self.max_workers); Engine::set_instance(engine); run!(Engine::start()); } pub fn max_workers(&mut self, workers: usize) -> &mut EngineBuilder { assert!(workers > 0, "There must be at least one worker for the engine to run"); self.max_workers = workers; self } /// Registers the manager for the specified component type. /// /// Defers internally to `register_manager()`. pub fn register_component<T: Component>(&mut self) -> &mut EngineBuilder { T::Manager::register(self); self } /// Registers the specified manager with the engine. /// /// Defers internally to `ComponentManager::register()`. pub fn register_manager<T: ComponentManager>(&mut self, manager: T) -> &mut EngineBuilder { let manager_id = ManagerId::of::<T>(); assert!( !self.managers.contains_key(&manager_id), "Manager {} with ID {:?} already registered", unsafe { type_name::<T>() }, &manager_id); // Box the manager as a trait object to construct the data and vtable pointers. let boxed_manager = Box::new(manager); // Add the manager to the type map and the component id to the component map. self.managers.insert(manager_id, boxed_manager); self } /// Registers the system with the engine. pub fn register_system<T: System>(&mut self, system: T) -> &mut EngineBuilder { let system_id = SystemId::of::<T>(); assert!( !self.systems.contains_key(&system_id), "System {} with ID {:?} already registered", unsafe { type_name::<T>() }, &system_id); self.systems.insert(system_id, Box::new(system)); self } /// Registers the debug system with the engine. pub fn register_debug_system<T: System>(&mut self, system: T) -> &mut EngineBuilder { let system_id = SystemId::of::<T>(); assert!( !self.debug_systems.contains_key(&system_id), "System {} with ID {:?} already registered", unsafe { type_name::<T>() }, &system_id); self.debug_systems.insert(system_id, Box::new(system)); self } }<|fim▁end|>
/// Retrieves a reference to current scene. /// /// Panics if the engine hasn't been created yet. pub fn scene<'a>() -> &'a Scene {
<|file_name|>VariableIdPattern.py<|end_file_name|><|fim▁begin|># Copyright 2016 Casey Jaymes # This file is part of PySCAP.<|fim▁hole|># it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # PySCAP is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with PySCAP. If not, see <http://www.gnu.org/licenses/>. import logging from scap.model.xs.StringType import StringType logger = logging.getLogger(__name__) class VariableIdPattern(StringType): # <xsd:pattern value="oval:[A-Za-z0-9_\-\.]+:var:[1-9][0-9]*"/> def get_value_pattern(self): return r'oval:[A-Za-z0-9_\-\.]+:var:[1-9][0-9]*'<|fim▁end|>
# # PySCAP is free software: you can redistribute it and/or modify
<|file_name|>activations.py<|end_file_name|><|fim▁begin|>from __future__ import absolute_import import six import warnings from . import backend as K from .utils.generic_utils import deserialize_keras_object from .engine import Layer def softmax(x, axis=-1): """Softmax activation function. # Arguments x : Tensor. axis: Integer, axis along which the softmax normalization is applied. # Returns Tensor, output of softmax transformation. # Raises ValueError: In case `dim(x) == 1`. """ ndim = K.ndim(x)<|fim▁hole|> if ndim == 2: return K.softmax(x) elif ndim > 2: e = K.exp(x - K.max(x, axis=axis, keepdims=True)) s = K.sum(e, axis=axis, keepdims=True) return e / s else: raise ValueError('Cannot apply softmax to a tensor that is 1D') def elu(x, alpha=1.0): return K.elu(x, alpha) def selu(x): """Scaled Exponential Linear Unit. (Klambauer et al., 2017) # Arguments x: A tensor or variable to compute the activation function for. # References - [Self-Normalizing Neural Networks](https://arxiv.org/abs/1706.02515) """ alpha = 1.6732632423543772848170429916717 scale = 1.0507009873554804934193349852946 return scale * K.elu(x, alpha) def softplus(x): return K.softplus(x) def softsign(x): return K.softsign(x) def relu(x, alpha=0., max_value=None): return K.relu(x, alpha=alpha, max_value=max_value) def tanh(x): return K.tanh(x) def sigmoid(x): return K.sigmoid(x) def hard_sigmoid(x): return K.hard_sigmoid(x) def linear(x): return x def serialize(activation): return activation.__name__ def deserialize(name, custom_objects=None): return deserialize_keras_object(name, module_objects=globals(), custom_objects=custom_objects, printable_module_name='activation function') def get(identifier): if identifier is None: return linear if isinstance(identifier, six.string_types): identifier = str(identifier) return deserialize(identifier) elif callable(identifier): if isinstance(identifier, Layer): warnings.warn(( 'Do not pass a layer instance (such as {identifier}) as the ' 'activation argument of another layer. Instead, advanced ' 'activation layers should be used just like any other ' 'layer in a model.' ).format(identifier=identifier.__class__.__name__)) return identifier else: raise ValueError('Could not interpret ' 'activation function identifier:', identifier)<|fim▁end|>
<|file_name|>CtrlDialogView.js<|end_file_name|><|fim▁begin|>define(['backbone', 'marionette', 'mustache', 'jquery', 'text!templates/ctrldialog.html'], function(Backbone, Marionette, Mustache, $, template) { return Marionette.ItemView.extend({<|fim▁hole|> this.model = new Backbone.Model( options ); this.render(); }, template: function(serialized_model) { return Mustache.render(template, serialized_model); }, ui: { 'ok': '.btn-ok', 'cancel': '.btn-cancel', 'dialog': '.dialog', 'close': '.dialog-close' }, events: { 'tap @ui.ok': 'onOk', 'tap @ui.cancel': 'onCancel', 'tap @ui.close': 'onCancel' }, onOk: function(ev) { this.trigger('ok'); this.destroy(); }, onCancel: function(ev) { this.trigger('cancel'); this.destroy(); }, onRender: function() { $('body').append(this.$el); this.ui.dialog.css({ 'marginTop': 0 - this.ui.dialog.height()/2 }); this.ui.dialog.addClass('bounceInDown animated'); }, onDestory: function() { this.$el.remove(); this.model.destroy(); }, className: 'dialogContainer' }); });<|fim▁end|>
initialize: function(options) { if (!options.icon_name) { options.icon_name = 'bird'; }
<|file_name|>compress.js<|end_file_name|><|fim▁begin|>/* * grunt-contrib-compress * http://gruntjs.com/ * * Copyright (c) 2016 Chris Talkington, contributors * Licensed under the MIT license. */ 'use strict'; var fs = require('fs'); var path = require('path'); var prettyBytes = require('pretty-bytes'); var chalk = require('chalk'); var zlib = require('zlib'); var archiver = require('archiver'); var streamBuffers = require('stream-buffers'); var _ = require('lodash'); module.exports = function(grunt) { var exports = { options: {} }; var fileStatSync = function() { var filepath = path.join.apply(path, arguments); if (grunt.file.exists(filepath)) { return fs.statSync(filepath); } return false; }; // 1 to 1 gziping of files exports.gzip = function(files, done) { exports.singleFile(files, zlib.createGzip, 'gz', done); grunt.log.ok('Compressed ' + chalk.cyan(files.length) + ' ' + grunt.util.pluralize(files.length, 'file/files.')); }; // 1 to 1 deflate of files exports.deflate = function(files, done) { exports.singleFile(files, zlib.createDeflate, 'deflate', done); grunt.log.ok('Compressed ' + chalk.cyan(files.length) + ' ' + grunt.util.pluralize(files.length, 'file/files.')); }; // 1 to 1 deflateRaw of files exports.deflateRaw = function(files, done) { exports.singleFile(files, zlib.createDeflateRaw, 'deflate', done); grunt.log.ok('Compressed ' + chalk.cyan(files.length) + ' ' + grunt.util.pluralize(files.length, 'file/files.')); }; // 1 to 1 compression of files, expects a compatible zlib method to be passed in, see above exports.singleFile = function(files, algorithm, extension, done) { grunt.util.async.forEachSeries(files, function(filePair, nextPair) { grunt.util.async.forEachSeries(filePair.src, function(src, nextFile) { // Must be a file if (grunt.file.isDir(src)) { return nextFile(); } // Ensure the dest folder exists grunt.file.mkdir(path.dirname(filePair.dest)); var srcStream = fs.createReadStream(src); var originalSize = exports.getSize(src); var destStream; function initDestStream() { destStream = fs.createWriteStream(filePair.dest); destStream.on('close', function() { var compressedSize = exports.getSize(filePair.dest); var ratio = Math.round(parseInt(compressedSize, 10) / parseInt(originalSize, 10) * 100) + '%'; grunt.verbose.writeln('Created ' + chalk.cyan(filePair.dest) + ' (' + compressedSize + ') - ' + chalk.cyan(ratio) + ' of the original size'); nextFile(); }); } // write to memory stream if source and destination are the same var tmpStream; if (src === filePair.dest) { tmpStream = new streamBuffers.WritableStreamBuffer(); tmpStream.on('close', function() { initDestStream(); destStream.write(this.getContents()); destStream.end(); }); } else { initDestStream(); } var compressor = algorithm.call(zlib, exports.options); compressor.on('error', function(err) { grunt.log.error(err); grunt.fail.warn(algorithm + ' failed.'); nextFile(); }); srcStream.pipe(compressor).pipe(tmpStream || destStream); }, nextPair); }, done); }; // Compress with tar, tgz and zip exports.tar = function(files, done) { if (typeof exports.options.archive !== 'string' || exports.options.archive.length === 0) { grunt.fail.warn('Unable to compress; no valid archive file was specified.'); return; } var mode = exports.options.mode; if (mode === 'tgz') { mode = 'tar'; exports.options.gzip = true; } var archive = archiver.create(mode, exports.options); var dest = exports.options.archive; var dataWhitelist = ['comment', 'date', 'mode', 'store', 'gid', 'uid']; var sourcePaths = {}; // Ensure dest folder exists grunt.file.mkdir(path.dirname(dest)); // Where to write the file var destStream = fs.createWriteStream(dest); archive.on('error', function(err) { grunt.log.error(err); grunt.fail.warn('Archiving failed.'); }); archive.on('entry', function(file) { var sp = sourcePaths[file.name] || 'unknown'; grunt.verbose.writeln('Archived ' + chalk.cyan(sp) + ' -> ' + chalk.cyan(dest + '/' + file.name)); }); destStream.on('error', function(err) { grunt.log.error(err); grunt.fail.warn('WriteStream failed.'); }); destStream.on('close', function() { var size = archive.pointer(); grunt.verbose.writeln('Created ' + chalk.cyan(dest) + ' (' + exports.getSize(size) + ')'); done(); }); archive.pipe(destStream); files.forEach(function(file) { var isExpandedPair = file.orig.expand || false; file.src.forEach(function(srcFile) { var fstat = fileStatSync(srcFile); if (!fstat) { grunt.fail.warn('unable to stat srcFile (' + srcFile + ')'); return; } var internalFileName = isExpandedPair ? file.dest : exports.unixifyPath(path.join(file.dest || '', srcFile)); // check if internal file name is not a dot, should not be present in an archive if (internalFileName === '.' || internalFileName === './') { return; } if (fstat.isDirectory() && internalFileName.slice(-1) !== '/') { srcFile += '/'; internalFileName += '/'; } var fileData = { name: internalFileName, stats: fstat }; for (var i = 0; i < dataWhitelist.length; i++) { if (typeof file[dataWhitelist[i]] === 'undefined') { continue; } if (typeof file[dataWhitelist[i]] === 'function') { fileData[dataWhitelist[i]] = file[dataWhitelist[i]](srcFile); } else { fileData[dataWhitelist[i]] = file[dataWhitelist[i]]; } } if (fstat.isFile()) { archive.file(srcFile, fileData); } else if (fstat.isDirectory()) { archive.append(null, fileData); } else { grunt.fail.warn('srcFile (' + srcFile + ') should be a valid file or directory'); return; } sourcePaths[internalFileName] = srcFile; }); }); grunt.log.ok('Compressed ' + chalk.cyan(files.length) + ' ' + grunt.util.pluralize(files.length, 'file/files.')); archive.finalize(); }; exports.getSize = function(filename, pretty) { var size = 0; if (typeof filename === 'string') { try { size = fs.statSync(filename).size; } catch (e) {} } else { size = filename; } if (pretty !== false) { if (!exports.options.pretty) { return size + ' bytes'; } return prettyBytes(size); } return Number(size); }; exports.autoDetectMode = function(dest) { if (exports.options.mode) { return exports.options.mode; } if (!dest) { return 'gzip';<|fim▁hole|> return 'tgz'; } var ext = path.extname(dest).replace('.', ''); if (ext === 'gz') { return 'gzip'; } return ext; }; exports.unixifyPath = function(filepath) { return process.platform === 'win32' ? filepath.replace(/\\/g, '/') : filepath; }; return exports; };<|fim▁end|>
} if (_.endsWith(dest, '.tar.gz')) {
<|file_name|>bootstrap.py<|end_file_name|><|fim▁begin|>############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Bootstrap a buildout-based project Simply run this script in a directory containing a buildout.cfg. The script accepts buildout command-line options, so you can use the -c option to specify an alternate configuration file. """ import os, shutil, sys, tempfile, urllib, urllib2, subprocess from optparse import OptionParser if sys.platform == 'win32': def quote(c): if ' ' in c: return '"%s"' % c # work around spawn lamosity on windows else: return c else: quote = str # See zc.buildout.easy_install._has_broken_dash_S for motivation and comments. stdout, stderr = subprocess.Popen( [sys.executable, '-Sc', 'try:\n' ' import ConfigParser\n' 'except ImportError:\n' ' print 1\n' 'else:\n' ' print 0\n'], stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate() has_broken_dash_S = bool(int(stdout.strip())) # In order to be more robust in the face of system Pythons, we want to # run without site-packages loaded. This is somewhat tricky, in # particular because Python 2.6's distutils imports site, so starting # with the -S flag is not sufficient. However, we'll start with that: if not has_broken_dash_S and 'site' in sys.modules: # We will restart with python -S. args = sys.argv[:] args[0:0] = [sys.executable, '-S'] args = map(quote, args) os.execv(sys.executable, args) # Now we are running with -S. We'll get the clean sys.path, import site # because distutils will do it later, and then reset the path and clean # out any namespace packages from site-packages that might have been # loaded by .pth files. clean_path = sys.path[:] import site # imported because of its side effects sys.path[:] = clean_path for k, v in sys.modules.items(): if k in ('setuptools', 'pkg_resources') or ( hasattr(v, '__path__') and len(v.__path__) == 1 and not os.path.exists(os.path.join(v.__path__[0], '__init__.py'))): # This is a namespace package. Remove it. sys.modules.pop(k) is_jython = sys.platform.startswith('java') setuptools_source = 'https://bitbucket.org/pypa/setuptools/raw/0.7.2/ez_setup.py' distribute_source = 'http://python-distribute.org/distribute_setup.py' # parsing arguments def normalize_to_url(option, opt_str, value, parser): if value: if '://' not in value: # It doesn't smell like a URL. value = 'file://%s' % ( urllib.pathname2url( os.path.abspath(os.path.expanduser(value))),) if opt_str == '--download-base' and not value.endswith('/'): # Download base needs a trailing slash to make the world happy. value += '/' else: value = None name = opt_str[2:].replace('-', '_') setattr(parser.values, name, value) usage = '''\ [DESIRED PYTHON FOR BUILDOUT] bootstrap.py [options] Bootstraps a buildout-based project. Simply run this script in a directory containing a buildout.cfg, using the Python that you want bin/buildout to use. Note that by using --setup-source and --download-base to point to local resources, you can keep this script from going over the network. ''' parser = OptionParser(usage=usage) parser.add_option("-v", "--version", dest="version", help="use a specific zc.buildout version") parser.add_option("-d", "--distribute", action="store_true", dest="use_distribute", default=False, help="Use Distribute rather than Setuptools.") parser.add_option("--setup-source", action="callback", dest="setup_source", callback=normalize_to_url, nargs=1, type="string", help=("Specify a URL or file location for the setup file. " "If you use Setuptools, this will default to " + setuptools_source + "; if you use Distribute, this " "will default to " + distribute_source + ".")) parser.add_option("--download-base", action="callback", dest="download_base", callback=normalize_to_url, nargs=1, type="string", help=("Specify a URL or directory for downloading " "zc.buildout and either Setuptools or Distribute. " "Defaults to PyPI.")) parser.add_option("--eggs", help=("Specify a directory for storing eggs. Defaults to " "a temporary directory that is deleted when the " "bootstrap script completes.")) parser.add_option("-t", "--accept-buildout-test-releases", dest='accept_buildout_test_releases', action="store_true", default=False, help=("Normally, if you do not specify a --version, the " "bootstrap script and buildout gets the newest " "*final* versions of zc.buildout and its recipes and " "extensions for you. If you use this flag, " "bootstrap and buildout will get the newest releases " "even if they are alphas or betas.")) parser.add_option("-c", None, action="store", dest="config_file", help=("Specify the path to the buildout configuration " "file to be used.")) options, args = parser.parse_args() # if -c was provided, we push it back into args for buildout's main function if options.config_file is not None: args += ['-c', options.config_file] if options.eggs: eggs_dir = os.path.abspath(os.path.expanduser(options.eggs)) else: eggs_dir = tempfile.mkdtemp() if options.setup_source is None: if options.use_distribute: options.setup_source = distribute_source else: options.setup_source = setuptools_source if options.accept_buildout_test_releases: args.append('buildout:accept-buildout-test-releases=true') args.append('bootstrap') try: import pkg_resources import setuptools # A flag. Sometimes pkg_resources is installed alone. if not hasattr(pkg_resources, '_distribute'): raise ImportError except ImportError: ez_code = urllib2.urlopen( options.setup_source).read().replace('\r\n', '\n') ez = {} exec ez_code in ez setup_args = dict(to_dir=eggs_dir, download_delay=0) if options.download_base: setup_args['download_base'] = options.download_base if options.use_distribute: setup_args['no_fake'] = True ez['use_setuptools'](**setup_args) if 'pkg_resources' in sys.modules: reload(sys.modules['pkg_resources']) import pkg_resources # This does not (always?) update the default working set. We will # do it. for path in sys.path: if path not in pkg_resources.working_set.entries: pkg_resources.working_set.add_entry(path) cmd = [quote(sys.executable), '-c',<|fim▁hole|>if not has_broken_dash_S: cmd.insert(1, '-S') find_links = options.download_base if not find_links: find_links = os.environ.get('bootstrap-testing-find-links') if find_links: cmd.extend(['-f', quote(find_links)]) if options.use_distribute: setup_requirement = 'distribute' else: setup_requirement = 'setuptools' ws = pkg_resources.working_set setup_requirement_path = ws.find( pkg_resources.Requirement.parse(setup_requirement)).location env = dict( os.environ, PYTHONPATH=setup_requirement_path) requirement = 'zc.buildout' version = options.version if version is None and not options.accept_buildout_test_releases: # Figure out the most recent final version of zc.buildout. import setuptools.package_index _final_parts = '*final-', '*final' def _final_version(parsed_version): for part in parsed_version: if (part[:1] == '*') and (part not in _final_parts): return False return True index = setuptools.package_index.PackageIndex( search_path=[setup_requirement_path]) if find_links: index.add_find_links((find_links,)) req = pkg_resources.Requirement.parse(requirement) if index.obtain(req) is not None: best = [] bestv = None for dist in index[req.project_name]: distv = dist.parsed_version if _final_version(distv): if bestv is None or distv > bestv: best = [dist] bestv = distv elif distv == bestv: best.append(dist) if best: best.sort() version = best[-1].version if version: requirement = '=='.join((requirement, version)) cmd.append(requirement) if is_jython: import subprocess exitcode = subprocess.Popen(cmd, env=env).wait() else: # Windows prefers this, apparently; otherwise we would prefer subprocess exitcode = os.spawnle(*([os.P_WAIT, sys.executable] + cmd + [env])) if exitcode != 0: sys.stdout.flush() sys.stderr.flush() print ("An error occurred when trying to install zc.buildout. " "Look above this message for any errors that " "were output by easy_install.") sys.exit(exitcode) ws.add_entry(eggs_dir) ws.require(requirement) import zc.buildout.buildout zc.buildout.buildout.main(args) if not options.eggs: # clean up temporary egg directory shutil.rmtree(eggs_dir)<|fim▁end|>
quote('from setuptools.command.easy_install import main; main()'), '-mqNxd', quote(eggs_dir)]