code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
package com.paratussoftware.ui.cli; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class GrimoireCLI { private static final String TITLE_FILE_NAME = "./lib/grimoire_title.txt"; public static void startGrimoireCLI(String[] args){ showTitle(); CLIMenuManager cliMenuManager = new CLIMenuManager(); while (true){ cliMenuManager.showMainMenu(); } } public static void showTitle(){ try (BufferedReader br = new BufferedReader(new FileReader(TITLE_FILE_NAME))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) {} } }
JArthurJohnston/Grimoire-V2
Demo/src/main/java/com/paratussoftware/ui/cli/GrimoireCLI.java
Java
mit
754
<?php namespace BDN\Migrations; use Doctrine\DBAL\Migrations\AbstractMigration; use Doctrine\DBAL\Schema\Schema; /** * Auto-generated Migration: Please modify to your needs! */ class Version20170820234613 extends AbstractMigration { /** * @param Schema $schema */ public function up(Schema $schema) { // this up() migration is auto-generated, please modify it to your needs $this->abortIf( $this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.' ); $this->addSql( 'CREATE TABLE cron_task (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, commands LONGTEXT NOT NULL COMMENT \'(DC2Type:array)\', `interval` INT NOT NULL, lastrun DATETIME DEFAULT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE orders (id INT AUTO_INCREMENT NOT NULL, number VARCHAR(255) DEFAULT NULL, additional_information VARCHAR(1000) DEFAULT NULL, state VARCHAR(255) NOT NULL, completed_at DATETIME DEFAULT NULL, items_total INT NOT NULL, adjustments_total INT NOT NULL, total INT NOT NULL, created_at DATETIME NOT NULL, updated_at DATETIME DEFAULT NULL, deleted_at DATETIME DEFAULT NULL, email VARCHAR(255) NOT NULL, UNIQUE INDEX UNIQ_E52FFDEE96901F54 (number), UNIQUE INDEX UNIQ_E52FFDEEE7927C74 (email), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE order_items (id INT AUTO_INCREMENT NOT NULL, order_id INT NOT NULL, quantity INT NOT NULL, unit_price INT NOT NULL, units_total INT NOT NULL, adjustments_total INT NOT NULL, total INT NOT NULL, is_immutable TINYINT(1) NOT NULL, INDEX IDX_62809DB08D9F6D38 (order_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE user_group (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(180) NOT NULL, roles LONGTEXT NOT NULL COMMENT \'(DC2Type:array)\', community_id INT NOT NULL, UNIQUE INDEX UNIQ_8F02BF9D5E237E06 (name), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE login_access_tokens (id INT AUTO_INCREMENT NOT NULL, user_id INT DEFAULT NULL, t_key VARCHAR(255) NOT NULL, expired TINYINT(1) NOT NULL, date DATETIME NOT NULL, redirect VARCHAR(255) DEFAULT NULL, UNIQUE INDEX UNIQ_7EC367D32CCFDC5D (t_key), INDEX IDX_7EC367D3A76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE oauth2_access_tokens (id INT AUTO_INCREMENT NOT NULL, client_id INT NOT NULL, user_id INT DEFAULT NULL, token VARCHAR(255) NOT NULL, expires_at INT DEFAULT NULL, scope VARCHAR(255) DEFAULT NULL, UNIQUE INDEX UNIQ_D247A21B5F37A13B (token), INDEX IDX_D247A21B19EB6921 (client_id), INDEX IDX_D247A21BA76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE oauth2_auth_codes (id INT AUTO_INCREMENT NOT NULL, client_id INT NOT NULL, user_id INT DEFAULT NULL, token VARCHAR(255) NOT NULL, redirect_uri LONGTEXT NOT NULL, expires_at INT DEFAULT NULL, scope VARCHAR(255) DEFAULT NULL, UNIQUE INDEX UNIQ_A018A10D5F37A13B (token), INDEX IDX_A018A10D19EB6921 (client_id), INDEX IDX_A018A10DA76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE oauth2_clients (id INT AUTO_INCREMENT NOT NULL, random_id VARCHAR(255) NOT NULL, redirect_uris LONGTEXT NOT NULL COMMENT \'(DC2Type:array)\', secret VARCHAR(255) NOT NULL, allowed_grant_types LONGTEXT NOT NULL COMMENT \'(DC2Type:array)\', name VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE oauth2_refresh_tokens (id INT AUTO_INCREMENT NOT NULL, client_id INT NOT NULL, user_id INT DEFAULT NULL, token VARCHAR(255) NOT NULL, expires_at INT DEFAULT NULL, scope VARCHAR(255) DEFAULT NULL, UNIQUE INDEX UNIQ_D394478C5F37A13B (token), INDEX IDX_D394478C19EB6921 (client_id), INDEX IDX_D394478CA76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE session (id INT AUTO_INCREMENT NOT NULL, ip VARCHAR(45) NOT NULL, date DATETIME NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE user (id INT AUTO_INCREMENT NOT NULL, username VARCHAR(180) NOT NULL, username_canonical VARCHAR(180) NOT NULL, email VARCHAR(180) NOT NULL, email_canonical VARCHAR(180) NOT NULL, enabled TINYINT(1) NOT NULL, salt VARCHAR(255) DEFAULT NULL, password VARCHAR(255) NOT NULL, last_login DATETIME DEFAULT NULL, confirmation_token VARCHAR(180) DEFAULT NULL, password_requested_at DATETIME DEFAULT NULL, roles LONGTEXT NOT NULL COMMENT \'(DC2Type:array)\', api_key VARCHAR(255) DEFAULT NULL, google_authenticator_secret VARCHAR(255) DEFAULT NULL, forums_id INT NOT NULL, forums_access_token INT NOT NULL, community_id INT NOT NULL, UNIQUE INDEX UNIQ_8D93D64992FC23A8 (username_canonical), UNIQUE INDEX UNIQ_8D93D649A0D96FBF (email_canonical), UNIQUE INDEX UNIQ_8D93D649C05FB297 (confirmation_token), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE user_user_group (user_id INT NOT NULL, group_id INT NOT NULL, INDEX IDX_28657971A76ED395 (user_id), INDEX IDX_28657971FE54D947 (group_id), PRIMARY KEY(user_id, group_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE user_oauth_clients (user_id INT NOT NULL, client_id INT NOT NULL, INDEX IDX_FD402C51A76ED395 (user_id), INDEX IDX_FD402C5119EB6921 (client_id), PRIMARY KEY(user_id, client_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE slack_invite (id INT AUTO_INCREMENT NOT NULL, user_id INT DEFAULT NULL, date DATETIME NOT NULL, INDEX IDX_738D77CA76ED395 (user_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE language (id INT AUTO_INCREMENT NOT NULL, active TINYINT(1) NOT NULL, language_key VARCHAR(15) NOT NULL, language VARCHAR(64) NOT NULL, UNIQUE INDEX UNIQ_D4DB71B55B160485 (language_key), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE library (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, version DOUBLE PRECISION NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE script (id INT AUTO_INCREMENT NOT NULL, git_id INT DEFAULT NULL, creator_id INT DEFAULT NULL, name VARCHAR(255) NOT NULL, product LONGTEXT NOT NULL COMMENT \'(DC2Type:object)\', description LONGTEXT NOT NULL, forum INT DEFAULT NULL, active TINYINT(1) NOT NULL, build_type_id VARCHAR(255) DEFAULT NULL, UNIQUE INDEX UNIQ_1C81873A5E237E06 (name), UNIQUE INDEX UNIQ_1C81873A4D4CA094 (git_id), INDEX IDX_1C81873A61220EA6 (creator_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE script_authors (script_id INT NOT NULL, user_id INT NOT NULL, INDEX IDX_D304ED1BA1C01850 (script_id), INDEX IDX_D304ED1BA76ED395 (user_id), PRIMARY KEY(script_id, user_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE script_users (script_id INT NOT NULL, user_id INT NOT NULL, INDEX IDX_78458A76A1C01850 (script_id), INDEX IDX_78458A76A76ED395 (user_id), PRIMARY KEY(script_id, user_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE script_groups (script_id INT NOT NULL, group_id INT NOT NULL, INDEX IDX_90B1718AA1C01850 (script_id), INDEX IDX_90B1718AFE54D947 (group_id), PRIMARY KEY(script_id, group_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE script_categories (script_id INT NOT NULL, category_id INT NOT NULL, INDEX IDX_CD9E8798A1C01850 (script_id), INDEX IDX_CD9E879812469DE2 (category_id), PRIMARY KEY(script_id, category_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE category (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE git (id INT AUTO_INCREMENT NOT NULL, url VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE releases (id INT AUTO_INCREMENT NOT NULL, script_id INT DEFAULT NULL, changelog LONGTEXT DEFAULT NULL, version DOUBLE PRECISION NOT NULL, date DATETIME NOT NULL, INDEX IDX_7896E4D1A1C01850 (script_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE review (id INT AUTO_INCREMENT NOT NULL, user_id INT DEFAULT NULL, script_id INT DEFAULT NULL, review LONGTEXT NOT NULL, stars INT NOT NULL, date DATETIME NOT NULL, accepted TINYINT(1) NOT NULL, INDEX IDX_794381C6A76ED395 (user_id), INDEX IDX_794381C6A1C01850 (script_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE hook (id INT AUTO_INCREMENT NOT NULL, server_id INT DEFAULT NULL, accessor VARCHAR(255) DEFAULT NULL, methodname VARCHAR(255) DEFAULT NULL, desctype VARCHAR(255) DEFAULT NULL, callclass VARCHAR(255) DEFAULT NULL, callmethod VARCHAR(255) DEFAULT NULL, calldesc VARCHAR(255) DEFAULT NULL, callargs VARCHAR(255) DEFAULT NULL, field VARCHAR(255) DEFAULT NULL, descfield VARCHAR(255) DEFAULT NULL, intoclass VARCHAR(255) DEFAULT NULL, classname VARCHAR(255) DEFAULT NULL, interface VARCHAR(255) DEFAULT NULL, invokemethod VARCHAR(255) DEFAULT NULL, argsdesc VARCHAR(255) DEFAULT NULL, type VARCHAR(255) NOT NULL, version DOUBLE PRECISION NOT NULL, INDEX IDX_A45843551844E6B7 (server_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE server (id INT AUTO_INCREMENT NOT NULL, server_id INT DEFAULT NULL, name VARCHAR(255) NOT NULL, active TINYINT(1) NOT NULL, version DOUBLE PRECISION NOT NULL, description LONGTEXT NOT NULL, provider_id INT DEFAULT NULL, INDEX IDX_5A6DD5F6A53A8AA (provider_id), UNIQUE INDEX UNIQ_5A6DD5F61844E6B7 (server_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE server_groups (server_id INT NOT NULL, group_id INT NOT NULL, INDEX IDX_891100B61844E6B7 (server_id), INDEX IDX_891100B6FE54D947 (group_id), PRIMARY KEY(server_id, group_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE server_authors (server_id INT NOT NULL, user_id INT NOT NULL, INDEX IDX_FC7231ED1844E6B7 (server_id), INDEX IDX_FC7231EDA76ED395 (user_id), PRIMARY KEY(server_id, user_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE server_details (server_id INT NOT NULL, serverdetail_id INT NOT NULL, INDEX IDX_5810361844E6B7 (server_id), INDEX IDX_58103634B5C767 (serverdetail_id), PRIMARY KEY(server_id, serverdetail_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE server_detail (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, value VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE server_slack_channel (id INT AUTO_INCREMENT NOT NULL, channel VARCHAR(255) NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE server_use (id INT AUTO_INCREMENT NOT NULL, datetime DATETIME NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE user_serveruses (serveruse_id INT NOT NULL, user_id INT NOT NULL, INDEX IDX_2E513393EB1E3248 (serveruse_id), INDEX IDX_2E513393A76ED395 (user_id), PRIMARY KEY(serveruse_id, user_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE server_serveruse (serveruse_id INT NOT NULL, server_id INT NOT NULL, INDEX IDX_28A1B5EAEB1E3248 (serveruse_id), INDEX IDX_28A1B5EA1844E6B7 (server_id), PRIMARY KEY(serveruse_id, server_id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE user_signature (id INT AUTO_INCREMENT NOT NULL, username VARCHAR(255) NOT NULL, abstract_signature_id INT DEFAULT NULL, INDEX IDX_AE688CA57E0AA10B (abstract_signature_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE type_client (id INT AUTO_INCREMENT NOT NULL, version VARCHAR(255) NOT NULL, release_date DATETIME NOT NULL, branch VARCHAR(255) NOT NULL, stable TINYINT(1) NOT NULL, build_id INT NOT NULL, active TINYINT(1) DEFAULT \'1\' NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE type_default_provider (id INT AUTO_INCREMENT NOT NULL, version VARCHAR(255) NOT NULL, release_date DATETIME NOT NULL, branch VARCHAR(255) NOT NULL, stable TINYINT(1) NOT NULL, build_id INT NOT NULL, active TINYINT(1) DEFAULT \'1\' NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE type_dreamscape_provider (id INT AUTO_INCREMENT NOT NULL, version VARCHAR(255) NOT NULL, release_date DATETIME NOT NULL, branch VARCHAR(255) NOT NULL, stable TINYINT(1) NOT NULL, build_id INT NOT NULL, active TINYINT(1) DEFAULT \'1\' NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE type_osscape_provider (id INT AUTO_INCREMENT NOT NULL, version VARCHAR(255) NOT NULL, release_date DATETIME NOT NULL, branch VARCHAR(255) NOT NULL, stable TINYINT(1) NOT NULL, build_id INT NOT NULL, active TINYINT(1) DEFAULT \'1\' NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE type_pkhonor_provider (id INT AUTO_INCREMENT NOT NULL, version VARCHAR(255) NOT NULL, release_date DATETIME NOT NULL, branch VARCHAR(255) NOT NULL, stable TINYINT(1) NOT NULL, build_id INT NOT NULL, active TINYINT(1) DEFAULT \'1\' NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE type_randoms (id INT AUTO_INCREMENT NOT NULL, version VARCHAR(255) NOT NULL, release_date DATETIME NOT NULL, branch VARCHAR(255) NOT NULL, stable TINYINT(1) NOT NULL, build_id INT NOT NULL, active TINYINT(1) DEFAULT \'1\' NOT NULL, PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE sylius_sequence (id INT AUTO_INCREMENT NOT NULL, idx INT NOT NULL, type VARCHAR(255) NOT NULL, UNIQUE INDEX UNIQ_AD3D8CC48CDE5729 (type), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE sylius_adjustment (id INT AUTO_INCREMENT NOT NULL, order_id INT DEFAULT NULL, order_item_id INT DEFAULT NULL, order_item_unit_id INT DEFAULT NULL, type VARCHAR(255) NOT NULL, label VARCHAR(255) DEFAULT NULL, amount INT NOT NULL, is_neutral TINYINT(1) NOT NULL, is_locked TINYINT(1) NOT NULL, origin_id INT DEFAULT NULL, origin_type VARCHAR(255) DEFAULT NULL, created_at DATETIME NOT NULL, updated_at DATETIME DEFAULT NULL, INDEX IDX_ACA6E0F28D9F6D38 (order_id), INDEX IDX_ACA6E0F2E415FB15 (order_item_id), INDEX IDX_ACA6E0F2F720C233 (order_item_unit_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE sylius_order_comment (id INT AUTO_INCREMENT NOT NULL, order_id INT NOT NULL, state VARCHAR(255) NOT NULL, comment LONGTEXT DEFAULT NULL, notify_customer TINYINT(1) NOT NULL, author VARCHAR(255) NOT NULL, created_at DATETIME NOT NULL, updated_at DATETIME DEFAULT NULL, INDEX IDX_8EA9CF098D9F6D38 (order_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE sylius_order_identity (id INT AUTO_INCREMENT NOT NULL, order_id INT NOT NULL, name VARCHAR(255) NOT NULL, value VARCHAR(255) DEFAULT NULL, INDEX IDX_5757A18E8D9F6D38 (order_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'CREATE TABLE sylius_order_item_unit (id INT AUTO_INCREMENT NOT NULL, order_item_id INT NOT NULL, adjustments_total INT NOT NULL, INDEX IDX_82BF226EE415FB15 (order_item_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE = InnoDB' ); $this->addSql( 'ALTER TABLE order_items ADD CONSTRAINT FK_62809DB08D9F6D38 FOREIGN KEY (order_id) REFERENCES orders (id) ON DELETE CASCADE' ); $this->addSql( 'ALTER TABLE login_access_tokens ADD CONSTRAINT FK_7EC367D3A76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE oauth2_access_tokens ADD CONSTRAINT FK_D247A21B19EB6921 FOREIGN KEY (client_id) REFERENCES oauth2_clients (id)' ); $this->addSql( 'ALTER TABLE oauth2_access_tokens ADD CONSTRAINT FK_D247A21BA76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE oauth2_auth_codes ADD CONSTRAINT FK_A018A10D19EB6921 FOREIGN KEY (client_id) REFERENCES oauth2_clients (id)' ); $this->addSql( 'ALTER TABLE oauth2_auth_codes ADD CONSTRAINT FK_A018A10DA76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE oauth2_refresh_tokens ADD CONSTRAINT FK_D394478C19EB6921 FOREIGN KEY (client_id) REFERENCES oauth2_clients (id)' ); $this->addSql( 'ALTER TABLE oauth2_refresh_tokens ADD CONSTRAINT FK_D394478CA76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE user_user_group ADD CONSTRAINT FK_28657971A76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE user_user_group ADD CONSTRAINT FK_28657971FE54D947 FOREIGN KEY (group_id) REFERENCES user_group (id)' ); $this->addSql( 'ALTER TABLE user_oauth_clients ADD CONSTRAINT FK_FD402C51A76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE user_oauth_clients ADD CONSTRAINT FK_FD402C5119EB6921 FOREIGN KEY (client_id) REFERENCES oauth2_clients (id)' ); $this->addSql( 'ALTER TABLE slack_invite ADD CONSTRAINT FK_738D77CA76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql('ALTER TABLE script ADD CONSTRAINT FK_1C81873A4D4CA094 FOREIGN KEY (git_id) REFERENCES git (id)'); $this->addSql( 'ALTER TABLE script ADD CONSTRAINT FK_1C81873A61220EA6 FOREIGN KEY (creator_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE script_authors ADD CONSTRAINT FK_D304ED1BA1C01850 FOREIGN KEY (script_id) REFERENCES script (id)' ); $this->addSql( 'ALTER TABLE script_authors ADD CONSTRAINT FK_D304ED1BA76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE script_users ADD CONSTRAINT FK_78458A76A1C01850 FOREIGN KEY (script_id) REFERENCES script (id)' ); $this->addSql( 'ALTER TABLE script_users ADD CONSTRAINT FK_78458A76A76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE script_groups ADD CONSTRAINT FK_90B1718AA1C01850 FOREIGN KEY (script_id) REFERENCES script (id)' ); $this->addSql( 'ALTER TABLE script_groups ADD CONSTRAINT FK_90B1718AFE54D947 FOREIGN KEY (group_id) REFERENCES user_group (id)' ); $this->addSql( 'ALTER TABLE script_categories ADD CONSTRAINT FK_CD9E8798A1C01850 FOREIGN KEY (script_id) REFERENCES script (id)' ); $this->addSql( 'ALTER TABLE script_categories ADD CONSTRAINT FK_CD9E879812469DE2 FOREIGN KEY (category_id) REFERENCES category (id)' ); $this->addSql( 'ALTER TABLE releases ADD CONSTRAINT FK_7896E4D1A1C01850 FOREIGN KEY (script_id) REFERENCES script (id)' ); $this->addSql( 'ALTER TABLE review ADD CONSTRAINT FK_794381C6A76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE review ADD CONSTRAINT FK_794381C6A1C01850 FOREIGN KEY (script_id) REFERENCES script (id)' ); $this->addSql( 'ALTER TABLE hook ADD CONSTRAINT FK_A45843551844E6B7 FOREIGN KEY (server_id) REFERENCES server (id)' ); $this->addSql( 'ALTER TABLE server ADD CONSTRAINT FK_5A6DD5F61844E6B7 FOREIGN KEY (server_id) REFERENCES server_slack_channel (id)' ); $this->addSql( 'ALTER TABLE server_groups ADD CONSTRAINT FK_891100B61844E6B7 FOREIGN KEY (server_id) REFERENCES server (id)' ); $this->addSql( 'ALTER TABLE server_groups ADD CONSTRAINT FK_891100B6FE54D947 FOREIGN KEY (group_id) REFERENCES user_group (id)' ); $this->addSql( 'ALTER TABLE server_authors ADD CONSTRAINT FK_FC7231ED1844E6B7 FOREIGN KEY (server_id) REFERENCES server (id)' ); $this->addSql( 'ALTER TABLE server_authors ADD CONSTRAINT FK_FC7231EDA76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE server_details ADD CONSTRAINT FK_5810361844E6B7 FOREIGN KEY (server_id) REFERENCES server (id)' ); $this->addSql( 'ALTER TABLE server_details ADD CONSTRAINT FK_58103634B5C767 FOREIGN KEY (serverdetail_id) REFERENCES server_detail (id)' ); $this->addSql( 'ALTER TABLE user_serveruses ADD CONSTRAINT FK_2E513393EB1E3248 FOREIGN KEY (serveruse_id) REFERENCES server_use (id)' ); $this->addSql( 'ALTER TABLE user_serveruses ADD CONSTRAINT FK_2E513393A76ED395 FOREIGN KEY (user_id) REFERENCES user (id)' ); $this->addSql( 'ALTER TABLE server_serveruse ADD CONSTRAINT FK_28A1B5EAEB1E3248 FOREIGN KEY (serveruse_id) REFERENCES server_use (id)' ); $this->addSql( 'ALTER TABLE server_serveruse ADD CONSTRAINT FK_28A1B5EA1844E6B7 FOREIGN KEY (server_id) REFERENCES server (id)' ); $this->addSql( 'ALTER TABLE sylius_adjustment ADD CONSTRAINT FK_ACA6E0F28D9F6D38 FOREIGN KEY (order_id) REFERENCES orders (id) ON DELETE CASCADE' ); $this->addSql( 'ALTER TABLE sylius_adjustment ADD CONSTRAINT FK_ACA6E0F2E415FB15 FOREIGN KEY (order_item_id) REFERENCES order_items (id) ON DELETE CASCADE' ); $this->addSql( 'ALTER TABLE sylius_adjustment ADD CONSTRAINT FK_ACA6E0F2F720C233 FOREIGN KEY (order_item_unit_id) REFERENCES sylius_order_item_unit (id) ON DELETE CASCADE' ); $this->addSql( 'ALTER TABLE sylius_order_comment ADD CONSTRAINT FK_8EA9CF098D9F6D38 FOREIGN KEY (order_id) REFERENCES orders (id)' ); $this->addSql( 'ALTER TABLE sylius_order_identity ADD CONSTRAINT FK_5757A18E8D9F6D38 FOREIGN KEY (order_id) REFERENCES orders (id)' ); $this->addSql( 'ALTER TABLE sylius_order_item_unit ADD CONSTRAINT FK_82BF226EE415FB15 FOREIGN KEY (order_item_id) REFERENCES order_items (id) ON DELETE CASCADE' ); } /** * @param Schema $schema */ public function down(Schema $schema) { // this down() migration is auto-generated, please modify it to your needs $this->abortIf( $this->connection->getDatabasePlatform()->getName() !== 'mysql', 'Migration can only be executed safely on \'mysql\'.' ); $this->addSql('ALTER TABLE order_items DROP FOREIGN KEY FK_62809DB08D9F6D38'); $this->addSql('ALTER TABLE sylius_adjustment DROP FOREIGN KEY FK_ACA6E0F28D9F6D38'); $this->addSql('ALTER TABLE sylius_order_comment DROP FOREIGN KEY FK_8EA9CF098D9F6D38'); $this->addSql('ALTER TABLE sylius_order_identity DROP FOREIGN KEY FK_5757A18E8D9F6D38'); $this->addSql('ALTER TABLE sylius_adjustment DROP FOREIGN KEY FK_ACA6E0F2E415FB15'); $this->addSql('ALTER TABLE sylius_order_item_unit DROP FOREIGN KEY FK_82BF226EE415FB15'); $this->addSql('ALTER TABLE user_user_group DROP FOREIGN KEY FK_28657971FE54D947'); $this->addSql('ALTER TABLE script_groups DROP FOREIGN KEY FK_90B1718AFE54D947'); $this->addSql('ALTER TABLE server_groups DROP FOREIGN KEY FK_891100B6FE54D947'); $this->addSql('ALTER TABLE oauth2_access_tokens DROP FOREIGN KEY FK_D247A21B19EB6921'); $this->addSql('ALTER TABLE oauth2_auth_codes DROP FOREIGN KEY FK_A018A10D19EB6921'); $this->addSql('ALTER TABLE oauth2_refresh_tokens DROP FOREIGN KEY FK_D394478C19EB6921'); $this->addSql('ALTER TABLE user_oauth_clients DROP FOREIGN KEY FK_FD402C5119EB6921'); $this->addSql('ALTER TABLE login_access_tokens DROP FOREIGN KEY FK_7EC367D3A76ED395'); $this->addSql('ALTER TABLE oauth2_access_tokens DROP FOREIGN KEY FK_D247A21BA76ED395'); $this->addSql('ALTER TABLE oauth2_auth_codes DROP FOREIGN KEY FK_A018A10DA76ED395'); $this->addSql('ALTER TABLE oauth2_refresh_tokens DROP FOREIGN KEY FK_D394478CA76ED395'); $this->addSql('ALTER TABLE user_user_group DROP FOREIGN KEY FK_28657971A76ED395'); $this->addSql('ALTER TABLE user_oauth_clients DROP FOREIGN KEY FK_FD402C51A76ED395'); $this->addSql('ALTER TABLE slack_invite DROP FOREIGN KEY FK_738D77CA76ED395'); $this->addSql('ALTER TABLE script DROP FOREIGN KEY FK_1C81873A61220EA6'); $this->addSql('ALTER TABLE script_authors DROP FOREIGN KEY FK_D304ED1BA76ED395'); $this->addSql('ALTER TABLE script_users DROP FOREIGN KEY FK_78458A76A76ED395'); $this->addSql('ALTER TABLE review DROP FOREIGN KEY FK_794381C6A76ED395'); $this->addSql('ALTER TABLE server_authors DROP FOREIGN KEY FK_FC7231EDA76ED395'); $this->addSql('ALTER TABLE user_serveruses DROP FOREIGN KEY FK_2E513393A76ED395'); $this->addSql('ALTER TABLE script_authors DROP FOREIGN KEY FK_D304ED1BA1C01850'); $this->addSql('ALTER TABLE script_users DROP FOREIGN KEY FK_78458A76A1C01850'); $this->addSql('ALTER TABLE script_groups DROP FOREIGN KEY FK_90B1718AA1C01850'); $this->addSql('ALTER TABLE script_categories DROP FOREIGN KEY FK_CD9E8798A1C01850'); $this->addSql('ALTER TABLE releases DROP FOREIGN KEY FK_7896E4D1A1C01850'); $this->addSql('ALTER TABLE review DROP FOREIGN KEY FK_794381C6A1C01850'); $this->addSql('ALTER TABLE script_categories DROP FOREIGN KEY FK_CD9E879812469DE2'); $this->addSql('ALTER TABLE script DROP FOREIGN KEY FK_1C81873A4D4CA094'); $this->addSql('ALTER TABLE hook DROP FOREIGN KEY FK_A45843551844E6B7'); $this->addSql('ALTER TABLE server_groups DROP FOREIGN KEY FK_891100B61844E6B7'); $this->addSql('ALTER TABLE server_authors DROP FOREIGN KEY FK_FC7231ED1844E6B7'); $this->addSql('ALTER TABLE server_details DROP FOREIGN KEY FK_5810361844E6B7'); $this->addSql('ALTER TABLE server_serveruse DROP FOREIGN KEY FK_28A1B5EA1844E6B7'); $this->addSql('ALTER TABLE server_details DROP FOREIGN KEY FK_58103634B5C767'); $this->addSql('ALTER TABLE server DROP FOREIGN KEY FK_5A6DD5F61844E6B7'); $this->addSql('ALTER TABLE user_serveruses DROP FOREIGN KEY FK_2E513393EB1E3248'); $this->addSql('ALTER TABLE server_serveruse DROP FOREIGN KEY FK_28A1B5EAEB1E3248'); $this->addSql('ALTER TABLE sylius_adjustment DROP FOREIGN KEY FK_ACA6E0F2F720C233'); $this->addSql('DROP TABLE cron_task'); $this->addSql('DROP TABLE orders'); $this->addSql('DROP TABLE order_items'); $this->addSql('DROP TABLE user_group'); $this->addSql('DROP TABLE login_access_tokens'); $this->addSql('DROP TABLE oauth2_access_tokens'); $this->addSql('DROP TABLE oauth2_auth_codes'); $this->addSql('DROP TABLE oauth2_clients'); $this->addSql('DROP TABLE oauth2_refresh_tokens'); $this->addSql('DROP TABLE session'); $this->addSql('DROP TABLE user'); $this->addSql('DROP TABLE user_user_group'); $this->addSql('DROP TABLE user_oauth_clients'); $this->addSql('DROP TABLE slack_invite'); $this->addSql('DROP TABLE language'); $this->addSql('DROP TABLE library'); $this->addSql('DROP TABLE script'); $this->addSql('DROP TABLE script_authors'); $this->addSql('DROP TABLE script_users'); $this->addSql('DROP TABLE script_groups'); $this->addSql('DROP TABLE script_categories'); $this->addSql('DROP TABLE category'); $this->addSql('DROP TABLE git'); $this->addSql('DROP TABLE releases'); $this->addSql('DROP TABLE review'); $this->addSql('DROP TABLE hook'); $this->addSql('DROP TABLE server'); $this->addSql('DROP TABLE server_groups'); $this->addSql('DROP TABLE server_authors'); $this->addSql('DROP TABLE server_details'); $this->addSql('DROP TABLE server_detail'); $this->addSql('DROP TABLE server_slack_channel'); $this->addSql('DROP TABLE server_use'); $this->addSql('DROP TABLE user_serveruses'); $this->addSql('DROP TABLE server_serveruse'); $this->addSql('DROP TABLE user_signature'); $this->addSql('DROP TABLE type_client'); $this->addSql('DROP TABLE type_default_provider'); $this->addSql('DROP TABLE type_dreamscape_provider'); $this->addSql('DROP TABLE type_osscape_provider'); $this->addSql('DROP TABLE type_pkhonor_provider'); $this->addSql('DROP TABLE type_randoms'); $this->addSql('DROP TABLE sylius_sequence'); $this->addSql('DROP TABLE sylius_adjustment'); $this->addSql('DROP TABLE sylius_order_comment'); $this->addSql('DROP TABLE sylius_order_identity'); $this->addSql('DROP TABLE sylius_order_item_unit'); } }
Parabot/BDN-V3
app/Migrations/Version20170820234613.php
PHP
mit
32,193
package com.openknowl.okhttpexample; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MainActivity extends AppCompatActivity { public static final String TAG = MainActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url("https://api.github.com/users/KimKyung-man") .build(); client.newCall(request).enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { e.printStackTrace(); } @Override public void onResponse(Call call, Response response) throws IOException { Log.i(TAG, "" + response.body().string()); } }); } }
openknowl/android-prototyper-tutorials
android/android_tutorial_8/OkHttpExample/app/src/main/java/com/openknowl/okhttpexample/MainActivity.java
Java
mit
1,171
(function($){ $.fn.onImagesLoaded = function(_cb,_ca) { return this.each(function() { var $imgs = (this.tagName.toLowerCase()==='img')?$(this):$('img',this), _cont = this, i = 0, _loading=function() { if( typeof _cb === 'function') _cb(_cont); }, _done=function() { if( typeof _ca === 'function' ) _ca(_cont); }; if( $imgs.length ) { $imgs.each(function() { var _img = this; _loading(); $(_img).load(function(){ _done(); }); }); } }); } })(jQuery)
flashycud/timestack
static/js/lib.js
JavaScript
mit
614
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* | ------------------------------------------------------------------------- | URI ROUTING | ------------------------------------------------------------------------- | This file lets you re-map URI requests to specific controller functions. | | Typically there is a one-to-one relationship between a URL string | and its corresponding controller class/method. The segments in a | URL normally follow this pattern: | | example.com/class/method/id/ | | In some instances, however, you may want to remap this relationship | so that a different class/function is called than the one | corresponding to the URL. | | Please see the user guide for complete details: | | http://codeigniter.com/user_guide/general/routing.html | | ------------------------------------------------------------------------- | RESERVED ROUTES | ------------------------------------------------------------------------- | | There are three reserved routes: | | $route['default_controller'] = 'welcome'; | | This route indicates which controller class should be loaded if the | URI contains no data. In the above example, the "welcome" class | would be loaded. | | $route['404_override'] = 'errors/page_missing'; | | This route will tell the Router which controller/method to use if those | provided in the URL cannot be matched to a valid route. | | $route['translate_uri_dashes'] = FALSE; | | This is not exactly a route, but allows you to automatically route | controller and method names that contain dashes. '-' isn't a valid | class or method name character, so it requires translation. | When you set this option to TRUE, it will replace ALL dashes in the | controller and method URI segments. | | Examples: my-controller/index -> my_controller/index | my-controller/my-method -> my_controller/my_method */ $route['default_controller'] = 'order/all'; $route['404_override'] = ''; $route['translate_uri_dashes'] = FALSE;
z32556601/90ping_backend
application/config/routes.php
PHP
mit
1,971
@NodeEntity public class Country{ @GraphId private Long id; @Indexed(unique=true) private String coutryName; @RelatedTo private Set<City> cities; public Country(){} public Country(String countryName){ this.countryName = countryName; } }
yanisIk/Hobdy
Domain/Country.java
Java
mit
254
<?php use Symfony\Component\Routing\Exception\MethodNotAllowedException; use Symfony\Component\Routing\Exception\ResourceNotFoundException; use Symfony\Component\Routing\RequestContext; /** * appDevUrlMatcher * * This class has been auto-generated * by the Symfony Routing Component. */ class appDevUrlMatcher extends Symfony\Bundle\FrameworkBundle\Routing\RedirectableUrlMatcher { /** * Constructor. */ public function __construct(RequestContext $context) { $this->context = $context; } public function match($pathinfo) { $allow = array(); $pathinfo = rawurldecode($pathinfo); if (0 === strpos($pathinfo, '/_')) { // _wdt if (0 === strpos($pathinfo, '/_wdt') && preg_match('#^/_wdt/(?P<token>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_wdt')), array ( '_controller' => 'web_profiler.controller.profiler:toolbarAction',)); } if (0 === strpos($pathinfo, '/_profiler')) { // _profiler_home if (rtrim($pathinfo, '/') === '/_profiler') { if (substr($pathinfo, -1) !== '/') { return $this->redirect($pathinfo.'/', '_profiler_home'); } return array ( '_controller' => 'web_profiler.controller.profiler:homeAction', '_route' => '_profiler_home',); } if (0 === strpos($pathinfo, '/_profiler/search')) { // _profiler_search if ($pathinfo === '/_profiler/search') { return array ( '_controller' => 'web_profiler.controller.profiler:searchAction', '_route' => '_profiler_search',); } // _profiler_search_bar if ($pathinfo === '/_profiler/search_bar') { return array ( '_controller' => 'web_profiler.controller.profiler:searchBarAction', '_route' => '_profiler_search_bar',); } } // _profiler_purge if ($pathinfo === '/_profiler/purge') { return array ( '_controller' => 'web_profiler.controller.profiler:purgeAction', '_route' => '_profiler_purge',); } if (0 === strpos($pathinfo, '/_profiler/i')) { // _profiler_info if (0 === strpos($pathinfo, '/_profiler/info') && preg_match('#^/_profiler/info/(?P<about>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_info')), array ( '_controller' => 'web_profiler.controller.profiler:infoAction',)); } // _profiler_import if ($pathinfo === '/_profiler/import') { return array ( '_controller' => 'web_profiler.controller.profiler:importAction', '_route' => '_profiler_import',); } } // _profiler_export if (0 === strpos($pathinfo, '/_profiler/export') && preg_match('#^/_profiler/export/(?P<token>[^/\\.]++)\\.txt$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_export')), array ( '_controller' => 'web_profiler.controller.profiler:exportAction',)); } // _profiler_phpinfo if ($pathinfo === '/_profiler/phpinfo') { return array ( '_controller' => 'web_profiler.controller.profiler:phpinfoAction', '_route' => '_profiler_phpinfo',); } // _profiler_search_results if (preg_match('#^/_profiler/(?P<token>[^/]++)/search/results$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_search_results')), array ( '_controller' => 'web_profiler.controller.profiler:searchResultsAction',)); } // _profiler if (preg_match('#^/_profiler/(?P<token>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler')), array ( '_controller' => 'web_profiler.controller.profiler:panelAction',)); } // _profiler_router if (preg_match('#^/_profiler/(?P<token>[^/]++)/router$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_router')), array ( '_controller' => 'web_profiler.controller.router:panelAction',)); } // _profiler_exception if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_exception')), array ( '_controller' => 'web_profiler.controller.exception:showAction',)); } // _profiler_exception_css if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception\\.css$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_exception_css')), array ( '_controller' => 'web_profiler.controller.exception:cssAction',)); } } if (0 === strpos($pathinfo, '/_configurator')) { // _configurator_home if (rtrim($pathinfo, '/') === '/_configurator') { if (substr($pathinfo, -1) !== '/') { return $this->redirect($pathinfo.'/', '_configurator_home'); } return array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::checkAction', '_route' => '_configurator_home',); } // _configurator_step if (0 === strpos($pathinfo, '/_configurator/step') && preg_match('#^/_configurator/step/(?P<index>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_configurator_step')), array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::stepAction',)); } // _configurator_final if ($pathinfo === '/_configurator/final') { return array ( '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::finalAction', '_route' => '_configurator_final',); } } } // application_sonata_super_market_homepage if (0 === strpos($pathinfo, '/hello') && preg_match('#^/hello/(?P<name>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'application_sonata_super_market_homepage')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\DefaultController::indexAction',)); } // application_sonata_supermarket_price if ($pathinfo === '/price') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PriceController::getPriceAction', '_route' => 'application_sonata_supermarket_price',); } if (0 === strpos($pathinfo, '/admin')) { // sonata_admin_redirect if (rtrim($pathinfo, '/') === '/admin') { if (substr($pathinfo, -1) !== '/') { return $this->redirect($pathinfo.'/', 'sonata_admin_redirect'); } return array ( '_controller' => 'Symfony\\Bundle\\FrameworkBundle\\Controller\\RedirectController::redirectAction', 'route' => 'sonata_admin_dashboard', 'permanent' => 'true', '_route' => 'sonata_admin_redirect',); } // sonata_admin_dashboard if ($pathinfo === '/admin/dashboard') { return array ( '_controller' => 'Sonata\\AdminBundle\\Controller\\CoreController::dashboardAction', '_route' => 'sonata_admin_dashboard',); } if (0 === strpos($pathinfo, '/admin/core')) { // sonata_admin_retrieve_form_element if ($pathinfo === '/admin/core/get-form-field-element') { return array ( '_controller' => 'sonata.admin.controller.admin:retrieveFormFieldElementAction', '_route' => 'sonata_admin_retrieve_form_element',); } // sonata_admin_append_form_element if ($pathinfo === '/admin/core/append-form-field-element') { return array ( '_controller' => 'sonata.admin.controller.admin:appendFormFieldElementAction', '_route' => 'sonata_admin_append_form_element',); } // sonata_admin_short_object_information if (0 === strpos($pathinfo, '/admin/core/get-short-object-description') && preg_match('#^/admin/core/get\\-short\\-object\\-description(?:\\.(?P<_format>html|json))?$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'sonata_admin_short_object_information')), array ( '_controller' => 'sonata.admin.controller.admin:getShortObjectDescriptionAction', '_format' => 'html',)); } // sonata_admin_set_object_field_value if ($pathinfo === '/admin/core/set-object-field-value') { return array ( '_controller' => 'sonata.admin.controller.admin:setObjectFieldValueAction', '_route' => 'sonata_admin_set_object_field_value',); } } if (0 === strpos($pathinfo, '/admin/s')) { // sonata_admin_search if ($pathinfo === '/admin/search') { return array ( '_controller' => 'Sonata\\AdminBundle\\Controller\\CoreController::searchAction', '_route' => 'sonata_admin_search',); } if (0 === strpos($pathinfo, '/admin/sonata/supermarket')) { if (0 === strpos($pathinfo, '/admin/sonata/supermarket/brand')) { // admin_sonata_supermarket_brand_list if ($pathinfo === '/admin/sonata/supermarket/brand/list') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\BrandAdminController::listAction', '_sonata_admin' => 'application_sonata_super_market.admin.brand', '_sonata_name' => 'admin_sonata_supermarket_brand_list', '_route' => 'admin_sonata_supermarket_brand_list',); } // admin_sonata_supermarket_brand_create if ($pathinfo === '/admin/sonata/supermarket/brand/create') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\BrandAdminController::createAction', '_sonata_admin' => 'application_sonata_super_market.admin.brand', '_sonata_name' => 'admin_sonata_supermarket_brand_create', '_route' => 'admin_sonata_supermarket_brand_create',); } // admin_sonata_supermarket_brand_batch if ($pathinfo === '/admin/sonata/supermarket/brand/batch') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\BrandAdminController::batchAction', '_sonata_admin' => 'application_sonata_super_market.admin.brand', '_sonata_name' => 'admin_sonata_supermarket_brand_batch', '_route' => 'admin_sonata_supermarket_brand_batch',); } // admin_sonata_supermarket_brand_edit if (preg_match('#^/admin/sonata/supermarket/brand/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_brand_edit')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\BrandAdminController::editAction', '_sonata_admin' => 'application_sonata_super_market.admin.brand', '_sonata_name' => 'admin_sonata_supermarket_brand_edit',)); } // admin_sonata_supermarket_brand_delete if (preg_match('#^/admin/sonata/supermarket/brand/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_brand_delete')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\BrandAdminController::deleteAction', '_sonata_admin' => 'application_sonata_super_market.admin.brand', '_sonata_name' => 'admin_sonata_supermarket_brand_delete',)); } // admin_sonata_supermarket_brand_show if (preg_match('#^/admin/sonata/supermarket/brand/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_brand_show')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\BrandAdminController::showAction', '_sonata_admin' => 'application_sonata_super_market.admin.brand', '_sonata_name' => 'admin_sonata_supermarket_brand_show',)); } // admin_sonata_supermarket_brand_export if ($pathinfo === '/admin/sonata/supermarket/brand/export') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\BrandAdminController::exportAction', '_sonata_admin' => 'application_sonata_super_market.admin.brand', '_sonata_name' => 'admin_sonata_supermarket_brand_export', '_route' => 'admin_sonata_supermarket_brand_export',); } } if (0 === strpos($pathinfo, '/admin/sonata/supermarket/category')) { // admin_sonata_supermarket_category_list if ($pathinfo === '/admin/sonata/supermarket/category/list') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CategoryAdminController::listAction', '_sonata_admin' => 'application_sonata_super_market.admin.category', '_sonata_name' => 'admin_sonata_supermarket_category_list', '_route' => 'admin_sonata_supermarket_category_list',); } // admin_sonata_supermarket_category_create if ($pathinfo === '/admin/sonata/supermarket/category/create') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CategoryAdminController::createAction', '_sonata_admin' => 'application_sonata_super_market.admin.category', '_sonata_name' => 'admin_sonata_supermarket_category_create', '_route' => 'admin_sonata_supermarket_category_create',); } // admin_sonata_supermarket_category_batch if ($pathinfo === '/admin/sonata/supermarket/category/batch') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CategoryAdminController::batchAction', '_sonata_admin' => 'application_sonata_super_market.admin.category', '_sonata_name' => 'admin_sonata_supermarket_category_batch', '_route' => 'admin_sonata_supermarket_category_batch',); } // admin_sonata_supermarket_category_edit if (preg_match('#^/admin/sonata/supermarket/category/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_category_edit')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CategoryAdminController::editAction', '_sonata_admin' => 'application_sonata_super_market.admin.category', '_sonata_name' => 'admin_sonata_supermarket_category_edit',)); } // admin_sonata_supermarket_category_delete if (preg_match('#^/admin/sonata/supermarket/category/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_category_delete')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CategoryAdminController::deleteAction', '_sonata_admin' => 'application_sonata_super_market.admin.category', '_sonata_name' => 'admin_sonata_supermarket_category_delete',)); } // admin_sonata_supermarket_category_show if (preg_match('#^/admin/sonata/supermarket/category/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_category_show')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CategoryAdminController::showAction', '_sonata_admin' => 'application_sonata_super_market.admin.category', '_sonata_name' => 'admin_sonata_supermarket_category_show',)); } // admin_sonata_supermarket_category_export if ($pathinfo === '/admin/sonata/supermarket/category/export') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CategoryAdminController::exportAction', '_sonata_admin' => 'application_sonata_super_market.admin.category', '_sonata_name' => 'admin_sonata_supermarket_category_export', '_route' => 'admin_sonata_supermarket_category_export',); } } if (0 === strpos($pathinfo, '/admin/sonata/supermarket/product')) { // admin_sonata_supermarket_product_list if ($pathinfo === '/admin/sonata/supermarket/product/list') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\ProductAdminController::listAction', '_sonata_admin' => 'application_sonata_super_market.admin.product', '_sonata_name' => 'admin_sonata_supermarket_product_list', '_route' => 'admin_sonata_supermarket_product_list',); } // admin_sonata_supermarket_product_create if ($pathinfo === '/admin/sonata/supermarket/product/create') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\ProductAdminController::createAction', '_sonata_admin' => 'application_sonata_super_market.admin.product', '_sonata_name' => 'admin_sonata_supermarket_product_create', '_route' => 'admin_sonata_supermarket_product_create',); } // admin_sonata_supermarket_product_batch if ($pathinfo === '/admin/sonata/supermarket/product/batch') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\ProductAdminController::batchAction', '_sonata_admin' => 'application_sonata_super_market.admin.product', '_sonata_name' => 'admin_sonata_supermarket_product_batch', '_route' => 'admin_sonata_supermarket_product_batch',); } // admin_sonata_supermarket_product_edit if (preg_match('#^/admin/sonata/supermarket/product/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_product_edit')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\ProductAdminController::editAction', '_sonata_admin' => 'application_sonata_super_market.admin.product', '_sonata_name' => 'admin_sonata_supermarket_product_edit',)); } // admin_sonata_supermarket_product_delete if (preg_match('#^/admin/sonata/supermarket/product/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_product_delete')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\ProductAdminController::deleteAction', '_sonata_admin' => 'application_sonata_super_market.admin.product', '_sonata_name' => 'admin_sonata_supermarket_product_delete',)); } // admin_sonata_supermarket_product_show if (preg_match('#^/admin/sonata/supermarket/product/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_product_show')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\ProductAdminController::showAction', '_sonata_admin' => 'application_sonata_super_market.admin.product', '_sonata_name' => 'admin_sonata_supermarket_product_show',)); } // admin_sonata_supermarket_product_export if ($pathinfo === '/admin/sonata/supermarket/product/export') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\ProductAdminController::exportAction', '_sonata_admin' => 'application_sonata_super_market.admin.product', '_sonata_name' => 'admin_sonata_supermarket_product_export', '_route' => 'admin_sonata_supermarket_product_export',); } } if (0 === strpos($pathinfo, '/admin/sonata/supermarket/customer')) { // admin_sonata_supermarket_customer_list if ($pathinfo === '/admin/sonata/supermarket/customer/list') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CustomerAdminController::listAction', '_sonata_admin' => 'application_sonata_super_market.admin.customer', '_sonata_name' => 'admin_sonata_supermarket_customer_list', '_route' => 'admin_sonata_supermarket_customer_list',); } // admin_sonata_supermarket_customer_create if ($pathinfo === '/admin/sonata/supermarket/customer/create') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CustomerAdminController::createAction', '_sonata_admin' => 'application_sonata_super_market.admin.customer', '_sonata_name' => 'admin_sonata_supermarket_customer_create', '_route' => 'admin_sonata_supermarket_customer_create',); } // admin_sonata_supermarket_customer_batch if ($pathinfo === '/admin/sonata/supermarket/customer/batch') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CustomerAdminController::batchAction', '_sonata_admin' => 'application_sonata_super_market.admin.customer', '_sonata_name' => 'admin_sonata_supermarket_customer_batch', '_route' => 'admin_sonata_supermarket_customer_batch',); } // admin_sonata_supermarket_customer_edit if (preg_match('#^/admin/sonata/supermarket/customer/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_customer_edit')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CustomerAdminController::editAction', '_sonata_admin' => 'application_sonata_super_market.admin.customer', '_sonata_name' => 'admin_sonata_supermarket_customer_edit',)); } // admin_sonata_supermarket_customer_delete if (preg_match('#^/admin/sonata/supermarket/customer/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_customer_delete')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CustomerAdminController::deleteAction', '_sonata_admin' => 'application_sonata_super_market.admin.customer', '_sonata_name' => 'admin_sonata_supermarket_customer_delete',)); } // admin_sonata_supermarket_customer_show if (preg_match('#^/admin/sonata/supermarket/customer/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_customer_show')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CustomerAdminController::showAction', '_sonata_admin' => 'application_sonata_super_market.admin.customer', '_sonata_name' => 'admin_sonata_supermarket_customer_show',)); } // admin_sonata_supermarket_customer_export if ($pathinfo === '/admin/sonata/supermarket/customer/export') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\CustomerAdminController::exportAction', '_sonata_admin' => 'application_sonata_super_market.admin.customer', '_sonata_name' => 'admin_sonata_supermarket_customer_export', '_route' => 'admin_sonata_supermarket_customer_export',); } } if (0 === strpos($pathinfo, '/admin/sonata/supermarket/purchaseorder')) { // admin_sonata_supermarket_purchaseorder_list if ($pathinfo === '/admin/sonata/supermarket/purchaseorder/list') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PurchaseOrderAdminController::listAction', '_sonata_admin' => 'application_sonata_super_market.admin.purchase_order', '_sonata_name' => 'admin_sonata_supermarket_purchaseorder_list', '_route' => 'admin_sonata_supermarket_purchaseorder_list',); } // admin_sonata_supermarket_purchaseorder_create if ($pathinfo === '/admin/sonata/supermarket/purchaseorder/create') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PurchaseOrderAdminController::createAction', '_sonata_admin' => 'application_sonata_super_market.admin.purchase_order', '_sonata_name' => 'admin_sonata_supermarket_purchaseorder_create', '_route' => 'admin_sonata_supermarket_purchaseorder_create',); } // admin_sonata_supermarket_purchaseorder_batch if ($pathinfo === '/admin/sonata/supermarket/purchaseorder/batch') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PurchaseOrderAdminController::batchAction', '_sonata_admin' => 'application_sonata_super_market.admin.purchase_order', '_sonata_name' => 'admin_sonata_supermarket_purchaseorder_batch', '_route' => 'admin_sonata_supermarket_purchaseorder_batch',); } // admin_sonata_supermarket_purchaseorder_edit if (preg_match('#^/admin/sonata/supermarket/purchaseorder/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_purchaseorder_edit')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PurchaseOrderAdminController::editAction', '_sonata_admin' => 'application_sonata_super_market.admin.purchase_order', '_sonata_name' => 'admin_sonata_supermarket_purchaseorder_edit',)); } // admin_sonata_supermarket_purchaseorder_delete if (preg_match('#^/admin/sonata/supermarket/purchaseorder/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_purchaseorder_delete')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PurchaseOrderAdminController::deleteAction', '_sonata_admin' => 'application_sonata_super_market.admin.purchase_order', '_sonata_name' => 'admin_sonata_supermarket_purchaseorder_delete',)); } // admin_sonata_supermarket_purchaseorder_show if (preg_match('#^/admin/sonata/supermarket/purchaseorder/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_purchaseorder_show')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PurchaseOrderAdminController::showAction', '_sonata_admin' => 'application_sonata_super_market.admin.purchase_order', '_sonata_name' => 'admin_sonata_supermarket_purchaseorder_show',)); } // admin_sonata_supermarket_purchaseorder_export if ($pathinfo === '/admin/sonata/supermarket/purchaseorder/export') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\PurchaseOrderAdminController::exportAction', '_sonata_admin' => 'application_sonata_super_market.admin.purchase_order', '_sonata_name' => 'admin_sonata_supermarket_purchaseorder_export', '_route' => 'admin_sonata_supermarket_purchaseorder_export',); } } if (0 === strpos($pathinfo, '/admin/sonata/supermarket/orderitem')) { // admin_sonata_supermarket_orderitem_list if ($pathinfo === '/admin/sonata/supermarket/orderitem/list') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\OrderItemAdminController::listAction', '_sonata_admin' => 'application_sonata_super_market.admin.order_item', '_sonata_name' => 'admin_sonata_supermarket_orderitem_list', '_route' => 'admin_sonata_supermarket_orderitem_list',); } // admin_sonata_supermarket_orderitem_create if ($pathinfo === '/admin/sonata/supermarket/orderitem/create') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\OrderItemAdminController::createAction', '_sonata_admin' => 'application_sonata_super_market.admin.order_item', '_sonata_name' => 'admin_sonata_supermarket_orderitem_create', '_route' => 'admin_sonata_supermarket_orderitem_create',); } // admin_sonata_supermarket_orderitem_batch if ($pathinfo === '/admin/sonata/supermarket/orderitem/batch') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\OrderItemAdminController::batchAction', '_sonata_admin' => 'application_sonata_super_market.admin.order_item', '_sonata_name' => 'admin_sonata_supermarket_orderitem_batch', '_route' => 'admin_sonata_supermarket_orderitem_batch',); } // admin_sonata_supermarket_orderitem_edit if (preg_match('#^/admin/sonata/supermarket/orderitem/(?P<id>[^/]++)/edit$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_orderitem_edit')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\OrderItemAdminController::editAction', '_sonata_admin' => 'application_sonata_super_market.admin.order_item', '_sonata_name' => 'admin_sonata_supermarket_orderitem_edit',)); } // admin_sonata_supermarket_orderitem_delete if (preg_match('#^/admin/sonata/supermarket/orderitem/(?P<id>[^/]++)/delete$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_orderitem_delete')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\OrderItemAdminController::deleteAction', '_sonata_admin' => 'application_sonata_super_market.admin.order_item', '_sonata_name' => 'admin_sonata_supermarket_orderitem_delete',)); } // admin_sonata_supermarket_orderitem_show if (preg_match('#^/admin/sonata/supermarket/orderitem/(?P<id>[^/]++)/show$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => 'admin_sonata_supermarket_orderitem_show')), array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\OrderItemAdminController::showAction', '_sonata_admin' => 'application_sonata_super_market.admin.order_item', '_sonata_name' => 'admin_sonata_supermarket_orderitem_show',)); } // admin_sonata_supermarket_orderitem_export if ($pathinfo === '/admin/sonata/supermarket/orderitem/export') { return array ( '_controller' => 'Application\\Sonata\\SuperMarketBundle\\Controller\\OrderItemAdminController::exportAction', '_sonata_admin' => 'application_sonata_super_market.admin.order_item', '_sonata_name' => 'admin_sonata_supermarket_orderitem_export', '_route' => 'admin_sonata_supermarket_orderitem_export',); } } } } } if (0 === strpos($pathinfo, '/shtumi_')) { // shtumi_ajaxautocomplete if ($pathinfo === '/shtumi_ajaxautocomplete') { return array ( '_controller' => 'Shtumi\\UsefulBundle\\Controller\\AjaxAutocompleteJSONController::getJSONAction', '_route' => 'shtumi_ajaxautocomplete',); } // shtumi_dependent_filtered_entity if ($pathinfo === '/shtumi_dependent_filtered_entity') { return array ( '_controller' => 'ShtumiUsefulBundle:DependentFilteredEntity:getOptions', '_route' => 'shtumi_dependent_filtered_entity',); } } // _welcome if (rtrim($pathinfo, '/') === '') { if (substr($pathinfo, -1) !== '/') { return $this->redirect($pathinfo.'/', '_welcome'); } return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\WelcomeController::indexAction', '_route' => '_welcome',); } if (0 === strpos($pathinfo, '/demo')) { if (0 === strpos($pathinfo, '/demo/secured')) { if (0 === strpos($pathinfo, '/demo/secured/log')) { if (0 === strpos($pathinfo, '/demo/secured/login')) { // _demo_login if ($pathinfo === '/demo/secured/login') { return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::loginAction', '_route' => '_demo_login',); } // _security_check if ($pathinfo === '/demo/secured/login_check') { return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::securityCheckAction', '_route' => '_security_check',); } } // _demo_logout if ($pathinfo === '/demo/secured/logout') { return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::logoutAction', '_route' => '_demo_logout',); } } if (0 === strpos($pathinfo, '/demo/secured/hello')) { // acme_demo_secured_hello if ($pathinfo === '/demo/secured/hello') { return array ( 'name' => 'World', '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloAction', '_route' => 'acme_demo_secured_hello',); } // _demo_secured_hello if (preg_match('#^/demo/secured/hello/(?P<name>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_demo_secured_hello')), array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloAction',)); } // _demo_secured_hello_admin if (0 === strpos($pathinfo, '/demo/secured/hello/admin') && preg_match('#^/demo/secured/hello/admin/(?P<name>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_demo_secured_hello_admin')), array ( '_controller' => 'Acme\\DemoBundle\\Controller\\SecuredController::helloadminAction',)); } } } // _demo if (rtrim($pathinfo, '/') === '/demo') { if (substr($pathinfo, -1) !== '/') { return $this->redirect($pathinfo.'/', '_demo'); } return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::indexAction', '_route' => '_demo',); } // _demo_hello if (0 === strpos($pathinfo, '/demo/hello') && preg_match('#^/demo/hello/(?P<name>[^/]++)$#s', $pathinfo, $matches)) { return $this->mergeDefaults(array_replace($matches, array('_route' => '_demo_hello')), array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::helloAction',)); } // _demo_contact if ($pathinfo === '/demo/contact') { return array ( '_controller' => 'Acme\\DemoBundle\\Controller\\DemoController::contactAction', '_route' => '_demo_contact',); } } throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException(); } }
rangakomarthicomo/SuperMarket
app/cache/dev/appDevUrlMatcher.php
PHP
mit
39,321
// Generated from ./Select.g4 by ANTLR 4.5 // jshint ignore: start var antlr4 = require('../../index'); var serializedATN = ["\3\u0430\ud6d1\u8206\uad2d\u4417\uaef1\u8d80\uaadd", "\2\17\177\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7\t\7\4\b\t", "\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t\r\4\16\t\16\3\2\3\2\3\2\3", "\2\3\2\3\2\3\2\3\3\3\3\3\4\3\4\3\5\3\5\3\6\3\6\3\6\3\6\3\6\3\7\3\7\3", "\7\3\7\3\b\3\b\3\b\3\t\3\t\3\t\3\t\3\t\3\t\3\n\3\n\3\n\3\n\3\n\3\n\3", "\n\5\nD\n\n\3\13\3\13\3\13\3\f\5\fJ\n\f\3\f\6\fM\n\f\r\f\16\fN\3\f\7", "\fR\n\f\f\f\16\fU\13\f\3\f\7\fX\n\f\f\f\16\f[\13\f\3\f\3\f\3\f\3\f\3", "\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\3\f\7\fl\n\f\f\f\16\fo\13\f\3", "\f\5\fr\n\f\3\r\6\ru\n\r\r\r\16\rv\3\16\6\16z\n\16\r\16\16\16{\3\16", "\3\16\3m\2\17\3\3\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31", "\16\33\17\3\2\7\4\2--//\3\2\62;\3\2\60\60\5\2C\\aac|\5\2\13\f\17\17", "\"\"\u008d\2\3\3\2\2\2\2\5\3\2\2\2\2\7\3\2\2\2\2\t\3\2\2\2\2\13\3\2", "\2\2\2\r\3\2\2\2\2\17\3\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25\3\2\2\2", "\2\27\3\2\2\2\2\31\3\2\2\2\2\33\3\2\2\2\3\35\3\2\2\2\5$\3\2\2\2\7&\3", "\2\2\2\t(\3\2\2\2\13*\3\2\2\2\r/\3\2\2\2\17\63\3\2\2\2\21\66\3\2\2\2", "\23C\3\2\2\2\25E\3\2\2\2\27q\3\2\2\2\31t\3\2\2\2\33y\3\2\2\2\35\36\7", "u\2\2\36\37\7g\2\2\37 \7n\2\2 !\7g\2\2!\"\7e\2\2\"#\7v\2\2#\4\3\2\2", "\2$%\7.\2\2%\6\3\2\2\2&\'\7*\2\2\'\b\3\2\2\2()\7+\2\2)\n\3\2\2\2*+\7", "h\2\2+,\7t\2\2,-\7q\2\2-.\7o\2\2.\f\3\2\2\2/\60\7c\2\2\60\61\7p\2\2", "\61\62\7f\2\2\62\16\3\2\2\2\63\64\7q\2\2\64\65\7t\2\2\65\20\3\2\2\2", "\66\67\7y\2\2\678\7j\2\289\7g\2\29:\7t\2\2:;\7g\2\2;\22\3\2\2\2<D\7", ">\2\2=>\7>\2\2>D\7?\2\2?D\7@\2\2@A\7@\2\2AD\7?\2\2BD\7?\2\2C<\3\2\2", "\2C=\3\2\2\2C?\3\2\2\2C@\3\2\2\2CB\3\2\2\2D\24\3\2\2\2EF\7k\2\2FG\7", "p\2\2G\26\3\2\2\2HJ\t\2\2\2IH\3\2\2\2IJ\3\2\2\2JL\3\2\2\2KM\t\3\2\2", "LK\3\2\2\2MN\3\2\2\2NL\3\2\2\2NO\3\2\2\2OS\3\2\2\2PR\t\4\2\2QP\3\2\2", "\2RU\3\2\2\2SQ\3\2\2\2ST\3\2\2\2TY\3\2\2\2US\3\2\2\2VX\t\3\2\2WV\3\2", "\2\2X[\3\2\2\2YW\3\2\2\2YZ\3\2\2\2Zr\3\2\2\2[Y\3\2\2\2\\]\7v\2\2]^\7", "t\2\2^_\7w\2\2_r\7g\2\2`a\7h\2\2ab\7c\2\2bc\7n\2\2cd\7u\2\2dr\7g\2\2", "ef\7p\2\2fg\7w\2\2gh\7n\2\2hr\7n\2\2im\7)\2\2jl\13\2\2\2kj\3\2\2\2l", "o\3\2\2\2mn\3\2\2\2mk\3\2\2\2np\3\2\2\2om\3\2\2\2pr\7)\2\2qI\3\2\2\2", "q\\\3\2\2\2q`\3\2\2\2qe\3\2\2\2qi\3\2\2\2r\30\3\2\2\2su\t\5\2\2ts\3", "\2\2\2uv\3\2\2\2vt\3\2\2\2vw\3\2\2\2w\32\3\2\2\2xz\t\6\2\2yx\3\2\2\2", "z{\3\2\2\2{y\3\2\2\2{|\3\2\2\2|}\3\2\2\2}~\b\16\2\2~\34\3\2\2\2\f\2", "CINSYmqv{\3\b\2\2"].join(""); var atn = new antlr4.atn.ATNDeserializer().deserialize(serializedATN); var decisionsToDFA = atn.decisionToState.map( function(ds, index) { return new antlr4.dfa.DFA(ds, index); }); function SelectLexer(input) { antlr4.Lexer.call(this, input); this._interp = new antlr4.atn.LexerATNSimulator(this, atn, decisionsToDFA, new antlr4.PredictionContextCache()); return this; } SelectLexer.prototype = Object.create(antlr4.Lexer.prototype); SelectLexer.prototype.constructor = SelectLexer; SelectLexer.EOF = antlr4.Token.EOF; SelectLexer.T__0 = 1; SelectLexer.T__1 = 2; SelectLexer.T__2 = 3; SelectLexer.T__3 = 4; SelectLexer.T__4 = 5; SelectLexer.T__5 = 6; SelectLexer.T__6 = 7; SelectLexer.T__7 = 8; SelectLexer.OPERATOR = 9; SelectLexer.ARRAYOPERATOR = 10; SelectLexer.CONSTANT = 11; SelectLexer.FIELD = 12; SelectLexer.WS = 13; SelectLexer.modeNames = [ "DEFAULT_MODE" ]; SelectLexer.literalNames = [ 'null', "'select'", "','", "'('", "')'", "'from'", "'and'", "'or'", "'where'", 'null', "'in'" ]; SelectLexer.symbolicNames = [ 'null', 'null', 'null', 'null', 'null', 'null', 'null', 'null', 'null', "OPERATOR", "ARRAYOPERATOR", "CONSTANT", "FIELD", "WS" ]; SelectLexer.ruleNames = [ "T__0", "T__1", "T__2", "T__3", "T__4", "T__5", "T__6", "T__7", "OPERATOR", "ARRAYOPERATOR", "CONSTANT", "FIELD", "WS" ]; SelectLexer.grammarFileName = "Select.g4"; exports.SelectLexer = SelectLexer;
bvellacott/papu-force-adapter
lib/antlr4/parsers/select/SelectLexer.js
JavaScript
mit
4,185
using System; using Microsoft.VisualStudio.Shell.Interop; using NUnit.Framework; using Telerik.JustMock; using VisualStudioSync.Controllers; namespace VisualStudioSync.Tests { [TestFixture] public class SettingsControllerTest { private const string Path = "path"; private const string Value = "test"; private IVsProfileDataManager _manager; private IVsSettingsErrorInformation _errorInformation; private IVsProfileSettingsFileCollection _files; private IXmlRepository _xmlRepository; private IVsProfileSettingsFileInfo _settingsFileInfo; private IVsProfileSettingsTree _sets; [SetUp] public void Setup() { _manager = Mock.Create<IVsProfileDataManager>(); _errorInformation = Mock.Create<IVsSettingsErrorInformation>(); _files = Mock.Create<IVsProfileSettingsFileCollection>(); _xmlRepository = Mock.Create<IXmlRepository>(); _settingsFileInfo = Mock.Create<IVsProfileSettingsFileInfo>(); _sets = Mock.Create<IVsProfileSettingsTree>(); } [Test] public void Get_CheckManager_CalledExportAllSettings() { //Arrange Mock.Arrange(() => _manager.ExportAllSettings( Arg.Matches<string>(path => path.StartsWith(Path)), out _errorInformation)) .MustBeCalled(); //Act CreateController().Get(); //Assert Mock.AssertAll(_manager); } [Test] public void Get_CheckRepository_CalledGetXml() { //Arrange Mock.Arrange(() => _xmlRepository.GetXml( Arg.Matches<string>(path => path.StartsWith(Path)))) .MustBeCalled(); //Act CreateController().Get(); //Assert Mock.AssertAll(_xmlRepository); } [Test] [ExpectedException(typeof(ArgumentNullException))] public void Set_ValueIsNull_ExpectedException() { //Act CreateController().Set(null); } [Test] public void Set_ValueIsntNull_CalledSetXml() { //Arrange Mock.Arrange(() => _xmlRepository.SetXml( Arg.Matches<string>(path => path.StartsWith(Path)), Value)) .MustBeCalled(); Mock.Arrange(() => _files.AddBrowseFile(Arg.AnyString, out _settingsFileInfo)).DoNothing(); Mock.Arrange(() => _manager.GetSettingsFiles(0, out _files)); //Act CreateController().Set(Value); //Assert Mock.AssertAll(_xmlRepository); } [Test] public void Set_ValueIsntNull_CalleGetSettingsFiles() { //Arrange Mock.Arrange(() => _manager.GetSettingsFiles(0, out _files)) .MustBeCalled(); Mock.Arrange(() => _files.AddBrowseFile(Arg.AnyString, out _settingsFileInfo)).DoNothing(); Mock.Arrange(() => _settingsFileInfo.GetSettingsForImport(out _sets)).DoNothing(); //Act CreateController().Set(Value); //Assert Mock.AssertAll(_xmlRepository); } [Test] public void Set_ValueIsntNull_CalleAddBrowseFile() { //Arrange Mock.Arrange(() => _files.AddBrowseFile( Arg.Matches<string>(path => path.StartsWith(Path)), out _settingsFileInfo)) .MustBeCalled(); Mock.Arrange(() => _manager.GetSettingsFiles(0, out _files)); //Act CreateController().Set(Value); //Assert Mock.AssertAll(_xmlRepository); } [Test] public void Set_ValueIsntNull_CalleGetSettingsForImport() { //Arrange Mock.Arrange(() => _settingsFileInfo.GetSettingsForImport(out _sets)) .MustBeCalled(); Mock.Arrange(() => _manager.GetSettingsFiles(0, out _files)); Mock.Arrange(() => _files.AddBrowseFile(Arg.AnyString, out _settingsFileInfo)); //Act CreateController().Set(Value); //Assert Mock.AssertAll(_xmlRepository); } [Test] public void Set_ValueIsntNull_CalleImportSettings() { //Arrange Mock.Arrange(() => _manager.ImportSettings(_sets, out _errorInformation)) .MustBeCalled(); Mock.Arrange(() => _manager.GetSettingsFiles(0, out _files)); Mock.Arrange(() => _files.AddBrowseFile(Arg.AnyString, out _settingsFileInfo)).DoNothing(); //Act CreateController().Set(Value); //Assert Mock.AssertAll(_xmlRepository); } private SettingsController CreateController() { return new SettingsController(Path, _manager, _xmlRepository); } } }
aquiladev/Coding4Fun.VisualStudioSync
VisualStudioSync.Tests/SettingsControllerTest.cs
C#
mit
4,052
import styled from 'styled-components'; const Wrapper = styled.div` width: 100%; height: 100%; display: block; align-items: space-between; `; export default Wrapper;
andyfrith/weather.goodapplemedia.com
app/containers/ForecastListItem/Wrapper.js
JavaScript
mit
176
<?php /** * Low Seg2Cat Language file * * @package low_seg2cat * @author Lodewijk Schutte <hi@gotolow.com> * @link http://gotolow.com/addons/low-seg2cat * @license http://creativecommons.org/licenses/by-sa/3.0/ */ $lang = array( 'category_groups' => 'Category groups', 'all_groups' => '-- All --', 'uri_pattern' => 'URI pattern', 'set_all_segments' => 'Set all segments', 'ignore_pagination' => 'Ignore pagination', 'parse_file_paths' => 'Parse file paths' ); /* End of file low_seg2cat_lang.php */
noslouch/pa
core/expressionengine/third_party/low_seg2cat/language/english/low_seg2cat_lang.php
PHP
mit
547
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Reflection; namespace AKDK.Messages.DockerEvents.Converters { /// <summary> /// JSON converter that that enables custom selection logic during deserialisation of the object to create based on the JSON encountered. /// </summary> /// <typeparam name="TBase"> /// The base type of object that the converter can deserialise. /// </typeparam> public abstract class JsonCreationConverter<TBase> : JsonConverter { /// <summary> /// Create a new <see cref="JsonCreationConverter{T}"/>. /// </summary> protected JsonCreationConverter() { } /// <summary> /// Can the converter write JSON? /// </summary> public override bool CanWrite { get { return false; } } /// <summary> /// Determine whether the converter can convert an object of the specified type. /// </summary> /// <param name="objectType"> /// The object type. /// </param> /// <returns> /// <c>true</c>, if the converter can convert an object of the specified type; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type objectType) { if (objectType == null) throw new ArgumentNullException(nameof(objectType)); return typeof(TBase).IsAssignableFrom(objectType); } /// <summary> /// Deserialise an object from JSON. /// </summary> /// <param name="reader"> /// The <see cref="JsonReader"/> to read from. /// </param><param name="objectType"> /// Type (or base type) of the object being deserialised. /// </param><param name="existingValue"> /// The existing value of the object being read. /// </param> /// <param name="serializer"> /// The calling serializer. /// </param> /// <returns> /// The deserialised object. /// </returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader == null) throw new ArgumentNullException(nameof(reader)); if (objectType == null) throw new ArgumentNullException(nameof(objectType)); if (serializer == null) throw new ArgumentNullException(nameof(serializer)); if (reader.TokenType == JsonToken.Null) return null; if (reader.TokenType != JsonToken.StartObject) { throw new FormatException( String.Format( "Unexpected token '{0}' encountered while deserialising object of type '{1}'.", reader.TokenType, typeof(TBase).FullName ) ); } JObject json = JObject.Load(reader); TBase target = Create(json); if (target == null) throw new InvalidOperationException("JsonCreationConverter.Create returned null."); // Populate the object properties serializer.Populate( json.CreateReader(), target ); return target; } /// <summary> /// Serialise an object to JSON. /// </summary> /// <param name="writer"> /// The <see cref="JsonWriter"/> to which serialised object data will be written. /// </param> /// <param name="value"> /// The object to serialise. /// </param> /// <param name="serializer"> /// The calling serialiser. /// </param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (writer == null) throw new ArgumentNullException(nameof(writer)); if (serializer == null) throw new ArgumentNullException(nameof(serializer)); throw new NotImplementedException("JsonCreationConverter cannot write JSON."); } /// <summary> /// Create an instance of to be populated, based properties in the JSON. /// </summary> /// <param name="json"> /// The JSON containing serialised object data. /// </param> /// <returns> /// The object instance to be populated. /// </returns> protected abstract TBase Create(JObject json); } }
tintoy/aykay-deekay
src/AKDK/Messages/DockerEvents/Converters/JsonCreationConverter.cs
C#
mit
3,851
<?php $files = array('global', 'module', 'admin', 'bootstrap', 'bootstrap-responsive', 'bootstrap-wysihtml5','datetimepicker'); $extended = array('install' => 'installation css', 'mailer' => 'Custom mailer css'); /* Do not edit below this line //-------------------------------*/ header("Content-Type: text/css; charset: UTF-8"); header("Cache-Control: must-revalidate"); header("Last-Modified: " . date(DateTime::RFC1123)); header("Expires: " . date(DateTime::RFC1123, time() + 600)); $css_file = '/* ------------------------------------------------------------ Expanse http://expansecms.org Content management for the web deisgner, by the web designer Written, with love, by Ian Tearle @iantearle Based on original work by Nate Cavanaugh and Jason Morrison All rights reserved. ============================================================ */ '; $folder = dirname(__FILE__).'/'; echo $css_file; ob_start("compress"); function compress($buffer) { /* remove comments */ $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer); /* remove tabs, spaces, newlines, etc. */ $buffer = str_replace(array("\r\n", "\r", "\n", "\t", ' ', ' ', ' '), '', $buffer); return $buffer; } $get_extended = isset($_GET['extend']) && ctype_alnum($_GET['extend']) ? $_GET['extend'] : ''; /* your css files */ foreach($files as $include) { $include = trim($include); if(!empty($get_extended) && isset($extended[$get_extended])) { $the_file = $folder.$get_extended.'.css'; } else { $the_file = $folder.$include.'.css'; } if(empty($include) || !file_exists($the_file)) { continue; } include($the_file); } ob_end_flush();
iantearle/Expanse-CMS-Public
expanse/css/expanse.css.php
PHP
mit
1,657
module.exports={ setup(context, cb){ //context.sigslot.signalAt('* * * * * *', 'sayHello') cb() }, sep(msg,next){ console.log(msg); return next() }, route(req, next){ switch(req.method){ case 'POST': return next() case 'GET': this.setOutput(this.time) default: return next(null, this.sigslot.abort()) } }, help(next){ next(this.error(404, `api ${this.api} is not supported yet`)) }, sayNow(next){ console.log(Date.now()) next() } }
ldarren/pico-api
test/util.js
JavaScript
mit
464
<?php namespace Murky\HomeBundle\Tests\Controller; use Symfony\Bundle\FrameworkBundle\Test\WebTestCase; class DefaultControllerTest extends WebTestCase { public function testIndex() { $client = static::createClient(); $crawler = $client->request('GET', '/hello/Fabien'); $this->assertTrue($crawler->filter('html:contains("Hello Fabien")')->count() > 0); } }
rlbaltha/biblio
src/Murky/HomeBundle/Tests/Controller/DefaultControllerTest.php
PHP
mit
399
/*********************************************** * MIT License * * Copyright (c) 2016 珠峰课堂,Ramroll * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ export * from "./ZButton" export * from "./BButton" export * from "./navbar/ZNavbar" export * from "./tabbar/Tabbar" export * from "./tabbar/TabbarItem" export * from "./ZBottomButton" export * from "./NetworkError" export * from "./CourseCardBig" export * from "./CourseCardSmall" export * from "./ZInput" export * from "./ZSwitch" export * from "./ZVCode" export * from "./ZImgCode" export * from "./NavBar" export * from "./HomeMenuView" export * from "./HomeMenuItem" export * from "./HomeGridView" export * from "./HomeGridItem" export * from "./QrImage"
njxiaohan/TransPal
app/domain/component/index.js
JavaScript
mit
1,752
goog.provide('ngeo.CreatefeatureController'); goog.provide('ngeo.createfeatureDirective'); goog.require('ngeo'); goog.require('ngeo.EventHelper'); /** @suppress {extraRequire} */ goog.require('ngeo.filters'); goog.require('ngeo.interaction.MeasureArea'); goog.require('ngeo.interaction.MeasureLength'); goog.require('ol.Feature'); goog.require('ol.geom.GeometryType'); goog.require('ol.interaction.Draw'); goog.require('ol.style.Style'); /** * A directive used to draw vector features of a single geometry type using * either a 'draw' or 'measure' interaction. Once a feature is finished being * drawn, it is added to a collection of features. * * The geometry types supported are: * - Point * - LineString * - Polygon * * Example: * * <a * href * translate * ngeo-btn * ngeo-createfeature * ngeo-createfeature-active="ctrl.createPointActive" * ngeo-createfeature-features="ctrl.features" * ngeo-createfeature-geom-type="ctrl.pointGeomType" * ngeo-createfeature-map="::ctrl.map" * class="btn btn-default ngeo-createfeature-point" * ng-class="{active: ctrl.createPointActive}" * ng-model="ctrl.createPointActive"> * </a> * * @htmlAttribute {boolean} ngeo-createfeature-active Whether the directive is * active or not. * @htmlAttribute {ol.Collection} ngeo-createfeature-features The collection of * features where to add those created by this directive. * @htmlAttribute {string} ngeo-createfeature-geom-type Determines the type * of geometry this directive should draw. * @htmlAttribute {ol.Map} ngeo-createfeature-map The map. * @return {angular.Directive} The directive specs. * @ngInject * @ngdoc directive * @ngname ngeoCreatefeature */ ngeo.createfeatureDirective = function() { return { controller: 'ngeoCreatefeatureController as cfCtrl', bindToController: true, scope: { 'active': '=ngeoCreatefeatureActive', 'features': '=ngeoCreatefeatureFeatures', 'geomType': '=ngeoCreatefeatureGeomType', 'map': '=ngeoCreatefeatureMap' } }; }; ngeo.module.directive('ngeoCreatefeature', ngeo.createfeatureDirective); /** * @param {gettext} gettext Gettext service. * @param {angular.$compile} $compile Angular compile service. * @param {angular.$filter} $filter Angular filter * @param {!angular.Scope} $scope Scope. * @param {angular.$timeout} $timeout Angular timeout service. * @param {ngeo.EventHelper} ngeoEventHelper Ngeo event helper service * @constructor * @struct * @ngInject * @ngdoc controller * @ngname ngeoCreatefeatureController */ ngeo.CreatefeatureController = function(gettext, $compile, $filter, $scope, $timeout, ngeoEventHelper) { /** * @type {boolean} * @export */ this.active = this.active === true; /** * @type {ol.Collection.<ol.Feature>|ol.source.Vector} * @export */ this.features; /** * @type {string} * @export */ this.geomType; /** * @type {ol.Map} * @export */ this.map; /** * @type {angular.$timeout} * @private */ this.timeout_ = $timeout; /** * @type {ngeo.EventHelper} * @private */ this.ngeoEventHelper_ = ngeoEventHelper; // Create the draw or measure interaction depending on the geometry type var interaction; var helpMsg; var contMsg; if (this.geomType === ngeo.GeometryType.POINT || this.geomType === ngeo.GeometryType.MULTI_POINT ) { interaction = new ol.interaction.Draw({ type: ol.geom.GeometryType.POINT }); } else if (this.geomType === ngeo.GeometryType.LINE_STRING || this.geomType === ngeo.GeometryType.MULTI_LINE_STRING ) { helpMsg = gettext('Click to start drawing length'); contMsg = gettext( 'Click to continue drawing<br/>' + 'Double-click or click last point to finish' ); interaction = new ngeo.interaction.MeasureLength( $filter('ngeoUnitPrefix'), { style: new ol.style.Style(), startMsg: $compile('<div translate>' + helpMsg + '</div>')($scope)[0], continueMsg: $compile('<div translate>' + contMsg + '</div>')($scope)[0] } ); } else if (this.geomType === ngeo.GeometryType.POLYGON || this.geomType === ngeo.GeometryType.MULTI_POLYGON ) { helpMsg = gettext('Click to start drawing area'); contMsg = gettext( 'Click to continue drawing<br/>' + 'Double-click or click starting point to finish' ); interaction = new ngeo.interaction.MeasureArea( $filter('ngeoUnitPrefix'), { style: new ol.style.Style(), startMsg: $compile('<div translate>' + helpMsg + '</div>')($scope)[0], continueMsg: $compile('<div translate>' + contMsg + '</div>')($scope)[0] } ); } goog.asserts.assert(interaction); interaction.setActive(this.active); this.map.addInteraction(interaction); /** * The draw or measure interaction responsible of drawing the vector feature. * The actual type depends on the geometry type. * @type {ol.interaction.Interaction} * @private */ this.interaction_ = interaction; // == Event listeners == $scope.$watch( function() { return this.active; }.bind(this), function(newVal) { this.interaction_.setActive(newVal); }.bind(this) ); var uid = ol.getUid(this); if (interaction instanceof ol.interaction.Draw) { this.ngeoEventHelper_.addListenerKey( uid, ol.events.listen( interaction, ol.interaction.Draw.EventType.DRAWEND, this.handleDrawEnd_, this ), true ); } else if (interaction instanceof ngeo.interaction.MeasureLength || interaction instanceof ngeo.interaction.MeasureArea) { this.ngeoEventHelper_.addListenerKey( uid, ol.events.listen( interaction, ngeo.MeasureEventType.MEASUREEND, this.handleDrawEnd_, this ), true ); } $scope.$on('$destroy', this.handleDestroy_.bind(this)); }; /** * Called when a feature is finished being drawn. Add the feature to the * collection. * @param {ol.interaction.Draw.Event|ngeo.MeasureEvent} event Event. * @export */ ngeo.CreatefeatureController.prototype.handleDrawEnd_ = function(event) { var feature = new ol.Feature(event.feature.getGeometry()); if (this.features instanceof ol.Collection) { this.features.push(feature); } else { this.features.addFeature(feature); } }; /** * Cleanup event listeners and remove the interaction from the map. * @private */ ngeo.CreatefeatureController.prototype.handleDestroy_ = function() { this.timeout_(function() { var uid = ol.getUid(this); this.ngeoEventHelper_.clearListenerKey(uid); this.interaction_.setActive(false); this.map.removeInteraction(this.interaction_); }.bind(this), 0); }; ngeo.module.controller( 'ngeoCreatefeatureController', ngeo.CreatefeatureController);
ger-benjamin/ngeo
src/directives/createfeature.js
JavaScript
mit
6,955
using System.Collections.Generic; using System.Security.Claims; namespace FujiyBlog.Web.Areas.Admin.ViewModels { public class AdminRoleSave { public string Id { get; set; } public string Name { get; set; } public IEnumerable<string> Claims { get; set; } } }
fujiy/FujiyBlog
src/FujiyBlog.Web/Areas/Admin/ViewModels/AdminRoleSave.cs
C#
mit
302
using UnityEngine; using System.Collections; using UnityEngine.UI; public class StartMenuUIControl : MonoBehaviour { /*===================== GameObjects =====================================================================================*/ public GameObject characterCreationMenuPrefab; /*===================== Menus =====================================================================================*/ public GameObject characterCreationMenu; /*===================== UI Elements =====================================================================================*/ public Button StartNewGameButton; public Button LoadGameButton; public Button GameInfoButton; public Button ExitGameButton; /*===================== Methods =====================================================================================*/ /*===================== Start() =====================================================================================*/ void Start(){ // Setup the characterCreationMenu // Get reference for menu because it was instantiated characterCreationMenu = GameObject.FindWithTag ("CharacterCreationMenu"); // Set characterCreationMenu's aphla to 0 (Makes transperent) characterCreationMenu.GetComponent<CanvasGroup> ().alpha = 0; // Block raycasts - making the menu not clickable characterCreationMenu.GetComponent<CanvasGroup> ().blocksRaycasts = false; // Activate CharacterCreationMenu characterCreationMenu.gameObject.SetActive (true); // Activate CharacterTraitsMenu characterCreationMenu.GetComponent<CharacterCreationUIControl> ().characterTraitsMenu.gameObject.SetActive (true); } // Start() /*===================== NewGame() =====================================================================================*/ // Fires when player clicks "StartNewGameButton" public void NewGame(){ // Deactivates MainMenu gameObject.SetActive(false); // Activates Character Creation Menu characterCreationMenu.gameObject.SetActive(true); // Runs setup needed for characterCreationMenu characterCreationMenu.GetComponent<CharacterCreationUIControl> ().SetUp (); } // NewGame() /*===================== LoadGame() =====================================================================================*/ // Fires when player clicks "LoadGameButton" public void LoadGame(){ Application.LoadLevel (1); } // LoadGame() /*===================== GameInfo() =====================================================================================*/ // Fires when player clicks "GameInfoButton" public void GameInfo(){ } // GameInfo() /*===================== ExitGame() =====================================================================================*/ // Fires when player clicks "ExitGameButton" public void ExitGame(){ // Exits the game Application.Quit(); } // ExitGame() } // class
Ross-Byrne/Management_Mayhem
Assets/Scripts/UI/StartMenu/StartMenuUIControl.cs
C#
mit
2,906
Mini.define('layerTemplate', function(){ var $detail = $('#t-detail').html() return { detail: _.template($detail) } }); Mini.define('serviceLayer', [ 'layerTemplate' ], function(layerTemplate){ return { ctn: function(e) { layer.open({ title: '箱动态列表', type: 1, skin: 'layui-layer-rim my-layer-skin', //加上边框 area: ['480px', 'auto'], //宽高 content: layerTemplate.detail(e.data) }) } } })
hoozi/hyd2
js/site/components/serviceLayer.js
JavaScript
mit
559
# frozen_string_literal: true Rails.application.routes.draw do match "lock/login", to: "lock#login", as: "lock_login", via: :get match "lock/refused", to: "lock#refused", as: "unlock_refused", via: :get match "lock/unlock", to: "lock#unlock", as: "unlock", via: :post end
charlotte-ruby/lock
config/routes.rb
Ruby
mit
279
// For vendors for example jQuery, Lodash, angular2-jwt just import them here unless you plan on // chunking vendors files for async loading. You would need to import the async loaded vendors // at the entry point of the async loaded file. Also see custom-typings.d.ts as you also need to // run `typings install x` where `x` is your module // Angular 2 import '@angular/platform-browser'; import '@angular/platform-browser-dynamic'; import '@angular/router'; import '@angular/forms'; import '@angular/common'; import '@angular/core'; import '@angular/http'; import '@angularclass/form-validators'; // RxJS import 'rxjs/add/operator/map'; import 'rxjs/add/operator/mergeMap'; if ('production' === ENV) { // Production } else { // Development }
katallaxie/generator-angular2-starter
template/src/vendor.ts
TypeScript
mit
756
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2018 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Internal function to process the separation of a physics body from a tile. * * @function Phaser.Physics.Arcade.Tilemap.ProcessTileSeparationX * @since 3.0.0 * * @param {Phaser.Physics.Arcade.Body} body - The Body object to separate. * @param {number} x - The x separation amount. */ var ProcessTileSeparationX = function (body, x) { if (x < 0) { body.blocked.left = true; } else if (x > 0) { body.blocked.right = true; } body.position.x -= x; if (body.bounce.x === 0) { body.velocity.x = 0; } else { body.velocity.x = -body.velocity.x * body.bounce.x; } }; module.exports = ProcessTileSeparationX;
rblopes/phaser
src/physics/arcade/tilemap/ProcessTileSeparationX.js
JavaScript
mit
901
<?php namespace Oro\Bundle\UserBundle\Tests\Unit\Type; use Oro\Bundle\UserBundle\Form\Type\ChangePasswordType; use Symfony\Component\Form\Test\FormIntegrationTestCase; class ChangePasswordTypeTest extends FormIntegrationTestCase { /** @var \PHPUnit_Framework_MockObject_MockObject */ protected $subscriber; /** @var ChangePasswordType */ protected $type; public function setUp() { parent::setUp(); $this->subscriber = $this->getMockBuilder('Oro\Bundle\UserBundle\Form\EventListener\ChangePasswordSubscriber') ->disableOriginalConstructor() ->getMock(); $this->type = new ChangePasswordType($this->subscriber); } /** * Test buildForm */ public function testBuildForm() { $builder = $this->getMock('Symfony\Component\Form\Test\FormBuilderInterface'); $options = array(); $builder->expects($this->once()) ->method('addEventSubscriber') ->with($this->isInstanceOf('Oro\Bundle\UserBundle\Form\EventListener\ChangePasswordSubscriber')); $builder->expects($this->exactly(2)) ->method('add') ->will($this->returnSelf()); $this->type->buildForm($builder, $options); } /** * Test defaults */ public function testSetDefaultOptions() { $resolver = $this->getMock('Symfony\Component\OptionsResolver\OptionsResolverInterface'); $resolver->expects($this->once()) ->method('setDefaults') ->with($this->isType('array')); $this->type->configureOptions($resolver); } /** * Test name */ public function testName() { $this->assertEquals('oro_change_password', $this->type->getName()); } }
akeneo/platform
src/Oro/Bundle/UserBundle/Tests/Unit/Form/Type/ChangePasswordTypeTest.php
PHP
mit
1,781
export function mergeUsers({ props, state, uuid }) { if (props.response.result.users && props.response.result.users.length !== 0) { let orderKey = 1 for (const user of props.response.result.users) { user.orderKey = orderKey const usersInState = state.get('admin.users') const uidInState = Object.keys(usersInState).filter((uid) => { return usersInState[uid].email === user.email })[0] if (uidInState) { state.merge(`admin.users.${uidInState}`, user) } else { state.set(`admin.users.${uuid()}`, user) } orderKey++ } } else { return { noUsersFound: true } } } export function getNextPage({ props, state }) { let nextPage = 1 switch (props.nextPage) { case 'previous': nextPage = parseInt(state.get('admin.currentPage')) - 1 break case 'next': nextPage = parseInt(state.get('admin.currentPage')) + 1 break case 'last': nextPage = state.get('admin.pages') break default: if (typeof props.nextPage === 'number') { nextPage = Math.floor(props.nextPage) } } return { nextPage } }
yacoma/auth-boilerplate
client/app/modules/admin/actions.js
JavaScript
mit
1,148
QuakeMap::Application.configure do # Settings specified here will take precedence over those in config/environment.rb # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Log error messages when you accidentally call methods on nil. config.whiny_nils = true # Show full error reports and disable caching config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment config.action_controller.allow_forgery_protection = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Use SQL instead of Active Record's schema dumper when creating the test database. # This is necessary if your schema can't be completely dumped by the schema dumper, # like if you have constraints or database-specific column types # config.active_record.schema_format = :sql # Print deprecation notices to the stderr config.active_support.deprecation = :stderr # Configure static asset server for tests with Cache-Control for performance config.serve_static_assets = true config.static_cache_control = 'public, max-age=3600' # Allow pass debug_assets=true as a query parameter to load pages with unpackaged assets config.assets.allow_debugging = true end
QuakeMap/quakemap
config/environments/test.rb
Ruby
mit
1,814
package errors import ( "net/http" "fmt" ) // NewValidationError creates a new APIError with 422 Unprocessable entity http status code to be used as reporting the validation failure func NewValidationError(e ... error) APIError { return APIError{ StatusCode: http.StatusUnprocessableEntity, Title: "Request data validation error", LocalizationKey: "validation_error", Errors: e, } } // NewParameterRequiredError returns a new native error reporting that a specified parameter is missing func NewParameterRequiredError(param string) error { return New(fmt.Sprintf("Parameter %s is required", param)) } // NewParameterRequiredError returns a new native error reporting that a specified parameter is invalid func NewParameterInvalidError(param string) error { return New(fmt.Sprintf("Parameter %s failed to pass validation", param)) }
uroshercog/kanban-board-backend
http/errors/validation.go
GO
mit
874
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) { var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; return c > 3 && r && Object.defineProperty(target, key, r), r; }; import { customElement, html, LitElement, property, } from "lit-element"; import { fireEvent } from "./util/fire-event"; import { getMouseTouchLocation } from "./util/get-mouse-touch-location"; import { getTouchIdentifier } from "./util/get-touch-identifier"; import { matchesSelectorAndParentsTo } from "./util/match-selector"; let LitDraggable = class LitDraggable extends LitElement { constructor() { super(...arguments); this.disabled = false; this._dragging = false; } firstUpdated() { this.addEventListener("mousedown", this._dragStart.bind(this), { capture: true, passive: false, }); this.addEventListener("touchstart", this._dragStart.bind(this), { capture: true, passive: false, }); document.addEventListener("mousemove", this._drag.bind(this), { capture: true, passive: false, }); document.addEventListener("touchmove", this._drag.bind(this), { capture: true, passive: false, }); document.addEventListener("mouseup", this._dragEnd.bind(this), { capture: true, passive: false, }); document.addEventListener("touchcancel", this._dragEnd.bind(this), { capture: true, passive: false, }); document.addEventListener("touchend", this._dragEnd.bind(this), { capture: true, passive: false, }); } render() { return html `<slot></slot>`; } _dragStart(ev) { if ((ev.type.startsWith("mouse") && ev.button !== 0) || this.disabled) { return; } console.log(ev); if (this.handle && !matchesSelectorAndParentsTo(ev.currentTarget, this.handle, this.offsetParent)) { return; } ev.preventDefault(); ev.stopPropagation(); if (ev.type === "touchstart") { this._touchIdentifier = getTouchIdentifier(ev); } const pos = getMouseTouchLocation(ev, this._touchIdentifier); if (!pos) { return; } this.startX = pos.x; this.startY = pos.y; this._dragging = true; fireEvent(this, "dragStart", { startX: this.startX, startY: this.startY, }); } _drag(ev) { if (!this._dragging || this.disabled) { return; } ev.preventDefault(); ev.stopPropagation(); const pos = getMouseTouchLocation(ev, this._touchIdentifier); if (!pos) { return; } let deltaX = pos.x - this.startX; let deltaY = pos.y - this.startY; if (this.grid) { deltaX = Math.round(deltaX / this.grid[0]) * this.grid[0]; deltaY = Math.round(deltaY / this.grid[1]) * this.grid[1]; } if (!deltaX && !deltaY) { return; } fireEvent(this, "dragging", { deltaX, deltaY, }); } _dragEnd(ev) { if (!this._dragging || this.disabled) { return; } ev.preventDefault(); ev.stopPropagation(); this._touchIdentifier = undefined; this._dragging = false; fireEvent(this, "dragEnd"); } }; __decorate([ property({ type: Array }) ], LitDraggable.prototype, "grid", void 0); __decorate([ property({ type: Boolean, reflect: true }) ], LitDraggable.prototype, "disabled", void 0); __decorate([ property() ], LitDraggable.prototype, "handle", void 0); LitDraggable = __decorate([ customElement("lit-draggable") ], LitDraggable); export { LitDraggable }; //# sourceMappingURL=lit-draggable.js.map
cdnjs/cdnjs
ajax/libs/lit-grid-layout/1.1.4/lit-draggable.js
JavaScript
mit
4,479
using System; class A { internal string S; internal void Say() { Console.WriteLine(S); } } class Program { private static void doit(Action sayit) { sayit(); } static void Main(string[] args) { A a = new A(); a.S = "I am one"; A b = new A(); b.S = "I am two"; doit(a.Say); doit(b.Say); } }
autumn009/TanoCSharpSamples
Chap4/デリゲート型はインスタンスを区別する/デリゲート型はインスタンスを区別する/Program.cs
C#
mit
398
<?php /* Safe sample input : backticks interpretation, reading the file /tmp/tainted.txt sanitize : use mysql_real_escape_string via an object and a classic getter construction : interpretation with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $tainted = `cat /tmp/tainted.txt`; class Sanitize{ private $data; public function __construct($input){ $this->data = $input ; } public function getData(){ return $this->data; } public function sanitize(){ $this->data = mysql_real_escape_string($this->data) ; } } $sanitizer = new Sanitize($tainted) ; $sanitizer->sanitize(); $tainted = $sanitizer->getData(); $query = "SELECT * FROM ' $tainted '"; $conn = mysql_connect('localhost', 'mysql_user', 'mysql_password'); // Connection to the database (address, user, password) mysql_select_db('dbname') ; echo "query : ". $query ."<br /><br />" ; $res = mysql_query($query); //execution while($data =mysql_fetch_array($res)){ print_r($data) ; echo "<br />" ; } mysql_close($conn); ?>
stivalet/PHP-Vulnerability-test-suite
Injection/CWE_89/safe/CWE_89__backticks__object-func_mysql_real_escape_stringGetter__select_from-interpretation_simple_quote.php
PHP
mit
1,889
#include <Python.h> #include <maya/MFnPlugin.h> #include <maya/MGlobal.h> #include <maya/MPxNode.h> #include <maya/MFnTypedAttribute.h> #include <maya/MFnGenericAttribute.h> #include <maya/MFnNumericData.h> #include <maya/MFnNumericAttribute.h> #include <maya/MFnNumericData.h> #include <maya/MFnMatrixData.h> #include <maya/MDataBlock.h> #include <maya/MArrayDataHandle.h> #include <maya/MVector.h> #include <maya/MMatrix.h> #include <maya/MFnDependencyNode.h> #ifdef _WIN32 #pragma warning(disable: 4127) #endif #define EXPRESPY_NODE_ID 0x00070004 // ‚à‚µ‰½‚©‚ƏՓ˂·‚é‚Ȃ珑‚«Š·‚¦‚邱‚ƁB(Free: 0x00000000 ` 0x0007ffff) #if PY_MAJOR_VERSION < 3 // py2 ‚Å‚Í io.StringIO ‚ł͂Ȃ­ StringIO.StringIO ‚ðŽg—p‚·‚邱‚ƂŠstr ‚Æ unicode ‚É—¼‘Ήž‚³‚¹‚éB // cStringIO ‚É‚µ‚È‚¢‚Ì‚Í unicode ‚ð’Ê‚·‚½‚߁B #define STRINGIO_MODULE "StringIO" #define BUILTINS_MODULE_NAME "__builtin__" #define PYINT_fromLong PyInt_FromLong #define PYSTR_fromChar PyString_FromString #define PYBYTES_asChar PyString_AsString #define PYBYTES_check PyString_Check #define PYBYTES_SIZE PyString_GET_SIZE #else // py3 ‚Å‚Í io.StringIO ‚ðŽg—p‚µ unicode ‚݂̂ɑΉž‚·‚éB #define STRINGIO_MODULE "io" #define BUILTINS_MODULE_NAME "builtins" #define PYINT_fromLong PyLong_FromLong #define PYSTR_fromChar PyUnicode_FromString #define PYBYTES_asChar PyBytes_AsString #define PYBYTES_check PyBytes_Check #define PYBYTES_SIZE PyBytes_GET_SIZE #endif //============================================================================= /// Functions. //============================================================================= /// ƒ‚ƒWƒ…[ƒ‹‚ðƒCƒ“ƒ|[ƒg‚·‚éBPyImport_ImportModule ‚æ‚荂…€B static inline PyObject* _importModule(const char* name) { PyObject* nameo = PYSTR_fromChar(name); if (nameo) { PyObject* mod = PyImport_Import(nameo); Py_DECREF(nameo); return mod; } return NULL; } /// dict ‚©‚ç type ƒIƒuƒWƒFƒNƒg‚𓾂éB static inline PyObject* _getTypeObject(PyObject* dict, const char* name) { PyObject* o = PyDict_GetItemString(dict, name); return PyType_Check(o) ? o : NULL; } /// ’l‚ÌŽQÆ‚ð’D‚¢‚‚ dict ‚É’l‚ðƒZƒbƒg‚·‚éB static inline void _setDictStealValue(PyObject* dic, const char* key, PyObject* valo) { if (valo) { PyDict_SetItemString(dic, key, valo); Py_DECREF(valo); } else { PyDict_SetItemString(dic, key, Py_None); } } /// ƒL[‚Æ’l‚ÌŽQÆ‚ð’D‚¢‚‚ I/O —p dict ‚É’l‚ðƒZƒbƒg‚·‚éB static inline void _setIODictStealValue(PyObject* dic, PyObject* keyo, PyObject* valo) { if (valo) { PyDict_SetItem(dic, keyo, valo); Py_DECREF(valo); } else { PyDict_SetItem(dic, keyo, Py_None); } Py_DECREF(keyo); } /// dict ‚É int ‚ðƒL[‚Æ‚µ‚Ä PyObject* ‚ðƒZƒbƒg‚·‚éB static inline void _setDictValue(PyObject* dic, int key, PyObject* valo) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { PyDict_SetItem(dic, keyo, valo); Py_DECREF(keyo); } } /// dict ‚©‚ç int ‚ðƒL[‚Æ‚µ‚Ä PyObject* ‚𓾂éB static inline PyObject* _getDictValue(PyObject* dic, int key) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { PyObject* valo = PyDict_GetItem(dic, keyo); Py_DECREF(keyo); return valo; } return NULL; } /// Œ^”»•ÊÏ‚Ý‚Ì sequence ‚Ì PyObject* ‚©‚ç double3 ‚Ì data ‚𓾂éB static inline MObject _getDouble3Value(PyObject* valo) { MFnNumericData fnOutData; MObject data = fnOutData.create(MFnNumericData::k3Double); fnOutData.setData( PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 0)), PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 1)), PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 2)) ); return data; } /// Œ^”»•ÊÏ‚Ý‚Ì sequence ‚Ì PyObject* ‚©‚ç double4 ‚Ì data ‚𓾂éB static inline MObject _getDouble4Value(PyObject* valo) { MFnNumericData fnOutData; MObject data = fnOutData.create(MFnNumericData::k3Double); fnOutData.setData( PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 0)), PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 1)), PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 2)), PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 3)) ); return data; } /// Œ^”»•ÊÏ‚Ý‚Ì sequence ‚Ì PyObject* ‚©‚ç float3 ‚Ì data ‚𓾂éB static inline MObject _getFloat3Value(PyObject* valo) { MFnNumericData fnOutData; MObject data = fnOutData.create(MFnNumericData::k3Float); fnOutData.setData( static_cast<float>(PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 0))), static_cast<float>(PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 1))), static_cast<float>(PyFloat_AS_DOUBLE(PySequence_GetItem(valo, 2))) ); return data; } /// sequence ‚Ì PyObject* ‚©‚ç double2, double3, double4, long2, long3 ‚Ì‚¢‚¸‚ê‚©‚𓾂éB static inline MObject _getTypedSequence(PyObject* valo) { MObject data; Py_ssize_t num = PySequence_Length(valo); if (num < 2 || 4 < num) return data; bool hasFloat = false; int ival[4]; double fval[4]; for (Py_ssize_t i=0; i<num; ++i) { PyObject* v = PySequence_GetItem(valo, i); if (PyFloat_Check(v)) { hasFloat = true; fval[i] = PyFloat_AS_DOUBLE(v); #if PY_MAJOR_VERSION < 3 } else if (PyInt_Check(v)) { ival[i] = PyInt_AS_LONG(v); fval[i] = static_cast<double>(ival[i]); #endif } else if (PyLong_Check(v)) { ival[i] = static_cast<int>(PyLong_AsLong(v)); // TODO: OverflowError ‘΍ôB fval[i] = static_cast<double>(ival[i]); } else { return data; } } MFnNumericData fnOutData; switch (num) { case 2: if (hasFloat) { data = fnOutData.create(MFnNumericData::k2Double); fnOutData.setData(fval[0], fval[1]); } else { data = fnOutData.create(MFnNumericData::k2Long); fnOutData.setData(ival[0], ival[1]); } break; case 3: if (hasFloat) { data = fnOutData.create(MFnNumericData::k3Double); fnOutData.setData(fval[0], fval[1], fval[2]); } else { data = fnOutData.create(MFnNumericData::k3Long); fnOutData.setData(ival[0], ival[1], ival[2]); } break; case 4: data = fnOutData.create(MFnNumericData::k4Double); fnOutData.setData(fval[0], fval[1], fval[2], fval[3]); break; } return data; } /// Œ^”»•ÊÏ‚Ý‚Ì PyObject* ‚Ì’l‚ð MMatrix ‚É“¾‚éB static inline void _getMatrixValueFromPyObject(MMatrix& mat, PyObject* valo) { PyObject* getElement = PyObject_GetAttrString(valo, "getElement"); if (getElement) { PyObject* idxs[] = { PYINT_fromLong(0), PYINT_fromLong(1), PYINT_fromLong(2), PYINT_fromLong(3) }; PyObject* args = PyTuple_New(2); for (unsigned i=0; i<4; ++i) { PyTuple_SET_ITEM(args, 0, idxs[i]); for (unsigned j=0; j<4; ++j) { PyTuple_SET_ITEM(args, 1, idxs[j]); PyObject* vo = PyObject_CallObject(getElement, args); //PyObject* vo = PyObject_CallFunction(getElement, "(ii)", i, j); if (vo) { mat.matrix[i][j] = PyFloat_AS_DOUBLE(vo); Py_DECREF(vo); } else { mat.matrix[i][j] = MMatrix::identity[i][j]; } } } PyTuple_SET_ITEM(args, 0, idxs[0]); PyTuple_SET_ITEM(args, 1, idxs[1]); Py_DECREF(args); Py_DECREF(idxs[2]); Py_DECREF(idxs[3]); } else { mat.setToIdentity(); } } //============================================================================= /// Exprespy node class. //============================================================================= class Exprespy : public MPxNode { PyObject* _base_globals; PyObject* _input; PyObject* _output; PyObject* _globals; PyCodeObject* _codeobj; PyObject* _mplug2_input; PyObject* _mplug2_output; PyObject* _mplug1_input; PyObject* _mplug1_output; PyObject* _api2_dict; PyObject* _type2_MVector; PyObject* _type2_MPoint; PyObject* _type2_MEulerRotation; PyObject* _type2_MMatrix; PyObject* _type2_MObject; PyObject* _type2_MQuaternion; PyObject* _type2_MColor; PyObject* _type2_MFloatVector; PyObject* _type2_MFloatPoint; PyObject* _api1_dict; PyObject* _type1_MObject; PyObject* _type_StringIO; PyObject* _sys_dict; PyObject* _sys_stdout; PyObject* _sys_stderr; int _count; MStatus _compileCode(MDataBlock&); MStatus _executeCode(MDataBlock&); void _printPythonError(); void _setInputScalar(int key, const double& val); void _setInputString(int key, const MString& str); void _setInputShort2(int key, MObject& data); void _setInputShort3(int key, MObject& data); void _setInputLong2(int key, MObject& data); void _setInputLong3(int key, MObject& data); void _setInputFloat2(int key, MObject& data); void _setInputFloat3(int key, MObject& data); void _setInputDouble2(int key, MObject& data); void _setInputDouble3(int key, MObject& data); void _setInputDouble4(int key, MObject& data); void _setInputVector3(int key, MObject& data); void _setInputMatrix(int key, MObject& data); void _setInputMObject2(int key); void _setOutputMObject2(int key, PyObject* valo); void _preparePyPlug2(); void _setInputMObject1(int key); void _setOutputMObject1(int key, PyObject* valo); void _preparePyPlug1(); public: static MTypeId id; static MString name; static MObject aCode; static MObject aInputsAsApi1Object; static MObject aCompiled; static MObject aInput; static MObject aOutput; static void* creator() { return new Exprespy; } static MStatus initialize(); Exprespy(); virtual ~Exprespy(); MStatus compute(const MPlug&, MDataBlock&); #if MAYA_API_VERSION >= 20160000 SchedulingType schedulingType () const { return MPxNode::kGloballySerial; } #endif }; MTypeId Exprespy::id(EXPRESPY_NODE_ID); MString Exprespy::name("exprespy"); MObject Exprespy::aCode; MObject Exprespy::aInputsAsApi1Object; MObject Exprespy::aCompiled; MObject Exprespy::aInput; MObject Exprespy::aOutput; //------------------------------------------------------------------------------ /// Static: Initialization. //------------------------------------------------------------------------------ MStatus Exprespy::initialize() { MFnTypedAttribute fnTyped; MFnNumericAttribute fnNumeric; MFnGenericAttribute fnGeneric; // code aCode = fnTyped.create("code", "cd", MFnData::kString); fnTyped.setConnectable(false); CHECK_MSTATUS_AND_RETURN_IT( addAttribute(aCode) ); // inputsAsApi1Object aInputsAsApi1Object = fnNumeric.create("inputsAsApi1Object", "iaa1o", MFnNumericData::kBoolean, false); fnTyped.setConnectable(false); CHECK_MSTATUS_AND_RETURN_IT( addAttribute(aInputsAsApi1Object) ); // compiled aCompiled = fnNumeric.create("compile", "cm", MFnNumericData::kBoolean, false); fnNumeric.setWritable(false); fnNumeric.setStorable(false); fnNumeric.setHidden(true); CHECK_MSTATUS_AND_RETURN_IT( addAttribute(aCompiled) ); // input aInput = fnGeneric.create("input", "i"); // “ü—͂̏ꍇ‚Í kAny ‚¾‚¯‚ŃRƒlƒNƒg‚Í‘S‚Ä‹–—e‚³‚ê‚邪 setAttr ‚ł͒e‚©‚ê‚Ä‚µ‚Ü‚¤‚̂ŁAŒ‹‹Ç‘S‚Ă̗ñ‹“‚ª•K—vB fnGeneric.addDataAccept(MFnData::kAny); fnGeneric.addDataAccept(MFnData::kNumeric); // ‚±‚ê‚Í–³‚­‚Ä‚à‘åä•v‚»‚¤‚¾‚ªˆê‰žB fnGeneric.addNumericDataAccept(MFnNumericData::k2Short); fnGeneric.addNumericDataAccept(MFnNumericData::k3Short); fnGeneric.addNumericDataAccept(MFnNumericData::k2Long); fnGeneric.addNumericDataAccept(MFnNumericData::k3Long); fnGeneric.addNumericDataAccept(MFnNumericData::k2Float); fnGeneric.addNumericDataAccept(MFnNumericData::k3Float); fnGeneric.addNumericDataAccept(MFnNumericData::k2Double); fnGeneric.addNumericDataAccept(MFnNumericData::k3Double); fnGeneric.addNumericDataAccept(MFnNumericData::k4Double); fnGeneric.addDataAccept(MFnData::kPlugin); fnGeneric.addDataAccept(MFnData::kPluginGeometry); fnGeneric.addDataAccept(MFnData::kString); fnGeneric.addDataAccept(MFnData::kMatrix); fnGeneric.addDataAccept(MFnData::kStringArray); fnGeneric.addDataAccept(MFnData::kDoubleArray); fnGeneric.addDataAccept(MFnData::kIntArray); fnGeneric.addDataAccept(MFnData::kPointArray); fnGeneric.addDataAccept(MFnData::kVectorArray); fnGeneric.addDataAccept(MFnData::kComponentList); fnGeneric.addDataAccept(MFnData::kMesh); fnGeneric.addDataAccept(MFnData::kLattice); fnGeneric.addDataAccept(MFnData::kNurbsCurve); fnGeneric.addDataAccept(MFnData::kNurbsSurface); fnGeneric.addDataAccept(MFnData::kSphere); fnGeneric.addDataAccept(MFnData::kDynArrayAttrs); fnGeneric.addDataAccept(MFnData::kSubdSurface); // ˆÈ‰º‚̓Nƒ‰ƒbƒVƒ…‚·‚éB //fnGeneric.addDataAccept(MFnData::kDynSweptGeometry); //fnGeneric.addDataAccept(MFnData::kNObject); //fnGeneric.addDataAccept(MFnData::kNId); fnGeneric.setArray(true); CHECK_MSTATUS_AND_RETURN_IT(addAttribute(aInput)); // output aOutput = fnGeneric.create("output", "o"); // o—͂̏ꍇ‚Í kAny ‚¾‚¯‚Å‚Í Numeric ‚Æ NumericData ˆÈŠO‚̃RƒlƒNƒg‚Í‹–—e‚³‚ê‚È‚¢B // setAttr ‚Í•s—v‚Ȃ̂ŁA“ü—͂ƈႢ NumericData ‚Ì—ñ‹“‚܂ł͕s—v‚Æ‚·‚éB fnGeneric.addDataAccept(MFnData::kAny); //fnGeneric.addDataAccept(MFnData::kNumeric); //fnGeneric.addNumericDataAccept(MFnNumericData::k2Short); //fnGeneric.addNumericDataAccept(MFnNumericData::k3Short); //fnGeneric.addNumericDataAccept(MFnNumericData::k2Long); //fnGeneric.addNumericDataAccept(MFnNumericData::k3Long); //fnGeneric.addNumericDataAccept(MFnNumericData::k2Float); //fnGeneric.addNumericDataAccept(MFnNumericData::k3Float); //fnGeneric.addNumericDataAccept(MFnNumericData::k2Double); //fnGeneric.addNumericDataAccept(MFnNumericData::k3Double); //fnGeneric.addNumericDataAccept(MFnNumericData::k4Double); fnGeneric.addDataAccept(MFnData::kPlugin); fnGeneric.addDataAccept(MFnData::kPluginGeometry); fnGeneric.addDataAccept(MFnData::kString); fnGeneric.addDataAccept(MFnData::kMatrix); fnGeneric.addDataAccept(MFnData::kStringArray); fnGeneric.addDataAccept(MFnData::kDoubleArray); fnGeneric.addDataAccept(MFnData::kIntArray); fnGeneric.addDataAccept(MFnData::kPointArray); fnGeneric.addDataAccept(MFnData::kVectorArray); fnGeneric.addDataAccept(MFnData::kComponentList); fnGeneric.addDataAccept(MFnData::kMesh); fnGeneric.addDataAccept(MFnData::kLattice); fnGeneric.addDataAccept(MFnData::kNurbsCurve); fnGeneric.addDataAccept(MFnData::kNurbsSurface); fnGeneric.addDataAccept(MFnData::kSphere); fnGeneric.addDataAccept(MFnData::kDynArrayAttrs); fnGeneric.addDataAccept(MFnData::kSubdSurface); // ˆÈ‰º‚Í input ‚ƈá‚Á‚ăNƒ‰ƒbƒVƒ…‚Í‚µ‚È‚¢‚悤‚¾‚ª•s—v‚¾‚낤B //fnGeneric.addDataAccept(MFnData::kDynSweptGeometry); //fnGeneric.addDataAccept(MFnData::kNObject); //fnGeneric.addDataAccept(MFnData::kNId); fnGeneric.setWritable(false); fnGeneric.setStorable(false); fnGeneric.setArray(true); fnGeneric.setDisconnectBehavior(MFnAttribute::kDelete); CHECK_MSTATUS_AND_RETURN_IT(addAttribute(aOutput)); // Set the attribute dependencies. attributeAffects(aCode, aCompiled); attributeAffects(aCode, aOutput); attributeAffects(aInputsAsApi1Object, aOutput); attributeAffects(aInput, aOutput); return MS::kSuccess; } //------------------------------------------------------------------------------ /// Constructor. //------------------------------------------------------------------------------ Exprespy::Exprespy() : _base_globals(NULL), _input(NULL), _output(NULL), _globals(NULL), _codeobj(NULL), _mplug2_input(NULL), _mplug2_output(NULL), _mplug1_input(NULL), _mplug1_output(NULL), _api2_dict(NULL), _type2_MVector(NULL), _type2_MPoint(NULL), _type2_MEulerRotation(NULL), _type2_MMatrix(NULL), _type2_MObject(NULL), _type2_MQuaternion(NULL), _type2_MColor(NULL), _type2_MFloatVector(NULL), _type2_MFloatPoint(NULL), _api1_dict(NULL), _type1_MObject(NULL), _type_StringIO(NULL), _sys_dict(NULL), _sys_stdout(NULL), _sys_stderr(NULL), _count(0) { } //------------------------------------------------------------------------------ /// Destructor. //------------------------------------------------------------------------------ Exprespy::~Exprespy() { if (_base_globals) { PyGILState_STATE gil = PyGILState_Ensure(); Py_XDECREF(_sys_stdout); Py_XDECREF(_sys_stderr); Py_XDECREF(_mplug2_input); Py_XDECREF(_mplug2_output); Py_XDECREF(_mplug1_input); Py_XDECREF(_mplug1_output); Py_XDECREF(_codeobj); Py_XDECREF(_globals); Py_DECREF(_output); Py_DECREF(_input); Py_DECREF(_base_globals); PyGILState_Release(gil); } } //------------------------------------------------------------------------------ /// Computation. //------------------------------------------------------------------------------ MStatus Exprespy::compute(const MPlug& plug, MDataBlock& block) { if (plug == aCompiled) { return _compileCode(block); } else if (plug == aOutput) { return _executeCode(block); } return MS::kUnknownParameter; } //------------------------------------------------------------------------------ /// Compile a code. //------------------------------------------------------------------------------ MStatus Exprespy::_compileCode(MDataBlock& block) { MString code = block.inputValue(aCode).asString(); //MGlobal::displayInfo("COMPILE"); // Python ‚̏ˆ—ŠJŽniGILŽæ“¾jB PyGILState_STATE gil = PyGILState_Ensure(); // ˆê“x\’zÏ‚݂ȂçŒÃ‚¢ƒRƒ“ƒpƒCƒ‹Ï‚݃R[ƒh‚ð”jŠüB if (_base_globals) { Py_CLEAR(_codeobj); Py_CLEAR(_globals); // ‰‚߂ĂȂçŠÂ‹«\’z‚·‚éB } else { PyObject* builtins = PyImport_ImportModule(BUILTINS_MODULE_NAME); if (builtins) { // ƒ[ƒJƒ‹ŠÂ‹« (globals) ‚̃x[ƒX‚ð\’z‚·‚éB // ‚±‚ê‚͏‘‚«Š·‚¦‚ç‚ê‚È‚¢‚悤‚ɕێ‚µAŠeƒR[ƒhŒü‚¯‚ɂ͂±‚ê‚𕡐»‚µ‚Ä—˜—p‚·‚éB _base_globals = PyDict_New(); _input = PyDict_New(); _output = PyDict_New(); if (_base_globals && _input && _output) { // ‘g‚ݍž‚ÝŽ«‘‚ðƒZƒbƒgB _setDictStealValue(_base_globals, "__builtins__", builtins); _setDictStealValue(_base_globals, "__name__", PYSTR_fromChar("__exprespy__")); // ƒm[ƒh‚Ì“üo—͂̂½‚ß‚Ì dict ‚𐶐¬B PyDict_SetItemString(_base_globals, "IN", _input); PyDict_SetItemString(_base_globals, "OUT", _output); // ƒ‚ƒWƒ…[ƒ‹‚ðƒCƒ“ƒ|[ƒg‚µ globals ‚ɃZƒbƒgB PyObject* mod_api2 = _importModule("maya.api.OpenMaya"); _setDictStealValue(_base_globals, "api", mod_api2); _setDictStealValue(_base_globals, "math", _importModule("math")); _setDictStealValue(_base_globals, "cmds", _importModule("maya.cmds")); _setDictStealValue(_base_globals, "mel", _importModule("maya.mel")); PyObject* mod_api1 = _importModule("maya.OpenMaya"); _setDictStealValue(_base_globals, "api1", mod_api1); PyObject* mod_sys = _importModule("sys"); _setDictStealValue(_base_globals, "sys", mod_sys); // Python API ‚©‚çƒNƒ‰ƒX‚ðŽæ“¾‚µ‚Ä‚¨‚­Bu–³‚­‚È‚ç‚È‚¢‘O’ñv‚Å INCREF ‚¹‚¸‚ɕێ‚·‚éB // NOTE: –³‚­‚Ȃ邱‚Æ‚à—L‚蓾‚éi—Ⴆ‚΁AŽQÆ‚ð”jŠü‚µ‚ăCƒ“ƒ|[ƒg‚µ’¼‚µj‚ƍl‚¦‚邯­XŠëŒ¯‚ł͂ ‚éB if (mod_api2) { _api2_dict = PyModule_GetDict(mod_api2); _type2_MVector = _getTypeObject(_api2_dict, "MVector"); _type2_MPoint = _getTypeObject(_api2_dict, "MPoint"); _type2_MEulerRotation = _getTypeObject(_api2_dict, "MEulerRotation"); _type2_MMatrix = _getTypeObject(_api2_dict, "MMatrix"); _type2_MObject = _getTypeObject(_api2_dict, "MObject"); _type2_MQuaternion = _getTypeObject(_api2_dict, "MQuaternion"); _type2_MColor = _getTypeObject(_api2_dict, "MColor"); _type2_MFloatVector = _getTypeObject(_api2_dict, "MFloatVector"); _type2_MFloatPoint = _getTypeObject(_api2_dict, "MFloatPoint"); } if (mod_api1) { _api1_dict = PyModule_GetDict(mod_api1); _type1_MObject = _getTypeObject(_api1_dict, "MObject"); } // o—̓XƒgƒŠ[ƒ€‚ðæ‚ÁŽæ‚邽‚߂̏€”õB if (mod_sys) { PyObject* mod_StringIO = _importModule(STRINGIO_MODULE); if (mod_StringIO) { _type_StringIO = PyDict_GetItemString(PyModule_GetDict(mod_StringIO), "StringIO"); if (_type_StringIO) { // stdout ‚Æ stdin ‚Í INCREF ‚µ‚Ä‚¨‚©‚È‚¢‚ƁAæ‚ÁŽæ‚Á‚½Žž‚ɃNƒ‰ƒbƒVƒ…‚µ‚½‚è‚·‚éB _sys_dict = PyModule_GetDict(mod_sys); _sys_stdout = PyDict_GetItemString(_sys_dict, "stdout"); if (_sys_stdout) Py_INCREF(_sys_stdout); _sys_stderr = PyDict_GetItemString(_sys_dict, "stderr"); if (_sys_stderr) Py_INCREF(_sys_stderr); } } } } else { // ŠÂ‹«\’z‚ÉŽ¸”sB Py_CLEAR(_base_globals); Py_CLEAR(_input); Py_CLEAR(_output); } } } // ƒ[ƒJƒ‹ŠÂ‹«‚Ì•¡»‚ƁAƒ\[ƒXƒR[ƒh‚̃Rƒ“ƒpƒCƒ‹B if (_base_globals) { _globals = PyDict_Copy(_base_globals); if (_globals) { _codeobj = reinterpret_cast<PyCodeObject*>(Py_CompileString(code.asChar(), "exprespy_code", Py_file_input)); if(PyErr_Occurred()){ //MGlobal::displayInfo("Compile: error!"); Py_CLEAR(_codeobj); _printPythonError(); } } _count = 0; } // Python ‚̏ˆ—I—¹iGIL‰ð•újB PyGILState_Release(gil); // ƒRƒ“ƒpƒCƒ‹‚̐¬”Û‚ðƒZƒbƒgB //MGlobal::displayInfo(_codeobj ? "successfull" : "failed"); block.outputValue(aCompiled).set(_codeobj ? true : false); return MS::kSuccess; } //------------------------------------------------------------------------------ /// Execute a code. //------------------------------------------------------------------------------ MStatus Exprespy::_executeCode(MDataBlock& block) { block.inputValue(aCompiled); MArrayDataHandle hArrOutput = block.outputArrayValue(aOutput); if (_codeobj) { //MGlobal::displayInfo("EXECUTE"); // GILŽæ“¾‘O‚ɏ㗬•]‰¿‚ðI‚¦‚éB const bool inputsAsApi1Object = block.inputValue(aInputsAsApi1Object).asBool(); MArrayDataHandle hArrInput = block.inputArrayValue(aInput); // ‚±‚Ì’iŠK‚ŏ㗬‚ª•]‰¿‚³‚êI‚í‚Á‚Ä‚¢‚éB // Python ‚̏ˆ—ŠJŽniGILŽæ“¾jB PyGILState_STATE gil = PyGILState_Ensure(); // .input[i] ‚©‚ç’l‚ð“¾‚Ä IN[i] ‚ɃZƒbƒg‚·‚éB if (hArrInput.elementCount()) { do { const unsigned idx = hArrInput.elementIndex(); MDataHandle hInput = hArrInput.inputValue(); if (hInput.type() == MFnData::kNumeric) { // generic ‚ł́AŽc”O‚È‚ª‚琔’lŒ^‚̏ڍׂ͔»•ʂł«‚È‚¢B _setInputScalar(idx, hInput.asGenericDouble()); } else { MObject data = hInput.data(); switch (data.apiType()) { case MFn::kMatrixData: // matrix --> MMatrix (API2) _setInputMatrix(idx, data); break; case MFn::kStringData: // string --> unicode _setInputString(idx, hInput.asString()); break; case MFn::kData2Short: // short2 --> list _setInputShort2(idx, data); break; case MFn::kData3Short: // short3 --> list _setInputShort3(idx, data); break; case MFn::kData2Long: // long2 --> list _setInputLong2(idx, data); break; case MFn::kData3Long: // long3 --> list _setInputLong3(idx, data); break; case MFn::kData2Float: // float2 --> list _setInputFloat2(idx, data); break; case MFn::kData3Float: // float3 --> list _setInputFloat3(idx, data); break; case MFn::kData2Double: // double2 --> list _setInputDouble2(idx, data); break; case MFn::kData3Double: // double3 --> MVector (API2) _setInputVector3(idx, data); break; case MFn::kData4Double: // double3 --> list _setInputDouble4(idx, data); break; default: // other data --> MObject (API2 or 1) //MGlobal::displayInfo(data.apiTypeStr()); if (! data.hasFn(MFn::kData)) { // Ú‘±‚Ì undo Žž‚È‚Ç‚É kInvalid ‚ª—ˆ‚éBisNull() ‚Å‚à”»’èo—ˆ‚½‚ªAˆê‰ž data ‚¾‚¯’Ê‚·‚悤‚É‚·‚éB _setDictValue(_input, idx, Py_None); } else if (inputsAsApi1Object) { _setInputMObject1(idx); } else { _setInputMObject2(idx); } } } } while (hArrInput.next()); } // ƒJƒEƒ“ƒ^[‚ðƒZƒbƒgB _setDictStealValue(_globals, "COUNT", PYINT_fromLong(_count)); ++_count; // sys.stdout ‚ð StringIO ‚Å’D‚¤B // ‰½ŒÌ‚© print ‚̏o—͍s‚ª‹t“]‚·‚邱‚Æ‚ª‚ ‚é‚̂ŁAƒoƒbƒtƒ@‚É—­‚߂Ĉê‰ñ‚Å write ‚·‚邿‚¤‚É‚·‚éB // python ‚Ì print ‚à MGloba::displayInfo ‚à Maya ‚ɐ§Œä‚ª•Ô‚³‚ê‚È‚¢ŒÀ‚è flush ‚³‚ê‚È‚¢‚̂ŁA‚»‚Ì“_‚͕ςí‚ç‚È‚¢B // ‚È‚¨A‚±‚Ì‹t“]Œ»Û‚Í‹N‚«‚½‚è‹N‚«‚È‚©‚Á‚½‚肵AðŒ‚͂悭•ª‚©‚ç‚È‚¢BMaya 2017 win64 ‚Å‚¢‚­‚ç‚©ŽŽ‚·‚ÆŠÈ’P‚ɍČ»o—ˆ‚½B PyObject* stream = NULL; if (_sys_stdout && _type_StringIO) { stream = PyObject_CallObject(_type_StringIO, NULL); if (stream) { PyDict_SetItemString(_sys_dict, "stdout", stream); } } // ƒRƒ“ƒpƒCƒ‹Ï‚݃R[ƒhƒIƒuƒWƒFƒNƒg‚ðŽÀsB #if PY_MAJOR_VERSION < 3 PyEval_EvalCode(_codeobj, _globals, NULL); #else PyEval_EvalCode(reinterpret_cast<PyObject*>(_codeobj), _globals, NULL); #endif if(PyErr_Occurred()){ //MGlobal::displayInfo("PyEval_EvalCode: error!"); _printPythonError(); } // NOTE: py3 ‚ł̓Gƒ‰[ƒCƒ“ƒWƒP[ƒ^‚ðƒNƒŠƒA‚·‚é‘O‚É open Ï‚Ý StringIO ‚ðŽg—p‚·‚邯ƒNƒ‰ƒbƒVƒ…‚·‚é‚̂ŒˆÓ!! // StringIO ‚Ì’†g‚ð–{“–‚Ì sys.stdout ‚ɏ‘‚«o‚µAsys.stdout ‚ðŒ³‚É–ß‚·B // MGlobal::displayInfo ‚ð—p‚¢‚È‚¢‚̂́AƒRƒƒ“ƒg‰»‚ð‚³‚¹‚¸‚Ƀ_ƒCƒŒƒNƒg‚É print ‚³‚¹‚邽‚߁B if (stream) { PyObject* str = PyObject_CallMethod(stream, "getvalue", NULL); if (str) { #if PY_MAJOR_VERSION < 3 if ((PyUnicode_Check(str) && PyUnicode_GET_SIZE(str)) || PYBYTES_SIZE(str)) #else if (PyUnicode_GET_SIZE(str)) #endif PyObject_CallMethod(_sys_stdout, "write", "(O)", str); Py_DECREF(str); } PyDict_SetItemString(_sys_dict, "stdout", _sys_stdout); PyObject_CallMethod(stream, "close", NULL); Py_DECREF(stream); } // .output[i] ‚É OUT[i] ‚Ì’l‚ðƒZƒbƒg‚·‚éB‘¶Ý‚µ‚È‚¢‚à‚̂∵‚¦‚È‚¢‚à‚̏ꍇ‚Í–³Ž‹‚·‚éB if (hArrOutput.elementCount()) { MMatrix mat; do { const unsigned idx = hArrOutput.elementIndex(); PyObject* valo = _getDictValue(_output, idx); // •ÛŽ‚µ‚È‚¢‚̂ŠINCREF ‚µ‚È‚¢B if (! valo) continue; // float --> double if (PyFloat_Check(valo)) { hArrOutput.outputValue().setGenericDouble(PyFloat_AS_DOUBLE(valo), true); #if PY_MAJOR_VERSION < 3 // int --> int } else if (PyInt_Check(valo)) { hArrOutput.outputValue().setGenericInt(PyInt_AS_LONG(valo), true); #endif // long int --> int } else if (PyLong_Check(valo)) { hArrOutput.outputValue().setGenericInt(PyLong_AsLong(valo), true); // TODO: OverflowError ‘΍ôB // bool --> bool } else if (PyBool_Check(valo)) { hArrOutput.outputValue().setGenericBool(valo == Py_True, true); // str(bytes) --> string } else if (PYBYTES_check(valo)) { hArrOutput.outputValue().set(MString(PYBYTES_asChar(valo))); // unicode(str) --> string } else if (PyUnicode_Check(valo)) { // ‚±‚ꂾ‚Æ py3 ‚¾‚ÆŒ‹‰Ê‚ª‚¨‚©‚µ‚­Apy2 ‚Å‚àƒR[ƒh‚̃Gƒ“ƒR[ƒhƒ^ƒCƒv‚Ɉˑ¶‚·‚邱‚ƂɂȂéB // ƒAƒgƒŠƒrƒ…[ƒg‚́AOS‚ÆŒ¾Œê‚²‚Ƃɒè‚ß‚ç‚ꂽMayaƒV[ƒ“‚̃Gƒ“ƒR[ƒhƒ^ƒCƒv‚ª³‚µ‚¢B // Linux or Mac: utf-8, Windows“ú–{Œê=cp932(SJIS), WindowsŠÈ‘Ì’†‘Œê=cp936(GBK) //PyObject* es = PyUnicode_AsEncodedString(valo, Py_FileSystemDefaultEncoding, NULL); //if (es) { // hArrOutput.outputValue().set(MString(PYBYTES_asChar(es))); // Py_DECREF(es); //} // wchar_t ‚Ì‚Ü‚Ü MString ‰»‚·‚邪 3.2 –¢–ž‚¾‚Æ API ‚ªŒÃ‚¢‚̂Ő؂蕪‚¯‚éB #if PY_MAJOR_VERSION < 3 || (PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION < 2) wchar_t* ws = 0; Py_ssize_t siz = PyUnicode_GET_SIZE(valo); if (siz) { ++siz; ws = reinterpret_cast<wchar_t*>(PyMem_Malloc(siz * sizeof(wchar_t))); } if (ws) { PyUnicode_AsWideChar(reinterpret_cast<PyUnicodeObject*>(valo), ws, siz); #else wchar_t* ws = PyUnicode_AsWideCharString(valo, NULL); if (ws) { #endif hArrOutput.outputValue().set(MString(ws)); PyMem_Free(ws); } else hArrOutput.outputValue().set(MString()); // MMatrix (API2) --> matrix } else if (_type2_MMatrix && PyObject_IsInstance(valo, _type2_MMatrix)) { _getMatrixValueFromPyObject(mat, valo); hArrOutput.outputValue().set(MFnMatrixData().create(mat)); // MVector, MPoint, MEulerRotation (API2) --> double3 } else if ((_type2_MVector && PyObject_IsInstance(valo, _type2_MVector)) || (_type2_MPoint && PyObject_IsInstance(valo, _type2_MPoint)) || (_type2_MEulerRotation && PyObject_IsInstance(valo, _type2_MEulerRotation))) { hArrOutput.outputValue().set(_getDouble3Value(valo)); // MQuaternion (API2) --> double4 } else if (_type2_MQuaternion && PyObject_IsInstance(valo, _type2_MQuaternion)) { hArrOutput.outputValue().set(_getDouble4Value(valo)); // MFloatVector, MFloatPoint, MColor (API2) --> float3 } else if ((_type2_MFloatVector && PyObject_IsInstance(valo, _type2_MFloatVector)) || (_type2_MFloatPoint && PyObject_IsInstance(valo, _type2_MFloatPoint)) || (_type2_MColor && PyObject_IsInstance(valo, _type2_MColor))) { hArrOutput.outputValue().set(_getFloat3Value(valo)); // sequence --> double2, double3, double4, long2, long3, or null } else if (PySequence_Check(valo)) { hArrOutput.outputValue().set(_getTypedSequence(valo)); // MObject (API2 or 1) --> data } else if (_type2_MObject && PyObject_IsInstance(valo, _type2_MObject)) { _setOutputMObject2(idx, valo); } else if (_type1_MObject && PyObject_IsInstance(valo, _type1_MObject)) { _setOutputMObject1(idx, valo); } } while (hArrOutput.next()); } // ŽŸ‰ñ‚Ì‚½‚ß‚É IN ‚Æ OUT ‚ðƒNƒŠƒA‚µ‚Ä‚¨‚­B PyDict_Clear(_input); PyDict_Clear(_output); // Python ‚̏ˆ—I—¹iGIL‰ð•újB PyGILState_Release(gil); } return hArrOutput.setAllClean(); } //------------------------------------------------------------------------------ /// Python ‚̃Gƒ‰[‚ð Maya ‚̃Gƒ‰[ƒƒbƒZ[ƒW‚Æ‚µ‚ďo—Í‚·‚éB /// ƒƒbƒZ[ƒW‚ðÔ‚­‚·‚鋤‚ɁA‰½ŒÌ‚©s‚̏‡˜‚ª‹t“]‚·‚éê‡‚ª‚ ‚é‚Ì‚ð‰ñ”ð‚·‚éB //------------------------------------------------------------------------------ #if PY_MAJOR_VERSION < 3 void Exprespy::_printPythonError() { // “–‘R‚È‚ª‚çAƒRƒ“ƒpƒCƒ‹ƒGƒ‰[‚Å‚Í traceback ƒIƒuƒWƒFƒNƒg‚Í“¾‚ç‚ꂸAƒ‰ƒ“ƒ^ƒCƒ€ƒGƒ‰[‚ł͓¾‚ç‚ê‚éB //PyObject *errtyp, *errval, *tb; //PyErr_Fetch(&errtyp, &errval, &tb); //MGlobal::displayInfo( // MString("errtyp=") + (errtyp ? "1" : "0") // + ", errval=" + (errval ? "1" : "0") // + ", tb=" + (tb ? "1" : "0") //); //PyErr_Restore(errtyp, errval, tb); // sys.stderr ‚ð StringIO ‚Å’D‚¤B PyObject* stream = NULL; if (_sys_stderr && _type_StringIO) { stream = PyObject_CallObject(_type_StringIO, NULL); if (stream) { PyDict_SetItemString(_sys_dict, "stderr", stream); } } // Œ»Ý‚̃Gƒ‰[î•ñ‚ð stderr ‚ɏ‘‚«o‚·B PyErr_Print(); // StringIO ‚Ì’†g‚ð–{“–‚Ì sys.stderr ‚ɏ‘‚«o‚µAsys.stderr ‚ðŒ³‚É–ß‚·B if (stream) { PyObject* str = PyObject_CallMethod(stream, "getvalue", NULL); if (str) { if (PYBYTES_SIZE(str)) { MGlobal::displayError(PYBYTES_asChar(str)); } Py_DECREF(str); } PyDict_SetItemString(_sys_dict, "stderr", _sys_stderr); PyObject_CallMethod(stream, "close", NULL); Py_DECREF(stream); } } //------------------------------------------------------------------------------ #else void Exprespy::_printPythonError() { // py3 ‚ł́Atraceback ƒIƒuƒWƒFƒNƒg‚̓Rƒ“ƒpƒCƒ‹ƒGƒ‰[‚Å‚àƒ‰ƒ“ƒ^ƒCƒ€ƒGƒ‰[‚Å‚à“¾‚ç‚ê‚È‚¢B // StringIO ‚𐶐¬‚µ‚悤‚Æ‚·‚邯 SystemError: <class '_io.StringIO'> returned a result with an error set ‚ƂȂéB // traceback.format_exc() ‚Å‚àƒGƒ‰[ƒeƒLƒXƒg‚𓾂ç‚ê‚È‚¢B // ‚Ç‚¤‚µ‚Ă悢‚©•ª‚©‚ç‚È‚¢‚̂ŠPyErr_Print ‚𒼐ڌĂԂ݂̂ƂµA‚»‚ÌŒã‚Ì displayError ‚ŐԂ­‚·‚éB PyErr_Print(); MGlobal::displayError("An error has occured."); #if 0 #if 0 PyObject *errtyp, *errval, *tb; PyErr_Fetch(&errtyp, &errval, &tb); MGlobal::displayInfo( MString("errtyp=") + (errtyp ? "1" : "0") + ", errval=" + (errval ? "1" : "0") + ", tb=" + (tb ? "1" : "0") ); if (! tb) { PyErr_Restore(errtyp, errval, tb); PyErr_Print(); return; } #endif MGlobal::displayInfo("import traceback"); PyObject* mod_traceback = PyImport_ImportModule("traceback"); if (mod_traceback) { #if 0 MGlobal::displayInfo("get format_tb"); PyObject* format_tb = PyDict_GetItemString(PyModule_GetDict(mod_traceback), "format_tb"); // borrow MGlobal::displayInfo(MString("format_tb=") + (format_tb ? "1" : "0")); PyObject* str = PyObject_CallFunction(format_tb, "(O)", tb); #else MGlobal::displayInfo("get format_exc"); PyObject* format_exc = PyDict_GetItemString(PyModule_GetDict(mod_traceback), "format_exc"); // borrow MGlobal::displayInfo(MString("format_exc=") + (format_exc ? "1" : "0")); PyObject* str = PyObject_CallObject(format_exc, NULL); #endif MGlobal::displayInfo(MString("str=") + (str ? "1" : "0")); if (str) { MGlobal::displayInfo("asUTF8"); PyObject* bs = PyUnicode_AsUTF8String(str); MString mstr; mstr.setUTF8(PYBYTES_asChar(bs)); MGlobal::displayError(mstr); Py_DECREF(bs); Py_DECREF(str); } Py_DECREF(mod_traceback); } //Py_DECREF(errtyp); //Py_DECREF(errval); //Py_DECREF(tb); #endif } #endif //------------------------------------------------------------------------------ /// _input dict ‚ɃXƒJƒ‰[”’l‚ðƒZƒbƒg‚·‚éB //------------------------------------------------------------------------------ void Exprespy::_setInputScalar(int key, const double& val) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { // “ü—Í‚©‚çŒ^”»•ʏo—ˆ‚È‚¢‚½‚߁A‚¹‚߂Đ®”‚ÆŽÀ”‚ð”»•Ê‚·‚éB int i = static_cast<int>(val); if (static_cast<double>(i) == val) { _setIODictStealValue(_input, keyo, PYINT_fromLong(i)); } else { _setIODictStealValue(_input, keyo, PyFloat_FromDouble(val)); } } } //------------------------------------------------------------------------------ /// _input dict ‚É•¶Žš—ñ‚ðƒZƒbƒg‚·‚éB //------------------------------------------------------------------------------ void Exprespy::_setInputString(int key, const MString& str) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { _setIODictStealValue(_input, keyo, PyUnicode_FromString(str.asUTF8())); } } //------------------------------------------------------------------------------ /// _input dict ‚É—v‘f‚ª 2`4 ŒÂ‚Ì’l‚ð list ‚É‚µ‚ăZƒbƒg‚·‚éB //------------------------------------------------------------------------------ void Exprespy::_setInputShort2(int key, MObject& data) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { short x, y; MFnNumericData(data).getData(x, y); _setIODictStealValue(_input, keyo, Py_BuildValue("[hh]", x, y)); } } void Exprespy::_setInputShort3(int key, MObject& data) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { short x, y, z; MFnNumericData(data).getData(x, y, z); _setIODictStealValue(_input, keyo, Py_BuildValue("[hhh]", x, y, z)); } } void Exprespy::_setInputLong2(int key, MObject& data) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { int x, y; MFnNumericData(data).getData(x, y); _setIODictStealValue(_input, keyo, Py_BuildValue("[ii]", x, y)); } } void Exprespy::_setInputLong3(int key, MObject& data) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { int x, y, z; MFnNumericData(data).getData(x, y, z); _setIODictStealValue(_input, keyo, Py_BuildValue("[iii]", x, y, z)); } } void Exprespy::_setInputFloat2(int key, MObject& data) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { float x, y; MFnNumericData(data).getData(x, y); _setIODictStealValue(_input, keyo, Py_BuildValue("[ff]", x, y)); } } void Exprespy::_setInputFloat3(int key, MObject& data) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { float x, y, z; MFnNumericData(data).getData(x, y, z); _setIODictStealValue(_input, keyo, Py_BuildValue("[fff]", x, y, z)); } } void Exprespy::_setInputDouble2(int key, MObject& data) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { double x, y; MFnNumericData(data).getData(x, y); _setIODictStealValue(_input, keyo, Py_BuildValue("[dd]", x, y)); } } void Exprespy::_setInputDouble3(int key, MObject& data) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { double x, y, z; MFnNumericData(data).getData(x, y, z); _setIODictStealValue(_input, keyo, Py_BuildValue("[ddd]", x, y, z)); } } void Exprespy::_setInputDouble4(int key, MObject& data) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { double x, y, z, w; MFnNumericData(data).getData(x, y, z, w); _setIODictStealValue(_input, keyo, Py_BuildValue("[dddd]", x, y, z, w)); } } //------------------------------------------------------------------------------ /// _input dict ‚É double3 ‚ð MVector ‚© list ‚É‚µ‚ăZƒbƒg‚·‚éB //------------------------------------------------------------------------------ void Exprespy::_setInputVector3(int key, MObject& data) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { double x, y, z; MFnNumericData(data).getData(x, y, z); if (_type2_MVector) { _setIODictStealValue(_input, keyo, PyObject_CallFunction(_type2_MVector, "(ddd)", x, y, z)); } else { _setIODictStealValue(_input, keyo, Py_BuildValue("[ddd]", x, y, z)); } } } //------------------------------------------------------------------------------ /// _input dict ‚É matrix ‚ð MMatrix ‚© list ‚É‚µ‚ăZƒbƒg‚·‚éB //------------------------------------------------------------------------------ void Exprespy::_setInputMatrix(int key, MObject& data) { PyObject* keyo = PYINT_fromLong(key); if (keyo) { MMatrix m = MFnMatrixData(data).matrix(); if (_type2_MMatrix) { _setIODictStealValue(_input, keyo, PyObject_CallFunction(_type2_MMatrix, "(N)", Py_BuildValue( "(dddddddddddddddd)", m.matrix[0][0], m.matrix[0][1], m.matrix[0][2], m.matrix[0][3], m.matrix[1][0], m.matrix[1][1], m.matrix[1][2], m.matrix[1][3], m.matrix[2][0], m.matrix[2][1], m.matrix[2][2], m.matrix[2][3], m.matrix[3][0], m.matrix[3][1], m.matrix[3][2], m.matrix[3][3] ))); } else { _setIODictStealValue(_input, keyo, Py_BuildValue( "[dddddddddddddddd]", m.matrix[0][0], m.matrix[0][1], m.matrix[0][2], m.matrix[0][3], m.matrix[1][0], m.matrix[1][1], m.matrix[1][2], m.matrix[1][3], m.matrix[2][0], m.matrix[2][1], m.matrix[2][2], m.matrix[2][3], m.matrix[3][0], m.matrix[3][1], m.matrix[3][2], m.matrix[3][3] )); } } } //------------------------------------------------------------------------------ /// _input dict ‚É Python API 2 MObject ƒf[ƒ^‚ðƒZƒbƒg‚·‚éB /// MObjet ‚ð C++ ‚©‚ç Python ‚ɕϊ·‚·‚éŽè’i‚ª–³‚¢‚̂ŁA•s–{ˆÓ‚È‚ª‚ç MPlug ‚ð—˜—pB //------------------------------------------------------------------------------ void Exprespy::_setInputMObject2(int key) { _preparePyPlug2(); if (! _mplug2_input) return; PyObject* keyo = PYINT_fromLong(key); if (! keyo) return; PyObject* mplug = PyObject_CallMethod(_mplug2_input, "elementByLogicalIndex", "(O)", keyo); if (mplug) { _setIODictStealValue(_input, keyo, PyObject_CallMethod(mplug, "asMObject", NULL)); Py_DECREF(mplug); } else { Py_DECREF(keyo); } } //------------------------------------------------------------------------------ /// _output dict ‚©‚瓾‚½ Python API 2 MObject ƒf[ƒ^‚ðo—̓vƒ‰ƒO‚ɃZƒbƒg‚·‚éB /// MObjet ‚ð Python ‚©‚ç C++ ‚ɕϊ·‚·‚éŽè’i‚ª–³‚¢‚̂ŁA•s–{ˆÓ‚È‚ª‚ç MPlug ‚ð—˜—pB //------------------------------------------------------------------------------ void Exprespy::_setOutputMObject2(int key, PyObject* valo) { _preparePyPlug2(); if (! _mplug2_output) return; PyObject* mplug = PyObject_CallMethod(_mplug2_output, "elementByLogicalIndex", "(i)", key); if (mplug) { PyObject_CallMethod(mplug, "setMObject", "(O)", valo); Py_DECREF(mplug); } } //------------------------------------------------------------------------------ /// MObject ƒf[ƒ^“üo—͂̂½‚ß‚Ì Python API 2 MPlug ‚ðŽæ“¾‚µ‚Ä‚¨‚­B //------------------------------------------------------------------------------ void Exprespy::_preparePyPlug2() { if (_mplug2_input || ! _api2_dict) return; PyObject* pysel = PyObject_CallObject(PyDict_GetItemString(_api2_dict, "MSelectionList"), NULL); if (! pysel) return; MString nodename = MFnDependencyNode(thisMObject()).name(); PyObject_CallMethod(pysel, "add", "(s)", nodename.asChar()); PyObject* pynode = PyObject_CallMethod(pysel, "getDependNode", "(i)", 0); Py_DECREF(pysel); if (! pynode) return; PyObject* pyfn = PyObject_CallFunction(PyDict_GetItemString(_api2_dict, "MFnDependencyNode"), "(O)", pynode); Py_DECREF(pynode); if (! pyfn) return; PyObject* findPlug = PyObject_GetAttrString(pyfn, "findPlug"); // DECREF •s—vB _mplug2_input = PyObject_CallFunction(findPlug, "(sO)", "i", Py_False); _mplug2_output = PyObject_CallFunction(findPlug, "(sO)", "o", Py_False); Py_DECREF(pyfn); } //------------------------------------------------------------------------------ /// _input dict ‚É Python API 1 MObject ƒf[ƒ^‚ðƒZƒbƒg‚·‚éB /// MObjet ‚ð C++ ‚©‚ç Python ‚ɕϊ·‚·‚éŽè’i‚ª–³‚¢‚̂ŁA•s–{ˆÓ‚È‚ª‚ç MPlug ‚ð—˜—pB //------------------------------------------------------------------------------ void Exprespy::_setInputMObject1(int key) { _preparePyPlug1(); if (! _mplug1_input) return; PyObject* keyo = PYINT_fromLong(key); if (! keyo) return; PyObject* mplug = PyObject_CallMethod(_mplug1_input, "elementByLogicalIndex", "(O)", keyo); if (! mplug) { Py_DECREF(keyo); return; } PyObject* valo = PyObject_CallMethod(mplug, "asMObject", NULL); Py_DECREF(mplug); _setIODictStealValue(_input, keyo, valo); } //------------------------------------------------------------------------------ /// _output dict ‚©‚瓾‚½ Python API 1 MObject ƒf[ƒ^‚ðo—̓vƒ‰ƒO‚ɃZƒbƒg‚·‚éB /// MObjet ‚ð Python ‚©‚ç C++ ‚ɕϊ·‚·‚éŽè’i‚ª–³‚¢‚̂ŁA•s–{ˆÓ‚È‚ª‚ç MPlug ‚ð—˜—pB //------------------------------------------------------------------------------ void Exprespy::_setOutputMObject1(int key, PyObject* valo) { _preparePyPlug1(); if (! _mplug1_output) return; PyObject* mplug = PyObject_CallMethod(_mplug1_output, "elementByLogicalIndex", "(i)", key); if (mplug) { PyObject_CallMethod(mplug, "setMObject", "(O)", valo); Py_DECREF(mplug); } } //------------------------------------------------------------------------------ /// MObject ƒf[ƒ^“üo—͂̂½‚ß‚Ì Python API 1 MPlug ‚ðŽæ“¾‚µ‚Ä‚¨‚­B //------------------------------------------------------------------------------ void Exprespy::_preparePyPlug1() { if (_mplug1_input || ! _api1_dict) return; PyObject* pysel = PyObject_CallObject(PyDict_GetItemString(_api1_dict, "MSelectionList"), NULL); if (! pysel) return; MString nodename = MFnDependencyNode(thisMObject()).name(); PyObject_CallMethod(pysel, "add", "(s)", nodename.asChar()); PyObject* pynode = PyObject_CallObject(_type1_MObject, NULL); if (! pynode) return; PyObject_CallMethod(pysel, "getDependNode", "(iO)", 0, pynode); Py_DECREF(pysel); if (PyObject_CallMethod(pynode, "isNull", NULL) != Py_True) { PyObject* pyfn = PyObject_CallFunction(PyDict_GetItemString(_api1_dict, "MFnDependencyNode"), "(O)", pynode); PyObject* findPlug = PyObject_GetAttrString(pyfn, "findPlug"); // DECREF •s—vB if (findPlug) { _mplug1_input = PyObject_CallFunction(findPlug, "(sO)", "i", Py_False); _mplug1_output = PyObject_CallFunction(findPlug, "(sO)", "o", Py_False); if (PyObject_CallMethod(_mplug1_input, "isNull", NULL) == Py_True) Py_CLEAR(_mplug1_input); if (PyObject_CallMethod(_mplug1_output, "isNull", NULL) == Py_True) Py_CLEAR(_mplug1_output); } Py_DECREF(pyfn); } Py_DECREF(pynode); } //============================================================================= // ENTRY POINT FUNCTIONS //============================================================================= MStatus initializePlugin(MObject obj) { static const char* VERSION = "3.0.0.20210411"; static const char* VENDER = "Ryusuke Sasaki"; MFnPlugin plugin(obj, VENDER, VERSION, "Any"); MStatus stat = plugin.registerNode(Exprespy::name, Exprespy::id, Exprespy::creator, Exprespy::initialize); CHECK_MSTATUS_AND_RETURN_IT(stat); return MS::kSuccess; } MStatus uninitializePlugin(MObject obj) { MStatus stat = MFnPlugin(obj).deregisterNode(Exprespy::id); CHECK_MSTATUS_AND_RETURN_IT(stat); return MS::kSuccess; }
ryusas/maya_exprespy
srcs/exprespy.cpp
C++
mit
49,535
import logging logging.basicConfig(level=logging.DEBUG) import nengo import nengo_spinnaker import numpy as np def test_probe_ensemble_voltages(): with nengo.Network("Test Network") as network: # Create an Ensemble with 2 neurons that have known gain and bias. The # result is that we know how the membrane voltage should change over # time even with no external stimulus. ens = nengo.Ensemble(2, 1) ens.bias = [0.5, 1.0] ens.gain = [0.0, 0.0] # Add the voltage probe probe = nengo.Probe(ens.neurons, "voltage") # Compute the rise time to 95% max_t = -ens.neuron_type.tau_rc * np.log(0.05) # Run the simulation for this period of time sim = nengo_spinnaker.Simulator(network) with sim: sim.run(max_t) # Compute the ideal voltage curves c = 1.0 - np.exp(-sim.trange() / ens.neuron_type.tau_rc) ideal = np.dot(ens.bias[:, np.newaxis], c[np.newaxis, :]).T # Assert that the ideal curves match the retrieved curves well assert np.allclose(ideal, sim.data[probe], atol=1e-3) if __name__ == "__main__": test_probe_ensemble_voltages()
project-rig/nengo_spinnaker
regression-tests/test_voltage_probing.py
Python
mit
1,158
using System; namespace Proxy { class RealPhoto : IPhoto { private string fileName; public RealPhoto(string fileName) { this.fileName = fileName; LoadPhoto(fileName); } public void Display() { Console.WriteLine("Displaying " + fileName); } private void LoadPhoto(String fileName) { Console.WriteLine("Loading " + fileName); } } }
IvayloP/TelerikAcademy2016-2017
HQC/04.DesingPatterns/02.StructuralPatterns/Proxy/RealPhoto.cs
C#
mit
477
<div class="workplace"> <div class="row-fluid"> <div class="span12"> <?php $this->load->view('admin/includes/message'); ?> <div class="head clearfix"> <div class="isw-grid"></div> <h1>API Manager</h1> </div> <div class="block-fluid table-sorting clearfix"> <table cellpadding="0" cellspacing="0" width="100%" class="table" id="TableDeferLoading"> <thead> <tr> <th width="5%">ID</th> <th width="13%">Title</th> <th width="24%">Host</th> <th width="12%">Username</th> <th width="8%">Api Type</th> <th width="14%">Updated Date Time</th> <th width="14%">Created Date Time</th> <th width="10%">Options</th> </tr> </thead> </table> </div> <a href="<?php echo site_url('admin/apimanager/add') ?>"><button class="btn" type="button">Add an api</button></a> </div> </div> <div class="dr"><span></span></div> <div class="row-fluid"> <div class="span3"> <div class="head clearfix"> <div class="isw-brush"></div> <h1>Options Icons</h1> </div> <div class="block"> <ul class="the-icons clearfix"> <li><i class="isb-cloud"></i> Services List</li> <li><i class="isb-edit"></i> Edit Record</li> <li><i class="isb-delete"></i> Delete Record</li> </ul> </div> </div> </div> </div> <script type="text/javascript" charset="utf-8"> $(document).ready(function() { $('#TableDeferLoading').dataTable ({ 'bProcessing' : true, 'bServerSide' : true, 'bAutoWidth' : false, 'sPaginationType': 'full_numbers', 'sAjaxSource' : '<?php echo site_url('admin/apimanager/listener'); ?>', 'aoColumnDefs': [ { "bSortable": false, "aTargets": [ 7 ] } ], 'sDom' : 'T<"clear">lfrtip', //datatable export buttons 'oTableTools' : { //datatable export buttons "sSwfPath": "<?php echo $this->config->item('assets_url');?>js/plugins/dataTables/media/swf/copy_csv_xls_pdf.swf", "sRowSelect": "multi" }, 'aoColumns' : [ { 'bSearchable': false, 'bVisible' : true }, null, null, null, null, null, null, null ], 'fnServerData': function(sSource, aoData, fnCallback) { <?php if($this->config->item('csrf_protection') === TRUE){ ?> aoData.push({ name : '<?php echo $this->config->item('csrf_token_name'); ?>', value : $.cookie('<?php echo $this->config->item('csrf_cookie_name'); ?>') }); <?php } ?> $.ajax ({ 'dataType': 'json', 'type' : 'POST', 'url' : sSource, 'data' : aoData, 'success' : fnCallback }); } }); }); </script>
muhammad-shariq/exclusiveunlock
application/views/admin/apimanager/list.php
PHP
mit
3,622
<div class="nav_menu"> <div> <div class="top_menu" style="padding-left: 20px;"> <div class="container"><div class="row"><div class="col-md-12"> <div class="top_info"><span><i class="fa fa-phone-square"></i>+91 9829211106</span><span> <i class="fa fa-envelope-o"></i> <a href="mailto:info@vidhyarthidarpan.com" style="color: #ffffff;"> info@vidhyarthidarpan.com</a></span></div> <div class="right_top_menu"> <button type="button" class="top_m1 navbar-toggle" data-toggle="collapse" data-target=".top_menu2"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> </div> </div></div></div> </div> <div class="logo_panel" style="padding-left: 20px;"> <div class="container"> <div class="row"> <div class="col-md-2 col-xs-4 logo1"> <div class="logo"><a href="http://www.vidhyarthidarpan.com/" title="Go to Vidhyarthi Darpan"><img src="http://www.vidhyarthidarpan.com/images/logo.png" class="img-responsive" alt="logo"></a></div> </div> <div class="col-md-8"> <div class="clearfix"></div> </div> </div> </div> </div> </div> <nav> <div class="nav toggle"> <a id="menu_toggle"><i class="fa fa-bars"></i></a> </div> <ul class="nav navbar-nav navbar-right"> <li class=""> <a href="javascript:;" class="user-profile dropdown-toggle" data-toggle="dropdown" aria-expanded="false"> <img src="<?php /* echo profilepic($_SESSION['manage_session']['profilePhoto']); */ ?>" alt=""><?php echo $_SESSION['manage_session']['iName']; ?> <span class=" fa fa-angle-down"></span> </a> <ul class="dropdown-menu dropdown-usermenu pull-right"> <li><a href="<?php echo base_url('manage/user'); ?>"> Profile</a></li> <li> <a href="javascript:;"> <span class="badge bg-red pull-right">50%</span> <span>Settings</span> </a> </li> <li><a href="javascript:;">Help</a></li> <li><a href="<?php echo base_url('manage_logout'); ?>"><i class="fa fa-sign-out pull-right"></i> Log Out</a></li> </ul> </li> <!-- <li role="presentation" class="dropdown"> <a href="javascript:;" class="dropdown-toggle info-number" data-toggle="dropdown" aria-expanded="false"> <i class="fa fa-envelope-o"></i> <span class="badge bg-green">6</span> </a> <ul id="menu1" class="dropdown-menu list-unstyled msg_list" role="menu"> <li> <a> <span class="image"><img src="<?php echo base_url(); ?>public/images/img.jpg" alt="Profile Image" /></span> <span> <span>John Smith</span> <span class="time">3 mins ago</span> </span> <span class="message"> Film festivals used to be do-or-die moments for movie makers. They were where... </span> </a> </li> <li> <a> <span class="image"><img src="<?php echo base_url(); ?>public/images/img.jpg" alt="Profile Image" /></span> <span> <span>John Smith</span> <span class="time">3 mins ago</span> </span> <span class="message"> Film festivals used to be do-or-die moments for movie makers. They were where... </span> </a> </li> <li> <a> <span class="image"><img src="<?php echo base_url(); ?>public/images/img.jpg" alt="Profile Image" /></span> <span> <span>John Smith</span> <span class="time">3 mins ago</span> </span> <span class="message"> Film festivals used to be do-or-die moments for movie makers. They were where... </span> </a> </li> <li> <a> <span class="image"><img src="<?php echo base_url(); ?>public/images/img.jpg" alt="Profile Image" /></span> <span> <span>John Smith</span> <span class="time">3 mins ago</span> </span> <span class="message"> Film festivals used to be do-or-die moments for movie makers. They were where... </span> </a> </li> <li> <div class="text-center"> <a> <strong>See All Alerts</strong> <i class="fa fa-angle-right"></i> </a> </div> </li> </ul> </li>--> </ul> </nav> </div>
ajaykumarparashar11/VD
application/views/manage/layout/header.php
PHP
mit
6,983
'use strict'; var Lab = require('lab'), Hapi = require('hapi'), Plugin = require('../../../lib/plugins/sugendran'); var describe = Lab.experiment; var it = Lab.test; var expect = Lab.expect; var before = Lab.before; var after = Lab.after; describe('sugendran', function() { var server = new Hapi.Server(); it('Plugin successfully loads', function(done) { server.pack.register(Plugin, function(err) { expect(err).to.not.exist; done(); }); }); it('Plugin registers routes', function(done) { var table = server.table(); expect(table).to.have.length(1); expect(table[0].path).to.equal('/sugendran'); done(); }); it('Plugin route responses', function(done) { var table = server.table(); expect(table).to.have.length(1); expect(table[0].path).to.equal('/sugendran'); var request = { method: 'GET', url: '/sugendran' }; server.inject(request, function(res) { expect(res.statusCode).to.equal(200); expect(res.result).to.equal('don\'t worry, be hapi!'); done(); }); }); });
nvcexploder/hapi-lxjs
test/plugins/sugendran/index.js
JavaScript
mit
1,090
import app from 'flarum/forum/app'; import { extend } from 'flarum/common/extend'; import DiscussionControls from 'flarum/forum/utils/DiscussionControls'; import DiscussionPage from 'flarum/forum/components/DiscussionPage'; import Button from 'flarum/common/components/Button'; export default function addStickyControl() { extend(DiscussionControls, 'moderationControls', function (items, discussion) { if (discussion.canSticky()) { items.add( 'sticky', Button.component( { icon: 'fas fa-thumbtack', onclick: this.stickyAction.bind(discussion), }, app.translator.trans( discussion.isSticky() ? 'flarum-sticky.forum.discussion_controls.unsticky_button' : 'flarum-sticky.forum.discussion_controls.sticky_button' ) ) ); } }); DiscussionControls.stickyAction = function () { this.save({ isSticky: !this.isSticky() }).then(() => { if (app.current.matches(DiscussionPage)) { app.current.get('stream').update(); } m.redraw(); }); }; }
flarum/sticky
js/src/forum/addStickyControl.js
JavaScript
mit
1,121
from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import AdaBoostClassifier from skTMVA import convert_bdt_sklearn_tmva import cPickle import numpy as np from numpy.random import RandomState RNG = RandomState(21) # Construct an example dataset for binary classification n_vars = 2 n_events = 10000 signal = RNG.multivariate_normal( np.ones(n_vars), np.diag(np.ones(n_vars)), n_events) background = RNG.multivariate_normal( np.ones(n_vars) * -1, np.diag(np.ones(n_vars)), n_events) X = np.concatenate([signal, background]) y = np.ones(X.shape[0]) w = RNG.randint(1, 10, n_events * 2) y[signal.shape[0]:] *= -1 permute = RNG.permutation(y.shape[0]) X = X[permute] y = y[permute] # Use all dataset for training X_train, y_train, w_train = X, y, w # Declare BDT - we are going to use AdaBoost Decision Tree dt = DecisionTreeClassifier(max_depth=3, min_samples_leaf=int(0.05*len(X_train))) bdt = AdaBoostClassifier(dt, algorithm='SAMME', n_estimators=800, learning_rate=0.5) # Train BDT bdt.fit(X_train, y_train) # Save BDT to pickle file with open('bdt_sklearn_to_tmva_example.pkl', 'wb') as fid: cPickle.dump(bdt, fid) # Save BDT to TMVA xml file # Note: # - declare input variable names and their type # - variable order is important for TMVA convert_bdt_sklearn_tmva(bdt, [('var1', 'F'), ('var2', 'F')], 'bdt_sklearn_to_tmva_example.xml')
yuraic/koza4ok
examples/bdt_sklearn_to_tmva_AdaBoost.py
Python
mit
1,493
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Network::Mgmt::V2020_08_01 module Models # # Defines values for ProcessorArchitecture # module ProcessorArchitecture Amd64 = "Amd64" X86 = "X86" end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_network/lib/2020-08-01/generated/azure_mgmt_network/models/processor_architecture.rb
Ruby
mit
371
'use strict' import assert from 'assert' import { btoa } from 'Base64' import decode from 'jwt-decode' import token from './data/token' import tokenTimezone from './data/token-timezone' import ls from 'local-storage' import bluebird from 'bluebird' import sinon from 'sinon' const setTokenExp = (timestamp) => { // hacky adjustment of expiration of the token const decoded = decode(token) decoded.exp = timestamp / 1000 const [head, , sig] = token.split('.') return `${head}.${btoa(JSON.stringify(decoded))}.${sig}` } describe('Token Store', () => { const localStorageKey = 'coolKey' let updatedToken beforeEach(() => { // HACK around https://github.com/auth0/jwt-decode/issues/5 global.window = global // HACK around cookie monster returning undefined when document isn't there global.document = {} }) beforeEach(() => { updatedToken = setTokenExp(Date.now() + 1000) }) afterEach(() => { delete global.window delete global.document ls.remove(localStorageKey) }) it('should set user after no token is present', () => { const tokenStore = require('../src')() tokenStore.on('Token received', (_, user) => { assert.equal(user.first_name, 'Mike') assert.equal(user.last_name, 'Atkins') }) tokenStore.init() tokenStore.setToken(token) }) it('should get the token out of local storage', () => { ls.set(localStorageKey, token) const tokenStore = require('../src')({localStorageKey}) tokenStore.on('Token received', (_, user) => { assert.equal(user.first_name, 'Mike') assert.equal(user.last_name, 'Atkins') }) tokenStore.init() }) it('should catch an exception token is not present in local storage', () => { ls.set(localStorageKey, undefined) const tokenStore = require('../src')({localStorageKey}) tokenStore.on('Token received', assert.fail) tokenStore.init() }) it('if no token call refresh & set token', done => { const tokenStore = require('../src')({refresh: () => bluebird.resolve(updatedToken) }) tokenStore.on('Token received', (_, user) => { assert.equal(user.first_name, 'Mike') assert.equal(user.last_name, 'Atkins') done() }) tokenStore.init() }) it('if token is expired, call refresh with expired token', done => { ls.set(localStorageKey, token) require('../src')({ localStorageKey, refresh: (t) => { assert.equal(t, token) done() return bluebird.resolve(updatedToken) } }).init() }) it('if token is expired, call refresh & set token', done => { ls.set(localStorageKey, token) const tokenStore = require('../src')({ localStorageKey, refresh: () => bluebird.resolve(updatedToken) }) let callCount = 0 tokenStore.on('Token received', (_, user) => { assert.equal(user.first_name, 'Mike') assert.equal(user.last_name, 'Atkins') if (++callCount === 2) { done() } }) tokenStore.init() }) it('if token valid, leave as is', () => { ls.set(localStorageKey, setTokenExp(Date.now() + 100 * 60 * 1000)) const tokenStore = require('../src')({ localStorageKey, refresh: () => assert.fail('should not be called') }) tokenStore.on('Token received', (_, user) => { assert.equal(user.first_name, 'Mike') assert.equal(user.last_name, 'Atkins') }) tokenStore.init() }) it('if token to expire soon, refresh after interval', done => { ls.set(localStorageKey, updatedToken) const tokenStore = require('../src')({ localStorageKey, refresh: () => bluebird.resolve(updatedToken), refreshInterval: 1000 }) let callCount = 0 tokenStore.on('Token received', (_, user) => { assert.equal(user.first_name, 'Mike') assert.equal(user.last_name, 'Atkins') if (++callCount === 2) { done() } }) tokenStore.init() }) describe('with fake timers', () => { let clock beforeEach(() => { clock = sinon.useFakeTimers() }) afterEach(() => { clock.restore() }) it('doesn\'t refresh if still outside the expiry window', () => { ls.set(localStorageKey, updatedToken) const tokenStore = require('../src')({ localStorageKey, refresh: () => bluebird.resolve(updatedToken), expiryWindow: 1, refreshInterval: 10 }) const spy = sinon.spy() tokenStore.on('Token received', spy) tokenStore.init() clock.tick(11) assert.equal(spy.callCount, 1) }) }) it('refreshes the token and sets it', done => { ls.set(localStorageKey, setTokenExp(Date.now() + 100 * 60 * 1000)) const tokenStore = require('../src')({ localStorageKey, refresh: () => bluebird.resolve(tokenTimezone) }) let callCount = 0 tokenStore.on('Token received', (_, user) => { callCount++ if (callCount === 1) { assert(!user.timezone) } else if (callCount === 2) { assert.equal(user.timezone, 'UTC') done() } else { assert.fail('shouldn\'t be called more than twice') } }) tokenStore.init() tokenStore.refreshToken() }) describe('sad path', () => { it('should not blow up when cookie is not present', () => { let tokenStore assert.doesNotThrow(() => tokenStore = require('../src')()) assert.doesNotThrow(() => tokenStore.init()) }) it('should not blow up when cookie is invalid', () => { const token = 'g4rBaG3' require('cookie-monster').set('XSRF-TOKEN', token) let tokenStore assert.doesNotThrow(() => tokenStore = require('../src')()) assert.doesNotThrow(() => tokenStore.init()) }) }) describe('default cookie key', () => { let tokenFromStore let user beforeEach(() => { require('cookie-monster').set('XSRF-TOKEN', token) const tokenStore = require('../src')() tokenStore.on('Token received', (t, u) => { tokenFromStore = t user = u }) tokenStore.init() }) it('should get the XSRF-TOKEN and return it', () => { assert.equal(tokenFromStore, token) }) it('should return user', () => { assert.equal(user.first_name, 'Mike') assert.equal(user.last_name, 'Atkins') }) }) describe('override cookie key', () => { let tokenFromStore beforeEach(() => { require('cookie-monster').set('NOT-XSRF-TOKEN', token) const tokenStore = require('../src')({ cookie: 'NOT-XSRF-TOKEN' }) tokenStore.on('Token received', (t) => { tokenFromStore = t }) tokenStore.init() }) it('should get the NOT-XSRF-TOKEN and return it', () => { assert.equal(tokenFromStore, token) }) }) describe('terminate', () => { let cookieMonster beforeEach(() => { cookieMonster = require('cookie-monster') cookieMonster.set('XSRF-TOKEN', token) }) it('should set token to undefined on explicit termination', done => { let callCount = 0 const tokenStore = require('../src')({ refresh: (t) => { if (callCount === 0) { cookieMonster.set('XSRF-TOKEN', token, {expires: 'Thu, 01 Jan 1970 00:00:01 GMT'}) assert.equal(t, token) } if (callCount === 1) { assert.equal(t, undefined) } callCount++ return bluebird.resolve(t) } }) tokenStore.init() tokenStore.terminate() tokenStore.refreshToken() done() }) it('should not set token to undefined when no explicit termination', done => { let callCount = 0 const tokenStore = require('../src')({ refresh: (t) => { if (!t) { return bluebird.resolve() } if (callCount === 0) { cookieMonster.set('XSRF-TOKEN', token, {expires: 'Thu, 01 Jan 1970 00:00:01 GMT'}) assert.equal(t, token) } if (callCount === 1) { assert.equal(t, token) } callCount++ return bluebird.resolve(t) } }) tokenStore.init() tokenStore.refreshToken() done() }) }) })
lanetix/react-jwt-store
test/index.js
JavaScript
mit
8,273
<?php /** * This file is part of the fangface/yii2-concord package * * For the full copyright and license information, please view * the file LICENSE.md that was distributed with this source code. * * @package fangface/yii2-concord * @author Fangface <dev@fangface.net> * @copyright Copyright (c) 2014 Fangface <dev@fangface.net> * @license https://github.com/fangface/yii2-concord/blob/master/LICENSE.md MIT License * */ namespace fangface\models\eav; use fangface\db\ActiveRecord; /** * Default Active Record class for the attributeEntities table * * @method AttributeEntities findOne($condition = null) static * @method AttributeEntities[] findAll($condition = null) static * @method AttributeEntities[] findByCondition($condition, $one) static */ class AttributeEntities extends ActiveRecord { protected $disableAutoBehaviors = true; }
fangface/yii2-concord
src/models/eav/AttributeEntities.php
PHP
mit
865
<?php namespace Acme\PaymentBundle\Controller; use Payum\Bundle\PayumBundle\Controller\PayumController; use Payum\Core\Exception\RequestNotSupportedException; use Payum\Core\Request\BinaryMaskStatusRequest; use Payum\Core\Request\SyncRequest; use Symfony\Component\HttpFoundation\Request; class DetailsController extends PayumController { public function viewAction(Request $request) { $token = $this->getHttpRequestVerifier()->verify($request); $payment = $this->getPayum()->getPayment($token->getPaymentName()); try { $payment->execute(new SyncRequest($token)); } catch (RequestNotSupportedException $e) {} $status = new BinaryMaskStatusRequest($token); $payment->execute($status); return $this->render('AcmePaymentBundle:Details:view.html.twig', array( 'status' => $status, 'paymentTitle' => ucwords(str_replace(array('_', '-'), ' ', $token->getPaymentName())) )); } }
a2xchip/SagepayBundleSandbox
src/Acme/PaymentBundle/Controller/DetailsController.php
PHP
mit
1,005
import sys script, encoding, error = sys.argv def main(language_file, encoding, errors): line = language_file.readline() if line: print_line(line, encoding, errors) return main(language_file, encoding, errors) def print_line(line, encoding, errors): next_lang = line.strip() raw_bytes = next_lang.encode(encoding, errors=errors) cooked_string = raw_bytes.decode(encoding, errors=errors) print(raw_bytes, "<===>", cooked_string) languages = open("languages.txt", encoding="utf-8") main(languages, encoding, error)
Herne/pythonplayground
lp3thw/ex23.py
Python
mit
563
using System; using Microsoft.AspNetCore.Mvc; using Smidge.CompositeFiles; using Smidge.Models; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Logging; using Smidge.FileProcessors; using Smidge.Cache; using Microsoft.AspNetCore.Authorization; namespace Smidge.Controllers { /// <summary> /// Controller for handling minified/combined responses /// </summary> [AddCompressionHeader(Order = 0)] [AddExpiryHeaders(Order = 1)] [CheckNotModified(Order = 2)] [CompositeFileCacheFilter(Order = 3)] [AllowAnonymous] public class SmidgeController : Controller { private readonly ISmidgeFileSystem _fileSystem; private readonly IBundleManager _bundleManager; private readonly IBundleFileSetGenerator _fileSetGenerator; private readonly PreProcessPipelineFactory _processorFactory; private readonly IPreProcessManager _preProcessManager; private readonly ILogger _logger; /// <summary> /// Constructor /// </summary> /// <param name="fileSystemHelper"></param> /// <param name="bundleManager"></param> /// <param name="fileSetGenerator"></param> /// <param name="processorFactory"></param> /// <param name="preProcessManager"></param> /// <param name="logger"></param> public SmidgeController( ISmidgeFileSystem fileSystemHelper, IBundleManager bundleManager, IBundleFileSetGenerator fileSetGenerator, PreProcessPipelineFactory processorFactory, IPreProcessManager preProcessManager, ILogger<SmidgeController> logger) { _fileSystem = fileSystemHelper ?? throw new ArgumentNullException(nameof(fileSystemHelper)); _bundleManager = bundleManager ?? throw new ArgumentNullException(nameof(bundleManager)); _fileSetGenerator = fileSetGenerator ?? throw new ArgumentNullException(nameof(fileSetGenerator)); _processorFactory = processorFactory ?? throw new ArgumentNullException(nameof(processorFactory)); _preProcessManager = preProcessManager ?? throw new ArgumentNullException(nameof(preProcessManager)); _logger = logger; } /// <summary> /// Handles requests for named bundles /// </summary> /// <param name="bundleModel">The bundle model</param> /// <returns></returns> public async Task<IActionResult> Bundle( [FromServices] BundleRequestModel bundleModel) { if (!_bundleManager.TryGetValue(bundleModel.FileKey, out Bundle foundBundle)) { return NotFound(); } var bundleOptions = foundBundle.GetBundleOptions(_bundleManager, bundleModel.Debug); var cacheBusterValue = bundleModel.ParsedPath.CacheBusterValue; //now we need to determine if this bundle has already been created var cacheFile = _fileSystem.CacheFileSystem.GetCachedCompositeFile(cacheBusterValue, bundleModel.Compression, bundleModel.FileKey, out var cacheFilePath); if (cacheFile.Exists) { _logger.LogDebug($"Returning bundle '{bundleModel.FileKey}' from cache"); if (!string.IsNullOrWhiteSpace(cacheFile.PhysicalPath)) { //if physical path is available then it's the physical file system, in which case we'll deliver the file with the PhysicalFileResult //FilePathResult uses IHttpSendFileFeature which is a native host option for sending static files return PhysicalFile(cacheFile.PhysicalPath, bundleModel.Mime); } else { return File(cacheFile.CreateReadStream(), bundleModel.Mime); } } //the bundle doesn't exist so we'll go get the files, process them and create the bundle //TODO: We should probably lock here right?! we don't want multiple threads trying to do this at the same time, we'll need a dictionary of locks to do this effectively //get the files for the bundle var files = _fileSetGenerator.GetOrderedFileSet(foundBundle, _processorFactory.CreateDefault( //the file type in the bundle will always be the same foundBundle.Files[0].DependencyType)) .ToArray(); if (files.Length == 0) { return NotFound(); } using (var bundleContext = new BundleContext(cacheBusterValue, bundleModel, cacheFilePath)) { var watch = new Stopwatch(); watch.Start(); _logger.LogDebug($"Processing bundle '{bundleModel.FileKey}', debug? {bundleModel.Debug} ..."); //we need to do the minify on the original files foreach (var file in files) { await _preProcessManager.ProcessAndCacheFileAsync(file, bundleOptions, bundleContext); } //Get each file path to it's hashed location since that is what the pre-processed file will be saved as var fileInfos = files.Select(x => _fileSystem.CacheFileSystem.GetCacheFile( x, () => _fileSystem.GetRequiredFileInfo(x), bundleOptions.FileWatchOptions.Enabled, Path.GetExtension(x.FilePath), cacheBusterValue, out _)); using (var resultStream = await GetCombinedStreamAsync(fileInfos, bundleContext)) { //compress the response (if enabled) var compressedStream = await Compressor.CompressAsync( //do not compress anything if it's not enabled in the bundle options bundleOptions.CompressResult ? bundleModel.Compression : CompressionType.None, resultStream); //save the resulting compressed file, if compression is not enabled it will just save the non compressed format // this persisted file will be used in the CheckNotModifiedAttribute which will short circuit the request and return // the raw file if it exists for further requests to this path await CacheCompositeFileAsync(_fileSystem.CacheFileSystem, cacheFilePath, compressedStream); _logger.LogDebug($"Processed bundle '{bundleModel.FileKey}' in {watch.ElapsedMilliseconds}ms"); //return the stream return File(compressedStream, bundleModel.Mime); } } } /// <summary> /// Handles requests for composite files (non-named bundles) /// </summary> /// <param name="file"></param> /// <returns></returns> public async Task<IActionResult> Composite( [FromServices] CompositeFileModel file) { if (!file.ParsedPath.Names.Any()) { return NotFound(); } var defaultBundleOptions = _bundleManager.GetDefaultBundleOptions(false); var cacheBusterValue = file.ParsedPath.CacheBusterValue; var cacheFile = _fileSystem.CacheFileSystem.GetCachedCompositeFile(cacheBusterValue, file.Compression, file.FileKey, out var cacheFilePath); if (cacheFile.Exists) { //this is already processed, return it if (!string.IsNullOrWhiteSpace(cacheFile.PhysicalPath)) { //if physical path is available then it's the physical file system, in which case we'll deliver the file with the PhysicalFileResult //FilePathResult uses IHttpSendFileFeature which is a native host option for sending static files return PhysicalFile(cacheFile.PhysicalPath, file.Mime); } else { return File(cacheFile.CreateReadStream(), file.Mime); } } using (var bundleContext = new BundleContext(cacheBusterValue, file, cacheFilePath)) { var files = file.ParsedPath.Names.Select(filePath => _fileSystem.CacheFileSystem.GetRequiredFileInfo( $"{file.ParsedPath.CacheBusterValue}/{filePath + file.Extension}")); using (var resultStream = await GetCombinedStreamAsync(files, bundleContext)) { var compressedStream = await Compressor.CompressAsync(file.Compression, resultStream); await CacheCompositeFileAsync(_fileSystem.CacheFileSystem, cacheFilePath, compressedStream); return File(compressedStream, file.Mime); } } } private static async Task CacheCompositeFileAsync(ICacheFileSystem cacheProvider, string filePath, Stream compositeStream) { await cacheProvider.WriteFileAsync(filePath, compositeStream); if (compositeStream.CanSeek) compositeStream.Position = 0; } /// <summary> /// Combines files into a single stream /// </summary> /// <param name="files"></param> /// <param name="bundleContext"></param> /// <returns></returns> private async Task<Stream> GetCombinedStreamAsync(IEnumerable<IFileInfo> files, BundleContext bundleContext) { //TODO: Here we need to be able to prepend/append based on a "BundleContext" (or similar) List<Stream> inputs = null; try { inputs = files.Where(x => x.Exists) .Select(x => x.CreateReadStream()) .ToList(); var delimeter = bundleContext.BundleRequest.Extension == ".js" ? ";\n" : "\n"; var combined = await bundleContext.GetCombinedStreamAsync(inputs, delimeter); return combined; } finally { if (inputs != null) { foreach (var input in inputs) { input.Dispose(); } } } } } }
Shazwazza/Smidge
src/Smidge/Controllers/SmidgeController.cs
C#
mit
10,731
require './spec/spec_helper' describe Economic::CashBookEntry do let(:session) { make_session } subject { Economic::CashBookEntry.new(:session => session) } it "inherits from Economic::Entity" do Economic::CashBookEntry.ancestors.should include(Economic::Entity) end describe ".proxy" do it "should return a CashBookEntryProxy" do subject.proxy.should be_instance_of(Economic::CashBookEntryProxy) end it "should return a proxy owned by session" do subject.proxy.session.should == session end end describe "#save" do it 'should save it' do stub_request('CashBookEntry_CreateFromData', nil, :success) subject.save end end end
kongens-net/rconomic
spec/economic/cash_book_entry_spec.rb
Ruby
mit
698
/** * @file KeyboardButton.cpp * @brief Contains KeyboardButton class implementation * @author Khalin Yevhen * @version 0.0.2 * @date 28.09.17 */ #include "KeyboardButton.h" #include "..\khalin03\Button.cpp" KeyboardButton::KeyboardButton(ButtonForm form, int code, string name) : Button(form), code(code), name(name) { } KeyboardButton::~KeyboardButton() { } int KeyboardButton::getCode() { return code; } string KeyboardButton::getName() { return name; } void KeyboardButton::setData(int & code) { this->code = code; } void KeyboardButton::setData(string name, int & code) { this->code = code; this->name = name; } bool KeyboardButton::operator==(int val) { return val == code; } void KeyboardButton::operator-=(char c) { string newName; char iter = name[0]; int addedCounter = 0; for (auto i = 0; i < name.length(); i++) { iter = name[i]; if (iter != c) { newName += iter; } } name = newName; }
kit25a/se-cpp
khalin-yevhen/src/khalin04/keyboardButton.cpp
C++
mit
992
#include "perspectivecamera.h" #include <stdexcept> #include <gtc/matrix_transform.hpp> using namespace Camera; PerspectiveCamera::PerspectiveCamera(float verticalFieldOfView, float aspectRatio) : verticalFieldOfView(verticalFieldOfView), aspectRatio(aspectRatio) { changeZoomFactor(glm::vec2(1.0f, 1.0f)); changeProjectionMatrix(); } PerspectiveCamera::~PerspectiveCamera() { } void PerspectiveCamera::changeZoomFactor(const glm::vec2& zoom) { if (!validateZoomFactor(zoom)) throw std::invalid_argument("Zoom factors cannot be negative!"); this->zoom = zoom; verticalFieldOfView = 2 * std::atan(1.0f / zoom.y); changeProjectionMatrix(); } void PerspectiveCamera::changeFieldOfView(float verticalFieldOfView) { this->verticalFieldOfView = verticalFieldOfView; changeProjectionMatrix(); } void PerspectiveCamera::changeAspectRatio(int width, int height) { if (width > 0 && height > 0) this->aspectRatio = (float)width / (float)height; else this->aspectRatio = (float)16 / (float)9; changeProjectionMatrix(); } void PerspectiveCamera::changeProjectionMatrix() { projection = glm::perspective(verticalFieldOfView, aspectRatio, zNear, zFar); } void PerspectiveCamera::contextUpdated(QOpenGLWidget* updatedContext) { changeAspectRatio(updatedContext->width(), updatedContext->height()); }
Vaub/uGL
Project/uGL/uGLCore/perspectivecamera.cpp
C++
mit
1,319
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Validator\Constraints; use Symfony\Component\Validator\Constraint; use Symfony\Component\Validator\ConstraintValidator; use Symfony\Component\Validator\Exception\UnexpectedTypeException; use Symfony\Component\Validator\Exception\UnexpectedValueException; /** * Validates whether a value is a valid timezone identifier. * * @author Javier Spagnoletti <phansys@gmail.com> * @author Hugo Hamon <hugohamon@neuf.fr> */ class TimezoneValidator extends ConstraintValidator { /** * {@inheritdoc} */ public function validate($value, Constraint $constraint) { if (!$constraint instanceof Timezone) { throw new UnexpectedTypeException($constraint, Timezone::class); } if (null === $value || '' === $value) { return; } if (!is_scalar($value) && !(\is_object($value) && method_exists($value, '__toString'))) { throw new UnexpectedValueException($value, 'string'); } $value = (string) $value; // @see: https://bugs.php.net/bug.php?id=75928 if ($constraint->countryCode) { $timezoneIds = \DateTimeZone::listIdentifiers($constraint->zone, $constraint->countryCode); } else { $timezoneIds = \DateTimeZone::listIdentifiers($constraint->zone); } if ($timezoneIds && \in_array($value, $timezoneIds, true)) { return; } if ($constraint->countryCode) { $code = Timezone::TIMEZONE_IDENTIFIER_IN_COUNTRY_ERROR; } elseif (\DateTimeZone::ALL !== $constraint->zone) { $code = Timezone::TIMEZONE_IDENTIFIER_IN_ZONE_ERROR; } else { $code = Timezone::TIMEZONE_IDENTIFIER_ERROR; } $this->context->buildViolation($constraint->message) ->setParameter('{{ value }}', $this->formatValue($value)) ->setCode($code) ->addViolation(); } /** * {@inheritdoc} */ public function getDefaultOption() { return 'zone'; } /** * {@inheritdoc} */ protected function formatValue($value, $format = 0) { $value = parent::formatValue($value, $format); if (!$value || \DateTimeZone::PER_COUNTRY === $value) { return $value; } return array_search($value, (new \ReflectionClass(\DateTimeZone::class))->getConstants(), true) ?: $value; } }
curry684/symfony
src/Symfony/Component/Validator/Constraints/TimezoneValidator.php
PHP
mit
2,714
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class FigureQuintupleDot11 : Figure { private const int score = 5; public FigureQuintupleDot11(int player): base(player) { figure[4, 4] = figure[5, 4] = figure[5, 5] = figure[5, 6] = figure[5, 7] = player; } public override void rotate() { currentPossition = ++currentPossition % 8; switch (currentPossition) { case 0: for (short i = 0; i < 8; i++) { for (short j = 0; j < 8; j++) { figure[i, j] = 0; } } figure[4, 4] = figure[5, 4] = figure[5, 5] = figure[5, 6] = figure[5, 7] = owner; break; case 1: figure[5, 4] = figure[5, 5] = figure[5, 6] = figure[5, 7] = 0; figure[4, 3] = figure[5, 3] = figure[6, 3] = figure[7, 3] = owner; break; case 2: figure[4, 3] = figure[5, 3] = figure[6, 3] = figure[7, 3] = 0; figure[3, 1] = figure[3, 2] = figure[3, 3] = figure[3, 4] = owner; break; case 3: figure[3, 1] = figure[3, 2] = figure[3, 3] = figure[3, 4] = 0; figure[1, 5] = figure[2, 5] = figure[3, 5] = figure[4, 5] = owner; break; case 4: for (short i = 0; i < 8; i++) { for (short j = 0; j < 8; j++) { figure[i, j] = 0; } } figure[4, 4] = figure[5, 1] = figure[5, 2] = figure[5, 3] = figure[5, 4] = owner; break; case 5: figure[5, 1] = figure[5, 2] = figure[5, 3] = figure[5, 4] = 0; figure[1, 3] = figure[2, 3] = figure[3, 3] = figure[4, 3] = owner; break; case 6: figure[1, 3] = figure[2, 3] = figure[3, 3] = figure[4, 3] = 0; figure[3, 4] = figure[3, 5] = figure[3, 6] = figure[3, 7] = owner; break; case 7: figure[3, 4] = figure[3, 5] = figure[3, 6] = figure[3, 7] = 0; figure[4, 5] = figure[5, 5] = figure[6, 5] = figure[7, 5] = owner; break; } } }
siderisltd/Telerik-Academy
All TeamProjects/TeamProject C# 1_ Blokus/Blokus/FigureQuintupleDot11.cs
C#
mit
2,564
using System; namespace C5 { [Serializable] internal class MultiplicityOne<K> : MappedCollectionValue<K, System.Collections.Generic.KeyValuePair<K, int>> { public MultiplicityOne(ICollectionValue<K> coll) : base(coll) { } public override System.Collections.Generic.KeyValuePair<K, int> Map(K k) { return new System.Collections.Generic.KeyValuePair<K, int>(k, 1); } } }
sestoft/C5
C5/Enumerators/MultiplicityOne.cs
C#
mit
401
<?php // src/Blogger/BlogBundle/Controller/PageController.php namespace Blogger\BlogBundle\Controller; use Blogger\BlogBundle\Entity\Enquiry; use Blogger\BlogBundle\Form\EnquiryType; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class PageController extends Controller { public function indexAction() { return $this->render('BloggerBlogBundle:Page:index.html.twig'); } public function aboutAction() { return $this->render('BloggerBlogBundle:Page:about.html.twig'); } public function contactAction() { $enquiry = new Enquiry(); $form = $this->createForm(new EnquiryType(), $enquiry); $request = $this->getRequest(); if ($request->getMethod() == 'POST') { $form->bindRequest($request); if ($form->isValid()) { $message = \Swift_Message::newInstance() ->setSubject('Contact enquiry from symblog') ->setFrom('leonardo.chaves.freitas@gmail.com') ->setTo('leochaves@gmail.com') ->setBody($this->renderView('BloggerBlogBundle:Page:contactEmail.txt.twig', array('enquiry' => $enquiry))); $this->get('mailer')->send($message); $this->get('session')->setFlash('blogger-notice', 'Your contact enquiry was successfully sent. Thank you!'); // Redirect - This is important to prevent users re-posting // the form if they refresh the page return $this->redirect($this->generateUrl('BloggerBlogBundle_contact')); } } return $this->render('BloggerBlogBundle:Page:contact.html.twig', array( 'form' => $form->createView() )); } }
leochaves/Blog-Symfony
src/Blogger/BlogBundle/Controller/PageController.php
PHP
mit
1,713
<?php namespace Sustain\AppBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class ActivityType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('title','text', array('attr' => array('class' => 'text form-control', 'placeholder' => 'Title of your activity'),)) ->add('description', 'ckeditor', array('config_name' => 'editor_simple',)) ->add('objectives', 'entity', array('class' => 'AppBundle:Objective','property'=>'objective','query_builder' => function(\Sustain\AppBundle\Entity\ObjectiveRepository $er) use ($options) { return $er->createQueryBuilder('o') ->orderBy('o.objective', 'ASC'); }, 'expanded'=>true,'multiple'=>true, 'label' => 'Select Objectives', 'attr' => array('class' => 'checkbox'), )) ->add('tags', 'entity', array('class' => 'AppBundle:Tag','property'=>'name','query_builder' => function(\Sustain\AppBundle\Entity\TagRepository $er) use ($options) { return $er->createQueryBuilder('t') ->orderBy('t.name', 'ASC'); }, 'expanded'=>true,'multiple'=>true, 'label' => 'Select Labels', 'attr' => array('class' => 'checkbox'), )) ; } /** * @param OptionsResolverInterface $resolver */ public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Sustain\AppBundle\Entity\Activity' )); } /** * @return string */ public function getName() { return 'sustain_appbundle_activity'; } }
rlbaltha/sustain
src/Sustain/AppBundle/Form/ActivityType.php
PHP
mit
1,979
/** * @file SpriteInterface.cpp * @author Duncan Campbell * @version 1.0 * * @section LICENSE * * The MIT License (MIT) * * Copyright (c) 2016 Duncan Campbell * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * @section DESCRIPTION * * */ #include "SpriteInterface.hpp"
dacampbell/PseudoEngine
lib/Luna/src/SpriteInterface.cpp
C++
mit
1,312
module LightMobile::ApplicationHelper include AgentHelpers::DetectorHelper end
kaspernj/light_mobile
app/helpers/light_mobile/application_helper.rb
Ruby
mit
81
# Install NGINX include_recipe 'nginx' # Disable default site nginx_site 'default' do enable false end # Create web directory directory node[:site][:webserver][:root] do recursive true owner node[:site][:user] group node[:site][:group] mode 00755 action :create end # Create site directory directory "#{node[:site][:webserver][:root]}/#{node[:site][:webserver][:sitefolder]}/site" do recursive true owner node[:site][:user] group node[:site][:group] mode 00755 action :create end # Create logs directory "#{node[:site][:webserver][:root]}/#{node[:site][:webserver][:sitefolder]}/logs" do recursive true owner node[:site][:user] group node[:site][:group] mode 0755 action :create end file "#{node[:site][:webserver][:root]}/#{node[:site][:webserver][:sitefolder]}/logs/access.log" do owner node[:site][:user] group node[:site][:group] mode 0755 action :create end file "#{node[:site][:webserver][:root]}/#{node[:site][:webserver][:sitefolder]}/logs/error.log" do owner node[:site][:user] group node[:site][:group] mode 0755 action :create end # Create server definition template "/etc/nginx/sites-available/#{node[:site][:webserver][:sitename]}" do source "server.erb" owner "root" group "root" mode 0755 end nginx_site "#{node[:site][:webserver][:sitename]}" do enable true notifies :reload, 'service[nginx]' end # Create 404 file template "#{node[:site][:webserver][:root]}/#{node[:site][:webserver][:sitefolder]}/site/404.html" do source "404.erb.html" owner node[:site][:user] group node[:site][:group] mode 0755 end # Create 500 file template "#{node[:site][:webserver][:root]}/#{node[:site][:webserver][:sitefolder]}/site/50x.html" do source "50x.erb.html" owner node[:site][:user] group node[:site][:group] mode 0755 end # # Create PHPInfo test file # template "#{node[:site][:webserver][:root]}/#{node[:site][:webserver][:sitefolder]}/site/index.php" do # source "test.php.erb" # owner node[:site][:user] # group node[:site][:group] # mode 0755 # end
mattidupre/chef-nginx
recipes/webserver.rb
Ruby
mit
2,049
{ ("use strict"); var HTMLElement = scope.wrappers.HTMLElement; var mixin = scope.mixin; var registerWrapper = scope.registerWrapper; var unsafeUnwrap = scope.unsafeUnwrap; var unwrap = scope.unwrap; var wrap = scope.wrap; var contentTable = new WeakMap(); var templateContentsOwnerTable = new WeakMap(); function getTemplateContentsOwner(doc) { if (!doc.defaultView) return doc; var d = templateContentsOwnerTable.get(doc); if (!d) { d = doc.implementation.createHTMLDocument(""); while (d.lastChild) { d.removeChild(d.lastChild); } templateContentsOwnerTable.set(doc, d); } return d; } function extractContent(templateElement) { var doc = getTemplateContentsOwner(templateElement.ownerDocument); var df = unwrap(doc.createDocumentFragment()); var child; while ((child = templateElement.firstChild)) { df.appendChild(child); } return df; } var OriginalHTMLTemplateElement = window.HTMLTemplateElement; function HTMLTemplateElement(node) { HTMLElement.call(this, node); if (!OriginalHTMLTemplateElement) { var content = extractContent(node); contentTable.set(this, wrap(content)); } } HTMLTemplateElement.prototype = Object.create(HTMLElement.prototype); mixin(HTMLTemplateElement.prototype, { constructor: HTMLTemplateElement, get content() { if (OriginalHTMLTemplateElement) return wrap(unsafeUnwrap(this).content); return contentTable.get(this); } }); if (OriginalHTMLTemplateElement) registerWrapper(OriginalHTMLTemplateElement, HTMLTemplateElement); scope.wrappers.HTMLTemplateElement = HTMLTemplateElement; }
stas-vilchik/bdd-ml
data/6744.js
JavaScript
mit
1,705
// Copyright (c) The Perspex Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.Linq; using Perspex.Controls; using Perspex.Controls.Presenters; using Perspex.Controls.Primitives; using Perspex.Controls.Templates; using Perspex.VisualTree; using Xunit; namespace Perspex.Controls.UnitTests { public class ScrollViewerTests { [Fact] public void Content_Is_Created() { var target = new ScrollViewer { Template = new FuncControlTemplate<ScrollViewer>(CreateTemplate), Content = "Foo", }; target.ApplyTemplate(); var presenter = target.GetTemplateChild<ScrollContentPresenter>("contentPresenter"); Assert.IsType<TextBlock>(presenter.Child); } [Fact] public void ScrollViewer_In_Template_Sets_Child_TemplatedParent() { var target = new ContentControl { Template = new FuncControlTemplate<ContentControl>(CreateNestedTemplate), Content = "Foo", }; target.ApplyTemplate(); var presenter = target.GetVisualDescendents() .OfType<ContentPresenter>() .Single(x => x.Name == "this"); Assert.Equal(target, presenter.TemplatedParent); } private Control CreateTemplate(ScrollViewer control) { return new Grid { ColumnDefinitions = new ColumnDefinitions { new ColumnDefinition(1, GridUnitType.Star), new ColumnDefinition(GridLength.Auto), }, RowDefinitions = new RowDefinitions { new RowDefinition(1, GridUnitType.Star), new RowDefinition(GridLength.Auto), }, Children = new Controls { new ScrollContentPresenter { Name = "contentPresenter", [~ContentPresenter.ContentProperty] = control[~ContentControl.ContentProperty], [~~ScrollContentPresenter.ExtentProperty] = control[~~ScrollViewer.ExtentProperty], [~~ScrollContentPresenter.OffsetProperty] = control[~~ScrollViewer.OffsetProperty], [~~ScrollContentPresenter.ViewportProperty] = control[~~ScrollViewer.ViewportProperty], [~ScrollContentPresenter.CanScrollHorizontallyProperty] = control[~ScrollViewer.CanScrollHorizontallyProperty], }, new ScrollBar { Name = "horizontalScrollBar", Orientation = Orientation.Horizontal, [~RangeBase.MaximumProperty] = control[~ScrollViewer.HorizontalScrollBarMaximumProperty], [~~RangeBase.ValueProperty] = control[~~ScrollViewer.HorizontalScrollBarValueProperty], [~ScrollBar.ViewportSizeProperty] = control[~ScrollViewer.HorizontalScrollBarViewportSizeProperty], [~ScrollBar.VisibilityProperty] = control[~ScrollViewer.HorizontalScrollBarVisibilityProperty], [Grid.RowProperty] = 1, }, new ScrollBar { Name = "verticalScrollBar", Orientation = Orientation.Vertical, [~RangeBase.MaximumProperty] = control[~ScrollViewer.VerticalScrollBarMaximumProperty], [~~RangeBase.ValueProperty] = control[~~ScrollViewer.VerticalScrollBarValueProperty], [~ScrollBar.ViewportSizeProperty] = control[~ScrollViewer.VerticalScrollBarViewportSizeProperty], [~ScrollBar.VisibilityProperty] = control[~ScrollViewer.VerticalScrollBarVisibilityProperty], [Grid.ColumnProperty] = 1, }, }, }; } private Control CreateNestedTemplate(ContentControl control) { return new ScrollViewer { Template = new FuncControlTemplate<ScrollViewer>(CreateTemplate), Content = new ContentPresenter { Name = "this" } }; } } }
kekekeks/Perspex
tests/Perspex.Controls.UnitTests/ScrollViewerTests.cs
C#
mit
4,573
package golog import . "fmt" import . "github.com/mndrix/golog/term" import . "github.com/mndrix/golog/util" import "bytes" import "github.com/mndrix/ps" // Database is an immutable Prolog database. All write operations on the // database produce a new database without affecting the previous one. // A database is a mapping from predicate indicators (foo/3) to clauses. // The database may or may not implement indexing. It's unusual to // interact with databases directly. One usually calls methods on Machine // instead. type Database interface { // Asserta adds a term to the database at the start of any existing // terms with the same name and arity. Asserta(Term) Database // Assertz adds a term to the database at the end of any existing // terms with the same name and arity. Assertz(Term) Database // Candidates() returns a list of clauses that might unify with a term. // Returns error if no predicate with appropriate // name and arity has been defined. Candidates(Term) ([]Term, error) // Candidates_() is like Candidates() but panics on error. Candidates_(Term) []Term // ClauseCount returns the number of clauses in the database ClauseCount() int // String returns a string representation of the entire database String() string } // NewDatabase returns a new, empty database func NewDatabase() Database { var db mapDb db.clauseCount = 0 db.predicates = ps.NewMap() return &db } type mapDb struct { clauseCount int // number of clauses in the database predicates ps.Map // term indicator => *clauses } func (self *mapDb) Asserta(term Term) Database { return self.assert('a', term) } func (self *mapDb) Assertz(term Term) Database { return self.assert('z', term) } func (self *mapDb) assert(side rune, term Term) Database { var newMapDb mapDb var cs *clauses // find the indicator under which this term is classified indicator := term.Indicator() if IsClause(term) { // ':-' uses the indicator of its head term indicator = Head(term).Indicator() } oldClauses, ok := self.predicates.Lookup(indicator) if ok { // clauses exist for this predicate switch side { case 'a': cs = oldClauses.(*clauses).cons(term) case 'z': cs = oldClauses.(*clauses).snoc(term) } } else { // brand new predicate cs = newClauses().snoc(term) } newMapDb.clauseCount = self.clauseCount + 1 newMapDb.predicates = self.predicates.Set(indicator, cs) return &newMapDb } func (self *mapDb) Candidates_(t Term) []Term { ts, err := self.Candidates(t) if err != nil { panic(err) } return ts } func (self *mapDb) Candidates(t Term) ([]Term, error) { indicator := t.Indicator() cs, ok := self.predicates.Lookup(indicator) if !ok { // this predicate hasn't been defined return nil, Errorf("Undefined predicate: %s", indicator) } // quick return for an atom term if !IsCompound(t) { return cs.(*clauses).all(), nil } // ignore clauses that can't possibly unify with our term candidates := make([]Term, 0) cs.(*clauses).forEach(func(clause Term) { if !IsCompound(clause) { Debugf(" ... discarding. Not compound term\n") return } head := clause if IsClause(clause) { head = Head(clause) } if t.(*Compound).MightUnify(head.(*Compound)) { Debugf(" ... adding to candidates: %s\n", clause) candidates = append(candidates, clause) } }) Debugf(" final candidates = %s\n", candidates) return candidates, nil } func (self *mapDb) ClauseCount() int { return self.clauseCount } func (self *mapDb) String() string { var buf bytes.Buffer keys := self.predicates.Keys() for _, key := range keys { cs, _ := self.predicates.Lookup(key) cs.(*clauses).forEach(func(t Term) { Fprintf(&buf, "%s.\n", t) }) } return buf.String() }
bransorem/golog
database.go
GO
mit
3,740
from cereal import car from opendbc.can.packer import CANPacker from selfdrive.car.mazda import mazdacan from selfdrive.car.mazda.values import CarControllerParams, Buttons from selfdrive.car import apply_std_steer_torque_limits VisualAlert = car.CarControl.HUDControl.VisualAlert class CarController(): def __init__(self, dbc_name, CP, VM): self.apply_steer_last = 0 self.packer = CANPacker(dbc_name) self.steer_rate_limited = False self.brake_counter = 0 def update(self, c, CS, frame): can_sends = [] apply_steer = 0 self.steer_rate_limited = False if c.active: # calculate steer and also set limits due to driver torque new_steer = int(round(c.actuators.steer * CarControllerParams.STEER_MAX)) apply_steer = apply_std_steer_torque_limits(new_steer, self.apply_steer_last, CS.out.steeringTorque, CarControllerParams) self.steer_rate_limited = new_steer != apply_steer if CS.out.standstill and frame % 5 == 0: # Mazda Stop and Go requires a RES button (or gas) press if the car stops more than 3 seconds # Send Resume button at 20hz if we're engaged at standstill to support full stop and go! # TODO: improve the resume trigger logic by looking at actual radar data can_sends.append(mazdacan.create_button_cmd(self.packer, CS.CP.carFingerprint, CS.crz_btns_counter, Buttons.RESUME)) if c.cruiseControl.cancel or (CS.out.cruiseState.enabled and not c.enabled): # If brake is pressed, let us wait >70ms before trying to disable crz to avoid # a race condition with the stock system, where the second cancel from openpilot # will disable the crz 'main on'. crz ctrl msg runs at 50hz. 70ms allows us to # read 3 messages and most likely sync state before we attempt cancel. self.brake_counter = self.brake_counter + 1 if frame % 10 == 0 and not (CS.out.brakePressed and self.brake_counter < 7): # Cancel Stock ACC if it's enabled while OP is disengaged # Send at a rate of 10hz until we sync with stock ACC state can_sends.append(mazdacan.create_button_cmd(self.packer, CS.CP.carFingerprint, CS.crz_btns_counter, Buttons.CANCEL)) else: self.brake_counter = 0 self.apply_steer_last = apply_steer # send HUD alerts if frame % 50 == 0: ldw = c.hudControl.visualAlert == VisualAlert.ldw steer_required = c.hudControl.visualAlert == VisualAlert.steerRequired # TODO: find a way to silence audible warnings so we can add more hud alerts steer_required = steer_required and CS.lkas_allowed_speed can_sends.append(mazdacan.create_alert_command(self.packer, CS.cam_laneinfo, ldw, steer_required)) # send steering command can_sends.append(mazdacan.create_steering_control(self.packer, CS.CP.carFingerprint, frame, apply_steer, CS.cam_lkas)) new_actuators = c.actuators.copy() new_actuators.steer = apply_steer / CarControllerParams.STEER_MAX return new_actuators, can_sends
commaai/openpilot
selfdrive/car/mazda/carcontroller.py
Python
mit
3,112
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { RelationComponent } from './relation/relation.component'; const routes: Routes = [{ path: 'relation', component: RelationComponent }]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class DataVRoutingModule {}
cipchk/ng-alain
src/app/routes/data-v/data-v-routing.module.ts
TypeScript
mit
365
<?php namespace SleepingOwl\Html; use Illuminate\Html\HtmlBuilder as IlluminateHtmlBuilder; use SleepingOwl\Admin\Models\Form\FormItem; use SleepingOwl\DateFormatter\DateFormatter; use SleepingOwl\Admin\Admin; use SleepingOwl\Admin\AssetManager\AssetManager; use Session; /** * Class HtmlBuilder */ class HtmlBuilder extends IlluminateHtmlBuilder { /** * @var string[] */ protected $tagsWithoutContent = [ 'input', 'img', 'br', 'hr' ]; /** * @param $tag * @param array $attributes * @param string $content * @return string */ public function tag($tag, $attributes = [], $content = null) { return $this->getOpeningTag($tag, $attributes) . $content . $this->getClosingTag($tag); } /** * @param string $key * @param string $value * @return string */ protected function attributeElement($key, $value) { if (is_array($value)) { $value = implode(' ', $value); } return parent::attributeElement($key, $value); } /** * @param $tag * @param array $attributes * @return string */ protected function getOpeningTag($tag, array $attributes) { $result = '<' . $tag; if ( ! empty($attributes)) { $result .= $this->attributes($attributes); } if ($this->isTagNeedsClosingTag($tag)) { $result .= '>'; } return $result; } /** * @param $tag * @return string */ protected function getClosingTag($tag) { $closingTag = '/>'; if ($this->isTagNeedsClosingTag($tag)) { $closingTag = '</' . $tag . '>'; } return $closingTag; } /** * @param $tag * @return bool */ protected function isTagNeedsClosingTag($tag) { return ! in_array($tag, $this->tagsWithoutContent); } /** * This method will generate input type text field * * @param $name * @param string $label * @param string $value * @param array $options * @return $this */ public static function text($name, $label = '', $value = '', $options = []) { AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js')); AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js')); return view('admin::_partials/form_elements/input_text') ->with('name', $name) ->with('label', $label) ->with('value', $value) ->with('options', $options) ->with('error', self::getError($name)); } public static function textWithActions($name, $label = '', $value = '', $options = [], $actions = []) { AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js')); AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js')); return view('admin::_partials/form_elements/input_text') ->with('name', $name) ->with('label', $label) ->with('value', $value) ->with('options', $options) ->with('actions', $actions) ->with('error', self::getError($name)); } /** * @param $name * @param string $label * @param int $value * @param array $options * @return $this */ public static function number($name, $label = '', $value = 0, $options = []) { AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js')); AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js')); if (empty($options['id'])) $options['id'] = uniqid(); return view('admin::_partials/form_elements/input_number') ->with('value', $value) ->with('name', $name) ->with('label', $label) ->with('options', $options) ->with('error', self::getError($name)); } /** * This method will generate input email * * @param $name * @param string $label * @param string $value * @param array $options * @return $this */ public static function emailField($name, $label = '', $value = '', $options = []) { AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js')); AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js')); return view('admin::_partials/form_elements/input_email') ->with('name', $name) ->with('label', $label) ->with('value', $value) ->with('options', $options) ->with('error', self::getError($name)); } public static function emailGroupField($name, $label = '', $value = '', $options = []) { $values = explode(',', $value); AssetManager::addScript(Admin::instance()->router->routeToAsset('js/tag-it.js')); AssetManager::addStyle(Admin::instance()->router->routeToAsset('css/jquery.tagit.css')); if (empty($options['id'])) $options['id'] = uniqid(); return view('admin::_partials/form_elements/input_email_group') ->with('name', $name) ->with('label', $label) ->with('values', $values) ->with('options', $options) ->with('error', self::getError($name)); } /** * This method will generate input type password field * * @param $name * @param string $label * @param string $value * @param array $options * @return $this */ public static function password($name, $label = '', $value = '', $options = []) { AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js')); AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js')); return view('admin::_partials/form_elements/input_password') ->with('name', $name) ->with('label', $label) ->with('value', $value) ->with('options', $options) ->with('error', self::getError($name)); } /** * This method will generate input type text field * * @param $name * @param string $label * @param string $value * @param array $options * @return $this */ public static function price($name, $label = '', $value = '', $options = [], $currency = '$') { AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js')); AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js')); return view('admin::_partials/form_elements/input_price') ->with('name', $name) ->with('label', $label) ->with('value', $value) ->with('options', $options) ->with('currency', $currency) ->with('error', self::getError($name)); } /** * This method will generate input color * * @param $name * @param string $label * @param string $value * @param array $options * @return $this */ public static function color($name, $label = '', $value = '', $options = []) { AssetManager::addScript(Admin::instance()->router->routeToAsset('js/bootstrap-colorpicker.js')); AssetManager::addStyle(Admin::instance()->router->routeToAsset('css/bootstrap-colorpicker.min.css')); AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js')); AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js')); if (empty($options['id'])) { $options['id'] = uniqid(); } return view('admin::_partials/form_elements/input_color') ->with('name', $name) ->with('label', $label) ->with('value', $value) ->with('options', $options) ->with('error', self::getError($name)); } /** * @param $name * @param $label * @param null $value * @param array $options * @return $this */ public static function radio($name, $label, $value = null, array $options = []) { AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js')); AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js')); return view('admin::_partials/form_elements/radio') ->with('name', $name) ->with('label', $label) ->with('value', (is_null($value)) ? 1 : $value) ->with('options', $options) ->with('error', self::getError($name)); } /** * @param $name string * @param $label string * @param null $value string * @param array $options * @param $addonValue string * @return $this */ public static function radioAddon($name, $label, $value = null, array $options = [], $addonValue) { return view('admin::_partials/form_elements/radio_addon') ->with('name', $name) ->with('label', $label) ->with('value', (is_null($value)) ? 1 : $value) ->with('options', $options) ->with('addonValue', $addonValue) ->with('error', self::getError($name)); } /** * @param $name * @param $label * @param null $value * @param array $options * @return $this */ public static function checkbox($name, $label, $value = null, array $options = []) { AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js')); AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js')); return view('admin::_partials/form_elements/checkbox') ->with('name', $name) ->with('label', $label) ->with('value', (is_null($value)) ? 1 : $value) ->with('options', $options) ->with('error', self::getError($name)); } /** * @param $name string * @param $label string * @param null $value string * @param array $options * @param $addonValue string * @return $this */ public static function checkboxAddon($name, $label, $value = null, array $options = [], $addonValue) { return view('admin::_partials/form_elements/checkbox_addon') ->with('name', $name) ->with('label', $label) ->with('value', (is_null($value)) ? 1 : $value) ->with('options', $options) ->with('addonValue', $addonValue) ->with('error', self::getError($name)); } /** * @param $name * @param $label * @param array $list * @param null $value * @param array $options * @return $this */ public static function select($name, $label, array $list = [], $value = null, array $options = []) { AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js')); AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js')); return view('admin::_partials/form_elements/select') ->with('name', $name) ->with('label', $label) ->with('value', $value) ->with('list', $list) ->with('options', $options) ->with('id', (!empty($options['id']) ? $options['id'] : $name)) ->with('error', self::getError($name)); } public static function date($name, $label, $value = null, array $options = [], $dateFormat = DateFormatter::SHORT, $timeFormat = DateFormatter::NONE) { $value = DateFormatter::format($value, $dateFormat, $timeFormat, 'dd.MM.y'); if (empty($options['id'])) $options['id'] = uniqid(); AssetManager::addScript(Admin::instance()->router->routeToAsset('js/bootstrap-datepicker.js')); AssetManager::addStyle(Admin::instance()->router->routeToAsset('css/datepicker.css')); AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js')); AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js')); return view('admin::_partials/form_elements/date') ->with('name', $name) ->with('label', $label) ->with('value', $value) ->with('options', $options) ->with('format', $dateFormat) ->with('id', $options['id']) ->with('error', self::getError($name)); } public static function datetime($name, $label, $value = null, array $options = [], $rule = [], $dateFormat = DateFormatter::SHORT, $timeFormat = DateFormatter::SHORT) { if ($value) { $value = DateFormatter::format($value, $dateFormat, $timeFormat, 'dd.MM.y H:mm'); } if (empty($options['id'])) { $options['id'] = uniqid(); } AssetManager::addScript(Admin::instance()->router->routeToAsset('js/moment.js')); AssetManager::addScript(Admin::instance()->router->routeToAsset('js/bootstrap-datetimepicker.min.js')); AssetManager::addStyle(Admin::instance()->router->routeToAsset('css/bootstrap-datetimepicker.min.css')); AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js')); AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js')); return view('admin::_partials/view_filters/datetime') ->with('name', $name) ->with('label', $label) ->with('value', $value) ->with('options', $options) ->with('date_format', $dateFormat) ->with('time_format', $timeFormat) ->with('id', $options['id']) ->with('rule', $rule) ->with('error', self::getError($name)); } public static function textarea($name, $label, $value = null, array $options = []) { $options['id'] = uniqid(); if (!empty($options['data-editor'])) { switch ($options['data-editor']) { case FormItem\Textarea::EDITOR_WYSIHTML: AssetManager::addStyle(Admin::instance()->router->routeToAsset('css/bootstrap-wysihtml5.css')); AssetManager::addScript(Admin::instance()->router->routeToAsset('js/wysihtml5-0.3.0.js')); AssetManager::addScript(Admin::instance()->router->routeToAsset('js/bootstrap-wysihtml5.js')); break; } } AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley.min.js')); AssetManager::addScript(Admin::instance()->router->routeToAsset('js/parsley-init.js')); return view('admin::_partials/form_elements/textarea') ->with('name', $name) ->with('label', $label) ->with('value', $value) ->with('options', $options) ->with('id', $options['id']) ->with('error', self::getError($name)); } /** * Returns error by key * * @param $key * @return string */ public static function getError($key) { $errors = Session::get('errors'); return $errors ? $errors->has($key) ? $errors->first() : '' : ''; } }
procoders/admin
src/SleepingOwl/Html/HtmlBuilder.php
PHP
mit
15,241
package cz.pfreiberg.knparser.exporter.oracledatabase; import java.sql.SQLException; import java.util.List; import cz.pfreiberg.knparser.ConnectionParameters; import cz.pfreiberg.knparser.domain.jednotky.TJednotek; import cz.pfreiberg.knparser.util.VfkUtil; public class TJednotekOracleDatabaseJdbcExporter extends CisOracleDatabaseJdbcExporter { private final static String name = "T_JEDNOTEK"; private final static String insert = "INSERT INTO " + name + " VALUES" + "(?,?,?,?,?)"; public TJednotekOracleDatabaseJdbcExporter(List<TJednotek> tJednotek, ConnectionParameters connectionParameters) { super(connectionParameters, name, insert); prepareStatement(tJednotek, name); } @Override public void insert(String table, Object rawRecord, boolean isRecord) throws SQLException { TJednotek record = (TJednotek) rawRecord; psInsert.setObject(1, record.getKod()); psInsert.setObject(2, record.getNazev()); psInsert.setObject(3, VfkUtil.convertToDatabaseDate(record.getPlatnostOd())); psInsert.setObject(4, VfkUtil.convertToDatabaseDate(record.getPlatnostDo())); psInsert.setObject(5, record.getZkratka()); } }
pfreiberg/knparser
src/main/java/cz/pfreiberg/knparser/exporter/oracledatabase/TJednotekOracleDatabaseJdbcExporter.java
Java
mit
1,193
using System.Collections.Generic; using System.Text; namespace DB2DataContextDriver.CodeGen { public class ClassDefinition { public string Name { get; set; } public string Inherits { get; set; } public List<string> Methods { get; set; } public List<PropertyDefinition> Properties { get; set; } public override string ToString() { var sb = new StringBuilder(); if (string.IsNullOrWhiteSpace(Inherits)) { sb.AppendFormat("public class {0} {{\n", Name); } else { sb.AppendFormat("public class {0} : {1} {{\n", Name, Inherits); } if (Methods != null) { foreach (var method in Methods) { sb.AppendLine("\t" + method.ToString()); } } if (Properties != null) { foreach (var property in Properties) { sb.AppendLine("\t" + property.ToString()); } } return sb.Append("}\n").ToString(); } } }
treytomes/DB2LinqPadDriver
DB2DataContextDriver/CodeGen/ClassDefinition.cs
C#
mit
941
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DigitAsWord")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DigitAsWord")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("653800a4-096d-4786-abda-996e996d6ba7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
DJBuro/Telerik
C#1/ConditionalStatements/DigitAsWord/Properties/AssemblyInfo.cs
C#
mit
1,398
import pprint from cytoolz import ( assoc, concatv, partial, pipe, ) from semantic_version import ( Spec, ) from eth_utils import ( add_0x_prefix, to_dict, to_tuple, ) from solc import ( get_solc_version, compile_standard, ) from solc.exceptions import ( ContractsNotFound, ) from populus.utils.compile import ( load_json_if_string, normalize_contract_metadata, ) from populus.utils.linking import ( normalize_standard_json_link_references, ) from populus.utils.mappings import ( has_nested_key, get_nested_key, set_nested_key, ) from .base import ( BaseCompilerBackend, ) @to_dict def build_standard_input_sources(source_file_paths): for file_path in source_file_paths: with open(file_path) as source_file: yield file_path, {'content': source_file.read()} @to_dict def normalize_standard_json_contract_data(contract_data): if 'metadata' in contract_data: yield 'metadata', normalize_contract_metadata(contract_data['metadata']) if 'evm' in contract_data: evm_data = contract_data['evm'] if 'bytecode' in evm_data: yield 'bytecode', add_0x_prefix(evm_data['bytecode'].get('object', '')) if 'linkReferences' in evm_data['bytecode']: yield 'linkrefs', normalize_standard_json_link_references( evm_data['bytecode']['linkReferences'], ) if 'deployedBytecode' in evm_data: yield 'bytecode_runtime', add_0x_prefix(evm_data['deployedBytecode'].get('object', '')) if 'linkReferences' in evm_data['deployedBytecode']: yield 'linkrefs_runtime', normalize_standard_json_link_references( evm_data['deployedBytecode']['linkReferences'], ) if 'abi' in contract_data: yield 'abi', load_json_if_string(contract_data['abi']) if 'userdoc' in contract_data: yield 'userdoc', load_json_if_string(contract_data['userdoc']) if 'devdoc' in contract_data: yield 'devdoc', load_json_if_string(contract_data['devdoc']) @to_tuple def normalize_compilation_result(compilation_result): """ Take the result from the --standard-json compilation and flatten it into an iterable of contract data dictionaries. """ for source_path, file_contracts in compilation_result['contracts'].items(): for contract_name, raw_contract_data in file_contracts.items(): contract_data = normalize_standard_json_contract_data(raw_contract_data) yield pipe( contract_data, partial(assoc, key='source_path', value=source_path), partial(assoc, key='name', value=contract_name), ) REQUIRED_OUTPUT_SELECTION = [ 'abi', 'metadata', 'evm.bytecode', 'evm.bytecode.object', 'evm.bytecode.linkReferences', 'evm.deployedBytecode', 'evm.deployedBytecode.object', 'evm.deployedBytecode.linkReferences', ] OUTPUT_SELECTION_KEY = 'settings.outputSelection.*.*' class SolcStandardJSONBackend(BaseCompilerBackend): project_source_glob = ('*.sol', ) test_source_glob = ('Test*.sol', ) def __init__(self, *args, **kwargs): if get_solc_version() not in Spec('>=0.4.11'): raise OSError( "The 'SolcStandardJSONBackend can only be used with solc " "versions >=0.4.11. The SolcCombinedJSONBackend should be used " "for all versions <=0.4.8" ) super(SolcStandardJSONBackend, self).__init__(*args, **kwargs) def get_compiled_contracts(self, source_file_paths, import_remappings): self.logger.debug("Import remappings: %s", import_remappings) self.logger.debug("Compiler Settings PRE: %s", pprint.pformat(self.compiler_settings)) # DEBUG self.compiler_settings['output_values'] = [] self.logger.debug("Compiler Settings POST: %s", pprint.pformat(self.compiler_settings)) if 'remappings' in self.compiler_settings and import_remappings is not None: self.logger.warn("Import remappings setting will by overridden by backend settings") sources = build_standard_input_sources(source_file_paths) std_input = { 'language': 'Solidity', 'sources': sources, 'settings': { 'remappings': import_remappings, 'outputSelection': { '*': { '*': REQUIRED_OUTPUT_SELECTION } } } } # solc command line options as passed to solc_wrapper() # https://github.com/ethereum/py-solc/blob/3a6de359dc31375df46418e6ffd7f45ab9567287/solc/wrapper.py#L20 command_line_options = self.compiler_settings.get("command_line_options", {}) # Get Solidity Input Description settings section # http://solidity.readthedocs.io/en/develop/using-the-compiler.html#input-description std_input_settings = self.compiler_settings.get("stdin", {}) std_input['settings'].update(std_input_settings) # Make sure the output selection has all of the required output values. if has_nested_key(std_input, OUTPUT_SELECTION_KEY): current_selection = get_nested_key(std_input, OUTPUT_SELECTION_KEY) output_selection = list(set(concatv(current_selection, REQUIRED_OUTPUT_SELECTION))) else: output_selection = REQUIRED_OUTPUT_SELECTION set_nested_key(std_input, OUTPUT_SELECTION_KEY, output_selection) self.logger.debug("std_input sections: %s", std_input.keys()) self.logger.debug("Input Description JSON settings are: %s", std_input["settings"]) self.logger.debug("Command line options are: %s", command_line_options) try: compilation_result = compile_standard(std_input, **command_line_options) except ContractsNotFound: return {} compiled_contracts = normalize_compilation_result(compilation_result) return compiled_contracts
pipermerriam/populus
populus/compilation/backends/solc_standard_json.py
Python
mit
6,140
import React from 'react'; import moment from 'moment'; import { storiesOf } from '@storybook/react'; import { withInfo } from '@storybook/addon-info'; import isInclusivelyAfterDay from '../src/utils/isInclusivelyAfterDay'; import isSameDay from '../src/utils/isSameDay'; import SingleDatePickerWrapper from '../examples/SingleDatePickerWrapper'; const datesList = [ moment(), moment().add(1, 'days'), moment().add(3, 'days'), moment().add(9, 'days'), moment().add(10, 'days'), moment().add(11, 'days'), moment().add(12, 'days'), moment().add(13, 'days'), ]; storiesOf('SDP - Day Props', module) .add('default', withInfo()(() => ( <SingleDatePickerWrapper autoFocus /> ))) .add('allows all days, including past days', withInfo()(() => ( <SingleDatePickerWrapper isOutsideRange={() => false} autoFocus /> ))) .add('allows next two weeks only', withInfo()(() => ( <SingleDatePickerWrapper isOutsideRange={day => !isInclusivelyAfterDay(day, moment()) || isInclusivelyAfterDay(day, moment().add(2, 'weeks')) } autoFocus /> ))) .add('with some blocked dates', withInfo()(() => ( <SingleDatePickerWrapper isDayBlocked={day1 => datesList.some(day2 => isSameDay(day1, day2))} autoFocus /> ))) .add('with some highlighted dates', withInfo()(() => ( <SingleDatePickerWrapper isDayHighlighted={day1 => datesList.some(day2 => isSameDay(day1, day2))} autoFocus /> ))) .add('blocks fridays', withInfo()(() => ( <SingleDatePickerWrapper isDayBlocked={day => moment.weekdays(day.weekday()) === 'Friday'} autoFocus /> ))) .add('with custom daily details', withInfo()(() => ( <SingleDatePickerWrapper numberOfMonths={1} renderDayContents={day => day.format('ddd')} autoFocus /> )));
airbnb/react-dates
stories/SingleDatePicker_day.js
JavaScript
mit
1,865
/** * */ package com.forgedui.model.titanium; import com.forgedui.model.Element; import com.forgedui.model.titanium.annotations.Composite; import com.forgedui.model.titanium.annotations.EnumValues; import com.forgedui.model.titanium.annotations.Review; import com.forgedui.model.titanium.annotations.SupportedPlatform; import com.forgedui.model.titanium.annotations.Unmapped; /** * @AutoGenerated */ public class Window extends TitaniumUIContainer { /** * */ @Unmapped private static final long serialVersionUID = 1L; @Unmapped public static final String ORIENTATION_MODE_FACE_DOWN = "Titanium.UI.FACE_DOWN"; @Unmapped public static final String ORIENTATION_MODE_FACE_UP = "Titanium.UI.FACE_UP"; @Unmapped public static final String ORIENTATION_MODE_PORTRAIT = "Titanium.UI.PORTRAIT"; @Unmapped public static final String ORIENTATION_MODE_UPSIDE_PORTRAIT = "Titanium.UI.UPSIDE_PORTRAIT"; @Unmapped public static final String ORIENTATION_MODE_UNKNOWN = "Titanium.UI.UNKNOWN"; @Unmapped public static final String ORIENTATION_MODE_LANDSCAPE_LEFT = "Titanium.UI.LANDSCAPE_LEFT"; @Unmapped public static final String ORIENTATION_MODE_LANDSCAPE_RIGHT = "Titanium.UI.LANDSCAPE_RIGHT"; @Unmapped public static final String MODAL_PROP = "modal"; @Unmapped public static final String TITLE_BAR_PROP = "titleBar"; @Unmapped public static final String TABS_HIDDEN_PROP = "tabsGroupHidden"; @Unmapped public static final String FULL_SCREEN_PROP = "fullScreen"; @Unmapped public static final String ORIENTATION_MODES_PROP = "orientationModes"; private Boolean exitOnClose; private Boolean tabBarHidden; private Boolean navBarHidden; @Review(note = "What is the highest class in hierarchy for this") @SupportedPlatform(platforms = "iphone") private TitaniumUIBoundedElement[] toolbar; private Boolean translucent; private String url; @EnumValues(values = { "Titanium.UI.FACE_DOWN", "Titanium.UI.FACE_UP", "Titanium.UI.LANDSCAPE_LEFT", "Titanium.UI.LANDSCAPE_RIGHT", "Titanium.UI.PORTRAIT", "Titanium.UI.UNKNOWN", "Titanium.UI.UPSIDE_PORTRAIT" }, type = "integer") private String[] orientationModes; private Boolean fullscreen; @Composite private TitleBar titleBar; private Boolean modal; public Window() { this.type = "Titanium.UI.Window"; } public Boolean getExitOnClose() { return exitOnClose; } public void setExitOnClose(Boolean exitOnClose) { this.exitOnClose = exitOnClose; } public Boolean getTabBarHidden() { return tabBarHidden; } public void setTabBarHidden(Boolean tabBarHidden) { Boolean old = this.tabBarHidden; this.tabBarHidden = tabBarHidden; listeners.firePropertyChange(TABS_HIDDEN_PROP, old, tabBarHidden); } public Boolean getNavBarHidden() { return navBarHidden; } public void setNavBarHidden(Boolean navBarHidden) { this.navBarHidden = navBarHidden; } public TitaniumUIBoundedElement[] getToolbar() { return toolbar; } public void setToolbar(TitaniumUIBoundedElement[] toolbar) { TitaniumUIBoundedElement[] oldToolbar = toolbar; if (toolbar != null){ for (TitaniumUIBoundedElement titaniumUIElement : toolbar) { titaniumUIElement.setParent(null); } } this.toolbar = oldToolbar; if (toolbar != null){ for (TitaniumUIBoundedElement titaniumUIElement : toolbar) { titaniumUIElement.setParent(this); } } listeners.firePropertyChange("Window.toolbar", oldToolbar, oldToolbar); } public Boolean getTranslucent() { return translucent; } public void setTranslucent(Boolean translucent) { this.translucent = translucent; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String[] getOrientationModes() { return orientationModes; } public void setOrientationModes(String[] orientationModes) { this.orientationModes = orientationModes; } public Boolean getFullscreen() { return fullscreen; } public void setFullscreen(Boolean fullscreen) { Boolean old = this.fullscreen; this.fullscreen = fullscreen; listeners.firePropertyChange(FULL_SCREEN_PROP, old, fullscreen); } public Boolean getModal() { return modal; } public void setModal(Boolean modal) { Boolean oldValue = this.modal; this.modal = modal; listeners.firePropertyChange(MODAL_PROP, oldValue, modal); } public void setTitleBar(TitleBar titleBar) { TitleBar oldTitleBar = this.titleBar; this.titleBar = titleBar; fireElementPropertySet(TITLE_BAR_PROP, oldTitleBar, titleBar); } public TitleBar getTitleBar() { return titleBar; } @Override public void setParent(Element parent) { this.parent = parent; if (parent != null && name == null){ String fileName = getDiagram().getFile().getName(); if (fileName.indexOf('.') >= 0){ fileName = fileName.substring(0, fileName.indexOf('.')); } setName(fileName); } } }
ShoukriKattan/ForgedUI-Eclipse
com.forgedui.core/src/com/forgedui/model/titanium/Window.java
Java
mit
4,862
import datetime from django.http import HttpResponse from django.shortcuts import get_object_or_404, render from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_POST from ..tasks import trigger_instance from . import app_settings from .enums import StateEnum from .models import Call @csrf_exempt @require_POST def twiml_callback(request, ident): call = get_object_or_404(Call, ident=ident) return render(request, 'reminders/calls/twiml_callback.xml', { 'call': call, }, content_type='text/xml') @csrf_exempt @require_POST def gather_callback(request, ident): call = get_object_or_404(Call, ident=ident) # Mark if the user actually pressed a button if request.POST.get('Digits'): call.button_pressed = datetime.datetime.utcnow() call.save(update_fields=('button_pressed',)) return render( request, 'reminders/calls/gather_callback.xml', content_type='text/xml' ) @csrf_exempt @require_POST def status_callback(request, ident): """ https://www.twilio.com/help/faq/voice/what-do-the-call-statuses-mean Example POST data: SipResponseCode: 500 ApiVersion: 2010-04-01 AccountSid: AC7d6b676d2a17527a71a2bb41301b5e6f Duration: 0 Direction: outbound-api CallStatus: busy SequenceNumber: 0 Timestamp: Mon, 16 Nov 2015 16:10:53 +0000 Caller: +441143032046 CallDuration: 0 To: +447753237119 CallbackSource: call-progress-events Called: +447751231511 From: +441143032046 CallSid: CA19fd373bd82b81b602c75d1ddc7745e7 """ call = get_object_or_404(Call, ident=ident) try: call.state = { 'queued': StateEnum.dialing, 'initiated': StateEnum.dialing, 'ringing': StateEnum.dialing, 'in-progress': StateEnum.answered, 'completed': StateEnum.answered, 'busy': StateEnum.busy, 'no-answer': StateEnum.no_answer, 'cancelled': StateEnum.failed, 'failed': StateEnum.failed, }[request.POST['CallStatus']] except KeyError: call.state = StateEnum.unknown call.state_updated = datetime.datetime.utcnow() call.save(update_fields=('state', 'state_updated')) if not call.button_pressed \ and call.instance.calls.count() < app_settings.RETRY_COUNT: trigger_instance.apply_async( args=(call.instance_id,), countdown=app_settings.RETRY_AFTER_SECONDS, ) return HttpResponse('')
takeyourmeds/takeyourmeds-web
takeyourmeds/reminders/reminders_calls/views.py
Python
mit
2,634
package de.kumpelblase2.jhipsterwebsocket.domain.util; import java.io.IOException; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.SerializerProvider; /** * Custom Jackson serializer for displaying Joda DateTime objects. */ public class CustomDateTimeSerializer extends JsonSerializer<DateTime> { private static DateTimeFormatter formatter = DateTimeFormat .forPattern("yyyy-MM-dd'T'HH:mm:ss'Z'"); @Override public void serialize(DateTime value, JsonGenerator generator, SerializerProvider serializerProvider) throws IOException { generator.writeString(formatter.print(value.toDateTime(DateTimeZone.UTC))); } }
kumpelblase2/jhipster-websocket-example
src/main/java/de/kumpelblase2/jhipsterwebsocket/domain/util/CustomDateTimeSerializer.java
Java
mit
944
require 'couchdb'
Gimi/couchdb-client
lib/couchdb-client.rb
Ruby
mit
18
namespace CodingDojo { public class InterlockedBoolean { private readonly bool _value; private static readonly InterlockedBoolean FalseValue = new InterlockedBoolean(false); private static readonly InterlockedBoolean TrueValue = new InterlockedBoolean(true); private InterlockedBoolean(bool value) { _value = value; } public static InterlockedBoolean Get(bool? value) { return value; } public static implicit operator bool(InterlockedBoolean interlockedBoolean) { return interlockedBoolean._value; } public static implicit operator InterlockedBoolean(bool value) { return value ? TrueValue : FalseValue; } public static InterlockedBoolean operator !(InterlockedBoolean b) { return !b._value; } public static InterlockedBoolean operator &(InterlockedBoolean a, InterlockedBoolean b) { return a._value && b._value; } public static bool operator false(InterlockedBoolean a) { return !a._value; } public static bool operator true(InterlockedBoolean a) { return a._value; } public static InterlockedBoolean operator |(InterlockedBoolean a, InterlockedBoolean b) { return a._value || b._value; } public static InterlockedBoolean operator ^(InterlockedBoolean a, InterlockedBoolean b) { return a._value ^ b._value; } public static InterlockedBoolean operator ==(InterlockedBoolean a, InterlockedBoolean b) { if ((object)a == null && (object)b == null) return true; if ((object)a == null || (object)b == null) return false; return a._value == b._value; } public static InterlockedBoolean operator !=(InterlockedBoolean a, InterlockedBoolean b) { return !(a == b); } public static InterlockedBoolean operator ==(InterlockedBoolean a, bool b) { if ((object)a == null) return false; return a._value == b; } public static InterlockedBoolean operator !=(InterlockedBoolean a, bool b) { return !(a == b); } public static InterlockedBoolean operator ==(bool a, InterlockedBoolean b) { if ((object)b == null) return false; return a == b._value; } public static InterlockedBoolean operator !=(bool a, InterlockedBoolean b) { return !(a == b); } public override string ToString() { return _value.ToString(); } public override bool Equals(object obj) { if (obj is InterlockedBoolean) return _value == (obj as InterlockedBoolean)._value; return _value.Equals(obj); } public override int GetHashCode() { return _value.GetHashCode(); } } }
JanVoracek/interlocked-boolean
InterlockedBoolean.cs
C#
mit
3,117
require 'active_record' require "active_record/version" class ActiveRecord::Base class << self ################################# Generic where clause and inclusion builder ########################### # Query specification format # # Hash containing association specific query specification, # each of which will map a param field to its param metadata # needed to construct where condition. Param metadata involve # information about the table, column the param maps to and # the operator that need to applied in the query with the # table column for the given param value. The operator passed # is delegated to Arel::Table. So, all operators accepted # by it are allowed (as mentioned in the example below) # # { # :self => # { # <param_field> => # { # :column => <col_name_sym> # :filter_operator => <:gt|:lt|:gteq|:lteq|:in|:not_in>, # } # } # :association1 => # { # <param_field> => # { # :column => <col_name_sym> # :filter_operator => <:gt|:lt|:gteq|:lteq|:in|:not_in>, # }, # ... # :join_filter => # { # :table1_column => <column_name>, :table2_column => <column_name>, # }, # :is_inclusion_mandatory => <true|false> # }, # ... # } # Applies inclusion and where conditions/clauses for the model called upon. # Where conditions are generated based on the presence of a param value. def apply_includes_and_where_clauses(params, query_spec) model = self inclusions, where_clauses = get_inclusions_and_where_clauses(params, query_spec) active_record = model.includes(inclusions) where_clauses.each { |e| active_record = active_record.where(e) } active_record end # Returns association inclusions and where conditions/clauses for the model called upon. # Association inclusion is based on the presence of related where conditions. # Where conditions are generated based on the presence of a param value. def get_inclusions_and_where_clauses(params, query_spec) result = emit_inclusion_and_filter_details(params, query_spec) inclusions = result.keys - [:self] where_clause_filters = result.values.flatten [inclusions, where_clause_filters] end def emit_inclusion_and_filter_details(params, query_spec) exclusions = [:join_filter, :is_inclusion_mandatory] query_spec.each_with_object({}) do |(association, association_filter_spec), res| join_spec, is_inclusion_mandatory = association_filter_spec.values_at(*exclusions) new_association_filter_spec = association_filter_spec.reject { |e| exclusions.include?(e) } association_model = get_association_model(association) join_filter = get_association_join_filter(join_spec, self, association_model) where_clause_filters = new_association_filter_spec.each_with_object([]) do |(param_field, filter_spec), filter_res| value = params[param_field] if value.present? filter_res << get_where_clause_filter(filter_spec, value, association_model) end end if where_clause_filters.present? res[association] = where_clause_filters res[association] << join_filter if join_filter.present? elsif is_inclusion_mandatory res[association] = (join_filter.present?) ? [join_filter] : [] end end end # Obtain ActiveRecord model from the association def get_association_model(association) (association == :self) ? self : self.reflect_on_association(association.to_sym).klass end private def get_association_join_filter(join_filter, table1, table2) return if join_filter.blank? table1_col, table2_col = join_filter.values_at(:table1_column, :table2_column) get_where_clause_sql(table2.arel_table[table2_col], table1, table1_col, :eq) end def get_where_clause_filter(filter_spec, value, table) # Hash filters have good equality query abstractions. # So choosing them over string filters for equality operator if filter_spec[:filter_operator] == :eq construct_hash_filter(value, filter_spec, table) else construct_str_filter(value, filter_spec, table) end end def construct_str_filter(arg_value, filter_spec, table) operator, column = filter_spec.values_at(:filter_operator, :column) get_where_clause_sql(arg_value, table, column, operator) end def get_where_clause_sql(arg_value, table, column, operator) table_arel = table.arel_table sql = table_arel.where(table_arel[column].send(operator, arg_value)).to_sql sql.split("WHERE").last end def construct_hash_filter(arg_value, filter_spec, table) column = filter_spec[:column] hash_filter = {column => arg_value} (table != :self) ? {table.table_name.to_sym => hash_filter} : hash_filter end end end
kaushikd49/ar-auto-filter
lib/activerecord-auto_filter.rb
Ruby
mit
5,309
window.onload = () => { const root = new THREERoot({ fov: 60 }); root.renderer.setClearColor(0x222222); root.camera.position.set(0, 0, 100); let light = new THREE.DirectionalLight(0xffffff); root.add(light); light = new THREE.DirectionalLight(0xffffff); light.position.z = 1; root.add(light); // mesh / skeleton based on https://threejs.org/docs/scenes/bones-browser.html const segmentHeight = 8; const segmentCount = 4; const height = segmentHeight * segmentCount; const halfHeight = height * 0.5; const sizing = { segmentHeight, segmentCount, height, halfHeight }; const bones = createBones(sizing); const geometry = createGeometry(sizing); const mesh = createMesh(geometry, bones); const skeletonHelper = new THREE.SkeletonHelper(mesh); root.add(skeletonHelper); root.add(mesh); let time = 0; root.addUpdateCallback(() => { time += (1/60); mesh.material.uniforms.time.value = time % 1; bones.forEach(bone => { bone.rotation.z = Math.sin(time) * 0.25; }) }); }; function createBones(sizing) { const bones = []; let prevBone = new THREE.Bone(); bones.push(prevBone); prevBone.position.y = -sizing.halfHeight; for (let i = 0; i < sizing.segmentCount; i++) { const bone = new THREE.Bone(); bone.position.y = sizing.segmentHeight; bones.push(bone); prevBone.add(bone); prevBone = bone; } return bones; } function createGeometry(sizing) { let baseGeometry = new THREE.CylinderGeometry( 5, // radiusTop 5, // radiusBottom sizing.height, // height 8, // radiusSegments sizing.segmentCount * 4, // heightSegments true // openEnded ); baseGeometry = new THREE.Geometry().fromBufferGeometry(baseGeometry); for (let i = 0; i < baseGeometry.vertices.length; i++) { const vertex = baseGeometry.vertices[i]; const y = (vertex.y + sizing.halfHeight); const skinIndex = Math.floor(y / sizing.segmentHeight); const skinWeight = (y % sizing.segmentHeight) / sizing.segmentHeight; // skinIndices = indices of up to 4 bones for the vertex to be influenced by baseGeometry.skinIndices.push(new THREE.Vector4(skinIndex, skinIndex + 1, 0, 0)); // skinWeights = weights for each of the bones referenced by index above (between 0 and 1) baseGeometry.skinWeights.push(new THREE.Vector4(1 - skinWeight, skinWeight, 0, 0)); } // create a prefab for each vertex const prefab = new THREE.TetrahedronGeometry(1); const prefabCount = baseGeometry.vertices.length; const geometry = new BAS.PrefabBufferGeometry(prefab, prefabCount); // position (copy vertex position) geometry.createAttribute('aPosition', 3, function(data, i) { baseGeometry.vertices[i].toArray(data); }); // skin indices, copy from geometry, based on vertex geometry.createAttribute('skinIndex', 4, (data, i) => { baseGeometry.skinIndices[i].toArray(data); }); // skin weights, copy from geometry, based on vertex geometry.createAttribute('skinWeight', 4, (data, i) => { baseGeometry.skinWeights[i].toArray(data); }); // rotation (this is completely arbitrary) const axis = new THREE.Vector3(); geometry.createAttribute('aAxisAngle', 4, function(data, i) { BAS.Utils.randomAxis(axis); axis.toArray(data); data[3] = Math.PI * 2; }); return geometry; } function createMesh(geometry, bones) { const material = new BAS.StandardAnimationMaterial({ skinning: true, side: THREE.DoubleSide, flatShading: true, uniforms: { time: {value: 0}, }, vertexParameters: ` uniform float time; attribute vec3 aPosition; attribute vec4 aAxisAngle; `, vertexFunctions: [ BAS.ShaderChunk.quaternion_rotation ], vertexPosition: ` vec4 q = quatFromAxisAngle(aAxisAngle.xyz, aAxisAngle.w * time); transformed = rotateVector(q, transformed); transformed += aPosition; ` }); const mesh = new THREE.SkinnedMesh(geometry, material); const skeleton = new THREE.Skeleton(bones); mesh.add(bones[0]); mesh.bind(skeleton); return mesh; }
zadvorsky/three.bas
examples/skinning_prefabs/main.js
JavaScript
mit
4,231
import imp import os tools = [] for name in os.listdir(os.path.dirname(__file__)): if not name.startswith('_'): # _ in the front indicates that this tool is disabled directory = os.path.join(os.path.dirname(__file__), name) if os.path.isdir(directory): file = os.path.join(directory, name + '.py') tool = imp.load_source(name, file) tools.append(getattr(tool, name))
nullzero/wpcgi
wpcgi/tools/__init__.py
Python
mit
424
#!/usr/bin/env python # Copyright (c) 2011, 2013 SEOmoz, Inc # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to # permit persons to whom the Software is furnished to do so, subject to # the following conditions: # # The above copyright notice and this permission notice shall be # included in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE # LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION # OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION # WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. from setuptools import setup setup( name='s3po', version='0.6.1', description='An uploading daemon for S3', long_description='''Boto is a wonderful library. This is just a little help for dealing with multipart uploads, batch uploading with gevent and getting some help when mocking''', author='Moz, Inc.', author_email="turbo@moz.com", url='http://github.com/seomoz/s3po', packages=['s3po', 's3po.backends'], license='MIT', platforms='Posix; MacOS X', install_requires=[ 'boto3', 'coverage', 'gevent', 'mock', 'nose', 'python_swiftclient', 'six' ], classifiers=[ 'License :: OSI Approved :: MIT License', 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'Topic :: Internet :: WWW/HTTP', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.6', 'Programming Language :: Python :: 3.7', ] )
seomoz/s3po
setup.py
Python
mit
2,278
module Provision VERSION = "0.0.1" end
chenfisher/provision
lib/provision/version.rb
Ruby
mit
41
@extends('admin') @section('title', 'Promotions') @section('content') <div class="row"> <div class="col-md-5"> <h3 class="modal-title">{{ $result->total() }} {{ str_plural('Promotion', $result->count()) }}</h3> </div> <div class="col-md-12 page-action text-right"> @can('add_promotions') <a href="{{ route('promotions.create') }}" class="btn btn-primary btn-sm"> <i class="glyphicon glyphicon-plus-sign"></i> Create</a> @endcan </div> <br><br><br><br> <!-- /.box-header --> <div class="box-body"> <table id="example1" class="table table-bordered table-striped"> <thead> <tr> <th>Name</th> <th>Hourly Discount</th> <th>Daily Discount</th> <th>Price Discount</th> <th>Start Date</th> <th>End Date</th> @can('edit_promotions', 'delete_promotions') <th class="text-center">Actions</th> @endcan </tr> </thead> @foreach($result as $item) <tr> <td>{{ $item->name }}</td> <td>{{ $item->hourlyRatePercentage }}</td> <td>{{ $item->dailyRatePercentage }}</td> <td>{{ $item->priceRatePercentage }}</td> <td>{{ $item->start_date }}</td> <td>{{ $item->end_date }}</td> @can('edit_promotions') <td class="text-center"> @include('shared._actions', [ 'entity' => 'promotions', 'id' => $item->id ]) </td> @endcan </tr> @endforeach </table> </div> <!-- /.box-body --> </div> <!-- /.box --> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <!-- Bootstrap 3.3.7 --> <link rel="stylesheet" href="../../bower_components/bootstrap/dist/css/bootstrap.min.css"> <!-- Font Awesome --> <link rel="stylesheet" href="../../bower_components/font-awesome/css/font-awesome.min.css"> <!-- Ionicons --> <link rel="stylesheet" href="../../bower_components/Ionicons/css/ionicons.min.css"> <!-- DataTables --> <link rel="stylesheet" href="../../bower_components/datatables.net-bs/css/dataTables.bootstrap.min.css"> <!-- <body class="hold-transition skin-blue sidebar-mini"> --> <!-- jQuery 3 --> <script src="../../bower_components/jquery/dist/jquery.min.js"></script> <!-- Bootstrap 3.3.7 --> <script src="../../bower_components/bootstrap/dist/js/bootstrap.min.js"></script> <!-- DataTables --> <script src="../../bower_components/datatables.net/js/jquery.dataTables.min.js"></script> <script src="../../bower_components/datatables.net-bs/js/dataTables.bootstrap.min.js"></script> <!-- SlimScroll --> <script src="../../bower_components/jquery-slimscroll/jquery.slimscroll.min.js"></script> <!-- FastClick --> <script src="../../bower_components/fastclick/lib/fastclick.js"></script> <!-- page script --> <script> $(function () { $('#example1').DataTable() $('#example2').DataTable({ 'paging' : true, 'lengthChange': false, 'searching' : false, 'ordering' : true, 'info' : true, 'autoWidth' : false }) }) </script> @endsection
ryanzzeng/laravelStarter
resources/views/promotion/index.blade.php
PHP
mit
3,673
package bg; import com.renren.api.RennException; /** 定时刷新信息. * @author ZCH */ public final class Driver { /** magic number. * set magic number 180000 */ private static final int MN = 180000; /** 调用dirive()函数. * @param args String[] */ public static void main(final String[] args) { drive(); } /** Timer. */ private static void drive() { long interval = MN; while (true) { InfoBG.getInfo(); try { OrganBG.getOrgan(); } catch (RennException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } System.out.println("=============================="); try { Thread.sleep(interval); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } /** constructer. */ private Driver() { } }
sibojia/ihomepage
infohub-yt/src/bg/Driver.java
Java
mit
1,054
namespace NServiceBus.AcceptanceTests.Basic { using System; using System.Threading.Tasks; using AcceptanceTesting; using EndpointTemplates; using NUnit.Framework; public class When_multiple_mappings_exists : NServiceBusAcceptanceTest { [Test] public async Task First_registration_should_be_the_final_destination() { var context = await Scenario.Define<Context>() .WithEndpoint<Sender>(b => b.When((session, c) => session.Send(new MyCommand1()))) .WithEndpoint<Receiver1>() .WithEndpoint<Receiver2>() .Done(c => c.WasCalled1 || c.WasCalled2) .Run(); Assert.IsTrue(context.WasCalled1); Assert.IsFalse(context.WasCalled2); } public class Context : ScenarioContext { public bool WasCalled1 { get; set; } public bool WasCalled2 { get; set; } } public class Sender : EndpointConfigurationBuilder { public Sender() { EndpointSetup<DefaultServer>() .AddMapping<MyCommand1>(typeof(Receiver1)) .AddMapping<MyCommand2>(typeof(Receiver2)); } } public class Receiver1 : EndpointConfigurationBuilder { public Receiver1() { EndpointSetup<DefaultServer>(); } public class MyMessageHandler : IHandleMessages<MyBaseCommand> { public Context Context { get; set; } public Task Handle(MyBaseCommand message, IMessageHandlerContext context) { Context.WasCalled1 = true; return Task.Delay(2000); // Just to be sure the other receiver is finished } } } public class Receiver2 : EndpointConfigurationBuilder { public Receiver2() { EndpointSetup<DefaultServer>(); } public class MyMessageHandler : IHandleMessages<MyBaseCommand> { public Context Context { get; set; } public Task Handle(MyBaseCommand message, IMessageHandlerContext context) { Context.WasCalled2 = true; return Task.Delay(2000); // Just to be sure the other receiver is finished } } } [Serializable] public abstract class MyBaseCommand : ICommand { } [Serializable] public class MyCommand1 : MyBaseCommand { } [Serializable] public class MyCommand2 : MyBaseCommand { } } }
sbmako/NServiceBus.MongoDB
src/NServiceBus.MongoDB.Acceptance.Tests/App_Packages/NSB.AcceptanceTests.6.0.0/Basic/When_multiple_mappings_exists.cs
C#
mit
2,894
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered.org <http://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.mod.mixin.core.event.entity.living; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLivingBase; import net.minecraftforge.event.entity.EntityEvent; import org.spongepowered.api.entity.living.Living; import org.spongepowered.api.event.entity.living.LivingEvent; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Shadow; @Mixin(value = net.minecraftforge.event.entity.living.LivingEvent.class, remap = false) public abstract class MixinEventLiving extends EntityEvent implements LivingEvent { @Shadow public EntityLivingBase entityLiving; public MixinEventLiving(Entity entity) { super(entity); } @Override public Living getLiving() { return (Living) this.entityLiving; } @Override public Living getEntity() { return (Living) this.entityLiving; } }
phase/Sponge
src/main/java/org/spongepowered/mod/mixin/core/event/entity/living/MixinEventLiving.java
Java
mit
2,143
import test from 'ava'; import snapshot from '../../helpers/snapshot'; import Vue from 'vue/dist/vue.common.js'; import u from '../../../src/lib/components/u/index.vue'; import commonTest from '../../common/unit'; const testOptions = { test, Vue, snapshot, component : window.morning._origin.Form.extend(u), name : 'u', attrs : ``, uiid : 2, delVmEl : false, _baseTestHookCustomMount : false }; commonTest.componentBase(testOptions);
Morning-UI/morning-ui
test/unit/components/u.js
JavaScript
mit
586
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Enable Rack::Cache to put a simple HTTP cache in front of your application # Add `rack-cache` to your Gemfile before enabling this. # For large-scale production use, consider using a caching reverse proxy like # NGINX, varnish or squid. # config.action_dispatch.rack_cache = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = true # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups. # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production. # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. config.action_mailer.default_url_options = { :host => 'handelatnewberry.herokuapp.com' } config.action_mailer.delivery_method = :smtp config.action_mailer.perform_deliveries = true config.action_mailer.raise_delivery_errors = false config.action_mailer.default :charset => "utf-8" config.action_mailer.smtp_settings = { address: "smtp.gmail.com", port: 587, domain: "handelatnewberry.herokuapp.com", authentication: "plain", enable_starttls_auto: true, user_name: ENV['EMAIL'], password: ENV['PASSWORD'] } # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false end
reginafcompton/handelatnewberry
config/environments/production.rb
Ruby
mit
3,853
/*Création des cookies*/ $(document).ready(function () { CreateCookies(); $('input:not([type="submit"])').each(function () { $(this).val(''); }); }); /*Ajout des vols dans la recherche*/ function addResultVols(toAppend, compagnie, code, provenance, destination, imgSrc, date, heure, ArrDep, imgArrDep,data_vols,typeAlert,statut) { var dateTd = (date === null) ? '' : '<td>' + date + '</td>'; var trString = '<tr class="'+ArrDep+'" active="OK" data-codevol="'+code+'" data-typevols="result">'+ '<td class="imgArrDep"><img src="'+imgArrDep+'"/></td>'+ '<td class="logoCompagny"><img src="'+imgSrc+'"/></td>'+ '<td class="numVol">'+code+'</td>'+ '<td>'+provenance+'</td>'+ '<td>'+destination+'</td>'+ dateTd+ '<td>'+heure+'</td>'+ '<td>'+statut+'</td>'+ '<td class="ToggleTd"><input type="checkbox" name="Alert" class="Alert'+typeAlert+' toggleCheckBox" data-vols="'+data_vols+'"/></td>'+ '</tr>'; var tr = $.parseHTML(trString); toAppend.append(tr); } /*Ajout message -> Aucun Vol*/ function addNoVol(toAppend) { var trString = '<tr class="NoResultVol">' + '<td colspan="9" style="text-align:center;">Aucun vol ne correspond à la provenance et à la destination soumise ou à la date soumise </td>' + '</tr>'; var tr = $.parseHTML(trString); toAppend.append(tr); } /*Création des cookies*/ function CreateCookies() { Cookies.set('provenance', ''); Cookies.set('destination', ''); Cookies.set('dateVol', ''); } /*Vérifier si les cookies existent*/ function CookiesExists() { return Cookies.get('provenance') !== '' && Cookies.get('destination') !== '' && Cookies.get('dateVol') !== ''; } /*Véfier si les cookies contiennent les données de la précédente recherche*/ function IsSetCookies(prov, dest, date) { return Cookies.get('provenance') == prov && Cookies.get('destination') == dest && Cookies.get('dateVol') == date; } /*Set Cookie*/ function SetCookies(prov, dest, date) { Cookies.set('provenance', prov); Cookies.set('destination', dest); Cookies.set('dateVol', date); } /*Nettoyage précédent résultat*/ function NettoyageResult(trs,envoiOk) { trs.remove(); if(envoiOk.hasClass("displayButton")) envoiOk.removeClass("displayButton"); if(!envoiOk.hasClass('noDisplayButton')) envoiOk.addClass('noDisplayButton'); } /*Select -> set à défaut*/ function DefaultSelect(heureVol, textArriveeDepart, selectName) { var selected = $('select[name="'+selectName+'"] option:selected'); if(selected.attr('id') != "default"){ selected.removeAttr("selected"); $('select[name="' + selectName + '"]').selectpicker('val', $('select[name="' + selectName +'"] #default').text()); } heureVol.text('Heure'); textArriveeDepart.text($('select[name="' + selectName +'"] #default').text()); } /* Message Erreur Invalide */ function MessageErreurInvalide(message, checkValid, messageText) { if (!checkValid) { var messageErreur = message.find('span[itemprop="3"]'); messageErreur.find('mark').text(messageText); AfficheMessageGenerique2(message.find('span[itemprop="1"]'), 'noDisplayGenerique2'); AfficheMessageGenerique2(message.find('span[itemprop="2"]'), 'noDisplayGenerique2'); AfficheMessageGenerique(message, "displayGenerique"); AfficheMessageGenerique2(messageErreur, "displayGenerique2"); } } /* Recherche des vols */ $("#zoneRecherche").submit(function (event) { event.preventDefault(); var provenance = $('select[name="ProvSearch"] option:selected'); var destination = $('select[name="DestSearch"] option:selected'); var dateVol; /*Récupération dateVol*/ $("#dateVolRecherche input").each(function () { if ($(this).hasClass('displayGenerique2')) { dateVol = $(this).val(); return; } }) var message = $('#MessageErreurProvDest'); var provSuccess = $('select[name="ProvSearch"]').siblings('button').hasClass('success'); var destSuccess = $('select[name="DestSearch"]').siblings('button').hasClass('success'); dateVol = dateVol.replace(/[/]/g, '-'); if (!MessageErreurRecherche(provenance.val(), message, 'provenance') || !MessageErreurRecherche(destination.val(), message, 'destination') || !MessageErreurRecherche(dateVol, message, 'jour du vol')) return; AfficheMessageGenerique2(message, 'noDisplayGenerique2'); if(!CompareProvDest(provenance.val(),destination.val())) return; AfficheMessageGenerique2(message, 'noDisplayGenerique2'); if (provSuccess && destSuccess) { $("#ResultatVol").modal("show"); let urlRechercheVol = urlApi+"/RechercheVols/" + provenance.val() + "/" + destination.val() + "/" + dateVol; /*Lancement de la recherche*/ if (!CookiesExists() || !IsSetCookies(provenance.val(), destination.val(), dateVol)) { /*Enregistrement des valeurs de la recherche*/ SetCookies(provenance.val(), destination.val(),dateVol); /*Nettoyage précédente recherche*/ NettoyageResult($("#RechercheVol tr"), $(".EnvoiOkRechercheVol")); DefaultSelect($("#heureVol"), $("#ResultatSearchVol > thead > tr > .ResultArrivéeOuDépart"), "resultatVol"); /*Appel API*/ $.getJSON(urlRechercheVol, {}) .done(function (data) { if (Object.keys(data).indexOf("message") == -1) { DefaultSelect($("#heureVol"), $("#ResultatSearchVol > thead > tr > .ResultArrivéeOuDépart"), "resultatVol"); Object.keys(data).forEach(function (key) { var ArrDep = (Object.keys(data[key]).indexOf("Arr") !== -1) ? "Arrivée" : "Départ"; addResultVols( $("#RechercheVol"), data[key].Compagnie, data[key].CodeVol, data[key].Provenance, data[key].Destination, data[key].Img, data[key].Date, (ArrDep == "Arrivée") ? data[key].Arr : data[key].Dep, ArrDep, data[key].imgArrDep, "Search", 'RechercheVol', data[key].Statut ); }); /*Contrôle fenetre modal*/ $(".AlertRechercheVol").each(function () { var EnvoiOk = $(".EnvoiOkRechercheVol"); $(this).change(function () { CheckButtonCheckBox(EnvoiOk, $(this)); ControleCheckBox(EnvoiOk, 'RechercheVol'); }); }); /*Paramétrage Bootstrap Toggle Checkbox*/ $('.toggleCheckBox[data-vols="Search"]').bootstrapToggle({ on: 'Suivi', off: 'Non Suivi', onstyle: "success", size: "small", height: 60, width: 85 }); } else { addNoVol($("#RechercheVol")); return; } }); } } else { MessageErreurInvalide(message, provSuccess, 'provenance invalide'); MessageErreurInvalide(message, destSuccess, 'destination invalide'); return; } });
aimanwakidou/SiteAeroport
js/RechercheVol.js
JavaScript
mit
7,968
using System; using System.Collections.Generic; using System.Text; namespace CommandLineDeploymentTool { class Arguments { public string DeployType { get; private set; } public string BackupFolder { get; private set; } public string AppName { get; private set; } public string AppFolder { get; private set; } public string DeployFolder { get; private set; } public string CategoryName { get; private set; } public string FireDaemonPath { get; private set; } public bool Restore { get; set; } public string RestorePath { get; set; } public string ApplicationPoolName { get; private set; } public bool NoBackup { get; private set; } public bool NoStop { get; private set; } public bool NoStart { get; private set; } public Arguments(string[] args, bool fineTuneArgs) { if (fineTuneArgs) { // handles quotations if necessary args = this.FineTune(args); } this.AssignFields(args); } private string[] FineTune(string[] args) { List<string> argList = new List<string>(); foreach (string arg in args) { if (arg.Trim().StartsWith("/")) { argList.Add(arg); } else { string lastItem = argList[argList.Count - 1]; lastItem += " " + arg; argList[argList.Count - 1] = lastItem; } } return argList.ToArray(); } private void AssignFields(string[] args) { foreach (string arg in args) { int indexOfColon = arg.Contains(":") ? arg.IndexOf(':') : arg.Length; string argKey = arg.Substring(1, indexOfColon - 1); string argVal = arg.Length > indexOfColon ? arg.Substring(indexOfColon + 1, arg.Length - indexOfColon - 1) : string.Empty; switch (argKey) { case "deployType": this.DeployType = argVal; break; case "backupFolder": this.BackupFolder = argVal; break; case "appName": this.AppName = argVal; break; case "appFolder": this.AppFolder = argVal; break; case "deployFolder": this.DeployFolder = argVal; break; case "categoryName": this.CategoryName = argVal; break; case "fireDaemonPath": this.FireDaemonPath = argVal; break; case "restore": this.Restore = true; break; case "restorePath": this.RestorePath = argVal; break; case "applicationPool": this.ApplicationPoolName = argVal; break; case "noBackup": this.NoBackup = true; break; case "noStop": this.NoStop = true; break; case "noStart": this.NoStart = true; break; } } } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append(Environment.GetCommandLineArgs()[0]).Append(" "); if (!string.IsNullOrEmpty(this.DeployType)) sb.Append("/deployType:" + this.DeployType).Append(" "); if (!string.IsNullOrEmpty(this.BackupFolder)) sb.Append("/backupFolder:" + this.BackupFolder).Append(" "); if (!string.IsNullOrEmpty(this.AppName)) sb.Append("/appName:" + this.AppName).Append(" "); if (!string.IsNullOrEmpty(this.AppFolder)) sb.Append("/appFolder:" + this.AppFolder).Append(" "); if (!string.IsNullOrEmpty(this.DeployFolder)) sb.Append("/deployFolder:" + this.DeployFolder).Append(" "); if (!string.IsNullOrEmpty(this.CategoryName)) sb.Append("/categoryName:" + this.CategoryName).Append(" "); if (!string.IsNullOrEmpty(this.FireDaemonPath)) sb.Append("/fireDaemonPath:" + this.FireDaemonPath).Append(" "); if (this.Restore) sb.Append("/restore:").Append(" "); if (!string.IsNullOrEmpty(this.RestorePath)) sb.Append("/restorePath:" + this.RestorePath).Append(" "); if (!string.IsNullOrEmpty(this.ApplicationPoolName)) sb.Append("/applicationPool:" + this.ApplicationPoolName).Append(" "); if (this.NoBackup) sb.Append("/noBackup:").Append(" "); if (this.NoStop) sb.Append("/noStop:").Append(" "); if (this.NoStart) sb.Append("/noStart:").Append(" "); return sb.ToString(); } public static string HelpString { get { StringBuilder sb = new StringBuilder(); sb.AppendLine(@"Usage:"); sb.AppendLine(); sb.AppendLine(@"Format : /deployType:<deployType>"); sb.AppendLine(@"Desc. : Type of deployment"); sb.AppendLine(@"Sample : /deployType:COM"); sb.AppendLine(@"Sample : /deployType:EXE"); sb.AppendLine(@"Sample : /deployType:FIREDAEMONAPP"); sb.AppendLine(@"Sample : /deployType:IIS"); sb.AppendLine(@"Sample : /deployType:WINDOWSSERVICE"); sb.AppendLine(); sb.AppendLine(@"Format : /backupRootFolder:<backupRootFolder>"); sb.AppendLine(@"Desc. : Use this pat as a root to backups"); sb.AppendLine(@"Sample : /backupRootFolder:D:\Backups"); sb.AppendLine(); sb.AppendLine(@"Format : /appName:<appName>"); sb.AppendLine(@"Desc. : Name of the application (Generally dll or exe name)"); sb.AppendLine(@"Sample (COM) : /appName:MyApp (dll name)"); sb.AppendLine(@"Sample (EXE) : /appName:MyApp (exe name)"); sb.AppendLine(@"Sample (FIREDAEMONAPP) : /appName:MyApp (name seen in firedaemon)"); sb.AppendLine(@"Sample (IIS) : /appName:MyApp (not important in iis case, you may give anything)"); sb.AppendLine(@"Sample (WINDOWSSERVICE) : /appName:Myapp (exe name)"); sb.AppendLine(); sb.AppendLine(@"Format : /appFolder:<appFolder>"); sb.AppendLine(@"Desc. : Root folder of the application"); sb.AppendLine(@"Sample : /appFolder:D:\MyAppFolder"); sb.AppendLine(); sb.AppendLine(@"Format : /deployFolder:<deployFolder>"); sb.AppendLine(@"Desc. : Root folder of the deployed (new version) application"); sb.AppendLine(@"Sample : /deployFolder:D:\DeployFolder"); sb.AppendLine(); sb.AppendLine(@"Format : /categoryName:<categoryName>"); sb.AppendLine(@"Desc. : Name of the com category (Needed for category shutdown etc.). Only used in COM deployments"); sb.AppendLine(@"Sample : /categoryName:MyAppCategory"); sb.AppendLine(); sb.AppendLine(@"Format : /fireDaemonPath:<fireDaemonPath>"); sb.AppendLine(@"Desc. : Path for the FireDaemon.exe. Only used in FIREDAEMONAPP deployments"); sb.AppendLine(@"Sample : /fireDaemonPath:C:\Program Files\FireDaemon\FireDaemon.exe"); sb.AppendLine(); sb.AppendLine(@"Format : /restore"); sb.AppendLine(@"Desc. : Restore from backup, if the deployment fails. Or if you want to get back to previous version"); sb.AppendLine(); sb.AppendLine(@"Format : /restorePath:<restorePath>"); sb.AppendLine(@"Desc. : Path of the backup from which to restore"); sb.AppendLine(@"Sample : /restorePath:D:\Backups\MyApp\Backup_20150101_013030"); sb.AppendLine(); sb.AppendLine(@"Format : /applicationPool:<applicationPool>"); sb.AppendLine(@"Desc. : Name of the IIS ApplicationPool only used in IIS deployments"); sb.AppendLine(@"Sample : /applicationPool:DefaultAppPool"); sb.AppendLine(); sb.AppendLine(@"Format : /noBackup"); sb.AppendLine(@"Desc. : Bypasses backup step (Normal exection: Backup, Stop, Deploy, Start"); sb.AppendLine(); sb.AppendLine(@"Format : /noStop"); sb.AppendLine(@"Desc. : Bypasses stop step (Normal exection: Backup, Stop, Deploy, Start"); sb.AppendLine(); sb.AppendLine(@"Format : /noStart"); sb.AppendLine(@"Desc. : Bypasses start step (Normal exection: Backup, Stop, Deploy, Start"); return sb.ToString(); } } } }
erdalgokten/CommandLineDeploymentTool
CommandLineDeploymentTool/Arguments.cs
C#
mit
9,801
/* * * ProjectList constants * */ // export const DEFAULT_ACTION = 'app/ProjectList/DEFAULT_ACTION'; export const GET_PROJECTS_OWNED_ACTION = 'app/ProjectList/GET_PROJECTS_OWNED'; export const GET_PROJECTS_OWNED_SUCCESS_ACTION = 'app/ProjectList/GET_PROJECTS_OWNED_SUCCESS'; export const GET_PROJECTS_OWNED_ERROR_ACTION = 'app/ProjectList/GET_PROJECTS_OWNED_ERROR'; export const GET_PROJECTS_ACCESS_ACTION = 'app/ProjectList/GET_PROJECTS_ACCESS'; export const GET_PROJECTS_ACCESS_SUCCESS_ACTION = 'app/ProjectList/GET_PROJECTS_ACCESS_SUCCESS'; export const GET_PROJECTS_ACCESS_ERROR_ACTION = 'app/ProjectList/GET_PROJECTS_ACCESS_ERROR';
VeloCloud/website-ui
app/containers/ProjectList/constants.js
JavaScript
mit
642
from django.core.management import setup_environ import settings setup_environ(settings) from apps.modules.tasks import update_data update_data.delay()
udbhav/eurorack-planner
scripts/update_data.py
Python
mit
167
// // // MIT License // // Copyright (c) 2017 Stellacore Corporation. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject // to the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY // KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS // BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN // AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // /*! \file \brief Definitions for dat::Jump */ #include "libdat/Jump.h" #include "libdat/compare.h" #include <iomanip> #include <sstream> namespace dat { //====================================================================== // explicit Jump :: Jump ( size_t const & ndx , double const & lo , double const & hi ) : theNdx(ndx) , theLo(lo) , theHi(hi) { } // copy constructor -- compiler provided // assignment operator -- compiler provided // destructor -- compiler provided bool Jump :: nearlyEquals ( Jump const & other ) const { bool same(theNdx == other.theNdx); if (same) { same &= dat::nearlyEquals(theLo, other.theLo); same &= dat::nearlyEquals(theHi, other.theHi); } return same; } std::string Jump :: infoString ( std::string const & title ) const { std::ostringstream oss; oss << std::fixed << std::setprecision(3u); oss << title << " " << std::setw(4u) << theNdx << " " << std::setw(9u) << theLo << " " << std::setw(9u) << theHi ; return oss.str(); } //====================================================================== }
transpixel/tpqz
libdat/Jump.cpp
C++
mit
2,242
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("samplemvc")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("samplemvc")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d1809673-942c-4ad3-ae67-80be4e9db5bf")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.2.5.1")] [assembly: AssemblyFileVersion("1.2.5.1")]
dlmelendez/identitydocumentdb
sample/samplemvc/Properties/AssemblyInfo.cs
C#
mit
1,349
import core from 'core-js'; var originStorage = new Map(); function ensureType(value){ if(value instanceof Origin){ return value; } return new Origin(value); } /** * A metadata annotation that describes the origin module of the function to which it's attached. * * @class Origin * @constructor * @param {string} moduleId The origin module id. * @param {string} moduleMember The name of the export in the origin module. */ export class Origin { constructor(moduleId, moduleMember){ this.moduleId = moduleId; this.moduleMember = moduleMember; } /** * Get the Origin annotation for the specified function. * * @method get * @static * @param {Function} fn The function to inspect for Origin metadata. * @return {Origin} Returns the Origin metadata. */ static get(fn){ var origin = originStorage.get(fn); if(origin !== undefined){ return origin; } if(typeof fn.origin === 'function'){ originStorage.set(fn, origin = ensureType(fn.origin())); } else if(fn.origin !== undefined){ originStorage.set(fn, origin = ensureType(fn.origin)); } return origin; } /** * Set the Origin annotation for the specified function. * * @method set * @static * @param {Function} fn The function to set the Origin metadata on. * @param {origin} fn The Origin metadata to store on the function. * @return {Origin} Returns the Origin metadata. */ static set(fn, origin){ if(Origin.get(fn) === undefined){ originStorage.set(fn, origin); } } }
behzad88/aurelia-ts-port
aurelia-latest/metadata/origin.js
JavaScript
mit
1,546
import numpy as np import cv2 import matplotlib.image as mpimg import pickle from line import Line from warp_transformer import WarpTransformer from moviepy.editor import VideoFileClip calibration_mtx_dist_filename = 'dist_pickle.p' # load mtx, dist dist_pickle = pickle.load(open(calibration_mtx_dist_filename, "rb" )) mtx = dist_pickle["mtx"] dist = dist_pickle["dist"] def binary_image_via_threshold(img, s_thresh=(170, 255), sx_thresh=(20, 100)): ''' From Advanced Lane Finding lesson, section 30 ''' img = np.copy(img) # Convert to HLS color space and separate the V channel hls = cv2.cvtColor(img, cv2.COLOR_RGB2HLS).astype(np.float) l_channel = hls[:,:,1] s_channel = hls[:,:,2] # Sobel x sobelx = cv2.Sobel(l_channel, cv2.CV_64F, 1, 0) # Take the derivative in x abs_sobelx = np.absolute(sobelx) # Absolute x derivative to accentuate lines away from horizontal scaled_sobel = np.uint8(255*abs_sobelx/np.max(abs_sobelx)) # Threshold x gradient sxbinary = np.zeros_like(scaled_sobel) sxbinary[(scaled_sobel >= sx_thresh[0]) & (scaled_sobel <= sx_thresh[1])] = 1 # Threshold color channel s_binary = np.zeros_like(s_channel) s_binary[(s_channel >= s_thresh[0]) & (s_channel <= s_thresh[1])] = 1 # combined them here. combined = np.zeros_like(s_channel) combined[(sxbinary == 1) | (s_binary == 1)] = 1 return combined # Perspective transform src = np.array([[262, 677], [580, 460], [703, 460], [1040, 677]]).astype(np.float32) dst = np.array([[262, 720], [262, 0], [1040, 0], [1040, 720]]).astype(np.float32) # Create transformer object transformer = WarpTransformer(src, dst) left_line = Line() right_line = Line() def non_sliding(binary_warped, line): nonzero = binary_warped.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) margin = 100 left_fit = left_line.current_fit right_fit = right_line.current_fit left_lane_inds = ((nonzerox > (left_fit[0]*(nonzeroy**2) + left_fit[1]*nonzeroy + left_fit[2] - margin)) & (nonzerox < (left_fit[0]*(nonzeroy**2) + left_fit[1]*nonzeroy + left_fit[2] + margin))) right_lane_inds = ((nonzerox > (right_fit[0]*(nonzeroy**2) + right_fit[1]*nonzeroy + right_fit[2] - margin)) & (nonzerox < (right_fit[0]*(nonzeroy**2) + right_fit[1]*nonzeroy + right_fit[2] + margin))) # Extract left and right line pixel positions leftx = nonzerox[left_lane_inds] lefty = nonzeroy[left_lane_inds] rightx = nonzerox[right_lane_inds] righty = nonzeroy[right_lane_inds] if line == 'left': return leftx, lefty elif line == 'right': return rightx, righty def sliding_window(binary_warped, line): out_img = (np.dstack((binary_warped, binary_warped, binary_warped)) * 255).astype(np.uint8) histogram = np.sum(binary_warped[int(binary_warped.shape[0]/2):,:], axis=0) # Find the peak of the left and right halves of the histogram # These will be the starting point for the left and right lines midpoint = np.int(histogram.shape[0]/2) leftx_base = np.argmax(histogram[:midpoint]) rightx_base = np.argmax(histogram[midpoint:]) + midpoint # Choose the number of sliding windows nwindows = 9 # Set height of windows window_height = np.int(binary_warped.shape[0]/nwindows) # Identify the x and y positions of all nonzero pixels in the image nonzero = binary_warped.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) # Current positions to be updated for each window leftx_current = leftx_base rightx_current = rightx_base # Set the width of the windows +/- margin margin = 100 # Set minimum number of pixels found to recenter window minpix = 50 # Create empty lists to receive left and right lane pixel indices left_lane_inds = [] right_lane_inds = [] # Step through the windows one by one for window in range(nwindows): # Identify window boundaries in x and y (and right and left) win_y_low = binary_warped.shape[0] - (window+1)*window_height win_y_high = binary_warped.shape[0] - window*window_height win_xleft_low = leftx_current - margin win_xleft_high = leftx_current + margin win_xright_low = rightx_current - margin win_xright_high = rightx_current + margin # Draw the windows on the visualization image cv2.rectangle(out_img, (win_xleft_low,win_y_low), (win_xleft_high,win_y_high), color=(0,255,0), thickness=2) # Green cv2.rectangle(out_img, (win_xright_low,win_y_low), (win_xright_high,win_y_high), color=(0,255,0), thickness=2) # Green # Identify the nonzero pixels in x and y within the window good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0] good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0] # Append these indices to the lists left_lane_inds.append(good_left_inds) right_lane_inds.append(good_right_inds) # If you found > minpix pixels, recenter next window on their mean position if len(good_left_inds) > minpix: leftx_current = np.int(np.mean(nonzerox[good_left_inds])) if len(good_right_inds) > minpix: rightx_current = np.int(np.mean(nonzerox[good_right_inds])) # Concatenate the arrays of indices left_lane_inds = np.concatenate(left_lane_inds) right_lane_inds = np.concatenate(right_lane_inds) # Extract left and right line pixel positions leftx = nonzerox[left_lane_inds] lefty = nonzeroy[left_lane_inds] rightx = nonzerox[right_lane_inds] righty = nonzeroy[right_lane_inds] if line == 'left': return leftx, lefty elif line == 'right': return rightx, righty def pipeline(start_img): ''' Incoming image must be RGB!! ''' undist = cv2.undistort(start_img, mtx, dist, None, mtx) combined = binary_image_via_threshold(undist) binary_warped = transformer.to_birdview(combined) # Check if line was detected in previous frame: if left_line.detected == True: leftx, lefty = non_sliding(binary_warped, 'left') elif left_line.detected == False: leftx, lefty = sliding_window(binary_warped, 'left') left_line.detected = True if right_line.detected == True: rightx, righty = non_sliding(binary_warped, 'right') elif right_line.detected == False: rightx, righty = sliding_window(binary_warped, 'right') right_line.detected = True # Fit a second order polynomial to each left_fit = np.polyfit(lefty, leftx, 2) right_fit = np.polyfit(righty, rightx, 2) # Stash away polynomials left_line.current_fit = left_fit right_line.current_fit = right_fit # Generate x and y values for plotting ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0]) left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2] right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2] # Define conversions in x and y from pixels space to meters ym_per_pix = 30/720 # meters per pixel in y dimension xm_per_pix = 3.7/700 # meters per pixel in x dimension # Fit new polynomials to x,y in world space left_fit_cr = np.polyfit(lefty*ym_per_pix, leftx*xm_per_pix, deg=2) right_fit_cr = np.polyfit(righty*ym_per_pix, rightx*xm_per_pix, deg=2) # Calculate radii of curvature in meters y_eval = np.max(ploty) # Where radius of curvature is measured left_curverad = ((1 + (2*left_fit_cr[0]*y_eval*ym_per_pix + left_fit_cr[1])**2)**1.5) / np.absolute(2*left_fit_cr[0]) right_curverad = ((1 + (2*right_fit_cr[0]*y_eval*ym_per_pix + right_fit_cr[1])**2)**1.5) / np.absolute(2*right_fit_cr[0]) midpoint = np.int(start_img.shape[1]/2) middle_of_lane = (right_fitx[-1] - left_fitx[-1]) / 2.0 + left_fitx[-1] offset = (midpoint - middle_of_lane) * xm_per_pix # Create an image to draw the lines on warped_zero = np.zeros_like(binary_warped).astype(np.uint8) color_warped = np.dstack((warped_zero, warped_zero, warped_zero)) # Recast the x and y points into usable format for cv2.fillPoly() pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))]) pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))]) pts = np.hstack((pts_left, pts_right)) # Draw the lane onto the warped blank image cv2.fillPoly(color_warped, np.int_([pts]), (0,255, 0)) # Warp the blank back to original image space using inverse perspective matrix (Minv) unwarped = transformer.to_normal(color_warped) # Combine the result with the original image result = cv2.addWeighted(undist, 1, unwarped, 0.3, 0) radius = np.mean([left_curverad, right_curverad]) # Add radius and offset calculations to top of video cv2.putText(result,"Curvature Radius: " + "{:0.2f}".format(radius) + ' m', org=(50,50), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=2, color=(0,0,0), lineType = cv2.LINE_AA, thickness=2) cv2.putText(result,"Lane center offset: " + "{:0.2f}".format(offset) + ' m', org=(50,100), fontFace=cv2.FONT_HERSHEY_SIMPLEX, fontScale=2, color=(0,0,0), lineType = cv2.LINE_AA, thickness=2) return result if __name__ == '__main__': movie_output = 'final_output.mp4' clip1 = VideoFileClip("project_video.mp4") driving_clip = clip1.fl_image(pipeline) driving_clip.write_videofile(movie_output, audio=False)
mez/carnd
P4_advance_lane_finding/main.py
Python
mit
9,709
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MyFramework.ServiceModel { /// <summary> /// 通用的服务返回结果. /// </summary> public class CommonServiceResult<T> { public CommonServiceResult() { } public CommonServiceResult(Exception ex) { this.ResultCode = "SYSTEM_EXCEPTION"; this.ResultMessage = ex.Message; } /// <summary> /// 结果码. /// </summary> public string ResultCode { set; get; } /// <summary> /// 结果消息. /// </summary> public string ResultMessage { set; get; } /// <summary> /// 结果数据. /// </summary> public T ResultData { set; get; } /// <summary> /// 是否执行成功. /// </summary> public bool IsSuccess { get { return this.ResultCode == ResultCodeIsSuccess; } } public override string ToString() { StringBuilder buff = new StringBuilder(); buff.AppendLine(this.ResultCode.ToString()); buff.AppendLine(this.ResultMessage); return buff.ToString(); } /// <summary> /// 处理成功. /// </summary> public const string ResultCodeIsSuccess = "0"; /// <summary> /// 默认的,成功的执行结果. /// </summary> public static readonly CommonServiceResult<T> DefaultSuccessResult = new CommonServiceResult<T>() { ResultCode = ResultCodeIsSuccess, ResultMessage = "success", }; /// <summary> /// 数据不存在. /// </summary> public const string ResultCodeIsDataNotFound = "COMMON_DATA_NOT_FOUND"; /// <summary> /// 默认的,数据不存在的执行结果. /// </summary> public static readonly CommonServiceResult<T> DataNotFoundResult = new CommonServiceResult<T>() { ResultCode = ResultCodeIsDataNotFound, ResultMessage = "数据不存在!", }; /// <summary> /// 数据已存在. /// </summary> public const string ResultCodeIsDataHadExists = "COMMON_DATA_HAD_EXISTS"; /// <summary> /// 默认的,数据已存在的执行结果. /// </summary> public static readonly CommonServiceResult<T> DataHadExistsResult = new CommonServiceResult<T>() { ResultCode = ResultCodeIsDataHadExists, ResultMessage = "数据已存在!", }; /// <summary> /// 创建默认的成功的结果. /// </summary> /// <param name="resultData"></param> /// <returns></returns> public static CommonServiceResult<T> CreateDefaultSuccessResult(T resultData) { CommonServiceResult<T> result = new CommonServiceResult<T>() { ResultCode = ResultCodeIsSuccess, ResultMessage = "success", ResultData = resultData }; return result; } /// <summary> /// 复制结果. /// </summary> /// <param name="commonServiceResult"></param> /// <returns></returns> public static CommonServiceResult<T> CopyFrom(CommonServiceResult commonServiceResult) { CommonServiceResult<T> result = new CommonServiceResult<T>() { ResultCode = commonServiceResult.ResultCode, ResultMessage = commonServiceResult.ResultMessage }; return result; } } public class CommonServiceResult : CommonServiceResult<dynamic> { public CommonServiceResult() { } public CommonServiceResult(Exception ex) { this.ResultCode = "SYSTEM_EXCEPTION"; this.ResultMessage = ex.Message; } /// <summary> /// 默认的,成功的执行结果. /// </summary> public new static readonly CommonServiceResult DefaultSuccessResult = new CommonServiceResult() { ResultCode = ResultCodeIsSuccess, ResultMessage = "success", }; /// <summary> /// 默认的,数据不存在的执行结果. /// </summary> public new static readonly CommonServiceResult DataNotFoundResult = new CommonServiceResult() { ResultCode = ResultCodeIsDataNotFound, ResultMessage = "数据不存在!", }; /// <summary> /// 默认的,数据已存在的执行结果. /// </summary> public new static readonly CommonServiceResult DataHadExistsResult = new CommonServiceResult() { ResultCode = ResultCodeIsDataHadExists, ResultMessage = "数据已存在!", }; /// <summary> /// 创建默认的成功的结果. /// </summary> /// <param name="resultData"></param> /// <returns></returns> public new static CommonServiceResult CreateDefaultSuccessResult(dynamic resultData) { CommonServiceResult result = new CommonServiceResult() { ResultCode = ResultCodeIsSuccess, ResultMessage = "success", ResultData = resultData }; return result; } } }
wangzhiqing999/my-csharp-project
MyFramework.Service/ServiceModel/CommonServiceResult.cs
C#
mit
5,657
/** * @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 */ import {CommonModule, Location} from '@angular/common'; import {SpyLocation} from '@angular/common/testing'; import {ChangeDetectionStrategy, Component, Injectable, NgModule, NgModuleFactoryLoader, NgModuleRef, NgZone, OnDestroy, ɵConsole as Console, ɵNoopNgZone as NoopNgZone} from '@angular/core'; import {ComponentFixture, TestBed, fakeAsync, inject, tick} from '@angular/core/testing'; import {By} from '@angular/platform-browser/src/dom/debug/by'; import {expect} from '@angular/platform-browser/testing/src/matchers'; import {ActivatedRoute, ActivatedRouteSnapshot, ActivationEnd, ActivationStart, CanActivate, CanDeactivate, ChildActivationEnd, ChildActivationStart, DefaultUrlSerializer, DetachedRouteHandle, Event, GuardsCheckEnd, GuardsCheckStart, Navigation, NavigationCancel, NavigationEnd, NavigationError, NavigationStart, PRIMARY_OUTLET, ParamMap, Params, PreloadAllModules, PreloadingStrategy, Resolve, ResolveEnd, ResolveStart, RouteConfigLoadEnd, RouteConfigLoadStart, RouteReuseStrategy, Router, RouterEvent, RouterModule, RouterPreloader, RouterStateSnapshot, RoutesRecognized, RunGuardsAndResolvers, UrlHandlingStrategy, UrlSegmentGroup, UrlSerializer, UrlTree} from '@angular/router'; import {Observable, Observer, Subscription, of } from 'rxjs'; import {filter, first, map, tap} from 'rxjs/operators'; import {forEach} from '../src/utils/collection'; import {RouterTestingModule, SpyNgModuleFactoryLoader} from '../testing'; describe('Integration', () => { const noopConsole: Console = {log() {}, warn() {}}; beforeEach(() => { TestBed.configureTestingModule({ imports: [RouterTestingModule.withRoutes([{path: 'simple', component: SimpleCmp}]), TestModule], providers: [{provide: Console, useValue: noopConsole}] }); }); it('should navigate with a provided config', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.navigateByUrl('/simple'); advance(fixture); expect(location.path()).toEqual('/simple'); }))); it('should navigate from ngOnInit hook', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { router.resetConfig([ {path: '', component: SimpleCmp}, {path: 'one', component: RouteCmp}, ]); const fixture = createRoot(router, RootCmpWithOnInit); expect(location.path()).toEqual('/one'); expect(fixture.nativeElement).toHaveText('route'); }))); describe('navigation', function() { it('should navigate to the current URL', fakeAsync(inject([Router], (router: Router) => { router.onSameUrlNavigation = 'reload'; router.resetConfig([ {path: '', component: SimpleCmp}, {path: 'simple', component: SimpleCmp}, ]); const fixture = createRoot(router, RootCmp); const events: Event[] = []; router.events.subscribe(e => onlyNavigationStartAndEnd(e) && events.push(e)); router.navigateByUrl('/simple'); tick(); router.navigateByUrl('/simple'); tick(); expectEvents(events, [ [NavigationStart, '/simple'], [NavigationEnd, '/simple'], [NavigationStart, '/simple'], [NavigationEnd, '/simple'] ]); }))); describe('relativeLinkResolution', () => { beforeEach(inject([Router], (router: Router) => { router.resetConfig([{ path: 'foo', children: [{path: 'bar', children: [{path: '', component: RelativeLinkCmp}]}] }]); })); it('should not ignore empty paths in legacy mode', fakeAsync(inject([Router], (router: Router) => { router.relativeLinkResolution = 'legacy'; const fixture = createRoot(router, RootCmp); router.navigateByUrl('/foo/bar'); advance(fixture); const link = fixture.nativeElement.querySelector('a'); expect(link.getAttribute('href')).toEqual('/foo/bar/simple'); }))); it('should ignore empty paths in corrected mode', fakeAsync(inject([Router], (router: Router) => { router.relativeLinkResolution = 'corrected'; const fixture = createRoot(router, RootCmp); router.navigateByUrl('/foo/bar'); advance(fixture); const link = fixture.nativeElement.querySelector('a'); expect(link.getAttribute('href')).toEqual('/foo/simple'); }))); }); it('should set the restoredState to null when executing imperative navigations', fakeAsync(inject([Router], (router: Router) => { router.resetConfig([ {path: '', component: SimpleCmp}, {path: 'simple', component: SimpleCmp}, ]); const fixture = createRoot(router, RootCmp); let event: NavigationStart; router.events.subscribe(e => { if (e instanceof NavigationStart) { event = e; } }); router.navigateByUrl('/simple'); tick(); expect(event !.navigationTrigger).toEqual('imperative'); expect(event !.restoredState).toEqual(null); }))); it('should set history.state if passed using imperative navigation', fakeAsync(inject([Router, Location], (router: Router, location: SpyLocation) => { router.resetConfig([ {path: '', component: SimpleCmp}, {path: 'simple', component: SimpleCmp}, ]); const fixture = createRoot(router, RootCmp); let navigation: Navigation = null !; router.events.subscribe(e => { if (e instanceof NavigationStart) { navigation = router.getCurrentNavigation() !; } }); router.navigateByUrl('/simple', {state: {foo: 'bar'}}); tick(); const history = (location as any)._history; expect(history[history.length - 1].state.foo).toBe('bar'); expect(history[history.length - 1].state) .toEqual({foo: 'bar', navigationId: history.length}); expect(navigation.extras.state).toBeDefined(); expect(navigation.extras.state).toEqual({foo: 'bar'}); }))); it('should not pollute browser history when replaceUrl is set to true', fakeAsync(inject([Router, Location], (router: Router, location: SpyLocation) => { router.resetConfig([ {path: '', component: SimpleCmp}, {path: 'a', component: SimpleCmp}, {path: 'b', component: SimpleCmp} ]); const fixture = createRoot(router, RootCmp); router.navigateByUrl('/a', {replaceUrl: true}); router.navigateByUrl('/b', {replaceUrl: true}); tick(); expect(location.urlChanges).toEqual(['replace: /', 'replace: /b']); }))); it('should skip navigation if another navigation is already scheduled', fakeAsync(inject([Router, Location], (router: Router, location: SpyLocation) => { router.resetConfig([ {path: '', component: SimpleCmp}, {path: 'a', component: SimpleCmp}, {path: 'b', component: SimpleCmp} ]); const fixture = createRoot(router, RootCmp); router.navigate( ['/a'], {queryParams: {a: true}, queryParamsHandling: 'merge', replaceUrl: true}); router.navigate( ['/b'], {queryParams: {b: true}, queryParamsHandling: 'merge', replaceUrl: true}); tick(); /** * Why do we have '/b?b=true' and not '/b?a=true&b=true'? * * This is because the router has the right to stop a navigation mid-flight if another * navigation has been already scheduled. This is why we can use a top-level guard * to perform redirects. Calling `navigate` in such a guard will stop the navigation, and * the components won't be instantiated. * * This is a fundamental property of the router: it only cares about its latest state. * * This means that components should only map params to something else, not reduce them. * In other words, the following component is asking for trouble: * * ``` * class MyComponent { * constructor(a: ActivatedRoute) { * a.params.scan(...) * } * } * ``` * * This also means "queryParamsHandling: 'merge'" should only be used to merge with * long-living query parameters (e.g., debug). */ expect(router.url).toEqual('/b?b=true'); }))); }); describe('navigation warning', () => { let warnings: string[] = []; class MockConsole { warn(message: string) { warnings.push(message); } } beforeEach(() => { warnings = []; TestBed.overrideProvider(Console, {useValue: new MockConsole()}); }); describe('with NgZone enabled', () => { it('should warn when triggered outside Angular zone', fakeAsync(inject([Router, NgZone], (router: Router, ngZone: NgZone) => { ngZone.runOutsideAngular(() => { router.navigateByUrl('/simple'); }); expect(warnings.length).toBe(1); expect(warnings[0]) .toBe( `Navigation triggered outside Angular zone, did you forget to call 'ngZone.run()'?`); }))); it('should not warn when triggered inside Angular zone', fakeAsync(inject([Router, NgZone], (router: Router, ngZone: NgZone) => { ngZone.run(() => { router.navigateByUrl('/simple'); }); expect(warnings.length).toBe(0); }))); }); describe('with NgZone disabled', () => { beforeEach(() => { TestBed.overrideProvider(NgZone, {useValue: new NoopNgZone()}); }); it('should not warn when triggered outside Angular zone', fakeAsync(inject([Router, NgZone], (router: Router, ngZone: NgZone) => { ngZone.runOutsideAngular(() => { router.navigateByUrl('/simple'); }); expect(warnings.length).toBe(0); }))); }); }); describe('should execute navigations serially', () => { let log: any[] = []; beforeEach(() => { log = []; TestBed.configureTestingModule({ providers: [ { provide: 'trueRightAway', useValue: () => { log.push('trueRightAway'); return true; } }, { provide: 'trueIn2Seconds', useValue: () => { log.push('trueIn2Seconds-start'); let res: any = null; const p = new Promise(r => res = r); setTimeout(() => { log.push('trueIn2Seconds-end'); res(true); }, 2000); return p; } } ] }); }); describe('should advance the parent route after deactivating its children', () => { @Component({template: '<router-outlet></router-outlet>'}) class Parent { constructor(route: ActivatedRoute) { route.params.subscribe((s: any) => { log.push(s); }); } } @Component({template: 'child1'}) class Child1 { ngOnDestroy() { log.push('child1 destroy'); } } @Component({template: 'child2'}) class Child2 { constructor() { log.push('child2 constructor'); } } @NgModule({ declarations: [Parent, Child1, Child2], entryComponents: [Parent, Child1, Child2], imports: [RouterModule] }) class TestModule { } beforeEach(() => TestBed.configureTestingModule({imports: [TestModule]})); it('should work', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'parent/:id', component: Parent, children: [ {path: 'child1', component: Child1}, {path: 'child2', component: Child2}, ] }]); router.navigateByUrl('/parent/1/child1'); advance(fixture); router.navigateByUrl('/parent/2/child2'); advance(fixture); expect(location.path()).toEqual('/parent/2/child2'); expect(log).toEqual([ {id: '1'}, 'child1 destroy', {id: '2'}, 'child2 constructor', ]); }))); }); it('should not wait for prior navigations to start a new navigation', fakeAsync(inject([Router, Location], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'a', component: SimpleCmp, canActivate: ['trueRightAway', 'trueIn2Seconds']}, {path: 'b', component: SimpleCmp, canActivate: ['trueRightAway', 'trueIn2Seconds']} ]); router.navigateByUrl('/a'); tick(100); fixture.detectChanges(); router.navigateByUrl('/b'); tick(100); // 200 fixture.detectChanges(); expect(log).toEqual( ['trueRightAway', 'trueIn2Seconds-start', 'trueRightAway', 'trueIn2Seconds-start']); tick(2000); // 2200 fixture.detectChanges(); expect(log).toEqual([ 'trueRightAway', 'trueIn2Seconds-start', 'trueRightAway', 'trueIn2Seconds-start', 'trueIn2Seconds-end', 'trueIn2Seconds-end' ]); }))); }); it('Should work inside ChangeDetectionStrategy.OnPush components', fakeAsync(() => { @Component({ selector: 'root-cmp', template: `<router-outlet></router-outlet>`, changeDetection: ChangeDetectionStrategy.OnPush, }) class OnPushOutlet { } @Component({selector: 'need-cd', template: `{{'it works!'}}`}) class NeedCdCmp { } @NgModule({ declarations: [OnPushOutlet, NeedCdCmp], entryComponents: [OnPushOutlet, NeedCdCmp], imports: [RouterModule], }) class TestModule { } TestBed.configureTestingModule({imports: [TestModule]}); const router: Router = TestBed.get(Router); const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'on', component: OnPushOutlet, children: [{ path: 'push', component: NeedCdCmp, }], }]); advance(fixture); router.navigateByUrl('on'); advance(fixture); router.navigateByUrl('on/push'); advance(fixture); expect(fixture.nativeElement).toHaveText('it works!'); })); it('should not error when no url left and no children are matching', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [{path: 'simple', component: SimpleCmp}] }]); router.navigateByUrl('/team/33/simple'); advance(fixture); expect(location.path()).toEqual('/team/33/simple'); expect(fixture.nativeElement).toHaveText('team 33 [ simple, right: ]'); router.navigateByUrl('/team/33'); advance(fixture); expect(location.path()).toEqual('/team/33'); expect(fixture.nativeElement).toHaveText('team 33 [ , right: ]'); }))); it('should work when an outlet is in an ngIf', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'child', component: OutletInNgIf, children: [{path: 'simple', component: SimpleCmp}] }]); router.navigateByUrl('/child/simple'); advance(fixture); expect(location.path()).toEqual('/child/simple'); }))); it('should work when an outlet is added/removed', fakeAsync(() => { @Component({ selector: 'someRoot', template: `[<div *ngIf="cond"><router-outlet></router-outlet></div>]` }) class RootCmpWithLink { cond: boolean = true; } TestBed.configureTestingModule({declarations: [RootCmpWithLink]}); const router: Router = TestBed.get(Router); const fixture = createRoot(router, RootCmpWithLink); router.resetConfig([ {path: 'simple', component: SimpleCmp}, {path: 'blank', component: BlankCmp}, ]); router.navigateByUrl('/simple'); advance(fixture); expect(fixture.nativeElement).toHaveText('[simple]'); fixture.componentInstance.cond = false; advance(fixture); expect(fixture.nativeElement).toHaveText('[]'); fixture.componentInstance.cond = true; advance(fixture); expect(fixture.nativeElement).toHaveText('[simple]'); })); it('should update location when navigating', fakeAsync(() => { @Component({template: `record`}) class RecordLocationCmp { private storedPath: string; constructor(loc: Location) { this.storedPath = loc.path(); } } @NgModule({declarations: [RecordLocationCmp], entryComponents: [RecordLocationCmp]}) class TestModule { } TestBed.configureTestingModule({imports: [TestModule]}); const router = TestBed.get(Router); const location = TestBed.get(Location); const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'record/:id', component: RecordLocationCmp}]); router.navigateByUrl('/record/22'); advance(fixture); const c = fixture.debugElement.children[1].componentInstance; expect(location.path()).toEqual('/record/22'); expect(c.storedPath).toEqual('/record/22'); router.navigateByUrl('/record/33'); advance(fixture); expect(location.path()).toEqual('/record/33'); })); it('should skip location update when using NavigationExtras.skipLocationChange with navigateByUrl', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = TestBed.createComponent(RootCmp); advance(fixture); router.resetConfig([{path: 'team/:id', component: TeamCmp}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); expect(fixture.nativeElement).toHaveText('team 22 [ , right: ]'); router.navigateByUrl('/team/33', {skipLocationChange: true}); advance(fixture); expect(location.path()).toEqual('/team/22'); expect(fixture.nativeElement).toHaveText('team 33 [ , right: ]'); }))); it('should skip location update when using NavigationExtras.skipLocationChange with navigate', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = TestBed.createComponent(RootCmp); advance(fixture); router.resetConfig([{path: 'team/:id', component: TeamCmp}]); router.navigate(['/team/22']); advance(fixture); expect(location.path()).toEqual('/team/22'); expect(fixture.nativeElement).toHaveText('team 22 [ , right: ]'); router.navigate(['/team/33'], {skipLocationChange: true}); advance(fixture); expect(location.path()).toEqual('/team/22'); expect(fixture.nativeElement).toHaveText('team 33 [ , right: ]'); }))); it('should navigate after navigation with skipLocationChange', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = TestBed.createComponent(RootCmpWithNamedOutlet); advance(fixture); router.resetConfig([{path: 'show', outlet: 'main', component: SimpleCmp}]); router.navigate([{outlets: {main: 'show'}}], {skipLocationChange: true}); advance(fixture); expect(location.path()).toEqual(''); expect(fixture.nativeElement).toHaveText('main [simple]'); router.navigate([{outlets: {main: null}}], {skipLocationChange: true}); advance(fixture); expect(location.path()).toEqual(''); expect(fixture.nativeElement).toHaveText('main []'); }))); describe('"eager" urlUpdateStrategy', () => { beforeEach(() => { const serializer = new DefaultUrlSerializer(); TestBed.configureTestingModule({ providers: [{ provide: 'authGuardFail', useValue: (a: any, b: any) => { return new Promise(res => { setTimeout(() => res(serializer.parse('/login')), 1); }); } }] }); }); it('should eagerly update the URL with urlUpdateStrategy="eagar"', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = TestBed.createComponent(RootCmp); advance(fixture); router.resetConfig([{path: 'team/:id', component: TeamCmp}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); expect(fixture.nativeElement).toHaveText('team 22 [ , right: ]'); router.urlUpdateStrategy = 'eager'; (router as any).hooks.beforePreactivation = () => { expect(location.path()).toEqual('/team/33'); expect(fixture.nativeElement).toHaveText('team 22 [ , right: ]'); return of (null); }; router.navigateByUrl('/team/33'); advance(fixture); expect(fixture.nativeElement).toHaveText('team 33 [ , right: ]'); }))); it('should eagerly update the URL with urlUpdateStrategy="eagar"', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = TestBed.createComponent(RootCmp); advance(fixture); router.urlUpdateStrategy = 'eager'; router.resetConfig([ {path: 'team/:id', component: SimpleCmp, canActivate: ['authGuardFail']}, {path: 'login', component: AbsoluteSimpleLinkCmp} ]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); // Redirects to /login advance(fixture, 1); expect(location.path()).toEqual('/login'); // Perform the same logic again, and it should produce the same result router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); // Redirects to /login advance(fixture, 1); expect(location.path()).toEqual('/login'); }))); it('should eagerly update URL after redirects are applied with urlUpdateStrategy="eagar"', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = TestBed.createComponent(RootCmp); advance(fixture); router.resetConfig([{path: 'team/:id', component: TeamCmp}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); expect(fixture.nativeElement).toHaveText('team 22 [ , right: ]'); router.urlUpdateStrategy = 'eager'; let urlAtNavStart = ''; let urlAtRoutesRecognized = ''; router.events.subscribe(e => { if (e instanceof NavigationStart) { urlAtNavStart = location.path(); } if (e instanceof RoutesRecognized) { urlAtRoutesRecognized = location.path(); } }); router.navigateByUrl('/team/33'); advance(fixture); expect(urlAtNavStart).toBe('/team/22'); expect(urlAtRoutesRecognized).toBe('/team/33'); expect(fixture.nativeElement).toHaveText('team 33 [ , right: ]'); }))); }); it('should navigate back and forward', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [{path: 'simple', component: SimpleCmp}, {path: 'user/:name', component: UserCmp}] }]); let event: NavigationStart; router.events.subscribe(e => { if (e instanceof NavigationStart) { event = e; } }); router.navigateByUrl('/team/33/simple'); advance(fixture); expect(location.path()).toEqual('/team/33/simple'); const simpleNavStart = event !; router.navigateByUrl('/team/22/user/victor'); advance(fixture); const userVictorNavStart = event !; location.back(); advance(fixture); expect(location.path()).toEqual('/team/33/simple'); expect(event !.navigationTrigger).toEqual('hashchange'); expect(event !.restoredState !.navigationId).toEqual(simpleNavStart.id); location.forward(); advance(fixture); expect(location.path()).toEqual('/team/22/user/victor'); expect(event !.navigationTrigger).toEqual('hashchange'); expect(event !.restoredState !.navigationId).toEqual(userVictorNavStart.id); }))); it('should navigate to the same url when config changes', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'a', component: SimpleCmp}]); router.navigate(['/a']); advance(fixture); expect(location.path()).toEqual('/a'); expect(fixture.nativeElement).toHaveText('simple'); router.resetConfig([{path: 'a', component: RouteCmp}]); router.navigate(['/a']); advance(fixture); expect(location.path()).toEqual('/a'); expect(fixture.nativeElement).toHaveText('route'); }))); it('should navigate when locations changes', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [{path: 'user/:name', component: UserCmp}] }]); const recordedEvents: any[] = []; router.events.forEach(e => onlyNavigationStartAndEnd(e) && recordedEvents.push(e)); router.navigateByUrl('/team/22/user/victor'); advance(fixture); (<any>location).simulateHashChange('/team/22/user/fedor'); advance(fixture); (<any>location).simulateUrlPop('/team/22/user/fedor'); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ user fedor, right: ]'); expectEvents(recordedEvents, [ [NavigationStart, '/team/22/user/victor'], [NavigationEnd, '/team/22/user/victor'], [NavigationStart, '/team/22/user/fedor'], [NavigationEnd, '/team/22/user/fedor'] ]); }))); it('should update the location when the matched route does not change', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{path: '**', component: CollectParamsCmp}]); router.navigateByUrl('/one/two'); advance(fixture); const cmp = fixture.debugElement.children[1].componentInstance; expect(location.path()).toEqual('/one/two'); expect(fixture.nativeElement).toHaveText('collect-params'); expect(cmp.recordedUrls()).toEqual(['one/two']); router.navigateByUrl('/three/four'); advance(fixture); expect(location.path()).toEqual('/three/four'); expect(fixture.nativeElement).toHaveText('collect-params'); expect(cmp.recordedUrls()).toEqual(['one/two', 'three/four']); }))); describe('should reset location if a navigation by location is successful', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [{ provide: 'in1Second', useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { let res: any = null; const p = new Promise(_ => res = _); setTimeout(() => res(true), 1000); return p; } }] }); }); it('work', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'simple', component: SimpleCmp, canActivate: ['in1Second']}]); // Trigger two location changes to the same URL. // Because of the guard the order will look as follows: // - location change 'simple' // - start processing the change, start a guard // - location change 'simple' // - the first location change gets canceled, the URL gets reset to '/' // - the second location change gets finished, the URL should be reset to '/simple' (<any>location).simulateUrlPop('/simple'); (<any>location).simulateUrlPop('/simple'); tick(2000); advance(fixture); expect(location.path()).toEqual('/simple'); }))); }); it('should support secondary routes', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [ {path: 'user/:name', component: UserCmp}, {path: 'simple', component: SimpleCmp, outlet: 'right'} ] }]); router.navigateByUrl('/team/22/(user/victor//right:simple)'); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ user victor, right: simple ]'); }))); it('should support secondary routes in separate commands', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [ {path: 'user/:name', component: UserCmp}, {path: 'simple', component: SimpleCmp, outlet: 'right'} ] }]); router.navigateByUrl('/team/22/user/victor'); advance(fixture); router.navigate(['team/22', {outlets: {right: 'simple'}}]); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ user victor, right: simple ]'); }))); it('should deactivate outlets', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [ {path: 'user/:name', component: UserCmp}, {path: 'simple', component: SimpleCmp, outlet: 'right'} ] }]); router.navigateByUrl('/team/22/(user/victor//right:simple)'); advance(fixture); router.navigateByUrl('/team/22/user/victor'); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ user victor, right: ]'); }))); it('should deactivate nested outlets', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'team/:id', component: TeamCmp, children: [ {path: 'user/:name', component: UserCmp}, {path: 'simple', component: SimpleCmp, outlet: 'right'} ] }, {path: '', component: BlankCmp} ]); router.navigateByUrl('/team/22/(user/victor//right:simple)'); advance(fixture); router.navigateByUrl('/'); advance(fixture); expect(fixture.nativeElement).toHaveText(''); }))); it('should set query params and fragment', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'query', component: QueryParamsAndFragmentCmp}]); router.navigateByUrl('/query?name=1#fragment1'); advance(fixture); expect(fixture.nativeElement).toHaveText('query: 1 fragment: fragment1'); router.navigateByUrl('/query?name=2#fragment2'); advance(fixture); expect(fixture.nativeElement).toHaveText('query: 2 fragment: fragment2'); }))); it('should ignore null and undefined query params', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'query', component: EmptyQueryParamsCmp}]); router.navigate(['query'], {queryParams: {name: 1, age: null, page: undefined}}); advance(fixture); const cmp = fixture.debugElement.children[1].componentInstance; expect(cmp.recordedParams).toEqual([{name: '1'}]); }))); it('should throw an error when one of the commands is null/undefined', fakeAsync(inject([Router], (router: Router) => { createRoot(router, RootCmp); router.resetConfig([{path: 'query', component: EmptyQueryParamsCmp}]); expect(() => router.navigate([ undefined, 'query' ])).toThrowError(`The requested path contains undefined segment at index 0`); }))); it('should push params only when they change', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [{path: 'user/:name', component: UserCmp}] }]); router.navigateByUrl('/team/22/user/victor'); advance(fixture); const team = fixture.debugElement.children[1].componentInstance; const user = fixture.debugElement.children[1].children[1].componentInstance; expect(team.recordedParams).toEqual([{id: '22'}]); expect(team.snapshotParams).toEqual([{id: '22'}]); expect(user.recordedParams).toEqual([{name: 'victor'}]); expect(user.snapshotParams).toEqual([{name: 'victor'}]); router.navigateByUrl('/team/22/user/fedor'); advance(fixture); expect(team.recordedParams).toEqual([{id: '22'}]); expect(team.snapshotParams).toEqual([{id: '22'}]); expect(user.recordedParams).toEqual([{name: 'victor'}, {name: 'fedor'}]); expect(user.snapshotParams).toEqual([{name: 'victor'}, {name: 'fedor'}]); }))); it('should work when navigating to /', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: '', pathMatch: 'full', component: SimpleCmp}, {path: 'user/:name', component: UserCmp} ]); router.navigateByUrl('/user/victor'); advance(fixture); expect(fixture.nativeElement).toHaveText('user victor'); router.navigateByUrl('/'); advance(fixture); expect(fixture.nativeElement).toHaveText('simple'); }))); it('should cancel in-flight navigations', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'user/:name', component: UserCmp}]); const recordedEvents: any[] = []; router.events.forEach(e => recordedEvents.push(e)); router.navigateByUrl('/user/init'); advance(fixture); const user = fixture.debugElement.children[1].componentInstance; let r1: any, r2: any; router.navigateByUrl('/user/victor') !.then(_ => r1 = _); router.navigateByUrl('/user/fedor') !.then(_ => r2 = _); advance(fixture); expect(r1).toEqual(false); // returns false because it was canceled expect(r2).toEqual(true); // returns true because it was successful expect(fixture.nativeElement).toHaveText('user fedor'); expect(user.recordedParams).toEqual([{name: 'init'}, {name: 'fedor'}]); expectEvents(recordedEvents, [ [NavigationStart, '/user/init'], [RoutesRecognized, '/user/init'], [GuardsCheckStart, '/user/init'], [ChildActivationStart], [ActivationStart], [GuardsCheckEnd, '/user/init'], [ResolveStart, '/user/init'], [ResolveEnd, '/user/init'], [ActivationEnd], [ChildActivationEnd], [NavigationEnd, '/user/init'], [NavigationStart, '/user/victor'], [NavigationCancel, '/user/victor'], [NavigationStart, '/user/fedor'], [RoutesRecognized, '/user/fedor'], [GuardsCheckStart, '/user/fedor'], [ChildActivationStart], [ActivationStart], [GuardsCheckEnd, '/user/fedor'], [ResolveStart, '/user/fedor'], [ResolveEnd, '/user/fedor'], [ActivationEnd], [ChildActivationEnd], [NavigationEnd, '/user/fedor'] ]); }))); it('should handle failed navigations gracefully', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'user/:name', component: UserCmp}]); const recordedEvents: any[] = []; router.events.forEach(e => recordedEvents.push(e)); let e: any; router.navigateByUrl('/invalid') !.catch(_ => e = _); advance(fixture); expect(e.message).toContain('Cannot match any routes'); router.navigateByUrl('/user/fedor'); advance(fixture); expect(fixture.nativeElement).toHaveText('user fedor'); expectEvents(recordedEvents, [ [NavigationStart, '/invalid'], [NavigationError, '/invalid'], [NavigationStart, '/user/fedor'], [RoutesRecognized, '/user/fedor'], [GuardsCheckStart, '/user/fedor'], [ChildActivationStart], [ActivationStart], [GuardsCheckEnd, '/user/fedor'], [ResolveStart, '/user/fedor'], [ResolveEnd, '/user/fedor'], [ActivationEnd], [ChildActivationEnd], [NavigationEnd, '/user/fedor'] ]); }))); // Errors should behave the same for both deferred and eager URL update strategies ['deferred', 'eager'].forEach((strat: any) => { it('should dispatch NavigationError after the url has been reset back', fakeAsync(() => { const router: Router = TestBed.get(Router); const location: SpyLocation = TestBed.get(Location); const fixture = createRoot(router, RootCmp); router.resetConfig( [{path: 'simple', component: SimpleCmp}, {path: 'throwing', component: ThrowingCmp}]); router.urlUpdateStrategy = strat; router.navigateByUrl('/simple'); advance(fixture); let routerUrlBeforeEmittingError = ''; let locationUrlBeforeEmittingError = ''; router.events.forEach(e => { if (e instanceof NavigationError) { routerUrlBeforeEmittingError = router.url; locationUrlBeforeEmittingError = location.path(); } }); router.navigateByUrl('/throwing').catch(() => null); advance(fixture); expect(routerUrlBeforeEmittingError).toEqual('/simple'); expect(locationUrlBeforeEmittingError).toEqual('/simple'); })); it('should reset the url with the right state when navigation errors', fakeAsync(() => { const router: Router = TestBed.get(Router); const location: SpyLocation = TestBed.get(Location); const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'simple1', component: SimpleCmp}, {path: 'simple2', component: SimpleCmp}, {path: 'throwing', component: ThrowingCmp} ]); router.urlUpdateStrategy = strat; let event: NavigationStart; router.events.subscribe(e => { if (e instanceof NavigationStart) { event = e; } }); router.navigateByUrl('/simple1'); advance(fixture); const simple1NavStart = event !; router.navigateByUrl('/throwing').catch(() => null); advance(fixture); router.navigateByUrl('/simple2'); advance(fixture); location.back(); tick(); expect(event !.restoredState !.navigationId).toEqual(simple1NavStart.id); })); it('should not trigger another navigation when resetting the url back due to a NavigationError', fakeAsync(() => { const router = TestBed.get(Router); router.onSameUrlNavigation = 'reload'; const fixture = createRoot(router, RootCmp); router.resetConfig( [{path: 'simple', component: SimpleCmp}, {path: 'throwing', component: ThrowingCmp}]); router.urlUpdateStrategy = strat; const events: any[] = []; router.events.forEach((e: any) => { if (e instanceof NavigationStart) { events.push(e.url); } }); router.navigateByUrl('/simple'); advance(fixture); router.navigateByUrl('/throwing').catch(() => null); advance(fixture); // we do not trigger another navigation to /simple expect(events).toEqual(['/simple', '/throwing']); })); }); it('should dispatch NavigationCancel after the url has been reset back', fakeAsync(() => { TestBed.configureTestingModule( {providers: [{provide: 'returnsFalse', useValue: () => false}]}); const router: Router = TestBed.get(Router); const location: SpyLocation = TestBed.get(Location); const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'simple', component: SimpleCmp}, {path: 'throwing', loadChildren: 'doesnotmatter', canLoad: ['returnsFalse']} ]); router.navigateByUrl('/simple'); advance(fixture); let routerUrlBeforeEmittingError = ''; let locationUrlBeforeEmittingError = ''; router.events.forEach(e => { if (e instanceof NavigationCancel) { routerUrlBeforeEmittingError = router.url; locationUrlBeforeEmittingError = location.path(); } }); location.simulateHashChange('/throwing'); advance(fixture); expect(routerUrlBeforeEmittingError).toEqual('/simple'); expect(locationUrlBeforeEmittingError).toEqual('/simple'); })); it('should support custom error handlers', fakeAsync(inject([Router], (router: Router) => { router.errorHandler = (error) => 'resolvedValue'; const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'user/:name', component: UserCmp}]); const recordedEvents: any[] = []; router.events.forEach(e => recordedEvents.push(e)); let e: any; router.navigateByUrl('/invalid') !.then(_ => e = _); advance(fixture); expect(e).toEqual('resolvedValue'); expectEvents(recordedEvents, [[NavigationStart, '/invalid'], [NavigationError, '/invalid']]); }))); it('should recover from malformed uri errors', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { router.resetConfig([{path: 'simple', component: SimpleCmp}]); const fixture = createRoot(router, RootCmp); router.navigateByUrl('/invalid/url%with%percent'); advance(fixture); expect(location.path()).toEqual('/'); }))); it('should support custom malformed uri error handler', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const customMalformedUriErrorHandler = (e: URIError, urlSerializer: UrlSerializer, url: string): UrlTree => { return urlSerializer.parse('/?error=The-URL-you-went-to-is-invalid'); }; router.malformedUriErrorHandler = customMalformedUriErrorHandler; router.resetConfig([{path: 'simple', component: SimpleCmp}]); const fixture = createRoot(router, RootCmp); router.navigateByUrl('/invalid/url%with%percent'); advance(fixture); expect(location.path()).toEqual('/?error=The-URL-you-went-to-is-invalid'); }))); it('should not swallow errors', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'simple', component: SimpleCmp}]); router.navigateByUrl('/invalid'); expect(() => advance(fixture)).toThrow(); router.navigateByUrl('/invalid2'); expect(() => advance(fixture)).toThrow(); }))); it('should replace state when path is equal to current path', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [{path: 'simple', component: SimpleCmp}, {path: 'user/:name', component: UserCmp}] }]); router.navigateByUrl('/team/33/simple'); advance(fixture); router.navigateByUrl('/team/22/user/victor'); advance(fixture); router.navigateByUrl('/team/22/user/victor'); advance(fixture); location.back(); advance(fixture); expect(location.path()).toEqual('/team/33/simple'); }))); it('should handle componentless paths', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmpWithTwoOutlets); router.resetConfig([ { path: 'parent/:id', children: [ {path: 'simple', component: SimpleCmp}, {path: 'user/:name', component: UserCmp, outlet: 'right'} ] }, {path: 'user/:name', component: UserCmp} ]); // navigate to a componentless route router.navigateByUrl('/parent/11/(simple//right:user/victor)'); advance(fixture); expect(location.path()).toEqual('/parent/11/(simple//right:user/victor)'); expect(fixture.nativeElement).toHaveText('primary [simple] right [user victor]'); // navigate to the same route with different params (reuse) router.navigateByUrl('/parent/22/(simple//right:user/fedor)'); advance(fixture); expect(location.path()).toEqual('/parent/22/(simple//right:user/fedor)'); expect(fixture.nativeElement).toHaveText('primary [simple] right [user fedor]'); // navigate to a normal route (check deactivation) router.navigateByUrl('/user/victor'); advance(fixture); expect(location.path()).toEqual('/user/victor'); expect(fixture.nativeElement).toHaveText('primary [user victor] right []'); // navigate back to a componentless route router.navigateByUrl('/parent/11/(simple//right:user/victor)'); advance(fixture); expect(location.path()).toEqual('/parent/11/(simple//right:user/victor)'); expect(fixture.nativeElement).toHaveText('primary [simple] right [user victor]'); }))); it('should not deactivate aux routes when navigating from a componentless routes', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, TwoOutletsCmp); router.resetConfig([ {path: 'simple', component: SimpleCmp}, {path: 'componentless', children: [{path: 'simple', component: SimpleCmp}]}, {path: 'user/:name', outlet: 'aux', component: UserCmp} ]); router.navigateByUrl('/componentless/simple(aux:user/victor)'); advance(fixture); expect(location.path()).toEqual('/componentless/simple(aux:user/victor)'); expect(fixture.nativeElement).toHaveText('[ simple, aux: user victor ]'); router.navigateByUrl('/simple(aux:user/victor)'); advance(fixture); expect(location.path()).toEqual('/simple(aux:user/victor)'); expect(fixture.nativeElement).toHaveText('[ simple, aux: user victor ]'); }))); it('should emit an event when an outlet gets activated', fakeAsync(() => { @Component({ selector: 'container', template: `<router-outlet (activate)="recordActivate($event)" (deactivate)="recordDeactivate($event)"></router-outlet>` }) class Container { activations: any[] = []; deactivations: any[] = []; recordActivate(component: any): void { this.activations.push(component); } recordDeactivate(component: any): void { this.deactivations.push(component); } } TestBed.configureTestingModule({declarations: [Container]}); const router: Router = TestBed.get(Router); const fixture = createRoot(router, Container); const cmp = fixture.componentInstance; router.resetConfig( [{path: 'blank', component: BlankCmp}, {path: 'simple', component: SimpleCmp}]); cmp.activations = []; cmp.deactivations = []; router.navigateByUrl('/blank'); advance(fixture); expect(cmp.activations.length).toEqual(1); expect(cmp.activations[0] instanceof BlankCmp).toBe(true); router.navigateByUrl('/simple'); advance(fixture); expect(cmp.activations.length).toEqual(2); expect(cmp.activations[1] instanceof SimpleCmp).toBe(true); expect(cmp.deactivations.length).toEqual(1); expect(cmp.deactivations[0] instanceof BlankCmp).toBe(true); })); it('should update url and router state before activating components', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'cmp', component: ComponentRecordingRoutePathAndUrl}]); router.navigateByUrl('/cmp'); advance(fixture); const cmp = fixture.debugElement.children[1].componentInstance; expect(cmp.url).toBe('/cmp'); expect(cmp.path.length).toEqual(2); }))); describe('data', () => { class ResolveSix implements Resolve<number> { resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): number { return 6; } } beforeEach(() => { TestBed.configureTestingModule({ providers: [ {provide: 'resolveTwo', useValue: (a: any, b: any) => 2}, {provide: 'resolveFour', useValue: (a: any, b: any) => 4}, {provide: 'resolveSix', useClass: ResolveSix}, {provide: 'resolveError', useValue: (a: any, b: any) => Promise.reject('error')}, {provide: 'resolveNullError', useValue: (a: any, b: any) => Promise.reject(null)}, {provide: 'numberOfUrlSegments', useValue: (a: any, b: any) => a.url.length}, ] }); }); it('should provide resolved data', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmpWithTwoOutlets); router.resetConfig([{ path: 'parent/:id', data: {one: 1}, resolve: {two: 'resolveTwo'}, children: [ {path: '', data: {three: 3}, resolve: {four: 'resolveFour'}, component: RouteCmp}, { path: '', data: {five: 5}, resolve: {six: 'resolveSix'}, component: RouteCmp, outlet: 'right' } ] }]); router.navigateByUrl('/parent/1'); advance(fixture); const primaryCmp = fixture.debugElement.children[1].componentInstance; const rightCmp = fixture.debugElement.children[3].componentInstance; expect(primaryCmp.route.snapshot.data).toEqual({one: 1, two: 2, three: 3, four: 4}); expect(rightCmp.route.snapshot.data).toEqual({one: 1, two: 2, five: 5, six: 6}); const primaryRecorded: any[] = []; primaryCmp.route.data.forEach((rec: any) => primaryRecorded.push(rec)); const rightRecorded: any[] = []; rightCmp.route.data.forEach((rec: any) => rightRecorded.push(rec)); router.navigateByUrl('/parent/2'); advance(fixture); expect(primaryRecorded).toEqual([{one: 1, three: 3, two: 2, four: 4}]); expect(rightRecorded).toEqual([{one: 1, five: 5, two: 2, six: 6}]); }))); it('should handle errors', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig( [{path: 'simple', component: SimpleCmp, resolve: {error: 'resolveError'}}]); const recordedEvents: any[] = []; router.events.subscribe(e => e instanceof RouterEvent && recordedEvents.push(e)); let e: any = null; router.navigateByUrl('/simple') !.catch(error => e = error); advance(fixture); expectEvents(recordedEvents, [ [NavigationStart, '/simple'], [RoutesRecognized, '/simple'], [GuardsCheckStart, '/simple'], [GuardsCheckEnd, '/simple'], [ResolveStart, '/simple'], [NavigationError, '/simple'] ]); expect(e).toEqual('error'); }))); it('should handle empty errors', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig( [{path: 'simple', component: SimpleCmp, resolve: {error: 'resolveNullError'}}]); const recordedEvents: any[] = []; router.events.subscribe(e => e instanceof RouterEvent && recordedEvents.push(e)); let e: any = 'some value'; router.navigateByUrl('/simple').catch(error => e = error); advance(fixture); expect(e).toEqual(null); }))); it('should preserve resolved data', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'parent', resolve: {two: 'resolveTwo'}, children: [ {path: 'child1', component: CollectParamsCmp}, {path: 'child2', component: CollectParamsCmp} ] }]); const e: any = null; router.navigateByUrl('/parent/child1'); advance(fixture); router.navigateByUrl('/parent/child2'); advance(fixture); const cmp = fixture.debugElement.children[1].componentInstance; expect(cmp.route.snapshot.data).toEqual({two: 2}); }))); it('should rerun resolvers when the urls segments of a wildcard route change', fakeAsync(inject([Router, Location], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: '**', component: CollectParamsCmp, resolve: {numberOfUrlSegments: 'numberOfUrlSegments'} }]); router.navigateByUrl('/one/two'); advance(fixture); const cmp = fixture.debugElement.children[1].componentInstance; expect(cmp.route.snapshot.data).toEqual({numberOfUrlSegments: 2}); router.navigateByUrl('/one/two/three'); advance(fixture); expect(cmp.route.snapshot.data).toEqual({numberOfUrlSegments: 3}); }))); describe('should run resolvers for the same route concurrently', () => { let log: string[]; let observer: Observer<any>; beforeEach(() => { log = []; TestBed.configureTestingModule({ providers: [ { provide: 'resolver1', useValue: () => { const obs$ = new Observable((obs: Observer<any>) => { observer = obs; return () => {}; }); return obs$.pipe(map(() => log.push('resolver1'))); } }, { provide: 'resolver2', useValue: () => { return of (null).pipe(map(() => { log.push('resolver2'); observer.next(null); observer.complete(); })); } }, ] }); }); it('works', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'a', resolve: { one: 'resolver1', two: 'resolver2', }, component: SimpleCmp }]); router.navigateByUrl('/a'); advance(fixture); expect(log).toEqual(['resolver2', 'resolver1']); }))); }); }); describe('router links', () => { it('should support skipping location update for anchor router links', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = TestBed.createComponent(RootCmp); advance(fixture); router.resetConfig([{path: 'team/:id', component: TeamCmp}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); expect(fixture.nativeElement).toHaveText('team 22 [ , right: ]'); const teamCmp = fixture.debugElement.childNodes[1].componentInstance; teamCmp.routerLink = ['/team/0']; advance(fixture); const anchor = fixture.debugElement.query(By.css('a')).nativeElement; anchor.click(); advance(fixture); expect(fixture.nativeElement).toHaveText('team 0 [ , right: ]'); expect(location.path()).toEqual('/team/22'); teamCmp.routerLink = ['/team/1']; advance(fixture); const button = fixture.debugElement.query(By.css('button')).nativeElement; button.click(); advance(fixture); expect(fixture.nativeElement).toHaveText('team 1 [ , right: ]'); expect(location.path()).toEqual('/team/22'); }))); it('should support string router links', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [ {path: 'link', component: StringLinkCmp}, {path: 'simple', component: SimpleCmp} ] }]); router.navigateByUrl('/team/22/link'); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ link, right: ]'); const native = fixture.nativeElement.querySelector('a'); expect(native.getAttribute('href')).toEqual('/team/33/simple'); expect(native.getAttribute('target')).toEqual('_self'); native.click(); advance(fixture); expect(fixture.nativeElement).toHaveText('team 33 [ simple, right: ]'); }))); it('should not preserve query params and fragment by default', fakeAsync(() => { @Component({ selector: 'someRoot', template: `<router-outlet></router-outlet><a routerLink="/home">Link</a>` }) class RootCmpWithLink { } TestBed.configureTestingModule({declarations: [RootCmpWithLink]}); const router: Router = TestBed.get(Router); const fixture = createRoot(router, RootCmpWithLink); router.resetConfig([{path: 'home', component: SimpleCmp}]); const native = fixture.nativeElement.querySelector('a'); router.navigateByUrl('/home?q=123#fragment'); advance(fixture); expect(native.getAttribute('href')).toEqual('/home'); })); it('should not throw when commands is null', fakeAsync(() => { @Component({ selector: 'someCmp', template: `<router-outlet></router-outlet><a [routerLink]="null">Link</a><button [routerLink]="null">Button</button>` }) class CmpWithLink { } TestBed.configureTestingModule({declarations: [CmpWithLink]}); const router: Router = TestBed.get(Router); let fixture: ComponentFixture<CmpWithLink> = createRoot(router, CmpWithLink); router.resetConfig([{path: 'home', component: SimpleCmp}]); const anchor = fixture.nativeElement.querySelector('a'); const button = fixture.nativeElement.querySelector('button'); expect(() => anchor.click()).not.toThrow(); expect(() => button.click()).not.toThrow(); })); it('should update hrefs when query params or fragment change', fakeAsync(() => { @Component({ selector: 'someRoot', template: `<router-outlet></router-outlet><a routerLink="/home" preserveQueryParams preserveFragment>Link</a>` }) class RootCmpWithLink { } TestBed.configureTestingModule({declarations: [RootCmpWithLink]}); const router: Router = TestBed.get(Router); const fixture = createRoot(router, RootCmpWithLink); router.resetConfig([{path: 'home', component: SimpleCmp}]); const native = fixture.nativeElement.querySelector('a'); router.navigateByUrl('/home?q=123'); advance(fixture); expect(native.getAttribute('href')).toEqual('/home?q=123'); router.navigateByUrl('/home?q=456'); advance(fixture); expect(native.getAttribute('href')).toEqual('/home?q=456'); router.navigateByUrl('/home?q=456#1'); advance(fixture); expect(native.getAttribute('href')).toEqual('/home?q=456#1'); })); it('should correctly use the preserve strategy', fakeAsync(() => { @Component({ selector: 'someRoot', template: `<router-outlet></router-outlet><a routerLink="/home" [queryParams]="{q: 456}" queryParamsHandling="preserve">Link</a>` }) class RootCmpWithLink { } TestBed.configureTestingModule({declarations: [RootCmpWithLink]}); const router: Router = TestBed.get(Router); const fixture = createRoot(router, RootCmpWithLink); router.resetConfig([{path: 'home', component: SimpleCmp}]); const native = fixture.nativeElement.querySelector('a'); router.navigateByUrl('/home?a=123'); advance(fixture); expect(native.getAttribute('href')).toEqual('/home?a=123'); })); it('should correctly use the merge strategy', fakeAsync(() => { @Component({ selector: 'someRoot', template: `<router-outlet></router-outlet><a routerLink="/home" [queryParams]="{removeMe: null, q: 456}" queryParamsHandling="merge">Link</a>` }) class RootCmpWithLink { } TestBed.configureTestingModule({declarations: [RootCmpWithLink]}); const router: Router = TestBed.get(Router); const fixture = createRoot(router, RootCmpWithLink); router.resetConfig([{path: 'home', component: SimpleCmp}]); const native = fixture.nativeElement.querySelector('a'); router.navigateByUrl('/home?a=123&removeMe=123'); advance(fixture); expect(native.getAttribute('href')).toEqual('/home?a=123&q=456'); })); it('should support using links on non-a tags', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [ {path: 'link', component: StringLinkButtonCmp}, {path: 'simple', component: SimpleCmp} ] }]); router.navigateByUrl('/team/22/link'); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ link, right: ]'); const button = fixture.nativeElement.querySelector('button'); expect(button.getAttribute('tabindex')).toEqual('0'); button.click(); advance(fixture); expect(fixture.nativeElement).toHaveText('team 33 [ simple, right: ]'); }))); it('should support absolute router links', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [ {path: 'link', component: AbsoluteLinkCmp}, {path: 'simple', component: SimpleCmp} ] }]); router.navigateByUrl('/team/22/link'); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ link, right: ]'); const native = fixture.nativeElement.querySelector('a'); expect(native.getAttribute('href')).toEqual('/team/33/simple'); native.click(); advance(fixture); expect(fixture.nativeElement).toHaveText('team 33 [ simple, right: ]'); }))); it('should support relative router links', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [ {path: 'link', component: RelativeLinkCmp}, {path: 'simple', component: SimpleCmp} ] }]); router.navigateByUrl('/team/22/link'); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ link, right: ]'); const native = fixture.nativeElement.querySelector('a'); expect(native.getAttribute('href')).toEqual('/team/22/simple'); native.click(); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ simple, right: ]'); }))); it('should support top-level link', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RelativeLinkInIfCmp); advance(fixture); router.resetConfig( [{path: 'simple', component: SimpleCmp}, {path: '', component: BlankCmp}]); router.navigateByUrl('/'); advance(fixture); expect(fixture.nativeElement).toHaveText(''); const cmp = fixture.componentInstance; cmp.show = true; advance(fixture); expect(fixture.nativeElement).toHaveText('link'); const native = fixture.nativeElement.querySelector('a'); expect(native.getAttribute('href')).toEqual('/simple'); native.click(); advance(fixture); expect(fixture.nativeElement).toHaveText('linksimple'); }))); it('should support query params and fragments', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [ {path: 'link', component: LinkWithQueryParamsAndFragment}, {path: 'simple', component: SimpleCmp} ] }]); router.navigateByUrl('/team/22/link'); advance(fixture); const native = fixture.nativeElement.querySelector('a'); expect(native.getAttribute('href')).toEqual('/team/22/simple?q=1#f'); native.click(); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ simple, right: ]'); expect(location.path()).toEqual('/team/22/simple?q=1#f'); }))); it('should support history state', fakeAsync(inject([Router, Location], (router: Router, location: SpyLocation) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [ {path: 'link', component: LinkWithState}, {path: 'simple', component: SimpleCmp} ] }]); router.navigateByUrl('/team/22/link'); advance(fixture); const native = fixture.nativeElement.querySelector('a'); expect(native.getAttribute('href')).toEqual('/team/22/simple'); native.click(); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ simple, right: ]'); // Check the history entry const history = (location as any)._history; expect(history[history.length - 1].state.foo).toBe('bar'); expect(history[history.length - 1].state) .toEqual({foo: 'bar', navigationId: history.length}); }))); it('should set href on area elements', fakeAsync(() => { @Component({ selector: 'someRoot', template: `<router-outlet></router-outlet><map><area routerLink="/home" /></map>` }) class RootCmpWithArea { } TestBed.configureTestingModule({declarations: [RootCmpWithArea]}); const router: Router = TestBed.get(Router); const fixture = createRoot(router, RootCmpWithArea); router.resetConfig([{path: 'home', component: SimpleCmp}]); const native = fixture.nativeElement.querySelector('area'); expect(native.getAttribute('href')).toEqual('/home'); })); }); describe('redirects', () => { it('should work', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'old/team/:id', redirectTo: 'team/:id'}, {path: 'team/:id', component: TeamCmp} ]); router.navigateByUrl('old/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); }))); it('should update Navigation object after redirects are applied', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); let initialUrl, afterRedirectUrl; router.resetConfig([ {path: 'old/team/:id', redirectTo: 'team/:id'}, {path: 'team/:id', component: TeamCmp} ]); router.events.subscribe(e => { if (e instanceof NavigationStart) { const navigation = router.getCurrentNavigation(); initialUrl = navigation && navigation.finalUrl; } if (e instanceof RoutesRecognized) { const navigation = router.getCurrentNavigation(); afterRedirectUrl = navigation && navigation.finalUrl; } }); router.navigateByUrl('old/team/22'); advance(fixture); expect(initialUrl).toBeUndefined(); expect(router.serializeUrl(afterRedirectUrl as any)).toBe('/team/22'); }))); it('should not break the back button when trigger by location change', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = TestBed.createComponent(RootCmp); advance(fixture); router.resetConfig([ {path: 'initial', component: BlankCmp}, {path: 'old/team/:id', redirectTo: 'team/:id'}, {path: 'team/:id', component: TeamCmp} ]); location.go('initial'); location.go('old/team/22'); // initial navigation router.initialNavigation(); advance(fixture); expect(location.path()).toEqual('/team/22'); location.back(); advance(fixture); expect(location.path()).toEqual('/initial'); // location change (<any>location).go('/old/team/33'); advance(fixture); expect(location.path()).toEqual('/team/33'); location.back(); advance(fixture); expect(location.path()).toEqual('/initial'); }))); }); describe('guards', () => { describe('CanActivate', () => { describe('should not activate a route when CanActivate returns false', () => { beforeEach(() => { TestBed.configureTestingModule( {providers: [{provide: 'alwaysFalse', useValue: (a: any, b: any) => false}]}); }); it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); const recordedEvents: any[] = []; router.events.forEach(e => recordedEvents.push(e)); router.resetConfig( [{path: 'team/:id', component: TeamCmp, canActivate: ['alwaysFalse']}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/'); expectEvents(recordedEvents, [ [NavigationStart, '/team/22'], [RoutesRecognized, '/team/22'], [GuardsCheckStart, '/team/22'], [ChildActivationStart], [ActivationStart], [GuardsCheckEnd, '/team/22'], [NavigationCancel, '/team/22'], ]); expect((recordedEvents[5] as GuardsCheckEnd).shouldActivate).toBe(false); }))); }); describe( 'should not activate a route when CanActivate returns false (componentless route)', () => { beforeEach(() => { TestBed.configureTestingModule( {providers: [{provide: 'alwaysFalse', useValue: (a: any, b: any) => false}]}); }); it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'parent', canActivate: ['alwaysFalse'], children: [{path: 'team/:id', component: TeamCmp}] }]); router.navigateByUrl('parent/team/22'); advance(fixture); expect(location.path()).toEqual('/'); }))); }); describe('should activate a route when CanActivate returns true', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [{ provide: 'alwaysTrue', useValue: (a: ActivatedRouteSnapshot, s: RouterStateSnapshot) => true }] }); }); it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig( [{path: 'team/:id', component: TeamCmp, canActivate: ['alwaysTrue']}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); }))); }); describe('should work when given a class', () => { class AlwaysTrue implements CanActivate { canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { return true; } } beforeEach(() => { TestBed.configureTestingModule({providers: [AlwaysTrue]}); }); it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig( [{path: 'team/:id', component: TeamCmp, canActivate: [AlwaysTrue]}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); }))); }); describe('should work when returns an observable', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [{ provide: 'CanActivate', useValue: (a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { return Observable.create((observer: any) => { observer.next(false); }); } }] }); }); it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig( [{path: 'team/:id', component: TeamCmp, canActivate: ['CanActivate']}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/'); }))); }); describe('should work when returns a promise', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [{ provide: 'CanActivate', useValue: (a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { if (a.params['id'] === '22') { return Promise.resolve(true); } else { return Promise.resolve(false); } } }] }); }); it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig( [{path: 'team/:id', component: TeamCmp, canActivate: ['CanActivate']}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); router.navigateByUrl('/team/33'); advance(fixture); expect(location.path()).toEqual('/team/22'); }))); }); describe('should reset the location when cancleling a navigation', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [{ provide: 'alwaysFalse', useValue: (a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { return false; } }] }); }); it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'one', component: SimpleCmp}, {path: 'two', component: SimpleCmp, canActivate: ['alwaysFalse']} ]); router.navigateByUrl('/one'); advance(fixture); expect(location.path()).toEqual('/one'); location.go('/two'); advance(fixture); expect(location.path()).toEqual('/one'); }))); }); describe('should redirect to / when guard returns false', () => { beforeEach(() => TestBed.configureTestingModule({ providers: [{ provide: 'returnFalseAndNavigate', useFactory: (router: Router) => () => { router.navigate(['/']); return false; }, deps: [Router] }] })); it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { router.resetConfig([ { path: '', component: SimpleCmp, }, {path: 'one', component: RouteCmp, canActivate: ['returnFalseAndNavigate']} ]); const fixture = TestBed.createComponent(RootCmp); router.navigateByUrl('/one'); advance(fixture); expect(location.path()).toEqual('/'); expect(fixture.nativeElement).toHaveText('simple'); }))); }); describe('should redirect when guard returns UrlTree', () => { beforeEach(() => TestBed.configureTestingModule({ providers: [ { provide: 'returnUrlTree', useFactory: (router: Router) => () => { return router.parseUrl('/redirected'); }, deps: [Router] }, { provide: 'returnRootUrlTree', useFactory: (router: Router) => () => { return router.parseUrl('/'); }, deps: [Router] } ] })); it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const recordedEvents: any[] = []; let cancelEvent: NavigationCancel = null !; router.events.forEach((e: any) => { recordedEvents.push(e); if (e instanceof NavigationCancel) cancelEvent = e; }); router.resetConfig([ {path: '', component: SimpleCmp}, {path: 'one', component: RouteCmp, canActivate: ['returnUrlTree']}, {path: 'redirected', component: SimpleCmp} ]); const fixture = TestBed.createComponent(RootCmp); router.navigateByUrl('/one'); advance(fixture); expect(location.path()).toEqual('/redirected'); expect(fixture.nativeElement).toHaveText('simple'); expect(cancelEvent && cancelEvent.reason) .toBe('NavigationCancelingError: Redirecting to "/redirected"'); expectEvents(recordedEvents, [ [NavigationStart, '/one'], [RoutesRecognized, '/one'], [GuardsCheckStart, '/one'], [ChildActivationStart, undefined], [ActivationStart, undefined], [NavigationCancel, '/one'], [NavigationStart, '/redirected'], [RoutesRecognized, '/redirected'], [GuardsCheckStart, '/redirected'], [ChildActivationStart, undefined], [ActivationStart, undefined], [GuardsCheckEnd, '/redirected'], [ResolveStart, '/redirected'], [ResolveEnd, '/redirected'], [ActivationEnd, undefined], [ChildActivationEnd, undefined], [NavigationEnd, '/redirected'], ]); }))); it('works with root url', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const recordedEvents: any[] = []; let cancelEvent: NavigationCancel = null !; router.events.forEach((e: any) => { recordedEvents.push(e); if (e instanceof NavigationCancel) cancelEvent = e; }); router.resetConfig([ {path: '', component: SimpleCmp}, {path: 'one', component: RouteCmp, canActivate: ['returnRootUrlTree']} ]); const fixture = TestBed.createComponent(RootCmp); router.navigateByUrl('/one'); advance(fixture); expect(location.path()).toEqual('/'); expect(fixture.nativeElement).toHaveText('simple'); expect(cancelEvent && cancelEvent.reason) .toBe('NavigationCancelingError: Redirecting to "/"'); expectEvents(recordedEvents, [ [NavigationStart, '/one'], [RoutesRecognized, '/one'], [GuardsCheckStart, '/one'], [ChildActivationStart, undefined], [ActivationStart, undefined], [NavigationCancel, '/one'], [NavigationStart, '/'], [RoutesRecognized, '/'], [GuardsCheckStart, '/'], [ChildActivationStart, undefined], [ActivationStart, undefined], [GuardsCheckEnd, '/'], [ResolveStart, '/'], [ResolveEnd, '/'], [ActivationEnd, undefined], [ChildActivationEnd, undefined], [NavigationEnd, '/'], ]); }))); }); describe('runGuardsAndResolvers', () => { let guardRunCount = 0; let resolverRunCount = 0; beforeEach(() => { guardRunCount = 0; resolverRunCount = 0; TestBed.configureTestingModule({ providers: [ { provide: 'guard', useValue: () => { guardRunCount++; return true; } }, {provide: 'resolver', useValue: () => resolverRunCount++} ] }); }); function configureRouter(router: Router, runGuardsAndResolvers: RunGuardsAndResolvers): ComponentFixture<RootCmpWithTwoOutlets> { const fixture = createRoot(router, RootCmpWithTwoOutlets); router.resetConfig([ { path: 'a', runGuardsAndResolvers, component: RouteCmp, canActivate: ['guard'], resolve: {data: 'resolver'} }, {path: 'b', component: SimpleCmp, outlet: 'right'}, { path: 'c/:param', runGuardsAndResolvers, component: RouteCmp, canActivate: ['guard'], resolve: {data: 'resolver'} }, { path: 'd/:param', component: WrapperCmp, runGuardsAndResolvers, children: [ { path: 'e/:param', component: SimpleCmp, canActivate: ['guard'], resolve: {data: 'resolver'}, }, ] } ]); router.navigateByUrl('/a'); advance(fixture); return fixture; } it('should rerun guards and resolvers when params change', fakeAsync(inject([Router], (router: Router) => { const fixture = configureRouter(router, 'paramsChange'); const cmp: RouteCmp = fixture.debugElement.children[1].componentInstance; const recordedData: any[] = []; cmp.route.data.subscribe((data: any) => recordedData.push(data)); expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); router.navigateByUrl('/a;p=1'); advance(fixture); expect(guardRunCount).toEqual(2); expect(recordedData).toEqual([{data: 0}, {data: 1}]); router.navigateByUrl('/a;p=2'); advance(fixture); expect(guardRunCount).toEqual(3); expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}]); router.navigateByUrl('/a;p=2?q=1'); advance(fixture); expect(guardRunCount).toEqual(3); expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}]); }))); it('should rerun guards and resolvers when query params change', fakeAsync(inject([Router], (router: Router) => { const fixture = configureRouter(router, 'paramsOrQueryParamsChange'); const cmp: RouteCmp = fixture.debugElement.children[1].componentInstance; const recordedData: any[] = []; cmp.route.data.subscribe((data: any) => recordedData.push(data)); expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); router.navigateByUrl('/a;p=1'); advance(fixture); expect(guardRunCount).toEqual(2); expect(recordedData).toEqual([{data: 0}, {data: 1}]); router.navigateByUrl('/a;p=2'); advance(fixture); expect(guardRunCount).toEqual(3); expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}]); router.navigateByUrl('/a;p=2?q=1'); advance(fixture); expect(guardRunCount).toEqual(4); expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}, {data: 3}]); router.navigateByUrl('/a;p=2(right:b)?q=1'); advance(fixture); expect(guardRunCount).toEqual(4); expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}, {data: 3}]); }))); it('should always rerun guards and resolvers', fakeAsync(inject([Router], (router: Router) => { const fixture = configureRouter(router, 'always'); const cmp: RouteCmp = fixture.debugElement.children[1].componentInstance; const recordedData: any[] = []; cmp.route.data.subscribe((data: any) => recordedData.push(data)); expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); router.navigateByUrl('/a;p=1'); advance(fixture); expect(guardRunCount).toEqual(2); expect(recordedData).toEqual([{data: 0}, {data: 1}]); router.navigateByUrl('/a;p=2'); advance(fixture); expect(guardRunCount).toEqual(3); expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}]); router.navigateByUrl('/a;p=2?q=1'); advance(fixture); expect(guardRunCount).toEqual(4); expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}, {data: 3}]); router.navigateByUrl('/a;p=2(right:b)?q=1'); advance(fixture); expect(guardRunCount).toEqual(5); expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}, {data: 3}, {data: 4}]); }))); it('should rerun rerun guards and resolvers when path params change', fakeAsync(inject([Router], (router: Router) => { const fixture = configureRouter(router, 'pathParamsChange'); const cmp: RouteCmp = fixture.debugElement.children[1].componentInstance; const recordedData: any[] = []; cmp.route.data.subscribe((data: any) => recordedData.push(data)); // First navigation has already run expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); // Changing any optional params will not result in running guards or resolvers router.navigateByUrl('/a;p=1'); advance(fixture); expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); router.navigateByUrl('/a;p=2'); advance(fixture); expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); router.navigateByUrl('/a;p=2?q=1'); advance(fixture); expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); router.navigateByUrl('/a;p=2(right:b)?q=1'); advance(fixture); expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); // Change to new route with path param should run guards and resolvers router.navigateByUrl('/c/paramValue'); advance(fixture); expect(guardRunCount).toEqual(2); // Modifying a path param should run guards and resolvers router.navigateByUrl('/c/paramValueChanged'); advance(fixture); expect(guardRunCount).toEqual(3); // Adding optional params should not cause guards/resolvers to run router.navigateByUrl('/c/paramValueChanged;p=1?q=2'); advance(fixture); expect(guardRunCount).toEqual(3); }))); it('should rerun when a parent segment changes', fakeAsync(inject([Router], (router: Router) => { const fixture = configureRouter(router, 'pathParamsChange'); const cmp: RouteCmp = fixture.debugElement.children[1].componentInstance; // Land on an inital page router.navigateByUrl('/d/1;dd=11/e/2;dd=22'); advance(fixture); expect(guardRunCount).toEqual(2); // Changes cause re-run on the config with the guard router.navigateByUrl('/d/1;dd=11/e/3;ee=22'); advance(fixture); expect(guardRunCount).toEqual(3); // Changes to the parent also cause re-run router.navigateByUrl('/d/2;dd=11/e/3;ee=22'); advance(fixture); expect(guardRunCount).toEqual(4); }))); it('should rerun rerun guards and resolvers when path or query params change', fakeAsync(inject([Router], (router: Router) => { const fixture = configureRouter(router, 'pathParamsOrQueryParamsChange'); const cmp: RouteCmp = fixture.debugElement.children[1].componentInstance; const recordedData: any[] = []; cmp.route.data.subscribe((data: any) => recordedData.push(data)); // First navigation has already run expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); // Changing matrix params will not result in running guards or resolvers router.navigateByUrl('/a;p=1'); advance(fixture); expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); router.navigateByUrl('/a;p=2'); advance(fixture); expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); // Adding query params will re-run guards/resolvers router.navigateByUrl('/a;p=2?q=1'); advance(fixture); expect(guardRunCount).toEqual(2); expect(recordedData).toEqual([{data: 0}, {data: 1}]); // Changing query params will re-run guards/resolvers router.navigateByUrl('/a;p=2?q=2'); advance(fixture); expect(guardRunCount).toEqual(3); expect(recordedData).toEqual([{data: 0}, {data: 1}, {data: 2}]); }))); it('should allow a predicate function to determine when to run guards and resolvers', fakeAsync(inject([Router], (router: Router) => { const fixture = configureRouter(router, (from, to) => to.paramMap.get('p') === '2'); const cmp: RouteCmp = fixture.debugElement.children[1].componentInstance; const recordedData: any[] = []; cmp.route.data.subscribe((data: any) => recordedData.push(data)); // First navigation has already run expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); // Adding `p` param shouldn't cause re-run router.navigateByUrl('/a;p=1'); advance(fixture); expect(guardRunCount).toEqual(1); expect(recordedData).toEqual([{data: 0}]); // Re-run should trigger on p=2 router.navigateByUrl('/a;p=2'); advance(fixture); expect(guardRunCount).toEqual(2); expect(recordedData).toEqual([{data: 0}, {data: 1}]); // Any other changes don't pass the predicate router.navigateByUrl('/a;p=3?q=1'); advance(fixture); expect(guardRunCount).toEqual(2); expect(recordedData).toEqual([{data: 0}, {data: 1}]); // Changing query params will re-run guards/resolvers router.navigateByUrl('/a;p=3?q=2'); advance(fixture); expect(guardRunCount).toEqual(2); expect(recordedData).toEqual([{data: 0}, {data: 1}]); }))); }); describe('should wait for parent to complete', () => { let log: string[]; beforeEach(() => { log = []; TestBed.configureTestingModule({ providers: [ { provide: 'parentGuard', useValue: () => { return delayPromise(10).then(() => { log.push('parent'); return true; }); } }, { provide: 'childGuard', useValue: () => { return delayPromise(5).then(() => { log.push('child'); return true; }); } } ] }); }); function delayPromise(delay: number): Promise<boolean> { let resolve: (val: boolean) => void; const promise = new Promise<boolean>(res => resolve = res); setTimeout(() => resolve(true), delay); return promise; } it('works', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'parent', canActivate: ['parentGuard'], children: [ {path: 'child', component: SimpleCmp, canActivate: ['childGuard']}, ] }]); router.navigateByUrl('/parent/child'); advance(fixture); tick(15); expect(log).toEqual(['parent', 'child']); }))); }); }); describe('CanDeactivate', () => { let log: any; beforeEach(() => { log = []; TestBed.configureTestingModule({ providers: [ { provide: 'CanDeactivateParent', useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { return a.params['id'] === '22'; } }, { provide: 'CanDeactivateTeam', useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { return c.route.snapshot.params['id'] === '22'; } }, { provide: 'CanDeactivateUser', useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { return a.params['name'] === 'victor'; } }, { provide: 'RecordingDeactivate', useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { log.push({path: a.routeConfig !.path, component: c}); return true; } }, { provide: 'alwaysFalse', useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { return false; } }, { provide: 'alwaysFalseAndLogging', useValue: (c: any, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { log.push('called'); return false; } }, { provide: 'alwaysFalseWithDelayAndLogging', useValue: () => { log.push('called'); let resolve: (result: boolean) => void; const promise = new Promise(res => resolve = res); setTimeout(() => resolve(false), 0); return promise; } }, { provide: 'canActivate_alwaysTrueAndLogging', useValue: () => { log.push('canActivate called'); return true; } }, ] }); }); describe('should not deactivate a route when CanDeactivate returns false', () => { it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig( [{path: 'team/:id', component: TeamCmp, canDeactivate: ['CanDeactivateTeam']}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); let successStatus: boolean = false; router.navigateByUrl('/team/33') !.then(res => successStatus = res); advance(fixture); expect(location.path()).toEqual('/team/33'); expect(successStatus).toEqual(true); let canceledStatus: boolean = false; router.navigateByUrl('/team/44') !.then(res => canceledStatus = res); advance(fixture); expect(location.path()).toEqual('/team/33'); expect(canceledStatus).toEqual(false); }))); it('works with componentless routes', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ { path: 'grandparent', canDeactivate: ['RecordingDeactivate'], children: [{ path: 'parent', canDeactivate: ['RecordingDeactivate'], children: [{ path: 'child', canDeactivate: ['RecordingDeactivate'], children: [{ path: 'simple', component: SimpleCmp, canDeactivate: ['RecordingDeactivate'] }] }] }] }, {path: 'simple', component: SimpleCmp} ]); router.navigateByUrl('/grandparent/parent/child/simple'); advance(fixture); expect(location.path()).toEqual('/grandparent/parent/child/simple'); router.navigateByUrl('/simple'); advance(fixture); const child = fixture.debugElement.children[1].componentInstance; expect(log.map((a: any) => a.path)).toEqual([ 'simple', 'child', 'parent', 'grandparent' ]); expect(log[0].component instanceof SimpleCmp).toBeTruthy(); [1, 2, 3].forEach(i => expect(log[i].component).toBeNull()); expect(child instanceof SimpleCmp).toBeTruthy(); expect(child).not.toBe(log[0].component); }))); it('works with aux routes', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'two-outlets', component: TwoOutletsCmp, children: [ {path: 'a', component: BlankCmp}, { path: 'b', canDeactivate: ['RecordingDeactivate'], component: SimpleCmp, outlet: 'aux' } ] }]); router.navigateByUrl('/two-outlets/(a//aux:b)'); advance(fixture); expect(location.path()).toEqual('/two-outlets/(a//aux:b)'); router.navigate(['two-outlets', {outlets: {aux: null}}]); advance(fixture); expect(log.map((a: any) => a.path)).toEqual(['b']); expect(location.path()).toEqual('/two-outlets/(a)'); }))); it('works with a nested route', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [ {path: '', pathMatch: 'full', component: SimpleCmp}, {path: 'user/:name', component: UserCmp, canDeactivate: ['CanDeactivateUser']} ] }]); router.navigateByUrl('/team/22/user/victor'); advance(fixture); // this works because we can deactivate victor router.navigateByUrl('/team/33'); advance(fixture); expect(location.path()).toEqual('/team/33'); router.navigateByUrl('/team/33/user/fedor'); advance(fixture); // this doesn't work cause we cannot deactivate fedor router.navigateByUrl('/team/44'); advance(fixture); expect(location.path()).toEqual('/team/33/user/fedor'); }))); }); it('should not create a route state if navigation is canceled', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'main', component: TeamCmp, children: [ {path: 'component1', component: SimpleCmp, canDeactivate: ['alwaysFalse']}, {path: 'component2', component: SimpleCmp} ] }]); router.navigateByUrl('/main/component1'); advance(fixture); router.navigateByUrl('/main/component2'); advance(fixture); const teamCmp = fixture.debugElement.children[1].componentInstance; expect(teamCmp.route.firstChild.url.value[0].path).toEqual('component1'); expect(location.path()).toEqual('/main/component1'); }))); it('should not run CanActivate when CanDeactivate returns false', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'main', component: TeamCmp, children: [ { path: 'component1', component: SimpleCmp, canDeactivate: ['alwaysFalseWithDelayAndLogging'] }, { path: 'component2', component: SimpleCmp, canActivate: ['canActivate_alwaysTrueAndLogging'] }, ] }]); router.navigateByUrl('/main/component1'); advance(fixture); expect(location.path()).toEqual('/main/component1'); router.navigateByUrl('/main/component2'); advance(fixture); expect(location.path()).toEqual('/main/component1'); expect(log).toEqual(['called']); }))); it('should call guards every time when navigating to the same url over and over again', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'simple', component: SimpleCmp, canDeactivate: ['alwaysFalseAndLogging']}, {path: 'blank', component: BlankCmp} ]); router.navigateByUrl('/simple'); advance(fixture); router.navigateByUrl('/blank'); advance(fixture); expect(log).toEqual(['called']); expect(location.path()).toEqual('/simple'); router.navigateByUrl('/blank'); advance(fixture); expect(log).toEqual(['called', 'called']); expect(location.path()).toEqual('/simple'); }))); describe('next state', () => { let log: string[]; class ClassWithNextState implements CanDeactivate<TeamCmp> { canDeactivate( component: TeamCmp, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState: RouterStateSnapshot): boolean { log.push(currentState.url, nextState.url); return true; } } beforeEach(() => { log = []; TestBed.configureTestingModule({ providers: [ ClassWithNextState, { provide: 'FunctionWithNextState', useValue: (cmp: any, currentRoute: ActivatedRouteSnapshot, currentState: RouterStateSnapshot, nextState: RouterStateSnapshot) => { log.push(currentState.url, nextState.url); return true; } } ] }); }); it('should pass next state as the 4 argument when guard is a class', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig( [{path: 'team/:id', component: TeamCmp, canDeactivate: [ClassWithNextState]}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); router.navigateByUrl('/team/33'); advance(fixture); expect(location.path()).toEqual('/team/33'); expect(log).toEqual(['/team/22', '/team/33']); }))); it('should pass next state as the 4 argument when guard is a function', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'team/:id', component: TeamCmp, canDeactivate: ['FunctionWithNextState']} ]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); router.navigateByUrl('/team/33'); advance(fixture); expect(location.path()).toEqual('/team/33'); expect(log).toEqual(['/team/22', '/team/33']); }))); }); describe('should work when given a class', () => { class AlwaysTrue implements CanDeactivate<TeamCmp> { canDeactivate( component: TeamCmp, route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { return true; } } beforeEach(() => { TestBed.configureTestingModule({providers: [AlwaysTrue]}); }); it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig( [{path: 'team/:id', component: TeamCmp, canDeactivate: [AlwaysTrue]}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); router.navigateByUrl('/team/33'); advance(fixture); expect(location.path()).toEqual('/team/33'); }))); }); describe('should work when returns an observable', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [{ provide: 'CanDeactivate', useValue: (c: TeamCmp, a: ActivatedRouteSnapshot, b: RouterStateSnapshot) => { return Observable.create((observer: any) => { observer.next(false); }); } }] }); }); it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig( [{path: 'team/:id', component: TeamCmp, canDeactivate: ['CanDeactivate']}]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); router.navigateByUrl('/team/33'); advance(fixture); expect(location.path()).toEqual('/team/22'); }))); }); }); describe('CanActivateChild', () => { describe('should be invoked when activating a child', () => { beforeEach(() => { TestBed.configureTestingModule({ providers: [{ provide: 'alwaysFalse', useValue: (a: any, b: any) => a.paramMap.get('id') === '22', }] }); }); it('works', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: '', canActivateChild: ['alwaysFalse'], children: [{path: 'team/:id', component: TeamCmp}] }]); router.navigateByUrl('/team/22'); advance(fixture); expect(location.path()).toEqual('/team/22'); router.navigateByUrl('/team/33') !.catch(() => {}); advance(fixture); expect(location.path()).toEqual('/team/22'); }))); }); it('should find the guard provided in lazy loaded module', fakeAsync(inject( [Router, Location, NgModuleFactoryLoader], (router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => { @Component({selector: 'admin', template: '<router-outlet></router-outlet>'}) class AdminComponent { } @Component({selector: 'lazy', template: 'lazy-loaded'}) class LazyLoadedComponent { } @NgModule({ declarations: [AdminComponent, LazyLoadedComponent], imports: [RouterModule.forChild([{ path: '', component: AdminComponent, children: [{ path: '', canActivateChild: ['alwaysTrue'], children: [{path: '', component: LazyLoadedComponent}] }] }])], providers: [{provide: 'alwaysTrue', useValue: () => true}], }) class LazyLoadedModule { } loader.stubbedModules = {lazy: LazyLoadedModule}; const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'admin', loadChildren: 'lazy'}]); router.navigateByUrl('/admin'); advance(fixture); expect(location.path()).toEqual('/admin'); expect(fixture.nativeElement).toHaveText('lazy-loaded'); }))); }); describe('CanLoad', () => { let canLoadRunCount = 0; beforeEach(() => { canLoadRunCount = 0; TestBed.configureTestingModule({ providers: [ {provide: 'alwaysFalse', useValue: (a: any) => false}, { provide: 'returnFalseAndNavigate', useFactory: (router: any) => (a: any) => { router.navigate(['blank']); return false; }, deps: [Router], }, { provide: 'alwaysTrue', useValue: () => { canLoadRunCount++; return true; } }, ] }); }); it('should not load children when CanLoad returns false', fakeAsync(inject( [Router, Location, NgModuleFactoryLoader], (router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => { @Component({selector: 'lazy', template: 'lazy-loaded'}) class LazyLoadedComponent { } @NgModule({ declarations: [LazyLoadedComponent], imports: [RouterModule.forChild([{path: 'loaded', component: LazyLoadedComponent}])] }) class LoadedModule { } loader.stubbedModules = {lazyFalse: LoadedModule, lazyTrue: LoadedModule}; const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'lazyFalse', canLoad: ['alwaysFalse'], loadChildren: 'lazyFalse'}, {path: 'lazyTrue', canLoad: ['alwaysTrue'], loadChildren: 'lazyTrue'} ]); const recordedEvents: any[] = []; router.events.forEach(e => recordedEvents.push(e)); // failed navigation router.navigateByUrl('/lazyFalse/loaded'); advance(fixture); expect(location.path()).toEqual('/'); expectEvents(recordedEvents, [ [NavigationStart, '/lazyFalse/loaded'], // [GuardsCheckStart, '/lazyFalse/loaded'], [NavigationCancel, '/lazyFalse/loaded'], ]); recordedEvents.splice(0); // successful navigation router.navigateByUrl('/lazyTrue/loaded'); advance(fixture); expect(location.path()).toEqual('/lazyTrue/loaded'); expectEvents(recordedEvents, [ [NavigationStart, '/lazyTrue/loaded'], [RouteConfigLoadStart], [RouteConfigLoadEnd], [RoutesRecognized, '/lazyTrue/loaded'], [GuardsCheckStart, '/lazyTrue/loaded'], [ChildActivationStart], [ActivationStart], [ChildActivationStart], [ActivationStart], [GuardsCheckEnd, '/lazyTrue/loaded'], [ResolveStart, '/lazyTrue/loaded'], [ResolveEnd, '/lazyTrue/loaded'], [ActivationEnd], [ChildActivationEnd], [ActivationEnd], [ChildActivationEnd], [NavigationEnd, '/lazyTrue/loaded'], ]); }))); it('should support navigating from within the guard', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'lazyFalse', canLoad: ['returnFalseAndNavigate'], loadChildren: 'lazyFalse'}, {path: 'blank', component: BlankCmp} ]); const recordedEvents: any[] = []; router.events.forEach(e => recordedEvents.push(e)); router.navigateByUrl('/lazyFalse/loaded'); advance(fixture); expect(location.path()).toEqual('/blank'); expectEvents(recordedEvents, [ [NavigationStart, '/lazyFalse/loaded'], // No GuardCheck events as `canLoad` is a special guard that's not actually part of the // guard lifecycle. [NavigationCancel, '/lazyFalse/loaded'], [NavigationStart, '/blank'], [RoutesRecognized, '/blank'], [GuardsCheckStart, '/blank'], [ChildActivationStart], [ActivationStart], [GuardsCheckEnd, '/blank'], [ResolveStart, '/blank'], [ResolveEnd, '/blank'], [ActivationEnd], [ChildActivationEnd], [NavigationEnd, '/blank'] ]); }))); // Regression where navigateByUrl with false CanLoad no longer resolved `false` value on // navigateByUrl promise: https://github.com/angular/angular/issues/26284 it('should resolve navigateByUrl promise after CanLoad executes', fakeAsync(inject( [Router, Location, NgModuleFactoryLoader], (router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => { @Component({selector: 'lazy', template: 'lazy-loaded'}) class LazyLoadedComponent { } @NgModule({ declarations: [LazyLoadedComponent], imports: [RouterModule.forChild([{path: 'loaded', component: LazyLoadedComponent}])] }) class LazyLoadedModule { } loader.stubbedModules = {lazy: LazyLoadedModule}; const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'lazy-false', canLoad: ['alwaysFalse'], loadChildren: 'lazy'}, {path: 'lazy-true', canLoad: ['alwaysTrue'], loadChildren: 'lazy'}, ]); let navFalseResult: any; let navTrueResult: any; router.navigateByUrl('/lazy-false').then(v => { navFalseResult = v; }); advance(fixture); router.navigateByUrl('/lazy-true').then(v => { navTrueResult = v; }); advance(fixture); expect(navFalseResult).toBe(false); expect(navTrueResult).toBe(true); }))); it('should execute CanLoad only once', fakeAsync(inject( [Router, Location, NgModuleFactoryLoader], (router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => { @Component({selector: 'lazy', template: 'lazy-loaded'}) class LazyLoadedComponent { } @NgModule({ declarations: [LazyLoadedComponent], imports: [RouterModule.forChild([{path: 'loaded', component: LazyLoadedComponent}])] }) class LazyLoadedModule { } loader.stubbedModules = {lazy: LazyLoadedModule}; const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'lazy', canLoad: ['alwaysTrue'], loadChildren: 'lazy'}]); router.navigateByUrl('/lazy/loaded'); advance(fixture); expect(location.path()).toEqual('/lazy/loaded'); expect(canLoadRunCount).toEqual(1); router.navigateByUrl('/'); advance(fixture); expect(location.path()).toEqual('/'); router.navigateByUrl('/lazy/loaded'); advance(fixture); expect(location.path()).toEqual('/lazy/loaded'); expect(canLoadRunCount).toEqual(1); }))); }); describe('order', () => { class Logger { logs: string[] = []; add(thing: string) { this.logs.push(thing); } } beforeEach(() => { TestBed.configureTestingModule({ providers: [ Logger, { provide: 'canActivateChild_parent', useFactory: (logger: Logger) => () => (logger.add('canActivateChild_parent'), true), deps: [Logger] }, { provide: 'canActivate_team', useFactory: (logger: Logger) => () => (logger.add('canActivate_team'), true), deps: [Logger] }, { provide: 'canDeactivate_team', useFactory: (logger: Logger) => () => (logger.add('canDeactivate_team'), true), deps: [Logger] }, { provide: 'canDeactivate_simple', useFactory: (logger: Logger) => () => (logger.add('canDeactivate_simple'), true), deps: [Logger] } ] }); }); it('should call guards in the right order', fakeAsync(inject( [Router, Location, Logger], (router: Router, location: Location, logger: Logger) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: '', canActivateChild: ['canActivateChild_parent'], children: [{ path: 'team/:id', canActivate: ['canActivate_team'], canDeactivate: ['canDeactivate_team'], component: TeamCmp }] }]); router.navigateByUrl('/team/22'); advance(fixture); router.navigateByUrl('/team/33'); advance(fixture); expect(logger.logs).toEqual([ 'canActivateChild_parent', 'canActivate_team', 'canDeactivate_team', 'canActivateChild_parent', 'canActivate_team' ]); }))); it('should call deactivate guards from bottom to top', fakeAsync(inject( [Router, Location, Logger], (router: Router, location: Location, logger: Logger) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: '', children: [{ path: 'team/:id', canDeactivate: ['canDeactivate_team'], children: [{path: '', component: SimpleCmp, canDeactivate: ['canDeactivate_simple']}], component: TeamCmp }] }]); router.navigateByUrl('/team/22'); advance(fixture); router.navigateByUrl('/team/33'); advance(fixture); expect(logger.logs).toEqual(['canDeactivate_simple', 'canDeactivate_team']); }))); }); }); describe('route events', () => { it('should fire matching (Child)ActivationStart/End events', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'user/:name', component: UserCmp}]); const recordedEvents: any[] = []; router.events.forEach(e => recordedEvents.push(e)); router.navigateByUrl('/user/fedor'); advance(fixture); expect(fixture.nativeElement).toHaveText('user fedor'); expect(recordedEvents[3] instanceof ChildActivationStart).toBe(true); expect(recordedEvents[3].snapshot).toBe(recordedEvents[9].snapshot.root); expect(recordedEvents[9] instanceof ChildActivationEnd).toBe(true); expect(recordedEvents[9].snapshot).toBe(recordedEvents[9].snapshot.root); expect(recordedEvents[4] instanceof ActivationStart).toBe(true); expect(recordedEvents[4].snapshot.routeConfig.path).toBe('user/:name'); expect(recordedEvents[8] instanceof ActivationEnd).toBe(true); expect(recordedEvents[8].snapshot.routeConfig.path).toBe('user/:name'); expectEvents(recordedEvents, [ [NavigationStart, '/user/fedor'], [RoutesRecognized, '/user/fedor'], [GuardsCheckStart, '/user/fedor'], [ChildActivationStart], [ActivationStart], [GuardsCheckEnd, '/user/fedor'], [ResolveStart, '/user/fedor'], [ResolveEnd, '/user/fedor'], [ActivationEnd], [ChildActivationEnd], [NavigationEnd, '/user/fedor'] ]); }))); it('should allow redirection in NavigationStart', fakeAsync(inject([Router], (router: Router) => { const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'blank', component: UserCmp}, {path: 'user/:name', component: BlankCmp}, ]); const navigateSpy = spyOn(router, 'navigate').and.callThrough(); const recordedEvents: any[] = []; const navStart$ = router.events.pipe( tap(e => recordedEvents.push(e)), filter(e => e instanceof NavigationStart), first()); navStart$.subscribe((e: NavigationStart | NavigationError) => { router.navigate( ['/blank'], {queryParams: {state: 'redirected'}, queryParamsHandling: 'merge'}); advance(fixture); }); router.navigate(['/user/:fedor']); advance(fixture); expect(navigateSpy.calls.mostRecent().args[1].queryParams); }))); }); describe('routerActiveLink', () => { it('should set the class when the link is active (a tag)', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [{ path: 'link', component: DummyLinkCmp, children: [{path: 'simple', component: SimpleCmp}, {path: '', component: BlankCmp}] }] }]); router.navigateByUrl('/team/22/link;exact=true'); advance(fixture); advance(fixture); expect(location.path()).toEqual('/team/22/link;exact=true'); const nativeLink = fixture.nativeElement.querySelector('a'); const nativeButton = fixture.nativeElement.querySelector('button'); expect(nativeLink.className).toEqual('active'); expect(nativeButton.className).toEqual('active'); router.navigateByUrl('/team/22/link/simple'); advance(fixture); expect(location.path()).toEqual('/team/22/link/simple'); expect(nativeLink.className).toEqual(''); expect(nativeButton.className).toEqual(''); }))); it('should not set the class until the first navigation succeeds', fakeAsync(() => { @Component({ template: '<router-outlet></router-outlet><a routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}" ></a>' }) class RootCmpWithLink { } TestBed.configureTestingModule({declarations: [RootCmpWithLink]}); const router: Router = TestBed.get(Router); const f = TestBed.createComponent(RootCmpWithLink); advance(f); const link = f.nativeElement.querySelector('a'); expect(link.className).toEqual(''); router.initialNavigation(); advance(f); expect(link.className).toEqual('active'); })); it('should set the class on a parent element when the link is active', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [{ path: 'link', component: DummyLinkWithParentCmp, children: [{path: 'simple', component: SimpleCmp}, {path: '', component: BlankCmp}] }] }]); router.navigateByUrl('/team/22/link;exact=true'); advance(fixture); advance(fixture); expect(location.path()).toEqual('/team/22/link;exact=true'); const native = fixture.nativeElement.querySelector('#link-parent'); expect(native.className).toEqual('active'); router.navigateByUrl('/team/22/link/simple'); advance(fixture); expect(location.path()).toEqual('/team/22/link/simple'); expect(native.className).toEqual(''); }))); it('should set the class when the link is active', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [{ path: 'link', component: DummyLinkCmp, children: [{path: 'simple', component: SimpleCmp}, {path: '', component: BlankCmp}] }] }]); router.navigateByUrl('/team/22/link'); advance(fixture); advance(fixture); expect(location.path()).toEqual('/team/22/link'); const native = fixture.nativeElement.querySelector('a'); expect(native.className).toEqual('active'); router.navigateByUrl('/team/22/link/simple'); advance(fixture); expect(location.path()).toEqual('/team/22/link/simple'); expect(native.className).toEqual('active'); }))); it('should expose an isActive property', fakeAsync(() => { @Component({ template: `<a routerLink="/team" routerLinkActive #rla="routerLinkActive"></a> <p>{{rla.isActive}}</p> <span *ngIf="rla.isActive"></span> <span [ngClass]="{'highlight': rla.isActive}"></span> <router-outlet></router-outlet>` }) class ComponentWithRouterLink { } TestBed.configureTestingModule({declarations: [ComponentWithRouterLink]}); const router: Router = TestBed.get(Router); router.resetConfig([ { path: 'team', component: TeamCmp, }, { path: 'otherteam', component: TeamCmp, } ]); const fixture = TestBed.createComponent(ComponentWithRouterLink); router.navigateByUrl('/team'); expect(() => advance(fixture)).not.toThrow(); advance(fixture); const paragraph = fixture.nativeElement.querySelector('p'); expect(paragraph.textContent).toEqual('true'); router.navigateByUrl('/otherteam'); advance(fixture); advance(fixture); expect(paragraph.textContent).toEqual('false'); })); }); describe('lazy loading', () => { it('works', fakeAsync(inject( [Router, Location, NgModuleFactoryLoader], (router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => { @Component({ selector: 'lazy', template: 'lazy-loaded-parent [<router-outlet></router-outlet>]' }) class ParentLazyLoadedComponent { } @Component({selector: 'lazy', template: 'lazy-loaded-child'}) class ChildLazyLoadedComponent { } @NgModule({ declarations: [ParentLazyLoadedComponent, ChildLazyLoadedComponent], imports: [RouterModule.forChild([{ path: 'loaded', component: ParentLazyLoadedComponent, children: [{path: 'child', component: ChildLazyLoadedComponent}] }])] }) class LoadedModule { } loader.stubbedModules = {expected: LoadedModule}; const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'lazy', loadChildren: 'expected'}]); router.navigateByUrl('/lazy/loaded/child'); advance(fixture); expect(location.path()).toEqual('/lazy/loaded/child'); expect(fixture.nativeElement).toHaveText('lazy-loaded-parent [lazy-loaded-child]'); }))); it('should have 2 injector trees: module and element', fakeAsync(inject( [Router, Location, NgModuleFactoryLoader], (router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => { @Component({ selector: 'lazy', template: 'parent[<router-outlet></router-outlet>]', viewProviders: [ {provide: 'shadow', useValue: 'from parent component'}, ], }) class Parent { } @Component({selector: 'lazy', template: 'child'}) class Child { } @NgModule({ declarations: [Parent], imports: [RouterModule.forChild([{ path: 'parent', component: Parent, children: [ {path: 'child', loadChildren: 'child'}, ] }])], providers: [ {provide: 'moduleName', useValue: 'parent'}, {provide: 'fromParent', useValue: 'from parent'}, ], }) class ParentModule { } @NgModule({ declarations: [Child], imports: [RouterModule.forChild([{path: '', component: Child}])], providers: [ {provide: 'moduleName', useValue: 'child'}, {provide: 'fromChild', useValue: 'from child'}, {provide: 'shadow', useValue: 'from child module'}, ], }) class ChildModule { } loader.stubbedModules = { parent: ParentModule, child: ChildModule, }; const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'lazy', loadChildren: 'parent'}]); router.navigateByUrl('/lazy/parent/child'); advance(fixture); expect(location.path()).toEqual('/lazy/parent/child'); expect(fixture.nativeElement).toHaveText('parent[child]'); const pInj = fixture.debugElement.query(By.directive(Parent)).injector !; const cInj = fixture.debugElement.query(By.directive(Child)).injector !; expect(pInj.get('moduleName')).toEqual('parent'); expect(pInj.get('fromParent')).toEqual('from parent'); expect(pInj.get(Parent)).toBeAnInstanceOf(Parent); expect(pInj.get('fromChild', null)).toEqual(null); expect(pInj.get(Child, null)).toEqual(null); expect(cInj.get('moduleName')).toEqual('child'); expect(cInj.get('fromParent')).toEqual('from parent'); expect(cInj.get('fromChild')).toEqual('from child'); expect(cInj.get(Parent)).toBeAnInstanceOf(Parent); expect(cInj.get(Child)).toBeAnInstanceOf(Child); // The child module can not shadow the parent component expect(cInj.get('shadow')).toEqual('from parent component'); const pmInj = pInj.get(NgModuleRef).injector; const cmInj = cInj.get(NgModuleRef).injector; expect(pmInj.get('moduleName')).toEqual('parent'); expect(cmInj.get('moduleName')).toEqual('child'); expect(pmInj.get(Parent, '-')).toEqual('-'); expect(cmInj.get(Parent, '-')).toEqual('-'); expect(pmInj.get(Child, '-')).toEqual('-'); expect(cmInj.get(Child, '-')).toEqual('-'); }))); // https://github.com/angular/angular/issues/12889 it('should create a single instance of lazy-loaded modules', fakeAsync(inject( [Router, Location, NgModuleFactoryLoader], (router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => { @Component({ selector: 'lazy', template: 'lazy-loaded-parent [<router-outlet></router-outlet>]' }) class ParentLazyLoadedComponent { } @Component({selector: 'lazy', template: 'lazy-loaded-child'}) class ChildLazyLoadedComponent { } @NgModule({ declarations: [ParentLazyLoadedComponent, ChildLazyLoadedComponent], imports: [RouterModule.forChild([{ path: 'loaded', component: ParentLazyLoadedComponent, children: [{path: 'child', component: ChildLazyLoadedComponent}] }])] }) class LoadedModule { static instances = 0; constructor() { LoadedModule.instances++; } } loader.stubbedModules = {expected: LoadedModule}; const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'lazy', loadChildren: 'expected'}]); router.navigateByUrl('/lazy/loaded/child'); advance(fixture); expect(fixture.nativeElement).toHaveText('lazy-loaded-parent [lazy-loaded-child]'); expect(LoadedModule.instances).toEqual(1); }))); // https://github.com/angular/angular/issues/13870 it('should create a single instance of guards for lazy-loaded modules', fakeAsync(inject( [Router, Location, NgModuleFactoryLoader], (router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => { @Injectable() class Service { } @Injectable() class Resolver implements Resolve<Service> { constructor(public service: Service) {} resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { return this.service; } } @Component({selector: 'lazy', template: 'lazy'}) class LazyLoadedComponent { resolvedService: Service; constructor(public injectedService: Service, route: ActivatedRoute) { this.resolvedService = route.snapshot.data['service']; } } @NgModule({ declarations: [LazyLoadedComponent], providers: [Service, Resolver], imports: [ RouterModule.forChild([{ path: 'loaded', component: LazyLoadedComponent, resolve: {'service': Resolver}, }]), ] }) class LoadedModule { } loader.stubbedModules = {expected: LoadedModule}; const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'lazy', loadChildren: 'expected'}]); router.navigateByUrl('/lazy/loaded'); advance(fixture); expect(fixture.nativeElement).toHaveText('lazy'); const lzc = fixture.debugElement.query(By.directive(LazyLoadedComponent)).componentInstance; expect(lzc.injectedService).toBe(lzc.resolvedService); }))); it('should emit RouteConfigLoadStart and RouteConfigLoadEnd event when route is lazy loaded', fakeAsync(inject( [Router, Location, NgModuleFactoryLoader], (router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => { @Component({ selector: 'lazy', template: 'lazy-loaded-parent [<router-outlet></router-outlet>]', }) class ParentLazyLoadedComponent { } @Component({selector: 'lazy', template: 'lazy-loaded-child'}) class ChildLazyLoadedComponent { } @NgModule({ declarations: [ParentLazyLoadedComponent, ChildLazyLoadedComponent], imports: [RouterModule.forChild([{ path: 'loaded', component: ParentLazyLoadedComponent, children: [{path: 'child', component: ChildLazyLoadedComponent}], }])] }) class LoadedModule { } const events: Array<RouteConfigLoadStart|RouteConfigLoadEnd> = []; router.events.subscribe(e => { if (e instanceof RouteConfigLoadStart || e instanceof RouteConfigLoadEnd) { events.push(e); } }); loader.stubbedModules = {expected: LoadedModule}; const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'lazy', loadChildren: 'expected'}]); router.navigateByUrl('/lazy/loaded/child'); advance(fixture); expect(events.length).toEqual(2); expect(events[0].toString()).toEqual('RouteConfigLoadStart(path: lazy)'); expect(events[1].toString()).toEqual('RouteConfigLoadEnd(path: lazy)'); }))); it('throws an error when forRoot() is used in a lazy context', fakeAsync(inject( [Router, Location, NgModuleFactoryLoader], (router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => { @Component({selector: 'lazy', template: 'should not show'}) class LazyLoadedComponent { } @NgModule({ declarations: [LazyLoadedComponent], imports: [RouterModule.forRoot([{path: 'loaded', component: LazyLoadedComponent}])] }) class LoadedModule { } loader.stubbedModules = {expected: LoadedModule}; const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'lazy', loadChildren: 'expected'}]); let recordedError: any = null; router.navigateByUrl('/lazy/loaded') !.catch(err => recordedError = err); advance(fixture); expect(recordedError.message) .toEqual( `RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead.`); }))); it('should combine routes from multiple modules into a single configuration', fakeAsync(inject( [Router, Location, NgModuleFactoryLoader], (router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => { @Component({selector: 'lazy', template: 'lazy-loaded-2'}) class LazyComponent2 { } @NgModule({ declarations: [LazyComponent2], imports: [RouterModule.forChild([{path: 'loaded', component: LazyComponent2}])] }) class SiblingOfLoadedModule { } @Component({selector: 'lazy', template: 'lazy-loaded-1'}) class LazyComponent1 { } @NgModule({ declarations: [LazyComponent1], imports: [ RouterModule.forChild([{path: 'loaded', component: LazyComponent1}]), SiblingOfLoadedModule ] }) class LoadedModule { } loader.stubbedModules = {expected1: LoadedModule, expected2: SiblingOfLoadedModule}; const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'lazy1', loadChildren: 'expected1'}, {path: 'lazy2', loadChildren: 'expected2'} ]); router.navigateByUrl('/lazy1/loaded'); advance(fixture); expect(location.path()).toEqual('/lazy1/loaded'); router.navigateByUrl('/lazy2/loaded'); advance(fixture); expect(location.path()).toEqual('/lazy2/loaded'); }))); it('should allow lazy loaded module in named outlet', fakeAsync(inject( [Router, NgModuleFactoryLoader], (router: Router, loader: SpyNgModuleFactoryLoader) => { @Component({selector: 'lazy', template: 'lazy-loaded'}) class LazyComponent { } @NgModule({ declarations: [LazyComponent], imports: [RouterModule.forChild([{path: '', component: LazyComponent}])] }) class LazyLoadedModule { } loader.stubbedModules = {lazyModule: LazyLoadedModule}; const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [ {path: 'user/:name', component: UserCmp}, {path: 'lazy', loadChildren: 'lazyModule', outlet: 'right'}, ] }]); router.navigateByUrl('/team/22/user/john'); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ user john, right: ]'); router.navigateByUrl('/team/22/(user/john//right:lazy)'); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ user john, right: lazy-loaded ]'); }))); it('should allow componentless named outlet to render children', fakeAsync(inject( [Router, NgModuleFactoryLoader], (router: Router, loader: SpyNgModuleFactoryLoader) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'team/:id', component: TeamCmp, children: [ {path: 'user/:name', component: UserCmp}, {path: 'simple', outlet: 'right', children: [{path: '', component: SimpleCmp}]}, ] }]); router.navigateByUrl('/team/22/user/john'); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ user john, right: ]'); router.navigateByUrl('/team/22/(user/john//right:simple)'); advance(fixture); expect(fixture.nativeElement).toHaveText('team 22 [ user john, right: simple ]'); }))); describe('should use the injector of the lazily-loaded configuration', () => { class LazyLoadedServiceDefinedInModule {} @Component({ selector: 'eager-parent', template: 'eager-parent <router-outlet></router-outlet>', }) class EagerParentComponent { } @Component({ selector: 'lazy-parent', template: 'lazy-parent <router-outlet></router-outlet>', }) class LazyParentComponent { } @Component({ selector: 'lazy-child', template: 'lazy-child', }) class LazyChildComponent { constructor( lazy: LazyParentComponent, // should be able to inject lazy/direct parent lazyService: LazyLoadedServiceDefinedInModule, // should be able to inject lazy service eager: EagerParentComponent // should use the injector of the location to create a parent ) {} } @NgModule({ declarations: [LazyParentComponent, LazyChildComponent], imports: [RouterModule.forChild([{ path: '', children: [{ path: 'lazy-parent', component: LazyParentComponent, children: [{path: 'lazy-child', component: LazyChildComponent}] }] }])], providers: [LazyLoadedServiceDefinedInModule] }) class LoadedModule { } @NgModule({ declarations: [EagerParentComponent], entryComponents: [EagerParentComponent], imports: [RouterModule] }) class TestModule { } beforeEach(() => { TestBed.configureTestingModule({ imports: [TestModule], }); }); it('should use the injector of the lazily-loaded configuration', fakeAsync(inject( [Router, Location, NgModuleFactoryLoader], (router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => { loader.stubbedModules = {expected: LoadedModule}; const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'eager-parent', component: EagerParentComponent, children: [{path: 'lazy', loadChildren: 'expected'}] }]); router.navigateByUrl('/eager-parent/lazy/lazy-parent/lazy-child'); advance(fixture); expect(location.path()).toEqual('/eager-parent/lazy/lazy-parent/lazy-child'); expect(fixture.nativeElement).toHaveText('eager-parent lazy-parent lazy-child'); }))); }); it('works when given a callback', fakeAsync(inject( [Router, Location, NgModuleFactoryLoader], (router: Router, location: Location) => { @Component({selector: 'lazy', template: 'lazy-loaded'}) class LazyLoadedComponent { } @NgModule({ declarations: [LazyLoadedComponent], imports: [RouterModule.forChild([{path: 'loaded', component: LazyLoadedComponent}])], }) class LoadedModule { } const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'lazy', loadChildren: () => LoadedModule}]); router.navigateByUrl('/lazy/loaded'); advance(fixture); expect(location.path()).toEqual('/lazy/loaded'); expect(fixture.nativeElement).toHaveText('lazy-loaded'); }))); it('error emit an error when cannot load a config', fakeAsync(inject( [Router, Location, NgModuleFactoryLoader], (router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => { loader.stubbedModules = {}; const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'lazy', loadChildren: 'invalid'}]); const recordedEvents: any[] = []; router.events.forEach(e => recordedEvents.push(e)); router.navigateByUrl('/lazy/loaded') !.catch(s => {}); advance(fixture); expect(location.path()).toEqual('/'); expectEvents(recordedEvents, [ [NavigationStart, '/lazy/loaded'], [RouteConfigLoadStart], [NavigationError, '/lazy/loaded'], ]); }))); it('should work with complex redirect rules', fakeAsync(inject( [Router, Location, NgModuleFactoryLoader], (router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => { @Component({selector: 'lazy', template: 'lazy-loaded'}) class LazyLoadedComponent { } @NgModule({ declarations: [LazyLoadedComponent], imports: [RouterModule.forChild([{path: 'loaded', component: LazyLoadedComponent}])], }) class LoadedModule { } loader.stubbedModules = {lazy: LoadedModule}; const fixture = createRoot(router, RootCmp); router.resetConfig( [{path: 'lazy', loadChildren: 'lazy'}, {path: '**', redirectTo: 'lazy'}]); router.navigateByUrl('/lazy/loaded'); advance(fixture); expect(location.path()).toEqual('/lazy/loaded'); }))); it('should work with wildcard route', fakeAsync(inject( [Router, Location, NgModuleFactoryLoader], (router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => { @Component({selector: 'lazy', template: 'lazy-loaded'}) class LazyLoadedComponent { } @NgModule({ declarations: [LazyLoadedComponent], imports: [RouterModule.forChild([{path: '', component: LazyLoadedComponent}])], }) class LazyLoadedModule { } loader.stubbedModules = {lazy: LazyLoadedModule}; const fixture = createRoot(router, RootCmp); router.resetConfig([{path: '**', loadChildren: 'lazy'}]); router.navigateByUrl('/lazy'); advance(fixture); expect(location.path()).toEqual('/lazy'); expect(fixture.nativeElement).toHaveText('lazy-loaded'); }))); describe('preloading', () => { beforeEach(() => { TestBed.configureTestingModule( {providers: [{provide: PreloadingStrategy, useExisting: PreloadAllModules}]}); const preloader = TestBed.get(RouterPreloader); preloader.setUpPreloading(); }); it('should work', fakeAsync(inject( [Router, Location, NgModuleFactoryLoader], (router: Router, location: Location, loader: SpyNgModuleFactoryLoader) => { @Component({selector: 'lazy', template: 'should not show'}) class LazyLoadedComponent { } @NgModule({ declarations: [LazyLoadedComponent], imports: [RouterModule.forChild( [{path: 'LoadedModule2', component: LazyLoadedComponent}])] }) class LoadedModule2 { } @NgModule({ imports: [RouterModule.forChild([{path: 'LoadedModule1', loadChildren: 'expected2'}])] }) class LoadedModule1 { } loader.stubbedModules = {expected: LoadedModule1, expected2: LoadedModule2}; const fixture = createRoot(router, RootCmp); router.resetConfig([ {path: 'blank', component: BlankCmp}, {path: 'lazy', loadChildren: 'expected'} ]); router.navigateByUrl('/blank'); advance(fixture); const config = router.config as any; const firstConfig = config[1]._loadedConfig !; expect(firstConfig).toBeDefined(); expect(firstConfig.routes[0].path).toEqual('LoadedModule1'); const secondConfig = firstConfig.routes[0]._loadedConfig !; expect(secondConfig).toBeDefined(); expect(secondConfig.routes[0].path).toEqual('LoadedModule2'); }))); }); describe('custom url handling strategies', () => { class CustomUrlHandlingStrategy implements UrlHandlingStrategy { shouldProcessUrl(url: UrlTree): boolean { return url.toString().startsWith('/include') || url.toString() === '/'; } extract(url: UrlTree): UrlTree { const oldRoot = url.root; const children: any = {}; if (oldRoot.children[PRIMARY_OUTLET]) { children[PRIMARY_OUTLET] = oldRoot.children[PRIMARY_OUTLET]; } const root = new UrlSegmentGroup(oldRoot.segments, children); return new (UrlTree as any)(root, url.queryParams, url.fragment); } merge(newUrlPart: UrlTree, wholeUrl: UrlTree): UrlTree { const oldRoot = newUrlPart.root; const children: any = {}; if (oldRoot.children[PRIMARY_OUTLET]) { children[PRIMARY_OUTLET] = oldRoot.children[PRIMARY_OUTLET]; } forEach(wholeUrl.root.children, (v: any, k: any) => { if (k !== PRIMARY_OUTLET) { children[k] = v; } v.parent = this; }); const root = new UrlSegmentGroup(oldRoot.segments, children); return new (UrlTree as any)(root, newUrlPart.queryParams, newUrlPart.fragment); } } beforeEach(() => { TestBed.configureTestingModule( {providers: [{provide: UrlHandlingStrategy, useClass: CustomUrlHandlingStrategy}]}); }); it('should work', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'include', component: TeamCmp, children: [ {path: 'user/:name', component: UserCmp}, {path: 'simple', component: SimpleCmp} ] }]); const events: any[] = []; router.events.subscribe(e => e instanceof RouterEvent && events.push(e)); // supported URL router.navigateByUrl('/include/user/kate'); advance(fixture); expect(location.path()).toEqual('/include/user/kate'); expectEvents(events, [ [NavigationStart, '/include/user/kate'], [RoutesRecognized, '/include/user/kate'], [GuardsCheckStart, '/include/user/kate'], [GuardsCheckEnd, '/include/user/kate'], [ResolveStart, '/include/user/kate'], [ResolveEnd, '/include/user/kate'], [NavigationEnd, '/include/user/kate'] ]); expect(fixture.nativeElement).toHaveText('team [ user kate, right: ]'); events.splice(0); // unsupported URL router.navigateByUrl('/exclude/one'); advance(fixture); expect(location.path()).toEqual('/exclude/one'); expect(Object.keys(router.routerState.root.children).length).toEqual(0); expect(fixture.nativeElement).toHaveText(''); expectEvents(events, [ [NavigationStart, '/exclude/one'], [GuardsCheckStart, '/exclude/one'], [GuardsCheckEnd, '/exclude/one'], [NavigationEnd, '/exclude/one'] ]); events.splice(0); // another unsupported URL location.go('/exclude/two'); advance(fixture); expect(location.path()).toEqual('/exclude/two'); expectEvents(events, []); // back to a supported URL location.go('/include/simple'); advance(fixture); expect(location.path()).toEqual('/include/simple'); expect(fixture.nativeElement).toHaveText('team [ simple, right: ]'); expectEvents(events, [ [NavigationStart, '/include/simple'], [RoutesRecognized, '/include/simple'], [GuardsCheckStart, '/include/simple'], [GuardsCheckEnd, '/include/simple'], [ResolveStart, '/include/simple'], [ResolveEnd, '/include/simple'], [NavigationEnd, '/include/simple'] ]); }))); it('should handle the case when the router takes only the primary url', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.resetConfig([{ path: 'include', component: TeamCmp, children: [ {path: 'user/:name', component: UserCmp}, {path: 'simple', component: SimpleCmp} ] }]); const events: any[] = []; router.events.subscribe(e => e instanceof RouterEvent && events.push(e)); location.go('/include/user/kate(aux:excluded)'); advance(fixture); expect(location.path()).toEqual('/include/user/kate(aux:excluded)'); expectEvents(events, [ [NavigationStart, '/include/user/kate'], [RoutesRecognized, '/include/user/kate'], [GuardsCheckStart, '/include/user/kate'], [GuardsCheckEnd, '/include/user/kate'], [ResolveStart, '/include/user/kate'], [ResolveEnd, '/include/user/kate'], [NavigationEnd, '/include/user/kate'] ]); events.splice(0); location.go('/include/user/kate(aux:excluded2)'); advance(fixture); expectEvents(events, []); router.navigateByUrl('/include/simple'); advance(fixture); expect(location.path()).toEqual('/include/simple(aux:excluded2)'); expectEvents(events, [ [NavigationStart, '/include/simple'], [RoutesRecognized, '/include/simple'], [GuardsCheckStart, '/include/simple'], [GuardsCheckEnd, '/include/simple'], [ResolveStart, '/include/simple'], [ResolveEnd, '/include/simple'], [NavigationEnd, '/include/simple'] ]); }))); }); describe('relativeLinkResolution', () => { @Component({selector: 'link-cmp', template: `<a [routerLink]="['../simple']">link</a>`}) class RelativeLinkCmp { } @NgModule({ declarations: [RelativeLinkCmp], imports: [RouterModule.forChild([ {path: 'foo/bar', children: [{path: '', component: RelativeLinkCmp}]}, ])] }) class LazyLoadedModule { } it('should not ignore empty path when in legacy mode', fakeAsync(inject( [Router, NgModuleFactoryLoader], (router: Router, loader: SpyNgModuleFactoryLoader) => { router.relativeLinkResolution = 'legacy'; loader.stubbedModules = {expected: LazyLoadedModule}; const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'lazy', loadChildren: 'expected'}]); router.navigateByUrl('/lazy/foo/bar'); advance(fixture); const link = fixture.nativeElement.querySelector('a'); expect(link.getAttribute('href')).toEqual('/lazy/foo/bar/simple'); }))); it('should ignore empty path when in corrected mode', fakeAsync(inject( [Router, NgModuleFactoryLoader], (router: Router, loader: SpyNgModuleFactoryLoader) => { router.relativeLinkResolution = 'corrected'; loader.stubbedModules = {expected: LazyLoadedModule}; const fixture = createRoot(router, RootCmp); router.resetConfig([{path: 'lazy', loadChildren: 'expected'}]); router.navigateByUrl('/lazy/foo/bar'); advance(fixture); const link = fixture.nativeElement.querySelector('a'); expect(link.getAttribute('href')).toEqual('/lazy/foo/simple'); }))); }); }); describe('Custom Route Reuse Strategy', () => { class AttachDetachReuseStrategy implements RouteReuseStrategy { stored: {[k: string]: DetachedRouteHandle} = {}; shouldDetach(route: ActivatedRouteSnapshot): boolean { return route.routeConfig !.path === 'a'; } store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void { this.stored[route.routeConfig !.path !] = detachedTree; } shouldAttach(route: ActivatedRouteSnapshot): boolean { return !!this.stored[route.routeConfig !.path !]; } retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle { return this.stored[route.routeConfig !.path !]; } shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean { return future.routeConfig === curr.routeConfig; } } class ShortLifecycle implements RouteReuseStrategy { shouldDetach(route: ActivatedRouteSnapshot): boolean { return false; } store(route: ActivatedRouteSnapshot, detachedTree: DetachedRouteHandle): void {} shouldAttach(route: ActivatedRouteSnapshot): boolean { return false; } retrieve(route: ActivatedRouteSnapshot): DetachedRouteHandle|null { return null; } shouldReuseRoute(future: ActivatedRouteSnapshot, curr: ActivatedRouteSnapshot): boolean { if (future.routeConfig !== curr.routeConfig) { return false; } if (Object.keys(future.params).length !== Object.keys(curr.params).length) { return false; } return Object.keys(future.params).every(k => future.params[k] === curr.params[k]); } } it('should support attaching & detaching fragments', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.routeReuseStrategy = new AttachDetachReuseStrategy(); router.resetConfig([ { path: 'a', component: TeamCmp, children: [{path: 'b', component: SimpleCmp}], }, {path: 'c', component: UserCmp}, ]); router.navigateByUrl('/a/b'); advance(fixture); const teamCmp = fixture.debugElement.children[1].componentInstance; const simpleCmp = fixture.debugElement.children[1].children[1].componentInstance; expect(location.path()).toEqual('/a/b'); expect(teamCmp).toBeDefined(); expect(simpleCmp).toBeDefined(); router.navigateByUrl('/c'); advance(fixture); expect(location.path()).toEqual('/c'); expect(fixture.debugElement.children[1].componentInstance).toBeAnInstanceOf(UserCmp); router.navigateByUrl('/a;p=1/b;p=2'); advance(fixture); const teamCmp2 = fixture.debugElement.children[1].componentInstance; const simpleCmp2 = fixture.debugElement.children[1].children[1].componentInstance; expect(location.path()).toEqual('/a;p=1/b;p=2'); expect(teamCmp2).toBe(teamCmp); expect(simpleCmp2).toBe(simpleCmp); expect(teamCmp.route).toBe(router.routerState.root.firstChild); expect(teamCmp.route.snapshot).toBe(router.routerState.snapshot.root.firstChild); expect(teamCmp.route.snapshot.params).toEqual({p: '1'}); expect(teamCmp.route.firstChild.snapshot.params).toEqual({p: '2'}); }))); it('should support shorter lifecycles', fakeAsync(inject([Router, Location], (router: Router, location: Location) => { const fixture = createRoot(router, RootCmp); router.routeReuseStrategy = new ShortLifecycle(); router.resetConfig([{path: 'a', component: SimpleCmp}]); router.navigateByUrl('/a'); advance(fixture); const simpleCmp1 = fixture.debugElement.children[1].componentInstance; expect(location.path()).toEqual('/a'); router.navigateByUrl('/a;p=1'); advance(fixture); expect(location.path()).toEqual('/a;p=1'); const simpleCmp2 = fixture.debugElement.children[1].componentInstance; expect(simpleCmp1).not.toBe(simpleCmp2); }))); it('should not mount the component of the previously reused route when the outlet was not instantiated at the time of route activation', fakeAsync(() => { @Component({ selector: 'root-cmp', template: '<div *ngIf="isToolpanelShowing"><router-outlet name="toolpanel"></router-outlet></div>' }) class RootCmpWithCondOutlet implements OnDestroy { private subscription: Subscription; public isToolpanelShowing: boolean = false; constructor(router: Router) { this.subscription = router.events.pipe(filter(event => event instanceof NavigationEnd)) .subscribe( () => this.isToolpanelShowing = !!router.parseUrl(router.url).root.children['toolpanel']); } public ngOnDestroy(): void { this.subscription.unsubscribe(); } } @Component({selector: 'tool-1-cmp', template: 'Tool 1 showing'}) class Tool1Component { } @Component({selector: 'tool-2-cmp', template: 'Tool 2 showing'}) class Tool2Component { } @NgModule({ declarations: [RootCmpWithCondOutlet, Tool1Component, Tool2Component], imports: [ CommonModule, RouterTestingModule.withRoutes([ {path: 'a', outlet: 'toolpanel', component: Tool1Component}, {path: 'b', outlet: 'toolpanel', component: Tool2Component}, ]), ], }) class TestModule { } TestBed.configureTestingModule({imports: [TestModule]}); const router: Router = TestBed.get(Router); router.routeReuseStrategy = new AttachDetachReuseStrategy(); const fixture = createRoot(router, RootCmpWithCondOutlet); // Activate 'tool-1' router.navigate([{outlets: {toolpanel: 'a'}}]); advance(fixture); expect(fixture).toContainComponent(Tool1Component, '(a)'); // Deactivate 'tool-1' router.navigate([{outlets: {toolpanel: null}}]); advance(fixture); expect(fixture).not.toContainComponent(Tool1Component, '(b)'); // Activate 'tool-1' router.navigate([{outlets: {toolpanel: 'a'}}]); advance(fixture); expect(fixture).toContainComponent(Tool1Component, '(c)'); // Deactivate 'tool-1' router.navigate([{outlets: {toolpanel: null}}]); advance(fixture); expect(fixture).not.toContainComponent(Tool1Component, '(d)'); // Activate 'tool-2' router.navigate([{outlets: {toolpanel: 'b'}}]); advance(fixture); expect(fixture).toContainComponent(Tool2Component, '(e)'); })); }); }); describe('Testing router options', () => { describe('paramsInheritanceStrategy', () => { beforeEach(() => { TestBed.configureTestingModule( {imports: [RouterTestingModule.withRoutes([], {paramsInheritanceStrategy: 'always'})]}); }); it('should configure the router', fakeAsync(inject([Router], (router: Router) => { expect(router.paramsInheritanceStrategy).toEqual('always'); }))); }); describe('malformedUriErrorHandler', () => { function malformedUriErrorHandler(e: URIError, urlSerializer: UrlSerializer, url: string) { return urlSerializer.parse('/error'); } beforeEach(() => { TestBed.configureTestingModule( {imports: [RouterTestingModule.withRoutes([], {malformedUriErrorHandler})]}); }); it('should configure the router', fakeAsync(inject([Router], (router: Router) => { expect(router.malformedUriErrorHandler).toBe(malformedUriErrorHandler); }))); }); }); function expectEvents(events: Event[], pairs: any[]) { expect(events.length).toEqual(pairs.length); for (let i = 0; i < events.length; ++i) { expect((<any>events[i].constructor).name).toBe(pairs[i][0].name); expect((<any>events[i]).url).toBe(pairs[i][1]); } } function onlyNavigationStartAndEnd(e: Event): boolean { return e instanceof NavigationStart || e instanceof NavigationEnd; } @Component( {selector: 'link-cmp', template: `<a routerLink="/team/33/simple" [target]="'_self'">link</a>`}) class StringLinkCmp { } @Component({selector: 'link-cmp', template: `<button routerLink="/team/33/simple">link</button>`}) class StringLinkButtonCmp { } @Component({ selector: 'link-cmp', template: `<router-outlet></router-outlet><a [routerLink]="['/team/33/simple']">link</a>` }) class AbsoluteLinkCmp { } @Component({ selector: 'link-cmp', template: `<router-outlet></router-outlet><a routerLinkActive="active" [routerLinkActiveOptions]="{exact: exact}" [routerLink]="['./']">link</a> <button routerLinkActive="active" [routerLinkActiveOptions]="{exact: exact}" [routerLink]="['./']">button</button> ` }) class DummyLinkCmp { private exact: boolean; constructor(route: ActivatedRoute) { this.exact = route.snapshot.paramMap.get('exact') === 'true'; } } @Component({selector: 'link-cmp', template: `<a [routerLink]="['/simple']">link</a>`}) class AbsoluteSimpleLinkCmp { } @Component({selector: 'link-cmp', template: `<a [routerLink]="['../simple']">link</a>`}) class RelativeLinkCmp { } @Component({ selector: 'link-cmp', template: `<a [routerLink]="['../simple']" [queryParams]="{q: '1'}" fragment="f">link</a>` }) class LinkWithQueryParamsAndFragment { } @Component({ selector: 'link-cmp', template: `<a [routerLink]="['../simple']" [state]="{foo: 'bar'}">link</a>` }) class LinkWithState { } @Component({selector: 'simple-cmp', template: `simple`}) class SimpleCmp { } @Component({selector: 'collect-params-cmp', template: `collect-params`}) class CollectParamsCmp { private params: any = []; private urls: any = []; constructor(private route: ActivatedRoute) { route.params.forEach(p => this.params.push(p)); route.url.forEach(u => this.urls.push(u)); } recordedUrls(): string[] { return this.urls.map((a: any) => a.map((p: any) => p.path).join('/')); } } @Component({selector: 'blank-cmp', template: ``}) class BlankCmp { } @Component({ selector: 'team-cmp', template: `team {{id | async}} ` + `[ <router-outlet></router-outlet>, right: <router-outlet name="right"></router-outlet> ]` + `<a [routerLink]="routerLink" skipLocationChange></a>` + `<button [routerLink]="routerLink" skipLocationChange></button>` }) class TeamCmp { id: Observable<string>; recordedParams: Params[] = []; snapshotParams: Params[] = []; routerLink = ['.']; constructor(public route: ActivatedRoute) { this.id = route.params.pipe(map((p: any) => p['id'])); route.params.forEach(p => { this.recordedParams.push(p); this.snapshotParams.push(route.snapshot.params); }); } } @Component({ selector: 'two-outlets-cmp', template: `[ <router-outlet></router-outlet>, aux: <router-outlet name="aux"></router-outlet> ]` }) class TwoOutletsCmp { } @Component({selector: 'user-cmp', template: `user {{name | async}}`}) class UserCmp { name: Observable<string>; recordedParams: Params[] = []; snapshotParams: Params[] = []; constructor(route: ActivatedRoute) { this.name = route.params.pipe(map((p: any) => p['name'])); route.params.forEach(p => { this.recordedParams.push(p); this.snapshotParams.push(route.snapshot.params); }); } } @Component({selector: 'wrapper', template: `<router-outlet></router-outlet>`}) class WrapperCmp { } @Component( {selector: 'query-cmp', template: `query: {{name | async}} fragment: {{fragment | async}}`}) class QueryParamsAndFragmentCmp { name: Observable<string|null>; fragment: Observable<string>; constructor(route: ActivatedRoute) { this.name = route.queryParamMap.pipe(map((p: ParamMap) => p.get('name'))); this.fragment = route.fragment; } } @Component({selector: 'empty-query-cmp', template: ``}) class EmptyQueryParamsCmp { recordedParams: Params[] = []; constructor(route: ActivatedRoute) { route.queryParams.forEach(_ => this.recordedParams.push(_)); } } @Component({selector: 'route-cmp', template: `route`}) class RouteCmp { constructor(public route: ActivatedRoute) {} } @Component({ selector: 'link-cmp', template: `<div *ngIf="show"><a [routerLink]="['./simple']">link</a></div> <router-outlet></router-outlet>` }) class RelativeLinkInIfCmp { show: boolean = false; } @Component( {selector: 'child', template: '<div *ngIf="alwaysTrue"><router-outlet></router-outlet></div>'}) class OutletInNgIf { alwaysTrue = true; } @Component({ selector: 'link-cmp', template: `<router-outlet></router-outlet> <div id="link-parent" routerLinkActive="active" [routerLinkActiveOptions]="{exact: exact}"> <div ngClass="{one: 'true'}"><a [routerLink]="['./']">link</a></div> </div>` }) class DummyLinkWithParentCmp { private exact: boolean; constructor(route: ActivatedRoute) { this.exact = (<any>route.snapshot.params).exact === 'true'; } } @Component({selector: 'cmp', template: ''}) class ComponentRecordingRoutePathAndUrl { private path: any; private url: any; constructor(router: Router, route: ActivatedRoute) { this.path = (router.routerState as any).pathFromRoot(route); this.url = router.url.toString(); } } @Component({selector: 'root-cmp', template: `<router-outlet></router-outlet>`}) class RootCmp { } @Component({selector: 'root-cmp-on-init', template: `<router-outlet></router-outlet>`}) class RootCmpWithOnInit { constructor(private router: Router) {} ngOnInit(): void { this.router.navigate(['one']); } } @Component({ selector: 'root-cmp', template: `primary [<router-outlet></router-outlet>] right [<router-outlet name="right"></router-outlet>]` }) class RootCmpWithTwoOutlets { } @Component({selector: 'root-cmp', template: `main [<router-outlet name="main"></router-outlet>]`}) class RootCmpWithNamedOutlet { } @Component({selector: 'throwing-cmp', template: ''}) class ThrowingCmp { constructor() { throw new Error('Throwing Cmp'); } } function advance(fixture: ComponentFixture<any>, millis?: number): void { tick(millis); fixture.detectChanges(); } function createRoot(router: Router, type: any): ComponentFixture<any> { const f = TestBed.createComponent(type); advance(f); router.initialNavigation(); advance(f); return f; } @Component({selector: 'lazy', template: 'lazy-loaded'}) class LazyComponent { } @NgModule({ imports: [RouterTestingModule, CommonModule], entryComponents: [ BlankCmp, SimpleCmp, TwoOutletsCmp, TeamCmp, UserCmp, StringLinkCmp, DummyLinkCmp, AbsoluteLinkCmp, AbsoluteSimpleLinkCmp, RelativeLinkCmp, DummyLinkWithParentCmp, LinkWithQueryParamsAndFragment, LinkWithState, CollectParamsCmp, QueryParamsAndFragmentCmp, StringLinkButtonCmp, WrapperCmp, OutletInNgIf, ComponentRecordingRoutePathAndUrl, RouteCmp, RootCmp, RelativeLinkInIfCmp, RootCmpWithTwoOutlets, RootCmpWithNamedOutlet, EmptyQueryParamsCmp, ThrowingCmp ], exports: [ BlankCmp, SimpleCmp, TwoOutletsCmp, TeamCmp, UserCmp, StringLinkCmp, DummyLinkCmp, AbsoluteLinkCmp, AbsoluteSimpleLinkCmp, RelativeLinkCmp, DummyLinkWithParentCmp, LinkWithQueryParamsAndFragment, LinkWithState, CollectParamsCmp, QueryParamsAndFragmentCmp, StringLinkButtonCmp, WrapperCmp, OutletInNgIf, ComponentRecordingRoutePathAndUrl, RouteCmp, RootCmp, RootCmpWithOnInit, RelativeLinkInIfCmp, RootCmpWithTwoOutlets, RootCmpWithNamedOutlet, EmptyQueryParamsCmp, ThrowingCmp ], declarations: [ BlankCmp, SimpleCmp, TeamCmp, TwoOutletsCmp, UserCmp, StringLinkCmp, DummyLinkCmp, AbsoluteLinkCmp, AbsoluteSimpleLinkCmp, RelativeLinkCmp, DummyLinkWithParentCmp, LinkWithQueryParamsAndFragment, LinkWithState, CollectParamsCmp, QueryParamsAndFragmentCmp, StringLinkButtonCmp, WrapperCmp, OutletInNgIf, ComponentRecordingRoutePathAndUrl, RouteCmp, RootCmp, RootCmpWithOnInit, RelativeLinkInIfCmp, RootCmpWithTwoOutlets, RootCmpWithNamedOutlet, EmptyQueryParamsCmp, ThrowingCmp ] }) class TestModule { }
hansl/angular
packages/router/test/integration.spec.ts
TypeScript
mit
182,197
/*global require module*/ var q = require('q'); var async = require('async'); var constants = require('./_constants'); var Logger = require('./logger'); var CompiledNode = require('./compiled-node'); var EvaluatedNode = require('./evaluated-node'); var _8a2a4f008c464f9b81b3b5f4e75772c5 = { evaluateValue: function(mapper, logger, parent, name, instanceNode, requiredOnly) { var evaluated = new EvaluatedNode(this); evaluated.content = this.value; return q().then(function () { return evaluated; }); }, evaluateObject: function(mapper, logger, parent, name, instanceNode, requiredOnly) { var self = this; var defer = q.defer(); var hasMissingNode = false; var evaluated = new EvaluatedNode(this); evaluated.children = (this.children instanceof Array) ? [] : {}; evaluated.content = (this.children instanceof Array) ? [] : {}; async.each( Object.keys(self.children), function (key, done) { self.children[key].evaluate(mapper, logger, evaluated, key, instanceNode).then(function (child) { evaluated.children[key] = child; evaluated.content[key] = child.content; hasMissingNode = hasMissingNode || child.isMissing; }) .finally(function () { done(); }) }, function (err) { if (hasMissingNode) { evaluated.content = null; evaluated.isMissing = (self.isRequired); } defer.resolve(evaluated); } ); return defer.promise } }; module.exports = Module; /*------------------------------------------------------------------------------ A module contains 0, 1 or more properties A property contains 0 or 1 selector and 0 or 1 module ------------------------------------------------------------------------------*/ function Module(source) { var helper = _8a2a4f008c464f9b81b3b5f4e75772c5; function getSource(mapper, logger) { function _getSource(source) { if (source) { if (typeof(source) === 'function') { return _getSource(source(mapper, logger)); } if (typeof(source.getSource) === 'function') { return _getSource(source.getSource(mapper, logger)); } } return source; } return _getSource(source); } function validate(mapper, instanceNode, logger) { return q().then(function () { return getSourceModule(mapper, module); }) .then(function (module) { if (module === undefined) { return true; } else if (module === null) { return true; } else if (typeof(module.validate) === 'function') { return module.validate(mapper, instanceNode); } else { return true; } }); } function __compile(parent, source, name) { var compiled = new CompiledNode(null, null, parent, name); if (source !== undefined && source !== null) { var content = source.content; if (content === undefined) { compiled.value = content; compiled.setIsRequired(false); compiled._evaluate = helper.evaluateValue; } else if (content === null) { compiled.value = content; compiled.setIsRequired(false); compiled._evaluate = helper.evaluateValue; } else if (content.$isModule) { compiled = content._compile(parent, name); } else if (content[constants.interface.compile]) { compiled = content[constants.interface.compile]._compile(parent, name); } else if (typeof(content) === 'object') { compiled._evaluate = helper.evaluateObject; compiled.children = (content instanceof Array) ? [] : {}; compiled.newContent(); var keys = Object.keys(content); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var child = __compile(compiled, {content: content[key]}, key); compiled.children[key] = child; compiled.content[key] = child.content; } } else { compiled.value = content; compiled.setIsRequired(false); compiled._evaluate = helper.evaluateValue; } } return compiled; } function _compile(parent, name) { var logger = parent.logger; var containingModule = parent.mapper && parent.mapper.containingModule; var mapper = parent.mapper && parent.mapper.newChild(logger, containingModule); var source = getSource(mapper, module); return __compile(parent, source, name); } function compile(mapper, logger) { var compiled = new CompiledNode(mapper, logger); return _compile(compiled, ''); } return { $isModule: true, logger: null, getSource: function (mapper, logger) { return getSource(mapper, logger); }, validate: function (mapper, instanceNode, logger) { return validate.call(this, mapper, instanceNode, logger || this.logger); }, _compile: function (parent, name) { return _compile(parent, name); }, compile: function (mapper, logger) { return compile(mapper, logger || this.logger).content; }, evaluate: function (mapper, instanceNode, logger) { var api = this.compile(mapper, logger); api._ = instanceNode; return api._; }, setLogger: function (val) { this.logger = val; return this; } }; }
cellanda/flexapi-core-js
lib/module.js
JavaScript
mit
6,246
from setuptools import setup, find_packages setup( name="Coinbox-mod-customer", version="0.2", packages=find_packages(), zip_safe=True, namespace_packages=['cbmod'], include_package_data=True, install_requires=[ 'sqlalchemy>=0.7, <1.0', 'PyDispatcher>=2.0.3, <3.0', 'ProxyTypes>=0.9, <1.0', 'Babel>=1.3, <2.0', 'PySide>=1.0,<2.0' ], author='Coinbox POS Team', author_email='coinboxpos@googlegroups.com', description='Coinbox POS customer module', license='MIT', url='http://coinboxpos.org/' )
coinbox/coinbox-mod-customer
setup.py
Python
mit
654
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE78_OS_Command_Injection__char_file_w32_spawnv_82_bad.cpp Label Definition File: CWE78_OS_Command_Injection.strings.label.xml Template File: sources-sink-82_bad.tmpl.cpp */ /* * @description * CWE: 78 OS Command Injection * BadSource: file Read input from a file * GoodSource: Fixed string * Sinks: w32_spawnv * BadSink : execute command with spawnv * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer * * */ #ifndef OMITBAD #include "std_testcase.h" #include "CWE78_OS_Command_Injection__char_file_w32_spawnv_82.h" #include <process.h> namespace CWE78_OS_Command_Injection__char_file_w32_spawnv_82 { void CWE78_OS_Command_Injection__char_file_w32_spawnv_82_bad::action(char * data) { { char *args[] = {COMMAND_INT_PATH, COMMAND_ARG1, COMMAND_ARG2, COMMAND_ARG3, NULL}; /* spawnv - specify the path where the command is located */ /* POTENTIAL FLAW: Execute command without validating input possibly leading to command injection */ _spawnv(_P_WAIT, COMMAND_INT_PATH, args); } } } #endif /* OMITBAD */
maurer/tiamat
samples/Juliet/testcases/CWE78_OS_Command_Injection/s04/CWE78_OS_Command_Injection__char_file_w32_spawnv_82_bad.cpp
C++
mit
1,190
//= require jquery3 //= require popper //= require bootstrap //= require turbolinks //= require_tree .
mrysav/familiar
app/assets/javascripts/application.js
JavaScript
mit
102
module Quovo module Models class IframeToken < Base fields %i( user token ) def url "https://embed.quovo.com/auth/#{token}" end end end end
CanopyFA/quovo-ruby
lib/quovo/models/iframe_token.rb
Ruby
mit
200
#include "sendmessagedialog.h" #include "ui_sendmessagedialog.h" #include "clientcommandmanager.h" #include "clientcommand.h" SendMessageDialog::SendMessageDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SendMessageDialog) { ui->setupUi(this); errorPopup = new ErrorPopup(); attach(errorPopup); } SendMessageDialog::~SendMessageDialog() { delete errorPopup; delete ui; } void SendMessageDialog::on_buttonBox_accepted() { QByteArray receiverByteArray = ui->friendname_lineedit->text().toUtf8(); const char* receiver = receiverByteArray.constData(); QByteArray messageByteArray = ui->message_textedit->toPlainText().toUtf8(); const char* message = messageByteArray.constData(); // call client command to send a message int retVal = ClientCommandManager::clientCommand->SendCommand(receiver, message); if (retVal == -1) { // char message[] = "SendCommand error\0"; changeMessage( "SendCommand error\0"); } if (retVal == 0) { // char message[] = "message sent!\0"; changeMessage("message sent!\0"); } } void SendMessageDialog::on_unfriend_button_clicked() { if (ui->friendname_lineedit->text().isEmpty()) { char message[] = "please enter your \"friend\"'s name first!\0"; changeMessage((std::string) message); return; } QByteArray friendNameByteArray = ui->friendname_lineedit->text().toUtf8(); const char* friendName = friendNameByteArray.constData(); // CALL CLIENTCOMMAND TO UNFRIEND int retVal = ClientCommandManager::clientCommand->UnCommand(friendName); if (retVal == -1) { char message[] = "unfriend error\0"; changeMessage((std::string) message); } if (retVal == 0) { char message[] = "unfriend success\0"; changeMessage((std::string) message); } } void SendMessageDialog::changeMessage(std::string _message) { message = _message; notify(message); } std::string SendMessageDialog::getMessage() { return message; } void SendMessageDialog::setReceiver(std::string username) { QString qstr = QString::fromStdString(username); ui->friendname_lineedit->setText(qstr); }
taragu/sharefile
sharefileclient/sendmessagedialog.cpp
C++
mit
2,196
<?php namespace Etk\Bundle\AdminBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritdoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('etk_admin'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
eibertek/etek10
src/Etk/Bundle/AdminBundle/DependencyInjection/Configuration.php
PHP
mit
909
<?php namespace spec\GrumPHP\Runner; use GrumPHP\Runner\TaskResult; use GrumPHP\Task\Context\ContextInterface; use GrumPHP\Task\TaskInterface; use PhpSpec\ObjectBehavior; class TaskResultSpec extends ObjectBehavior { const FAILED_TASK_MESSAGE = 'failed task message'; function it_creates_passed_task(TaskInterface $task, ContextInterface $context) { $this->beConstructedThrough('createPassed', array($task, $context)); $this->getTask()->shouldBe($task); $this->getResultCode()->shouldBe(TaskResult::PASSED); $this->isPassed()->shouldBe(true); $this->getMessage()->shouldBeNull(); } function it_creates_failed_task(TaskInterface $task, ContextInterface $context) { $this->beConstructedThrough('createFailed', array($task, $context, self::FAILED_TASK_MESSAGE)); $this->getTask()->shouldBe($task); $this->getResultCode()->shouldBe(TaskResult::FAILED); $this->isPassed()->shouldBe(false); $this->getMessage()->shouldBe(self::FAILED_TASK_MESSAGE); } function it_creates_skipped_task(TaskInterface $task, ContextInterface $context) { $this->beConstructedThrough('createSkipped', array($task, $context)); $this->getTask()->shouldBe($task); $this->getResultCode()->shouldBe(TaskResult::SKIPPED); $this->isPassed()->shouldBe(false); } function it_should_be_a_blocking_task_if_it_is_a_failed_task(TaskInterface $task, ContextInterface $context) { $this->beConstructedThrough('createFailed', array($task, $context, self::FAILED_TASK_MESSAGE)); $this->isBlocking()->shouldBe(true); } function it_should_not_be_a_blocking_task_if_it_is_a_passed_task(TaskInterface $task, ContextInterface $context) { $this->beConstructedThrough('createPassed', array($task, $context, self::FAILED_TASK_MESSAGE)); $this->isBlocking()->shouldBe(false); } function it_should_not_be_a_blocking_task_if_it_is_a_non_blocking_failed_task(TaskInterface $task, ContextInterface $context) { $this->beConstructedThrough('createNonBlockingFailed', array($task, $context, self::FAILED_TASK_MESSAGE)); $this->isBlocking()->shouldBe(false); } }
mikechernev/grumphp
spec/GrumPHP/Runner/TaskResultSpec.php
PHP
mit
2,248