code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
<!doctype html> <!--[if lt IE 7]><html class="no-js lt-ie9 lt-ie8 lt-ie7" lang="en"> <![endif]--> <!--[if (IE 7)&!(IEMobile)]><html class="no-js lt-ie9 lt-ie8" lang="en"><![endif]--> <!--[if (IE 8)&!(IEMobile)]><html class="no-js lt-ie9" lang="en"><![endif]--> <!--[if gt IE 8]><!--> <html class="no-js" lang="en"><!--<![endif]--> <head> {% include _head.html %} </head> <body class="post"> {% include _browser-upgrade.html %} {% include _navigation.html %} {% if page.image.feature %} <div class="image-wrap"> <img src= {% if page.image.feature contains 'http' %} "{{ page.image.feature }}" {% else %} "{{ site.url }}/images/{{ page.image.feature }}" {% endif %} alt="{{ page.title }} feature image"> {% if page.image.credit %} <span class="image-credit">Photo Credit: <a href="{{ page.image.creditlink }}">{{ page.image.credit }}</a></span> {% endif %} </div><!-- /.image-wrap --> {% endif %} <div id="main" role="main"> <div class="article-author-side"> {% include _author-bio.html %} </div> <article class="post"> <div class="headline-wrap"> {% if page.link %} <h1><a href="{{ page.link }}">{{ page.title }}</a></h1> {% else %} <h1><a href="{{ site.url }}{{ page.url }}" rel="bookmark" title="{{ page.title }}">{{ page.title }}</a></h1> {% endif %} </div><!--/ .headline-wrap --> <div class="article-wrap"> {{ content }} <hr /> <footer role="contentinfo"> {% if page.share != false %}{% include _social-share.html %}{% endif %} <p class="byline"><strong>{{ page.title }}</strong> was published on <time datetime="{{ page.date | date_to_xmlschema }}">{{ page.date | date: "%B %d, %Y" }}</time>{% if page.modified %} and last modified on <time datetime="{{ page.modified | date: "%Y-%m-%d" }}">{{ page.modified | date: "%B %d, %Y" }}</time>{% endif %}.</p> </footer> </div><!-- /.article-wrap --> {% if site.owner.disqus-shortname and page.comments == true %} <section id="disqus_thread"></section><!-- /#disqus_thread --> {% endif %} </article> </div><!-- /#main --> <div class="footer-wrap"> {% if page.share %} <div class="related-articles"> <h4>You might also enjoy <small class="pull-right">(<a href="{{ site.url }}/posts/">View all posts</a>)</small></h4> <ul> {% for post in site.related_posts limit:3 %} <li><a href="{{ site.url }}{{ post.url }}" title="{{ post.title }}">{{ post.title }}</a></li> {% endfor %} </ul> <hr /> </div><!-- /.related-articles --> {% endif %} <footer> {% include _footer.html %} </footer> </div><!-- /.footer-wrap --> {% include _scripts.html %} </body> </html>
yanuartadityan/yanuartadityan.github.io
_layouts/post.html
HTML
mit
2,710
module Main where import Synonyms import Test.Hspec main :: IO () main = hspec $ do let d = Definition "foo" ["b"] in describe "lookupDefinition" $ do it "returns Nothing when no matches" $ lookupDefinition "a" [d] `shouldBe` Nothing it "returns Just Definition when found" $ lookupDefinition "foo" [d] `shouldBe` Just d describe "definitions" $ it "converts a list of definitions" $ definitions ["foo bar baz"] `shouldBe` [Definition "foo" ["bar", "baz"]] describe "convertToDefinition" $ it "converts to a definition" $ convertToDefinition "foo bar baz" `shouldBe` Definition "foo" ["bar", "baz"]
justincampbell/synonyms
Spec.hs
Haskell
mit
720
// // Klak - Utilities for creative coding with Unity // // Copyright (C) 2016 Keijiro Takahashi // // 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. // using UnityEngine; using UnityEditor; namespace Klak.Wiring { [CanEditMultipleObjects] [CustomEditor(typeof(Noise))] public class NoiseEditor : Editor { SerializedProperty _frequency; SerializedProperty _octaves; SerializedProperty _bias; SerializedProperty _amplitude; SerializedProperty _outputEvent; void OnEnable() { _frequency = serializedObject.FindProperty("_frequency"); _octaves = serializedObject.FindProperty("_octaves"); _bias = serializedObject.FindProperty("_bias"); _amplitude = serializedObject.FindProperty("_amplitude"); _outputEvent = serializedObject.FindProperty("_outputEvent"); } public override void OnInspectorGUI() { serializedObject.Update(); EditorGUILayout.PropertyField(_frequency); EditorGUILayout.PropertyField(_octaves); EditorGUILayout.Space(); EditorGUILayout.PropertyField(_bias); EditorGUILayout.PropertyField(_amplitude); EditorGUILayout.Space(); EditorGUILayout.HelpBox( "Output = (Noise + Bias) * Amplitude", MessageType.None, true ); EditorGUILayout.Space(); EditorGUILayout.PropertyField(_outputEvent); serializedObject.ApplyModifiedProperties(); } } }
atomicguy/codejam
MagentaMidiUnity/Assets/Klak/Wiring/Editor/Input/NoiseEditor.cs
C#
mit
2,699
#include <stdio.h> main() { char current_char = EOF; while ((current_char = getchar()) != EOF) { if (current_char == '\t') { printf("\\t"); } else if (current_char == '\b') { printf("\\b"); } else if (current_char == '\\') { printf("\\\\"); } else { printf("%c", current_char); } } }
jhpy1024/CProgrammingLanguageExercises
exercise_1-10.c
C
mit
445
package se.kjellstrand.colorclock.activity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import se.kjellstrand.colorclock.R; /** * Opens up the native share dialog. */ public class ShareActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent sendIntent = new Intent(); sendIntent.setAction(Intent.ACTION_SEND); sendIntent.putExtra(Intent.EXTRA_TEXT, getString(R.string.sharing_text)); sendIntent.setType("text/plain"); startActivity(sendIntent); finish(); } }
carlemil/ColorClock
src/se/kjellstrand/colorclock/activity/ShareActivity.java
Java
mit
671
# frozen_string_literal: true require 'rubycritic/generators/text/lint' module RubyCritic module Generator class LintReport def initialize(analysed_modules) @analysed_modules = analysed_modules end def generate_report FileUtils.mkdir_p(generator.file_directory) File.open(generator.file_pathname, 'w+') do |file| file.write(reports.join("\n")) end end def generator Text::Lint end def reports @analysed_modules.sort.map do |mod| generator.new(mod).render end end end end end
whitesmith/rubycritic
lib/rubycritic/generators/lint_report.rb
Ruby
mit
616
--- title: Deriving a Hopfield Network from The Bayesian Perspective author: Akiva Lipshitz date: June 28, 2017 layout: post --- Hopfield Networks are models of content addressable memory. In other words, they are dynamical systems designed to encode $N$ arbitrary strings and then converge to a point of perfect recall of any one of these strings if stimulated with any noised version of one of these strings. The usual textbook presentation on Hopfield networks begins by presenting the dynamical system without any motivation and only then going on to study its properties. Here, I build a hopfield network from the bottom up. I begin with a motivating question that leads to a Bayesian formulation of the problem. Gradient based optimization yields an expression remarkably similar to the actual Hopfield network. By taking a first order taylor approximation of the derived dynamical system, I arrive at the true update rule for Hopfield nets. I then study (*currently a work in progress*) the dynamical properties of this Hopfield network. The present article follows in the spirit of my previous train of articles, ending with [The Dynamics of Gradient Descent in Linear Least Squares Regression](http://theideasmith.github.io/2017/06/22/Asymptotic-Convergence-of-Gradient-Descent-for-Linear-Regression-Least-Squares-Optimization.html). Perhaps in a sequel article I will try to extend the Hopfield network, which currently operates on binary signals, to continuous valued inputs as well as to translation and scale invariance. ## Deriving a Dynamical System Implementing *content addressable memory* as a dynamical systems necessitates an ansatz equation, i.e. some initial symbolic structure to play around with. (As much as the field would like its neuronal models to be structure free, the only way to get there is by making simplifying assumptions and introducing structure.). Let there be $N$ unique binary strings of length $K$ indexed by $\mu$, $\mathbf{x}^\mu$, which can be observed with some bits randomly flipped, i.e. signal noise. **Input Strings** ![Some example patterns]({{site.url}}/images/Bayesian Hopfield Nets_files/Bayesian Hopfield Nets_7_0.png) Such observations are initially sampled from a uniform distribution over binary strings and then this string is permuted by sampling from a noise distribution. Observations will be denoted by the random variable $\mathbf{X}$. In particular, a single bit in random observation $X_j$ is kept with probability $1-p$ and flipped with probability $p$. In particular, let the permutative process be interpreted as a random variable $\zeta$ defined over the binary sample space $\Omega = \{-1, 1\}$ (The author originally tried $\{0,1\}$ as a sample space but came to a point where this definition made some terms very difficult to deal with analytically. As such, the paper will follow the convention of using the range of the $\text{sgn}$ function as its binary digits).Now, $$ \zeta_j \sim \text{Bernoulli}(p) $$ such that $$ X_j = x_j\zeta_j $$ It follows that it is in fact the case $X_j = x_j$ with probability $1-p$ and $X_j=-x_j$ with probability $p$. Henceforth will be derived a dynamical system to converge upon the most likely true signal given some noisy observation of it, as defined in (1). Specifically, the system will be represented by $T$ units, each denoted by $z_j$ which evolve over time. These units in the system are initialized with a random sample from the observation distribution. $$ z_{j}(0) \sim \text{Bernoulli}(p) $$ The network's prediction $\mathbf{z}$ of the true denoised signal $\mathbf{x}$ can be optimized by maximizing the likelihood that it is in fact the true signal. This means solving the program $$ \arg \max\limits_{\mathbf{z_j}}\mathcal{P}(\mathbf{z}_j(0)) $$ First, I define a uniform distribution over the set of true signals. $$ \mathcal{P}(\mathbf{x}) = \frac{1}{N} $$ Next, I write a distribution for the likelihood of observing any noised signal given the true signal. $$ \mathcal{P}(\mathbf{\tilde{x}} \mid \mathbf{x}) = \alpha^{H_\mu }\beta^{T-H_\mu} \\ $$ where $\alpha =\frac{p}{1-p}$, $\beta = 1-p$ and $H_\mu$ is the number of pairwise different bits betIen the $\mu$th true signal $\mathbf{x}^\mu$ and the current estimate of the true signal $z_j$, $$ H_\mu =\sum\limits_{j=1}^T x_j\wedge z_j\\ $$ in which $a \wedge b$ is the logical $\text{EQUALITY}$ operator. Equation $(7)$ is merely a symbolic abstraction and is now rewritten explicitly. $$ H_\mu = \frac{1}{2} \left[ N - \sum\limits_{j=1}^T z_jx^\mu_j \right] = \frac{1}{2}\left[N- \mathbf{z}\cdot\mathbf{x}^\mu \right] $$ It is beneficial to take a moment to understand equation $(8)$. If $z_j = x_j$, i.e. the network's prediction matches the true value, then $z_jx_j = 1$. Otherwise, $z_jx_j = -1$. Thus, $$\sum x_jz_j = C - I$$ where $C$ is the number of correct guesses and $I$ is the number of incorrect guesses. We would like only the number of incorrect guesses, i.e. $H^\mu = I$. Observe that $C=N-I$, such that $$\sum x_jz_j = N- 2I$$ Thus $$\frac{1}{2}\left[ N - \sum x_j z_j = I \right]$$ The above two distributions for $\mathcal{P}(\mathbf{x})$ and $\mathcal{P}(\mathbf{z(0)} \mid \mathbf{x}) $ can be combined with Bayes rule to write an expression for total probability of any initial state $z_j(0)$. While it may be advantageous to do so, for the sake of simplicity, the present discussion will not discuss the case of adding a bayesian prior. $$ \mathcal{P}(\mathbf{z}(0)) = \sum\limits^N_{\mu=1}\mathcal{P}(\mathbf{z}(0)\mid\mathbf{x}^\mu)\mathcal{P}(\mathbf{x}^\mu) $$ $$ \mathcal{P}(\mathbf{z}(0)) = \frac{\beta ^T}{N}\sum\limits^N_{\mu=1} \exp\left\{H_\mu\ln\alpha \right\} \\ $$ By maximizing $(12)$, we arrive at an optimal prediction $\mathbf{z}$. $$ \frac{\partial \mathcal{P}(z_j)}{\partial z_j} = \frac{\beta^T}{N}\ln\alpha\sum\limits^N_{\mu=1} \exp\left\{H_\mu\ln\alpha \right\} \frac{\partial H_\mu}{\partial z_j} $$ From $(8)$, $$\frac{\partial H_\mu}{\partial {z}_j} = -\frac{1}{2}x_j^\mu$$ Noting that $z_j$ is bounded to the closed interval $[-1, 1]$, I could use Lagrangian optimization to solve for $$\frac{\partial \mathcal{P}(z_j)}{\partial z_j} = 0$$ Keeping $z_j$ in a closed interval is equivalent to saying $\|z_j| = \sqrt{z_j^2} = 1$. Thus, ​ $$\nabla z_j = \lambda \frac{z_j}{|z_j|}$$ Because of the absolute value in the denominator, this will be really difficult to solve analytically. Do not fear. Due to the very simple bounds on $z_j$,gradient ascent is a viable solution but only if I place a nonlinear filter over each update to keep $z_j$ in line. The reason for this is because the learning equations Ire derived with the assumption that the range is bounded; I must therefore enforce this constraint in our updates because gradient descent cannot read our minds. Furthermore, it will not be necessary to perform a numerical integration $z_j:= z_j + \Delta z_j$ because I care only about the sign of $z_j$ and nothing more. As such, whether $\Delta z_j >0 $ or $\Delta z_j < 0$ is sufficient for our interests. $$ z_j:= \tanh\left\{\kappa \sum\limits^N_{\mu=1}x_j^\mu \alpha^{H_\mu} \right\} $$ where $\kappa$ is a chosen rate of convergence. If updates are to be discrete then the rule becomes very similar to the true hopfield update rule $$ z_j := \text{sgn}\left\{ \sum\limits^N_{\mu=1}x_j^\mu \alpha^{H_\mu} \right\} $$ **Learning Process** ![Learning Iterations]({{site.url}}/images/Bayesian Hopfield Nets_files/Bayesian Hopfield Nets_11_1.png) We have arrived at something very similar to the real Hopfield update rule by starting with maximum likelihood concerns. This shows that real Hopfield networks not only converge upon a solution, but onto a statistcally optimal one. Some simulations have shown that the given Hopfield update rule actually blows up quite quickly, causing numerical overflow. Because we really only care about the magnitude of each output node and not the rate of convergence, we can linearize the given update rule by taking its taylor expansion. ## Extensions ### Continuous Networks I can read your mind. The Hopfield networks we worked with here are nice and all but they are only configured on binary inputs. No fear; the networks rely on Hamming distance, which is a continuous function of its inputs. Thus, if instead of being limited to $\{-1,1\}$, the range $x_i$ and $z_j$ was expanded without notice to the entire interval $[-1, 1]$, continuity and monotonicity ensures everything will work as expected. ### Interval Equality The next issue we face is elitism. You see, Hopfield networks only serve those special variables that live in a very small part of the numerical world, $[-1, 1]$. Because we are so caring we need to provide equal opportunity for all noisy input signals to be reconstructed. We also have additional worries. The excluded numbers might start suing and charging discrimination. At that point, there will be boycotts, politically charged exchange of words...who knows what will happen. The entire numerical universe might just overflow. In addition, when you have really noisy crowds of numbers, 2 might take on the persona of .4, masquerade as such, infiltrate the inner circle, and rise to a position of prominance only to be unmasked. Do we really want to risk such a scandal? Of course not. So really, what do we do? Well, we're using $\tanh$ already to keep the outputs bounded, so why not just use it initially to keep the inputs bounded. To do this effectively, we need to preserve the relative scale of all numbers. This is easily accomplished by Z-Scoring all input signals and then running them through a nonlinearity $\tanh$. This comes with a cherry on top for free, which is that the same network is invariant to scale by only operating on relative scale. Some tests using $\tanh$ as a bounding nonlinearity unfortunately show that $\tanh$ saturates too quickly to really preserve the relative magnitudes of all inputs. If this is a concern, it might be best to just Z-Score. ## Analysis of The Hopfield Dynamical System As a sanity check, we can confirm that equation $(18)$ does in fact converge upon the true value by working backwards. Assume $z_j \approx x^w_j =1 $. Then $$ \sum\limits^N_{\mu=1}x_j^\mu \alpha^{H_\mu} \approx x^w_j $$ For this to happen, it must be that $$ x^w_j a^{H_w} > \sum\limits_{\mu \ne w} x^\mu_j \alpha^{H_\mu} $$ This is only the case if $0< \alpha \ll 1$. Given that $\alpha = \frac{p}{1-p}$, this requires $p \ll1-p$, or that the signal to noise ratio is very high. ## Conclusion We have shown that a Hopfield-like system emerges quite naturally when you ask the same question that Hopfield did and take a maximum likelihood approach to ansIring it. where $\kappa$ is the arbitrarily chosen rate of convergence. Eventually this system will converge on the denoised signal. *I usually post my blog articles before they are finished as an incentive for me to finish them. come back later and I'll do more in depth analysis of the stability and nuance in the Hopfield network I just derived* ## Supplementary Materials The python implementation of hopfield networks used to generate the figures is located [here](https://github.com/theideasmith/theideasmith.github.io/blob/master/_notebooks/Bayesian%20Hopfield%20Nets.ipynb). **Bibliography** Hancock, Edwin R., and Josef Kittler. "A Bayesian interpretation for the Hopfield network." *Neural Networks, 1993., IEEE International Conference on*. IEEE, 1993.
theideasmith/theideasmith.github.io
_posts/2017-6-28-Deriving-A-Hopfield-Network-From-The-Bayesian-Perspective.md
Markdown
mit
11,591
import {Injectable} from "@angular/core"; import {HttpClient} from './httpClient.service'; import {NotificationsService} from './notifications.service'; import {User} from '../models/user.model'; import {Team} from '../models/team.model'; import {Observable} from 'rxjs/Observable'; @Injectable() export class TeamService { constructor(private httpClient: HttpClient, private notifications: NotificationsService) { } fetchAllTeams(): Observable<any> { return this.httpClient.get('/api/v1/teams').map((res) => res.json()); } assignTeam(user_id: string, team_id: string): Observable<any> { return this.httpClient.post('/api/v1/teams/assign', { user_id: user_id, team_id: team_id }).map(res => res.json()).map(res => { if (res.success) { this.notifications.add("success", "User " + res.login + " was assigned successfully to team " + res.team + "."); } else { this.notifications.add("danger", "There was an error assigning user: " + res.error + ". Please try again."); } }); } unassignTeam(user_id: string, team_id: string): Observable<any> { return this.httpClient.post('/api/v1/teams/unassign', { user_id: user_id, team_id: team_id }).map(res => res.json()).map(res => { if (res.success) { this.notifications.add("success", "User was unassigned successfully."); } else { this.notifications.add("danger", "There was an error unassigning user: " + res.error + ". Please try again."); } }); } addTeam(teamname: string) { return this.httpClient.post('/api/v1/teams/', {name: teamname}).map(res=>res.json()).map(res => { if (res.success) { this.notifications.add("success", "Team was created successfully."); } else { this.notifications.add("danger", "There was an error creating team: " + res.error + ". Please try again."); } }); } deleteTeam(team_id: string){ return this.httpClient.post('/api/v1/teams/delete', {team_id: team_id}).map(res=>res.json()).map(res => { if (res.success) { this.notifications.add("success", "Team was deleted successfully."); } else { this.notifications.add("danger", "There was an error deleting team: " + res.error + ". Please try again."); } }); } }
BartoszSiemienczuk/teamsuite
public/app/services/team.service.ts
TypeScript
mit
2,602
--- uid: SolidEdgeFrameworkSupport.FeatureControlFrame.CompositePrimaryAndSecondaryText summary: remarks: ---
SolidEdgeCommunity/docs
docfx_project/apidoc/SolidEdgeFrameworkSupport.FeatureControlFrame.CompositePrimaryAndSecondaryText.md
Markdown
mit
115
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ActiveCollabTracSync.Entities.ActiveCollab { /// <summary> /// /// </summary> public class Project { /// <summary>Gets or sets the identifier.</summary> /// <value>The identifier.</value> public string Id { get; set; } /// <summary>Gets or sets the name.</summary> /// <value>The name.</value> public string Name { get; set; } /// <summary>Gets or sets the task lists.</summary> /// <value>The task lists.</value> public List<TaskList> TaskLists { get; set; } /// <summary>Gets or sets the tasks.</summary> /// <value>The tasks.</value> public List<Task> Tasks { get; set; } /// <summary> /// Initializes a new instance of the <see cref="Project"/> class. /// </summary> /// <param name="id">The identifier.</param> /// <param name="name">The name.</param> public Project(string id, string name) { Id = id; Name = name; } } }
sfarbota/activecollab-trac-sync
ActiveCollabTracSync/Entities/ActiveCollab/Project.cs
C#
mit
1,166
require_relative '../../../../automated_init' context "Write" do context "Substitute" do context "Message" do context "Initial" do message = Controls::Message.example stream_name = Controls::StreamName.example(category: 'testSubstituteWrite') writer = Write::Substitute.build writer.initial(message, stream_name) test "Expected version is no_stream" do assert(writer.written? { |msg, stream, expected_version| expected_version == :no_stream }) end end end end end
eventide-project/messaging
test/automated/write/substitute/message/write/initial.rb
Ruby
mit
549
# -*- coding: utf-8 -*- # Copyright (C) 2013 Michael Hogg # This file is part of bonemapy - See LICENSE.txt for information on usage and redistribution import bonemapy from distutils.core import setup setup( name = 'bonemapy', version = bonemapy.__version__, description = 'An ABAQUS plug-in to map bone properties from CT scans to 3D finite element bone/implant models', license = 'MIT license', keywords = ["ABAQUS", "plug-in","CT","finite","element","bone","properties","python"], author = 'Michael Hogg', author_email = 'michael.christopher.hogg@gmail.com', url = "https://github.com/mhogg/bonemapy", download_url = "https://github.com/mhogg/bonemapy/releases", classifiers = [ "Programming Language :: Python", "Programming Language :: Python :: 2", "Programming Language :: Python :: 2.6", "Development Status :: 4 - Beta", "Environment :: Other Environment", "Environment :: Plugins", "Intended Audience :: Healthcare Industry", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Topic :: Scientific/Engineering :: Medical Science Apps.", "Topic :: Scientific/Engineering :: Visualization", ], long_description = """ bonemapy is an ABAQUS plug-in that is used to extract bone density, or Hounsfield Unit (HU) values, from CT scans. The bone density can then be used to setup heterogeneous material properties for a 3D finite element bone/implant model. The HU values are extracted at the element integration points. Tri-linear interpolation is used to calculate the HU values at the location of the integration points. bonemapy produces a text file containing the HU values that is formatted so that it can easily be read using ABAQUS user subroutines that are required to apply the bone properties. An ABAQUS odb file is also created containing a fieldoutput representing HU so that the user can quickly visualise the mapped HU values. """, )
mhogg/bonemapy
setup.py
Python
mit
2,237
// Copyright (c) 2010-present Bifrost Entertainment AS and Tommy Nguyen // Distributed under the MIT License. // (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT) #include "Graphics/SpriteBatch.h" #include "Script/GameBase.h" using rainbow::GameBase; using rainbow::SpriteBatch; using rainbow::SpriteRef; using rainbow::SpriteVertex; using rainbow::Vec2f; using rainbow::graphics::Texture; namespace { constexpr auto operator"" _z(unsigned long long int u) -> size_t { return u; } } // namespace SpriteBatch::SpriteBatch(uint32_t count) : sprites_(count), vertices_(std::make_unique<SpriteVertex[]>(count * 4_z)) { R_ASSERT(count <= graphics::kMaxSprites, "Hard-coded limit reached"); array_.reconfigure([this] { bind_arrays(); }); } SpriteBatch::SpriteBatch(SpriteBatch&& batch) noexcept : sprites_(std::move(batch.sprites_)), vertices_(std::move(batch.vertices_)), normals_(std::move(batch.normals_)), count_(batch.count_), vertex_buffer_(std::move(batch.vertex_buffer_)), normal_buffer_(std::move(batch.normal_buffer_)), array_(std::move(batch.array_)), texture_(batch.texture_), normal_(batch.normal_), visible_(batch.visible_) { batch.clear(); } void SpriteBatch::set_normal(const Texture& texture) { if (!normals_) { normals_ = std::make_unique<Vec2f[]>(sprites_.size() * 4_z); array_.reconfigure([this] { bind_arrays(); }); } normal_ = &texture; } void SpriteBatch::set_texture(const Texture& texture) { texture_ = &texture; } void SpriteBatch::bring_to_front(uint32_t i) { sprites_.move(i, count_ - 1); } auto SpriteBatch::create_sprite(uint32_t width, uint32_t height) -> SpriteRef { if (count_ == sprites_.size()) { LOGW( "Tried to add a sprite (size: %ux%u) to a full SpriteBatch " "(capacity: %u). Increase the capacity and try again.", width, height, sprites_.size()); return {}; } new (sprites_.data() + count_) Sprite(width, height); const uint32_t offset = count_ * 4; std::fill_n(vertices_.get() + offset, 4, SpriteVertex{}); if (normals_) std::fill_n(normals_.get() + offset, 4, Vec2f::Zero); return {*this, sprites_.find_iterator(count_++)}; } void SpriteBatch::erase(uint32_t i) { bring_to_front(i); sprites_.data()[--count_].~Sprite(); } auto SpriteBatch::find_sprite_by_id(int id) const -> SpriteRef { auto sprites = sprites_.data(); for (uint32_t i = 0; i < count_; ++i) { if (sprites[i].id() == id) { // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast) return {*const_cast<SpriteBatch*>(this), sprites_.find_iterator(i)}; } } return {}; } void SpriteBatch::move(const Vec2f& delta) { if (delta.is_zero()) return; for (auto&& sprite : *this) sprite.move(delta); } void SpriteBatch::swap(uint32_t i, uint32_t j) { if (i == j) return; sprites_.swap(i, j); } void SpriteBatch::update(GameBase& context) { bool needs_update = false; auto sprites = sprites_.data(); auto texture = context.texture_provider().raw_get(*texture_); if (normals_) { auto normal = context.texture_provider().raw_get(*normal_); for (uint32_t i = 0; i < count_; ++i) { ArraySpan<Vec2f> normal_buffer{normals_.get() + i * 4, 4}; ArraySpan<SpriteVertex> vertex_buffer{vertices_.get() + i * 4, 4}; needs_update |= sprites[i].update(normal_buffer, normal) | sprites[i].update(vertex_buffer, texture); } } else { for (uint32_t i = 0; i < count_; ++i) { ArraySpan<SpriteVertex> buffer{vertices_.get() + i * 4, 4}; needs_update |= sprites[i].update(buffer, texture); } } if (needs_update) { const uint32_t count = count_ * 4; vertex_buffer_.upload(vertices_.get(), count * sizeof(SpriteVertex)); if (normals_) normal_buffer_.upload(normals_.get(), count * sizeof(Vec2f)); } } void SpriteBatch::bind_arrays() const { vertex_buffer_.bind(); if (normals_) normal_buffer_.bind(Shader::kAttributeNormal); } void rainbow::graphics::draw(Context& context, const SpriteBatch& batch) { if (batch.texture() == nullptr) { R_ASSERT(batch.texture() != nullptr, // "Cannot draw an untextured SpriteBatch"); return; } if (batch.normal() != nullptr) bind(context, *batch.normal(), 1); bind(context, *batch.texture()); draw(batch.vertex_array(), batch.vertex_count()); } #ifndef NDEBUG SpriteBatch::~SpriteBatch() { Director::assert_unused( this, "SpriteBatch deleted but is still in the render queue."); } #endif #ifdef RAINBOW_TEST SpriteBatch::SpriteBatch(const rainbow::ISolemnlySwearThatIAmOnlyTesting& test) : sprites_(4), vertices_(std::make_unique<SpriteVertex[]>(4 * 4)), vertex_buffer_(test), normal_buffer_(test) { } #endif // RAINBOW_TEST
tn0502/rainbow
src/Graphics/SpriteBatch.cpp
C++
mit
5,164
<?php namespace Symbiose\Component\Caching\Backend; use Zend\Cache\Backend\File as BaseFile; class File extends BaseFile { /** * Make and return a file name (with path) * * @param string $id Cache id * @return string File name (with path) */ public function getFile($id) { return parent::_file($id); } }
mbideau/Symbiose
src/Symbiose/Component/Caching/Backend/File.php
PHP
mit
342
const {CookieJar} = require('tough-cookie'); const {cookieToString, jarFromCookies, cookiesFromJar} = require('..'); describe('jarFromCookies()', () => { it('returns valid cookies', done => { const jar = jarFromCookies([{ key: 'foo', value: 'bar', domain: 'google.com' }]); jar.store.getAllCookies((err, cookies) => { expect(err).toBeNull(); expect(cookies[0].domain).toEqual('google.com'); expect(cookies[0].key).toEqual('foo'); expect(cookies[0].value).toEqual('bar'); expect(cookies[0].creation instanceof Date).toEqual(true); expect(cookies[0].expires).toEqual('Infinity'); done(); }); }); it('handles malformed JSON', () => { const jar = jarFromCookies('not a jar'); expect(jar.constructor.name).toBe('CookieJar'); }); }); describe('cookiesFromJar()', () => { it('returns valid jar', async () => { const d = new Date(); const initialCookies = [{ key: 'bar', value: 'baz', domain: 'insomnia.rest', expires: d }, { // This one will fail to parse, and be skipped bad: 'cookie' }]; const jar = CookieJar.fromJSON({cookies: initialCookies}); const cookies = await cookiesFromJar(jar); expect(cookies[0].domain).toBe('insomnia.rest'); expect(cookies[0].key).toBe('bar'); expect(cookies[0].value).toBe('baz'); expect(cookies[0].creation).toMatch(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/); expect(cookies[0].expires).toEqual(d.toISOString()); }); it('handles bad jar', async () => { const jar = CookieJar.fromJSON({cookies: []}); // MemoryStore never actually throws errors, so lets mock the // function to force it to this time. jar.store.getAllCookies = cb => cb(new Error('Dummy Error')); const cookies = await cookiesFromJar(jar); // Cookies failed to p expect(cookies.length).toBe(0); }); });
floatinglacier/mastercard-api-explorer
packages/insomnia-cookies/__tests__/index.test.js
JavaScript
mit
1,918
/* ** ** File: mission8.h ** ** Author: Adam Davison ** ** Description: ** Header file for the training library "Mission Nan" interface. ** ** History: */ #ifndef _MISSION_NAN_H_ #define _MISSION_NAN_H_ #ifndef _TRAINING_MISSION_H_ #include "TrainingMission.h" #endif #ifndef _GOAL_H_ #include "Goal.h" #endif namespace Training { class Mission8 : public TrainingMission { public: virtual /* void */ ~Mission8 (void); virtual int GetMissionID (void); virtual SectorID GetStartSectorID (void); //virtual bool RestoreShip (void); protected: virtual void CreateUniverse (void); virtual Condition* CreateMission (void); Goal* CreateGoal01 (void); Goal* CreateGoal02 (void); Goal* CreateGoal03 (void); Goal* CreateGoal04 (void); Goal* CreateGoal05 (void); Goal* CreateGoal06 (void); Goal* CreateGoal07 (void); Goal* CreateGoal08 (void); Goal* CreateGoal09 (void); ImodelIGC* pShip; ImissionIGC* pMission; ImodelIGC* pStation; }; } #endif
AllegianceZone/Allegiance
src/training/mission8.h
C
mit
1,521
--- layout: post title: Version One Prototype Shipped to Uganda published: true --- ![Screw Cutter Workshop]({{ site.url }}/images/screw_cutter_mp4.png "Uganda Surgeons Assess Screw Cutter") <div class="message"> Pictured: Dr. Blachut and Dr. O'Brien introduce the V1 Screw Cutter to hopeful Ugandan surgeons.</div> The Engineers in Scrubs screw cutter team sent their first prototype to Mulago Hospital, Uganda last May with the Uganda Sustainable Trauma Orthopaedic [(USTOP)](http://ustop.orthopaedics.med.ubc.ca) trip. The device was sent for a preliminary assessment with our preliminary stakeholders. Many of the staff deemed it to be a "good piece of engineering" and immediatley understood its tremendous value. However, they requested that it be: 1. Smaller to allow easier portability 2. Lighter so it could be carried over a large distance 3. Ability to cut more screws of different diameters The feedback received has been incorporated into the next version of the screw cutter. We hope to share it with you soon!
ScrewCutter/screwcutter.github.io
_posts/2014-05-01-first-uganda-prototype.md
Markdown
mit
1,034
import React from 'react'; import { connect } from 'react-redux'; import { browserHistory } from 'react-router'; import { recosActions } from '../../core/recos'; import { getRecommenders, getReco } from '../../core/recos'; import { isEditing } from '../../core/loading'; import Header from '../Header'; import TextField from 'material-ui/TextField'; import RaisedButton from 'material-ui/RaisedButton'; import { Card, CardText } from 'material-ui/Card'; import IconButton from 'material-ui/IconButton'; import NavigationClose from 'material-ui/svg-icons/navigation/close'; import FlatButton from 'material-ui/FlatButton'; import AutoComplete from 'material-ui/AutoComplete'; import LoadingIndicator from '../../components/LoadingIndicator'; import CategorySelector from '../../components/CategorySelector'; const blockStyle = { display: 'block' } class EditReco extends React.Component { // eslint-disable-line react/prefer-stateless-function constructor(props) { super(); this.state = { ...props.reco }; this.handleNameChange = this.handleNameChange.bind(this); this.handleRecommenderChange = this.handleRecommenderChange.bind(this); this.handleCategoryChange = this.handleCategoryChange.bind(this); this.saveButtonClicked = this.saveButtonClicked.bind(this); this.dispatchSaveButtonClicked = props.dispatchSaveButtonClicked; //Probably there is a better way to have evrything being into this. this.recommenders = props.recommenders; this.props = props; } handleNameChange(event) { this.setState({ name: event.target.value }); } handleRecommenderChange(value) { this.setState({ recommender: value }); } handleCategoryChange(newCategory) { if(this.state.category === newCategory) { newCategory = null; } this.setState({ category: newCategory }); } saveButtonClicked() { this.dispatchSaveButtonClicked(this.state.key, { name: this.state.name, recommender: this.state.recommender, category: this.state.category, }); } closeButtonClicked() { browserHistory.goBack(); } getHeaderSaveButton() { if(this.state.name) { return <FlatButton label="Save" />; } else { return null; } } render() { if(this.props.isLoading) { return <LoadingIndicator />; } return ( <div> <Header title={'Edit Reco'} iconElementLeft={<IconButton><NavigationClose /></IconButton>} onLeftIconButtonTouchTap={this.closeButtonClicked} /> <Card> <CardText> <TextField hintText={'Recommendation name'} style={blockStyle} type='text' value={this.state.name} onChange={this.handleNameChange} /> <AutoComplete hintText='Who recommended it?' searchText={this.state.recommender} dataSource={this.recommenders} onUpdateInput={this.handleRecommenderChange} onNewRequest={this.handleRecommenderChange} style={blockStyle} filter={AutoComplete.fuzzyFilter} maxSearchResults={5} /> <CategorySelector value={this.state.category} onChange={this.handleCategoryChange}/> <RaisedButton label={'Save'} style={blockStyle} primary={true} onClick={this.saveButtonClicked} disabled={!this.state.name} /> </CardText> </Card> </div> ); } } const mapStateToProps = (state, { params }) => { return { recommenders: getRecommenders(state).map( reco => reco.name), reco: getReco(state, params.recoId), isLoading: isEditing(state) }; }; const mapDispatchToProps = (dispatch) => { return { dispatchSaveButtonClicked: (id, reco) => { dispatch(recosActions.editReco(id, reco)) .then(() => { browserHistory.goBack(); }); } }; }; const EditRecoContainer = connect(mapStateToProps, mapDispatchToProps)(EditReco); export default EditRecoContainer;
pacog/recoreco
app/containers/EditReco/index.js
JavaScript
mit
4,199
using DragonSpark.Model.Selection; using System.Security.Claims; namespace DragonSpark.Application.Security.Identity.Claims.Access; public interface IAccessClaim<T> : ISelect<ClaimsPrincipal, Claim<T>> {}
DragonSpark/Framework
DragonSpark.Application/Security/Identity/Claims/Access/IAccessClaim.cs
C#
mit
209
#!python import re import sys import logging import boto.ec2 from texttable import Texttable from pprint import PrettyPrinter from optparse import OptionParser PP = PrettyPrinter( indent=2 ) ################### ### Arg parsing ################### parser = OptionParser("usage: %prog [options]" ) parser.add_option( "-v", "--verbose", default=None, action="store_true", help="enable debug output" ) parser.add_option( "-H", "--no-header", default=None, action="store_true", help="suppress table header" ) parser.add_option( "-r", "--region", default='us-east-1', help="ec2 region to connect to" ) parser.add_option( "-g", "--group", default=None, help="Include instances from these groups only (regex)" ) parser.add_option( "-G", "--exclude-group",default=None, help="Exclude instances from these groups (regex)" ) parser.add_option( "-n", "--name", default=None, help="Include instances with these names only (regex)" ) parser.add_option( "-N", "--exclude-name", default=None, help="Exclude instances with these names (regex)" ) parser.add_option( "-t", "--type", default=None, help="Include instances with these types only (regex)" ) parser.add_option( "-T", "--exclude-type", default=None, help="Exclude instances with these types (regex)" ) parser.add_option( "-z", "--zone", default=None, help="Include instances with these zones only (regex)" ) parser.add_option( "-Z", "--exclude-zone", default=None, help="Exclude instances with these zones (regex)" ) parser.add_option( "-s", "--state", default=None, help="Include instances with these states only (regex)" ) parser.add_option( "-S", "--exclude-state",default=None, help="Exclude instances with these states (regex)" ) (options, args) = parser.parse_args() ################### ### Logging ################### if options.verbose: log_level = logging.DEBUG else: log_level = logging.INFO logging.basicConfig(stream=sys.stdout, level=log_level) logging.basicConfig(stream=sys.stderr, level=(logging.ERROR,logging.CRITICAL)) ################### ### Connection ################### conn = boto.ec2.connect_to_region( options.region ) ################### ### Regexes ################### regexes = {} for opt in [ 'group', 'exclude_group', 'name', 'exclude_name', 'type', 'exclude_type', 'zone', 'exclude_zone', 'state', 'exclude_state' ]: ### we have a regex we should build if options.__dict__.get( opt, None ): regexes[ opt ] = re.compile( options.__dict__.get( opt ), re.IGNORECASE ) #PP.pprint( regexes ) def get_instances(): instances = [ i for r in conn.get_all_instances() for i in r.instances ] rv = []; for i in instances: ### we will assume this node is one of the nodes we want ### to operate on, and we will unset this flag if any of ### the criteria fail wanted_node = True for re_name, regex in regexes.iteritems(): ### What's the value we will be testing against? if re.search( 'group', re_name ): value = i.groups[0].name elif re.search( 'name', re_name ): value = i.tags.get( 'Name', '' ) elif re.search( 'type', re_name ): value = i.instance_type elif re.search( 'state', re_name ): value = i.state elif re.search( 'zone', re_name ): ### i.region is an object. i._placement is a string. value = str(i._placement) else: logging.error( "Don't know what to do with: %s" % re_name ) continue #PP.pprint( "name = %s value = %s pattern = %s" % ( re_name, value, regex.pattern ) ) ### Should the regex match or not match? if re.search( 'exclude', re_name ): rv_value = None else: rv_value = True ### if the match is not what we expect, then clearly we ### don't care about the node result = regex.search( value ) ### we expected to get no results, excellent if result == None and rv_value == None: pass ### we expected to get some match, excellent elif result is not None and rv_value is not None: pass ### we don't care about this node else: wanted_node = False break if wanted_node: rv.append( i ) return rv def list_instances(): table = Texttable( max_width=0 ) table.set_deco( Texttable.HEADER ) table.set_cols_dtype( [ 't', 't', 't', 't', 't', 't', 't', 't' ] ) table.set_cols_align( [ 'l', 'l', 'l', 'l', 'l', 'l', 'l', 't' ] ) if not options.no_header: ### using add_row, so the headers aren't being centered, for easier grepping table.add_row( [ '# id', 'Name', 'Type', 'Zone', 'Group', 'State', 'Root', 'Volumes' ] ) instances = get_instances() for i in instances: ### XXX there's a bug where you can't get the size of the volumes, it's ### always reported as None :( volumes = ", ".join( [ ebs.volume_id for ebs in i.block_device_mapping.values() if ebs.delete_on_termination == False ] ) ### you can use i.region instead of i._placement, but it pretty ### prints to RegionInfo:us-east-1. For now, use the private version ### XXX EVERY column in this output had better have a non-zero length ### or texttable blows up with 'width must be greater than 0' error table.add_row( [ i.id, i.tags.get( 'Name', ' ' ), i.instance_type, i._placement , i.groups[0].name, i.state, i.root_device_type, volumes or '-' ] ) #PP.pprint( i.__dict__ ) ### table.draw() blows up if there is nothing to print if instances or not options.no_header: print table.draw() if __name__ == '__main__': list_instances()
jib/aws-analysis-tools
instances.py
Python
mit
6,405
def read_data(file_name): return pd.read_csv(file_name) def preprocess(data): # Data Preprocessing data['GDP_scaled']=preprocessing.scale(data['GDP']) data['CLPRB_scaled']=preprocessing.scale(data['CLPRB']) data['EMFDB_scaled']=preprocessing.scale(data['EMFDB']) data['ENPRP_scaled']=preprocessing.scale(data['ENPRP']) data['NGMPB_scaled']=preprocessing.scale(data['NGMPB']) data['PAPRB_scaled']=preprocessing.scale(data['PAPRB']) data['PCP_scaled']=preprocessing.scale(data['PCP']) data['ZNDX_scaled']=preprocessing.scale(data['ZNDX']) data['OP_scaled']=preprocessing.scale(data['Nominal Price']) data['OP2_scaled']=preprocessing.scale(data['Inflation Adjusted Price']) return data def split_data(data): # Split data for train and test all_x = data[['GDP_scaled','CLPRB_scaled','EMFDB_scaled','ENPRP_scaled','NGMPB_scaled','PAPRB_scaled','PCP_scaled','ZNDX_scaled','OP_scaled', 'OP2_scaled']][:55] all_y = data[['NUETP']][:55] return cross_validation.train_test_split(all_x, all_y, test_size=0.2, random_state=0) # SVR for nuclear def SVR_predict(X_train, X_test, y_train, y_test): clf = SVR(kernel='sigmoid', C=90.0, epsilon=0.3).fit(X_train, y_train) print(clf.score(X_test, y_test)) future_x = data[['GDP_scaled','CLPRB_scaled','EMFDB_scaled','ENPRP_scaled','NGMPB_scaled','PAPRB_scaled','PCP_scaled','ZNDX_scaled','OP_scaled','OP2_scaled']][-6:] pred = pd.DataFrame(clf.predict(future_x)) pred.columns = [statelist[i]] result = pd.concat([result, pred], axis=1) return result
uwkejia/Clean-Energy-Outlook
examples/Extra/Codes/SVR_nuclear.py
Python
mit
1,586
package models import ( "database/sql/driver" "errors" "fmt" "time" ) const ( // DefaultLimit is the number of results we will return per page if the user doesn't specify another amount DefaultLimit = 25 // DefaultLimitString is DefaultLimit but in string form because types are a thing DefaultLimitString = "25" // MaxLimit is the maximum number of objects Dairycart will return in a response MaxLimit = 50 dataValidationPattern = `^[a-zA-Z\-_]{1,50}$` timeLayout = "2006-01-02T15:04:05.000000Z" ) // Dairytime is a custom time pointer struct that should interface well with Postgres's time type and allow for easily nullable time type Dairytime struct { time.Time } // Scan implements the Scanner interface. func (dt *Dairytime) Scan(value interface{}) error { if t, ok := value.(time.Time); !ok { return errors.New("value is not a time.Time") } else { dt.Time = t } return nil } // Value implements the driver Valuer interface. func (dt Dairytime) Value() (driver.Value, error) { return dt.Time, nil } // MarshalText satisfies the encoding.TestMarshaler interface func (dt Dairytime) MarshalText() ([]byte, error) { if dt.Time.IsZero() { return nil, nil } return []byte(dt.Time.Format(timeLayout)), nil } // UnmarshalText is a function which unmarshals a NullTime func (dt *Dairytime) UnmarshalText(text []byte) (err error) { if text == nil { return nil } if len(text) == 0 { return nil } dt.Time, _ = time.Parse(timeLayout, string(text)) return nil } var _ fmt.Stringer = (*Dairytime)(nil) func (dt *Dairytime) String() string { if dt == nil { return "nil" } return dt.Time.Format(timeLayout) } // ListResponse is a generic list response struct containing values that represent // pagination, meant to be embedded into other object response structs type ListResponse struct { Count uint64 `json:"count"` Limit uint8 `json:"limit"` Page uint64 `json:"page"` } var _ = error(new(ErrorResponse)) // ErrorResponse is a handy struct we can respond with in the event we have an error to report type ErrorResponse struct { Status int `json:"status"` Message string `json:"message"` } func (e *ErrorResponse) Error() string { return e.Message } // QueryFilter represents a query filter type QueryFilter struct { Page uint64 Limit uint8 CreatedAfter time.Time CreatedBefore time.Time UpdatedAfter time.Time UpdatedBefore time.Time IncludeArchived bool }
dairycart/dairycart
models/v1/helper_types.go
GO
mit
2,468
package ch.jalu.injector.demo; import ch.jalu.injector.Injector; import ch.jalu.injector.InjectorBuilder; import java.math.RoundingMode; /** * Small demo showing how an injector can be used to wire up an application. * <p> * In this entry point of the app, we only care about getting {@link CalculationService}. * We don't care and don't have to care about creating any of the classes it depends on * by creating the injector and letting it figure out which classes to create on its own. */ public class MyApp { public static void main(String... args) { String result = setUpAndRun(); System.out.println(result); } public static String setUpAndRun() { // Create the injector via the Builder Injector injector = new InjectorBuilder() .addDefaultHandlers("ch.jalu.injector.demo") .create(); // Save the value to associate to @RoundMode, our custom annotation injector.provide(RoundMode.class, RoundingMode.HALF_UP); // Tell the injector that we want to get CalculationService CalculationService calculationService = injector.getSingleton(CalculationService.class); // Run an action on it return calculationService.calculateCircumference(120.12345); } }
ljacqu/DependencyInjector
injector/src/test/java/ch/jalu/injector/demo/MyApp.java
Java
mit
1,293
#ifndef _EASYPSEUDO3D_H_ #define _EASYPSEUDO3D_H_ #include "libpseudo3d/config.h" #include "libpseudo3d/StageCanvas3D.h" #include "libpseudo3d/StageCanvas2D.h" #include "libpseudo3d/Proj2DEditOP.h" #endif // _EASYPSEUDO3D_H_
xzrunner/easyeditor
easypseudo3d/src/easypseudo3d.h
C
mit
226
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="de"> <head> <title>kosmotique fördern</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style>body { width: 800px }</style> <link rel="stylesheet" href="../css/common.css" type="text/css" /> </head> <body> <ul class="menu"> <li id="about"><a href="../about.html">About</a></li> <li id="texts"><a href="../texts/index.html">Words</a></li> <li id="events"><a href="../events/index.html">Dates</a></li> <li id="support" class="active"><a href="#">Support</a></li> <li><a href="../contact.html">Contact</a></li> </ul> <h1>Fördermitgliedschaft – so funktioniert's</h1> <p>Förderinnen und Förderer unterstützen den Verein ideell und finanziell. Wir wollen die Unterstützung auf viele Schultern verteilen. Weil die Verwaltung von Fördermitgliedschaften und -beiträgen Arbeit macht und kein Selbstzweck sein soll, schätzen wir besonders Mitglieder, die uns aus dem Hintergrund unterstützen ohne umfangreiche Dienstleistungen zu erwarten. Sie ermöglichen, dass wir uns auf unsere eigentlichen Aktivitäten konzentrieren können.</p> <p>Die Fördermitgliedschaft kann <a href="index.php">online</a> oder <a href="../doc/foerdermitgliedschaft_antrag.pdf">schriftlich</a> beantragt werden.</p> <p>Die Spendenbescheinigung zur Vorlage beim Finanzamt bekommen Förderinnen und Förderer für Beträge über 200€ automatisch zu Beginn des folgenden Kalenderjahres zugesandt. Kleinspenden unter 200€ erkennt das Finanzamt ohne Bescheinigung an (unter Vorlage der Kontoauszüge und einer Bescheinigung, die <a href="../doc/zuwendungsnachweis.pdf">hier</a> heruntergeladen werden kann). Auf dringenden Wunsch bestätigen wir auch Kleinspenden, setzen unsere Energie aber lieber anderweitig ein.</p> <p>Die Fördermitgliedschaft erlischt automatisch nach drei ausstehenden Monatsbeiträgen. Wir bitten jedoch um die schriftliche Erklärung des Austritts an betreiber_innen@kosmotique.org. Die Beitragshöhe kann per Antrag an o.g. Email-Adresse auch angepasst werden.</p> <p>Förderinnen und Förderer werden per Email über die Aktivitäten von kosmotique e.V. informiert und regelmäßig zu unseren Veranstaltungen eingeladen.</p> <p>Downloads:</p> <ul> <li><a href="../doc/foerdermitgliedschaft_info.pdf">diese Informationen als pdf</a></li> <li><a href="../doc/foerdermitgliedschaft_antrag.pdf">Antrag Fördermitgliedschaft</a></li> <li><a href="../doc/kosmotique_satzung.pdf">Satzung</a></li> <li><a href="../doc/zuwendungsnachweis.pdf">vereinfachter Zuwendungsnachweis</a></li> </ul> </body> </html>
kosmotique/kosmotique.org
support/howto.html
HTML
mit
2,831
package com.optimaize.webcrawlerverifier.bots; import com.google.common.collect.ImmutableList; import org.testng.annotations.Test; import static org.testng.Assert.*; public class GooglebotDataTest { @Test public void testGetIdentifier() throws Exception { assertEquals(GooglebotData.getInstance().getIdentifier(), "GOOGLEBOT"); } @Test public void testGetUserAgentChecker() throws Exception { assertTrue(GooglebotData.getInstance().getUserAgentChecker().apply("foo Googlebot bar")); assertFalse(GooglebotData.getInstance().getUserAgentChecker().apply("foo Google bar")); } @Test public void testGetIps() throws Exception { assertTrue(GooglebotData.getInstance().getIps().isEmpty()); } @Test public void testGetHostnames() throws Exception { assertEquals(GooglebotData.getInstance().getHostnames(), ImmutableList.of("googlebot.com")); } }
optimaize/webcrawler-verifier
src/test/java/com/optimaize/webcrawlerverifier/bots/GooglebotDataTest.java
Java
mit
932
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.12"/> <meta name="viewport" content="width=device-width, initial-scale=1"/> <title>Tempest: Tempest::Window::DragGestureRecognizer Struct Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="navtree.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="resize.js"></script> <script type="text/javascript" src="navtreedata.js"></script> <script type="text/javascript" src="navtree.js"></script> <script type="text/javascript"> $(document).ready(initResizable); </script> <link href="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/searchdata.js"></script> <script type="text/javascript" src="search/search.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> <link href="style.css" rel="stylesheet" type="text/css"/> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td id="projectlogo"><img alt="Logo" src="icon.png"/></td> <td id="projectalign" style="padding-left: 0.5em;"> <div id="projectname">Tempest </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.12 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <script type="text/javascript" src="menudata.js"></script> <script type="text/javascript" src="menu.js"></script> <script type="text/javascript"> $(function() { initMenu('',true,false,'search.php','Search'); $(document).ready(function() { init_search(); }); }); </script> <div id="main-nav"></div> </div><!-- top --> <div id="side-nav" class="ui-resizable side-nav-resizable"> <div id="nav-tree"> <div id="nav-tree-contents"> <div id="nav-sync" class="sync"></div> </div> </div> <div id="splitbar" style="-moz-user-select:none;" class="ui-resizable-handle"> </div> </div> <script type="text/javascript"> $(document).ready(function(){initNavTree('struct_window_1_1_drag_gesture_recognizer.html','');}); </script> <div id="doc-content"> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> </div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> <div class="header"> <div class="summary"> <a href="#pub-types">Public Types</a> &#124; <a href="#pub-methods">Public Member Functions</a> &#124; <a href="#pub-attribs">Public Attributes</a> &#124; <a href="struct_window_1_1_drag_gesture_recognizer-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">Tempest::Window::DragGestureRecognizer Struct Reference</div> </div> </div><!--header--> <div class="contents"> <div class="dynheader"> Inheritance diagram for Tempest::Window::DragGestureRecognizer:</div> <div class="dyncontent"> <div class="center"> <img src="struct_window_1_1_drag_gesture_recognizer.png" usemap="#Tempest::Window::DragGestureRecognizer_map" alt=""/> <map id="Tempest::Window::DragGestureRecognizer_map" name="Tempest::Window::DragGestureRecognizer_map"> <area href="class_tempest_1_1_gesture_recognizer.html" alt="Tempest::GestureRecognizer" shape="rect" coords="0,0,250,24"/> </map> </div></div> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-types"></a> Public Types</h2></td></tr> <tr class="memitem:af6ad3e83a79dea92e5a429b6ee64ae0a"><td class="memItemLeft" align="right" valign="top"><a id="af6ad3e83a79dea92e5a429b6ee64ae0a"></a>enum &#160;</td><td class="memItemRight" valign="bottom"><b>State</b> { <b>NonActivated</b>, <b>Press</b>, <b>Move</b> }</td></tr> <tr class="separator:af6ad3e83a79dea92e5a429b6ee64ae0a"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr class="memitem:a3463dc5ebbdda93c0d414d76b3e9fb97"><td class="memItemLeft" align="right" valign="top"><a id="a3463dc5ebbdda93c0d414d76b3e9fb97"></a> void&#160;</td><td class="memItemRight" valign="bottom"><b>deleteGesture</b> (<a class="el" href="class_tempest_1_1_abstract_gesture_event.html">AbstractGestureEvent</a> *g)</td></tr> <tr class="separator:a3463dc5ebbdda93c0d414d76b3e9fb97"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:aa2db7b37a81b7842f428e48bbaa20a3c"><td class="memItemLeft" align="right" valign="top"><a id="aa2db7b37a81b7842f428e48bbaa20a3c"></a> <a class="el" href="class_tempest_1_1_abstract_gesture_event.html">AbstractGestureEvent</a> *&#160;</td><td class="memItemRight" valign="bottom"><b>event</b> (const <a class="el" href="class_tempest_1_1_event.html">Event</a> &amp;e)</td></tr> <tr class="separator:aa2db7b37a81b7842f428e48bbaa20a3c"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-attribs"></a> Public Attributes</h2></td></tr> <tr class="memitem:a6857524ea5e940dacbb05e9e67e01496"><td class="memItemLeft" align="right" valign="top"><a id="a6857524ea5e940dacbb05e9e67e01496"></a> MemPool&lt; <a class="el" href="class_tempest_1_1_drag_gesture.html">DragGesture</a> &gt;&#160;</td><td class="memItemRight" valign="bottom"><b>pool</b></td></tr> <tr class="separator:a6857524ea5e940dacbb05e9e67e01496"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ab6f37e7494d80666bb789de20ed856c8"><td class="memItemLeft" align="right" valign="top"><a id="ab6f37e7494d80666bb789de20ed856c8"></a> State&#160;</td><td class="memItemRight" valign="bottom"><b>state</b></td></tr> <tr class="separator:ab6f37e7494d80666bb789de20ed856c8"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ae8f6bcd31e26ba9916f14c070aac25a6"><td class="memItemLeft" align="right" valign="top"><a id="ae8f6bcd31e26ba9916f14c070aac25a6"></a> int&#160;</td><td class="memItemRight" valign="bottom"><b>pointer</b></td></tr> <tr class="separator:ae8f6bcd31e26ba9916f14c070aac25a6"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:af0f4931d90572a2fe30300d8fb785964"><td class="memItemLeft" align="right" valign="top"><a id="af0f4931d90572a2fe30300d8fb785964"></a> <a class="el" href="struct_tempest_1_1_point.html">Point</a>&#160;</td><td class="memItemRight" valign="bottom"><b>spos</b></td></tr> <tr class="separator:af0f4931d90572a2fe30300d8fb785964"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:acef11d15b3acead1730e0e038457c1ee"><td class="memItemLeft" align="right" valign="top"><a id="acef11d15b3acead1730e0e038457c1ee"></a> <a class="el" href="struct_tempest_1_1_point.html">Point</a>&#160;</td><td class="memItemRight" valign="bottom"><b>pos</b></td></tr> <tr class="separator:acef11d15b3acead1730e0e038457c1ee"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <hr/>The documentation for this struct was generated from the following file:<ul> <li>ui/window.cpp</li> </ul> </div><!-- contents --> </div><!-- doc-content --> <!-- start footer part --> <div id="nav-path" class="navpath"><!-- id is needed for treeview function! --> <ul> <li class="navelem"><b>Tempest</b></li><li class="navelem"><a class="el" href="class_tempest_1_1_window.html">Window</a></li><li class="navelem"><a class="el" href="struct_window_1_1_drag_gesture_recognizer.html">DragGestureRecognizer</a></li> <li class="footer">Generated by <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.8.12 </li> </ul> </div> </body> </html>
enotio/Tempest
docs/struct_window_1_1_drag_gesture_recognizer.html
HTML
mit
8,494
! 7.53 ! Записать нули на места элементов, образованных пересечением главной и побочной диагоналей ! у верхних треугольных матрицы Z и Y program ex_7_53 implicit none integer, allocatable :: Z(:,:) integer :: In, Out, size_of_Z, i, column, k character(*), parameter :: output_file = "output.txt", input_file = "../data/input.txt" open (file=input_file, newunit=In) read(In, *) size_of_Z allocate(Z(size_of_Z,size_of_Z)) read(In, *) (Z(i,:), i = 1, size_of_Z) close (In) k = nint(size_of_Z / 2.0) do concurrent (column = 1:size_of_Z) Z(1:(k - abs(k - column)),column) = 0 end do open (file=output_file, newunit=Out) write(Out, *) '-z-' write(Out,*) Z(1,:) write(Out,*) Z(2,:) write(Out,*) Z(3,:) write(Out,*) Z(4,:) write(Out,*) Z(5,:) close (Out) end program ex_7_53
taxnuke/fortranlabs
ex_7_53/src/ex_7_53.f90
FORTRAN
mit
992
body { background: #fff; } .pipe { color: #eee; display: inline-block; width: 20px; text-align: center; } ul, ul li { list-style-type: none; margin: 0; overflow: hidden; } ul .btn, ul li .btn { margin-left: 2px; } ul .done, ul li .done { color: #aaa; text-decoration: line-through; font-style: italic; } ul li { padding-top: 10px; height: 30px; } ul li .actions { -webkit-transition: all 200ms linear; -moz-transition: all 200ms linear; transition: all 200ms linear; float: right; opacity: 0.5; } ul li .actions:hover { opacity: 1; } ul li.edit .actions { opacity: 1; }
sagish/compound-angular-todo
public/stylesheets/application.css
CSS
mit
612
using System; using System.Collections.Generic; using GenerateLocationData.Model; using Npgsql; namespace GenerateLocationData.BAG { public class BagFilter { private const string Query = @"SELECT DISTINCT openbareruimtenaam as straat FROM (SELECT ST_GeomFromText('{0}', 28992) as buurt) as foo, adres WHERE ST_Contains(buurt, geopunt)"; private readonly string connectionString; public BagFilter(string connectionString) { this.connectionString = connectionString; } /// <summary> /// Get all CBS neighbourhoods, specifically its name, boundary (in WKT), and center. /// </summary> public void Enhance(IEnumerable<LocationDescription> locationDescriptions) { using (var conn = new NpgsqlConnection(connectionString)) { conn.Open(); var streets = new List<string>(); foreach (var locationDescription in locationDescriptions) { var query = string.Format(Query, locationDescription.RdBoundary); using (var command = new NpgsqlCommand(query, conn)) { try { using (var dr = command.ExecuteReader()) { while (dr.Read()) { streets.Add(dr["straat"].ToString()); } } } catch (SystemException e) { Console.WriteLine(e.Message); } } locationDescription.Features.Add("straten", string.Join(";", streets)); } } } } }
TNOCS/csTouch
services/LocatorService/GenerateLocationData/BAG/BagFilter.cs
C#
mit
1,925
package main // github.com/cheggaaa/pb import ( "fmt" "os" "path/filepath" "strconv" "time" "github.com/cavaliercoder/grab" "github.com/fatih/color" "github.com/gosuri/uilive" rss "github.com/jteeuwen/go-pkg-rss" ) func getRss(podcast *Podcast) (*rss.Feed, error) { feed := rss.New(1, true, nil, nil) if err := feed.Fetch(podcast.Url, nil); err != nil { return nil, err } return feed, nil } func getRssName(url string) (string, error) { feed := rss.New(1, true, nil, nil) if err := feed.Fetch(url, nil); err != nil { return "", err } return feed.Channels[0].Title, nil } func syncPodcasts(startDate time.Time, nameOrID string, count int, chekMode bool) error { allReqs := [][]*grab.Request{} podcasts := []*Podcast{} if nameOrID == "" { podcasts = cfg.GetAllPodcasts() } else { p, err := cfg.GetPodcastByNameOrID(nameOrID) if err != nil { return err } podcasts = append(podcasts, p) } for n, podcast := range podcasts { var podcastList []*DownloadItem filter := MakeFilter(podcast) filter.Count = count filter.StartDate = startDate // download rss feed, err := getRss(podcast) if err != nil { printPodcastInfo(podcast, podcastList, n+1, err) continue } if len(feed.Channels) == 0 { log.Warnf(fmt.Sprintf("No channels in %s", podcast.Name)) continue } // filter podcastList, err = filter.FilterItems(feed.Channels[0]) if err != nil { printPodcastInfo(podcast, podcastList, n+1, err) continue } if chekMode { printPodcastInfo(podcast, podcastList, n+1, err) continue } // check for emptiness if len(podcastList) == 0 { log.Printf("%s : %s, %d files", color.CyanString("EMPTY"), podcast.Name, len(podcastList)) continue } // create download requests allReqs = append(allReqs, createRequests(podcast, podcastList)) } if !chekMode { startDownload(allReqs) for _, podcast := range podcasts { // FIXME: put right date according to rss or Item PubDate podcast.LastSynced = time.Now() if err := cfg.UpdatePodcast(podcast); err != nil { return err } } } return nil } func printPodcastInfo(podcast *Podcast, podcastList []*DownloadItem, index int, err error) { status := "" num := color.MagentaString("[" + strconv.Itoa(index) + "] ") if err != nil { status = color.RedString("FAIL") } else { color.GreenString("OK") } log.Printf("%s %s", num, podcast.Name) log.Printf("\t* Url : %s %s", podcast.Url, status) if err != nil { log.Warnf("Error: %s", err) } else { log.Printf("\t* Awaiting files : %d", len(podcastList)) for k, podcast := range podcastList { log.Printf("\t\t* [%d] : %s", k, podcast.ItemTitle) } } } func createRequests(podcast *Podcast, podcastList []*DownloadItem) []*grab.Request { reqs := []*grab.Request{} for _, entry := range podcastList { // create dir for each entry, path is set in filter // according to rules in configuration entryDownloadPath := filepath.Join(podcast.DownloadPath, entry.Dir) if !fileExists(entryDownloadPath) { if err := os.MkdirAll(entryDownloadPath, 0777); err != nil { log.Fatal(err) continue } } req, _ := grab.NewRequest(entry.Url) req.Filename = filepath.Join(entryDownloadPath, entry.Filename) req.Size = uint64(entry.Size) req.RemoveOnError = true reqs = append(reqs, req) } return reqs } func startDownload(downloadReqs [][]*grab.Request) { requestCount := len(downloadReqs) statusQueue := make(chan *downloadStatus, requestCount) doneQueue := make(chan bool, requestCount) client := grab.NewClient() go func() { // wait while all requests will be in queue for i := 0; i < requestCount; i++ { <-doneQueue } // close channels close(statusQueue) close(doneQueue) }() totalFiles := 0 for _, podcastReq := range downloadReqs { totalFiles += len(podcastReq) go func(requests []*grab.Request) { curPosition := 0 podcastTotal := len(requests) for _, req := range requests { // increas position, used for printing curPosition++ // start downloading resp := <-client.DoAsync(req) // send results to monitoring channel statusQueue <- &downloadStatus{ Total: podcastTotal, Current: curPosition, Response: resp, } // ensure files downloaded one by one, so wait complition for !resp.IsComplete() { time.Sleep(500 * time.Microsecond) } } }(podcastReq) } checkDownloadProgress(statusQueue, totalFiles) log.Infof("%d files downloaded.\n", totalFiles) } type downloadStatus struct { Total int // total requests count Current int // current position Response *grab.Response } func checkDownloadProgress(respch <-chan *downloadStatus, reqCount int) { timer := time.NewTicker(200 * time.Millisecond) ui := uilive.New() completed := 0 responses := make([]*downloadStatus, 0) ui.Start() for completed < reqCount { select { case resp := <-respch: if resp != nil { responses = append(responses, resp) } case <-timer.C: // print completed requests for i, resp := range responses { if resp != nil && resp.Response.IsComplete() { if resp.Response.Error != nil { showProgressError(ui, resp) } else { showProgressDone(ui, resp) } responses[i] = nil completed++ } } // print in progress requests for _, resp := range responses { if resp != nil { showProgressProc(ui, resp) } } } } timer.Stop() ui.Stop() } func bytesToMb(bytesCount uint64) float64 { return float64(bytesCount) / float64(1024*1024) } func showProgressError(ui *uilive.Writer, status *downloadStatus) { fmt.Fprintf(ui.Bypass(), "Error downloading %s: %v\n", status.Response.Request.URL(), status.Response.Error) } func showProgressDone(ui *uilive.Writer, status *downloadStatus) { fmt.Fprintf(ui.Bypass(), "Finished %s [%d/%d] %0.2f / %0.2f Mb (%d%%)\n", status.Response.Filename, status.Current, status.Total, bytesToMb(status.Response.BytesTransferred()), bytesToMb(status.Response.Size), int(100*status.Response.Progress())) } func showProgressProc(ui *uilive.Writer, status *downloadStatus) { fmt.Fprintf(ui, "Downloading %s [%d/%d] %0.2f / %0.2f Mb (%d%%)\n", status.Response.Filename, status.Current, status.Total, bytesToMb(status.Response.BytesTransferred()), bytesToMb(status.Response.Size), int(100*status.Response.Progress())) }
vali3nt/gopoddl
download.go
GO
mit
6,430
package cn.drct.wepay.exception; public class TradeException extends Exception { /** * */ private static final long serialVersionUID = -4735172784989026754L; private String msg; public TradeException(String code,String msg){ super(code); this.msg=msg; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
sunzy07/cn.drct.wepay
src/main/java/cn/drct/wepay/exception/TradeException.java
Java
mit
398
#ifndef CAFFE_ARRAY_BASE_HPP_ #define CAFFE_ARRAY_BASE_HPP_ #include <string> #include <vector> #include "caffe/array/math_functions.hpp" #include "caffe/proto/caffe.pb.h" #include "caffe/syncedmem.hpp" namespace std { // Print function for ArrayShape ostream &operator<<(ostream &os, const vector<int> &shape); } namespace caffe { // Return a temporary SyncedMemory, useful to evaluate nested expressions shared_ptr<SyncedMemory> temporaryMemory(size_t size); class ArrayMemory { protected: size_t offset_, size_; shared_ptr<SyncedMemory> memory_; void initializeMemory(size_t size); public: ArrayMemory(); explicit ArrayMemory(size_t size); explicit ArrayMemory(shared_ptr<SyncedMemory> memory, size_t size = 0); ArrayMemory(shared_ptr<SyncedMemory> memory, size_t offset, size_t size); // Avoid using this constructor, as it leads to serious issues if // ArrayMemory outlives memory! explicit ArrayMemory(SyncedMemory *memory, size_t size = 0); virtual ~ArrayMemory(); virtual const void *cpu_data_() const; virtual const void *gpu_data_() const; virtual void *mutable_cpu_data_(); virtual void *mutable_gpu_data_(); bool isBorrowed() const; virtual size_t size(); }; // Shape functions typedef std::vector<int> ArrayShape; ArrayShape make_shape(size_t d0); ArrayShape make_shape(size_t d0, size_t d1); ArrayShape make_shape(size_t d0, size_t d1, size_t d2); ArrayShape make_shape(size_t d0, size_t d1, size_t d2, size_t d3); ArrayShape make_shape(size_t d0, size_t d1, size_t d2, size_t d3, size_t d4); ArrayShape make_shape(size_t d0, size_t d1, size_t d2, size_t d3, size_t d4, size_t d5); size_t count(const ArrayShape &shape); std::string shapeToString(const ArrayShape &shape); enum ArrayMode { AR_DEFAULT = 0, AR_CPU = 1, AR_GPU = 2 }; ArrayMode globalArrayMode(); template<typename Dtype> class Expression; template<typename Dtype> class Array; template<typename Dtype> class ArrayBase { protected: // The ArrayBase reference allows any function to reference a ArrayBase object // without having to copy it and without worrying that it might get freed. struct Reference { ArrayShape shape; ArrayMode mode; Reference(ArrayShape shape, ArrayMode mode); virtual ~Reference(); virtual Array<Dtype> eval() const = 0; }; virtual shared_ptr<Reference> ref() const = 0; ArrayShape shape_; ArrayMode mode_; public: explicit ArrayBase(ArrayMode mode = AR_DEFAULT); explicit ArrayBase(const ArrayShape &shape, ArrayMode mode = AR_DEFAULT); virtual ~ArrayBase(); virtual Array<Dtype> eval() const = 0; virtual const ArrayShape & shape() const; virtual ArrayMode mode() const; // Get the Array mode GPU or CPU, no default mode allowed virtual ArrayMode effectiveMode() const; // Define all unary functions #define DECLARE_UNARY(F, f) Expression<Dtype> f() const; LIST_UNARY(DECLARE_UNARY) #undef DECLARE_UNARY // Define all binary functions #define DECLARE_BINARY(F, f)\ Expression<Dtype> f(const ArrayBase &other) const;\ Expression<Dtype> f(Dtype other) const; LIST_BINARY(DECLARE_BINARY) #undef DECLARE_BINARY Expression<Dtype> isub(Dtype o) const; Expression<Dtype> idiv(Dtype o) const; // Define various operators Expression<Dtype> operator+(const ArrayBase &o) const { return add(o); } Expression<Dtype> operator+(Dtype o) const { return add(o); } Expression<Dtype> operator-(const ArrayBase &o) const { return sub(o); } Expression<Dtype> operator-(Dtype o) const { return sub(o); } Expression<Dtype> operator*(const ArrayBase &o) const { return mul(o); } Expression<Dtype> operator*(Dtype o) const { return mul(o); } Expression<Dtype> operator/(const ArrayBase &o) const { return div(o); } Expression<Dtype> operator/(Dtype o) const { return div(o); } Expression<Dtype> operator-() const { return negate(); } // Define all reductions #define DECLARE_REDUCTION(F, f) Dtype f() const; LIST_REDUCTION(DECLARE_REDUCTION) #undef DECLARE_REDUCTION Dtype mean() const; }; template<typename T> Expression<T> operator+(T a, const ArrayBase<T> &b) { return b.add(a); } template<typename T> Expression<T> operator-(T a, const ArrayBase<T> &b) { return b.isub(a); } template<typename T> Expression<T> operator*(T a, const ArrayBase<T> &b) { return b.mul(a); } template<typename T> Expression<T> operator/(T a, const ArrayBase<T> &b) { return b.idiv(a); } } // namespace caffe #endif // CAFFE_ARRAY_BASE_HPP_
tinghuiz/learn-reflectance
caffe/include/caffe/array/base.hpp
C++
mit
4,489
<?php // Include the API require '../../lastfmapi/lastfmapi.php'; // Get the session auth data $file = fopen('../auth.txt', 'r'); // Put the auth data into an array $authVars = array( 'apiKey' => trim(fgets($file)), 'secret' => trim(fgets($file)), 'username' => trim(fgets($file)), 'sessionKey' => trim(fgets($file)), 'subscriber' => trim(fgets($file)) ); // Pass the array to the auth class to eturn a valid auth $auth = new lastfmApiAuth('setsession', $authVars); $apiClass = new lastfmApi(); $userClass = $apiClass->getPackage($auth, 'user'); // Setup the variables $methodVars = array( 'user' => 'RJ' ); if ( $tracks = $userClass->getTopTracks($methodVars) ) { echo '<b>Data Returned</b>'; echo '<pre>'; print_r($tracks); echo '</pre>'; } else { die('<b>Error '.$userClass->error['code'].' - </b><i>'.$userClass->error['desc'].'</i>'); } ?>
albertyw/6.470
src/process/lastfmapi/examples/user.gettoptracks/index.php
PHP
mit
861
package com.topology.impl.importers.sndlib; import com.topology.impl.primitives.LinkImpl; import com.topology.impl.primitives.NetworkElementImpl; import com.topology.impl.primitives.TopologyManagerImpl; import com.topology.importers.ImportTopology; import com.topology.primitives.TopologyManager; import com.topology.primitives.exception.FileFormatException; import com.topology.primitives.exception.TopologyException; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.EnumSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import static org.junit.jupiter.api.Assertions.*; public class SndLibImportTest { private static final Logger log = LoggerFactory.getLogger(SndLibImportTest.class); public enum SNDLibSource { ABILENE ("abilene.xml", 12, 15), ATLANTA("atlanta.xml", 15, 22), JANOS_US("janos-us.xml", 26, 42), JANOS_US_DUPLICATES("janos-us.xml", 26, 84, false), ZIB54("zib54.xml", 54, 80), ZIB54_DUPLICATES("zib54.xml", 54, 81, false); SNDLibSource(String fileName, int nodeNum, int linkNum) { this.fileName = fileName; this.nodeNum = nodeNum; this.linkNum = linkNum; this.removeDuplicaties = true; } SNDLibSource(String fileName, int nodeNum, int linkNum, boolean removeDuplicaties) { this.fileName = fileName; this.nodeNum = nodeNum; this.linkNum = linkNum; this.removeDuplicaties = removeDuplicaties; } final String fileName; final int nodeNum; final int linkNum; final boolean removeDuplicaties; } @ParameterizedTest(name = "{index} => message=''{0}''") @EnumSource(SndLibImportTest.SNDLibSource.class) public void testImport(SNDLibSource source) { ImportTopology importer = new SNDLibImportTopology(source.removeDuplicaties); TopologyManager manager = new TopologyManagerImpl(source.fileName); try { log.info("Loading topology from file {}", source.fileName); importer.importFromFile(this.getClass().getClassLoader().getResource(source.fileName).getFile(), manager); assertEquals(manager.getAllElements(NetworkElementImpl.class).size(), source.nodeNum, "Expected " + source.nodeNum + " nodes in " + source.fileName + ". Parsed Nodes = " + manager.getAllElements(NetworkElementImpl.class).size()); assertEquals(manager.getAllElements(LinkImpl.class).size(), source.linkNum, "Expected " + source.linkNum + " links in " + source.fileName + ". Parsed Links = " + manager.getAllElements(LinkImpl.class).size()); } catch (TopologyException e) { log.error("Topology Exception while parsing test.topology file", e); fail("Topology Exception while parsing test.topology file"); } catch (FileFormatException e) { log.error("FileFormat Exception while parsing test.topology file", e); fail("FileFormat Exception while parsing test.topology file"); } catch (IOException e) { log.error("IO Exception while parsing test.topology file", e); fail("IO Exception while parsing test.topology file"); } manager.removeAllElements(); } }
mohitc/NetworkTopologyDatastore
topology-importers/src/test/java/com/topology/impl/importers/sndlib/SndLibImportTest.java
Java
mit
3,152
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>JSDoc: Source: utils/schema.js</title> <script src="scripts/prettify/prettify.js"> </script> <script src="scripts/prettify/lang-css.js"> </script> <!--[if lt IE 9]> <script src="//html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> <link type="text/css" rel="stylesheet" href="styles/prettify-tomorrow.css"> <link type="text/css" rel="stylesheet" href="styles/jsdoc-default.css"> </head> <body> <div id="main"> <h1 class="page-title">Source: utils/schema.js</h1> <section> <article> <pre class="prettyprint source linenums"><code>/** * @module schema * @description * Low-level utilities to check, create and transform schemas */ /** * @name transformation * @type {object} * @description * Schema values transformation */ const transformation = { ANY_SCHEMA: {}, NOT_ANY_SCHEMA: { not: {} }, }; /** * @name is * @type {function} * @description * Verify the object could be a schema * Since draft-06 supports boolean as a schema definition * @param {object} schema * @returns {boolean} isSchema */ function is(schema) { return ( typeof schema === 'object' || typeof schema === 'boolean' ); } /** * @name transform * @type {function} * @description * Transform a schema pseudo presentation * Since draft-06 supports boolean as a schema definition * @param {object} schema * @returns {object} schema */ function transform(schema) { if (schema === true) { return transformation.ANY_SCHEMA; } else if (schema === false) { return transformation.NOT_ANY_SCHEMA; } return schema; } /** * @name make * @type {function} * @description * Generate a simple schema by a given object * @param {any} instance * @returns {object} schema */ function make(instance) { if (typeof instance !== 'object' || instance === null) { return { enum: [instance] }; } if (Array.isArray(instance)) { return { items: instance.map(make), // other items should be valid by `false` schema, aka not exist at all additionalItems: false }; } const required = Object.keys(instance); return { properties: required.reduce((memo, key) => ( Object.assign({}, memo, { [key]: make(instance[key]) }) ), {}), required, // other properties should be valid by `false` schema, aka not exist at all // additionalProperties: false, }; } module.exports = { is, make, transform, transformation, }; </code></pre> </article> </section> </div> <nav> <h2><a href="index.html">Home</a></h2><h3>Modules</h3><ul><li><a href="module-environment.html">environment</a></li><li><a href="module-formats.html">formats</a></li><li><a href="module-keywords.html">keywords</a></li><li><a href="module-properties.html">properties</a></li><li><a href="module-schema.html">schema</a></li><li><a href="module-state.html">state</a></li><li><a href="module-template.html">template</a></li><li><a href="module-utils.html">utils</a></li><li><a href="module-validators.html">validators</a></li></ul><h3>Global</h3><ul><li><a href="global.html#addFormat">addFormat</a></li><li><a href="global.html#Environment">Environment</a></li><li><a href="global.html#setErrorHandler">setErrorHandler</a></li><li><a href="global.html#useVersion">useVersion</a></li></ul> </nav> <br class="clear"> <footer> Documentation generated by <a href="https://github.com/jsdoc3/jsdoc">JSDoc 3.5.5</a> on Mon Oct 09 2017 18:03:34 GMT+0200 (CEST) </footer> <script> prettyPrint(); </script> <script src="scripts/linenumber.js"> </script> </body> </html>
korzio/djv
docs/auto/utils_schema.js.html
HTML
mit
3,714
/* * Copyright (c) 2014 Roman Kuznetsov * * 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 (including the next * paragraph) 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. */ #include "utils.h" #ifdef WIN32 #define WIN32_LEAN_AND_MEAN 1 #include <Windows.h> #include <stdio.h> #include <algorithm> #endif namespace framework { bool Utils::exists(const std::string& fileName) { #ifdef WIN32 DWORD dwAttrib = GetFileAttributesA(fileName.c_str()); if (dwAttrib != INVALID_FILE_ATTRIBUTES) return true; #endif return false; } bool Utils::readFileToString( const std::string& fileName, std::string& out ) { FILE* fp = 0; size_t filesize = 0; fp = fopen(fileName.c_str(), "rb"); if (!fp) return false; fseek(fp, 0, SEEK_END); filesize = ftell(fp); fseek(fp, 0, SEEK_SET); out.resize(filesize + 1); fread(&out[0], 1, filesize, fp); out[filesize] = 0; fclose(fp); return true; } }
rokuz/DemoOpenGL
demo/framework/utils.cpp
C++
mit
1,880
package com.xinyuan.pub.business.bi.dao.impl; import com.xinyuan.pub.business.bi.dao.BiHrPersonCntDao; import com.xinyuan.pub.dao.BiBaseDao; import com.xinyuan.pub.model.business.bi.po.BiHrPersonCnt; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Repository; import java.util.List; /** * @author liangyongjian * @desc 人员学历结构数据表 Dao层实现类 * @create 2018-06-22 21:26 **/ @Repository("biHrPersonCntDao") public class BiHrPersonCntDaoImpl extends BiBaseDao implements BiHrPersonCntDao { private static final Logger LOGGER = LoggerFactory.getLogger(BiHrPersonCntDaoImpl.class); @Override public List<BiHrPersonCnt> getAllBiHrPersonCntInfo() { LOGGER.debug("Dao层:获取全部原始人员学历结构数据信息"); return getReadSqlSession().selectList("biHrPersonCntDao.selectAllBiHrPersonCntInfo"); } }
mrajian/xinyuan
xinyuan-parent/xinyuan-pub-parent/xinyuan-pub-dao/src/main/java/com/xinyuan/pub/business/bi/dao/impl/BiHrPersonCntDaoImpl.java
Java
mit
916
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // ReSharper disable CheckNamespace using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics.Contracts; namespace System.Linq // ReSharper restore CheckNamespace { /// <summary> /// LINQ extension method overrides that offer greater efficiency for <see cref="ImmutableArray{T}"/> than the standard LINQ methods /// </summary> public static class ImmutableArrayExtensions { #region ImmutableArray<T> extensions /// <summary> /// Projects each element of a sequence into a new form. /// </summary> /// <typeparam name="T">The type of element contained by the collection.</typeparam> /// <typeparam name="TResult">The type of the result element.</typeparam> /// <param name="immutableArray">The immutable array.</param> /// <param name="selector">The selector.</param> [Pure] public static IEnumerable<TResult> Select<T, TResult>(this ImmutableArray<T> immutableArray, Func<T, TResult> selector) { immutableArray.ThrowNullRefIfNotInitialized(); // LINQ Select/Where have optimized treatment for arrays. // They also do not modify the source arrays or expose them to modifications. // Therefore we will just apply Select/Where to the underlying this.array array. return immutableArray.array.Select(selector); } /// <summary> /// Projects each element of a sequence to an <see cref="IEnumerable{T}"/>, /// flattens the resulting sequences into one sequence, and invokes a result /// selector function on each element therein. /// </summary> /// <typeparam name="TSource">The type of the elements of <paramref name="immutableArray"/>.</typeparam> /// <typeparam name="TCollection">The type of the intermediate elements collected by <paramref name="collectionSelector"/>.</typeparam> /// <typeparam name="TResult">The type of the elements of the resulting sequence.</typeparam> /// <param name="immutableArray">The immutable array.</param> /// <param name="collectionSelector">A transform function to apply to each element of the input sequence.</param> /// <param name="resultSelector">A transform function to apply to each element of the intermediate sequence.</param> /// <returns> /// An <see cref="IEnumerable{T}"/> whose elements are the result /// of invoking the one-to-many transform function <paramref name="collectionSelector"/> on each /// element of <paramref name="immutableArray"/> and then mapping each of those sequence elements and their /// corresponding source element to a result element. /// </returns> [Pure] public static IEnumerable<TResult> SelectMany<TSource, TCollection, TResult>( this ImmutableArray<TSource> immutableArray, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector) { immutableArray.ThrowNullRefIfNotInitialized(); if (collectionSelector == null || resultSelector == null) { // throw the same exception as would LINQ return Enumerable.SelectMany(immutableArray, collectionSelector, resultSelector); } // This SelectMany overload is used by the C# compiler for a query of the form: // from i in immutableArray // from j in anotherCollection // select Something(i, j); // SelectMany accepts an IEnumerable<TSource>, and ImmutableArray<TSource> is a struct. // By having a special implementation of SelectMany that operates on the ImmutableArray's // underlying array, we can avoid a few allocations, in particular for the boxed // immutable array object that would be allocated when it's passed as an IEnumerable<T>, // and for the EnumeratorObject that would be allocated when enumerating the boxed array. return immutableArray.Length == 0 ? Enumerable.Empty<TResult>() : SelectManyIterator(immutableArray, collectionSelector, resultSelector); } /// <summary> /// Filters a sequence of values based on a predicate. /// </summary> /// <typeparam name="T">The type of element contained by the collection.</typeparam> [Pure] public static IEnumerable<T> Where<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { immutableArray.ThrowNullRefIfNotInitialized(); // LINQ Select/Where have optimized treatment for arrays. // They also do not modify the source arrays or expose them to modifications. // Therefore we will just apply Select/Where to the underlying this.array array. return immutableArray.array.Where(predicate); } /// <summary> /// Gets a value indicating whether any elements are in this collection. /// </summary> /// <typeparam name="T">The type of element contained by the collection.</typeparam> /// <param name="immutableArray"></param> [Pure] public static bool Any<T>(this ImmutableArray<T> immutableArray) { return immutableArray.Length > 0; } /// <summary> /// Gets a value indicating whether any elements are in this collection /// that match a given condition. /// </summary> /// <typeparam name="T">The type of element contained by the collection.</typeparam> /// <param name="immutableArray"></param> /// <param name="predicate">The predicate.</param> [Pure] public static bool Any<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { immutableArray.ThrowNullRefIfNotInitialized(); Requires.NotNull(predicate, "predicate"); foreach (var v in immutableArray.array) { if (predicate(v)) { return true; } } return false; } /// <summary> /// Gets a value indicating whether all elements in this collection /// match a given condition. /// </summary> /// <typeparam name="T">The type of element contained by the collection.</typeparam> /// <param name="immutableArray"></param> /// <param name="predicate">The predicate.</param> /// <returns> /// <c>true</c> if every element of the source sequence passes the test in the specified predicate, or if the sequence is empty; otherwise, <c>false</c>. /// </returns> [Pure] public static bool All<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { immutableArray.ThrowNullRefIfNotInitialized(); Requires.NotNull(predicate, "predicate"); foreach (var v in immutableArray.array) { if (!predicate(v)) { return false; } } return true; } /// <summary> /// Determines whether two sequences are equal according to an equality comparer. /// </summary> /// <typeparam name="TDerived">The type of element in the compared array.</typeparam> /// <typeparam name="TBase">The type of element contained by the collection.</typeparam> [Pure] public static bool SequenceEqual<TDerived, TBase>(this ImmutableArray<TBase> immutableArray, ImmutableArray<TDerived> items, IEqualityComparer<TBase> comparer = null) where TDerived : TBase { immutableArray.ThrowNullRefIfNotInitialized(); items.ThrowNullRefIfNotInitialized(); if (object.ReferenceEquals(immutableArray.array, items.array)) { return true; } if (immutableArray.Length != items.Length) { return false; } if (comparer == null) { comparer = EqualityComparer<TBase>.Default; } for (int i = 0; i < immutableArray.Length; i++) { if (!comparer.Equals(immutableArray.array[i], items.array[i])) { return false; } } return true; } /// <summary> /// Determines whether two sequences are equal according to an equality comparer. /// </summary> /// <typeparam name="TDerived">The type of element in the compared array.</typeparam> /// <typeparam name="TBase">The type of element contained by the collection.</typeparam> [Pure] public static bool SequenceEqual<TDerived, TBase>(this ImmutableArray<TBase> immutableArray, IEnumerable<TDerived> items, IEqualityComparer<TBase> comparer = null) where TDerived : TBase { Requires.NotNull(items, "items"); if (comparer == null) { comparer = EqualityComparer<TBase>.Default; } int i = 0; int n = immutableArray.Length; foreach (var item in items) { if (i == n) { return false; } if (!comparer.Equals(immutableArray[i], item)) { return false; } i++; } return i == n; } /// <summary> /// Determines whether two sequences are equal according to an equality comparer. /// </summary> /// <typeparam name="TDerived">The type of element in the compared array.</typeparam> /// <typeparam name="TBase">The type of element contained by the collection.</typeparam> [Pure] public static bool SequenceEqual<TDerived, TBase>(this ImmutableArray<TBase> immutableArray, ImmutableArray<TDerived> items, Func<TBase, TBase, bool> predicate) where TDerived : TBase { Requires.NotNull(predicate, "predicate"); immutableArray.ThrowNullRefIfNotInitialized(); items.ThrowNullRefIfNotInitialized(); if (object.ReferenceEquals(immutableArray.array, items.array)) { return true; } if (immutableArray.Length != items.Length) { return false; } for (int i = 0, n = immutableArray.Length; i < n; i++) { if (!predicate(immutableArray[i], items[i])) { return false; } } return true; } /// <summary> /// Applies an accumulator function over a sequence. /// </summary> /// <typeparam name="T">The type of element contained by the collection.</typeparam> [Pure] public static T Aggregate<T>(this ImmutableArray<T> immutableArray, Func<T, T, T> func) { Requires.NotNull(func, "func"); if (immutableArray.Length == 0) { return default(T); } var result = immutableArray[0]; for (int i = 1, n = immutableArray.Length; i < n; i++) { result = func(result, immutableArray[i]); } return result; } /// <summary> /// Applies an accumulator function over a sequence. /// </summary> /// <typeparam name="TAccumulate">The type of the accumulated value.</typeparam> /// <typeparam name="T">The type of element contained by the collection.</typeparam> [Pure] public static TAccumulate Aggregate<TAccumulate, T>(this ImmutableArray<T> immutableArray, TAccumulate seed, Func<TAccumulate, T, TAccumulate> func) { Requires.NotNull(func, "func"); var result = seed; foreach (var v in immutableArray.array) { result = func(result, v); } return result; } /// <summary> /// Applies an accumulator function over a sequence. /// </summary> /// <typeparam name="TAccumulate">The type of the accumulated value.</typeparam> /// <typeparam name="TResult">The type of result returned by the result selector.</typeparam> /// <typeparam name="T">The type of element contained by the collection.</typeparam> [Pure] public static TResult Aggregate<TAccumulate, TResult, T>(this ImmutableArray<T> immutableArray, TAccumulate seed, Func<TAccumulate, T, TAccumulate> func, Func<TAccumulate, TResult> resultSelector) { Requires.NotNull(resultSelector, "resultSelector"); return resultSelector(Aggregate(immutableArray, seed, func)); } /// <summary> /// Returns the element at a specified index in a sequence. /// </summary> /// <typeparam name="T">The type of element contained by the collection.</typeparam> [Pure] public static T ElementAt<T>(this ImmutableArray<T> immutableArray, int index) { return immutableArray[index]; } /// <summary> /// Returns the element at a specified index in a sequence or a default value if the index is out of range. /// </summary> /// <typeparam name="T">The type of element contained by the collection.</typeparam> [Pure] public static T ElementAtOrDefault<T>(this ImmutableArray<T> immutableArray, int index) { if (index < 0 || index >= immutableArray.Length) { return default(T); } return immutableArray[index]; } /// <summary> /// Returns the first element in a sequence that satisfies a specified condition. /// </summary> /// <typeparam name="T">The type of element contained by the collection.</typeparam> [Pure] public static T First<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { Requires.NotNull(predicate, "predicate"); foreach (var v in immutableArray.array) { if (predicate(v)) { return v; } } // Throw the same exception that LINQ would. return Enumerable.Empty<T>().First(); } /// <summary> /// Returns the first element in a sequence that satisfies a specified condition. /// </summary> /// <typeparam name="T">The type of element contained by the collection.</typeparam> /// <param name="immutableArray"></param> [Pure] public static T First<T>(this ImmutableArray<T> immutableArray) { // In the event of an empty array, generate the same exception // that the linq extension method would. return immutableArray.Length > 0 ? immutableArray[0] : Enumerable.First(immutableArray.array); } /// <summary> /// Returns the first element of a sequence, or a default value if the sequence contains no elements. /// </summary> /// <typeparam name="T">The type of element contained by the collection.</typeparam> /// <param name="immutableArray"></param> [Pure] public static T FirstOrDefault<T>(this ImmutableArray<T> immutableArray) { return immutableArray.array.Length > 0 ? immutableArray.array[0] : default(T); } /// <summary> /// Returns the first element of the sequence that satisfies a condition or a default value if no such element is found. /// </summary> /// <typeparam name="T">The type of element contained by the collection.</typeparam> [Pure] public static T FirstOrDefault<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { Requires.NotNull(predicate, "predicate"); foreach (var v in immutableArray.array) { if (predicate(v)) { return v; } } return default(T); } /// <summary> /// Returns the last element of a sequence. /// </summary> /// <typeparam name="T">The type of element contained by the collection.</typeparam> /// <param name="immutableArray"></param> [Pure] public static T Last<T>(this ImmutableArray<T> immutableArray) { // In the event of an empty array, generate the same exception // that the linq extension method would. return immutableArray.Length > 0 ? immutableArray[immutableArray.Length - 1] : Enumerable.Last(immutableArray.array); } /// <summary> /// Returns the last element of a sequence that satisfies a specified condition. /// </summary> /// <typeparam name="T">The type of element contained by the collection.</typeparam> [Pure] public static T Last<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { Requires.NotNull(predicate, "predicate"); for (int i = immutableArray.Length - 1; i >= 0; i--) { if (predicate(immutableArray[i])) { return immutableArray[i]; } } // Throw the same exception that LINQ would. return Enumerable.Empty<T>().Last(); } /// <summary> /// Returns the last element of a sequence, or a default value if the sequence contains no elements. /// </summary> /// <typeparam name="T">The type of element contained by the collection.</typeparam> /// <param name="immutableArray"></param> [Pure] public static T LastOrDefault<T>(this ImmutableArray<T> immutableArray) { immutableArray.ThrowNullRefIfNotInitialized(); return immutableArray.array.LastOrDefault(); } /// <summary> /// Returns the last element of a sequence that satisfies a condition or a default value if no such element is found. /// </summary> /// <typeparam name="T">The type of element contained by the collection.</typeparam> [Pure] public static T LastOrDefault<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { Requires.NotNull(predicate, "predicate"); for (int i = immutableArray.Length - 1; i >= 0; i--) { if (predicate(immutableArray[i])) { return immutableArray[i]; } } return default(T); } /// <summary> /// Returns the only element of a sequence, and throws an exception if there is not exactly one element in the sequence. /// </summary> /// <typeparam name="T">The type of element contained by the collection.</typeparam> /// <param name="immutableArray"></param> [Pure] public static T Single<T>(this ImmutableArray<T> immutableArray) { immutableArray.ThrowNullRefIfNotInitialized(); return immutableArray.array.Single(); } /// <summary> /// Returns the only element of a sequence that satisfies a specified condition, and throws an exception if more than one such element exists. /// </summary> /// <typeparam name="T">The type of element contained by the collection.</typeparam> [Pure] public static T Single<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { Requires.NotNull(predicate, "predicate"); var first = true; var result = default(T); foreach (var v in immutableArray.array) { if (predicate(v)) { if (!first) { ImmutableArray.TwoElementArray.Single(); // throw the same exception as LINQ would } first = false; result = v; } } if (first) { Enumerable.Empty<T>().Single(); // throw the same exception as LINQ would } return result; } /// <summary> /// Returns the only element of a sequence, or a default value if the sequence is empty; this method throws an exception if there is more than one element in the sequence. /// </summary> /// <typeparam name="T">The type of element contained by the collection.</typeparam> /// <param name="immutableArray"></param> [Pure] public static T SingleOrDefault<T>(this ImmutableArray<T> immutableArray) { immutableArray.ThrowNullRefIfNotInitialized(); return immutableArray.array.SingleOrDefault(); } /// <summary> /// Returns the only element of a sequence that satisfies a specified condition or a default value if no such element exists; this method throws an exception if more than one element satisfies the condition. /// </summary> /// <typeparam name="T">The type of element contained by the collection.</typeparam> [Pure] public static T SingleOrDefault<T>(this ImmutableArray<T> immutableArray, Func<T, bool> predicate) { Requires.NotNull(predicate, "predicate"); var first = true; var result = default(T); foreach (var v in immutableArray.array) { if (predicate(v)) { if (!first) { ImmutableArray.TwoElementArray.Single(); // throw the same exception as LINQ would } first = false; result = v; } } return result; } /// <summary> /// Creates a dictionary based on the contents of this array. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="T">The type of element contained by the collection.</typeparam> /// <param name="immutableArray"></param> /// <param name="keySelector">The key selector.</param> /// <returns>The newly initialized dictionary.</returns> [Pure] public static Dictionary<TKey, T> ToDictionary<TKey, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector) { return ToDictionary(immutableArray, keySelector, EqualityComparer<TKey>.Default); } /// <summary> /// Creates a dictionary based on the contents of this array. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TElement">The type of the element.</typeparam> /// <typeparam name="T">The type of element contained by the collection.</typeparam> /// <param name="immutableArray"></param> /// <param name="keySelector">The key selector.</param> /// <param name="elementSelector">The element selector.</param> /// <returns>The newly initialized dictionary.</returns> [Pure] public static Dictionary<TKey, TElement> ToDictionary<TKey, TElement, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector, Func<T, TElement> elementSelector) { return ToDictionary(immutableArray, keySelector, elementSelector, EqualityComparer<TKey>.Default); } /// <summary> /// Creates a dictionary based on the contents of this array. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="T">The type of element contained by the collection.</typeparam> /// <param name="immutableArray"></param> /// <param name="keySelector">The key selector.</param> /// <param name="comparer">The comparer to initialize the dictionary with.</param> /// <returns>The newly initialized dictionary.</returns> [Pure] public static Dictionary<TKey, T> ToDictionary<TKey, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector, IEqualityComparer<TKey> comparer) { Requires.NotNull(keySelector, "keySelector"); var result = new Dictionary<TKey, T>(comparer); foreach (var v in immutableArray) { result.Add(keySelector(v), v); } return result; } /// <summary> /// Creates a dictionary based on the contents of this array. /// </summary> /// <typeparam name="TKey">The type of the key.</typeparam> /// <typeparam name="TElement">The type of the element.</typeparam> /// <typeparam name="T">The type of element contained by the collection.</typeparam> /// <param name="immutableArray"></param> /// <param name="keySelector">The key selector.</param> /// <param name="elementSelector">The element selector.</param> /// <param name="comparer">The comparer to initialize the dictionary with.</param> /// <returns>The newly initialized dictionary.</returns> [Pure] public static Dictionary<TKey, TElement> ToDictionary<TKey, TElement, T>(this ImmutableArray<T> immutableArray, Func<T, TKey> keySelector, Func<T, TElement> elementSelector, IEqualityComparer<TKey> comparer) { Requires.NotNull(keySelector, "keySelector"); Requires.NotNull(elementSelector, "elementSelector"); var result = new Dictionary<TKey, TElement>(immutableArray.Length, comparer); foreach (var v in immutableArray.array) { result.Add(keySelector(v), elementSelector(v)); } return result; } /// <summary> /// Copies the contents of this array to a mutable array. /// </summary> /// <typeparam name="T">The type of element contained by the collection.</typeparam> /// <param name="immutableArray"></param> /// <returns>The newly instantiated array.</returns> [Pure] public static T[] ToArray<T>(this ImmutableArray<T> immutableArray) { immutableArray.ThrowNullRefIfNotInitialized(); if (immutableArray.array.Length == 0) { return ImmutableArray<T>.Empty.array; } return (T[])immutableArray.array.Clone(); } #endregion #region ImmutableArray<T>.Builder extensions /// <summary> /// Returns the first element in the collection. /// </summary> /// <exception cref="System.InvalidOperationException">Thrown if the collection is empty.</exception> [Pure] public static T First<T>(this ImmutableArray<T>.Builder builder) { Requires.NotNull(builder, "builder"); if (!builder.Any()) { throw new InvalidOperationException(); } return builder[0]; } /// <summary> /// Returns the first element in the collection, or the default value if the collection is empty. /// </summary> [Pure] public static T FirstOrDefault<T>(this ImmutableArray<T>.Builder builder) { Requires.NotNull(builder, "builder"); return builder.Any() ? builder[0] : default(T); } /// <summary> /// Returns the last element in the collection. /// </summary> /// <exception cref="System.InvalidOperationException">Thrown if the collection is empty.</exception> [Pure] public static T Last<T>(this ImmutableArray<T>.Builder builder) { Requires.NotNull(builder, "builder"); if (!builder.Any()) { throw new InvalidOperationException(); } return builder[builder.Count - 1]; } /// <summary> /// Returns the last element in the collection, or the default value if the collection is empty. /// </summary> [Pure] public static T LastOrDefault<T>(this ImmutableArray<T>.Builder builder) { Requires.NotNull(builder, "builder"); return builder.Any() ? builder[builder.Count - 1] : default(T); } /// <summary> /// Returns a value indicating whether this collection contains any elements. /// </summary> [Pure] public static bool Any<T>(this ImmutableArray<T>.Builder builder) { Requires.NotNull(builder, "builder"); return builder.Count > 0; } #endregion #region Private Implementation Details /// <summary>Provides the core iterator implementation of <see cref="SelectMany"/>.</summary> private static IEnumerable<TResult> SelectManyIterator<TSource, TCollection, TResult>( this ImmutableArray<TSource> immutableArray, Func<TSource, IEnumerable<TCollection>> collectionSelector, Func<TSource, TCollection, TResult> resultSelector) { foreach (TSource item in immutableArray.array) { foreach (TCollection result in collectionSelector(item)) { yield return resultSelector(item, result); } } } #endregion } }
mafiya69/corefx
src/System.Collections.Immutable/src/System/Linq/ImmutableArrayExtensions.cs
C#
mit
30,414
--- title: Can the same organization submit multiple proposals? published: True tags: [small_grants_fund] categories: [faqs] layout: post --- <div class="content"> <p>Yes.</p> </div>
Vizzuality/gfw-howto
_posts/01-01-01-faq-sgf-can-the-same-organization-submit-multiple-proposals.md
Markdown
mit
183
var fs = require('fs') var path = require('path') module.exports.getConfig = getConfig var env = process.env.NODE_ENV || 'development' var configDirs = fs.readdirSync(path.resolve(__dirname, '../config')) var configObj = {} configDirs.forEach(function(dirName) { if (dirName.indexOf('.') !== 0) { // skip hidden folder like .DS_Store in Mac var config = require('../config/' + dirName + '/' + env) configObj[dirName] = config } }) function getConfig() { return configObj }
kenspirit/generator-evergrow
generators/app/templates/system/config-manager.js
JavaScript
mit
496
using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using Xe.BinaryMapper; namespace OpenKh.Kh2.Mixdata { public class BaseMixdata<T> : IEnumerable<T> where T : class { [Data] public int MagicCode { get; set; } [Data] public int Version { get; set; } [Data] public int Count { get; set; } [Data] public int Padding { get; set; } [Data] public List<T> Items { get; set; } public static BaseMixdata<T> Read(Stream stream) { var baseTable = BinaryMapping.ReadObject<BaseMixdata<T>>(stream); baseTable.Items = Enumerable.Range(0, baseTable.Count) .Select(_ => BinaryMapping.ReadObject<T>(stream)) .ToList(); return baseTable; } public static void Write(Stream stream, int magic, int version, List<T> items) => new BaseMixdata<T>() { MagicCode = magic, Version = version, Padding = 0, Items = items }.Write(stream); public void Write(Stream stream) { Count = Items.Count; BinaryMapping.WriteObject(stream, this); foreach (var item in Items) BinaryMapping.WriteObject(stream, item); } public IEnumerator<T> GetEnumerator() => Items.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => Items.GetEnumerator(); } }
Xeeynamo/KingdomHearts
OpenKh.Kh2/Mixdata/BaseMixdata.cs
C#
mit
1,518
package com.swfarm.biz.chain.bo; import java.io.Serializable; public class NamedPriceAdjustmentStep implements Serializable { private Long id; private String code; private String name; private String defaultSfmCode; private String defaultBuyerCountry; private String planName; private Double profitMargin; private Integer saleQuantityIncreaseThreshold; private Integer saleQuantityDecreaseThreshold; private Integer priority; private Boolean isInitialStep; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getCode() { return code; } public void setCode(String stepCode) { this.code = stepCode; } public String getName() { return name; } public void setName(String stepName) { this.name = stepName; } public String getDefaultSfmCode() { return defaultSfmCode; } public void setDefaultSfmCode(String defaultSfmCode) { this.defaultSfmCode = defaultSfmCode; } public String getDefaultBuyerCountry() { return defaultBuyerCountry; } public void setDefaultBuyerCountry(String defaultBuyerCountry) { this.defaultBuyerCountry = defaultBuyerCountry; } public String getPlanName() { return planName; } public void setPlanName(String planName) { this.planName = planName; } public Double getProfitMargin() { return profitMargin; } public void setProfitMargin(Double profitMargin) { this.profitMargin = profitMargin; } public Integer getSaleQuantityIncreaseThreshold() { return saleQuantityIncreaseThreshold; } public void setSaleQuantityIncreaseThreshold(Integer saleQuantityThreshold) { this.saleQuantityIncreaseThreshold = saleQuantityThreshold; } public Integer getSaleQuantityDecreaseThreshold() { return saleQuantityDecreaseThreshold; } public void setSaleQuantityDecreaseThreshold(Integer saleQuantityDecreaseThreshold) { this.saleQuantityDecreaseThreshold = saleQuantityDecreaseThreshold; } public Integer getPriority() { return priority; } public void setPriority(Integer priority) { this.priority = priority; } public Boolean getIsInitialStep() { if (isInitialStep == null) { isInitialStep = false; } return isInitialStep; } public void setIsInitialStep(Boolean isInitialStep) { this.isInitialStep = isInitialStep; } }
zhangqiang110/my4j
pms/src/main/java/com/swfarm/biz/chain/bo/NamedPriceAdjustmentStep.java
Java
mit
2,423
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Coq bench</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../../..">Unstable</a></li> <li><a href=".">8.5beta1 / contrib:jprover dev</a></li> <li class="active"><a href="">2015-02-03 21:08:42</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li><a href="../../../../../about.html">About</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href=".">« Up</a> <h1> contrib:jprover <small> dev <span class="label label-success">7 s</span> </small> </h1> <p><em><script>document.write(moment("2015-02-03 21:08:42 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2015-02-03 21:08:42 UTC)</em><p> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>ruby lint.rb unstable ../unstable/packages/coq:contrib:jprover/coq:contrib:jprover.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Dry install</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --dry-run coq:contrib:jprover.dev coq.8.5beta1</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>2 s</dd> </dl> <p>Dry install without Coq, to test if the problem was incompatibility with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>ulimit -Sv 2000000; timeout 5m opam install -y --deps-only coq:contrib:jprover.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>2 s</dd> </dl> <h2>Install</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>ulimit -Sv 2000000; timeout 5m opam install -y --verbose coq:contrib:jprover.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>7 s</dd> </dl> <h2>Installation size</h2> <p>Total: 820 K</p> <ul> <li>356 K <code>/home/bench/.opam/system/lib/coq/user-contrib/JProver/jall.cmxs</code></li> <li>112 K <code>/home/bench/.opam/system/lib/coq/user-contrib/JProver/jall.cmo</code></li> <li>101 K <code>/home/bench/.opam/system/lib/coq/user-contrib/JProver/jterm.cmxs</code></li> <li>73 K <code>/home/bench/.opam/system/lib/coq/user-contrib/JProver/jprover.cmxs</code></li> <li>59 K <code>/home/bench/.opam/system/lib/coq/user-contrib/JProver/jtunify.cmxs</code></li> <li>21 K <code>/home/bench/.opam/system/lib/coq/user-contrib/JProver/jterm.cmo</code></li> <li>20 K <code>/home/bench/.opam/system/lib/coq/user-contrib/JProver/jprover.cmo</code></li> <li>16 K <code>/home/bench/.opam/system/lib/coq/user-contrib/JProver/jlogic.cmxs</code></li> <li>15 K <code>/home/bench/.opam/system/lib/coq/user-contrib/JProver/opname.cmxs</code></li> <li>12 K <code>/home/bench/.opam/system/lib/coq/user-contrib/JProver/jtunify.cmo</code></li> <li>11 K <code>/home/bench/.opam/system/lib/coq/user-contrib/JProver/jprover.cmi</code></li> <li>6 K <code>/home/bench/.opam/system/lib/coq/user-contrib/JProver/jterm.cmi</code></li> <li>2 K <code>/home/bench/.opam/system/lib/coq/user-contrib/JProver/jtunify.cmi</code></li> <li>2 K <code>/home/bench/.opam/system/lib/coq/user-contrib/JProver/jlogic.cmi</code></li> <li>2 K <code>/home/bench/.opam/system/lib/coq/user-contrib/JProver/jlogic.cmo</code></li> <li>1 K <code>/home/bench/.opam/system/lib/coq/user-contrib/JProver/opname.cmo</code></li> <li>1 K <code>/home/bench/.opam/system/lib/coq/user-contrib/JProver/jall.cmi</code></li> <li>1 K <code>/home/bench/.opam/system/lib/coq/user-contrib/JProver/opname.cmi</code></li> <li>1 K <code>/home/bench/.opam/system/lib/coq/user-contrib/JProver/JProver.vo</code></li> <li>1 K <code>/home/bench/.opam/system/lib/coq/user-contrib/JProver/JProver.v</code></li> <li>1 K <code>/home/bench/.opam/system/lib/coq/user-contrib/JProver/JProver.glob</code></li> <li>1 K <code>/home/bench/.opam/system/lib/coq:contrib:jprover/opam.config</code></li> <li>1 K <code>/home/bench/.opam/system/install/coq:contrib:jprover.install</code></li> </ul> <h2>Uninstall</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq:contrib:jprover.dev</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>2 s</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> <small>Sources are on <a href="https://github.com/coq-bench">GitHub</a>. © Guillaume Claret.</small> </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io-old
clean/Linux-x86_64-4.02.1-1.2.0/unstable/8.5beta1/contrib:jprover/dev/2015-02-03_21-08-42.html
HTML
mit
7,839
# Docker-specific local settings import os DEBUG = True TEMPLATE_DEBUG = DEBUG DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'db', } } # Make this unique, and don't share it with anybody. SECRET_KEY = '' TEMPLATE_DIRS = ( '/srv/webldap/templates', ) EMAIL_FROM = 'root@localhost' REQ_EXPIRE_HRS = 48 REQ_EXPIRE_STR = '48 heures' LDAP_URI = 'ldap://{}:{}'.format(os.environ['LDAP_PORT_389_TCP_ADDR'], os.environ['LDAP_PORT_389_TCP_PORT']) LDAP_STARTTLS = False LDAP_CACERT = '' LDAP_BASE = 'dc=example,dc=net' LDAP_WEBLDAP_USER = 'cn=webldap,ou=service-users,dc=example,dc=net' LDAP_WEBLDAP_PASSWD = 'secret' LDAP_DEFAULT_GROUPS = [] LDAP_DEFAULT_ROLES = ['member']
FedeRez/webldap
app/webldap/local_settings.docker.py
Python
mit
764
module EffectiveEmailTemplates VERSION = '1.1.3'.freeze end
code-and-effect/effective_email_templates
lib/effective_email_templates/version.rb
Ruby
mit
62
--- description: Enable AMP in a page, and control the way Next.js adds AMP to the page with the AMP config. --- # next/amp <details> <summary><b>Examples</b></summary> <ul> <li><a href="https://github.com/vercel/next.js/tree/canary/examples/amp">AMP</a></li> </ul> </details> > AMP support is one of our advanced features, you can read more about it [here](/docs/advanced-features/amp-support/introduction.md). To enable AMP, add the following config to your page: ```jsx export const config = { amp: true } ``` The `amp` config accepts the following values: - `true` - The page will be AMP-only - `'hybrid'` - The page will have two versions, one with AMP and another one with HTML To learn more about the `amp` config, read the sections below. ## AMP First Page Take a look at the following example: ```jsx export const config = { amp: true } function About(props) { return <h3>My AMP About Page!</h3> } export default About ``` The page above is an AMP-only page, which means: - The page has no Next.js or React client-side runtime - The page is automatically optimized with [AMP Optimizer](https://github.com/ampproject/amp-toolbox/tree/master/packages/optimizer), an optimizer that applies the same transformations as AMP caches (improves performance by up to 42%) - The page has an user-accessible (optimized) version of the page and a search-engine indexable (unoptimized) version of the page ## Hybrid AMP Page Take a look at the following example: ```jsx import { useAmp } from 'next/amp' export const config = { amp: 'hybrid' } function About(props) { const isAmp = useAmp() return ( <div> <h3>My AMP About Page!</h3> {isAmp ? ( <amp-img width="300" height="300" src="/my-img.jpg" alt="a cool image" layout="responsive" /> ) : ( <img width="300" height="300" src="/my-img.jpg" alt="a cool image" /> )} </div> ) } export default About ``` The page above is a hybrid AMP page, which means: - The page is rendered as traditional HTML (default) and AMP HTML (by adding `?amp=1` to the URL) - The AMP version of the page only has valid optimizations applied with AMP Optimizer so that it is indexable by search-engines The page uses `useAmp` to differentiate between modes, it's a [React Hook](https://reactjs.org/docs/hooks-intro.html) that returns `true` if the page is using AMP, and `false` otherwise.
flybayer/next.js
docs/api-reference/next/amp.md
Markdown
mit
2,461
/* * print_chart.h * Kevin Coltin * * Contains functions for printing a chart of blackjack strategy to Latex. */ #ifndef PRINT_CHART_H #define PRINT_CHART_H #include <stdio.h> #include "bj_sims.h" #include "bj_strat.h" void printChart (Strategy **chart, const char *filename, int showWinPct, int MAKE_SIMPLE_CHART); void printHand (int i, Strategy **chart, int showWinPct, FILE *file); char * actionSymbol (int); void printSimsChart (HandSim **simsChart, Strategy **chart, const char *filename, int nsims); void printHandSims (int i, HandSim **simsChart, Strategy **chart, FILE *file, int nsims); #endif
kcoltin/blackjack
include/print_chart.h
C
mit
668
package io.github.tiscs.demos.oauth2.providers; import io.github.tiscs.demos.oauth2.entities.UserAccountEntity; import io.github.tiscs.demos.oauth2.entities.UserCredentialEntity; import io.github.tiscs.demos.oauth2.repositories.UserAccountRepository; import io.github.tiscs.demos.oauth2.repositories.UserCredentialRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.Collections; @Component public class JpaUserDetailsService implements UserDetailsService { private final UserCredentialRepository userCredentialRepository; private final UserAccountRepository userAccountRepository; @Autowired public JpaUserDetailsService(UserCredentialRepository userCredentialRepository, UserAccountRepository userAccountRepository) { this.userCredentialRepository = userCredentialRepository; this.userAccountRepository = userAccountRepository; } @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { UserCredentialEntity credential = userCredentialRepository.findOneByUserKey(username); UserAccountEntity account = userAccountRepository.findOne(credential.getAccountId()); LocalDateTime utcNow = ZonedDateTime.now(ZoneOffset.UTC).toLocalDateTime(); return new User( credential.getUserKey(), credential.getSecretCode(), !account.isDisabled(), !account.getExpiresAt().isBefore(utcNow), !credential.getExpiresAt().isBefore(utcNow), !account.isLocked(), Collections.emptyList() ); } }
Tiscs/spring-cloud-oauth2-demo
oauth2-server/src/main/java/io/github/tiscs/demos/oauth2/providers/JpaUserDetailsService.java
Java
mit
2,077
<!DOCTYPE html> <html> <head> <title>Dan at EDA</title> <meta charset="UTF-8"> <link href="https://fonts.googleapis.com/css?family=Average|Fugaz+One|Lusitana" rel="stylesheet"> <!-- Skeleton Normalize --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.css"> <!-- Skeleton --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.css"> <!-- My personal CSS --> <link rel="stylesheet" href="../styles/main.css"> </head> <body> <header class="container"> <div class="row"> <div class="twelve columns"> <div class="image-title"> <img class="logo u-max-full-width" src="../images/morning.jpg" alt="Enspiral Dev Academy"> </div> </div> <div class="twelve columns"> <div class="title"> <h1>Technical Part 1</h1> </div> </div> </div> </header> <div class="container"> <div class="row"> <nav class="two columns"> <a class="button" href="../index.html">Home</a> <a class="button" href="c1-reflection-blog.html">Reflection</a> <a class="button" href="c1-time-and-habits-blog.html">Time & Habits</a> <a class="button" href="t2-html-css-dom-p1.html">Technical Part 1</a> <a class="button" href="t2-html-css-dom-p2.html">Technical Part 2</a> <a class="button" href="t4-javascript-basics.html">Technical Part 3</a> <a class="button" href="c2-emotional-intelligence.html">Cultural Part 1</a> <a class="button" href="c3-meditation-process.html">Cultural Part 2</a> <a class="button" href="t3-design-to-web-blog.html">Design to Web</a> <a class="button" href="t5-problem-solving.html">Problem Solving</a> <a class="button" href="t6-js-language.html">JS Language</a> <a class="button" href="t6-scope.html">Scope</a> </nav> <div class="ten columns"> <div class="blog-content"> <strong>How would you describe HTML, CSS and the DOM?</strong> <p>HTML is the basic coding and filling of a webpage. All your text, links and other bits and bobs. <br>CSS is the styling given to the HTML. The colouring of texts, backgrounds and the size/shape of boxes. <br>DOM or "Domain Object Model" is the interface used by your web browser which interprets the data/code in your html and css files. It organises it lets you view specific parts of said code.</p> <strong>What is meant by boxifying design?</strong> <p>Turning everything on a webpage into many many boxes. Big boxes, little boxes, boxes in boxes in boxes in boxes. This is how you organise the placing of you page content </p> <strong>What is the box model?</strong> <p>Seen in the DOM, it displays the details of each box. How many pixels or percentage of the page it will cover including all padding and margins etc.</p> </div> </div> </div> </div> </body> <footer class="container"> <div class="row"> <div class="twelve columns"> <p>Foot notes</p> </div> </div> </footer> </html>
daniel-reason/daniel-reason.github.io
blog/t2-html-css-dom-p1.html
HTML
mit
3,469
/** * Copyright (c) 2015 Alexandre Vaillancourt. See full MIT license at the root of the repository. */ #pragma once #include <stdint.h> class DirtMap { public: DirtMap( float aWorldWidth, float aWorldHeight, int aCanvasWidth, int aCanvasHeight, float aDirtRate); ~DirtMap(); void simulateOneStep(); void patrol( float aX, float aY, float aRadius ); const float* getDirtMap() const { return mDirtMap; } const uint8_t* getDirtMapPix() const { return mIntMap; } uint8_t getDirtLevelScaled( float aX, float aY ); private: float mWorldWidth; float mWorldHeight; float mDirtRate; float* mDirtMap; uint8_t* mIntMap; float mDirtRatePerFrame; const float mSizeToGridScale; int mCanvasWidth; int mCanvasHeight; int mGridTileCount; float getDirtLevel( float aX, float aY ); };
vaillancourt/patrol
src/DirtMap.h
C
mit
848
describe "Build Manager" do describe ".truncate_changelog" do it "Truncates Changelog" do changelog = File.read("./pilot/spec/fixtures/build_manager/changelog_long") changelog = Pilot::BuildManager.truncate_changelog(changelog) expect(changelog).to eq(File.read("./pilot/spec/fixtures/build_manager/changelog_long_truncated")) end it "Keeps changelog if short enough" do changelog = "1234" changelog = Pilot::BuildManager.truncate_changelog(changelog) expect(changelog).to eq("1234") end it "Truncates based on bytes not characters" do changelog = "ü" * 4000 expect(changelog.unpack("C*").length).to eq(8000) changelog = Pilot::BuildManager.truncate_changelog(changelog) # Truncation appends "...", so the result is 1998 two-byte characters plus "..." for 3999 bytes. expect(changelog.unpack("C*").length).to eq(3999) end end describe ".sanitize_changelog" do it "removes emoji" do changelog = "I'm 🦇B🏧an!" changelog = Pilot::BuildManager.sanitize_changelog(changelog) expect(changelog).to eq("I'm Ban!") end it "removes emoji before truncating" do changelog = File.read("./pilot/spec/fixtures/build_manager/changelog_long") changelog = "🎉🎉🎉#{changelog}" changelog = Pilot::BuildManager.sanitize_changelog(changelog) expect(changelog).to eq(File.read("./pilot/spec/fixtures/build_manager/changelog_long_truncated")) end end describe ".has_changelog_or_whats_new?" do let(:fake_build_manager) { Pilot::BuildManager.new } let(:no_options) { {} } let(:changelog) { { changelog: "Sup" } } let(:whats_new_symbol) { { localized_build_info: { 'en-us' => { whats_new: 'Sup' } } } } let(:whats_new_string) { { localized_build_info: { 'en-us' => { 'whats_new' => 'Sup' } } } } it "returns false for no changelog or whats_new" do has = fake_build_manager.has_changelog_or_whats_new?(no_options) expect(has).to eq(false) end it "returns true for changelog" do has = fake_build_manager.has_changelog_or_whats_new?(changelog) expect(has).to eq(true) end it "returns true for whats_new with symbol" do has = fake_build_manager.has_changelog_or_whats_new?(whats_new_symbol) expect(has).to eq(true) end it "returns true for whats_new with string" do has = fake_build_manager.has_changelog_or_whats_new?(whats_new_string) expect(has).to eq(true) end end describe "distribute submits the build for review" do let(:mock_base_client) { "fake api base client" } let(:fake_build_manager) { Pilot::BuildManager.new } let(:app) do Spaceship::ConnectAPI::App.new("123-123-123-123", { name: "Mock App" }) end let(:pre_release_version) do Spaceship::ConnectAPI::PreReleaseVersion.new("123-123-123-123", { version: "1.0" }) end let(:app_localizations) do [ Spaceship::ConnectAPI::BetaAppLocalization.new("234", { feedbackEmail: 'email@email.com', marketingUrl: 'https://url.com', privacyPolicyUrl: 'https://url.com', description: 'desc desc desc', locale: 'en-us' }), Spaceship::ConnectAPI::BetaAppLocalization.new("432", { feedbackEmail: 'email@email.com', marketingUrl: 'https://url.com', privacyPolicyUrl: 'https://url.com', description: 'desc desc desc', locale: 'en-gb' }) ] end let(:build_localizations) do [ Spaceship::ConnectAPI::BetaBuildLocalization.new("234", { whatsNew: 'some more words', locale: 'en-us' }), Spaceship::ConnectAPI::BetaBuildLocalization.new("432", { whatsNew: 'some words', locale: 'en-gb' }) ] end let(:build_beta_detail_still_processing) do Spaceship::ConnectAPI::BuildBetaDetail.new("321", { internal_build_state: Spaceship::ConnectAPI::BuildBetaDetail::InternalState::PROCESSING, external_build_state: Spaceship::ConnectAPI::BuildBetaDetail::ExternalState::PROCESSING }) end let(:build_beta_detail) do Spaceship::ConnectAPI::BuildBetaDetail.new("321", { internal_build_state: Spaceship::ConnectAPI::BuildBetaDetail::InternalState::READY_FOR_BETA_TESTING, external_build_state: Spaceship::ConnectAPI::BuildBetaDetail::ExternalState::READY_FOR_BETA_SUBMISSION }) end let(:beta_groups) do [ Spaceship::ConnectAPI::BetaGroup.new("987", { name: "Blue Man Group" }), Spaceship::ConnectAPI::BetaGroup.new("654", { name: "Green Eggs and Ham" }) ] end let(:ready_to_submit_mock_build) do Spaceship::ConnectAPI::Build.new("123", { version: '', uploadedDate: '', processingState: Spaceship::ConnectAPI::Build::ProcessingState::VALID, usesNonExemptEncryption: nil }) end let(:distribute_options) do { apple_id: 'mock_apple_id', app_identifier: 'mock_app_id', distribute_external: true, groups: ["Blue Man Group"], skip_submission: false } end let(:mock_api_client_beta_app_localizations) do [ { "id" => "234", "attributes" => { "locale" => "en-us" } }, { "id" => "432", "attributes" => { "locale" => "en-gb" } } ] end let(:mock_api_client_beta_build_localizations) do [ { "id" => "234", "attributes" => { "locale" => "en-us" } }, { "id" => "432", "attributes" => { "locale" => "en-gb" } } ] end let(:mock_api_client_beta_groups) do [ { "id" => "987", "attributes" => { "name" => "Blue Man Group" } }, { "id" => "654", "attributes" => { "name" => "Green Eggs and Ham" } } ] end describe "distribute success" do let(:distribute_options_skip_waiting_non_localized_changelog) do { apple_id: 'mock_apple_id', app_identifier: 'mock_app_id', distribute_external: false, skip_submission: false, skip_waiting_for_build_processing: true, notify_external_testers: true, uses_non_exempt_encryption: false, changelog: "log of changing" } end let(:distribute_options_non_localized) do { apple_id: 'mock_apple_id', app_identifier: 'mock_app_id', distribute_external: true, groups: ["Blue Man Group"], skip_submission: false, demo_account_required: true, notify_external_testers: true, beta_app_feedback_email: "josh+oldfeedback@rokkincat.com", beta_app_description: "old description for all the things", uses_non_exempt_encryption: false, changelog: "log of changing" } end before(:each) do allow(fake_build_manager).to receive(:login) allow(mock_base_client).to receive(:team_id).and_return('') allow(Spaceship::ConnectAPI).to receive(:post_beta_app_review_submissions) # pretend it worked. allow(Spaceship::ConnectAPI::TestFlight).to receive(:instance).and_return(mock_base_client) # Allow build to return app, buidl_beta_detail, and pre_release_version # These are models that are expected to usually be included in the build passed into distribute allow(ready_to_submit_mock_build).to receive(:app).and_return(app) allow(ready_to_submit_mock_build).to receive(:pre_release_version).and_return(pre_release_version) end it "updates non-localized changelog and doesn't distribute" do allow(ready_to_submit_mock_build).to receive(:build_beta_detail).and_return(build_beta_detail_still_processing) options = distribute_options_skip_waiting_non_localized_changelog # Expect beta build localizations to be fetched expect(Spaceship::ConnectAPI).to receive(:get_beta_build_localizations).with({ filter: { build: ready_to_submit_mock_build.id }, includes: nil, limit: nil, sort: nil }).and_return(Spaceship::ConnectAPI::Response.new) expect(ready_to_submit_mock_build).to receive(:get_beta_build_localizations).and_wrap_original do |m, *args| m.call(*args) build_localizations end # Expect beta build localizations to be patched with a UI.success after mock_api_client_beta_build_localizations.each do |localization| expect(Spaceship::ConnectAPI).to receive(:patch_beta_build_localizations).with({ localization_id: localization['id'], attributes: { whatsNew: options[:changelog] } }) end expect(FastlaneCore::UI).to receive(:success).with("Successfully set the changelog for build") # Expect build beta details to be patched expect(Spaceship::ConnectAPI).to receive(:patch_build_beta_details).with({ build_beta_details_id: build_beta_detail.id, attributes: { autoNotifyEnabled: options[:notify_external_testers] } }) # Don't expect success messages expect(FastlaneCore::UI).to_not(receive(:message).with(/Distributing new build to testers/)) expect(FastlaneCore::UI).to_not(receive(:success).with(/Successfully distributed build to/)) fake_build_manager.distribute(options, build: ready_to_submit_mock_build) end it "updates non-localized demo_account_required, notify_external_testers, beta_app_feedback_email, and beta_app_description and distributes" do allow(ready_to_submit_mock_build).to receive(:build_beta_detail).and_return(build_beta_detail) options = distribute_options_non_localized # Expect App.find to be called from within Pilot::Manager expect(Spaceship::ConnectAPI::App).to receive(:get).and_return(app) # Expect a beta app review detail to be patched expect(Spaceship::ConnectAPI).to receive(:patch_beta_app_review_detail).with({ app_id: ready_to_submit_mock_build.app_id, attributes: { demoAccountRequired: options[:demo_account_required] } }) # Expect beta app localizations to be fetched expect(Spaceship::ConnectAPI).to receive(:get_beta_app_localizations).with({ filter: { app: ready_to_submit_mock_build.app.id }, includes: nil, limit: nil, sort: nil }).and_return(Spaceship::ConnectAPI::Response.new) expect(app).to receive(:get_beta_app_localizations).and_wrap_original do |m, *args| m.call(*args) app_localizations end # Expect beta app localizations to be patched with a UI.success after mock_api_client_beta_app_localizations.each do |localization| expect(Spaceship::ConnectAPI).to receive(:patch_beta_app_localizations).with({ localization_id: localization['id'], attributes: { feedbackEmail: options[:beta_app_feedback_email], description: options[:beta_app_description] } }) end expect(FastlaneCore::UI).to receive(:success).with("Successfully set the beta_app_feedback_email and/or beta_app_description") # Expect beta build localizations to be fetched expect(Spaceship::ConnectAPI).to receive(:get_beta_build_localizations).with({ filter: { build: ready_to_submit_mock_build.id }, includes: nil, limit: nil, sort: nil }).and_return(Spaceship::ConnectAPI::Response.new) expect(ready_to_submit_mock_build).to receive(:get_beta_build_localizations).and_wrap_original do |m, *args| m.call(*args) build_localizations end # Expect beta build localizations to be patched with a UI.success after mock_api_client_beta_build_localizations.each do |localization| expect(Spaceship::ConnectAPI).to receive(:patch_beta_build_localizations).with({ localization_id: localization['id'], attributes: { whatsNew: options[:changelog] } }) end expect(FastlaneCore::UI).to receive(:success).with("Successfully set the changelog for build") # Expect build beta details to be patched expect(Spaceship::ConnectAPI).to receive(:patch_build_beta_details).with({ build_beta_details_id: build_beta_detail.id, attributes: { autoNotifyEnabled: options[:notify_external_testers] } }) # A build will go back into a processing state after a patch # Expect wait_for_build_processing_to_be_complete to be called after patching expect(Spaceship::ConnectAPI).to receive(:patch_builds).with({ build_id: ready_to_submit_mock_build.id, attributes: { usesNonExemptEncryption: false } }) expect(fake_build_manager).to receive(:wait_for_build_processing_to_be_complete).and_return(ready_to_submit_mock_build) # Expect beta groups fetched from app. This tests: # 1. app.get_beta_groups is called # 2. client.get_beta_groups is called inside of app.beta_groups expect(Spaceship::ConnectAPI).to receive(:get_beta_groups).with({ filter: { app: ready_to_submit_mock_build.app.id }, includes: nil, limit: nil, sort: nil }).and_return(Spaceship::ConnectAPI::Response.new) expect(app).to receive(:get_beta_groups).and_wrap_original do |m, *args| m.call(*args) beta_groups end # Expect beta groups to be added to a builds. This tests: # 1. build.add_beta_groups is called # 2. client.add_beta_groups_to_build is called inside of build.add_beta_groups expect(Spaceship::ConnectAPI).to receive(:add_beta_groups_to_build).with({ build_id: ready_to_submit_mock_build.id, beta_group_ids: [beta_groups[0].id] }).and_return(Spaceship::ConnectAPI::Response.new) expect(ready_to_submit_mock_build).to receive(:add_beta_groups).with(beta_groups: [beta_groups[0]]).and_wrap_original do |m, *args| m.call(*args) end # Expect success messages expect(FastlaneCore::UI).to receive(:message).with(/Distributing new build to testers/) expect(FastlaneCore::UI).to receive(:success).with(/Successfully distributed build to/) fake_build_manager.distribute(options, build: ready_to_submit_mock_build) end end end describe "#upload" do describe "uses Manager.login (which does spaceship login)" do let(:fake_build_manager) { Pilot::BuildManager.new } let(:upload_options) do { apple_id: 'mock_apple_id', skip_waiting_for_build_processing: true, ipa: 'foo' } end before(:each) do allow(fake_build_manager).to receive(:fetch_app_platform).and_return('ios') fake_ipauploadpackagebuilder = double allow(fake_ipauploadpackagebuilder).to receive(:generate).and_return(true) allow(FastlaneCore::IpaUploadPackageBuilder).to receive(:new).and_return(fake_ipauploadpackagebuilder) fake_itunestransporter = double allow(fake_itunestransporter).to receive(:upload).and_return(true) allow(FastlaneCore::ItunesTransporter).to receive(:new).and_return(fake_itunestransporter) end it "NOT when skip_waiting_for_build_processing and apple_id are set" do # should not execute Manager.login (which does spaceship login) expect(fake_build_manager).not_to(receive(:login)) fake_build_manager.upload(upload_options) end it "when skip_waiting_for_build_processing and apple_id are not set" do # remove options that make login unnecessary upload_options.delete(:apple_id) upload_options.delete(:skip_waiting_for_build_processing) # allow Manager.login method this time expect(fake_build_manager).to receive(:login).at_least(:once) # other stuff required to let `upload` work: allow(FastlaneCore::IpaFileAnalyser).to receive(:fetch_app_identifier).and_return("com.fastlane") allow(fake_build_manager).to receive(:fetch_app_id).and_return(123) allow(FastlaneCore::IpaFileAnalyser).to receive(:fetch_app_version) allow(FastlaneCore::IpaFileAnalyser).to receive(:fetch_app_build) fake_app = double allow(fake_app).to receive(:id).and_return(123) allow(fake_build_manager).to receive(:app).and_return(fake_app) fake_build = double allow(fake_build).to receive(:app_version) allow(fake_build).to receive(:version) allow(FastlaneCore::BuildWatcher).to receive(:wait_for_build_processing_to_be_complete).and_return(fake_build) allow(fake_build_manager).to receive(:distribute) fake_build_manager.upload(upload_options) end end end end
manuyavuz/fastlane
pilot/spec/build_manager_spec.rb
Ruby
mit
17,148
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" lang="en-US"> <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <meta name="show-menu-auto-arrows" content="1" /> <meta name="show-menu-drop-shadows" content="0" /> <title>group1 | Ocean Matters</title> <link rel="pingback" href="../../xmlrpc.php" /> <!--[if IE 6]> <script type="text/javascript" src="../../wp-content/themes/u-design/scripts/DD_belatedPNG_0.0.8a-min.js"></script> <script type="text/javascript"> // <![CDATA[ DD_belatedPNG.fix('.pngfix, img, #home-page-content li, #page-content li, #bottom li, #footer li, #recentcomments li span'); // ]]> </script> <![endif]--> <link rel="alternate" type="application/rss+xml" title="Ocean Matters &raquo; Feed" href="../../feed/index.html" /> <link rel="alternate" type="application/rss+xml" title="Ocean Matters &raquo; Comments Feed" href="../../comments/feed/index.html" /> <link rel="alternate" type="application/rss+xml" title="Ocean Matters &raquo; group1 Comments Feed" href="feed/index.html" /> <link rel='stylesheet' id='reset-css' href='../../wp-content/themes/u-design/styles/common-css/reset-ver=1.0.css' type='text/css' media='screen' /> <link rel='stylesheet' id='text-css' href='../../wp-content/themes/u-design/styles/style1/css/text-ver=1.0.css' type='text/css' media='screen' /> <link rel='stylesheet' id='grid-960-css' href='../../wp-content/themes/u-design/styles/common-css/960-ver=1.0.css' type='text/css' media='screen' /> <link rel='stylesheet' id='superfish_menu-css' href='../../wp-content/themes/u-design/scripts/superfish-1.4.8/css/superfish-ver=1.0.css' type='text/css' media='screen' /> <link rel='stylesheet' id='pretty_photo-css' href='../../wp-content/themes/u-design/scripts/prettyPhoto/css/prettyPhoto-ver=3.1.3.css' type='text/css' media='screen' /> <link rel='stylesheet' id='style-css' href='../../wp-content/themes/u-design/styles/style1/css/style-ver=1.0.css' type='text/css' media='screen' /> <link rel='stylesheet' id='custom-style-css' href='../../wp-content/themes/u-design/styles/custom/custom_style-ver=4.1.1.php' type='text/css' media='screen' /> <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'></script> <script type='text/javascript'>try{jQuery.noConflict();}catch(e){};</script> <script type='text/javascript' src='../../wp-includes/js/jquery/jquery-migrate.min-ver=1.2.1.js'></script> <script type='text/javascript' src='../../wp-content/themes/u-design/scripts/prettyPhoto/js/jquery.prettyPhoto-ver=3.1.3.js'></script> <script type='text/javascript' src='../../wp-content/themes/u-design/scripts/superfish-1.4.8/js/superfish.combined-ver=1.0.0.js'></script> <script type='text/javascript' src='../../wp-content/themes/u-design/scripts/script-ver=1.0.js'></script> <link rel="EditURI" type="application/rsd+xml" title="RSD" href="../../xmlrpc.php-rsd.xml" /> <link rel="wlwmanifest" type="application/wlwmanifest+xml" href="../../wp-includes/wlwmanifest.xml" /> <link rel='canonical' href='index.html' /> <link rel='shortlink' href='index.html' /> <!-- platinum seo pack 1.3.8 --> <meta name="robots" content="index,follow,noodp,noydir" /> <link rel="canonical" href="index.html" /> <!-- /platinum one seo pack --> <!--[if lte IE 9]> <link rel="stylesheet" href="../../wp-content/themes/u-design/styles/common-css/ie-all.css" media="screen" type="text/css" /> <![endif]--> <!--[if lte IE 7]> <link rel="stylesheet" href="../../wp-content/themes/u-design/styles/common-css/ie6-7.css" media="screen" type="text/css" /> <![endif]--> <!--[if IE 6]> <link rel="stylesheet" href="../../wp-content/themes/u-design/styles/common-css/ie6.css" media="screen" type="text/css" /> <style type="text/css">body{ behavior: url("../../wp-content/themes/u-design/scripts/csshover3.htc.txt"); } </style> <![endif]--> </head> <body class="attachment single single-attachment postid-677 attachmentid-677 attachment-jpeg top-bg-color-dark "> <div id="wrapper-1" class="pngfix"> <div id="top-wrapper"> <div id="top-elements" class="container_24"> <div id="logo" class="grid_14"> <div class="site-name"><a title="Ocean Matters" class="pngfix" href="../../index.html">Ocean Matters</a></div> </div> <div id="slogan" class="grid_17"></div> <!-- end logo slogan --> <div class="social-media-area grid_9 prefix_15"> <div class="social_media_top widget_text substitute_widget_class"> <div class="textwidget"><div class="social-icons"> <ul> <li class="social_icon"><a href="http://twitter.com/home?status=Reading%20-%20http://www.oceanmatters.org/" title="Share Ocean Matters on Twitter" target="_blank"><img src="../../wp-content/themes/u-design/styles/common-images/twitter-icon.png" alt="Share Ocean Matters on twitter" border="0" /></a></li> <li class="social_icon"><a href="http://www.facebook.com/sharer.php?u=http://www.oceanmatters.org/" title="Share Ocean Matters on Facebook" target="_blank"><img src="../../wp-content/themes/u-design/styles/common-images/facebook-icon.png" alt="fShare Ocean Matters on Facebook" border="0" /></a></li> <li class="social_icon"><a href="http://www.linkedin.com/shareArticle?mini=true&url=CONTENT-URL&title=CONTENT-TITLE&summary=DEATILS-OPTIONAL&source=OCEAN%20MATTERS" title="Share Ocean Matters on LinkedIn" target="_blank"><img src="../../wp-content/themes/u-design/styles/common-images/linkedin-icon.png" alt="Share Ocean Matters on linkedin" border="0" /></a></li> <li class="social_icon"><a href="../../contact-us/index.html" title="E-mail"><img src="../../wp-content/themes/u-design/styles/common-images/email-icon.png" alt="email" border="0" /></a></li> </ul> </div> </div> </div> </div><!-- end social-media-area --> </div> <!-- end top-elements --> <div id="main-menu" class="pngfix"> <div id="dropdown-holder" class="container_24"> <div id="navigation-menu" class="navigation-menu"><ul id="menu-main" class="sf-menu"><li id="menu-item-949" class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-949"><a href="../../index.html"><span>Home</span></a></li> <li id="menu-item-957" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-957"><a href="../../staff/index.html"><span>Staff</span></a></li> <li id="menu-item-956" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-956"><a href="../../philosophy/index.html"><span>Philosophy</span></a></li> <li id="menu-item-958" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-958"><a href="../../student-testimonials/index.html"><span>Testimonials</span></a></li> <li id="menu-item-950" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-950"><a href="../../programs/index.html"><span>Programs</span></a> <ul class="sub-menu"> <li id="menu-item-1453" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1453"><a href="../../programs/coconut-island-oahu-hawaii-2014/index.html"><span>Coconut Island, Oahu, Hawaii for Grownups!</span></a></li> <li id="menu-item-951" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-951"><a href="../../programs/grand-cayman-july-2012/index.html"><span>Coral Reef Ecology: Grand Cayman</span></a></li> <li id="menu-item-952" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-952"><a href="../../programs/our-coral-reef-ecology-program-2013/index.html"><span>Customized Summer Marine Biology Programs</span></a></li> <li id="menu-item-953" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-953"><a href="../../programs/research/index.html"><span>Field Research</span></a></li> <li id="menu-item-954" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-954"><a href="../../programs/scuba/index.html"><span>Scuba</span></a></li> <li id="menu-item-955" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-955"><a href="../../programs/prerequisites/index.html"><span>Prerequisites</span></a></li> </ul> </li> <li id="menu-item-960" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-960"><a href="../../gallery/index.html"><span>Gallery</span></a></li> <li id="menu-item-959" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-959"><a href="../../blog/index.html"><span>Blog</span></a></li> <li id="menu-item-961" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-961"><a href="../../donate/index.html"><span>Donate</span></a></li> <li id="menu-item-962" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-962"><a href="../../faqs/index.html"><span>FAQ&#8217;s</span></a></li> <li id="menu-item-963" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-963"><a href="../../contact-us/index.html"><span>More Info</span></a> <ul class="sub-menu"> <li id="menu-item-964" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-964"><a href="../../contact-us/apply/index.html"><span>Apply To Ocean Matters Grand Cayman Program</span></a></li> </ul> </li> </ul></div> </div> <!-- end dropdown-holder --> </div> <!-- end top-main-menu --> </div> <!-- end top-wrapper --> <div class="clear"></div> <div id="page-content-title"> <div id="page-content-header" class="container_24"> <div id="page-title"> <h1>group1</h1> </div> <!-- end page-title --> </div> <!-- end page-content-header --> </div> <!-- end page-content-title --> <div class="clear"></div> <div id="page-content"> <div class="container_24"> <p class="breadcrumbs"><a href="../../index.html">Home</a><span class="breadarrow"> &rarr; </span><a href="../../category/marine-biology-blog/index.html">marine biology blog</a><span class="breadarrow"> &rarr; </span><a href="../index.html" rel="prev">Rain, Rain Go Away!</a> <span class="breadarrow"> &rarr; </span><span class='current_crumb'>group1 </span></p> </div> <div id="content-container" class="container_24"> <div id="main-content" class="grid_24"> <div class="main-content-padding"> <div class="post" id="post-677"> <h2><a href="../index.html" rev="attachment">Rain, Rain Go Away!</a> &raquo; group1</h2> <div class="entry"> <p class="attachment"><a href="../../wp-content/uploads/2012/11/group1.jpg"><img width="300" height="224" src="../../wp-content/uploads/2012/11/group1-300x224.jpg" class="attachment-medium" alt="group1" /></a></p> <div class="caption"></div> <div class="navigation"> <div class="alignleft"></div> <div class="alignright"><a rel='wp-prettyPhoto[gallery]' href='../hell/index.html'><img width="150" height="150" src="../../wp-content/uploads/2012/11/hell-150x150.jpg" class="attachment-thumbnail" alt="hell" /></a></div> </div> <br class="clear" /> </div> </div> </div><!-- end main-content-padding --> </div><!-- end main-content --> </div><!-- end content-container --> <div class="clear"></div> </div><!-- end page-content --> <div class="clear"></div> <div id="bottom-bg"> <div id="bottom" class="container_24"> <div class="bottom-content-padding"> <div id='bottom_1' class='one_third'><div class='column-content-wrapper'><div class="bottom-col-content widget_nav_menu custom-formatting"><h3 class="bottom-col-title">Quick Links:</h3><div class="menu-newfooter-container"><ul id="menu-newfooter" class="menu"><li id="menu-item-732" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-732"><a href="../../programs/index.html">Summer Marine Biology Programs for Young People and Educators</a> <ul class="sub-menu"> <li id="menu-item-736" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-736"><a href="../../programs/prerequisites/index.html">Prerequisites</a></li> <li id="menu-item-735" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-735"><a href="../../programs/research/index.html">Field Research</a></li> <li id="menu-item-734" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-734"><a href="../../programs/scuba/index.html">Scuba</a></li> <li id="menu-item-733" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-733"><a href="../../programs/our-coral-reef-ecology-program-2013/index.html">Customized Summer Marine Biology Programs</a></li> </ul> </li> <li id="menu-item-738" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-738"><a href="../../philosophy/index.html">Summer Marine Biology Programs for Young People and Educators</a></li> <li id="menu-item-727" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-727"><a href="../../staff/index.html">Summer Marine Biology Programs for Young People and Educators</a></li> <li id="menu-item-728" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-728"><a href="../../blog/index.html">Ocean Matters Blog</a></li> <li id="menu-item-737" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-737"><a href="../../faqs/index.html">FAQ&#8217;s</a></li> <li id="menu-item-726" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-726"><a href="../../student-testimonials/index.html">Summer Marine Biology Programs for Young People and Educators</a></li> <li id="menu-item-729" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-has-children menu-item-729"><a href="../../contact-us/index.html">More Info</a> <ul class="sub-menu"> <li id="menu-item-731" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-731"><a href="../../donate/index.html">How Can I Help Save Our Seas?</a></li> <li id="menu-item-730" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-730"><a href="../../contact-us/apply/index.html">Apply To Ocean Matters Grand Cayman Program</a></li> </ul> </li> </ul></div></div></div></div><!-- end bottom_1 --><div id='bottom_2' class='one_third'><div class='column-content-wrapper'><div class="bottom-col-content posts-in-sidebar substitute_widget_class"><h3 class="bottom-col-title">Ocean Matters Blog Posts:</h3> <ul class="pis-ul"> <li class="pis-li"> <p class="pis-title"> <a class="pis-title-link" href="../../founding-director-laura-parker-roerden-keynotes-at-mote-marine-labs-tea-for-the-sea/index.html" title="Permalink to Founding Director Laura Parker Roerden Keynotes at Mote Marine Labs Tea for the Sea" rel="bookmark"> Founding Director Laura Parker Roerden Keynotes at Mote Marine Labs Tea for the Sea </a> </p> </li> <li class="pis-li"> <p class="pis-title"> <a class="pis-title-link" href="../../grownups-join-us-in-hawaii-for-a-very-special-trip-june-22-july-1-2015/index.html" title="Permalink to Join Peter Yarrow of Peter, Paul &amp; Mary and National Geographic Underwater Photographer Brian Skerry in Hawaii for a Very Special Trip, June 23-July 1, 2015" rel="bookmark"> Join Peter Yarrow of Peter, Paul &#038; Mary and National Geographic Underwater Photographer Brian Skerry in Hawaii for a Very Special Trip, June 23-July 1, 2015 </a> </p> </li> <li class="pis-li"> <p class="pis-title"> <a class="pis-title-link" href="../../participate-in-the-last-straw-challenge/index.html" title="Permalink to Participate in the Last Straw Challenge!" rel="bookmark"> Participate in the Last Straw Challenge! </a> </p> </li> <li class="pis-li"> <p class="pis-title"> <a class="pis-title-link" href="../../ocean-matters-launches-history-of-whaling-project/index.html" title="Permalink to Ocean Matters Launches History of Whaling Project" rel="bookmark"> Ocean Matters Launches History of Whaling Project </a> </p> </li> <li class="pis-li"> <p class="pis-title"> <a class="pis-title-link" href="../../the-journey/index.html" title="Permalink to The Journey" rel="bookmark"> The Journey </a> </p> </li> </ul> <!-- / ul#pis-ul --> <!-- Generated by Posts in Sidebar v1.28 --> </div></div></div><!-- end bottom_2 --><div id='bottom_3' class='one_third last_column'><div class='column-content-wrapper'><div class="bottom-col-content widget_calendar substitute_widget_class"><div id="calendar_wrap"><table id="wp-calendar"> <caption>April 2015</caption> <thead> <tr> <th scope="col" title="Monday">M</th> <th scope="col" title="Tuesday">T</th> <th scope="col" title="Wednesday">W</th> <th scope="col" title="Thursday">T</th> <th scope="col" title="Friday">F</th> <th scope="col" title="Saturday">S</th> <th scope="col" title="Sunday">S</th> </tr> </thead> <tfoot> <tr> <td colspan="3" id="prev"><a href="../../2015/03/index.html">&laquo; Mar</a></td> <td class="pad">&nbsp;</td> <td colspan="3" id="next" class="pad">&nbsp;</td> </tr> </tfoot> <tbody> <tr> <td colspan="2" class="pad">&nbsp;</td><td>1</td><td>2</td><td>3</td><td>4</td><td>5</td> </tr> <tr> <td>6</td><td>7</td><td>8</td><td>9</td><td>10</td><td>11</td><td>12</td> </tr> <tr> <td>13</td><td>14</td><td>15</td><td id="today">16</td><td>17</td><td>18</td><td>19</td> </tr> <tr> <td>20</td><td>21</td><td>22</td><td>23</td><td>24</td><td>25</td><td>26</td> </tr> <tr> <td>27</td><td>28</td><td>29</td><td>30</td> <td class="pad" colspan="3">&nbsp;</td> </tr> </tbody> </table></div></div></div></div><!-- end bottom_3 --> </div> <!-- end bottom-content-padding --> </div> <!-- end bottom --> </div> <!-- end bottom-bg --> <div class="clear"></div> <div id="footer-bg"> <div id="footer" class="container_24 footer-top"> <div id="footer_text" class="grid_21"> <p> Copyright © 2001-2012 Ocean Matters | Contact: Laura Parker Roerden, Executive Director | (617) 304-4402 | <a href="mailto:info@oceanmatters.org">info@oceanmatters.org</a> <p><p><a href="http://www.shearpresence.com">Website Design by Shear Presence</a></strong> </p> </div> <div class="back-to-top"> <a href="index.html#top">Back to Top</a> </div> </div> </div> <div class="clear"></div> <script type='text/javascript' src='../../wp-includes/js/comment-reply.min-ver=4.1.1.js'></script> <script type='text/javascript' src='../../wp-content/themes/u-design/scripts/prettyPhoto/custom_params-ver=3.1.3.js'></script> </div><!-- end wrapper-1 --> </body> </html>
oceanmatters/static-site
rain-rain-go-away/group1/index.html
HTML
mit
20,237
# -*- coding: utf-8 -*- # Copyright (c) 2017-2020 Richard Hull and contributors # See LICENSE.rst for details. """ Simplified sprite animation framework. .. note:: This module is an evolving "work-in-progress" and should be treated as such until such time as this notice disappears. """ from time import sleep, perf_counter from PIL import Image class dict_wrapper(object): """ Helper class to turn dictionaries into objects. """ def __init__(self, d): for a, b in d.items(): if isinstance(b, (list, tuple)): setattr(self, a, [dict_wrapper(x) if isinstance(x, dict) else x for x in b]) else: setattr(self, a, dict_wrapper(b) if isinstance(b, dict) else b) class spritesheet(object): """ A sprite sheet is a series of images (usually animation frames) combined into a larger image. A dictionary is usually spread into the object constructor parameters with the following top-level attributes: :param image: A path to a sprite map image. :type image: str :param frames: A dictionary of settings that defines how to extract individual frames from the supplied image, as follows - ``width`` & ``height`` are required and specify the dimensions of the frames - ``regX`` & ``regY`` indicate the registration point or "origin" of the frames - ``count`` allows you to specify the total number of frames in the spritesheet; if omitted, this will be calculated based on the dimensions of the source images and the frames. Frames will be assigned indexes based on their position in the source images (left to right, top to bottom). :type frames: dict :param animations: A dictionary of key/value pairs where the key is the name of of the animation sequence, and the value are settings that defines an animation sequence as follows: - ``frames`` is a list of frame to show in sequence. Usually this comprises of frame numbers, but can refer to other animation sequences (which are handled much like a subroutine call). - ``speed`` determines how quickly the animation frames are cycled through compared to the how often the animation sequence yields. - ``next`` is optional, but if supplied, determines what happens when the animation sequence is exhausted. Typically this can be used to self-reference, so that it forms an infinite loop, but can hand off to any other animation sequence. :type animations: dict Loosely based on https://www.createjs.com/docs/easeljs/classes/SpriteSheet.html """ def __init__(self, image, frames, animations): with open(image, 'rb') as fp: self.image = Image.open(fp) self.image.load() self.frames = dict_wrapper(frames) self.animations = dict_wrapper(animations) # Reframe the sprite map in terms of the registration point (if set) regX = self.frames.regX if hasattr(self.frames, "regX") else 0 regY = self.frames.regY if hasattr(self.frames, "regY") else 0 self.image = self.image.crop((regX, regY, self.image.width - regX, self.image.height - regY)) self.width, self.height = self.image.size assert(self.width % self.frames.width == 0) assert(self.height % self.frames.height == 0) self.frames.size = (self.frames.width, self.frames.height) if not hasattr(self.frames, 'count'): self.frames.count = (self.width * self.height) // (self.frames.width * self.frames.height) self.cache = {} def __getitem__(self, frame_index): """ Returns (and caches) the frame for the given index. :param frame_index: The index of the frame. :type frame_index: int :returns: A Pillow image cropped from the main image corresponding to the given frame index. :raises TypeError: if the ``frame_index`` is not numeric :raises IndexError: if the ``frame_index`` is less than zero or more than the largest frame. """ if not isinstance(frame_index, int): raise TypeError("frame index must be numeric") if frame_index < 0 or frame_index > self.frames.count: raise IndexError("frame index out of range") cached_frame = self.cache.get(frame_index) if cached_frame is None: offset = frame_index * self.frames.width left = offset % self.width top = (offset // self.width) * self.frames.height right = left + self.frames.width bottom = top + self.frames.height bounds = [left, top, right, bottom] cached_frame = self.image.crop(bounds) self.cache[frame_index] = cached_frame return cached_frame def __len__(self): """ The number of frames in the sprite sheet """ return self.frames.count def animate(self, seq_name): """ Returns a generator which "executes" an animation sequence for the given ``seq_name``, inasmuch as the next frame for the given animation is yielded when requested. :param seq_name: The name of a previously defined animation sequence. :type seq_name: str :returns: A generator that yields all frames from the animation sequence. :raises AttributeError: If the ``seq_name`` is unknown. """ while True: index = 0 anim = getattr(self.animations, seq_name) speed = anim.speed if hasattr(anim, "speed") else 1 num_frames = len(anim.frames) while index < num_frames: frame = anim.frames[int(index)] index += speed if isinstance(frame, int): yield self[frame] else: for subseq_frame in self.animate(frame): yield subseq_frame if not hasattr(anim, "next"): break seq_name = anim.next class framerate_regulator(object): """ Implements a variable sleep mechanism to give the appearance of a consistent frame rate. Using a fixed-time sleep will cause animations to be jittery (looking like they are speeding up or slowing down, depending on what other work is occurring), whereas this class keeps track of when the last time the ``sleep()`` method was called, and calculates a sleep period to smooth out the jitter. :param fps: The desired frame rate, expressed numerically in frames-per-second. By default, this is set at 16.67, to give a frame render time of approximately 60ms. This can be overridden as necessary, and if no FPS limiting is required, the ``fps`` can be set to zero. :type fps: float """ def __init__(self, fps=16.67): if fps == 0: fps = -1 self.max_sleep_time = 1.0 / fps self.total_transit_time = 0 self.called = 0 self.start_time = None self.last_time = None def __enter__(self): self.enter_time = perf_counter() if not self.start_time: self.start_time = self.enter_time self.last_time = self.enter_time return self def __exit__(self, *args): """ Sleeps for a variable amount of time (dependent on when it was last called), to give a consistent frame rate. If it cannot meet the desired frame rate (i.e. too much time has occurred since the last call), then it simply exits without blocking. """ self.called += 1 self.total_transit_time += perf_counter() - self.enter_time if self.max_sleep_time >= 0: elapsed = perf_counter() - self.last_time sleep_for = self.max_sleep_time - elapsed if sleep_for > 0: sleep(sleep_for) self.last_time = perf_counter() def effective_FPS(self): """ Calculates the effective frames-per-second - this should largely correlate to the desired FPS supplied in the constructor, but no guarantees are given. :returns: The effective frame rate. :rtype: float """ if self.start_time is None: self.start_time = 0 elapsed = perf_counter() - self.start_time return self.called / elapsed def average_transit_time(self): """ Calculates the average transit time between the enter and exit methods, and return the time in milliseconds. :returns: The average transit in milliseconds. :rtype: float """ return self.total_transit_time * 1000.0 / self.called
rm-hull/luma.core
luma/core/sprite_system.py
Python
mit
8,896
'use strict' const { test } = require('tap') const Fastify = require('..') const { codes: { FST_ERR_DEC_ALREADY_PRESENT, FST_ERR_MISSING_MIDDLEWARE } } = require('../lib/errors') test('Should throw if the basic use API has not been overridden', t => { t.plan(1) const fastify = Fastify() try { fastify.use() t.fail('Should throw') } catch (err) { t.ok(err instanceof FST_ERR_MISSING_MIDDLEWARE) } }) test('Should be able to override the default use API', t => { t.plan(1) const fastify = Fastify() fastify.decorate('use', () => true) t.strictEqual(fastify.use(), true) }) test('Cannot decorate use twice', t => { t.plan(1) const fastify = Fastify() fastify.decorate('use', () => true) try { fastify.decorate('use', () => true) } catch (err) { t.ok(err instanceof FST_ERR_DEC_ALREADY_PRESENT) } }) test('Encapsulation works', t => { t.plan(2) const fastify = Fastify() fastify.register((instance, opts, next) => { instance.decorate('use', () => true) t.strictEqual(instance.use(), true) next() }) fastify.register((instance, opts, next) => { try { instance.use() t.fail('Should throw') } catch (err) { t.ok(err instanceof FST_ERR_MISSING_MIDDLEWARE) } next() }) fastify.ready() })
mcollina/fastify
test/middleware.test.js
JavaScript
mit
1,311
// Description: Async extension methods for LINQ (Language Integrated Query). // Website & Documentation: https://github.com/zzzprojects/LINQ-Async // Forum: https://github.com/zzzprojects/LINQ-Async/issues // License: http://www.zzzprojects.com/license-agreement/ // More projects: http://www.zzzprojects.com/ // Copyright (c) 2015 ZZZ Projects. All rights reserved. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; namespace Z.Linq { public class AsyncOrderedEnumerable<T> : IOrderedEnumerable<T> { public AsyncOrderedEnumerable(IOrderedEnumerable<T> source, CancellationToken cancellationToken) { CancellationToken = cancellationToken; Source = source; } public CancellationToken CancellationToken { get; set; } public IOrderedEnumerable<T> Source { get; set; } public IEnumerator<T> GetEnumerator() { return new AsyncEnumerator<T>(Source.GetEnumerator(), CancellationToken); } IEnumerator IEnumerable.GetEnumerator() { return new AsyncEnumerator<T>(Source.GetEnumerator(), CancellationToken); } public IOrderedEnumerable<T> CreateOrderedEnumerable<TKey>(Func<T, TKey> keySelector, IComparer<TKey> comparer, bool descending) { return Source.CreateOrderedEnumerable(keySelector, comparer, descending); } public static AsyncOrderedEnumerable<T> CreateFrom(IOrderedEnumerable<T> source, CancellationToken cancellationToken) { return new AsyncOrderedEnumerable<T>(source, cancellationToken); } } }
zzzprojects/LINQ-Async
src/Z.Linq.Async.Shared/EnumerableAsync/AsyncOrderedEnumerable`.cs
C#
mit
1,695
import React from "react"; import { storiesOf } from "@storybook/react"; import { withKnobs, boolean } from "@storybook/addon-knobs"; import centered from "@storybook/addon-centered/react"; import DarkModeKnobWrapper from "./DarkModeKnobWrapper"; import Heart from "../components/dots/Heart"; import Pride from "../components/dots/Pride"; import Triangle from "../components/dots/Triangle"; import Vroom from "../components/dots/Vroom"; import Pulse from "../components/dots/Pulse"; storiesOf("Dots", module) .addDecorator(withKnobs) .addDecorator(centered) .add("Heart", () => { const on = boolean("On", false); return ( <div> <Heart on={on} /> <Heart on={!on} /> </div> ); }) .add("Pride", () => ( <DarkModeKnobWrapper> <Pride on={boolean("On", false)} /> </DarkModeKnobWrapper> )) .add("Triangle", () => <Triangle on={boolean("On", false)} />) .add("Vroom", () => <Vroom on={boolean("On", false)} />) .add("Pulse", () => <Pulse on={boolean("On", false)} />);
Mathspy/binary-clock
src/stories/dots.stories.js
JavaScript
mit
1,037
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations def populate_target_amount(apps, schema_editor): Entry = apps.get_model("momentum", "Entry") for entry in Entry.objects.all(): entry.target_amount = entry.goal.target_amount entry.save() class Migration(migrations.Migration): dependencies = [ ('momentum', '0009_entry_target_amount'), ] operations = [ migrations.RunPython(populate_target_amount), ]
mod2/momentum
momentum/migrations/0010_target_data_migration.py
Python
mit
517
# FileMessage - simple class to write a message class FileMessage attr_reader :message_name def initialize(message_name) @message_name = message_name end def write_message(queue_location, message) File.open(queue_location + '/' + @message_name, 'w') do |file| file.puts message end end end
m1ckr1sk/FileMQ
lib/file_message.rb
Ruby
mit
319
io.stdout:setvbuf("no") --For console output Loader = require("Loader") --====CONFIG START====-- --Note: Make sure that your images are pngs. _Path = "/ExampleObjects/" _SheetName = "ExampleObjects.json" _ObjectsNames = {"AlienBeige","AlienBlue","AlienPink","DebrisGlass","DebrisStone","DebrisWood","Explosive"} --Fill in your objects names --====CONFIG END====-- --============Controls===========-- --Left Mouse: Add Object (Random)-- --=====WASD: Change Gravity======-- --===Q: Toggle Objects Debug=====-- --===============================-- --Note: You can only add objects if debug is off-- _ObjectsImages = {} _Objects = {} function love.load(args) _Background = love.graphics.newImage("Background.png") _Width, _Height = love.graphics.getWidth(), love.graphics.getHeight() love.physics.setMeter(64) _World = love.physics.newWorld(0, 9.81*64, false) BuildWorld(_World) for k, name in pairs(_ObjectsNames) do _ObjectsImages[name] = love.graphics.newImage(_Path..name..".png") --Loading the Images end end function love.update(dt) _World:update(dt) love.window.setTitle("PhysicsEditor Demo [FPS = "..love.timer.getFPS().." ]") local gx, gy, gs = 0, 9.81*64, 500 if love.keyboard.isDown("d") then _World:setGravity( gx+gs, gy ) end if love.keyboard.isDown("a") then _World:setGravity( gx-gs, gy ) end if love.keyboard.isDown("w") then _World:setGravity( gx, gy-gs*2 ) end if love.keyboard.isDown("s") then _World:setGravity( gx, gy ) end end function love.draw() love.graphics.setColor(255,255,255,255) love.graphics.draw(_Background,0,0,0,_Width/_Background:getWidth(),_Height/_Background:getHeight()) for k,obj in ipairs(_Objects) do obj:draw() end if _Debug then DebugWorld(_World) end end function love.mousepressed(x, y, button) if not _Debug then CreateRandObject(x,y) end end function love.keypressed(key,isrepeat) if key == "q" then _Debug = not _Debug end end function RandSeed() math.randomseed(math.random(1000,9999)*love.timer.getTime()) end function RandObject() RandSeed() return math.random(1,#_ObjectsNames) end function CreateRandObject(x,y) local objName = _ObjectsNames[RandObject()] print(objName) local obj = Loader.loadPath(_ObjectsImages[objName],_World,objName,_Path.._SheetName,x,y) table.insert(_Objects,obj) end function BuildWorld(world) local newEdge = function(World,xS,yS,xE,yE,type) xE, yE = xE - xS, yE - yS local object = {} object.body = love.physics.newBody( World, xS, yS, type ) object.body:setMass(5) object.shape = love.physics.newEdgeShape( 0, 0, xE, yE ) object.fixture = love.physics.newFixture( object.body, object.shape, 1 ) object.fixture:setRestitution(0) object.fixture:setFriction(.5) return object end newEdge(world,0,0,_Width,0) newEdge(world,_Width,0,_Width,_Height) newEdge(world,_Width,_Height,0,_Height) newEdge(world,0,_Height,0,0) end function DebugWorld(world) local bodies = world:getBodyList() for b=#bodies,1,-1 do local body = bodies[b] local bx,by = body:getPosition() local bodyAngle = body:getAngle() love.graphics.push() love.graphics.translate(bx,by) love.graphics.rotate(bodyAngle) math.randomseed(1) --for color generation local fixtures = body:getFixtureList() for i=1,#fixtures do local fixture = fixtures[i] local shape = fixture:getShape() local shapeType = shape:getType() local isSensor = fixture:isSensor() if (isSensor) then love.graphics.setColor(0,0,255,96) else love.graphics.setColor(math.random(32,200),math.random(32,200),math.random(32,200),96) end love.graphics.setLineWidth(1) if (shapeType == "circle") then local x,y = fixture:getMassData() --0.9.0 missing circleshape:getPoint() --local x,y = shape:getPoint() --0.9.1 local radius = shape:getRadius() love.graphics.circle("fill",x,y,radius,15) love.graphics.setColor(0,0,0,255) love.graphics.circle("line",x,y,radius,15) local eyeRadius = radius/4 love.graphics.setColor(0,0,0,255) love.graphics.circle("fill",x+radius-eyeRadius,y,eyeRadius,10) elseif (shapeType == "polygon") then local points = {shape:getPoints()} love.graphics.polygon("fill",points) love.graphics.setColor(0,0,0,255) love.graphics.polygon("line",points) elseif (shapeType == "edge") then love.graphics.setColor(0,0,0,255) love.graphics.line(shape:getPoints()) elseif (shapeType == "chain") then love.graphics.setColor(0,0,0,255) love.graphics.line(shape:getPoints()) end end love.graphics.pop() end local joints = world:getJointList() for index,joint in pairs(joints) do love.graphics.setColor(0,255,0,255) local x1,y1,x2,y2 = joint:getAnchors() if (x1 and x2) then love.graphics.setLineWidth(3) love.graphics.line(x1,y1,x2,y2) else love.graphics.setPointSize(3) if (x1) then love.graphics.point(x1,y1) end if (x2) then love.graphics.point(x2,y2) end end end local contacts = world:getContactList() for i=1,#contacts do love.graphics.setColor(255,0,0,255) love.graphics.setPointSize(3) local x1,y1,x2,y2 = contacts[i]:getPositions() if (x1) then love.graphics.point(x1,y1) end if (x2) then love.graphics.point(x2,y2) end end love.graphics.setColor(255,255,255,255) end
RamiLego4Game/Love2D-PhysicsEditor-Library
main.lua
Lua
mit
5,845
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> Partial Class frmpricechange #Region "Windows Form Designer generated code " <System.Diagnostics.DebuggerNonUserCode()> Public Sub New() MyBase.New() 'This call is required by the Windows Form Designer. InitializeComponent() End Sub 'Form overrides dispose to clean up the component list. <System.Diagnostics.DebuggerNonUserCode()> Protected Overloads Overrides Sub Dispose(ByVal Disposing As Boolean) If Disposing Then If Not components Is Nothing Then components.Dispose() End If End If MyBase.Dispose(Disposing) End Sub 'Required by the Windows Form Designer Private components As System.ComponentModel.IContainer Public ToolTip1 As System.Windows.Forms.ToolTip Public WithEvents cmdcancel As System.Windows.Forms.Button Public WithEvents cmdshow As System.Windows.Forms.Button Public WithEvents cmdenddate As System.Windows.Forms.Button Public WithEvents txtenddate As System.Windows.Forms.TextBox Public WithEvents txtstartdate As System.Windows.Forms.TextBox Public WithEvents cmdstart As System.Windows.Forms.Button Public WithEvents lblInstruction As System.Windows.Forms.Label Public WithEvents Label2 As System.Windows.Forms.Label Public WithEvents Label1 As System.Windows.Forms.Label 'NOTE: The following procedure is required by the Windows Form Designer 'It can be modified using the Windows Form Designer. 'Do not modify it using the code editor. <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent() Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(frmpricechange)) Me.components = New System.ComponentModel.Container() Me.ToolTip1 = New System.Windows.Forms.ToolTip(components) Me.cmdcancel = New System.Windows.Forms.Button Me.cmdshow = New System.Windows.Forms.Button Me.cmdenddate = New System.Windows.Forms.Button Me.txtenddate = New System.Windows.Forms.TextBox Me.txtstartdate = New System.Windows.Forms.TextBox Me.cmdstart = New System.Windows.Forms.Button Me.lblInstruction = New System.Windows.Forms.Label Me.Label2 = New System.Windows.Forms.Label Me.Label1 = New System.Windows.Forms.Label Me.SuspendLayout() Me.ToolTip1.Active = True Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle Me.Text = "Price Changes" Me.ClientSize = New System.Drawing.Size(442, 155) Me.Location = New System.Drawing.Point(3, 29) Me.Icon = CType(resources.GetObject("frmpricechange.Icon"), System.Drawing.Icon) Me.KeyPreview = True Me.MaximizeBox = False Me.MinimizeBox = False Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font Me.BackColor = System.Drawing.SystemColors.Control Me.ControlBox = True Me.Enabled = True Me.Cursor = System.Windows.Forms.Cursors.Default Me.RightToLeft = System.Windows.Forms.RightToLeft.No Me.ShowInTaskbar = True Me.HelpButton = False Me.WindowState = System.Windows.Forms.FormWindowState.Normal Me.Name = "frmpricechange" Me.cmdcancel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter Me.cmdcancel.Text = "&Cancel" Me.cmdcancel.Size = New System.Drawing.Size(81, 33) Me.cmdcancel.Location = New System.Drawing.Point(352, 112) Me.cmdcancel.TabIndex = 7 Me.cmdcancel.BackColor = System.Drawing.SystemColors.Control Me.cmdcancel.CausesValidation = True Me.cmdcancel.Enabled = True Me.cmdcancel.ForeColor = System.Drawing.SystemColors.ControlText Me.cmdcancel.Cursor = System.Windows.Forms.Cursors.Default Me.cmdcancel.RightToLeft = System.Windows.Forms.RightToLeft.No Me.cmdcancel.TabStop = True Me.cmdcancel.Name = "cmdcancel" Me.cmdshow.TextAlign = System.Drawing.ContentAlignment.MiddleCenter Me.cmdshow.Text = "&Show" Me.cmdshow.Size = New System.Drawing.Size(81, 33) Me.cmdshow.Location = New System.Drawing.Point(248, 112) Me.cmdshow.TabIndex = 6 Me.cmdshow.BackColor = System.Drawing.SystemColors.Control Me.cmdshow.CausesValidation = True Me.cmdshow.Enabled = True Me.cmdshow.ForeColor = System.Drawing.SystemColors.ControlText Me.cmdshow.Cursor = System.Windows.Forms.Cursors.Default Me.cmdshow.RightToLeft = System.Windows.Forms.RightToLeft.No Me.cmdshow.TabStop = True Me.cmdshow.Name = "cmdshow" Me.cmdenddate.TextAlign = System.Drawing.ContentAlignment.MiddleCenter Me.cmdenddate.Text = "..." Me.cmdenddate.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Bold Or System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.cmdenddate.Size = New System.Drawing.Size(33, 33) Me.cmdenddate.Location = New System.Drawing.Point(400, 64) Me.cmdenddate.TabIndex = 5 Me.cmdenddate.BackColor = System.Drawing.SystemColors.Control Me.cmdenddate.CausesValidation = True Me.cmdenddate.Enabled = True Me.cmdenddate.ForeColor = System.Drawing.SystemColors.ControlText Me.cmdenddate.Cursor = System.Windows.Forms.Cursors.Default Me.cmdenddate.RightToLeft = System.Windows.Forms.RightToLeft.No Me.cmdenddate.TabStop = True Me.cmdenddate.Name = "cmdenddate" Me.txtenddate.AutoSize = False Me.txtenddate.Size = New System.Drawing.Size(81, 33) Me.txtenddate.Location = New System.Drawing.Point(320, 64) Me.txtenddate.TabIndex = 4 Me.txtenddate.AcceptsReturn = True Me.txtenddate.TextAlign = System.Windows.Forms.HorizontalAlignment.Left Me.txtenddate.BackColor = System.Drawing.SystemColors.Window Me.txtenddate.CausesValidation = True Me.txtenddate.Enabled = True Me.txtenddate.ForeColor = System.Drawing.SystemColors.WindowText Me.txtenddate.HideSelection = True Me.txtenddate.ReadOnly = False Me.txtenddate.Maxlength = 0 Me.txtenddate.Cursor = System.Windows.Forms.Cursors.IBeam Me.txtenddate.MultiLine = False Me.txtenddate.RightToLeft = System.Windows.Forms.RightToLeft.No Me.txtenddate.ScrollBars = System.Windows.Forms.ScrollBars.None Me.txtenddate.TabStop = True Me.txtenddate.Visible = True Me.txtenddate.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D Me.txtenddate.Name = "txtenddate" Me.txtstartdate.AutoSize = False Me.txtstartdate.Size = New System.Drawing.Size(81, 33) Me.txtstartdate.Location = New System.Drawing.Point(112, 64) Me.txtstartdate.TabIndex = 2 Me.txtstartdate.AcceptsReturn = True Me.txtstartdate.TextAlign = System.Windows.Forms.HorizontalAlignment.Left Me.txtstartdate.BackColor = System.Drawing.SystemColors.Window Me.txtstartdate.CausesValidation = True Me.txtstartdate.Enabled = True Me.txtstartdate.ForeColor = System.Drawing.SystemColors.WindowText Me.txtstartdate.HideSelection = True Me.txtstartdate.ReadOnly = False Me.txtstartdate.Maxlength = 0 Me.txtstartdate.Cursor = System.Windows.Forms.Cursors.IBeam Me.txtstartdate.MultiLine = False Me.txtstartdate.RightToLeft = System.Windows.Forms.RightToLeft.No Me.txtstartdate.ScrollBars = System.Windows.Forms.ScrollBars.None Me.txtstartdate.TabStop = True Me.txtstartdate.Visible = True Me.txtstartdate.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D Me.txtstartdate.Name = "txtstartdate" Me.cmdstart.TextAlign = System.Drawing.ContentAlignment.MiddleCenter Me.cmdstart.Text = "..." Me.cmdstart.Font = New System.Drawing.Font("Verdana", 8.25!, System.Drawing.FontStyle.Bold Or System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte)) Me.cmdstart.Size = New System.Drawing.Size(33, 33) Me.cmdstart.Location = New System.Drawing.Point(192, 64) Me.cmdstart.TabIndex = 1 Me.cmdstart.BackColor = System.Drawing.SystemColors.Control Me.cmdstart.CausesValidation = True Me.cmdstart.Enabled = True Me.cmdstart.ForeColor = System.Drawing.SystemColors.ControlText Me.cmdstart.Cursor = System.Windows.Forms.Cursors.Default Me.cmdstart.RightToLeft = System.Windows.Forms.RightToLeft.No Me.cmdstart.TabStop = True Me.cmdstart.Name = "cmdstart" Me.lblInstruction.Text = "This Process will print you the Price Changes of the Date range you selected.Please Select the 'Start Date' and the 'End Date' and Click the Show button.Please Note the Start Date must be earlier than the 'End Date'" Me.lblInstruction.Size = New System.Drawing.Size(424, 45) Me.lblInstruction.Location = New System.Drawing.Point(8, 8) Me.lblInstruction.TabIndex = 8 Me.lblInstruction.TextAlign = System.Drawing.ContentAlignment.TopLeft Me.lblInstruction.BackColor = System.Drawing.SystemColors.Control Me.lblInstruction.Enabled = True Me.lblInstruction.ForeColor = System.Drawing.SystemColors.ControlText Me.lblInstruction.Cursor = System.Windows.Forms.Cursors.Default Me.lblInstruction.RightToLeft = System.Windows.Forms.RightToLeft.No Me.lblInstruction.UseMnemonic = True Me.lblInstruction.Visible = True Me.lblInstruction.AutoSize = False Me.lblInstruction.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D Me.lblInstruction.Name = "lblInstruction" Me.Label2.Text = "End Date:" Me.Label2.Size = New System.Drawing.Size(81, 33) Me.Label2.Location = New System.Drawing.Point(232, 72) Me.Label2.TabIndex = 3 Me.Label2.TextAlign = System.Drawing.ContentAlignment.TopLeft Me.Label2.BackColor = System.Drawing.SystemColors.Control Me.Label2.Enabled = True Me.Label2.ForeColor = System.Drawing.SystemColors.ControlText Me.Label2.Cursor = System.Windows.Forms.Cursors.Default Me.Label2.RightToLeft = System.Windows.Forms.RightToLeft.No Me.Label2.UseMnemonic = True Me.Label2.Visible = True Me.Label2.AutoSize = False Me.Label2.BorderStyle = System.Windows.Forms.BorderStyle.None Me.Label2.Name = "Label2" Me.Label1.Text = " Start Date:" Me.Label1.Size = New System.Drawing.Size(97, 25) Me.Label1.Location = New System.Drawing.Point(8, 72) Me.Label1.TabIndex = 0 Me.Label1.TextAlign = System.Drawing.ContentAlignment.TopLeft Me.Label1.BackColor = System.Drawing.SystemColors.Control Me.Label1.Enabled = True Me.Label1.ForeColor = System.Drawing.SystemColors.ControlText Me.Label1.Cursor = System.Windows.Forms.Cursors.Default Me.Label1.RightToLeft = System.Windows.Forms.RightToLeft.No Me.Label1.UseMnemonic = True Me.Label1.Visible = True Me.Label1.AutoSize = False Me.Label1.BorderStyle = System.Windows.Forms.BorderStyle.None Me.Label1.Name = "Label1" Me.Controls.Add(cmdcancel) Me.Controls.Add(cmdshow) Me.Controls.Add(cmdenddate) Me.Controls.Add(txtenddate) Me.Controls.Add(txtstartdate) Me.Controls.Add(cmdstart) Me.Controls.Add(lblInstruction) Me.Controls.Add(Label2) Me.Controls.Add(Label1) Me.ResumeLayout(False) Me.PerformLayout() End Sub #End Region End Class
nodoid/PointOfSale
VB/4PosBackOffice.NET/frmpricechange.Designer.vb
Visual Basic
mit
10,918
// Copyright (c) 2018-2019 The Bitcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <script/sigencoding.h> #include <script/script_flags.h> #include <test/lcg.h> #include <test/test_bitcoin.h> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(sigencoding_tests, BasicTestingSetup) static valtype SignatureWithHashType(valtype vchSig, SigHashType sigHash) { vchSig.push_back(static_cast<uint8_t>(sigHash.getRawSigHashType())); return vchSig; } static void CheckSignatureEncodingWithSigHashType(const valtype &vchSig, uint32_t flags) { ScriptError err = ScriptError::OK; BOOST_CHECK(CheckDataSignatureEncoding(vchSig, flags, &err)); const bool hasForkId = (flags & SCRIPT_ENABLE_SIGHASH_FORKID) != 0; const bool hasStrictEnc = (flags & SCRIPT_VERIFY_STRICTENC) != 0; const bool is64 = (vchSig.size() == 64); std::vector<BaseSigHashType> allBaseTypes{ BaseSigHashType::ALL, BaseSigHashType::NONE, BaseSigHashType::SINGLE}; std::vector<SigHashType> baseSigHashes; for (const BaseSigHashType &baseType : allBaseTypes) { const SigHashType baseSigHash = SigHashType().withBaseType(baseType); baseSigHashes.push_back(baseSigHash); baseSigHashes.push_back(baseSigHash.withAnyoneCanPay(true)); } for (const SigHashType &baseSigHash : baseSigHashes) { // Check the signature with the proper forkid flag. SigHashType sigHash = baseSigHash.withForkId(hasForkId); valtype validSig = SignatureWithHashType(vchSig, sigHash); BOOST_CHECK(CheckTransactionSignatureEncoding(validSig, flags, &err)); BOOST_CHECK_EQUAL(!is64, CheckTransactionECDSASignatureEncoding( validSig, flags, &err)); BOOST_CHECK_EQUAL(is64, CheckTransactionSchnorrSignatureEncoding( validSig, flags, &err)); // If we have strict encoding, we prevent the use of undefined flags. std::array<SigHashType, 2> undefSigHashes{ {SigHashType(sigHash.getRawSigHashType() | 0x20), sigHash.withBaseType(BaseSigHashType::UNSUPPORTED)}}; for (SigHashType undefSigHash : undefSigHashes) { valtype undefSighash = SignatureWithHashType(vchSig, undefSigHash); BOOST_CHECK_EQUAL( CheckTransactionSignatureEncoding(undefSighash, flags, &err), !hasStrictEnc); if (hasStrictEnc) { BOOST_CHECK(err == ScriptError::SIG_HASHTYPE); } BOOST_CHECK_EQUAL(CheckTransactionECDSASignatureEncoding( undefSighash, flags, &err), !(hasStrictEnc || is64)); if (is64 || hasStrictEnc) { BOOST_CHECK(err == (is64 ? ScriptError::SIG_BADLENGTH : ScriptError::SIG_HASHTYPE)); } BOOST_CHECK_EQUAL(CheckTransactionSchnorrSignatureEncoding( undefSighash, flags, &err), !(hasStrictEnc || !is64)); if (!is64 || hasStrictEnc) { BOOST_CHECK(err == (!is64 ? ScriptError::SIG_NONSCHNORR : ScriptError::SIG_HASHTYPE)); } } // If we check strict encoding, then invalid forkid is an error. SigHashType invalidSigHash = baseSigHash.withForkId(!hasForkId); valtype invalidSig = SignatureWithHashType(vchSig, invalidSigHash); BOOST_CHECK_EQUAL( CheckTransactionSignatureEncoding(invalidSig, flags, &err), !hasStrictEnc); if (hasStrictEnc) { BOOST_CHECK(err == (hasForkId ? ScriptError::MUST_USE_FORKID : ScriptError::ILLEGAL_FORKID)); } BOOST_CHECK_EQUAL( CheckTransactionECDSASignatureEncoding(invalidSig, flags, &err), !(hasStrictEnc || is64)); if (is64 || hasStrictEnc) { BOOST_CHECK(err == (is64 ? ScriptError::SIG_BADLENGTH : hasForkId ? ScriptError::MUST_USE_FORKID : ScriptError::ILLEGAL_FORKID)); } BOOST_CHECK_EQUAL( CheckTransactionSchnorrSignatureEncoding(invalidSig, flags, &err), !(hasStrictEnc || !is64)); if (!is64 || hasStrictEnc) { BOOST_CHECK(err == (!is64 ? ScriptError::SIG_NONSCHNORR : hasForkId ? ScriptError::MUST_USE_FORKID : ScriptError::ILLEGAL_FORKID)); } } } BOOST_AUTO_TEST_CASE(checksignatureencoding_test) { valtype minimalSig{0x30, 0x06, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01}; valtype highSSig{ 0x30, 0x45, 0x02, 0x20, 0x3e, 0x45, 0x16, 0xda, 0x72, 0x53, 0xcf, 0x06, 0x8e, 0xff, 0xec, 0x6b, 0x95, 0xc4, 0x12, 0x21, 0xc0, 0xcf, 0x3a, 0x8e, 0x6c, 0xcb, 0x8c, 0xbf, 0x17, 0x25, 0xb5, 0x62, 0xe9, 0xaf, 0xde, 0x2c, 0x02, 0x21, 0x00, 0xab, 0x1e, 0x3d, 0xa7, 0x3d, 0x67, 0xe3, 0x20, 0x45, 0xa2, 0x0e, 0x0b, 0x99, 0x9e, 0x04, 0x99, 0x78, 0xea, 0x8d, 0x6e, 0xe5, 0x48, 0x0d, 0x48, 0x5f, 0xcf, 0x2c, 0xe0, 0xd0, 0x3b, 0x2e, 0xf0}; std::vector<valtype> nonDERSigs{ // Non canonical total length. {0x30, 0x80, 0x06, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01}, // Zero length R. {0x30, 0x2f, 0x02, 0x00, 0x02, 0x21, 0x00, 0xab, 0x1e, 0x3d, 0xa7, 0x3d, 0x67, 0xe3, 0x20, 0x45, 0xa2, 0x0e, 0x0b, 0x99, 0x9e, 0x04, 0x99, 0x78, 0xea, 0x8d, 0x6e, 0xe5, 0x48, 0x0d, 0x48, 0x5f, 0xcf, 0x2c, 0xe0, 0xd0, 0x3b, 0x2e, 0xf0}, // Non canonical length for R. {0x30, 0x31, 0x02, 0x80, 0x01, 0x6c, 0x02, 0x21, 0x00, 0xab, 0x1e, 0x3d, 0xa7, 0x3d, 0x67, 0xe3, 0x20, 0x45, 0xa2, 0x0e, 0x0b, 0x99, 0x9e, 0x04, 0x99, 0x78, 0xea, 0x8d, 0x6e, 0xe5, 0x48, 0x0d, 0x48, 0x5f, 0xcf, 0x2c, 0xe0, 0xd0, 0x3b, 0x2e, 0xf0}, // Negative R. {0x30, 0x30, 0x02, 0x01, 0x80, 0x02, 0x21, 0x00, 0xab, 0x1e, 0x3d, 0xa7, 0x3d, 0x67, 0xe3, 0x20, 0x45, 0xa2, 0x0e, 0x0b, 0x99, 0x9e, 0x04, 0x99, 0x78, 0xea, 0x8d, 0x6e, 0xe5, 0x48, 0x0d, 0x48, 0x5f, 0xcf, 0x2c, 0xe0, 0xd0, 0x3b, 0x2e, 0xf0}, // Null prefixed R. {0x30, 0x31, 0x02, 0x02, 0x00, 0x01, 0x02, 0x21, 0x00, 0xab, 0x1e, 0x3d, 0xa7, 0x3d, 0x67, 0xe3, 0x20, 0x45, 0xa2, 0x0e, 0x0b, 0x99, 0x9e, 0x04, 0x99, 0x78, 0xea, 0x8d, 0x6e, 0xe5, 0x48, 0x0d, 0x48, 0x5f, 0xcf, 0x2c, 0xe0, 0xd0, 0x3b, 0x2e, 0xf0}, // Zero length S. {0x30, 0x2f, 0x02, 0x21, 0x00, 0xab, 0x1e, 0x3d, 0xa7, 0x3d, 0x67, 0xe3, 0x20, 0x45, 0xa2, 0x0e, 0x0b, 0x99, 0x9e, 0x04, 0x99, 0x78, 0xea, 0x8d, 0x6e, 0xe5, 0x48, 0x0d, 0x48, 0x5f, 0xcf, 0x2c, 0xe0, 0xd0, 0x3b, 0x2e, 0xf0, 0x02, 0x00}, // Non canonical length for S. {0x30, 0x31, 0x02, 0x21, 0x00, 0xab, 0x1e, 0x3d, 0xa7, 0x3d, 0x67, 0xe3, 0x20, 0x45, 0xa2, 0x0e, 0x0b, 0x99, 0x9e, 0x04, 0x99, 0x78, 0xea, 0x8d, 0x6e, 0xe5, 0x48, 0x0d, 0x48, 0x5f, 0xcf, 0x2c, 0xe0, 0xd0, 0x3b, 0x2e, 0xf0, 0x02, 0x80, 0x01, 0x6c}, // Negative S. {0x30, 0x30, 0x02, 0x21, 0x00, 0xab, 0x1e, 0x3d, 0xa7, 0x3d, 0x67, 0xe3, 0x20, 0x45, 0xa2, 0x0e, 0x0b, 0x99, 0x9e, 0x04, 0x99, 0x78, 0xea, 0x8d, 0x6e, 0xe5, 0x48, 0x0d, 0x48, 0x5f, 0xcf, 0x2c, 0xe0, 0xd0, 0x3b, 0x2e, 0xf0, 0x02, 0x01, 0x80}, // Null prefixed S. {0x30, 0x31, 0x02, 0x21, 0x00, 0xab, 0x1e, 0x3d, 0xa7, 0x3d, 0x67, 0xe3, 0x20, 0x45, 0xa2, 0x0e, 0x0b, 0x99, 0x9e, 0x04, 0x99, 0x78, 0xea, 0x8d, 0x6e, 0xe5, 0x48, 0x0d, 0x48, 0x5f, 0xcf, 0x2c, 0xe0, 0xd0, 0x3b, 0x2e, 0xf0, 0x02, 0x02, 0x00, 0x01}, }; std::vector<valtype> nonParsableSigs{ // Too short. {0x30}, {0x30, 0x06}, {0x30, 0x06, 0x02}, {0x30, 0x06, 0x02, 0x01}, {0x30, 0x06, 0x02, 0x01, 0x01}, {0x30, 0x06, 0x02, 0x01, 0x01, 0x02}, {0x30, 0x06, 0x02, 0x01, 0x01, 0x02, 0x01}, // Invalid type (must be 0x30, coumpound). {0x42, 0x06, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01}, // Invalid sizes. {0x30, 0x05, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01}, {0x30, 0x07, 0x02, 0x01, 0x01, 0x02, 0x01, 0x01}, // Invalid R and S sizes. {0x30, 0x06, 0x02, 0x00, 0x01, 0x02, 0x01, 0x01}, {0x30, 0x06, 0x02, 0x02, 0x01, 0x02, 0x01, 0x01}, {0x30, 0x06, 0x02, 0x01, 0x01, 0x02, 0x00, 0x01}, {0x30, 0x06, 0x02, 0x01, 0x01, 0x02, 0x02, 0x01}, // Invalid R and S types. {0x30, 0x06, 0x42, 0x01, 0x01, 0x02, 0x01, 0x01}, {0x30, 0x06, 0x02, 0x01, 0x01, 0x42, 0x01, 0x01}, // S out of bounds. {0x30, 0x06, 0x02, 0x01, 0x01, 0x02, 0x02, 0x00}, // Too long. {0x30, 0x47, 0x02, 0x21, 0x00, 0x8e, 0x45, 0x16, 0xda, 0x72, 0x53, 0xcf, 0x06, 0x8e, 0xff, 0xec, 0x6b, 0x95, 0xc4, 0x12, 0x21, 0xc0, 0xcf, 0x3a, 0x8e, 0x6c, 0xcb, 0x8c, 0xbf, 0x17, 0x25, 0xb5, 0x62, 0xe9, 0xaf, 0xde, 0x2c, 0x02, 0x22, 0x00, 0xab, 0x1e, 0x3d, 0x00, 0xa7, 0x3d, 0x67, 0xe3, 0x20, 0x45, 0xa2, 0x0e, 0x0b, 0x99, 0x9e, 0x04, 0x99, 0x78, 0xea, 0x8d, 0x6e, 0xe5, 0x48, 0x0d, 0x48, 0x5f, 0xcf, 0x2c, 0xe0, 0xd0, 0x3b, 0x2e, 0xf0}, }; valtype Zero64(64, 0); MMIXLinearCongruentialGenerator lcg; for (int i = 0; i < 4096; i++) { uint32_t flags = lcg.next(); ScriptError err = ScriptError::OK; // Empty sig is always validly encoded. BOOST_CHECK(CheckDataSignatureEncoding({}, flags, &err)); BOOST_CHECK(CheckTransactionSignatureEncoding({}, flags, &err)); BOOST_CHECK(CheckTransactionECDSASignatureEncoding({}, flags, &err)); BOOST_CHECK(CheckTransactionSchnorrSignatureEncoding({}, flags, &err)); // 64-byte signatures are valid as long as the hashtype is correct. CheckSignatureEncodingWithSigHashType(Zero64, flags); // Signatures are valid as long as the hashtype is correct. CheckSignatureEncodingWithSigHashType(minimalSig, flags); if (flags & SCRIPT_VERIFY_LOW_S) { // If we do enforce low S, then high S sigs are rejected. BOOST_CHECK(!CheckDataSignatureEncoding(highSSig, flags, &err)); BOOST_CHECK(err == ScriptError::SIG_HIGH_S); } else { // If we do not enforce low S, then high S sigs are accepted. CheckSignatureEncodingWithSigHashType(highSSig, flags); } for (const valtype &nonDERSig : nonDERSigs) { if (flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) { // If we get any of the dersig flags, the non canonical dersig // signature fails. BOOST_CHECK( !CheckDataSignatureEncoding(nonDERSig, flags, &err)); BOOST_CHECK(err == ScriptError::SIG_DER); } else { // If we do not check, then it is accepted. BOOST_CHECK(CheckDataSignatureEncoding(nonDERSig, flags, &err)); } } for (const valtype &nonDERSig : nonParsableSigs) { if (flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) { // If we get any of the dersig flags, the high S but non dersig // signature fails. BOOST_CHECK( !CheckDataSignatureEncoding(nonDERSig, flags, &err)); BOOST_CHECK(err == ScriptError::SIG_DER); } else { // If we do not check, then it is accepted. BOOST_CHECK(CheckDataSignatureEncoding(nonDERSig, flags, &err)); } } } } BOOST_AUTO_TEST_CASE(checkpubkeyencoding_test) { valtype compressedKey0{0x02, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0}; valtype compressedKey1{0x03, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x0f, 0xff}; valtype fullKey{0x04, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x0f, 0xff}; std::vector<valtype> invalidKeys{ // Degenerate keys. {}, {0x00}, {0x01}, {0x02}, {0x03}, {0x04}, {0x05}, {0x42}, {0xff}, // Invalid first byte 0x00. {0x00, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0}, {0x00, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x0f, 0xff}, // Invalid first byte 0x01. {0x01, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0}, {0x00, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x0f, 0xff}, // Invalid first byte 0x05. {0x05, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0}, {0x05, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x0f, 0xff}, // Invalid first byte 0xff. {0xff, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0}, {0xff, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x0f, 0xff}, // Compressed key too short. {0x02, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0}, {0x03, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x0f, 0xff}, // Compressed key too long. {0x02, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0xab, 0xba, 0x9a, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0}, {0x03, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0xab, 0xba, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x0f, 0xff}, // Compressed key, full key size. {0x02, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x0f, 0xff}, {0x03, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x0f, 0xff}, // Full key, too short. {0x04, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x0f, 0xff}, // Full key, too long. {0x04, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x56, 0x78, 0xab, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x0f, 0xff}, // Full key, compressed key size. {0x04, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0xab, 0xba, 0x9a, 0xde, 0xf0, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0}, }; MMIXLinearCongruentialGenerator lcg; for (int i = 0; i < 4096; i++) { uint32_t flags = lcg.next(); ScriptError err = ScriptError::OK; // Compressed and uncompressed pubkeys are always valid. BOOST_CHECK(CheckPubKeyEncoding(compressedKey0, flags, &err)); BOOST_CHECK(CheckPubKeyEncoding(compressedKey1, flags, &err)); BOOST_CHECK(CheckPubKeyEncoding(fullKey, flags, &err)); // If SCRIPT_VERIFY_STRICTENC is specified, we rule out invalid keys. const bool hasStrictEnc = (flags & SCRIPT_VERIFY_STRICTENC) != 0; const bool allowInvalidKeys = !hasStrictEnc; for (const valtype &key : invalidKeys) { BOOST_CHECK_EQUAL(CheckPubKeyEncoding(key, flags, &err), allowInvalidKeys); if (!allowInvalidKeys) { BOOST_CHECK(err == ScriptError::PUBKEYTYPE); } } } } BOOST_AUTO_TEST_CASE(checkschnorr_test) { // tests using 64 byte sigs (+hashtype byte where relevant) valtype Zero64(64, 0); valtype DER64{0x30, 0x3e, 0x02, 0x1d, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x02, 0x1d, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44}; BOOST_REQUIRE_EQUAL(Zero64.size(), 64); BOOST_REQUIRE_EQUAL(DER64.size(), 64); MMIXLinearCongruentialGenerator lcg; for (int i = 0; i < 4096; i++) { uint32_t flags = lcg.next(); const bool hasForkId = (flags & SCRIPT_ENABLE_SIGHASH_FORKID) != 0; ScriptError err = ScriptError::OK; valtype DER65_hb = SignatureWithHashType(DER64, SigHashType().withForkId(hasForkId)); valtype Zero65_hb = SignatureWithHashType(Zero64, SigHashType().withForkId(hasForkId)); BOOST_CHECK(CheckDataSignatureEncoding(DER64, flags, &err)); BOOST_CHECK(CheckTransactionSignatureEncoding(DER65_hb, flags, &err)); BOOST_CHECK( !CheckTransactionECDSASignatureEncoding(DER65_hb, flags, &err)); BOOST_CHECK(err == ScriptError::SIG_BADLENGTH); BOOST_CHECK( CheckTransactionSchnorrSignatureEncoding(DER65_hb, flags, &err)); BOOST_CHECK(CheckDataSignatureEncoding(Zero64, flags, &err)); BOOST_CHECK(CheckTransactionSignatureEncoding(Zero65_hb, flags, &err)); BOOST_CHECK( !CheckTransactionECDSASignatureEncoding(Zero65_hb, flags, &err)); BOOST_CHECK(err == ScriptError::SIG_BADLENGTH); BOOST_CHECK( CheckTransactionSchnorrSignatureEncoding(Zero65_hb, flags, &err)); } } BOOST_AUTO_TEST_SUITE_END()
ftrader-bitcoinabc/bitcoin-abc
src/test/sigencoding_tests.cpp
C++
mit
22,601
/* * Copyright (C) The Apache Software Foundation. All rights reserved. * * This software is published under the terms of the Apache Software * License version 1.1, a copy of which has been included with this * distribution in the LICENSE.APL file. */ // Contibutors: "Luke Blanshard" <Luke@quiq.com> // "Mark DONSZELMANN" <Mark.Donszelmann@cern.ch> // Anders Kristensen <akristensen@dynamicsoft.com> package org.apache.log4j; import org.apache.log4j.Category; import org.apache.log4j.Priority; import org.apache.log4j.DefaultCategoryFactory; import org.apache.log4j.config.PropertySetter; //import org.apache.log4j.config.PropertySetterException; import org.apache.log4j.spi.OptionHandler; import org.apache.log4j.spi.Configurator; import org.apache.log4j.spi.CategoryFactory; import org.apache.log4j.or.ObjectRenderer; import org.apache.log4j.or.RendererMap; import org.apache.log4j.helpers.LogLog; import org.apache.log4j.helpers.OptionConverter; import org.apache.log4j.helpers.FileWatchdog; import java.util.NoSuchElementException; import java.util.Enumeration; import java.util.Properties; import java.io.FileInputStream; import java.io.IOException; import java.util.StringTokenizer; import java.util.Hashtable; /** Extends {@link BasicConfigurator} to provide configuration from an external file. See <b>{@link #doConfigure(String, Hierarchy)}</b> for the expected format. <p>It is sometimes useful to see how log4j is reading configuration files. You can enable log4j internal logging by defining the <b>log4j.debug</b> variable. <P>As of log4j version 0.8.5, at the initialization of the Category class, the file <b>log4j.properties</b> will be searched from the search path used to load classes. If the file can be found, then it will be fed to the {@link PropertyConfigurator#configure(java.net.URL)} method. <p>The <code>PropertyConfigurator</code> does not handle the advanced configuration features supported by the {@link org.apache.log4j.xml.DOMConfigurator DOMConfigurator} such as support for {@link org.apache.log4j.spi.Filter Filters}, custom {@link org.apache.log4j.spi.ErrorHandler ErrorHandlers}, nested appenders such as the {@link org.apache.log4j.AsyncAppender AsyncAppender}, etc. <p><em>All option values admit variable substitution.</em> For example, if <code>java.home</code> system property is set to <code>/home/xyz</code> and the File option is set to the string <code>${java.home}/test.log</code>, then File option will be interpreted as the string <code>/home/xyz/test.log</code>. <p>The value of the substituted variable can be defined as a system property or in the configuration file file itself. <p>The syntax of variable substitution is similar to that of UNIX shells. The string between an opening <b>&quot;${&quot;</b> and closing <b>&quot;}&quot;</b> is interpreted as a key. Its value is searched in the system properties, and if not founf then in the configuration file being parsed. The corresponding value replaces the ${variableName} sequence. @author Ceki G&uuml;lc&uuml; @author Anders Kristensen @since 0.8.1 */ public class PropertyConfigurator extends BasicConfigurator implements Configurator { /** Used internally to keep track of configured appenders. */ protected Hashtable registry = new Hashtable(11); protected CategoryFactory categoryFactory = new DefaultCategoryFactory(); static final String CATEGORY_PREFIX = "log4j.category."; static final String FACTORY_PREFIX = "log4j.factory"; static final String ADDITIVITY_PREFIX = "log4j.additivity."; static final String ROOT_CATEGORY_PREFIX = "log4j.rootCategory"; static final String APPENDER_PREFIX = "log4j.appender."; static final String RENDERER_PREFIX = "log4j.renderer."; /** Key for specifying the {@link org.apache.log4j.spi.CategoryFactory CategoryFactory}. Currently set to "<code>log4j.categoryFactory</code>". */ public static final String CATEGORY_FACTORY_KEY = "log4j.categoryFactory"; static final private String INTERNAL_ROOT_NAME = "root"; /** Read configuration from a file. <b>The existing configuration is not cleared nor reset.</b> If you require a different behavior, then call {@link BasicConfigurator#resetConfiguration resetConfiguration} method before calling <code>doConfigure</code>. <p>The configuration file consists of statements in the format <code>key=value</code>. The syntax of different configuration elements are discussed below. <h3>Appender configuration</h3> <p>Appender configuration syntax is: <pre> # For appender named <i>appenderName</i>, set its class. # Note: The appender name can contain dots. log4j.appender.appenderName=fully.qualified.name.of.appender.class # Set appender specific options. log4j.appender.appenderName.option1=value1 ... log4j.appender.appenderName.optionN=valueN </pre> For each named appender you can configure its {@link Layout}. The syntax for configuring an appender's layout is: <pre> log4j.appender.appenderName.layout=fully.qualified.name.of.layout.class log4j.appender.appenderName.layout.option1=value1 .... log4j.appender.appenderName.layout.optionN=valueN </pre> <h3>Configuring categories</h3> <p>The syntax for configuring the root category is: <pre> log4j.rootCategory=[priority], appenderName, appenderName, ... </pre> <p>This syntax means that an optional <em>priority value</em> can be supplied followed by appender names separated by commas. <p>The priority value can consist of the string values FATAL, ERROR, WARN, INFO, DEBUG or a <em>custom priority</em> value. A custom priority value can be specified in the form <code>priority#classname</code>. <p>If a priority value is specified, then the root priority is set to the corresponding priority. If no priority value is specified, then the root priority remains untouched. <p>The root category can be assigned multiple appenders. <p>Each <i>appenderName</i> (separated by commas) will be added to the root category. The named appender is defined using the appender syntax defined above. <p>For non-root categories the syntax is almost the same: <pre> log4j.category.category_name=[priority|INHERITED], appenderName, appenderName, ... </pre> <p>The meaning of the optional priority value is discussed above in relation to the root category. In addition however, the value INHERITED can be specified meaning that the named category should inherit its priority from the category hierarchy. <p>If no priority value is supplied, then the priority of the named category remains untouched. <p>By default categories inherit their priority from the hierarchy. However, if you set the priority of a category and later decide that that category should inherit its priority, then you should specify INHERITED as the value for the priority value. <p>Similar to the root category syntax, each <i>appenderName</i> (separated by commas) will be attached to the named category. <p>See the <a href="../../../../manual.html#additivity">appender additivity rule</a> in the user manual for the meaning of the <code>additivity</code> flag. <p>The user can override any of the {@link Hierarchy#disable} family of methods by setting the a key "log4j.disableOverride" to <code>true</code> or any value other than false. As in <pre>log4j.disableOverride=true </pre> <h3>ObjectRenderers</h3> You can customize the way message objects of a given type are converted to String before being logged. This is done by specifying an {@link org.apache.log4j.or.ObjectRenderer ObjectRenderer} for the object type would like to customize. <p>The syntax is: <pre> log4j.renderer.fully.qualified.name.of.rendered.class=fully.qualified.name.of.rendering.class </pre> As in, <pre> log4j.renderer.my.Fruit=my.FruitRenderer </pre> <h3>Class Factories</h3> In case you are using your own subtypes of the <code>Category</code> class and wish to use configuration files, then you <em>must</em> set the <code>categoryFactory</code> for the subtype that you are using. <p>The syntax is: <pre> log4j.categoryFactory=fully.qualified.name.of.categoryFactory.class </pre> See {@link org.apache.log4j.examples.MyCategory} for an example. <h3>Example</h3> <p>An example configuration is given below. Other configuration file examples are given in {@link org.apache.log4j.examples.Sort} class documentation. <pre> # Set options for appender named "A1". # Appender "A1" will be a SyslogAppender log4j.appender.A1=org.apache.log4j.net.SyslogAppender # The syslog daemon resides on www.abc.net log4j.appender.A1.SyslogHost=www.abc.net # A1's layout is a PatternLayout, using the conversion pattern # <b>%r %-5p %c{2} %M.%L %x - %m\n</b>. Thus, the log output will # include # the relative time since the start of the application in # milliseconds, followed by the priority of the log request, # followed by the two rightmost components of the category name, # followed by the callers method name, followed by the line number, # the nested disgnostic context and finally the message itself. # Refer to the documentation of {@link PatternLayout} for further information # on the syntax of the ConversionPattern key. log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%-4r %-5p %c{2} %M.%L %x - %m\n # Set options for appender named "A2" # A2 should be a RollingFileAppender, with maximum file size of 10 MB # using at most one backup file. A2's layout is TTCC, using the # ISO8061 date format with context printing enabled. log4j.appender.A2=org.apache.log4j.RollingFileAppender log4j.appender.A2.MaxFileSize=10MB log4j.appender.A2.MaxBackupIndex=1 log4j.appender.A2.layout=org.apache.log4j.TTCCLayout log4j.appender.A2.layout.ContextPrinting=enabled log4j.appender.A2.layout.DateFormat=ISO8601 # Root category set to DEBUG using the A2 appender defined above. log4j.rootCategory=DEBUG, A2 # Category definitions: # The SECURITY category inherits is priority from root. However, it's output # will go to A1 appender defined above. It's additivity is non-cumulative. log4j.category.SECURITY=INHERIT, A1 log4j.additivity.SECURITY=false # Only warnings or above will be logged for the category "SECURITY.access". # Output will go to A1. log4j.category.SECURITY.access=WARN # The category "class.of.the.day" inherits its priority from the # category hierarchy. Output will go to the appender's of the root # category, A2 in this case. log4j.category.class.of.the.day=INHERIT </pre> <p>Refer to the <b>setOption</b> method in each Appender and Layout for class specific options. <p>Use the <code>#</code> or <code>!</code> characters at the beginning of a line for comments. <p> @param configFileName The name of the configuration file where the configuration information is stored. */ public void doConfigure(String configFileName, Hierarchy hierarchy) { Properties props = new Properties(); try { FileInputStream istream = new FileInputStream(configFileName); props.load(istream); istream.close(); } catch (IOException e) { LogLog.error("Could not read configuration file ["+configFileName+"].", e); LogLog.error("Ignoring configuration file [" + configFileName+"]."); return; } // If we reach here, then the config file is alright. doConfigure(props, hierarchy); } /** */ static public void configure(String configFilename) { new PropertyConfigurator().doConfigure(configFilename, Category.defaultHierarchy); } /** Read configuration options from url <code>configURL</code>. @since 0.8.2 */ public static void configure(java.net.URL configURL) { new PropertyConfigurator().doConfigure(configURL, Category.defaultHierarchy); } /** Read configuration options from <code>properties</code>. See {@link #doConfigure(String, Hierarchy)} for the expected format. */ static public void configure(Properties properties) { new PropertyConfigurator().doConfigure(properties, Category.defaultHierarchy); } /** Like {@link #configureAndWatch(String, long)} except that the default delay as defined by {@link FileWatchdog#DEFAULT_DELAY} is used. @param configFilename A file in key=value format. */ static public void configureAndWatch(String configFilename) { configureAndWatch(configFilename, FileWatchdog.DEFAULT_DELAY); } /** Read the configuration file <code>configFilename</code> if it exists. Moreover, a thread will be created that will periodically check if <code>configFilename</code> has been created or modified. The period is determined by the <code>delay</code> argument. If a change or file creation is detected, then <code>configFilename</code> is read to configure log4j. @param configFilename A file in key=value format. @param delay The delay in milliseconds to wait between each check. */ static public void configureAndWatch(String configFilename, long delay) { PropertyWatchdog pdog = new PropertyWatchdog(configFilename); pdog.setDelay(delay); pdog.start(); } /** Read configuration options from <code>properties</code>. See {@link #doConfigure(String, Hierarchy)} for the expected format. */ public void doConfigure(Properties properties, Hierarchy hierarchy) { String value = properties.getProperty(LogLog.DEBUG_KEY); if(value == null) { value = properties.getProperty(LogLog.CONFIG_DEBUG_KEY); if(value != null) LogLog.warn("[log4j.configDebug] is deprecated. Use [log4j.debug] instead."); } if(value != null) { LogLog.setInternalDebugging(OptionConverter.toBoolean(value, true)); } // Check if the config file overides the shipped code flag. String override = properties.getProperty( BasicConfigurator.DISABLE_OVERRIDE_KEY); hierarchy.overrideAsNeeded(override); if(override == null) { String disableStr = properties.getProperty(BasicConfigurator.DISABLE_KEY); if(disableStr != null) hierarchy.disable(disableStr); } configureRootCategory(properties, hierarchy); configureCategoryFactory(properties); parseCatsAndRenderers(properties, hierarchy); LogLog.debug("Finished configuring."); // We don't want to hold references to appenders preventing their // garbage collection. registry.clear(); } /** Read configuration options from url <code>configURL</code>. */ public void doConfigure(java.net.URL configURL, Hierarchy hierarchy) { Properties props = new Properties(); LogLog.debug("Reading configuration from URL " + configURL); try { props.load(configURL.openStream()); } catch (java.io.IOException e) { LogLog.error("Could not read configuration file from URL [" + configURL + "].", e); LogLog.error("Ignoring configuration file [" + configURL +"]."); return; } doConfigure(props, hierarchy); } // -------------------------------------------------------------------------- // Internal stuff // -------------------------------------------------------------------------- /** Check the provided <code>Properties</code> object for a {@link org.apache.log4j.spi.CategoryFactory CategoryFactory} entry specified by {@link #CATEGORY_FACTORY_KEY}. If such an entry exists, an attempt is made to create an instance using the default constructor. This instance is used for subsequent Category creations within this configurator. @see #parseCatsAndRenderers */ protected void configureCategoryFactory(Properties props) { String factoryClassName = OptionConverter.findAndSubst(CATEGORY_FACTORY_KEY, props); if(factoryClassName != null) { LogLog.debug("Setting category factory to ["+factoryClassName+"]."); categoryFactory = (CategoryFactory) OptionConverter.instantiateByClassName(factoryClassName, CategoryFactory.class, categoryFactory); PropertySetter.setProperties(categoryFactory, props, FACTORY_PREFIX + "."); // When the following line is commented out, the configured // factory is discarded along with the PropertyConfigurator // instance. // // Category.getDefaultHierarchy().setCategoryFactory(categoryFactory); } } /* void configureOptionHandler(OptionHandler oh, String prefix, Properties props) { String[] options = oh.getOptionStrings(); if(options == null) return; String value; for(int i = 0; i < options.length; i++) { value = OptionConverter.findAndSubst(prefix + options[i], props); LogLog.debug( "Option " + options[i] + "=[" + (value == null? "N/A" : value)+"]."); // Some option handlers assume that null value are not passed to them. // So don't remove this check if(value != null) { oh.setOption(options[i], value); } } oh.activateOptions(); } */ void configureRootCategory(Properties props, Hierarchy hierarchy) { String value = OptionConverter.findAndSubst(ROOT_CATEGORY_PREFIX, props); if(value == null) LogLog.debug("Could not find root category information. Is this OK?"); else { Category root = hierarchy.getRoot(); synchronized(root) { parseCategory(props, root, ROOT_CATEGORY_PREFIX, INTERNAL_ROOT_NAME, value); } } } /** Parse non-root elements, such non-root categories and renderers. */ protected void parseCatsAndRenderers(Properties props, Hierarchy hierarchy) { Enumeration enum = props.propertyNames(); while(enum.hasMoreElements()) { String key = (String) enum.nextElement(); if(key.startsWith(CATEGORY_PREFIX)) { String categoryName = key.substring(CATEGORY_PREFIX.length()); String value = OptionConverter.findAndSubst(key, props); Category cat = hierarchy.getInstance(categoryName, categoryFactory); synchronized(cat) { parseCategory(props, cat, key, categoryName, value); parseAdditivityForCategory(props, cat, categoryName); } } else if(key.startsWith(RENDERER_PREFIX)) { String renderedClass = key.substring(RENDERER_PREFIX.length()); String renderingClass = OptionConverter.findAndSubst(key, props); addRenderer(hierarchy, renderedClass, renderingClass); } } } /** Parse the additivity option for a non-root category. */ void parseAdditivityForCategory(Properties props, Category cat, String categoryName) { String value = OptionConverter.findAndSubst(ADDITIVITY_PREFIX + categoryName, props); LogLog.debug("Handling "+ADDITIVITY_PREFIX + categoryName+"=["+value+"]"); // touch additivity only if necessary if((value != null) && (!value.equals(""))) { boolean additivity = OptionConverter.toBoolean(value, true); LogLog.debug("Setting additivity for \""+categoryName+"\" to "+ additivity); cat.setAdditivity(additivity); } } /** This method must work for the root category as well. */ void parseCategory(Properties props, Category cat, String optionKey, String catName, String value) { LogLog.debug("Parsing for [" +catName +"] with value=[" + value+"]."); // We must skip over ',' but not white space StringTokenizer st = new StringTokenizer(value, ","); // If value is not in the form ", appender.." or "", then we should set // the priority of the category. if(!(value.startsWith(",") || value.equals(""))) { // just to be on the safe side... if(!st.hasMoreTokens()) return; String priorityStr = st.nextToken(); LogLog.debug("Priority token is [" + priorityStr + "]."); // If the priority value is inherited, set category priority value to // null. We also check that the user has not specified inherited for the // root category. if(priorityStr.equalsIgnoreCase(BasicConfigurator.INHERITED) && !catName.equals(INTERNAL_ROOT_NAME)) { cat.setPriority(null); } else { cat.setPriority(OptionConverter.toPriority(priorityStr, Priority.DEBUG)); } LogLog.debug("Category " + catName + " set to " + cat.getPriority()); } // Remove all existing appenders. They will be reconstructed below. cat.removeAllAppenders(); Appender appender; String appenderName; while(st.hasMoreTokens()) { appenderName = st.nextToken().trim(); if(appenderName == null || appenderName.equals(",")) continue; LogLog.debug("Parsing appender named \"" + appenderName +"\"."); appender = parseAppender(props, appenderName); if(appender != null) { cat.addAppender(appender); } } } Appender parseAppender(Properties props, String appenderName) { Appender appender = registryGet(appenderName); if((appender != null)) { LogLog.debug("Appender \"" + appenderName + "\" was already parsed."); return appender; } // Appender was not previously initialized. String prefix = APPENDER_PREFIX + appenderName; String layoutPrefix = prefix + ".layout"; appender = (Appender) OptionConverter.instantiateByKey(props, prefix, org.apache.log4j.Appender.class, null); if(appender == null) { LogLog.error( "Could not instantiate appender named \"" + appenderName+"\"."); return null; } appender.setName(appenderName); if(appender instanceof OptionHandler) { if(appender.requiresLayout()) { Layout layout = (Layout) OptionConverter.instantiateByKey(props, layoutPrefix, Layout.class, null); if(layout != null) { appender.setLayout(layout); LogLog.debug("Parsing layout options for \"" + appenderName +"\"."); //configureOptionHandler(layout, layoutPrefix + ".", props); PropertySetter.setProperties(layout, props, layoutPrefix + "."); LogLog.debug("End of parsing for \"" + appenderName +"\"."); } } //configureOptionHandler((OptionHandler) appender, prefix + ".", props); PropertySetter.setProperties(appender, props, prefix + "."); LogLog.debug("Parsed \"" + appenderName +"\" options."); } registryPut(appender); return appender; } void registryPut(Appender appender) { registry.put(appender.getName(), appender); } Appender registryGet(String name) { return (Appender) registry.get(name); } } class PropertyWatchdog extends FileWatchdog { PropertyWatchdog(String filename) { super(filename); } /** Call {@link PropertyConfigurator#configure(String)} with the <code>filename</code> to reconfigure log4j. */ public void doOnChange() { new PropertyConfigurator().doConfigure(filename, Category.defaultHierarchy); } }
pitpitman/GraduateWork
jakarta-log4j-1.1.3/src/java/org/apache/log4j/PropertyConfigurator.java
Java
mit
23,774
define(function(require) { /** * The Promises/A+ compliance test suite * * Converted from https://github.com/promises-aplus/promises-tests * Thanks @domenic and A+ team for this massive work! **/ require('spec/base/promiseSpec/aplus/2.1.2'); require('spec/base/promiseSpec/aplus/2.1.3'); require('spec/base/promiseSpec/aplus/2.2.1'); require('spec/base/promiseSpec/aplus/2.2.2'); require('spec/base/promiseSpec/aplus/2.2.3'); require('spec/base/promiseSpec/aplus/2.2.4'); require('spec/base/promiseSpec/aplus/2.2.5'); require('spec/base/promiseSpec/aplus/2.2.6'); require('spec/base/promiseSpec/aplus/2.2.7'); require('spec/base/promiseSpec/aplus/2.3.1'); require('spec/base/promiseSpec/aplus/2.3.2'); require('spec/base/promiseSpec/aplus/2.3.3'); require('spec/base/promiseSpec/aplus/2.3.4'); });
Ptico/beejs
test/specs/base/promiseSpec/aplus.js
JavaScript
mit
840
# Knex 튜토리얼 Node.js를 통해 MySQL을 이용하는 방법에는 아래와 같이 여러 가지가 있습니다. 1. 쿼리를 직접 작성한 후 실행 ([mysql](https://www.npmjs.com/package/mysql), ...) 2. 쿼리 빌더를 통해서 쿼리 실행 ([Knex.js](http://knexjs.org/), [Squel.js](https://hiddentao.com/squel/), ...) 3. ORM(Object)을 통해서 쿼리 실행 ([Sequelize](http://docs.sequelizejs.com/), [Bookshelf.js](http://bookshelfjs.org/), [Objection.js](http://vincit.github.io/objection.js/), ...) 실무에서는 1번 방식을 사용하는 경우는 거의 없고, 주로 2번 방식과 3번 방식을 사용합니다. 쿼리 빌더는 쿼리를 직접 작성하는 대신 프로그래밍 언어로 작성된 API를 이용해 간접적으로 쿼리를 작성하는 방식을 말합니다. 쿼리 빌더를 사용하면 쿼리의 조합과 재사용을 유연하고 편리하게 할 수 있습니다. ORM(Object Relational Mapping)은 데이터베이스를 객체 지향 프로그래밍을 통해 다룰 수 있게 만들어주는 도구입니다. Validation 등의 부가 기능을 내장하고 있는 경우가 많으며 테이블 간의 관계도 편하게 다룰 수 있으나, 잘 사용하게 되기까지 필요한 학습 비용이 높다는 단점이 있습니다. 이 강의에서 사용할 Knex.js는 Node.js와 브라우저 위에서 사용가능한 쿼리 빌더입니다. SQL과 비슷한 형태의 문법을 가지고 있고, 또 마이그레이션 기능을 내장하고 있어 널리 사용되고 있습니다. 또한 MySQL, Postgres, MSSQL, Oracle과 같은 유명한 DBMS를 지원합니다. ## 목차 1. [Knex - Query Builder](queryBuilder.md) 2. [Knex - Schema Builder](schemaBuilder.md)
hsootree/TIL
Knex/README.md
Markdown
mit
1,742
import React from 'react' import { Image, Reveal } from 'shengnian-ui-react' const RevealExampleHidden = () => ( <Reveal animated='small fade'> <Reveal.Content visible> <Image src='/assets/images/wireframe/square-image.png' size='small' /> </Reveal.Content> <Reveal.Content hidden> <Image src='/assets/images/avatar/large/ade.jpg' size='small' /> </Reveal.Content> </Reveal> ) export default RevealExampleHidden
shengnian/shengnian-ui-react
docs/app/Examples/elements/Reveal/Content/RevealExampleHidden.js
JavaScript
mit
446
package org.usfirst.frc.team2503.r2016.subsystem; import org.usfirst.frc.team2503.r2016.subsystem.base.DataSpeedControllerSubsystem; import org.usfirst.frc.team2503.r2016.subsystem.base.DataSubsystem; import edu.wpi.first.wpilibj.SpeedController; public class RhinoTrackSubsystem extends DataSpeedControllerSubsystem { public enum RhinoTrackSubsystemDataKey implements DataSubsystem.SubsystemDataKey { POWER } @Override public void tick() { double power = (double) this.getDataKey(RhinoTrackSubsystemDataKey.POWER); this.set(power); } public void setPower(double power) { this.setDataKey(RhinoTrackSubsystemDataKey.POWER, power); } public RhinoTrackSubsystem(SpeedController _controller) { super(_controller); this.setDataKey(RhinoTrackSubsystemDataKey.POWER, 0.0d); } public RhinoTrackSubsystem(SpeedControllerSubsystemType type, final int channel) { super(type, channel); this.setDataKey(RhinoTrackSubsystemDataKey.POWER, 0.0d); } }
frc2503/r2016
src/org/usfirst/frc/team2503/r2016/subsystem/RhinoTrackSubsystem.java
Java
mit
987
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head profile="http://selenium-ide.openqa.org/profiles/test-case"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="selenium.base" href="http://localhost/PSI_Implementacija/" /> <title>Test3-MarijaJankovic</title> </head> <body> <table cellpadding="1" cellspacing="1" border="1"> <thead> <tr><td rowspan="1" colspan="3">Test3-MarijaJankovic</td></tr> </thead><tbody> <tr> <td>open</td> <td>/PSI_Implementacija/index.php/PrelistavanjeRestoranaCtrl/index</td> <td></td> </tr> <tr> <td>type</td> <td>name=brLjudi</td> <td>1</td> </tr> <tr> <td>type</td> <td>name=brLjudi</td> <td>2</td> </tr> <tr> <td>select</td> <td>name=opstina</td> <td>label=Novi Beograd</td> </tr> <tr> <td>type</td> <td>vremeOd</td> <td>2016-06-14 14:00</td> </tr> <tr> <td>type</td> <td>vremeDo</td> <td>2016-06-14 15:00</td> </tr> <tr> <td>clickAndWait</td> <td>//button[@type='submit']</td> <td></td> </tr> <tr> <td>clickAndWait</td> <td>link=Detaljnije i rezervacija</td> <td></td> </tr> <tr> <td>type</td> <td>vremeOd</td> <td>2015-12-12 12:00</td> </tr> <tr> <td>type</td> <td>vremeDo</td> <td>2015-12-12 14:00</td> </tr> <tr> <td>type</td> <td>name=brLjudi</td> <td>1</td> </tr> <tr> <td>type</td> <td>name=brLjudi</td> <td>2</td> </tr> <tr> <td>clickAndWait</td> <td>//button[@type='submit']</td> <td></td> </tr> </tbody></table> </body> </html>
MarijaJankovic623/PSI_Implementacija
tests_selenium/Test3-MarijaJankovic.html
HTML
mit
1,613
/* global appSettings */ var $result, $resultContainer, $resultsButton, $resultsPane, $renderingLabel, $window = $(window), path = require('path'), _ = require('lodash'), isEnabled = true, messenger = require(path.resolve(__dirname, '../messenger')), renderer = require(path.resolve(__dirname, './asciidoc.js')).get(), formats = require(path.resolve(__dirname, '../formats')), source = '', shell = require('shell'), formatter = null, subscriptions = [], _fileInfo, _buildFlags = []; var detectRenderer = function (fileInfo) { var rendererPath, currentFormatter; currentFormatter = formats.getByFileExtension(fileInfo.ext); if (formatter === null || currentFormatter.name !== formatter.name) { formatter = currentFormatter; rendererPath = path.resolve(__dirname, './' + formatter.name.toLowerCase()); renderer = require(rendererPath).get(); messenger.publish.file('formatChanged', formatter); } }; var handlers = { opened: function(fileInfo){ refreshSubscriptions(); $result.animate({ scrollTop: $result.offset().top }, 10); }, sourceChanged: function(fileInfo){ handlers.contentChanged(fileInfo); }, contentChanged: function (fileInfo) { if (isEnabled && $result) { _fileInfo = fileInfo; if (!_.isUndefined(_fileInfo)) { if (_fileInfo.isBlank) { $result.html(''); } else { if(_fileInfo.contents.length > 0){ var flags = ''; detectRenderer(_fileInfo); source = _fileInfo.contents; _buildFlags.forEach(function (buildFlag) { flags += ':' + buildFlag + ':\n' }); source = flags + source; if(!$renderingLabel.is(':visible')){ $renderingLabel.fadeIn('fast'); } renderer(source, function (e) { $result.html(e.html); if($renderingLabel.is(':visible')){ $renderingLabel.fadeOut('fast'); } }); } } } } }, clearBuildFlags: function (params) { _buildFlags = []; }, buildFlags: function (buildFlags) { _buildFlags = buildFlags; handlers.contentChanged(_fileInfo); }, showResults: function() { subscribe(); $resultsPane.css('visibility', 'visible'); $resultsButton .removeClass('fa-chevron-left') .addClass('fa-chevron-right') .one('click', handlers.hideResults); messenger.publish.layout('showResults'); }, hideResults: function () { unsubscribe(); $resultsPane.css('visibility', 'hidden'); $resultsButton .removeClass('fa-chevron-right') .addClass('fa-chevron-left') .one('click', handlers.showResults); messenger.publish.layout('hideResults'); }, fileSelected: function(){ refreshSubscriptions(); _buildFlags = []; }, allFilesClosed: function () { $result.html(''); $renderingLabel.fadeOut('fast'); } }; var subscribe = function () { isEnabled = true; subscriptions.push(messenger.subscribe.file('new', handlers.opened)); subscriptions.push(messenger.subscribe.file('opened', handlers.opened)); subscriptions.push(messenger.subscribe.file('contentChanged', handlers.contentChanged)); subscriptions.push(messenger.subscribe.file('sourceChange', handlers.sourceChanged)); subscriptions.push(messenger.subscribe.file('allFilesClosed', handlers.allFilesClosed)); subscriptions.push(messenger.subscribe.format('buildFlags', handlers.buildFlags)); subscriptions.push(messenger.subscribe.metadata('buildFlags.clear', handlers.clearBuildFlags)); }; var unsubscribe = function () { isEnabled = false; subscriptions.forEach(function (subscription) { messenger.unsubscribe(subscription); }); subscriptions = []; }; var refreshSubscriptions = function(){ unsubscribe(); subscribe(); }; subscribe(); messenger.subscribe.file('selected', handlers.fileSelected); messenger.subscribe.file('rerender', function (data, envelope) { renderer(source, function (e) { $result.html(e.html); }); }); var openExternalLinksInBrowser = function (e) { var href; var element = e.target; if (element.nodeName === 'A') { href = element.getAttribute('href'); shell.openExternal(href); e.preventDefault(); } }; document.addEventListener('click', openExternalLinksInBrowser, false); var setHeight = function (offSetValue) { $resultsPane.css('height', $window.height() - offSetValue + 'px'); $window.on('resize', function (e) { $resultsPane.css('height', $window.height() - offSetValue + 'px'); }); }; $(function () { $result = $('#result'); $resultContainer = $('#result-container'); $resultsPane = $('#result-pane'); $resultsButton = $('#result-button'); $renderingLabel = $('#rendering-label'); $resultsPane .css('left', appSettings.split()) .css('width', appSettings.resultsWidth()); $resultsButton.one('click', handlers.hideResults); setHeight(appSettings.editingContainerOffset()); });
Tasarinan/dockWriter
app/modules/results/index.js
JavaScript
mit
5,811
<?php $this->load->view('partials/mdb-header') ?> <<<<<<< HEAD <!-- /.Primary Style Header --> <div class="wrapper"> <div class="outer"> <div class="row"> <!-- <div class="col-lg-12"> --> <div class="jumbotron"> <h1 class="h1-responsive">Latihan</h1> <hr class="my-2"> <p>It uses utility classes for typography and spacing to space content out within the larger container.</p> ======= <?php $this->load->view('partials/mhs_navbar') ?> <br><br><br> <body> <div class="container-fluid"> <div id="lul" class="row"> <div class="col-md-2"></div> <div class="col-md-6"> <!--Panel--> <div class="card card-block"> <h4 class="card-title">Panel title</h4> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <div class="flex-row"> <a class="card-link">Card link</a> <a class="card-link">Another link</a> </div> </div> <!--/.Panel--> </div> </div> <div class="row"> <div class="col-md-2"></div> <div class="col-md-4"> <div class="sp toolbar tab-pane" id="htmPane"> <div class="pane-label">html</div> <div class="inner" id="editor"></div> >>>>>>> ad240c42a0c37e6211328743b19719ad6cf6217e </div> </div> <<<<<<< HEAD <div class="col-sm-6 result" id="return"> ======= <div class="col-md-4" > <div class="card card-block" id="return"> <h4 class="card-title">Live Preview</h4> </div> </div> <div class="col-md-2"> <!--Panel--> <div class="card card-block"> <h4 class="card-title">Options</h4> <a class="btn btn-md btn-primary" id="show">Tampil Soal</a> <a type="submit" class="btn btn-md btn-primary">Sumbit</a> <a type="submit" class="btn btn-md btn-primary">To html</a> </div> <!--/.Panel--> >>>>>>> ad240c42a0c37e6211328743b19719ad6cf6217e </div> </div> </div> </body> <?php $this->load->view('partials/mdb-footer') ?>
aisy/polieditor
application/views/errors/latihan.php
PHP
mit
2,213
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Security.Claims; using Microsoft.AspNet.Authorization; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Mvc; using Microsoft.Extensions.Logging; using MyWebPlayground.Models; using MyWebPlayground.Services; using MyWebPlayground.ViewModels.Manage; namespace MyWebPlayground.Controllers { [Authorize] public class ManageController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly IEmailSender _emailSender; private readonly ISmsSender _smsSender; private readonly ILogger _logger; public ManageController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IEmailSender emailSender, ISmsSender smsSender, ILoggerFactory loggerFactory) { _userManager = userManager; _signInManager = signInManager; _emailSender = emailSender; _smsSender = smsSender; _logger = loggerFactory.CreateLogger<ManageController>(); } // // GET: /Manage/Index [HttpGet] public async Task<IActionResult> Index(ManageMessageId? message = null) { ViewData["StatusMessage"] = message == ManageMessageId.ChangePasswordSuccess ? "Your password has been changed." : message == ManageMessageId.SetPasswordSuccess ? "Your password has been set." : message == ManageMessageId.SetTwoFactorSuccess ? "Your two-factor authentication provider has been set." : message == ManageMessageId.Error ? "An error has occurred." : message == ManageMessageId.AddPhoneSuccess ? "Your phone number was added." : message == ManageMessageId.RemovePhoneSuccess ? "Your phone number was removed." : ""; var user = await GetCurrentUserAsync(); var model = new IndexViewModel { HasPassword = await _userManager.HasPasswordAsync(user), PhoneNumber = await _userManager.GetPhoneNumberAsync(user), TwoFactor = await _userManager.GetTwoFactorEnabledAsync(user), Logins = await _userManager.GetLoginsAsync(user), BrowserRemembered = await _signInManager.IsTwoFactorClientRememberedAsync(user) }; return View(model); } // // POST: /Manage/RemoveLogin [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemoveLogin(RemoveLoginViewModel account) { ManageMessageId? message = ManageMessageId.Error; var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.RemoveLoginAsync(user, account.LoginProvider, account.ProviderKey); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); message = ManageMessageId.RemoveLoginSuccess; } } return RedirectToAction(nameof(ManageLogins), new { Message = message }); } // // GET: /Manage/AddPhoneNumber public IActionResult AddPhoneNumber() { return View(); } // // POST: /Manage/AddPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> AddPhoneNumber(AddPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } // Generate the token and send it var user = await GetCurrentUserAsync(); var code = await _userManager.GenerateChangePhoneNumberTokenAsync(user, model.PhoneNumber); await _smsSender.SendSmsAsync(model.PhoneNumber, "Your security code is: " + code); return RedirectToAction(nameof(VerifyPhoneNumber), new { PhoneNumber = model.PhoneNumber }); } // // POST: /Manage/EnableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> EnableTwoFactorAuthentication() { var user = await GetCurrentUserAsync(); if (user != null) { await _userManager.SetTwoFactorEnabledAsync(user, true); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(1, "User enabled two-factor authentication."); } return RedirectToAction(nameof(Index), "Manage"); } // // POST: /Manage/DisableTwoFactorAuthentication [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> DisableTwoFactorAuthentication() { var user = await GetCurrentUserAsync(); if (user != null) { await _userManager.SetTwoFactorEnabledAsync(user, false); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(2, "User disabled two-factor authentication."); } return RedirectToAction(nameof(Index), "Manage"); } // // GET: /Manage/VerifyPhoneNumber [HttpGet] public async Task<IActionResult> VerifyPhoneNumber(string phoneNumber) { var code = await _userManager.GenerateChangePhoneNumberTokenAsync(await GetCurrentUserAsync(), phoneNumber); // Send an SMS to verify the phone number return phoneNumber == null ? View("Error") : View(new VerifyPhoneNumberViewModel { PhoneNumber = phoneNumber }); } // // POST: /Manage/VerifyPhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> VerifyPhoneNumber(VerifyPhoneNumberViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.ChangePhoneNumberAsync(user, model.PhoneNumber, model.Code); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.AddPhoneSuccess }); } } // If we got this far, something failed, redisplay the form ModelState.AddModelError(string.Empty, "Failed to verify phone number"); return View(model); } // // GET: /Manage/RemovePhoneNumber [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> RemovePhoneNumber() { var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.SetPhoneNumberAsync(user, null); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.RemovePhoneSuccess }); } } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } // // GET: /Manage/ChangePassword [HttpGet] public IActionResult ChangePassword() { return View(); } // // POST: /Manage/ChangePassword [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> ChangePassword(ChangePasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.ChangePasswordAsync(user, model.OldPassword, model.NewPassword); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(3, "User changed their password successfully."); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.ChangePasswordSuccess }); } AddErrors(result); return View(model); } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } // // GET: /Manage/SetPassword [HttpGet] public IActionResult SetPassword() { return View(); } // // POST: /Manage/SetPassword [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> SetPassword(SetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await GetCurrentUserAsync(); if (user != null) { var result = await _userManager.AddPasswordAsync(user, model.NewPassword); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); return RedirectToAction(nameof(Index), new { Message = ManageMessageId.SetPasswordSuccess }); } AddErrors(result); return View(model); } return RedirectToAction(nameof(Index), new { Message = ManageMessageId.Error }); } //GET: /Manage/ManageLogins [HttpGet] public async Task<IActionResult> ManageLogins(ManageMessageId? message = null) { ViewData["StatusMessage"] = message == ManageMessageId.RemoveLoginSuccess ? "The external login was removed." : message == ManageMessageId.AddLoginSuccess ? "The external login was added." : message == ManageMessageId.Error ? "An error has occurred." : ""; var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var userLogins = await _userManager.GetLoginsAsync(user); var otherLogins = _signInManager.GetExternalAuthenticationSchemes().Where(auth => userLogins.All(ul => auth.AuthenticationScheme != ul.LoginProvider)).ToList(); ViewData["ShowRemoveButton"] = user.PasswordHash != null || userLogins.Count > 1; return View(new ManageLoginsViewModel { CurrentLogins = userLogins, OtherLogins = otherLogins }); } // // POST: /Manage/LinkLogin [HttpPost] [ValidateAntiForgeryToken] public IActionResult LinkLogin(string provider) { // Request a redirect to the external login provider to link a login for the current user var redirectUrl = Url.Action("LinkLoginCallback", "Manage"); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, User.GetUserId()); return new ChallengeResult(provider, properties); } // // GET: /Manage/LinkLoginCallback [HttpGet] public async Task<ActionResult> LinkLoginCallback() { var user = await GetCurrentUserAsync(); if (user == null) { return View("Error"); } var info = await _signInManager.GetExternalLoginInfoAsync(User.GetUserId()); if (info == null) { return RedirectToAction(nameof(ManageLogins), new { Message = ManageMessageId.Error }); } var result = await _userManager.AddLoginAsync(user, info); var message = result.Succeeded ? ManageMessageId.AddLoginSuccess : ManageMessageId.Error; return RedirectToAction(nameof(ManageLogins), new { Message = message }); } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } public enum ManageMessageId { AddPhoneSuccess, AddLoginSuccess, ChangePasswordSuccess, SetTwoFactorSuccess, SetPasswordSuccess, RemoveLoginSuccess, RemovePhoneSuccess, Error } private async Task<ApplicationUser> GetCurrentUserAsync() { return await _userManager.FindByIdAsync(HttpContext.User.GetUserId()); } #endregion } }
planset/MyWebPlayground
Controllers/ManageController.cs
C#
mit
13,295
namespace PickUp.Web { using System; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin; using Microsoft.Owin.Security.Cookies; using Owin; using PickUp.Data; using PickUp.Data.Models; public partial class Startup { // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Configure the db context, user manager and signin manager to use a single instance per request app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create); // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider // Configure the sign in cookie app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { // Enables the application to validate the security stamp when the user logs in. // This is a security feature which is used when you change a password or add an external login to your account. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) } }); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process. app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); // Enables the application to remember the second login verification factor such as phone or email. // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from. // This is similar to the RememberMe option when you log in. app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); // app.UseFacebookAuthentication( // appId: "", // appSecret: ""); } } }
ivanvasilev/PickUp
Source/Web/PickUp.Web/App_Start/Startup.Auth.cs
C#
mit
2,929
package repl // Create creates . . . something func (shell *Shell) Create(args []string) (string, error) { if !shell.IsConnected() { return "", ErrNotConnected } return "", nil }
hoop33/elasticprompt
repl/create.go
GO
mit
185
/** * @license Angular v4.2.6 * (c) 2010-2017 Google, Inc. https://angular.io/ * License: MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@angular/common'), require('@angular/core'), require('rxjs/BehaviorSubject'), require('rxjs/Subject'), require('rxjs/observable/from'), require('rxjs/observable/of'), require('rxjs/operator/concatMap'), require('rxjs/operator/every'), require('rxjs/operator/first'), require('rxjs/operator/map'), require('rxjs/operator/mergeMap'), require('rxjs/operator/reduce'), require('rxjs/Observable'), require('rxjs/operator/catch'), require('rxjs/operator/concatAll'), require('rxjs/util/EmptyError'), require('rxjs/observable/fromPromise'), require('rxjs/operator/last'), require('rxjs/operator/mergeAll'), require('@angular/platform-browser'), require('rxjs/operator/filter')) : typeof define === 'function' && define.amd ? define(['exports', '@angular/common', '@angular/core', 'rxjs/BehaviorSubject', 'rxjs/Subject', 'rxjs/observable/from', 'rxjs/observable/of', 'rxjs/operator/concatMap', 'rxjs/operator/every', 'rxjs/operator/first', 'rxjs/operator/map', 'rxjs/operator/mergeMap', 'rxjs/operator/reduce', 'rxjs/Observable', 'rxjs/operator/catch', 'rxjs/operator/concatAll', 'rxjs/util/EmptyError', 'rxjs/observable/fromPromise', 'rxjs/operator/last', 'rxjs/operator/mergeAll', '@angular/platform-browser', 'rxjs/operator/filter'], factory) : (factory((global.ng = global.ng || {}, global.ng.router = global.ng.router || {}),global.ng.common,global.ng.core,global.Rx,global.Rx,global.Rx.Observable,global.Rx.Observable,global.Rx.Observable.prototype,global.Rx.Observable.prototype,global.Rx.Observable.prototype,global.Rx.Observable.prototype,global.Rx.Observable.prototype,global.Rx.Observable.prototype,global.Rx,global.Rx.Observable.prototype,global.Rx.Observable.prototype,global.Rx,global.Rx.Observable,global.Rx.Observable.prototype,global.Rx.Observable.prototype,global.ng.platformBrowser,global.Rx.Observable.prototype)); }(this, (function (exports,_angular_common,_angular_core,rxjs_BehaviorSubject,rxjs_Subject,rxjs_observable_from,rxjs_observable_of,rxjs_operator_concatMap,rxjs_operator_every,rxjs_operator_first,rxjs_operator_map,rxjs_operator_mergeMap,rxjs_operator_reduce,rxjs_Observable,rxjs_operator_catch,rxjs_operator_concatAll,rxjs_util_EmptyError,rxjs_observable_fromPromise,rxjs_operator_last,rxjs_operator_mergeAll,_angular_platformBrowser,rxjs_operator_filter) { 'use strict'; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } /** * @license Angular v4.2.6 * (c) 2010-2017 Google, Inc. https://angular.io/ * License: MIT */ /** * @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 */ /** * \@whatItDoes Represents an event triggered when a navigation starts. * * \@stable */ var NavigationStart = (function () { /** * @param {?} id * @param {?} url */ function NavigationStart(id, url) { this.id = id; this.url = url; } /** * \@docsNotRequired * @return {?} */ NavigationStart.prototype.toString = function () { return "NavigationStart(id: " + this.id + ", url: '" + this.url + "')"; }; return NavigationStart; }()); /** * \@whatItDoes Represents an event triggered when a navigation ends successfully. * * \@stable */ var NavigationEnd = (function () { /** * @param {?} id * @param {?} url * @param {?} urlAfterRedirects */ function NavigationEnd(id, url, urlAfterRedirects) { this.id = id; this.url = url; this.urlAfterRedirects = urlAfterRedirects; } /** * \@docsNotRequired * @return {?} */ NavigationEnd.prototype.toString = function () { return "NavigationEnd(id: " + this.id + ", url: '" + this.url + "', urlAfterRedirects: '" + this.urlAfterRedirects + "')"; }; return NavigationEnd; }()); /** * \@whatItDoes Represents an event triggered when a navigation is canceled. * * \@stable */ var NavigationCancel = (function () { /** * @param {?} id * @param {?} url * @param {?} reason */ function NavigationCancel(id, url, reason) { this.id = id; this.url = url; this.reason = reason; } /** * \@docsNotRequired * @return {?} */ NavigationCancel.prototype.toString = function () { return "NavigationCancel(id: " + this.id + ", url: '" + this.url + "')"; }; return NavigationCancel; }()); /** * \@whatItDoes Represents an event triggered when a navigation fails due to an unexpected error. * * \@stable */ var NavigationError = (function () { /** * @param {?} id * @param {?} url * @param {?} error */ function NavigationError(id, url, error) { this.id = id; this.url = url; this.error = error; } /** * \@docsNotRequired * @return {?} */ NavigationError.prototype.toString = function () { return "NavigationError(id: " + this.id + ", url: '" + this.url + "', error: " + this.error + ")"; }; return NavigationError; }()); /** * \@whatItDoes Represents an event triggered when routes are recognized. * * \@stable */ var RoutesRecognized = (function () { /** * @param {?} id * @param {?} url * @param {?} urlAfterRedirects * @param {?} state */ function RoutesRecognized(id, url, urlAfterRedirects, state) { this.id = id; this.url = url; this.urlAfterRedirects = urlAfterRedirects; this.state = state; } /** * \@docsNotRequired * @return {?} */ RoutesRecognized.prototype.toString = function () { return "RoutesRecognized(id: " + this.id + ", url: '" + this.url + "', urlAfterRedirects: '" + this.urlAfterRedirects + "', state: " + this.state + ")"; }; return RoutesRecognized; }()); /** * \@whatItDoes Represents an event triggered before lazy loading a route config. * * \@experimental */ var RouteConfigLoadStart = (function () { /** * @param {?} route */ function RouteConfigLoadStart(route) { this.route = route; } /** * @return {?} */ RouteConfigLoadStart.prototype.toString = function () { return "RouteConfigLoadStart(path: " + this.route.path + ")"; }; return RouteConfigLoadStart; }()); /** * \@whatItDoes Represents an event triggered when a route has been lazy loaded. * * \@experimental */ var RouteConfigLoadEnd = (function () { /** * @param {?} route */ function RouteConfigLoadEnd(route) { this.route = route; } /** * @return {?} */ RouteConfigLoadEnd.prototype.toString = function () { return "RouteConfigLoadEnd(path: " + this.route.path + ")"; }; return RouteConfigLoadEnd; }()); /** * @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 */ /** * \@whatItDoes Name of the primary outlet. * * \@stable */ var PRIMARY_OUTLET = 'primary'; var ParamsAsMap = (function () { /** * @param {?} params */ function ParamsAsMap(params) { this.params = params || {}; } /** * @param {?} name * @return {?} */ ParamsAsMap.prototype.has = function (name) { return this.params.hasOwnProperty(name); }; /** * @param {?} name * @return {?} */ ParamsAsMap.prototype.get = function (name) { if (this.has(name)) { var /** @type {?} */ v = this.params[name]; return Array.isArray(v) ? v[0] : v; } return null; }; /** * @param {?} name * @return {?} */ ParamsAsMap.prototype.getAll = function (name) { if (this.has(name)) { var /** @type {?} */ v = this.params[name]; return Array.isArray(v) ? v : [v]; } return []; }; Object.defineProperty(ParamsAsMap.prototype, "keys", { /** * @return {?} */ get: function () { return Object.keys(this.params); }, enumerable: true, configurable: true }); return ParamsAsMap; }()); /** * Convert a {\@link Params} instance to a {\@link ParamMap}. * * \@stable * @param {?} params * @return {?} */ function convertToParamMap(params) { return new ParamsAsMap(params); } var NAVIGATION_CANCELING_ERROR = 'ngNavigationCancelingError'; /** * @param {?} message * @return {?} */ function navigationCancelingError(message) { var /** @type {?} */ error = Error('NavigationCancelingError: ' + message); ((error))[NAVIGATION_CANCELING_ERROR] = true; return error; } /** * @param {?} error * @return {?} */ function isNavigationCancelingError(error) { return ((error))[NAVIGATION_CANCELING_ERROR]; } /** * @param {?} segments * @param {?} segmentGroup * @param {?} route * @return {?} */ function defaultUrlMatcher(segments, segmentGroup, route) { var /** @type {?} */ parts = ((route.path)).split('/'); if (parts.length > segments.length) { // The actual URL is shorter than the config, no match return null; } if (route.pathMatch === 'full' && (segmentGroup.hasChildren() || parts.length < segments.length)) { // The config is longer than the actual URL but we are looking for a full match, return null return null; } var /** @type {?} */ posParams = {}; // Check each config part against the actual URL for (var /** @type {?} */ index = 0; index < parts.length; index++) { var /** @type {?} */ part = parts[index]; var /** @type {?} */ segment = segments[index]; var /** @type {?} */ isParameter = part.startsWith(':'); if (isParameter) { posParams[part.substring(1)] = segment; } else if (part !== segment.path) { // The actual URL part does not match the config, no match return null; } } return { consumed: segments.slice(0, parts.length), posParams: posParams }; } /** * @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 */ var LoadedRouterConfig = (function () { /** * @param {?} routes * @param {?} module */ function LoadedRouterConfig(routes, module) { this.routes = routes; this.module = module; } return LoadedRouterConfig; }()); /** * @param {?} config * @param {?=} parentPath * @return {?} */ function validateConfig(config, parentPath) { if (parentPath === void 0) { parentPath = ''; } // forEach doesn't iterate undefined values for (var /** @type {?} */ i = 0; i < config.length; i++) { var /** @type {?} */ route = config[i]; var /** @type {?} */ fullPath = getFullPath(parentPath, route); validateNode(route, fullPath); } } /** * @param {?} route * @param {?} fullPath * @return {?} */ function validateNode(route, fullPath) { if (!route) { throw new Error("\n Invalid configuration of route '" + fullPath + "': Encountered undefined route.\n The reason might be an extra comma.\n\n Example:\n const routes: Routes = [\n { path: '', redirectTo: '/dashboard', pathMatch: 'full' },\n { path: 'dashboard', component: DashboardComponent },, << two commas\n { path: 'detail/:id', component: HeroDetailComponent }\n ];\n "); } if (Array.isArray(route)) { throw new Error("Invalid configuration of route '" + fullPath + "': Array cannot be specified"); } if (!route.component && (route.outlet && route.outlet !== PRIMARY_OUTLET)) { throw new Error("Invalid configuration of route '" + fullPath + "': a componentless route cannot have a named outlet set"); } if (route.redirectTo && route.children) { throw new Error("Invalid configuration of route '" + fullPath + "': redirectTo and children cannot be used together"); } if (route.redirectTo && route.loadChildren) { throw new Error("Invalid configuration of route '" + fullPath + "': redirectTo and loadChildren cannot be used together"); } if (route.children && route.loadChildren) { throw new Error("Invalid configuration of route '" + fullPath + "': children and loadChildren cannot be used together"); } if (route.redirectTo && route.component) { throw new Error("Invalid configuration of route '" + fullPath + "': redirectTo and component cannot be used together"); } if (route.path && route.matcher) { throw new Error("Invalid configuration of route '" + fullPath + "': path and matcher cannot be used together"); } if (route.redirectTo === void 0 && !route.component && !route.children && !route.loadChildren) { throw new Error("Invalid configuration of route '" + fullPath + "'. One of the following must be provided: component, redirectTo, children or loadChildren"); } if (route.path === void 0 && route.matcher === void 0) { throw new Error("Invalid configuration of route '" + fullPath + "': routes must have either a path or a matcher specified"); } if (typeof route.path === 'string' && route.path.charAt(0) === '/') { throw new Error("Invalid configuration of route '" + fullPath + "': path cannot start with a slash"); } if (route.path === '' && route.redirectTo !== void 0 && route.pathMatch === void 0) { var /** @type {?} */ exp = "The default value of 'pathMatch' is 'prefix', but often the intent is to use 'full'."; throw new Error("Invalid configuration of route '{path: \"" + fullPath + "\", redirectTo: \"" + route.redirectTo + "\"}': please provide 'pathMatch'. " + exp); } if (route.pathMatch !== void 0 && route.pathMatch !== 'full' && route.pathMatch !== 'prefix') { throw new Error("Invalid configuration of route '" + fullPath + "': pathMatch can only be set to 'prefix' or 'full'"); } if (route.children) { validateConfig(route.children, fullPath); } } /** * @param {?} parentPath * @param {?} currentRoute * @return {?} */ function getFullPath(parentPath, currentRoute) { if (!currentRoute) { return parentPath; } if (!parentPath && !currentRoute.path) { return ''; } else if (parentPath && !currentRoute.path) { return parentPath + "/"; } else if (!parentPath && currentRoute.path) { return currentRoute.path; } else { return parentPath + "/" + currentRoute.path; } } /** * @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 */ /** * @param {?} a * @param {?} b * @return {?} */ function shallowEqualArrays(a, b) { if (a.length !== b.length) return false; for (var /** @type {?} */ i = 0; i < a.length; ++i) { if (!shallowEqual(a[i], b[i])) return false; } return true; } /** * @param {?} a * @param {?} b * @return {?} */ function shallowEqual(a, b) { var /** @type {?} */ k1 = Object.keys(a); var /** @type {?} */ k2 = Object.keys(b); if (k1.length != k2.length) { return false; } var /** @type {?} */ key; for (var /** @type {?} */ i = 0; i < k1.length; i++) { key = k1[i]; if (a[key] !== b[key]) { return false; } } return true; } /** * @template T * @param {?} arr * @return {?} */ function flatten(arr) { return Array.prototype.concat.apply([], arr); } /** * @template T * @param {?} a * @return {?} */ function last$1(a) { return a.length > 0 ? a[a.length - 1] : null; } /** * @param {?} bools * @return {?} */ /** * @template K, V * @param {?} map * @param {?} callback * @return {?} */ function forEach(map$$1, callback) { for (var /** @type {?} */ prop in map$$1) { if (map$$1.hasOwnProperty(prop)) { callback(map$$1[prop], prop); } } } /** * @template A, B * @param {?} obj * @param {?} fn * @return {?} */ function waitForMap(obj, fn) { if (Object.keys(obj).length === 0) { return rxjs_observable_of.of({}); } var /** @type {?} */ waitHead = []; var /** @type {?} */ waitTail = []; var /** @type {?} */ res = {}; forEach(obj, function (a, k) { var /** @type {?} */ mapped = rxjs_operator_map.map.call(fn(k, a), function (r) { return res[k] = r; }); if (k === PRIMARY_OUTLET) { waitHead.push(mapped); } else { waitTail.push(mapped); } }); var /** @type {?} */ concat$ = rxjs_operator_concatAll.concatAll.call(rxjs_observable_of.of.apply(void 0, waitHead.concat(waitTail))); var /** @type {?} */ last$ = rxjs_operator_last.last.call(concat$); return rxjs_operator_map.map.call(last$, function () { return res; }); } /** * @param {?} observables * @return {?} */ function andObservables(observables) { var /** @type {?} */ merged$ = rxjs_operator_mergeAll.mergeAll.call(observables); return rxjs_operator_every.every.call(merged$, function (result) { return result === true; }); } /** * @template T * @param {?} value * @return {?} */ function wrapIntoObservable(value) { if (_angular_core.ɵisObservable(value)) { return value; } if (_angular_core.ɵisPromise(value)) { // Use `Promise.resolve()` to wrap promise-like instances. // Required ie when a Resolver returns a AngularJS `$q` promise to correctly trigger the // change detection. return rxjs_observable_fromPromise.fromPromise(Promise.resolve(value)); } return rxjs_observable_of.of(value); } /** * @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 */ /** * @return {?} */ function createEmptyUrlTree() { return new UrlTree(new UrlSegmentGroup([], {}), {}, null); } /** * @param {?} container * @param {?} containee * @param {?} exact * @return {?} */ function containsTree(container, containee, exact) { if (exact) { return equalQueryParams(container.queryParams, containee.queryParams) && equalSegmentGroups(container.root, containee.root); } return containsQueryParams(container.queryParams, containee.queryParams) && containsSegmentGroup(container.root, containee.root); } /** * @param {?} container * @param {?} containee * @return {?} */ function equalQueryParams(container, containee) { return shallowEqual(container, containee); } /** * @param {?} container * @param {?} containee * @return {?} */ function equalSegmentGroups(container, containee) { if (!equalPath(container.segments, containee.segments)) return false; if (container.numberOfChildren !== containee.numberOfChildren) return false; for (var /** @type {?} */ c in containee.children) { if (!container.children[c]) return false; if (!equalSegmentGroups(container.children[c], containee.children[c])) return false; } return true; } /** * @param {?} container * @param {?} containee * @return {?} */ function containsQueryParams(container, containee) { return Object.keys(containee).length <= Object.keys(container).length && Object.keys(containee).every(function (key) { return containee[key] === container[key]; }); } /** * @param {?} container * @param {?} containee * @return {?} */ function containsSegmentGroup(container, containee) { return containsSegmentGroupHelper(container, containee, containee.segments); } /** * @param {?} container * @param {?} containee * @param {?} containeePaths * @return {?} */ function containsSegmentGroupHelper(container, containee, containeePaths) { if (container.segments.length > containeePaths.length) { var /** @type {?} */ current = container.segments.slice(0, containeePaths.length); if (!equalPath(current, containeePaths)) return false; if (containee.hasChildren()) return false; return true; } else if (container.segments.length === containeePaths.length) { if (!equalPath(container.segments, containeePaths)) return false; for (var /** @type {?} */ c in containee.children) { if (!container.children[c]) return false; if (!containsSegmentGroup(container.children[c], containee.children[c])) return false; } return true; } else { var /** @type {?} */ current = containeePaths.slice(0, container.segments.length); var /** @type {?} */ next = containeePaths.slice(container.segments.length); if (!equalPath(container.segments, current)) return false; if (!container.children[PRIMARY_OUTLET]) return false; return containsSegmentGroupHelper(container.children[PRIMARY_OUTLET], containee, next); } } /** * \@whatItDoes Represents the parsed URL. * * \@howToUse * * ``` * \@Component({templateUrl:'template.html'}) * class MyComponent { * constructor(router: Router) { * const tree: UrlTree = * router.parseUrl('/team/33/(user/victor//support:help)?debug=true#fragment'); * const f = tree.fragment; // return 'fragment' * const q = tree.queryParams; // returns {debug: 'true'} * const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET]; * const s: UrlSegment[] = g.segments; // returns 2 segments 'team' and '33' * g.children[PRIMARY_OUTLET].segments; // returns 2 segments 'user' and 'victor' * g.children['support'].segments; // return 1 segment 'help' * } * } * ``` * * \@description * * Since a router state is a tree, and the URL is nothing but a serialized state, the URL is a * serialized tree. * UrlTree is a data structure that provides a lot of affordances in dealing with URLs * * \@stable */ var UrlTree = (function () { /** * \@internal * @param {?} root * @param {?} queryParams * @param {?} fragment */ function UrlTree(root, queryParams, fragment) { this.root = root; this.queryParams = queryParams; this.fragment = fragment; } Object.defineProperty(UrlTree.prototype, "queryParamMap", { /** * @return {?} */ get: function () { if (!this._queryParamMap) { this._queryParamMap = convertToParamMap(this.queryParams); } return this._queryParamMap; }, enumerable: true, configurable: true }); /** * \@docsNotRequired * @return {?} */ UrlTree.prototype.toString = function () { return DEFAULT_SERIALIZER.serialize(this); }; return UrlTree; }()); /** * \@whatItDoes Represents the parsed URL segment group. * * See {\@link UrlTree} for more information. * * \@stable */ var UrlSegmentGroup = (function () { /** * @param {?} segments * @param {?} children */ function UrlSegmentGroup(segments, children) { var _this = this; this.segments = segments; this.children = children; /** * The parent node in the url tree */ this.parent = null; forEach(children, function (v, k) { return v.parent = _this; }); } /** * Whether the segment has child segments * @return {?} */ UrlSegmentGroup.prototype.hasChildren = function () { return this.numberOfChildren > 0; }; Object.defineProperty(UrlSegmentGroup.prototype, "numberOfChildren", { /** * Number of child segments * @return {?} */ get: function () { return Object.keys(this.children).length; }, enumerable: true, configurable: true }); /** * \@docsNotRequired * @return {?} */ UrlSegmentGroup.prototype.toString = function () { return serializePaths(this); }; return UrlSegmentGroup; }()); /** * \@whatItDoes Represents a single URL segment. * * \@howToUse * * ``` * \@Component({templateUrl:'template.html'}) * class MyComponent { * constructor(router: Router) { * const tree: UrlTree = router.parseUrl('/team;id=33'); * const g: UrlSegmentGroup = tree.root.children[PRIMARY_OUTLET]; * const s: UrlSegment[] = g.segments; * s[0].path; // returns 'team' * s[0].parameters; // returns {id: 33} * } * } * ``` * * \@description * * A UrlSegment is a part of a URL between the two slashes. It contains a path and the matrix * parameters associated with the segment. * * \@stable */ var UrlSegment = (function () { /** * @param {?} path * @param {?} parameters */ function UrlSegment(path, parameters) { this.path = path; this.parameters = parameters; } Object.defineProperty(UrlSegment.prototype, "parameterMap", { /** * @return {?} */ get: function () { if (!this._parameterMap) { this._parameterMap = convertToParamMap(this.parameters); } return this._parameterMap; }, enumerable: true, configurable: true }); /** * \@docsNotRequired * @return {?} */ UrlSegment.prototype.toString = function () { return serializePath(this); }; return UrlSegment; }()); /** * @param {?} as * @param {?} bs * @return {?} */ function equalSegments(as, bs) { return equalPath(as, bs) && as.every(function (a, i) { return shallowEqual(a.parameters, bs[i].parameters); }); } /** * @param {?} as * @param {?} bs * @return {?} */ function equalPath(as, bs) { if (as.length !== bs.length) return false; return as.every(function (a, i) { return a.path === bs[i].path; }); } /** * @template T * @param {?} segment * @param {?} fn * @return {?} */ function mapChildrenIntoArray(segment, fn) { var /** @type {?} */ res = []; forEach(segment.children, function (child, childOutlet) { if (childOutlet === PRIMARY_OUTLET) { res = res.concat(fn(child, childOutlet)); } }); forEach(segment.children, function (child, childOutlet) { if (childOutlet !== PRIMARY_OUTLET) { res = res.concat(fn(child, childOutlet)); } }); return res; } /** * \@whatItDoes Serializes and deserializes a URL string into a URL tree. * * \@description The url serialization strategy is customizable. You can * make all URLs case insensitive by providing a custom UrlSerializer. * * See {\@link DefaultUrlSerializer} for an example of a URL serializer. * * \@stable * @abstract */ var UrlSerializer = (function () { function UrlSerializer() { } /** * Parse a url into a {\@link UrlTree} * @abstract * @param {?} url * @return {?} */ UrlSerializer.prototype.parse = function (url) { }; /** * Converts a {\@link UrlTree} into a url * @abstract * @param {?} tree * @return {?} */ UrlSerializer.prototype.serialize = function (tree) { }; return UrlSerializer; }()); /** * \@whatItDoes A default implementation of the {\@link UrlSerializer}. * * \@description * * Example URLs: * * ``` * /inbox/33(popup:compose) * /inbox/33;open=true/messages/44 * ``` * * DefaultUrlSerializer uses parentheses to serialize secondary segments (e.g., popup:compose), the * colon syntax to specify the outlet, and the ';parameter=value' syntax (e.g., open=true) to * specify route specific parameters. * * \@stable */ var DefaultUrlSerializer = (function () { function DefaultUrlSerializer() { } /** * Parses a url into a {\@link UrlTree} * @param {?} url * @return {?} */ DefaultUrlSerializer.prototype.parse = function (url) { var /** @type {?} */ p = new UrlParser(url); return new UrlTree(p.parseRootSegment(), p.parseQueryParams(), p.parseFragment()); }; /** * Converts a {\@link UrlTree} into a url * @param {?} tree * @return {?} */ DefaultUrlSerializer.prototype.serialize = function (tree) { var /** @type {?} */ segment = "/" + serializeSegment(tree.root, true); var /** @type {?} */ query = serializeQueryParams(tree.queryParams); var /** @type {?} */ fragment = typeof tree.fragment === "string" ? "#" + encodeURI(/** @type {?} */ ((tree.fragment))) : ''; return "" + segment + query + fragment; }; return DefaultUrlSerializer; }()); var DEFAULT_SERIALIZER = new DefaultUrlSerializer(); /** * @param {?} segment * @return {?} */ function serializePaths(segment) { return segment.segments.map(function (p) { return serializePath(p); }).join('/'); } /** * @param {?} segment * @param {?} root * @return {?} */ function serializeSegment(segment, root) { if (!segment.hasChildren()) { return serializePaths(segment); } if (root) { var /** @type {?} */ primary = segment.children[PRIMARY_OUTLET] ? serializeSegment(segment.children[PRIMARY_OUTLET], false) : ''; var /** @type {?} */ children_1 = []; forEach(segment.children, function (v, k) { if (k !== PRIMARY_OUTLET) { children_1.push(k + ":" + serializeSegment(v, false)); } }); return children_1.length > 0 ? primary + "(" + children_1.join('//') + ")" : primary; } else { var /** @type {?} */ children = mapChildrenIntoArray(segment, function (v, k) { if (k === PRIMARY_OUTLET) { return [serializeSegment(segment.children[PRIMARY_OUTLET], false)]; } return [k + ":" + serializeSegment(v, false)]; }); return serializePaths(segment) + "/(" + children.join('//') + ")"; } } /** * This method is intended for encoding *key* or *value* parts of query component. We need a custom * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be * encoded per http://tools.ietf.org/html/rfc3986: * query = *( pchar / "/" / "?" ) * pchar = unreserved / pct-encoded / sub-delims / ":" / "\@" * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" * pct-encoded = "%" HEXDIG HEXDIG * sub-delims = "!" / "$" / "&" / "'" / "(" / ")" * / "*" / "+" / "," / ";" / "=" * @param {?} s * @return {?} */ function encode(s) { return encodeURIComponent(s) .replace(/%40/g, '@') .replace(/%3A/gi, ':') .replace(/%24/g, '$') .replace(/%2C/gi, ',') .replace(/%3B/gi, ';'); } /** * @param {?} s * @return {?} */ function decode(s) { return decodeURIComponent(s); } /** * @param {?} path * @return {?} */ function serializePath(path) { return "" + encode(path.path) + serializeParams(path.parameters); } /** * @param {?} params * @return {?} */ function serializeParams(params) { return Object.keys(params).map(function (key) { return ";" + encode(key) + "=" + encode(params[key]); }).join(''); } /** * @param {?} params * @return {?} */ function serializeQueryParams(params) { var /** @type {?} */ strParams = Object.keys(params).map(function (name) { var /** @type {?} */ value = params[name]; return Array.isArray(value) ? value.map(function (v) { return encode(name) + "=" + encode(v); }).join('&') : encode(name) + "=" + encode(value); }); return strParams.length ? "?" + strParams.join("&") : ''; } var SEGMENT_RE = /^[^\/()?;=&#]+/; /** * @param {?} str * @return {?} */ function matchSegments(str) { var /** @type {?} */ match = str.match(SEGMENT_RE); return match ? match[0] : ''; } var QUERY_PARAM_RE = /^[^=?&#]+/; /** * @param {?} str * @return {?} */ function matchQueryParams(str) { var /** @type {?} */ match = str.match(QUERY_PARAM_RE); return match ? match[0] : ''; } var QUERY_PARAM_VALUE_RE = /^[^?&#]+/; /** * @param {?} str * @return {?} */ function matchUrlQueryParamValue(str) { var /** @type {?} */ match = str.match(QUERY_PARAM_VALUE_RE); return match ? match[0] : ''; } var UrlParser = (function () { /** * @param {?} url */ function UrlParser(url) { this.url = url; this.remaining = url; } /** * @return {?} */ UrlParser.prototype.parseRootSegment = function () { this.consumeOptional('/'); if (this.remaining === '' || this.peekStartsWith('?') || this.peekStartsWith('#')) { return new UrlSegmentGroup([], {}); } // The root segment group never has segments return new UrlSegmentGroup([], this.parseChildren()); }; /** * @return {?} */ UrlParser.prototype.parseQueryParams = function () { var /** @type {?} */ params = {}; if (this.consumeOptional('?')) { do { this.parseQueryParam(params); } while (this.consumeOptional('&')); } return params; }; /** * @return {?} */ UrlParser.prototype.parseFragment = function () { return this.consumeOptional('#') ? decodeURI(this.remaining) : null; }; /** * @return {?} */ UrlParser.prototype.parseChildren = function () { if (this.remaining === '') { return {}; } this.consumeOptional('/'); var /** @type {?} */ segments = []; if (!this.peekStartsWith('(')) { segments.push(this.parseSegment()); } while (this.peekStartsWith('/') && !this.peekStartsWith('//') && !this.peekStartsWith('/(')) { this.capture('/'); segments.push(this.parseSegment()); } var /** @type {?} */ children = {}; if (this.peekStartsWith('/(')) { this.capture('/'); children = this.parseParens(true); } var /** @type {?} */ res = {}; if (this.peekStartsWith('(')) { res = this.parseParens(false); } if (segments.length > 0 || Object.keys(children).length > 0) { res[PRIMARY_OUTLET] = new UrlSegmentGroup(segments, children); } return res; }; /** * @return {?} */ UrlParser.prototype.parseSegment = function () { var /** @type {?} */ path = matchSegments(this.remaining); if (path === '' && this.peekStartsWith(';')) { throw new Error("Empty path url segment cannot have parameters: '" + this.remaining + "'."); } this.capture(path); return new UrlSegment(decode(path), this.parseMatrixParams()); }; /** * @return {?} */ UrlParser.prototype.parseMatrixParams = function () { var /** @type {?} */ params = {}; while (this.consumeOptional(';')) { this.parseParam(params); } return params; }; /** * @param {?} params * @return {?} */ UrlParser.prototype.parseParam = function (params) { var /** @type {?} */ key = matchSegments(this.remaining); if (!key) { return; } this.capture(key); var /** @type {?} */ value = ''; if (this.consumeOptional('=')) { var /** @type {?} */ valueMatch = matchSegments(this.remaining); if (valueMatch) { value = valueMatch; this.capture(value); } } params[decode(key)] = decode(value); }; /** * @param {?} params * @return {?} */ UrlParser.prototype.parseQueryParam = function (params) { var /** @type {?} */ key = matchQueryParams(this.remaining); if (!key) { return; } this.capture(key); var /** @type {?} */ value = ''; if (this.consumeOptional('=')) { var /** @type {?} */ valueMatch = matchUrlQueryParamValue(this.remaining); if (valueMatch) { value = valueMatch; this.capture(value); } } var /** @type {?} */ decodedKey = decode(key); var /** @type {?} */ decodedVal = decode(value); if (params.hasOwnProperty(decodedKey)) { // Append to existing values var /** @type {?} */ currentVal = params[decodedKey]; if (!Array.isArray(currentVal)) { currentVal = [currentVal]; params[decodedKey] = currentVal; } currentVal.push(decodedVal); } else { // Create a new value params[decodedKey] = decodedVal; } }; /** * @param {?} allowPrimary * @return {?} */ UrlParser.prototype.parseParens = function (allowPrimary) { var /** @type {?} */ segments = {}; this.capture('('); while (!this.consumeOptional(')') && this.remaining.length > 0) { var /** @type {?} */ path = matchSegments(this.remaining); var /** @type {?} */ next = this.remaining[path.length]; // if is is not one of these characters, then the segment was unescaped // or the group was not closed if (next !== '/' && next !== ')' && next !== ';') { throw new Error("Cannot parse url '" + this.url + "'"); } var /** @type {?} */ outletName = ((undefined)); if (path.indexOf(':') > -1) { outletName = path.substr(0, path.indexOf(':')); this.capture(outletName); this.capture(':'); } else if (allowPrimary) { outletName = PRIMARY_OUTLET; } var /** @type {?} */ children = this.parseChildren(); segments[outletName] = Object.keys(children).length === 1 ? children[PRIMARY_OUTLET] : new UrlSegmentGroup([], children); this.consumeOptional('//'); } return segments; }; /** * @param {?} str * @return {?} */ UrlParser.prototype.peekStartsWith = function (str) { return this.remaining.startsWith(str); }; /** * @param {?} str * @return {?} */ UrlParser.prototype.consumeOptional = function (str) { if (this.peekStartsWith(str)) { this.remaining = this.remaining.substring(str.length); return true; } return false; }; /** * @param {?} str * @return {?} */ UrlParser.prototype.capture = function (str) { if (!this.consumeOptional(str)) { throw new Error("Expected \"" + str + "\"."); } }; return UrlParser; }()); /** * @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 */ var NoMatch = (function () { /** * @param {?=} segmentGroup */ function NoMatch(segmentGroup) { this.segmentGroup = segmentGroup || null; } return NoMatch; }()); var AbsoluteRedirect = (function () { /** * @param {?} urlTree */ function AbsoluteRedirect(urlTree) { this.urlTree = urlTree; } return AbsoluteRedirect; }()); /** * @param {?} segmentGroup * @return {?} */ function noMatch(segmentGroup) { return new rxjs_Observable.Observable(function (obs) { return obs.error(new NoMatch(segmentGroup)); }); } /** * @param {?} newTree * @return {?} */ function absoluteRedirect(newTree) { return new rxjs_Observable.Observable(function (obs) { return obs.error(new AbsoluteRedirect(newTree)); }); } /** * @param {?} redirectTo * @return {?} */ function namedOutletsRedirect(redirectTo) { return new rxjs_Observable.Observable(function (obs) { return obs.error(new Error("Only absolute redirects can have named outlets. redirectTo: '" + redirectTo + "'")); }); } /** * @param {?} route * @return {?} */ function canLoadFails(route) { return new rxjs_Observable.Observable(function (obs) { return obs.error(navigationCancelingError("Cannot load children because the guard of the route \"path: '" + route.path + "'\" returned false")); }); } /** * Returns the `UrlTree` with the redirection applied. * * Lazy modules are loaded along the way. * @param {?} moduleInjector * @param {?} configLoader * @param {?} urlSerializer * @param {?} urlTree * @param {?} config * @return {?} */ function applyRedirects(moduleInjector, configLoader, urlSerializer, urlTree, config) { return new ApplyRedirects(moduleInjector, configLoader, urlSerializer, urlTree, config).apply(); } var ApplyRedirects = (function () { /** * @param {?} moduleInjector * @param {?} configLoader * @param {?} urlSerializer * @param {?} urlTree * @param {?} config */ function ApplyRedirects(moduleInjector, configLoader, urlSerializer, urlTree, config) { this.configLoader = configLoader; this.urlSerializer = urlSerializer; this.urlTree = urlTree; this.config = config; this.allowRedirects = true; this.ngModule = moduleInjector.get(_angular_core.NgModuleRef); } /** * @return {?} */ ApplyRedirects.prototype.apply = function () { var _this = this; var /** @type {?} */ expanded$ = this.expandSegmentGroup(this.ngModule, this.config, this.urlTree.root, PRIMARY_OUTLET); var /** @type {?} */ urlTrees$ = rxjs_operator_map.map.call(expanded$, function (rootSegmentGroup) { return _this.createUrlTree(rootSegmentGroup, _this.urlTree.queryParams, /** @type {?} */ ((_this.urlTree.fragment))); }); return rxjs_operator_catch._catch.call(urlTrees$, function (e) { if (e instanceof AbsoluteRedirect) { // after an absolute redirect we do not apply any more redirects! _this.allowRedirects = false; // we need to run matching, so we can fetch all lazy-loaded modules return _this.match(e.urlTree); } if (e instanceof NoMatch) { throw _this.noMatchError(e); } throw e; }); }; /** * @param {?} tree * @return {?} */ ApplyRedirects.prototype.match = function (tree) { var _this = this; var /** @type {?} */ expanded$ = this.expandSegmentGroup(this.ngModule, this.config, tree.root, PRIMARY_OUTLET); var /** @type {?} */ mapped$ = rxjs_operator_map.map.call(expanded$, function (rootSegmentGroup) { return _this.createUrlTree(rootSegmentGroup, tree.queryParams, /** @type {?} */ ((tree.fragment))); }); return rxjs_operator_catch._catch.call(mapped$, function (e) { if (e instanceof NoMatch) { throw _this.noMatchError(e); } throw e; }); }; /** * @param {?} e * @return {?} */ ApplyRedirects.prototype.noMatchError = function (e) { return new Error("Cannot match any routes. URL Segment: '" + e.segmentGroup + "'"); }; /** * @param {?} rootCandidate * @param {?} queryParams * @param {?} fragment * @return {?} */ ApplyRedirects.prototype.createUrlTree = function (rootCandidate, queryParams, fragment) { var /** @type {?} */ root = rootCandidate.segments.length > 0 ? new UrlSegmentGroup([], (_a = {}, _a[PRIMARY_OUTLET] = rootCandidate, _a)) : rootCandidate; return new UrlTree(root, queryParams, fragment); var _a; }; /** * @param {?} ngModule * @param {?} routes * @param {?} segmentGroup * @param {?} outlet * @return {?} */ ApplyRedirects.prototype.expandSegmentGroup = function (ngModule, routes, segmentGroup, outlet) { if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) { return rxjs_operator_map.map.call(this.expandChildren(ngModule, routes, segmentGroup), function (children) { return new UrlSegmentGroup([], children); }); } return this.expandSegment(ngModule, segmentGroup, routes, segmentGroup.segments, outlet, true); }; /** * @param {?} ngModule * @param {?} routes * @param {?} segmentGroup * @return {?} */ ApplyRedirects.prototype.expandChildren = function (ngModule, routes, segmentGroup) { var _this = this; return waitForMap(segmentGroup.children, function (childOutlet, child) { return _this.expandSegmentGroup(ngModule, routes, child, childOutlet); }); }; /** * @param {?} ngModule * @param {?} segmentGroup * @param {?} routes * @param {?} segments * @param {?} outlet * @param {?} allowRedirects * @return {?} */ ApplyRedirects.prototype.expandSegment = function (ngModule, segmentGroup, routes, segments, outlet, allowRedirects) { var _this = this; var /** @type {?} */ routes$ = rxjs_observable_of.of.apply(void 0, routes); var /** @type {?} */ processedRoutes$ = rxjs_operator_map.map.call(routes$, function (r) { var /** @type {?} */ expanded$ = _this.expandSegmentAgainstRoute(ngModule, segmentGroup, routes, r, segments, outlet, allowRedirects); return rxjs_operator_catch._catch.call(expanded$, function (e) { if (e instanceof NoMatch) { return rxjs_observable_of.of(null); } throw e; }); }); var /** @type {?} */ concattedProcessedRoutes$ = rxjs_operator_concatAll.concatAll.call(processedRoutes$); var /** @type {?} */ first$ = rxjs_operator_first.first.call(concattedProcessedRoutes$, function (s) { return !!s; }); return rxjs_operator_catch._catch.call(first$, function (e, _) { if (e instanceof rxjs_util_EmptyError.EmptyError) { if (_this.noLeftoversInUrl(segmentGroup, segments, outlet)) { return rxjs_observable_of.of(new UrlSegmentGroup([], {})); } throw new NoMatch(segmentGroup); } throw e; }); }; /** * @param {?} segmentGroup * @param {?} segments * @param {?} outlet * @return {?} */ ApplyRedirects.prototype.noLeftoversInUrl = function (segmentGroup, segments, outlet) { return segments.length === 0 && !segmentGroup.children[outlet]; }; /** * @param {?} ngModule * @param {?} segmentGroup * @param {?} routes * @param {?} route * @param {?} paths * @param {?} outlet * @param {?} allowRedirects * @return {?} */ ApplyRedirects.prototype.expandSegmentAgainstRoute = function (ngModule, segmentGroup, routes, route, paths, outlet, allowRedirects) { if (getOutlet(route) !== outlet) { return noMatch(segmentGroup); } if (route.redirectTo === undefined) { return this.matchSegmentAgainstRoute(ngModule, segmentGroup, route, paths); } if (allowRedirects && this.allowRedirects) { return this.expandSegmentAgainstRouteUsingRedirect(ngModule, segmentGroup, routes, route, paths, outlet); } return noMatch(segmentGroup); }; /** * @param {?} ngModule * @param {?} segmentGroup * @param {?} routes * @param {?} route * @param {?} segments * @param {?} outlet * @return {?} */ ApplyRedirects.prototype.expandSegmentAgainstRouteUsingRedirect = function (ngModule, segmentGroup, routes, route, segments, outlet) { if (route.path === '**') { return this.expandWildCardWithParamsAgainstRouteUsingRedirect(ngModule, routes, route, outlet); } return this.expandRegularSegmentAgainstRouteUsingRedirect(ngModule, segmentGroup, routes, route, segments, outlet); }; /** * @param {?} ngModule * @param {?} routes * @param {?} route * @param {?} outlet * @return {?} */ ApplyRedirects.prototype.expandWildCardWithParamsAgainstRouteUsingRedirect = function (ngModule, routes, route, outlet) { var _this = this; var /** @type {?} */ newTree = this.applyRedirectCommands([], /** @type {?} */ ((route.redirectTo)), {}); if (((route.redirectTo)).startsWith('/')) { return absoluteRedirect(newTree); } return rxjs_operator_mergeMap.mergeMap.call(this.lineralizeSegments(route, newTree), function (newSegments) { var /** @type {?} */ group = new UrlSegmentGroup(newSegments, {}); return _this.expandSegment(ngModule, group, routes, newSegments, outlet, false); }); }; /** * @param {?} ngModule * @param {?} segmentGroup * @param {?} routes * @param {?} route * @param {?} segments * @param {?} outlet * @return {?} */ ApplyRedirects.prototype.expandRegularSegmentAgainstRouteUsingRedirect = function (ngModule, segmentGroup, routes, route, segments, outlet) { var _this = this; var _a = match(segmentGroup, route, segments), matched = _a.matched, consumedSegments = _a.consumedSegments, lastChild = _a.lastChild, positionalParamSegments = _a.positionalParamSegments; if (!matched) return noMatch(segmentGroup); var /** @type {?} */ newTree = this.applyRedirectCommands(consumedSegments, /** @type {?} */ ((route.redirectTo)), /** @type {?} */ (positionalParamSegments)); if (((route.redirectTo)).startsWith('/')) { return absoluteRedirect(newTree); } return rxjs_operator_mergeMap.mergeMap.call(this.lineralizeSegments(route, newTree), function (newSegments) { return _this.expandSegment(ngModule, segmentGroup, routes, newSegments.concat(segments.slice(lastChild)), outlet, false); }); }; /** * @param {?} ngModule * @param {?} rawSegmentGroup * @param {?} route * @param {?} segments * @return {?} */ ApplyRedirects.prototype.matchSegmentAgainstRoute = function (ngModule, rawSegmentGroup, route, segments) { var _this = this; if (route.path === '**') { if (route.loadChildren) { return rxjs_operator_map.map.call(this.configLoader.load(ngModule.injector, route), function (cfg) { route._loadedConfig = cfg; return new UrlSegmentGroup(segments, {}); }); } return rxjs_observable_of.of(new UrlSegmentGroup(segments, {})); } var _a = match(rawSegmentGroup, route, segments), matched = _a.matched, consumedSegments = _a.consumedSegments, lastChild = _a.lastChild; if (!matched) return noMatch(rawSegmentGroup); var /** @type {?} */ rawSlicedSegments = segments.slice(lastChild); var /** @type {?} */ childConfig$ = this.getChildConfig(ngModule, route); return rxjs_operator_mergeMap.mergeMap.call(childConfig$, function (routerConfig) { var /** @type {?} */ childModule = routerConfig.module; var /** @type {?} */ childConfig = routerConfig.routes; var _a = split(rawSegmentGroup, consumedSegments, rawSlicedSegments, childConfig), segmentGroup = _a.segmentGroup, slicedSegments = _a.slicedSegments; if (slicedSegments.length === 0 && segmentGroup.hasChildren()) { var /** @type {?} */ expanded$_1 = _this.expandChildren(childModule, childConfig, segmentGroup); return rxjs_operator_map.map.call(expanded$_1, function (children) { return new UrlSegmentGroup(consumedSegments, children); }); } if (childConfig.length === 0 && slicedSegments.length === 0) { return rxjs_observable_of.of(new UrlSegmentGroup(consumedSegments, {})); } var /** @type {?} */ expanded$ = _this.expandSegment(childModule, segmentGroup, childConfig, slicedSegments, PRIMARY_OUTLET, true); return rxjs_operator_map.map.call(expanded$, function (cs) { return new UrlSegmentGroup(consumedSegments.concat(cs.segments), cs.children); }); }); }; /** * @param {?} ngModule * @param {?} route * @return {?} */ ApplyRedirects.prototype.getChildConfig = function (ngModule, route) { var _this = this; if (route.children) { // The children belong to the same module return rxjs_observable_of.of(new LoadedRouterConfig(route.children, ngModule)); } if (route.loadChildren) { // lazy children belong to the loaded module if (route._loadedConfig !== undefined) { return rxjs_observable_of.of(route._loadedConfig); } return rxjs_operator_mergeMap.mergeMap.call(runCanLoadGuard(ngModule.injector, route), function (shouldLoad) { if (shouldLoad) { return rxjs_operator_map.map.call(_this.configLoader.load(ngModule.injector, route), function (cfg) { route._loadedConfig = cfg; return cfg; }); } return canLoadFails(route); }); } return rxjs_observable_of.of(new LoadedRouterConfig([], ngModule)); }; /** * @param {?} route * @param {?} urlTree * @return {?} */ ApplyRedirects.prototype.lineralizeSegments = function (route, urlTree) { var /** @type {?} */ res = []; var /** @type {?} */ c = urlTree.root; while (true) { res = res.concat(c.segments); if (c.numberOfChildren === 0) { return rxjs_observable_of.of(res); } if (c.numberOfChildren > 1 || !c.children[PRIMARY_OUTLET]) { return namedOutletsRedirect(/** @type {?} */ ((route.redirectTo))); } c = c.children[PRIMARY_OUTLET]; } }; /** * @param {?} segments * @param {?} redirectTo * @param {?} posParams * @return {?} */ ApplyRedirects.prototype.applyRedirectCommands = function (segments, redirectTo, posParams) { return this.applyRedirectCreatreUrlTree(redirectTo, this.urlSerializer.parse(redirectTo), segments, posParams); }; /** * @param {?} redirectTo * @param {?} urlTree * @param {?} segments * @param {?} posParams * @return {?} */ ApplyRedirects.prototype.applyRedirectCreatreUrlTree = function (redirectTo, urlTree, segments, posParams) { var /** @type {?} */ newRoot = this.createSegmentGroup(redirectTo, urlTree.root, segments, posParams); return new UrlTree(newRoot, this.createQueryParams(urlTree.queryParams, this.urlTree.queryParams), urlTree.fragment); }; /** * @param {?} redirectToParams * @param {?} actualParams * @return {?} */ ApplyRedirects.prototype.createQueryParams = function (redirectToParams, actualParams) { var /** @type {?} */ res = {}; forEach(redirectToParams, function (v, k) { var /** @type {?} */ copySourceValue = typeof v === 'string' && v.startsWith(':'); if (copySourceValue) { var /** @type {?} */ sourceName = v.substring(1); res[k] = actualParams[sourceName]; } else { res[k] = v; } }); return res; }; /** * @param {?} redirectTo * @param {?} group * @param {?} segments * @param {?} posParams * @return {?} */ ApplyRedirects.prototype.createSegmentGroup = function (redirectTo, group, segments, posParams) { var _this = this; var /** @type {?} */ updatedSegments = this.createSegments(redirectTo, group.segments, segments, posParams); var /** @type {?} */ children = {}; forEach(group.children, function (child, name) { children[name] = _this.createSegmentGroup(redirectTo, child, segments, posParams); }); return new UrlSegmentGroup(updatedSegments, children); }; /** * @param {?} redirectTo * @param {?} redirectToSegments * @param {?} actualSegments * @param {?} posParams * @return {?} */ ApplyRedirects.prototype.createSegments = function (redirectTo, redirectToSegments, actualSegments, posParams) { var _this = this; return redirectToSegments.map(function (s) { return s.path.startsWith(':') ? _this.findPosParam(redirectTo, s, posParams) : _this.findOrReturn(s, actualSegments); }); }; /** * @param {?} redirectTo * @param {?} redirectToUrlSegment * @param {?} posParams * @return {?} */ ApplyRedirects.prototype.findPosParam = function (redirectTo, redirectToUrlSegment, posParams) { var /** @type {?} */ pos = posParams[redirectToUrlSegment.path.substring(1)]; if (!pos) throw new Error("Cannot redirect to '" + redirectTo + "'. Cannot find '" + redirectToUrlSegment.path + "'."); return pos; }; /** * @param {?} redirectToUrlSegment * @param {?} actualSegments * @return {?} */ ApplyRedirects.prototype.findOrReturn = function (redirectToUrlSegment, actualSegments) { var /** @type {?} */ idx = 0; for (var _i = 0, actualSegments_1 = actualSegments; _i < actualSegments_1.length; _i++) { var s = actualSegments_1[_i]; if (s.path === redirectToUrlSegment.path) { actualSegments.splice(idx); return s; } idx++; } return redirectToUrlSegment; }; return ApplyRedirects; }()); /** * @param {?} moduleInjector * @param {?} route * @return {?} */ function runCanLoadGuard(moduleInjector, route) { var /** @type {?} */ canLoad = route.canLoad; if (!canLoad || canLoad.length === 0) return rxjs_observable_of.of(true); var /** @type {?} */ obs = rxjs_operator_map.map.call(rxjs_observable_from.from(canLoad), function (injectionToken) { var /** @type {?} */ guard = moduleInjector.get(injectionToken); return wrapIntoObservable(guard.canLoad ? guard.canLoad(route) : guard(route)); }); return andObservables(obs); } /** * @param {?} segmentGroup * @param {?} route * @param {?} segments * @return {?} */ function match(segmentGroup, route, segments) { if (route.path === '') { if ((route.pathMatch === 'full') && (segmentGroup.hasChildren() || segments.length > 0)) { return { matched: false, consumedSegments: [], lastChild: 0, positionalParamSegments: {} }; } return { matched: true, consumedSegments: [], lastChild: 0, positionalParamSegments: {} }; } var /** @type {?} */ matcher = route.matcher || defaultUrlMatcher; var /** @type {?} */ res = matcher(segments, segmentGroup, route); if (!res) { return { matched: false, consumedSegments: /** @type {?} */ ([]), lastChild: 0, positionalParamSegments: {}, }; } return { matched: true, consumedSegments: /** @type {?} */ ((res.consumed)), lastChild: /** @type {?} */ ((res.consumed.length)), positionalParamSegments: /** @type {?} */ ((res.posParams)), }; } /** * @param {?} segmentGroup * @param {?} consumedSegments * @param {?} slicedSegments * @param {?} config * @return {?} */ function split(segmentGroup, consumedSegments, slicedSegments, config) { if (slicedSegments.length > 0 && containsEmptyPathRedirectsWithNamedOutlets(segmentGroup, slicedSegments, config)) { var /** @type {?} */ s = new UrlSegmentGroup(consumedSegments, createChildrenForEmptySegments(config, new UrlSegmentGroup(slicedSegments, segmentGroup.children))); return { segmentGroup: mergeTrivialChildren(s), slicedSegments: [] }; } if (slicedSegments.length === 0 && containsEmptyPathRedirects(segmentGroup, slicedSegments, config)) { var /** @type {?} */ s = new UrlSegmentGroup(segmentGroup.segments, addEmptySegmentsToChildrenIfNeeded(segmentGroup, slicedSegments, config, segmentGroup.children)); return { segmentGroup: mergeTrivialChildren(s), slicedSegments: slicedSegments }; } return { segmentGroup: segmentGroup, slicedSegments: slicedSegments }; } /** * @param {?} s * @return {?} */ function mergeTrivialChildren(s) { if (s.numberOfChildren === 1 && s.children[PRIMARY_OUTLET]) { var /** @type {?} */ c = s.children[PRIMARY_OUTLET]; return new UrlSegmentGroup(s.segments.concat(c.segments), c.children); } return s; } /** * @param {?} segmentGroup * @param {?} slicedSegments * @param {?} routes * @param {?} children * @return {?} */ function addEmptySegmentsToChildrenIfNeeded(segmentGroup, slicedSegments, routes, children) { var /** @type {?} */ res = {}; for (var _i = 0, routes_1 = routes; _i < routes_1.length; _i++) { var r = routes_1[_i]; if (isEmptyPathRedirect(segmentGroup, slicedSegments, r) && !children[getOutlet(r)]) { res[getOutlet(r)] = new UrlSegmentGroup([], {}); } } return Object.assign({}, children, res); } /** * @param {?} routes * @param {?} primarySegmentGroup * @return {?} */ function createChildrenForEmptySegments(routes, primarySegmentGroup) { var /** @type {?} */ res = {}; res[PRIMARY_OUTLET] = primarySegmentGroup; for (var _i = 0, routes_2 = routes; _i < routes_2.length; _i++) { var r = routes_2[_i]; if (r.path === '' && getOutlet(r) !== PRIMARY_OUTLET) { res[getOutlet(r)] = new UrlSegmentGroup([], {}); } } return res; } /** * @param {?} segmentGroup * @param {?} segments * @param {?} routes * @return {?} */ function containsEmptyPathRedirectsWithNamedOutlets(segmentGroup, segments, routes) { return routes.some(function (r) { return isEmptyPathRedirect(segmentGroup, segments, r) && getOutlet(r) !== PRIMARY_OUTLET; }); } /** * @param {?} segmentGroup * @param {?} segments * @param {?} routes * @return {?} */ function containsEmptyPathRedirects(segmentGroup, segments, routes) { return routes.some(function (r) { return isEmptyPathRedirect(segmentGroup, segments, r); }); } /** * @param {?} segmentGroup * @param {?} segments * @param {?} r * @return {?} */ function isEmptyPathRedirect(segmentGroup, segments, r) { if ((segmentGroup.hasChildren() || segments.length > 0) && r.pathMatch === 'full') { return false; } return r.path === '' && r.redirectTo !== undefined; } /** * @param {?} route * @return {?} */ function getOutlet(route) { return route.outlet || PRIMARY_OUTLET; } /** * @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 */ var Tree = (function () { /** * @param {?} root */ function Tree(root) { this._root = root; } Object.defineProperty(Tree.prototype, "root", { /** * @return {?} */ get: function () { return this._root.value; }, enumerable: true, configurable: true }); /** * \@internal * @param {?} t * @return {?} */ Tree.prototype.parent = function (t) { var /** @type {?} */ p = this.pathFromRoot(t); return p.length > 1 ? p[p.length - 2] : null; }; /** * \@internal * @param {?} t * @return {?} */ Tree.prototype.children = function (t) { var /** @type {?} */ n = findNode(t, this._root); return n ? n.children.map(function (t) { return t.value; }) : []; }; /** * \@internal * @param {?} t * @return {?} */ Tree.prototype.firstChild = function (t) { var /** @type {?} */ n = findNode(t, this._root); return n && n.children.length > 0 ? n.children[0].value : null; }; /** * \@internal * @param {?} t * @return {?} */ Tree.prototype.siblings = function (t) { var /** @type {?} */ p = findPath(t, this._root); if (p.length < 2) return []; var /** @type {?} */ c = p[p.length - 2].children.map(function (c) { return c.value; }); return c.filter(function (cc) { return cc !== t; }); }; /** * \@internal * @param {?} t * @return {?} */ Tree.prototype.pathFromRoot = function (t) { return findPath(t, this._root).map(function (s) { return s.value; }); }; return Tree; }()); /** * @template T * @param {?} value * @param {?} node * @return {?} */ function findNode(value, node) { if (value === node.value) return node; for (var _i = 0, _a = node.children; _i < _a.length; _i++) { var child = _a[_i]; var /** @type {?} */ node_1 = findNode(value, child); if (node_1) return node_1; } return null; } /** * @template T * @param {?} value * @param {?} node * @return {?} */ function findPath(value, node) { if (value === node.value) return [node]; for (var _i = 0, _a = node.children; _i < _a.length; _i++) { var child = _a[_i]; var /** @type {?} */ path = findPath(value, child); if (path.length) { path.unshift(node); return path; } } return []; } var TreeNode = (function () { /** * @param {?} value * @param {?} children */ function TreeNode(value, children) { this.value = value; this.children = children; } /** * @return {?} */ TreeNode.prototype.toString = function () { return "TreeNode(" + this.value + ")"; }; return TreeNode; }()); /** * @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 */ /** * \@whatItDoes Represents the state of the router. * * \@howToUse * * ``` * \@Component({templateUrl:'template.html'}) * class MyComponent { * constructor(router: Router) { * const state: RouterState = router.routerState; * const root: ActivatedRoute = state.root; * const child = root.firstChild; * const id: Observable<string> = child.params.map(p => p.id); * //... * } * } * ``` * * \@description * RouterState is a tree of activated routes. Every node in this tree knows about the "consumed" URL * segments, the extracted parameters, and the resolved data. * * See {\@link ActivatedRoute} for more information. * * \@stable */ var RouterState = (function (_super) { __extends(RouterState, _super); /** * \@internal * @param {?} root * @param {?} snapshot */ function RouterState(root, snapshot) { var _this = _super.call(this, root) || this; _this.snapshot = snapshot; setRouterState(_this, root); return _this; } /** * @return {?} */ RouterState.prototype.toString = function () { return this.snapshot.toString(); }; return RouterState; }(Tree)); /** * @param {?} urlTree * @param {?} rootComponent * @return {?} */ function createEmptyState(urlTree, rootComponent) { var /** @type {?} */ snapshot = createEmptyStateSnapshot(urlTree, rootComponent); var /** @type {?} */ emptyUrl = new rxjs_BehaviorSubject.BehaviorSubject([new UrlSegment('', {})]); var /** @type {?} */ emptyParams = new rxjs_BehaviorSubject.BehaviorSubject({}); var /** @type {?} */ emptyData = new rxjs_BehaviorSubject.BehaviorSubject({}); var /** @type {?} */ emptyQueryParams = new rxjs_BehaviorSubject.BehaviorSubject({}); var /** @type {?} */ fragment = new rxjs_BehaviorSubject.BehaviorSubject(''); var /** @type {?} */ activated = new ActivatedRoute(emptyUrl, emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, snapshot.root); activated.snapshot = snapshot.root; return new RouterState(new TreeNode(activated, []), snapshot); } /** * @param {?} urlTree * @param {?} rootComponent * @return {?} */ function createEmptyStateSnapshot(urlTree, rootComponent) { var /** @type {?} */ emptyParams = {}; var /** @type {?} */ emptyData = {}; var /** @type {?} */ emptyQueryParams = {}; var /** @type {?} */ fragment = ''; var /** @type {?} */ activated = new ActivatedRouteSnapshot([], emptyParams, emptyQueryParams, fragment, emptyData, PRIMARY_OUTLET, rootComponent, null, urlTree.root, -1, {}); return new RouterStateSnapshot('', new TreeNode(activated, [])); } /** * \@whatItDoes Contains the information about a route associated with a component loaded in an * outlet. * An `ActivatedRoute` can also be used to traverse the router state tree. * * \@howToUse * * ``` * \@Component({...}) * class MyComponent { * constructor(route: ActivatedRoute) { * const id: Observable<string> = route.params.map(p => p.id); * const url: Observable<string> = route.url.map(segments => segments.join('')); * // route.data includes both `data` and `resolve` * const user = route.data.map(d => d.user); * } * } * ``` * * \@stable */ var ActivatedRoute = (function () { /** * \@internal * @param {?} url * @param {?} params * @param {?} queryParams * @param {?} fragment * @param {?} data * @param {?} outlet * @param {?} component * @param {?} futureSnapshot */ function ActivatedRoute(url, params, queryParams, fragment, data, outlet, component, futureSnapshot) { this.url = url; this.params = params; this.queryParams = queryParams; this.fragment = fragment; this.data = data; this.outlet = outlet; this.component = component; this._futureSnapshot = futureSnapshot; } Object.defineProperty(ActivatedRoute.prototype, "routeConfig", { /** * The configuration used to match this route * @return {?} */ get: function () { return this._futureSnapshot.routeConfig; }, enumerable: true, configurable: true }); Object.defineProperty(ActivatedRoute.prototype, "root", { /** * The root of the router state * @return {?} */ get: function () { return this._routerState.root; }, enumerable: true, configurable: true }); Object.defineProperty(ActivatedRoute.prototype, "parent", { /** * The parent of this route in the router state tree * @return {?} */ get: function () { return this._routerState.parent(this); }, enumerable: true, configurable: true }); Object.defineProperty(ActivatedRoute.prototype, "firstChild", { /** * The first child of this route in the router state tree * @return {?} */ get: function () { return this._routerState.firstChild(this); }, enumerable: true, configurable: true }); Object.defineProperty(ActivatedRoute.prototype, "children", { /** * The children of this route in the router state tree * @return {?} */ get: function () { return this._routerState.children(this); }, enumerable: true, configurable: true }); Object.defineProperty(ActivatedRoute.prototype, "pathFromRoot", { /** * The path from the root of the router state tree to this route * @return {?} */ get: function () { return this._routerState.pathFromRoot(this); }, enumerable: true, configurable: true }); Object.defineProperty(ActivatedRoute.prototype, "paramMap", { /** * @return {?} */ get: function () { if (!this._paramMap) { this._paramMap = rxjs_operator_map.map.call(this.params, function (p) { return convertToParamMap(p); }); } return this._paramMap; }, enumerable: true, configurable: true }); Object.defineProperty(ActivatedRoute.prototype, "queryParamMap", { /** * @return {?} */ get: function () { if (!this._queryParamMap) { this._queryParamMap = rxjs_operator_map.map.call(this.queryParams, function (p) { return convertToParamMap(p); }); } return this._queryParamMap; }, enumerable: true, configurable: true }); /** * @return {?} */ ActivatedRoute.prototype.toString = function () { return this.snapshot ? this.snapshot.toString() : "Future(" + this._futureSnapshot + ")"; }; return ActivatedRoute; }()); /** * \@internal * @param {?} route * @return {?} */ function inheritedParamsDataResolve(route) { var /** @type {?} */ pathToRoot = route.pathFromRoot; var /** @type {?} */ inhertingStartingFrom = pathToRoot.length - 1; while (inhertingStartingFrom >= 1) { var /** @type {?} */ current = pathToRoot[inhertingStartingFrom]; var /** @type {?} */ parent = pathToRoot[inhertingStartingFrom - 1]; // current route is an empty path => inherits its parent's params and data if (current.routeConfig && current.routeConfig.path === '') { inhertingStartingFrom--; // parent is componentless => current route should inherit its params and data } else if (!parent.component) { inhertingStartingFrom--; } else { break; } } return pathToRoot.slice(inhertingStartingFrom).reduce(function (res, curr) { var /** @type {?} */ params = Object.assign({}, res.params, curr.params); var /** @type {?} */ data = Object.assign({}, res.data, curr.data); var /** @type {?} */ resolve = Object.assign({}, res.resolve, curr._resolvedData); return { params: params, data: data, resolve: resolve }; }, /** @type {?} */ ({ params: {}, data: {}, resolve: {} })); } /** * \@whatItDoes Contains the information about a route associated with a component loaded in an * outlet * at a particular moment in time. ActivatedRouteSnapshot can also be used to traverse the router * state tree. * * \@howToUse * * ``` * \@Component({templateUrl:'./my-component.html'}) * class MyComponent { * constructor(route: ActivatedRoute) { * const id: string = route.snapshot.params.id; * const url: string = route.snapshot.url.join(''); * const user = route.snapshot.data.user; * } * } * ``` * * \@stable */ var ActivatedRouteSnapshot = (function () { /** * \@internal * @param {?} url * @param {?} params * @param {?} queryParams * @param {?} fragment * @param {?} data * @param {?} outlet * @param {?} component * @param {?} routeConfig * @param {?} urlSegment * @param {?} lastPathIndex * @param {?} resolve */ function ActivatedRouteSnapshot(url, params, queryParams, fragment, data, outlet, component, routeConfig, urlSegment, lastPathIndex, resolve) { this.url = url; this.params = params; this.queryParams = queryParams; this.fragment = fragment; this.data = data; this.outlet = outlet; this.component = component; this._routeConfig = routeConfig; this._urlSegment = urlSegment; this._lastPathIndex = lastPathIndex; this._resolve = resolve; } Object.defineProperty(ActivatedRouteSnapshot.prototype, "routeConfig", { /** * The configuration used to match this route * @return {?} */ get: function () { return this._routeConfig; }, enumerable: true, configurable: true }); Object.defineProperty(ActivatedRouteSnapshot.prototype, "root", { /** * The root of the router state * @return {?} */ get: function () { return this._routerState.root; }, enumerable: true, configurable: true }); Object.defineProperty(ActivatedRouteSnapshot.prototype, "parent", { /** * The parent of this route in the router state tree * @return {?} */ get: function () { return this._routerState.parent(this); }, enumerable: true, configurable: true }); Object.defineProperty(ActivatedRouteSnapshot.prototype, "firstChild", { /** * The first child of this route in the router state tree * @return {?} */ get: function () { return this._routerState.firstChild(this); }, enumerable: true, configurable: true }); Object.defineProperty(ActivatedRouteSnapshot.prototype, "children", { /** * The children of this route in the router state tree * @return {?} */ get: function () { return this._routerState.children(this); }, enumerable: true, configurable: true }); Object.defineProperty(ActivatedRouteSnapshot.prototype, "pathFromRoot", { /** * The path from the root of the router state tree to this route * @return {?} */ get: function () { return this._routerState.pathFromRoot(this); }, enumerable: true, configurable: true }); Object.defineProperty(ActivatedRouteSnapshot.prototype, "paramMap", { /** * @return {?} */ get: function () { if (!this._paramMap) { this._paramMap = convertToParamMap(this.params); } return this._paramMap; }, enumerable: true, configurable: true }); Object.defineProperty(ActivatedRouteSnapshot.prototype, "queryParamMap", { /** * @return {?} */ get: function () { if (!this._queryParamMap) { this._queryParamMap = convertToParamMap(this.queryParams); } return this._queryParamMap; }, enumerable: true, configurable: true }); /** * @return {?} */ ActivatedRouteSnapshot.prototype.toString = function () { var /** @type {?} */ url = this.url.map(function (segment) { return segment.toString(); }).join('/'); var /** @type {?} */ matched = this._routeConfig ? this._routeConfig.path : ''; return "Route(url:'" + url + "', path:'" + matched + "')"; }; return ActivatedRouteSnapshot; }()); /** * \@whatItDoes Represents the state of the router at a moment in time. * * \@howToUse * * ``` * \@Component({templateUrl:'template.html'}) * class MyComponent { * constructor(router: Router) { * const state: RouterState = router.routerState; * const snapshot: RouterStateSnapshot = state.snapshot; * const root: ActivatedRouteSnapshot = snapshot.root; * const child = root.firstChild; * const id: Observable<string> = child.params.map(p => p.id); * //... * } * } * ``` * * \@description * RouterStateSnapshot is a tree of activated route snapshots. Every node in this tree knows about * the "consumed" URL segments, the extracted parameters, and the resolved data. * * \@stable */ var RouterStateSnapshot = (function (_super) { __extends(RouterStateSnapshot, _super); /** * \@internal * @param {?} url * @param {?} root */ function RouterStateSnapshot(url, root) { var _this = _super.call(this, root) || this; _this.url = url; setRouterState(_this, root); return _this; } /** * @return {?} */ RouterStateSnapshot.prototype.toString = function () { return serializeNode(this._root); }; return RouterStateSnapshot; }(Tree)); /** * @template U, T * @param {?} state * @param {?} node * @return {?} */ function setRouterState(state, node) { node.value._routerState = state; node.children.forEach(function (c) { return setRouterState(state, c); }); } /** * @param {?} node * @return {?} */ function serializeNode(node) { var /** @type {?} */ c = node.children.length > 0 ? " { " + node.children.map(serializeNode).join(", ") + " } " : ''; return "" + node.value + c; } /** * The expectation is that the activate route is created with the right set of parameters. * So we push new values into the observables only when they are not the initial values. * And we detect that by checking if the snapshot field is set. * @param {?} route * @return {?} */ function advanceActivatedRoute(route) { if (route.snapshot) { var /** @type {?} */ currentSnapshot = route.snapshot; var /** @type {?} */ nextSnapshot = route._futureSnapshot; route.snapshot = nextSnapshot; if (!shallowEqual(currentSnapshot.queryParams, nextSnapshot.queryParams)) { ((route.queryParams)).next(nextSnapshot.queryParams); } if (currentSnapshot.fragment !== nextSnapshot.fragment) { ((route.fragment)).next(nextSnapshot.fragment); } if (!shallowEqual(currentSnapshot.params, nextSnapshot.params)) { ((route.params)).next(nextSnapshot.params); } if (!shallowEqualArrays(currentSnapshot.url, nextSnapshot.url)) { ((route.url)).next(nextSnapshot.url); } if (!shallowEqual(currentSnapshot.data, nextSnapshot.data)) { ((route.data)).next(nextSnapshot.data); } } else { route.snapshot = route._futureSnapshot; // this is for resolved data ((route.data)).next(route._futureSnapshot.data); } } /** * @param {?} a * @param {?} b * @return {?} */ function equalParamsAndUrlSegments(a, b) { var /** @type {?} */ equalUrlParams = shallowEqual(a.params, b.params) && equalSegments(a.url, b.url); var /** @type {?} */ parentsMismatch = !a.parent !== !b.parent; return equalUrlParams && !parentsMismatch && (!a.parent || equalParamsAndUrlSegments(a.parent, /** @type {?} */ ((b.parent)))); } /** * @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 */ /** * @param {?} routeReuseStrategy * @param {?} curr * @param {?} prevState * @return {?} */ function createRouterState(routeReuseStrategy, curr, prevState) { var /** @type {?} */ root = createNode(routeReuseStrategy, curr._root, prevState ? prevState._root : undefined); return new RouterState(root, curr); } /** * @param {?} routeReuseStrategy * @param {?} curr * @param {?=} prevState * @return {?} */ function createNode(routeReuseStrategy, curr, prevState) { // reuse an activated route that is currently displayed on the screen if (prevState && routeReuseStrategy.shouldReuseRoute(curr.value, prevState.value.snapshot)) { var /** @type {?} */ value = prevState.value; value._futureSnapshot = curr.value; var /** @type {?} */ children = createOrReuseChildren(routeReuseStrategy, curr, prevState); return new TreeNode(value, children); // retrieve an activated route that is used to be displayed, but is not currently displayed } else if (routeReuseStrategy.retrieve(curr.value)) { var /** @type {?} */ tree_1 = ((routeReuseStrategy.retrieve(curr.value))).route; setFutureSnapshotsOfActivatedRoutes(curr, tree_1); return tree_1; } else { var /** @type {?} */ value = createActivatedRoute(curr.value); var /** @type {?} */ children = curr.children.map(function (c) { return createNode(routeReuseStrategy, c); }); return new TreeNode(value, children); } } /** * @param {?} curr * @param {?} result * @return {?} */ function setFutureSnapshotsOfActivatedRoutes(curr, result) { if (curr.value.routeConfig !== result.value.routeConfig) { throw new Error('Cannot reattach ActivatedRouteSnapshot created from a different route'); } if (curr.children.length !== result.children.length) { throw new Error('Cannot reattach ActivatedRouteSnapshot with a different number of children'); } result.value._futureSnapshot = curr.value; for (var /** @type {?} */ i = 0; i < curr.children.length; ++i) { setFutureSnapshotsOfActivatedRoutes(curr.children[i], result.children[i]); } } /** * @param {?} routeReuseStrategy * @param {?} curr * @param {?} prevState * @return {?} */ function createOrReuseChildren(routeReuseStrategy, curr, prevState) { return curr.children.map(function (child) { for (var _i = 0, _a = prevState.children; _i < _a.length; _i++) { var p = _a[_i]; if (routeReuseStrategy.shouldReuseRoute(p.value.snapshot, child.value)) { return createNode(routeReuseStrategy, child, p); } } return createNode(routeReuseStrategy, child); }); } /** * @param {?} c * @return {?} */ function createActivatedRoute(c) { return new ActivatedRoute(new rxjs_BehaviorSubject.BehaviorSubject(c.url), new rxjs_BehaviorSubject.BehaviorSubject(c.params), new rxjs_BehaviorSubject.BehaviorSubject(c.queryParams), new rxjs_BehaviorSubject.BehaviorSubject(c.fragment), new rxjs_BehaviorSubject.BehaviorSubject(c.data), c.outlet, c.component, c); } /** * @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 */ /** * @param {?} route * @param {?} urlTree * @param {?} commands * @param {?} queryParams * @param {?} fragment * @return {?} */ function createUrlTree(route, urlTree, commands, queryParams, fragment) { if (commands.length === 0) { return tree(urlTree.root, urlTree.root, urlTree, queryParams, fragment); } var /** @type {?} */ nav = computeNavigation(commands); if (nav.toRoot()) { return tree(urlTree.root, new UrlSegmentGroup([], {}), urlTree, queryParams, fragment); } var /** @type {?} */ startingPosition = findStartingPosition(nav, urlTree, route); var /** @type {?} */ segmentGroup = startingPosition.processChildren ? updateSegmentGroupChildren(startingPosition.segmentGroup, startingPosition.index, nav.commands) : updateSegmentGroup(startingPosition.segmentGroup, startingPosition.index, nav.commands); return tree(startingPosition.segmentGroup, segmentGroup, urlTree, queryParams, fragment); } /** * @param {?} command * @return {?} */ function isMatrixParams(command) { return typeof command === 'object' && command != null && !command.outlets && !command.segmentPath; } /** * @param {?} oldSegmentGroup * @param {?} newSegmentGroup * @param {?} urlTree * @param {?} queryParams * @param {?} fragment * @return {?} */ function tree(oldSegmentGroup, newSegmentGroup, urlTree, queryParams, fragment) { var /** @type {?} */ qp = {}; if (queryParams) { forEach(queryParams, function (value, name) { qp[name] = Array.isArray(value) ? value.map(function (v) { return "" + v; }) : "" + value; }); } if (urlTree.root === oldSegmentGroup) { return new UrlTree(newSegmentGroup, qp, fragment); } return new UrlTree(replaceSegment(urlTree.root, oldSegmentGroup, newSegmentGroup), qp, fragment); } /** * @param {?} current * @param {?} oldSegment * @param {?} newSegment * @return {?} */ function replaceSegment(current, oldSegment, newSegment) { var /** @type {?} */ children = {}; forEach(current.children, function (c, outletName) { if (c === oldSegment) { children[outletName] = newSegment; } else { children[outletName] = replaceSegment(c, oldSegment, newSegment); } }); return new UrlSegmentGroup(current.segments, children); } var Navigation = (function () { /** * @param {?} isAbsolute * @param {?} numberOfDoubleDots * @param {?} commands */ function Navigation(isAbsolute, numberOfDoubleDots, commands) { this.isAbsolute = isAbsolute; this.numberOfDoubleDots = numberOfDoubleDots; this.commands = commands; if (isAbsolute && commands.length > 0 && isMatrixParams(commands[0])) { throw new Error('Root segment cannot have matrix parameters'); } var cmdWithOutlet = commands.find(function (c) { return typeof c === 'object' && c != null && c.outlets; }); if (cmdWithOutlet && cmdWithOutlet !== last$1(commands)) { throw new Error('{outlets:{}} has to be the last command'); } } /** * @return {?} */ Navigation.prototype.toRoot = function () { return this.isAbsolute && this.commands.length === 1 && this.commands[0] == '/'; }; return Navigation; }()); /** * Transforms commands to a normalized `Navigation` * @param {?} commands * @return {?} */ function computeNavigation(commands) { if ((typeof commands[0] === 'string') && commands.length === 1 && commands[0] === '/') { return new Navigation(true, 0, commands); } var /** @type {?} */ numberOfDoubleDots = 0; var /** @type {?} */ isAbsolute = false; var /** @type {?} */ res = commands.reduce(function (res, cmd, cmdIdx) { if (typeof cmd === 'object' && cmd != null) { if (cmd.outlets) { var /** @type {?} */ outlets_1 = {}; forEach(cmd.outlets, function (commands, name) { outlets_1[name] = typeof commands === 'string' ? commands.split('/') : commands; }); return res.concat([{ outlets: outlets_1 }]); } if (cmd.segmentPath) { return res.concat([cmd.segmentPath]); } } if (!(typeof cmd === 'string')) { return res.concat([cmd]); } if (cmdIdx === 0) { cmd.split('/').forEach(function (urlPart, partIndex) { if (partIndex == 0 && urlPart === '.') { // skip './a' } else if (partIndex == 0 && urlPart === '') { isAbsolute = true; } else if (urlPart === '..') { numberOfDoubleDots++; } else if (urlPart != '') { res.push(urlPart); } }); return res; } return res.concat([cmd]); }, []); return new Navigation(isAbsolute, numberOfDoubleDots, res); } var Position = (function () { /** * @param {?} segmentGroup * @param {?} processChildren * @param {?} index */ function Position(segmentGroup, processChildren, index) { this.segmentGroup = segmentGroup; this.processChildren = processChildren; this.index = index; } return Position; }()); /** * @param {?} nav * @param {?} tree * @param {?} route * @return {?} */ function findStartingPosition(nav, tree, route) { if (nav.isAbsolute) { return new Position(tree.root, true, 0); } if (route.snapshot._lastPathIndex === -1) { return new Position(route.snapshot._urlSegment, true, 0); } var /** @type {?} */ modifier = isMatrixParams(nav.commands[0]) ? 0 : 1; var /** @type {?} */ index = route.snapshot._lastPathIndex + modifier; return createPositionApplyingDoubleDots(route.snapshot._urlSegment, index, nav.numberOfDoubleDots); } /** * @param {?} group * @param {?} index * @param {?} numberOfDoubleDots * @return {?} */ function createPositionApplyingDoubleDots(group, index, numberOfDoubleDots) { var /** @type {?} */ g = group; var /** @type {?} */ ci = index; var /** @type {?} */ dd = numberOfDoubleDots; while (dd > ci) { dd -= ci; g = ((g.parent)); if (!g) { throw new Error('Invalid number of \'../\''); } ci = g.segments.length; } return new Position(g, false, ci - dd); } /** * @param {?} command * @return {?} */ function getPath(command) { if (typeof command === 'object' && command != null && command.outlets) { return command.outlets[PRIMARY_OUTLET]; } return "" + command; } /** * @param {?} commands * @return {?} */ function getOutlets(commands) { if (!(typeof commands[0] === 'object')) return _a = {}, _a[PRIMARY_OUTLET] = commands, _a; if (commands[0].outlets === undefined) return _b = {}, _b[PRIMARY_OUTLET] = commands, _b; return commands[0].outlets; var _a, _b; } /** * @param {?} segmentGroup * @param {?} startIndex * @param {?} commands * @return {?} */ function updateSegmentGroup(segmentGroup, startIndex, commands) { if (!segmentGroup) { segmentGroup = new UrlSegmentGroup([], {}); } if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) { return updateSegmentGroupChildren(segmentGroup, startIndex, commands); } var /** @type {?} */ m = prefixedWith(segmentGroup, startIndex, commands); var /** @type {?} */ slicedCommands = commands.slice(m.commandIndex); if (m.match && m.pathIndex < segmentGroup.segments.length) { var /** @type {?} */ g = new UrlSegmentGroup(segmentGroup.segments.slice(0, m.pathIndex), {}); g.children[PRIMARY_OUTLET] = new UrlSegmentGroup(segmentGroup.segments.slice(m.pathIndex), segmentGroup.children); return updateSegmentGroupChildren(g, 0, slicedCommands); } else if (m.match && slicedCommands.length === 0) { return new UrlSegmentGroup(segmentGroup.segments, {}); } else if (m.match && !segmentGroup.hasChildren()) { return createNewSegmentGroup(segmentGroup, startIndex, commands); } else if (m.match) { return updateSegmentGroupChildren(segmentGroup, 0, slicedCommands); } else { return createNewSegmentGroup(segmentGroup, startIndex, commands); } } /** * @param {?} segmentGroup * @param {?} startIndex * @param {?} commands * @return {?} */ function updateSegmentGroupChildren(segmentGroup, startIndex, commands) { if (commands.length === 0) { return new UrlSegmentGroup(segmentGroup.segments, {}); } else { var /** @type {?} */ outlets_2 = getOutlets(commands); var /** @type {?} */ children_2 = {}; forEach(outlets_2, function (commands, outlet) { if (commands !== null) { children_2[outlet] = updateSegmentGroup(segmentGroup.children[outlet], startIndex, commands); } }); forEach(segmentGroup.children, function (child, childOutlet) { if (outlets_2[childOutlet] === undefined) { children_2[childOutlet] = child; } }); return new UrlSegmentGroup(segmentGroup.segments, children_2); } } /** * @param {?} segmentGroup * @param {?} startIndex * @param {?} commands * @return {?} */ function prefixedWith(segmentGroup, startIndex, commands) { var /** @type {?} */ currentCommandIndex = 0; var /** @type {?} */ currentPathIndex = startIndex; var /** @type {?} */ noMatch = { match: false, pathIndex: 0, commandIndex: 0 }; while (currentPathIndex < segmentGroup.segments.length) { if (currentCommandIndex >= commands.length) return noMatch; var /** @type {?} */ path = segmentGroup.segments[currentPathIndex]; var /** @type {?} */ curr = getPath(commands[currentCommandIndex]); var /** @type {?} */ next = currentCommandIndex < commands.length - 1 ? commands[currentCommandIndex + 1] : null; if (currentPathIndex > 0 && curr === undefined) break; if (curr && next && (typeof next === 'object') && next.outlets === undefined) { if (!compare(curr, next, path)) return noMatch; currentCommandIndex += 2; } else { if (!compare(curr, {}, path)) return noMatch; currentCommandIndex++; } currentPathIndex++; } return { match: true, pathIndex: currentPathIndex, commandIndex: currentCommandIndex }; } /** * @param {?} segmentGroup * @param {?} startIndex * @param {?} commands * @return {?} */ function createNewSegmentGroup(segmentGroup, startIndex, commands) { var /** @type {?} */ paths = segmentGroup.segments.slice(0, startIndex); var /** @type {?} */ i = 0; while (i < commands.length) { if (typeof commands[i] === 'object' && commands[i].outlets !== undefined) { var /** @type {?} */ children = createNewSegmentChildren(commands[i].outlets); return new UrlSegmentGroup(paths, children); } // if we start with an object literal, we need to reuse the path part from the segment if (i === 0 && isMatrixParams(commands[0])) { var /** @type {?} */ p = segmentGroup.segments[startIndex]; paths.push(new UrlSegment(p.path, commands[0])); i++; continue; } var /** @type {?} */ curr = getPath(commands[i]); var /** @type {?} */ next = (i < commands.length - 1) ? commands[i + 1] : null; if (curr && next && isMatrixParams(next)) { paths.push(new UrlSegment(curr, stringify(next))); i += 2; } else { paths.push(new UrlSegment(curr, {})); i++; } } return new UrlSegmentGroup(paths, {}); } /** * @param {?} outlets * @return {?} */ function createNewSegmentChildren(outlets) { var /** @type {?} */ children = {}; forEach(outlets, function (commands, outlet) { if (commands !== null) { children[outlet] = createNewSegmentGroup(new UrlSegmentGroup([], {}), 0, commands); } }); return children; } /** * @param {?} params * @return {?} */ function stringify(params) { var /** @type {?} */ res = {}; forEach(params, function (v, k) { return res[k] = "" + v; }); return res; } /** * @param {?} path * @param {?} params * @param {?} segment * @return {?} */ function compare(path, params, segment) { return path == segment.path && shallowEqual(params, segment.parameters); } /** * @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 */ var NoMatch$1 = (function () { function NoMatch$1() { } return NoMatch$1; }()); /** * @param {?} rootComponentType * @param {?} config * @param {?} urlTree * @param {?} url * @return {?} */ function recognize(rootComponentType, config, urlTree, url) { return new Recognizer(rootComponentType, config, urlTree, url).recognize(); } var Recognizer = (function () { /** * @param {?} rootComponentType * @param {?} config * @param {?} urlTree * @param {?} url */ function Recognizer(rootComponentType, config, urlTree, url) { this.rootComponentType = rootComponentType; this.config = config; this.urlTree = urlTree; this.url = url; } /** * @return {?} */ Recognizer.prototype.recognize = function () { try { var /** @type {?} */ rootSegmentGroup = split$1(this.urlTree.root, [], [], this.config).segmentGroup; var /** @type {?} */ children = this.processSegmentGroup(this.config, rootSegmentGroup, PRIMARY_OUTLET); var /** @type {?} */ root = new ActivatedRouteSnapshot([], Object.freeze({}), Object.freeze(this.urlTree.queryParams), /** @type {?} */ ((this.urlTree.fragment)), {}, PRIMARY_OUTLET, this.rootComponentType, null, this.urlTree.root, -1, {}); var /** @type {?} */ rootNode = new TreeNode(root, children); var /** @type {?} */ routeState = new RouterStateSnapshot(this.url, rootNode); this.inheritParamsAndData(routeState._root); return rxjs_observable_of.of(routeState); } catch (e) { return new rxjs_Observable.Observable(function (obs) { return obs.error(e); }); } }; /** * @param {?} routeNode * @return {?} */ Recognizer.prototype.inheritParamsAndData = function (routeNode) { var _this = this; var /** @type {?} */ route = routeNode.value; var /** @type {?} */ i = inheritedParamsDataResolve(route); route.params = Object.freeze(i.params); route.data = Object.freeze(i.data); routeNode.children.forEach(function (n) { return _this.inheritParamsAndData(n); }); }; /** * @param {?} config * @param {?} segmentGroup * @param {?} outlet * @return {?} */ Recognizer.prototype.processSegmentGroup = function (config, segmentGroup, outlet) { if (segmentGroup.segments.length === 0 && segmentGroup.hasChildren()) { return this.processChildren(config, segmentGroup); } return this.processSegment(config, segmentGroup, segmentGroup.segments, outlet); }; /** * @param {?} config * @param {?} segmentGroup * @return {?} */ Recognizer.prototype.processChildren = function (config, segmentGroup) { var _this = this; var /** @type {?} */ children = mapChildrenIntoArray(segmentGroup, function (child, childOutlet) { return _this.processSegmentGroup(config, child, childOutlet); }); checkOutletNameUniqueness(children); sortActivatedRouteSnapshots(children); return children; }; /** * @param {?} config * @param {?} segmentGroup * @param {?} segments * @param {?} outlet * @return {?} */ Recognizer.prototype.processSegment = function (config, segmentGroup, segments, outlet) { for (var _i = 0, config_1 = config; _i < config_1.length; _i++) { var r = config_1[_i]; try { return this.processSegmentAgainstRoute(r, segmentGroup, segments, outlet); } catch (e) { if (!(e instanceof NoMatch$1)) throw e; } } if (this.noLeftoversInUrl(segmentGroup, segments, outlet)) { return []; } throw new NoMatch$1(); }; /** * @param {?} segmentGroup * @param {?} segments * @param {?} outlet * @return {?} */ Recognizer.prototype.noLeftoversInUrl = function (segmentGroup, segments, outlet) { return segments.length === 0 && !segmentGroup.children[outlet]; }; /** * @param {?} route * @param {?} rawSegment * @param {?} segments * @param {?} outlet * @return {?} */ Recognizer.prototype.processSegmentAgainstRoute = function (route, rawSegment, segments, outlet) { if (route.redirectTo) throw new NoMatch$1(); if ((route.outlet || PRIMARY_OUTLET) !== outlet) throw new NoMatch$1(); if (route.path === '**') { var /** @type {?} */ params = segments.length > 0 ? ((last$1(segments))).parameters : {}; var /** @type {?} */ snapshot_1 = new ActivatedRouteSnapshot(segments, params, Object.freeze(this.urlTree.queryParams), /** @type {?} */ ((this.urlTree.fragment)), getData(route), outlet, /** @type {?} */ ((route.component)), route, getSourceSegmentGroup(rawSegment), getPathIndexShift(rawSegment) + segments.length, getResolve(route)); return [new TreeNode(snapshot_1, [])]; } var _a = match$1(rawSegment, route, segments), consumedSegments = _a.consumedSegments, parameters = _a.parameters, lastChild = _a.lastChild; var /** @type {?} */ rawSlicedSegments = segments.slice(lastChild); var /** @type {?} */ childConfig = getChildConfig(route); var _b = split$1(rawSegment, consumedSegments, rawSlicedSegments, childConfig), segmentGroup = _b.segmentGroup, slicedSegments = _b.slicedSegments; var /** @type {?} */ snapshot = new ActivatedRouteSnapshot(consumedSegments, parameters, Object.freeze(this.urlTree.queryParams), /** @type {?} */ ((this.urlTree.fragment)), getData(route), outlet, /** @type {?} */ ((route.component)), route, getSourceSegmentGroup(rawSegment), getPathIndexShift(rawSegment) + consumedSegments.length, getResolve(route)); if (slicedSegments.length === 0 && segmentGroup.hasChildren()) { var /** @type {?} */ children_3 = this.processChildren(childConfig, segmentGroup); return [new TreeNode(snapshot, children_3)]; } if (childConfig.length === 0 && slicedSegments.length === 0) { return [new TreeNode(snapshot, [])]; } var /** @type {?} */ children = this.processSegment(childConfig, segmentGroup, slicedSegments, PRIMARY_OUTLET); return [new TreeNode(snapshot, children)]; }; return Recognizer; }()); /** * @param {?} nodes * @return {?} */ function sortActivatedRouteSnapshots(nodes) { nodes.sort(function (a, b) { if (a.value.outlet === PRIMARY_OUTLET) return -1; if (b.value.outlet === PRIMARY_OUTLET) return 1; return a.value.outlet.localeCompare(b.value.outlet); }); } /** * @param {?} route * @return {?} */ function getChildConfig(route) { if (route.children) { return route.children; } if (route.loadChildren) { return ((route._loadedConfig)).routes; } return []; } /** * @param {?} segmentGroup * @param {?} route * @param {?} segments * @return {?} */ function match$1(segmentGroup, route, segments) { if (route.path === '') { if (route.pathMatch === 'full' && (segmentGroup.hasChildren() || segments.length > 0)) { throw new NoMatch$1(); } return { consumedSegments: [], lastChild: 0, parameters: {} }; } var /** @type {?} */ matcher = route.matcher || defaultUrlMatcher; var /** @type {?} */ res = matcher(segments, segmentGroup, route); if (!res) throw new NoMatch$1(); var /** @type {?} */ posParams = {}; forEach(/** @type {?} */ ((res.posParams)), function (v, k) { posParams[k] = v.path; }); var /** @type {?} */ parameters = Object.assign({}, posParams, res.consumed[res.consumed.length - 1].parameters); return { consumedSegments: res.consumed, lastChild: res.consumed.length, parameters: parameters }; } /** * @param {?} nodes * @return {?} */ function checkOutletNameUniqueness(nodes) { var /** @type {?} */ names = {}; nodes.forEach(function (n) { var /** @type {?} */ routeWithSameOutletName = names[n.value.outlet]; if (routeWithSameOutletName) { var /** @type {?} */ p = routeWithSameOutletName.url.map(function (s) { return s.toString(); }).join('/'); var /** @type {?} */ c = n.value.url.map(function (s) { return s.toString(); }).join('/'); throw new Error("Two segments cannot have the same outlet name: '" + p + "' and '" + c + "'."); } names[n.value.outlet] = n.value; }); } /** * @param {?} segmentGroup * @return {?} */ function getSourceSegmentGroup(segmentGroup) { var /** @type {?} */ s = segmentGroup; while (s._sourceSegment) { s = s._sourceSegment; } return s; } /** * @param {?} segmentGroup * @return {?} */ function getPathIndexShift(segmentGroup) { var /** @type {?} */ s = segmentGroup; var /** @type {?} */ res = (s._segmentIndexShift ? s._segmentIndexShift : 0); while (s._sourceSegment) { s = s._sourceSegment; res += (s._segmentIndexShift ? s._segmentIndexShift : 0); } return res - 1; } /** * @param {?} segmentGroup * @param {?} consumedSegments * @param {?} slicedSegments * @param {?} config * @return {?} */ function split$1(segmentGroup, consumedSegments, slicedSegments, config) { if (slicedSegments.length > 0 && containsEmptyPathMatchesWithNamedOutlets(segmentGroup, slicedSegments, config)) { var /** @type {?} */ s_1 = new UrlSegmentGroup(consumedSegments, createChildrenForEmptyPaths(segmentGroup, consumedSegments, config, new UrlSegmentGroup(slicedSegments, segmentGroup.children))); s_1._sourceSegment = segmentGroup; s_1._segmentIndexShift = consumedSegments.length; return { segmentGroup: s_1, slicedSegments: [] }; } if (slicedSegments.length === 0 && containsEmptyPathMatches(segmentGroup, slicedSegments, config)) { var /** @type {?} */ s_2 = new UrlSegmentGroup(segmentGroup.segments, addEmptyPathsToChildrenIfNeeded(segmentGroup, slicedSegments, config, segmentGroup.children)); s_2._sourceSegment = segmentGroup; s_2._segmentIndexShift = consumedSegments.length; return { segmentGroup: s_2, slicedSegments: slicedSegments }; } var /** @type {?} */ s = new UrlSegmentGroup(segmentGroup.segments, segmentGroup.children); s._sourceSegment = segmentGroup; s._segmentIndexShift = consumedSegments.length; return { segmentGroup: s, slicedSegments: slicedSegments }; } /** * @param {?} segmentGroup * @param {?} slicedSegments * @param {?} routes * @param {?} children * @return {?} */ function addEmptyPathsToChildrenIfNeeded(segmentGroup, slicedSegments, routes, children) { var /** @type {?} */ res = {}; for (var _i = 0, routes_3 = routes; _i < routes_3.length; _i++) { var r = routes_3[_i]; if (emptyPathMatch(segmentGroup, slicedSegments, r) && !children[getOutlet$1(r)]) { var /** @type {?} */ s = new UrlSegmentGroup([], {}); s._sourceSegment = segmentGroup; s._segmentIndexShift = segmentGroup.segments.length; res[getOutlet$1(r)] = s; } } return Object.assign({}, children, res); } /** * @param {?} segmentGroup * @param {?} consumedSegments * @param {?} routes * @param {?} primarySegment * @return {?} */ function createChildrenForEmptyPaths(segmentGroup, consumedSegments, routes, primarySegment) { var /** @type {?} */ res = {}; res[PRIMARY_OUTLET] = primarySegment; primarySegment._sourceSegment = segmentGroup; primarySegment._segmentIndexShift = consumedSegments.length; for (var _i = 0, routes_4 = routes; _i < routes_4.length; _i++) { var r = routes_4[_i]; if (r.path === '' && getOutlet$1(r) !== PRIMARY_OUTLET) { var /** @type {?} */ s = new UrlSegmentGroup([], {}); s._sourceSegment = segmentGroup; s._segmentIndexShift = consumedSegments.length; res[getOutlet$1(r)] = s; } } return res; } /** * @param {?} segmentGroup * @param {?} slicedSegments * @param {?} routes * @return {?} */ function containsEmptyPathMatchesWithNamedOutlets(segmentGroup, slicedSegments, routes) { return routes.some(function (r) { return emptyPathMatch(segmentGroup, slicedSegments, r) && getOutlet$1(r) !== PRIMARY_OUTLET; }); } /** * @param {?} segmentGroup * @param {?} slicedSegments * @param {?} routes * @return {?} */ function containsEmptyPathMatches(segmentGroup, slicedSegments, routes) { return routes.some(function (r) { return emptyPathMatch(segmentGroup, slicedSegments, r); }); } /** * @param {?} segmentGroup * @param {?} slicedSegments * @param {?} r * @return {?} */ function emptyPathMatch(segmentGroup, slicedSegments, r) { if ((segmentGroup.hasChildren() || slicedSegments.length > 0) && r.pathMatch === 'full') { return false; } return r.path === '' && r.redirectTo === undefined; } /** * @param {?} route * @return {?} */ function getOutlet$1(route) { return route.outlet || PRIMARY_OUTLET; } /** * @param {?} route * @return {?} */ function getData(route) { return route.data || {}; } /** * @param {?} route * @return {?} */ function getResolve(route) { return route.resolve || {}; } /** * @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 */ /** * \@whatItDoes Provides a way to customize when activated routes get reused. * * \@experimental * @abstract */ var RouteReuseStrategy = (function () { function RouteReuseStrategy() { } /** * Determines if this route (and its subtree) should be detached to be reused later * @abstract * @param {?} route * @return {?} */ RouteReuseStrategy.prototype.shouldDetach = function (route) { }; /** * Stores the detached route. * * Storing a `null` value should erase the previously stored value. * @abstract * @param {?} route * @param {?} handle * @return {?} */ RouteReuseStrategy.prototype.store = function (route, handle) { }; /** * Determines if this route (and its subtree) should be reattached * @abstract * @param {?} route * @return {?} */ RouteReuseStrategy.prototype.shouldAttach = function (route) { }; /** * Retrieves the previously stored route * @abstract * @param {?} route * @return {?} */ RouteReuseStrategy.prototype.retrieve = function (route) { }; /** * Determines if a route should be reused * @abstract * @param {?} future * @param {?} curr * @return {?} */ RouteReuseStrategy.prototype.shouldReuseRoute = function (future, curr) { }; return RouteReuseStrategy; }()); /** * Does not detach any subtrees. Reuses routes as long as their route config is the same. */ var DefaultRouteReuseStrategy = (function () { function DefaultRouteReuseStrategy() { } /** * @param {?} route * @return {?} */ DefaultRouteReuseStrategy.prototype.shouldDetach = function (route) { return false; }; /** * @param {?} route * @param {?} detachedTree * @return {?} */ DefaultRouteReuseStrategy.prototype.store = function (route, detachedTree) { }; /** * @param {?} route * @return {?} */ DefaultRouteReuseStrategy.prototype.shouldAttach = function (route) { return false; }; /** * @param {?} route * @return {?} */ DefaultRouteReuseStrategy.prototype.retrieve = function (route) { return null; }; /** * @param {?} future * @param {?} curr * @return {?} */ DefaultRouteReuseStrategy.prototype.shouldReuseRoute = function (future, curr) { return future.routeConfig === curr.routeConfig; }; return DefaultRouteReuseStrategy; }()); /** * @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 */ /** * \@docsNotRequired * \@experimental */ var ROUTES = new _angular_core.InjectionToken('ROUTES'); var RouterConfigLoader = (function () { /** * @param {?} loader * @param {?} compiler * @param {?=} onLoadStartListener * @param {?=} onLoadEndListener */ function RouterConfigLoader(loader, compiler, onLoadStartListener, onLoadEndListener) { this.loader = loader; this.compiler = compiler; this.onLoadStartListener = onLoadStartListener; this.onLoadEndListener = onLoadEndListener; } /** * @param {?} parentInjector * @param {?} route * @return {?} */ RouterConfigLoader.prototype.load = function (parentInjector, route) { var _this = this; if (this.onLoadStartListener) { this.onLoadStartListener(route); } var /** @type {?} */ moduleFactory$ = this.loadModuleFactory(/** @type {?} */ ((route.loadChildren))); return rxjs_operator_map.map.call(moduleFactory$, function (factory) { if (_this.onLoadEndListener) { _this.onLoadEndListener(route); } var /** @type {?} */ module = factory.create(parentInjector); return new LoadedRouterConfig(flatten(module.injector.get(ROUTES)), module); }); }; /** * @param {?} loadChildren * @return {?} */ RouterConfigLoader.prototype.loadModuleFactory = function (loadChildren) { var _this = this; if (typeof loadChildren === 'string') { return rxjs_observable_fromPromise.fromPromise(this.loader.load(loadChildren)); } else { return rxjs_operator_mergeMap.mergeMap.call(wrapIntoObservable(loadChildren()), function (t) { if (t instanceof _angular_core.NgModuleFactory) { return rxjs_observable_of.of(t); } else { return rxjs_observable_fromPromise.fromPromise(_this.compiler.compileModuleAsync(t)); } }); } }; return RouterConfigLoader; }()); /** * @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 */ /** * \@whatItDoes Provides a way to migrate AngularJS applications to Angular. * * \@experimental * @abstract */ var UrlHandlingStrategy = (function () { function UrlHandlingStrategy() { } /** * Tells the router if this URL should be processed. * * When it returns true, the router will execute the regular navigation. * When it returns false, the router will set the router state to an empty state. * As a result, all the active components will be destroyed. * * @abstract * @param {?} url * @return {?} */ UrlHandlingStrategy.prototype.shouldProcessUrl = function (url) { }; /** * Extracts the part of the URL that should be handled by the router. * The rest of the URL will remain untouched. * @abstract * @param {?} url * @return {?} */ UrlHandlingStrategy.prototype.extract = function (url) { }; /** * Merges the URL fragment with the rest of the URL. * @abstract * @param {?} newUrlPart * @param {?} rawUrl * @return {?} */ UrlHandlingStrategy.prototype.merge = function (newUrlPart, rawUrl) { }; return UrlHandlingStrategy; }()); /** * \@experimental */ var DefaultUrlHandlingStrategy = (function () { function DefaultUrlHandlingStrategy() { } /** * @param {?} url * @return {?} */ DefaultUrlHandlingStrategy.prototype.shouldProcessUrl = function (url) { return true; }; /** * @param {?} url * @return {?} */ DefaultUrlHandlingStrategy.prototype.extract = function (url) { return url; }; /** * @param {?} newUrlPart * @param {?} wholeUrl * @return {?} */ DefaultUrlHandlingStrategy.prototype.merge = function (newUrlPart, wholeUrl) { return newUrlPart; }; return DefaultUrlHandlingStrategy; }()); /** * @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 */ /** * @param {?} error * @return {?} */ function defaultErrorHandler(error) { throw error; } /** * \@internal * @param {?} snapshot * @return {?} */ function defaultRouterHook(snapshot) { return (rxjs_observable_of.of(null)); } /** * \@whatItDoes Provides the navigation and url manipulation capabilities. * * See {\@link Routes} for more details and examples. * * \@ngModule RouterModule * * \@stable */ var Router = (function () { /** * @param {?} rootComponentType * @param {?} urlSerializer * @param {?} rootContexts * @param {?} location * @param {?} injector * @param {?} loader * @param {?} compiler * @param {?} config */ function Router(rootComponentType, urlSerializer, rootContexts, location, injector, loader, compiler, config) { var _this = this; this.rootComponentType = rootComponentType; this.urlSerializer = urlSerializer; this.rootContexts = rootContexts; this.location = location; this.config = config; this.navigations = new rxjs_BehaviorSubject.BehaviorSubject(/** @type {?} */ ((null))); this.routerEvents = new rxjs_Subject.Subject(); this.navigationId = 0; /** * Error handler that is invoked when a navigation errors. * * See {\@link ErrorHandler} for more information. */ this.errorHandler = defaultErrorHandler; /** * Indicates if at least one navigation happened. */ this.navigated = false; /** * Used by RouterModule. This allows us to * pause the navigation either before preactivation or after it. * \@internal */ this.hooks = { beforePreactivation: defaultRouterHook, afterPreactivation: defaultRouterHook }; /** * Extracts and merges URLs. Used for AngularJS to Angular migrations. */ this.urlHandlingStrategy = new DefaultUrlHandlingStrategy(); this.routeReuseStrategy = new DefaultRouteReuseStrategy(); var onLoadStart = function (r) { return _this.triggerEvent(new RouteConfigLoadStart(r)); }; var onLoadEnd = function (r) { return _this.triggerEvent(new RouteConfigLoadEnd(r)); }; this.ngModule = injector.get(_angular_core.NgModuleRef); this.resetConfig(config); this.currentUrlTree = createEmptyUrlTree(); this.rawUrlTree = this.currentUrlTree; this.configLoader = new RouterConfigLoader(loader, compiler, onLoadStart, onLoadEnd); this.currentRouterState = createEmptyState(this.currentUrlTree, this.rootComponentType); this.processNavigations(); } /** * \@internal * TODO: this should be removed once the constructor of the router made internal * @param {?} rootComponentType * @return {?} */ Router.prototype.resetRootComponentType = function (rootComponentType) { this.rootComponentType = rootComponentType; // TODO: vsavkin router 4.0 should make the root component set to null // this will simplify the lifecycle of the router. this.currentRouterState.root.component = this.rootComponentType; }; /** * Sets up the location change listener and performs the initial navigation. * @return {?} */ Router.prototype.initialNavigation = function () { this.setUpLocationChangeListener(); if (this.navigationId === 0) { this.navigateByUrl(this.location.path(true), { replaceUrl: true }); } }; /** * Sets up the location change listener. * @return {?} */ Router.prototype.setUpLocationChangeListener = function () { var _this = this; // Zone.current.wrap is needed because of the issue with RxJS scheduler, // which does not work properly with zone.js in IE and Safari if (!this.locationSubscription) { this.locationSubscription = (this.location.subscribe(Zone.current.wrap(function (change) { var /** @type {?} */ rawUrlTree = _this.urlSerializer.parse(change['url']); var /** @type {?} */ source = change['type'] === 'popstate' ? 'popstate' : 'hashchange'; setTimeout(function () { _this.scheduleNavigation(rawUrlTree, source, { replaceUrl: true }); }, 0); }))); } }; Object.defineProperty(Router.prototype, "routerState", { /** * The current route state * @return {?} */ get: function () { return this.currentRouterState; }, enumerable: true, configurable: true }); Object.defineProperty(Router.prototype, "url", { /** * The current url * @return {?} */ get: function () { return this.serializeUrl(this.currentUrlTree); }, enumerable: true, configurable: true }); Object.defineProperty(Router.prototype, "events", { /** * An observable of router events * @return {?} */ get: function () { return this.routerEvents; }, enumerable: true, configurable: true }); /** * \@internal * @param {?} e * @return {?} */ Router.prototype.triggerEvent = function (e) { this.routerEvents.next(e); }; /** * Resets the configuration used for navigation and generating links. * * ### Usage * * ``` * router.resetConfig([ * { path: 'team/:id', component: TeamCmp, children: [ * { path: 'simple', component: SimpleCmp }, * { path: 'user/:name', component: UserCmp } * ]} * ]); * ``` * @param {?} config * @return {?} */ Router.prototype.resetConfig = function (config) { validateConfig(config); this.config = config; }; /** * \@docsNotRequired * @return {?} */ Router.prototype.ngOnDestroy = function () { this.dispose(); }; /** * Disposes of the router * @return {?} */ Router.prototype.dispose = function () { if (this.locationSubscription) { this.locationSubscription.unsubscribe(); this.locationSubscription = ((null)); } }; /** * Applies an array of commands to the current url tree and creates a new url tree. * * When given an activate route, applies the given commands starting from the route. * When not given a route, applies the given command starting from the root. * * ### Usage * * ``` * // create /team/33/user/11 * router.createUrlTree(['/team', 33, 'user', 11]); * * // create /team/33;expand=true/user/11 * router.createUrlTree(['/team', 33, {expand: true}, 'user', 11]); * * // you can collapse static segments like this (this works only with the first passed-in value): * router.createUrlTree(['/team/33/user', userId]); * * // If the first segment can contain slashes, and you do not want the router to split it, you * // can do the following: * * router.createUrlTree([{segmentPath: '/one/two'}]); * * // create /team/33/(user/11//right:chat) * router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: 'chat'}}]); * * // remove the right secondary node * router.createUrlTree(['/team', 33, {outlets: {primary: 'user/11', right: null}}]); * * // assuming the current url is `/team/33/user/11` and the route points to `user/11` * * // navigate to /team/33/user/11/details * router.createUrlTree(['details'], {relativeTo: route}); * * // navigate to /team/33/user/22 * router.createUrlTree(['../22'], {relativeTo: route}); * * // navigate to /team/44/user/22 * router.createUrlTree(['../../team/44/user/22'], {relativeTo: route}); * ``` * @param {?} commands * @param {?=} navigationExtras * @return {?} */ Router.prototype.createUrlTree = function (commands, navigationExtras) { if (navigationExtras === void 0) { navigationExtras = {}; } var relativeTo = navigationExtras.relativeTo, queryParams = navigationExtras.queryParams, fragment = navigationExtras.fragment, preserveQueryParams = navigationExtras.preserveQueryParams, queryParamsHandling = navigationExtras.queryParamsHandling, preserveFragment = navigationExtras.preserveFragment; if (_angular_core.isDevMode() && preserveQueryParams && (console) && (console.warn)) { console.warn('preserveQueryParams is deprecated, use queryParamsHandling instead.'); } var /** @type {?} */ a = relativeTo || this.routerState.root; var /** @type {?} */ f = preserveFragment ? this.currentUrlTree.fragment : fragment; var /** @type {?} */ q = null; if (queryParamsHandling) { switch (queryParamsHandling) { case 'merge': q = Object.assign({}, this.currentUrlTree.queryParams, queryParams); break; case 'preserve': q = this.currentUrlTree.queryParams; break; default: q = queryParams || null; } } else { q = preserveQueryParams ? this.currentUrlTree.queryParams : queryParams || null; } return createUrlTree(a, this.currentUrlTree, commands, /** @type {?} */ ((q)), /** @type {?} */ ((f))); }; /** * Navigate based on the provided url. This navigation is always absolute. * * Returns a promise that: * - resolves to 'true' when navigation succeeds, * - resolves to 'false' when navigation fails, * - is rejected when an error happens. * * ### Usage * * ``` * router.navigateByUrl("/team/33/user/11"); * * // Navigate without updating the URL * router.navigateByUrl("/team/33/user/11", { skipLocationChange: true }); * ``` * * In opposite to `navigate`, `navigateByUrl` takes a whole URL * and does not apply any delta to the current one. * @param {?} url * @param {?=} extras * @return {?} */ Router.prototype.navigateByUrl = function (url, extras) { if (extras === void 0) { extras = { skipLocationChange: false }; } var /** @type {?} */ urlTree = url instanceof UrlTree ? url : this.parseUrl(url); var /** @type {?} */ mergedTree = this.urlHandlingStrategy.merge(urlTree, this.rawUrlTree); return this.scheduleNavigation(mergedTree, 'imperative', extras); }; /** * Navigate based on the provided array of commands and a starting point. * If no starting route is provided, the navigation is absolute. * * Returns a promise that: * - resolves to 'true' when navigation succeeds, * - resolves to 'false' when navigation fails, * - is rejected when an error happens. * * ### Usage * * ``` * router.navigate(['team', 33, 'user', 11], {relativeTo: route}); * * // Navigate without updating the URL * router.navigate(['team', 33, 'user', 11], {relativeTo: route, skipLocationChange: true}); * ``` * * In opposite to `navigateByUrl`, `navigate` always takes a delta that is applied to the current * URL. * @param {?} commands * @param {?=} extras * @return {?} */ Router.prototype.navigate = function (commands, extras) { if (extras === void 0) { extras = { skipLocationChange: false }; } validateCommands(commands); if (typeof extras.queryParams === 'object' && extras.queryParams !== null) { extras.queryParams = this.removeEmptyProps(extras.queryParams); } return this.navigateByUrl(this.createUrlTree(commands, extras), extras); }; /** * Serializes a {\@link UrlTree} into a string * @param {?} url * @return {?} */ Router.prototype.serializeUrl = function (url) { return this.urlSerializer.serialize(url); }; /** * Parses a string into a {\@link UrlTree} * @param {?} url * @return {?} */ Router.prototype.parseUrl = function (url) { return this.urlSerializer.parse(url); }; /** * Returns whether the url is activated * @param {?} url * @param {?} exact * @return {?} */ Router.prototype.isActive = function (url, exact) { if (url instanceof UrlTree) { return containsTree(this.currentUrlTree, url, exact); } var /** @type {?} */ urlTree = this.urlSerializer.parse(url); return containsTree(this.currentUrlTree, urlTree, exact); }; /** * @param {?} params * @return {?} */ Router.prototype.removeEmptyProps = function (params) { return Object.keys(params).reduce(function (result, key) { var /** @type {?} */ value = params[key]; if (value !== null && value !== undefined) { result[key] = value; } return result; }, {}); }; /** * @return {?} */ Router.prototype.processNavigations = function () { var _this = this; rxjs_operator_concatMap.concatMap .call(this.navigations, function (nav) { if (nav) { _this.executeScheduledNavigation(nav); // a failed navigation should not stop the router from processing // further navigations => the catch return nav.promise.catch(function () { }); } else { return (rxjs_observable_of.of(null)); } }) .subscribe(function () { }); }; /** * @param {?} rawUrl * @param {?} source * @param {?} extras * @return {?} */ Router.prototype.scheduleNavigation = function (rawUrl, source, extras) { var /** @type {?} */ lastNavigation = this.navigations.value; // If the user triggers a navigation imperatively (e.g., by using navigateByUrl), // and that navigation results in 'replaceState' that leads to the same URL, // we should skip those. if (lastNavigation && source !== 'imperative' && lastNavigation.source === 'imperative' && lastNavigation.rawUrl.toString() === rawUrl.toString()) { return Promise.resolve(true); // return value is not used } // Because of a bug in IE and Edge, the location class fires two events (popstate and // hashchange) every single time. The second one should be ignored. Otherwise, the URL will // flicker. if (lastNavigation && source == 'hashchange' && lastNavigation.source === 'popstate' && lastNavigation.rawUrl.toString() === rawUrl.toString()) { return Promise.resolve(true); // return value is not used } var /** @type {?} */ resolve = null; var /** @type {?} */ reject = null; var /** @type {?} */ promise = new Promise(function (res, rej) { resolve = res; reject = rej; }); var /** @type {?} */ id = ++this.navigationId; this.navigations.next({ id: id, source: source, rawUrl: rawUrl, extras: extras, resolve: resolve, reject: reject, promise: promise }); // Make sure that the error is propagated even though `processNavigations` catch // handler does not rethrow return promise.catch(function (e) { return Promise.reject(e); }); }; /** * @param {?} __0 * @return {?} */ Router.prototype.executeScheduledNavigation = function (_a) { var _this = this; var id = _a.id, rawUrl = _a.rawUrl, extras = _a.extras, resolve = _a.resolve, reject = _a.reject; var /** @type {?} */ url = this.urlHandlingStrategy.extract(rawUrl); var /** @type {?} */ urlTransition = !this.navigated || url.toString() !== this.currentUrlTree.toString(); if (urlTransition && this.urlHandlingStrategy.shouldProcessUrl(rawUrl)) { this.routerEvents.next(new NavigationStart(id, this.serializeUrl(url))); Promise.resolve() .then(function (_) { return _this.runNavigate(url, rawUrl, !!extras.skipLocationChange, !!extras.replaceUrl, id, null); }) .then(resolve, reject); // we cannot process the current URL, but we could process the previous one => // we need to do some cleanup } else if (urlTransition && this.rawUrlTree && this.urlHandlingStrategy.shouldProcessUrl(this.rawUrlTree)) { this.routerEvents.next(new NavigationStart(id, this.serializeUrl(url))); Promise.resolve() .then(function (_) { return _this.runNavigate(url, rawUrl, false, false, id, createEmptyState(url, _this.rootComponentType).snapshot); }) .then(resolve, reject); } else { this.rawUrlTree = rawUrl; resolve(null); } }; /** * @param {?} url * @param {?} rawUrl * @param {?} shouldPreventPushState * @param {?} shouldReplaceUrl * @param {?} id * @param {?} precreatedState * @return {?} */ Router.prototype.runNavigate = function (url, rawUrl, shouldPreventPushState, shouldReplaceUrl, id, precreatedState) { var _this = this; if (id !== this.navigationId) { this.location.go(this.urlSerializer.serialize(this.currentUrlTree)); this.routerEvents.next(new NavigationCancel(id, this.serializeUrl(url), "Navigation ID " + id + " is not equal to the current navigation id " + this.navigationId)); return Promise.resolve(false); } return new Promise(function (resolvePromise, rejectPromise) { // create an observable of the url and route state snapshot // this operation do not result in any side effects var /** @type {?} */ urlAndSnapshot$; if (!precreatedState) { var /** @type {?} */ moduleInjector = _this.ngModule.injector; var /** @type {?} */ redirectsApplied$ = applyRedirects(moduleInjector, _this.configLoader, _this.urlSerializer, url, _this.config); urlAndSnapshot$ = rxjs_operator_mergeMap.mergeMap.call(redirectsApplied$, function (appliedUrl) { return rxjs_operator_map.map.call(recognize(_this.rootComponentType, _this.config, appliedUrl, _this.serializeUrl(appliedUrl)), function (snapshot) { _this.routerEvents.next(new RoutesRecognized(id, _this.serializeUrl(url), _this.serializeUrl(appliedUrl), snapshot)); return { appliedUrl: appliedUrl, snapshot: snapshot }; }); }); } else { urlAndSnapshot$ = rxjs_observable_of.of({ appliedUrl: url, snapshot: precreatedState }); } var /** @type {?} */ beforePreactivationDone$ = rxjs_operator_mergeMap.mergeMap.call(urlAndSnapshot$, function (p) { return rxjs_operator_map.map.call(_this.hooks.beforePreactivation(p.snapshot), function () { return p; }); }); // run preactivation: guards and data resolvers var /** @type {?} */ preActivation; var /** @type {?} */ preactivationTraverse$ = rxjs_operator_map.map.call(beforePreactivationDone$, function (_a) { var appliedUrl = _a.appliedUrl, snapshot = _a.snapshot; var /** @type {?} */ moduleInjector = _this.ngModule.injector; preActivation = new PreActivation(snapshot, _this.currentRouterState.snapshot, moduleInjector); preActivation.traverse(_this.rootContexts); return { appliedUrl: appliedUrl, snapshot: snapshot }; }); var /** @type {?} */ preactivationCheckGuards$ = rxjs_operator_mergeMap.mergeMap.call(preactivationTraverse$, function (_a) { var appliedUrl = _a.appliedUrl, snapshot = _a.snapshot; if (_this.navigationId !== id) return rxjs_observable_of.of(false); return rxjs_operator_map.map.call(preActivation.checkGuards(), function (shouldActivate) { return { appliedUrl: appliedUrl, snapshot: snapshot, shouldActivate: shouldActivate }; }); }); var /** @type {?} */ preactivationResolveData$ = rxjs_operator_mergeMap.mergeMap.call(preactivationCheckGuards$, function (p) { if (_this.navigationId !== id) return rxjs_observable_of.of(false); if (p.shouldActivate) { return rxjs_operator_map.map.call(preActivation.resolveData(), function () { return p; }); } else { return rxjs_observable_of.of(p); } }); var /** @type {?} */ preactivationDone$ = rxjs_operator_mergeMap.mergeMap.call(preactivationResolveData$, function (p) { return rxjs_operator_map.map.call(_this.hooks.afterPreactivation(p.snapshot), function () { return p; }); }); // create router state // this operation has side effects => route state is being affected var /** @type {?} */ routerState$ = rxjs_operator_map.map.call(preactivationDone$, function (_a) { var appliedUrl = _a.appliedUrl, snapshot = _a.snapshot, shouldActivate = _a.shouldActivate; if (shouldActivate) { var /** @type {?} */ state = createRouterState(_this.routeReuseStrategy, snapshot, _this.currentRouterState); return { appliedUrl: appliedUrl, state: state, shouldActivate: shouldActivate }; } else { return { appliedUrl: appliedUrl, state: null, shouldActivate: shouldActivate }; } }); // applied the new router state // this operation has side effects var /** @type {?} */ navigationIsSuccessful; var /** @type {?} */ storedState = _this.currentRouterState; var /** @type {?} */ storedUrl = _this.currentUrlTree; routerState$ .forEach(function (_a) { var appliedUrl = _a.appliedUrl, state = _a.state, shouldActivate = _a.shouldActivate; if (!shouldActivate || id !== _this.navigationId) { navigationIsSuccessful = false; return; } _this.currentUrlTree = appliedUrl; _this.rawUrlTree = _this.urlHandlingStrategy.merge(_this.currentUrlTree, rawUrl); _this.currentRouterState = state; if (!shouldPreventPushState) { var /** @type {?} */ path = _this.urlSerializer.serialize(_this.rawUrlTree); if (_this.location.isCurrentPathEqualTo(path) || shouldReplaceUrl) { _this.location.replaceState(path); } else { _this.location.go(path); } } new ActivateRoutes(_this.routeReuseStrategy, state, storedState) .activate(_this.rootContexts); navigationIsSuccessful = true; }) .then(function () { if (navigationIsSuccessful) { _this.navigated = true; _this.routerEvents.next(new NavigationEnd(id, _this.serializeUrl(url), _this.serializeUrl(_this.currentUrlTree))); resolvePromise(true); } else { _this.resetUrlToCurrentUrlTree(); _this.routerEvents.next(new NavigationCancel(id, _this.serializeUrl(url), '')); resolvePromise(false); } }, function (e) { if (isNavigationCancelingError(e)) { _this.resetUrlToCurrentUrlTree(); _this.navigated = true; _this.routerEvents.next(new NavigationCancel(id, _this.serializeUrl(url), e.message)); resolvePromise(false); } else { _this.routerEvents.next(new NavigationError(id, _this.serializeUrl(url), e)); try { resolvePromise(_this.errorHandler(e)); } catch (ee) { rejectPromise(ee); } } _this.currentRouterState = storedState; _this.currentUrlTree = storedUrl; _this.rawUrlTree = _this.urlHandlingStrategy.merge(_this.currentUrlTree, rawUrl); _this.location.replaceState(_this.serializeUrl(_this.rawUrlTree)); }); }); }; /** * @return {?} */ Router.prototype.resetUrlToCurrentUrlTree = function () { var /** @type {?} */ path = this.urlSerializer.serialize(this.rawUrlTree); this.location.replaceState(path); }; return Router; }()); var CanActivate = (function () { /** * @param {?} path */ function CanActivate(path) { this.path = path; } Object.defineProperty(CanActivate.prototype, "route", { /** * @return {?} */ get: function () { return this.path[this.path.length - 1]; }, enumerable: true, configurable: true }); return CanActivate; }()); var CanDeactivate = (function () { /** * @param {?} component * @param {?} route */ function CanDeactivate(component, route) { this.component = component; this.route = route; } return CanDeactivate; }()); var PreActivation = (function () { /** * @param {?} future * @param {?} curr * @param {?} moduleInjector */ function PreActivation(future, curr, moduleInjector) { this.future = future; this.curr = curr; this.moduleInjector = moduleInjector; this.canActivateChecks = []; this.canDeactivateChecks = []; } /** * @param {?} parentContexts * @return {?} */ PreActivation.prototype.traverse = function (parentContexts) { var /** @type {?} */ futureRoot = this.future._root; var /** @type {?} */ currRoot = this.curr ? this.curr._root : null; this.traverseChildRoutes(futureRoot, currRoot, parentContexts, [futureRoot.value]); }; /** * @return {?} */ PreActivation.prototype.checkGuards = function () { var _this = this; if (this.canDeactivateChecks.length === 0 && this.canActivateChecks.length === 0) { return rxjs_observable_of.of(true); } var /** @type {?} */ canDeactivate$ = this.runCanDeactivateChecks(); return rxjs_operator_mergeMap.mergeMap.call(canDeactivate$, function (canDeactivate) { return canDeactivate ? _this.runCanActivateChecks() : rxjs_observable_of.of(false); }); }; /** * @return {?} */ PreActivation.prototype.resolveData = function () { var _this = this; if (this.canActivateChecks.length === 0) return rxjs_observable_of.of(null); var /** @type {?} */ checks$ = rxjs_observable_from.from(this.canActivateChecks); var /** @type {?} */ runningChecks$ = rxjs_operator_concatMap.concatMap.call(checks$, function (check) { return _this.runResolve(check.route); }); return rxjs_operator_reduce.reduce.call(runningChecks$, function (_, __) { return _; }); }; /** * @param {?} futureNode * @param {?} currNode * @param {?} contexts * @param {?} futurePath * @return {?} */ PreActivation.prototype.traverseChildRoutes = function (futureNode, currNode, contexts, futurePath) { var _this = this; var /** @type {?} */ prevChildren = nodeChildrenAsMap(currNode); // Process the children of the future route futureNode.children.forEach(function (c) { _this.traverseRoutes(c, prevChildren[c.value.outlet], contexts, futurePath.concat([c.value])); delete prevChildren[c.value.outlet]; }); // Process any children left from the current route (not active for the future route) forEach(prevChildren, function (v, k) { return _this.deactivateRouteAndItsChildren(v, /** @type {?} */ ((contexts)).getContext(k)); }); }; /** * @param {?} futureNode * @param {?} currNode * @param {?} parentContexts * @param {?} futurePath * @return {?} */ PreActivation.prototype.traverseRoutes = function (futureNode, currNode, parentContexts, futurePath) { var /** @type {?} */ future = futureNode.value; var /** @type {?} */ curr = currNode ? currNode.value : null; var /** @type {?} */ context = parentContexts ? parentContexts.getContext(futureNode.value.outlet) : null; // reusing the node if (curr && future._routeConfig === curr._routeConfig) { if (this.shouldRunGuardsAndResolvers(curr, future, /** @type {?} */ ((future._routeConfig)).runGuardsAndResolvers)) { this.canActivateChecks.push(new CanActivate(futurePath)); var /** @type {?} */ outlet = ((((context)).outlet)); this.canDeactivateChecks.push(new CanDeactivate(outlet.component, curr)); } else { // we need to set the data future.data = curr.data; future._resolvedData = curr._resolvedData; } // If we have a component, we need to go through an outlet. if (future.component) { this.traverseChildRoutes(futureNode, currNode, context ? context.children : null, futurePath); // if we have a componentless route, we recurse but keep the same outlet map. } else { this.traverseChildRoutes(futureNode, currNode, parentContexts, futurePath); } } else { if (curr) { this.deactivateRouteAndItsChildren(currNode, context); } this.canActivateChecks.push(new CanActivate(futurePath)); // If we have a component, we need to go through an outlet. if (future.component) { this.traverseChildRoutes(futureNode, null, context ? context.children : null, futurePath); // if we have a componentless route, we recurse but keep the same outlet map. } else { this.traverseChildRoutes(futureNode, null, parentContexts, futurePath); } } }; /** * @param {?} curr * @param {?} future * @param {?} mode * @return {?} */ PreActivation.prototype.shouldRunGuardsAndResolvers = function (curr, future, mode) { switch (mode) { case 'always': return true; case 'paramsOrQueryParamsChange': return !equalParamsAndUrlSegments(curr, future) || !shallowEqual(curr.queryParams, future.queryParams); case 'paramsChange': default: return !equalParamsAndUrlSegments(curr, future); } }; /** * @param {?} route * @param {?} context * @return {?} */ PreActivation.prototype.deactivateRouteAndItsChildren = function (route, context) { var _this = this; var /** @type {?} */ children = nodeChildrenAsMap(route); var /** @type {?} */ r = route.value; forEach(children, function (node, childName) { if (!r.component) { _this.deactivateRouteAndItsChildren(node, context); } else if (context) { _this.deactivateRouteAndItsChildren(node, context.children.getContext(childName)); } else { _this.deactivateRouteAndItsChildren(node, null); } }); if (!r.component) { this.canDeactivateChecks.push(new CanDeactivate(null, r)); } else if (context && context.outlet && context.outlet.isActivated) { this.canDeactivateChecks.push(new CanDeactivate(context.outlet.component, r)); } else { this.canDeactivateChecks.push(new CanDeactivate(null, r)); } }; /** * @return {?} */ PreActivation.prototype.runCanDeactivateChecks = function () { var _this = this; var /** @type {?} */ checks$ = rxjs_observable_from.from(this.canDeactivateChecks); var /** @type {?} */ runningChecks$ = rxjs_operator_mergeMap.mergeMap.call(checks$, function (check) { return _this.runCanDeactivate(check.component, check.route); }); return rxjs_operator_every.every.call(runningChecks$, function (result) { return result === true; }); }; /** * @return {?} */ PreActivation.prototype.runCanActivateChecks = function () { var _this = this; var /** @type {?} */ checks$ = rxjs_observable_from.from(this.canActivateChecks); var /** @type {?} */ runningChecks$ = rxjs_operator_mergeMap.mergeMap.call(checks$, function (check) { return andObservables(rxjs_observable_from.from([_this.runCanActivateChild(check.path), _this.runCanActivate(check.route)])); }); return rxjs_operator_every.every.call(runningChecks$, function (result) { return result === true; }); }; /** * @param {?} future * @return {?} */ PreActivation.prototype.runCanActivate = function (future) { var _this = this; var /** @type {?} */ canActivate = future._routeConfig ? future._routeConfig.canActivate : null; if (!canActivate || canActivate.length === 0) return rxjs_observable_of.of(true); var /** @type {?} */ obs = rxjs_operator_map.map.call(rxjs_observable_from.from(canActivate), function (c) { var /** @type {?} */ guard = _this.getToken(c, future); var /** @type {?} */ observable; if (guard.canActivate) { observable = wrapIntoObservable(guard.canActivate(future, _this.future)); } else { observable = wrapIntoObservable(guard(future, _this.future)); } return rxjs_operator_first.first.call(observable); }); return andObservables(obs); }; /** * @param {?} path * @return {?} */ PreActivation.prototype.runCanActivateChild = function (path) { var _this = this; var /** @type {?} */ future = path[path.length - 1]; var /** @type {?} */ canActivateChildGuards = path.slice(0, path.length - 1) .reverse() .map(function (p) { return _this.extractCanActivateChild(p); }) .filter(function (_) { return _ !== null; }); return andObservables(rxjs_operator_map.map.call(rxjs_observable_from.from(canActivateChildGuards), function (d) { var /** @type {?} */ obs = rxjs_operator_map.map.call(rxjs_observable_from.from(d.guards), function (c) { var /** @type {?} */ guard = _this.getToken(c, d.node); var /** @type {?} */ observable; if (guard.canActivateChild) { observable = wrapIntoObservable(guard.canActivateChild(future, _this.future)); } else { observable = wrapIntoObservable(guard(future, _this.future)); } return rxjs_operator_first.first.call(observable); }); return andObservables(obs); })); }; /** * @param {?} p * @return {?} */ PreActivation.prototype.extractCanActivateChild = function (p) { var /** @type {?} */ canActivateChild = p._routeConfig ? p._routeConfig.canActivateChild : null; if (!canActivateChild || canActivateChild.length === 0) return null; return { node: p, guards: canActivateChild }; }; /** * @param {?} component * @param {?} curr * @return {?} */ PreActivation.prototype.runCanDeactivate = function (component, curr) { var _this = this; var /** @type {?} */ canDeactivate = curr && curr._routeConfig ? curr._routeConfig.canDeactivate : null; if (!canDeactivate || canDeactivate.length === 0) return rxjs_observable_of.of(true); var /** @type {?} */ canDeactivate$ = rxjs_operator_mergeMap.mergeMap.call(rxjs_observable_from.from(canDeactivate), function (c) { var /** @type {?} */ guard = _this.getToken(c, curr); var /** @type {?} */ observable; if (guard.canDeactivate) { observable = wrapIntoObservable(guard.canDeactivate(component, curr, _this.curr, _this.future)); } else { observable = wrapIntoObservable(guard(component, curr, _this.curr, _this.future)); } return rxjs_operator_first.first.call(observable); }); return rxjs_operator_every.every.call(canDeactivate$, function (result) { return result === true; }); }; /** * @param {?} future * @return {?} */ PreActivation.prototype.runResolve = function (future) { var /** @type {?} */ resolve = future._resolve; return rxjs_operator_map.map.call(this.resolveNode(resolve, future), function (resolvedData) { future._resolvedData = resolvedData; future.data = Object.assign({}, future.data, inheritedParamsDataResolve(future).resolve); return null; }); }; /** * @param {?} resolve * @param {?} future * @return {?} */ PreActivation.prototype.resolveNode = function (resolve, future) { var _this = this; return waitForMap(resolve, function (k, v) { var /** @type {?} */ resolver = _this.getToken(v, future); return resolver.resolve ? wrapIntoObservable(resolver.resolve(future, _this.future)) : wrapIntoObservable(resolver(future, _this.future)); }); }; /** * @param {?} token * @param {?} snapshot * @return {?} */ PreActivation.prototype.getToken = function (token, snapshot) { var /** @type {?} */ config = closestLoadedConfig(snapshot); var /** @type {?} */ injector = config ? config.module.injector : this.moduleInjector; return injector.get(token); }; return PreActivation; }()); var ActivateRoutes = (function () { /** * @param {?} routeReuseStrategy * @param {?} futureState * @param {?} currState */ function ActivateRoutes(routeReuseStrategy, futureState, currState) { this.routeReuseStrategy = routeReuseStrategy; this.futureState = futureState; this.currState = currState; } /** * @param {?} parentContexts * @return {?} */ ActivateRoutes.prototype.activate = function (parentContexts) { var /** @type {?} */ futureRoot = this.futureState._root; var /** @type {?} */ currRoot = this.currState ? this.currState._root : null; this.deactivateChildRoutes(futureRoot, currRoot, parentContexts); advanceActivatedRoute(this.futureState.root); this.activateChildRoutes(futureRoot, currRoot, parentContexts); }; /** * @param {?} futureNode * @param {?} currNode * @param {?} contexts * @return {?} */ ActivateRoutes.prototype.deactivateChildRoutes = function (futureNode, currNode, contexts) { var _this = this; var /** @type {?} */ children = nodeChildrenAsMap(currNode); // Recurse on the routes active in the future state to de-activate deeper children futureNode.children.forEach(function (futureChild) { var /** @type {?} */ childOutletName = futureChild.value.outlet; _this.deactivateRoutes(futureChild, children[childOutletName], contexts); delete children[childOutletName]; }); // De-activate the routes that will not be re-used forEach(children, function (v, childName) { _this.deactivateRouteAndItsChildren(v, contexts); }); }; /** * @param {?} futureNode * @param {?} currNode * @param {?} parentContext * @return {?} */ ActivateRoutes.prototype.deactivateRoutes = function (futureNode, currNode, parentContext) { var /** @type {?} */ future = futureNode.value; var /** @type {?} */ curr = currNode ? currNode.value : null; if (future === curr) { // Reusing the node, check to see if the children need to be de-activated if (future.component) { // If we have a normal route, we need to go through an outlet. var /** @type {?} */ context = parentContext.getContext(future.outlet); if (context) { this.deactivateChildRoutes(futureNode, currNode, context.children); } } else { // if we have a componentless route, we recurse but keep the same outlet map. this.deactivateChildRoutes(futureNode, currNode, parentContext); } } else { if (curr) { // Deactivate the current route which will not be re-used this.deactivateRouteAndItsChildren(currNode, parentContext); } } }; /** * @param {?} route * @param {?} parentContexts * @return {?} */ ActivateRoutes.prototype.deactivateRouteAndItsChildren = function (route, parentContexts) { if (this.routeReuseStrategy.shouldDetach(route.value.snapshot)) { this.detachAndStoreRouteSubtree(route, parentContexts); } else { this.deactivateRouteAndOutlet(route, parentContexts); } }; /** * @param {?} route * @param {?} parentContexts * @return {?} */ ActivateRoutes.prototype.detachAndStoreRouteSubtree = function (route, parentContexts) { var /** @type {?} */ context = parentContexts.getContext(route.value.outlet); if (context && context.outlet) { var /** @type {?} */ componentRef = context.outlet.detach(); var /** @type {?} */ contexts = context.children.onOutletDeactivated(); this.routeReuseStrategy.store(route.value.snapshot, { componentRef: componentRef, route: route, contexts: contexts }); } }; /** * @param {?} route * @param {?} parentContexts * @return {?} */ ActivateRoutes.prototype.deactivateRouteAndOutlet = function (route, parentContexts) { var _this = this; var /** @type {?} */ context = parentContexts.getContext(route.value.outlet); if (context) { var /** @type {?} */ children = nodeChildrenAsMap(route); var /** @type {?} */ contexts_1 = route.value.component ? context.children : parentContexts; forEach(children, function (v, k) { _this.deactivateRouteAndItsChildren(v, contexts_1); }); if (context.outlet) { // Destroy the component context.outlet.deactivate(); // Destroy the contexts for all the outlets that were in the component context.children.onOutletDeactivated(); } } }; /** * @param {?} futureNode * @param {?} currNode * @param {?} contexts * @return {?} */ ActivateRoutes.prototype.activateChildRoutes = function (futureNode, currNode, contexts) { var _this = this; var /** @type {?} */ children = nodeChildrenAsMap(currNode); futureNode.children.forEach(function (c) { _this.activateRoutes(c, children[c.value.outlet], contexts); }); }; /** * @param {?} futureNode * @param {?} currNode * @param {?} parentContexts * @return {?} */ ActivateRoutes.prototype.activateRoutes = function (futureNode, currNode, parentContexts) { var /** @type {?} */ future = futureNode.value; var /** @type {?} */ curr = currNode ? currNode.value : null; advanceActivatedRoute(future); // reusing the node if (future === curr) { if (future.component) { // If we have a normal route, we need to go through an outlet. var /** @type {?} */ context = parentContexts.getOrCreateContext(future.outlet); this.activateChildRoutes(futureNode, currNode, context.children); } else { // if we have a componentless route, we recurse but keep the same outlet map. this.activateChildRoutes(futureNode, currNode, parentContexts); } } else { if (future.component) { // if we have a normal route, we need to place the component into the outlet and recurse. var /** @type {?} */ context = parentContexts.getOrCreateContext(future.outlet); if (this.routeReuseStrategy.shouldAttach(future.snapshot)) { var /** @type {?} */ stored = ((this.routeReuseStrategy.retrieve(future.snapshot))); this.routeReuseStrategy.store(future.snapshot, null); context.children.onOutletReAttached(stored.contexts); context.attachRef = stored.componentRef; context.route = stored.route.value; if (context.outlet) { // Attach right away when the outlet has already been instantiated // Otherwise attach from `RouterOutlet.ngOnInit` when it is instantiated context.outlet.attach(stored.componentRef, stored.route.value); } advanceActivatedRouteNodeAndItsChildren(stored.route); } else { var /** @type {?} */ config = parentLoadedConfig(future.snapshot); var /** @type {?} */ cmpFactoryResolver = config ? config.module.componentFactoryResolver : null; context.route = future; context.resolver = cmpFactoryResolver; if (context.outlet) { // Activate the outlet when it has already been instantiated // Otherwise it will get activated from its `ngOnInit` when instantiated context.outlet.activateWith(future, cmpFactoryResolver); } this.activateChildRoutes(futureNode, null, context.children); } } else { // if we have a componentless route, we recurse but keep the same outlet map. this.activateChildRoutes(futureNode, null, parentContexts); } } }; return ActivateRoutes; }()); /** * @param {?} node * @return {?} */ function advanceActivatedRouteNodeAndItsChildren(node) { advanceActivatedRoute(node.value); node.children.forEach(advanceActivatedRouteNodeAndItsChildren); } /** * @param {?} snapshot * @return {?} */ function parentLoadedConfig(snapshot) { for (var /** @type {?} */ s = snapshot.parent; s; s = s.parent) { var /** @type {?} */ route = s._routeConfig; if (route && route._loadedConfig) return route._loadedConfig; if (route && route.component) return null; } return null; } /** * @param {?} snapshot * @return {?} */ function closestLoadedConfig(snapshot) { if (!snapshot) return null; for (var /** @type {?} */ s = snapshot.parent; s; s = s.parent) { var /** @type {?} */ route = s._routeConfig; if (route && route._loadedConfig) return route._loadedConfig; } return null; } /** * @template T * @param {?} node * @return {?} */ function nodeChildrenAsMap(node) { var /** @type {?} */ map$$1 = {}; if (node) { node.children.forEach(function (child) { return map$$1[child.value.outlet] = child; }); } return map$$1; } /** * @param {?} commands * @return {?} */ function validateCommands(commands) { for (var /** @type {?} */ i = 0; i < commands.length; i++) { var /** @type {?} */ cmd = commands[i]; if (cmd == null) { throw new Error("The requested path contains " + cmd + " segment at index " + i); } } } /** * @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 */ /** * \@whatItDoes Lets you link to specific parts of your app. * * \@howToUse * * Consider the following route configuration: * `[{ path: 'user/:name', component: UserCmp }]` * * When linking to this `user/:name` route, you can write: * `<a routerLink='/user/bob'>link to user component</a>` * * \@description * * The RouterLink directives let you link to specific parts of your app. * * When the link is static, you can use the directive as follows: * `<a routerLink="/user/bob">link to user component</a>` * * If you use dynamic values to generate the link, you can pass an array of path * segments, followed by the params for each segment. * * For instance `['/team', teamId, 'user', userName, {details: true}]` * means that we want to generate a link to `/team/11/user/bob;details=true`. * * Multiple static segments can be merged into one * (e.g., `['/team/11/user', userName, {details: true}]`). * * The first segment name can be prepended with `/`, `./`, or `../`: * * If the first segment begins with `/`, the router will look up the route from the root of the * app. * * If the first segment begins with `./`, or doesn't begin with a slash, the router will * instead look in the children of the current activated route. * * And if the first segment begins with `../`, the router will go up one level. * * You can set query params and fragment as follows: * * ``` * <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" fragment="education"> * link to user component * </a> * ``` * RouterLink will use these to generate this link: `/user/bob#education?debug=true`. * * (Deprecated in v4.0.0 use `queryParamsHandling` instead) You can also tell the * directive to preserve the current query params and fragment: * * ``` * <a [routerLink]="['/user/bob']" preserveQueryParams preserveFragment> * link to user component * </a> * ``` * * You can tell the directive to how to handle queryParams, available options are: * - 'merge' merge the queryParams into the current queryParams * - 'preserve' prserve the current queryParams * - default / '' use the queryParams only * same options for {\@link NavigationExtras#queryParamsHandling} * * ``` * <a [routerLink]="['/user/bob']" [queryParams]="{debug: true}" queryParamsHandling="merge"> * link to user component * </a> * ``` * * The router link directive always treats the provided input as a delta to the current url. * * For instance, if the current url is `/user/(box//aux:team)`. * * Then the following link `<a [routerLink]="['/user/jim']">Jim</a>` will generate the link * `/user/(jim//aux:team)`. * * \@ngModule RouterModule * * See {\@link Router#createUrlTree} for more information. * * \@stable */ var RouterLink = (function () { /** * @param {?} router * @param {?} route * @param {?} tabIndex * @param {?} renderer * @param {?} el */ function RouterLink(router, route, tabIndex, renderer, el) { this.router = router; this.route = route; this.commands = []; if (tabIndex == null) { renderer.setElementAttribute(el.nativeElement, 'tabindex', '0'); } } Object.defineProperty(RouterLink.prototype, "routerLink", { /** * @param {?} commands * @return {?} */ set: function (commands) { if (commands != null) { this.commands = Array.isArray(commands) ? commands : [commands]; } else { this.commands = []; } }, enumerable: true, configurable: true }); Object.defineProperty(RouterLink.prototype, "preserveQueryParams", { /** * @deprecated 4.0.0 use `queryParamsHandling` instead. * @param {?} value * @return {?} */ set: function (value) { if (_angular_core.isDevMode() && (console) && (console.warn)) { console.warn('preserveQueryParams is deprecated!, use queryParamsHandling instead.'); } this.preserve = value; }, enumerable: true, configurable: true }); /** * @return {?} */ RouterLink.prototype.onClick = function () { var /** @type {?} */ extras = { skipLocationChange: attrBoolValue(this.skipLocationChange), replaceUrl: attrBoolValue(this.replaceUrl), }; this.router.navigateByUrl(this.urlTree, extras); return true; }; Object.defineProperty(RouterLink.prototype, "urlTree", { /** * @return {?} */ get: function () { return this.router.createUrlTree(this.commands, { relativeTo: this.route, queryParams: this.queryParams, fragment: this.fragment, preserveQueryParams: attrBoolValue(this.preserve), queryParamsHandling: this.queryParamsHandling, preserveFragment: attrBoolValue(this.preserveFragment), }); }, enumerable: true, configurable: true }); return RouterLink; }()); RouterLink.decorators = [ { type: _angular_core.Directive, args: [{ selector: ':not(a)[routerLink]' },] }, ]; /** * @nocollapse */ RouterLink.ctorParameters = function () { return [ { type: Router, }, { type: ActivatedRoute, }, { type: undefined, decorators: [{ type: _angular_core.Attribute, args: ['tabindex',] },] }, { type: _angular_core.Renderer, }, { type: _angular_core.ElementRef, }, ]; }; RouterLink.propDecorators = { 'queryParams': [{ type: _angular_core.Input },], 'fragment': [{ type: _angular_core.Input },], 'queryParamsHandling': [{ type: _angular_core.Input },], 'preserveFragment': [{ type: _angular_core.Input },], 'skipLocationChange': [{ type: _angular_core.Input },], 'replaceUrl': [{ type: _angular_core.Input },], 'routerLink': [{ type: _angular_core.Input },], 'preserveQueryParams': [{ type: _angular_core.Input },], 'onClick': [{ type: _angular_core.HostListener, args: ['click',] },], }; /** * \@whatItDoes Lets you link to specific parts of your app. * * See {\@link RouterLink} for more information. * * \@ngModule RouterModule * * \@stable */ var RouterLinkWithHref = (function () { /** * @param {?} router * @param {?} route * @param {?} locationStrategy */ function RouterLinkWithHref(router, route, locationStrategy) { var _this = this; this.router = router; this.route = route; this.locationStrategy = locationStrategy; this.commands = []; this.subscription = router.events.subscribe(function (s) { if (s instanceof NavigationEnd) { _this.updateTargetUrlAndHref(); } }); } Object.defineProperty(RouterLinkWithHref.prototype, "routerLink", { /** * @param {?} commands * @return {?} */ set: function (commands) { if (commands != null) { this.commands = Array.isArray(commands) ? commands : [commands]; } else { this.commands = []; } }, enumerable: true, configurable: true }); Object.defineProperty(RouterLinkWithHref.prototype, "preserveQueryParams", { /** * @param {?} value * @return {?} */ set: function (value) { if (_angular_core.isDevMode() && (console) && (console.warn)) { console.warn('preserveQueryParams is deprecated, use queryParamsHandling instead.'); } this.preserve = value; }, enumerable: true, configurable: true }); /** * @param {?} changes * @return {?} */ RouterLinkWithHref.prototype.ngOnChanges = function (changes) { this.updateTargetUrlAndHref(); }; /** * @return {?} */ RouterLinkWithHref.prototype.ngOnDestroy = function () { this.subscription.unsubscribe(); }; /** * @param {?} button * @param {?} ctrlKey * @param {?} metaKey * @param {?} shiftKey * @return {?} */ RouterLinkWithHref.prototype.onClick = function (button, ctrlKey, metaKey, shiftKey) { if (button !== 0 || ctrlKey || metaKey || shiftKey) { return true; } if (typeof this.target === 'string' && this.target != '_self') { return true; } var /** @type {?} */ extras = { skipLocationChange: attrBoolValue(this.skipLocationChange), replaceUrl: attrBoolValue(this.replaceUrl), }; this.router.navigateByUrl(this.urlTree, extras); return false; }; /** * @return {?} */ RouterLinkWithHref.prototype.updateTargetUrlAndHref = function () { this.href = this.locationStrategy.prepareExternalUrl(this.router.serializeUrl(this.urlTree)); }; Object.defineProperty(RouterLinkWithHref.prototype, "urlTree", { /** * @return {?} */ get: function () { return this.router.createUrlTree(this.commands, { relativeTo: this.route, queryParams: this.queryParams, fragment: this.fragment, preserveQueryParams: attrBoolValue(this.preserve), queryParamsHandling: this.queryParamsHandling, preserveFragment: attrBoolValue(this.preserveFragment), }); }, enumerable: true, configurable: true }); return RouterLinkWithHref; }()); RouterLinkWithHref.decorators = [ { type: _angular_core.Directive, args: [{ selector: 'a[routerLink]' },] }, ]; /** * @nocollapse */ RouterLinkWithHref.ctorParameters = function () { return [ { type: Router, }, { type: ActivatedRoute, }, { type: _angular_common.LocationStrategy, }, ]; }; RouterLinkWithHref.propDecorators = { 'target': [{ type: _angular_core.HostBinding, args: ['attr.target',] }, { type: _angular_core.Input },], 'queryParams': [{ type: _angular_core.Input },], 'fragment': [{ type: _angular_core.Input },], 'queryParamsHandling': [{ type: _angular_core.Input },], 'preserveFragment': [{ type: _angular_core.Input },], 'skipLocationChange': [{ type: _angular_core.Input },], 'replaceUrl': [{ type: _angular_core.Input },], 'href': [{ type: _angular_core.HostBinding },], 'routerLink': [{ type: _angular_core.Input },], 'preserveQueryParams': [{ type: _angular_core.Input },], 'onClick': [{ type: _angular_core.HostListener, args: ['click', ['$event.button', '$event.ctrlKey', '$event.metaKey', '$event.shiftKey'],] },], }; /** * @param {?} s * @return {?} */ function attrBoolValue(s) { return s === '' || !!s; } /** * @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 */ /** * \@whatItDoes Lets you add a CSS class to an element when the link's route becomes active. * * \@howToUse * * ``` * <a routerLink="/user/bob" routerLinkActive="active-link">Bob</a> * ``` * * \@description * * The RouterLinkActive directive lets you add a CSS class to an element when the link's route * becomes active. * * Consider the following example: * * ``` * <a routerLink="/user/bob" routerLinkActive="active-link">Bob</a> * ``` * * When the url is either '/user' or '/user/bob', the active-link class will * be added to the `a` tag. If the url changes, the class will be removed. * * You can set more than one class, as follows: * * ``` * <a routerLink="/user/bob" routerLinkActive="class1 class2">Bob</a> * <a routerLink="/user/bob" [routerLinkActive]="['class1', 'class2']">Bob</a> * ``` * * You can configure RouterLinkActive by passing `exact: true`. This will add the classes * only when the url matches the link exactly. * * ``` * <a routerLink="/user/bob" routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: * true}">Bob</a> * ``` * * You can assign the RouterLinkActive instance to a template variable and directly check * the `isActive` status. * ``` * <a routerLink="/user/bob" routerLinkActive #rla="routerLinkActive"> * Bob {{ rla.isActive ? '(already open)' : ''}} * </a> * ``` * * Finally, you can apply the RouterLinkActive directive to an ancestor of a RouterLink. * * ``` * <div routerLinkActive="active-link" [routerLinkActiveOptions]="{exact: true}"> * <a routerLink="/user/jim">Jim</a> * <a routerLink="/user/bob">Bob</a> * </div> * ``` * * This will set the active-link class on the div tag if the url is either '/user/jim' or * '/user/bob'. * * \@ngModule RouterModule * * \@stable */ var RouterLinkActive = (function () { /** * @param {?} router * @param {?} element * @param {?} renderer * @param {?} cdr */ function RouterLinkActive(router, element, renderer, cdr) { var _this = this; this.router = router; this.element = element; this.renderer = renderer; this.cdr = cdr; this.classes = []; this.active = false; this.routerLinkActiveOptions = { exact: false }; this.subscription = router.events.subscribe(function (s) { if (s instanceof NavigationEnd) { _this.update(); } }); } Object.defineProperty(RouterLinkActive.prototype, "isActive", { /** * @return {?} */ get: function () { return this.active; }, enumerable: true, configurable: true }); /** * @return {?} */ RouterLinkActive.prototype.ngAfterContentInit = function () { var _this = this; this.links.changes.subscribe(function (_) { return _this.update(); }); this.linksWithHrefs.changes.subscribe(function (_) { return _this.update(); }); this.update(); }; Object.defineProperty(RouterLinkActive.prototype, "routerLinkActive", { /** * @param {?} data * @return {?} */ set: function (data) { var /** @type {?} */ classes = Array.isArray(data) ? data : data.split(' '); this.classes = classes.filter(function (c) { return !!c; }); }, enumerable: true, configurable: true }); /** * @param {?} changes * @return {?} */ RouterLinkActive.prototype.ngOnChanges = function (changes) { this.update(); }; /** * @return {?} */ RouterLinkActive.prototype.ngOnDestroy = function () { this.subscription.unsubscribe(); }; /** * @return {?} */ RouterLinkActive.prototype.update = function () { var _this = this; if (!this.links || !this.linksWithHrefs || !this.router.navigated) return; var /** @type {?} */ hasActiveLinks = this.hasActiveLinks(); // react only when status has changed to prevent unnecessary dom updates if (this.active !== hasActiveLinks) { this.classes.forEach(function (c) { return _this.renderer.setElementClass(_this.element.nativeElement, c, hasActiveLinks); }); Promise.resolve(hasActiveLinks).then(function (active) { return _this.active = active; }); } }; /** * @param {?} router * @return {?} */ RouterLinkActive.prototype.isLinkActive = function (router) { var _this = this; return function (link) { return router.isActive(link.urlTree, _this.routerLinkActiveOptions.exact); }; }; /** * @return {?} */ RouterLinkActive.prototype.hasActiveLinks = function () { return this.links.some(this.isLinkActive(this.router)) || this.linksWithHrefs.some(this.isLinkActive(this.router)); }; return RouterLinkActive; }()); RouterLinkActive.decorators = [ { type: _angular_core.Directive, args: [{ selector: '[routerLinkActive]', exportAs: 'routerLinkActive', },] }, ]; /** * @nocollapse */ RouterLinkActive.ctorParameters = function () { return [ { type: Router, }, { type: _angular_core.ElementRef, }, { type: _angular_core.Renderer, }, { type: _angular_core.ChangeDetectorRef, }, ]; }; RouterLinkActive.propDecorators = { 'links': [{ type: _angular_core.ContentChildren, args: [RouterLink, { descendants: true },] },], 'linksWithHrefs': [{ type: _angular_core.ContentChildren, args: [RouterLinkWithHref, { descendants: true },] },], 'routerLinkActiveOptions': [{ type: _angular_core.Input },], 'routerLinkActive': [{ type: _angular_core.Input },], }; /** * @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 */ /** * Store contextual information about a {\@link RouterOutlet} * * \@stable */ var OutletContext = (function () { function OutletContext() { this.outlet = null; this.route = null; this.resolver = null; this.children = new ChildrenOutletContexts(); this.attachRef = null; } return OutletContext; }()); /** * Store contextual information about the children (= nested) {\@link RouterOutlet} * * \@stable */ var ChildrenOutletContexts = (function () { function ChildrenOutletContexts() { this.contexts = new Map(); } /** * Called when a `RouterOutlet` directive is instantiated * @param {?} childName * @param {?} outlet * @return {?} */ ChildrenOutletContexts.prototype.onChildOutletCreated = function (childName, outlet) { var /** @type {?} */ context = this.getOrCreateContext(childName); context.outlet = outlet; this.contexts.set(childName, context); }; /** * Called when a `RouterOutlet` directive is destroyed. * We need to keep the context as the outlet could be destroyed inside a NgIf and might be * re-created later. * @param {?} childName * @return {?} */ ChildrenOutletContexts.prototype.onChildOutletDestroyed = function (childName) { var /** @type {?} */ context = this.getContext(childName); if (context) { context.outlet = null; } }; /** * Called when the corresponding route is deactivated during navigation. * Because the component get destroyed, all children outlet are destroyed. * @return {?} */ ChildrenOutletContexts.prototype.onOutletDeactivated = function () { var /** @type {?} */ contexts = this.contexts; this.contexts = new Map(); return contexts; }; /** * @param {?} contexts * @return {?} */ ChildrenOutletContexts.prototype.onOutletReAttached = function (contexts) { this.contexts = contexts; }; /** * @param {?} childName * @return {?} */ ChildrenOutletContexts.prototype.getOrCreateContext = function (childName) { var /** @type {?} */ context = this.getContext(childName); if (!context) { context = new OutletContext(); this.contexts.set(childName, context); } return context; }; /** * @param {?} childName * @return {?} */ ChildrenOutletContexts.prototype.getContext = function (childName) { return this.contexts.get(childName) || null; }; return ChildrenOutletContexts; }()); /** * @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 */ /** * \@whatItDoes Acts as a placeholder that Angular dynamically fills based on the current router * state. * * \@howToUse * * ``` * <router-outlet></router-outlet> * <router-outlet name='left'></router-outlet> * <router-outlet name='right'></router-outlet> * ``` * * A router outlet will emit an activate event any time a new component is being instantiated, * and a deactivate event when it is being destroyed. * * ``` * <router-outlet * (activate)='onActivate($event)' * (deactivate)='onDeactivate($event)'></router-outlet> * ``` * \@ngModule RouterModule * * \@stable */ var RouterOutlet = (function () { /** * @param {?} parentContexts * @param {?} location * @param {?} resolver * @param {?} name * @param {?} changeDetector */ function RouterOutlet(parentContexts, location, resolver, name, changeDetector) { this.parentContexts = parentContexts; this.location = location; this.resolver = resolver; this.changeDetector = changeDetector; this.activated = null; this._activatedRoute = null; this.activateEvents = new _angular_core.EventEmitter(); this.deactivateEvents = new _angular_core.EventEmitter(); this.name = name || PRIMARY_OUTLET; parentContexts.onChildOutletCreated(this.name, this); } /** * @return {?} */ RouterOutlet.prototype.ngOnDestroy = function () { this.parentContexts.onChildOutletDestroyed(this.name); }; /** * @return {?} */ RouterOutlet.prototype.ngOnInit = function () { if (!this.activated) { // If the outlet was not instantiated at the time the route got activated we need to populate // the outlet when it is initialized (ie inside a NgIf) var /** @type {?} */ context = this.parentContexts.getContext(this.name); if (context && context.route) { if (context.attachRef) { // `attachRef` is populated when there is an existing component to mount this.attach(context.attachRef, context.route); } else { // otherwise the component defined in the configuration is created this.activateWith(context.route, context.resolver || null); } } } }; Object.defineProperty(RouterOutlet.prototype, "locationInjector", { /** * @deprecated since v4 * * @return {?} */ get: function () { return this.location.injector; }, enumerable: true, configurable: true }); Object.defineProperty(RouterOutlet.prototype, "locationFactoryResolver", { /** * @deprecated since v4 * * @return {?} */ get: function () { return this.resolver; }, enumerable: true, configurable: true }); Object.defineProperty(RouterOutlet.prototype, "isActivated", { /** * @return {?} */ get: function () { return !!this.activated; }, enumerable: true, configurable: true }); Object.defineProperty(RouterOutlet.prototype, "component", { /** * @return {?} */ get: function () { if (!this.activated) throw new Error('Outlet is not activated'); return this.activated.instance; }, enumerable: true, configurable: true }); Object.defineProperty(RouterOutlet.prototype, "activatedRoute", { /** * @return {?} */ get: function () { if (!this.activated) throw new Error('Outlet is not activated'); return (this._activatedRoute); }, enumerable: true, configurable: true }); Object.defineProperty(RouterOutlet.prototype, "activatedRouteData", { /** * @return {?} */ get: function () { if (this._activatedRoute) { return this._activatedRoute.snapshot.data; } return {}; }, enumerable: true, configurable: true }); /** * Called when the `RouteReuseStrategy` instructs to detach the subtree * @return {?} */ RouterOutlet.prototype.detach = function () { if (!this.activated) throw new Error('Outlet is not activated'); this.location.detach(); var /** @type {?} */ cmp = this.activated; this.activated = null; this._activatedRoute = null; return cmp; }; /** * Called when the `RouteReuseStrategy` instructs to re-attach a previously detached subtree * @param {?} ref * @param {?} activatedRoute * @return {?} */ RouterOutlet.prototype.attach = function (ref, activatedRoute) { this.activated = ref; this._activatedRoute = activatedRoute; this.location.insert(ref.hostView); }; /** * @return {?} */ RouterOutlet.prototype.deactivate = function () { if (this.activated) { var /** @type {?} */ c = this.component; this.activated.destroy(); this.activated = null; this._activatedRoute = null; this.deactivateEvents.emit(c); } }; /** * @param {?} activatedRoute * @param {?} resolver * @return {?} */ RouterOutlet.prototype.activateWith = function (activatedRoute, resolver) { if (this.isActivated) { throw new Error('Cannot activate an already activated outlet'); } this._activatedRoute = activatedRoute; var /** @type {?} */ snapshot = activatedRoute._futureSnapshot; var /** @type {?} */ component = (((snapshot._routeConfig)).component); resolver = resolver || this.resolver; var /** @type {?} */ factory = resolver.resolveComponentFactory(component); var /** @type {?} */ childContexts = this.parentContexts.getOrCreateContext(this.name).children; var /** @type {?} */ injector = new OutletInjector(activatedRoute, childContexts, this.location.injector); this.activated = this.location.createComponent(factory, this.location.length, injector); // Calling `markForCheck` to make sure we will run the change detection when the // `RouterOutlet` is inside a `ChangeDetectionStrategy.OnPush` component. this.changeDetector.markForCheck(); this.activateEvents.emit(this.activated.instance); }; return RouterOutlet; }()); RouterOutlet.decorators = [ { type: _angular_core.Directive, args: [{ selector: 'router-outlet', exportAs: 'outlet' },] }, ]; /** * @nocollapse */ RouterOutlet.ctorParameters = function () { return [ { type: ChildrenOutletContexts, }, { type: _angular_core.ViewContainerRef, }, { type: _angular_core.ComponentFactoryResolver, }, { type: undefined, decorators: [{ type: _angular_core.Attribute, args: ['name',] },] }, { type: _angular_core.ChangeDetectorRef, }, ]; }; RouterOutlet.propDecorators = { 'activateEvents': [{ type: _angular_core.Output, args: ['activate',] },], 'deactivateEvents': [{ type: _angular_core.Output, args: ['deactivate',] },], }; var OutletInjector = (function () { /** * @param {?} route * @param {?} childContexts * @param {?} parent */ function OutletInjector(route, childContexts, parent) { this.route = route; this.childContexts = childContexts; this.parent = parent; } /** * @param {?} token * @param {?=} notFoundValue * @return {?} */ OutletInjector.prototype.get = function (token, notFoundValue) { if (token === ActivatedRoute) { return this.route; } if (token === ChildrenOutletContexts) { return this.childContexts; } return this.parent.get(token, notFoundValue); }; return OutletInjector; }()); /** *@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 */ /** * \@whatItDoes Provides a preloading strategy. * * \@experimental * @abstract */ var PreloadingStrategy = (function () { function PreloadingStrategy() { } /** * @abstract * @param {?} route * @param {?} fn * @return {?} */ PreloadingStrategy.prototype.preload = function (route, fn) { }; return PreloadingStrategy; }()); /** * \@whatItDoes Provides a preloading strategy that preloads all modules as quickly as possible. * * \@howToUse * * ``` * RouteModule.forRoot(ROUTES, {preloadingStrategy: PreloadAllModules}) * ``` * * \@experimental */ var PreloadAllModules = (function () { function PreloadAllModules() { } /** * @param {?} route * @param {?} fn * @return {?} */ PreloadAllModules.prototype.preload = function (route, fn) { return rxjs_operator_catch._catch.call(fn(), function () { return rxjs_observable_of.of(null); }); }; return PreloadAllModules; }()); /** * \@whatItDoes Provides a preloading strategy that does not preload any modules. * * \@description * * This strategy is enabled by default. * * \@experimental */ var NoPreloading = (function () { function NoPreloading() { } /** * @param {?} route * @param {?} fn * @return {?} */ NoPreloading.prototype.preload = function (route, fn) { return rxjs_observable_of.of(null); }; return NoPreloading; }()); /** * The preloader optimistically loads all router configurations to * make navigations into lazily-loaded sections of the application faster. * * The preloader runs in the background. When the router bootstraps, the preloader * starts listening to all navigation events. After every such event, the preloader * will check if any configurations can be loaded lazily. * * If a route is protected by `canLoad` guards, the preloaded will not load it. * * \@stable */ var RouterPreloader = (function () { /** * @param {?} router * @param {?} moduleLoader * @param {?} compiler * @param {?} injector * @param {?} preloadingStrategy */ function RouterPreloader(router, moduleLoader, compiler, injector, preloadingStrategy) { this.router = router; this.injector = injector; this.preloadingStrategy = preloadingStrategy; var onStartLoad = function (r) { return router.triggerEvent(new RouteConfigLoadStart(r)); }; var onEndLoad = function (r) { return router.triggerEvent(new RouteConfigLoadEnd(r)); }; this.loader = new RouterConfigLoader(moduleLoader, compiler, onStartLoad, onEndLoad); } /** * @return {?} */ RouterPreloader.prototype.setUpPreloading = function () { var _this = this; var /** @type {?} */ navigations$ = rxjs_operator_filter.filter.call(this.router.events, function (e) { return e instanceof NavigationEnd; }); this.subscription = rxjs_operator_concatMap.concatMap.call(navigations$, function () { return _this.preload(); }).subscribe(function () { }); }; /** * @return {?} */ RouterPreloader.prototype.preload = function () { var /** @type {?} */ ngModule = this.injector.get(_angular_core.NgModuleRef); return this.processRoutes(ngModule, this.router.config); }; /** * @return {?} */ RouterPreloader.prototype.ngOnDestroy = function () { this.subscription.unsubscribe(); }; /** * @param {?} ngModule * @param {?} routes * @return {?} */ RouterPreloader.prototype.processRoutes = function (ngModule, routes) { var /** @type {?} */ res = []; for (var _i = 0, routes_5 = routes; _i < routes_5.length; _i++) { var route = routes_5[_i]; // we already have the config loaded, just recurse if (route.loadChildren && !route.canLoad && route._loadedConfig) { var /** @type {?} */ childConfig = route._loadedConfig; res.push(this.processRoutes(childConfig.module, childConfig.routes)); // no config loaded, fetch the config } else if (route.loadChildren && !route.canLoad) { res.push(this.preloadConfig(ngModule, route)); // recurse into children } else if (route.children) { res.push(this.processRoutes(ngModule, route.children)); } } return rxjs_operator_mergeAll.mergeAll.call(rxjs_observable_from.from(res)); }; /** * @param {?} ngModule * @param {?} route * @return {?} */ RouterPreloader.prototype.preloadConfig = function (ngModule, route) { var _this = this; return this.preloadingStrategy.preload(route, function () { var /** @type {?} */ loaded$ = _this.loader.load(ngModule.injector, route); return rxjs_operator_mergeMap.mergeMap.call(loaded$, function (config) { route._loadedConfig = config; return _this.processRoutes(config.module, config.routes); }); }); }; return RouterPreloader; }()); RouterPreloader.decorators = [ { type: _angular_core.Injectable }, ]; /** * @nocollapse */ RouterPreloader.ctorParameters = function () { return [ { type: Router, }, { type: _angular_core.NgModuleFactoryLoader, }, { type: _angular_core.Compiler, }, { type: _angular_core.Injector, }, { type: PreloadingStrategy, }, ]; }; /** * @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 */ /** * \@whatItDoes Contains a list of directives * \@stable */ var ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkWithHref, RouterLinkActive]; /** * \@whatItDoes Is used in DI to configure the router. * \@stable */ var ROUTER_CONFIGURATION = new _angular_core.InjectionToken('ROUTER_CONFIGURATION'); /** * \@docsNotRequired */ var ROUTER_FORROOT_GUARD = new _angular_core.InjectionToken('ROUTER_FORROOT_GUARD'); var ROUTER_PROVIDERS = [ _angular_common.Location, { provide: UrlSerializer, useClass: DefaultUrlSerializer }, { provide: Router, useFactory: setupRouter, deps: [ _angular_core.ApplicationRef, UrlSerializer, ChildrenOutletContexts, _angular_common.Location, _angular_core.Injector, _angular_core.NgModuleFactoryLoader, _angular_core.Compiler, ROUTES, ROUTER_CONFIGURATION, [UrlHandlingStrategy, new _angular_core.Optional()], [RouteReuseStrategy, new _angular_core.Optional()] ] }, ChildrenOutletContexts, { provide: ActivatedRoute, useFactory: rootRoute, deps: [Router] }, { provide: _angular_core.NgModuleFactoryLoader, useClass: _angular_core.SystemJsNgModuleLoader }, RouterPreloader, NoPreloading, PreloadAllModules, { provide: ROUTER_CONFIGURATION, useValue: { enableTracing: false } }, ]; /** * @return {?} */ function routerNgProbeToken() { return new _angular_core.NgProbeToken('Router', Router); } /** * \@whatItDoes Adds router directives and providers. * * \@howToUse * * RouterModule can be imported multiple times: once per lazily-loaded bundle. * Since the router deals with a global shared resource--location, we cannot have * more than one router service active. * * That is why there are two ways to create the module: `RouterModule.forRoot` and * `RouterModule.forChild`. * * * `forRoot` creates a module that contains all the directives, the given routes, and the router * service itself. * * `forChild` creates a module that contains all the directives and the given routes, but does not * include the router service. * * When registered at the root, the module should be used as follows * * ``` * \@NgModule({ * imports: [RouterModule.forRoot(ROUTES)] * }) * class MyNgModule {} * ``` * * For submodules and lazy loaded submodules the module should be used as follows: * * ``` * \@NgModule({ * imports: [RouterModule.forChild(ROUTES)] * }) * class MyNgModule {} * ``` * * \@description * * Managing state transitions is one of the hardest parts of building applications. This is * especially true on the web, where you also need to ensure that the state is reflected in the URL. * In addition, we often want to split applications into multiple bundles and load them on demand. * Doing this transparently is not trivial. * * The Angular router solves these problems. Using the router, you can declaratively specify * application states, manage state transitions while taking care of the URL, and load bundles on * demand. * * [Read this developer guide](https://angular.io/docs/ts/latest/guide/router.html) to get an * overview of how the router should be used. * * \@stable */ var RouterModule = (function () { /** * @param {?} guard * @param {?} router */ function RouterModule(guard, router) { } /** * Creates a module with all the router providers and directives. It also optionally sets up an * application listener to perform an initial navigation. * * Options: * * `enableTracing` makes the router log all its internal events to the console. * * `useHash` enables the location strategy that uses the URL fragment instead of the history * API. * * `initialNavigation` disables the initial navigation. * * `errorHandler` provides a custom error handler. * @param {?} routes * @param {?=} config * @return {?} */ RouterModule.forRoot = function (routes, config) { return { ngModule: RouterModule, providers: [ ROUTER_PROVIDERS, provideRoutes(routes), { provide: ROUTER_FORROOT_GUARD, useFactory: provideForRootGuard, deps: [[Router, new _angular_core.Optional(), new _angular_core.SkipSelf()]] }, { provide: ROUTER_CONFIGURATION, useValue: config ? config : {} }, { provide: _angular_common.LocationStrategy, useFactory: provideLocationStrategy, deps: [ _angular_common.PlatformLocation, [new _angular_core.Inject(_angular_common.APP_BASE_HREF), new _angular_core.Optional()], ROUTER_CONFIGURATION ] }, { provide: PreloadingStrategy, useExisting: config && config.preloadingStrategy ? config.preloadingStrategy : NoPreloading }, { provide: _angular_core.NgProbeToken, multi: true, useFactory: routerNgProbeToken }, provideRouterInitializer(), ], }; }; /** * Creates a module with all the router directives and a provider registering routes. * @param {?} routes * @return {?} */ RouterModule.forChild = function (routes) { return { ngModule: RouterModule, providers: [provideRoutes(routes)] }; }; return RouterModule; }()); RouterModule.decorators = [ { type: _angular_core.NgModule, args: [{ declarations: ROUTER_DIRECTIVES, exports: ROUTER_DIRECTIVES },] }, ]; /** * @nocollapse */ RouterModule.ctorParameters = function () { return [ { type: undefined, decorators: [{ type: _angular_core.Optional }, { type: _angular_core.Inject, args: [ROUTER_FORROOT_GUARD,] },] }, { type: Router, decorators: [{ type: _angular_core.Optional },] }, ]; }; /** * @param {?} platformLocationStrategy * @param {?} baseHref * @param {?=} options * @return {?} */ function provideLocationStrategy(platformLocationStrategy, baseHref, options) { if (options === void 0) { options = {}; } return options.useHash ? new _angular_common.HashLocationStrategy(platformLocationStrategy, baseHref) : new _angular_common.PathLocationStrategy(platformLocationStrategy, baseHref); } /** * @param {?} router * @return {?} */ function provideForRootGuard(router) { if (router) { throw new Error("RouterModule.forRoot() called twice. Lazy loaded modules should use RouterModule.forChild() instead."); } return 'guarded'; } /** * \@whatItDoes Registers routes. * * \@howToUse * * ``` * \@NgModule({ * imports: [RouterModule.forChild(ROUTES)], * providers: [provideRoutes(EXTRA_ROUTES)] * }) * class MyNgModule {} * ``` * * \@stable * @param {?} routes * @return {?} */ function provideRoutes(routes) { return [ { provide: _angular_core.ANALYZE_FOR_ENTRY_COMPONENTS, multi: true, useValue: routes }, { provide: ROUTES, multi: true, useValue: routes }, ]; } /** * @param {?} ref * @param {?} urlSerializer * @param {?} contexts * @param {?} location * @param {?} injector * @param {?} loader * @param {?} compiler * @param {?} config * @param {?=} opts * @param {?=} urlHandlingStrategy * @param {?=} routeReuseStrategy * @return {?} */ function setupRouter(ref, urlSerializer, contexts, location, injector, loader, compiler, config, opts, urlHandlingStrategy, routeReuseStrategy) { if (opts === void 0) { opts = {}; } var /** @type {?} */ router = new Router(null, urlSerializer, contexts, location, injector, loader, compiler, flatten(config)); if (urlHandlingStrategy) { router.urlHandlingStrategy = urlHandlingStrategy; } if (routeReuseStrategy) { router.routeReuseStrategy = routeReuseStrategy; } if (opts.errorHandler) { router.errorHandler = opts.errorHandler; } if (opts.enableTracing) { var /** @type {?} */ dom_1 = _angular_platformBrowser.ɵgetDOM(); router.events.subscribe(function (e) { dom_1.logGroup("Router Event: " + ((e.constructor)).name); dom_1.log(e.toString()); dom_1.log(e); dom_1.logGroupEnd(); }); } return router; } /** * @param {?} router * @return {?} */ function rootRoute(router) { return router.routerState.root; } /** * To initialize the router properly we need to do in two steps: * * We need to start the navigation in a APP_INITIALIZER to block the bootstrap if * a resolver or a guards executes asynchronously. Second, we need to actually run * activation in a BOOTSTRAP_LISTENER. We utilize the afterPreactivation * hook provided by the router to do that. * * The router navigation starts, reaches the point when preactivation is done, and then * pauses. It waits for the hook to be resolved. We then resolve it only in a bootstrap listener. */ var RouterInitializer = (function () { /** * @param {?} injector */ function RouterInitializer(injector) { this.injector = injector; this.initNavigation = false; this.resultOfPreactivationDone = new rxjs_Subject.Subject(); } /** * @return {?} */ RouterInitializer.prototype.appInitializer = function () { var _this = this; var /** @type {?} */ p = this.injector.get(_angular_common.LOCATION_INITIALIZED, Promise.resolve(null)); return p.then(function () { var /** @type {?} */ resolve = ((null)); var /** @type {?} */ res = new Promise(function (r) { return resolve = r; }); var /** @type {?} */ router = _this.injector.get(Router); var /** @type {?} */ opts = _this.injector.get(ROUTER_CONFIGURATION); if (_this.isLegacyDisabled(opts) || _this.isLegacyEnabled(opts)) { resolve(true); } else if (opts.initialNavigation === 'disabled') { router.setUpLocationChangeListener(); resolve(true); } else if (opts.initialNavigation === 'enabled') { router.hooks.afterPreactivation = function () { // only the initial navigation should be delayed if (!_this.initNavigation) { _this.initNavigation = true; resolve(true); return _this.resultOfPreactivationDone; // subsequent navigations should not be delayed } else { return (rxjs_observable_of.of(null)); } }; router.initialNavigation(); } else { throw new Error("Invalid initialNavigation options: '" + opts.initialNavigation + "'"); } return res; }); }; /** * @param {?} bootstrappedComponentRef * @return {?} */ RouterInitializer.prototype.bootstrapListener = function (bootstrappedComponentRef) { var /** @type {?} */ opts = this.injector.get(ROUTER_CONFIGURATION); var /** @type {?} */ preloader = this.injector.get(RouterPreloader); var /** @type {?} */ router = this.injector.get(Router); var /** @type {?} */ ref = this.injector.get(_angular_core.ApplicationRef); if (bootstrappedComponentRef !== ref.components[0]) { return; } if (this.isLegacyEnabled(opts)) { router.initialNavigation(); } else if (this.isLegacyDisabled(opts)) { router.setUpLocationChangeListener(); } preloader.setUpPreloading(); router.resetRootComponentType(ref.componentTypes[0]); this.resultOfPreactivationDone.next(/** @type {?} */ ((null))); this.resultOfPreactivationDone.complete(); }; /** * @param {?} opts * @return {?} */ RouterInitializer.prototype.isLegacyEnabled = function (opts) { return opts.initialNavigation === 'legacy_enabled' || opts.initialNavigation === true || opts.initialNavigation === undefined; }; /** * @param {?} opts * @return {?} */ RouterInitializer.prototype.isLegacyDisabled = function (opts) { return opts.initialNavigation === 'legacy_disabled' || opts.initialNavigation === false; }; return RouterInitializer; }()); RouterInitializer.decorators = [ { type: _angular_core.Injectable }, ]; /** * @nocollapse */ RouterInitializer.ctorParameters = function () { return [ { type: _angular_core.Injector, }, ]; }; /** * @param {?} r * @return {?} */ function getAppInitializer(r) { return r.appInitializer.bind(r); } /** * @param {?} r * @return {?} */ function getBootstrapListener(r) { return r.bootstrapListener.bind(r); } /** * A token for the router initializer that will be called after the app is bootstrapped. * * \@experimental */ var ROUTER_INITIALIZER = new _angular_core.InjectionToken('Router Initializer'); /** * @return {?} */ function provideRouterInitializer() { return [ RouterInitializer, { provide: _angular_core.APP_INITIALIZER, multi: true, useFactory: getAppInitializer, deps: [RouterInitializer] }, { provide: ROUTER_INITIALIZER, useFactory: getBootstrapListener, deps: [RouterInitializer] }, { provide: _angular_core.APP_BOOTSTRAP_LISTENER, multi: true, useExisting: ROUTER_INITIALIZER }, ]; } /** * @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 */ /** * @module * @description * Entry point for all public APIs of the common package. */ /** * \@stable */ var VERSION = new _angular_core.Version('4.2.6'); exports.RouterLink = RouterLink; exports.RouterLinkWithHref = RouterLinkWithHref; exports.RouterLinkActive = RouterLinkActive; exports.RouterOutlet = RouterOutlet; exports.NavigationCancel = NavigationCancel; exports.NavigationEnd = NavigationEnd; exports.NavigationError = NavigationError; exports.NavigationStart = NavigationStart; exports.RouteConfigLoadEnd = RouteConfigLoadEnd; exports.RouteConfigLoadStart = RouteConfigLoadStart; exports.RoutesRecognized = RoutesRecognized; exports.RouteReuseStrategy = RouteReuseStrategy; exports.Router = Router; exports.ROUTES = ROUTES; exports.ROUTER_CONFIGURATION = ROUTER_CONFIGURATION; exports.ROUTER_INITIALIZER = ROUTER_INITIALIZER; exports.RouterModule = RouterModule; exports.provideRoutes = provideRoutes; exports.ChildrenOutletContexts = ChildrenOutletContexts; exports.OutletContext = OutletContext; exports.NoPreloading = NoPreloading; exports.PreloadAllModules = PreloadAllModules; exports.PreloadingStrategy = PreloadingStrategy; exports.RouterPreloader = RouterPreloader; exports.ActivatedRoute = ActivatedRoute; exports.ActivatedRouteSnapshot = ActivatedRouteSnapshot; exports.RouterState = RouterState; exports.RouterStateSnapshot = RouterStateSnapshot; exports.PRIMARY_OUTLET = PRIMARY_OUTLET; exports.convertToParamMap = convertToParamMap; exports.UrlHandlingStrategy = UrlHandlingStrategy; exports.DefaultUrlSerializer = DefaultUrlSerializer; exports.UrlSegment = UrlSegment; exports.UrlSegmentGroup = UrlSegmentGroup; exports.UrlSerializer = UrlSerializer; exports.UrlTree = UrlTree; exports.VERSION = VERSION; exports.ɵROUTER_PROVIDERS = ROUTER_PROVIDERS; exports.ɵflatten = flatten; exports.ɵa = ROUTER_FORROOT_GUARD; exports.ɵg = RouterInitializer; exports.ɵh = getAppInitializer; exports.ɵi = getBootstrapListener; exports.ɵd = provideForRootGuard; exports.ɵc = provideLocationStrategy; exports.ɵj = provideRouterInitializer; exports.ɵf = rootRoute; exports.ɵb = routerNgProbeToken; exports.ɵe = setupRouter; exports.ɵk = Tree; exports.ɵl = TreeNode; Object.defineProperty(exports, '__esModule', { value: true }); }))); //# sourceMappingURL=router.umd.js.map
batimiasu/angular-tour-of-heroes
node_modules/@angular/router/bundles/router.umd.js
JavaScript
mit
220,558
(function(forp, $){ /** * BarChart Class */ forp.BarChart = function(conf) { forp.Graph.call(this, conf); this.tmp = null; this.restore = function() { if(this.tmp) { this.ctx.clearRect(0, 0, this.element.width, this.element.height); this.ctx.drawImage(this.tmp, 0, 0); } }; this.highlight = function(idx) { if(!this.tmp) { this.tmp = document.createElement('canvas'); this.tmp.width = this.element.width; this.tmp.height = this.element.height; this.tmp.style.width = '100%'; this.tmp.style.height = '100px'; var context = this.tmp.getContext('2d'); context.drawImage(this.element, 0, 0); } this.ctx.beginPath(); this.ctx.strokeStyle = '#4D90FE'; this.ctx.lineWidth = 60; this.ctx.moveTo(idx, this.conf.yaxis.length); this.ctx.lineTo( idx, this.conf.yaxis.length - ( (this.conf.val.call(this, idx) * 100) / this.conf.yaxis.max ) ); this.ctx.closePath(); this.ctx.stroke(); }; this.draw = function() { if(!this.drawn) { this.drawn = true; var len = this.datas.length; this.element.width = document.body.clientWidth*2; this.element.height = this.conf.yaxis.length; this.element.style.width = '100%'; this.element.style.height = this.conf.yaxis.length + 'px'; this.element.style.marginBottom = '-3px'; this.element.style.backgroundColor = '#333'; var x = 0; for(var i = 0; i < len; i++) { this.ctx.beginPath(); this.ctx.strokeStyle = this.conf.color.call(this, i); this.ctx.lineWidth = 50; this.ctx.moveTo( x, 25 ); this.ctx.lineTo( x += ( (this.conf.val.call(this, i) * this.element.width) / this.conf.xaxis.max ) +2, 25 ); this.ctx.closePath(); this.ctx.stroke(); } if(this.conf.mousemove) { var self = this; this.bind( 'mousemove', function(e) { self.conf.mousemove.call(self,e); } ) } } return this; }; }; })(forp, jMicro);
aterrien/forp-ui
src/js/lib/view/indicator/barchart.js
JavaScript
mit
2,948
const Parse = require('./parser'); describe('test_parse', () => { describe('test_parse_key_values', () => { it('should return the key values specified in the config from the body', () => { const config = { keys: ['to', 'from'], }; const request = { body: { to: 'inbound@inbound.example.com', from: 'Test User <test@example.com>', subject: 'Test Subject', }, }; const parse = new Parse(config, request); const keyValues = parse.keyValues(); const expectedValues = { to: 'inbound@inbound.example.com', from: 'Test User <test@example.com>', }; expect(keyValues).to.be.an('object'); expect(keyValues).to.deep.equal(expectedValues); }); it('should return the key values specified in the config from the payload', () => { const config = { keys: ['to', 'from'], }; const request = { payload: { to: 'inbound@inbound.example.com', from: 'Test User <test@example.com>', subject: 'Test Subject', }, }; const parse = new Parse(config, request); const keyValues = parse.keyValues(); const expectedValues = { to: 'inbound@inbound.example.com', from: 'Test User <test@example.com>', }; expect(keyValues).to.be.an('object'); expect(keyValues).to.deep.equal(expectedValues); }); }); describe('test_parse_get_raw_email', () => { it('should return null if no raw email property in payload', (done) => { const parse = new Parse({}, {}); function callback(email) { expect(email).to.be.null(); done(); } parse.getRawEmail(callback); }); it('should parse raw email from payload and return a mail object', (done) => { const request = { body: { email: 'MIME-Version: 1.0\r\nReceived: by 0.0.0.0 with HTTP; Wed, 10 Aug 2016 14:44:21 -0700 (PDT)\r\nFrom: Example User <test@example.com>\r\nDate: Wed, 10 Aug 2016 14:44:21 -0700\r\nSubject: Inbound Parse Test Raw Data\r\nTo: inbound@inbound.inbound.com\r\nContent-Type: multipart/alternative; boundary=001a113ee97c89842f0539be8e7a\r\n\r\n--001a113ee97c89842f0539be8e7a\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\nHello Twilio SendGrid!\r\n\r\n--001a113ee97c89842f0539be8e7a\r\nContent-Type: text/html; charset=UTF-8\r\nContent-Transfer-Encoding: quoted-printable\r\n\r\n<html><body><strong>Hello Twilio SendGrid!</body></html>\r\n\r\n--001a113ee97c89842f0539be8e7a--\r\n', }, }; const parse = new Parse({}, request); function callback(email) { expect(email).to.be.an('object'); done(); } parse.getRawEmail(callback); }); }); });
sendgrid/sendgrid-nodejs
packages/inbound-mail-parser/src/parser.spec.js
JavaScript
mit
2,789
/* * Swaggy Jenkins * Jenkins API clients generated from Swagger / Open API specification * * The version of the OpenAPI document: 1.1.2-pre.0 * Contact: blah@cliffano.com * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package org.openapitools.model; import java.util.Objects; import java.util.Arrays; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import org.openapitools.model.GithubRepositories; import org.openapitools.model.GithubRespositoryContainerlinks; import com.fasterxml.jackson.annotation.*; import javax.validation.constraints.*; import javax.validation.Valid; import io.micronaut.core.annotation.*; import javax.annotation.Generated; /** * GithubRespositoryContainer */ @JsonPropertyOrder({ GithubRespositoryContainer.JSON_PROPERTY_PROPERTY_CLASS, GithubRespositoryContainer.JSON_PROPERTY_LINKS, GithubRespositoryContainer.JSON_PROPERTY_REPOSITORIES }) @JsonTypeName("GithubRespositoryContainer") @Generated(value="org.openapitools.codegen.languages.JavaMicronautClientCodegen", date="2022-02-13T02:16:15.805366Z[Etc/UTC]") @Introspected public class GithubRespositoryContainer { public static final String JSON_PROPERTY_PROPERTY_CLASS = "_class"; private String propertyClass; public static final String JSON_PROPERTY_LINKS = "_links"; private GithubRespositoryContainerlinks links; public static final String JSON_PROPERTY_REPOSITORIES = "repositories"; private GithubRepositories repositories; public GithubRespositoryContainer() { } public GithubRespositoryContainer propertyClass(String propertyClass) { this.propertyClass = propertyClass; return this; } /** * Get propertyClass * @return propertyClass **/ @Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_PROPERTY_CLASS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public String getPropertyClass() { return propertyClass; } @JsonProperty(JSON_PROPERTY_PROPERTY_CLASS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setPropertyClass(String propertyClass) { this.propertyClass = propertyClass; } public GithubRespositoryContainer links(GithubRespositoryContainerlinks links) { this.links = links; return this; } /** * Get links * @return links **/ @Valid @Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_LINKS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public GithubRespositoryContainerlinks getLinks() { return links; } @JsonProperty(JSON_PROPERTY_LINKS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setLinks(GithubRespositoryContainerlinks links) { this.links = links; } public GithubRespositoryContainer repositories(GithubRepositories repositories) { this.repositories = repositories; return this; } /** * Get repositories * @return repositories **/ @Valid @Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_REPOSITORIES) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public GithubRepositories getRepositories() { return repositories; } @JsonProperty(JSON_PROPERTY_REPOSITORIES) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setRepositories(GithubRepositories repositories) { this.repositories = repositories; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } GithubRespositoryContainer githubRespositoryContainer = (GithubRespositoryContainer) o; return Objects.equals(this.propertyClass, githubRespositoryContainer.propertyClass) && Objects.equals(this.links, githubRespositoryContainer.links) && Objects.equals(this.repositories, githubRespositoryContainer.repositories); } @Override public int hashCode() { return Objects.hash(propertyClass, links, repositories); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class GithubRespositoryContainer {\n"); sb.append(" propertyClass: ").append(toIndentedString(propertyClass)).append("\n"); sb.append(" links: ").append(toIndentedString(links)).append("\n"); sb.append(" repositories: ").append(toIndentedString(repositories)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
cliffano/swaggy-jenkins
clients/java-micronaut-client/generated/src/main/java/org/openapitools/model/GithubRespositoryContainer.java
Java
mit
5,141
/* tslint:disable max-line-length */ import { TestBed, getTestBed } from '@angular/core/testing'; import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { HttpClient, HttpResponse } from '@angular/common/http'; import { of } from 'rxjs'; import { take, map } from 'rxjs/operators'; import * as moment from 'moment'; import { DATE_TIME_FORMAT } from 'app/shared/constants/input.constants'; import { CourseService } from 'app/entities/course/course.service'; import { ICourse, Course } from 'app/shared/model/course.model'; describe('Service Tests', () => { describe('Course Service', () => { let injector: TestBed; let service: CourseService; let httpMock: HttpTestingController; let elemDefault: ICourse; let currentDate: moment.Moment; beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], }); injector = getTestBed(); service = injector.get(CourseService); httpMock = injector.get(HttpTestingController); currentDate = moment(); elemDefault = new Course(0, 'AAAAAAA', 'AAAAAAA', 'AAAAAAA', 'AAAAAAA', currentDate, currentDate, false); }); describe('Service methods', async () => { it('should find an element', async () => { const returnedFromService = Object.assign( { startDate: currentDate.format(DATE_TIME_FORMAT), endDate: currentDate.format(DATE_TIME_FORMAT), }, elemDefault, ); service .find(123) .pipe(take(1)) .subscribe(resp => expect(resp).toMatchObject({ body: elemDefault })); const req = httpMock.expectOne({ method: 'GET' }); req.flush(JSON.stringify(returnedFromService)); }); it('should create a Course', async () => { const returnedFromService = Object.assign( { id: 0, startDate: currentDate.format(DATE_TIME_FORMAT), endDate: currentDate.format(DATE_TIME_FORMAT), }, elemDefault, ); const expected = Object.assign( { startDate: currentDate, endDate: currentDate, }, returnedFromService, ); service .create(new Course(null)) .pipe(take(1)) .subscribe(resp => expect(resp).toMatchObject({ body: expected })); const req = httpMock.expectOne({ method: 'POST' }); req.flush(JSON.stringify(returnedFromService)); }); it('should update a Course', async () => { const returnedFromService = Object.assign( { title: 'BBBBBB', studentGroupName: 'BBBBBB', teachingAssistantGroupName: 'BBBBBB', instructorGroupName: 'BBBBBB', startDate: currentDate.format(DATE_TIME_FORMAT), endDate: currentDate.format(DATE_TIME_FORMAT), onlineCourse: true, }, elemDefault, ); const expected = Object.assign( { startDate: currentDate, endDate: currentDate, }, returnedFromService, ); service .update(expected) .pipe(take(1)) .subscribe(resp => expect(resp).toMatchObject({ body: expected })); const req = httpMock.expectOne({ method: 'PUT' }); req.flush(JSON.stringify(returnedFromService)); }); it('should return a list of Course', async () => { const returnedFromService = Object.assign( { title: 'BBBBBB', studentGroupName: 'BBBBBB', teachingAssistantGroupName: 'BBBBBB', instructorGroupName: 'BBBBBB', startDate: currentDate.format(DATE_TIME_FORMAT), endDate: currentDate.format(DATE_TIME_FORMAT), onlineCourse: true, }, elemDefault, ); const expected = Object.assign( { startDate: currentDate, endDate: currentDate, }, returnedFromService, ); service .query(expected) .pipe( take(1), map(resp => resp.body), ) .subscribe(body => expect(body).toContainEqual(expected)); const req = httpMock.expectOne({ method: 'GET' }); req.flush(JSON.stringify([returnedFromService])); httpMock.verify(); }); it('should delete a Course', async () => { const rxPromise = service.delete(123).subscribe(resp => expect(resp.ok)); const req = httpMock.expectOne({ method: 'DELETE' }); req.flush({ status: 200 }); }); }); afterEach(() => { httpMock.verify(); }); }); });
ls1intum/ArTEMiS
src/test/javascript/spec/app/entities/course/course.service.spec.ts
TypeScript
mit
5,874
#ifndef BITCOINGUI_H #define BITCOINGUI_H #include <QMainWindow> #include <QSystemTrayIcon> #include <QMap> class TransactionTableModel; class WalletFrame; class WalletView; class ClientModel; class WalletModel; class WalletStack; class TransactionView; class OverviewPage; class AddressBookPage; class SendCoinsDialog; class SignVerifyMessageDialog; class Notificator; class RPCConsole; class CWallet; QT_BEGIN_NAMESPACE class QLabel; class QModelIndex; class QProgressBar; class QStackedWidget; class QUrl; class QListWidget; class QPushButton; class QAction; QT_END_NAMESPACE /** dollarcoin GUI main class. This class represents the main window of the dollarcoin UI. It communicates with both the client and wallet models to give the user an up-to-date view of the current core state. */ class BitcoinGUI : public QMainWindow { Q_OBJECT public: static const QString DEFAULT_WALLET; explicit BitcoinGUI(bool fIsTestnet = false, QWidget *parent = 0); ~BitcoinGUI(); /** Set the client model. The client model represents the part of the core that communicates with the P2P network, and is wallet-agnostic. */ void setClientModel(ClientModel *clientModel); /** Set the wallet model. The wallet model represents a bitcoin wallet, and offers access to the list of transactions, address book and sending functionality. */ bool addWallet(const QString& name, WalletModel *walletModel); bool setCurrentWallet(const QString& name); void removeAllWallets(); /** Used by WalletView to allow access to needed QActions */ // Todo: Use Qt signals for these QAction * getOverviewAction() { return overviewAction; } QAction * getHistoryAction() { return historyAction; } QAction * getAddressBookAction() { return addressBookAction; } QAction * getReceiveCoinsAction() { return receiveCoinsAction; } QAction * getSendCoinsAction() { return sendCoinsAction; } protected: void changeEvent(QEvent *e); void closeEvent(QCloseEvent *event); void dragEnterEvent(QDragEnterEvent *event); void dropEvent(QDropEvent *event); bool eventFilter(QObject *object, QEvent *event); private: ClientModel *clientModel; WalletFrame *walletFrame; QLabel *labelEncryptionIcon; QLabel *labelConnectionsIcon; QLabel *labelBlocksIcon; QLabel *progressBarLabel; QProgressBar *progressBar; QMenuBar *appMenuBar; QAction *overviewAction; QAction *historyAction; QAction *quitAction; QAction *sendCoinsAction; QAction *addressBookAction; QAction *signMessageAction; QAction *verifyMessageAction; QAction *aboutAction; QAction *receiveCoinsAction; QAction *optionsAction; QAction *toggleHideAction; QAction *encryptWalletAction; QAction *backupWalletAction; QAction *changePassphraseAction; QAction *aboutQtAction; QAction *openRPCConsoleAction; QSystemTrayIcon *trayIcon; Notificator *notificator; TransactionView *transactionView; RPCConsole *rpcConsole; QMovie *syncIconMovie; /** Keep track of previous number of blocks, to detect progress */ int prevBlocks; /** Create the main UI actions. */ void createActions(bool fIsTestnet); /** Create the menu bar and sub-menus. */ void createMenuBar(); /** Create the toolbars */ void createToolBars(); /** Create system tray icon and notification */ void createTrayIcon(bool fIsTestnet); /** Create system tray menu (or setup the dock menu) */ void createTrayIconMenu(); public slots: /** Set number of connections shown in the UI */ void setNumConnections(int count); /** Set number of blocks shown in the UI */ void setNumBlocks(int count, int nTotalBlocks); /** Set the encryption status as shown in the UI. @param[in] status current encryption status @see WalletModel::EncryptionStatus */ void setEncryptionStatus(int status); /** Notify the user of an event from the core network or transaction handling code. @param[in] title the message box / notification title @param[in] message the displayed text @param[in] style modality and style definitions (icon and used buttons - buttons only for message boxes) @see CClientUIInterface::MessageBoxFlags @param[in] ret pointer to a bool that will be modified to whether Ok was clicked (modal only) */ void message(const QString &title, const QString &message, unsigned int style, bool *ret = NULL); /** Asks the user whether to pay the transaction fee or to cancel the transaction. It is currently not possible to pass a return value to another thread through BlockingQueuedConnection, so an indirected pointer is used. https://bugreports.qt-project.org/browse/QTBUG-10440 @param[in] nFeeRequired the required fee @param[out] payFee true to pay the fee, false to not pay the fee */ void askFee(qint64 nFeeRequired, bool *payFee); void handleURI(QString strURI); /** Show incoming transaction notification for new transactions. */ void incomingTransaction(const QString& date, int unit, qint64 amount, const QString& type, const QString& address); private slots: /** Switch to overview (home) page */ void gotoOverviewPage(); /** Switch to history (transactions) page */ void gotoHistoryPage(); /** Switch to address book page */ void gotoAddressBookPage(); /** Switch to receive coins page */ void gotoReceiveCoinsPage(); /** Switch to send coins page */ void gotoSendCoinsPage(QString addr = ""); /** Show Sign/Verify Message dialog and switch to sign message tab */ void gotoSignMessageTab(QString addr = ""); /** Show Sign/Verify Message dialog and switch to verify message tab */ void gotoVerifyMessageTab(QString addr = ""); /** Show configuration dialog */ void optionsClicked(); /** Show about dialog */ void aboutClicked(); #ifndef Q_OS_MAC /** Handle tray icon clicked */ void trayIconActivated(QSystemTrayIcon::ActivationReason reason); #endif /** Show window if hidden, unminimize when minimized, rise when obscured or show if hidden and fToggleHidden is true */ void showNormalIfMinimized(bool fToggleHidden = false); /** Simply calls showNormalIfMinimized(true) for use in SLOT() macro */ void toggleHidden(); /** called by a timer to check if fRequestShutdown has been set **/ void detectShutdown(); }; #endif // BITCOINGUI_H
dollarcoins/source
src/qt/bitcoingui.h
C
mit
6,623
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>User agent detail - Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/536.26.14 (KHTML, like Gecko)</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/css/materialize.min.css"> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <link href="../circle.css" rel="stylesheet"> </head> <body> <div class="container"> <div class="section"> <h1 class="header center orange-text">User agent detail</h1> <div class="row center"> <h5 class="header light"> Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/536.26.14 (KHTML, like Gecko) </h5> </div> </div> <div class="section"> <table class="striped"><tr><th></th><th colspan="3">General</th><th colspan="5">Device</th><th colspan="3">Bot</th><th colspan="2"></th></tr><tr><th>Provider</th><th>Browser</th><th>Engine</th><th>OS</th><th>Brand</th><th>Model</th><th>Type</th><th>Is mobile</th><th>Is touch</th><th>Is bot</th><th>Name</th><th>Type</th><th>Parse time</th><th>Actions</th></tr><tr><th colspan="14" class="green lighten-3">Test suite</th></tr><tr><td>UAParser<br /><small>v0.5.0.2</small><br /><small>vendor/thadafinser/uap-core/tests/test_ua.yaml</small></td><td>AppleMail 536.26.14</td><td><i class="material-icons">close</i></td><td> </td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-cfed3005-df48-4fa8-bf03-4f6ef8988f59">Detail</a> <!-- Modal Structure --> <div id="modal-cfed3005-df48-4fa8-bf03-4f6ef8988f59" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UAParser result detail</h4> <p><pre><code class="php">Array ( [user_agent_string] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/536.26.14 (KHTML, like Gecko) [family] => AppleMail [major] => 536 [minor] => 26 [patch] => 14 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><th colspan="14" class="green lighten-3">Providers</th></tr><tr><td>BrowscapFull<br /><small>6014</small><br /></td><td>Apple Mail 6.0</td><td>WebKit </td><td>MacOSX 10.8</td><td style="border-left: 1px solid #555">Apple</td><td>Macintosh</td><td>Desktop</td><td></td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.012</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-47a9cd06-e213-4882-bc34-db6aed664223">Detail</a> <!-- Modal Structure --> <div id="modal-47a9cd06-e213-4882-bc34-db6aed664223" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>BrowscapFull result detail</h4> <p><pre><code class="php">stdClass Object ( [browser_name_regex] => /^mozilla\/5\.0 \(.*mac os x 10.8.*\) applewebkit.* \(khtml.* like gecko\)$/ [browser_name_pattern] => mozilla/5.0 (*mac os x 10?8*) applewebkit* (khtml* like gecko) [parent] => Apple Mail for OSX [comment] => Apple Mail for OSX [browser] => Apple Mail [browser_type] => Email Client [browser_bits] => 32 [browser_maker] => Apple Inc [browser_modus] => unknown [version] => 6.0 [majorver] => 6 [minorver] => 0 [platform] => MacOSX [platform_version] => 10.8 [platform_description] => Mac OS X [platform_bits] => 32 [platform_maker] => Apple Inc [alpha] => [beta] => [win16] => [win32] => [win64] => [frames] => [iframes] => [tables] => [cookies] => [backgroundsounds] => [javascript] => [vbscript] => [javaapplets] => 1 [activexcontrols] => [ismobiledevice] => [istablet] => [issyndicationreader] => [crawler] => [isfake] => [isanonymized] => [ismodified] => [cssversion] => 0 [aolversion] => 0 [device_name] => Macintosh [device_maker] => Apple Inc [device_type] => Desktop [device_pointing_method] => mouse [device_code_name] => Macintosh [device_brand_name] => Apple [renderingengine_name] => WebKit [renderingengine_version] => unknown [renderingengine_description] => For Google Chrome, iOS (including both mobile Safari, WebViews within third-party apps, and web clips), Safari, Arora, Midori, OmniWeb, Shiira, iCab since version 4, Web, SRWare Iron, Rekonq, and in Maxthon 3. [renderingengine_maker] => Apple Inc ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>BrowscapLite<br /><small>6014</small><br /></td> <td colspan="12" class="center-align red lighten-1"> <strong>No result found</strong> </td> </tr><tr><td>BrowscapPhp<br /><small>6014</small><br /></td><td>Apple Mail </td><td><i class="material-icons">close</i></td><td>MacOSX </td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>Desktop</td><td></td><td></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.024</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-ad0041a2-b0f4-43f6-a70d-cad1443caa68">Detail</a> <!-- Modal Structure --> <div id="modal-ad0041a2-b0f4-43f6-a70d-cad1443caa68" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>BrowscapPhp result detail</h4> <p><pre><code class="php">stdClass Object ( [browser_name_regex] => /^mozilla\/5\.0 \(.*mac os x.*\) applewebkit.* \(khtml.* like gecko\)$/ [browser_name_pattern] => mozilla/5.0 (*mac os x*) applewebkit* (khtml* like gecko) [parent] => Apple Mail for OSX [comment] => Apple Mail for OSX [browser] => Apple Mail [browser_type] => unknown [browser_bits] => 0 [browser_maker] => Apple Inc [browser_modus] => unknown [version] => 0.0 [majorver] => 0 [minorver] => 0 [platform] => MacOSX [platform_version] => unknown [platform_description] => unknown [platform_bits] => 0 [platform_maker] => unknown [alpha] => false [beta] => false [win16] => false [win32] => false [win64] => false [frames] => false [iframes] => false [tables] => false [cookies] => false [backgroundsounds] => false [javascript] => false [vbscript] => false [javaapplets] => false [activexcontrols] => false [ismobiledevice] => [istablet] => [issyndicationreader] => false [crawler] => [isfake] => false [isanonymized] => false [ismodified] => false [cssversion] => 0 [aolversion] => 0 [device_name] => unknown [device_maker] => unknown [device_type] => Desktop [device_pointing_method] => mouse [device_code_name] => unknown [device_brand_name] => unknown [renderingengine_name] => unknown [renderingengine_version] => unknown [renderingengine_description] => unknown [renderingengine_maker] => unknown ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>DonatjUAParser<br /><small>v0.5.1</small><br /></td><td>AppleWebKit 536.26.14</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-15fbc1f0-2615-4d42-b5d9-a30dd647b050">Detail</a> <!-- Modal Structure --> <div id="modal-15fbc1f0-2615-4d42-b5d9-a30dd647b050" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>DonatjUAParser result detail</h4> <p><pre><code class="php">Array ( [platform] => Macintosh [browser] => AppleWebKit [version] => 536.26.14 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>JenssegersAgent<br /><small>v2.3.3</small><br /></td><td>Mozilla </td><td><i class="material-icons">close</i></td><td>OS X 10_8_2</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-b85a2b91-6a55-4436-a82c-1ea0d46e2e51">Detail</a> <!-- Modal Structure --> <div id="modal-b85a2b91-6a55-4436-a82c-1ea0d46e2e51" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>JenssegersAgent result detail</h4> <p><pre><code class="php">Array ( [browserName] => Mozilla [browserVersion] => [osName] => OS X [osVersion] => 10_8_2 [deviceModel] => Macintosh [isMobile] => [isRobot] => [botName] => ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>NeutrinoApiCom<br /><small></small><br /></td><td>Apple Mail </td><td><i class="material-icons">close</i></td><td>OS X 10.8.2</td><td style="border-left: 1px solid #555"></td><td></td><td>email-client</td><td></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.20701</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-8c2a7a4e-3fbf-4df2-8d61-5e730422f67b">Detail</a> <!-- Modal Structure --> <div id="modal-8c2a7a4e-3fbf-4df2-8d61-5e730422f67b" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>NeutrinoApiCom result detail</h4> <p><pre><code class="php">stdClass Object ( [mobile_screen_height] => 0 [is_mobile] => [type] => email-client [mobile_brand] => [mobile_model] => [version] => [is_android] => [browser_name] => Apple Mail [operating_system_family] => OS X [operating_system_version] => 10.8.2 [is_ios] => [producer] => Apple Inc. [operating_system] => OS X 10.8 Mountain Lion [mobile_screen_width] => 0 [mobile_browser] => ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>PiwikDeviceDetector<br /><small>3.6.1</small><br /></td><td> </td><td> </td><td>Mac 10.8</td><td style="border-left: 1px solid #555"></td><td></td><td>desktop</td><td></td><td></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.007</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-4a941d34-a8d3-4914-9724-346f60ad7046">Detail</a> <!-- Modal Structure --> <div id="modal-4a941d34-a8d3-4914-9724-346f60ad7046" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>PiwikDeviceDetector result detail</h4> <p><pre><code class="php">Array ( [client] => [operatingSystem] => Array ( [name] => Mac [short_name] => MAC [version] => 10.8 [platform] => ) [device] => Array ( [brand] => [brandName] => [model] => [device] => 0 [deviceName] => desktop ) [bot] => [extra] => Array ( [isBot] => [isBrowser] => [isFeedReader] => [isMobileApp] => [isPIM] => [isLibrary] => [isMediaPlayer] => [isCamera] => [isCarBrowser] => [isConsole] => [isFeaturePhone] => [isPhablet] => [isPortableMediaPlayer] => [isSmartDisplay] => [isSmartphone] => [isTablet] => [isTV] => [isDesktop] => 1 [isMobile] => [isTouchEnabled] => ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>SinergiBrowserDetector<br /><small>6.0.1</small><br /></td><td>Mozilla 5.0</td><td><i class="material-icons">close</i></td><td>OS X 10.8.2</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td></td><td><i class="material-icons">close</i></td><td></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-ec1cd248-02b0-457e-8a9d-35bb99af008c">Detail</a> <!-- Modal Structure --> <div id="modal-ec1cd248-02b0-457e-8a9d-35bb99af008c" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>SinergiBrowserDetector result detail</h4> <p><pre><code class="php">Array ( [browser] => Sinergi\BrowserDetector\Browser Object ( [userAgent:Sinergi\BrowserDetector\Browser:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/536.26.14 (KHTML, like Gecko) ) [name:Sinergi\BrowserDetector\Browser:private] => Mozilla [version:Sinergi\BrowserDetector\Browser:private] => 5.0 [isRobot:Sinergi\BrowserDetector\Browser:private] => [isChromeFrame:Sinergi\BrowserDetector\Browser:private] => [isFacebookWebView:Sinergi\BrowserDetector\Browser:private] => [isCompatibilityMode:Sinergi\BrowserDetector\Browser:private] => ) [operatingSystem] => Sinergi\BrowserDetector\Os Object ( [name:Sinergi\BrowserDetector\Os:private] => OS X [version:Sinergi\BrowserDetector\Os:private] => 10.8.2 [isMobile:Sinergi\BrowserDetector\Os:private] => [userAgent:Sinergi\BrowserDetector\Os:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/536.26.14 (KHTML, like Gecko) ) ) [device] => Sinergi\BrowserDetector\Device Object ( [name:Sinergi\BrowserDetector\Device:private] => unknown [userAgent:Sinergi\BrowserDetector\Device:private] => Sinergi\BrowserDetector\UserAgent Object ( [userAgentString:Sinergi\BrowserDetector\UserAgent:private] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/536.26.14 (KHTML, like Gecko) ) ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UAParser<br /><small>v3.4.5</small><br /></td><td>AppleMail 536.26.14</td><td><i class="material-icons">close</i></td><td>Mac OS X 10.8.2</td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.005</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-3160e405-8a8f-46dd-8f47-5115f06462d2">Detail</a> <!-- Modal Structure --> <div id="modal-3160e405-8a8f-46dd-8f47-5115f06462d2" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UAParser result detail</h4> <p><pre><code class="php">UAParser\Result\Client Object ( [ua] => UAParser\Result\UserAgent Object ( [major] => 536 [minor] => 26 [patch] => 14 [family] => AppleMail ) [os] => UAParser\Result\OperatingSystem Object ( [major] => 10 [minor] => 8 [patch] => 2 [patchMinor] => [family] => Mac OS X ) [device] => UAParser\Result\Device Object ( [brand] => [model] => [family] => Other ) [originalUserAgent] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/536.26.14 (KHTML, like Gecko) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UserAgentApiCom<br /><small></small><br /></td><td>Mozilla 5.0</td><td>WebKit 536.26.14</td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>Desktop</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.15201</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-afeb05fb-26b9-4509-b8ac-0c604a9e97d6">Detail</a> <!-- Modal Structure --> <div id="modal-afeb05fb-26b9-4509-b8ac-0c604a9e97d6" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UserAgentApiCom result detail</h4> <p><pre><code class="php">stdClass Object ( [platform_name] => Mac OSX Mountain Lion [platform_version] => Mac OS X 10_8 [platform_type] => Desktop [browser_name] => Mozilla [browser_version] => 5.0 [engine_name] => WebKit [engine_version] => 536.26.14 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>UserAgentStringCom<br /><small></small><br /></td><td>Safari </td><td><i class="material-icons">close</i></td><td>OS X 10.8.2</td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td></td><td>0.059</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-08a9ddfb-838f-48d7-9ede-1d132306b2ee">Detail</a> <!-- Modal Structure --> <div id="modal-08a9ddfb-838f-48d7-9ede-1d132306b2ee" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>UserAgentStringCom result detail</h4> <p><pre><code class="php">stdClass Object ( [agent_type] => Browser [agent_name] => Safari [agent_version] => -- [os_type] => Macintosh [os_name] => OS X [os_versionName] => [os_versionNumber] => 10_8_2 [os_producer] => [os_producerURL] => [linux_distibution] => Null [agent_language] => [agent_languageTag] => ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhatIsMyBrowserCom<br /><small></small><br /></td><td>Mozilla 5.0</td><td>WebKit 536.26.14</td><td>Mac OS X 10.8.2</td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.23401</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-5fc1ff22-a74d-481b-9ad1-fcfde73ded9c">Detail</a> <!-- Modal Structure --> <div id="modal-5fc1ff22-a74d-481b-9ad1-fcfde73ded9c" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhatIsMyBrowserCom result detail</h4> <p><pre><code class="php">stdClass Object ( [operating_system_name] => Mac OS X [simple_sub_description_string] => [simple_browser_string] => Mozilla 5 on Mac OS X (Mountain Lion) [browser_version] => 5 [extra_info] => Array ( ) [operating_platform] => [extra_info_table] => Array ( ) [layout_engine_name] => WebKit [detected_addons] => Array ( ) [operating_system_flavour_code] => [hardware_architecture] => [operating_system_flavour] => [operating_system_frameworks] => Array ( ) [browser_name_code] => mozilla [operating_system_version] => Mountain Lion [simple_operating_platform_string] => [is_abusive] => [layout_engine_version] => 536.26.14 [browser_capabilities] => Array ( ) [operating_platform_vendor_name] => [operating_system] => Mac OS X (Mountain Lion) [operating_system_version_full] => 10.8.2 [operating_platform_code] => [browser_name] => Mozilla [operating_system_name_code] => mac-os-x [user_agent] => Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/536.26.14 (KHTML, like Gecko) [browser_version_full] => 5.0 [browser] => Mozilla 5 ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>WhichBrowser<br /><small>v2.0.18</small><br /></td><td> </td><td>Webkit 536.26.14</td><td>OS X Mountain Lion 10.8</td><td style="border-left: 1px solid #555"></td><td></td><td>desktop</td><td></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-083a336f-5d73-4505-84f3-c5fc9bb78652">Detail</a> <!-- Modal Structure --> <div id="modal-083a336f-5d73-4505-84f3-c5fc9bb78652" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>WhichBrowser result detail</h4> <p><pre><code class="php">Array ( [engine] => Array ( [name] => Webkit [version] => 536.26.14 ) [os] => Array ( [name] => OS X [version] => Array ( [value] => 10.8 [nickname] => Mountain Lion ) ) [device] => Array ( [type] => desktop ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Woothee<br /><small>v1.2.0</small><br /></td><td> </td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>pc</td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td>0.001</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-f00e7198-0e22-49fe-bad0-dbb3a9cde9b9">Detail</a> <!-- Modal Structure --> <div id="modal-f00e7198-0e22-49fe-bad0-dbb3a9cde9b9" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Woothee result detail</h4> <p><pre><code class="php">Array ( [category] => pc [os] => Mac OSX [os_version] => 10.8.2 [name] => UNKNOWN [version] => UNKNOWN [vendor] => UNKNOWN ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Wurfl<br /><small>1.7.1.0</small><br /></td><td> </td><td><i class="material-icons">close</i></td><td>Mac OS X 10.8.2</td><td style="border-left: 1px solid #555"></td><td></td><td>Desktop</td><td></td><td></td><td style="border-left: 1px solid #555"></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0.016</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-a2bedf8c-4a95-42a7-96c5-aaf233b2ac50">Detail</a> <!-- Modal Structure --> <div id="modal-a2bedf8c-4a95-42a7-96c5-aaf233b2ac50" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Wurfl result detail</h4> <p><pre><code class="php">Array ( [virtual] => Array ( [is_android] => false [is_ios] => false [is_windows_phone] => false [is_app] => false [is_full_desktop] => true [is_largescreen] => true [is_mobile] => false [is_robot] => false [is_smartphone] => false [is_touchscreen] => false [is_wml_preferred] => false [is_xhtmlmp_preferred] => false [is_html_preferred] => true [advertised_device_os] => Mac OS X [advertised_device_os_version] => 10.8.2 [advertised_browser] => [advertised_browser_version] => [complete_device_name] => generic web browser [device_name] => generic web browser [form_factor] => Desktop [is_phone] => false [is_app_webview] => true ) [all] => Array ( [brand_name] => generic web browser [model_name] => [unique] => true [ununiqueness_handler] => [is_wireless_device] => false [device_claims_web_support] => true [has_qwerty_keyboard] => true [can_skip_aligned_link_row] => true [uaprof] => [uaprof2] => [uaprof3] => [nokia_series] => 0 [nokia_edition] => 0 [device_os] => [mobile_browser] => [mobile_browser_version] => [device_os_version] => [pointing_method] => mouse [release_date] => 1994_january [marketing_name] => [model_extra_info] => [nokia_feature_pack] => 0 [can_assign_phone_number] => false [is_tablet] => false [manufacturer_name] => [is_bot] => false [is_google_glass] => false [proportional_font] => false [built_in_back_button_support] => false [card_title_support] => false [softkey_support] => false [table_support] => false [numbered_menus] => false [menu_with_select_element_recommended] => false [menu_with_list_of_links_recommended] => false [icons_on_menu_items_support] => false [break_list_of_links_with_br_element_recommended] => false [access_key_support] => false [wrap_mode_support] => false [times_square_mode_support] => false [deck_prefetch_support] => false [elective_forms_recommended] => false [wizards_recommended] => false [image_as_link_support] => false [insert_br_element_after_widget_recommended] => false [wml_can_display_images_and_text_on_same_line] => false [wml_displays_image_in_center] => false [opwv_wml_extensions_support] => false [wml_make_phone_call_string] => none [chtml_display_accesskey] => false [emoji] => false [chtml_can_display_images_and_text_on_same_line] => false [chtml_displays_image_in_center] => false [imode_region] => none [chtml_make_phone_call_string] => tel: [chtml_table_support] => true [xhtml_honors_bgcolor] => true [xhtml_supports_forms_in_table] => true [xhtml_support_wml2_namespace] => false [xhtml_autoexpand_select] => false [xhtml_select_as_dropdown] => true [xhtml_select_as_radiobutton] => true [xhtml_select_as_popup] => true [xhtml_display_accesskey] => false [xhtml_supports_invisible_text] => false [xhtml_supports_inline_input] => false [xhtml_supports_monospace_font] => false [xhtml_supports_table_for_layout] => false [xhtml_supports_css_cell_table_coloring] => false [xhtml_format_as_css_property] => false [xhtml_format_as_attribute] => false [xhtml_nowrap_mode] => false [xhtml_marquee_as_css_property] => false [xhtml_readable_background_color1] => #FFFFFF [xhtml_readable_background_color2] => #FFFFFF [xhtml_allows_disabled_form_elements] => false [xhtml_document_title_support] => true [xhtml_preferred_charset] => utf8 [opwv_xhtml_extensions_support] => false [xhtml_make_phone_call_string] => none [xhtmlmp_preferred_mime_type] => text/html [xhtml_table_support] => false [xhtml_send_sms_string] => none [xhtml_send_mms_string] => none [xhtml_file_upload] => supported [cookie_support] => true [accept_third_party_cookie] => true [xhtml_supports_iframe] => full [xhtml_avoid_accesskeys] => true [xhtml_can_embed_video] => play_and_stop [ajax_support_javascript] => true [ajax_manipulate_css] => true [ajax_support_getelementbyid] => true [ajax_support_inner_html] => true [ajax_xhr_type] => standard [ajax_manipulate_dom] => true [ajax_support_events] => true [ajax_support_event_listener] => true [ajax_preferred_geoloc_api] => none [xhtml_support_level] => 4 [preferred_markup] => html_web_4_0 [wml_1_1] => false [wml_1_2] => false [wml_1_3] => false [html_wi_w3_xhtmlbasic] => true [html_wi_oma_xhtmlmp_1_0] => false [html_wi_imode_html_1] => false [html_wi_imode_html_2] => false [html_wi_imode_html_3] => false [html_wi_imode_html_4] => false [html_wi_imode_html_5] => false [html_wi_imode_htmlx_1] => false [html_wi_imode_htmlx_1_1] => false [html_wi_imode_compact_generic] => false [html_web_3_2] => true [html_web_4_0] => true [voicexml] => false [multipart_support] => false [total_cache_disable_support] => false [time_to_live_support] => false [resolution_width] => 800 [resolution_height] => 600 [columns] => 120 [max_image_width] => 800 [max_image_height] => 600 [rows] => 200 [physical_screen_width] => 400 [physical_screen_height] => 400 [dual_orientation] => false [density_class] => 1.0 [wbmp] => false [bmp] => true [epoc_bmp] => false [gif_animated] => true [jpg] => true [png] => true [tiff] => false [transparent_png_alpha] => false [transparent_png_index] => false [svgt_1_1] => true [svgt_1_1_plus] => false [greyscale] => false [gif] => true [colors] => 65536 [webp_lossy_support] => false [webp_lossless_support] => false [post_method_support] => true [basic_authentication_support] => true [empty_option_value_support] => true [emptyok] => false [nokia_voice_call] => false [wta_voice_call] => false [wta_phonebook] => false [wta_misc] => false [wta_pdc] => false [https_support] => true [phone_id_provided] => false [max_data_rate] => 3200 [wifi] => true [sdio] => false [vpn] => false [has_cellular_radio] => false [max_deck_size] => 100000 [max_url_length_in_requests] => 128 [max_url_length_homepage] => 0 [max_url_length_bookmark] => 0 [max_url_length_cached_page] => 0 [max_no_of_connection_settings] => 0 [max_no_of_bookmarks] => 0 [max_length_of_username] => 0 [max_length_of_password] => 0 [max_object_size] => 0 [downloadfun_support] => false [directdownload_support] => false [inline_support] => false [oma_support] => false [ringtone] => false [ringtone_3gpp] => false [ringtone_midi_monophonic] => false [ringtone_midi_polyphonic] => false [ringtone_imelody] => false [ringtone_digiplug] => false [ringtone_compactmidi] => false [ringtone_mmf] => false [ringtone_rmf] => false [ringtone_xmf] => false [ringtone_amr] => false [ringtone_awb] => false [ringtone_aac] => false [ringtone_wav] => false [ringtone_mp3] => false [ringtone_spmidi] => false [ringtone_qcelp] => false [ringtone_voices] => 1 [ringtone_df_size_limit] => 0 [ringtone_directdownload_size_limit] => 0 [ringtone_inline_size_limit] => 0 [ringtone_oma_size_limit] => 0 [wallpaper] => false [wallpaper_max_width] => 0 [wallpaper_max_height] => 0 [wallpaper_preferred_width] => 0 [wallpaper_preferred_height] => 0 [wallpaper_resize] => none [wallpaper_wbmp] => false [wallpaper_bmp] => false [wallpaper_gif] => false [wallpaper_jpg] => false [wallpaper_png] => false [wallpaper_tiff] => false [wallpaper_greyscale] => false [wallpaper_colors] => 2 [wallpaper_df_size_limit] => 0 [wallpaper_directdownload_size_limit] => 0 [wallpaper_inline_size_limit] => 0 [wallpaper_oma_size_limit] => 0 [screensaver] => false [screensaver_max_width] => 0 [screensaver_max_height] => 0 [screensaver_preferred_width] => 0 [screensaver_preferred_height] => 0 [screensaver_resize] => none [screensaver_wbmp] => false [screensaver_bmp] => false [screensaver_gif] => false [screensaver_jpg] => false [screensaver_png] => false [screensaver_greyscale] => false [screensaver_colors] => 2 [screensaver_df_size_limit] => 0 [screensaver_directdownload_size_limit] => 0 [screensaver_inline_size_limit] => 0 [screensaver_oma_size_limit] => 0 [picture] => false [picture_max_width] => 0 [picture_max_height] => 0 [picture_preferred_width] => 0 [picture_preferred_height] => 0 [picture_resize] => none [picture_wbmp] => false [picture_bmp] => false [picture_gif] => false [picture_jpg] => false [picture_png] => false [picture_greyscale] => false [picture_colors] => 2 [picture_df_size_limit] => 0 [picture_directdownload_size_limit] => 0 [picture_inline_size_limit] => 0 [picture_oma_size_limit] => 0 [video] => false [oma_v_1_0_forwardlock] => false [oma_v_1_0_combined_delivery] => false [oma_v_1_0_separate_delivery] => false [streaming_video] => false [streaming_3gpp] => false [streaming_mp4] => false [streaming_mov] => false [streaming_video_size_limit] => 0 [streaming_real_media] => none [streaming_flv] => false [streaming_3g2] => false [streaming_vcodec_h263_0] => -1 [streaming_vcodec_h263_3] => -1 [streaming_vcodec_mpeg4_sp] => -1 [streaming_vcodec_mpeg4_asp] => -1 [streaming_vcodec_h264_bp] => -1 [streaming_acodec_amr] => none [streaming_acodec_aac] => none [streaming_wmv] => none [streaming_preferred_protocol] => rtsp [streaming_preferred_http_protocol] => none [wap_push_support] => false [connectionless_service_indication] => false [connectionless_service_load] => false [connectionless_cache_operation] => false [connectionoriented_unconfirmed_service_indication] => false [connectionoriented_unconfirmed_service_load] => false [connectionoriented_unconfirmed_cache_operation] => false [connectionoriented_confirmed_service_indication] => false [connectionoriented_confirmed_service_load] => false [connectionoriented_confirmed_cache_operation] => false [utf8_support] => true [ascii_support] => false [iso8859_support] => false [expiration_date] => false [j2me_cldc_1_0] => false [j2me_cldc_1_1] => false [j2me_midp_1_0] => false [j2me_midp_2_0] => false [doja_1_0] => false [doja_1_5] => false [doja_2_0] => false [doja_2_1] => false [doja_2_2] => false [doja_3_0] => false [doja_3_5] => false [doja_4_0] => false [j2me_jtwi] => false [j2me_mmapi_1_0] => false [j2me_mmapi_1_1] => false [j2me_wmapi_1_0] => false [j2me_wmapi_1_1] => false [j2me_wmapi_2_0] => false [j2me_btapi] => false [j2me_3dapi] => false [j2me_locapi] => false [j2me_nokia_ui] => false [j2me_motorola_lwt] => false [j2me_siemens_color_game] => false [j2me_siemens_extension] => false [j2me_heap_size] => 0 [j2me_max_jar_size] => 0 [j2me_storage_size] => 0 [j2me_max_record_store_size] => 0 [j2me_screen_width] => 0 [j2me_screen_height] => 0 [j2me_canvas_width] => 0 [j2me_canvas_height] => 0 [j2me_bits_per_pixel] => 0 [j2me_audio_capture_enabled] => false [j2me_video_capture_enabled] => false [j2me_photo_capture_enabled] => false [j2me_capture_image_formats] => none [j2me_http] => false [j2me_https] => false [j2me_socket] => false [j2me_udp] => false [j2me_serial] => false [j2me_gif] => false [j2me_gif89a] => false [j2me_jpg] => false [j2me_png] => false [j2me_bmp] => false [j2me_bmp3] => false [j2me_wbmp] => false [j2me_midi] => false [j2me_wav] => false [j2me_amr] => false [j2me_mp3] => false [j2me_mp4] => false [j2me_imelody] => false [j2me_rmf] => false [j2me_au] => false [j2me_aac] => false [j2me_realaudio] => false [j2me_xmf] => false [j2me_wma] => false [j2me_3gpp] => false [j2me_h263] => false [j2me_svgt] => false [j2me_mpeg4] => false [j2me_realvideo] => false [j2me_real8] => false [j2me_realmedia] => false [j2me_left_softkey_code] => 0 [j2me_right_softkey_code] => 0 [j2me_middle_softkey_code] => 0 [j2me_select_key_code] => 0 [j2me_return_key_code] => 0 [j2me_clear_key_code] => 0 [j2me_datefield_no_accepts_null_date] => false [j2me_datefield_broken] => false [receiver] => false [sender] => false [mms_max_size] => 0 [mms_max_height] => 0 [mms_max_width] => 0 [built_in_recorder] => false [built_in_camera] => false [mms_jpeg_baseline] => false [mms_jpeg_progressive] => false [mms_gif_static] => false [mms_gif_animated] => false [mms_png] => false [mms_bmp] => false [mms_wbmp] => false [mms_amr] => false [mms_wav] => false [mms_midi_monophonic] => false [mms_midi_polyphonic] => false [mms_midi_polyphonic_voices] => 0 [mms_spmidi] => false [mms_mmf] => false [mms_mp3] => false [mms_evrc] => false [mms_qcelp] => false [mms_ota_bitmap] => false [mms_nokia_wallpaper] => false [mms_nokia_operatorlogo] => false [mms_nokia_3dscreensaver] => false [mms_nokia_ringingtone] => false [mms_rmf] => false [mms_xmf] => false [mms_symbian_install] => false [mms_jar] => false [mms_jad] => false [mms_vcard] => false [mms_vcalendar] => false [mms_wml] => false [mms_wbxml] => false [mms_wmlc] => false [mms_video] => false [mms_mp4] => false [mms_3gpp] => false [mms_3gpp2] => false [mms_max_frame_rate] => 0 [nokiaring] => false [picturemessage] => false [operatorlogo] => false [largeoperatorlogo] => false [callericon] => false [nokiavcard] => false [nokiavcal] => false [sckl_ringtone] => false [sckl_operatorlogo] => false [sckl_groupgraphic] => false [sckl_vcard] => false [sckl_vcalendar] => false [text_imelody] => false [ems] => false [ems_variablesizedpictures] => false [ems_imelody] => false [ems_odi] => false [ems_upi] => false [ems_version] => 0 [siemens_ota] => false [siemens_logo_width] => 101 [siemens_logo_height] => 29 [siemens_screensaver_width] => 101 [siemens_screensaver_height] => 50 [gprtf] => false [sagem_v1] => false [sagem_v2] => false [panasonic] => false [sms_enabled] => false [wav] => false [mmf] => false [smf] => false [mld] => false [midi_monophonic] => false [midi_polyphonic] => false [sp_midi] => false [rmf] => false [xmf] => false [compactmidi] => false [digiplug] => false [nokia_ringtone] => false [imelody] => false [au] => false [amr] => false [awb] => false [aac] => false [mp3] => false [voices] => 1 [qcelp] => false [evrc] => false [flash_lite_version] => [fl_wallpaper] => false [fl_screensaver] => false [fl_standalone] => false [fl_browser] => false [fl_sub_lcd] => false [full_flash_support] => true [css_supports_width_as_percentage] => true [css_border_image] => none [css_rounded_corners] => none [css_gradient] => none [css_spriting] => true [css_gradient_linear] => none [is_transcoder] => false [transcoder_ua_header] => user-agent [rss_support] => false [pdf_support] => true [progressive_download] => true [playback_vcodec_h263_0] => -1 [playback_vcodec_h263_3] => -1 [playback_vcodec_mpeg4_sp] => -1 [playback_vcodec_mpeg4_asp] => -1 [playback_vcodec_h264_bp] => -1 [playback_real_media] => none [playback_3gpp] => false [playback_3g2] => false [playback_mp4] => false [playback_mov] => false [playback_acodec_amr] => none [playback_acodec_aac] => none [playback_df_size_limit] => 0 [playback_directdownload_size_limit] => 0 [playback_inline_size_limit] => 0 [playback_oma_size_limit] => 0 [playback_acodec_qcelp] => false [playback_wmv] => none [hinted_progressive_download] => false [html_preferred_dtd] => html4 [viewport_supported] => false [viewport_width] => width_equals_max_image_width [viewport_userscalable] => [viewport_initial_scale] => [viewport_maximum_scale] => [viewport_minimum_scale] => [mobileoptimized] => false [handheldfriendly] => false [canvas_support] => none [image_inlining] => true [is_smarttv] => false [is_console] => false [nfc_support] => false [ux_full_desktop] => true [jqm_grade] => A [is_sencha_touch_ok] => true ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr><tr><td>Zsxsoft<br /><small>1.3</small><br /></td><td> </td><td><i class="material-icons">close</i></td><td>Mac OS X 10.8.2 </td><td style="border-left: 1px solid #555"></td><td></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td style="border-left: 1px solid #555"><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td><i class="material-icons">close</i></td><td>0</td><td> <!-- Modal Trigger --> <a class="modal-trigger btn waves-effect waves-light" href="#modal-5d43e024-b46c-44f6-8914-529b05569bc2">Detail</a> <!-- Modal Structure --> <div id="modal-5d43e024-b46c-44f6-8914-529b05569bc2" class="modal modal-fixed-footer"> <div class="modal-content"> <h4>Zsxsoft result detail</h4> <p><pre><code class="php">Array ( [browser] => Array ( [link] => http://www.mozilla.org/ [title] => Mozilla Compatible [name] => Mozilla Compatible [version] => [code] => mozilla [image] => img/16/browser/mozilla.png ) [os] => Array ( [link] => http://www.apple.com/macosx/ [name] => Mac OS X 10.8.2 [version] => [code] => mac-3 [x64] => [title] => Mac OS X 10.8.2 [type] => os [dir] => os [image] => img/16/os/mac-3.png ) [device] => Array ( [link] => [title] => [model] => [brand] => [code] => null [dir] => device [type] => device [image] => img/16/device/null.png ) [platform] => Array ( [link] => http://www.apple.com/macosx/ [name] => Mac OS X 10.8.2 [version] => [code] => mac-3 [x64] => [title] => Mac OS X 10.8.2 [type] => os [dir] => os [image] => img/16/os/mac-3.png ) ) </code></pre></p> </div> <div class="modal-footer"> <a href="#!" class="modal-action modal-close waves-effect waves-green btn-flat ">close</a> </div> </div> </td></tr></table> </div> <div class="section"> <h1 class="header center orange-text">About this comparison</h1> <div class="row center"> <h5 class="header light"> The primary goal of this project is simple<br /> I wanted to know which user agent parser is the most accurate in each part - device detection, bot detection and so on...<br /> <br /> The secondary goal is to provide a source for all user agent parsers to improve their detection based on this results.<br /> <br /> You can also improve this further, by suggesting ideas at <a href="https://github.com/ThaDafinser/UserAgentParserComparison">ThaDafinser/UserAgentParserComparison</a><br /> <br /> The comparison is based on the abstraction by <a href="https://github.com/ThaDafinser/UserAgentParser">ThaDafinser/UserAgentParser</a> </h5> </div> </div> <div class="card"> <div class="card-content"> Comparison created <i>2016-05-10 08:05:28</i> | by <a href="https://github.com/ThaDafinser">ThaDafinser</a> </div> </div> </div> <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.3/js/materialize.min.js"></script> <script src="http://cdnjs.cloudflare.com/ajax/libs/list.js/1.2.0/list.min.js"></script> <script> $(document).ready(function(){ // the "href" attribute of .modal-trigger must specify the modal ID that wants to be triggered $('.modal-trigger').leanModal(); }); </script> </body> </html>
ThaDafinser/UserAgentParserComparison
v5/user-agent-detail/b1/8c/b18cc71b-79da-41f5-8fcf-fa20e7103d76.html
HTML
mit
52,694
import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import static com.mongodb.client.model.Filters.*; import com.mongodb.client.result.UpdateResult; import org.bson.Document; import org.bson.conversions.Bson; import java.util.ArrayList; import java.util.GregorianCalendar; import java.util.List; public class BlogPostDAO { private MongoCollection<Document> postsCollection; public BlogPostDAO(final MongoDatabase blogDatabase) { postsCollection = blogDatabase.getCollection("posts"); } public Document findByPermalink(String permalink) { return postsCollection.find(new Document("permalink", permalink)).first(); } public List<Document> findByDateDescending(int limit) { return postsCollection.find().sort(new Document("date", -1)).limit(limit).into(new ArrayList<Document>()); } public List<Document> findByTagDateDescending(final String tag) { // BasicDBObject query = new BasicDBObject("tags", tag); Bson filter = in("tags",tag); //System.out.println("/tag query: " + filter.toBsonDocument(Document.class,new Co).toJson()); List<Document> posts = postsCollection.find(filter).sort(new Document("date", -1)) .limit(10).into(new ArrayList<Document>()); System.out.println("For tag: "+tag); return posts; } public String addPost(String title, String body, List tags, String username) { System.out.println("inserting blog entry " + title + " " + body); String permalink = title.replaceAll("\\s", "_"); // whitespace becomes _ permalink = permalink.replaceAll("\\W", ""); // get rid of non alphanumeric permalink = permalink.toLowerCase(); String permLinkExtra = String.valueOf(GregorianCalendar .getInstance().getTimeInMillis()); permalink += permLinkExtra; Document post = new Document("title", title); post.append("author", username); post.append("body", body); post.append("permalink", permalink); post.append("tags", tags); post.append("comments", new java.util.ArrayList()); post.append("date", new java.util.Date()); try { postsCollection.insertOne(post); System.out.println("Inserting blog post with permalink " + permalink); } catch (Exception e) { System.out.println("Error inserting post"); return null; } return permalink; } public void addPostComment(final String name, final String email, final String body, final String permalink) { Document comment = new Document("author", name) .append("body", body); if (email != null && !email.equals("")) { comment.append("email", email); } UpdateResult result = postsCollection.updateOne(new Document("permalink", permalink), new Document("$push", new Document("comments", comment))); System.out.println("Matches: " +result.getMatchedCount()); System.out.println("Modified: " + result.getModifiedCount()); } }
bbb1991/java_spark_example
src/main/java/BlogPostDAO.java
Java
mit
3,172
package org.herrdommel; import org.apache.catalina.Context; import org.apache.catalina.connector.Connector; import org.apache.tomcat.util.descriptor.web.SecurityCollection; import org.apache.tomcat.util.descriptor.web.SecurityConstraint; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; /** * Enabled port 80 * @author <a href="mailto:dominik.mohr@adesso.de">Dominik Mohr</a> * @since 30.07.2017 */ @Profile("production") @Configuration public class TomcatHttpsConfig { @Value("${server.port}") private int defaultPort; @Value("${server.http.port}") private int httpPort; @Bean public EmbeddedServletContainerFactory servletContainer() { TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory() { @Override protected void postProcessContext(Context context) { SecurityConstraint securityConstraint = new SecurityConstraint(); securityConstraint.setUserConstraint("CONFIDENTIAL"); SecurityCollection collection = new SecurityCollection(); collection.addPattern("/*"); securityConstraint.addCollection(collection); context.addConstraint(securityConstraint); } }; tomcat.addAdditionalTomcatConnectors(initiateHttpConnector()); return tomcat; } private Connector initiateHttpConnector() { Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol"); connector.setScheme("http"); connector.setPort(httpPort); connector.setSecure(false); connector.setRedirectPort(defaultPort); return connector; } }
herrdommel/spring-boot-seed
src/main/java/org/herrdommel/TomcatHttpsConfig.java
Java
mit
2,064
<?php declare(strict_types=1); namespace Doctrine\Tests\ORM\Functional\Ticket; use Doctrine\Deprecations\PHPUnit\VerifyDeprecations; use Doctrine\ORM\Mapping\Column; use Doctrine\ORM\Mapping\Entity; use Doctrine\ORM\Mapping\GeneratedValue; use Doctrine\ORM\Mapping\Id; use Doctrine\ORM\Mapping\MappedSuperclass; use Doctrine\ORM\Mapping\NamedQueries; use Doctrine\ORM\Mapping\NamedQuery; use Doctrine\Tests\OrmFunctionalTestCase; use function count; /** * @group DDC-1404 */ class DDC1404Test extends OrmFunctionalTestCase { use VerifyDeprecations; protected function setUp(): void { parent::setUp(); try { $this->_schemaTool->createSchema( [ $this->_em->getClassMetadata(DDC1404ParentEntity::class), $this->_em->getClassMetadata(DDC1404ChildEntity::class), ] ); $this->loadFixtures(); } catch (Exception $exc) { } } public function testTicket(): void { $this->expectDeprecationWithIdentifier('https://github.com/doctrine/orm/issues/8592'); $repository = $this->_em->getRepository(DDC1404ChildEntity::class); $queryAll = $repository->createNamedQuery('all'); $queryFirst = $repository->createNamedQuery('first'); $querySecond = $repository->createNamedQuery('second'); self::assertEquals('SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1404ChildEntity p', $queryAll->getDQL()); self::assertEquals('SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1404ChildEntity p WHERE p.id = 1', $queryFirst->getDQL()); self::assertEquals('SELECT p FROM Doctrine\Tests\ORM\Functional\Ticket\DDC1404ChildEntity p WHERE p.id = 2', $querySecond->getDQL()); self::assertCount(2, $queryAll->getResult()); self::assertCount(1, $queryFirst->getResult()); self::assertCount(1, $querySecond->getResult()); } public function loadFixtures(): void { $c1 = new DDC1404ChildEntity('ChildEntity 1'); $c2 = new DDC1404ChildEntity('ChildEntity 2'); $this->_em->persist($c1); $this->_em->persist($c2); $this->_em->flush(); } } /** * @MappedSuperclass * @NamedQueries({ * @NamedQuery(name="all", query="SELECT p FROM __CLASS__ p"), * @NamedQuery(name="first", query="SELECT p FROM __CLASS__ p WHERE p.id = 1"), * }) */ class DDC1404ParentEntity { /** * @var int * @Id * @Column(type="integer") * @GeneratedValue() */ protected $id; public function getId(): int { return $this->id; } } /** * @Entity * @NamedQueries({ * @NamedQuery(name="first", query="SELECT p FROM __CLASS__ p WHERE p.id = 1"), * @NamedQuery(name="second", query="SELECT p FROM __CLASS__ p WHERE p.id = 2") * }) */ class DDC1404ChildEntity extends DDC1404ParentEntity { /** * @var string * @Column(type="string") */ private $name; public function __construct(string $name) { $this->name = $name; } public function getName(): string { return $this->name; } public function setName(string $name): void { $this->name = $name; } }
doctrine/doctrine2
tests/Doctrine/Tests/ORM/Functional/Ticket/DDC1404Test.php
PHP
mit
3,287
#ifndef _KERNEL_VESA_H_ #define _KERNEL_VESA_H_ #include <Kernel/Kernel.h> struct VbeInfo { char Signature[4]; struct { u8 Minor; u8 Major; } Version; u16 Oem[2]; u8 Capabilities[4]; u16 VideoModes[2]; u16 TotalMemory; }; struct VbeModeInfo { u16 Attributes; u8 WindowA, WindowB; u16 Granularity; u16 WindowSize; u16 SegmentA, SegmentB; u16 WindowFunction[2]; u16 Pitch; u16 Width, Height; u8 CharacterWidth, CharacterHeight, Planes; u8 Bpp; u8 Banks; u8 PixelFormat, BankSize, ImagePages; u8 _Reserved0; u8 RedMask, RedShift; u8 GreenMask, GreenShift; u8 BlueMask, BlueShift; u8 _ReservedMask, _ReservedShift; u8 ColorAttributes; u32 Address; u32 _Reserved1; u16 _Reserved2; }; bool VESA_Call(u8 function, u16 b = 0, u16 c = 0, u16 d = 0, u16 destination = 0); VbeInfo VESA_GetInformations(); VbeModeInfo VESA_GetModeInformations(u16 mode); void VESA_SetMode(u16 mode); #endif
jbatonnet/system
Source/Kernel/Devices/Drivers/VESA/VESA.h
C
mit
1,033
<div data-tabs-text='TabContainer' class='sc-tabs--with-text'> <button class="sc-inline-link sc-tab sc-tab--with-text--active sc-font-m" data-section='Tab1'>Tab 1</button> <div class='sc-tabs__content sc-tabs__content--visible' data-section='Tab1'> <p>Tab 1 Content</p> <a href='#'>Link</a> </div> <button class="sc-inline-link sc-tab sc-font-m" data-section='Tab2'>Tab 2</button> <div class='sc-tabs__content' data-section='Tab2'> <h3>Tab 2 Content</h3> <p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium.</p> </div> <button class="sc-inline-link sc-tab sc-font-m" data-section='Tab3'>Tab 3</button> <div class='sc-tabs__content' data-section='Tab3'> <h3>Tab 3 Content</h3> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin et pulvinar eros, ut feugiat lacus. Duis convallis ligula id tempus rhoncus. Curabitur tempus metus sit amet accumsan pulvinar. Pellentesque sed aliquam nisl. Sed libero tortor, posuere quis quam sed, ultrices feugiat nulla. Fusce ullamcorper odio eget tempus rhoncus. Etiam lacinia odio quis faucibus auctor. Curabitur a velit vel nisi facilisis vulputate. Vivamus feugiat, arcu eget accumsan feugiat, purus risus aliquam justo, id fermentum mauris dolor sit amet libero. Aenean laoreet vel justo et eleifend. Nulla facilisi. Quisque sit amet arcu sit amet nibh sagittis viverra. Mauris fringilla cursus ipsum et mollis. Cras eget sapien consequat, tincidunt enim vitae, vehicula lacus. In tristique venenatis urna, nec tincidunt nisl vulputate a. Curabitur dictum neque non tempus rhoncus.</p> </div> <button class="sc-inline-link sc-tab sc-font-m" data-section='Tab4'>Tab 4</button> <div class='sc-tabs__content' data-section='Tab4'> <h3>Tab 4 Content</h3> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin et pulvinar eros, ut feugiat lacus. Duis convallis ligula id tempus rhoncus. Curabitur tempus metus sit amet accumsan pulvinar. Pellentesque sed aliquam nisl. Sed libero tortor, posuere quis quam sed, ultrices feugiat nulla. Fusce ullamcorper odio eget tempus rhoncus. Etiam lacinia odio quis faucibus auctor. Curabitur a velit vel nisi facilisis vulputate. Vivamus feugiat, arcu eget accumsan feugiat, purus risus aliquam justo, id fermentum mauris dolor sit amet libero. Aenean laoreet vel justo et eleifend. Nulla facilisi. Quisque sit amet arcu sit amet nibh sagittis viverra. Mauris fringilla cursus ipsum et mollis. Cras eget sapien consequat, tincidunt enim vitae, vehicula lacus. In tristique venenatis urna, nec tincidunt nisl vulputate a. Curabitur dictum neque non tempus rhoncus.</p> </div> </div>
AutoScout24/showcar-ui
src/06-components/atoms/tabs/docs/tabs-text.html
HTML
mit
3,110
var Connection = require(['tedious']).Connection; var config = { userName: 'masproject2017', password: 'MAS.2017', server: 'masproject.database.windows.net', // If you are on Microsoft Azure, you need this: options: { encrypt: true, database: 'AdventureWorks' } }; var connection = new Connection(config); connection.on('connect', function (err) { // If no error, then good to proceed. console.log("Connected"); });
DamnDaniel7/MAS-PROJECT
js/main.js
JavaScript
mit
459
<?php namespace ApiExport\Module\App\Model\DTO\Filter; /** * Class FeedItem. */ class FeedItem { /** @var int */ public $id; /** @var int */ public $feedId; /** @var string */ public $hash; /** @var \DateTime */ public $startDate; /** @var \DateTime */ public $endDate; /** @var bool */ public $isEnabled; /** @var bool */ public $isViewed; /** @var bool */ public $isApproved; /** @var bool */ public $isReposted; /** @var bool */ public $isSent; }
UbikZ/api-export
src/Module/App/Model/DTO/Filter/FeedItem.php
PHP
mit
544
--- path: '/building-with-gatsby' date: '2017-08-19T20:51:00.000Z' title: 'Building with Gatsby.js' tags: - code - gatsby - shiny --- I've always been fascinated by static sites — there's something alluring about building a site and being able to deploy it anywhere, without worrying about web middleware, scaling infrastructure, managing databases, or any of the other fun pieces of modern web development. It's been a while since I've refreshed my own personal site, so in the interest of [documenting learning](https://academy.realm.io/posts/droidcon-boston-chiu-ki-chan-how-to-be-an-android-expert/), I'm going to write this post while building a shiny new site using [Gatsby](https://www.gatsbyjs.org/), a JavaScript-based newcomer to the world of static sites. This is my first time using it, so I'm writing this post and learning as I go. Get. Excited. 🎉 ## Getting Started My first impression of Gatsby is encouraging — their site is gorgeously-designed and their documentation gets right to the point of setting up a new site. I haven't needed to travel far to discover that it has everything I need right out of the box, complete with a handy CLI. ``` $ npm install -g gatsby $ gatsby new chrisvolldotcom $ cd chrisvolldotcom $ gatsby develop ``` Running the setup script is painless and presents me with a nicely-structured boilerplate project. Diving in, I'm already noticing a couple things: 1. There's almost no configuration. The project starts out with a small `gatsby-config.js` file with the project title and a minimal list of plugins. 2. Everything is templated out using React. Neat! 3. Gatsby has its own router. I don't immediately see any centralized routing logic, so my assumption is that adding a file to the `/src/pages` directory magically adds a route for it. 4. The console output mentions GraphQL. Interesting! I'm dying to see how this is used in the context of a static website. Loading up the freshly-built site, I'm presented with a rather spartan page — the perfect blank canvas to build on: ![Screenshot of the default Gatsby boilerplate homepage](./images/screen-1.png) Already I can tell that the developer experience is phenomenal. Gatsby comes with hot reloading right out of the box, so I can just dive right in. ## Setting up a blog Let's find a way to render this blog post I'm writing. To the docs! The docs are actually pretty light on this, so I'm my assumption is that implementing a blog has a very generalized solution, like building on support for loading markdown files. By good fortune, the Gatsby authors anticipated this, the first post on their blog describes [building a blog](https://www.gatsbyjs.org/blog/2017-07-19-creating-a-blog-with-gatsby/). How meta. 🤘 This post confirms my suspicion that this functionality isn't built right in. I won't repeat everything from that tutorial here, but there are a couple interesting takeaways: - Gatsby has a plugin system sort of similar to webpack. If you want to use markdown files, for instance, you need to add the ability to load and parse them. - Gatsby comes with built-in support for server-side rendering of React components. Get that SEO juice a-flowin' - It uses Redux internally, and [exposes its action creators](https://www.gatsbyjs.org/docs/bound-action-creators/) It works! ![Screenshot of this very blog post being rendered within the Gatsby demo page](./images/screen-2.png) So far so good! But no weekend project would be complete without a little debugging... Error messages in Gatsby aren't always descriptive of the problem. For instance, I encountered an error [where the graphql schema failed to compile](https://github.com/gatsbyjs/gatsby/issues/1567). Turns out I'm just dumb and can't format dates, and it provided enough context to nudge me in the right direction. And don't count on GitHub Pages if you plan to use a custom domain name! If you want offline mode, you'll need support for service workers, which require HTTPS; GitHub Pages [doesn't yet offer HTTPS](https://github.com/isaacs/github/issues/156) for custom domain names sadly — I found this out the hard way. ## Takeaways - Gatsby and the community around it are incredible. By no means is it perfect — it came out of beta a month ago! — but I kept thinking, "🤔 I wish it could do...", only to discover that a plugin already exists with that exact functionality. - Gatsby does a ton of magic behind the scenes. In some contexts I could see how this may be a problem, but the upsides of not having to think about offline mode, server-side rendering, bundle chunking, and other headaches are totally worth it. For my day job I love tinkering with webpack, but if I'm churning out a quick weekend project, I want to be able to iterate quickly. - If you're familiar with React and the ecosystem around it, you'll feel right at home with Gatsby. Trying it out is super easy — just [install the demo app](https://www.gatsbyjs.org/docs/) and dive right in. After only a couple days of work I was able to put together a pretty simple static blog. [Take a gander at the source code here](https://github.com/chrisvoll/chrisvolldotcom) to see how it works!
chrisvoll/chrisvolldotcom
src/posts/08-19-2017-build-with-gatsby/index.md
Markdown
mit
5,205
package basic; import java.util.Arrays; /** * Created by bonismo * 14/10/12 上午10:35 */ public class HelloWord { public static void main(String[] args) { System.out.println("Hello,World!"); System.out.println("Hello,Java"); // ASCII 排序 System.out.println((char) 1); System.out.println((char) 20); System.out.println((char) 10); System.out.println((char) 2); System.out.println((char) 65); Object[] objects = {(char) 1, (char) 20, (char) 10, (char) 2}; Arrays.sort(objects); System.out.println(Arrays.toString(objects)); } }
StayHungryStayFoolish/stayhungrystayfoolish.github.com
JavaSE/src/main/java/basic/HelloWord.java
Java
mit
635
using System; using System.Diagnostics; namespace Martini { [DebuggerDisplay("Type = {Type} Token = {_token}")] internal class Token { private string _token; public Token(string token) { _token = token; } public Token(char token) : this(token.ToString()) { } public Token(TokenType tokenType, string token) : this(token) { Type = tokenType; } public Token(TokenType tokenType, char token) : this(tokenType, token.ToString()) { } public string Value { get { return _token; } set { _token = value; } } public Sentence Sentence { get; set; } public TokenType Type { get; set; } = TokenType.Text; public int FromColumn { get; set; } = -1; public int ToColumn => FromColumn + Length; public int Length => _token.Length; public static bool operator ==(Token x, string y) { return !ReferenceEquals(x, null) && x.ToString().Equals(y, StringComparison.OrdinalIgnoreCase); } public static bool operator !=(Token x, string y) { return !(x == y); } public static implicit operator string(Token token) => token?.ToString(); public override string ToString() => _token; protected bool Equals(Token other) => string.Equals(_token, other._token); public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != this.GetType()) return false; return Equals((Token)obj); } public override int GetHashCode() => _token?.GetHashCode() ?? 0; } }
he-dev/Martini
Martini/_Codebase/_data/Token.cs
C#
mit
1,854
/* Standard CSS */ body { margin: 0px; } #foot { background-color:#D0D0D0; width: 100%; height: 50px; position:absolute; /* added */ bottom:0; /* added */ left:0; /* added */ text-align: center; } .link { font-color: #303030; text-decoration: none; font-family: "CICPG","Roboto","Tahoma","Verdana","Arial"; } .link:hover { text-decoration: underline; font-color: #000010; } h1 { font-family: "CICPG","Roboto","Tahoma","Verdana","Arial"; font-size: 20px; } h2 { font-family: "CICPG","Roboto","Tahoma","Verdana","Arial"; font-size: 16px; } h3 { font-family: "CICPG","Roboto","Tahoma","Verdana","Arial"; font-size: 14px; } h4 { font-family: "CICPG","Roboto","Tahoma","Verdana","Arial"; font-size: 12px; } .border_top_1 { border-top: 1px solid #303030; } .border0 { border: 0px solid #000000; } .padding0 { padding: 0px; } .lt0 { font-size: 8px; } .lt1 { font-size: 12px; } .lt2 { font-seize:14px; }
ReneFGJ/Brapci
css/prj_style.css
CSS
mit
1,122
// This file was generated based on 'C:\ProgramData\Uno\Packages\UnoCore\0.13.2\Source\Uno\Compiler\ShaderGenerator\$.uno'. // WARNING: Changes might be lost if you edit this file directly. #ifndef __APP_UNO_COMPILER_SHADER_GENERATOR_SHADER_STAGE_INLINE_ATTRIBUTE_H__ #define __APP_UNO_COMPILER_SHADER_GENERATOR_SHADER_STAGE_INLINE_ATTRIBUTE_H__ #include <app/Uno.Attribute.h> #include <Uno.h> namespace app { namespace Uno { namespace Compiler { namespace ShaderGenerator { struct ShaderStageInlineAttribute; struct ShaderStageInlineAttribute__uType : ::app::Uno::Attribute__uType { }; ShaderStageInlineAttribute__uType* ShaderStageInlineAttribute__typeof(); void ShaderStageInlineAttribute___ObjInit_1(ShaderStageInlineAttribute* __this); ShaderStageInlineAttribute* ShaderStageInlineAttribute__New_1(::uStatic* __this); struct ShaderStageInlineAttribute : ::app::Uno::Attribute { void _ObjInit_1() { ShaderStageInlineAttribute___ObjInit_1(this); } }; }}}} #endif
blyk/BlackCode-Fuse
AndroidUI/.build/Simulator/Android/include/app/Uno.Compiler.ShaderGenerator.ShaderStageInlineAttribute.h
C
mit
981
package eu.bcvsolutions.idm.core.security.evaluator.role; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Description; import org.springframework.stereotype.Component; import org.springframework.util.Assert; import eu.bcvsolutions.idm.core.model.entity.IdmRequest; import eu.bcvsolutions.idm.core.security.api.domain.AuthorizationPolicy; import eu.bcvsolutions.idm.core.security.api.service.SecurityService; import eu.bcvsolutions.idm.core.security.evaluator.AbstractAuthorizationEvaluator; import eu.bcvsolutions.idm.core.workflow.model.dto.WorkflowProcessInstanceDto; import eu.bcvsolutions.idm.core.workflow.service.WorkflowProcessInstanceService; /** * Currently logged user can work with requests, when identity was involved to approving. * * Search ({@link #getPermissions}) is not implemented. * * @author Vít Švanda */ @Component @Description("Currently logged user can work with requests, when identity was involved to approving.") public class RequestByWfInvolvedIdentityEvaluator extends AbstractAuthorizationEvaluator<IdmRequest> { private final WorkflowProcessInstanceService processService; private final SecurityService securityService; @Autowired public RequestByWfInvolvedIdentityEvaluator( SecurityService securityService, WorkflowProcessInstanceService processService) { Assert.notNull(securityService, "Service is required."); Assert.notNull(processService, "Service is required."); // this.securityService = securityService; this.processService = processService; } @Override public Set<String> getPermissions(IdmRequest entity, AuthorizationPolicy policy) { Set<String> permissions = super.getPermissions(entity, policy); if (entity == null || !securityService.isAuthenticated() || entity.getWfProcessId() == null) { return permissions; } // // search process instance by role request - its returned, if currently logged identity was involved in wf WorkflowProcessInstanceDto processInstance = processService.get(entity.getWfProcessId(), true); if (processInstance != null) { permissions.addAll(policy.getPermissions()); } return permissions; } }
bcvsolutions/CzechIdMng
Realization/backend/core/core-impl/src/main/java/eu/bcvsolutions/idm/core/security/evaluator/role/RequestByWfInvolvedIdentityEvaluator.java
Java
mit
2,221
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>higman-s: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / extra-dev</a></li> <li class="active"><a href="">8.10.0 / higman-s - 8.8.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> higman-s <small> 8.8.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2020-07-31 23:28:00 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2020-07-31 23:28:00 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-threads base base-unix base conf-findutils 1 Virtual package relying on findutils conf-m4 1 Virtual package relying on m4 coq 8.10.0 Formal proof management system num 1.3 The legacy Num library for arbitrary-precision integer and rational arithmetic ocaml 4.07.1 The OCaml compiler (virtual package) ocaml-base-compiler 4.07.1 Official release 4.07.1 ocaml-config 1 OCaml Switch Configuration ocamlfind 1.8.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/higman-s&quot; license: &quot;LGPL&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/HigmanS&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.8&quot; &amp; &lt; &quot;8.9~&quot;} ] tags: [ &quot;keyword: Higman&#39;s lemma&quot; &quot;keyword: well quasi-ordering&quot; &quot;category: Mathematics/Combinatorics and Graph Theory&quot; &quot;date: 2007-09-14&quot; ] authors: [ &quot;William Delobel &lt;william.delobel@lif.univ-mrs.fr&gt;&quot; ] bug-reports: &quot;https://github.com/coq-contribs/higman-s/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/higman-s.git&quot; synopsis: &quot;Higman&#39;s lemma on an unrestricted alphabet&quot; description: &quot;This proof is more or less the proof given by Monika Seisenberger in \&quot;An Inductive Version of Nash-Williams&#39; Minimal-Bad-Sequence Argument for Higman&#39;s Lemma\&quot;.&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/higman-s/archive/v8.8.0.tar.gz&quot; checksum: &quot;md5=325f622153d894179fd0ce2f23478f13&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-higman-s.8.8.0 coq.8.10.0</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.10.0). The following dependencies couldn&#39;t be met: - coq-higman-s -&gt; coq &lt; 8.9~ -&gt; ocaml &lt; 4.06.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-higman-s.8.8.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.07.1-2.0.6/extra-dev/8.10.0/higman-s/8.8.0.html
HTML
mit
7,000
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>coinductive-reals: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.8.1 / coinductive-reals - 8.7.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> coinductive-reals <small> 8.7.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2021-12-06 00:47:38 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-12-06 00:47:38 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-ocamlbuild base OCamlbuild binary and libraries distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 1 Virtual package relying on perl coq 8.8.1 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.02.3 The OCaml compiler (virtual package) ocaml-base-compiler 4.02.3 Official 4.02.3 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/coinductive-reals&quot; license: &quot;LGPL&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/CoinductiveReals&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.7&quot; &amp; &lt; &quot;8.8~&quot;} &quot;coq-qarith-stern-brocot&quot; {&gt;= &quot;8.7&quot; &amp; &lt; &quot;8.8~&quot;} ] tags: [ &quot;keyword: real numbers&quot; &quot;keyword: co-inductive types&quot; &quot;keyword: co-recursion&quot; &quot;keyword: exact arithmetic&quot; &quot;category: Mathematics/Arithmetic and Number Theory/Real numbers&quot; &quot;date: 2007-04-24&quot; ] authors: [ &quot;Milad Niqui &lt;milad@cs.ru.nl&gt; [http://www.cs.ru.nl/~milad]&quot; ] bug-reports: &quot;https://github.com/coq-contribs/coinductive-reals/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/coinductive-reals.git&quot; synopsis: &quot;Real numbers as coinductive ternary streams&quot; description: &quot;&quot;&quot; http://www.cs.ru.nl/~milad/ETrees/coinductive-field/ See the README file&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/coinductive-reals/archive/v8.7.0.tar.gz&quot; checksum: &quot;md5=add528791eebf008f2236f6c33a12cd4&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-coinductive-reals.8.7.0 coq.8.8.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.8.1). The following dependencies couldn&#39;t be met: - coq-coinductive-reals -&gt; coq &lt; 8.8~ -&gt; ocaml &lt; 4.02.0 base of this switch (use `--unlock-base&#39; to force) Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-coinductive-reals.8.7.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.02.3-2.0.6/released/8.8.1/coinductive-reals/8.7.0.html
HTML
mit
7,430
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>tree-diameter: Not compatible 👼</title> <link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" /> <link href="../../../../../bootstrap.min.css" rel="stylesheet"> <link href="../../../../../bootstrap-custom.css" rel="stylesheet"> <link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet"> <script src="../../../../../moment.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="navbar navbar-default" role="navigation"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a> </div> <div id="navbar" class="collapse navbar-collapse"> <ul class="nav navbar-nav"> <li><a href="../..">clean / released</a></li> <li class="active"><a href="">8.6.1 / tree-diameter - 8.7.0</a></li> </ul> </div> </div> </div> <div class="article"> <div class="row"> <div class="col-md-12"> <a href="../..">« Up</a> <h1> tree-diameter <small> 8.7.0 <span class="label label-info">Not compatible 👼</span> </small> </h1> <p>📅 <em><script>document.write(moment("2021-10-24 00:12:32 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2021-10-24 00:12:32 UTC)</em><p> <h2>Context</h2> <pre># Packages matching: installed # Name # Installed # Synopsis base-bigarray base base-num base Num library distributed with the OCaml compiler base-threads base base-unix base camlp5 7.14 Preprocessor-pretty-printer of OCaml conf-findutils 1 Virtual package relying on findutils conf-perl 1 Virtual package relying on perl coq 8.6.1 Formal proof management system num 0 The Num library for arbitrary-precision integer and rational arithmetic ocaml 4.05.0 The OCaml compiler (virtual package) ocaml-base-compiler 4.05.0 Official 4.05.0 release ocaml-config 1 OCaml Switch Configuration ocamlfind 1.9.1 A library manager for OCaml # opam file: opam-version: &quot;2.0&quot; maintainer: &quot;Hugo.Herbelin@inria.fr&quot; homepage: &quot;https://github.com/coq-contribs/tree-diameter&quot; license: &quot;LGPL 2.1&quot; build: [make &quot;-j%{jobs}%&quot;] install: [make &quot;install&quot;] remove: [&quot;rm&quot; &quot;-R&quot; &quot;%{lib}%/coq/user-contrib/TreeDiameter&quot;] depends: [ &quot;ocaml&quot; &quot;coq&quot; {&gt;= &quot;8.7&quot; &amp; &lt; &quot;8.8~&quot;} ] tags: [ &quot;keyword: program verification&quot; &quot;keyword: trees&quot; &quot;keyword: paths&quot; &quot;keyword: graphs&quot; &quot;keyword: distance&quot; &quot;keyword: diameter&quot; &quot;category: Computer Science/Decision Procedures and Certified Algorithms/Correctness proofs of algorithms&quot; ] authors: [ &quot;Jean-Christophe Filliâtre&quot; ] bug-reports: &quot;https://github.com/coq-contribs/tree-diameter/issues&quot; dev-repo: &quot;git+https://github.com/coq-contribs/tree-diameter.git&quot; synopsis: &quot;Diameter of a binary tree&quot; description: &quot;&quot;&quot; This contribution contains the verification of a divide-and-conquer algorithm to compute the diameter of a binary tree (the maxmimal distance between two nodes in the tree).&quot;&quot;&quot; flags: light-uninstall url { src: &quot;https://github.com/coq-contribs/tree-diameter/archive/v8.7.0.tar.gz&quot; checksum: &quot;md5=828e673a375124912359a2e5c13d2f86&quot; } </pre> <h2>Lint</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Dry install 🏜️</h2> <p>Dry install with the current Coq version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam install -y --show-action coq-tree-diameter.8.7.0 coq.8.6.1</code></dd> <dt>Return code</dt> <dd>5120</dd> <dt>Output</dt> <dd><pre>[NOTE] Package coq is already installed (current version is 8.6.1). The following dependencies couldn&#39;t be met: - coq-tree-diameter -&gt; coq &gt;= 8.7 Your request can&#39;t be satisfied: - No available version of coq satisfies the constraints No solution found, exiting </pre></dd> </dl> <p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-tree-diameter.8.7.0</code></dd> <dt>Return code</dt> <dd>0</dd> </dl> <h2>Install dependencies</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Install 🚀</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Duration</dt> <dd>0 s</dd> </dl> <h2>Installation size</h2> <p>No files were installed.</p> <h2>Uninstall 🧹</h2> <dl class="dl-horizontal"> <dt>Command</dt> <dd><code>true</code></dd> <dt>Return code</dt> <dd>0</dd> <dt>Missing removes</dt> <dd> none </dd> <dt>Wrong removes</dt> <dd> none </dd> </dl> </div> </div> </div> <hr/> <div class="footer"> <p class="text-center"> Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣 </p> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script src="../../../../../bootstrap.min.js"></script> </body> </html>
coq-bench/coq-bench.github.io
clean/Linux-x86_64-4.05.0-2.0.1/released/8.6.1/tree-diameter/8.7.0.html
HTML
mit
7,207
# Satyr _This handsome, grinning man has the furry legs of a goat and a set of curling ram horns extending from his temples._ **Satyr CR 4** **XP 1,200** CN Medium [fey](creatureTypes#_fey) **Init** +2; **Senses** low-light vision; [Perception](../skills/perception#_perception) +18 **Defense** **AC** 18, touch 13, flat-footed 15 (+2 Dex, +1 dodge, +5 natural) **hp** 44 (8d6+16) **Fort** +4, **Ref** +8, **Will** +8 **DR** 5/cold iron **Offense** **Speed** 40 ft. **Melee** dagger +6 (1d4+2/19–20), horns +1 (1d6+1) **Ranged** short bow +6 (1d6/×3) **Special Attacks** pipes **Spell-Like Abilities** (CL 8th) At will—_ [charm person](../spells/charmPerson#_charm-person) _(DC 15)_, [dancing lights](../spells/dancingLights#_dancing-lights)_, _ [ghost sound](../spells/ghostSound#_ghost-sound)_ (DC 14), _ [sleep](../spells/sleep#_sleep) _(DC 15), _ [suggestion](../spells/suggestion#_suggestion) _(DC 17) 1/day—_ [fear](../spells/fear#_fear) _(DC 18), _ [summon nature's ally III](../spells/summonNatureSAlly#_summon-nature-s-ally-iii)_ **Statistics** **Str** 14, **Dex** 15, **Con** 15, **Int** 12, **Wis** 14, **Cha** 19 **Base** **Atk** +4; **CMB** +6; **CMD** 18 **Feats** [Dodge](../feats#_dodge), [Mobility](../feats#_mobility), [Skill Focus](../feats#_skill-focus) ( [Perception](../skills/perception#_perception)), [Weapon Finesse](../feats#_weapon-finesse) **Skills** [Bluff](../skills/bluff#_bluff) +15, [Diplomacy](../skills/diplomacy#_diplomacy) +15, [Disguise](../skills/disguise#_disguise) +9, [Intimidate](../skills/intimidate#_intimidate) +9, [Knowledge](../skills/knowledge#_knowledge) (nature) +10, [Perception](../skills/perception#_perception) +18, [Perform](../skills/perform#_perform) (wind instruments) +19, [Stealth](../skills/stealth#_stealth) +17, [Survival](../skills/survival#_survival) +7; **Racial Modifiers** +4 [Perception](../skills/perception#_perception), +4 [Perform](../skills/perform#_perform), +4 [Stealth](../skills/stealth#_stealth) **Languages** Common, Sylvan **Ecology** **Environment** temperate forests **Organization** solitary, pair, band (3–6), or orgy (7–11) **Treasure** standard (dagger, short bow plus 20 arrows, masterwork panpipes, other treasure) **Special Abilities** **Pipes (Su)** A satyr can focus and empower his magic by playing haunting melodies on his panpipes. When he plays, all creatures within a 60-foot radius must make a DC 18 Will save or be affected by _ [charm person](../spells/charmPerson#_charm-person)_,_ [fear](../spells/fear#_fear)_,_ [sleep](../spells/sleep#_sleep)_, or _ [suggestion](../spells/suggestion#_suggestion)_, depending on what tune the satyr chooses. A creature that successfully saves against any of the pipes' effects cannot be affected by the same set of pipes for 24 hours, but can still be affected by the satyr's other spell-like abilities as normal. The satyr's use of his pipes does not count toward his uses per day of his spell-like abilities, and if separated from them he may continue to use his standard abilities. The pipes themselves are masterwork, and a satyr can craft a replacement with 1 week of labor. The save DC is Charisma-based. Satyrs, known in some regions as fauns, are debauched and hedonistic creatures of the deepest, most primeval parts of the woods. They adore wine, music, and carnal delights, and are renowned as rakes and smooth-talkers, wooing unwary maidens and shepherd boys and leaving a trail of awkward explanations and unplanned pregnancies in their wakes. Though their bodies are almost always those of attractive and well-built men, much of the satyrs' talent for seduction lies in their talent for music. With the aid of his eponymous pipes, a satyr is capable of weaving a wide variety of melodic spells designed to enchant others and bring them in line with his capricious desires. In addition to their constant frolicking, satyrs often act as guardians of the creatures in their forest homes, and any who manage to turn the satyr's lust to wrath are likely to find themselves facing down dangerous animals surrounding the faun. Still, while satyrs tend to value their own amusement well above the rights of others, they bear no ill will toward those they seduce. Children born from such encounters are always full-blooded satyrs, and are generally spirited away by their riotous kin soon after birth.
brunokoga/pathfinder-markdown
prd_markdown/monsters/satyr.md
Markdown
mit
4,391
/** * Config Interface */ "use strict"; /* Node modules */ /* Third-party modules */ /* Files */ export interface IConfigInterface { url: string; mongoOptions?: { uri_decode_auth?: boolean; db?: any; server?: any; replSet?: any; mongos?: any; promiseLibrary?: any; }; poolOptions?: { name?: string; max?: number; min?: number; refreshIdle?: boolean; idleTimeoutMillis?: number; reapIntervalMillis?: number; returnToHead?: boolean; priorityRange?: number; validate?: (client: any) => boolean; validateAsync?: (client: any, callback: (remove: boolean) => void) => void; log?: boolean | ((log: string, level: string) => void); }; }
riggerthegeek/steeplejack-mongodb
lib/configInterface.ts
TypeScript
mit
796
declare namespace java { namespace awt { namespace image { abstract class RGBImageFilter extends java.awt.image.ImageFilter { protected origmodel: java.awt.image.ColorModel protected newmodel: java.awt.image.ColorModel protected canFilterIndexColorModel: boolean public constructor() public setColorModel(arg0: java.awt.image.ColorModel): void public substituteColorModel(arg0: java.awt.image.ColorModel, arg1: java.awt.image.ColorModel): void public filterIndexColorModel(arg0: java.awt.image.IndexColorModel): java.awt.image.IndexColorModel public filterRGBPixels(arg0: number | java.lang.Integer, arg1: number | java.lang.Integer, arg2: number | java.lang.Integer, arg3: number | java.lang.Integer, arg4: number[] | java.lang.Integer[], arg5: number | java.lang.Integer, arg6: number | java.lang.Integer): void public setPixels(arg0: number | java.lang.Integer, arg1: number | java.lang.Integer, arg2: number | java.lang.Integer, arg3: number | java.lang.Integer, arg4: java.awt.image.ColorModel, arg5: number[] | java.lang.Byte[], arg6: number | java.lang.Integer, arg7: number | java.lang.Integer): void public setPixels(arg0: number | java.lang.Integer, arg1: number | java.lang.Integer, arg2: number | java.lang.Integer, arg3: number | java.lang.Integer, arg4: java.awt.image.ColorModel, arg5: number[] | java.lang.Integer[], arg6: number | java.lang.Integer, arg7: number | java.lang.Integer): void public abstract filterRGB(arg0: number | java.lang.Integer, arg1: number | java.lang.Integer, arg2: number | java.lang.Integer): number } } } }
wizawu/1c
@types/jdk/java.awt.image.RGBImageFilter.d.ts
TypeScript
mit
1,665
#include <stdio.h> #include <stdlib.h> void next_generation(int *current, int *next, int length); int main() { int i, j, sum; int n,current[20], next[20]; do{ scanf("%d", &n); }while(n < 0 && n > 20); for(i=0;i<n;i++) scanf(" %d", &current[i]); next[0]=0; next[n-1]=0; for(i = 0;i < 1000; i++) { sum = 0; for(j = 0;j < n; j++) { if(current[j] == 0) sum++; } next_generation(current, next, n); if(sum == n) { break; } } return 0; } void next_generation(int *current, int *next, int length) { int i; for(i = 0; i < length; i++) { if(current[i] == 1) printf("*"); else printf("."); } for(i = 1; i < length - 1; i++) { if(current[i-1] == 1 && current[i+1] == 0) next[i] = 1; else if(current[i-1] == 0 && current[i+1] == 1) next[i] = 1; else next[i] = 0; } for(i=0;i<length;i++) { current[i]=next[i]; } printf("\n"); }
Ivan-Killer/po-homework
2015-2016/A/07/05/task2.c
C
mit
1,143